# prize35-10 Exercise 1: richness versus diversity indices for three invented survey sites import math sites = { "Old wood": [30, 22, 18, 12, 10, 8], "Hay meadow": [20, 18, 15, 14, 12, 11, 10], "Barley field": [200, 10, 5, 3, 2, 1, 1, 1], } def indices(counts): total = sum(counts) shares = [c / total for c in counts] h = -sum(s * math.log(s) for s in shares) simpson = 1 - sum(s * s for s in shares) return len(counts), h, simpson, h / math.log(len(counts)) print("site richness Shannon H Simpson 1-D evenness") results = {} for name, counts in sites.items(): results[name] = indices(counts) r, h, d, j = results[name] print(f"{name:13} {r:8} {h:9.2f} {d:11.2f} {j:8.2f}") for position, label in ((0, "richness"), (1, "Shannon H"), (2, "Simpson 1-D")): order = sorted(results, key=lambda n: results[n][position], reverse=True) print(f"ranked by {label}:", ", ".join(order)) # Output: # site richness Shannon H Simpson 1-D evenness # Old wood 6 1.69 0.80 0.94 # Hay meadow 7 1.92 0.85 0.99 # Barley field 8 0.49 0.19 0.24 # ranked by richness: Barley field, Hay meadow, Old wood # ranked by Shannon H: Hay meadow, Old wood, Barley field # ranked by Simpson 1-D: Hay meadow, Old wood, Barley field # Reading it: the barley field has the most species but by far the lowest diversity, because one species makes up almost the whole sample. # Richness alone ranks it first; Shannon and Simpson, which also weigh evenness, rank it last. Use more than one measure.