GSTools v1.3: a toolbox for geostatistical modelling in Python

. Geostatistics as a subﬁeld of statistics accounts for the spatial correlations encountered in many applications of, for example, earth sciences. Valuable information can be extracted from these correlations, also helping to address the often encountered burden of data scarcity. Despite the value of additional data, the use of geostatistics still falls short of its potential. This problem is often connected to the lack of user-friendly software hampering the use and application of geo-statistics. We therefore present GSTools , a Python-based software suite for solving a wide range of geostatistical problems. We chose Python due to its unique balance between usability, ﬂexibility, and efﬁciency and due to its adoption in the scientiﬁc community. GSTools provides methods for generating random ﬁelds; it can perform kriging, variogram estimation and much more. We demonstrate its abilities by virtue of a series of example applications detailing their use.

Addressing these challenges, we present GSTools -an extensive Python package for geostatistical analysis (Müller and Schüler, 2021).To the best of our knowledge, no opensource Python package that provides such a comprehensive collection of random field generation, forward modelling, kriging and data analysis currently exists.
We believe that the choice of Python has the potential to address several of the challenges for geostatistical applications.First, a script language like Python allows for striking a balance between ease of use (as provided by graphical user interfaces) and flexibility (as provided by command-linebased tools).The presence of a graphical user interface (GUI) is sometimes seen as an indication of usability (Remy, 2005;Rubin et al., 2018).However, a GUI does not necessarily make software more user-friendly, almost always limits flexibility, increases the programming effort, and makes reproducibility of results and workflows harder or even unfeasible (Queiroz et al., 2017).Also note that in recent years pow-Published by Copernicus Publications on behalf of the European Geosciences Union.S. Müller et al.: GeoStatTools erful tools emerged in data science to represent data along with code snippets, documentation and results in interactive computational notebooks provided by Jupyter (Perkel, 2018;Beg et al., 2021).Second, Python is known as a glue language, being able to combine independent software solutions to achieve complex workflows.This is particularly important since geostatistics often relies on ready-made solvers for data generation or partial differential equation (PDE)based model solvers.Third, Python is a simple yet powerful language with an increasing user base and community support for scientific computing and data analysis.It thus has a wide appeal and excellent prospects for the foreseeable future.This guarantees that engineers and scientists with only a moderate background in computer science are able to apply the toolbox and to make the necessary application-specific adjustments.Finally, the licensing should be as permissive as possible to guarantee adoption and even further development by interested users.
We introduce GSTools and present its main features with a general overview of its functionality and abilities in Sect. 2. We focus on the covariance model, field generation kriging and variogram estimation.In Sect.3, we discuss the wider context of GSTools, namely a number of Python packages connected with GSTools which can be used to seamlessly model geostatistical workflows.Section 4 presents a number of workflows to showcase the abilities of GSTools and demonstrate its usage.We close out with a short summary of the main advantages of GSTools and concluding remarks.

Covariance models and variography
The powerful CovModel class represents covariance and variogram models.Methods provided by this class are the basis for most of the functionality of GSTools, such as variography, spatial random field generation and kriging.

Covariance models
GSTools implements a CovModel class to define covariance models of weakly stationary (spatial) processes.Here, weak stationarity means that the associated semi-variogram is bounded, since we assume a constant mean and a finite variance.To approximate unbounded variograms such as the power-law model (Webster and Oliver, 2007), we provide a set of truncated power-law models following Di Federico and Neuman (1997).The internal representation of a (semi-)variogram γ is given by where r is the (isotropic) lag distance, is the (main) correlation length, s is a rescaling factor to adjust model representation (default is 1), σ 2 is the variance or partial sill, n is the nugget or sub-scale variance, and cor(h) is the modeldefining, normalized correlation function depending on the non-dimensional distance h = s • r .The associated covariance and correlation functions are given by the following: Note that covariance and correlation are neglecting the nugget effect at the origin.Thus, the variance is interpreted as the variation above the nugget, which is sometimes referred to as the partial sill of the semi-variogram or the correlated variability (Rubin, 2003).Consequently, the sill or limit of the semi-variogram is calculated as the sum of variance and nugget.
The (semi-)variogram, covariance and correlation functions of a model are accessible through model.variogram,model.covarianceand model.correlation,respectively.Every covariance model is defined by at least six parameters: dimension dim, variance var, main length scale len_scale, rescale factor rescale, anisotropy ratios anis and rotation angles angles, with the last two being dimension dependent.Figure 1 shows an example code for instantiating an exponential model and the resulting model functions exemplifying the parameters.Table 1 provides an overview of the predefined models in GSTools.
In addition to the predefined covariance models, users can specify their own model functions by providing a normalized correlation function.Figure 2 shows a reimplementation of the exponential model in only three lines of code.
The dimension-dependent spectrum of an isotropic covariance model can be called with model.spectrum.It is directly calculated from the covariance function by the following: Here, r = |r| and k = |k| are the norms of the corresponding vectors, and H is the Hankel transform, which provides a mathematically self-contained and numerically robust formulation of the radially symmetric Fourier transformation.GSTools makes use of an implementation of H provided by the Python package hankel (Murray and Poulin, 2019;Ogata, 2005).For models with a known analytical solution, GSTools uses them for improved computations.
A prerequisite for kriging or random field generation is that the applied covariance function is positive (semi-)definite.That can be checked through the spectral  (Rubin, 2003).Note that the rescaling factor is 1 by default.The right panel shows the plot of the variogram, covariance and correlation functions of the model, which can be created with convenience plotting methods. Matern Rasmussen and Williams ( 2005) Rasmussen and Williams ( 2005) Chilès and Delfiner (2012) Linear (1 − h) (h<1) Webster and Oliver (2007) Circular Webster and Oliver ( 2007) Webster and Oliver ( 2007) Matérn ( 1960) Matérn ( 1960) Chilès and Delfiner ( 2012) Wendland (1995) Di Federico and Neuman (1997) Di Federico and Neuman (1997) Formulas including the subscript (h < 1) are piecewise-defined functions being constantly zero for h ≥ 1.Here, h is the non-dimensional distance, d is the dimension, (x) is the gamma function, K ν (x) is the modified Bessel function of the second kind, J ν (x) is the Bessel function of the first kind, 2 F 1 (a, b, c, x) is the ordinary hyper-geometric function and E ν (x) is the exponential integral function (Abramowitz et al., 1972).All other variables are shape parameters of the respective models.
https://doi.org/10.5194/gmd-15-3161-2022Geosci.Model Dev., 15, 3161-3182, 2022  density which is derived by the following (note that S only depends on the norm of k): From Bochner's theorem (Rudin, 1990), it follows that the spectral density is a probability density function if and only if the underlying covariance function is positive (semi-)definite, which all predefined models in GSTools satisfy.As a consequence, the error variance during kriging is always non-negative.

Anisotropy and rotation
Variograms are typically defined based on the lag distance r, resulting in an isotropic model.However, many natural processes involve anisotropy with varying correlation ranges in different (orthogonal) directions.An example is hydraulic conductivity, where anisotropy typically arises from the geologic stratification.The implementation of anisotropy in GSTools is based on the non-dimensional distance (Rubin, 2003): where = s • 1 is the main length scale incorporating the rescale factor s, e i = i 1 represents the anisotropy ratios and r = (r 1 , r 2 , . ..) represents the distances along the main axis of correlation resulting in the isotropic distance r.Consequently, GSTools uses a main length scale, a set of anisotropy ratios and a set of rotation angles to fully describe an anisotropic model.
In practice, the main directions of correlation do not necessarily follow the principal axis.The CovModel accounts for rotation through rotation angles, where their number m depends on the dimension d: m = d•(d−1) 2 .In two dimensions, rotation is fully described by a single angle for rotation in the xy plane, and in three dimensions three angles are applied to the xy plane, xz plane and yz plane, respectively.In three dimensions these are often referred to as Tait-Bryan angles yaw, pitch and roll (Goldstein, 1980); see Fig. 3 for an example.One unique feature of GSTools is the support of arbitrary dimensionality in all provided routines.For rotation in higher dimensions, we apply the following scheme: the first angles coincide with those of the next lower dimension, and the added d − 1 angles describe rotations in the planes of the added dimension (in 3D: xz and yz).Thus, there are 6 rotation angles in 4D, 10 in 5D, etc. Rotation in higher dimensions is only relevant for spatio-temporal modelling with three spatial dimensions and application to other fields of research with high-dimension data.The scheme was chosen for metric spatio-temporal models to account for spatial anisotropy in a similar way as a simple spatial model.
Rotation in the x i x j plane is described by the matrix The order of rotating planes is determined by the described scheme, i.e.
The alternating signs of the rotation angles (−1) i−1 α i were chosen to match Tait-Bryan angles in 3D.

Geographical coordinates
Earth's surface is a non-Euclidean manifold, and all largescale, geographically referenced data will necessarily reflect that.We deal with the non-Euclidean nature of this kind of data by assuming the Earth to be a perfect sphere and then using the fact that the distance between two points ) is given by their latitude (φ) and longitude (λ) and can be described by a central angle calculated from the great circle distance: A huge family of valid models on the sphere can be derived from 3D models by inserting the chordal distance which results in the associated Yadrenko covariance model C Y (Lantuéjoul et al., 2019): The underlying manifold introduces new restrictions for covariance models to be positive definite.The manifold structure of the sphere only allows for isotropic models.For small-scale applications, it is valid to assume anisotropy.An appropriate adaption is the use of a 2D projection like Gauss-Krüger coordinates.We provide Yadrenko models as a unified representation for non-Euclidian coordinates since they facilitate all presented models to be used with geographical coordinates as demonstrated in Fig. 4.

Empirical variogram, data preparation and model fitting
The empirical variogram is an important tool for analysing spatially correlated data.It is estimated with the subpackage gstools.variogram,which provides two estimators for the empirical variogram: Matheron and Cressie (Webster and Oliver, 2007).The default Matheron's estimator for a variogram γ of a spatial random field U is given by where M(r) is the set of all pairwise spatial random field points, separated by the distance r and a certain tolerance ε > 0. Cressie's estimator, which is more robust to outliers, is given by Both estimators require predefined bins M(r) to group the pairwise point distances of the given field.GSTools provides a standard binning routine, where the maximal bin width is set to one-third of the diameter of the containing box of the field, the number of bins is determined by Sturges' rule (Sturges, 1926) and all bins have equal width.Figure 5 provides an example of the variogram estimation of an unstructured spatial random field with automatic binning.
GSTools accounts for anisotropy by providing estimating routines for directional variograms along a specified direction with a certain angle tolerance and bandwidth.When providing orthogonal axes, it is possible to fit a theoretical model and its anisotropy ratios as shown in Fig. 6.Determining the main rotation axes from given data, however, is up to the user and beyond the scope of the presented GSTools version.
Field data often do not follow a normal distribution, which is a crucial assumption for variogram estimation.For example, transmissivity is usually assumed to be lognormally distributed (Dagan, 1989), while rainfall data are normalized by applying the Box-Cox transformation (Cecinati et al., 2017).GSTools provides a set of normalizers based on power transforms, which can be fitted to a given data set using a maximum likelihood approach (Eliason, 1993): LogNormal, BoxCox (Box and Cox, 1964), YeoJohnson (Yeo and Johnson, 2000), Modulus (John and Draper, 1980) and Manly (Manly, 1976).An example application is shown in Fig. 7, and a comparison of all provided normalizers can be seen in Fig. 8.
GSTools also provides routines to detrend data.For example, temperature could decrease with elevation or conductivity could decrease with depth.Another application is analysing spatial correlation of residuals after application of a regression model to the data.All routines dealing with data have the keywords trend, normalizer and mean, where the last keyword describes the mean of the normalized data.
2.2 Kriging, random fields and conditioned random fields

Kriging
The subpackage gstools.krigeprovides routines for Gaussian process regression, also known as kriging, which is a method of data interpolation based on predefined covariance models (Wackernagel, 2003).Kriging aims to derive the value of a field z at some point x 0 , when there are fixed conditioning values z(x 1 ). ..z(x n ) at given points x 1 . ..x n .The resulting value z 0 at x 0 is calculated as a weighted mean z 0 = n i=1 w i • z i , where the weights, w = (w 1 , . .., w n ), are determined by the specific kriging routine.
We provide multiple kriging routines derived from the Krige class.(i) Simple: the data are interpolated with a given mean value for the kriging field.(ii) Ordinary: the mean of the resulting field is unknown and estimated alonghttps://doi.org/10.5194/gmd-15-3161-2022 Geosci.Model Dev., 15, 3161-3182, 2022  side the interpolation (unbiasedness).(iii) Universal: in addition to ordinary kriging, one can provide drift functions f 1 , . .., f k .(iv) ExtDrift: like universal kriging but the drift is provided by an external source.The advantage of using the general Krige class is the combination of all described features, such as for instance using universal kriging with a functional drift together with additional external drifts.A typical scenario is a temperature interpolation with an assumed north-south drift (functional drift) and a linear correlation to altitude (external drift).
Since all variogram models in GSTools assume weak stationarity, the kriging system is always built on the asso-ciated covariance function:   and E 0 = (e i0 ) T i=1...l at the target point, where l is the number of external drifts.The parameters µ, φ = (φ 1 , . .., φ k ) T and ψ = (ψ 1 , . .., ψ l ) T are Lagrange multipliers for the unbiased condition, the functional drifts and the external drifts, respectively.The vector 1 and its Lagrange multiplier µ are given in brackets since their appearance depends on whether the system should be unbiased or not (ordinary vs. simple kriging).Note that the number of functional drifts k and external drifts l can be zero, depending on whether they are given or not.
GSTools also provides the possibility to incorporate measurement errors variances σ 2 i for each conditioning point by adjusting the covariance matrix (Wackernagel, 2003): By default, the measurement error variances, σ 2 i , are set to the model nugget.In order to get numerically stable results, we solve the kriging system with the pseudo-inverse matrix, which has the advantage that redundant data or multiple mea-surements at the same location are averaged out in the resulting field (Mohammadi et al., 2017).
One last feature is the capability of kriging the mean (Wackernagel, 2003), which allows for deriving the mean value estimated during ordinary kriging or estimating the mean drift determined from given functional and/or external drift terms as shown in Fig. 9.A minimal example for regression kriging is shown in Fig. 10.

Random fields
A core element of GSTools is the spatial random field generator class SRF.A covariance model (Sect.2.1) is needed to instantiate a spatial random field.We provide two ways for field generation: structured or unstructured.In both cases, the positions at which the field will be evaluated are given by a pos argument.In the structured case, pos contains one tuple per dimension, each defining the subdivision of the corresponding axis resulting in a rectilinear grid.For unstructured grids, the pos tuple contains the x, y and z coordinates of every evaluation point.SRF allows for controlling the underlying pseudo-random number generation by a seed to reproduce field generation.A code example is given in https://doi.org/10.5194/gmd-15-3161-2022 Geosci.Model Dev., 15, 3161-3182, 2022  Fig. 11.Field generation is performed through the randomization method (Kraichnan, 1970;Heße et al., 2014), which utilizes the spectral density (Eq.5) of the variogram model to approximate a Wiener process in Fourier space by where N is the number of Fourier modes of the approximation.The random variables Z 1,i , Z 2,i ∼ N (0, 1) are mutually independent and are drawn from a standard normal distribution.The k i values are mutually independent random samples, which are drawn from the spectral density with the aid of emcee, a Python package for Markov chain Monte Carlo sampling (Foreman-Mackey et al., 2013).The randomization method is implemented in the RandMeth class and used by default.The RandMeth routines create isotropic random fields.Thus, the corresponding covariance is radially symmetric, and the spectral density can be calculated by the Hankel transformation.Anisotropy is realized by rescaling and rotating the input points.The work-flow allows users to generate a random field only from a given correlation, covariance or variogram function.
A key advantage of the randomization method implementation is the possibility to extend a generated SRF seamlessly, which not only preserves its statistical properties but also preserves the actual realization of the SRF.Potential applications are the following.(i) Particle simulations, where random incompressible velocity fields can be generated exactly at the location of the individual particles (see workflow in Sect.2.3.1).It avoids interpolation errors, arising from gridbased velocity fields.(ii) If concentration plumes are simulated on a large domain, the SRF can be calculated on demand only for the time dependent spatial extent of the plume.And (iii) for high-performance computing applications, the field generation can be directly coupled to the domain decomposition, and each task only generates the SRF for its part of the domain.There are two main classes of alternative methods to the randomization method (Heße et al., 2014).By decomposing the covariance function, small spatial random fields can be computed very fast.But the computational cost quickly becomes unfeasible as the field grows in size.A second and quite popular class is the sequential Gaussian method, which can also create conditioned spatial random fields.However, numerical problems can arise if the underlying correlation function is smooth at the origin, and the computational costs also become unfeasible for highly resolved random fields (Emery, 2004).
Just like the kriging routines, the spatial random field generator allows for incorporating predefined trend, normalizer and mean for a greater variety of distributions.A special SRF class feature is the capability to perform variance upscaling to respect generation of random fields on mesh cells with a certain volume.We hereby use the upscaling method coarse graining (Attinger, 2003) to rescale the variance in Eq. ( 19) at each target point based on a given filter volume size λ: where is the correlation length, and λ = d √ V is the filter size derived from the cell volume V depending on the field dimension, assuming the cell element is a hypercube.This approach was derived from the groundwater flow equation, assuming a Gaussian covariance model and should therefore be used with caution in differing scenarios.An example is provided in the workflow in Sect.4.3.

Conditioned random fields
When point measurements of a target variable are available, they need to be considered when generating random fields.GSTools provides a class CondSRF combining kriging and random field generation, where we first derive the kriged field and the error variance and then generate a random field with zero mean where the variance in Eq. ( 19) is replaced with the estimated error variance.This procedure is advantageous to classical sequential Gaussian simulation (Webster and Oliver, 2007), as (i) we make use of the randomization method to generate a single random field, and (ii) we only need to solve the kriging problem once and not sequentially.
Figure 12 shows an example of an ensemble of conditioned random fields in one dimension.Where measurements of the target variables are available, all realizations satisfy them.However, random fields behave as unconditional fields (i.e. of an ensemble with identical parameters, like mean, variance and correlation length) where no point measurements are available (x > 6).Characteristics, such as the ensemble variance, significantly change given the distribution of measurements and conditioning.The ensemble mean and the kriging field coincide, proving that the kriging field is the best linear unbiased predictor for the given data.

Additional features
2.3.1 Incompressible random vector field generation Kraichnan (1970) was the first to suggest a randomization method for studying the diffusion of single particles in a random incompressible velocity field.He came up with a randomization method which includes a projector, ensuring the incompressibility of the vector field.
When U is the mean velocity (oriented towards the first basis vector e 1 ), we generate random fluctuations with a given covariance model around U .And at the same time, we ensure that the velocity field remains incompressible; that is, ∇ •U = 0 by using the randomization method (Eq.19) and adding a projector p(k i ) to every mode being summed: Calculating ∇ •U = 0 verifies that the resulting field is indeed incompressible.An example is shown in Fig. 13.Things like boundary conditions cannot be modelled with this method, but it can be used, for example, in transport simulations of the saturated subsurface (Schüler et al., 2016) or for studying turbulent open water (Kraichnan, 1970).

Field transformations
GSTools generates Gaussian random fields while real data often do not follow a Gaussian distribution.This is typically addressed through data transformation.Transformations can be combined sequentially to create more complex scenarios as in Fig. 14.Note that, in contrast to normalizers, transformations cannot be fitted to given data, which leaves the choice of the best transformation to the user.

Spatio-temporal modelling
Spatio-temporal modelling provides insights into timedependent stochastic processes like rainfall, air temperature or crop yield, which is of high practical relevance.GSTools provides the metric spatio-temporal model (Cressie and Wikle, 2011) for all covariance models by enhancing the spatial with a time dimension, resulting in the spatio-temporal dimension d st : where r is the isotropified spatial distance as defined in Eq. ( 6), t is the temporal distance and t the isotropified temporal distance.The parameter κ accounts for a spatiotemporal anisotropy ratio and is the last entry of the anis array appended to the spatial anisotropy ratios.The implementation in GSTools enables the direct incorporation of spatial anisotropy and rotation in a spatio-temporal model.It further supports the use of arbitrary spatial dimensions in spatio-temporal models.Figure 15 shows the generation of a spatio-temporal random field with one spatial dimension.

Working on meshes
For improved handling of spatial random fields as input for PDE solvers like the finite element method (FEM), GSTools provides an interface for a number of mesh standards, such as meshio (Schlömer et al., 2021), PyVista (Sullivan and Kaszynski, 2019) and ogs5py (Müller et al., 2020).When using meshio or PyVista, the generated fields will be stored immediately in the mesh container.There are two options to generate a field on a given mesh: either on the points (points="points") or on the cell centroids (points="centroids"), which is important depending on the specification of the variable in the numerical scheme.Figure 16 provides an example.
3 GSTools within the ecosystem of the GeoStat Framework GSTools is part of a larger suite of Python packages, collectively hosted on GitHub under https://github.com/GeoStat-Framework (last access: 31 March 2022).The other packages in the GeoStat Framework complement some of the abilities of GSTools and form a comprehensive framework for geostatistical applications.We introduce some packages and demonstrate how they interact with, enhance and leverage the abilities of GSTools.

ogs5py
ogs5py (Müller et al., 2020) provides a Python API for the FEM-based OpenGeoSys 5 (Kolditz et al., 2012) scientific software suite for hydrogeological processes like groundwater flow and transport modelling where data scarcity is a typical shortcoming.Examples are point measurements of hydraulic head from observation wells and breakthrough curves from tracer experiments.Inferring hydraulic conductivity from these data requires a modelling framework with integrated stochastic data generation.The combination of GSTools with ogs5py enables a user to integrate the geostatistical modelling of an aquifer with hydrogeological simulations.Such an example for pumping test simulations is provided in Sect.4.3.

welltestpy and AnaFlow
A pumping test is a cost-effective subsurface observation method typically used by hydrogeologists for aquifer characterization.The package welltestpy (Müller et al., 2021b) provides tools to handle, process, plot and analyse data from pumping test campaigns.It assists practitioners in identifying hydrogeological parameters by fitting measured drawdowns to some conceptual flow model.The package contains a number of examples that illustrate these abilities.
AnaFlow (Müller et al., 2021a) provides a wide range of analytical expressions for pumping tests under various conditions.Classical examples are Thiem's and Theis' solution assuming homogeneous aquifer properties.In addition, AnaFlow provides extended versions of both solutions, which account for aquifer heterogeneity and allow for esti-   mating higher-order geostatistical parameters like variance and correlation length (Zech et al., 2012(Zech et al., , 2016)).

PyKrige
GSTools provides an interface to the stand-alone package PyKrige (Murphy et al., 2021) for more specialized kriging applications.After 10 years of independent development, PyKrige has recently been migrated to the GeoStat Framework, and its functionality is currently integrated with the other packages.So far, the covariance model can be exchanged between the packages.In the future, PyKrige will become the kriging toolbox for the GeoStat Framework, providing advanced methods.

Interoperability
To integrate GSTools into the Scientific Python Stack, we provide a set of interfaces to other packages.These include the above-mentioned packages ogs5py, meshio, PyVista and pyevtk (https://github.com/pyscience-projects/pyevtk, last access: 31 March 2022 ) for mesh operations.Other packages for geostatistics are also supported, such as PyKrige (Sect.3.3) and scikit-gstat (Mälicke, 2022), the latter having a focus on variography and can be used for more detailed variogram estimation.For both packages, interfaces are provided to convert covariance models of GSTools to or from their counterparts in the respective package.Another package worth mentioning is verde (Uieda, 2018), a Python library for processing and gridding spatial data.Some of the features provided there can be easily combined with capabilities of GSTools such as detrending data to preprocess inputs.Kriging is a well-established interpolation method applied in many fields of natural science.We compare two options of incorporating auxiliary variables to calculate the kriging weights: (i) regression kriging (RK), where the trend of input data is estimated by regression and simple kriging is applied to the residuals, and (ii) universal kriging (UK), where the         with temperature decreasing with latitude.A potential explanation here is the general temperature increase towards the Equator.While the UK mean fits better with the cross-section at 10 • longitude (Fig. 21), the RK mean fits the scatter diagram better, as expected.

Heterogeneous transport simulation: the impact of connectivity
The combination of ogs5py and GSTools makes it possible to quickly set up and run subsurface flow and transport simulations in a heterogeneous aquifer setting.The critical step is the generation of a spatially distributed hydraulic conductivity distribution, adapted to the numerical simulation grid.We further demonstrate GSTools' ability to generate different connectivity structures, and we discuss their impact on transport results.The resources for this workflow are provided in Müller and Zech (2021a).
A flow and transport model is initialized through an instance of the OGS class from ogs5py, with simple mesh generation (Fig. 22) and specification of model parameters and boundary conditions.Random fields are initialized through the SRF class (Fig. 23).By passing the subclass model.msh,mesh details are transferred for generating distributed values at particular mesh locations, even for unstructured grids.The subroutine transform.zinnharveyallows for generating Gaussian structures where the mean values of the field are not connected but the low-or highconductivity areas are connected, using the transformation by Zinn and Harvey (2003).Note that the correlation lengths undergo rescaling (Gong et al., 2013).The concept of connectivity follows the paper by Zinn and Harvey (2003), where connectedness refers to connected paths of extreme or special values in the conductivity field.
Simulated tracer plumes in Fig. 24 show the particular effects of connectivity: the plume remains relatively compact for classical Gaussian fields, where mean values are connected.Transformed fields lead to more disrupted, dynamic plumes, which is mostly caused by trapping in areas of connected low conductivity and preferential flow in connected high-conductivity areas. https://doi.org/10.5194/gmd-15-3161-2022 Geosci.Model Dev., 15, 3161-3182, 2022

Characterizing mean drawdowns of a pumping test ensemble
Combining flow simulations in ogs5py with random fields of GSTools allows for performing Monte Carlo studies to identify ensemble mean behaviour.Zech et al. (2016) made use of this workflow to prove the applicability of an effective drawdown solution for pumping tests in random conductivity.We present a short form of their workflow, which is accessible in Müller and Zech (2021b).The flow model is initialized through the OGS class with model parameters and boundary conditions creating the convergent flow setting of a pumping test.The mesh generation and time stepping can be specifically adapted to the non-uniform flow conditions.Ensembles of heterogeneous transmissivity fields are generated with the SRF class where reproducibility is controlled by the seed and where normal fields are converted in place with normalizer.LogNormal as shown in Fig. 25.
The implementation of the randomization method (Sect.2.2.2) allows for the adaption of random fields to the non-uniform grid.The associated variance upscaling follows the coarse graining procedure for Gaussian variograms according to Eq. ( 20).
Calculated ensemble means can be compared to analytical solutions (Fig. 26), such as Theis' solution for homogeneous media or the effective drawdown solution by Zech et al. (2016), making use of their implementations in welltestpy and AnaFlow.

Geostatistical exercises with the Herten aquifer
We demonstrate how to estimate variograms and how to condition spatial random fields on observations using data from the Herten aquifer analogue (Bayer et al., 2011).The aquifer analogue was created from surveying multiple outcrop faces at a gravel pit, situated in the Rhine valley in southern Germany.The 2D information was interpolated to a 3D data set, including hydraulic, thermal and chemical information.The workflow files are provided in Schüler and Müller (2021).
We determine spatial correlations through variogram estimation using gstools.variogram.First, we identify the full transmissivity structure.The aquifer analogue data are given in a facies structure with one hydraulic conduc-tivity value K per facies.We calculate transmissivity by integrating the hydraulic conductivity over the vertical axis T (x, y) = K(x, y, z) dz.The structured transmissivity is shown in Fig. 27, which we consider as true distribution for the following exercises.
We select 13×13 virtual observations on a rectangular grid (Fig. 27), covering a subarea of about 42 m 2 .These observations are used to determine the empirical variogram shown in Fig. 28.We fit an exponential covariance model to the data, which suits well with a coefficient of determination of R 2 = 0.913.We use the fitted exponential variogram model and ordinary kriging to create conditioned spatial random fields with CondSRF. Figure 29 shows one realization and the absolute difference to the true transmissivity (Fig. 27).Differences grow with increasing distance from observations.This trend can be even better seen in a transmissivity transect shown in Fig. 30.The standard deviation calculated from 20 realizations of conditioned SRFs shows that deviations from the reference field are significantly lower close to observation points.

Conclusions
The GSTools package provides a Python-based platform for geostatistical applications.It is similar to software packages like gstat for R or stand-alone packages like TPROGS (Carle, 1999), GSLIB (Deutsch and Journel, 1997) and S-GeMS (Remy, 2005).However, we believe that a comprehensive and ready-made geostatistical software package for Python has advantages, simply through the choice of the programming language, as it has a gentle learning curve, is often used as a glue language and is widely adopted by the scientific community.Salient features of GSTools are its random field generation and its versatile covariance model.It is furthermore integrated with other Python packages, like PyKrige (Murphy et al., 2021), ogs5py (Müller et al., 2020) or scikit-gstat (Mälicke, 2022), and provides interfaces to meshio (Schlömer et al., 2021) and PyVista (Sullivan and Kaszynski, 2019).GeoStat Examples (https: //github.com/GeoStat-Examples,last access: 31 March 2022 ) provides a number of applications, including the four presented workflows.They showcase the abilities of GSTools and can serve as a starting point for practitioners to develop their own solutions for the geostatistical problems they face.

Figure 1 .
Figure1.Initialization of an exponential covariance model given by cor(h) = exp(−h)(Rubin, 2003).Note that the rescaling factor is 1 by default.The right panel shows the plot of the variogram, covariance and correlation functions of the model, which can be created with convenience plotting methods.

Figure 2 .
Figure 2. Initialization of a user-defined exponential covariance model.The only thing that needs to be defined is the normalized correlation function cor.

Figure 3 .
Figure 3. Spatial covariance structure of an anisotropic exponential model in 3D plotted with the built-in interactive routines of GSTools.The example shows an eighth turn on the xy plane with anisotropy factors (1/2, 1/4).Rotation angles are given in radians.

Figure 4 .
Figure 4. Initialization of a Yadrenko covariance model.We use the Earth's radius as the rescaling factor to have a meaningful length scale.The routine vario_yadrenko still depends on the central angle given in radians.

Figure 5 .
Figure 5. Estimating an empirical variogram of synthetic unstructured data and fitting an exponential model.The number of bins was calculated to be 21 with a maximum bin distance of ca.45.
plane) I 3 = [2, 3] (yz plane), etc.These values define a rotation matrix Rot to transform principal axes to the directions of correlation and the back-rotation matrix DeRot = Rot −1 for the inverse:

Figure 6 .
Figure 6.Estimation of directional variograms for given main axes: the code snippet shows the setup for estimating and fitting the variogram to an anisotropic field.The graphs show the main axes of the rotated model and the fitting results.Plotting commands have been omitted.

Figure 7 .
Figure 7. Estimating an empirical variogram (bottom left) of synthetic unstructured data (top left) after Box-Cox normalization of skewed input values.Panels on the right show the histogram of the data values before (top) and after (bottom) the normalization.For demonstration purposes, a Matern model was fitted to the empirical variogram.Plotting commands have been omitted.

Figure 9 .
Figure 9.Comparison of simple, ordinary and universal kriging.All three routines have a similar setup, where simple kriging needs an estimated mean and where universal kriging needs additional drift functions.Plotting commands have been omitted.

Figure 10 .
Figure 10.A simple setup for linear regression kriging.Although the interpolation coincides with a piecewise linear function, we gain information about the error variances between the conditioning points as shown in the right plot.
C = (C(x i , x j )) ij =1...n being the covariance matrix, depending on the conditioning points and the given model.C 0 = (C(x i , x 0 )) T i=1...n is the covariance vector for the target point x 0 .F = (f j (x i )) i=1...n,j =1...k is a submatrix containing the functional drift values at the conditioning points and F 0 = (f i (x 0 )) T i=1...k at the target point, where k is the number of functional drifts.E = (e ij ) i=1...n,j =1...l is a submatrix containing the external drift values at the conditioning points

Figure 11 .
Figure 11.Generation of a structured random field following a Gaussian variogram.

Figure 12 .
Figure 12.An example for an ensemble of 1D random fields conditioned to five measurements (dots).Plotting commands have been omitted.

Figure 13 .
Figure 13.Generation of a structured incompressible random vector field with exponential variogram.

Figure 14 .
Figure 14.Example of a log-transformed binary field with the low values being connected by applying the zinnharvey, binary and lognormal transformations successively.

Figure 15 .
Figure 15.A workflow to generate a spatio-temporal random field with one spatial dimension.

Figure 16 .
Figure16.Generating spatial random fields on finite element method (FEM) meshes: either on cell centroids (middle) or mesh points (right).Plotting commands have been omitted.

Figure 17 .
Figure 17.Estimating the temperature variogram with geographic coordinates using the spherical Yadrenko model.Estimated length scale is ca.0.9 (radians) and sill is around 13.

Figure 18 .
Figure 18.Setting up universal kriging with a drift function.

Figure 19 .
Figure 19.Workflow for regression kriging with a linear regression model.

Figure 21 .
Figure 21.Scatterplot of latitude-temperature values (grey dots), the linear regression result (dashed orange line), universal kriging mean drift (dashed blue line) and the cross-sections of the respective kriging interpolation (solid lines).

Figure 22 .
Figure 22.Initialization of an OGS model with mesh generation.

Figure 23 .
Figure 23.Generating correlated log-normal SRFs adapted to the mesh settings of the numerical model for three connectivity structures following the Zinn and Harvey (2003) transformation.

Figure 25 .
Figure 25.Workflow to generate an ensemble of transmissivity fields on a given mesh (a).A single realization in shown in the right plot (b).

Figure 26 .
Figure 26.Comparison the ensemble mean drawdown h(r, t) (a, d) with the effective head solution h CG (r, t) (c, f) for two parameter sets.The vanishing absolute difference between both (b, e) shows that they perfectly agree.

Figure 18
Figure 18 shows how to set up the UK estimator, including the drift function, and Fig. 19 shows the setup of the RK estimator.RK requires the preceding of fitting the regression model for the trend of the Detrended kriging routine.The interpolation results are shown in Fig. 20, indicating that both methods provide equally good results.

Figure 21
Figure21shows the estimated mean trends for both UK and RK, revealing completely contrary results.The RK result indicates an increase in mean temperature with increasing latitude, which seems reasonable given a raising terrain elevation from the Baltic Sea in the north towards the Alps in the south.The estimated mean of UK shows the opposite

Figure 27 .
Figure 27.Transmissivity of the Herten aquifer analogue and locations of virtual observations marked as black dots.

Figure 29 .
Figure 29.One realization of the conditioned SRF (a) and absolute difference (b) between the "true" (Fig. 27) and conditioned transmissivity, showing increasing differences with distance from the conditioning area (rectangle).

Figure 30 .
Figure 30.Generation of an ensemble of 20 conditional realizations and transmissivity transects T (x) at y = 4 m.The thick blue line is the true transmissivity (Fig. 27), and the shaded area shows the range of 1 standard deviation calculated from 20 realizations of conditioned fields.Black points indicate the observations.