openmapp-analyses 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+ """
2
+ openmapp-analyses: combine the analysis lists of tools such as Rivet, SModelS and CheckMATE,
3
+ and search them offline.
4
+
5
+ Python use:
6
+ >>> from openmapp_analyses import load, search
7
+ >>> data = load() # the locally saved database
8
+ >>> papers = search(data, tools=["SModelS", "CheckMATE"])
9
+ """
10
+
11
+ __version__ = "1.0.0"
12
+
13
+ from .combine import build_database # noqa: E402,F401
14
+ from .store import load, save, data_file # noqa: E402,F401
15
+ from .search import search, find_tool_name # noqa: E402,F401
@@ -0,0 +1,6 @@
1
+ """Allows running the tool as `python -m openmapp_analyses ...`."""
2
+ import sys
3
+
4
+ from .cli import main
5
+
6
+ sys.exit(main())
@@ -0,0 +1,81 @@
1
+ """
2
+ Analysis IDs from the current arXiv comment, for papers that have no ID yet.
3
+
4
+ INSPIRE keeps the comment of the first arXiv version; the link to the experiment's result page
5
+ (e.g. ".../Atlas/GROUPS/PHYSICS/PAPERS/<ID>") is sometimes only added in a later version.
6
+ arXiv's API is asked about many papers per request, with the 3 s pause arXiv asks for.
7
+
8
+ API documentation: https://info.arxiv.org/help/api/user-manual.html
9
+ """
10
+
11
+ import re
12
+ import time
13
+ import urllib.parse
14
+ import urllib.request
15
+ import xml.etree.ElementTree as ET
16
+
17
+ from .inspire import analysis_ids_from_links
18
+
19
+ API_URL = "https://export.arxiv.org/api/query"
20
+ BATCH_SIZE = 50
21
+ PAUSE = 3.0
22
+ NS = {"atom": "http://www.w3.org/2005/Atom", "arxiv": "http://arxiv.org/schemas/atom"}
23
+
24
+
25
+ def _get_text(url, timeout=60):
26
+ req = urllib.request.Request(url, headers={"User-Agent": "openmapp-analyses"})
27
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
28
+ return resp.read().decode("utf-8")
29
+
30
+
31
+ def _arxiv_number(entry_id):
32
+ """'http://arxiv.org/abs/1103.2929v2' -> '1103.2929'."""
33
+ number = entry_id.split("/abs/", 1)[-1]
34
+ return number.rsplit("v", 1)[0] if number.rsplit("v", 1)[-1].isdigit() else number
35
+
36
+
37
+ def fetch_comments(arxiv_ids, get_text=_get_text, sleep=time.sleep):
38
+ """Return {arXiv number: comment} for the given arXiv numbers."""
39
+ comments = {}
40
+ for b in range(0, len(arxiv_ids), BATCH_SIZE):
41
+ if b:
42
+ sleep(PAUSE)
43
+ ids = arxiv_ids[b:b + BATCH_SIZE]
44
+ url = API_URL + "?" + urllib.parse.urlencode({"id_list": ",".join(ids), "max_results": len(ids)})
45
+ root = ET.fromstring(get_text(url))
46
+ for entry in root.findall("atom:entry", NS):
47
+ entry_id = entry.findtext("atom:id", default="", namespaces=NS)
48
+ comment = entry.findtext("arxiv:comment", default="", namespaces=NS)
49
+ if entry_id and comment:
50
+ comments[_arxiv_number(entry_id)] = re.sub(r"\s*\n\s*", "", comment)
51
+ return comments
52
+
53
+
54
+ ID_IN_REPORT_NUMBER = re.compile(r"^(ATLAS|CMS|LHCb|ALICE)-(PAS-)?[A-Z0-9]+-\d{2,4}-\d{2,4}$", re.I)
55
+
56
+
57
+ def add_ids_from_arxiv(database, log=print, fetch=None):
58
+ """Add analysis IDs from arXiv to papers that have an arXiv number but no ID yet."""
59
+ fetch = fetch or fetch_comments
60
+ todo = {}
61
+ for a in database["analyses"]:
62
+ info = a.get("inspire", {})
63
+ if not info.get("arXiv_id") or info.get("analysis_ids"):
64
+ continue
65
+ if any(ID_IN_REPORT_NUMBER.match(r) for r in info.get("report_numbers", [])):
66
+ continue
67
+ todo[info["arXiv_id"]] = info
68
+ if not todo:
69
+ return
70
+ try:
71
+ comments = fetch(list(todo))
72
+ except Exception as exc:
73
+ log(f" arXiv: could not be reached ({type(exc).__name__}: {exc}); skipped")
74
+ return
75
+ found = 0
76
+ for number, info in todo.items():
77
+ ids = analysis_ids_from_links(comments.get(number, ""))
78
+ if ids:
79
+ info["analysis_ids"] = ids
80
+ found += 1
81
+ log(f" arXiv: {len(todo)} papers without an analysis ID checked, {found} found")
@@ -0,0 +1,422 @@
1
+ """
2
+ The `openmapp-analyses` command.
3
+
4
+ openmapp-analyses update download all tool files (needs internet), save locally
5
+ openmapp-analyses tools list the tools and how many papers each covers
6
+ openmapp-analyses search [conditions] find papers (offline)
7
+ openmapp-analyses sources the list of tools, from HEPData's config.py
8
+
9
+ Run `openmapp-analyses <command> --help` for the options of each command.
10
+ """
11
+
12
+ import argparse
13
+ import json
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ from . import __version__
18
+ from .combine import add_inspire_info, build_database, keep_previous, validate
19
+ from .hepdata_models import model_sources
20
+ from .hepdata_sources import HEPDATA_CONFIG_URL, resolve_sources
21
+ from .inspire import normalise_arxiv
22
+ from .search import find_tool_name, search
23
+ from .store import NoDatabaseError, data_dir, data_file, load, save
24
+
25
+ ORIGIN_WORDS = {
26
+ "hepdata": "HEPData's config.py",
27
+ "hepdata-saved": "HEPData's config.py, copy saved by an earlier update",
28
+ "packaged": "the list packaged with openmapp-analyses",
29
+ "file": "a file given with --sources",
30
+ }
31
+
32
+
33
+ def _folder(args):
34
+ """Where the database, hepdata_config.py and sources.json are kept."""
35
+ return Path(args.data).expanduser().resolve().parent if args.data else data_dir()
36
+
37
+
38
+
39
+ def _short(text, width):
40
+ text = str(text)
41
+ return text if len(text) <= width else text[: width - 1] + "…"
42
+
43
+
44
+ def _label(analysis):
45
+ """A human-readable name for a paper: the analysis ID if a tool gives one, else the INSPIRE title."""
46
+ for key in ("ana_id", "pretty_name"):
47
+ for entry in analysis["tools"].values():
48
+ value = entry.get("analysis_info", {}).get(key)
49
+ if value:
50
+ return str(value)
51
+ if analysis.get("inspire", {}).get("title"):
52
+ return analysis["inspire"]["title"]
53
+ for entry in analysis["tools"].values():
54
+ if entry.get("analysis_info", {}).get("title"):
55
+ return str(entry["analysis_info"]["title"])
56
+ for entry in analysis["tools"].values():
57
+ for impl in entry["implementations"]:
58
+ if impl.get("name"):
59
+ return impl["name"]
60
+ return ""
61
+
62
+
63
+ def _n_impl(entry):
64
+ return len(entry["implementations"])
65
+
66
+
67
+ def _papers(n):
68
+ return f"{n} paper" if n == 1 else f"{n} papers"
69
+
70
+
71
+ def _warn_unread_tools(database, names):
72
+ """Warn if a tool the user searched for could not be read in the last update."""
73
+ for name in names:
74
+ tool = find_tool_name(database, name)
75
+ report = database["sources"][tool]
76
+ if report["status"] == "error":
77
+ print(f"Warning: {tool} could not be read in the last update, so it has no data. "
78
+ f"Run 'openmapp-analyses update' again.", file=sys.stderr)
79
+ elif report["status"] == "kept":
80
+ print(f"Note: {tool} data is from an earlier update ({report.get('kept_from')}); "
81
+ f"its file could not be read in the last update.", file=sys.stderr)
82
+
83
+
84
+ # Commands
85
+
86
+ def cmd_update(args):
87
+ print("Getting the list of tools:")
88
+ # --local is for offline testing: it never downloads HEPData's config.py
89
+ use_hepdata = not args.no_hepdata and not args.local
90
+ tools, tool_list = resolve_sources(_folder(args), sources_file=args.sources, use_hepdata=use_hepdata)
91
+ tools.update(model_sources())
92
+
93
+ print("Reading tool files:")
94
+ database = build_database(tools, local_dir=args.local)
95
+ database["tool_list"] = tool_list
96
+
97
+ try:
98
+ previous = load(args.data)
99
+ except (NoDatabaseError, ValueError):
100
+ previous = None
101
+ if not args.strict:
102
+ for tool in keep_previous(database, previous):
103
+ print(f" KEPT {tool:15s} could not be read now; keeping its data from the previous update")
104
+
105
+ if args.no_inspire:
106
+ database["inspire_status"] = {"status": "skipped"}
107
+ else:
108
+ print("Adding paper information from INSPIRE:")
109
+ status = add_inspire_info(database, previous, refresh=args.refresh_inspire)
110
+ print(f" INSPIRE: information for {status['n_with_info']} of {len(database['analyses'])} papers")
111
+
112
+ errors = validate(database)
113
+ if errors:
114
+ print("The combined data does NOT follow the schema:")
115
+ for e in errors[:20]:
116
+ print(" " + e)
117
+ print("Nothing was saved; your previous database is unchanged.")
118
+ return 1
119
+
120
+ failed = [t for t, r in database["sources"].items() if r["status"] != "ok"]
121
+ if failed and args.strict:
122
+ print(f"Failed tools: {', '.join(failed)} (--strict: nothing saved)")
123
+ return 1
124
+
125
+ path = save(database, args.data)
126
+ n_multi = sum(1 for a in database["analyses"] if len(a["tools"]) > 1)
127
+ print(f"Saved {_papers(len(database['analyses']))} ({n_multi} in more than one tool) to {path}")
128
+ if failed:
129
+ print(f"Warning: could not read {', '.join(failed)}; run 'openmapp-analyses tools' for details.")
130
+ return 0
131
+
132
+
133
+ def cmd_tools(args):
134
+ database = load(args.data)
135
+ if args.json:
136
+ print(json.dumps(database["sources"], indent=2, ensure_ascii=False))
137
+ return 0
138
+ print(f"Database: {args.data or data_file()}")
139
+ print(f"Last update: {database['date_created']}")
140
+ tool_list = database.get("tool_list")
141
+ if tool_list:
142
+ when = f", retrieved {tool_list['retrieved']}" if tool_list.get("retrieved") else ""
143
+ print(f"Tool list: {ORIGIN_WORDS.get(tool_list['origin'], tool_list['origin'])}{when}")
144
+ if tool_list.get("error"):
145
+ print(f" (HEPData's config.py could not be read: {_short(tool_list['error'], 60)})")
146
+ print()
147
+ print(f"{'Tool':16s} {'Papers':>7s} {'Impl.':>6s} {'Format':7s} {'Version':18s} Status")
148
+ print("-" * 71)
149
+ for tool, r in database["sources"].items():
150
+ if r["status"] in ("ok", "kept"):
151
+ status = "ok" if r["status"] == "ok" else f"kept from {(r.get('kept_from') or '?')[:10]}"
152
+ print(f"{tool:16s} {r['n_analyses']:7d} {r['n_implementations']:6d} {r['format']:7s} "
153
+ f"{_short(r.get('version') or '-', 18):18s} {status}")
154
+ else:
155
+ print(f"{tool:16s} {'-':>7s} {'-':>6s} {'-':7s} {'-':18s} ERROR: {_short(r['error'], 40)}")
156
+ print(f"\nTotal: {_papers(len(database['analyses']))}")
157
+ inspire = database.get("inspire_status", {"status": "skipped"})
158
+ if inspire["status"] == "skipped":
159
+ print("INSPIRE information: not added (run 'openmapp-analyses update' without --no-inspire)")
160
+ elif inspire["status"] == "ok":
161
+ print(f"INSPIRE information: {inspire.get('n_with_info', 0)} papers")
162
+ else:
163
+ error = _short(inspire.get("error", ""), 60)
164
+ if inspire.get("n_with_info"):
165
+ print(f"INSPIRE information: {inspire['n_with_info']} papers, from an earlier update "
166
+ f"(INSPIRE could not be reached last time: {error})")
167
+ else:
168
+ print(f"INSPIRE information: none yet; INSPIRE could not be reached ({error}). "
169
+ f"Try 'openmapp-analyses update' again later.")
170
+ return 0
171
+
172
+
173
+ def cmd_search(args):
174
+ database = load(args.data)
175
+ where = list(args.where or [])
176
+ if args.arxiv:
177
+ where.append(("arXiv_id", "=", normalise_arxiv(args.arxiv)))
178
+ if database.get("inspire_status", {}).get("status", "skipped") == "skipped":
179
+ print("Note: no INSPIRE information in the database, so only tools that give arXiv numbers "
180
+ "themselves (e.g. SModelS, ADL) can be found. Run 'openmapp-analyses update'.",
181
+ file=sys.stderr)
182
+ results = search(
183
+ database,
184
+ tools=args.tool,
185
+ any_tools=args.any_tool,
186
+ not_tools=args.not_tool,
187
+ inspire_ids=args.inspire_id,
188
+ analysis_ids=args.analysis_id,
189
+ where=where,
190
+ )
191
+ _warn_unread_tools(database, (args.tool or []) + (args.any_tool or []) + (args.not_tool or []))
192
+
193
+ if args.json:
194
+ print(json.dumps(results, indent=2, ensure_ascii=False))
195
+ return 0
196
+
197
+ print(f"{_papers(len(results))} found")
198
+ if args.other:
199
+ counts = {}
200
+ for a in results:
201
+ for t, entry in a["tools"].items():
202
+ c = counts.setdefault(t, [0, 0])
203
+ c[0] += 1
204
+ c[1] += _n_impl(entry)
205
+ if counts:
206
+ print(f"\n{'Tool':16s} {'Papers':>7s} {'Impl.':>6s}")
207
+ for t in sorted(counts, key=lambda k: -counts[k][0]):
208
+ print(f"{t:16s} {counts[t][0]:7d} {counts[t][1]:6d}")
209
+ return 0
210
+
211
+ if not results:
212
+ return 0
213
+ print()
214
+ shown = results if args.limit == 0 else results[: args.limit]
215
+ for a in shown:
216
+ tools = ", ".join(f"{t}({_n_impl(e)})" if _n_impl(e) > 1 else t for t, e in a["tools"].items())
217
+ print(f"{a['inspire_id']:>8d} {_short(_label(a), 40):40s} {tools}")
218
+ if args.links:
219
+ for t, entry in a["tools"].items():
220
+ for impl in entry["implementations"]:
221
+ print(f"{'':10s}{t:15s} {impl['main_url']}")
222
+ if len(shown) < len(results):
223
+ print(f"\n... {len(results) - len(shown)} more (use --limit 0 to show all, or --json)")
224
+ return 0
225
+
226
+
227
+ def cmd_show(args):
228
+ database = load(args.data)
229
+ found = search(database, inspire_ids=[args.inspire_id])
230
+ if not found:
231
+ print(f"INSPIRE ID {args.inspire_id} is not implemented in any tool in the database.")
232
+ return 1
233
+ a = found[0]
234
+ if args.json:
235
+ print(json.dumps(a, indent=2, ensure_ascii=False))
236
+ return 0
237
+
238
+ tools = a["tools"]
239
+ if args.tool:
240
+ names = [find_tool_name(database, t) for t in args.tool]
241
+ missing = [t for t in names if t not in tools]
242
+ if missing:
243
+ print(f"Not implemented in: {', '.join(missing)}")
244
+ tools = {t: tools[t] for t in names if t in tools}
245
+ args.details = True
246
+
247
+ n = len(a["tools"])
248
+ print(f"INSPIRE ID {a['inspire_id']} https://inspirehep.net/literature/{a['inspire_id']}")
249
+ label = _label(a)
250
+ ins = a.get("inspire", {})
251
+ if label and label != ins.get("title"):
252
+ print(label)
253
+ if ins.get("title"):
254
+ print(f"Title: {ins['title']}")
255
+ facts = []
256
+ if ins.get("arXiv_id"):
257
+ facts.append(f"arXiv:{ins['arXiv_id']}")
258
+ if ins.get("collaborations"):
259
+ facts.append(", ".join(ins["collaborations"]))
260
+ if ins.get("year"):
261
+ facts.append(str(ins["year"]))
262
+ if facts:
263
+ print(" " + " | ".join(facts))
264
+ if args.details:
265
+ if ins.get("report_numbers"):
266
+ print(f"Report numbers: {', '.join(ins['report_numbers'])}")
267
+ if ins.get("dois"):
268
+ print(f"DOI: {', '.join(ins['dois'])}")
269
+ print(f"Implemented in {n} tool{'s' if n != 1 else ''}:")
270
+
271
+ if not args.details:
272
+ for tool, entry in tools.items():
273
+ k = _n_impl(entry)
274
+ print(f" {tool:16s} {k} implementation{'s' if k != 1 else ''}")
275
+ print("\nFor names and links: add --details (all tools) or --tool TOOL (one tool).")
276
+ return 0
277
+
278
+ for tool, entry in tools.items():
279
+ print(f"\n== {tool} ==")
280
+ for key, value in entry.get("analysis_info", {}).items():
281
+ print(f" {key}: {value}")
282
+ for i, impl in enumerate(entry["implementations"], 1):
283
+ print(f" implementation {i}:")
284
+ for key, value in impl.items():
285
+ print(f" {key}: {value}")
286
+ return 0
287
+
288
+
289
+ def cmd_sources(args):
290
+ """Show the list of tools (from HEPData's config.py if it can be reached), optionally save it."""
291
+ tools, report = resolve_sources(_folder(args), use_hepdata=not args.no_hepdata,
292
+ log=lambda *a: None)
293
+ when = f", retrieved {report['retrieved']}" if report.get("retrieved") else ""
294
+ print(f"Tool list from {ORIGIN_WORDS[report['origin']]}{when}")
295
+ if report.get("error"):
296
+ print(f"(HEPData's config.py could not be read: {report['error']})")
297
+ print()
298
+ print(f"{'Tool':16s} URL")
299
+ print("-" * 70)
300
+ for name, cfg in tools.items():
301
+ print(f"{name:16s} {cfg['url']}")
302
+ if cfg.get("url_template"):
303
+ print(f"{'':16s} old file format; links made with: {cfg['url_template']}")
304
+ if report["origin"] in ("hepdata", "hepdata-saved"):
305
+ print(f"\nSaved in {_folder(args)}: hepdata_config.py (not run, only read) and sources.json")
306
+ if args.output:
307
+ content = {"_comment": f"List of tools from {ORIGIN_WORDS[report['origin']]}.",
308
+ "origin": report.get("location", HEPDATA_CONFIG_URL),
309
+ "retrieved": report.get("retrieved"), "tools": tools}
310
+ Path(args.output).write_text(json.dumps(content, indent=2) + "\n", encoding="utf-8")
311
+ print(f"Written to {args.output} (usable with 'update --sources {args.output}')")
312
+ return 0
313
+
314
+
315
+ # Command-line definition
316
+
317
+ SEARCH_EXAMPLES = """examples:
318
+ openmapp-analyses search --tool smodels (only smodels)
319
+ openmapp-analyses search --tool smodels --other (analyses in SModelS and in all the other tools)
320
+ openmapp-analyses search --tool smodels --tool combine (in both)
321
+ openmapp-analyses search --any-tool smodels --any-tool checkmate (in either)
322
+ openmapp-analyses search --tool smodels --not-tool checkmate (in SModelS, not CheckMATE)
323
+ openmapp-analyses search --inspire-id 1847779 --links
324
+ openmapp-analyses search --arxiv 2102.10874 (which tools implement this paper)
325
+ openmapp-analyses search --analysis-id ATLAS-SUSY-2018-31 (search with analysis-id)
326
+ openmapp-analyses search --where collaborations=CMS --where year=2021
327
+ openmapp-analyses search --where "title~dark matter"
328
+ openmapp-analyses search --where signature_type=prompt
329
+ openmapp-analyses search --where "name~SUSY-2018" (~ = contains)
330
+ """
331
+
332
+
333
+ def build_parser():
334
+ parser = argparse.ArgumentParser(
335
+ prog="openmapp-analyses",
336
+ description="Which tools implement which experimental analyses? Combine the tools' "
337
+ "analysis lists and search them offline.",
338
+ )
339
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
340
+ parser.add_argument("--data", metavar="FILE",
341
+ help="use this database file instead of the default location")
342
+ sub = parser.add_subparsers(dest="command", metavar="command")
343
+
344
+ p = sub.add_parser("update", help="download all tool files and save the combined database (needs internet)")
345
+ p.add_argument("--local", metavar="DIR",
346
+ help="offline test: read DIR/<Tool>.json instead of downloading (uses the packaged tool list)")
347
+ p.add_argument("--sources", metavar="FILE",
348
+ help="use this list of tools instead of the one from HEPData's config.py")
349
+ p.add_argument("--no-hepdata", action="store_true",
350
+ help="do not download HEPData's config.py; use the saved copy or the packaged list")
351
+ p.add_argument("--strict", action="store_true", help="do not save if any tool could not be read")
352
+ p.add_argument("--no-inspire", action="store_true",
353
+ help="do not add arXiv number, title, collaboration and year from INSPIRE")
354
+ p.add_argument("--refresh-inspire", action="store_true",
355
+ help="ask INSPIRE again about every paper (normally only new papers are looked up)")
356
+ p.set_defaults(func=cmd_update)
357
+
358
+ p = sub.add_parser("tools", help="list the tools, their version and how many papers each covers")
359
+ p.add_argument("--json", action="store_true", help="print as JSON")
360
+ p.set_defaults(func=cmd_tools)
361
+
362
+ p = sub.add_parser("search", help="find papers (all conditions must match)",
363
+ epilog=SEARCH_EXAMPLES, formatter_class=argparse.RawDescriptionHelpFormatter)
364
+ p.add_argument("--tool", action="append", metavar="TOOL", help="implemented in this tool (repeat: in ALL of them)")
365
+ p.add_argument("--any-tool", action="append", metavar="TOOL", help="implemented in at least one of these tools")
366
+ p.add_argument("--not-tool", action="append", metavar="TOOL", help="NOT implemented in this tool")
367
+ p.add_argument("--inspire-id", action="append", type=int, metavar="ID", help="this INSPIRE ID (repeatable)")
368
+ p.add_argument("--arxiv", metavar="ID", help="this arXiv number, e.g. 2102.10874 or arXiv:2102.10874v2")
369
+ p.add_argument("--where", action="append", metavar="FIELD=VALUE",
370
+ help="any field in the data, e.g. signature_type=prompt, analysis id like ana_id=ATLAS-SUSY-2018-31; use ~ for 'contains'")
371
+ p.add_argument("--analysis-id", action="append", metavar="ID",
372
+ help="an analysis ID, e.g. ATLAS-SUSY-2018-31; searched in the tools' analysis IDs, "
373
+ "implementation names and INSPIRE report numbers")
374
+ p.add_argument("--other", action="store_true", help="only show how many papers, per tool")
375
+ p.add_argument("--links", action="store_true", help="also show the link of each implementation")
376
+ p.add_argument("--json", action="store_true", help="print the full results as JSON")
377
+ p.add_argument("--limit", type=int, default=50, help="maximum number of papers to list (0 = all; default 50)")
378
+ p.set_defaults(func=cmd_search)
379
+
380
+ p = sub.add_parser("show", help="which tools implement one paper (add --details for names and links)",
381
+ epilog="examples:\n"
382
+ " openmapp-analyses show 1847779 (list of tools)\n"
383
+ " openmapp-analyses show 1847779 --details (all names and links)\n"
384
+ " openmapp-analyses show 1847779 --tool smodels (details for one tool)",
385
+ formatter_class=argparse.RawDescriptionHelpFormatter)
386
+ p.add_argument("inspire_id", type=int, metavar="INSPIRE_ID")
387
+ p.add_argument("-d", "--details", action="store_true",
388
+ help="show each tool's information, implementation names and links")
389
+ p.add_argument("--tool", action="append", metavar="TOOL",
390
+ help="show details only for this tool (repeatable)")
391
+ p.add_argument("--json", action="store_true", help="print as JSON")
392
+ p.set_defaults(func=cmd_show)
393
+
394
+ p = sub.add_parser("sources", help="show the list of tools and their URLs, read from HEPData's config.py")
395
+ p.add_argument("-o", "--output", metavar="FILE", help="also write the list to FILE (sources.json format)")
396
+ p.add_argument("--no-hepdata", action="store_true",
397
+ help="do not download HEPData's config.py; show the saved copy or the packaged list")
398
+ p.set_defaults(func=cmd_sources)
399
+
400
+ return parser
401
+
402
+
403
+ def main(argv=None):
404
+ parser = build_parser()
405
+ args = parser.parse_args(argv)
406
+ if not getattr(args, "func", None):
407
+ parser.print_help()
408
+ return 0
409
+ try:
410
+ return args.func(args)
411
+ except NoDatabaseError as exc:
412
+ print(exc, file=sys.stderr)
413
+ return 1
414
+ except ValueError as exc:
415
+ print(f"Error: {exc}", file=sys.stderr)
416
+ return 2
417
+ except BrokenPipeError: # e.g. output piped into `head`
418
+ return 0
419
+
420
+
421
+ if __name__ == "__main__":
422
+ sys.exit(main())