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,256 @@
1
+ """
2
+ The "engine": download each tool's analyses JSON file, convert it to one
3
+ common shape, merge everything by INSPIRE ID, and check the result against
4
+ schema.json.
5
+
6
+ This is the same logic as the first prototype script (combine_analyses.py),
7
+ split into functions so the command line and Python users can both call it.
8
+ """
9
+
10
+ import json
11
+ import string
12
+ import urllib.request
13
+ from datetime import datetime, timezone
14
+ from pathlib import Path
15
+
16
+ PACKAGE_DIR = Path(__file__).resolve().parent
17
+ SOURCES_FILE = PACKAGE_DIR / "sources.json"
18
+ SCHEMA_FILE = PACKAGE_DIR / "schema.json"
19
+ OUTPUT_SCHEMA_VERSION = "1.0.0"
20
+ STATISTICAL_MODELS = {"combine", "histfactory", "hs3"}
21
+
22
+
23
+ def load_sources(path=None):
24
+ """The list of tools and the URL of each one's file (default: the packaged sources.json)."""
25
+ path = Path(path) if path else SOURCES_FILE
26
+ return json.loads(path.read_text(encoding="utf-8"))["tools"]
27
+
28
+
29
+ # Reading the input files
30
+
31
+ def load_tool_file(tool, cfg, local_dir=None, timeout=60):
32
+ """Return the parsed JSON for one tool, from the web or from a local folder."""
33
+ if local_dir:
34
+ with open(Path(local_dir) / f"{tool}.json", encoding="utf-8") as f:
35
+ return json.load(f)
36
+ req = urllib.request.Request(cfg["url"], headers={"User-Agent": "openmapp-analyses"})
37
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
38
+ return json.loads(resp.read().decode("utf-8"))
39
+
40
+
41
+ def detect_format(data):
42
+ """'new' = Martin's schema (has an 'analyses' list); 'old' = {inspire_id: [values]}."""
43
+ if isinstance(data, dict) and isinstance(data.get("analyses"), list):
44
+ return "new"
45
+ if isinstance(data, dict) and data and all(isinstance(v, list) for v in data.values()):
46
+ return "old"
47
+ raise ValueError("unrecognised file format")
48
+
49
+
50
+ # Building finished links from templates
51
+
52
+ def template_fields(template):
53
+ """Names of the {placeholders} in a template: '{path}/{name}.cc' -> {'path', 'name'}."""
54
+ return {field for _, field, _, _ in string.Formatter().parse(template) if field}
55
+
56
+
57
+ def fill_templates(url_templates, values):
58
+ """Fill each template; skip a link if a value it needs is missing."""
59
+ links = {}
60
+ for link_type, template in url_templates.items():
61
+ needed = template_fields(template)
62
+ if all(values.get(f) not in (None, "") for f in needed):
63
+ links[link_type] = template.format(**{f: values[f] for f in needed})
64
+ return links
65
+
66
+ # Converting each format to one common shape:
67
+ # {inspire_id: {"analysis_info": {...}, "implementations": [...]}}
68
+
69
+ def convert_new_format(data):
70
+ templates = data.get("url_templates", {})
71
+ result = {}
72
+ for ana in data["analyses"]:
73
+ inspire_id = int(ana["inspire_id"])
74
+ # analysis-level fields, e.g. ana_id, arXiv_id, pretty_name
75
+ info = {k: v for k, v in ana.items() if k not in ("inspire_id", "implementations")}
76
+ implementations = []
77
+ for impl in ana.get("implementations", []):
78
+ # placeholders come from the implementation ({name}, {path})
79
+ # or from the analysis ({arXiv_id}, {publication_doi})
80
+ links = fill_templates(templates, {**info, **impl})
81
+ implementations.append({**impl, **links})
82
+ if not implementations:
83
+ continue
84
+ entry = {"implementations": implementations}
85
+ if info:
86
+ entry["analysis_info"] = info
87
+ _add_entry(result, inspire_id, entry)
88
+ return result
89
+
90
+
91
+ def convert_old_format(data, url_template):
92
+ if not url_template:
93
+ raise ValueError("old-format file but no url_template set in sources.json")
94
+ result = {}
95
+ for inspire_id, values in data.items():
96
+ implementations = [{"raw_value": str(v), "main_url": url_template.format(v)} for v in values]
97
+ if implementations:
98
+ _add_entry(result, int(inspire_id), {"implementations": implementations})
99
+ return result
100
+
101
+
102
+ def _add_entry(result, inspire_id, entry):
103
+ """If the same INSPIRE ID appears twice in one tool's file, merge the two."""
104
+ if inspire_id in result:
105
+ result[inspire_id]["implementations"].extend(entry["implementations"])
106
+ if "analysis_info" in entry:
107
+ result[inspire_id].setdefault("analysis_info", {}).update(entry["analysis_info"])
108
+ else:
109
+ result[inspire_id] = entry
110
+
111
+
112
+ # Read all tools, merge by INSPIRE ID
113
+
114
+ def build_database(sources=None, local_dir=None, log=print):
115
+ """
116
+ Read every tool and return the combined database (a dict ready to save as JSON).
117
+ One tool failing does not stop the others: it is recorded with status "error".
118
+ """
119
+ sources = sources if sources is not None else load_sources()
120
+ combined = {} # inspire_id -> {tool: entry}
121
+ report_all = {}
122
+
123
+ for tool, cfg in sources.items():
124
+ kind = "statistical_model" if tool.lower() in STATISTICAL_MODELS else "tool"
125
+ report = {"source_url": cfg["url"], "kind": kind}
126
+ try:
127
+ if cfg.get("hepdata_analysis"):
128
+ from .hepdata_models import convert_hepdata_records, fetch_records
129
+ data = load_tool_file(tool, cfg, local_dir) if local_dir else fetch_records(cfg["hepdata_analysis"])
130
+ fmt = "hepdata"
131
+ else:
132
+ data = load_tool_file(tool, cfg, local_dir)
133
+ fmt = detect_format(data)
134
+ if fmt == "hepdata":
135
+ per_id = convert_hepdata_records(data, cfg["hepdata_analysis"])
136
+ report.update({"tool_name_in_file": None, "version": None,
137
+ "date_created": None, "schema_version": None})
138
+ elif fmt == "new":
139
+ per_id = convert_new_format(data)
140
+ report.update({k: data.get(k) for k in ("version", "date_created", "schema_version")})
141
+ report["tool_name_in_file"] = data.get("tool")
142
+ else:
143
+ per_id = convert_old_format(data, cfg.get("url_template"))
144
+ report.update({"tool_name_in_file": None, "version": None,
145
+ "date_created": None, "schema_version": None})
146
+ for inspire_id, entry in per_id.items():
147
+ combined.setdefault(inspire_id, {})[tool] = entry
148
+ report.update({
149
+ "status": "ok",
150
+ "format": fmt,
151
+ "n_analyses": len(per_id),
152
+ "n_implementations": sum(len(e["implementations"]) for e in per_id.values()),
153
+ })
154
+ log(f" OK {tool:15s} {fmt} format, {len(per_id)} analyses")
155
+ except Exception as exc:
156
+ report.update({"status": "error", "error": f"{type(exc).__name__}: {exc}"})
157
+ log(f" ERROR {tool:15s} {report['error']}")
158
+ report_all[tool] = report
159
+
160
+ analyses = [
161
+ {"inspire_id": iid, "tools": {t: combined[iid][t] for t in sorted(combined[iid], key=str.lower)}}
162
+ for iid in sorted(combined)
163
+ ]
164
+ return {
165
+ "schema_version": OUTPUT_SCHEMA_VERSION,
166
+ "date_created": datetime.now(timezone.utc).isoformat(timespec="seconds"),
167
+ "sources": report_all,
168
+ "analyses": analyses,
169
+ }
170
+
171
+
172
+ def keep_previous(database, previous):
173
+ """
174
+ For every tool that failed in this update but worked before, put back its
175
+ data from the previous database, so a website being down for one night
176
+ does not make that tool disappear. Its status becomes "kept".
177
+ """
178
+ if not previous:
179
+ return []
180
+ kept = []
181
+ old_by_id = {a["inspire_id"]: a for a in previous.get("analyses", [])}
182
+ new_by_id = {a["inspire_id"]: a for a in database["analyses"]}
183
+ old_sources = previous.get("sources", {})
184
+ for tool, report in database["sources"].items():
185
+ # same name as before, or else the same file URL (a tool renamed in the tool list)
186
+ old_name = tool if tool in old_sources else next(
187
+ (k for k, r in old_sources.items() if r.get("source_url") == report.get("source_url")), None)
188
+ old_report = old_sources.get(old_name) if old_name else None
189
+ if report["status"] != "error" or not old_report or old_report["status"] == "error":
190
+ continue
191
+ for iid, old in old_by_id.items():
192
+ if old_name in old["tools"]:
193
+ new = new_by_id.setdefault(iid, {"inspire_id": iid, "tools": {}})
194
+ new["tools"][tool] = old["tools"][old_name]
195
+ restored = {k: v for k, v in old_report.items() if k not in ("status", "error", "kept_from")}
196
+ restored.update({
197
+ "status": "kept",
198
+ "error": report["error"],
199
+ "kept_from": old_report.get("kept_from") or previous.get("date_created"),
200
+ })
201
+ database["sources"][tool] = restored
202
+ kept.append(tool)
203
+ database["analyses"] = [
204
+ {"inspire_id": iid, "tools": {t: a["tools"][t] for t in sorted(a["tools"], key=str.lower)}}
205
+ for iid, a in sorted(new_by_id.items())
206
+ ]
207
+ return kept
208
+
209
+
210
+ def add_inspire_info(database, previous=None, refresh=False, log=print, fetch=None):
211
+ """
212
+ Add an "inspire" block (arXiv number, title, collaboration, ...) to every paper.
213
+ Information from the previous database is reused, unless it was made with another data
214
+ format version (then INSPIRE is asked again, once). If INSPIRE cannot be reached,
215
+ the previous information is kept and the update still succeeds.
216
+ """
217
+ from .inspire import fetch_inspire_info
218
+ fetch = fetch or fetch_inspire_info
219
+
220
+ old = {a["inspire_id"]: a["inspire"]
221
+ for a in (previous or {}).get("analyses", []) if a.get("inspire")}
222
+ ids = [a["inspire_id"] for a in database["analyses"]]
223
+ same_format = (previous or {}).get("schema_version") == OUTPUT_SCHEMA_VERSION
224
+ try:
225
+ info = fetch(ids, previous=old if same_format else {}, refresh=refresh, log=log)
226
+ status = {"status": "ok"}
227
+ except Exception as exc:
228
+ info = {i: old[i] for i in ids if i in old}
229
+ status = {"status": "kept", "error": f"{type(exc).__name__}: {exc}"}
230
+ log(f" INSPIRE: could not be reached ({status['error']}); "
231
+ f"keeping earlier information for {len(info)} papers")
232
+
233
+ for i, a in enumerate(database["analyses"]):
234
+ block = info.get(a["inspire_id"])
235
+ # rebuild so the keys appear in a readable order: inspire_id, inspire, tools
236
+ database["analyses"][i] = {"inspire_id": a["inspire_id"],
237
+ **({"inspire": block} if block else {}),
238
+ "tools": a["tools"]}
239
+ from .arxiv import add_ids_from_arxiv
240
+ add_ids_from_arxiv(database, log=log)
241
+
242
+ status["n_with_info"] = sum(1 for a in database["analyses"] if a.get("inspire"))
243
+ database["inspire_status"] = status
244
+ return status
245
+
246
+
247
+ def validate(database, schema_path=None):
248
+ """Check the database against the JSON schema; return a list of error messages (empty = valid)."""
249
+ import jsonschema
250
+ schema = json.loads(Path(schema_path or SCHEMA_FILE).read_text(encoding="utf-8"))
251
+ validator = jsonschema.Draft202012Validator(schema)
252
+ messages = []
253
+ for err in sorted(validator.iter_errors(database), key=lambda e: list(e.path)):
254
+ where = "/".join(str(p) for p in err.path) or "(top level)"
255
+ messages.append(f"{where}: {err.message}")
256
+ return messages
@@ -0,0 +1,76 @@
1
+ """
2
+ Statistical models stored in HEPData records: HistFactory and HS3 likelihoods.
3
+
4
+ They have no analyses JSON file in HEPData's config.py, because the files are kept in the
5
+ HEPData records themselves. HEPData's search finds the records that have them
6
+ (q=analysis:HistFactory), with a link to each file.
7
+ """
8
+
9
+ import json
10
+ import time
11
+ import urllib.parse
12
+ import urllib.request
13
+
14
+ from . import __version__
15
+
16
+ SEARCH_URL = "https://www.hepdata.net/search/"
17
+ MODEL_TYPES = ("HistFactory", "HS3")
18
+ PAGE_SIZE = 50
19
+ PAUSE = 1.0
20
+ MAX_PAGES = 200
21
+
22
+
23
+ # HEPData's search refuses unknown client names (HTTP 403) but accepts python-requests
24
+ USER_AGENT = f"openmapp-analyses/{__version__} python-requests/2.32.3"
25
+
26
+
27
+ def _get_json(url, timeout=60):
28
+ req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
29
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
30
+ return json.loads(resp.read().decode("utf-8"))
31
+
32
+
33
+ def model_sources():
34
+ """Entries for the list of sources, next to the tools from HEPData's config.py."""
35
+ return {t: {"url": SEARCH_URL + "?" + urllib.parse.urlencode({"q": f"analysis:{t}"}),
36
+ "hepdata_analysis": t} for t in MODEL_TYPES}
37
+
38
+
39
+ def fetch_records(analysis_type, get_json=None, sleep=time.sleep):
40
+ """All HEPData search results for records with this type of file, page by page."""
41
+ get_json = get_json or _get_json
42
+ results = []
43
+ for page in range(1, MAX_PAGES + 1):
44
+ if page > 1:
45
+ sleep(PAUSE)
46
+ params = {"q": f"analysis:{analysis_type}", "format": "json", "page": page, "size": PAGE_SIZE}
47
+ data = get_json(SEARCH_URL + "?" + urllib.parse.urlencode(params))
48
+ batch = data.get("results", [])
49
+ results.extend(batch)
50
+ total = data.get("total") or data.get("hits", {}).get("total")
51
+ if len(batch) < PAGE_SIZE or (total and len(results) >= total):
52
+ break
53
+ return {"results": results}
54
+
55
+
56
+ def convert_hepdata_records(data, analysis_type):
57
+ """HEPData search results -> {inspire_id: {"implementations": [...]}}, one per file."""
58
+ result = {}
59
+ for record in data.get("results", []):
60
+ try:
61
+ inspire_id = int(record.get("inspire_id"))
62
+ except (TypeError, ValueError):
63
+ continue
64
+ descriptions = {r.get("url"): r.get("description") for r in record.get("resources", [])}
65
+ implementations = []
66
+ for item in record.get("analyses", []):
67
+ url = item.get("analysis")
68
+ if item.get("type") != analysis_type or not url:
69
+ continue
70
+ implementation = {"name": item.get("filename") or analysis_type, "main_url": url}
71
+ if descriptions.get(url):
72
+ implementation["description"] = descriptions[url]
73
+ implementations.append(implementation)
74
+ if implementations:
75
+ result.setdefault(inspire_id, {"implementations": []})["implementations"].extend(implementations)
76
+ return result
@@ -0,0 +1,162 @@
1
+ """
2
+ The list of tools, taken from HEPData itself.
3
+
4
+ HEPData's own configuration file (hepdata/config.py) contains ANALYSES_ENDPOINTS:
5
+ every tool HEPData links to and the URL of its analyses JSON
6
+ file. Using that list means a new tool, or a changed URL, reaches this package
7
+ without any change to the package.
8
+
9
+ How the list is chosen during `update` (first one that works):
10
+ 1. HEPData's current config.py, downloaded from GitHub. It is saved as
11
+ hepdata_config.py next to the database, and sources.json is written from it.
12
+ 2. The copy saved by an earlier update (if GitHub cannot be reached).
13
+ 3. The sources.json packaged with openmapp-analyses (if there is no saved copy).
14
+ A file given with --sources always wins over all three.
15
+
16
+ Safety: config.py is never run or imported. It imports parts of HEPData's server
17
+ software (celery, invenio), so importing it would fail on a normal computer, and
18
+ running downloaded code is a risk anyway. Python's `ast` module reads the file as
19
+ text and only the ANALYSES_ENDPOINTS value is taken, and only if it is plain data.
20
+ """
21
+
22
+ import ast
23
+ import json
24
+ import urllib.request
25
+ from datetime import datetime, timezone
26
+ from pathlib import Path
27
+
28
+ from .combine import SOURCES_FILE
29
+
30
+ HEPDATA_CONFIG_URL = "https://raw.githubusercontent.com/HEPData/hepdata/refs/heads/main/hepdata/config.py"
31
+ CONFIG_COPY_NAME = "hepdata_config.py"
32
+ SOURCES_COPY_NAME = "sources.json"
33
+ VARIABLE = "ANALYSES_ENDPOINTS"
34
+ MAX_BYTES = 2_000_000 # config.py is about 20 kB; refuse anything absurdly large
35
+
36
+
37
+ def _get_text(url, timeout=60):
38
+ req = urllib.request.Request(url, headers={"User-Agent": "openmapp-analyses"})
39
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
40
+ data = resp.read(MAX_BYTES + 1)
41
+ if len(data) > MAX_BYTES:
42
+ raise ValueError(f"{url} is larger than expected ({MAX_BYTES} bytes)")
43
+ return data.decode("utf-8")
44
+
45
+
46
+ def read_analyses_endpoints(text):
47
+ """
48
+ Return the ANALYSES_ENDPOINTS dictionary from the text of HEPData's config.py,
49
+ WITHOUT running the file. Commented-out entries are ignored automatically.
50
+ """
51
+ tree = ast.parse(text)
52
+ value = None
53
+ for node in tree.body:
54
+ if isinstance(node, ast.Assign):
55
+ if any(isinstance(t, ast.Name) and t.id == VARIABLE for t in node.targets):
56
+ value = node.value
57
+ elif isinstance(node, ast.AnnAssign):
58
+ if isinstance(node.target, ast.Name) and node.target.id == VARIABLE:
59
+ value = node.value
60
+ if value is None:
61
+ raise ValueError(f"{VARIABLE} not found in HEPData's config.py")
62
+ try:
63
+ endpoints = ast.literal_eval(value) # only accepts plain data (dicts, strings, numbers)
64
+ except ValueError as exc:
65
+ raise ValueError(f"{VARIABLE} in HEPData's config.py is not plain data") from exc
66
+ if not isinstance(endpoints, dict) or not endpoints:
67
+ raise ValueError(f"{VARIABLE} in HEPData's config.py is empty or not a dictionary")
68
+ return endpoints
69
+
70
+
71
+ def endpoints_to_sources(endpoints):
72
+ """
73
+ Convert HEPData's ANALYSES_ENDPOINTS into our sources.json content.
74
+ We keep HEPData's tool names (the keys) and, per tool, the file URL and
75
+ url_template (only needed for tools still using the old file format).
76
+ HEPData-only settings (subscribe_user_id, description, license) are left out.
77
+ """
78
+ tools = {}
79
+ for name, cfg in endpoints.items():
80
+ if not isinstance(cfg, dict) or not cfg.get("endpoint_url"):
81
+ continue # e.g. a tool listed without a URL yet
82
+ entry = {"url": cfg["endpoint_url"]}
83
+ if cfg.get("url_template"):
84
+ entry["url_template"] = cfg["url_template"]
85
+ tools[str(name)] = entry
86
+ if not tools:
87
+ raise ValueError(f"no tool with an endpoint_url in {VARIABLE}")
88
+ return tools
89
+
90
+
91
+ def _write_sources(tools, path, origin_url, retrieved):
92
+ content = {
93
+ "_comment": f"Written by openmapp-analyses from {VARIABLE} in HEPData's config.py. Do not edit: "
94
+ f"it is rewritten at every update.",
95
+ "origin": origin_url,
96
+ "retrieved": retrieved,
97
+ "tools": tools,
98
+ }
99
+ path.write_text(json.dumps(content, indent=2) + "\n", encoding="utf-8")
100
+
101
+
102
+ def fetch_from_hepdata(folder, url=HEPDATA_CONFIG_URL, get_text=None):
103
+ """
104
+ Download HEPData's config.py, save it as hepdata_config.py in `folder`,
105
+ read the tool list from it and write sources.json in `folder`.
106
+ Returns the tools. Raises an exception if anything fails; nothing is
107
+ overwritten in that case.
108
+ """
109
+ text = (get_text or _get_text)(url)
110
+ tools = endpoints_to_sources(read_analyses_endpoints(text)) # check before saving anything
111
+ folder = Path(folder)
112
+ folder.mkdir(parents=True, exist_ok=True)
113
+ (folder / CONFIG_COPY_NAME).write_text(text, encoding="utf-8")
114
+ retrieved = datetime.now(timezone.utc).isoformat(timespec="seconds")
115
+ _write_sources(tools, folder / SOURCES_COPY_NAME, url, retrieved)
116
+ return tools, retrieved
117
+
118
+
119
+ def resolve_sources(folder, sources_file=None, use_hepdata=True, log=print, get_text=None):
120
+ """
121
+ Decide which list of tools to use. Returns (tools, tool_list_report).
122
+
123
+ tool_list_report says where the list came from, and is stored in the database:
124
+ origin = "file" a file given with --sources
125
+ "hepdata" HEPData's config.py, downloaded now
126
+ "hepdata-saved" HEPData's config.py saved by an earlier update
127
+ "packaged" the sources.json packaged with openmapp-analyses
128
+ """
129
+ if sources_file:
130
+ tools = json.loads(Path(sources_file).read_text(encoding="utf-8"))["tools"]
131
+ log(f" Tool list: {len(tools)} tools from {sources_file}")
132
+ return tools, {"origin": "file", "location": str(sources_file)}
133
+
134
+ error = None
135
+ if use_hepdata:
136
+ try:
137
+ tools, retrieved = fetch_from_hepdata(folder, get_text=get_text)
138
+ log(f" Tool list: {len(tools)} tools from HEPData's config.py ({', '.join(tools)})")
139
+ return tools, {"origin": "hepdata", "location": HEPDATA_CONFIG_URL, "retrieved": retrieved}
140
+ except Exception as exc:
141
+ error = f"{type(exc).__name__}: {exc}"
142
+ log(f" Tool list: could not read HEPData's config.py ({error})")
143
+
144
+ saved = Path(folder) / SOURCES_COPY_NAME
145
+ if saved.exists():
146
+ try:
147
+ content = json.loads(saved.read_text(encoding="utf-8"))
148
+ tools = content["tools"]
149
+ log(f" Tool list: using the copy saved on {content.get('retrieved', '?')} ({len(tools)} tools)")
150
+ return tools, {"origin": "hepdata-saved", "location": str(saved),
151
+ "retrieved": content.get("retrieved"), "error": error}
152
+ except Exception:
153
+ pass # a damaged copy: fall through to the packaged list
154
+
155
+ content = json.loads(SOURCES_FILE.read_text(encoding="utf-8"))
156
+ tools = content["tools"]
157
+ log(f" Tool list: using the list packaged with openmapp-analyses ({len(tools)} tools)")
158
+ report = {"origin": "packaged", "location": "openmapp_analyses/sources.json",
159
+ "retrieved": content.get("retrieved")}
160
+ if error:
161
+ report["error"] = error
162
+ return tools, report
@@ -0,0 +1,174 @@
1
+ """
2
+ Add information from INSPIRE (inspirehep.net) to every paper: arXiv number,
3
+ title, collaboration, year, report numbers, DOIs and analysis IDs.
4
+
5
+ Analysis IDs come from links to the experiments' result pages in the arXiv comment, which
6
+ INSPIRE keeps as a note, e.g.
7
+ "... available at https://atlas.web.cern.ch/Atlas/GROUPS/PHYSICS/PAPERS/TOPQ-2023-44".
8
+ If INSPIRE's note has none, arxiv.py looks at the current arXiv comment.
9
+
10
+ Most tools only give the INSPIRE ID, so this is what makes e.g. arXiv search
11
+ work for all tools.
12
+
13
+ How it works:
14
+ - INSPIRE's search API is asked about many papers in one request
15
+ (q=recid:A or recid:B or ...), BATCH_SIZE at a time, returning only the
16
+ fields we need.
17
+ - INSPIRE allows 15 requests per 5 seconds per computer, so we pause
18
+ between requests and wait and retry if INSPIRE answers "too many requests" (HTTP 429).
19
+ - Papers already looked up in a previous update are not asked again
20
+ (unless refresh=True), so later updates are fast.
21
+
22
+ API documentation: https://github.com/inspirehep/rest-api-doc
23
+ """
24
+
25
+ import json
26
+ import re
27
+ import time
28
+ import urllib.error
29
+ import urllib.parse
30
+ import urllib.request
31
+
32
+ API_URL = "https://inspirehep.net/api/literature"
33
+ FIELDS = ["control_number", "arxiv_eprints", "titles", "collaborations",
34
+ "report_numbers", "dois", "earliest_date", "public_notes"]
35
+ BATCH_SIZE = 50 # papers per request (keeps the URL short)
36
+ PAUSE = 0.5 # seconds between requests (INSPIRE allows 15 per 5 s)
37
+ MAX_RETRIES = 4
38
+ RESULT_PAGES = [
39
+ (re.compile(r"atlas\.web\.cern\.ch/Atlas/GROUPS/PHYSICS/(?:PAPERS|CONFNOTES)/((?:ATLAS-)?[A-Z]+-\d{4}-\d+)",
40
+ re.I), "ATLAS-"),
41
+ (re.compile(r"cms-results\.web\.cern\.ch/cms-results/public-results/(?:publications|preliminary-results)/"
42
+ r"([A-Z0-9]+-\d{2}-\d{3})", re.I), "CMS-"),
43
+ (re.compile(r"lhcbproject/Publications/\w+/(LHCb-(?:PAPER|CONF)-\d{4}-\d+)", re.I), ""),
44
+ ]
45
+
46
+
47
+ def _get_json(url, timeout=60):
48
+ req = urllib.request.Request(url, headers={"User-Agent": "openmapp-analyses",
49
+ "Accept": "application/json"})
50
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
51
+ return json.loads(resp.read().decode("utf-8"))
52
+
53
+
54
+ def _query_url(ids):
55
+ query = " or ".join(f"recid:{i}" for i in ids)
56
+ params = {"q": query, "size": len(ids), "fields": ",".join(FIELDS)}
57
+ return API_URL + "?" + urllib.parse.urlencode(params)
58
+
59
+
60
+ def _values(items, key="value"):
61
+ """[{"value": "ATLAS"}, ...] -> ["ATLAS", ...], skipping empty ones."""
62
+ out = []
63
+ for item in items or []:
64
+ v = item.get(key) if isinstance(item, dict) else None
65
+ if v and v not in out:
66
+ out.append(v)
67
+ return out
68
+
69
+
70
+ def parse_record(metadata):
71
+ """Turn INSPIRE's metadata for one paper into our compact 'inspire' block."""
72
+ info = {}
73
+ arxiv = _values(metadata.get("arxiv_eprints"))
74
+ if arxiv:
75
+ info["arXiv_id"] = arxiv[0]
76
+ titles = _values(metadata.get("titles"), key="title")
77
+ if titles:
78
+ info["title"] = titles[0]
79
+ collaborations = _values(metadata.get("collaborations"))
80
+ if collaborations:
81
+ info["collaborations"] = collaborations
82
+ date = metadata.get("earliest_date")
83
+ if date and str(date)[:4].isdigit():
84
+ info["year"] = int(str(date)[:4])
85
+ reports = _values(metadata.get("report_numbers"))
86
+ if reports:
87
+ info["report_numbers"] = reports
88
+ dois = _values(metadata.get("dois"))
89
+ if dois:
90
+ info["dois"] = dois
91
+ ids = analysis_ids_from_links(" ".join(_values(metadata.get("public_notes"))))
92
+ if ids:
93
+ info["analysis_ids"] = ids
94
+ return info
95
+
96
+
97
+ def analysis_ids_from_links(text):
98
+ """
99
+ Analysis IDs from links to the experiments' result pages, e.g.
100
+ '.../Atlas/GROUPS/PHYSICS/PAPERS/TOPQ-2023-44' -> 'ATLAS-TOPQ-2023-44',
101
+ '.../public-results/publications/SUS-19-006' -> 'CMS-SUS-19-006',
102
+ '.../lhcbproject/Publications/p/LHCb-PAPER-2022-001.html' -> 'LHCb-PAPER-2022-001'.
103
+ """
104
+ ids = []
105
+ for pattern, prefix in RESULT_PAGES:
106
+ for found in pattern.findall(text):
107
+ found = found.upper().replace("LHCB-", "LHCb-")
108
+ if prefix and not found.startswith(prefix):
109
+ found = prefix + found
110
+ if found not in ids:
111
+ ids.append(found)
112
+ return ids
113
+
114
+
115
+ def _fetch_batch(ids, get_json, sleep):
116
+ """Ask INSPIRE about one batch of IDs, retrying on 'too many requests'."""
117
+ url = _query_url(ids)
118
+ for attempt in range(MAX_RETRIES):
119
+ try:
120
+ return get_json(url)
121
+ except urllib.error.HTTPError as exc:
122
+ if exc.code == 429 and attempt < MAX_RETRIES - 1:
123
+ sleep(5 * (attempt + 1)) # INSPIRE: wait at least 5 s
124
+ continue
125
+ raise
126
+ raise RuntimeError("unreachable")
127
+
128
+
129
+ def fetch_inspire_info(inspire_ids, previous=None, refresh=False, log=print,
130
+ get_json=_get_json, sleep=time.sleep):
131
+ """
132
+ Return {inspire_id: info} for all given IDs.
133
+
134
+ previous: {inspire_id: info} from the last update; these are reused unless refresh=True.
135
+ Raises an exception if INSPIRE cannot be reached at all (the caller decides what to do).
136
+ """
137
+ previous = previous or {}
138
+ result = {} if refresh else {i: previous[i] for i in inspire_ids if i in previous}
139
+ todo = [i for i in inspire_ids if i not in result]
140
+ if not todo:
141
+ log(f" INSPIRE: all {len(result)} papers already known (use --refresh-inspire to ask again)")
142
+ return result
143
+
144
+ n_batches = (len(todo) + BATCH_SIZE - 1) // BATCH_SIZE
145
+ log(f" INSPIRE: looking up {len(todo)} papers in {n_batches} requests"
146
+ + (f" ({len(result)} already known)" if result else ""))
147
+ for b in range(n_batches):
148
+ ids = todo[b * BATCH_SIZE:(b + 1) * BATCH_SIZE]
149
+ if b:
150
+ sleep(PAUSE)
151
+ answer = _fetch_batch(ids, get_json, sleep)
152
+ for hit in answer.get("hits", {}).get("hits", []):
153
+ meta = hit.get("metadata", {})
154
+ recid = meta.get("control_number") or hit.get("id")
155
+ try:
156
+ recid = int(recid)
157
+ except (TypeError, ValueError):
158
+ continue
159
+ if recid in ids:
160
+ result[recid] = parse_record(meta)
161
+
162
+ missing = [i for i in todo if i not in result]
163
+ if missing:
164
+ shown = ", ".join(map(str, missing[:10])) + (" ..." if len(missing) > 10 else "")
165
+ log(f" INSPIRE: {len(missing)} IDs not found in INSPIRE: {shown}")
166
+ return result
167
+
168
+
169
+ def normalise_arxiv(text):
170
+ """'arXiv:2102.10874v2' -> '2102.10874'; 'hep-ph/0603175v1' -> 'hep-ph/0603175'."""
171
+ text = str(text).strip()
172
+ if text.lower().startswith("arxiv:"):
173
+ text = text[6:]
174
+ return re.sub(r"(?<=\d)v\d+$", "", text)