Lab 11: Spatial community composition
BIO597 Spatial Analysis of Biodiversity
How does our view of an amphibian community change when a site is a 10 km, 20 km, or 40 km grid cell? Does community similarity decline with distance? Can climate and geographic separation help explain the differences?
We will use the original Maine amphibian occurrences and WorldClim rasters to:
- Build site-by-species matrices at three grid grains.
- Map richness and compare distance decay of Jaccard similarity.
- Fit a generalized dissimilarity model (GDM) at each grain.
- Interpret how spatial aggregation and sampling affect the results.
Run from docs/labs. Use the same data and settings across grains so that
changes in the definition of a site are the main comparison.
0. Environment and imports
Install the gdmbayes package first
pip install gdmbayes
from pathlib import Path
import geopandas as gpd
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import rasterio
from rasterio.mask import mask
from shapely.geometry import box
from scipy.spatial.distance import pdist, squareform, jaccard
from gdmbayes import GDM
CRS = "EPSG:26919" # UTM zone 19N: distances in meters, suitable for Maine.
GRAINS = [10, 20, 40] # Cell width in kilometers.
MIN_RECORDS = 1
OUTPUT = Path("outputs/Lab11")
OUTPUT.mkdir(parents=True, exist_ok=True)
Exercise 1: Define sites and compare communities
1. Load occurrences and the Maine boundary
Retain named species and points within Maine. Each occurrence is a record, not necessarily a different individual. Species names are used as supplied; synonyms or identification errors can affect the community matrix.
maine = gpd.read_file("ME_ShapeFiles/Maine_State_Boundary.shp").to_crs(CRS).dissolve()
records = gpd.read_file("../data/amphibians.geojson").to_crs(CRS)
records = records.dropna(subset=["species"])
records = records[records.species != ""]
records = gpd.clip(records, maine)
print("Maine records:", len(records))
print("Species labels:", records.species.nunique())
ax = maine.plot(color="whitesmoke", edgecolor="gray", figsize=(6, 7))
records.plot(ax=ax, markersize=2, alpha=0.25)
ax.set_title("Amphibian occurrence records")
ax.set_axis_off()
plt.show()
2. Aggregate records to a spatial grid
Grain is the width of a grid cell. A larger cell pools records from more places. Our grids share a fixed origin, so 10 km cells nest within 20 km cells, and 20 km cells nest within 40 km cells.
The helper below assigns each point a column and row, counts records by site
and species, and draws the occupied cells. // means integer division: it
finds which cell contains a coordinate. We clip cell outlines to Maine for
mapping, but use the original square centers for geographic distances.
Only cells meeting MIN_RECORDS become sites. Gray areas on the maps have no
retained site; they are not evidence of zero richness. Coastal cells contain
less land than interior cells, even at the same nominal grain.
# A fixed southwest grid corner, in UTM meters.
x0 = 320_000
y0 = 4_720_000
def grid_communities(grain_km):
width = grain_km * 1000
points = records.copy()
points["col"] = ((points.geometry.x - x0) // width).astype(int)
points["row"] = ((points.geometry.y - y0) // width).astype(int)
points["site_id"] = points.col.astype(str) + "_" + points.row.astype(str)
community = pd.crosstab(points.site_id, points.species)
cell_locations = points[["site_id", "col", "row"]].drop_duplicates()
cells = []
for cell in cell_locations.itertuples():
x = x0 + cell.col * width
y = y0 + cell.row * width
cells.append({"site_id": cell.site_id, "xc": x + width / 2,
"yc": y + width / 2, "geometry": box(x, y, x + width, y + width)})
sites = gpd.GeoDataFrame(cells, crs=CRS).set_index("site_id")
sites = gpd.clip(sites, maine).sort_index()
community = community.reindex(sites.index)
sites["n_records"] = community.sum(axis=1)
sites["richness"] = (community > 0).sum(axis=1)
sites = sites[sites.n_records >= MIN_RECORDS].copy()
community = community.loc[sites.index]
return sites, community
sites_by_grain = {}
communities = {}
grain_summary = pd.DataFrame()
for grain in GRAINS:
sites, community = grid_communities(grain)
sites_by_grain[grain] = sites
communities[grain] = community
grain_summary.loc[grain, "n_sites"] = len(sites)
grain_summary.loc[grain, "n_records"] = sites.n_records.sum()
grain_summary.loc[grain, "mean_richness"] = sites.richness.mean()
grain_summary.loc[grain, "median_records_per_site"] = sites.n_records.median()
grain_summary.index.name = "grain_km"
display(grain_summary)
display(communities[20].head())
sites_by_grain and communities store the results for each grain. For example,
communities[20] is the 20 km site-by-species count matrix.
3. Compare richness maps
Use one color scale across all three maps. Changing grain changes the area represented by a site; higher richness in larger cells need not mean that the underlying landscape has changed.
max_richness = max(sites.richness.max() for sites in sites_by_grain.values())
fig, axes = plt.subplots(1, 3, figsize=(13, 6), layout="constrained")
for ax, grain in zip(axes, GRAINS):
maine.plot(ax=ax, color="lightgray", edgecolor="gray")
sites_by_grain[grain].plot(ax=ax, column="richness", cmap="viridis",
vmin=0, vmax=max_richness, legend=True)
ax.set_title(f"{grain} km cells")
ax.set_axis_off()
fig.savefig(OUTPUT / "richness_by_grain.png", dpi=150)
plt.show()
fig, axes = plt.subplots(1, 2, figsize=(10, 6), layout="constrained")
for ax, column in zip(axes, ["n_records", "richness"]):
maine.plot(ax=ax, color="lightgray", edgecolor="gray")
sites_by_grain[10].plot(ax=ax, column=column, legend=True)
ax.set_title(f"10 km: {column}")
ax.set_axis_off()
plt.show()
Discuss: Which apparent hotspots persist across grains? Where do record
numbers and richness coincide? How would incomplete sampling or small coastal
land areas affect the comparison? Later, try MIN_RECORDS = 5 and rerun the
analysis. This excludes sparsely recorded sites; it does not equalize effort.
4. Species lists, turnover, and nestedness
Use Jaccard dissimilarity on presence/absence, as in Lab10. Jaccard
similarity is 1 - dissimilarity: one means identical lists; zero means no
shared species. These compare recorded lists, not known true communities.
A poorer list may be a subset of a richer list (nestedness), or some species may be replaced by others (turnover). Total Jaccard dissimilarity can reflect both. The two invented examples below have the same dissimilarity.
print("Subset, AB versus ABCD:", jaccard([True, True, False, False],
[True, True, True, True]))
print("Replacement, ABC versus ACD:", jaccard([True, True, True, False],
[True, False, True, True]))
5. Calculate all site pairs
SciPy's pdist calculates each unique pair once, in a fixed order. Using the
same site order for the community matrix and coordinates gives matching
vectors of dissimilarity and distance. No species-list comparison is made
for unsampled cells.
def community_pairs(sites, community):
presence = community.loc[sites.index] > 0
dissimilarity = pdist(presence, metric="jaccard")
distance_km = pdist(sites[["xc", "yc"]]) / 1000
return pd.DataFrame({"distance_km": distance_km,
"jaccard": dissimilarity,
"similarity": 1 - dissimilarity})
pairs_by_grain = {}
for grain in GRAINS:
pairs_by_grain[grain] = community_pairs(sites_by_grain[grain], communities[grain])
display(pairs_by_grain[20].head())
6. Distance decay of similarity
Do more distant sites tend to share fewer species? Plot all pairs, then average similarity within 50 km distance bands to make the broad pattern easier to see. The averages use all pairs in each band.
A distance-decay pattern may reflect environmental differences, dispersal, history, or sampling. Pairs reuse the same sites, so they are not independent replicates. We describe the pattern rather than report an ordinary regression p-value treating every pair as independent.
def distance_bands(pairs):
rows = []
for lower in range(0, 650, 50):
in_band = pairs[(pairs.distance_km >= lower) & (pairs.distance_km < lower + 50)]
if len(in_band) == 0:
continue
rows.append({"distance_km": in_band.distance_km.mean(),
"mean_similarity": in_band.similarity.mean(),
"n_pairs": len(in_band)})
return pd.DataFrame(rows)
binned_decay = {}
fig, axes = plt.subplots(1, 3, figsize=(13, 4), layout="constrained")
for ax, grain in zip(axes, GRAINS):
pairs = pairs_by_grain[grain]
bands = distance_bands(pairs)
binned_decay[grain] = bands
ax.scatter(pairs.distance_km, pairs.similarity, s=2, alpha=0.03)
ax.plot(bands.distance_km, bands.mean_similarity, color="black", marker="o")
ax.set(title=f"{grain} km cells", xlabel="Distance between cell centers (km)",
ylabel="Jaccard similarity", ylim=(0, 1))
grain_summary.loc[grain, "distance_similarity_rho"] = pairs.distance_km.corr(
pairs.similarity, method="spearman")
fig.savefig(OUTPUT / "distance_decay_by_grain.png", dpi=150)
plt.show()
display(grain_summary)
Discuss: Does the shape or strength of distance decay change with grain?
The Spearman correlation (rho) is a descriptive summary, not an independent-
pair significance test. Check the number of pairs in binned_decay[10] before
interpreting the ends of the curve. Why might aggregation increase similarity?
7. Map differences among neighboring sites
For each sampled cell, average its Jaccard dissimilarity to sampled neighbors within 1.5 cell widths. This includes touching side and diagonal neighbors. Cells with no sampled neighbor receive a missing value.
This is a map of local compositional difference, not richness or a rate per kilometer. The comparison distance grows with grain, so the maps have different spatial support. Missing cells are not places with zero turnover.
for grain in GRAINS:
sites = sites_by_grain[grain]
pairs = pairs_by_grain[grain]
distances = squareform(pairs.distance_km.to_numpy())
dissimilarities = squareform(pairs.jaccard.to_numpy())
local_difference = []
for i in range(len(sites)):
neighbors = (distances[i] > 0) & (distances[i] <= 1.5 * grain)
if neighbors.any():
local_difference.append(dissimilarities[i, neighbors].mean())
else:
local_difference.append(np.nan)
sites["neighbor_dissimilarity"] = local_difference
fig, axes = plt.subplots(1, 3, figsize=(13, 6), layout="constrained")
for ax, grain in zip(axes, GRAINS):
maine.plot(ax=ax, color="lightgray", edgecolor="gray")
sites_by_grain[grain].plot(ax=ax, column="neighbor_dissimilarity", cmap="magma",
vmin=0, vmax=1, legend=True)
ax.set_title(f"{grain} km: neighbor dissimilarity")
ax.set_axis_off()
fig.savefig(OUTPUT / "neighbor_dissimilarity_by_grain.png", dpi=150)
plt.show()
Discuss: Are the most compositionally different neighborhoods also the richest? Inspect two contrasting sites' species lists. Could a high neighbor dissimilarity reflect an undersampled site or a subset pattern rather than species replacement?
Exercise 2: Generalized dissimilarity modeling at each grain
8. Describe the climate of each site
Distance decay combines several possible explanations. GDM relates pairwise community dissimilarity to climate differences and geographic separation. We will use two familiar WorldClim variables:
| Predictor | Variable | Units |
|---|---|---|
temperature_c |
BIO1, annual mean temperature | °C |
precipitation_mm |
BIO12, annual precipitation | mm/year |
Calculate the mean of valid raster pixels intersecting each cell's Maine land area. This represents the site rather than weighting climate by occurrence locations. Edge pixels are included and equally weighted; this is an approximate zonal mean, not an exact area-weighted average. The climate layers summarize 1970–2000 conditions, while occurrences span multiple years.
CLIMATE_DIR = Path("../data/bioclim_ME")
CLIMATE_LAYERS = {"temperature_c": 1, "precipitation_mm": 12}
CLIMATE_LAYERS = {
'wc2.1_2.5m_bio_1.tif': 'temperature_c',
'wc2.1_2.5m_bio_2.tif': 'diurnal_range_c',
'wc2.1_2.5m_bio_3.tif': 'isothermality',
'wc2.1_2.5m_bio_4.tif': 'temp_seasonality',
'wc2.1_2.5m_bio_5.tif': 'max_temp_warmest',
'wc2.1_2.5m_bio_6.tif': 'min_temperature_coldest',
'wc2.1_2.5m_bio_7.tif': 'temp_range',
'wc2.1_2.5m_bio_8.tif': 'temp_wettest_q',
'wc2.1_2.5m_bio_9.tif': 'temp_driest_q',
'wc2.1_2.5m_bio_10.tif': 'temp_warmest_q',
'wc2.1_2.5m_bio_11.tif': 'temp_coldest_q',
'wc2.1_2.5m_bio_12.tif': 'precip',
'wc2.1_2.5m_bio_13.tif': 'precip_wettest_m',
'wc2.1_2.5m_bio_14.tif': 'precip_driest_m',
'wc2.1_2.5m_bio_15.tif': 'precip_seasonality',
'wc2.1_2.5m_bio_16.tif': 'precip_wettest_q',
'wc2.1_2.5m_bio_17.tif': 'precip_driest_q',
'wc2.1_2.5m_bio_18.tif': 'precip_warmest_q',
'wc2.1_2.5m_bio_19.tif': 'precip_coldest_q',
}
CLIMATE_DIR = Path("../data/bioclim_ME")
predictors = list(CLIMATE_LAYERS.values())
def add_climate(sites):
sites = sites.copy()
for f, name in CLIMATE_LAYERS.items():
path = CLIMATE_DIR / f
means = []
with rasterio.open(path) as raster:
raster_sites = sites.to_crs(raster.crs)
for geometry in raster_sites.geometry:
pixels, transform = mask(raster, [geometry], crop=True,
filled=False, all_touched=True)
valid_pixels = pixels[0].compressed()
if len(valid_pixels) == 0:
means.append(np.nan)
else:
means.append(valid_pixels.mean())
sites[name] = means
return sites
climate_sites = {}
for grain in GRAINS:
sites = add_climate(sites_by_grain[grain])
climate_sites[grain] = sites
print(grain, "km: sites missing climate =", sites[predictors].isna().any(axis=1).sum())
display(climate_sites[20][predictors].describe())
display(climate_sites[20][predictors].corr())
fig, axes = plt.subplots(2, 3, figsize=(10, 6), layout="constrained")
for ax, name in zip(axes.flat, predictors):
maine.plot(ax=ax, color="lightgray", edgecolor="gray")
climate_sites[20].plot(ax=ax, column=name, legend=True)
ax.set_title(name)
ax.set_axis_off()
plt.show()
9. Prepare GDM inputs
GDM models dissimilarity between pairs, not the occurrence of one species. Its fitted response is between 0 and 1. Smooth, increasing transformations allow a given climate difference to matter more in some parts of a gradient than in others. See Ferrier et al. (2007).
The installed gdmbayes package expects:
X: one row per site, withxc,yc,time_idxfirst, then climate. Coordinates are projected meters. Alltime_idxvalues are zero because we pool years; this is a required placeholder, not a fitted temporal predictor.y: Jaccard dissimilarities inpdistorder for those same rows.
Drop sites without climate, then align the matrix to the retained site IDs. Recalculate pairs after that selection; keeping an earlier pair vector would misalign the response and predictors.
model_sites = {}
model_X = {}
model_y = {}
for grain in GRAINS:
sites = climate_sites[grain].dropna(subset=predictors).copy()
community = communities[grain].loc[sites.index]
X = sites[["xc", "yc"]].copy()
X["time_idx"] = 0
X[predictors] = sites[predictors]
y = pdist(community > 0, metric="jaccard")
model_sites[grain] = sites
model_X[grain] = X
model_y[grain] = y
print(grain, "km:", len(X), "sites and", len(y), "pairs")
display(model_X[20].head())
10. Fit one standard GDM per grain
First fit a geography-only baseline, then geography plus temperature and precipitation. knots=0 gives a simple
three-basis smooth response for each predictor. Keep the settings unchanged
across grains. Geography uses straight-line distance, not movement routes.
explained_ is the fraction of training deviance explained, not R² or
held-out predictive accuracy. The importance values are fitted transformation
heights; they are not p-values or causal effects. Correlated climate and
geography can share explanatory information.
models = {}
predictions = {}
gdm_summary = pd.DataFrame()
importance = pd.DataFrame()
for grain in GRAINS:
X = model_X[grain]
y = model_y[grain]
geography_only = GDM(geo=True, knots=0).fit(X[["xc", "yc", "time_idx"]], y)
model = GDM(geo=True, knots=0).fit(X, y)
models[grain] = model
predictions[grain] = model.predict(X)
gdm_summary.loc[grain, "n_sites"] = len(X)
gdm_summary.loc[grain, "n_pairs"] = len(y)
gdm_summary.loc[grain, "geography_only_deviance_pct"] = 100 * geography_only.explained_
gdm_summary.loc[grain, "training_deviance_explained_pct"] = 100 * model.explained_
for name, value in model.predictor_importance_.items():
importance.loc[grain, name] = value
gdm_summary.index.name = "grain_km"
importance.index.name = "grain_km"
display(gdm_summary)
display(importance)
fig, axes = plt.subplots(1, 3, figsize=(12, 4), layout="constrained")
for ax, grain in zip(axes, GRAINS):
ax.scatter(predictions[grain], model_y[grain], s=3, alpha=0.05)
ax.plot([0, 1], [0, 1], color="black", linestyle="--")
ax.set(title=f"{grain} km: training fit", xlabel="Predicted Jaccard dissimilarity",
ylabel="Observed Jaccard dissimilarity", xlim=(0, 1), ylim=(0, 1))
fig.savefig(OUTPUT / "gdm_training_fit_by_grain.png", dpi=150)
plt.show()
Discuss: Where do predictions miss the observed dissimilarities? Why might larger cells produce a different apparent fit? Different grains change the sites, pairs, and response distribution, so deviance explained is not a controlled contest between models on the same test data. A real prediction test should hold out geographic groups of sites, not randomly split pairs that still share sites with training data.
11. Read the climate transformations
Use gdm_transform to see how the fitted model stretches each climate gradient.
The helper varies one predictor while holding the other inputs fixed. It sums
the transformed contributions and subtracts the starting value, leaving that
predictor's cumulative effect.
A steep segment indicates more modeled community change across that climate interval. A flat segment indicates little modeled change. The y axis is partial ecological distance, not species richness, occurrence probability, or a habitat optimum. Climate units stay on the x axis.
# Sort bioclim variable importance by values, so we can look at only the most relevant ones
sorted_cols = importance.sum().sort_values(ascending=False).index
importance_sorted = importance[sorted_cols].drop(columns=['geo'])
importance_sorted
def climate_curve(model, X, predictor):
curve = pd.DataFrame(index=range(100))
for column in X.columns:
curve[column] = X[column].median()
curve[predictor] = np.linspace(X[predictor].min(), X[predictor].max(), 100)
effect = model.gdm_transform(curve).sum(axis=1)
effect = effect - effect[0]
return pd.DataFrame({"value": curve[predictor], "effect": effect})
curves = {}
fig, axes = plt.subplots(2, 3, figsize=(11, 4), layout="constrained")
for ax, name in zip(axes.flat, importance_sorted.columns):
for grain in GRAINS:
curve = climate_curve(models[grain], model_X[grain], name)
curves[(grain, name)] = curve
ax.plot(curve.value, curve.effect, label=f"{grain} km")
ax.set(xlabel=name, ylabel="Partial ecological distance")
ax.legend()
fig.savefig(OUTPUT / "gdm_climate_curves_by_grain.png", dpi=150)
plt.show()
Discuss: Which climate intervals show the most modeled change? Do the curves
agree across grains? Compare their heights with importance. Curve ranges and
fitted coefficients change with grain; these are associations rather than
independent evidence of a physiological threshold or climate causation.
12. Compare the grains together
Keep site counts, observed patterns, and model fit in the same table. A coarser grain pools species lists, smooths climate, reduces the number of sites, and changes what a pairwise comparison represents.
comparison = grain_summary.join(gdm_summary, rsuffix="_gdm")
display(comparison)
PCA map and biplot of expected community composition
As in Lab09, give the map and a PCA biplot the same color key. First transform the environmental predictors with the fitted GDM. The package returns several weighted spline components per predictor; sum these to get one transformed column for each climate variable. Fit PCA without standardizing these columns, so the GDM weights are preserved.
There are 19 climate predictors, and we will collapse these into 2 PCs for plotting. Red and green encode their rescaled scores; blue is held constant. More similar colors indicate more similar climate-associated expected composition. Geographic distance is a pairwise term and is excluded from this site-level transformation. The colors are a visualization, not calibrated Jaccard distances or species-richness values.
The arrows show increasing transformed climate layers with the largest loadings. Their
lengths describe contributions to the displayed PCA pattern. Gray areas have no
modeled site. Set pca_grain to 10 or 40 to repeat the figure; each grain gets
its own PCA and color scale, so matching colors across runs are not a shared key.
from sklearn.decomposition import PCA
from sklearn.preprocessing import MinMaxScaler
pca_grain = 20 # Try 10 or 40 as well.
X_biplot = model_X[pca_grain]
model = models[pca_grain]
# Sum each predictor's weighted spline components.
weighted_splines = model.gdm_transform(X_biplot)
n_basis = model.preprocessor_.n_spline_bases_
transformed = pd.DataFrame(index=X_biplot.index)
for i, name in enumerate(predictors):
start = i * n_basis
stop = start + n_basis
transformed[name] = weighted_splines[:, start:stop].sum(axis=1)
pca = PCA(n_components=2)
scores = pca.fit_transform(transformed)
scaled_scores = MinMaxScaler(clip=True).fit_transform(scores)
colors = np.column_stack([scaled_scores, np.full(len(scores), 0.5)])
fig, axes = plt.subplots(1, 2, figsize=(11, 5), layout="constrained")
maine.plot(ax=axes[0], color="lightgray", edgecolor="gray")
model_sites[pca_grain].loc[X_biplot.index].plot(ax=axes[0], color=colors)
axes[0].set_title(f"{pca_grain} km: expected composition")
axes[0].set_axis_off()
axes[1].scatter(scores[:, 0], scores[:, 1], c=colors, s=25)
loadings = pca.components_.T * np.sqrt(pca.explained_variance_)
# Get the predictors with the largest loadings
idx = np.argpartition(np.sum(np.abs(loadings), axis=1), -2)[-2:]
for i in idx:
vector = loadings[i]
name = predictors[i]
axes[1].annotate("", xy=vector, xytext=(0, 0),
arrowprops={"arrowstyle": "->", "color": "black"})
axes[1].text(vector[0] * 1.1, vector[1] * 1.1, name, fontsize=9)
axes[1].set(title="GDM-transformed climate: PCA",
xlabel=f"PC1 ({pca.explained_variance_ratio_[0]:.0%} of variance)",
ylabel=f"PC2 ({pca.explained_variance_ratio_[1]:.0%} of variance)")
axes[1].set_aspect("equal")
fig.savefig(OUTPUT / f"gdm_pca_biplot_{pca_grain}_km.png", dpi=150)
plt.show()
Discuss: Where do colors change most strongly across Maine? Which climate gradient aligns with that change? Compare this map with richness and neighbor dissimilarity: why do they describe different aspects of the community?
13. Save results
The main figures are saved when drawn. Save site maps, community matrices, GDM inputs, pairwise observed/predicted values, distance-band summaries, and climate curves. The saved inputs and settings above allow the models to be refit.
comparison.to_csv(OUTPUT / "grain_comparison.csv")
importance.to_csv(OUTPUT / "gdm_predictor_importance.csv")
for grain in GRAINS:
climate_sites[grain].to_file(OUTPUT / f"sites_{grain}_km.gpkg", driver="GPKG")
communities[grain].to_csv(OUTPUT / f"community_{grain}_km.csv")
model_X[grain].to_csv(OUTPUT / f"gdm_inputs_{grain}_km.csv")
pairs_by_grain[grain].to_csv(OUTPUT / f"observed_pairs_{grain}_km.csv", index=False)
binned_decay[grain].to_csv(OUTPUT / f"distance_bands_{grain}_km.csv", index=False)
fitted_pairs = community_pairs(model_sites[grain], communities[grain])
fitted_pairs["predicted_jaccard"] = predictions[grain]
fitted_pairs.to_csv(OUTPUT / f"gdm_pairs_{grain}_km.csv", index=False)
for name in predictors:
curves[(grain, name)].to_csv(OUTPUT / f"gdm_curve_{name}_{grain}_km.csv", index=False)
print("Results saved in", OUTPUT)
Interpretation and deliverables
Submit the completed notebook and a 400–600 word interpretation supported by your figures and grain-comparison table. Address:
- How grain changes observed richness, sampled-site numbers, and the maps.
- Distance decay at each grain, including the possibility of nestedness and uneven reporting rather than only species replacement.
- What GDM adds to geographic distance alone, and how its fit, predictor contributions, and climate transformations change with grain.
- Which conclusions persist across grains, which are sensitive to the site definition, and what data would improve an ecological interpretation.
Keep the main comparison at MIN_RECORDS = 1. As a sensitivity exercise,
repeat with MIN_RECORDS = 5 and report whether your conclusions change.
Do not interpret fitting the same records as independent validation.
References: week 11 topics, Ferrier et al. (2007), GDM, gdmbayes source and examples, and WorldClim variables.
np.full(len(scores), 0.5)