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