Skip to content

Download the Jupyter notebook

Assignment 12: Spatial trait variation in California

BIO597 Spatial Analysis of Biodiversity

Repeat Lab12 for California. How do typical amphibian traits and local trait variation relate to latitude, climate, and habitat across this larger, environmentally varied state?

Follow the lab's five analyses: community mean traits, functional dispersion, a trait-shuffling null model, FDis–environment correlations, and a linked community trait PCA map/biplot. Use 30 km cells, pool frogs and salamanders, and give each recorded species equal weight. You may reuse and adapt code from the lab. Preparation helpers are supplied so you can concentrate on the ecology.

Submit this notebook with figures, tables, short answers, and a 400–600 word synthesis. Include your name and cite the supplied data sources.

Name:

Inputs and environment

Run from docs/assignments using the Lab12 environment. The three California files have the same layout and trait columns as the prepared Maine files:

Input Path from this notebook
Grid, climate, latitude, and habitat fractions ../data/Lab12/CA_30KM_grid.geojson
Occurrence counts by site and species ../data/Lab12/CA_Amphib_site_by_species.csv
Species with all five traits ../data/Lab12/CA_traits.csv
State boundary for map backgrounds ../data/CA_ShapeFiles/California_State_Boundary.shp

The inputs are already prepared from CA_amphibians.geojson, bioclim_CA, CAHabitatMap, and AmphiTraits_Final.csv. Do not repeat occurrence cleaning, name matching, gridding, or raster extraction. Read the California preprocessing notes, including the species missing traits and the habitat crosswalk.

Records with coordinate uncertainty below 100 m were retained, including repeated observations. The grid contains cells with more than two species. Counts are numbers of records, not animal abundances. The California projection is EPSG:3310, not Maine's UTM projection.

from pathlib import Path

import geopandas as gpd
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.decomposition import PCA

CRS = "EPSG:3310"
MIN_COVERAGE = 0.8
N_RANDOM = 1000
SEED = 12
DATA = Path("../data/Lab12")
OUTPUT = Path("outputs/Assignment12/SpatialTraitVariation")
OUTPUT.mkdir(parents=True, exist_ok=True)

1. Load the prepared communities and traits

Load the three tables as sites, community, and traits. Use site_id as the index for sites and communities, and species for traits, just as in the lab. Load the boundary as california and project it to CRS.

Report the number of cells, recorded species, and species with complete traits. Map recorded richness on the California background. Inspect n_records beside richness and identify species absent from the complete trait table. The preprocessing notes distinguish an unmatched name from a matched but incomplete trait row.

# Load CA_30KM_grid.geojson, CA_Amphib_site_by_species.csv, and CA_traits.csv.
# Set the site and species indexes, as in Lab12.
# Load california and project it to CRS.
# Display table sizes, missing-trait species, and a richness map.

Interpretation 1: Where are recorded communities richest? Which sampling gaps or differences in record totals might affect that pattern? Why must species without complete traits still contribute to richness? Distinguish a species absent from the trait table from a species absent from a cell.

Before looking at trait correlations, propose one directional hypothesis about a trait and latitude, climate, or habitat, with a biological explanation.

Your answer:

2. Put species in a shared trait space

Use all five supplied traits. Log-transform them, standardize the columns, and fit a two-component species PCA. Save trait_space, trait_pca, species_scores, and loadings, following the lab. Plot species in PCA space, label them, and display the loadings and variance explained.

Traits describe typical species values, not measurements of animals at each observation. Frogs and salamanders remain together throughout this assignment.

TRAIT_COLUMNS = list(traits.columns)
TRAIT_LABELS = {
    "MaxBody": "Maximum adult length (mm)",
    "MinAgeMat": "Minimum maturity age (years)",
    "MaxClutch": "Maximum clutch size",
    "MinSizeMat": "Minimum size at maturity (mm)",
    "MinClutch": "Minimum clutch size",
}
trait_lookup = traits
# Log10-transform and standardize traits, then create trait_space.
# Fit trait_pca and make species_scores and loadings.
# Plot the species and report the variance explained by PC1 and PC2.

Interpretation 2: What biological combinations distinguish the two axes? Choose two nearby species and two contrasting species, referring to their original trait values. Why log-transform and standardize? Why should functional dispersion use all five traits even when the figure displays two PCs?

Your answer:

3. Map typical community traits

Use the supplied helper from Lab12. Each species present receives one vote; repeated records do not increase its weight. The helper returns a geometric mean and the proportion of recorded species with trait information. Means below 80% coverage remain missing.

Build trait_maps for all five traits. Map maximum body length, maturity age, and maximum clutch size, using california as the background. Inspect coverage as well as the trait means; do not fill missing means with zero.

def summarize_trait(sites, community, column):
    result = sites.copy()
    means = []
    coverages = []
    for site_id, row in community.iterrows():
        # Get only the species that occur in this community
        names = row[row > 0].index
        # reindex the trait lookup table to only have those species present
        species_traits = trait_lookup.reindex(names)
        values = species_traits[column]
        values = values.dropna()
        # calculate the fraction of species that have trait info
        coverage = len(values) / len(names)
        coverages.append(coverage)
        if coverage >= MIN_COVERAGE:
            log_values = np.log10(values)
            means.append(10 ** log_values.mean())
        else:
            means.append(np.nan)
    result["trait_mean"] = means
    result["trait_coverage"] = coverages
    return result
# Build trait_maps by calling summarize_trait for each trait.
# Map MaxBody, MinAgeMat, and MaxClutch with appropriate labels.
# Examine how many cells retain valid trait means and where coverage is low.

Interpretation 3: Where do typical community traits differ? Could missing traits or differences in sampling help explain those patterns? Describe what "typical maximum body length" means without treating it as mean animal size. Which areas are excluded by the coverage requirement?

Your answer:

Compare typical traits with the predictors

The prepared grid includes midpoint latitude, all 19 BIO variables, and habitat area fractions. These are cell means and area fractions, rather than SDs or the habitat proportions of occurrence records. Habitat fractions sum to one over classified pixels in the California portion of each cell, including mapped water.

California's original map legend differs from Maine's. The first six broad groups are analogous to the lab; habitat_introduced and habitat_disturbed retain two additional mapped categories. "Other natural" includes shrubland, grassland, desert, alpine and rock vegetation. Exact habitat comparisons between states require care because the source maps differ.

Calculate descriptive Spearman correlations between typical maximum length and every predictor. Make six example scatterplots using PLOT_PREDICTORS. You may substitute other predictors if you explain the choice.

CLIMATE_COLUMNS = {
    "bio_1": "Annual mean temperature (°C)",
    "bio_2": "Mean diurnal temperature range (°C)",
    "bio_3": "Isothermality (%)",
    "bio_4": "Temperature seasonality (SD × 100)",
    "bio_5": "Maximum temperature, warmest month (°C)",
    "bio_6": "Minimum temperature, coldest month (°C)",
    "bio_7": "Annual temperature range (°C)",
    "bio_8": "Mean temperature, wettest quarter (°C)",
    "bio_9": "Mean temperature, driest quarter (°C)",
    "bio_10": "Mean temperature, warmest quarter (°C)",
    "bio_11": "Mean temperature, coldest quarter (°C)",
    "bio_12": "Annual precipitation (mm)",
    "bio_13": "Precipitation, wettest month (mm)",
    "bio_14": "Precipitation, driest month (mm)",
    "bio_15": "Precipitation seasonality (CV)",
    "bio_16": "Precipitation, wettest quarter (mm)",
    "bio_17": "Precipitation, driest quarter (mm)",
    "bio_18": "Precipitation, warmest quarter (mm)",
    "bio_19": "Precipitation, coldest quarter (mm)",
}

HABITAT_COLUMNS = {
    "habitat_agriculture": "Agriculture fraction",
    "habitat_developed": "Developed fraction",
    "habitat_open_water": "Open water fraction",
    "habitat_other_natural": "Other natural habitat fraction",
    "habitat_upland_forest": "Upland forest fraction",
    "habitat_wetland": "Wetland/aquatic vegetation fraction",
    "habitat_introduced": "Introduced vegetation fraction",
    "habitat_disturbed": "Recently disturbed fraction",
}
PREDICTORS = {"latitude": "Midpoint latitude (°N)"}
PREDICTORS.update(CLIMATE_COLUMNS)
PREDICTORS.update(HABITAT_COLUMNS)


PLOT_PREDICTORS = ["latitude", "bio_1", "bio_6", "bio_10",
                   "habitat_upland_forest", "habitat_developed"]
# Compare trait_maps["MaxBody"] with all predictors using Spearman correlation.
# Plot six example relationships with labels from PREDICTORS.

Interpretation 4: Does the pattern support your initial hypothesis? Compare a geographic, a climatic, and a habitat relationship. Why would a strong correlation alone fail to identify an independent cause? Explain how habitat fractions constrain one another.

Your answer:

4. Richness versus functional dispersion

The community matrix includes species without complete traits. Do not use trait_space.loc[names] on the full species list. The supplied code below selects species with complete traits and cells with at least three of those species and at least 80% coverage. Use functional_sites and functional_presence for all FDis calculations and the null model.

Use the lab's dispersion function to calculate FDis for each retained cell, using all five standardized log traits. Map trait_richness and FDis, then plot their relationship. Also inspect how trait richness differs from total recorded richness. The cell mean trait maps and FDis summarize different properties.

# Select complete-trait species and keep matching grid cells.
known_presence = community[trait_space.index] > 0
functional_sites = sites.copy()
functional_sites["trait_richness"] = known_presence.sum(axis=1)
functional_sites["trait_coverage"] = functional_sites["trait_richness"] / sites["richness"]
functional_sites = functional_sites[functional_sites["trait_coverage"] >= MIN_COVERAGE]
functional_sites = functional_sites[functional_sites["trait_richness"] >= 3].copy()
functional_presence = known_presence.loc[functional_sites.index]
print("Cells retained for functional analyses:", len(functional_sites))


def dispersion(values):
    centroid = values.mean(axis=0)
    squared_differences = (values - centroid) ** 2
    distances = np.sqrt(squared_differences.sum(axis=1))
    return distances.mean()
# For each row of functional_presence, select the species present.
# Look up their standardized traits and calculate dispersion.
# Store the results in functional_sites["functional_dispersion"].
# Map trait_richness and functional_dispersion, and plot their relationship.

Hold richness fixed

Among retained cells with four trait-covered species, select the lowest and highest FDis. Draw their species on the species PCA with the regional species pool in gray and the local centroid marked. Print both species lists and FDis values. Use trait_richness, not total richness, to hold the number of analyzed species fixed.

# Find low and high FDis cells with trait_richness == 4.
# Plot each local species set and centroid on the species PCA.
# Print the cell IDs, species lists, and FDis values.

Interpretation 5: Which species and traits create the contrast? Can two equally rich communities have different functional diversity? Explain why a PCA picture can miss differences measured by the full five-dimensional FDis. Would your conclusions change if the excluded species had very unusual traits?

Your answer:

5. Compare dispersion with a null model

Use 1,000 shuffles and seed 12, matching the current lab. Each shuffle reassigns whole five-trait profiles among the complete-trait California species while keeping each cell's species list fixed. The helper is provided below.

Call it with functional_presence, not raw record counts or a different set of cells. Save the result as null_draws. Copy functional_sites to null_sites, calculate the null mean and sample SD for each cell, and calculate:

ses_fdis = (observed FDis - null mean) / null SD

Leave SES missing when the null SD is zero or nearly zero, as in the lab. Map SES with a common scale of −3 to +3. Plot a null histogram for one cell and mark its observed FDis. These effect sizes are not, by themselves, p-values.

def null_dispersion(presence, trait_space, n_random):
    # Match the species order, then turn occurrence counts into presence/absence.
    presence = presence[trait_space.index]
    presence = presence > 0
    values = trait_space.to_numpy()
    rng = np.random.default_rng(SEED)

    # Store one dispersion value per randomization and grid cell.
    simulated = np.zeros((n_random, len(presence)))
    for draw in range(n_random):
        # Reassign whole trait profiles among species; keep all five traits together.
        shuffled = rng.permutation(values)
        for site_number, present in enumerate(presence.to_numpy()):
            # Keep the cell's species list fixed and calculate its shuffled dispersion.
            simulated[draw, site_number] = dispersion(shuffled[present])
    return simulated
# Generate null_draws from functional_presence, trait_space, and N_RANDOM.
# Calculate null_mean, null_sd, and ses_fdis in null_sites.
# Map SES and compare one observed cell with its null histogram.

Interpretation 6: Which communities are more clustered or spread out than expected from this regional pool? What does the null model keep fixed? Why shuffle all traits together? Explain why clustering does not establish environmental filtering and why the choice of species pool matters.

Your answer:

6. Evaluate correlations between FDis and environmental predictors

Repeat Step 4 of Lab12 using the California communities. Calculate Pearson correlations between observed functional_dispersion and every predictor. Use null_sites, which already contains the observed FDis and predictors for the retained cells. Omit missing values for each comparison.

Display the correlations and make the same six scatterplots as the lab using PLOT_PREDICTORS: latitude, annual mean temperature, minimum temperature of the coldest month, mean temperature of the warmest quarter, upland forest fraction, and developed fraction. Label the vertical axis Functional dispersion.

These plots describe how much traits vary within communities. Use observed FDis here; the SES map in Section 5 asks whether that spread differs from the regional null expectation. The correlations are descriptive, and nearby cells share species and environmental conditions.

# Calculate Pearson correlations between functional_dispersion and all PREDICTORS.
# Drop missing values for each comparison and display the correlations.
# Make six FDis scatterplots using PLOT_PREDICTORS, as in Lab12 Step 4.

Interpretation 7: Which predictors have the strongest associations with trait dispersion? Do these resemble the relationships with typical maximum length? Distinguish a community's mean traits, its observed trait spread, and its departure from the regional null expectation. Propose one biological explanation for the strongest pattern and one alternative involving sampling or species availability.

Your answer:

7. Put community trait combinations on the map

Repeat the lab's final synthesis using the retained functional cells:

  1. Assemble their five geometric mean traits from trait_maps, take log10, standardize, and fit a new community PCA. One row is now a grid cell.
  2. Rank every predictor by its average squared Pearson correlation with the five log community mean traits. Select the leading climate variable and leading habitat fraction. This ranking is descriptive, not a significance test.
  3. Color cells using their first two PC scores, as in the lab. Use identical colors for each cell on the California map and in the PCA scatterplot.
  4. Add arrows for latitude, the leading climate variable, and the leading habitat fraction, using their correlations with the displayed PC axes.

Keep names such as community_traits, community_pca, community_scores, community_loadings, predictor_ranking, and map_sites from the lab. Use sites for the gray background and only the retained cells for the colored map. Report the variance explained and show the trait loadings and predictor ranking.

# Build community_traits for functional_sites.index from the five trait_maps.
# Log10-transform, standardize, and calculate community_scores and loadings.
# Rank PREDICTORS using all five log community mean traits.
# Select latitude, the leading climate variable, and the leading habitat fraction.
# Assign PCA-based colors, following Lab12.
# Make the linked California grid map and community PCA scatterplot.
# Add the three predictor arrows and a readable legend.
# Save the synthesis figure in OUTPUT.

Interpretation 8: What trait combinations occur in different parts of California? How do the predictor arrows help interpret them? How much variation is represented by the two axes? Compare this map with richness and FDis.

Contrast one California finding with Maine. The PCAs and color scales are fitted separately, so matching colors between states do not imply matching traits. Discuss the loadings and biological trait values rather than comparing colors or PC signs directly. Habitat classifications also differ between states.

Your answer:

8. Save results and synthesize

Save the following in OUTPUT: the retained site summaries including coverage, FDis and SES; the species and community PCA scores and loadings; the predictor ranking; the observed-FDis Pearson correlation table; and the synthesis figure. Use CSVs and a GeoPackage with descriptive names.

Write a 400–600 word synthesis addressing the main question. Use numerical examples and at least three figures to explain:

  • Geographic, climate, and habitat patterns in typical traits and trait spread.
  • How richness, observed FDis, and null-model SES answer different questions.
  • Which environmental predictors are associated with observed trait dispersion.
  • What the community PCA map adds and what the displayed two axes omit.
  • How your initial hypothesis compares with the exploratory results.
  • How missing traits, sampling, shared species, habitat fractions, and the California regional pool limit the conclusions.

Do not describe observation counts as abundance or correlations as causal effects. Propose one additional biological dataset or survey that would test your explanation.

Your synthesis:

# Save your site summaries, PCA tables, predictor ranking, FDis correlations,
# and synthesis figure.

Sources