SpaceTimeVariogram class

class skgstat.SpaceTimeVariogram(coordinates, values, xdist_func='euclidean', tdist_func='euclidean', x_lags=10, t_lags='max', maxlag=None, xbins='even', tbins='even', estimator='matheron', use_nugget=False, model='product-sum', verbose=False)[source]
__init__(coordinates, values, xdist_func='euclidean', tdist_func='euclidean', x_lags=10, t_lags='max', maxlag=None, xbins='even', tbins='even', estimator='matheron', use_nugget=False, model='product-sum', verbose=False)[source]

Initialize self. See help(type(self)) for accurate signature.

contour(ax=None, zoom_factor=100.0, levels=10, colors='k', linewidths=0.3, method='fast', **kwargs)[source]

Variogram 2D contour plot

Plot a 2D contour plot of the experimental variogram. The experimental semi-variance values are spanned over a space - time lag meshgrid. This grid is (linear) interpolated onto the given resolution for visual reasons. Then, contour lines are caluclated from the denser grid. Their number can be specified by levels.

Parameters
  • ax (matplotlib.AxesSubplot, None) – If None a new matplotlib.Figure will be created, otherwise the plot will be rendered into the given subplot.

  • zoom_factor (float) – The experimental variogram will be interpolated onto a regular grid for visual reasons. The density of this plot can be set by zoom_factor. A factor of 10 will enlarge each of the axes by 10. Higher zoom_factors result in smoother contours, but are expansive in calculation time.

  • levels (int) – Number of levels to be formed for finding contour lines. More levels result in more detailed plots, but are expansive in terms of calculation time.

  • colors (str, list) – Will be passed down to matplotlib.pyplot.contour as c parameter.

  • linewidths (float, list) – Will be passed down to matplotlib.pyplot.contour as linewidths parameter.

  • method (str) – The method used for densifying the meshgrid. Can be one of ‘fast’ or ‘precise’. Fast will use the scipy.ndimage.zoom method to incresae the node density. This is fast, but cannot interpolate behind any NaN occurance. ‘Precise’ performs an actual linear interpolation between the nodes using scipy.interpolate.griddata. This takes more time, but the result is less smoothed out.

  • kwargs (dict) – Other arguments that can be specific to contour or contourf type. Accepts xlabel, ylabel, xlim and ylim as of this writing.

Returns

fig – The Figure object used for rendering the contour plot.

Return type

matplotlib.Figure

contourf(ax=None, zoom_factor=100.0, levels=10, cmap='RdYlBu_r', method='fast', **kwargs)[source]

Variogram 2D filled contour plot

Plot a 2D filled contour plot of the experimental variogram. The experimental semi-variance values are spanned over a space - time lag meshgrid. This grid is (linear) interpolated onto the given resolution for visual reasons. Then, contour lines are caluclated from the denser grid. Their number can be specified by levels. Finally, each contour region is filled with a color supplied by the specified cmap.

Parameters
  • ax (matplotlib.AxesSubplot, None) – If None a new matplotlib.Figure will be created, otherwise the plot will be rendered into the given subplot.

  • zoom_factor (float) – The experimental variogram will be interpolated onto a regular grid for visual reasons. The density of this plot can be set by zoom_factor. A factor of 10 will enlarge each of the axes by 10. Higher zoom_factors result in smoother contours, but are expansive in calculation time.

  • levels (int) – Number of levels to be formed for finding contour lines. More levels result in more detailed plots, but are expansive in terms of calculation time.

  • cmap (str) – Will be passed down to matplotlib.pyplot.contourf as cmap parameter. Can be any valid color range supported by matplotlib.

  • method (str) – The method used for densifying the meshgrid. Can be one of ‘fast’ or ‘precise’. Fast will use the scipy.ndimage.zoom method to incresae the node density. This is fast, but cannot interpolate behind any NaN occurance. ‘Precise’ performs an actual linear interpolation between the nodes using scipy.interpolate.griddata. This takes more time, but the result is less smoothed out.

  • kwargs (dict) – Other arguments that can be specific to contour or contourf type. Accepts xlabel, ylabel, xlim and ylim as of this writing.

Returns

fig – The Figure object used for rendering the contour plot.

Return type

matplotlib.Figure

create_TMarginal()[source]

Create an instance of skgstat.Variogram for the time marginal variogram by arranging the coordinates and values and infer parameters from this SpaceTimeVariogram instance.

create_XMarginal()[source]

Create an instance of skgstat.Variogram for the space marginal variogram by arranging the coordinates and values and infer parameters from this SpaceTimeVariogram instance.

distance

Distance matrices

Returns both the space and time distance matrix. This property is equivalent to two separate calls of xdistance and tdistance.

Returns

distance matrices – Returns a tuple of the two distance matrices in space and time. Each distance matrix is a flattened upper triangle of the distance matrix squareform in row orientation.

Return type

(numpy.array, numpy.array)

experimental

Experimental Variogram

Returns an experimental variogram for the given data. The semivariances are arranged over the spatial binning as defined in SpaceTimeVariogram.xbins and temporal binning defined in SpaceTimeVariogram.tbins.

Returns

variogram – Returns an two dimensional array of semivariances over space on the first axis and time over the second axis.

Return type

numpy.ndarray

fitted_model
get_marginal(axis, lag=0)[source]

Marginal Variogram

Returns the marginal experimental variogram of axis for the given lag on the other axis. Axis can either be ‘space’ or ‘time’. The parameter lag specifies the index of the desired lag class on the other axis.

Parameters
  • axis (str) – The axis a marginal variogram shall be calculated for. Can either be ‘ space’ or ‘time’.

  • lag (int) – Index of the lag class group on the other axis to be used. In case this is 0, this is often considered to be the marginal variogram of the axis.

Returns

variogram – Marginal variogram of the given axis

Return type

numpy.array

lag_classes()[source]

Iterator over all lag classes

Returns an iterator over all lag classes by aligning all time lags over all space lags. This means that it will yield all time lag groups for a space lag of index 0 at first and then iterate the space lags.

Returns

Return type

iterator

lag_groups(axis)[source]

Lag class group mask array

Returns a mask array for the given axis (either ‘space’ or ‘time’). It will have as amany elements as the respective distance matrices. Unlike the base Variogram class, it does not mask the array of pairwise differences.. It will mask the distance matrix of the respective axis.

Parameters

axis (str) – Can either be ‘space’ or ‘time’. Specifies the axis the mask array shall be returned for.

Returns

masK_array – mask array that identifies the lag class group index for each pair of points on the given axis.

Return type

numpy.array

marginals(plot=True, axes=None, sharey=True, include_model=False, **kwargs)[source]

Plot marginal variograms

Plots the two marginal variograms into a new or existing figure. The space marginal variogram is defined to be the variogram of temporal lag class 0, while the time marginal variogram uses only spatial lag class 0. In case the expected variability is not of same magnitude, the sharey parameter should be set to False in order to use separated y-axes.

Parameters
  • plot (bool) –

    Deprecated since version 0.4: With version 0.4, this parameter will be removed

    If set to False, no matplotlib.Figure will be returned. Instead a tuple of the two marginal experimental variogram values is returned.

  • axes (list) – Is either None to create a new matplotlib.Figure. Otherwise it has to be a list of two matplotlib.AxesSubplot instances, which will then be used for plotting.

  • sharey (bool) – If True (default), the two marginal variograms will share their y-axis to increase comparability. Should be set to False in the variances are of different magnitude.

  • include_model (bool) – If True, the marginal variogram models fitted to the respective axis are included into the plot.

  • kwargs (dict) – Only kwargs accepted is figsize, if ax is None. Anything else will be ignored.

Returns

  • variograms (tuple) – If plot is False, a tuple of numpy.arrays are returned. These are the two experimental marginal variograms.

  • plots (matplotlib.Figure) – If plot is True, the matplotlib.Figure will be returned.

plot(kind='scatter', ax=None, **kwargs)[source]

Plot the experimental variogram

At the current version the SpaceTimeVariogram class is not capable of modeling a spe-time variogram function, therefore all plots will only show the experimental variogram. As the experimental space-time semivariance is depending on a space and a time lag, one would basically need a 3D scatter plot, which is the default plot. However, 3D plots can be, especially for scientific usage, a bit problematic. Therefore the plot function can plot a variety of 3D and 2D plots.

Parameters
  • kind (str) –

    Has to be one of:

    • scatter

    • surface

    • contour

    • contourf

    • matrix

    • marginals

  • ax (matplotlib.AxesSubplot, mpl_toolkits.mplot3d.Axes3D, None) – If None, the function will create a new figure and suitable Axes. Else, the Axes object can be passed to plot the variogram into an existing figure. In this case, one has to pass the correct type of Axes, whether it’s a 3D or 2D kind of a plot.

  • kwargs (dict) – All keyword arguments are passed down to the actual plotting function. Refer to their documentation for a more detailed description.

Returns

fig

Return type

matplotlib.Figure

preprocessing(force=False)[source]

Preprocessing

Start all necessary calculation jobs needed to derive an experimental variogram. This hasto be present before the model fitting can be done. The force parameter will make all calculation functions to delete all cached intermediate results and make a clean calculation.

Parameters

force (bool) – If True, all cached intermediate results will be deleted and a clean calculation will be done.

scatter(ax=None, elev=30, azim=220, c='blue', depthshade=True, **kwargs)[source]

3D Scatter Variogram

Plot the experimental variogram into a 3D matplotlib.Figure. The two variogram axis (space, time) will span a meshgrid over the x and y axis and the semivariance will be plotted as z value over the respective space and time lag coordinate.

Parameters
  • ax (mpl_toolkits.mplot3d.Axes3D, None) – If ax is None (default), a new Figure and Axes instance will be created. If ax is given, this instance will be used for the plot.

  • elev (int) – The elevation of the 3D plot, which is a rotation over the xy-plane.

  • azim (int) – The azimuth of the 3D plot, which is a rotation over the z-axis.

  • c (str) – Color of the scatter points, will be passed to the matplotlib c argument. The function also accepts color as an alias.

  • depthshade (bool) – If True, the scatter points will change their color according to the distance from the viewport for illustration reasons.

  • kwargs (dict) – Other kwargs accepted are only color as an alias for c and figsize, if ax is None. Anything else will be ignored.

Returns

fig

Return type

matplotlib.Figure

Examples

In case an ax shall be passed to the function, note that this plot requires an AxesSubplot, that is capable of creating a 3D plot. This can be done like:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# STV is an instance of SpaceTimeVariogram
STV.scatter(ax=ax)
set_bin_func(bin_func, axis)[source]

Set binning function

Set a new binning function to either the space or time axis. Both axes support the methods: [‘even’, ‘uniform’]:

  • ‘even’, create even width bins

  • ‘uniform’, create bins of uniform distribution

Parameters
  • bin_func (str) – Sepcifies the function to be loaded. Can be either ‘even’ or ‘uniform’.

  • axis (str) – Specifies the axis to be used for binning. Can be either ‘space’ or ‘time’, or one of the two shortcuts ‘s’ and ‘t’

set_model(model_name)[source]

Set space-time model

Set a new space-time model. It has to be either a callable of correct signature or a string identifying one of the predefined models

Parameters

model_name (str, callable) –

Either a callable of correct signature or a valid model name. Valid names are:

  • sum

  • product

  • product-sum

set_tdist_func(func_name)[source]

Set new space distance function

Set a new function for calculating the distance matrix in the space dimension. At the moment only strings are supported. Will be passed to scipy.spatical.distance.pdist as ‘metric’ attribute.

Parameters

func_name (str) – The name of the function used to calculate the pairwise distances. Will be passed to scipy.spatial.distance.pdist as the ‘metric’ attribute.

Raises

ValueError : in case a non-string argument is passed.

set_values(values)[source]

Set new values

The values should be an (m, n) array with m matching the size of coordinates first dimension and n is the time dimension.

Raises
  • ValueError : in case n <= 1 or values are not an array of correct – dimensionality

  • AttributeError : in case values cannot be converted to a numpy.array

set_xdist_func(func_name)[source]

Set new space distance function

Set a new function for calculating the distance matrix in the space dimension. At the moment only strings are supported. Will be passed to scipy.spatical.distance.pdist as ‘metric’ attribute.

Parameters

func_name (str) – The name of the function used to calculate the pairwise distances. Will be passed to scipy.spatial.distance.pdist as the ‘metric’ attribute.

Raises

ValueError : in case a non-string argument is passed.

surface(ax=None, elev=30, azim=220, color='blue', alpha=0.5, **kwargs)[source]

3D Scatter Variogram

Plot the experimental variogram into a 3D matplotlib.Figure. The two variogram axis (space, time) will span a meshgrid over the x and y axis and the semivariance will be plotted as z value over the respective space and time lag coordinate. Unlike scatter the semivariance will not be scattered as points but rather as a surface plot. The surface is approximated by (Delauney) triangulation of the z-axis.

Parameters
  • ax (mpl_toolkits.mplot3d.Axes3D, None) – If ax is None (default), a new Figure and Axes instance will be created. If ax is given, this instance will be used for the plot.

  • elev (int) – The elevation of the 3D plot, which is a rotation over the xy-plane.

  • azim (int) – The azimuth of the 3D plot, which is a rotation over the z-axis.

  • color (str) – Color of the scatter points, will be passed to the matplotlib color argument. The function also accepts c as an alias.

  • alpha (float) – Sets the transparency of the surface as 0 <= alpha <= 1, with 0 being completely transparent.

  • kwargs (dict) – Other kwargs accepted are only color as an alias for c and figsize, if ax is None. Anything else will be ignored.

Returns

fig

Return type

matplotlib.Figure

Notes

In case an ax shall be passed to the function, note that this plot requires an AxesSubplot, that is capable of creating a 3D plot. This can be done like:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# STV is an instance of SpaceTimeVariogram
STV.surface(ax=ax)
tbins

Temporal binning

Returns the bin edges over the temporal axis. These can be used to align the temporal lag class grouping to actual time lags. The length of the array matches the number of temporal lag classes.

Returns

bins – Returns the edges of the current temporal binning.

Return type

numpy.array

tdistance

Time distance

Returns a distance matrix containing the distance of all observation points in time. The time ‘coordiantes’ are created from the values multidimensional array, where the second dimension is assumed to be time. The unit will be time steps.

Returns

tdistance – 1D-array of the upper triangle of a squareform representation of the distance matrix.

Return type

numpy.array

values

Values

The SpaceTimeVariogram stores (and needs) the observations as a two dimensional array. The first axis (rows) need to match the coordinate array, but instead of containing one value for each location, the values shall contain a time series per location.

Returns

values – Returns a two dimensional array of all observations. The first dimension (rows) matches the coordinate array and the second axis contains the time series for each observation point.

Return type

numpy.array

xbins

Spatial binning

Returns the bin edges over the spatial axis. These can be used to align the spatial lag class grouping to actual distance lags. The length of the array matches the number of spatial lag classes.

Returns

bins – Returns the edges of the current spatial binning.

Return type

numpy.array

xdistance

Distance matrix (space)

Return the upper triangle of the squareform pairwise distance matrix.

Returns

xdistance – 1D-array of the upper triangle of a squareform representation of the distance matrix.

Return type

numpy.array