Belle II Software development
caf_pxd_gain.py
1
8
9"""
10airflow script for PXD gain calibration.
11"""
12
13import basf2
14from pxd.calibration import gain_calibration
15from prompt.utils import filter_by_max_files_per_run, filter_by_max_events_per_run
16from prompt import CalibrationSettings, INPUT_DATA_FILTERS
17from caf.utils import ExpRun, IoV
18from itertools import groupby
19from itertools import chain
20from math import ceil, inf
21from prompt.calibrations.caf_beamspot import settings as beamspot_calibration
22
23
24settings = CalibrationSettings(name="PXD gain calibration",
25 expert_username="takaham",
26 description=__doc__,
27 input_data_formats=["cdst"],
28 input_data_names=["physics"],
29 input_data_filters={
30 "physics": [
31 INPUT_DATA_FILTERS["Data Tag"]["bhabha_all_calib"],
32 INPUT_DATA_FILTERS["Beam Energy"]["4S"],
33 INPUT_DATA_FILTERS["Beam Energy"]["Continuum"],
34 INPUT_DATA_FILTERS["Beam Energy"]["Scan"],
35 INPUT_DATA_FILTERS["Beam Energy"][""],
36 INPUT_DATA_FILTERS["Run Type"]["physics"],
37 INPUT_DATA_FILTERS["Data Quality Tag"]["Good"]]},
38 expert_config={
39 "debug": False,
40 "total_jobs": 1000,
41 "gain_method": "analytic",
42 "min_files_per_chunk": 10,
43 "min_events_per_file": 1000, # avoid empty files
44 "max_events_per_run": 4000000,
45 "max_files_per_run": 20, # only valid when max_events/run = 0
46 "payload_boundaries": []
47 },
48 depends_on=[beamspot_calibration])
49
50
51def get_calibrations(input_data, **kwargs):
52 """
53 Parameters:
54 input_data (dict): Should contain every name from the 'input_data_names' variable as a key.
55 Each value is a dictionary with {"/path/to/file_e1_r5.root": IoV(1,5,1,5), ...}. Useful for
56 assigning to calibration.files_to_iov
57
58 **kwargs: Configuration options to be sent in. Since this may change we use kwargs as a way to help prevent
59 backwards compatibility problems. But you could use the correct arguments in b2caf-prompt-run for this
60 release explicitly if you want to.
61
62 Currently only kwargs["output_iov"] is used. This is the output IoV range that your payloads should
63 correspond to. Generally your highest ExpRun payload should be open ended e.g. IoV(3,4,-1,-1)
64
65 Returns:
66 list(caf.framework.Calibration): All of the calibration objects we want to assign to the CAF process
67 """
68
69 # Set up config options
70 requested_iov = kwargs.get("requested_iov", None)
71 output_iov = IoV(requested_iov.exp_low, requested_iov.run_low, -1, -1)
72 # expert config
73 expert_config = kwargs.get("expert_config")
74 gain_method = expert_config["gain_method"]
75 debug = expert_config["debug"]
76 total_jobs = expert_config["total_jobs"]
77 max_events_per_run = expert_config["max_events_per_run"]
78 max_files_per_run = expert_config["max_files_per_run"]
79 min_files_per_chunk = expert_config["min_files_per_chunk"]
80 min_events_per_file = expert_config["min_events_per_file"]
81 cal_kwargs = expert_config.get("kwargs", {})
82
83 # print all config
84 basf2.B2INFO(f"Requested iov: {requested_iov} ")
85 basf2.B2INFO(f"Expert config: {expert_config} ")
86 # basf2.B2INFO(f"Expert sets payload boundaries are: {expert_config['payload_boundaries']} ")
87
88 # Read input_data
89 file_to_iov_physics = input_data["physics"]
90
91 # Reduce data and create calibration instances for different data categories
92 cal_list = []
93 if max_events_per_run < 0:
94 basf2.B2INFO("No file reduction applied.")
95 reduced_file_to_iov_physics = file_to_iov_physics
96 elif max_events_per_run == 0:
97 basf2.B2INFO(f"Reducing to a maximum of {max_files_per_run} files per run.")
98 reduced_file_to_iov_physics = filter_by_max_files_per_run(file_to_iov_physics,
99 max_files_per_run, min_events_per_file)
100 else:
101 basf2.B2INFO(f"Reducing to a maximum of {max_events_per_run} events per run.")
102 reduced_file_to_iov_physics = filter_by_max_events_per_run(file_to_iov_physics,
103 max_events_per_run, random_select=True)
104
105 # input_files_physics = list(reduced_file_to_iov_physics.keys())
106 input_iov_set_physics = set(reduced_file_to_iov_physics.values())
107 exp_set = {iov.exp_low for iov in input_iov_set_physics}
108
109 # boundaries setting for run chunks (At certain runs, gain was tuned)
110 payload_boundaries = [ExpRun(output_iov.exp_low, output_iov.run_low)]
111 payload_boundaries.extend([ExpRun(*boundary) for boundary in expert_config["payload_boundaries"]])
112 # We don't need run 0 for the first exp as it's handled by output_iov
113 payload_boundaries.extend([ExpRun(exp, 0) for exp in sorted(exp_set)[1:]])
114 basf2.B2INFO(f"Final Boundaries: {payload_boundaries}")
115
116 # run chunk creation
117 chunks_head = payload_boundaries
118 chunks_tail = payload_boundaries[1:] + [ExpRun(inf, inf)]
119 iov_chunks = [list(g) for k, g in groupby(sorted(input_iov_set_physics),
120 lambda x: [i for i, j in zip(chunks_head, chunks_tail) if i <= x < j])]
121
122 # Create calibrations from chunks
123 input_file_to_iov = reduced_file_to_iov_physics
124 iCal = 0
125 for ichunk, chunk in enumerate(iov_chunks):
126 first_iov = IoV(chunk[0].exp_low, chunk[0].run_low, -1, -1)
127 last_iov = IoV(chunk[-1].exp_low, chunk[-1].run_low, -1, -1)
128 if last_iov < output_iov: # All the chunk iovs are earlier than the requested
129 continue
130 else:
131 input_files = list(chain.from_iterable([list(g) for k, g in groupby(
132 input_file_to_iov, lambda x: input_file_to_iov[x] in chunk) if k]))
133 # Check the minimum number of files in the physics/beam run chunk
134 if len(input_files) < min_files_per_chunk:
135 basf2.B2WARNING(f"No enough file in sub run chunk [{chunk[0]},{chunk[-1]}]: {len(input_files)},\
136but {min_files_per_chunk} required!")
137 continue
138 # From the second chunk within the requested range, we have the iov defined by the first run
139 specific_iov = first_iov if iCal > 0 else output_iov
140 basf2.B2INFO(f"Total number of files actually used as input = {len(input_files)} for the output {specific_iov}")
141 cal_name = f"{ichunk+1}_PXDAnalyticGainCalibration"
142 if (not debug):
143 cal = gain_calibration(
144 cal_name=cal_name,
145 gain_method=gain_method,
146 # boundaries=vector_from_runs(payload_boundaries),
147 input_files=input_files,
148 **cal_kwargs)
149 for alg in cal.algorithms:
150 alg.params["iov_coverage"] = specific_iov
151 cal_list.append(cal)
152 else:
153 basf2.B2INFO(f"Dry run on Calibration(name={cal_name})")
154 iCal += 1
155
156 # The number of calibrations depends on the 'chunking' above. We would like to make sure that the total number of
157 # batch jobs submitted is approximately constant and reasonable, no matter how many files and chunks are used.
158 # So we define 1000 total jobs and split this between the calibrations depending on the fraction of total input
159 # files in the calibrations.
160
161 # total_jobs = expert_config["total_jobs"]
162 total_input_files = len(reduced_file_to_iov_physics)
163
164 for cal in cal_list:
165 fraction_of_input_files = len(cal.input_files) / total_input_files
166 # Assign the max collector jobs to be roughly the same fraction of total jobs
167 cal.max_collector_jobs = ceil(fraction_of_input_files * total_jobs)
168 basf2.B2INFO(f"{cal.name} will submit a maximum of {cal.max_collector_jobs} batch jobs")
169
170 return cal_list