Skip to content

Instantly share code, notes, and snippets.

@SavinaRoja
Created February 16, 2012 19:09
Show Gist options
  • Save SavinaRoja/1847078 to your computer and use it in GitHub Desktop.
Save SavinaRoja/1847078 to your computer and use it in GitHub Desktop.
Putting down some concepts and an implementation of certain probability distributions.
#Probability Distributions implemented interactively.
#An exercise in python mathematics and statistical methods
#I am developing this to further my understanding of bio-informatics by using
#a base-up approach.
import math
import random
class Binomial:
'''The binomial distribution has two possible outcomes. which may be
thought of in terms of 1 or 0, True or False, Positive or Negative.
Important parameters are the p value, which is the probability of yielding
1 (the probability of getting 0 is then consequently (1 - p)) and N, the
number of tries.'''
def __init__(self, N = 20, p = 0.5):
if self.checkN(N):
self.N = N
else:
self.N = 20
if self.checkP(p):
self.p = p
else:
self.p = 0.5
def checkP(self, val):
if 0 <= val <= 1:
return True
else:
print('Invalid p value, must be between 0 and 1')
return False
def checkN(self, val):
try:
val = int(val)
return True
except ValueError:
print('Invalid N value, must be an integer')
return False
def changeP(self, val):
if self.checkP(val):
self.p = val
else:
print('p value remains {0}'.format(self.p))
def changeN(self, val):
if self.checkN(val):
self.N = val
else:
print('N value remains {0}'.format(self.N))
def kProb(self, k, cumulative = '='):
P = 0
if 0 <= k <= self.N:
if cumulative == '<':
krange = xrange(0, k)
elif cumulative == '>':
krange = xrange(k + 1, self.N + 1)
elif cumulative == '=':
krange = [k]
elif cumulative == '<=':
krange = xrange(0, k + 1)
elif cumulative == '>=':
krange = xrange(k, self.N + 1)
else:
print('Improper control string: use \"<\", \">\", \"=\", \"<=\", or \">=\"')
krange = False
if krange:
for kval in krange:
factnum = math.factorial(self.N)
factden = math.factorial(kval) * math.factorial(self.N - kval)
fact = factnum / factden
pek = self.p ** kval
ompenmk = (1.0 - self.p) ** (self.N - kval)
P += fact * pek * ompenmk
return P
def generateNull(self):
nullstr = ''
for each in xrange(self.N):
r = random.random()
if r > self.p:
nullstr += '0'
else:
nullstr += '1'
return nullstr
def calculateVariance(self):
pass
def calculateMean(self):
m = 0
for kval in xrange(1, self.N + 1):
m += kval * self.kProb(kval)
return m
bn = Binomial()
#print(bn.generateNull())
#print(bn.calculateMean())
#print(bn.kProb(6, '='))
#print(bn.kProb(6, '<'))
#print(bn.kProb(6, '<='))
#print(bn.kProb(6, '>'))
#print(bn.kProb(6, '>='))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment