-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfit.py
More file actions
executable file
·161 lines (122 loc) · 4.25 KB
/
Copy pathfit.py
File metadata and controls
executable file
·161 lines (122 loc) · 4.25 KB
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
#!/usr/bin/env python
#
# fit.py
#
"""
Fitting routines
"""
from itertools import chain
from multiprocessing import Pool, Process
from statistics import mean
import json
import pandas as pd
from femtofitter import PathQuery
def find_and_fit(filename: str, query: PathQuery, fit_range: float, mrc_path=None):
query = PathQuery.From(query)
path = query.as_path()
results = run_fit(filename, path, fit_range, mrc_path)
results.update(query.as_dict())
results['kt'] = mean(map(float, query['kt'].split("_")))
return results
def run_fit(fitter_class,
filename: str,
query: PathQuery,
fit_range: float,
fit_chi2: bool = False,
mrc_path: str = None):
from ROOT import TFile
from ROOT import Data3D
tfile = TFile.Open(filename)
assert tfile
path = query.as_path()
tdir = tfile.Get(path)
assert tdir
fitter = fitter_class.From(tfile, path, fit_range)
if mrc_path is not None:
from ROOT import apply_momentum_resolution_correction
mrc = tfile.Get(mrc_path)
print("MRC:",mrc)
if mrc == None:
print("missing mrc path %r" % mrc_path)
return
apply_momentum_resolution_correction(fitter.data, mrc)
fit_results = fitter.fit_chi2() if fit_chi2 else fitter.fit_pml()
if not fit_results:
print(f"Could not fit: {query.as_path()}")
return
results = dict(fit_results.as_map())
results.update(query.as_dict())
results['fit_range'] = fit_range
results['kT'] = mean(map(float, query.kt.split("_")))
results['chi2'] = fitter.resid_chi2(fit_results)
results['ndof'] = fitter.size()
results['rchi2'] = results['chi2'] / results['ndof']
results['mrc'] = mrc_path
return results
def parallel_fit_all(tfile,
ofilename=None,
mrc_path=None,
fitrange=0.21,
chi2=False):
"""
"""
from stumpy.utils import walk_matching
from datetime import datetime
from pathlib import Path
filename = Path(str(tfile.GetName()))
cfg = 'cfg*'
pair = cent = kt = mfield = '*'
search = f"AnalysisQ3D/{cfg}/{pair}/{cent}/{kt}/{mfield}"
mrc_path = "AnalysisTrueQ3D/cfg5348379EA4DD77C6/{pair}/00_90/{kt}/{magfield}/mrc"
paths = []
mrc_paths = []
for path, _ in walk_matching(tfile, search):
query = PathQuery.from_path(path)
assert path == query.as_path()
paths.append(query)
mrc_paths.append((query, mrc_path.format(**query.as_dict())))
configuration_information = get_configuration_json(tfile, paths)
filename = str(filename.absolute())
pool = Pool()
work = chain(
((filename, p, fitrange, chi2) for p in paths),
((filename, p, fitrange, chi2, m) for p, m in mrc_paths),
)
results = pool.starmap(run_fit_gauss_full, work)
#results += pool.starmap(run_fit_gauss, ])
#results += pool.starmap(run_fit_levy, [(filename, p, fitrange) for p in paths[:1]])
df = pd.DataFrame(results)
output_data = {
'filename': filename,
'timestamp': datetime.now().isoformat(timespec='milliseconds'),
'df': df.to_dict(orient='records'),
'config': configuration_information,
}
if ofilename:
with Path(ofilename).open('w') as outfile:
json.dump(output_data, outfile, indent=True)
else:
from pprint import pprint
pprint(output_data)
def get_configuration_json(tfile, queries):
from ROOT import AliFemtoConfigObject
result = {}
for c in {"%s/%s" % (q.analysis, q.cfg) for q in queries}:
path = f"{c}/config"
config = tfile.Get(path)
# if not config:
if not isinstance(config, AliFemtoConfigObject):
print("Missing AliFemtoConfigObject 'config' in %r" % path)
continue
result[c] = json.loads(config.as_JSON_string())
return result
if __name__ == "__main__":
import sys
try:
filename = sys.argv[1]
except IndexError:
filename = 'data.root'
from ROOT import gSystem, TFile
assert 0 <= gSystem.Load('build/libFemtoFitter.so')
data = TFile.Open(filename)
parallel_fit_all(data, "fitres-%s.json" % filename.rpartition('.')[0])