Skip to content

Time-Series Analysis

Trend tests, phenology, pattern matching, segmentation and clustering.

mann_kendall

zeit.mann_kendall(
    data, *, method="hamed_rao", alpha=0.05, lag=None, period=1,
    min_valid=4, dates=None, band=None, nodata="auto", chunks=None,
    n_jobs=-1,
)

Mann-Kendall trend test and Theil-Sen slope for every pixel, a Rust port of pymannkendall. One function for every input, like bfast_monitor: it reads what data is and returns an xarray.Dataset with one variable per metric, georeferenced when the input is. All parameters but data are keyword-only. It replaces zeit.trend.run_mann_kendall_dask, run_mann_kendall_image and DataArray.zeit.run_mann_kendall; the accessor form is now DataArray.zeit.mann_kendall. Tutorial: Trend Analysis.

data is any input of the BFAST family: a raster load_raster reads, a (time, y, x) cube (a dask cube stays lazy), a (time, band, y, x) cube or Dataset with band=, a numpy array or one pixel's series. No dates are needed: the test runs on the order of the observations, so the slope is per time step (one value per year gives a slope per year).

Parameter Type Default Description
data path, DataArray, Dataset, ndarray, list or pd.Series required The series to test, one value per time step.
method str "hamed_rao" "original", "hamed_rao" (autocorrelation-corrected, for annual composites), "yue_wang" or "seasonal" (Hirsch & Slack, pools period season slots).
alpha float 0.05 Significance level.
lag int None Lags used by the autocorrelation corrections. None: all.
period int 1 Observations per cycle, for "seasonal" (e.g. 23 for 16-day data).
min_valid int 4 Pixels with fewer valid values are NaN.
dates list None Date of each time step. Not needed: the test only uses the order of the observations.
band str or int None The index to use in a (time, band, y, x) cube or a Dataset.
nodata "auto", float or None "auto" Value marking a missing observation besides NaN, as in bfast_monitor.
chunks "auto", dict None Inputs read from disk: None reads into memory; "auto" or a dict keeps them lazy.
n_jobs int -1 Threads. -1: all the cores but one, or every core of a cluster job (how they are counted).

Returns an xarray.Dataset of (y, x) float32 maps (no y/x dims for one pixel; lazy for a dask cube or chunks=):

Variable Meaning
trend 1 increasing, -1 decreasing, 0 no significant trend.
h 1 if significant at alpha, else 0.
p Two-sided p-value.
z Standardised test statistic.
tau Kendall's tau.
s, var_s Mann-Kendall score and its (corrected) variance.
slope Theil-Sen slope, per time step (per period for "seasonal").
intercept Intercept of the robust line.
annual = zeit.load_raster("LT_Stack_NDVI_Rondonia.tif")   # one NDVI value per year
mk = zeit.mann_kendall(annual)
browning = (mk.h == 1) & (mk.trend == -1)
zeit.save_raster(mk, "mk_rondonia")                       # slope.tif, p.tif, ...

# 16-day composites tested directly: 23 observations per year
mk16 = zeit.mann_kendall(ndvi_16d, method="seasonal", period=23)

# One series
zeit.mann_kendall([0.41, 0.44, 0.39, 0.47, 0.52, 0.49, 0.55, 0.58, 0.61, 0.60]).slope.item()

ar_trend

zeit.ar_trend(
    data, *, time="step", harmonics=0, period=None, gaps="exact",
    min_valid=0, dates=None, band=None, nodata="auto", chunks=None,
    n_jobs=-1,
)

Linear trend with AR(1) errors, fitted by REML, for every pixel: remotePARTS's fitAR (Ives et al. 2021, Remote Sensing of Environment 266, 112678), on the Rust core. The series is intercept + slope * t (plus harmonics, for sub-annual data) and its errors follow an AR(1) process whose coefficient rho is estimated with the trend, so the t-test of the slope accounts for the autocorrelation of the series. A parametric alternative to mann_kendall, and the per-pixel step of parts. Same inputs and outputs as mann_kendall.

Parameter Type Default Description
data path, DataArray, Dataset, ndarray, list or pd.Series required The series, as for mann_kendall.
time str "step" "step": t = 1, 2, ... as remotePARTS (slope per time step); "year": decimal years of the dates (slope per year).
harmonics int 0 Pairs of harmonics (cos, sin) of the seasonal cycle in the design.
period float None Observations per cycle of the harmonics, for time="step"; from the dates when not given.
gaps str "exact" "exact": observations k dates apart are correlated by rho**k; "ignore": the valid observations are taken as consecutive, as remotePARTS's fitAR.
min_valid int 0 Pixels with fewer valid values are NaN (at least the design's columns + 2).
dates list None Date of each time step (needed for time="year").
band str or int None The index to use in a (time, band, y, x) cube or a Dataset.
nodata "auto", float or None "auto" Value marking a missing observation besides NaN.
chunks "auto", dict None Inputs read from disk: None reads into memory; "auto" or a dict keeps them lazy.
n_jobs int -1 Threads. -1: all the cores but one, or every core of a cluster job (how they are counted).

Returns an xarray.Dataset of (y, x) float32 maps: for each coefficient (intercept, slope, cos1, sin1, ...) its value and _se, _t, _p (two-sided); rho, mse (the variance of the innovations) and loglik.

ar = zeit.ar_trend(annual)                        # slope per year for annual composites
greening = (ar.slope > 0) & (ar.slope_p < 0.05)
ar16 = zeit.ar_trend(ndvi_16d, time="year", harmonics=2)   # 16-day data, slope per year

parts

zeit.parts(
    data, *, trend=None, response="slope", classes=None,
    covariates=None, mask=None, partsize=1500, npart=None, ncross=6,
    nugget="ml", correlation="exponential", range=None, shape=None,
    fit_n=1000, scaled=False, seed=0, time="step", harmonics=0,
    period=None, gaps="exact", dates=None, band=None, nodata="auto",
    n_jobs=-1,
)

The regional test of the pixels' trends by PARTS (remotePARTS's fitGLS_partition, Ives et al. 2021). Counting the pixels with a significant trend says little about a region: neighbouring pixels are correlated, and thousands of tests are run at once. PARTS answers the regional questions with valid p-values: does the mean trend of the region differ from 0, do the trends differ between land-cover classes, do they depend on a covariate. It fits each pixel's trend (ar_trend), fits the spatial correlation of the pixels to the correlations of their residual series (fitCor), and then a GLS of the trends on the design in random partitions of the pixels, combined into a t-test of each coefficient and a chi-square test of the design, both corrected for the correlation between partitions.

A step-by-step guide with figures, a worked example and the pitfalls: Regional Trends (PARTS).

Distances are in the cube's units: give a cube in projected coordinates. The results match remotePARTS's to 1e-10 for a given nugget; remotePARTS 1.0.4 crosses the partitions after the first without their nugget, which Zeit does not.

Parameter Type Default Description
data path, DataArray, Dataset or ndarray required A (time, y, x) cube, in projected coordinates.
trend Dataset None An ar_trend result to test instead of fitting it.
response str "slope" The variable of the trend tested.
classes (y, x) layer None Classes (land cover, ...): a mean trend per class, and the chi-square test that they differ.
covariates dict None {name: (y, x) layer}: their effects on the trend (with a mean), and the chi-square test of them.
mask (y, x) layer None The pixels tested (a region of interest).
partsize int 1500 Pixels per partition (remotePARTS uses 1500 to 3000).
npart int None Partitions; all the pixels by default. A few hundred are often enough: the correlation between partitions bounds what more of them gain.
ncross int 6 Partitions crossed to measure the correlation between partitions.
nugget "ml" or float "ml" Each partition's maximum-likelihood nugget, or a given one.
correlation str "exponential" "exponential", exp(-d / range), or "exponential_power", exp(-(d / range) ** shape).
range float None The correlation's range when known; fitted to the residuals when None.
shape float None The shape of "exponential_power", when known.
fit_n int 1000 Pixels sampled to fit the correlation.
scaled bool False Distances divided by their largest in each matrix (remotePARTS's default distm_scaled), or in the cube's units.
seed int 0 Seed of the samples and partitions.
time str "step" As for ar_trend.
harmonics int 0 As for ar_trend.
period float None As for ar_trend.
gaps str "exact" As for ar_trend.
dates list None Date of each time step.
band str or int None The index to use in a (time, band, y, x) cube or a Dataset.
nodata "auto", float or None "auto" Value marking a missing observation besides NaN.
n_jobs int -1 Threads. -1: all the cores but one, or every core of a cluster job (how they are counted).

Returns a PartsResult: table (a DataFrame of the coefficients: estimate, se, t, p), p_chisqr (the chi-square test of the design against a single mean, None without classes or covariates; remotePARTS floors it at 1e-6), f, df1, df2, correlation (the function and its parameters), nuggets, partitions (each partition's coefficients and nugget), npart, partsize, n_pixels.

res = zeit.parts(annual, classes=landcover, partsize=1500, npart=200)
print(res)                       # the mean trend of each class, and whether they differ
res.table.loc["class 3", "p"]
zeit.parts(annual, mask=roi)     # does the region's mean trend differ from 0?

emerging_hotspots

zeit.emerging_hotspots(
    data, radius=1, *, shape="square", lag=1, reference="date",
    alpha=0.05, trend="hamed_rao", band=None, nodata="auto",
    n_jobs=-1,
)

Emerging hot spot analysis (ESRI's Space Time Pattern Mining; R sfdep's emerging_hotspot_analysis): where the values cluster high (hot spots) or low (cold spots), and how that changed over the dates. For each date, the Getis-Ord Gi* z-score of each pixel (Getis & Ord 1992): the sum of its neighbourhood (the pixel among it) against the mean, the neighbourhood the pixels within radius at that date and the lag dates before. A hot spot is a date whose Gi* is significantly positive, a cold spot significantly negative. Then the Mann-Kendall test of each pixel's Gi* series, and its pattern as ESRI's documentation defines them:

Code Pattern Definition (hot spots; the cold ones, negative, alike)
1 new hot at the last date only
2 consecutive one run of hot dates, at the end
3 intensifying hot on 90 % of the dates or more, the last one too, its Gi* rising significantly
4 persistent the same, without a significant trend
5 diminishing the same, its Gi* falling significantly
6 sporadic hot at the last date, on and off before, never cold
7 oscillating hot at the last date, cold at some date before
8 historical hot on 90 % of the dates, not at the last
0 no pattern

Where two definitions hold, the first of the table. Each date's Gi* is computed from row prefix sums, a few operations a pixel whatever the radius's area, and the trends in parallel.

The Gi* equals sfdep 0.2.5's (include_gi = TRUE, queen neighbours, k the lag) to 1e-14, and the trend test Kendall's to its single precision (tests/data/make_hotspots_sfdep_fixtures.R). sfdep's patterns differ: it takes the significance of each Gi* from 199 permutations and has rules of its own (it calls sporadic a pixel not significant at the last date); Zeit's follow ESRI's definitions with the normal p-values of the Gi. As sfdep's, the Gi of a date measures the dates before it in its neighbourhood against that date's mean: with a lag, a rise everywhere lowers it (reference="cube" measures every date against the whole cube's). On a grid of 50 x 50 cells and 12 dates, sfdep takes 13 minutes (28 s with 9 permutations); Zeit 4 to 7 ms (benchmarks/vs_originals/hotspots.py).

Parameter Type Default Description
data path, DataArray, Dataset or ndarray required One variable as a (time, y, x) cube (an index, a count, an anomaly). Missing values are left out of the sums and statistics.
radius int 1 The neighbourhood in pixels: with shape="square" the (2 radius + 1)² pixels around (1: the 8 neighbours, queen contiguity, sfdep's default); with "circle" those whose centres are within it.
shape str "square" "square" or "circle".
lag int 1 The dates before each date in its neighbourhood (sfdep's k, ESRI's neighbourhood time step).
reference str "date" "date": each date's Gi* against that date's mean and standard deviation (as sfdep: a place hot against the others at that date); "cube": against the whole cube's (a date high everywhere is hot everywhere).
alpha float 0.05 The significance of the Gi* (two-sided, normal) and of its trend.
trend str "hamed_rao" The trend test of the Gi* series: "hamed_rao" (the Gi* of consecutive dates share neighbours, so their series are autocorrelated), "original" Mann-Kendall (ESRI's and sfdep's) or "yue_wang".
band str or int None The index to use in a (time, band, y, x) cube or a Dataset.
nodata "auto", float or None "auto" Value marking a missing observation besides NaN.
n_jobs int -1 Threads. -1: all the cores but one, or every core of a cluster job (how they are counted).

Returns an xarray.Dataset: category (y, x) int8, the pattern's code (-128 with fewer than 3 dates; flag_values and flag_meanings, the names in zeit.emerging_hotspots.PATTERNS); gi (time, y, x), the Gi* z-scores, and p, their p-values; trend_z, trend_p and tau, the trend test of the Gi*; n_hot and n_cold, the dates a significant hot or cold spot.

loss = -zeit.load_raster("ndvi_annual.tif")                  # (time, y, x): where the losses concentrate
ehs = zeit.emerging_hotspots(loss, radius=3, shape="circle")
ehs.category.zeit.plot()                                       # legend: the patterns
new_fronts = ehs.category.isin([1, 2, 3])                     # new, consecutive, intensifying hot spots

Modes and lagged correlation

Two questions about a cube of maps over time, and the same machinery behind both (the seasonal cycle taken out of each pixel, pixel blocks read in parallel, results that do not depend on the number of threads). eof finds the few spatial patterns and time series that explain most of the variability. lagged_correlation asks where, and after how many months, a driver (a climate index, a regional mean, another cube) is followed by the pixels' series, and fdr says which of those pixels to believe when thousands of them are tested at once. Tutorial: EOFs and lagged correlation. Agreement with xeofs, eofs, xarray, scipy and statsmodels: Against the original implementations.

eof

zeit.eof(
    data, n_modes=10, *, anomaly="month", harmonics=2, base=None,
    detrend=False, standardize=False, weights="area", min_valid=0.8,
    min_date_valid=0.5, scaling="units", solver="auto",
    oversampling=10, power_iterations=4, rotate=0, kaiser=True,
    north_n="dates", correlation_maps=False, seed=42, band=None,
    nodata="auto", n_jobs=-1,
)

Temporal empirical orthogonal functions (principal components) of a cube: the maps (EOFs) and the time series (PCs) that explain most of its variance. The seasonal cycle is taken out of each pixel (anomaly), the pixels are weighted by their area, and the cube X (dates x pixels) is decomposed as X = U S V^T. The dates are the short side, so the singular vectors come from the dates x dates Gram matrix summed over blocks of 4096 pixels (solver="exact") or from a randomized range finder with power iterations (Halko, Martinsson & Tropp 2011; solver="randomized") in a few passes over the pixels. The maps come in one more pass. Pixels with too few valid dates (min_valid) have NaN maps; dates with too few valid pixels (min_date_valid) are left out of the fit and get their PC by least squares over their valid pixels (Everson & Sirovich 1995), flagged in pc_filled. The sign of each mode is fixed so that its PC correlates positively with the area-weighted mean anomaly (a dipole: its largest value is positive), because the sign of a singular vector is arbitrary. The result is bitwise the same for any n_jobs.

North et al.'s (1982) rule of thumb says when a mode can be told from its neighbours: an eigenvalue λ has a sampling error of λ sqrt(2 / n), and a mode is separable when its error bar does not touch its neighbours'. With north_n="dates" (default) n is the number of dates, as in eofs; for series with memory it is too large, and "autocorrelation" uses T (1 - ρ) / (1 + ρ) with the lag-1 autocorrelation of each PC. rotate=m rotates the first m modes by Kaiser's (1958) varimax, with Kaiser's row normalization, to patterns that are more local.

Parameter Type Default Description
data path, DataArray or Dataset required One variable (an index) as a (time, y, x) cube (a Dataset with band=). Missing values are NaN. Aggregate to months first (data.resample(time="MS").mean()) if the gaps of the dates would drop them from the fit.
n_modes int 10 Modes computed, at most the number of dates - 1.
anomaly str "month" What is removed from each pixel's series: "month" (the climatology of each calendar month; a month needs two values at least), "harmonic" (a constant and harmonics sine and cosine pairs of the year, by least squares) or "none" (only the mean).
harmonics int 2 The order of the harmonic fit.
base tuple None (first_year, last_year): the years that define the climatology (default all).
detrend bool False Remove a straight line from each pixel too.
standardize bool False Divide each pixel by the standard deviation of its anomalies: the decomposition of the correlation matrix instead of the covariance.
weights str or array "area" "area": the area of each pixel (pixel_area), normalized to mean 1, so a pixel of a high latitude counts for what it covers; "coslat": cos(latitude), for a geographic CRS only; "none"; or an array (y, x). Without a CRS the weights are 1 (a warning).
min_valid float 0.8 A pixel is kept when this fraction of the dates is valid after the anomalies.
min_date_valid float 0.5 A date is part of the fit when this fraction of the kept pixels is valid there.
scaling str "units" "units": each EOF in the data's units per standard deviation of its PC (the PCs have unit variance); "none": orthonormal EOFs, the PCs carry the variance.
solver str "auto" "exact", "randomized", or "auto" (exact with up to 1000 dates, else randomized).
oversampling int 10 Columns of the randomized sketch beyond n_modes.
power_iterations int 4 Power passes of the randomized solver: each costs a pass over the data and makes the deeper modes more accurate.
rotate int 0 Rotate the first rotate modes (2 or more) by varimax. The rotated EOFs are always in data units per standard deviation of the PC.
kaiser bool True Kaiser's row normalization in the rotation.
north_n str "dates" The number of independent dates of North's error: "dates" or "autocorrelation".
correlation_maps bool False Also return corrmap: the correlation of each pixel with each PC.
seed int 42 Seed of the randomized solver's test matrix.
band str or int None The index to use in a (time, band, y, x) cube or a Dataset.
nodata "auto", float or None "auto" Value marking a missing observation besides NaN.
n_jobs int -1 Threads. -1: all the cores but one, or every core of a cluster job (how they are counted).

Returns an xarray.Dataset: eof (mode, y, x) and pc (mode, time); variance (mode), the fraction of the total variance of each mode, and eigenvalue (mode), s² / (T - 1) of the weighted data; north_error (mode) and separable (mode); pc_filled (time), the dates whose PC comes from the gappy projection. With rotate: eof_rotated (mode_rotated, y, x), pc_rotated (unit variance) and variance_rotated, ordered by variance. With correlation_maps: corrmap. Attributes: total_variance, solver (the one that ran), weights, anomaly, n_pixels and n_dates kept in the fit.

ndvi = zeit.load_raster("ndvi_monthly.tif")                   # (time, y, x)
ds = zeit.eof(ndvi, n_modes=5, rotate=3)
ds.variance.values                                             # fraction of the variance of each mode
ds.separable.values                                            # which modes North's rule separates
ds.eof.sel(mode=1).zeit.plot()                                 # the first pattern
ds.pc.sel(mode=1).plot()                                       # and its time series

The conventions of the references

The EOFs of eofs and xeofs are those of the weighted data (orthonormal, or in the weighted data's units), and the sign of each is arbitrary. Zeit's scaling="units" EOFs have the weights taken out again, so that a map is in the data's units and its PC has unit variance; with equal weights they equal eofs' eofs(eofscaling=2) and pcs(pcscaling=1) up to the sign. The rotated PCs of xeofs carry the variance, Zeit's have unit variance. The randomized solver is exact for the modes North's rule separates and approximate for the deeper ones; solver="exact" costs one pass over the data and a dates x dates eigenproblem, and is the one to use up to a few hundred dates.

lagged_correlation

zeit.lagged_correlation(
    x, y, lags=3, *, step="month", match="nearest", tolerance="8D",
    anomaly="month", method="pearson", best="absolute", min_pairs=10,
    effective_n=True, sidak=True, alpha_fdr=0.1, band=None,
    nodata="auto", n_jobs=-1,
)

The correlation of every pixel's series x with a driver y at several lags. At lag k the pairs are (x_t, y_{t-k}): y leads x by k steps, and a driver that acts two months later shows its strongest correlation at lag 2. The pairs are the dates where both are valid. The driver is one series (a pandas.Series with a DatetimeIndex, or a DataArray of time: a climate index, a regional mean) or a cube on the grid of x (each pixel against its own).

With step="month" (default) both are averaged to calendar months first, so a monthly index can drive a 16-day series and the lags are months; with step="dates" the driver is matched to the dates of x (match, tolerance) and the lags are observations of x. The seasonal cycle is taken out of both (anomaly), otherwise the shared seasonality dominates every correlation.

The p-value is a two-sided Student t test with the effective number of pairs n (1 - rx ry) / (1 + rx ry) (Bretherton et al. 1999; rx and ry the lag-1 autocorrelations, their product clamped to 0 to 0.99), because consecutive values of a smooth series are not independent: with n instead, a map of a slowly varying index is covered with false positives. The p-value of the best lag is adjusted for having tried the lags (Sidak), and significant marks the pixels whose best lag passes the Benjamini-Hochberg false discovery rate (alpha_fdr, fdr). Spearman's correlation uses average ranks on each lag's pairs.

Parameter Type Default Description
x path, DataArray or Dataset required The series of every pixel: a (time, y, x) cube.
y Series, DataArray or cube required The driver: one series, or a (time, y, x) cube on the grid of x.
lags int or list 3 K for the lags 0, 1, ..., K, or the list of lags (steps; negative: x leads).
step str "month" "month": both averaged to calendar months, lags in months. "dates": y matched to the dates of x, lags in observations of x.
match str "nearest" For step="dates": "nearest" (the nearest date of y within tolerance), "exact", "month" (a date of the same calendar month) or "year".
tolerance str or float "8D" For match="nearest": days, or a string like "8D", "2W", "12h".
anomaly str "month" Taken out of both before correlating: "month", "harmonic", "mean" or "none" (the raw values: trends and seasonality then count).
method str "pearson" "pearson" or "spearman".
best str "absolute" The best lag: the largest |r|, or the largest positive ("positive") or negative ("negative") r.
min_pairs int 10 Fewer pairs give NaN.
effective_n bool True False takes the pairs as independent (the p-values are then too small for smooth series).
sidak bool True Adjust best_p for the number of lags tried.
alpha_fdr float 0.1 The false discovery rate of significant. Wilks (2016) recommends twice the level the single tests would have.
band str or int None The index to use in a (time, band, y, x) cube or a Dataset.
nodata "auto", float or None "auto" Value marking a missing observation besides NaN.
n_jobs int -1 Threads. -1: all the cores but one, or every core of a cluster job (how they are counted).

Returns an xarray.Dataset: r, p, n (pairs) and n_eff (effective pairs), each (lag, y, x), with r and p in float32; best_r, best_lag (-1 where no lag has a correlation), best_p (Sidak-adjusted), q (the false discovery rate adjusted p) and significant (q <= alpha_fdr), each (y, x). The attribute p_threshold is the p-value up to which best_p is significant.

ndvi = zeit.load_raster("ndvi_16d.tif")                                   # (time, y, x), 16-day
oni = pd.read_csv("oni.csv", index_col=0, parse_dates=True)["oni"]       # monthly climate index
lc = zeit.lagged_correlation(ndvi, oni, lags=6)                           # ndvi_t against oni_{t-k}, k = 0..6 months
lc.best_lag.where(lc.significant).zeit.plot()                             # where, and after how many months
lc.r.sel(lag=3)                                                           # the correlation at one lag

fdr

zeit.fdr(p, alpha=0.1)

Benjamini and Hochberg's (1995) false discovery rate procedure. Of the M p-values that are not NaN, the ones at or below the threshold p* (the largest p_(i) with p_(i) <= i alpha / M) are significant: among them, at most the fraction alpha is expected to be false discoveries when the tests are independent or positively dependent. Wilks (2016) recommends it for maps of tests, with alpha twice the level the single tests would have (a global 0.10 for 0.05).

Parameter Type Default Description
p array or DataArray required The p-values, any shape (a DataArray gives its coordinates back); NaN are left out.
alpha float 0.1 The false discovery rate.

Returns (q, threshold, significant): q, the adjusted p-values (the smallest rate at which each one is significant), NaN where p is; threshold, p* (0 when nothing is significant); significant, bool, q <= alpha. q equals scipy.stats.false_discovery_control(p, method="bh") and statsmodels' fdrcorrection.

q, threshold, significant = zeit.fdr(p_map, alpha=0.10)
trend = zeit.mann_kendall(ndvi)
q, _, sig = zeit.fdr(trend.p, alpha=0.10)      # the trend map, corrected for testing every pixel

FORCE time series analysis

Six functions ported from the higher-level time series analysis of FORCE 3.11.00 (Frantz 2019, Remote Sensing 11, 1124; GPL-3.0-or-later). They are the steps of FORCE's TSA after the interpolation (interpolate and standardize are in Pre-processing): spectral-temporal metrics and their folds by period, linear trends, change-aftereffect-trend, clear-observation statistics and polar phenology metrics. Each runs on any input of the BFAST family (a (time, y, x) cube in memory or dask, a raster, a numpy array, one pixel's series) and returns floats, not FORCE's int16 scaled by 10000. Tutorial: FORCE's time series analysis chain. Agreement with FORCE on 10,000 pixels: Against the original implementations.

temporal_metrics

zeit.temporal_metrics(
    data,
    metrics=('min', 'p25', 'median', 'p75', 'max', 'mean', 'std'), *,
    by=None, ddof=1, dates=None, band=None, nodata="auto",
    chunks=None, n_jobs=-1,
)

Statistics of each pixel's series, over all of it or by period: FORCE's spectral-temporal metrics (STM; Müller et al. 2015) and their folds (FBY, FBQ, FBM, FBW, FBD). The series can have any spacing; NaN marks a missing observation.

Parameter Type Default Description
data DataArray, Dataset, path, ndarray, list or pd.Series required A (time, y, x) cube, a (time, band, y, x) cube or Dataset with band=, a numpy array with dates=, or one pixel's series.
metrics sequence of str ("min", "p25", "median", "p75", "max", "mean", "std") min, max, range, iqr, mean, std, skew, kurtosis (excess), count (valid observations), median and pNN for any integer percentile 0-100 (R-7, as np.nanpercentile).
by str None None: the statistics of the whole series. "year", "quarter", "month", "week" or "doy": those of each period (the dates are needed).
ddof int 1 Degrees of freedom of std: the divisor is n - ddof (1 is the sample deviation, as FORCE's STD).
dates list None Date of each time step, for inputs that carry none.
band str or int None The index to use in a (time, band, y, x) cube or a Dataset.
nodata "auto", float or None "auto" Value marking a missing observation besides NaN, as in mann_kendall.
chunks "auto", dict None Inputs read from disk: None reads into memory; otherwise the result is lazy.
n_jobs int -1 Threads. -1: all the cores but one, or every core of a cluster job (how they are counted).

Returns an xarray.DataArray (metric, y, x), or (metric, <by>, y, x) with by, with the names of the metrics in metric. Float32 for float32 input, else float64. Pixels without a valid observation are NaN (0 for count). The periods are the years from the first to the last date, 1-4, 1-12, 1-52, 1-365, all of them, the empty ones NaN. The week is min(ceil(doy / 7), 52) and the day of the year counts 365 days, 29 February sharing day 60 with 1 March, so that a calendar day is the same day of the year in every year (FORCE's calendar).

Differences from FORCE. skew (M3 / sigma^3, the population deviation) and kurtosis (excess) are NaN in a series with fewer than 2 distinct values, where FORCE leaves them undefined; std with n <= ddof is NaN. The output is not rounded to int16.

stm = zeit.temporal_metrics(ndvi, ["p10", "median", "p90", "std"])        # (metric, y, x)
yearly = zeit.temporal_metrics(ndvi, ["mean", "max"], by="year")           # (metric, year, y, x)

linear_trend

zeit.linear_trend(
    data, *, conf=0.95, tail="two", dim=None, band=None,
    nodata="auto", chunks=None, n_jobs=-1,
)

The linear trend of each pixel's series: FORCE's TRY, TRQ, TRM, TRW and TRD, depending on the series (the yearly, quarterly, monthly, weekly or daily folds of temporal_metrics). A least-squares line on the position of each step along dim (0, 1, 2..., counting the missing steps too, so the slope is per step: per year for a yearly series), with a t-test of the slope. A pixel with fewer than 3 valid steps is NaN.

Parameter Type Default Description
data DataArray, path, ndarray, list or pd.Series required A (time, y, x) cube, or a series along another axis such as the (metric, year, y, x) result of temporal_metrics(..., by="year").
conf float 0.95 Confidence level of the test of the slope.
tail str "two" "two", "left" (is the slope significantly negative?) or "right".
dim str None The axis of the series: "time" (default when it exists) or another, such as "year". A metric axis of length 1 is dropped; with more, choose one with .sel(metric=...).
band str or int None The index to use in a (time, band, y, x) cube or a Dataset.
nodata "auto", float or None "auto" Value marking a missing observation besides NaN.
chunks "auto", dict None Inputs read from disk: None reads into memory; otherwise the result is lazy.
n_jobs int -1 Threads. -1: all the cores but one, or every core of a cluster job (how they are counted).

Returns an xarray.Dataset of (y, x) maps:

Variable Meaning
mean, offset Mean of the valid steps; the fit at the first step.
slope Slope per step.
pct_gain, abs_gain The slope times the number of steps, as a percentage of the offset (0 unless the offset is positive) and as is.
rsq R squared, 0-1 (FORCE writes it times 10000).
sig -1, 0 or 1: the slope is significantly negative, not significant, or positive.
rmse, mae, maxe Root mean square, mean absolute and largest absolute residual.
num, len Valid steps, and steps.

Differences from FORCE. The critical value is the exact quantile of Student's t with num - 2 degrees of freedom, tabled once per degrees of freedom; FORCE iterates Hill's approximation to a tolerance of 1e-4, so sig can differ only where the t-value is that close to the limit.

yearly = zeit.temporal_metrics(ndvi, ["mean"], by="year")
trend = zeit.linear_trend(yearly)                    # trend.slope: NDVI per year
greening = trend.sig == 1

cat

zeit.cat(
    data, *, penalty=False, conf=0.95, tail="two", dim=None,
    band=None, nodata="auto", chunks=None, n_jobs=-1,
)

The change-aftereffect-trend of each pixel's series (CAT; Hird et al. 2016): FORCE's CAY, CAQ, CAM, CAW and CAD. The change is the greatest loss between a valid step and the valid one before it (positive for a loss; a series that only rises keeps its smallest rise). The series is split at that step, and the trend of linear_trend is fit to the whole series (total_), to the steps before the change (before_, from the first up to two before the change step, as FORCE defines it) and from the change step on (after_). A part without valid steps is NaN; one with fewer than 3 has only its mean, num and len.

Parameter Type Default Description
data DataArray, path, ndarray, list or pd.Series required As for linear_trend.
penalty bool False Weight each loss by what the series has lost by the next valid step (FORCE's CHANGE_PENALTY), which discounts a dip the series recovers from.
conf float 0.95 Confidence level of the test of the slopes.
tail str "two" "two", "left" or "right".
dim str None The axis of the series, as for linear_trend.
band str or int None The index to use in a (time, band, y, x) cube or a Dataset.
nodata "auto", float or None "auto" Value marking a missing observation besides NaN.
chunks "auto", dict None Inputs read from disk: None reads into memory; otherwise the result is lazy.
n_jobs int -1 Threads. -1: all the cores but one, or every core of a cluster job (how they are counted).

Returns an xarray.Dataset of (y, x) maps: change (the greatest loss), loss (the change as a percentage of total_offset, 0 unless that is positive), change_time (the coordinate of dim at the change: the date, the year, the month..., NaN or NaT when there is none) and the twelve variables of linear_trend for each part, prefixed total_, before_ and after_: 39 in all. A pixel with fewer than 2 valid steps is NaN.

Differences from FORCE. With penalty, FORCE compares the penalized value of each candidate with the unpenalized change of the best one so far, mixing two scales; Zeit compares penalized with penalized, and returns the winner's unpenalized change, as FORCE. The two can pick another step (15% of the pixels on yearly folds, 70% on monthly ones in the benchmark). The t quantile is exact, as in linear_trend.

yearly = zeit.temporal_metrics(ndvi, ["mean"], by="year")
ch = zeit.cat(yearly, penalty=True)                  # ch.change_time: the year of the greatest loss
ch.after_slope                                       # the recovery after it, per year

clear_observations

zeit.clear_observations(
    data, *, months=1, metrics=('count', 'mean', 'max'), start=None,
    end=None, dates=None, band=None, nodata="auto", chunks=None,
    n_jobs=-1,
)

The clear-sky observations of each pixel in windows of months, and the gaps between them: FORCE's CSO (Ernst et al. 2018). An observation is valid where the value is finite (NaN and NoData are cloud or missing), or True in a boolean cube. In each window the intervals, in days, run from the start of the window to the first valid observation, between consecutive ones, and from the last to the end of the window. A window without a valid observation has one interval, as long as the window, and a count of 0. The dates are needed and must not decrease.

Parameter Type Default Description
data DataArray, path, ndarray, list or pd.Series required A cube of any values (valid where finite), or a boolean cube (True: clear).
months int 1 The length of a window in months, 1 to 12.
metrics sequence of str ("count", "mean", "max") count (the valid observations) and, of the intervals in days, the metrics of temporal_metrics: min, max, range, iqr, mean, std, skew, kurtosis, median, pNN.
start, end date None The windows begin on the first day of the month of start and go on until the one that holds end, which is included whole. Default: the first and last date.
dates list None Date of each time step, for inputs that carry none.
band str or int None The index to use in a (time, band, y, x) cube or a Dataset.
nodata "auto", float or None "auto" Value marking a missing observation besides NaN.
chunks "auto", dict None Inputs read from disk: None reads into memory; otherwise the result is lazy.
n_jobs int -1 Threads. -1: all the cores but one, or every core of a cluster job (how they are counted).

Returns an xarray.DataArray (metric, window, y, x), with window the first day of each window and window_end (along window) its end, exclusive. Float32 for float32 input, else float64.

Differences from FORCE. FORCE mixes the number of observations n with the number of intervals k: its standard deviation divides by n - 1, its skewness and kurtosis by n, and its quantiles are taken over the first n of the k intervals (reading stale memory when observations share a day). Here every metric but count is over the same k intervals; count, min, max, range and mean equal FORCE's, the others differ where n != k. In a window without a valid observation FORCE writes 0 for std, skew, kurtosis and the quantiles; here std, skew and kurtosis are NaN. FORCE leaves out the last window when it starts in the month the range ends in (December's, with 1-month windows); Zeit keeps it.

cso = zeit.clear_observations(ndvi, months=3, metrics=["count", "max"])    # (metric, window, y, x)
longest_gap = zeit.clear_observations(ndvi.notnull(), metrics=["max"])     # a boolean cube works too

References: Müller, H., Rufin, P., Griffiths, P., Barros Siqueira, A. J., & Hostert, P. (2015). Remote Sensing of Environment, 156, 490-499 (STM). Hird, J. N., Castilla, G., McDermid, G. J., & Bueno, I. T. (2016). IEEE JSTARS, 9, 3372-3383 (CAT). Ernst, S., Lymburner, L., & Sixsmith, J. (2018). Remote Sensing, 10, 1570 (CSO). The full list, with the interpolation's, is in the tutorial.

polar_metrics

zeit.polar_metrics(
    data, metrics=('VSS', 'VPS', 'VES', 'VSA', 'RMR', 'IGS'), *,
    start=0.2, mid=0.5, end=0.8, adaptive=True, dates=None, band=None,
    nodata="auto", chunks=None, n_jobs=-1,
)

The polar phenology metrics of each pixel and year: FORCE's POL (polar-hl.c, Frantz), which implements and extends the polar metrics of Brooks et al. (2020). Each date of a regular series is a vector: the value is the radius and the day of the year the angle. The mean of all the vectors is the long-term mean vector; the opposite direction, the time of least activity, starts the phenological year. Along each year's season the values are accumulated and divided by their total, and the dates where that fraction reaches start, mid and end are the start, middle and end of the season; the rest of the 39 metrics (dates, lengths, values, amplitudes, integrals and rates) come from those points. Only what the requested metrics need is computed. The series must be regular, a constant step of whole days (the output of interpolate with step=, FORCE's TSI) and cover at least 2 years; a missing step (NaN) is filled by linear interpolation in time, as FORCE does.

Parameter Type Default Description
data DataArray, path, ndarray, list or pd.Series required A (time, y, x) cube of a non-negative index (negative values count as 0), a numpy array with dates=, or one pixel's series.
metrics sequence of str ("VSS", "VPS", "VES", "VSA", "RMR", "IGS") Any of the 39 names in the table below, upper or lower case.
start, mid, end float 0.2, 0.5, 0.8 The fractions of the season's accumulated value that mark its start, middle and end (FORCE's POL_START_THRESHOLD, POL_MID_THRESHOLD and POL_END_THRESHOLD), each between 0 and 1.
adaptive bool True Fine-tune the start of each year's season from its own mean vector, not the long-term one (FORCE's POL_ADAPTIVE).
dates list None Date of each time step, for inputs that carry none.
band str or int None The index to use in a (time, band, y, x) cube or a Dataset.
nodata "auto", float or None "auto" Value marking a missing observation besides NaN, as in mann_kendall.
chunks "auto", dict None Inputs read from disk: None reads into memory; otherwise the result is lazy.
n_jobs int -1 Threads. -1: all the cores but one, or every core of a cluster job (how they are counted).

Returns an xarray.DataArray (metric, year, y, x): one band per calendar year from the first date's to the last's, float32 for float32 input, else float64, unrounded (FORCE writes truncated int16). A season belongs to the year it ends in when the long-term start of the year is before day 182, else to the year after it begins, so a series of n years has n - 1 seasons and one year (the first or the last) is NaN. A series need not start on 1 January: a season whose start of the year is before the first date (or has no step in the series) is NaN, and the seasons whose start is in the series are measured as usual (FORCE, which looks for the first start for ever, finds no season at all in that case and writes 0 for every metric); a season cut short by the end of the series is measured from the steps it has, as in FORCE. linear_trend of one metric along year is FORCE's TRO of it and cat its CAO.

The 39 metrics. A date counts days from 1 January of the band's year (365 days a year, 29 February sharing day 60 with 1 March). Data is the unit of the input.

Name Meaning Unit
DEM date of the early minimum (first step of the season with a non-zero accumulated fraction) days
DLM date of the late minimum (the step after the last one with the fraction 1: the start of the next season) days
DPS date of the peak (first maximum of the growing season) days
DSS, DMS, DES date of the start, the middle and the end of the season (the fraction reaches start, mid, end) days
DEV, DAV, DLV date of the mean vector of the early (start to mid), whole (start to end) and late (mid to end) growing season days
LTS, LGS, LGV length of the total season (DLM - DEM), of the growing season (DES - DSS) and between the early and late mean vectors (DLV - DEV) days
VEM, VLM value at the early and at the late minimum data
VPS value at the peak data
VSS, VMS, VES value at the start, the middle and the end of the season data
VEV, VAV, VLV length of the early, whole and late mean vector (the mean, not the sum, of the points of the window) data
VBL base level, (VEM + VLM) / 2 data
VGM, VGV mean and standard deviation (n - 1) of the growing season data
VGA green amplitude, peak minus (VSS + VES) / 2 data
VSA seasonal amplitude, peak minus base level data
VPA peak amplitude, peak minus the value at the middle data
DPY start of the phenological year (long-term, the same every year; negative when it falls before 1 January of the band's year) days
DPV shift of the season's own start from DPY (0 without adaptive) days
IST seasonal integral, above the base level data × year
IBL base integral, under the base level data × year
IBT total integral of the season data × year
IGS green integral, above the green level in the growing season data × year
IRR, IFR rising and falling integral (the sum of the rises and of the falls) data × month
RAR, RAF average rate of rise (early growing season) and of fall (late growing season); the sum of the rates over all the steps of the window, as FORCE data / month
RMR, RMF maximum rate of rise (early growing season) and of fall (late growing season) data / month

Differences from FORCE. All are deliberate.

  • Dates count from 1 January of the band's year, FORCE's from 1 January of the first year of the series (continuous days). A linear trend along year is then directly the change per year; FORCE subtracts 365 from the slope of a date (its in_ce) to get the same. To compare with FORCE's rasters add 365 * i to the dates of year i (FORCE also writes the slope of a date times 1000).
  • What FORCE leaves undefined is NaN. FORCE casts a NaN to int16 and writes garbage (0 on x86): a season whose accumulated total is 0 (a pixel of zero index), a season without steps, the mean vector or rate of a window without steps, VGM without a step, VGV with fewer than 2. Nothing is clipped to 16 bits (FORCE wraps an integral past 32767).
  • DPV is 0 without adaptive, where FORCE writes -DPY (a start it never set).
  • STANDARDIZE_POL does nothing in FORCE and does not exist here: use standardize.
tsi = zeit.interpolate(ndvi * 10000, "rbf", step=16)           # FORCE's TSI
pol = zeit.polar_metrics(tsi, ["DSS", "DES", "VPS", "IGS"])    # (metric, year, y, x)
sos_trend = zeit.linear_trend(pol.sel(metric="DSS"))           # days per year, along year

Reference: Brooks, B.-G. J., Lee, D. C., Pomara, L. Y., & Hargrove, W. W. (2020). Monitoring broadscale vegetational diversity and change across North American landscapes using land surface phenology. Forests, 11(6), 606. doi:10.3390/f11060606.

Phenology

phenology

zeit.phenology(
    data, *, curve="beck", method="threshold", weights=None,
    dates=None, annual=True, max_seasons=None, whittaker_lambda=10.0,
    apply_whittaker=True, apply_hants=False, hants_frequencies=3,
    hants_threshold=0.1, min_season_length=0, min_amplitude=0.0,
    min_pixel_amplitude=0.1, season_retry=True, band=None,
    nodata="auto", chunks=None, n_jobs=-1,
)

Land surface phenology, written from the papers (Whittaker: Eilers 2003; HANTS: Roerink et al. 2000; the curves of Beck 2006, Elmore 2012, Gu 2009, Klosterman 2014, Zhang 2003, Jönsson & Eklundh and Fisher 2006), not from the code of R phenofit, which stays a useful reference to compare outputs with: smooths each pixel's series (Whittaker or HANTS), splits it into seasons, fits a curve to each season and extracts 19 transition metrics plus the fit's R² and RMSE, every pixel in parallel in the Rust core. One function for every input, like bfast_monitor (the same data table), with dates at any spacing. It replaces zeit.phenology.run_phenology_dask and DataArray.zeit.run_phenology; the accessor form is now DataArray.zeit.phenology, and the engine module is internal (zeit._phenology). Tutorial: Phenology.

The day numbering of the core (days since January 1st of the first year) and the first year are computed from the dates, so no day-of-year array is needed.

Parameter Type Default Description
data path, DataArray, Dataset, ndarray, list or pd.Series required A vegetation-index series with dates (see bfast_monitor).
curve str or int "beck" Fitted curve: "beck", "elmore", "gu", "klos", "zhang", "ag" or "dl" (or its integer code).
method str or int "threshold" "threshold", "derivative", "gu" or "klosterman" (or its integer code). Recorded in attrs; every metric family is computed whatever the method.
weights DataArray or array None Per-observation reliability weights in [0, 1], aligned with the data (e.g. from qc_sentinel2_scl).
dates list None Date of each time step, for numpy input and series without dates.
annual bool True True: one value per calendar year, (year, y, x), dates as day of year. False: one value per detected season, (season, y, x), dates as days since January 1st of the first year (attrs["base_year"]).
max_seasons int None Years (with annual) or seasons per pixel. Default: the number of years in the series.
whittaker_lambda float 10.0 Whittaker smoothness.
apply_whittaker bool True Smooth with Whittaker before fitting.
apply_hants bool False Smooth with HANTS (harmonics) instead.
hants_frequencies int 3 HANTS harmonics.
hants_threshold float 0.1 HANTS outlier threshold.
min_season_length int 0 Drop seasons shorter than this many days.
min_amplitude float 0.0 Drop seasons with a smaller amplitude.
min_pixel_amplitude float 0.1 Skip pixels whose whole series varies less than this (water, urban).
season_retry bool True Retry pixels with no season once with a relaxed trough threshold.
band str or int None The index to use in a (time, band, y, x) cube or a Dataset.
nodata "auto", float or None "auto" Value marking a missing observation besides NaN, as in bfast_monitor.
chunks "auto", dict None Inputs read from disk: None reads into memory; "auto" or a dict keeps them lazy.
n_jobs int -1 Threads. -1: all the cores but one, or every core of a cluster job (how they are counted).

Returns an xarray.Dataset with 21 variables, each (year, y, x) (annual=True, year coordinate from the first year) or (season, y, x) (season = 1, 2, …): TRS2.sos, TRS2.eos, TRS5.sos, TRS5.eos, TRS6.sos, TRS6.eos, DER.sos, DER.pos, DER.eos, UD, SD, DD, RD, Greenup, Maturity, Senescence, Dormancy, LOS, POP, R2, RMSE (see the 19 metrics). NaN where no season was found. The names contain dots, so select them with brackets: pheno["TRS5.sos"]. The result is georeferenced and lazy for a dask cube or chunks=; save_raster writes one GeoTIFF per metric with one band per year (2019, 2020, …) or season.

ndvi_16d = zeit.regularize_time_series(ndvi, freq="16D", method="median")   # (time, y, x)
pheno = zeit.phenology(ndvi_16d, curve="beck", min_season_length=45, min_amplitude=0.15)
sos = pheno["TRS5.sos"]                         # (year, y, x), day of year
late = sos.sel(year=2021) - sos.sel(year=[2019, 2020]).mean("year")
zeit.save_raster(pheno, "pheno_out")            # TRS2.sos.tif, ..., one band per year

# Double cropping: up to 3 seasons per pixel instead of one value per year
seasons = zeit.phenology(ndvi_16d, annual=False, max_seasons=3)

Pattern matching (TWDTW)

Tutorial: Pattern Matching.

twdtw

zeit.twdtw(
    data, patterns, *, band=None, steepness=0.1, midpoint=50.0,
    cycle="year", max_elapsed=None, nodata="auto", chunks=None,
    n_jobs=-1,
)

Classifies time series by Time-Weighted Dynamic Time Warping (Maus et al. 2016): each pattern, a typical series of a class, is matched against every pixel's series, and the class of a pixel is the pattern with the lowest distance. The distance is that of the R package twdtw (checked against it to 1e-12): the pattern may match any stretch of the series, each pair of matched observations costs their Euclidean distance plus a logistic time weight

\[ w(\Delta t) = \frac{1}{1 + e^{-\text{steepness}\,(\Delta t - \text{midpoint})}} \]

of the days \(\Delta t\) between them, and dates a pixel has no value for are left out of its series. One function for every input; it replaces classify_twdtw, run_twdtw and run_twdtw_batch.

Input Example Where the dates come from
A cube (time, y, x), or (time, band, y, x) for several bands; anything load_raster reads ndvi Its time coordinate. A dask cube stays lazy.
One pixel: a pandas.Series (or a DataFrame, one column per band) indexed by dates series Its index

Patterns are {name: series}: a pandas.Series indexed by dates, a DataFrame with one column per band, or a DataArray with time (and band). With several bands, the cube's bands are taken by the patterns' column names.

Parameter Type Default Description
data DataArray, path, pd.Series or pd.DataFrame required The series to classify (see the table above).
patterns dict required {name: pattern}, one per class. Names cannot hold spaces.
band str None A cube with a band dim and one-band patterns: the band to classify.
steepness float 0.1 Steepness of the logistic time weight, per day.
midpoint float 50.0 Days apart at which a pair costs half a unit more (R's time_weight = c(0.1, 50)).
cycle str or None "year" "year": the days between dates are counted between days of the year, around it (31 December and 1 January are a day apart), so a pattern of one year matches the same season of any year. None: between the dates themselves.
max_elapsed float None Pairs farther apart than this many days are never matched. None: no limit.
nodata "auto", float or None "auto" Value marking a missing observation: the raster's NoData (0 for integer data without one), a number, or None.
chunks "auto", dict None Inputs read from disk: None reads into memory; otherwise the result is lazy.
n_jobs int -1 Threads. -1: all the cores but one, or every core of a cluster job (how they are counted).

Returns an xarray.Dataset:

Variable Dims Meaning
label (y, x) The class: 1 for the first pattern, 2 for the second… (0: no observation). Its flag_meanings hold the names, which zeit.plot shows in the legend.
distance (y, x) TWDTW distance to that pattern. High values mean no pattern fits well.
distances (pattern, y, x) Distance to every pattern.
pattern_value, pattern_time (pattern, pattern_step[, band]) The patterns, so that zeit.plot(cube, fit=result) draws the best one aligned with a clicked pixel's series. save_raster skips them.
patterns = {"soy": soy, "pasture": pasture, "forest": forest}   # pandas Series indexed by dates
classes = zeit.twdtw(ndvi, patterns)
classes.label.zeit.plot(basemap="satellite")                     # legend: soy, pasture, forest
unknown = classes.label.where(classes.distance < 3, 0)          # 0 where nothing fits
zeit.plot(ndvi, fit=classes)                                     # click a pixel: its best match
zeit.save_raster(classes, "twdtw")                               # label.tif, distance.tif, distances.tif

Segmentation (SNIC)

Tutorial: Segmentation.

snic

zeit.snic(
    data, *, spacing=10, compactness=0.5, seeds=None,
    grid="rectangular", padding=None, tile_size=None,
    random_state=None, nodata="auto", n_jobs=-1,
)

SNIC superpixels of an image or a whole cube: every value of a pixel off its y/x (each band, each date) is one feature, so two pixels are alike when their whole trajectories are, as sits_segment(seg_fn = sits_snic()). Given the same seeds, labels match the reference C implementation. It replaces run_snic (the engine, still in zeit.segmentation) and the accessor's run_snic.

Parameter Type Default Description
data DataArray, ndarray or path required (y, x), (band, y, x), (time, y, x) or (time, band, y, x), read into memory. Pixels with any missing feature are left unlabelled (-1).
spacing float or pair 10 Seed spacing in pixels.
compactness float 0.5 Regularity of the segments, in data units. Higher is more compact.
seeds (n, 2) array None Explicit (row, col) seeds; overrides the grid.
grid str "rectangular" "rectangular", "diamond", "hexagonal" or "random".
padding float or pair None Seed-free margin. Default spacing / 2.
tile_size int or pair None Segment tiles of this size independently, in parallel.
random_state int None Seed for grid="random".
nodata "auto", float or None "auto" Value marking a missing observation.
n_jobs int -1 Threads.

Returns an xarray.Dataset: labels (y, x) (georeferenced; -1 unlabelled), means (segment, ...) with the cube's dims and coordinates ((segment, time, band) for a (time, band, y, x) cube), and n_pixels, centroid_x, centroid_y (segment) (map coordinates). save_raster writes the labels; snic_to_polygons makes polygons.

seg = zeit.snic(ndvi, spacing=8, compactness=0.3)          # ndvi: (time, y, x)
zeit.save_raster(seg, "results/snic")                       # labels.tif
polygons = zeit.snic_to_polygons(seg, include_means=True)   # one column per date

snic_to_polygons

zeit.segmentation.snic_to_polygons(
    result, transform=None, crs=None, include_means=False,
)

Converts SNIC labels to a GeoDataFrame, one polygon per segment, like sits_segment(). Also exported as zeit.snic_to_polygons.

Parameter Type Default Description
result Dataset or SnicResult required Output of zeit.snic (its transform, CRS and feature names are used) or of the engine run_snic.
transform Affine None Geotransform of a SnicResult (identity: pixel coordinates); taken from a Dataset.
crs None Coordinate reference system of a SnicResult; taken from a Dataset.
include_means bool False Add each segment's mean features as columns, named by the cube's coordinates (2022-01-01_ndvi, …; f0, f1, … for a SnicResult).

snic_grid

zeit.segmentation.snic_grid(
    shape, spacing, padding=None, type="rectangular",
    random_state=None,
)

The seed grids of the R snic package, as (n, 2) (row, col) positions. Also exported as zeit.snic_grid.

Parameter Type Default Description
shape (int, int) required Image (rows, cols).
spacing float or pair required Seed spacing.
padding float or pair None Seed-free margin.
type str "rectangular" Grid type, as in zeit.snic's grid.
random_state int None Seed for "random".

Field boundaries

Fields from the stochastic watershed (Angulo & Jeulin 2007), after the MappingDemo notebook (Baumann 2020, after Emmanuelle Gouillart's segmentation tutorial); preset="notebook" reproduces the notebook's values exactly, and the defaults are those chosen by the sensitivity analysis and spatial cross-validation of phases 24e and 24f. A gradient image is flooded from many random markers; the frequency with which each pixel lands on a watershed boundary is thresholded (hysteresis), the complement is labelled and a final watershed grows those labels into fields. The building blocks are equal, value for value, to scikit-image's and SciPy's. Tutorial: Field boundaries.

fields

zeit.fields(
    data, *, gradient=None, method="montecarlo", realizations=None,
    markers=None, min_distance=20, marker_radius=3, n_neighbors=20,
    coloring="knn", low=None, high=0.6, min_size=None, final=None,
    mask=None, mask_threshold=None, band=None, time=None, preset=None,
    random_state=None, n_jobs=None, marker_density=None,
    mask_quantile=None, combine="mean",
)

Delineates fields in an image, or in a stack or series (the multitemporal gradient is then the default).

The defaults come from the sensitivity analysis (24e) and the spatial cross-validation (24f) on 64 windows in Brazil and the Chaco: the mean F of the field matching rises from 0.50 with the notebook's values to 0.63 with these. In forested landscapes such as the Dry Chaco, a forest mask like the notebook's swir16 > 2000 raises F (about 0.66 to 0.74), so pass mask= or mask_threshold= there; no mask is the default because an absolute threshold does not transfer between regions. Pixels where the gradient is not finite (NoData of every layer, in the multitemporal gradient) are left out of the flooded area by both methods, like masked pixels, and labelled 0.

Parameter Type Default Description
data DataArray, ndarray or path required (y, x), (band, y, x), (time, y, x) or (time, band, y, x). Dims of length 1 are squeezed.
gradient str, DataArray or ndarray None "tophat" (the notebook's), "sobel" or "multitemporal" (see edge_gradient), or a ready (y, x) gradient. None: "sobel" for one 2-D image, "multitemporal" for several layers (bands and/or dates); "tophat" with the notebook preset.
combine str "mean" With the multitemporal gradient: "mean" or "max" of the layers' gradients. No effect otherwise.
method str "montecarlo" "montecarlo" (the notebook's loop) or "exact": the exact probability of uniform one-pixel markers, in about the time of one union-find pass. The low and high thresholds are not yet calibrated for "exact": they are applied as given and need tuning.
realizations int None Monte Carlo: how many watersheds; None is 200 (500 with the notebook preset).
markers int or list None Random markers per watershed (for "exact", the number of markers of the model); None (without marker_density) is a density of 1000 per million pixels (the notebook preset: a count of 1000). A list of (2, k) (row, col) arrays is used as given, one per realization.
marker_density float None Markers per million pixels of the whole grid (rows * cols), instead of markers (an error to give both): max(1, round(marker_density * rows * cols / 1e6)). markers is a count per image, so the same value is a different density on windows of different sizes; F rises up to about 400 to 1000 per million pixels and is flat above (phase 24e). Neither given: 1000. attrs holds the resolved markers and the marker_density.
min_distance float 20 Pixels between markers after thinning.
marker_radius int 3 Radius of the disk each marker is dilated to.
n_neighbors, coloring int, str 20, "knn" The marker colouring graph; "unique" gives every marker its own label.
low, high float None (0.1), 0.6 Hysteresis thresholds on the boundary probability; low=None is 0.1 (0.3 with the notebook preset).
min_size int None Objects of fewer pixels are removed before the final watershed; None is 10 (50 with the notebook preset). The cross-validation preferred 0, at the edge of the grid; up to 25 costs at most 0.006 in F and nothing in D, and 10 avoids thousands of one-pixel objects.
final str None "image" or "gradient": the surface of the final watershed. None: the image for one 2-D image, else the gradient.
mask (y, x) bool None True where the pixel is kept (e.g. not forest).
mask_threshold float None Keep the pixels where the image is greater than this, in its own units. Not together with mask.
mask_quantile float None A relative mask, in percent (0 to 100): keep the pixels where the image is strictly greater than its own percentile over the finite pixels (numpy.percentile, linear). The absolute threshold does not transfer between regions (phase 24e). Needs one 2-D image; not together with mask or mask_threshold. attrs holds mask_quantile and the mask_threshold it resolved to.
band, time None Select one band and/or date of a stack or cube.
preset str None "notebook": every notebook value not passed explicitly: gradient="tophat", realizations=500, markers=1000 (a count, unless marker_density is given), low=0.3, min_size=50, final="image" and mask_threshold=2000 (Landsat SWIR1 reflectance times 10000; not with mask, mask_threshold or mask_quantile). An argument passed explicitly wins.
random_state int None Seed of the Monte Carlo; the result does not depend on n_jobs.
n_jobs int None Threads (None or -1: all the cores but one).

Returns an xarray.Dataset, georeferenced like the input: labels (y, x) (int32, 1..k, 0 outside the mask), boundary (y, x) (float32 boundary probability) and gradient (y, x). attrs["boundary_label"] is 1 when label 1 is the boundary network (the notebook keeps it as a label of its own and grows it), else 0: fields_to_polygons drops it. save_raster writes the three maps.

swir = zeit.load_raster("B5_medoid_2019.tif")                    # raw digital numbers
res = zeit.fields(swir, preset="notebook", random_state=0)       # the notebook's values
res = zeit.fields(swir, random_state=0)                          # the tuned defaults
polygons = zeit.fields_to_polygons(res)
res = zeit.fields(cube, mask=~forest, method="exact", markers=500)   # multitemporal gradient

fields_tiled

zeit.fields_tiled(
    src, out, *, tile=512, overlap=None, polygons=True, n_jobs=None,
    random_state=None, **fields_kwargs,
)

fields for rasters too large for one call (the Gran Chaco is about 1.2e9 pixels at 30 m per year). The raster is cut into tile x tile cores. Pass 1 computes the boundary probability of each core from its window enlarged by overlap pixels on every side and keeps the core; pass 2 makes the labels of each core from that probability and the image of the same enlarged window, with fields' own code (hysteresis, labelling, min_size, the final watershed), and keeps the core. Two pixels facing each other across a seam are one field when either tile's enlarged labelling gives them the same label; the ids are joined through chains of such pairs (a union-find), renumbered 1..k and written, and the polygons are made block by block and dissolved across the blocks. Only windows are in memory, never the raster.

The gradient is the whole raster's, not each tile's: the stretch percentiles of "tophat" and "sobel" and the mean and standard deviation of each layer of "multitemporal" are those of the raster (of a regular sample of 16 Mpx per layer when it is larger). The marker density is the same on every tile, and each tile draws from SeedSequence(random_state, spawn_key=(row, col)), so the result depends on neither n_jobs nor the order of the tiles (it does on tile).

Parameter Type Default Description
src path or DataArray required A raster (GeoTIFF, VRT...; one band, or several for the multitemporal gradient) read by window, or a (y, x) / (band, y, x) DataArray.
out path required Output folder: labels.tif (int32 COG; the boundary network, when kept, is id 1), boundary.tif (float32 COG, the probability) and fields.gpkg.
tile int 512 Pixels per side of a core (smaller tiles cost less per pixel, measured).
overlap int None Pixels of window around the core; None is max(64, 4 * min_distance) (80 at the defaults).
polygons bool True Also write fields.gpkg, with the columns of fields_to_polygons.
n_jobs int None Threads in all (None: all but one). The tiles run min(n_jobs, tiles) at a time.
random_state int None Seed.
**fields_kwargs gradient (a name), method, realizations, marker_density, min_distance, marker_radius, n_neighbors, coloring, low, high, min_size, final, mask_threshold, band, combine, as in fields. markers (a count per image, a different density on every tile), mask, mask_quantile (a percentile of the whole raster), preset and time are errors.

Returns a dict: labels, boundary and polygons (paths), n_fields (without the network), boundary_label, tiles (rows, cols), overlap and n_polygons.

What a tile cannot see: the hysteresis joins a boundary pixel to a strong one along any path, and min_size counts an object's pixels, but both look only inside the enlarged window, so a boundary line connected to a strong one only beyond the overlap, or an object cut by the window, can differ from the whole raster's. The labels are the whole raster's as a partition up to the Monte Carlo's own noise and these edge effects (see benchmarks/fields/tiled/README.md).

res = zeit.fields_tiled("chaco_2020.vrt", "out/", random_state=0, n_jobs=8)
res["labels"], res["n_fields"]

fields_to_polygons

zeit.fields_to_polygons(
    result, *, transform=None, crs=None, include_boundary=False,
)

Converts the labels to a GeoDataFrame, one row per field (a MultiPolygon if the label is in several pieces), with columns field (the label), n_pixels, area_ha, perimeter_m, compactness (Polsby-Popper, 4 pi A / P^2, 1 for a circle) and geometry. Label 0 and the boundary network are skipped.

Area and perimeter are planar in a projected CRS (feet and other units are converted to metres) and geodesic on the CRS's ellipsoid in a geographic one. Without a CRS, area_ha and perimeter_m are NaN, with a warning, and compactness is computed in the units of the transform.

Parameter Type Default Description
result Dataset, DataArray or ndarray required The output of fields (its transform, CRS and boundary label are used), its labels, or an integer array.
transform Affine None Instead of the result's (identity: pixel coordinates).
crs None Instead of the result's.
include_boundary bool False Keep the boundary network's polygon.

edge_gradient

zeit.edge_gradient(
    data, method="tophat", *, band=None, time=None, combine="max",
    n_jobs=None,
)

The edge-strength image that fields floods. "tophat" is the notebook's: the image stretched between its 2nd and 98th percentiles, black_tophat(img, 3x3) - 0.5 * img, then a grey dilation. "sobel" is the Sobel magnitude of the stretched image (equal to skimage.filters.sobel). "multitemporal" standardises and Sobels every layer (each date and band) and combines them with combine ("max" or "mean", the sum over the layers with a value divided by their number; "sum" is an older name for "mean"). "tophat" and "sobel" need one 2-D image, so select it with band / time. Returns a (y, x) DataArray with the input's coordinates.

stochastic_watershed

zeit.stochastic_watershed(
    gradient, *, method="montecarlo", realizations=200, markers=None,
    min_distance=20, marker_radius=3, n_neighbors=20, coloring="knn",
    mask=None, marker_density=None, random_state=None, n_jobs=None,
    return_counts=False,
)

The probability that each pixel lies on a watershed boundary (Angulo & Jeulin 2007): the part of fields that costs the time. The parameters are fields's (realizations=200; markers=None is a density of 1000 per million pixels; marker_density sets another density instead), and mask is inside every watershed; pixels of non-finite gradient are always left out, by both methods. Returns a (y, x) float32 DataArray in [0, 1] (with return_counts, also the raw counts of the Monte Carlo).

watershed

zeit.watershed(elevation, markers, *, mask=None, connectivity=1)

Marker-controlled watershed, equal to skimage.segmentation.watershed: floods elevation from the integer markers (0: unlabelled), inside mask, with 4 (connectivity=1) or 8 (2) neighbours. Returns int32 labels.

Texture

texture

zeit.texture(
    data, *, features=None, window=7, levels=32, distance=1, lo=None,
    hi=None, summary="median", n_jobs=-1,
)

Texture features of an image in a moving window, inputs for a classifier where fields, pastures, orchards and forests differ in texture but not in spectrum. The grey-level co-occurrence matrix's properties (Haralick et al. 1973) are scikit-image's graycomatrix(..., angles=[0, pi/4, pi/2, 3pi/4], symmetric=True, normed=True) and graycoprops for each pixel's window (cut by the image's edges), averaged over the four angles: equal to 1e-12, and 78 times faster on one thread (benchmarks/vs_originals/texture.py). Three of spfeas's window statistics (Graesser et al. 2012) complete them. A cube is summarized over time first.

Parameter Type Default Description
data DataArray or ndarray required A map (y, x), or a cube (time, y, x) summarized by summary.
features str or list None All twelve, or any of: contrast, dissimilarity, homogeneity, asm, energy, correlation, entropy (base 2), glcm_mean, glcm_variance, and the window's mean, std and gradient (mean Sobel magnitude).
window int 7 The window's side in pixels (odd).
levels int 32 Grey levels (2-254) the values are quantized to over [lo, hi].
distance int 1 The pairs' distance in pixels.
lo, hi float None The range quantized; default the image's 2nd and 98th percentiles.
summary str "median" A cube's summary: "median", "mean", "min", "max", "std" or "amplitude" (95th - 5th percentile).
n_jobs int -1 Threads.

Returns an xarray.DataArray (feature, y, x), the map's coordinates kept; NaN where a window has no valid pair.

tex = zeit.texture(ndvi, summary="max", window=7, features=["contrast", "entropy", "std"])
stack = xr.concat([ndvi.median("time").expand_dims(feature=["ndvi"]), tex], "feature")  # predictors

Clustering (SOM)

som

zeit.som(
    data, *, x=3, y=3, sample=50000, num_iters=None,
    algorithm="online", sigma=1.0, learning_rate=0.5,
    decay="linear_decay_to_zero", neighborhood="gaussian",
    topology="rectangular", init="random", seed=42, nodata="auto",
    chunks=None, n_jobs=-1,
)

Clusters the pixels of a map or a cube with a self-organizing map. Every value a pixel holds off its y/x is a feature (each date of an index, each band of each date, each map of a Dataset), so pixels share a neuron when their whole trajectories are alike. The SOM is trained on a random sample of the pixels by the SOM engine (a bit-for-bit port of minisom), then every pixel goes to its best-matching neuron. Tutorial: Clustering.

Parameter Type Default Description
data DataArray, Dataset, ndarray or path required A map, a stack, a (time, y, x) or (time, band, y, x) cube (in memory or dask), a Dataset of maps (e.g. phenology metrics), or anything load_raster reads. The features should share a scale: the distance adds them up as they are.
x, y int 3, 3 Neurons of the grid: x * y clusters. Small grids cluster; large ones (10 × 10 and up) explore the data.
sample int or None 50000 Pixels to train on, drawn at random among those with every feature; None: all of them.
num_iters int None "online": single-sample updates (default 20 passes over the sample). "batch": passes (default 20).
algorithm str "online" "online" or "batch" (parallel). On small grids the batch update can leave neurons empty; the online one does not, and is about as fast on 50,000 samples.
sigma, learning_rate float 1.0, 0.5 Initial neighbourhood radius (grid units) and learning rate.
decay str "linear_decay_to_zero" Online: how the learning rate falls. Ending at 0 lets the prototypes settle; minisom's default, "asymptotic_decay", ends at a third of it, and the last samples seen still pull them (on 30,000 Rondônia trajectories: a mean distance 10% larger, prototypes up to twice as far from their pixels' mean). Or "inverse_decay_to_zero".
neighborhood str "gaussian" "gaussian", "mexican_hat", "bubble" or "triangle".
topology str "rectangular" "rectangular" or "hexagonal".
init str or None "random" Initial prototypes: "random" (sample pixels), "pca" (first two principal components; poor on a grid one neuron wide) or None (minisom's random unit vectors).
seed int 42 Seed of the sample, the initial weights and the sample order.
nodata "auto", float or None "auto" Value marking a missing observation. Pixels with a missing feature get no neuron.
chunks "auto", dict None A raster path: read lazily.
n_jobs int -1 Threads.

Returns an xarray.Dataset: label (y, x) (the neuron, 1 to x * y; 0 without one; the grid positions i_j in flag_meanings), distance (y, x) (to the neuron's prototype: large where the map represents the pixel poorly), prototypes (neuron, ...) with the cube's dims and coordinates (prototypes.sel(neuron=3) is a series over time) and n_pixels (neuron); the grid position of each neuron in the i/j coordinates and the sample's mean distance in attrs["quantization_error"]. Georeferenced as the input; a lazy cube stays lazy. With sample=None and the same arguments, the prototypes are the engine's and label is SOM.predict + 1.

ndvi = zeit.load_raster("LT_Stack_NDVI_Rondonia.tif")     # (time, y, x)
clusters = zeit.som(ndvi, x=2, y=2, sample=30_000)
clusters.prototypes.sel(neuron=1).plot()                  # one typical trajectory
clusters.label.zeit.plot()                                # the cluster map
zeit.plot(ndvi, fit=clusters)                             # click a pixel: its series and its prototype

clean_samples

zeit.clean_samples(
    data, samples, *, label="class", x=None, y=None, num_iters=None,
    algorithm="online", sigma=1.0, learning_rate=0.5,
    decay="linear_decay_to_zero", neighborhood="gaussian",
    topology="rectangular", init="random", seed=42, date=None,
    nodata="auto", n_jobs=-1,
)

Checks labelled samples with a SOM before a classifier is trained on them, as sits_som_clean_samples of the R sits package: a SOM is trained on the features of the samples (read as train_classifier reads them), and a sample whose class differs from the majority class of its neuron is suspicious.

Parameter Type Default Description
data as in train_classifier required What the classifier will be trained on.
samples GeoDataFrame or path required Points with their class, reprojected when in another CRS.
label str "class" The column holding the class.
x, y int None Neurons of the grid; by default a square grid of about 5 * sqrt(n) neurons for n samples.
date date None CCDC segments: the date whose models are the features.
num_iters, algorithm, sigma, learning_rate, decay, neighborhood, topology, init, seed, nodata, n_jobs As in som.

Returns the samples as given (GeoDataFrame, same CRS), with neuron (0: outside the data or a missing feature), neuron_class (the neuron's majority class), purity (the share of the neuron's samples in that class) and keep (the sample's class is its neuron's; False without a neuron).

checked = zeit.clean_samples(stack, "samples.gpkg", label="class")
print(checked[~checked.keep])                              # the suspicious ones
rf = zeit.train_classifier(stack, checked[checked.keep], label="class")

SOM

class zeit.ai.SOM(
    x, y, input_len, sigma=1.0, learning_rate=0.5,
    decay_function="asymptotic_decay",
    neighborhood_function="gaussian", topology="rectangular",
    random_seed=42, sigma_decay_function="asymptotic_decay",
)

The engine of zeit.som, for samples you arrange yourself: a self-organizing map in Rust (online and batch, the batch one multi-threaded), an operation-by-operation port of Python minisom 2.3: with the same random_seed and arguments the trained codebook is bit-for-bit identical to MiniSom.train (algorithm="online") or MiniSom.train_batch_offline (algorithm="batch"), 30–190 times faster. Tutorial: Clustering.

Parameter Type Default Description
x, y int required Grid size.
input_len int required Features per sample.
sigma float 1.0 Initial spread of the neighbourhood function.
learning_rate float 0.5 Initial learning rate.
decay_function str "asymptotic_decay" "asymptotic_decay", "inverse_decay_to_zero" or "linear_decay_to_zero".
neighborhood_function str "gaussian" "gaussian", "mexican_hat", "bubble" or "triangle".
topology str "rectangular" "rectangular" or "hexagonal".
random_seed int 42 Seed of the numpy.random.RandomState used for initialisation and sample order (the same draws as minisom).
sigma_decay_function str "asymptotic_decay" "asymptotic_decay", "inverse_decay_to_one" or "linear_decay_to_one".
Method Description
random_weights_init(data) / pca_weights_init(data) Initialise the weights from random samples / from the first two principal components.
train(data, num_iters, n_jobs=-1, algorithm="online", random_order=False, use_epochs=False) Train on (samples, features), continuing from the current weights. "online": num_iters single-sample updates (epochs with use_epochs=True). "batch": num_iters passes over the data, parallel with n_jobs, same result for any n_jobs.
predict(data, n_jobs=-1) Flat index i * y + j of each sample's best-matching unit.
winner(x) Grid coordinates (i, j) of one sample's best-matching unit.
quantization(data, n_jobs=-1) / quantization_error(data, n_jobs=-1) Best-matching codebook vector of each sample / mean distance to it.
get_weights() Codebook, shape (x, y, input_len).
filter_noisy_samples(data, labels, n_jobs=-1) Boolean mask of samples to keep: False where a sample's label disagrees with the majority label of its neuron.
from zeit.ai import SOM

som = SOM(x=10, y=10, input_len=X.shape[1], sigma=1.5)
som.random_weights_init(X)
som.train(X, num_iters=20, algorithm="batch")    # 20 passes, multi-threaded
clusters = som.predict(X)