Belle II Software development
caf_svd_dedx.py
1#!/usr/bin/env python3
2
3
10'''
11Script to perform the SVD dE/dx calibration
12'''
13from prompt import CalibrationSettings, INPUT_DATA_FILTERS
14import basf2 as b2
15from ROOT.Belle2 import SVDdEdxCalibrationAlgorithm, SVDdEdxValidationAlgorithm
16
17import modularAnalysis as ma
18import vertex as vx
19import reconstruction as re
20
21settings = CalibrationSettings(
22 name="caf_svd_dedx",
23 expert_username="lisovsky",
24 description=__doc__,
25 input_data_formats=["cdst"],
26 input_data_names=["hadron_calib"],
27 input_data_filters={"hadron_calib": [INPUT_DATA_FILTERS["Data Tag"]["hadron_calib"],
28 INPUT_DATA_FILTERS["Beam Energy"]["4S"],
29 INPUT_DATA_FILTERS["Beam Energy"]["Continuum"],
30 INPUT_DATA_FILTERS["Run Type"]["physics"],
31 INPUT_DATA_FILTERS["Magnet"]["On"]]},
32
33 expert_config={
34 "isMC": False,
35 "listOfMutedCalibrations": [], # dEdxCalibration, dEdxValidation
36 "rerun_reco": False, # need to rerun reconstruction for calibration?
37 "rerun_reco_val": True, # need to rerun reconstruction for validation?
38 "MaxFilesPerRun": 15,
39 "MaxFilesPerRunValidation": 6, # be careful in MC to not exclude certain event types
40 "MinEvtsPerFile": 1,
41 "MaxEvtsPerFile": 20000, # only if rerun the reco, to prevent jobs >10h
42 "MinEvtsPerTree": 100,
43 "NBinsP": 69,
44 "NBinsdEdx": 100,
45 "dedxCutoff": 5.e6,
46 "NumROCpoints": 175,
47 "MinROCMomentum": 0.,
48 "MaxROCMomentum": 2.5,
49 "NumEffBins": 30,
50 "MaxEffMomentum": 2.5
51 },
52 depends_on=[])
53
54
55def create_path(rerun_reco, isMC, expert_config):
56 rec_path = b2.Path()
57
58 # expert_config = kwargs.get("expert_config")
59 max_events_per_file = expert_config["MaxEvtsPerFile"]
60
61 if rerun_reco:
62 rec_path.add_module(
63 'RootInput',
64 branchNames=[
65 'RawARICHs',
66 'RawCDCs',
67 'RawECLs',
68 'RawFTSWs',
69 'RawKLMs',
70 'RawPXDs',
71 'RawSVDs',
72 'RawTOPs',
73 'RawTRGs',
74 'RawDataBlock',
75 'RawCOPPER'],
76 entrySequences=[f'0:{max_events_per_file - 1}'],
77 logLevel=b2.LogLevel.ERROR)
78 if not isMC:
79 re.add_unpackers(path=rec_path)
80 else:
81 rec_path.add_module("Gearbox")
82 rec_path.add_module("Geometry")
83
84 re.add_reconstruction(path=rec_path, pruneTracks=False)
85 rec_path.add_module('VXDDedxPID')
86 else:
87 rec_path.add_module('RootInput')
88
89 # Fill particle lists
90 ma.fillParticleList("pi+:all", "", path=rec_path)
91 ma.fillParticleList("pi+:lambda", "nCDCHits > 0", path=rec_path) # pi without track quality for reconstructing lambda
92 ma.fillParticleList("pi+:cut", "abs(dr) < 0.5 and abs(dz) < 2 and pValue > 0.00001 and nSVDHits > 1",
93 path=rec_path) # pions for reconstructing D and Dstar
94
95 ma.fillParticleList('K-:cut', cut='abs(dr) < 0.5 and abs(dz) < 2 and pValue > 0.00001 and nSVDHits > 1', path=rec_path) # kaon
96 ma.fillParticleList('e+:cut', cut='nSVDHits > 0', path=rec_path) # electron
97 # proton. In data, we only see background at p<0.25 GeV which motivates adding this cut.
98 ma.fillParticleList('p+:lambda', cut='nCDCHits > 0 and nSVDHits > 0 and p > 0.25', path=rec_path)
99
100 # ----------------------------------------------------------------------------
101 # Reconstruct D*(D0->K-pi+)pi+ and cc.
102 ma.reconstructDecay(decayString='D0:kpi -> K-:cut pi+:cut', cut='1.7 < M < 2.', path=rec_path)
103 ma.reconstructDecay(
104 decayString='D*+:myDstar -> D0:kpi pi+:all',
105 cut='1.95 < M <2.05 and massDifference(0) < 0.16',
106 path=rec_path)
107
108 # Reconstruct Lambda->p+pi- and cc.
109 ma.reconstructDecay('Lambda0:myLambda -> p+:lambda pi-:lambda', '1.1 < M < 1.3', path=rec_path)
110
111 # Reconstruct gamma->e+e- (photon conversion)
112 ma.reconstructDecay('gamma:myGamma -> e+:cut e-:cut', '0.0 < M < 0.5', path=rec_path)
113
114 # ----------------------------------------------------------------------------
115 # vertex fits
116 vx.treeFit(list_name='D*+:myDstar', conf_level=0, ipConstraint=True, updateAllDaughters=True, path=rec_path)
117 vx.treeFit(list_name='Lambda0:myLambda', conf_level=0, ipConstraint=True, updateAllDaughters=True, path=rec_path)
118 vx.treeFit(list_name='gamma:myGamma', conf_level=0, path=rec_path)
119
120 # ----------------------------------------------------------------------------
121 # Final selections on Lambda:
122 # - a tighter InvM range
123 # - a good vertex quality and a displacement requirement
124 # - a kinematic requirement p(p)>p(pi) which should always be satisfied in a true Lambda decay
125 # - a veto on the misidentified converted photons using the convertedPhotonInvariantMass tool, m(ee)>0.02 GeV
126 # - a veto on the misidentified K0S->pipi decays, vetoeing the region 0.488<m(pipi)<0.513 GeV
127
128 ma.cutAndCopyList(
129 outputListName='Lambda0:cut',
130 inputListName='Lambda0:myLambda',
131 cut=(
132 "1.10 < InvM < 1.13 and chiProb > 0.001 and distance>1.0 and "
133 "formula(daughter(0,p)) > formula(daughter(1,p)) and convertedPhotonInvariantMass(0,1) > 0.02 and "
134 "[[formula((((daughter(0, px)**2+daughter(0, py)**2+daughter(0, pz)**2 + 0.13957**2)**0.5+"
135 "daughter(1, E))*((daughter(0, px)**2+daughter(0, py)**2+daughter(0, pz)**2 + 0.13957**2)**0.5+"
136 "daughter(1, E))-(daughter(0, px)+daughter(1, px))*(daughter(0, px)+daughter(1, px))-(daughter(0, py)+"
137 "daughter(1, py))*(daughter(0, py)+daughter(1, py))-(daughter(0, pz)+daughter(1, pz))*(daughter(0, pz)+"
138 "daughter(1, pz)))**0.5) < 0.488]"
139 "or [formula((((daughter(0, px)**2+daughter(0, py)**2+daughter(0, pz)**2 + 0.13957**2)**0.5+"
140 "daughter(1, E))*((daughter(0, px)**2+daughter(0, py)**2+daughter(0, pz)**2 + 0.13957**2)**0.5+"
141 "daughter(1, E))-(daughter(0, px)+daughter(1, px))*(daughter(0, px)+daughter(1, px))-(daughter(0, py)+"
142 "daughter(1, py))*(daughter(0, py)+daughter(1, py))-(daughter(0, pz)+daughter(1, pz))*(daughter(0, pz)+"
143 "daughter(1, pz)))**0.5) > 0.513]]"
144 ),
145 path=rec_path)
146
147 # ----------------------------------------------------------------------------
148 # Selections on Dstar
149 # - a tighter InvM and deltaM range
150 # - a good vertex quality
151
152 ma.cutAndCopyList(
153 outputListName='D*+:cut',
154 inputListName='D*+:myDstar',
155 cut='massDifference(0) < 0.151 and 1.85 < daughter(0, InvM) < 1.88 and 1.95 < InvM < 2.05 and chiProb > 0.001',
156 path=rec_path)
157
158 # ----------------------------------------------------------------------------
159 # Selections on gamma
160 # - a good vertex quality
161 # - the dr cut on the origin vertex coordinate of the photon conversion, that excludes the beam background
162 # - a tighter range on both the invariant mass and the convertedPhotonInvariantMass
163 # - geometric cuts on proximity of e+ and e- with convertedPhotonDelR and convertedPhotonDelZ
164
165 ma.cutAndCopyList(
166 outputListName='gamma:cut',
167 inputListName='gamma:myGamma',
168 cut=('chiProb > 0.001 and 1 < dr < 12 and InvM < 0.01'
169 'and convertedPhotonInvariantMass(0,1) < 0.005'
170 'and -0.05 < convertedPhotonDelR(0,1) < 0.15'
171 'and -0.05 < convertedPhotonDelZ(0,1) < 0.05'
172 ),
173 path=rec_path)
174 return rec_path
175
176
177def get_calibrations(input_data, **kwargs):
178 """
179 Parameters:
180 input_data (dict): Should contain every name from the 'input_data_names' variable as a key.
181 Each value is a dictionary with {"/path/to/file_e1_r5.root": IoV(1,5,1,5), ...}. Useful for
182 assigning to calibration.files_to_iov
183
184 **kwargs: Configuration options to be sent in. Since this may change we use kwargs as a way to help prevent
185 backwards compatibility problems. But you could use the correct arguments in b2caf-prompt-run for this
186 release explicitly if you want to.
187
188 Currently only kwargs["requested_iov"] and kwargs["expert_config"] are used.
189
190 "requested_iov" is the IoV range of the bucket and your payloads should correspond to this range.
191 However your highest payload IoV should be open ended e.g. IoV(3,4,-1,-1)
192
193 "expert_config" is the input configuration. It takes default values from your `CalibrationSettings` but these are
194 overwritten by values from the 'expert_config' key in your input `caf_config.json` file when running ``b2caf-prompt-run``.
195
196 Returns:
197 list(caf.framework.Calibration): All of the calibration objects we want to assign to the CAF process
198 """
199 import basf2
200 # Set up config options
201
202 # In this script we want to use one sources of input data.
203 # Get the input files from the input_data variable
204 file_to_iov_hadron_calib = input_data["hadron_calib"]
205
206 expert_config = kwargs.get("expert_config")
207
208 isMC = expert_config["isMC"]
209 listOfMutedCalibrations = expert_config["listOfMutedCalibrations"]
210 rerun_reco = expert_config["rerun_reco"]
211 rerun_reco_val = expert_config["rerun_reco_val"]
212 max_files_per_run = expert_config["MaxFilesPerRun"]
213 max_files_per_run_validation = expert_config["MaxFilesPerRunValidation"]
214
215 # If you are using Raw data there's a chance that input files could have zero events.
216 # This causes a B2FATAL in basf2 RootInput so the collector job will fail.
217 # Currently we don't have a good way of filtering this on the automated side, so we can check here.
218 min_events_per_file = expert_config["MinEvtsPerFile"]
219
220 from prompt.utils import filter_by_max_files_per_run
221
222 reduced_file_to_iov_hadron_calib = filter_by_max_files_per_run(file_to_iov_hadron_calib, max_files_per_run, min_events_per_file)
223 input_files_hadron_calib = list(reduced_file_to_iov_hadron_calib.keys())
224 basf2.B2INFO(f"Total number of files actually used as input for calibration = {len(input_files_hadron_calib)}")
225
226 reduced_file_to_iov_hadron_validation = filter_by_max_files_per_run(
227 file_to_iov_hadron_calib, max_files_per_run_validation, min_events_per_file)
228 input_files_hadron_validation = list(reduced_file_to_iov_hadron_validation.keys())
229 basf2.B2INFO(f"Total number of files actually used as input for validation = {len(input_files_hadron_validation)}")
230 # Get the overall IoV we our process should cover. Includes the end values that we may want to ignore since our output
231 # IoV should be open ended. We could also use this as part of the input data selection in some way.
232 requested_iov = kwargs.get("requested_iov", None)
233
234 from caf.utils import IoV
235 # The actual value our output IoV payload should have. Notice that we've set it open ended.
236 output_iov = IoV(requested_iov.exp_low, requested_iov.run_low, -1, -1)
237
238
240
241 algo = SVDdEdxCalibrationAlgorithm()
242 algo.setMonitoringPlots(True)
243 algo.setNumPBins(expert_config['NBinsP'])
244 algo.setNumDEdxBins(expert_config['NBinsdEdx'])
245 algo.setDEdxCutoff(expert_config['dedxCutoff'])
246 algo.setMinEvtsPerTree(expert_config['MinEvtsPerTree'])
247
248 algo_val = SVDdEdxValidationAlgorithm()
249 algo_val.setMonitoringPlots(True)
250 algo_val.setMinEvtsPerTree(expert_config['MinEvtsPerTree'])
251 algo_val.setNumROCpoints(expert_config['NumROCpoints'])
252 algo_val.setMinROCMomentum(expert_config['MinROCMomentum'])
253 algo_val.setMaxROCMomentum(expert_config['MaxROCMomentum'])
254 algo_val.setNumEffBins(expert_config['NumEffBins'])
255 algo_val.setMaxEffMomentum(expert_config['MaxEffMomentum'])
256
257
259
260 from caf.framework import Calibration
261
262 rec_path = create_path(rerun_reco, isMC, expert_config)
263 rec_path_validation = create_path(rerun_reco_val, isMC, expert_config)
264
265 dedx_calibration = Calibration("SVDdEdxCalibration",
266 collector="SVDdEdxCollector",
267 algorithms=[algo],
268 input_files=input_files_hadron_calib,
269 pre_collector_path=rec_path)
270
271 dedx_validation = Calibration("SVDdEdxValidation",
272 collector="SVDdEdxValidationCollector",
273 algorithms=[algo_val],
274 backend_args={"queue": "l"},
275 input_files=input_files_hadron_validation,
276 pre_collector_path=rec_path_validation)
277 # Do this for the default AlgorithmStrategy to force the output payload IoV
278 # It may be different if you are using another strategy like SequentialRunByRun
279 for algorithm in dedx_calibration.algorithms:
280 algorithm.params = {"apply_iov": output_iov}
281
282 # Most other options like database chain and backend args will be overwritten by b2caf-prompt-run.
283 # So we don't bother setting them.
284
285 dedx_validation.depends_on(dedx_calibration)
286 # You must return all calibrations you want to run in the prompt process, even if it's only one
287 list_of_calibrations = []
288 if "dEdxCalibration" not in listOfMutedCalibrations:
289 list_of_calibrations.append(dedx_calibration)
290 if "dEdxValidation" not in listOfMutedCalibrations:
291 list_of_calibrations.append(dedx_validation)
292
293 return list_of_calibrations
294
295