Coverage for src/scixplorer/models/affiliation.py: 98%
127 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-18 23:06 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-18 23:06 +0000
1"""Institutions known to SciX, from ``affiliations.tsv`` and ``affiliations_country.tsv``:
2the copies downloaded by :func:`scixplorer.data.refresh` if there are any, else the
3packaged snapshot.
5Both files come unmodified from the ``adsabs/CanonicalAffiliations``
6repository (GPL-3.0; see ``NOTICE.md`` in :mod:`scixplorer.data`).
8``affiliations.tsv`` has one row per (parent, child) pair, with parent ``0``
9meaning "no parent"; an affiliation listed under several parents is merged into
10one :class:`Affiliation`. Countries come from ``affiliations_country.tsv``,
11whose columns are found by heading: ``ISO Country, Country, Parent, Child,
12...``. An older layout, ``Country, [Aff_id_parent], Aff_id_child, ...``, with
13no ISO codes, is still read (a cache written by an earlier version may hold it).
14"""
16from __future__ import annotations
18import csv
19import dataclasses
20import functools
21from collections.abc import Iterator, Mapping
22from typing import ClassVar
24from .. import data
25from ..expr import NOTHING
26from ..fields import StringField
27from ..model import Model
28from ..query import MemoryBackend, Query
30__all__ = ["Affiliation"]
32#: Parent id used in ``affiliations.tsv`` for an affiliation without a parent.
33NO_PARENT = "0"
36#: Header of ``affiliations.tsv``.
37AFFILIATION_COLUMNS = ["Parent", "Child", "Abbrev", "Canonical Name"]
39#: Accepted headings of the country file's columns, by meaning. Only ``code`` may be absent.
40COUNTRY_COLUMNS = {
41 "country": ("Country",),
42 "code": ("ISO Country",),
43 "parent": ("Parent", "[Aff_id_parent]"),
44 "child": ("Child", "Aff_id_child"),
45}
48def _read_tsv(text: str) -> tuple[list[str], Iterator[list[str]]]:
49 """The header of a TSV file and an iterator over its non-blank data rows (fields stripped)."""
50 rows = csv.reader(text.splitlines(), delimiter="\t", quoting=csv.QUOTE_NONE)
51 header = [value.strip() for value in next(rows, [])]
53 def data_rows() -> Iterator[list[str]]:
54 for row in rows:
55 row = [value.strip() for value in row]
56 if any(row):
57 yield row
59 return header, data_rows()
62@dataclasses.dataclass(frozen=True)
63class _Country:
64 """A country as one row of the country file gives it."""
66 name: str
67 code: str | None
70def _fit(row: list[str], width: int) -> list[str] | None:
71 """``row`` with exactly ``width`` fields, or ``None`` if that cannot be done without guessing.
73 A short row is padded with empty fields. A long row loses surplus empty
74 fields, but only if all its empty fields are adjacent, so that it does not
75 matter which of them are dropped (upstream has a row with one tab too many
76 between an empty parent and the child).
77 """
78 excess = len(row) - width
79 if excess <= 0:
80 return row + [""] * -excess
81 empty = [i for i, value in enumerate(row) if not value]
82 if len(empty) < excess or empty != list(range(empty[0], empty[0] + len(empty))):
83 return None
84 return row[: empty[0]] + row[empty[0] + excess :]
87def _countries(text: str) -> dict[str, _Country]:
88 """Map ``"parent|child"`` to country from the country file, finding its columns by heading.
90 Rows that cannot be fitted to the header (see :func:`_fit`) are skipped.
91 """
92 header, rows = _read_tsv(text)
93 index: dict[str, int] = {}
94 for meaning, headings in COUNTRY_COLUMNS.items():
95 found = [header.index(heading) for heading in headings if heading in header]
96 if found:
97 index[meaning] = found[0]
98 elif meaning != "code":
99 raise ValueError(f"affiliations_country.tsv has no {' or '.join(headings)} column: {header}")
100 countries: dict[str, _Country] = {}
101 for raw in rows:
102 row = _fit(raw, len(header))
103 if row is None:
104 continue
105 code = row[index["code"]] if "code" in index else ""
106 countries[f"{row[index['parent']]}|{row[index['child']]}"] = _Country(row[index["country"]], code or None)
107 return countries
110def _country(countries: Mapping[str, _Country], parent: str, child: str) -> _Country | None:
111 """The first country with a name found for one (parent, child) row.
113 Keys are tried in the order of the previous implementation: the exact pair,
114 then the child with no parent, then the parent with no child. The country
115 file leaves the parent empty where ``affiliations.tsv`` has ``0``, so
116 top-level affiliations resolve through the second key.
117 """
118 for key in (f"{parent}|{child}", f"|{child}", f"{parent}|"):
119 country = countries.get(key)
120 if country is not None and country.name:
121 return country
122 return None
125@dataclasses.dataclass
126class _Merged:
127 """The rows of ``affiliations.tsv`` for one affiliation id, merged."""
129 abbreviation: str
130 canonical_name: str
131 parent_ids: list[str] = dataclasses.field(default_factory=list)
132 country: _Country | None = None
135def _parse(read: data.Reader) -> tuple[Affiliation, ...]:
136 """Read and merge every affiliation from the two data files."""
137 countries = _countries(read("affiliations_country.tsv"))
139 header, rows = _read_tsv(read("affiliations.tsv"))
140 if header != AFFILIATION_COLUMNS:
141 raise ValueError(f"affiliations.tsv should have the columns {AFFILIATION_COLUMNS}, not {header}")
142 merged: dict[str, _Merged] = {}
143 for parent, child, abbreviation, canonical_name in rows:
144 entry = merged.setdefault(child, _Merged(abbreviation, canonical_name))
145 if parent and parent != NO_PARENT and parent not in entry.parent_ids:
146 entry.parent_ids.append(parent)
147 if entry.country is None:
148 entry.country = _country(countries, parent, child)
150 return tuple(
151 Affiliation(
152 id=child,
153 abbreviation=entry.abbreviation,
154 canonical_name=entry.canonical_name,
155 country=entry.country.name if entry.country else None,
156 country_code=entry.country.code if entry.country else None,
157 parent_ids=tuple(entry.parent_ids),
158 )
159 for child, entry in merged.items()
160 )
163@functools.lru_cache(maxsize=None)
164def _load() -> tuple[Affiliation, ...]:
165 """Every affiliation, read once (until :func:`_reset`)."""
166 return data.load("affiliations", _parse)
169def _reset() -> None:
170 """Forget the loaded affiliations, so the next query reads the data again."""
171 _load.cache_clear()
172 Affiliation._backend.clear()
175class Affiliation(Model):
176 """An institution, identified by its ADS canonical affiliation id (e.g. ``'A00211'``).
178 Affiliations are held in memory and queried locally::
180 affiliations = (
181 Affiliation
182 .select()
183 .where(Affiliation.country_code == "AU")
184 .order_by(Affiliation.abbreviation)
185 )
187 Countries are spelled out as the upstream data spells them ("United
188 States", "United Kingdom"), and those spellings can change between
189 releases of the data; ``country == "USA"`` simply matches nothing. Filter on
190 :attr:`country_code` (ISO 3166-1 alpha-2, e.g. "US") for a stable condition.
192 Institutions form a hierarchy (a department within a university): see
193 :attr:`parents`, :attr:`children` and :attr:`siblings`.
194 """
196 _key = "id"
197 _backend: ClassVar[MemoryBackend[Affiliation]] = MemoryBackend(_load, key="id")
199 id = StringField("ADS canonical affiliation identifier, e.g. 'A00211'.")
200 abbreviation = StringField("Short name of the institution, e.g. 'Harvard U'.")
201 canonical_name = StringField("Full canonical name, e.g. 'Harvard University, Massachusetts'.")
202 country = StringField(
203 "Country of the institution, spelled out as the upstream data spells it (e.g. 'United States', "
204 "'United Kingdom'), or None if not known. Spellings may change between data releases: filter on "
205 "country_code for a stable condition."
206 )
207 country_code = StringField(
208 "ISO 3166-1 alpha-2 code of the country as the upstream data gives it (e.g. 'US', 'GB', 'AU'), "
209 "or None if not known (also with data in the older layout, which has no codes). The stable "
210 "way to filter by country."
211 )
212 parent_ids = StringField(
213 "Identifiers of the parent institutions, in data-file order (empty for a top-level one).",
214 multivalued=True,
215 )
217 @classmethod
218 def lookup(cls, affiliation_id: str) -> Affiliation | None:
219 """The affiliation with this id, or ``None``. Constant time."""
220 return cls._backend.lookup(affiliation_id)
222 @property
223 def parents(self) -> list[Affiliation]:
224 """The parent institutions, in :attr:`parent_ids` order (unknown ids skipped)."""
225 found = (self.lookup(parent_id) for parent_id in self.parent_ids or ())
226 return [parent for parent in found if parent is not None]
228 @property
229 def parent(self) -> Affiliation | None:
230 """The first parent institution, or ``None``."""
231 parents = self.parents
232 return parents[0] if parents else None
234 @property
235 def children(self) -> Query[Affiliation]:
236 """A query for the institutions that list this one as a parent."""
237 query = type(self).select()
238 if self.id is None: 238 ↛ 239line 238 didn't jump to line 239 because the condition on line 238 was never true
239 return query.where(NOTHING)
240 return query.where(Affiliation.parent_ids == self.id)
242 @property
243 def siblings(self) -> Query[Affiliation]:
244 """A query for the other institutions sharing at least one parent with this one."""
245 query = type(self).select()
246 if not self.parent_ids:
247 return query.where(NOTHING)
248 siblings = Affiliation.parent_ids.in_(self.parent_ids)
249 if self.id is not None: 249 ↛ 251line 249 didn't jump to line 251 because the condition on line 249 was always true
250 siblings &= Affiliation.id != self.id
251 return query.where(siblings)
253 def __str__(self) -> str:
254 return self.canonical_name or self.abbreviation or self.id or repr(self)
256 def __repr__(self) -> str:
257 if self.id is None:
258 return super().__repr__()
259 name = f" ({self.abbreviation})" if self.abbreviation else ""
260 return f"<Affiliation: id={self.id!r}{name}>"
263data.register("affiliations", _parse, _reset)