Assignment 06: A First-Principles Species Distribution Model
BIO597 Spatial Analysis of Biodiversity
This assignment asks you to build and interpret a simple one-variable species distribution model without using an SDM package. You will choose one amphibian species, describe the environmental values at its occurrence records, compare those values with background environments, create a suitability curve, and project that curve across Maine.
Deliverable
Submit a completed notebook with code, maps, plots, and short written interpretations. Your goal is to show that you understand the moving parts of an SDM before we use more automated modeling tools.
Learning goals
By the end of this assignment, you should be able to:
- describe the difference between occurrence, background, and absence data
- extract one raster predictor at species occurrence records
- compare used environments with available environments
- create a simple environmental suitability score
- project a suitability score across raster space
- explain why a conceptual SDM is not the same as a validated prediction model
Data
Use:
Amphibians_ME/Amphibians_ME.csvfor occurrence records/home/jovyan/shared-readwrite/bioclim/for one environmental variable of your choice that is NOT mean annual temperature../labs/ME_ShapeFiles/Maine_State_Boundary.shpfor the Maine boundary
You may use the same species as the lab or choose a different species with at least 100 usable records.
1. Import packages
Import pandas, geopandas, rioxarray, xarray, numpy, matplotlib.pyplot, and Path.
# Import packages here.
2. Load and combine the Maine boundary
Read the Maine state boundary shapefile, inspect its CRS and shape, and dissolve it to one row.
boundary_path = "../labs/ME_ShapeFiles/Maine_State_Boundary.shp"
# Read the boundary.
# Print its shape and CRS.
# Dissolve it to one row.
3. Open and clip environmental data
Select one environmental variable of your choosing that is NOT mean annual temperature. You can choose one you think will work well or one you think is less important for the study organism. Open the variable .tif file with masked=True, clip it to Maine, and remove the band dimension with squeeze().
bioclim_path = Path("/home/jovyan/shared-readwrite/bioclim")
bio1_path = bioclim_path / ___________________
# Open bio1 with rxr.open_rasterio().
# Clip it to the dissolved Maine boundary.
# Squeeze out the band dimension.
# Convert to degrees Celsius if needed.
4. Map your environmental variable
Create a map of the clipped temperature raster. Include a title.
# Plot annual mean temperature for Maine.
5. Load and prepare amphibian occurrence records
Read the tab-delimited amphibian file. Keep gbifID, species, longitude, latitude, coordinate uncertainty, and year. Convert coordinates to numeric values and remove records missing species or coordinates.
amphibians = pd.read_csv(
"Amphibians_ME/Amphibians_ME.csv",
sep=__________,
low_memory=False,
)
columns_to_keep = [
"gbifID",
"species",
"decimalLongitude",
"decimalLatitude",
"coordinateUncertaintyInMeters",
"year",
]
# Keep only columns_to_keep.
# Convert longitude and latitude to numeric values.
# Drop records missing species, longitude, or latitude.
6. Choose one species
Display the most common species, then choose one species with at least 100 records. Store its scientific name as target_species.
# Display species counts.
target_species = "____________________________"
# Filter the occurrence table to your target species.
# Display the number of records and the first five rows.
Why did you choose this species? Include one sentence about record count and one sentence about why it may or may not be appropriate for this simple model.
7. Create an occurrence GeoDataFrame
Use longitude and latitude to create point geometry. Assign EPSG:4326. Confirm that the occurrence CRS and raster CRS are compatible.
# Create presence_gdf.
# Print the occurrence CRS and raster CRS.
CRS check: Explain why coordinate systems matter before extracting raster values at points.
8. Extract environment at occurrence points
Create xarray.DataArray objects for point longitude and latitude. Use .sel(..., method="nearest") to extract BIO1 values at occurrence records. Add the extracted values to a column named bio1_c.
# Create point_x and point_y.
# Extract temperature values.
# Add them to presence_gdf as bio1_c.
# Drop records with missing bio1_c.
# Rebuild point_x and point_y after dropping missing values.
9. Summarize occurrence environment
Calculate the count, mean, standard deviation, minimum, and maximum of bio1_c at occurrence records.
# Summarize occurrence temperature values.
Interpretation: In two or three sentences, describe the environmental range represented by your species records.
10. Sample background environment
Create a random sample of up to 5,000 valid cells from Maine for your environmental variable. Use a random seed so your results are reproducible.
rng = np.random.default_rng(597)
# Create an array of valid raster environmental values.
# Randomly sample up to 5000 cells without replacement.
# Print the background sample size, mean, and standard deviation.
11. Compare occurrence and background environments
Make overlapping histograms of occurrence environment and background environment. Use density-scaled histograms so the shapes can be compared even though the sample sizes differ.
# Create an overlapping histogram of background and occurrence temperatures.
Interpretation: Does your species appear to use a narrow or broad subset of available environmental space? Explain using your plot.
12. Define a suitability function
Write a function that takes observed, optimum, and tolerance and returns:
np.exp(-0.5 * ((observed - optimum) / tolerance) ** 2)
This creates a score near 1 when observed environment is close to the optimum and closer to 0 as temperature gets farther away.
def environmental_suitability(observed, optimum, tolerance):
# Replace this comment with the suitability calculation.
return __________
13. Plot your suitability curve
Use the mean occurrence environmental value as the optimum and the standard deviation of occurrence as the tolerance. Plot suitability across the full range of Maine BIO1 values.
# Calculate presence_mean and presence_sd.
# Create a sequence of environmental values across the raster range.
# Calculate suitability for those values.
# Plot the curve.
Interpretation: What value receives the highest suitability score? What does the tolerance control?
14. Project suitability across Maine
Apply your suitability function to every cell in the environmental raster. Keep missing raster cells missing.
# Use xr.apply_ufunc() to apply environmental_suitability to the raster.
# Store the result as suitability.
# Mask cells where the environmental raster is missing.
15. Map suitability
Create a continuous suitability map with values from 0 to 1.
# Plot the suitability raster.
16. Overlay occurrence points
Plot your suitability raster and overlay the occurrence points. This is a visual check, not a formal validation.
# Plot suitability and overlay presence_gdf points.
Visual check: Do occurrence points generally fall in areas with higher predicted suitability? Describe any mismatch you see.
17. Compare occurrence and background suitability scores
Extract suitability at occurrence records. Also calculate suitability for your background environmental values. Compare the two distributions with histograms.
# Extract suitability at occurrence points.
# Calculate suitability for background environmental values.
# Print mean occurrence suitability and mean background suitability.
# Plot overlapping histograms.
Interpretation: Did your model score occurrence records higher than background locations? What would it mean if it did not?
18. Change the tolerance
Create two additional suitability rasters: one with half the observed standard deviation and one with twice the observed standard deviation. Map all three side by side.
# Create narrow_suitability using presence_sd / 2.
# Create broad_suitability using presence_sd * 2.
# Plot narrow, original, and broad suitability maps side by side.
Interpretation: How does tolerance affect the predicted distribution? Which tolerance seems most defensible for your species, and why?
19. Threshold the continuous map
Convert your continuous suitability map to a binary suitable/unsuitable map using a threshold of your choice. Report the fraction of Maine climate cells labeled suitable.
threshold = __________
# Create a binary suitability map.
# Plot it.
# Calculate the fraction of non-missing cells labeled suitable.
Threshold justification: Why did you choose this threshold? How would the map change with a lower or higher threshold?
20. Save your outputs
Save your continuous suitability raster as Assignment06_suitability.tif. Save a CSV containing your occurrence records and extracted BIO1 values as Assignment06_presence.csv.
# Save the suitability raster.
# Save the occurrence table with extracted temperature values.
Final reflection
Answer each question in two or three sentences.
- In this exercise, what information came from occurrence records and what information came from the environmental raster?
- Why did we compare occurrence environment with background environment?
- Why is this suitability score not the same as probability of presence?
- Name two ecological or sampling processes ignored by this one-variable model.
- What would a full SDM package add beyond this first-principles workflow?
Submit your work
Run the notebook from top to bottom. Make sure all maps, plots, saved files, and written answers are complete. Then commit and push the completed notebook to your class GitHub repository.
git add docs/assignments/Assignment-06-FirstPrinciplesSDM.ipynb
git commit -m "Complete first principles SDM assignment"
git push