Added license info into the .py files.
[golden_search.git] / measurements.py
blob94fb7773c4cdb4abc9263e8221c2efd0373d475a
1 # For licensing info see the included LICENSE file
3 # Josef Moudrik, <J dot Moudrik at standard google mail ending>, 2012
5 import math
7 from number import Number
9 def avg(l):
10 assert len(l)
11 return sum(l) / float(len(l))
13 class MethodAnalyzer:
14 def __init__(self):
15 self.method_data = {}
16 self.method_avg_sdsq = {}
18 def addMeasurement(self, m):
19 assert m.method
20 l = self.method_data.get(m.method, [])
21 l.append( m.computeStats() )
22 self.method_data[m.method] = l
24 def computeStats(self, verbose=False):
25 for method, l in self.method_data.iteritems():
26 avg_sdsq = avg( [ t[2] for t in l ] )
27 min_sdsq = min( t[2] for t in l )
28 max_sdsq = max( t[2] for t in l )
30 self.method_avg_sdsq[method] = avg_sdsq
31 if verbose:
32 print method
33 print "min =", min_sdsq
34 print "avg =", avg_sdsq
35 print "max =", max_sdsq
37 class M:
38 def __init__(self, name, ms, method=None, units=None, precise=False):
39 if units == None:
40 units = {'m':1}
42 if precise:
43 assert len(ms) == 1
45 self.name = name
46 self.ms = map(float, ms)
47 #self.ms = ms
48 self.method = method
49 self.units = units
50 self.precise = precise
52 def computeStats(self):
53 n = len(self.ms)
54 mean = avg(self.ms)
55 # delime takhle kvuli nevychylenymu odhadu
56 sdsq = sum((x - mean)**2 for x in self.ms) / ( (n - 1) if n > 1 else 1 )
58 return (n, mean, sdsq)
60 def toNumber(self, method_resolution=None, method_analyzer=None):
61 if self.precise:
62 return Number(self.ms[0], units=self.units, string=self.name)
64 n, mean, sdsq = self.computeStats()
65 if self.method:
66 if method_analyzer:
67 mavg = method_analyzer.method_avg_sdsq[self.method]
68 if sdsq < mavg:
69 sdsq = mavg
71 # the more measurements, the better
72 sdsq /= n
74 if method_resolution:
75 # add the resolution of the method
76 sdsq += method_resolution[self.method] ** 2
78 return Number(mean, sdsq=sdsq, units=self.units, string=self.name)