Add a PyMOL builder to SCons and generalize PYMOL_PATH setup.
[thesis.git] / tex / src / figures / cantilever-data / avg_data.py
1 #!/usr/bin/python
2
3 import numpy, sys
4
5 DATAFILE='./data/raw'
6 KFILE='./data/spring-constants'
7 AVGFILE='./data/averaged-data'
8
9 KCUTS=[45, 90]
10
11 def read_raw(Kcuts=KCUTS, datafile=DATAFILE):
12     FofV = {}
13     Ks = []
14     for i in range(len(Kcuts)+1):
15         Ks.append([])
16     for line in file(datafile, 'r'):
17         if line[0] == '#':
18             continue # ignore comments
19         fields = line.strip().split('\t')
20         force = float(fields[0])
21         rate = float(fields[1])
22         spring = float(fields[2])
23
24         ispring = 0
25         while ispring < len(Kcuts) and spring > Kcuts[ispring]:
26             ispring += 1
27         Ks[ispring].append(spring)
28         if rate not in FofV.keys():
29             FofV[rate]=[]
30             for i in range(len(Ks)):
31                 FofV[rate].append([])
32         FofV[rate][ispring].append(force)
33     return (Ks, FofV)
34
35 def write_k_file(Ks, kfile=KFILE):
36     avgK = [0]*len(Ks)
37     stdK = [0]*len(Ks)
38     numK = [0]*len(Ks)
39     kf = file(kfile, 'w')
40     for i in range(len(Ks)):
41         K = numpy.array(Ks[i])
42         avgK[i] = K.mean()
43         stdK[i] = K.std()
44         numK[i] = len(K)
45
46         if i == 1:
47             continue # poor calibration bumps for the older cantilevers
48         print >> kf, "K(%d) = %g +/- %g, (# %d)" \
49             % (i, avgK[i], stdK[i], numK[i])
50     kf.close()
51     return (avgK, stdK, numK)
52
53 def write_average_file(FofV, avgK, avgfile=AVGFILE):
54     Vs = FofV.keys()
55     Vs.sort()
56     af = file(AVGFILE, 'w')
57     print >> af, '#'+'\t'.join(\
58         ['Pulling speed (nm/s)','Spring constant (pN/nm)',
59          'Mean force (pN)','Std. force (pN)','Events (#)'])
60     for V in Vs:
61         for i,k in enumerate(avgK):
62             if i == 1:
63                 continue # poor calibration bumps for the older cantilevers
64             F = numpy.array(FofV[V][i])
65             if len(F) == 0:
66                 continue
67             outs= [V, k, F.mean(), F.std(), len(F)]
68             souts = ["%.2f" % (x) for x in outs]
69             souts[-1] = "%d" % outs[-1] # special treatment for the integer
70             print >> af, '\t'.join(souts)
71     af.close()
72
73 if __name__ == '__main__':
74     Ks,FofV = read_raw()
75     avgK,stdK,numK = write_k_file(Ks)
76     write_average_file(FofV, avgK)