13from concurrent.futures
import ThreadPoolExecutor
18from conditions_db
import cli_download, ConditionsDB, encode_name
19from softwaretrigger
import db_access
23 """Small helper class as the difflib does not understand dicts directly (as they are not hashable)"""
26 """Create a hash for the object out of the json string"""
27 return hash(json.dumps(self))
31 """Helper class to translate the user-specified database(s) into parameters for basf2"""
34 """Init the stored databases and exp/run from the specified command argument"""
43 split_argument = command_argument.split(
":")
44 if len(split_argument) == 2:
45 command_argument, exp_run = split_argument
47 if exp_run !=
"latest":
51 raise argparse.ArgumentTypeError(
52 f
"Do not understand the exp/run argument '{exp_run}'")
54 elif len(split_argument) != 1:
55 raise argparse.ArgumentTypeError(
56 f
"Do not understand the database argument '{command_argument}'")
59 self.
_database = command_argument.split(
",")
62 def normalize(database):
64 if os.path.exists(database):
65 if os.path.basename(database) !=
"database.txt":
66 database = os.path.join(database,
"database.txt")
74 Set the basf2 database chain according to the specified databases.
75 Before that, clean up and invalidate everything from th database.
77 The distinction between file databases and global databases is done
78 via the fact of a file/folder with this name exists or not.
80 from ROOT
import Belle2
83 basf2.conditions.override_globaltags()
86 if os.path.exists(database):
87 basf2.conditions.prepend_testing_payloads(database)
89 basf2.conditions.prepend_globaltag(database)
91 db_access.set_event_number(evt_number=0, run_number=int(self.
_run),
96 Get all cuts stored in the database(s)
97 and sort them according to base_identifier, cut_identifier.
101 all_cuts = db_access.get_all_cuts()
102 all_cuts = sorted(all_cuts,
103 key=
lambda cut: (cut[
"Base Identifier"], cut[
"Cut Identifier"]))
104 all_cuts = list(
map(HashableCut, all_cuts))
108def diff_function(args):
110 Show the diff between two specified databases.
112 first_database_cuts = args.first_database.get_all_cuts()
113 second_database_cuts = args.second_database.get_all_cuts()
115 diff = difflib.SequenceMatcher(
116 a=list(
map(str, first_database_cuts)), b=list(
map(str, second_database_cuts)))
118 def print_cut(cut, prefix=" "):
120 print(
"\x1b[31m", end=
"")
122 print(
"\x1b[32m", end=
"")
124 print(
"\x1b[0m", end=
"")
126 def print_cuts(prefix, cuts):
130 for tag, i1, i2, j1, j2
in diff.get_opcodes():
132 if args.only_changes:
134 print_cuts(
" ", diff.b[j1:j2])
135 if tag
in [
"delete",
"replace"]:
136 print_cuts(
"-", diff.a[i1:i2])
137 if tag
in [
"insert",
"replace"]:
138 print_cuts(
"+", diff.b[j1:j2])
141def add_cut_function(args):
143 Add a cut with the given parameters and also add it to the trigger menu.
145 args.database.set_database()
147 db_access.upload_cut_to_db(cut_string=args.cut_string, base_identifier=args.base_identifier,
148 cut_identifier=args.cut_identifier, prescale_factor=args.prescale_factor,
149 reject_cut=args.reject_cut.lower() ==
"true", iov=
None)
150 trigger_menu = db_access.download_trigger_menu_from_db(args.base_identifier,
151 do_set_event_number=
False)
152 if trigger_menu
is None:
153 print(f
"Trigger menu '{args.base_identifier}' not found. Creating a new one.")
155 db_access.upload_trigger_menu_to_db(args.base_identifier, [args.cut_identifier], accept_mode=
True, iov=
None)
157 cuts = [str(cut)
for cut
in trigger_menu.getCutIdentifiers()]
159 if args.cut_identifier
not in cuts:
160 cuts.append(args.cut_identifier)
162 db_access.upload_trigger_menu_to_db(args.base_identifier, cuts,
163 accept_mode=trigger_menu.isAcceptMode(), iov=
None)
166def remove_cut_function(args):
168 Remove a cut with the given name from the trigger menu.
170 args.database.set_database()
172 trigger_menu = db_access.download_trigger_menu_from_db(
173 args.base_identifier, do_set_event_number=
False)
174 cuts = [str(cut)
for cut
in trigger_menu.getCutIdentifiers()
if str(cut) != args.cut_identifier]
176 db_access.upload_trigger_menu_to_db(
177 args.base_identifier, cuts, accept_mode=trigger_menu.isAcceptMode(), iov=
None)
180def print_function(args):
182 Print the cuts stored in the database(s).
184 cuts = args.database.get_all_cuts()
185 df = pd.DataFrame(cuts)
187 if args.format ==
"pandas":
188 pd.set_option(
"display.max_rows", 500)
189 pd.set_option(
"display.max_colwidth", 200)
190 pd.set_option(
'display.max_columns', 500)
191 pd.set_option(
'display.width', 1000)
193 elif args.format
in [
"github",
"gitlab"]:
194 from tabulate
import tabulate
195 print(tabulate(df, tablefmt=
"github", showindex=
False, headers=
"keys"))
196 elif args.format ==
"grid":
197 from tabulate
import tabulate
198 print(tabulate(df, tablefmt=
"grid", showindex=
False, headers=
"keys"))
199 elif args.format ==
"json":
201 print(json.dumps(df.to_dict(
"records"), indent=2))
202 elif args.format ==
"list":
203 for base_identifier, cuts
in df.groupby(
"Base Identifier"):
204 for _, cut
in cuts.iterrows():
205 print(cut[
"Base Identifier"], cut[
"Cut Identifier"])
206 elif args.format ==
"human-readable":
207 print(
"Currently, the following menus and triggers are in the database")
208 for base_identifier, cuts
in df.groupby(
"Base Identifier"):
209 print(base_identifier)
211 print(
"\tUsed triggers:\n\t\t" +
212 ", ".join(list(cuts[
"Cut Identifier"])))
213 print(
"\tIs in accept mode:\n\t\t" +
214 str(cuts[
"Reject Menu"].iloc[0]))
215 for _, cut
in cuts.iterrows():
216 print(
"\t\tCut Name:\n\t\t\t" + cut[
"Cut Identifier"])
217 print(
"\t\tCut condition:\n\t\t\t" + cut[
"Cut Condition"])
218 print(
"\t\tCut prescaling\n\t\t\t" +
219 str(cut[
"Cut Prescaling"]))
220 print(
"\t\tCut is a reject cut:\n\t\t\t" +
221 str(cut[
"Reject Cut"]))
224 raise AttributeError(f
"Do not understand format {args.format}")
227def create_script_function(args):
229 Print the b2hlt_trigger commands to create a lobal database copy.
231 cuts = args.database.get_all_cuts()
232 df = pd.DataFrame(cuts)
234 sfmt =
'b2hlt_triggers add_cut \
235"{Base Identifier}" "{Cut Identifier}" "{Cut Condition}" "{Cut Prescaling}" "{Reject Cut}"'.format
236 if args.filename
is None:
237 df.apply(
lambda x: print(sfmt(**x)), 1)
239 with open(args.filename,
'w')
as f:
240 df.apply(
lambda x: f.write(sfmt(**x) +
'\n'), 1)
243def iov_includes(iov_list, exp, run):
245 Comparison function between two IoVs (start, end) stored in the database and
246 the given exp/run combination.
249 copied_iov_list = iov_list[2:]
250 copied_iov_list = list(
map(
lambda x: x
if x != -1
else float(
"inf"), copied_iov_list))
252 exp_start, run_start, exp_end, run_end = copied_iov_list
254 return (exp_start, run_start) <= (exp, run) <= (exp_end, run_end)
257def download_function(args):
259 Download the trigger cuts in the given database to disk and set their IoV to infinity.
261 if len(args.database._database) != 1:
262 raise AttributeError(
"Can only download from a single database! Please do not specify more than one.")
264 global_tag = args.database._database[0]
267 os.makedirs(args.destination, exist_ok=
True)
270 req = db.request(
"GET", f
"/globalTag/{encode_name(global_tag)}/globalTagPayloads",
271 f
"Downloading list of payloads for {global_tag} tag")
274 for payload
in req.json():
275 name = payload[
"payloadId"][
"basf2Module"][
"name"]
276 if not name.startswith(
"software_trigger_cut"):
279 local_file, remote_file, checksum, iovlist = cli_download.check_payload(args.destination, payload)
281 new_iovlist = list(filter(
lambda iov: iov_includes(iov, args.database._experiment, args.database._run), iovlist))
285 if local_file
in download_list:
286 download_list[local_file][-1] += iovlist
288 download_list[local_file] = [local_file, remote_file, checksum, iovlist]
293 with ThreadPoolExecutor(max_workers=20)
as pool:
294 for iovlist
in pool.map(
lambda x: cli_download.download_file(db, *x), download_list.values()):
299 full_iovlist += iovlist
302 for iov
in sorted(full_iovlist):
304 iov = [iov[0], iov[1], 0, 0, -1, -1]
305 dbfile.append(
"dbstore/{} {} {},{},{},{}\n".format(*iov))
306 with open(os.path.join(args.destination,
"database.txt"),
"w")
as txtfile:
307 txtfile.writelines(dbfile)
312 Main function to be called from b2hlt_triggers.
314 parser = argparse.ArgumentParser(
316Execute different actions on stored trigger menus in the database.
318Call with `%(prog)s [command] --help` to get a description on each command.
319Please also see the examples at the end of this help.
321Many commands require one (or many) specified databases. Different formats are possible.
322All arguments need to be written in quotation marks.
323* "online" Use the latest version in the "online" database
324 (or any other specified global tag).
325* "online:latest" Same as just "online", makes things a bit clearer.
326* "online:8/345" Use the version in the "online" database (or any other specified global tag)
327 which was present in exp 8 run 345.
328* "localdb:4/42" Use the local database specified in the given folder for the given exp/run.
329* "localdb/database.txt" It is also possible to specify a file directly.
330* "online,localdb" First look in localdb, then in the online GT
331* "online,localdb:9/1" Can also be combined with the exp/run (It is then valid for all database accesses)
335* Check what has changed between 8/1 and 9/1 in the online GT.
337 %(prog)s diff --first-database "online:8/1" --second-database "online:9/1" --only-changes
339* Especially useful while editing trigger cuts and menus: check what has changed between the latest
340 version online and what is currently additionally in localdb
342 %(prog)s diff --first-database "online:latest" --second-database "online,localdb:latest"
344 This use case is so common, it is even the default
348* Print the latest version of the cuts in online (plus what is defined in the localdb) in a human-friendly way
352* Print the version of the cuts which was present in 8/1 online in a format understandable by GitLab
353 (you need to have the tabulate package installed)
355 %(prog)s print --database "online:8/1" --format human-readable
357* Add a new skim cut named "accept_b2bcluster_3D" with the specified parameters and upload it to localdb
359 %(prog)s add_cut skim accept_b2bcluster_3D "[[nB2BCC3DLE >= 1] and [G1CMSBhabhaLE < 2]]" 1 False
361* Remove the cut "accept_bhabha" from the trigger menu "skim"
363 %(prog)s remove_cut skim accept_bhabha
365* Download the latest state of the triggers into the folder "localdb", e.g. to be used for local studies
370 formatter_class=argparse.RawDescriptionHelpFormatter,
371 usage=
"%(prog)s command"
373 parser.set_defaults(func=
lambda *args: parser.print_help())
374 subparsers = parser.add_subparsers(title=
"command",
375 description=
"Choose the command to execute")
378 diff_parser = subparsers.add_parser(
"diff", help=
"Compare the trigger menu in two different databases.",
379 formatter_class=argparse.RawDescriptionHelpFormatter,
381Compare the two trigger menus present in the two specified databases
382(or database chains) for the given exp/run combination (or the latest
384Every line in the output is one trigger line. A "+" in front means the
385trigger line is present in the second database, but not in the first.
386A "-" means exactly the opposite. Updates trigger lines will show up
387as both "-" and "+" (with different parameters).
389The two databases (or database chains) can be specified as describes
390in the general help (check b2hlt_triggers --help).
391By default, the latest version of the online database will be
392compared with what is defined on top in the localdb.
394 diff_parser.add_argument(
"--first-database", help=
"First database to compare. Defaults to 'online:latest'.",
396 diff_parser.add_argument(
"--second-database", help=
"Second database to compare. Defaults to 'online,localdb:latest'.",
398 diff_parser.add_argument(
399 "--only-changes", help=
"Do not show unchanged lines.", action=
"store_true")
400 diff_parser.set_defaults(func=diff_function)
403 print_parser = subparsers.add_parser(
"print", help=
"Print the cuts stored in the given database.",
404 formatter_class=argparse.RawDescriptionHelpFormatter,
406Print the defined trigger menu and trigger cuts in a human-friendly
407(default) or machine-friendly way.
408The database (or database chain) needs to be specified in the general
409help (check b2hlt_triggers --help).
411For additional formatting options please install the tabulate package with
413 pip3 install --user tabulate
415By default the latest version on the online database and what is defined on
416top in the localdb will be shown.
418 print_parser.add_argument(
"--database", help=
"Which database to print. Defaults to 'online,localdb:latest'.",
420 choices = [
"human-readable",
"json",
"list",
"pandas"]
422 from tabulate
import tabulate
423 choices += [
'github',
'gitlab',
'grid']
426 print_parser.add_argument(
"--format", help=
"Choose the format how to print the trigger cuts. "
427 "To get access to more options please install the tabulate package using pip",
428 choices=choices, default=
"human-readable")
429 print_parser.set_defaults(func=print_function)
432 create_script_parser = subparsers.add_parser(
434 help=
"Create b2hlt_triggers command to create a online globaltag copy.",
435 formatter_class=argparse.RawDescriptionHelpFormatter,
437Generate the required b2hlt_trigger commands to reproduce an online globaltag for a given exp/run
438number to create a local database version of it.
440 create_script_parser.add_argument(
"--database", help=
"Which database to print. Defaults to 'online:latest'.",
442 create_script_parser.add_argument(
"--filename", default=
None,
443 help=
"Write to given filename instead of stdout.")
444 create_script_parser.set_defaults(func=create_script_function)
447 add_cut_parser = subparsers.add_parser(
"add_cut", help=
"Add a new cut.",
448 formatter_class=argparse.RawDescriptionHelpFormatter,
450Add a cut with the given properties and upload it into the localdb database.
451After that, you can upload it to the central database, to e.g. staging_online.
453As a base line for editing, a database much be specified in the usual format
454(check b2hlt_triggers --help).
455It defaults to the latest version online and the already present changes in
457Please note that the IoV of the created trigger line and menu is set to infinite.
459 add_cut_parser.add_argument(
"--database", help=
"Where to take the trigger menu from. Defaults to 'online,localdb:latest'.",
461 add_cut_parser.add_argument(
"base_identifier",
462 help=
"base_identifier of the cut to add", choices=[
"prefilter",
"filter",
"skim"])
463 add_cut_parser.add_argument(
"cut_identifier",
464 help=
"cut_identifier of the cut to add")
465 add_cut_parser.add_argument(
"cut_string",
466 help=
"cut_string of the cut to add")
467 add_cut_parser.add_argument(
"prescale_factor", type=int,
468 help=
"prescale of the cut to add")
469 add_cut_parser.add_argument(
470 "reject_cut", help=
"Is the new cut a reject cut?")
471 add_cut_parser.set_defaults(func=add_cut_function)
474 remove_cut_parser = subparsers.add_parser(
"remove_cut", help=
"Remove a cut of the given name.",
475 formatter_class=argparse.RawDescriptionHelpFormatter,
477Remove a cut with the given base and cut identifier from the trigger menu
478and upload the new trigger menu to the localdb.
479After that, you can upload it to the central database, to e.g. staging_online.
481As a base line for editing, a database much be specified in the usual format
482(check b2hlt_triggers --help).
483It defaults to the latest version online and the already present changes in
485Please note that the IoV of the created trigger menu is set to infinite.
487The old cut payload will not be deleted from the database. This is not
488needed as only cuts specified in a trigger menu are used.
490 remove_cut_parser.add_argument(
"base_identifier",
491 help=
"base_identifier of the cut to delete", choices=[
"prefilter",
"filter",
"skim"])
492 remove_cut_parser.add_argument(
"cut_identifier",
493 help=
"cut_identifier of the cut to delete")
494 remove_cut_parser.add_argument(
"--database",
495 help=
"Where to take the trigger menu from. Defaults to 'online,localdb:latest'.",
497 remove_cut_parser.set_defaults(func=remove_cut_function)
500 download_parser = subparsers.add_parser(
"download", help=
"Download the trigger menu from the database.",
501 formatter_class=argparse.RawDescriptionHelpFormatter,
503Download all software trigger related payloads from the specified database
504into the folder localdb and create a localdb/database.txt. This is
505especially useful when doing local trigger studies which should use the
506latest version of the online triggers. By default, the latest
507version of the online GT will be downloaded.
509Attention: this script will override a database defined in the destination
510folder (default localdb)!
511Attention 2: all IoVs of the downloaded triggers will be set to 0, 0, -1, -1
512so you can use the payloads from your local studies for whatever run you want.
513This should not (never!) be used to upload or edit new triggers and
514is purely a convenience function to synchronize your local studies
515with the online database!
517Please note that for this command you can only specify a single database
518(all others can work with multiple databases).
520 download_parser.add_argument(
"--database",
521 help=
"Single database where to take the trigger menu from. Defaults to 'online:latest'.",
523 download_parser.add_argument(
"--destination",
524 help=
"In which folder to store the output", default=
"localdb")
525 download_parser.set_defaults(func=download_function)
527 args = parser.parse_args()
int _experiment
the experiment number, default (= latest) is 99999
__init__(self, command_argument)
int _run
the run number, default (= latest) is 99999
list _database
the specified databases
static DBStore & Instance()
Instance of a singleton DBStore.