changeset 32:4d9778ade7b2

python3, add sd and mean caching
author Henry S. Thompson <ht@inf.ed.ac.uk>
date Thu, 29 Jul 2021 12:44:47 +0100
parents 1252f8100c6a
children a5a353728540
files signif.py
diffstat 1 files changed, 25 insertions(+), 14 deletions(-) [+]
line wrap: on
line diff
--- a/signif.py	Thu Jul 29 12:44:00 2021 +0100
+++ b/signif.py	Thu Jul 29 12:44:47 2021 +0100
@@ -4,33 +4,44 @@
 from math import sqrt
 
 def mean(self):
-  # Assumes the keys of this distribution are numbers!
-  return float(sum(v*self[v] for v in self.keys()))/self.N()
+  try:
+    return self.mean_value
+  except AttributeError:
+    # Assumes the keys of this distribution are numbers!
+    self.mean_value=float(sum(v*self[v] for v in self.keys()))/self.N()
+    return self.mean_value
+
+def sd(self):
+  try:
+    return self.sd_value
+  except AttributeError:
+    ssd = 0
+    for v in self.keys():
+      d = v-self.mean()
+      ssd+=d*d*self[v]
+    self.sd_value=sqrt(ssd/float(self.N()))
+    return self.sd_value
 
 FreqDist.mean=mean
+FreqDist.sd=sd
 
-def bell(self,maxVal=None,bars=False,**kwargs):
+def bell(self,maxVal=None,bars=False,block=True,**kwargs):
   # Assumes the keys of this distribution are numbers!
   if maxVal is not None:
     sk = sorted([k for k in self.keys() if k<=maxVal]) # range(max(self.keys())+1)
   else:
     sk=sorted(self.keys())
-  print len(sk)
+  print(len(sk))
   #sk.append(sk[-1]+1)
   #sk[0:0]=[(sk[0]-1)]
   mm=0 # sk[0]
   mean = self.mean()
-  tot = 0
-  ssd = 0
-  for v in self.keys():
-    d = v-mean
-    ssd+=d*d*self[v]
-  sd=sqrt(ssd/float(self.N()))
+  sd = self.sd()
   #print (mean,sd)
   kv=[self[k] for k in sk]
   pylab.figure().subplots_adjust(bottom=0.15)
   pylab.plot(sk,kv,color='blue')
-  if kwargs['xtra']:
+  if 'xtra' in kwargs and kwargs['xtra']:
     xtra=kwargs['xtra']
     pylab.plot(sk,[xtra[k] for k in sk],color='red')
   if bars:
@@ -46,7 +57,7 @@
              (mean-mm+(2*sd),mean-mm+(2*sd)),bb,
              color='green')
   pylab.xlabel("N %s, max %s\nmean %5.2f, s.d. %5.2f"%(self.N(),mv,mean, sd))
-  pylab.show()
+  pylab.show(block=block)
 
 FreqDist.bell=bell
 
@@ -90,8 +101,8 @@
   n1=len(r1)
   n2=len(r2)
   (ar,ties)=ranks(r1+r2,key=lambda e:e[1])
-  s1=sum(r[0] for r in ar if r[1][2] is 1)
-  s2=sum(r[0] for r in ar if r[1][2] is 2)
+  s1=sum(r[0] for r in ar if r[1][2] == 1)
+  s2=sum(r[0] for r in ar if r[1][2] == 2)
   u1=float(n1*n2)+(float(n1*(n1+1))/2.0)-float(s1)
   u2=float(n1*n2)+(float(n2*(n2+1))/2.0)-float(s2)
   u=min(u1,u2)