pylamda 0.1.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.
pylamda/bib.py ADDED
@@ -0,0 +1,859 @@
1
+ """BibTeX export of the references of LAMDA files (design document, section 10).
2
+
3
+ 1. **Collect** the references of each file: dataset DOI, level reference, partner
4
+ references, and identifiers in comment lines, line 2 and the notes
5
+ (:func:`collect_references`).
6
+ 2. **Extract** the identifiers: DOIs, ADS/SciX bibcodes, arXiv IDs
7
+ (:func:`pylamda.references.find_identifiers`).
8
+ 3. **Resolve** them (``online=True``). SciX is the source of the bibliographic records:
9
+ DOIs and arXiv IDs are searched in SciX, and all bibcodes are exported as BibTeX in
10
+ one request. DOIs that SciX does not know (datasets) are resolved with doi.org. SciX
11
+ needs the user's API token (:func:`scix_token`); without it, only DOIs are resolved
12
+ (doi.org).
13
+ 4. Identifiers that are not resolved (or offline) give a ``@misc`` entry with the
14
+ identifier and a note saying what the reference is for.
15
+ 5. The main papers of LAMDA and EMAA are added from ``pylamda/data/database_refs.bib``.
16
+
17
+ References given only as free text ("Flower (2001)") are not guessed: they are listed
18
+ in :attr:`BibResult.free_text`.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import os
25
+ import re
26
+ import stat
27
+ import unicodedata
28
+ import warnings
29
+ from collections.abc import Iterable
30
+ from dataclasses import dataclass, field, replace
31
+ from importlib.resources import files
32
+ from pathlib import Path
33
+
34
+ from .catalogue import load_catalogue
35
+ from .model import LamdaData
36
+ from .reader import read
37
+ from .references import find_identifiers
38
+
39
+ #: Base URL of the SciX API (the same API as ADS).
40
+ SCIX_API = "https://api.scixplorer.org/v1"
41
+ #: SciX abstract page of a bibcode: ``SCIX_ABS + bibcode``.
42
+ SCIX_ABS = "https://scixplorer.org/abs/"
43
+ #: Keys in ``database_refs.bib`` that every export gets: the LAMDA paper and the 2020 LAMDA
44
+ #: status review (decided 2026-11-18, design decision 10).
45
+ LAMDA_KEYS: tuple[str, ...] = ("Schoier2005", "vanderTak2020")
46
+ #: Keys added if a file comes from EMAA (EMAA's citation policy).
47
+ EMAA_KEYS: tuple[str, ...] = ("Faure2025", "EMAA")
48
+ #: The acknowledgement EMAA asks for (https://emaa.osug.fr/citation-policy).
49
+ EMAA_ACKNOWLEDGEMENT = (
50
+ "This research has made use of spectroscopic and collisional data from the EMAA database "
51
+ "(https://dx.doi.org/10.17178/EMAA). EMAA is supported by the Observatoire des Sciences de l'Univers "
52
+ "de Grenoble (OSUG) (https://ror.org/03vte9x46)."
53
+ )
54
+ #: What LAMDA asks for besides the citation (https://home.strw.leidenuniv.nl/~moldata/).
55
+ LAMDA_REQUEST = (
56
+ "LAMDA asks to mention the date when the database was accessed, and to cite the original papers "
57
+ "of the spectroscopic and collisional data of each molecule."
58
+ )
59
+
60
+ _DATABASE_NOTES = {
61
+ "Schoier2005": "LAMDA database",
62
+ "vanderTak2020": "LAMDA database (2020 status review)",
63
+ "Faure2025": "EMAA database",
64
+ "EMAA": "EMAA database (dataset DOI)",
65
+ }
66
+ _ROLE_TEXT = {"dataset": "dataset", "levels": "levels and radiative data", "comments": "named in a comment"}
67
+ _SEARCH_CHUNK = 900 # characters of a SciX query (the limit is 1000)
68
+ _EXPORT_CHUNK = 200 # bibcodes per SciX export request
69
+
70
+
71
+ class BibError(RuntimeError):
72
+ """Online resolution failed (e.g. SciX rejected the token)."""
73
+
74
+
75
+ # ------------------------------------------------------------------- references in files
76
+ @dataclass
77
+ class Reference:
78
+ """One reference found in a file.
79
+
80
+ Attributes
81
+ ----------
82
+ path : str or None
83
+ The file (None for data not read from a file).
84
+ molecule : str
85
+ The molecule of the file.
86
+ role : str
87
+ ``"dataset"`` (dataset DOI), ``"levels"`` (reference on the NLEV line),
88
+ ``"collisions"`` (partner line) or ``"comments"`` (a comment line, line 2 or
89
+ the notes; only with an identifier).
90
+ partner : str or None
91
+ The partner (by ID) for ``"collisions"``.
92
+ text : str
93
+ The reference text.
94
+ identifiers : list of str
95
+ ``"doi:..."``, ``"bibcode:..."`` and ``"arxiv:..."`` found in the text.
96
+ """
97
+
98
+ path: str | None
99
+ molecule: str
100
+ role: str
101
+ partner: str | None
102
+ text: str
103
+ identifiers: list[str]
104
+
105
+ @property
106
+ def use(self) -> str:
107
+ """str: What the reference is for (``"collision rates with p-H2"``)."""
108
+ if self.role == "collisions":
109
+ return f"collision rates with {self.partner}"
110
+ return _ROLE_TEXT.get(self.role, self.role)
111
+
112
+
113
+ def collect_references(data: LamdaData) -> list[Reference]:
114
+ """The references of one data set.
115
+
116
+ Parameters
117
+ ----------
118
+ data : LamdaData
119
+ The data (comment lines are read from ``data.source_map`` if present).
120
+
121
+ Returns
122
+ -------
123
+ list of Reference
124
+ Dataset DOI, level reference and partner references (with or without
125
+ identifiers), then the comment lines, line 2 and notes that hold an identifier.
126
+ """
127
+ path = data.source_map.path if data.source_map else None
128
+ mol = data.molecule
129
+ refs = []
130
+ if data.dataset_doi:
131
+ refs.append(Reference(path, mol, "dataset", None, data.dataset_doi, [f"doi:{data.dataset_doi}"]))
132
+ if data.level_reference.strip():
133
+ text = data.level_reference.strip()
134
+ refs.append(Reference(path, mol, "levels", None, text, find_identifiers(text)))
135
+ for c in data.collisions:
136
+ if c.reference.strip():
137
+ text = c.reference.strip()
138
+ refs.append(Reference(path, mol, "collisions", c.label, text, find_identifiers(text)))
139
+ for text in _comment_texts(data):
140
+ ids = find_identifiers(text)
141
+ if ids:
142
+ refs.append(Reference(path, mol, "comments", None, text.strip().lstrip("!").strip(), ids))
143
+ return refs
144
+
145
+
146
+ def _comment_texts(data: LamdaData) -> list[str]:
147
+ """Line 2 (title), the notes and the comment lines of the file (not the partner lines)."""
148
+ texts = [data.title, *data.notes]
149
+ smap = data.source_map
150
+ if smap is not None:
151
+ notes_from = smap.notes or len(smap.raw) + 1
152
+ texts += [line for i, line in enumerate(smap.raw, 1) if i < notes_from and line.lstrip().startswith("!")]
153
+ fix_note = re.compile(r"^\s*!\s*pylamda \S+ fix:") # pylamda's own fix notes are not references
154
+ return [t for t in texts if t and t.strip() and not fix_note.match(t)]
155
+
156
+
157
+ def is_emaa(data: LamdaData) -> bool:
158
+ """Whether a data set comes from EMAA (dataset DOI ``10.17178/EMAA...`` or "EMAA" in its texts).
159
+
160
+ Parameters
161
+ ----------
162
+ data : LamdaData
163
+ The data.
164
+
165
+ Returns
166
+ -------
167
+ bool
168
+ True if there is an EMAA hint.
169
+ """
170
+ if (data.dataset_doi or "").upper().startswith("10.17178/EMAA"):
171
+ return True
172
+ texts = [data.level_reference, data.source, *(c.reference for c in data.collisions), *_comment_texts(data)]
173
+ return any(re.search(r"\bEMAA\b", t or "") for t in texts)
174
+
175
+
176
+ # ------------------------------------------------------------------- BibTeX text
177
+ def split_entries(text: str) -> list[str]:
178
+ """The entries of a BibTeX text (``@type{key, ...}``), without comments around them."""
179
+ out = []
180
+ for m in re.finditer(r"@\s*(\w+)\s*([{(])", text):
181
+ if m.group(1).lower() in ("comment", "preamble", "string"):
182
+ continue
183
+ open_, close = m.group(2), "}" if m.group(2) == "{" else ")"
184
+ depth, i = 0, m.end() - 1
185
+ while i < len(text):
186
+ ch = text[i]
187
+ if ch == open_:
188
+ depth += 1
189
+ elif ch == close:
190
+ depth -= 1
191
+ if depth == 0:
192
+ out.append(text[m.start() : i + 1].strip())
193
+ break
194
+ i += 1
195
+ return out
196
+
197
+
198
+ def entry_key(entry: str) -> str:
199
+ """The key of a BibTeX entry."""
200
+ m = re.match(r"@\s*\w+\s*[{(]\s*([^,\s]*)\s*,", entry)
201
+ return m.group(1) if m else ""
202
+
203
+
204
+ def _set_key(entry: str, key: str) -> str:
205
+ return re.sub(r"^(@\s*\w+\s*[{(]\s*)[^,]*?(\s*,)", lambda m: m.group(1) + key + m.group(2), entry, count=1)
206
+
207
+
208
+ def _field_span(entry: str, name: str) -> tuple[int, int] | None:
209
+ """(start, end) of the value of field ``name`` (with its braces or quotes)."""
210
+ m = re.search(rf"[,{{\s]{re.escape(name)}\s*=\s*", entry, re.I)
211
+ if not m:
212
+ return None
213
+ i = m.end()
214
+ if i >= len(entry):
215
+ return None
216
+ if entry[i] in "{":
217
+ depth = 0
218
+ for j in range(i, len(entry)):
219
+ depth += {"{": 1, "}": -1}.get(entry[j], 0)
220
+ if depth == 0:
221
+ return i, j + 1
222
+ return None
223
+ if entry[i] == '"':
224
+ j = i + 1
225
+ while j < len(entry) and (entry[j] != '"' or entry[j - 1] == "\\"):
226
+ j += 1
227
+ return i, j + 1
228
+ m2 = re.match(r"[^,}\s]+", entry[i:])
229
+ return (i, i + m2.end()) if m2 else None
230
+
231
+
232
+ def entry_field(entry: str, name: str) -> str | None:
233
+ """The value of a field of a BibTeX entry, without the outer braces or quotes."""
234
+ span = _field_span(entry, name)
235
+ if span is None:
236
+ return None
237
+ value = entry[span[0] : span[1]]
238
+ if value[:1] in '{"':
239
+ value = value[1:-1]
240
+ return value.strip()
241
+
242
+
243
+ def _set_field(entry: str, name: str, value: str) -> str:
244
+ """Set (replace or add) a field, ``name = {value}``."""
245
+ span = _field_span(entry, name)
246
+ if span is not None:
247
+ return entry[: span[0]] + "{" + value + "}" + entry[span[1] :]
248
+ body = entry.rstrip()[:-1].rstrip().rstrip(",")
249
+ return f"{body},\n {name} = {{{value}}}\n}}"
250
+
251
+
252
+ def _ascii_letters(text: str) -> str:
253
+ """Letters of a name without LaTeX accents, braces and blanks (``Sch{\\"o}ier`` -> ``Schoier``)."""
254
+ text = re.sub(r"\\[\"'`^~=.uvHckbdrt]\s*\{?\s*([A-Za-z])\s*\}?", r"\1", text)
255
+ letters = {"l": "l", "L": "L", "o": "o", "O": "O", "ss": "ss", "ae": "ae", "AE": "AE", "aa": "a", "AA": "A"}
256
+ text = re.sub(r"\\(ss|ae|AE|aa|AA|[lLoOij])(?![A-Za-z])", lambda m: letters.get(m.group(1), m.group(1)), text)
257
+ text = re.sub(r"\\[A-Za-z]+", "", text)
258
+ text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode()
259
+ return re.sub(r"[^A-Za-z]", "", text)
260
+
261
+
262
+ def key_from_entry(entry: str) -> str | None:
263
+ """``<first author surname><year>`` of a BibTeX entry (``Yang2010``), or None."""
264
+ author, year = entry_field(entry, "author"), entry_field(entry, "year")
265
+ if not author or not year or not re.fullmatch(r"\{?\d{4}\}?", year.strip()):
266
+ return None
267
+ first = re.split(r"\s+and\s+", author.strip())[0]
268
+ depth, cut = 0, None
269
+ for i, ch in enumerate(first): # a comma outside braces separates "Surname, Given"
270
+ depth += {"{": 1, "}": -1}.get(ch, 0)
271
+ if ch == "," and depth == 0:
272
+ cut = i
273
+ break
274
+ surname = first[:cut] if cut is not None else first.split()[-1] if first.split() else ""
275
+ surname = _ascii_letters(surname)
276
+ return f"{surname}{year.strip('{}')}" if surname else None
277
+
278
+
279
+ def key_from_text(text: str) -> str | None:
280
+ """``<author><year>`` guessed from a free reference text (``"Yang et al. (2010)"`` -> ``Yang2010``)."""
281
+ m = re.search(r"([A-Z][A-Za-z'\-]+).{0,60}?\b((?:19|20)\d\d)\b", text or "")
282
+ return f"{_ascii_letters(m.group(1))}{m.group(2)}" if m else None
283
+
284
+
285
+ def identifier_context(text: str, identifier: str) -> str:
286
+ """The part of a reference text that belongs to one identifier (for :func:`key_from_text`).
287
+
288
+ The text before the identifier, back to the previous identifier or the last ``;``:
289
+ in ``"Yang 2010 doi:A; Dagdigian 2022 doi:B"``, ``"Dagdigian 2022 "`` for ``doi:B``.
290
+
291
+ Parameters
292
+ ----------
293
+ text : str
294
+ The reference text.
295
+ identifier : str
296
+ One of its identifiers (``"doi:..."``, ...).
297
+
298
+ Returns
299
+ -------
300
+ str
301
+ The part of the text; the whole text if the identifier is not found in it.
302
+ """
303
+ lower = text.lower()
304
+ value = identifier.split(":", 1)[1].lower()
305
+ idx = lower.find(value)
306
+ if idx < 0:
307
+ return text
308
+ start = lower.rfind(";", 0, idx) + 1
309
+ for other in find_identifiers(text):
310
+ v = other.split(":", 1)[1].lower()
311
+ j = lower.find(v)
312
+ if v != value and 0 <= j and j + len(v) <= idx:
313
+ start = max(start, j + len(v))
314
+ return text[start:idx]
315
+
316
+
317
+ def _escape(text: str) -> str:
318
+ return re.sub(r"([&%#_$])", r"\\\1", text)
319
+
320
+
321
+ def _misc(key: str, identifier: str, note: str) -> str:
322
+ """A ``@misc`` entry for an identifier that is not resolved."""
323
+ kind, value = identifier.split(":", 1)
324
+ if kind == "doi":
325
+ fields = [f"doi = {{{value}}}"]
326
+ elif kind == "bibcode":
327
+ fields = [f"howpublished = {{\\url{{{SCIX_ABS}{value}}}}}", f"adsurl = {{{SCIX_ABS}{value}}}"]
328
+ else:
329
+ fields = [f"eprint = {{{value}}}", "archivePrefix = {arXiv}"]
330
+ return "@misc{" + key + ",\n " + ",\n ".join([f"note = {{{_escape(note)}}}", *fields]) + ",\n}"
331
+
332
+
333
+ # ------------------------------------------------------------------- token, cache, HTTP
334
+ def scix_token(token: str | None = None) -> str | None:
335
+ """The user's SciX API token.
336
+
337
+ Looked up in this order:
338
+
339
+ 1. the ``token`` argument;
340
+ 2. the environment variable ``SCIX_API_TOKEN``;
341
+ 3. the file ``$XDG_CONFIG_HOME/pylamda/scix_token`` (default
342
+ ``~/.config/pylamda/scix_token``), first line. A warning is given if other users
343
+ can read the file.
344
+
345
+ Parameters
346
+ ----------
347
+ token : str or None, optional
348
+ A token given directly.
349
+
350
+ Returns
351
+ -------
352
+ str or None
353
+ The token, or None if there is none. pylamda never writes it to files, logs,
354
+ the cache or messages.
355
+ """
356
+ if token:
357
+ return token.strip()
358
+ if os.environ.get("SCIX_API_TOKEN", "").strip():
359
+ return os.environ["SCIX_API_TOKEN"].strip()
360
+ path = token_file()
361
+ if path.is_file():
362
+ if path.stat().st_mode & (stat.S_IRWXG | stat.S_IRWXO):
363
+ warnings.warn(f"{path} can be read by other users; run: chmod 600 {path}", stacklevel=2)
364
+ lines = path.read_text(encoding="utf-8").splitlines()
365
+ return lines[0].strip() if lines and lines[0].strip() else None
366
+ return None
367
+
368
+
369
+ def token_file() -> Path:
370
+ """The SciX token file, ``$XDG_CONFIG_HOME/pylamda/scix_token`` (default ``~/.config/...``)."""
371
+ return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "pylamda" / "scix_token"
372
+
373
+
374
+ def default_cache() -> Path:
375
+ """The cache of resolved references, ``$XDG_CACHE_HOME/pylamda/bib_cache.json`` (default ``~/.cache/...``)."""
376
+ return Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache") / "pylamda" / "bib_cache.json"
377
+
378
+
379
+ class _Cache:
380
+ """Resolved references: bibcode -> BibTeX, DOI/arXiv -> bibcode ("" = not in SciX), DOI -> BibTeX."""
381
+
382
+ SECTIONS = ("bibtex", "doi_bibcode", "arxiv_bibcode", "doi_bibtex")
383
+
384
+ def __init__(self, path: Path | None):
385
+ self.path = path
386
+ self.data: dict[str, dict[str, str]] = {s: {} for s in self.SECTIONS}
387
+ self.changed = False
388
+ if path is not None and path.is_file():
389
+ try:
390
+ stored = json.loads(path.read_text(encoding="utf-8"))
391
+ for s in self.SECTIONS:
392
+ self.data[s].update(stored.get(s, {}))
393
+ except (OSError, ValueError):
394
+ warnings.warn(f"cannot read the cache {path}; starting a new one", stacklevel=2)
395
+
396
+ def get(self, section: str, key: str) -> str | None:
397
+ return self.data[section].get(key)
398
+
399
+ def set(self, section: str, key: str, value: str) -> None:
400
+ if self.data[section].get(key) != value:
401
+ self.data[section][key] = value
402
+ self.changed = True
403
+
404
+ def save(self) -> None:
405
+ if self.path is None or not self.changed:
406
+ return
407
+ self.path.parent.mkdir(parents=True, exist_ok=True)
408
+ self.path.write_text(json.dumps(self.data, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
409
+
410
+
411
+ class HttpClient:
412
+ """SciX and doi.org over HTTPS (with ``requests``).
413
+
414
+ Parameters
415
+ ----------
416
+ token : str or None
417
+ The SciX API token (None: SciX is not used).
418
+ timeout : float, optional
419
+ Timeout of each request [s]. Default: 30.
420
+ """
421
+
422
+ def __init__(self, token: str | None, timeout: float = 30.0):
423
+ import requests # imported here, so that 'import pylamda' stays fast
424
+
425
+ from . import __version__
426
+
427
+ self._requests = requests
428
+ self._session = requests.Session()
429
+ self._session.headers["User-Agent"] = f"pylamda/{__version__}"
430
+ self._token = token
431
+ self.timeout = timeout
432
+
433
+ @property
434
+ def has_token(self) -> bool:
435
+ """bool: Whether a SciX token is set."""
436
+ return bool(self._token)
437
+
438
+ def _scix(self, method: str, path: str, **kw) -> dict:
439
+ headers = {"Authorization": f"Bearer {self._token}"}
440
+ try:
441
+ r = self._session.request(method, f"{SCIX_API}{path}", headers=headers, timeout=self.timeout, **kw)
442
+ except self._requests.RequestException as exc:
443
+ raise BibError(f"SciX request failed: {type(exc).__name__}") from None
444
+ if r.status_code == 401:
445
+ raise BibError("SciX rejected the API token (HTTP 401); check SCIX_API_TOKEN or the token file")
446
+ if r.status_code != 200:
447
+ raise BibError(f"SciX request {path} failed: HTTP {r.status_code}")
448
+ return r.json()
449
+
450
+ def scix_search(self, query: str, fields: str) -> list[dict]:
451
+ """The documents of a SciX search (``fl`` = ``fields``, up to 2000)."""
452
+ out = self._scix("GET", "/search/query", params={"q": query, "fl": fields, "rows": 2000})
453
+ return out.get("response", {}).get("docs", [])
454
+
455
+ def scix_export(self, bibcodes: list[str]) -> str:
456
+ """BibTeX of the bibcodes (SciX export)."""
457
+ return self._scix("POST", "/export/bibtex", json={"bibcode": bibcodes}).get("export", "")
458
+
459
+ def doi_bibtex(self, doi: str) -> str | None:
460
+ """BibTeX of a DOI from doi.org (content negotiation), or None if not found."""
461
+ try:
462
+ r = self._session.get(
463
+ f"https://doi.org/{doi}", headers={"Accept": "application/x-bibtex"}, timeout=self.timeout
464
+ )
465
+ except self._requests.RequestException:
466
+ return None
467
+ text = r.text.strip() if r.status_code == 200 else ""
468
+ return text if text.startswith("@") else None
469
+
470
+
471
+ # ------------------------------------------------------------------- result
472
+ @dataclass
473
+ class BibEntry:
474
+ """One entry of the BibTeX export.
475
+
476
+ Attributes
477
+ ----------
478
+ key : str
479
+ The BibTeX key.
480
+ bibtex : str
481
+ The entry.
482
+ source : str
483
+ ``"database"`` (shipped), ``"scix"``, ``"doi.org"`` or ``"unresolved"`` (``@misc``).
484
+ identifiers : list of str
485
+ The identifiers that led to it (``"doi:..."``, ...).
486
+ note : str
487
+ What it is cited for (``"CO: collision rates with p-H2"``).
488
+ """
489
+
490
+ key: str
491
+ bibtex: str
492
+ source: str
493
+ identifiers: list[str] = field(default_factory=list)
494
+ note: str = ""
495
+
496
+
497
+ @dataclass
498
+ class BibResult:
499
+ """Result of :func:`bibtex`.
500
+
501
+ Attributes
502
+ ----------
503
+ entries : list of BibEntry
504
+ The entries: database papers first, then in the order found.
505
+ free_text : list of Reference
506
+ Level and partner references without an identifier (not in the export).
507
+ warnings : list of str
508
+ What could not be resolved, and why.
509
+ keys : dict of str to str
510
+ Identifier -> key of every entry (for ``keys`` in the next run).
511
+ emaa : bool
512
+ Whether a file comes from EMAA (the export then holds EMAA's acknowledgement).
513
+ n_files : int
514
+ Number of data sets.
515
+ """
516
+
517
+ entries: list[BibEntry] = field(default_factory=list)
518
+ free_text: list[Reference] = field(default_factory=list)
519
+ warnings: list[str] = field(default_factory=list)
520
+ keys: dict[str, str] = field(default_factory=dict)
521
+ emaa: bool = False
522
+ n_files: int = 0
523
+
524
+ def text(self) -> str:
525
+ """The ``.bib`` file: a header with the database requests, then the entries with notes."""
526
+ from . import __version__
527
+
528
+ head = [
529
+ f"% References of {self.n_files} LAMDA file{'s' if self.n_files != 1 else ''}, by pylamda {__version__}."
530
+ ]
531
+ if any(e.key in LAMDA_KEYS for e in self.entries):
532
+ head.append(f"% {LAMDA_REQUEST}")
533
+ if self.emaa:
534
+ head.append(f"% EMAA asks for this acknowledgement: {EMAA_ACKNOWLEDGEMENT}")
535
+ parts = ["\n".join(head)]
536
+ for e in self.entries:
537
+ note = f"{e.note} (pylamda reference catalogue)" if e.source == "catalogue" else e.note
538
+ parts.append((f"% {note}\n" if note else "") + e.bibtex)
539
+ return "\n\n".join(parts) + "\n"
540
+
541
+ def write(self, path: str | os.PathLike) -> None:
542
+ """Write :meth:`text` to ``path``."""
543
+ Path(path).write_text(self.text(), encoding="utf-8")
544
+
545
+
546
+ # ------------------------------------------------------------------- export
547
+ @dataclass
548
+ class _Work:
549
+ """One cited work: its identifiers and what it is used for."""
550
+
551
+ identifiers: list[str]
552
+ text: str
553
+ uses: dict[str, list[str]] = field(default_factory=dict) # molecule -> uses
554
+ bibcode: str | None = None
555
+ bibtex: str | None = None
556
+ source: str = "unresolved"
557
+ catalogue_key: str | None = None
558
+
559
+ def add_use(self, molecule: str, use: str) -> None:
560
+ uses = self.uses.setdefault(molecule, [])
561
+ if use not in uses:
562
+ uses.append(use)
563
+
564
+ @property
565
+ def note(self) -> str:
566
+ return "; ".join(f"{mol}: {', '.join(uses)}" for mol, uses in self.uses.items())
567
+
568
+
569
+ def _from_catalogue(
570
+ cat, data: LamdaData, fname: str | None, ref: Reference, works: dict, result: BibResult
571
+ ) -> list[str]:
572
+ """Add the papers of a free-text reference that the catalogue knows; return the parts it does not know."""
573
+ unresolved = []
574
+ for seg, hit in cat.find_all(ref.text, molecule=data.molecule, file=fname, role=ref.role, partner=ref.partner):
575
+ if hit is None or hit.key is None:
576
+ unresolved.append(seg)
577
+ continue
578
+ ident = f"bibcode:{hit.bibcode}"
579
+ w = works.get(ident)
580
+ if w is None:
581
+ ids = [ident] + ([f"doi:{hit.doi}"] if hit.doi else [])
582
+ w = works[ident] = _Work(
583
+ ids, seg, bibcode=hit.bibcode, bibtex=cat.bibtex.get(hit.key), source="catalogue", catalogue_key=hit.key
584
+ )
585
+ w.add_use(data.molecule, ref.use)
586
+ if hit.match == "text":
587
+ result.warnings.append(
588
+ f"{fname or data.molecule}: {seg!r} found in the reference catalogue by its text only "
589
+ f"({hit.key}, cited there for another molecule): check it"
590
+ )
591
+ return unresolved
592
+
593
+
594
+ def database_entries() -> dict[str, str]:
595
+ """The shipped BibTeX entries of the LAMDA and EMAA papers, by key.
596
+
597
+ Returns
598
+ -------
599
+ dict of str to str
600
+ Key -> entry, from ``pylamda/data/database_refs.bib``.
601
+ """
602
+ text = files("pylamda").joinpath("data/database_refs.bib").read_text(encoding="utf-8")
603
+ return {entry_key(e): e for e in split_entries(text)}
604
+
605
+
606
+ def bibtex(
607
+ sources: Iterable[LamdaData | str | os.PathLike],
608
+ *,
609
+ online: bool = False,
610
+ token: str | None = None,
611
+ database_refs: bool = True,
612
+ keys: dict[str, str] | None = None,
613
+ cache: bool | str | os.PathLike = True,
614
+ catalogue: bool = True,
615
+ client: object | None = None,
616
+ ) -> BibResult:
617
+ """The BibTeX entries of the references of LAMDA files.
618
+
619
+ Parameters
620
+ ----------
621
+ sources : iterable of LamdaData, str or os.PathLike
622
+ Data sets or files (read with :func:`pylamda.read`).
623
+ online : bool, optional
624
+ Resolve the identifiers with SciX and doi.org. Default: False (``@misc``
625
+ entries with the identifiers).
626
+ token : str or None, optional
627
+ SciX API token; default: :func:`scix_token` (environment, token file).
628
+ database_refs : bool, optional
629
+ Add the main papers of LAMDA (always) and EMAA (if a file comes from EMAA).
630
+ Default: True.
631
+ keys : dict of str to str or None, optional
632
+ Identifier -> key from an earlier run, to keep keys stable.
633
+ cache : bool, str or os.PathLike, optional
634
+ Cache of resolved references: True = :func:`default_cache`, False = none, or a
635
+ file. Default: True.
636
+ catalogue : bool, optional
637
+ Look up free-text references in the shipped reference catalogue
638
+ (:mod:`pylamda.catalogue`); found ones become entries with source ``"catalogue"``,
639
+ without network. Default: True.
640
+ client : object or None, optional
641
+ The HTTP client (default :class:`HttpClient`); tests pass a fake one.
642
+
643
+ Returns
644
+ -------
645
+ BibResult
646
+ The entries, the free-text references, warnings and the keys.
647
+
648
+ Raises
649
+ ------
650
+ LamdaReadError
651
+ If a file cannot be read.
652
+ BibError
653
+ If SciX rejects the token.
654
+ """
655
+ datas = [s if isinstance(s, LamdaData) else read(s) for s in sources]
656
+ result = BibResult(n_files=len(datas), emaa=any(is_emaa(d) for d in datas))
657
+
658
+ works: dict[str, _Work] = {}
659
+ cat = load_catalogue() if catalogue else None
660
+ for d in datas:
661
+ fname = Path(d.source_map.path).name if d.source_map else None
662
+ for ref in collect_references(d):
663
+ if not ref.identifiers and ref.role in ("levels", "collisions"):
664
+ unresolved = _from_catalogue(cat, d, fname, ref, works, result) if cat else [ref.text]
665
+ if unresolved:
666
+ text = "; ".join(unresolved)
667
+ result.free_text.append(ref if text == ref.text else replace(ref, text=text))
668
+ for ident in ref.identifiers:
669
+ w = works.setdefault(ident, _Work([ident], identifier_context(ref.text, ident)))
670
+ w.add_use(d.molecule, ref.use)
671
+
672
+ if cat is not None: # identifiers whose paper the catalogue knows: its reviewed BibTeX, offline
673
+ known = {}
674
+ for key, e in cat.entries.items():
675
+ known[f"bibcode:{e['bibcode']}".lower()] = key
676
+ if e.get("doi"):
677
+ known[f"doi:{e['doi']}".lower()] = key
678
+ for w in works.values():
679
+ key = next((known[i.lower()] for i in w.identifiers if i.lower() in known), None)
680
+ if key is not None and w.bibtex is None and key in cat.bibtex:
681
+ w.bibcode, w.bibtex, w.source = cat.entries[key]["bibcode"], cat.bibtex[key], "catalogue"
682
+ w.catalogue_key = key
683
+
684
+ if online and works:
685
+ cache_path = default_cache() if cache is True else (Path(cache) if cache else None)
686
+ _resolve(list(works.values()), client or HttpClient(scix_token(token)), _Cache(cache_path), result)
687
+
688
+ # merge works that are the same paper (same bibcode or DOI)
689
+ merged: list[_Work] = []
690
+ by_id: dict[str, _Work] = {}
691
+ for w in works.values():
692
+ ids = [i.lower() for i in w.identifiers]
693
+ if w.bibcode:
694
+ ids.append(f"bibcode:{w.bibcode}".lower())
695
+ if w.bibtex and entry_field(w.bibtex, "doi"):
696
+ ids.append(f"doi:{entry_field(w.bibtex, 'doi')}".lower())
697
+ same = next((by_id[i] for i in ids if i in by_id), None)
698
+ if same is None:
699
+ merged.append(w)
700
+ same = w
701
+ else:
702
+ same.identifiers += [i for i in w.identifiers if i not in same.identifiers]
703
+ for mol, uses in w.uses.items():
704
+ for u in uses:
705
+ same.add_use(mol, u)
706
+ if same.bibtex is None and w.bibtex is not None:
707
+ same.bibtex, same.bibcode, same.source = w.bibtex, w.bibcode, w.source
708
+ for i in ids:
709
+ by_id.setdefault(i, same)
710
+
711
+ # the database papers
712
+ used_keys: set[str] = set()
713
+ if database_refs:
714
+ db = database_entries()
715
+ wanted = [*LAMDA_KEYS, *(EMAA_KEYS if result.emaa else ())]
716
+ db_ids: dict[str, BibEntry] = {}
717
+ for key in wanted:
718
+ e = BibEntry(key, db[key], "database", note=_DATABASE_NOTES.get(key, "database"))
719
+ doi = entry_field(db[key], "doi")
720
+ adsurl = entry_field(db[key], "adsurl") or ""
721
+ for ident in (f"doi:{doi}" if doi else None, f"bibcode:{adsurl[len(SCIX_ABS) :]}" if adsurl else None):
722
+ if ident:
723
+ e.identifiers.append(ident)
724
+ db_ids[ident.lower()] = e
725
+ result.entries.append(e)
726
+ used_keys.add(key)
727
+ kept = []
728
+ for w in merged:
729
+ ids = {i.lower() for i in w.identifiers} | ({f"bibcode:{w.bibcode}".lower()} if w.bibcode else set())
730
+ hit = next((db_ids[i] for i in ids if i in db_ids), None)
731
+ if hit is None:
732
+ kept.append(w)
733
+ else: # cited by a file too: one entry, with the file's use
734
+ hit.note = f"{hit.note}; {w.note}"
735
+ hit.identifiers += [i for i in w.identifiers if i not in hit.identifiers]
736
+ merged = kept
737
+
738
+ # keys and entries
739
+ keys = dict(keys or {})
740
+ for w in merged:
741
+ key = next((keys[i] for i in w.identifiers if i in keys), None)
742
+ if key is None and w.catalogue_key and w.catalogue_key not in used_keys:
743
+ key = w.catalogue_key
744
+ if key is None or key in used_keys:
745
+ base = (key_from_entry(w.bibtex) if w.bibtex else None) or key_from_text(w.text)
746
+ base = base or re.sub(r"[^A-Za-z0-9_.:-]", "_", w.identifiers[0].replace(":", "_", 1))
747
+ key = base
748
+ for suffix in "abcdefghijklmnopqrstuvwxyz":
749
+ if key not in used_keys:
750
+ break
751
+ key = base + suffix
752
+ used_keys.add(key)
753
+ entry = _set_key(w.bibtex, key) if w.bibtex else _misc(key, w.identifiers[0], w.note)
754
+ if w.source == "scix" and w.bibcode:
755
+ entry = _set_field(entry, "adsurl", f"{SCIX_ABS}{w.bibcode}")
756
+ result.entries.append(BibEntry(key, entry, w.source, list(w.identifiers), w.note))
757
+ for e in result.entries:
758
+ for i in e.identifiers:
759
+ result.keys[i] = e.key
760
+ return result
761
+
762
+
763
+ def _chunks(terms: list[str], field_name: str) -> list[str]:
764
+ """SciX queries ``field:"a" OR field:"b" ...`` below the length limit."""
765
+ out, current = [], ""
766
+ for t in terms:
767
+ part = f'{field_name}:"{t}"'
768
+ if current and len(current) + 4 + len(part) > _SEARCH_CHUNK:
769
+ out.append(current)
770
+ current = ""
771
+ current = f"{current} OR {part}" if current else part
772
+ if current:
773
+ out.append(current)
774
+ return out
775
+
776
+
777
+ def _resolve(works: list[_Work], client, cache: _Cache, result: BibResult) -> None:
778
+ """Resolve the works in place: SciX for bibcodes, DOIs, arXiv IDs; doi.org for other DOIs."""
779
+ works = [w for w in works if w.source != "catalogue"] # these come with their BibTeX
780
+ kind = {w.identifiers[0]: w.identifiers[0].split(":", 1) for w in works}
781
+ has_token = getattr(client, "has_token", True)
782
+
783
+ # 1. DOIs and arXiv IDs -> bibcodes (SciX search)
784
+ for w in works:
785
+ k, v = kind[w.identifiers[0]]
786
+ if k == "bibcode":
787
+ w.bibcode = v
788
+ elif k in ("doi", "arxiv"):
789
+ hit = cache.get(f"{k}_bibcode", v.lower())
790
+ if hit is not None:
791
+ w.bibcode = hit or None
792
+ if has_token:
793
+ for k, fieldname, prefix in (("doi", "doi", ""), ("arxiv", "identifier", "arXiv:")):
794
+ todo = sorted(
795
+ {
796
+ kind[w.identifiers[0]][1]
797
+ for w in works
798
+ if kind[w.identifiers[0]][0] == k
799
+ and cache.get(f"{k}_bibcode", kind[w.identifiers[0]][1].lower()) is None
800
+ }
801
+ )
802
+ if not todo:
803
+ continue
804
+ found: dict[str, str] = {}
805
+ for query in _chunks([prefix + v for v in todo], fieldname):
806
+ for doc in client.scix_search(query, "bibcode,doi,identifier"):
807
+ values = doc.get("doi" if k == "doi" else "identifier", []) or []
808
+ for v in todo:
809
+ target = (prefix + v).lower()
810
+ if any(str(x).lower() == target for x in values):
811
+ old = found.get(v.lower())
812
+ # prefer the journal record to an arXiv preprint record
813
+ if old is None or ("arXiv" in old and "arXiv" not in doc["bibcode"]):
814
+ found[v.lower()] = doc["bibcode"]
815
+ for v in todo:
816
+ cache.set(f"{k}_bibcode", v.lower(), found.get(v.lower(), ""))
817
+ for w in works:
818
+ kk, v = kind[w.identifiers[0]]
819
+ if kk == k and v.lower() in found:
820
+ w.bibcode = found[v.lower()]
821
+
822
+ # 2. bibcodes -> BibTeX (SciX export, one request per chunk)
823
+ need = sorted({w.bibcode for w in works if w.bibcode})
824
+ if has_token:
825
+ missing = [b for b in need if cache.get("bibtex", b) is None]
826
+ for i in range(0, len(missing), _EXPORT_CHUNK):
827
+ for entry in split_entries(client.scix_export(missing[i : i + _EXPORT_CHUNK])):
828
+ cache.set("bibtex", entry_key(entry), entry)
829
+ for w in works:
830
+ if w.bibcode and cache.get("bibtex", w.bibcode):
831
+ w.bibtex, w.source = cache.get("bibtex", w.bibcode), "scix"
832
+
833
+ # 3. DOIs not in SciX -> doi.org
834
+ for w in works:
835
+ k, v = kind[w.identifiers[0]]
836
+ if w.bibtex is None and k == "doi":
837
+ text = cache.get("doi_bibtex", v.lower())
838
+ if text is None:
839
+ text = client.doi_bibtex(v)
840
+ if text:
841
+ cache.set("doi_bibtex", v.lower(), text)
842
+ entries = split_entries(text or "")
843
+ if entries:
844
+ w.bibtex, w.source = entries[0], "doi.org"
845
+ else:
846
+ result.warnings.append(f"{w.identifiers[0]}: not found in SciX or at doi.org")
847
+ cache.save()
848
+
849
+ if not has_token:
850
+ n = sum(1 for w in works if w.bibtex is None and kind[w.identifiers[0]][0] in ("bibcode", "arxiv"))
851
+ if n:
852
+ result.warnings.append(
853
+ f"{n} bibcodes/arXiv IDs not resolved: SciX needs an API token (SCIX_API_TOKEN or {token_file()})"
854
+ )
855
+ for w in works:
856
+ if w.bibcode and w.bibtex is None and has_token:
857
+ result.warnings.append(f"bibcode {w.bibcode}: not found in SciX")
858
+ elif kind[w.identifiers[0]][0] == "arxiv" and w.bibtex is None and has_token:
859
+ result.warnings.append(f"{w.identifiers[0]}: not found in SciX")