Movatterモバイル変換


[0]ホーム

URL:


Type:Package
Title:Markov Random Field Models for Image Analysis
Version:1.0
Maintainer:Victor Freguglia <victorfreguglia@gmail.com>
Description:Model fitting, sampling and visualization for the (Hidden) Markov Random Field model with pairwise interactions and general interaction structure from Freguglia, Garcia & Bicas (2020) <doi:10.1002/env.2613>, which has many popular models used in 2-dimensional lattices as particular cases, like the Ising Model and Potts Model. A complete manuscript describing the package is available in Freguglia & Garcia (2022) <doi:10.18637/jss.v101.i08>.
License:GPL-3
Encoding:UTF-8
LazyData:true
Imports:Rcpp (≥ 1.0.1), dplyr(≥ 0.8.1), tidyr, methods, ggplot2,Rdpack
Depends:R (≥ 3.5.0)
LinkingTo:Rcpp, RcppArmadillo
RdMacros:Rdpack
RoxygenNote:7.1.2
Suggests:testthat (≥ 2.1.0), covr, knitr, rmarkdown, glue
VignetteBuilder:knitr
URL:https://github.com/Freguglia/mrf2d
BugReports:https://github.com/Freguglia/mrf2d/issues
NeedsCompilation:yes
Packaged:2022-01-25 16:21:16 UTC; victor
Author:Victor FregugliaORCID iD [aut, cre]
Repository:CRAN
Date/Publication:2022-01-25 23:52:42 UTC

mrf2d: Markov Random Field Models for Image Analysis

Description

mrf2d contains tools for Markov Random Field models ontwo-dimensional lattices.

To learn more aboutmrf2d, read the paper atdoi:10.18637/jss.v101.i08.

Author(s)

Maintainer: Victor Fregugliavictorfreguglia@gmail.com (ORCID)

See Also

Useful links:


Example objects frommrf2d

Description

Z_potts andtheta_potts are example objects formrf2d.

Z_potts is amatrix object containing an observed lattice of a 3 color(C = 2) Potts model.

theta_potts is the parameter array used to sample it,it consists of a configuration with one parameter (-1.0) and two relativepositions (to be used with a nearest-neighbor structure).

Author(s)

Victor Freguglia

Examples

theta_pottsdplot(Z_potts)

Creation of basis functions

Description

fourier_2d() andpolynomial_2d() creates alist of basisfunctions to be used as the fixed effect infit_ghm.

Usage

fourier_2d(max_freqs, lattice_dim)polynomial_2d(poly_deg, lattice_dim)

Arguments

max_freqs

A length 2 numeric vector with maximum frequencies considered(x-axis and y-axis direction, respectively).

lattice_dim

A length 2 numeric vector with lattice dimensions (N,M)to be used.

poly_deg

A length 2 numeric vector with degrees of the bivariatepolynomial to be considered.

Details

fourier_2d() is for 2-dimensional Fourier transform.

Value

Alist of functions.

Author(s)

Victor Freguglia

See Also

A paper with detailed description of the package can be found atdoi:10.18637/jss.v101.i08.

Examples

fourier_2d(c(10,10), dim(Z_potts))polynomial_2d(c(3,3), dim(Z_potts))

BOLD5000 neuroimaging data

Description

An image extracted from the "BOLD5000" open dataset. It was read fromthe file in path⁠BOLD5000/DS001499/SUB-CSI2/SES-16/ANAT/SUB-CSI2_SES-16_T1W.NII.GZ⁠,available at the OpenNeuro platform (https://openneuro.org/datasets/ds001499/versions/1.3.0).

Usage

bold5000

Format

An object of classmatrix (inherits fromarray) with 176 rows and 256 columns.

Details

The file was read using theoro.nifti package and the image was extracted from thematrix in slice 160.

References

Chang, N., Pyles, J. A., Marcus, A., Gupta, A., Tarr, M. J., & Aminoff, E. M. (2019).BOLD5000, a public fMRI dataset while viewing 5000 visual images. Scientific data, 6(1), 1-18.

See Also

A paper with detailed description of the package can be found atdoi:10.18637/jss.v101.i08.


Conditional probabilities in a pixel position

Description

Computes the vector of conditional probabilitiesfor a pixel position given a field, an interaction structure anda parameter array.

Usage

cp_mrf2d(Z, mrfi, theta, pos)

Arguments

Z

Amatrix with integers in⁠{0,...,C}⁠.

mrfi

Amrfi object representing theinteraction structure.

theta

A 3-dimensional array describing potentials. Slices representinteracting positions, rows represent pixel values and columns representneighbor values. As an example:theta[1,3,2] has the potential for thepair of values 0,2 observed in the second relative position ofmrfi.

pos

Length-2 vector with the position to compute conditionalprobabilities in.

Value

Anumeric vector with the conditional probabilities.

Author(s)

Victor Freguglia

See Also

A paper with detailed description of the package can be found atdoi:10.18637/jss.v101.i08.

Examples

cp_mrf2d(Z_potts, mrfi(1), theta_potts, c(57,31))cp_mrf2d(Z_potts, mrfi(1), theta_potts*0.1, c(57,31))

Example Data

Description

mrf2d contains a set of simulated fields to illustrate itsusage.

field1

A binary field sampled from a sparse interaction structure:mrfi(1) + c(4,4)

hfield1

A continuous valued field, obtained by Gaussian mixture drivenbyfield1.

Usage

field1hfield1

Format

An object of classmatrix (inherits fromarray) with 150 rows and 150 columns.

An object of classmatrix (inherits fromarray) with 150 rows and 150 columns.

Author(s)

Victor Freguglia


Plotting functions for lattice data

Description

dplot() andcplot() are functions for plotting lattice data.They are an alternative to base R'simage() function usingggplot2instead.dplot is used for discrete data andcplot for continuous data, they onlydiffer in the fact that pixel values are treated as a factor indplot,therefore, a discrete scale is used.

Usage

dplot(Z, legend = FALSE)cplot(Y, legend = TRUE)

Arguments

Z

Amatrix object with integers only.

legend

logical indicating whether a legend should be included or not.

Y

Amatrix object with continuous values.

Details

Since returns aggplot object, other layers can be added to itusing the usualggplot2 syntax in order to modify any aspect of the plot.

The data frame used to create the object has columns namedx,y andvalue, which are mapped tox,y andfill, respectively, usedwithgeom_tile().

Value

aggplot object.

Author(s)

Victor Freguglia

Examples

# Plotting discrete datadplot(Z_potts)#Making it continuouscplot(Z_potts + rnorm(length(Z_potts)))#Adding extra ggplot layerslibrary(ggplot2)dplot(Z_potts) + ggtitle("This is a title")dplot(Z_potts, legend = TRUE) + scale_fill_brewer(palette = "Set1")

EM estimation for Gaussian Hidden Markov field

Description

fit_ghm fits a Gaussian Mixture model with hidden componentsdriven by a Markov random field with known parameters. The inclusion of alinear combination of basis functions as a fixed effect is also possible.

The algorithm is a modification of of(Zhang et al. 2001), which isdescribed in (Freguglia et al. 2020).

Usage

fit_ghm(  Y,  mrfi,  theta,  fixed_fn = list(),  equal_vars = FALSE,  init_mus = NULL,  init_sigmas = NULL,  maxiter = 100,  max_dist = 10^-3,  icm_cycles = 6,  verbose = interactive(),  qr = NULL)

Arguments

Y

A matrix of observed (continuous) pixel values.

mrfi

Amrfi object representing theinteraction structure.

theta

A 3-dimensional array describing potentials. Slices representinteracting positions, rows represent pixel values and columns representneighbor values. As an example:theta[1,3,2] has the potential for thepair of values 0,2 observed in the second relative position ofmrfi.

fixed_fn

A list of functionsfn(x,y) to be considered as a fixedeffect. Seebasis_functions.

equal_vars

logical indicating if the mixture model has the samevariances in all mixture components.

init_mus

Optional. Anumeric with length (C+1) with the initial meanestimate for each component.

init_sigmas

Otional. Anumeric with length (C+1) with initial sampledeviation estimate for each component.

maxiter

The maximum number of iterations allowed. Defaults to 100.

max_dist

Defines a stopping condition. The algorithm stops if themaximum absolute difference between parameters of two consecutive iterationsis less thanmax_dist.

icm_cycles

Number of steps used in the Iterated Conditional Modesalgorithm executed in each interaction. Defaults to 6.

verbose

logical indicating wheter to print the progress or not.

qr

The QR decomposition of the design matrix. Used internally.

Details

If eitherinit_mus orinit_sigmas isNULL an EM algorithmconsidering an independent uniform distriburion for the hidden component isfitted first and its estimated means and sample deviations are used asinitial values. This is necessary because the algorithm may not converge ifthe initial parameter configuration is too far from the maximum likelihoodestimators.

max_dist defines a stopping condition. The algorithm will stop if themaximum absolute difference between (\mu and\sigma) parametersin consecutive iterations is less thanmax_dist.

Value

Ahmrfout containing:

Author(s)

Victor Freguglia

References

Freguglia V, Garcia NL, Bicas JL (2020).“Hidden Markov random field models applied to color homogeneity evaluation in dyed textile images.”Environmetrics,31(4), e2613.

Zhang Y, Brady M, Smith S (2001).“Segmentation of brain MR images through a hidden Markov random field model and the expectation-maximization algorithm.”IEEE transactions on medical imaging,20(1), 45–57.

See Also

A paper with detailed description of the package can be found atdoi:10.18637/jss.v101.i08.

Examples

# Sample a Gaussian mixture with components given by Z_potts# mean values are 0, 1 and 2 and a linear effect on the x-axis.set.seed(2)Y <- Z_potts + rnorm(length(Z_potts), sd = 0.4) +      (row(Z_potts) - mean(row(Z_potts)))*0.01# Check what the data looks likecplot(Y)fixed <- polynomial_2d(c(1,0), dim(Y))fit <- fit_ghm(Y, mrfi = mrfi(1), theta = theta_potts, fixed_fn = fixed)fit$parcplot(fit$fixed)

Maximum Pseudo-likelihood fitting of MRFs on 2d lattices.

Description

Parameter estimation for Markov random fields viaPseudo-Likelihood function optimization. Seepl_mrf2d for information on thePseudo-Likelihood function.

Usage

fit_pl(  Z,  mrfi,  family = "onepar",  init = 0,  optim_args = list(method = "BFGS"),  return_optim = FALSE)

Arguments

Z

Amatrix object containing the observed MRF.NA values can beused to create a subregion of the lattice for non-rectangular data.

mrfi

Amrfi object representing theinteraction structure.

family

The family of parameter restrictions to potentials. Familiesare:'onepar','oneeach','absdif','dif' or'free'.Seemrf2d-familiy.

init

The initial value to be used in the optimization. It can be:

  • A validarray of parameter values according tofamily.

  • 0. If set to0 an array with '0“ in all entries is created.

optim_args

Additional parameters passed tooptim().

return_optim

logical indicating whether information from theoptim() call are returned.

Value

An object of classmrfout with elements:

Author(s)

Victor Freguglia

See Also

A paper with detailed description of the package can be found atdoi:10.18637/jss.v101.i08.

Examples

fit_pl(Z_potts, mrfi(1), family = "onepar")fit_pl(Z_potts, mrfi(1), family = "oneeach")fit_pl(Z_potts, mrfi(2), family = "onepar")

Stochastic Approximation fitting of MRFs on 2d lattices

Description

Estimates the parameters of a MRF by successively sampling froma parameter configuration and updating it by comparing the sufficient statisticsof the sampled field and the observed field.

This method aims to find the parameter value where the gradient of thelikelihood function is equal to zero.

Usage

fit_sa(  Z,  mrfi,  family = "onepar",  gamma_seq,  init = 0,  cycles = 5,  refresh_each = length(gamma_seq) + 1,  refresh_cycles = 60,  verbose = interactive())

Arguments

Z

Amatrix object containing the observed MRF.NA values can beused to create a subregion of the lattice for non-rectangular data.

mrfi

Amrfi object representing theinteraction structure.

family

The family of parameter restrictions to potentials. Familiesare:'onepar','oneeach','absdif','dif' or'free'.Seemrf2d-familiy.

gamma_seq

Anumeric vector with the sequence of constantsused in each step\gamma_t.

init

The initial value to be used in the optimization. It can be:

  • A validarray of parameter values according tofamily.

  • 0. If set to0 an array with '0“ in all entries is created.

cycles

The number of updates to be done (for each each pixel).

refresh_each

An integer with the number of iterations taken before acomplete refresh (restart from a random state). This prevents the sample frombeing stuck in a mode for too long. Defaults tolength(gamma_seq) + 1 (norefresh happens).

refresh_cycles

An integer indicating how many Gibbs Sampler cycles areperformed when a refresh happens. Larger is usually better, but slower.

verbose

logical indicating whether the iteration number is printedduring execution.

Details

The stochastic approximation method consists of, given an observed fieldZ,and a starting parameters configuration\theta_0, successively samplea fieldZ_t from the current parameter configuration and estimate thedirection of the gradient of the likelihood function by comparing thesufficient statistics in the current sample and the observed field.

The solution is updated by moving in the estimated direction with a predefinedstep size\gamma_t, a new fieldZ_{t+1} is sampled using the newparameter configuration andZ_t as an initial value, and the process isrepeated.

\theta_{t+1} = \theta_t - \gamma_t(T(Z_t) - T(Z)),

whereT(Z) is the sufficient statistics for the reference field,T(Z_t) is the sufficient statistics for a field sampled from\theta_t.

gamma_seq is normalized internally by diving values bylength(Z), so thechoice of the sequence is invariant to the lattice dimensions. Typically, asequence likeseq(from = 1, to = 0, length.out = 1000) should be used fordefining a sequence with1000 steps. Some tuning of this sequence isrequired.

Value

Amrfout object with the following elements:

Note

Stochastic Approximation is called "Controllable Simulated Annealing" insome references.

Examples where Stochastic Approximation is used with MRFs are(Gimel'farb 1996), (Atchadé et al. 2013).

Author(s)

Victor Freguglia

References

Wikipedia (2019).“Stochastic approximation.”https://en.wikipedia.org/wiki/Stochastic_approximation.

Atchadé YF, Lartillot N, Robert C, others (2013).“Bayesian computation for statistical models with intractable normalizing constants.”Brazilian Journal of Probability and Statistics,27(4), 416–436.

Gimel'farb GL (1996).“Texture modeling by multiple pairwise pixel interactions.”IEEE Transactions on pattern analysis and machine intelligence,18(11), 1110–1114.

See Also

A paper with detailed description of the package can be found atdoi:10.18637/jss.v101.i08.

Examples

set.seed(2)fit1 <- fit_sa(Z_potts, mrfi(1), family = "oneeach", gamma_seq = seq(1, 0, length.out = 50))# Estimated parametersfit1$theta# A visualization of estimated gradient norm over iterations.plot(fit1$metrics, type = "l")fit_sa(Z_potts, mrfi(1), family = "oneeach", gamma_seq = seq(1, 0, length.out = 50))

MRF fitting functions output

Description

MRF fitting functions output

Usage

## S3 method for class 'hmrfout'print(x, ...)## S3 method for class 'hmrfout'summary(object, ...)## S3 method for class 'hmrfout'plot(x, ...)

Arguments

x

ahmrfout object.

...

other arguments not used by this method.

object

ahmrfout object.


Parameter restriction families

Description

Different parameter restrictions can be included in estimation processesto make suremrf2d can successfully include a wide range of model types inits inference functions.

For model identifiability, at least one linear restriction is necessary.mrf2d always assume\theta_{0,0,r} = 0 for all relative positionsr.

Additionally, each family of restrictions may introduce other restrictions:

'onepar'

This family assumes the model is defined by a single parameterby adding the restriction

\theta_{a,b,r} = \phi * 1(a != b).

Here1() denotes de indicator function. In words, the parameter mustbe the same value for any pair with different values and 0 for anyequal-valued pair.

'oneeach'

Similar to'onepar', parameters are 0 for equal-valued pairs and aconstant for pairs with different values, but the constant may differbetween different relative positionsr:

\theta{a,b,r} = \phi_r * 1(a != b).

'absdif'

All parameters\theta_{a,b,r} with the same absolute differencebetweena andb must be equal within each relative positionr. (Note that'absdif' is equal to'oneeach' for binary images).

\theta_{a,b,r} = \sum_d \phi_{d,r} * 1(|a-b| == d)

'dif'

The same as'absdif', but parameters may differ between positive andnegative differences.

\theta_{a,b,r} = \sum_d \phi_{d,r} * 1(a-b == d)

'free'

No additional restriction, all parameters other than\theta_{0,0,r}vary freely.

Author(s)

Victor Freguglia

See Also

vignette("mrf2d-family", package = "mrf2d")

A paper with detailed description of the package can be found atdoi:10.18637/jss.v101.i08.


mrfi: MRF interaction structure

Description

Themrfi S4 class is a representation of the interactionstructure for a spatially-stationary Markov Random Field.

The functionmrfi() provides an interface for creationmrfi objects. Aplot method is also available for visualization, aswell as conversion methods likeas.list and operators like+.

mrfi() creates an object of classmrfi based on a distancerule and optionally a list of relative positions. The argumentmax_norm andnorm_type can be used to automatically include all positions within a"range" defined by the norm type chosen and distance using that norm.

A list of relative positions may also be included to specify sparseinteraction structures, for example. Alternatively,rpositions()can be used to create a based exclusively on a list of relative positions.

Simple operations are provided to include (set union)new interacting positions to amrfi object with the'+' operator andremove positions (set difference) with-. Individual positions can beincluded/excluded using length-2 vectors in the right hand side. Union andset difference of complete structures can also be computed by adding orsubtracting twomrfi objects.

These operations deal with opposite directions filtering to avoid redundancyin the interaction structure.

Usage

mrfi(max_norm = 1, norm_type = "1", positions = NULL)rpositions(positions)## S3 method for class 'mrfi'as.list(x, ...)## S4 method for signature 'mrfi'length(x)## S4 method for signature 'mrfi,numeric,missing'x[[i]]## S4 method for signature 'mrfi,numeric,missing'x[i]## S4 method for signature 'mrfi,numeric'e1 + e2## S4 method for signature 'mrfi,numeric'e1 - e2## S4 method for signature 'mrfi,mrfi'e1 + e2## S4 method for signature 'mrfi,mrfi'e1 - e2mrfi_to_string(mrfi)

Arguments

max_norm

anumeric value. All points with norm\lemax_distare included.

norm_type

acharacter indicating the norm type used. Possible valuesare "m", "1", "2", etc. Seenorm for details.

positions

alist ofnumeric vectors of length 2. Each vectorcorresponds to a relative position included.

x

mrfi object.

...

other arguments not used by this method.

i

vector of indexes to extract interacting positions.

e1,mrfi

Amrfi object.

e2

Either a secondmrfi object or a length 2numeric with the newrelative position to include (+) or remove (-).

Details

The interaction structure is defined by the list of relativepositions in it. For a specific pixel, conditional to the values of pixels inthese relative positions from it, its value is independent of any other pixelin the image.

The relative positions are indentified by two integersrx andryrepresenting the "shift" in thex-axis andy-axis respectively. As anexample: The relative position⁠(1,0)⁠ representes the pixel in the immediateright position, while⁠(-1,0)⁠ the left one.

Note that the inclusion of a relative position to the dependence also impliesits opposite direction is not conditionally independent (commutativeness ofdependence), but only one is included in themrfi object.

To illustrate that, a nearest neighbor dependence structure can be specifiedby:

mrfi(1)

Note that it only includes the positions⁠(1,0)⁠ and⁠(0,1)⁠, but whenvisualizing it, for example,mrf2d understands the opposite directionsare also conditionally dependent, as in

plot(mrfi(1)).

Value

Amrfi object.

as.list(): converts themrfi object to a list of interactingpositions (list of length-2 vectors).

[[: converts to list and subsets it.

[: subsets themrfi object and returns anothermrfi object.

+: computes the union of the interaction structure in amrfi object withanumeric representing an additional position to include or anothermrfiobject.

Slots

Rmat

A 2-columnmatrix where each row represents a relative positionof interaction.

Note

If a position inpositions is already included due to themax_norm andnorm_type specification, the second ocurrence is ignored.The same is valid for repeated or opposite positions inpositions.

See Also

A paper with detailed description of the package can be found atdoi:10.18637/jss.v101.i08.

Examples

plot(mrfi(max_norm = 2, norm_type = "1"))plot(mrfi(max_norm = 2, norm_type = "m"))plot(mrfi(max_norm = 2, norm_type = "1", positions = list(c(4,4))))as.list(mrfi(1))mrfi(1)[[1]]mrfi(2)[[1:3]]mrfi(1)rpositions(list(c(1,0), c(0,1)))mrfi(2)mrfi(2, norm_type = "m")mrfi(1, positions = list(c(4,4), c(-4,4)))#Repeated positions are handled automaticallymrfi(1, positions = list(c(1,0), c(2,0)))mrfi(1) + c(2,0)mrfi(1) - c(1,0)mrfi(1) + mrfi(0, positions = list(c(2,0)))mrfi(2) - mrfi(1)

MRF fitting functions output

Description

MRF fitting functions output

Usage

## S3 method for class 'mrfout'print(x, ...)## S3 method for class 'mrfout'summary(object, ...)## S3 method for class 'mrfout'plot(x, ...)

Arguments

x

amrfout object.

...

other arguments not used by this method.

object

amrfout object.


Pseudo-likelihood function for MRFs on 2d lattices

Description

Computes the pseudo-likelihood function of a Markov Random Fieldon a 2-dimensional lattice.

Usage

pl_mrf2d(Z, mrfi, theta, log_scale = TRUE)

Arguments

Z

Amatrix with integers in⁠{0,...,C}⁠.

mrfi

Amrfi object representing theinteraction structure.

theta

A 3-dimensional array describing potentials. Slices representinteracting positions, rows represent pixel values and columns representneighbor values. As an example:theta[1,3,2] has the potential for thepair of values 0,2 observed in the second relative position ofmrfi.

log_scale

Alogical value indicating whether the returned valueshould be in logarithmic scale.

Details

The pseudo-likelihood function is defined as the product ofconditional probabilities of each pixel given its neighbors:

\prod_i P(Z_i | Z_{{N}_i}, \theta).

Value

Anumeric with the pseudo-likelihood value.

Author(s)

Victor Freguglia

See Also

A paper with detailed description of the package can be found atdoi:10.18637/jss.v101.i08.

Examples

pl_mrf2d(Z_potts, mrfi(1), theta_potts)

Plotting ofmrfi objects.

Description

Plots a visual representation of the interaction structuredescribed in amrfi object. The black tile represents a reference pixeland gray tiles are shown in relative positions with dependent pixels.

Aggplot object is used, therefore, the user can load theggplot2package and add moreggplot layers to freely customize theplot.

Usage

## S3 method for class 'mrfi'plot(x, include_axis = FALSE, include_opposite = TRUE, ...)

Arguments

x

Amrfi object.

include_axis

logical indicating whether the axis and grid linesare included. IfFALSEtheme_void() is added to theggplot object.

include_opposite

´logical' whether opposite directions should beincluded in the visualization of the dependence structure.

...

other arguments not used by this method.

Details

Thedata.frame used for theggplot call has columns namesrxandry repŕesenting the relative positions.

Value

Aggplot object usinggeom_tile() to represent interactingrelative positions.

Author(s)

Victor Freguglia

Examples

plot(mrfi(1))library(ggplot2)plot(mrfi(1)) + geom_tile(fill = "red")plot(mrfi(1)) + geom_tile(fill = "blue") + theme_void()plot(mrfi(1)) + geom_text(aes(label = paste0("(",rx,",",ry,")")))

Sampling of Markov Random Fields on 2d lattices

Description

Performs pixelwise updates based on conditional distributionsto sample from a Markov random field.

Usage

rmrf2d(  init_Z,  mrfi,  theta,  cycles = 60,  sub_region = NULL,  fixed_region = NULL)

Arguments

init_Z

One of two options:

  • Amatrix object with the initial field configuration. Itsvaluesmust be integers in⁠{0,...,C}⁠.

  • A length 2numeric vector with the lattice dimensions.

mrfi

Amrfi object representing theinteraction structure.

theta

A 3-dimensional array describing potentials. Slices representinteracting positions, rows represent pixel values and columns representneighbor values. As an example:theta[1,3,2] has the potential for thepair of values 0,2 observed in the second relative position ofmrfi.

cycles

The number of updates to be done (for each each pixel).

sub_region

NULL if the whole lattice is considered or alogicalmatrix withTRUE for pixels in the considered region.

fixed_region

NULL if the whole lattice is to be sampled or alogicalmatrix withTRUE for pixels to be considered fixed. Fixedpixels are not updated in the Gibbs Sampler.

Details

This function implements a Gibbs Sampling scheme to sample froma Markov random field by iteratively sampling pixel values from theconditional distribution

P(Z_i | Z_{{N}_i}, \theta).

A cycle means exactly one update to each pixel. The order pixels aresampled is randomized within each cycle.

Ifinit_Z is passed as a length 2 vector with lattice dimensions, theinitial field is sampled from independent discrete uniform distributions in⁠{0,...,C}⁠. The value of C is obtained from the number of rows/columns oftheta.

A MRF can be sampled in a non-rectangular region of the lattice with the use ofthesub_region argument or by setting pixels toNA in the initialconfigurationinit_Z. Pixels withNA values ininit_Z are completelydisconsidered from the conditional probabilities and have the same effect assettingsub_region = is.na(init_Z). Ifinit_Z hasNA values,sub_region is ignored and a warning is produced.

A specific region can be kept constant during the Gibbs Sampler by using thefixed_region argument. Keeping a subset of pixels constant is useful whenyou want to sample in a specific region of the image conditional to therest, for example, in texture synthesis problems.

Value

Amatrix with the sampled field.

Note

As in any Gibbs Sampling scheme, a large number of cycles may berequired to achieve the target distribution, specially for stronginteraction systems.

Author(s)

Victor Freguglia

See Also

A paper with detailed description of the package can be found atdoi:10.18637/jss.v101.i08.

rmrf2d_mc for generating multiple points of aMarkov Chain to be used in Monte-Carlo methods.

Examples

# Sample using specified lattice dimensionZ <- rmrf2d(c(150,150), mrfi(1), theta_potts)#Sample using itial configurationZ2 <- rmrf2d(Z, mrfi(1), theta_potts)# View resultsdplot(Z)dplot(Z2)# Using sub-regionssubreg <- matrix(TRUE, 150, 150)subreg <- abs(row(subreg) - 75) + abs(col(subreg) - 75) <= 80# view the sub-regiondplot(subreg)Z3 <- rmrf2d(c(150,150), mrfi(1), theta_potts, sub_region = subreg)dplot(Z3)# Using fixed regionsfixreg <- matrix(as.logical(diag(150)), 150, 150)# Set initial configuration: diagonal values are 0.init_Z4 <- Zinit_Z4[fixreg] <- 0Z4 <- rmrf2d(init_Z4, mrfi(1), theta_potts, fixed_region = fixreg)dplot(Z4)# Combine fixed regions and sub-regionsZ5 <- rmrf2d(init_Z4, mrfi(1), theta_potts,fixed_region = fixreg, sub_region = subreg)dplot(Z5)

Markov Chain sampling of MRFs for Monte-Carlo methods

Description

Generates a Markov Chain of random fields and returns thesufficient statistics for each of the observations.

This function automatizes the process of generating a random sample of MRFsto be used in Monte-Carlo methods by wrappingrmrf2dand executing it multiple time while storing sufficient statistics insteadof the entire lattice.

Usage

rmrf2d_mc(  init_Z,  mrfi,  theta,  family,  nmc = 100,  burnin = 100,  cycles = 4,  verbose = interactive())

Arguments

init_Z

One of two options:

  • Amatrix object with the initial field configuration. Itsvaluesmust be integers in⁠{0,...,C}⁠.

  • A length 2numeric vector with the lattice dimensions.

mrfi

Amrfi object representing theinteraction structure.

theta

A 3-dimensional array describing potentials. Slices representinteracting positions, rows represent pixel values and columns representneighbor values. As an example:theta[1,3,2] has the potential for thepair of values 0,2 observed in the second relative position ofmrfi.

family

The family of parameter restrictions to potentials. Familiesare:'onepar','oneeach','absdif','dif' or'free'.Seemrf2d-familiy.

nmc

Number of samples to be stored.

burnin

Number of cycles iterated before start collecting sufficientstatistics.

cycles

Number of cycles between collected samples.

verbose

logical indicating whether to print iteration number or not.

Value

A matrix where each row contains the vector of sufficient statisticsfor an observation.

Note

Fixed regions and incomplete lattices are not supported.

Author(s)

Victor Freguglia

Examples

rmrf2d_mc(c(80, 80), mrfi(1), theta_potts, family = "oneeach", nmc = 8)

Summarized representation of theta arrays

Description

smr_array creates a vector containing only the free parameters from an arraygiven a restrictionfamily.exapand_array is the reverseoperation, expanding a complete array from the vector of sufficient statistics.

Usage

smr_array(theta, family)expand_array(theta_vec, family, mrfi, C)

Arguments

theta

A 3-dimensional array describing potentials. Slices representinteracting positions, rows represent pixel values and columns representneighbor values. As an example:theta[1,3,2] has the potential for thepair of values 0,2 observed in the second relative position ofmrfi.

family

The family of parameter restrictions to potentials. Familiesare:'onepar','oneeach','absdif','dif' or'free'.Seemrf2d-familiy.

theta_vec

Anumeric vector with the free parameters of a potentialarray. It's dimension depends on the restrictionfamily,C and the numberof interacting positions onmrfi.

mrfi

Amrfi object representing theinteraction structure.

C

The maximum value of the field.

Details

The order the parameters appear in the summarized vector matchesthe order insmr_stat().

vec_description() provides adata.frame object describingwhich are the relative positions and interactions associated with eachelement of the summarized vector in the same order.

Value

smr_array returns a numeric vector with the free parameters oftheta.

expand_array returns a three-dimensionalarray of potentials.

Author(s)

Victor Freguglia

See Also

A paper with detailed description of the package can be found atdoi:10.18637/jss.v101.i08

Examples

smr_array(theta_potts, "onepar")smr_array(theta_potts, "oneeach")expand_array(0.99, family = "onepar", mrfi = mrfi(1), C = 2)expand_array(c(0.1, 0.2), family = "oneeach", mrfi = mrfi(1), C = 3)

Summary Statistics

Description

Computes the summary count statistics of a field given aninteraction structure and a restriction family.

Usage

smr_stat(Z, mrfi, family)cohist(Z, mrfi)vec_description(mrfi, family, C)

Arguments

Z

Amatrix object containing the observed MRF.NA values can beused to create a subregion of the lattice for non-rectangular data.

mrfi

Amrfi object representing theinteraction structure.

family

The family of parameter restrictions to potentials. Familiesare:'onepar','oneeach','absdif','dif' or'free'.Seemrf2d-familiy.

C

The maximum value of the field.

Details

The order the summarized counts appear in the summary vector matchesthe order insmr_array().

Value

A numeric vector with the summarized counts.

An array representing the co-ocurrence histogram ofZ in the relativepositions contained inmrfi. Each row and column corresponds a pair of valuesin⁠(0, ..., C)⁠ and each slice corresponds to

Adata.frame describing the relative positionand interaction associated with each potential in the vectorform in each row, in the same order.

Author(s)

Victor Freguglia

See Also

A paper with detailed description of the package can be found atdoi:10.18637/jss.v101.i08

Examples

smr_stat(Z_potts, mrfi(1), "onepar")smr_stat(Z_potts, mrfi(1), "oneeach")cohist(Z_potts, mrfi(1))

[8]ページ先頭

©2009-2025 Movatter.jp