FRAGSTATS metrics comparison#
The aim of this notebook is to compare the landscape metrics computed by PyLandStats with those computed by FRAGSTATS (v4.2), which is the reference implementation that PyLandStats follows.
The comparison uses an extract of the Canton of Vaud (Switzerland) derived from the CORINE Land Cover dataset of the year 2000, together with the .patch, .class and .land files that FRAGSTATS produces, which ship with the docs in the data/fragstats directory.
This notebook is executed when building the docs, therefore the comparison below is performed against the very version of PyLandStats that this page documents, i.e., if any metric diverged from FRAGSTATS beyond the tolerance set below, this page would not build.
import numpy as np
import pandas as pd
import pylandstats as pls
Let us set the relative tolerance to 0.001, i.e., we accept a relative difference of 0.1% between the values computed with PyLandStats and FRAGSTATS, and define some utilities:
fragstats_abbrev_dict = pls.settings.fragstats_abbrev_dict
tol = 1e-3
data_dir = "data/fragstats"
basename = "vaud_g100_clc00_V18_5"
def read_fragstats_csv(csv_filepath):
"""Read a CSV file dumped by FRAGSTATS into a data frame."""
# `na_values` is required because of the leading whitespaces that FRAGSTATS
# leaves when saving CSV files
fragstats_df = pd.read_csv(csv_filepath, na_values=[" N/A"])
fragstats_df.columns = fragstats_df.columns.str.strip()
try:
fragstats_df["TYPE"] = (
fragstats_df["TYPE"].str.strip().str.replace("cls_", "").astype(int)
)
except KeyError:
pass
return fragstats_df
def get_comparable_metrics(metrics, fragstats_df, *, abbrev_dict=None):
"""Get the metrics that the FRAGSTATS dump features, and those that it does not.
A metric cannot be compared either because it has no FRAGSTATS counterpart (e.g.,
the disjunct core area metrics) or because the FRAGSTATS files were dumped before
the metric was implemented in PyLandStats (e.g., the core area metrics).
"""
if abbrev_dict is None:
abbrev_dict = fragstats_abbrev_dict
comparable, missing = [], []
for metric in metrics:
abbrev = abbrev_dict.get(metric)
if abbrev is not None and abbrev in fragstats_df.columns:
comparable.append(metric)
else:
missing.append(metric)
return sorted(comparable), sorted(missing)
We will now instantiate a PyLandStats landscape with the raster file:
ls = pls.Landscape(f"{data_dir}/{basename}.tif", res=(100, 100))
Patch-level metrics#
If the value of any metric differs more than the relative tolerance defined above, a RuntimeError will be raised.
patch_df = read_fragstats_csv(f"{data_dir}/{basename}.patch")
patch_metrics, missing_patch_metrics = get_comparable_metrics(
pls.Landscape.PATCH_METRICS, patch_df
)
for patch_metric in patch_metrics:
fragstats_abbrev = fragstats_abbrev_dict[patch_metric]
for class_val in ls.classes:
fragstats_ser = patch_df[fragstats_abbrev][patch_df["TYPE"] == class_val]
pls_ser = getattr(ls, patch_metric)(class_val=class_val)
if not np.allclose(fragstats_ser, pls_ser, tol, equal_nan=True):
raise RuntimeError(patch_metric, class_val, fragstats_ser, pls_ser)
print(f"{patch_metric}: OK")
# ACHTUNG: asserted explicitly so that implementing a new metric does not
# silently reduce the coverage of this comparison
assert set(missing_patch_metrics) == {
"core_area",
"core_area_index",
"number_of_core_areas",
}
print(f"\nnot in the FRAGSTATS dump: {missing_patch_metrics}")
area: OK
euclidean_nearest_neighbor: OK
fractal_dimension: OK
perimeter: OK
perimeter_area_ratio: OK
shape_index: OK
not in the FRAGSTATS dump: ['core_area', 'core_area_index', 'number_of_core_areas']
Class-level metrics#
class_df = read_fragstats_csv(f"{data_dir}/{basename}.class")
# ACHTUNG: the 'total_area' metric is 'CA' at the class level (and 'TA' at the landscape
# level), whereas PyLandStats uses 'TA' in both cases
class_abbrev_dict = dict(fragstats_abbrev_dict, total_area="CA")
class_metrics, missing_class_metrics = get_comparable_metrics(
set(pls.Landscape.CLASS_METRICS).difference(pls.Landscape.DISTR_METRICS),
class_df,
abbrev_dict=class_abbrev_dict,
)
for class_metric in class_metrics:
fragstats_abbrev = class_abbrev_dict[class_metric]
for class_val in ls.classes:
fragstats_val = class_df[fragstats_abbrev][class_df["TYPE"] == class_val].iloc[
0
]
pls_val = getattr(ls, class_metric)(class_val=class_val)
if not (
np.isclose(fragstats_val, pls_val, tol)
or np.isclose(fragstats_val, pls_val, atol=tol)
):
raise RuntimeError(
f"{class_metric} (class {class_val}): fragstats {fragstats_val},"
f" pylandstats {pls_val}"
)
print(f"{class_metric}: OK")
# ACHTUNG: asserted explicitly so that implementing a new metric does not
# silently reduce the coverage of this comparison
assert set(missing_class_metrics) == {
"core_area_proportion_of_landscape",
"number_of_disjunct_core_areas",
"total_core_area",
}
print(f"\nnot in the FRAGSTATS dump: {missing_class_metrics}")
edge_density: OK
effective_mesh_size: OK
landscape_shape_index: OK
largest_patch_index: OK
number_of_patches: OK
patch_density: OK
proportion_of_landscape: OK
total_area: OK
total_edge: OK
not in the FRAGSTATS dump: ['core_area_proportion_of_landscape', 'number_of_disjunct_core_areas', 'total_core_area']
Landscape-level metrics#
We exclude the distribution statistics and the entropy metrics, since except for the Shannon diversity index and the contagion, they are not implemented in FRAGSTATS. Note also that we use a relative tolerance of 1% at the landscape level.
landscape_df = read_fragstats_csv(f"{data_dir}/{basename}.land")
landscape_metrics, missing_landscape_metrics = get_comparable_metrics(
set(pls.Landscape.LANDSCAPE_METRICS)
.difference(set(pls.Landscape.ENTROPY_METRICS).union(pls.Landscape.DISTR_METRICS))
.union(["shannon_diversity_index", "contagion"]),
landscape_df,
)
for landscape_metric in landscape_metrics:
fragstats_abbrev = fragstats_abbrev_dict[landscape_metric]
fragstats_val = landscape_df[fragstats_abbrev].iloc[0]
pls_val = getattr(ls, landscape_metric)()
if not np.isclose(fragstats_val, pls_val, rtol=0.01):
raise RuntimeError(
f"{landscape_metric}: fragstats {fragstats_val}, pylandstats {pls_val}"
)
print(f"{landscape_metric}: OK")
# ACHTUNG: asserted explicitly so that implementing a new metric does not
# silently reduce the coverage of this comparison
assert set(missing_landscape_metrics) == {
"number_of_disjunct_core_areas",
"total_core_area",
}
print(f"\nnot in the FRAGSTATS dump: {missing_landscape_metrics}")
contagion: OK
edge_density: OK
effective_mesh_size: OK
landscape_shape_index: OK
largest_patch_index: OK
number_of_patches: OK
patch_density: OK
shannon_diversity_index: OK
total_area: OK
total_edge: OK
not in the FRAGSTATS dump: ['number_of_disjunct_core_areas', 'total_core_area']
The metrics listed as “not in the FRAGSTATS dump” above are implemented in PyLandStats but cannot be compared here, since the FRAGSTATS files were dumped before they were implemented. Regenerating them requires running FRAGSTATS 4.2 manually. The same comparison is also performed in the test suite, which asserts that the list of metrics that cannot be compared does not grow unnoticed.