Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Shannon Diversity Index
#!/usr/bin/env python
# Shannon Diversity Index
# http://en.wikipedia.org/wiki/Shannon_index
import sys
def sdi(data):
""" Given a hash { 'species': count } , returns the SDI
>>> sdi({'a': 10, 'b': 20, 'c': 30,})
1.0114042647073518"""
from math import log as ln
def p(n, N):
""" Relative abundance """
if n is 0:
return 0
else:
return (float(n)/N) * ln(float(n)/N)
N = sum(data.values())
return -sum(p(n, N) for n in data.values() if n is not 0)
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.