How to calculate biodiversity indices

Drashti Shah
Bioinformatics with Rust
2 min readDec 30, 2023

--

Generated with AI

Rust functions that return Simpson’s Diversity Index and Shannon-Weiner Index based on count of species and count of individuals within a species.

Notes on Interpretation

  • These indexes are based on species richness and species evenness measures.
  • Species richness refers to unique number of species in a given area.
  • Species evenness is based on counts of individuals within a species. If these counts per species are similar, there’s more evenness. And if these counts have a large variation, there’s less evenness.
  • The Simpson’s Index value should be between 0 and 1. A higher value implies more implies more species and more evenness.
  • The Shannon-Weiner Index value should be more than or equal to 0. A higher value implies more species and more evenness.
  • Comparing the Simpson’s Index with the Shannon-Weiner Index is meaningless. Instead, you should choose one and use it to track biodiversity (at species level) across space and time.

Code & Examples

use std::collections::HashMap;

fn main() {
// Initialize a HashMap with species as keys and their respective counts as values
// Example of low biodiversity
let count_of_individuals_per_species: HashMap<String, f64> = HashMap::from([
("A".to_string(), 1.0),
("B".to_string(), 1.0),
("C".to_string(), 1.0),
("D".to_string(), 1.0),
("E".to_string(), 21.0),
]);
println!("{:?}", simpson_index(count_of_individuals_per_species.clone()));
println!("{:?}", shannon_weiner_index(count_of_individuals_per_species.clone()));
}

fn simpson_index(mut species_data: HashMap<String, f64>) -> f64 {
let total: f64 = species_data.values().sum();
for (_key, value) in species_data.iter_mut() {
// Simpson's index formula
*value = (*value / total).powf(2.0);
}
1.0 - species_data.values().sum::<f64>()
}

fn shannon_weiner_index(mut species_data: HashMap<String, f64>) -> f64 {
let total: f64 = species_data.values().sum();
for (_key, value) in species_data.iter_mut() {
// Update value for each species using Shannon-Weiner formula
*value = (*value / total) * (*value / total).ln();
}
species_data.values().sum::<f64>() * -1.0
}

Next Steps

  • Play with this code in Rust Playground
  • Watch this video from Khan Academy on Simpson’s Diversity Index
  • Watch this video from Bryan Tripper on Shannon Index

--

--

Drashti Shah
Bioinformatics with Rust

ESG & climate data scientist by day. Aspiring computational biologist by night.