Skip to content

API reference

Data

Harmonised Landsat 5-9 and/or Sentinel-2 L2A images over a region, sorted by time.

Parameters:

Name Type Description Default
sensor str

"landsat" (Landsat 5, 7, 8 and 9), "sentinel2", or one of "L5", "L7", "L8", "L9", "S2".

required
region Geometry

Images intersecting this region are selected.

required
start str

Date range, "YYYY-MM-DD"; end is exclusive.

required
end str

Date range, "YYYY-MM-DD"; end is exclusive.

required
max_cloud float

Largest scene cloud cover in percent (CLOUD_COVER for Landsat, CLOUDY_PIXEL_PERCENTAGE for Sentinel-2).

None
cloud_buffer int

Pixels by which cloud and cloud shadow are grown before masking (default 3, i.e. 90 m for Landsat, 60 m for the 20 m Sentinel-2 SCL); 0 keeps the QA masks as they are.

CLOUD_BUFFER

Returns:

Type Description
ImageCollection

Prepared images (see :func:prepare).

Examples:

ls = topocorr.collection("landsat", aoi, "1990-01-01", "2026-01-01", max_cloud=60)

Illumination and masks for each image, from its sun angles and the DEM.

Parameters:

Name Type Description Default
images Image or ImageCollection

Images prepared by :func:topocorr.collection (they carry tc_sun_zenith and tc_sun_azimuth).

required
dem str or Image

DEM name ("glo30", "nasadem", "srtm", "aw3d30"), image asset id, or an elevation image in metres.

'glo30'
steep float

Steep-slope threshold in degrees.

STEEP
shadow_search int

Distance in pixels searched for terrain that casts a shadow (see :func:shadow_search).

SHADOW_SEARCH

Returns:

Type Description
Image or ImageCollection

Bands cos_i, cast_shadow, self_shadow, low_illumination, steep and tc_flag (see :mod:topocorr.flags), with the input image's properties.

Corrections

Correct the illumination of each image.

Parameters:

Name Type Description Default
images Image or ImageCollection

Images prepared by :func:topocorr.collection.

required
model StackModel

A stack model from :func:topocorr.fit, needed by "scsc-stack", "c-stack" and "se-stack" (not used by the per-image methods). Its strata, slope classes, steep threshold, sample size and seed are used; min_slope, steep, sample_size, min_pixels, fit_mask and seed apply to the per-image methods only.

None
method ('scsc-stack', 'c-stack', 'se-stack', 'scsc', 'c', 'cosine')

Correction method. By default "scsc-stack", which needs model. When the model's images have the sun north of the tile in some images and south of it in others (near the equator; :attr:topocorr.StackModel.sun_both_sides), "scsc-stack" warns and uses per-image SCS+C ("scsc") instead, and "c-stack" per-image C ("c"): one curve c(zenith) cannot follow per-image c there and can bias trends on east- and west-facing slopes.

"scsc-stack"
dem str or Image

DEM name, image asset id, or an elevation image in metres; for the stack methods, the DEM the model was fitted with.

'glo30'
min_slope float

Smallest slope in degrees of the pixels used to fit c.

5.0
steep float

Steep-slope threshold in degrees; steeper pixels are not corrected.

STEEP
shadow_search int

Hill-shadow search distance in pixels (per-image methods; the stack methods use the model's value). See :func:topocorr.masking.shadow_search.

SHADOW_SEARCH
sample_size int

Number of pixels drawn for each image's fit (before masked pixels are dropped).

5000
min_pixels int

Fewest usable pixels for a fit.

100
region Geometry

Area to sample for the fit; by default the image footprint.

None
fit_mask (str, Image or None)

Pixels used to fit c. The default "worldcover-trees" fits tree cover only (ESA WorldCover 2021, class 10; the 2021 map is also used for older scenes). An ee.Image fits the pixels where it is non-zero; None fits all pixels. Covers of different brightness that sit on different aspects (dark forest on shaded slopes, bright grass on sunlit ones) bias a fit over all pixels, often to c < 0. The correction is still applied to every pixel. Ignored by "cosine". The stack model (topocorr.fit) fits land cover strata instead.

'worldcover-trees'
seed int

Random seed of the sample.

0

Returns:

Type Description
Image or ImageCollection

The reflectance bands corrected, plus cos_i and tc_flag; properties tc_method, tc_dem and, for "c" and "scsc", tc_fit_ok (all bands fitted), tc_n_sample and per band tc_c_<band>, tc_m_<band>, tc_fit_ok_<band>. The stack methods add tc_model (the model id) and per band tc_c_<band> (scsc-stack, c-stack: c per stratum name) or tc_m_<band> (se-stack: m_t per stratum code; -1 where the fit was not usable).

Examples:

corrected = topocorr.correct(ls, model) (scsc-stack), or topocorr.correct(ls, method="scsc", region=aoi) without a model.

(first − second) / (first + second) and a flag of pixels that mix corrected and raw.

For an image from :func:correct, adds band name and band <name>_mixed: 1 where one of the two bands was corrected and the other was not (see tc_corrected). Such values are not comparable with their neighbours or through time; mask them, or compute the index from the raw bands. For an image without tc_corrected (raw data), <name>_mixed is 0.

Examples:

ndvi = topocorr.normalized_difference(corrected, "nir", "red", "ndvi")

Stack model

Fit the stack model: c as a smooth function of solar zenith, per band and stratum.

Stage 1 fits ρ = m_t cos i + n_t in every image, band and stratum on a stratified sample of unflagged pixels with slopes inside slope_classes; stage 2 fits c(θz) across the stack (see :mod:topocorr.stack).

Parameters:

Name Type Description Default
images ImageCollection

Images from :func:topocorr.collection, all of one sensor family (Landsat 5/7, Landsat 8/9 or Sentinel-2).

required
dem str or Image

DEM name, image asset id, or an elevation image in metres. Use the same DEM in :func:topocorr.correct.

'glo30'
strata ('worldcover', 'worldcover-density', None or Image)

Land cover part of the strata (see :func:strata_image). "worldcover-density" splits tree cover by canopy density (Hansen tree cover in 2000: below 30, 30-50, 50-70 and at least 70 %), because on mountain slopes canopy density often follows aspect (dense forest on shaded slopes, open forest on sunlit ones) and a fit over all forest then learns composition, not illumination. With it, pixels with any recorded Hansen forest loss (2001 onward) are left out of the fit; they are still corrected.

'worldcover'
slope_classes sequence of float

Slope class edges in degrees (default 5-25, 25-40, 40-60).

SLOPE_CLASSES
degree int

Degree of the polynomial in solar zenith (lowered when the zenith range is narrow).

2
samples_per_stratum int

Pixels drawn per stratum and image.

500
min_pixels int

Fewest pixels for an image's stage-1 fit to count.

100
min_images int

Fewest usable images for a stratum's curve; otherwise its land cover's curve is used.

10
steep float

Steep-slope threshold in degrees; steeper pixels are not used.

STEEP
shadow_search int

Hill-shadow search distance in pixels (see :func:topocorr.masking.shadow_search); stored in the model and used again by the stack corrections and :func:topocorr.diagnose.

SHADOW_SEARCH
region Geometry

Area sampled; by default each image's footprint.

None
seed int

Random seed of the samples.

0
batch_size int

Images per Earth Engine request; halved automatically when Earth Engine reports too many concurrent computations (after a few waits and retries).

8
cache str or Path

JSON file of finished images: an interrupted fit resumes from it.

None
progress bool

Print progress to standard error.

True

Returns:

Type Description
StackModel

A fitted stack model (from :func:topocorr.fit, or :func:topocorr.load_model).

Attributes:

Name Type Description
bands tuple of str

Bands modelled.

codes tuple of int

Strata found in the stack (see :func:stratum_code).

images list of dict

Per image: id, time (ms), zenith, azimuth, sensor.

sums ndarray

Stage-1 sums, shape (images, strata, bands, 6) in the order of :data:SUMS.

settings dict

How the model was fitted: strata, cover_names, slope_classes, degree, min_pixels, min_images, samples_per_stratum, steep, dem, seed, sensor_family.

curves dict

curves[band][code] = :class:Curve; own strata and pooled land covers (code 10 cover).

used dict

used[band][code] = the code of the curve a stratum uses (its own, its land cover's) or None (not assessable).

id property

Short identifier of the model (hash of its settings, images and sums).

sun_both_sides property

True when the sun is north of the tile in some images and south of it in others.

This happens near the equator (in the test tiles, within about 10 degrees of it), where the sun passes north and south of the tile in the course of the year. Each side must hold at least :data:SUN_SIDE_SHARE of the images. Per-image c then differs between the two sides, which one curve c(zenith) cannot follow, and scsc-stack can bias trends on east- and west-facing slopes; :func:topocorr.correct uses per-image SCS+C for such a stack.

build(bands, codes, images, sums, settings, strata_image=None) classmethod

Run stage 2 on the stage-1 sums and return the model.

c(band, stratum, zenith)

Return c of a band and stratum at a solar zenith (NaN if not assessable).

code(stratum)

Stratum code from a code or a name.

curve(band, stratum)

Return the curve a stratum uses (its own or its cover's); None if not assessable.

from_dict(d) classmethod

Inverse of :meth:to_dict (stage 2 is refitted, so curves are identical).

image_fits(band, stratum)

Stage-1 results per image for one band and stratum, with zenith and usable.

name(code)

Readable stratum name, for example "trees/25-40" or "trees/all slopes".

summary()

Return a text table: per band and stratum, images, c at 30, 45 and 60°, source.

to_dict()

Plain dictionary (JSON-ready); the stage-2 curves are rebuilt on loading.

to_json(path)

Save the model as JSON; :func:load_model reads it back.

Read a model saved with :meth:StackModel.to_json.

Illumination artefacts

Map how much of each pixel's index trend comes from illumination (drift and total).

Parameters:

Name Type Description Default
images ImageCollection

Images from :func:topocorr.collection (raw reflectance).

required
model StackModel or dict of StackModel

A stack model, or one per sensor family (Landsat 5/7, Landsat 8/9, Sentinel-2) for a series that spans families; each image uses its family's model.

required
index ('ndvi', 'nbr', 'ndmi', 'evi', 'nirv')

The vegetation index tested.

"ndvi"
dem str or Image

The DEM the model was fitted with.

'glo30'
harmonics int

Annual harmonics removed before the trends (1-3).

2
min_obs int

Fewest usable observations of a pixel; fewer gives risk class 0.

20
trend_threshold float

|observed trend| (index units per year) below which the risk class is 4, "no trend".

0.001
shadow_search int

Hill-shadow search distance in pixels; by default the model's value.

None

Returns:

Type Description
Image

Bands :data:OUTPUT_BANDS on the 30 m grid of the first image; properties tc_index, tc_harmonics, tc_min_obs and tc_sun_both_sides (1 when a model's images have the sun north of the tile in some images and south of it in others, :attr:topocorr.StackModel.sun_both_sides; diagnose then warns, as the artefact estimate rests on one c(zenith) curve that does not follow per-image c there).

Comparing methods

Export the raw stack at fixed sample points, for :func:compare.

Parameters:

Name Type Description Default
images ImageCollection

Images from :func:topocorr.collection (raw reflectance), the stack the model was fitted on.

required
model StackModel

The stack model; its strata, slope classes, steep threshold and hill-shadow search are used.

required
region Geometry

Where the points are drawn.

required
n_points int

Points per stratum.

500
folder str

Google Drive folder and file name prefix of the two tables.

'topocorr_exports'
prefix str

Google Drive folder and file name prefix of the two tables.

'topocorr_exports'
manifest str or Path

Local path of the manifest (JSON); the model is saved next to it as <stem>_model.json.

'topocorr_compare.json'
dem str or Image

The DEM the model was fitted with.

'glo30'
seed int

Random seed of the points.

42
start bool

Start the export tasks (False only builds them).

True

Returns:

Type Description
dict

The manifest: task ids, Drive folder, file names, images, settings.

Examples:

topocorr.compare_export(oli, model, region=aoi, folder="topocorr_exports")

Compare correction methods on the tables of :func:compare_export (no Earth Engine calls).

Parameters:

Name Type Description Default
tables (str, Path or dict)

The manifest written by :func:compare_export (the two CSV files downloaded next to it), or the dict returned by :func:load_tables.

required
model (StackModel, str or Path)

The stack model; by default the one saved with the manifest.

None
methods sequence of str

Any of :data:METHODS ("none" is the uncorrected stack).

DEFAULT_METHODS
index ('nirv', 'ndvi', 'evi', 'nbr', 'ndmi')

The index for temporal noise and the drift share. NIRv by default: in NDVI the drift artefact is often near the noise level.

"nirv"
min_slope float

Smallest slope (degrees) of the forest points where the metrics are measured.

10.0
fit_min_slope (float, int)

Per-image fits ("c", "scsc", "se-stack"): smallest slope of the tree-cover points used, and fewest points per fit.

5.0
min_pixels (float, int)

Per-image fits ("c", "scsc", "se-stack"): smallest slope of the tree-cover points used, and fewest points per fit.

5.0
harmonics int

Annual harmonics in the temporal-noise fit and the drift test (1-3).

2
min_obs int

Fewest clear observations of a point.

20
exclude_loss bool

Leave points with recorded forest loss out of the metrics.

True

Returns:

Type Description
list of dict, or pandas.DataFrame when pandas is installed

One row per method: method, points, images, illumination_r, sunlit_shaded_gap, temporal_sd_nir, temporal_sd_<index>, out_of_range, predicted_drift_left, predicted_drift_high (the predicted drift left assumes that the stack model is right; see the module documentation) and tc_sun_both_sides: 1 when the model's images have the sun north of the tile in some images and south of it in others (near the equator; :attr:topocorr.StackModel.sun_both_sides), else 0. compare then warns: it applies every method as named, while :func:topocorr.correct would use per-image SCS+C instead of "scsc-stack" and per-image C instead of "c-stack".

Examples:

table = topocorr.compare("topocorr_compare.json")

Read the manifest of :func:compare_export and the two tables downloaded next to it.

Returns a dict with images (list of dict), points and raw (columns as arrays), model and scale.

Flags

Bits of the tc_flag band.

Flagged pixels are reported, not corrected: pixels in cast shadow, in self-shadow or on very steep slopes keep their input value. Low illumination is a warning only; those pixels are corrected. "No fit" is set on every pixel of an image in which the C or SCS+C fit of at least one band could not be used; those bands are returned unchanged (see tc_fit_ok_<band>). With the stack methods, "no fit" marks the pixels of a stratum whose per-image fit (se-stack) or c (scsc-stack) could not be used in at least one band, and "no model" the pixels whose stratum the stack model does not cover; both keep their input value in those bands.

BAND_BITS = {band: 1 << i for i, band in enumerate(BANDS)} module-attribute

Bits of the tc_corrected band: bit i is set where band BANDS[i] was corrected.

Ratio indices (NDVI, NBR, ...) must be computed from bands corrected together, or from raw bands, never from a corrected band and an uncorrected one: the illumination term then no longer cancels and the index takes a spurious dependence on terrain. :func:mixed finds such pixels; :func:topocorr.normalized_difference flags them.

CAST_SHADOW = 1 module-attribute

Shadow cast by surrounding terrain (and not self-shadowed).

EXCLUDED = CAST_SHADOW | SELF_SHADOW | STEEP module-attribute

Flags whose pixels keep their input value.

FLAGS = {'cast_shadow': CAST_SHADOW, 'self_shadow': SELF_SHADOW, 'steep': STEEP, 'no_fit': NO_FIT, 'low_illumination': LOW_ILLUMINATION, 'no_model': NO_MODEL} module-attribute

Flag names and their bit values.

LOW_ILLUMINATION = 16 module-attribute

Barely lit: 0 < cos i < 0.1. Flag only; the pixel is corrected.

NO_FIT = 8 module-attribute

The C or SCS+C fit of at least one band was not usable; those bands are unchanged.

NO_MODEL = 32 module-attribute

Stack methods: the pixel's stratum is not in the model or not assessable; not corrected.

SELF_SHADOW = 2 module-attribute

The slope faces away from the sun: cos i <= 0.

STEEP = 4 module-attribute

Slope above the steep threshold (60° by default).

decode(value)

Names of the flags set in a tc_flag value.

Examples:

>>> decode(20)
['steep', 'low_illumination']
>>> decode(0)
[]

mixed(corrected, bands)

Return True where some, but not all, of bands were corrected.

corrected is a tc_corrected value or array.

Examples:

>>> bool(mixed(BAND_BITS["nir"], ["nir", "red"]))  # NIR corrected, red not
True
>>> bool(mixed(BAND_BITS["nir"] | BAND_BITS["red"], ["nir", "red"]))
False