Assignment 11: Spatial community composition — blobs or stripes?
This is an imaginary exercise.
Maine can protect 1,000 km² as two compact blob parks or two long, narrow stripe parks. Each park covers 500 km². Which design would you recommend for conserving amphibian diversity?
Follow the analyses in Lab10, now comparing park shapes. You may reuse its code and functions. Complete the code cells and short answers. Submit this notebook with its maps, tables, and saved summary CSVs.
The data
ME_BlobStripeParks.geojson contains two
roughly round blobs and two elliptical stripes, five times as long as they
are wide. All four are imaginary, nonoverlapping, and within Maine and the
source sample bounds. Each point already has a park assignment.
Sampling follows Lab10. All real records inside these parks are retained.
All source records in amphibians.geojson determine each observed species'
convex hull, its 50 km buffer, and its record-count weight. Each of 50 invented
species inherits the buffered range and abundance weight of a randomly
sampled observed species. Added points are sampled within those ranges'
intersections with the parks, with counts proportional to the observed or
inherited weights. One point per invented species is reserved. There are
1,500 total points, including originals; seed = 597.
synthetic identifies generated points; imaginary_species identifies invented
taxa.
1. Import packages and load the data
Run from docs/assignments using the same environment as Lab10.
from pathlib import Path
import geopandas as gpd
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import entropy
from scipy.spatial.distance import jaccard, braycurtis
AREA_CRS = "EPSG:5070"
COLORS = {"blob": "forestgreen", "stripe": "darkorange"}
designs = ["blob", "stripe"]
features = gpd.read_file("../data/ME_BlobStripeParks.geojson")
parks = features[features.feature_type == "park"].copy()
parks = parks.to_crs(AREA_CRS).set_index("park_id")
records = features[features.feature_type == "occurrence"].copy().to_crs(AREA_CRS)
park_order = list(parks.index)
display(parks[["park_name", "scenario", "area_km2"]])
print("Total occurrence records:", len(records))
2. Map the parks and check the comparison
Map the four polygons and their points, using one color per design. Label the park IDs. A simple map is enough.
Calculate area in km² and show the total area and number of occurrence records for each design. Keep all records, including generated points and invented species, in the analyses below.
parks["measured_km2"] = parks.area / 1e6
display(parks.groupby("scenario").measured_km2.sum())
# Count records in each design with records.groupby("scenario").size().
# Plot the parks and occurrence points; label B1, B2, S1, and S2.
Interpretation: What is held equal between the designs? What differs besides shape? Predict which design will capture more species, and explain why.
Your answer:
3. Build the community matrix
Rows are parks; columns are species; entries are record counts. A zero means no records of that species in that park. It does not establish true absence.
community = pd.crosstab(records.park_id, records.species)
community = community.reindex(park_order, fill_value=0)
presence = community > 0
display(community)
How many species occur in the whole dataset? Choose one species and describe
its distribution among the four parks using its column in community.
Your answer:
4. Richness, Shannon diversity, and evenness
Use the lab's function below. Shannon uses scipy.stats.entropy; larger values
reflect more species, greater evenness, or both.
def diversity(community_counts):
results = pd.DataFrame(
index=community_counts.index,
columns=["n_records", "richness", "shannon"],
dtype=float,
)
for unit, counts in community_counts.iterrows():
species_present = counts[counts > 0]
results.loc[unit, "n_records"] = counts.sum()
if len(species_present) == 0:
continue
results.loc[unit, "richness"] = len(species_present)
results.loc[unit, "shannon"] = entropy(species_present)
return results
# Calculate park_metrics = diversity(community).
# Add park names and scenarios from parks.
# Add evenness = np.exp(shannon) / richness, as in Lab10.
# Display the table and make a simple richness or Shannon plot.
Does the richest park also have the highest Shannon diversity and evenness? What would adding 100 records of an already common species do to these measures?
Your answer:
5. Alpha, beta, and gamma diversity
Pool the two blob parks, then the two stripe parks. For each design, calculate:
- Alpha: mean richness of its two parks.
- Gamma: richness in the pooled species list.
- Multiplicative beta: gamma divided by alpha.
- Total records and pooled Shannon diversity.
Keep the park rows in community; use design_counts for the pooled rows.
design_counts = pd.DataFrame(index=designs, columns=community.columns, dtype=float)
for design in designs:
park_ids = parks[parks.scenario == design].index
design_counts.loc[design] = community.loc[park_ids].sum()
# Use diversity(design_counts) to start design_metrics.
# Rename its richness column to gamma_richness.
# For each design, find its two rows in park_metrics.
# Calculate mean_park_alpha and beta_ratio, then display design_metrics.
Which design has higher gamma diversity? Does alpha or complementarity between its two parks help explain the result? Why is pooled richness generally smaller than the sum of the two park richnesses?
List species recorded only in blobs and species recorded only in stripes.
Hint: make a set from the species with positive counts in each pooled row;
subtract one set from the other.
Your answer:
# Make blob_species and stripe_species from design_counts.
# Print species unique to each design.
Jaccard dissimilarity
Jaccard compares presence/absence: 0 means identical species lists; 1 means no
shared species. Use scipy.spatial.distance.jaccard on rows of presence.
print("B1 versus B2:", jaccard(presence.loc["B1"], presence.loc["B2"]))
# Build jaccard_distances, a four-by-four table, as in Lab10.
# Use nested loops over park_order and jaccard(presence.loc[a], presence.loc[b]).
# Display the table.
Compare B1–B2 with S1–S2. Which design's two parks have more different species lists? Does that agree with the beta ratios? Explain why Jaccard alone cannot distinguish species replacement from differences in richness.
Your answer:
Bray–Curtis dissimilarity
Use scipy.spatial.distance.braycurtis on record counts. Make a second
four-by-four table, bray_curtis_distances.
Then repeat the B1–B2 and S1–S2 comparisons using relative frequencies:
divide each park's species counts by its total records before calling
braycurtis.
print("B1 versus B2:", braycurtis(community.loc["B1"], community.loc["B2"]))
# Build and display bray_curtis_distances using the Jaccard loop pattern.
# For each within-design pair, divide each row by its sum and compare again.
Do Jaccard and Bray–Curtis tell the same story? What information does Bray–Curtis add? Why can unequal record totals affect its values, and what changes when you use relative frequencies?
Your answer:
6. Compare equal numbers of records
Use record-based rarefaction to check whether the pooled richness comparison persists when both designs contribute the same number of records. Draw without replacement and repeat 300 times, following the lab's loop.
For each design, report mean richness and the 2.5th and 97.5th percentiles of the draws. These percentiles describe resampling variation, not confidence intervals for true richness. Equal record counts do not establish equal survey effort or detectability.
equal_n = records.groupby("scenario").size().min()
rarefaction = pd.DataFrame()
# For each design, select its records and start an empty richness_samples list.
# Repeat 300 times:
# sample = design_records.sample(n=equal_n, replace=False, random_state=repeat)
# Append sample.species.nunique() to richness_samples.
# Store records_drawn, mean_richness, q025, and q975 in rarefaction.
# Use np.mean and np.quantile, then display the table.
Does equalizing record numbers change your preference? Which original sampling biases and simulation assumptions remain?
Your answer:
7. Rarity and restriction within the sample
Build species_context with each species' total records and number of occupied
parks. Define record-rare as at most five records across all four parks.
Use the same four parks as the reference throughout this section.
species_context = pd.DataFrame()
for species in community.columns:
counts = community[species]
species_context.loc[species, "n_records"] = counts.sum()
species_context.loc[species, "parks_recorded"] = sum(counts > 0)
rare_rows = species_context[species_context.n_records <= 5]
rare_species = list(rare_rows.index)
display(species_context)
Reuse restriction_metrics from Lab10 to calculate each park's:
- Sample-exclusive richness: species recorded in only one of the four parks.
- Weighted endemism proxy (WE): sum of
1 / parks_recordedfor species present. - Corrected WE (CWE): WE divided by park richness.
- Record-rare richness: number of record-rare species present.
Compare the two designs' pooled record-rare richness as well: count each rare species once per design, even if both parks record it.
# Copy the restriction_metrics function from Lab10.
# Calculate park_restriction = restriction_metrics(community).
# Display park_metrics.join(park_restriction).
# For each design, loop through rare_species.
# Count a species once if design_counts.loc[design, species] > 0.
Does a park with high WE also have high CWE? Which design captures more record-rare species? Are any sample-exclusive species relatively well recorded? Explain why these results do not establish that a species is endemic to a park or has a small population. How might invented species with few generated records affect these metrics?
Your answer:
8. Save results and make a recommendation
Save park_metrics.join(park_restriction), design_metrics, species_context,
jaccard_distances, bray_curtis_distances, and rarefaction as CSVs.
output_dir = Path("outputs/Assignment11")
output_dir.mkdir(parents=True, exist_ok=True)
# Save each table with .to_csv(output_dir / "table_name.csv").
Conservation recommendation (400–600 words)
Recommend blobs, stripes, or explain why the evidence does not favor one. Support your conclusion with your map and numerical results. Address:
- Alpha, gamma, beta, and the species contributed by each design.
- Shannon diversity, evenness, Jaccard, and Bray–Curtis: which comparisons influence your decision, and why?
- Whether rarefaction changes the result, and what rarity and restriction add.
- Why these four locations cannot isolate a causal effect of shape. The sampler includes geographic ranges and reporting patterns, but no explicit edge effects, dispersal, or population persistence. What additional biological evidence or repeated park placements would help test your explanation?
Your recommendation: