12This module implements several objects/functions to configure and run calibrations.
13These classes are used to construct the workflow of the calibration job.
14The actual processing code is mostly in the `caf.state_machines` module.
17__all__ = [
"CalibrationBase",
"Calibration",
"Algorithm",
"CAF"]
20from threading
import Thread
22from pathlib
import Path
26from basf2
import B2ERROR, B2WARNING, B2INFO, B2FATAL, B2DEBUG
27from basf2
import find_file
28from basf2
import conditions
as b2conditions
30from abc
import ABC, abstractmethod
33from caf.utils
import B2INFO_MULTILINE
34from caf.utils
import past_from_future_dependencies
35from caf.utils
import topological_sort
36from caf.utils
import all_dependencies
37from caf.utils
import method_dispatch
38from caf.utils
import temporary_workdir
39from caf.utils
import find_int_dirs
40from caf.utils
import LocalDatabase
41from caf.utils
import CentralDatabase
42from caf.utils
import parse_file_uri
44import caf.strategies
as strategies
45import caf.runners
as runners
46from caf.backends
import MaxSubjobsSplitter, MaxFilesSplitter
47from caf.state_machines
import CalibrationMachine, ConditionError, MachineError
48from caf.database
import CAFDB
54 collector (str, basf2.Module): The collector module or module name for this `Collection`.
55 input_files (list[str]): The input files to be used for only this `Collection`.
56 pre_collection_path (basf2.Path): The reconstruction `basf2.Path` to be run prior to the Collector module.
57 database_chain (list[CentralDatabase, LocalDatabase]): The database chain to be used initially for this `Collection`.
58 output_patterns (list[str]): Output patterns of files produced by collector which will be used to pass to the
59 `Algorithm.data_input` function. Setting this here, replaces the default completely.
60 max_files_for_collector_job (int): Maximum number of input files sent to each collector subjob for this `Collection`.
61 Technically this sets the SubjobSplitter to be used, not compatible with max_collector_jobs.
62 max_collector_jobs (int): Maximum number of collector subjobs for this `Collection`.
63 Input files are split evenly between them. Technically this sets the SubjobSplitter to be used. Not compatible with
64 max_files_for_collector_job.
65 backend_args (dict): The args for the backend submission of this `Collection`.
69 default_max_collector_jobs = 1000
72 job_config =
"collector_job.json"
77 pre_collector_path=None,
80 max_files_per_collector_job=None,
81 max_collector_jobs=None,
104 if pre_collector_path:
117 if max_files_per_collector_job
and max_collector_jobs:
118 B2FATAL(
"Cannot set both 'max_files_per_collector_job' and 'max_collector_jobs' of a collection!")
120 elif max_files_per_collector_job:
122 elif max_collector_jobs:
144 for tag
in reversed(b2conditions.default_globaltags):
148 self.
job_script = Path(find_file(
"calibration/scripts/caf/run_collector_path.py")).absolute()
149 """The basf2 steering file that will be used for Collector jobs run by this collection.
150This script will be copied into subjob directories as part of the input sandbox."""
157 Remove everything in the database_chain of this Calibration, including the default central database
158 tag automatically included from `basf2.conditions.default_globaltags <ConditionsConfiguration.default_globaltags>`.
165 global_tag (str): The central database global tag to use for this calibration.
167 Using this allows you to add a central database to the head of the global tag database chain for this collection.
168 The default database chain is just the central one from
169 `basf2.conditions.default_globaltags <ConditionsConfiguration.default_globaltags>`.
170 The input file global tag will always be overridden and never used unless explicitly set.
172 To turn off central database completely or use a custom tag as the base, you should call `Calibration.reset_database`
173 and start adding databases with `Calibration.use_local_database` and `Calibration.use_central_database`.
175 Alternatively you could set an empty list as the input database_chain when adding the Collection to the Calibration.
177 NOTE!! Since ``release-04-00-00`` the behaviour of basf2 conditions databases has changed.
178 All local database files MUST now be at the head of the 'chain', with all central database global tags in their own
179 list which will be checked after all local database files have been checked.
181 So even if you ask for ``["global_tag1", "localdb/database.txt", "global_tag2"]`` to be the database chain, the real order
182 that basf2 will use them is ``["global_tag1", "global_tag2", "localdb/database.txt"]`` where the file is checked first.
184 central_db = CentralDatabase(global_tag)
190 filename (str): The path to the database.txt of the local database
191 directory (str): The path to the payloads directory for this local database.
193 Append a local database to the chain for this collection.
194 You can call this function multiple times and each database will be added to the chain IN ORDER.
195 The databases are applied to this collection ONLY.
197 NOTE!! Since release-04-00-00 the behaviour of basf2 conditions databases has changed.
198 All local database files MUST now be at the head of the 'chain', with all central database global tags in their own
199 list which will be checked after all local database files have been checked.
201 So even if you ask for ["global_tag1", "localdb/database.txt", "global_tag2"] to be the database chain, the real order
202 that basf2 will use them is ["global_tag1", "global_tag2", "localdb/database.txt"] where the file is checked first.
204 local_db = LocalDatabase(filename, directory)
211 input_file (str): A local file/glob pattern or XROOTD URI
214 list: A list of the URIs found from the initial string.
217 uri = parse_file_uri(input_file)
218 if uri.scheme ==
"file":
221 uris = [parse_file_uri(f).geturl()
for f
in glob(input_file)]
237 if isinstance(value, str):
241 elif isinstance(value, list):
244 for pattern
in value:
248 raise TypeError(
"Input files must be a list or string")
263 from basf2
import Module
264 if isinstance(collector, str):
265 from basf2
import register_module
266 collector = register_module(collector)
267 if not isinstance(collector, Module):
268 B2ERROR(
"Collector needs to be either a Module or the name of such a module")
289 @max_collector_jobs.setter
296 self.
splitter = MaxSubjobsSplitter(max_subjobs=value)
303 return self.
splitter.max_files_per_subjob
307 @max_files_per_collector_job.setter
314 self.
splitter = MaxFilesSplitter(max_files_per_subjob=value)
319 Abstract base class of Calibration types. The CAF implements the :py:class:`Calibration` class which inherits from
320 this and runs the C++ CalibrationCollectorModule and CalibrationAlgorithm classes. But by inheriting from this
321 class and providing the minimal necessary methods/attributes you could plug in your own Calibration types
322 that doesn't depend on the C++ CAF at all and run everything in your own way.
324 .. warning:: Writing your own class inheriting from :py:class:`CalibrationBase` class is not recommended!
325 But it's there if you really need it.
328 name (str): Name of this calibration object. Should be unique if you are going to run it.
331 input_files (list[str]): Input files for this calibration. May contain wildcard expressions usable by `glob.glob`.
335 end_state =
"completed"
338 fail_state =
"failed"
376 The most important method. Runs inside a new Thread and is called from `CalibrationBase.start`
377 once the dependencies of this `CalibrationBase` have returned with state == end_state i.e. "completed".
383 A simple method you should implement that will return True or False depending on whether
384 the Calibration has been set up correctly and can be run safely.
390 calibration (`CalibrationBase`): The Calibration object which will produce constants that this one depends on.
392 Adds dependency of this calibration on another i.e. This calibration
393 will not run until the dependency has completed, and the constants produced
394 will be used via the database chain.
396 You can define multiple dependencies for a single calibration simply
397 by calling this multiple times. Be careful when adding the calibration into
398 the `CAF` not to add a circular/cyclic dependency. If you do the sort will return an
399 empty order and the `CAF` processing will fail.
401 This function appends to the `CalibrationBase.dependencies` and `CalibrationBase.future_dependencies` attributes of this
402 `CalibrationBase` and the input one respectively. This prevents us having to do too much recalculation later on.
405 if self.name != calibration.name:
407 if calibration
not in self.dependencies:
408 self.dependencies.append(calibration)
409 if self
not in calibration.dependencies:
410 calibration.future_dependencies.append(self)
412 B2WARNING(f
"Tried to add {calibration} as a dependency for {self} but they have the same name."
413 "Dependency was not added.")
417 Checks if all of the Calibrations that this one depends on have reached a successful end state.
423 Returns the list of calibrations in our dependency list that have failed.
428 failed.append(calibration)
433 We pass in default calibration options from the `CAF` instance here if called.
434 Won't overwrite any options already set.
436 for key, value
in defaults.items():
438 if getattr(self, key)
is None:
439 setattr(self, key, value)
440 except AttributeError:
441 print(f
"The calibration {self.name} does not support the attribute {key}.")
446 Every Calibration object must have at least one collector at least one algorithm.
447 You have the option to add in your collector/algorithm by argument here, or add them
448 later by changing the properties.
450 If you plan to use multiple `Collection` objects I recommend that you only set the name here and add the Collections
451 separately via `add_collection()`.
454 name (str): Name of this calibration. It should be unique for use in the `CAF`
456 collector (str, `basf2.Module`): Should be set to a CalibrationCollectorModule() or a string with the module name.
457 algorithms (list, ``ROOT.Belle2.CalibrationAlgorithm``): The algorithm(s) to use for this `Calibration`.
458 input_files (str, list[str]): Input files for use by this Calibration. May contain wildcards usable by `glob.glob`
460 A Calibration won't be valid in the `CAF` until it has all of these four attributes set. For example:
462 >>> cal = Calibration('TestCalibration1')
463 >>> col1 = register_module('CaTest')
464 >>> cal.add_collection('TestColl', col1)
468 >>> cal = Calibration('TestCalibration1', 'CaTest')
470 If you want to run a basf2 :py:class:`path <basf2.Path>` before your collector module when running over data
472 >>> cal.pre_collector_path = my_basf2_path
474 You don't have to put a RootInput module in this pre-collection path, but you can if
475 you need some special parameters. If you want to process sroot files the you have to explicitly add
476 SeqRootInput to your pre-collection path.
477 The inputFileNames parameter of (Seq)RootInput will be set by the CAF automatically for you.
480 You can use optional arguments to pass in some/all during initialisation of the `Calibration` class
482 >>> cal = Calibration( 'TestCalibration1', 'CaTest', [alg1,alg2], ['/path/to/file.root'])
484 you can change the input file list later on, before running with `CAF`
486 >>> cal.input_files = ['path/to/*.root', 'other/path/to/file2.root']
488 If you have multiple collections from calling `add_collection()` then you should instead set the pre_collector_path,
489 input_files, database chain etc from there. See `Collection`.
491 Adding the CalibrationAlgorithm(s) is easy
493 >>> alg1 = TestAlgo()
494 >>> cal.algorithms = alg1
498 >>> cal.algorithms = [alg1]
500 Or for multiple algorithms for one collector
502 >>> alg2 = TestAlgo()
503 >>> cal.algorithms = [alg1, alg2]
505 Note that when you set the algorithms, they are automatically wrapped and stored as a Python class
506 `Algorithm`. To access the C++ algorithm clas underneath directly do:
508 >>> cal.algorithms[i].algorithm
510 If you have a setup function that you want to run before each of the algorithms, set that with
512 >>> cal.pre_algorithms = my_function_object
514 If you want a different setup for each algorithm use a list with the same number of elements
515 as your algorithm list.
517 >>> cal.pre_algorithms = [my_function1, my_function2, ...]
519 You can also specify the dependencies of the calibration on others
521 >>> cal.depends_on(cal2)
523 By doing this, the `CAF` will respect the ordering of the calibrations and will pass the
524 calibration constants created by earlier completed calibrations to dependent ones.
527 moves = [
"submit_collector",
"complete",
"run_algorithms",
"iterate",
"fail_fully"]
529 alg_output_dir =
"algorithm_output"
531 checkpoint_states = [
"init",
"collector_completed",
"completed"]
533 default_collection_name =
"default"
540 pre_collector_path=None,
542 output_patterns=None,
543 max_files_per_collector_job=None,
544 max_collector_jobs=None,
562 max_files_per_collector_job,
595 for tag
in reversed(b2conditions.default_globaltags):
619 name (str): Unique name of this `Collection` in the Calibration.
620 collection (`Collection`): `Collection` object to use.
622 Adds a new `Collection` object to the `Calibration`. Any valid Collection will be used in the Calibration.
623 A default Collection is automatically added but isn't valid and won't run unless you have assigned a collector
625 You can ignore the default one and only add your own custom Collections. You can configure the default from the
626 Calibration(...) arguments or after creating the Calibration object via directly setting the cal.collector, cal.input_files
632 B2WARNING(f
"A Collection with the name '{name}' already exists in this Calibration. It has not been added."
633 "Please use another name.")
637 A full calibration consists of a collector AND an associated algorithm AND input_files.
640 1) We are missing any of the above.
641 2) There are multiple Collections and the Collectors have mis-matched granularities.
642 3) Any of our Collectors have granularities that don't match what our Strategy can use.
645 B2WARNING(f
"Empty algorithm list for {self.name}.")
648 if not any([collection.is_valid()
for collection
in self.
collections.values()]):
649 B2WARNING(f
"No valid Collections for {self.name}.")
654 if collection.is_valid():
655 collector_params = collection.collector.available_params()
656 for param
in collector_params:
657 if param.name ==
"granularity":
658 granularities.append(param.values)
659 if len(set(granularities)) > 1:
660 B2WARNING(
"Multiple different granularities set for the Collections in this Calibration.")
664 alg_type = type(alg.algorithm).__name__
665 incorrect_gran = [granularity
not in alg.strategy.allowed_granularities
for granularity
in granularities]
666 if any(incorrect_gran):
667 B2WARNING(f
"Selected strategy for {alg_type} does not match a collector's granularity.")
674 apply_to_default_collection (bool): Should we also reset the default collection?
676 Remove everything in the database_chain of this Calibration, including the default central database tag automatically
677 included from `basf2.conditions.default_globaltags <ConditionsConfiguration.default_globaltags>`. This will NOT affect the
678 database chain of any `Collection` other than the default one. You can prevent the default Collection from having its chain
679 reset by setting 'apply_to_default_collection' to False.
688 global_tag (str): The central database global tag to use for this calibration.
691 apply_to_default_collection (bool): Should we also call use_central_database on the default collection (if it exists)
693 Using this allows you to append a central database to the database chain for this calibration.
694 The default database chain is just the central one from
695 `basf2.conditions.default_globaltags <ConditionsConfiguration.default_globaltags>`.
696 To turn off central database completely or use a custom tag as the base, you should call `Calibration.reset_database`
697 and start adding databases with `Calibration.use_local_database` and `Calibration.use_central_database`.
699 Note that the database chain attached to the `Calibration` will only affect the default `Collection` (if it exists),
700 and the algorithm processes. So calling:
702 >> cal.use_central_database("global_tag")
704 will modify the database chain used by all the algorithms assigned to this `Calibration`, and modifies the database chain
707 >> cal.collections['default'].database_chain
711 >> cal.use_central_database(file_path, payload_dir, False)
713 will add the database to the Algorithm processes, but leave the default Collection database chain untouched.
714 So if you have multiple Collections in this Calibration *their database chains are separate*.
715 To specify an additional `CentralDatabase` for a different collection, you will have to call:
717 >> cal.collections['OtherCollection'].use_central_database("global_tag")
719 central_db = CentralDatabase(global_tag)
727 filename (str): The path to the database.txt of the local database
730 directory (str): The path to the payloads directory for this local database.
731 apply_to_default_collection (bool): Should we also call use_local_database on the default collection (if it exists)
733 Append a local database to the chain for this calibration.
734 You can call this function multiple times and each database will be added to the chain IN ORDER.
735 The databases are applied to this calibration ONLY.
736 The Local and Central databases applied via these functions are applied to the algorithm processes and optionally
737 the default `Collection` job as a database chain.
738 There are other databases applied to the processes later, checked by basf2 in this order:
740 1) Local Database from previous iteration of this Calibration.
741 2) Local Database chain from output of previous dependent Calibrations.
742 3) This chain of Local and Central databases where the last added is checked first.
744 Note that this function on the `Calibration` object will only affect the default `Collection` if it exists and if
745 'apply_to_default_collection' remains True. So calling:
747 >> cal.use_local_database(file_path, payload_dir)
749 will modify the database chain used by all the algorithms assigned to this `Calibration`, and modifies the database chain
752 >> cal.collections['default'].database_chain
756 >> cal.use_local_database(file_path, payload_dir, False)
758 will add the database to the Algorithm processes, but leave the default Collection database chain untouched.
760 If you have multiple Collections in this Calibration *their database chains are separate*.
761 To specify an additional `LocalDatabase` for a different collection, you will have to call:
763 >> cal.collections['OtherCollection'].use_local_database(file_path, payload_dir)
766 local_db = LocalDatabase(filename, directory)
777 B2WARNING(f
"You tried to get the attribute '{attr}' from the Calibration '{self.name}', "
778 "but the default collection doesn't exist."
779 f
"You should use the cal.collections['CollectionName'].{attr} to access a custom "
780 "collection's attributes directly.")
789 B2WARNING(f
"You tried to set the attribute '{attr}' from the Calibration '{self.name}', "
790 "but the default collection doesn't exist."
791 f
"You should use the cal.collections['CollectionName'].{attr} to access a custom "
792 "collection's attributes directly.")
806 from basf2
import Module
807 if isinstance(collector, str):
808 from basf2
import register_module
809 collector = register_module(collector)
810 if not isinstance(collector, Module):
811 B2ERROR(
"Collector needs to be either a Module or the name of such a module")
833 @files_to_iovs.setter
845 @pre_collector_path.setter
857 @output_patterns.setter
869 @max_files_per_collector_job.setter
881 @max_collector_jobs.setter
910 from ROOT
import Belle2
911 from ROOT.Belle2
import CalibrationAlgorithm
912 if isinstance(value, CalibrationAlgorithm):
915 B2ERROR(f
"Something other than CalibrationAlgorithm instance passed in ({type(value)}). "
916 "Algorithm needs to inherit from Belle2::CalibrationAlgorithm")
918 @algorithms.fset.register(tuple)
919 @algorithms.fset.register(list)
922 Alternate algorithms setter for lists and tuples of CalibrationAlgorithms.
924 from ROOT
import Belle2
925 from ROOT.Belle2
import CalibrationAlgorithm
929 if isinstance(alg, CalibrationAlgorithm):
932 B2ERROR(f
"Something other than CalibrationAlgorithm instance passed in {type(value)}."
933 "Algorithm needs to inherit from Belle2::CalibrationAlgorithm")
938 Callback run prior to each algorithm iteration.
940 return [alg.pre_algorithm
for alg
in self.
algorithms]
942 @pre_algorithms.setter
949 alg.pre_algorithm = func
951 B2ERROR(
"Something evaluated as False passed in as pre_algorithm function.")
953 @pre_algorithms.fset.register(tuple)
954 @pre_algorithms.fset.register(list)
957 Alternate pre_algorithms setter for lists and tuples of functions, should be one per algorithm.
961 for func, alg
in zip(values, self.
algorithms):
962 alg.pre_algorithm = func
964 B2ERROR(
"Number of functions and number of algorithms doesn't match.")
966 B2ERROR(
"Empty container passed in for pre_algorithm functions")
971 The `caf.strategies.AlgorithmStrategy` or `list` of them used when running the algorithm(s).
973 return [alg.strategy
for alg
in self.
algorithms]
982 alg.strategy = strategy
984 B2ERROR(
"Something evaluated as False passed in as a strategy.")
986 @strategies.fset.register(tuple)
987 @strategies.fset.register(list)
990 Alternate strategies setter for lists and tuples of functions, should be one per algorithm.
994 for strategy, alg
in zip(strategies, self.
algorithms):
995 alg.strategy = strategy
997 B2ERROR(
"Number of strategies and number of algorithms doesn't match.")
999 B2ERROR(
"Empty container passed in for strategies list")
1008 Main logic of the Calibration object.
1009 Will be run in a new Thread by calling the start() method.
1011 with CAFDB(self.
_db_path, read_only=
True)
as db:
1012 initial_state = db.get_calibration_value(self.
name,
"checkpoint")
1013 initial_iteration = db.get_calibration_value(self.
name,
"iteration")
1014 B2INFO(f
"Initial status of {self.name} found to be state={initial_state}, iteration={initial_iteration}")
1015 self.
machine = CalibrationMachine(self,
1016 iov_to_calibrate=self.
iov,
1017 initial_state=initial_state,
1018 iteration=initial_iteration)
1021 self.
machine.root_dir = Path(os.getcwd(), self.
name)
1026 all_iteration_paths = find_int_dirs(self.
machine.root_dir)
1027 for iteration_path
in all_iteration_paths:
1028 if int(iteration_path.name) > initial_iteration:
1029 shutil.rmtree(iteration_path)
1032 if self.
state ==
"init":
1034 B2INFO(f
"Attempting collector submission for calibration {self.name}.")
1036 except Exception
as err:
1042 if self.
state ==
"collector_failed":
1050 B2INFO(f
"Attempting to run algorithms for calibration {self.name}.")
1052 except MachineError
as err:
1057 if self.
machine.state ==
"algorithms_failed":
1064 while self.
state ==
"running_collector":
1068 except ConditionError:
1070 B2DEBUG(29, f
"Checking if collector jobs for calibration {self.name} have failed.")
1072 except ConditionError:
1079 The current major state of the calibration in the database file. The machine may have a different state.
1081 with CAFDB(self.
_db_path, read_only=
True)
as db:
1082 state = db.get_calibration_value(self.
name,
"state")
1089 B2DEBUG(29, f
"Setting {self.name} to state {state}.")
1091 db.update_calibration_value(self.
name,
"state", str(state))
1093 db.update_calibration_value(self.
name,
"checkpoint", str(state))
1094 B2DEBUG(29, f
"{self.name} set to {state}.")
1099 Retrieves the current iteration number in the database file.
1102 int: The current iteration number
1104 with CAFDB(self.
_db_path, read_only=
True)
as db:
1105 iteration = db.get_calibration_value(self.
name,
"iteration")
1112 B2DEBUG(29, f
"Setting {self.name} to {iteration}.")
1114 db.update_calibration_value(self.
name,
"iteration", iteration)
1115 B2DEBUG(29, f
"{self.name} set to {self.iteration}.")
1121 algorithm: The CalibrationAlgorithm instance that we want to execute.
1123 data_input : An optional function that sets the input files of the algorithm.
1124 pre_algorithm : An optional function that runs just prior to execution of the algorithm.
1125 Useful for set up e.g. module initialisation
1127 This is a simple wrapper class around the C++ CalibrationAlgorithm class.
1128 It helps to add functionality to algorithms for use by the Calibration and CAF classes rather
1129 than separating the logic into those classes directly.
1131 This is **not** currently a class that a user should interact with much during `CAF`
1132 setup (unless you're doing something advanced).
1133 The `Calibration` class should be doing the most of the creation of the defaults for these objects.
1135 Setting the `data_input` function might be necessary if you have set the `Calibration.output_patterns`.
1136 Also, setting the `pre_algorithm` to a function that should execute prior to each `strategies.AlgorithmStrategy`
1137 is often useful i.e. by calling for the Geometry module to initialise.
1140 def __init__(self, algorithm, data_input=None, pre_algorithm=None):
1146 cppname = type(algorithm).__cpp_name__
1148 self.
name = cppname[cppname.rfind(
'::') + 2:]
1171 Simple setup to set the input file names to the algorithm. Applied to the data_input attribute
1172 by default. This simply takes all files returned from the `Calibration.output_patterns` and filters
1173 for only the CollectorOutput.root files. Then it sets them as input files to the CalibrationAlgorithm class.
1175 collector_output_files = list(filter(
lambda file_path:
"CollectorOutput.root" == Path(file_path).name,
1177 info_lines = [f
"Input files used in {self.name}:"]
1178 info_lines.extend(collector_output_files)
1179 B2INFO_MULTILINE(info_lines)
1180 self.
algorithm.setInputFileNames(collector_output_files)
1186 calibration_defaults (dict): A dictionary of default options for calibrations run by this `CAF` instance e.g.
1188 >>> calibration_defaults={"max_iterations":2}
1190 This class holds `Calibration` objects and processes them. It defines the initial configuration/setup
1191 for the calibrations. But most of the real processing is done through the `caf.state_machines.CalibrationMachine`.
1193 The `CAF` class essentially does some initial setup, holds the `CalibrationBase` instances and calls the
1194 `CalibrationBase.start` when the dependencies are met.
1196 Much of the checking for consistency is done in this class so that no processing is done with an invalid
1197 setup. Choosing which files to use as input should be done from outside during the setup of the `CAF` and
1198 `CalibrationBase` instances.
1202 _db_name =
"caf_state.db"
1204 default_calibration_config = {
1205 "max_iterations": 5,
1229 if not calibration_defaults:
1230 calibration_defaults = {}
1239 Adds a `Calibration` that is to be used in this program to the list.
1240 Also adds an empty dependency list to the overall dictionary.
1241 You should not directly alter a `Calibration` object after it has been
1244 if calibration.is_valid():
1248 B2WARNING(f
"Tried to add a calibration with the name {calibration.name} twice.")
1250 B2WARNING(f
"Tried to add incomplete/invalid calibration ({calibration.name}) to the framework."
1251 "It was not added and will not be part of the final process.")
1255 This checks the future and past dependencies of each `Calibration` in the `CAF`.
1256 If any dependencies are not known to the `CAF` then they are removed from the `Calibration`
1259 calibration_names = [calibration.name
for calibration
in self.
calibrations.values()]
1261 def is_dependency_in_caf(dependency):
1263 Quick function to use with filter() and check dependencies against calibrations known to `CAF`
1265 dependency_in_caf = dependency.name
in calibration_names
1266 if not dependency_in_caf:
1267 B2WARNING(f
"The calibration {dependency.name} is a required dependency but is not in the CAF."
1268 " It has been removed as a dependency.")
1269 return dependency_in_caf
1274 filtered_future_dependencies = list(filter(is_dependency_in_caf, calibration.future_dependencies))
1275 calibration.future_dependencies = filtered_future_dependencies
1277 filtered_dependencies = list(filter(is_dependency_in_caf, calibration.dependencies))
1278 calibration.dependencies = filtered_dependencies
1282 - Uses dependency attributes of calibrations to create a dependency dictionary and passes it
1283 to a sorting algorithm.
1284 - Returns valid OrderedDict if sort was successful, empty one if it failed (most likely a cyclic dependency)
1291 future_dependencies_names = [dependency.name
for dependency
in calibration.future_dependencies]
1292 past_dependencies_names = [dependency.name
for dependency
in calibration.dependencies]
1295 self.
dependencies[calibration.name] = past_dependencies_names
1305 full_past_dependencies = past_from_future_dependencies(ordered_full_dependencies)
1308 full_deps = full_past_dependencies[calibration.name]
1309 explicit_deps = [cal.name
for cal
in calibration.dependencies]
1310 for dep
in full_deps:
1311 if dep
not in explicit_deps:
1312 calibration.dependencies.append(self.
calibrations[dep])
1315 ordered_dependency_list = []
1316 for ordered_calibration_name
in order:
1317 if ordered_calibration_name
in [dep.name
for dep
in calibration.dependencies]:
1318 ordered_dependency_list.append(self.
calibrations[ordered_calibration_name])
1319 calibration.dependencies = ordered_dependency_list
1320 order = ordered_full_dependencies
1326 Makes sure that the CAF has a valid backend setup. If one isn't set by the user (or if the
1327 one that is stored isn't a valid Backend object) we should create a default Local backend.
1329 if not isinstance(self.
_backend, caf.backends.Backend):
1335 Checks all current calibrations and removes any invalid Collections from their collections list.
1337 B2INFO(
"Checking for any invalid Collections in Calibrations.")
1339 valid_collections = {}
1340 for name, collection
in calibration.collections.items():
1341 if collection.is_valid():
1342 valid_collections[name] = collection
1344 B2WARNING(f
"Removing invalid Collection '{name}' from Calibration '{calibration.name}'.")
1345 calibration.collections = valid_collections
1350 iov(`caf.utils.IoV`): IoV to calibrate for this processing run. Only the input files necessary to calibrate
1351 this IoV will be used in the collection step.
1353 This function runs the overall calibration job, saves the outputs to the output_dir directory,
1354 and creates database payloads.
1356 Upload of final databases is not done here. This simply creates the local databases in
1357 the output directory. You should check the validity of your new local database before uploading
1358 to the conditions DB via the basf2 tools/interface to the DB.
1361 B2FATAL(
"There were no Calibration objects to run. Maybe you tried to add invalid ones?")
1365 B2FATAL(
"Couldn't order the calibrations properly. Could be a cyclic dependency.")
1382 db_initial_calibrations = db.query(
"select * from calibrations").fetchall()
1386 calibration._db_path = self.
_db_path
1387 calibration.output_database_dir = Path(self.
output_dir, calibration.name,
"outputdb").as_posix()
1388 calibration.iov = iov
1389 if not calibration.backend:
1390 calibration.backend = self.
backend
1392 if calibration.name
not in [db_cal[0]
for db_cal
in db_initial_calibrations]:
1393 db.insert_calibration(calibration.name)
1396 for cal_info
in db_initial_calibrations:
1397 if cal_info[0] == calibration.name:
1398 cal_initial_state = cal_info[2]
1399 cal_initial_iteration = cal_info[3]
1400 B2INFO(f
"Previous entry in database found for {calibration.name}.")
1401 B2INFO(f
"Setting {calibration.name} state to checkpoint state '{cal_initial_state}'.")
1402 calibration.state = cal_initial_state
1403 B2INFO(f
"Setting {calibration.name} iteration to '{cal_initial_iteration}'.")
1404 calibration.iteration = cal_initial_iteration
1406 calibration.daemon =
True
1413 keep_running =
False
1415 remaining_calibrations = []
1419 if (calibration.state == CalibrationBase.end_state
or calibration.state == CalibrationBase.fail_state):
1421 if calibration.is_alive():
1422 B2DEBUG(29, f
"Joining {calibration.name}.")
1425 if calibration.dependencies_met():
1426 if not calibration.is_alive():
1427 B2DEBUG(29, f
"Starting {calibration.name}.")
1430 except RuntimeError:
1433 B2DEBUG(29, f
"{calibration.name} probably just finished, join it later.")
1434 remaining_calibrations.append(calibration)
1436 if not calibration.failed_dependencies():
1437 remaining_calibrations.append(calibration)
1438 if remaining_calibrations:
1443 for calibration
in remaining_calibrations:
1444 for job
in calibration.jobs_to_submit[:]:
1445 calibration.backend.submit(job)
1446 calibration.jobs_to_submit.remove(job)
1449 B2INFO(
"Printing summary of final CAF status.")
1450 with CAFDB(self.
_db_path, read_only=
True)
as db:
1451 print(db.output_calibration_table())
1456 The `backend <backends.Backend>` that runs the collector job.
1457 When set, this is checked that a `backends.Backend` class instance was passed in.
1465 if isinstance(backend, caf.backends.Backend):
1468 B2ERROR(
'Backend property must inherit from Backend class.')
1472 Creates the output directory. If it already exists we are now going to try and restart the program from the last state.
1475 str: The absolute path of the new output_dir
1479 B2INFO(f
"{p.as_posix()} output directory already exists. "
1480 "We will try to restart from the previous finishing state.")
1483 p.mkdir(parents=
True)
1487 raise FileNotFoundError(f
"Attempted to create output_dir {p.as_posix()}, but it didn't work.")
1491 Creates the CAF status database. If it already exists we don't overwrite it.
1495 B2INFO(f
"Previous CAF database found {self._db_path}")
pre_algorithm
Function called after data_input but before algorithm.execute to do any remaining setup.
__init__(self, algorithm, data_input=None, pre_algorithm=None)
data_input
Function called before the pre_algorithm method to setup the input data that the CalibrationAlgorithm...
dict params
Parameters that could be used in the execution of the algorithm strategy/runner to modify behaviour.
algorithm
CalibrationAlgorithm instance (assumed to be true since the Calibration class checks)
strategy
The algorithm stratgey that will be used when running over the collected data.
default_inputdata_setup(self, input_file_paths)
dict dependencies
Dictionary of dependencies of Calibration objects, where value is the list of Calibration objects tha...
add_calibration(self, calibration)
_remove_missing_dependencies(self)
_order_calibrations(self)
int heartbeat
The heartbeat (seconds) between polling for Calibrations that are finished.
dict default_calibration_config
The defaults for Calibrations.
dict calibrations
Dictionary of calibrations for this CAF instance.
dict calibration_defaults
Default options applied to each calibration known to the CAF, if the Calibration has these defined by...
_backend
Private backend attribute.
dict future_dependencies
Dictionary of future dependencies of Calibration objects, where the value is all calibrations that wi...
_db_path
The path of the SQLite DB.
order
The ordering and explicit future dependencies of calibrations.
__init__(self, calibration_defaults=None)
str _db_name
The name of the SQLite DB that gets created.
_prune_invalid_collections(self)
str output_dir
Output path to store results of calibration and bookkeeping information.
list input_files
Files used for collection procedure.
list dependencies
List of calibration objects, where each one is a dependency of this one.
failed_dependencies(self)
dict files_to_iovs
File -> Iov dictionary, should be :
__init__(self, name, input_files=None)
_apply_calibration_defaults(self, defaults)
list future_dependencies
List of calibration objects that depend on this one.
str end_state
The name of the successful completion state.
str fail_state
The name of the failure state.
bool save_payloads
Marks this Calibration as one which has payloads that should be copied and uploaded.
list jobs_to_submit
A simple list of jobs that this Calibration wants submitted at some point.
str output_database_dir
The directory where we'll store the local database payloads from this calibration.
name
Name of calibration object.
depends_on(self, calibration)
iov
IoV which will be calibrated.
ignored_runs
List of ExpRun that will be ignored by this Calibration.
use_central_database(self, global_tag, apply_to_default_collection=True)
list database_chain
The database chain that is applied to the algorithms.
strategies
The strategy that the algorithm(s) will be run against.
dict results
Output results of algorithms for each iteration.
int heartbeat
This calibration's sleep time before rechecking to see if it can move state.
int collector_full_update_interval
While checking if the collector is finished we don't bother wastefully checking every subjob's status...
machine
The caf.state_machines.CalibrationMachine that we will run to process this calibration start to finis...
list checkpoint_states
Checkpoint states which we are allowed to restart from.
_db_path
Location of a SQLite database that will save the state of the calibration so that it can be restarted...
max_iterations
Variable to define the maximum number of iterations for this calibration specifically.
use_local_database(self, filename, directory="", apply_to_default_collection=True)
_get_default_collection_attribute(self, attr)
list _algorithms
Internal calibration algorithms stored for this calibration.
reset_database(self, apply_to_default_collection=True)
add_collection(self, name, collection)
algorithms
Algorithm classes that will be run by this Calibration.
backend
The backend <backends.Backend> we'll use for our collector submission in this calibration.
algorithms_runner
The class that runs all the algorithms in this Calibration using their assigned :py:class:caf....
max_files_per_collector_job(self)
dict collections
Collections stored for this calibration.
__init__(self, name, collector=None, algorithms=None, input_files=None, pre_collector_path=None, database_chain=None, output_patterns=None, max_files_per_collector_job=None, max_collector_jobs=None, backend_args=None)
str default_collection_name
Default collection name.
_set_default_collection_attribute(self, attr, value)
list job_cmd
The Collector caf.backends.Job.cmd attribute.
int default_max_collector_jobs
The default maximum number of collector jobs to create.
list input_files
Internal input_files stored for this calibration.
dict backend_args
Dictionary passed to the collector Job object to configure how the caf.backends.Backend instance shou...
_collector
Internal storage of collector attribute.
dict files_to_iovs
File -> Iov dictionary, should be :
list database_chain
The database chain used for this Collection.
__init__(self, collector=None, input_files=None, pre_collector_path=None, database_chain=None, output_patterns=None, max_files_per_collector_job=None, max_collector_jobs=None, backend_args=None)
list output_patterns
Output patterns of files produced by collector which will be used to pass to the Algorithm....
splitter
The SubjobSplitter to use when constructing collector subjobs from the overall Job object.
_input_files
set input files
pre_collector_path
Since many collectors require some different setup, if you set this attribute to a basf2....
max_files_per_collector_job(self)
collector
Collector module of this collection.
uri_list_from_input_file(input_file)
use_local_database(self, filename, directory="")
use_central_database(self, global_tag)