/
anisotropy
executable file
·200 lines (173 loc) · 7.7 KB
/
anisotropy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
#!/usr/bin/env python3
from __future__ import division
import numpy as np
from matplotlib import pyplot as pl
from photon_tools.anisotropy import *
def print_params(fit, desc, corrs, ncomponents):
"""
:type fit: A :class:`FitResult` giving a the fitted parameter values
:type desc: A :class:`ModelDesc` describing the model
:type corrs: TODO
"""
print(' irf period', fit.eval(desc.period))
print(' irf offset (parallel)', fit.eval(desc.offset_par))
print(' irf offset (perpendicular)', fit.eval(desc.offset_perp))
print(' g', fit.eval(desc.imbalance))
print(' r0', fit.eval(desc.r0))
if desc.tau_rot is not None:
print(' tau_rot', fit.eval(desc.tau_rot))
for comp_idx in range(ncomponents):
rate = desc.fluor_rates[comp_idx]
if rate is not None:
print(' Component %d' % comp_idx)
print(' tau', fit.eval(1/rate))
for pair_idx,(cdesc, pair) in enumerate(zip(desc.curves, corrs)):
print(' Pair %d (par=%s, perp=%s)' % (pair_idx, pair.name, pair.name))
if cdesc.exc_leakage != 0:
print(' leakage', '%1.2g' % fit.eval(cdesc.exc_leakage))
if cdesc.tau_rot is not None:
print(' tau_rot', fit.eval(cdesc.tau_rot))
ampls = map(fit.eval, cdesc.amps)
for comp_idx, amp in enumerate(ampls):
frac = amp / sum(ampls)
print(' amplitude%d' % comp_idx, '%1.2f (%2.1f%%)' % (amp, frac * 100))
def gen_json(p, corrs, ncomponents):
out = {}
out['period'] = p.period
out['offset-par'] = p.offset_par
out['offset-perp'] = p.offset_perp
out['g'] = p.imbalance
out['r0'] = p.r0
out['tau-rot'] = p.tau_rot
out['components'] = []
for comp_idx in range(ncomponents):
out['components'].append({
'tau': 1/p.fluor_rates[comp_idx]
})
out['curves'] = []
for pair_idx,(cdesc, pair) in enumerate(zip(p.curves, corrs)):
out['curves'].append({
'leakage': cdesc.exc_leakage,
'tau_rot': cdesc.tau_rot,
'ampls': cdesc.amps,
})
return out
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('corr', metavar='FILE', nargs='+', type=argparse.FileType('r'),
help="correlation function")
parser.add_argument('--irf', '-i', metavar='FILE', action='append', type=argparse.FileType('r'),
help='instrument response function')
parser.add_argument('--components', '-c', type=int, default=1,
help='number of fit components')
parser.add_argument('--rep-rate', '-r', type=float,
help='pulse repetition rate (Hertz)')
parser.add_argument('--periods', '-p', type=int, default=1,
help='how many pulse periods we should fit to')
parser.add_argument('--output', '-o', type=argparse.FileType('w'),
help='where to send output')
parser.add_argument('--no-offset', action='store_true',
help='do not fit temporal offset between data and IRF')
parser.add_argument('-j', '--jiffy', type=float,
help='Bin width in seconds')
parser.add_argument('-e', '--exc-leakage', action='store_true',
help='Whether to model leakage of excitation into detection channels')
parser.add_argument('-J', '--json', type=argparse.FileType('w'),
help='JSON output file')
parser.add_argument('--imbalance', '-g', type=float,
help='Fix detector imbalance factor g')
parser.add_argument('--lifetimes', '-t', type=float, action='append', default=[],
help='Fix fluorescence decay lifetimes (in picoseconds)')
parser.add_argument('-A', '--indep-aniso',
help='Fit per-dataset rotational coherence models')
parser.add_argument('-R', '--sep-resid', action='store_true',
help='Plot residuals on separate per-dataset axes')
parser.add_argument('--opacity', type=float, default=0.8, help='Set opacity of plot curves')
args = parser.parse_args()
def read_hist(file_obj):
return np.genfromtxt(str(file_obj.name), dtype=None, names='time,counts')
# Read IRF
irfs = [read_hist(irf) for irf in args.irf]
if len(irfs) != 2:
raise RuntimeError('Expected two IRFs')
times = irfs[0]['time']
irfs = Aniso(irfs[0]['counts'], irfs[1]['counts'])
# Determine the channel width (jiffy)
if args.jiffy is not None:
jiffy_ps = args.jiffy / 1e-12
else:
jiffy_ps = (times[1] - times[0]) # in picoseconds
# Determine the pulse repetition rate
if args.rep_rate is None:
period = estimate_rep_rate(irfs.par)
else:
period = int(1e12 / args.rep_rate / jiffy_ps) # period in ticks
print('Period', period, 'bins')
print('Channel width', jiffy_ps, 'ps')
print('Total decay length', args.periods * period, 'bins')
# Trim curves to desired length
trim = 0
n = args.periods * period
irfs = irfs.map(lambda x: x[:n-trim])
# Normalize IRF
irfs = normalize_irfs(irfs)
# Read fluorescence decays
corrs = [FitSet(a.name, irfs, Aniso(read_hist(a)['counts'][:n-trim],
read_hist(b)['counts'][:n-trim]))
for a,b in zip(args.corr[::2], args.corr[1::2])]
res0, res, desc = fit(corrs, jiffy_ps, period, args.components,
no_offset=args.no_offset,
periods=args.periods,
exc_leakage=args.exc_leakage,
imbalance=args.imbalance,
indep_aniso=args.indep_aniso,
fix_lifetimes=args.lifetimes)
# Present results
print()
print('Fitted parameters')
print_params(res, desc, corrs, args.components)
# Fix covariance
for comp_idx1 in range(args.components):
for pair1 in corrs:
for comp_idx2 in range(args.components):
for pair2 in corrs:
p1 = '%s_amplitude%d' % (pair1.name, comp_idx1)
p2 = '%s_amplitude%d' % (pair2.name, comp_idx2)
rate1 = res.eval(desc.fluor_rates[comp_idx1])
rate2 = res.eval(desc.fluor_rates[comp_idx2])
res.covar[p1][p2] /= rate1 * rate2
print()
print('Reduced chi-squared')
for name, curve in sorted(res.curves.items()):
print(' %-15s %1.3g' % (name, curve.reduced_chi_sqr))
print()
print('Standard error')
if res.stderr is not None:
for param, err in res.stderr.items():
print(' %-15s %1.2g' % (param, err))
else:
print(" Failed to compute due to flat axis")
print()
print('Correlations (coefficients less than 0.2 omitted)')
if res.correl is not None:
correls = {(param1,param2): res.correl[param1][param2]
for param1 in res.params.keys()
for param2 in res.params.keys()
if param1 < param2}
for (p1,p2), c in sorted(correls.items(), key=lambda x: x[1], reverse=True):
if abs(c) > 0.2:
print(' %-15s / %-15s %1.2f' % (p1, p2, c))
else:
print(" Failed to compute due to flat axis")
if args.json is not None:
import json
json.dump(gen_json(desc, corrs, args.components), args.json, indent=4)
fig = pl.figure()
plot(fig, corrs, result=res, jiffy_ps=jiffy_ps, sep_resid=args.sep_resid, opacity=args.opacity)
if args.output is not None:
pl.savefig(args.output, figsize=(5,5), dpi=600)
else:
pl.show()
if __name__ == '__main__':
main()