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