Cholesky_Midpoint_RF is a MATLAB toolkit for simulating two-dimensional Gaussian random fields of spatially variable geotechnical parameters on structured grids. It combines direct Cholesky simulation with scalable solver backends, observation conditioning, visualization, and engineering-data export. A backward-compatible interface is retained for the original homogeneous-site workflow.
- Four covariance models:
gaussian,exponential,spherical, andmatern - Anisotropic correlation lengths in the horizontal and vertical directions
- Direct Cholesky, Karhunen-Loève (KL), circulant-embedding, and Nyström solvers
- Automatic solver selection according to grid size and regularity
- Single or batch realizations, with optional parallel and GPU workflows
- Conditional random fields generated from grid-based observations and observation uncertainty
- Contour, surface, histogram, and variogram-cloud visualization
- CSV, VTK, and MAT export
- Legacy compatibility through
RandomField2DCholMethod.m,randex.m, andconrandex.m
In the conditional random-field workflow, each cell identified by integer indices j and k is represented by its midpoint. For cell dimensions dx and dy, the physical coordinates are
The midpoint convention associates every simulated value with the center of a finite cell rather than a cell corner.
Let two grid points be located at
The implementation introduces direction-dependent correlation lengths through the normalized separation
where corrLength(1) and corrLength(2) correspond to the positive scales ell_x and ell_y. The discrete covariance matrix is then assembled as
where variance is the field variance, nugget is the diagonal nugget, and the Kronecker delta equals one only when the two indices coincide.
The four normalized kernels implemented by rf2d.CovarianceModel are
and
Here, smoothness is the positive Matérn parameter nu, Gamma is the gamma function, and K_nu is the modified Bessel function of the second kind. The combination of ell_x, ell_y, and nu controls the directional persistence and local roughness of the field.
For n grid points, the covariance matrix is symmetrized and stabilized by a small diagonal jitter before factorization:
If a trial factorization is not positive definite, the Cholesky solver increases the jitter geometrically until a stable lower-triangular factor is obtained. A standard-normal vector is then transformed into a correlated realization:
Consequently,
and
For batch simulation, the same factor multiplies a matrix of independent standard-normal samples, which avoids repeating the factorization.
Positive geotechnical parameters such as cohesion and friction angle are commonly represented by lognormal random fields. Given a target arithmetic mean m and coefficient of variation v, the corresponding normal-space parameters are
If G(s) is a zero-mean, unit-variance Gaussian random field, the physical parameter field is obtained from
This transformation gives the requested first two marginal moments:
The legacy adapter uses this mapping to construct spatially varying cohesion and friction-angle fields from two Gaussian realizations.
Let x_u denote an unconditional realization over all grid cells, y the vector of measured values, and H the operator that selects simulated values at the observation cells. Define C_go as the grid-to-observation covariance, C_oo as the observation-to-observation covariance, and R as the diagonal observation-error covariance:
The kriging gain used by rf2d.ConditionalRandomField is
Each unconditional realization is corrected by its observation-space innovation:
The correction is strongest near reliable observations and decays spatially according to the selected covariance model. Nonzero observation variance prevents exact interpolation and represents measurement uncertainty.
-
KL solver: retains the leading covariance eigenpairs and samples from the reduced expansion
$$\mathbf{X}\approx\mu\mathbf{1}+\mathbf{V}_r\mathbf{\Lambda}_r^{1/2}\mathbf{z}_r.$$ -
Circulant embedding: embeds the stationary covariance on a larger regular grid, obtains its nonnegative spectrum using a two-dimensional FFT, and samples realizations through an inverse FFT.
-
Nyström approximation: selects landmark points and constructs a low-rank covariance approximation
$$\mathbf{C}\approx\mathbf{C}{nm}\mathbf{C}{mm}^{-1}\mathbf{C}_{mn}=\mathbf{B}\mathbf{B}^{\mathsf T}.$$
These backends reduce the memory or computational cost of direct dense factorization for larger problems.
The kernels produce distinctly different rates of spatial decorrelation even when the same nominal correlation length is used. The spherical model has compact support, whereas the exponential and Matérn models retain longer tails.
This standardized Matérn field uses correlation lengths of 20 m and 8 m. The plan and surface views expose the directional spatial structure, while the histogram provides a marginal comparison with the standard-normal density.
The circles mark the eight synthetic observation locations. Conditioning modifies the same unconditional realization toward the observed values and reduces the ensemble standard deviation in their neighborhoods.
All three figures are reproducible with fixed random seeds:
run("demo/generate_readme_figures.m")The script writes the PNG assets to docs/images/readme/.
- MATLAB R2020b or newer
- Statistics and Machine Learning Toolbox
- Parallel Computing Toolbox (optional, for
parfor,spmd, and GPU workflows)
Clone the repository, start MATLAB in the repository root, and add the project to the MATLAB path:
addpath(genpath(pwd))Generate and visualize a two-dimensional Matérn field:
x = linspace(0, 100, 128);
y = linspace(0, 40, 64);
params = struct( ...
"variance", 2.0, ...
"corrLength", [20 8], ...
"smoothness", 1.2, ...
"nugget", 1e-8);
g = rf2d.createGenerator( ...
x, y, "matern", params, ...
"Solver", "auto", ...
"Seed", 1234);
field = g.realize();
figure;
g.contourPlot(field, 20);The principal factory call is
g = rf2d.createGenerator(x, y, covarianceModel, covarianceParameters, Name=Value);Supported name-value options are:
Solver:"auto","cholesky","kl","circulant", or"approximate"Seed: random seedUseGPU: logical flag for solver samplingMean: scalar Gaussian-field meanMaxDirectPoints: automatic-routing threshold for dense direct solversMaxRank: rank used by the Nyström approximationKLModes: number of retained KL modesJitter: numerical stabilization term
Common generator methods include:
realize()orrealize("UseGPU", ..., "UseParallel", ...)generateBatch(nFields, useGPU, useParallel)reseed(seed)contourPlot,surfacePlot,histogramPlot, andvariogramCloudexportCSV,exportVTK, andexportMAT
rf2d.runConditionalRandomField(config)runs the file-based pipeline.rf2d.ConditionalRandomField.fromTables(gridTable, observationTable, config)runs an in-memory pipeline.randex(config)andconrandex(config)provide compatibility entry points.
The minimum configuration groups are:
grid.dx,grid.dycovModel.type,covModel.rangeX,covModel.rangeY,covModel.nuggetprior.mean,prior.stdsim.nRealizations,sim.randomSeed,sim.jitterio.gridTablePath,io.observationPath,io.unconditionalPath,io.conditionalPathlogging.enabled,logging.level
The grid table must contain id, j, and k; the observation table must contain j, k, obsValue, and obsVar.
With Solver="auto", the factory uses:
- Cholesky when the number of grid points does not exceed
MaxDirectPoints; - circulant embedding for larger regular grids;
- the approximate Nyström solver for larger nonregular cases.
Explicit requests for Cholesky or KL above the direct-point threshold are routed to Nyström. If solver preparation fails for numerical reasons, the generator also falls back to the approximate solver.
+rf2d/: covariance, generation, conditional-field, validation, and compatibility code+rf2d/+solvers/: Cholesky, KL, circulant-embedding, and Nyström solvers+rf2d/+viz/and+rf2d/+io/: plotting and export helpersdemo/: benchmark, CRF, Live Script, and README-figure scriptstests/: MATLAB unit and regression tests+docs/generateDocs.m: HTML-documentation publisher+toolbox/buildToolbox.m: MATLAB toolbox packagerRandomField2DCholMethod.m: historical API wrapper
The historical function remains available:
[RFC, RFPHI, c, phi] = RandomField2DCholMethod("Coord1.xlsx", 1, 0);It delegates to rf2d.LegacyAdapter and preserves the original output shapes.
Run the solver benchmark and plotting demo:
run("demo/demo_benchmark_rf2d.m")Run the CRF example with the project sample tables:
run("demo/demo_crf_rf2d.m")Generate HTML documentation or an installable MATLAB toolbox with:
docs.generateDocs
toolbox.buildToolboxGenerated HTML is written to docs/html/, and the toolbox package is written to dist/.
Run the complete test suite:
results = runtests("tests", "IncludeSubfolders", true);
table(results)Run the suite with an HTML coverage report:
import matlab.unittest.TestRunner
import matlab.unittest.plugins.CodeCoveragePlugin
import matlab.unittest.plugins.codecoverage.CoverageReport
suite = testsuite("tests", "IncludeSubfolders", true);
runner = TestRunner.withTextOutput;
runner.addPlugin(CodeCoveragePlugin.forFolder( ...
pwd, ...
"Producing", CoverageReport("tests/coverage")));
results = runner.run(suite);Zhang, Z.Y. (2023). Homogeneous Site Geotechnical Parameter Random Field Simulation System V1.0. Computer Software Copyright Registration No. 2023SR1776592, China. Registered December 2023.


