Skip to content

Instantly share code, notes, and snippets.

@audy
Created January 17, 2011 17:28
Show Gist options
  • Save audy/783125 to your computer and use it in GitHub Desktop.
Save audy/783125 to your computer and use it in GitHub Desktop.
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