Habitat Suitability and Landscape Connectivity for the Forest Musk Deer
This is Capstone 5 of the spatial analysis module (Part 7). It maps habitat for the forest musk deer (Moschus berezovskii) in the Huanglong Mountains of Shaanxi and asks which patches are large enough, and still connected, for the animals to move between them. The analysis follows Zheng et al. (2026) with a knowledge-driven model, a presence-background ensemble, and least-cost and circuit connectivity.
Data: 177 coarsened occurrence records and eight predictors in data/Data_and_Code_Forest_Musk_Deer (Dryad, doi:10.5061/dryad.qbzkh1902).
Study area: Huanglong Mountains, about 7,293 km².
Library:geolattice.spatial_analysis
Overview
Stage
Question
Main tools
Prepare
Are the layers on one metric grid?
reproject_raster, warp
Scale check
What can coarsened occurrence records support?
block summaries
Model A: multi-criteria
Which cells meet the published habitat requirements?
Installation. This notebook needs installation option 2 (core plus spatial analysis): pip install "geolattice[analysis]". See “Installation options” in the GeoLattice README.
Code
# Display matplotlib figures inline in this Jupyter notebook.%matplotlib inline# Standard library imports.import sys # make the capstone helper module importableimport time # report how long the heavier steps takeimport warnings # silence harmless runtime warnings from empty slicesfrom pathlib import Path # filesystem paths# Third-party numeric / geospatial / plotting stack.import geopandas as gpd # patch polygons and outputsimport matplotlib.pyplot as plt # maps and chartsimport numpy as np # raster arraysimport pandas as pd # tablesfrom IPython.display import display # rich table previewsfrom pyproj import Transformer # longitude / latitude -> UTMfrom scipy import ndimage # moving-window summaries and patch labellingfrom scipy import sparse # graph and circuit matricesfrom scipy.sparse import csgraph # cost distance (Dijkstra)from scipy.sparse.linalg import spsolve # circuit solves# Machine learning (scikit-learn).from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifierfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import roc_auc_score, roc_curvefrom sklearn.model_selection import GroupKFold, StratifiedShuffleSplitfrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import PolynomialFeatures, SplineTransformer, StandardScalerfrom sklearn.tree import DecisionTreeClassifier# Shared capstone helpers live next to this notebook.sys.path.insert(0, str(Path.cwd()))import data_processing as dp # paths and raster I/Oimport geolatticeROOT = Path(geolattice.__file__).resolve().parents[1]ifnot (ROOT /"Data").is_dir(): ROOT = dp.find_repo_root()# GeoLattice tools.from geolattice.raster import polygonize, reproject_raster, warp, write_raster_datafrom geolattice.spatial_analysis import ( gaussian, # bell-shaped membership around an optimum large, # sigmoid membership, large values -> 1 linear, # linear ramp membership monte_carlo_weights, # Dirichlet weight uncertainty score_contributions, # per-criterion weighted contributions small, # sigmoid membership, small values -> 1 weighted_linear_combination, # weighted linear combination)from geolattice.viz import apply_map_styleapply_map_style()warnings.filterwarnings("ignore", category=RuntimeWarning)warnings.filterwarnings("ignore", category=FutureWarning) # scikit-learn API deprecation noticeswarnings.filterwarnings("ignore", message=".*penalty.*") # same, for the L1 logistic modelpd.set_option("display.precision", 3)RNG = np.random.default_rng(2026) # one seed for every random step# Inputs and outputs.SRC = ROOT /"Data"/"03_spatial_analysis"/"Data_and_Code_Forest_Musk_Deer"OUT = dp.capstone_dir(ROOT, "musk_deer")print(f"Inputs: {SRC}")print(f"Outputs: {OUT}")
Study area. The Huanglong Mountains, south-east of Yan’an, Shaanxi Province (about 109.6°E to 110.6°E, 35.3°N to 36.4°N; 7,293 km²). The climate is temperate continental monsoon, annual precipitation is 400 to 600 mm and forest covers at least 65 percent of the land. Three nature reserves lie inside the area; two were designated for the brown eared pheasant, one for musk deer.
Question. Where is habitat for the forest musk deer, which patches are large enough to support home ranges, and where is movement between patches most constrained?
Data (Dryad, doi:10.5061/dryad.qbzkh1902, CC0):
File
Content
spe_example.csv
177 occurrence records from DNA-confirmed faecal samples (2016-2017, 2024), after a 120 m spatial filter
current/*.asc
The eight predictors retained by the authors, each already at its optimal neighbourhood scale, about 30 m cells
Coniferous forest (5) best, then broadleaf forest (4)
Dis_resident
Distance to settlements (m)
Prefers > 5,000 m
Dis_river
Distance to rivers (m)
Prefers proximity
Dis_road
Distance to roads (m)
Minor
Aspect
Transformed aspect (0-1)
Minor
A property of these data that shapes the whole analysis. Because the species is poached for musk, the authors coarsened every published coordinate to 0.1 decimal degrees, roughly 9 km east-west by 11 km north-south here. The predictors, in contrast, are 30 m grids. Section 4 shows what that means and how the two models below are designed around it. The results will therefore not reproduce the published maps cell for cell, and they should not be read as locating animals.
Records: 177
Distinct coordinate pairs after coarsening: 23
longitude
latitude
records
17
110.3
35.9
51
13
110.2
35.9
30
15
110.3
35.7
15
11
110.2
35.7
13
21
110.4
35.9
12
7
110.1
35.6
9
10
110.2
35.6
7
19
110.4
35.7
5
The 177 records collapse to 23 distinct 0.1° grid centres. Two thirds of the records sit on just four centres, which mostly reflects where the transects were walked. One centre, 110.3°E 35.1°N, lies south of the predictor extent and is dropped below.
Data preparation
The ASCII grids carry no projection file. Their header (cell size 0.000303°) shows geographic coordinates, so they are read as WGS 84, then projected to UTM zone 49N (the projection used in the paper) on a 90 m grid. A 90 m cell keeps the fine-scale detail the multi-criteria model needs while keeping the notebook fast.
Continuous layers use bilinear resampling.
Landcover uses the majority (mode) of the 30 m cells.
A road mask is built on the original grid (Dis_road == 0) and kept wherever any 30 m road cell falls in the 90 m cell, so thin roads are not lost.
Code
CRS_UTM ="EPSG:32649"# WGS 84 / UTM zone 49NCELL =90.0# analysis cell size (m)PREDICTORS = ["Slope", "Bio12", "Bio5", "Landcover", "Dis_resident", "Dis_river", "Dis_road", "Aspect"]t0 = time.time()GRID = {} # name -> path of the 90 m UTM rasterfor name in PREDICTORS: dst = OUT /f"{name.lower()}_90m.tif"ifnot dst.exists(): reproject_raster( SRC /"current"/f"{name}.asc", dst, CRS_UTM, src_crs="EPSG:4326", resample="mode"if name =="Landcover"else"bilinear", resolution=CELL, overwrite=True, ) GRID[name] = dst# Road mask on the source grid, then "max" so any road cell marks the 90 m cell.ROADS = OUT /"roads_90m.tif"ifnot ROADS.exists():from osgeo import gdal src = gdal.Open(str(SRC /"current"/"Dis_road.asc")) a = src.GetRasterBand(1).ReadAsArray() road30 = OUT /"roads_30m_src.tif" write_raster_data(road30, np.where(a ==-9999, 255, (a ==0)).astype("uint8"), crs="EPSG:4326", geotransform=src.GetGeoTransform(), nodata=255, overwrite=True) src =None reproject_raster(road30, ROADS, CRS_UTM, resample="max", resolution=CELL, overwrite=True) road30.unlink()print(f"Reprojection done in {time.time() - t0:.0f} s")# Load everything on the common grid.layers = {name: dp.read_band(path)[0] for name, path in GRID.items()}_, GT, _ = dp.read_band(GRID["Slope"])EXTENT = dp.extent_of(GRID["Slope"])valid = np.all([np.isfinite(a) for a in layers.values()], axis=0)roads = (dp.read_band(ROADS)[0] ==1) & validCELL_HA = CELL * CELL /1e4print(f"Grid: {valid.shape[1]} x {valid.shape[0]} cells, study area {valid.sum() * CELL_HA /100:,.0f} km2")print(f"Road cells: {roads.sum():,} ({roads.mean() / valid.mean():.1%} of the area)")
Reprojection done in 0 s
Grid: 976 x 1351 cells, study area 7,291 km2
Road cells: 39,023 (4.3% of the area)
Code
# Map the eight predictors.titles = {"Slope": "Slope (deg)", "Bio12": "Annual precipitation (mm)", "Bio5": "Max temp. warmest month (°C)","Landcover": "Land cover class", "Dis_resident": "Distance to settlement (m)","Dis_river": "Distance to river (m)", "Dis_road": "Distance to road (m)", "Aspect": "Aspect (transformed)"}cmaps = {"Slope": "YlOrBr", "Bio12": "Blues", "Bio5": "coolwarm", "Landcover": "tab10", "Dis_resident": "magma","Dis_river": "PuBu_r", "Dis_road": "magma", "Aspect": "twilight"}fig, axes = plt.subplots(2, 4, figsize=(20, 11))for ax, name inzip(axes.ravel(), PREDICTORS): arr = np.where(valid, layers[name], np.nan) kw =dict(vmin=0.5, vmax=10.5, interpolation="nearest") if name =="Landcover"else {} im = ax.imshow(arr, cmap=cmaps[name], extent=EXTENT, **kw) ax.set_title(titles[name]) ax.set_xticks([]); ax.set_yticks([]) plt.colorbar(im, ax=ax, fraction=0.04)plt.suptitle("Predictors on the 90 m UTM 49N grid", y=0.92)plt.show()# Land-cover composition.LC_NAMES = {1: "rainfed cropland", 2: "herbaceous cropland", 3: "irrigated cropland", 4: "broadleaf forest",5: "needle-leaved forest", 6: "grassland", 7: "marsh", 8: "flooded flat", 9: "impervious",10: "bare", 11: "water"}lc = layers["Landcover"]share = pd.Series({LC_NAMES[int(k)]: 100* np.mean(lc[valid] == k) for k in np.unique(lc[valid])}, name="% of area")display(share.sort_values(ascending=False).to_frame())
% of area
broadleaf forest
58.703
grassland
25.365
rainfed cropland
6.800
needle-leaved forest
4.244
flooded flat
2.143
herbaceous cropland
1.203
irrigated cropland
0.777
marsh
0.567
impervious
0.197
Two things stand out. Slope is smooth, with a maximum of 26°: the authors supplied it as a neighbourhood mean at their optimal scale (a 1,920 m radius), not as cell slope. And broadleaf forest dominates, while needle-leaved forest, the class the species prefers, covers only about 4 percent.
The scale problem: what coarsened records can support
A presence-background model compares conditions at occurrence points with conditions across the study area. That only works if the occurrence point and the predictor describe the same place. Here each record is known only to lie somewhere in a 0.1° block, while a predictor cell is 90 m wide.
Two quantities make the problem concrete for slope, the dominant driver:
the value at the grid centre, which is what a naive model would use;
the block mean over the 0.1° block around the centre, which is what the record can honestly represent.
Code
to_utm = Transformer.from_crs("EPSG:4326", CRS_UTM, always_xy=True)sites["x"], sites["y"] = to_utm.transform(sites.longitude.values, sites.latitude.values)rc = [dp.xy_to_rowcol(x, y, GT) for x, y inzip(sites.x, sites.y)]sites["row"] = [r for r, _ in rc]sites["col"] = [c for _, c in rc]inside = (sites.row.between(0, valid.shape[0] -1)) & (sites.col.between(0, valid.shape[1] -1))print("Dropped (outside the predictor extent):", sites.loc[~inside, ["longitude", "latitude"]].values.tolist())sites = sites[inside].reset_index(drop=True)# A centre that falls on a masked cell (outside the study-area outline) moves to the nearest valid cell.near_r, near_c = ndimage.distance_transform_edt(~valid, return_distances=False, return_indices=True)moved =~valid[sites.row, sites.col]sites["row"], sites["col"] = near_r[sites.row, sites.col], near_c[sites.row, sites.col]print(f"Centres moved onto the study area: {int(moved.sum())}")# Block size in cells: 0.1 degree of longitude and of latitude at the study-area centre.LAT0 =35.85BLOCK_X =int(round(0.1*111_320* np.cos(np.radians(LAT0)) / CELL)) # ~ 9.0 kmBLOCK_Y =int(round(0.1*110_950/ CELL)) # ~ 11.1 kmprint(f"0.1-degree block = {BLOCK_X} x {BLOCK_Y} cells ({BLOCK_X * CELL /1000:.1f} km x {BLOCK_Y * CELL /1000:.1f} km)")def block_mean(arr, mask, size=(BLOCK_Y, BLOCK_X)):"""Moving-window mean over valid cells only (NaN outside ``mask``).""" a = np.where(mask, arr, 0.0) num = ndimage.uniform_filter(a, size=size, mode="constant") den = ndimage.uniform_filter(mask.astype(float), size=size, mode="constant")return np.where(mask & (den >0), num / np.maximum(den, 1e-12), np.nan)slope = layers["Slope"]slope_block = block_mean(slope, valid)steep_block = block_mean((slope >22).astype(float), valid)sites["slope_at_centre"] = [slope[r, c] for r, c inzip(sites.row, sites.col)]sites["block_mean_slope"] = [slope_block[r, c] for r, c inzip(sites.row, sites.col)]sites["block_share_gt22"] = [steep_block[r, c] for r, c inzip(sites.row, sites.col)]summary = pd.DataFrame( {"occurrence blocks (mean)": sites[["slope_at_centre", "block_mean_slope", "block_share_gt22"]].mean(),"whole study area": [np.nanmean(slope[valid]), np.nanmean(slope[valid]), np.mean(slope[valid] >22)], })display(summary)
Dropped (outside the predictor extent): [[110.3, 35.1]]
Centres moved onto the study area: 1
0.1-degree block = 100 x 123 cells (9.0 km x 11.1 km)
occurrence blocks (mean)
whole study area
slope_at_centre
20.518
17.502
block_mean_slope
20.151
17.502
block_share_gt22
0.331
0.128
What this shows.
Around the occurrence blocks, mean slope is about 3° above the landscape average and the share of land steeper than 22° is more than twice as high. The habitat signal survives at block scale.
The centre cell itself is an arbitrary point. It has no ecological link to where a sample was collected, so treating centres as exact locations would train a model on noise at 90 m.
Design consequence. The notebook uses each kind of information at the scale it supports:
Model
Information
Scale
Role
A, multi-criteria
The species’ habitat requirements as published
90 m cells
Where local conditions are suitable
B, machine learning
The 22 occurrence blocks against the background
0.1° block summaries, mapped on a 270 m grid
Where the surrounding landscape resembles occupied blocks
The final map requires both. A cell that meets the habitat requirements but lies in a landscape unlike any occupied block, or the reverse, is not treated as primary habitat.
Model A: knowledge-driven habitat suitability
Each predictor is converted to a membership between 0 and 1 that follows the response the paper reports (Section 3.2 and Figure 2 of Zheng et al. 2026):
Aspect is left out: its transformation is not documented in the data release, so its direction cannot be interpreted.
Weights follow the paper’s relative contributions where they are reported: slope 56.2, precipitation 19.1, temperature 12.8. The paper gives only an upper bound (< 5 % each) for the rest; the remaining 11.9 points are split here as land cover 4.5, settlements 3.4, rivers 2.5 and roads 1.5. That split is a modelling choice, and Section 9 tests how much it matters.
Code
# Membership functions (GeoLattice) applied to every 90 m cell.lc_scores = {1: 0.1, 2: 0.1, 3: 0.1, 4: 0.8, 5: 1.0, 6: 0.3, 7: 0.1, 8: 0.05, 9: 0.0, 10: 0.0, 11: 0.0}lc_member = np.full(lc.shape, np.nan)for k, v in lc_scores.items(): lc_member[lc == k] = vmembers = {"slope": large(np.maximum(slope, 1e-6), midpoint=20.0, spread=12.0),"precipitation": gaussian(layers["Bio12"], midpoint=462.0, spread=0.004),"warm_temperature": small(layers["Bio5"], midpoint=27.0, spread=30.0),"land_cover": lc_member,"settlement_distance": linear(layers["Dis_resident"], 0.0, 5000.0),"river_distance": linear(layers["Dis_river"], 4000.0, 500.0),"road_distance": linear(layers["Dis_road"], 0.0, 1000.0),}members = {k: np.where(valid, np.clip(np.asarray(v, float), 0, 1), np.nan) for k, v in members.items()}WEIGHTS_A = {"slope": 56.2, "precipitation": 19.1, "warm_temperature": 12.8, "land_cover": 4.5,"settlement_distance": 3.4, "river_distance": 2.5, "road_distance": 1.5}# Plot the membership curves over the observed range of each variable.curve_vars = [("slope", slope, "Slope (deg)"), ("precipitation", layers["Bio12"], "Annual precipitation (mm)"), ("warm_temperature", layers["Bio5"], "Max temp. warmest month (°C)"), ("settlement_distance", layers["Dis_resident"], "Distance to settlement (m)"), ("river_distance", layers["Dis_river"], "Distance to river (m)"), ("road_distance", layers["Dis_road"], "Distance to road (m)")]fig, axes = plt.subplots(1, 6, figsize=(22, 3.4))for ax, (key, raw, label) inzip(axes, curve_vars): x, y = raw[valid], members[key][valid] idx = RNG.choice(x.size, 4000, replace=False) order = np.argsort(x[idx]) ax.plot(x[idx][order], y[idx][order], color="darkgreen") ax2 = ax.twinx() ax2.hist(x, bins=40, color="grey", alpha=0.25) ax2.set_yticks([]) ax.set_ylim(-0.02, 1.02) ax.set_xlabel(label) ax.set_title(f"{key} (w={WEIGHTS_A[key]})", fontsize=9)axes[0].set_ylabel("Membership")plt.tight_layout()plt.show()
Code
# Weighted linear combination (weights are normalised to sum to 1).stack_A = {k: np.nan_to_num(v) for k, v in members.items()}hsi_A = np.where(valid, weighted_linear_combination(stack_A, WEIGHTS_A), np.nan)# Which criterion contributes most in each cell?contrib = score_contributions(stack_A, WEIGHTS_A)names_A =list(contrib)w_norm = np.array([WEIGHTS_A[k] for k in names_A]) /sum(WEIGHTS_A.values())# Shortfall = weight x (1 - membership): the criterion that costs each cell most.shortfall = np.stack([w * (1- stack_A[k]) for w, k inzip(w_norm, names_A)])limiting = np.where(valid, np.argmax(shortfall, axis=0), -1)fig, axes = plt.subplots(1, 2, figsize=(16, 8))im = axes[0].imshow(hsi_A, cmap="viridis", extent=EXTENT, vmin=0, vmax=1)axes[0].set_title("Model A: knowledge-driven HSI (90 m)")plt.colorbar(im, ax=axes[0], fraction=0.04)cm = plt.get_cmap("Set2", len(names_A))axes[1].imshow(np.where(valid, limiting, np.nan), cmap=cm, extent=EXTENT, vmin=-0.5, vmax=len(names_A) -0.5, interpolation="nearest")handles = [plt.Rectangle((0, 0), 1, 1, fc=cm(i)) for i inrange(len(names_A))]axes[1].legend(handles, [n.replace("_", " ") for n in names_A], loc="lower left", fontsize=8)axes[1].set_title("Largest weighted shortfall (limiting criterion)")for ax in axes: ax.set_xticks([]); ax.set_yticks([])plt.tight_layout()plt.show()lim_share = pd.Series({names_A[i].replace("_", " "): 100* np.mean(limiting[valid] == i) for i inrange(len(names_A))}, name="% of area where limiting")display(lim_share.sort_values(ascending=False).to_frame())
% of area where limiting
slope
88.843
precipitation
10.298
warm temperature
0.860
land cover
0.000
settlement distance
0.000
river distance
0.000
road distance
0.000
Reading Model A. Because slope carries more than half the weight, the map follows the mountain blocks: high scores along the steep central ranges, low scores on the loess plateau edges and in the valleys. Across almost 90 percent of the area the limiting criterion is slope. Precipitation limits a block in the south-centre where annual rainfall rises above the 462 mm optimum, and warm-month temperature limits small areas in the north-east.
Checking Model A against the records at the scale they support. Model A used no occurrence data, so it can be tested on them: if it is right, the 0.1° blocks with records should have higher mean HSI than the rest of the landscape.
Code
hsi_A_block = block_mean(np.nan_to_num(hsi_A), valid)pres_vals = np.array([hsi_A_block[r, c] for r, c inzip(sites.row, sites.col)])# Compare with every valid cell's block mean (a block centred on each cell).bg_vals = hsi_A_block[valid][RNG.choice(valid.sum(), 20000, replace=False)]auc_A_block = roc_auc_score(np.r_[np.ones(pres_vals.size), np.zeros(bg_vals.size)], np.r_[pres_vals, bg_vals])print(f"Block-scale AUC of Model A against the 22 occurrence blocks: {auc_A_block:.2f}")
Block-scale AUC of Model A against the 22 occurrence blocks: 0.76
An AUC well above 0.5 means the published habitat requirements, applied without any occurrence data, already rank occupied blocks above the background. That is independent support for Model A, at the only scale the records allow.
Model B: presence-background ensemble
Block-scale predictors
Every predictor is summarised over a 0.1° moving block, the precision of the records. Land cover becomes two shares (needle-leaved forest; all forest), and slope gets a second summary, the share of land steeper than 22°. The block summaries are computed on the 90 m grid and sampled on a 270 m grid, which is ample for surfaces this smooth.
Code
AGG =3# 90 m -> 270 mCELL_B = CELL * AGGdef coarsen(arr, how="mean"):"""Aggregate a 90 m array to 270 m blocks of AGG x AGG cells.""" r, c = (arr.shape[0] // AGG) * AGG, (arr.shape[1] // AGG) * AGG blocks = arr[:r, :c].reshape(r // AGG, AGG, c // AGG, AGG)return np.nanmean(blocks, axis=(1, 3)) if how =="mean"else np.nanmax(blocks, axis=(1, 3))feature_src = {"slope_mean": slope,"slope_share_gt22": (slope >22).astype(float),"precipitation": layers["Bio12"],"warm_temperature": layers["Bio5"],"needleleaf_share": (lc ==5).astype(float),"forest_share": np.isin(lc, [4, 5]).astype(float),"dist_settlement": layers["Dis_resident"],"dist_river": layers["Dis_river"],"dist_road": layers["Dis_road"],}t0 = time.time()feat270 = {k: coarsen(block_mean(v, valid)) for k, v in feature_src.items()}valid270 = coarsen(valid.astype(float)) >=0.5print(f"Block summaries in {time.time() - t0:.0f} s; 270 m grid {valid270.shape[1]} x {valid270.shape[0]}, "f"{valid270.sum():,} cells")# Collinearity screen: correlations and variance inflation factors on the study area.F = pd.DataFrame({k: v[valid270] for k, v in feat270.items()}).dropna()def vif(df): out = {}for col in df.columns: X = df.drop(columns=col).values X = np.column_stack([np.ones(len(X)), X]) beta, *_ = np.linalg.lstsq(X, df[col].values, rcond=None) resid = df[col].values - X @ beta r2 =1- resid.var() / df[col].values.var() out[col] =1/max(1- r2, 1e-9)return pd.Series(out, name="VIF")corr = F.corr()fig, ax = plt.subplots(figsize=(7, 6))im = ax.imshow(corr, cmap="RdBu_r", vmin=-1, vmax=1)ax.set_xticks(range(len(corr)), corr.columns, rotation=60, ha="right", fontsize=8)ax.set_yticks(range(len(corr)), corr.columns, fontsize=8)for i inrange(len(corr)):for j inrange(len(corr)): ax.text(j, i, f"{corr.iloc[i, j]:.2f}", ha="center", va="center", fontsize=7)plt.colorbar(im, ax=ax, fraction=0.04)ax.set_title("Correlation of block-scale predictors")plt.show()display(vif(F).to_frame())
Block summaries in 0 s; 270 m grid 325 x 450, 99,997 cells
VIF
slope_mean
2.767
slope_share_gt22
2.137
precipitation
6.463
warm_temperature
11.252
needleleaf_share
1.288
forest_share
7.348
dist_settlement
3.666
dist_river
1.328
dist_road
1.595
At block scale, warm-month temperature has the highest VIF: it follows elevation, as precipitation and forest cover do. Following the paper’s rule (VIF < 5, priority to ecologically direct variables), the cell below drops variables one at a time, highest VIF first, while protecting slope share, temperature and precipitation, the three drivers the paper retained despite their correlation.
Code
protected = {"slope_share_gt22", "warm_temperature", "precipitation"}keep =list(F.columns)whileTrue: v = vif(F[keep]) candidates = v.drop(labels=[k for k in protected if k in v.index]).sort_values(ascending=False)if candidates.empty or candidates.iloc[0] <5orlen(keep) <=4:break keep.remove(candidates.index[0])FEATURES = keepprint("Retained predictors:", FEATURES)display(vif(F[FEATURES]).to_frame())
Only the total forest share is dropped. Temperature and precipitation stay above the threshold and are kept anyway, as the authors kept Bio5 and Bio12 (r = 0.77): their coefficients in the GLM should not be interpreted one at a time, but the tree-based members and the ensemble prediction are not harmed by the overlap.
Presences and background
Presences: the 22 block centres inside the area, one per block. Repeated records at a centre do not add information about habitat, only about survey effort, so they are not used as weights.
Background: eight sets of random cells (two each of 300, 500, 800 and 1,000), as in the paper, drawn across the study area excluding presence cells.
Code
rr270 = np.clip(sites.row.values // AGG, 0, valid270.shape[0] -1)cc270 = np.clip(sites.col.values // AGG, 0, valid270.shape[1] -1)# A centre that falls just outside the mask moves to the nearest valid 270 m cell.dist_idx = ndimage.distance_transform_edt(~valid270, return_distances=False, return_indices=True)rr270, cc270 = dist_idx[0][rr270, cc270], dist_idx[1][rr270, cc270]pres_cells = rr270 * valid270.shape[1] + cc270valid_idx = np.flatnonzero(valid270.ravel())bg_pool = np.setdiff1d(valid_idx, pres_cells)PA_SIZES = [300, 300, 500, 500, 800, 800, 1000, 1000]pa_sets = [RNG.choice(bg_pool, n, replace=False) for n in PA_SIZES]Xgrid = np.column_stack([feat270[k].ravel() for k in FEATURES]) # every 270 m cellX_pres = Xgrid[pres_cells]print(f"Presences: {len(pres_cells)} | background sets: {PA_SIZES}")# Spatial groups for cross-validation: 0.3-degree tiles (3 x 3 occurrence blocks).tile_rows =int(np.ceil(3* BLOCK_Y / AGG))tile_cols =int(np.ceil(3* BLOCK_X / AGG))def tile_id(cells): r, c = np.divmod(cells, valid270.shape[1])return (r // tile_rows) *1000+ (c // tile_cols)
Five algorithms cover the families the paper ensembled (it retained RF, GBM, MARS, MaxEnt, GLM and CTA):
Code
Algorithm
Notes
GLM
Logistic regression with quadratic terms
Smooth, unimodal responses
MAXENT
Logistic regression on linear, quadratic and spline (hinge-like) features with L1 penalty
The feature set and penalty of MaxEnt; MaxEnt is equivalent to this kind of penalised presence-background model (Renner and Warton 2013)
CTA
Classification tree, depth 4
Step-shaped responses
RF
Random forest
GBM
Gradient boosting
Stands in for MARS and GBM
Each is scored two ways, with AUC and the True Skill Statistic (TSS, at the threshold that maximises it):
Random 80/20 splits (10 repeats per background set; the paper used 20).
Spatial cross-validation: folds are 0.3° tiles, so a model is always tested on blocks far from the ones it learned from.
With only 22 presences, the difference between the two is part of the lesson.
Code
def make_models():return {"GLM": make_pipeline(StandardScaler(), PolynomialFeatures(2, include_bias=False), LogisticRegression(C=1.0, class_weight="balanced", max_iter=5000)),"MAXENT": make_pipeline(StandardScaler(), SplineTransformer(n_knots=5, degree=1), LogisticRegression(penalty="l1", solver="liblinear", C=0.5, class_weight="balanced", max_iter=5000)),"CTA": DecisionTreeClassifier(max_depth=4, min_samples_leaf=5, class_weight="balanced", random_state=1),"RF": RandomForestClassifier(n_estimators=200, min_samples_leaf=3, class_weight="balanced_subsample", n_jobs=-1, random_state=1),"GBM": HistGradientBoostingClassifier(max_depth=3, learning_rate=0.05, max_iter=200, class_weight="balanced", random_state=1), }def tss_max(y, p): fpr, tpr, _ = roc_curve(y, p)returnfloat(np.max(tpr - fpr))def assemble(bg): X = np.vstack([X_pres, Xgrid[bg]]) y = np.r_[np.ones(len(X_pres)), np.zeros(len(bg))] groups = tile_id(np.r_[pres_cells, bg])return X, y, groupst0 = time.time()rows = []oof_presence = {} # (background set, model) -> out-of-fold predictions at the 22 presencesfor s, bg inenumerate(pa_sets): X, y, groups = assemble(bg)# Random 80/20 splits (paper design).for rep, (tr, te) inenumerate(StratifiedShuffleSplit(n_splits=10, test_size=0.2, random_state=s).split(X, y)):for name, model in make_models().items(): p = model.fit(X[tr], y[tr]).predict_proba(X[te])[:, 1] rows.append(("random 80/20", s, name, roc_auc_score(y[te], p), tss_max(y[te], p)))# Spatial cross-validation on 0.3-degree tiles; predictions pooled across folds. n_groups =len(np.unique(groups[y ==1])) oof = {name: np.full(len(y), np.nan) for name in make_models()}for tr, te in GroupKFold(n_splits=min(5, n_groups)).split(X, y, groups):if y[tr].sum() <3or y[te].sum() ==0:continuefor name, model in make_models().items(): oof[name][te] = model.fit(X[tr], y[tr]).predict_proba(X[te])[:, 1]for name, p in oof.items(): oof_presence[(s, name)] = p[: len(X_pres)] ok = np.isfinite(p) rows.append(("spatial (0.3° tiles)", s, name, roc_auc_score(y[ok], p[ok]), tss_max(y[ok], p[ok])))evals = pd.DataFrame(rows, columns=["scheme", "pa_set", "model", "AUC", "TSS"])print(f"Evaluation runs: {len(evals)} in {time.time() - t0:.0f} s")perf = evals.groupby(["model", "scheme"])[["AUC", "TSS"]].mean().unstack("scheme")display(perf.round(3))
Evaluation runs: 440 in 231 s
AUC
TSS
scheme
random 80/20
spatial (0.3° tiles)
random 80/20
spatial (0.3° tiles)
model
CTA
0.657
0.633
0.342
0.270
GBM
0.743
0.751
0.582
0.482
GLM
0.664
0.722
0.515
0.433
MAXENT
0.744
0.739
0.616
0.445
RF
0.726
0.775
0.603
0.516
Code
fig, axes = plt.subplots(1, 2, figsize=(13, 4))for ax, metric inzip(axes, ["AUC", "TSS"]): data = [evals[(evals.model == m) & (evals.scheme == sch)][metric] for m in make_models()for sch in ["random 80/20", "spatial (0.3° tiles)"]] pos = [i *3+ j for i inrange(len(make_models())) for j in (0, 1)] bp = ax.boxplot(data, positions=pos, widths=0.8, patch_artist=True)for patch, j inzip(bp["boxes"], [0, 1] *len(make_models())): patch.set_facecolor(["#9ecae1", "#fdae6b"][j]) ax.set_xticks([i *3+0.5for i inrange(len(make_models()))], list(make_models())) ax.set_title(metric) ax.grid(axis="y", alpha=0.3)axes[0].legend([bp["boxes"][0], bp["boxes"][1]], ["random 80/20", "spatial tiles"], loc="lower left")plt.tight_layout()plt.show()# Stability across the eight background sets (paper: Table S7).display(evals[evals.scheme.str.startswith("spatial")].groupby("pa_set")[["AUC", "TSS"]].mean().T.round(3))
pa_set
0
1
2
3
4
5
6
7
AUC
0.731
0.758
0.700
0.722
0.746
0.702
0.712
0.722
TSS
0.442
0.483
0.378
0.409
0.475
0.398
0.419
0.428
Reading the evaluation. Two things stand out.
Random splits are mostly noise here. A 20 percent test set holds only about four presences, so a single split can give an AUC anywhere from 0.4 to 0.9. Mean AUC under random splits is about the same as, or lower than, under spatial tiles; only TSS comes out higher, because with four test presences one lucky threshold separates them easily. Spatial cross-validation pools out-of-fold predictions for all 22 presences, which gives a far more stable estimate.
The honest skill is moderate. Spatial AUCs of 0.72 to 0.78 for GLM, MaxEnt-style, RF and GBM, and 0.64 for the single tree, describe a model that ranks occupied blocks above the background clearly but far from perfectly.
The paper’s very high scores (mean ROC up to 0.999 for RF) come from random splits on 177 precise points. They measure something different and are not comparable with the scores here.
The ensemble below uses the spatial scores: an algorithm enters only if its mean spatial AUC is at least 0.70, and members are weighted by that AUC (the paper’s EMwmean rule, with a lower bar suited to an honest test on 22 blocks).
Code
spatial_auc = evals[evals.scheme.str.startswith("spatial")].groupby("model")["AUC"].mean()members_B = spatial_auc[spatial_auc >=0.70]if members_B.empty: # never leave the ensemble empty members_B = spatial_auc.nlargest(2)print("Ensemble members and AUC weights:")display(members_B.to_frame("weight (spatial AUC)"))# Fit every member on all presences with each background set, predict every 270 m cell, average.t0 = time.time()pred = {}fitted = {name: [] for name in members_B.index}for name in members_B.index: maps = []for bg in pa_sets: X, y, _ = assemble(bg) model = make_models()[name].fit(X, y) fitted[name].append(model) p = np.full(Xgrid.shape[0], np.nan) p[valid_idx] = model.predict_proba(Xgrid[valid_idx])[:, 1] maps.append(p) pred[name] = np.nanmean(maps, axis=0)w = members_B / members_B.sum()hsi_B270 =sum(w[name] * pred[name] for name in members_B.index).reshape(valid270.shape)hsi_B270 = np.where(valid270, hsi_B270, np.nan)print(f"Ensemble prediction in {time.time() - t0:.0f} s")def ensemble_predict(X):"""AUC-weighted mean over members, averaged over the eight background sets."""returnsum(w[n] * np.mean([m.predict_proba(X)[:, 1] for m in fitted[n]], axis=0) for n in members_B.index)
Importance is measured by permutation on the ensemble: shuffle one predictor, and record how much the AUC on the fitted data drops. Contributions are the drops rescaled to sum to 100, the same presentation as the paper.
Reading the importance and response curves. The response shapes agree in direction with the paper: suitability rises with mean slope and with the share of steep land, falls as warm-month temperature rises, rises with distance from settlements and falls with distance from rivers. Precipitation has an almost flat response.
The ranking differs. Distance to settlements carries about 45 percent of the importance and distance to roads about 18 percent, while slope and climate together carry less than a third. The paper found the reverse (slope 56 %, precipitation 19 %, temperature 13 %, every disturbance variable < 5 %). Three reasons are likely, and they are worth stating because each is a general lesson:
Survey design. The transects were laid out in and around the three reserves, which sit in the remote, road-poor centre of the area. At 10 km resolution “far from villages and roads” is what most distinguishes the surveyed blocks from the rest of the landscape, whether or not the deer select for it.
Unit of analysis. Inside a 10 km block, almost every block contains some steep land, so block-mean slope varies less than cell slope. The paper’s strong slope effect is partly a fine-scale effect that block summaries cannot see.
Correlated predictors share credit. Remote blocks are also the steep, forested, cooler ones; permutation importance assigns the shared signal to whichever variable the models used first.
This is why Model B is used only as landscape context and is combined with Model A, whose weights come from the paper’s fine-scale analysis.
Combining the two models
The two maps answer different questions. Model A asks whether a 90 m cell offers what the species needs. Model B asks whether the surrounding 10 km of landscape looks like the landscapes where the species was found. The combined suitability is their geometric mean,
\[
h = \sqrt{A \cdot B},
\]
which stays low when either model is low: one model cannot compensate for the other.
Code
B90 = np.repeat(np.repeat(hsi_B270, AGG, axis=0), AGG, axis=1) # back to 90 mB90 = np.pad(B90, ((0, valid.shape[0] - B90.shape[0]), (0, valid.shape[1] - B90.shape[1])), constant_values=np.nan)B90 = np.where(valid, B90, np.nan)hsi = np.sqrt(np.clip(hsi_A, 0, 1) * np.clip(B90, 0, 1))both = valid & np.isfinite(B90)r_AB = np.corrcoef(hsi_A[both], B90[both])[0, 1]print(f"Correlation between Model A and Model B across 90 m cells: r = {r_AB:.2f}")fig, axes = plt.subplots(1, 3, figsize=(20, 7))for ax, arr, title inzip(axes, [hsi_A, B90, hsi], ["Model A (local habitat)", "Model B (landscape context)","Combined suitability h = sqrt(A x B)"]): im = ax.imshow(arr, cmap="viridis", extent=EXTENT, vmin=0, vmax=1) ax.set_title(title) ax.set_xticks([]); ax.set_yticks([]) plt.colorbar(im, ax=ax, fraction=0.04)axes[2].scatter(sites.x, sites.y, c="red", s=20, edgecolor="white", zorder=5)plt.tight_layout()plt.show()
Correlation between Model A and Model B across 90 m cells: r = 0.68
Primary habitat patches
The paper defines primary habitat in two steps: a presence-based threshold on the suitability map, then a minimum patch size. The threshold step needs care here.
Why a presence threshold cannot be set at 90 m. The paper’s threshold (the lowest presence threshold at 90 percent, LPT90) is the suitability value exceeded at 90 percent of the occurrence points. With precise points that is well defined. Here each record is a 10 km block, so the 90 m value “at” a record does not exist.
What is done instead.
Landscape mask from Model B. LPT90 is applied to Model B, which works at block scale. The values used are out-of-fold predictions from the spatial cross-validation: what the ensemble predicts for each occurrence block when that block was left out. In-sample predictions would set the bar far too high, because the tree ensembles reproduce their 22 training blocks almost perfectly.
Equal-area selection on the combined map. Within that mask, the cells with the highest combined suitability \(h\) are kept until they cover 11.8 percent of the study area, the share the paper classed as primary habitat (863 of 7,293 km²). This is an explicit decision, not an estimate: it makes the configuration of habitat directly comparable with the published map, and the sensitivity table below shows what other shares would give.
Patch size. Connected cells (8-neighbour) forming at least 76 ha, the average home range used by the paper (Liu et al. 2020).
Code
# Out-of-fold ensemble value at each presence: what the ensemble predicts for a block it did not see.oof_ens =sum(w[n] * np.nanmean([oof_presence[(s, n)] for s inrange(len(pa_sets))], axis=0) for n in members_B.index)insample = hsi_B270.ravel()[pres_cells]print(f"Model B at the presences: in-sample median {np.median(insample):.2f}, out-of-fold median {np.nanmedian(oof_ens):.2f}")lpt90 =float(np.nanpercentile(oof_ens, 10))print(f"LPT90 on Model B (out-of-fold): {lpt90:.3f}; cells above it: {np.nanmean(B90[valid] >= lpt90):.0%} of the area")TOP_SHARE =863.0/7292.8# share of the study area classed as primary habitat by Zheng et al. (2026)MIN_PATCH_HA =76.0def primary_patches(top_share=TOP_SHARE, b_thr=lpt90, min_ha=MIN_PATCH_HA):"""Top `top_share` of h inside the Model B mask, then patches of at least `min_ha`.""" mask = valid & (B90 >= b_thr) h_thr = np.nanquantile(hsi[valid], 1- top_share) # equal-area cut on the whole study area suitable = mask & (hsi >= h_thr) lab, n = ndimage.label(suitable, structure=np.ones((3, 3))) sizes = np.bincount(lab.ravel())[1:] * CELL_HA keep_ids = np.flatnonzero(sizes >= min_ha) +1 order = keep_ids[np.argsort(-sizes[keep_ids -1])] relabel = np.zeros(lab.max() +1, dtype=int) relabel[order] = np.arange(1, len(order) +1) lab = relabel[lab] tab = pd.DataFrame({"patch": np.arange(1, len(order) +1), "area_km2": np.sort(sizes[keep_ids -1])[::-1] /100})return lab, tab, h_thrpatches, patch_tab, h_cut = primary_patches()print(f"Combined-suitability cut for the top {TOP_SHARE:.1%}: h >= {h_cut:.3f}")print(f"Primary habitat: {len(patch_tab)} patches, {patch_tab.area_km2.sum():,.1f} km2 "f"({patch_tab.area_km2.sum() / (valid.sum() * CELL_HA /100):.1%} of the study area)")patch_tab["share_%"] =100* patch_tab.area_km2 / patch_tab.area_km2.sum()patch_tab["mean_h"] = [np.nanmean(hsi[patches == p]) for p in patch_tab.patch]patch_tab["mean_slope_deg"] = [np.nanmean(slope[patches == p]) for p in patch_tab.patch]display(patch_tab.head(10))
Model B at the presences: in-sample median 0.78, out-of-fold median 0.22
LPT90 on Model B (out-of-fold): 0.135; cells above it: 40% of the area
Combined-suitability cut for the top 11.8%: h >= 0.534
Primary habitat: 6 patches, 857.1 km2 (11.8% of the study area)
sens = []for share in [0.08, TOP_SHARE, 0.16]:for label, b_thr in [("no mask", -np.inf), ("LPT80", float(np.nanpercentile(oof_ens, 20))), ("LPT90", lpt90)]: lab_s, tab_s, _ = primary_patches(share, b_thr) sens.append({"top share": f"{share:.1%}", "Model B mask": label, "patches": len(tab_s),"area_km2": round(tab_s.area_km2.sum()),"largest_km2": round(tab_s.area_km2.max()) iflen(tab_s) else0})sens = pd.DataFrame(sens)display(sens.pivot(index="top share", columns="Model B mask", values="patches").rename_axis(columns="patches"))display(sens.pivot(index="top share", columns="Model B mask", values="largest_km2").rename_axis(columns="largest patch (km2)"))
patches
LPT80
LPT90
no mask
top share
11.8%
6
6
6
16.0%
10
10
10
8.0%
10
10
10
largest patch (km2)
LPT80
LPT90
no mask
top share
11.8%
828
828
828
16.0%
1100
1100
1100
8.0%
492
492
492
Reading the sensitivity tables. The Model B mask removes nothing at these shares: every cell in the top 16 percent of combined suitability already lies inside the area where Model B exceeds LPT80, so Model B acts through the combined score, not through the mask. The selected share, in contrast, changes the configuration. At the paper’s 11.8 percent, one patch holds about 97 percent of primary habitat; at 8 percent it breaks into more, smaller patches; at 16 percent it grows further. The paper’s two largest patches (421 and 362 km²) are separated by its corridor L1. Here they are most likely merged into one patch, because block-scale context and the smooth slope layer do not resolve the narrow gap between them. Patch counts and the corridor network below should be read with that in mind.
Weight uncertainty in Model A
Only three of Model A’s seven weights come from the paper. monte_carlo_weights draws 500 weight vectors from a Dirichlet distribution centred on the baseline (concentration κ = 50) and reports, for every cell, the spread of the resulting HSI and the probability that the cell stays in the top 10 percent. It runs on the 270 m grid to keep memory modest.
Code
names_mc =list(WEIGHTS_A)M = np.stack([coarsen(np.where(valid, members[k], np.nan))[valid270] for k in names_mc])M = np.nan_to_num(M)t0 = time.time()mc = monte_carlo_weights(M, np.array([WEIGHTS_A[k] for k in names_mc]), kappa=50.0, n=500, batch=50, top_q=0.9, seed=7)print(f"Monte Carlo weights: {time.time() - t0:.0f} s; median Jaccard of top-10% sets vs baseline "f"{np.median(mc['jaccard']):.2f}")def to_grid270(vec): g = np.full(valid270.shape, np.nan) g[valid270] = vecreturn gfig, axes = plt.subplots(1, 2, figsize=(15, 7))im0 = axes[0].imshow(to_grid270(mc["sd"]), cmap="magma", extent=ext270)axes[0].set_title("SD of Model A HSI across weight draws")plt.colorbar(im0, ax=axes[0], fraction=0.04)im1 = axes[1].imshow(to_grid270(mc["p_top"]), cmap="YlGn", extent=ext270, vmin=0, vmax=1)axes[1].set_title("Probability of staying in the top 10 %")plt.colorbar(im1, ax=axes[1], fraction=0.04)for ax in axes: ax.set_xticks([]); ax.set_yticks([])plt.tight_layout()plt.show()
Monte Carlo weights: 3 s; median Jaccard of top-10% sets vs baseline 0.81
The spread is small compared with the range of the HSI, and the core steep blocks stay in the top 10 percent in nearly every draw. Cells near the edge of the top set are the ones whose status depends on the weight split; they are also where the patch boundaries above are least certain.
Resistance surface
Connectivity starts from a resistance surface: the cost for an animal to cross a cell. The paper converts suitability \(h\) into resistance with a negative exponential (Keeley et al. 2016):
\(R\) runs from 1 (best habitat) to 100 (worst). The parameter \(c\) sets the curvature. A habitat specialist may tolerate mediocre habitat while dispersing, so resistance should stay low over intermediate suitability and rise sharply only in poor habitat; the paper uses \(c = 8\) as baseline and tests 4 to 16.
The cost-weighted distance (CWD) from a patch to any cell is the minimum sum of resistance times distance along a path. Following Linkage Mapper (McRae and Kavanagh 2011), patches are linked when their cost-distance zones touch, that is, when no third patch lies between them in cost space. For each link the notebook reports:
the least-cost path (LCP) and its length;
the CWD between the patches and the Euclidean distance between their edges;
the ratio CWD : EucD. A ratio near 1 would mean an easy, straight route through good habitat; larger values mean detours or costly ground.
Cost distance is computed with Dijkstra’s algorithm (scipy.sparse.csgraph.dijkstra) on the 8-neighbour cell graph. The cost of moving between neighbouring cells is the mean of their resistances times the step length.
Code
NR, NC = valid270.shapenode_of =-np.ones(NR * NC, dtype=np.int64)node_of[valid_idx] = np.arange(valid_idx.size)STEPS = [(0, 1, 1.0), (1, 0, 1.0), (1, 1, np.sqrt(2)), (1, -1, np.sqrt(2))] # each undirected edge oncedef edges_for(R):"""Undirected 8-neighbour edges (i, j, step_length_m, mean_resistance).""" I, J, L, RM = [], [], [], [] rr, cc = np.divmod(valid_idx, NC)for dr, dc, s in STEPS: r2, c2 = rr + dr, cc + dc ok = (r2 >=0) & (r2 < NR) & (c2 >=0) & (c2 < NC) nb = np.full(rr.shape, -1) nb[ok] = node_of[r2[ok] * NC + c2[ok]] ok &= nb >=0 a, b = np.arange(valid_idx.size)[ok], nb[ok] I.append(a); J.append(b); L.append(np.full(a.size, s * CELL_B)) Rf = R.ravel()[valid_idx] RM.append(0.5* (Rf[a] + Rf[b]))return np.concatenate(I), np.concatenate(J), np.concatenate(L), np.concatenate(RM)def cost_graph(R): I, J, L, RM = edges_for(R) n = valid_idx.sizereturn sparse.coo_matrix((L * RM, (I, J)), shape=(n, n)).tocsr()patch_nodes = {p: node_of[np.flatnonzero(patch270.ravel() == p)] for p in np.unique(patch270) if p >0}patch_nodes = {p: v[v >=0] for p, v in patch_nodes.items() if (v >=0).any()}print(f"Patches on the 270 m grid: {len(patch_nodes)}")def corridors(R):"""Cost distances from each patch, adjacent links, least-cost paths and their statistics.""" G = cost_graph(R) cd, pred = {}, {}for p, nodes in patch_nodes.items(): d, pr, _ = csgraph.dijkstra(G, directed=False, indices=nodes, min_only=True, return_predecessors=True) cd[p], pred[p] = d, pr# Allocation: nearest patch in cost space for every node; links where allocation zones touch. ids = np.array(list(cd)) D = np.vstack([cd[p] for p in ids]) alloc = ids[np.argmin(D, axis=0)] I, J, _, _ = edges_for(R) pairs = {tuple(sorted(x)) for x inzip(alloc[I], alloc[J]) if x[0] != x[1]} xy = np.column_stack(dp.rowcol_to_xy(*np.divmod(valid_idx, NC), (ext270[0], CELL_B, 0, ext270[3], 0, -CELL_B))) links = []for a, b insorted(pairs): tot = cd[a] + cd[b] k =int(np.argmin(tot)) cwd =float(tot[k])# Trace the least-cost path from the best meeting node back into each patch.def trace(p): # nodes from the meeting node k back to patch p n, seg = k, []while n >=0: seg.append(n) n = pred[p][n]return seg path = np.array(trace(a)[::-1] + trace(b)[1:]) # patch a -> k -> patch b# Drop links whose least-cost path runs through a third patch (Linkage Mapper rule). others = patch270.ravel()[valid_idx[path]]if np.any((others >0) & (others != a) & (others != b)):continue steps = np.hypot(*np.diff(xy[path], axis=0).T).sum() iflen(path) >1else0.0# Edge-to-edge Euclidean distance between the two patches.from scipy.spatial import cKDTree tree = cKDTree(xy[patch_nodes[b]]) euc =float(tree.query(xy[patch_nodes[a]])[0].min()) links.append({"from": a, "to": b, "cwd": cwd, "lcp_length_m": steps, "euclid_m": max(euc, CELL_B),"path": path}) links = pd.DataFrame(links) links["cwd_to_euclid"] = links.cwd / links.euclid_mreturn links, cdt0 = time.time()links8, cd8 = corridors(R8)print(f"Corridors: {len(links8)} links in {time.time() - t0:.0f} s")display(links8.drop(columns="path").sort_values(["from", "to"]).head(12).round(1))print(f"LCP length: {links8.lcp_length_m.min():.0f} to {links8.lcp_length_m.max():,.0f} m "f"(mean {links8.lcp_length_m.mean():,.0f} m)")
Patches on the 270 m grid: 6
Corridors: 7 links in 0 s
from
to
cwd
lcp_length_m
euclid_m
cwd_to_euclid
0
1
2
3475.7
1415.5
1350.0
2.6
1
1
3
43334.2
10969.4
9164.1
4.7
2
1
4
21901.6
6761.2
6536.0
3.4
3
1
5
315959.9
54978.0
47253.1
6.7
4
1
6
290591.7
46542.5
43480.1
6.7
5
3
4
18432.5
7058.4
6524.8
2.8
6
5
6
24158.8
8547.4
8140.4
3.0
LCP length: 1416 to 54,978 m (mean 19,467 m)
With one dominant patch, most links run from that patch to small outlying patches. Two links to the far north-western patches are long (about 47 and 55 km of path). Linkage Mapper would normally drop such links with a maximum-distance setting; they are kept here to show that the north-western occurrence blocks are effectively isolated from the main habitat. The CWD : EucD ratios of the shorter links rank their quality: values near 2 to 3 mean the route follows reasonably good habitat, larger values mean costly detours.
Code
big3 = [1, 2, 3]key_links = links8[links8["from"].isin(big3) & links8["to"].isin(big3)].copy()if key_links.empty:print("The three largest patches are not directly linked; the paths below are the cheapest links that touch them.") key_links = links8[links8["from"].isin(big3) | links8["to"].isin(big3)].nsmallest(3, "cwd_to_euclid")display(key_links.drop(columns="path").round(2))
from
to
cwd
lcp_length_m
euclid_m
cwd_to_euclid
0
1
2
3475.75
1415.51
1350.0
2.57
1
1
3
43334.24
10969.40
9164.1
4.73
Pinch points with circuit theory
A least-cost path is one line. Circuit theory (McRae et al. 2008) treats the landscape as an electrical network in which each cell conducts in proportion to \(1/R\). Current injected in one patch and drained in another spreads over all routes in proportion to their ease, so it shows how many alternatives a corridor has. Where current is forced through a narrow strip, current density peaks: a pinch point, the place where losing a little habitat breaks the link.
For each link the notebook
restricts the network to the corridor, the cells where \(CWD_a + CWD_b \le CWD_{ab} + 10{,}000\) (the paper’s cutoff);
sets the voltage to 1 in one patch and 0 in the other, and solves Kirchhoff’s equations \(L\,v = 0\) for the remaining cells with a sparse solver;
scales the solution to 1 A and records the current through every cell.
Summing over links gives cumulative current density.
Code
CWD_CUTOFF =10_000.0def current_density(R, links, cd):"""Pairwise circuit current, summed over links, on the 270 m node set.""" I, J, L, RM = edges_for(R) g = (CELL_B / L) / RM # conductance: 1 / (mean resistance x relative step length) n = valid_idx.size total = np.zeros(n)for _, lk in links.iterrows(): a, b =int(lk["from"]), int(lk["to"]) inc = (cd[a] + cd[b]) <= lk.cwd + CWD_CUTOFF inc[patch_nodes[a]] = inc[patch_nodes[b]] =True sub = np.flatnonzero(inc) loc =-np.ones(n, dtype=np.int64) loc[sub] = np.arange(sub.size) e = inc[I] & inc[J] ii, jj, gg = loc[I[e]], loc[J[e]], g[e] m = sub.size Lap = sparse.coo_matrix((np.r_[-gg, -gg], (np.r_[ii, jj], np.r_[jj, ii])), shape=(m, m)).tocsr() Lap = Lap + sparse.diags(-np.asarray(Lap.sum(axis=1)).ravel()) fixed = np.zeros(m, dtype=bool) v = np.zeros(m) src, snk = loc[patch_nodes[a]], loc[patch_nodes[b]] fixed[src] = fixed[snk] =True v[src] =1.0 free =~fixedif free.sum() ==0:continue A = Lap[free][:, free].tocsc() rhs =-Lap[free][:, fixed] @ v[fixed] v[free] = spsolve(A, rhs) flow = gg * np.abs(v[ii] - v[jj]) # current on each edge node_cur = np.zeros(m) np.add.at(node_cur, ii, flow) np.add.at(node_cur, jj, flow) injected = (Lap[src] @ v).sum() # total current leaving the source patchif injected >0: total[sub] +=0.5* node_cur / injectedreturn totalt0 = time.time()cur8 = current_density(R8, links8, cd8)print(f"Circuit solves for {len(links8)} links in {time.time() - t0:.0f} s")cur_grid = np.full(NR * NC, np.nan)cur_grid[valid_idx] = cur8cur_grid = cur_grid.reshape(NR, NC)fig, axes = plt.subplots(1, 2, figsize=(18, 10))axes[0].imshow(R8, cmap="Greys", extent=ext270, alpha=0.5)axes[0].imshow(np.where(patch270 >0, patch270, np.nan), cmap="tab20", extent=ext270, interpolation="nearest", alpha=0.8)xy_nodes = np.column_stack(dp.rowcol_to_xy(*np.divmod(valid_idx, NC), (ext270[0], CELL_B, 0, ext270[3], 0, -CELL_B)))for _, lk in links8.iterrows(): is_key = lk["from"] in big3 and lk["to"] in big3 axes[0].plot(*xy_nodes[lk.path].T, color="red"if is_key else"black", lw=2.5if is_key else0.8)axes[0].set_title(f"Least-cost paths ({len(links8)} links; red: between the three largest patches)")show = np.where(cur_grid >0, cur_grid, np.nan)im = axes[1].imshow(np.log10(show), cmap="magma", extent=ext270, vmin=np.nanpercentile(np.log10(show), 40), vmax=np.nanpercentile(np.log10(show), 99.5))axes[1].imshow(np.where(roads270, 1.0, np.nan), cmap="cool", vmin=0, vmax=1, extent=ext270, interpolation="nearest", alpha=0.6)axes[1].contour(patch270 >0, levels=[0.5], colors="white", linewidths=0.6, extent=ext270, origin="upper")plt.colorbar(im, ax=axes[1], fraction=0.04, label="log10 cumulative current (A)")axes[1].set_title("Current density: pinch points (bright); roads (magenta)")for ax in axes: ax.set_xticks([]); ax.set_yticks([])plt.tight_layout()plt.show()
Circuit solves for 7 links in 0 s
Where pinch points meet roads
Pinch points are defined here as corridor cells outside patches in the top 5 percent of current. The cell below lists the road cells among them, the places where a crossing structure would do most for connectivity.
Pinch-point cells: 310 | on roads: 14 (5%)
Share of all corridor cells that are road cells: 2%
current_A
x
y
lon
lat
4
0.332
412020.41
3.982e+06
110.024
35.974
1
0.313
412290.41
3.982e+06
110.027
35.976
5
0.309
412290.41
3.982e+06
110.027
35.974
8
0.305
412020.41
3.981e+06
110.024
35.972
9
0.301
412290.41
3.981e+06
110.027
35.972
6
0.295
412560.41
3.982e+06
110.030
35.974
2
0.289
412560.41
3.982e+06
110.030
35.976
7
0.282
412830.41
3.982e+06
110.033
35.974
11
0.281
412020.41
3.981e+06
110.024
35.969
10
0.279
411750.41
3.981e+06
110.021
35.969
Road cells make up a larger share of pinch points than of corridor cells overall, by a factor of two to three. Roads therefore run disproportionately through the narrow parts of corridors, the pattern the paper reports for its corridor L1 and the south-western expressway. The table lists the road cells carrying the most current: the candidate sites for crossing structures.
The network topology hardly changes with \(c\): the same links appear (one extra at \(c = 16\)). Costs fall as \(c\) rises, because a larger \(c\) makes resistance drop faster with suitability, so intermediate habitat becomes cheap to cross; the CWD : EucD ratios between the largest patches fall accordingly. The pinch-point cells overlap only partly with the baseline (Jaccard about 0.3 to 0.4), so the exact bottleneck cells depend on \(c\) more than the paper reports, although they stay within the same corridors. When locating crossing structures, treat a pinch point as a stretch of corridor rather than an exact cell.
Protected-area gap analysis (optional external data)
The paper found that 66 percent of primary habitat lies inside the three reserves, leaving 34 percent unprotected. Reserve boundaries are not part of the data release. If a polygon file is placed at Data/03_spatial_analysis/capstone_spatial_analysis/musk_deer/protected_areas.gpkg (for example, exported from the World Database on Protected Areas), the cell below reports the protected share of each patch.
Code
PA_FILE = OUT /"protected_areas.gpkg"ifnot PA_FILE.exists():print(f"No protected-area file at {PA_FILE.relative_to(ROOT)}; gap analysis skipped.")else:from geolattice.raster import rasterize pa = gpd.read_file(PA_FILE).to_crs(CRS_UTM) tmp = OUT /"_pa.gpkg" pa.to_file(tmp, driver="GPKG") pa_ras = OUT /"protected_90m.tif" rasterize(tmp, pa_ras, template=GRID["Slope"], burn_value=1, dtype="uint8", nodata=0, overwrite=True) tmp.unlink() protected = dp.read_band(pa_ras)[0] ==1 gap = patch_tab[["patch", "area_km2"]].copy() gap["protected_pct"] = [100* np.mean(protected[patches == p]) for p in gap.patch] total =100* (protected & (patches >0)).sum() / (patches >0).sum()print(f"Primary habitat inside protected areas: {total:.1f} %") display(gap.head(10))
No protected-area file at Data/03_spatial_analysis/capstone_spatial_analysis/musk_deer/protected_areas.gpkg; gap analysis skipped.
Comparison with the published study, and limitations
Aspect
Zheng et al. (2026)
This notebook
Occurrence data
177 precise points
Same records, coarsened to 23 block centres (22 inside the area)
Model
Ensemble of 6 algorithms on 30 m cells
Model A (published requirements, 90 m) x Model B (5-algorithm ensemble on 0.1° block summaries)
Validation
Random 80/20 splits
Random and spatial cross-validation
Dominant drivers in the published model
Slope 56 %, precipitation 19 %, temperature 13 %
Used as Model A weights
Dominant drivers in the data-driven model
Slope, precipitation, temperature
Distance to settlements and roads (Model B, block scale); see Section 6.4
Primary habitat
19 patches, 863 km²; largest 421, 362, 21 km²
Area set to the paper’s share (857 km²); 6 patches, one of about 830 km²
Corridors
25, Linkage Mapper
7 cost-allocation links with least-cost paths
Pinch points
Circuitscape, CWD cutoff 10,000
Pairwise circuit solves, same cutoff
Limitations.
Coordinate generalisation. The public coordinates are deliberately imprecise. Model B can only learn what distinguishes 10 km landscapes, and its maps are smooth for that reason. Precise points would allow a cell-level model and would almost certainly sharpen and shift the patches.
Model A is only as good as its translation of the paper. Membership shapes were read from published response curves, and four of the seven weights were assigned here.
Presence-background design. Background points are not absences; the outputs are relative suitability, not probability of occurrence. Survey effort was concentrated in and around the reserves, which can bias both the occurrence blocks and the inferred preferences.
Sampling bias. Model B’s emphasis on distance from settlements most likely reflects where surveys were done. Target-group background sampling (background drawn from surveyed areas only) would reduce it, but the survey tracks are not part of the data release.
Static connectivity. Resistance from suitability assumes that animals disperse through the habitat they would live in, which telemetry or landscape genetics would need to confirm.
No reserve boundaries. The protected-area gap analysis needs an external boundary file.
Zheng, W., Luo, P., Li, Y., Hai, L., Jin, X., Qin, X., Yan, L., Hu, D. (2026). Assessing habitat suitability and landscape connectivity for the endangered forest musk deer (Moschus berezovskii) at its northern distribution margin: a multi-scale ensemble approach. Ecology and Evolution, 16, e74086. https://doi.org/10.1002/ece3.74086
Keeley, A. T. H., Beier, P., Gagnon, J. W. (2016). Estimating landscape resistance from habitat suitability: effects of data source and nonlinearities. Landscape Ecology, 31, 2151-2162.
McRae, B. H., Dickson, B. G., Keitt, T. H., Shah, V. B. (2008). Using circuit theory to model connectivity in ecology, evolution, and conservation. Ecology, 89, 2712-2724.
McRae, B. H., Kavanagh, D. M. (2011). Linkage Mapper connectivity analysis software. The Nature Conservancy.
Renner, I. W., Warton, D. I. (2013). Equivalence of MAXENT and Poisson point process models for species distribution modeling in ecology. Biometrics, 69, 274-281.
Pearson, R. G., Raxworthy, C. J., Nakamura, M., Peterson, A. T. (2007). Predicting species distributions from small numbers of occurrence records. Journal of Biogeography, 34, 102-117.
Allouche, O., Tsoar, A., Kadmon, R. (2006). Assessing the accuracy of species distribution models: prevalence, kappa and the true skill statistic (TSS). Journal of Applied Ecology, 43, 1223-1232.