Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,16 @@ Unreleased
does not bundle are under ``migrate/config/licenses/``, each cited with its URL and
sha256. A template or sidecar without an entry keeps its License (M203); a license
without a text blocks a plan (M211). CHANGES entries say what changed in the licenses.
* The atlases of the migration to TemplateFlow 2.0 (``tfmanager.migrate.atlases``, T04):
the config's ``atlases`` gives a row of ``tpl-<label>_atlases.tsv`` for each of the 35
atlases of the Archive (name, description, authors, curators, references), each citing
its sources, with the license of its ``licenses.table`` entry. The sidecars of an atlas
in the table lose the fields of the atlas as a whole, which its generated
``atlas-<label>_description.json`` now holds. An atlas without a row keeps its sidecars
(M212). template_description.json writes Authors and Curators as "Family I" (T06), and
config ``edits`` may create a sidecar (``create: true``): the migration describes the
``desc`` and ``atlas`` values that renames drop, corrects authors, broken links and the
ages of the dhcp surface templates (postmenstrual weeks).
* New warning TF118 redundant-entity: a ``desc``, ``seg`` or ``label`` that tells its file
apart from no other file of the template (``res``, ``den``, ``hemi`` and ``cohort``
aside). Masks keep ``desc``, probabilistic segmentations keep ``label``, and
Expand Down
143 changes: 143 additions & 0 deletions tfmanager/migrate/atlases.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
"""T04: the atlases table of a template, from the cited rows of the config (``atlases``).

* ``tpl-<label>_atlases.tsv`` has one row per atlas of the template's files: the config's
columns, and the license of the atlas's entry in ``licenses``; the columns are those of
BIDS and TemplateFlow (``ATLAS_COLUMNS``) that some row fills, in that order;
* the JSON sidecars of the files of those atlases lose the fields of the atlas as a whole:
those of the atlas description (``ATLAS_LEVEL_FIELDS``, TF608) and the fields that
described the atlas before 2.0 (``FORMER_FIELDS``). Fields about the files stay
(Description, Provenance, DeprecationNote, Source...);
* T08 then generates ``atlas-<label>_description.json`` from the table.

An atlas without a row in the config gets M212: the table leaves it out and its sidecars stay
as they are. A row whose atlas has no file is a stale decision (M108).
"""

from __future__ import annotations

import json

from ..generate import ATLAS_COLUMNS
from ..naming import parse
from ..tables import NA, dump_json, write_tsv
from ..validate.atlases import ATLAS_LEVEL_FIELDS
from .config import Config
from .findings import Finding
from .lookups import Write

CODE = 'T04'
#: Fields that described the whole atlas in sidecars before 2.0 (DiedrichsenLab's and
#: TemplateFlow's): the row of the atlases table holds what they said
FORMER_FIELDS = (
'Name',
'ShortDesc',
'LongDesc',
'IsDerivedFrom',
'BIDSVersion',
'Maps',
'Type',
'MapDesc',
)
SIDECAR_FIELDS = ATLAS_LEVEL_FIELDS + FORMER_FIELDS


def table_path(template: str) -> str:
return f'{template}_atlases.tsv'


def _cell(value) -> str:
if isinstance(value, list):
return json.dumps(value, ensure_ascii=False)
return str(value)


def atlases_table(rows: list[dict]) -> str:
"""The atlases table of ``rows`` (column -> value; lists become JSON arrays).

>>> print(atlases_table([{'atlas_id': 'atlas-A', 'name': 'A', 'license': 'CC0-1.0',
... 'authors': ['Doe J']},
... {'atlas_id': 'atlas-B', 'name': 'B', 'license': 'MIT'}]), end='')
atlas_id name license authors
atlas-A A CC0-1.0 ["Doe J"]
atlas-B B MIT n/a
"""
used = {c for row in rows for c in row}
columns = [c for c, level in ATLAS_COLUMNS.items() if level == 'required' or c in used]
cells = [{c: _cell(row[c]) if c in row else NA for c in columns} for row in rows]
return write_tsv(columns, cells)


def plan_atlases(
template: str,
files: dict[str, bytes | None],
write: Write,
config: Config,
) -> list[Finding]:
"""T04 for one template: write its atlases table and clean the sidecars of its atlases."""
findings: list[Finding] = []
parsed = {p: parse(p) for p in sorted(files, key=str.encode)}
parsed = {p: f for p, f in parsed.items() if f.is_bids}
labels = {f.entities['atlas'] for f in parsed.values() if 'atlas' in f.entities}
rows = {item.atlas: item for item in config.atlases_for(template)}
licenses = {item.atlas: item.license for item in config.licenses_for(template) if item.atlas}

for label in sorted(set(rows) - labels):
message = f'atlas-{label} has a row in the config but no file (after the renames).'
findings.append(Finding('M108', f'atlases/{template}/{label}', message))
for label in sorted(labels - set(rows)):
message = f'atlas-{label} has no row in the config: {table_path(template)} leaves it out.'
findings.append(Finding('M212', table_path(template), message))

described = sorted(labels & set(rows), key=str.encode)
if described:
table = [
{
'atlas_id': f'atlas-{label}',
'name': rows[label].columns['name'],
'license': licenses[label],
**{k: v for k, v in rows[label].columns.items() if k != 'name'},
}
for label in described
]
write(table_path(template), atlases_table(table).encode(), CODE)

for path, f in parsed.items():
if f.extension != '.json' or f.entities.get('atlas') not in described:
continue
data = files.get(path)
try:
sidecar = json.loads(data) if data is not None else None
except ValueError:
continue # reported by TF300
if not isinstance(sidecar, dict):
continue
kept = {k: v for k, v in sidecar.items() if k not in SIDECAR_FIELDS}
if kept != sidecar:
write(path, dump_json(kept).encode(), CODE)
return findings


def changes_item(template: str, before: dict, after: dict, done: dict) -> str | None:
"""T11: what T04 changed, for CHANGES (``None`` when nothing).

>>> item = changes_item('tpl-X', {'a.json': b'{}'}, {'tpl-X_atlases.tsv': b'', 'a.json': b''},
... {'tpl-X_atlases.tsv': ['T04'], 'a.json': ['T04']})
>>> item[:43]
'Atlases: tpl-X_atlases.tsv describes the at'
>>> item[-51:]
'fields of the atlas as a whole left 1 JSON sidecar.'
"""
path = table_path(template)
if path not in after:
return None
sidecars = sorted(
p for p, codes in done.items() if CODE in codes and p.endswith('.json') and p in before
)
item = (
f'Atlases: {path} describes the atlases (each row generates its'
' atlas-<label>_description.json)'
)
if sidecars:
n = len(sidecars)
item += f'; fields of the atlas as a whole left {n} JSON sidecar{"s" * (n != 1)}'
return item + '.'
59 changes: 59 additions & 0 deletions tfmanager/migrate/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ class Edit:
why: str
set: dict = field(default_factory=dict)
remove: tuple[str, ...] = ()
create: bool = False
"""Write the file (a sidecar) when it is missing and its data file exists."""

def apply(self, data: dict) -> dict:
out = {k: v for k, v in data.items() if k not in self.remove}
Expand Down Expand Up @@ -180,6 +182,18 @@ def scope(self) -> str:
return 'atlas' if self.atlas else 'files' if self.files else 'template'


@dataclass(frozen=True)
class Atlas:
"""A row of a template's atlases table (``atlases``); its license comes from ``licenses``."""

template: str
atlas: str
columns: dict
"""atlases.tsv column -> value (a string, an integer, or a list of strings)."""
evidence: str
why: str = ''


@dataclass(frozen=True)
class Config:
version: str
Expand All @@ -195,11 +209,15 @@ class Config:
participants: tuple[Participants, ...] = ()
license_texts: tuple[LicenseText, ...] = ()
licenses: tuple[License, ...] = ()
atlases: tuple[Atlas, ...] = ()
digest: str = ''

def licenses_for(self, template: str) -> list[License]:
return [item for item in self.licenses if item.template == template]

def atlases_for(self, template: str) -> list[Atlas]:
return [item for item in self.atlases if item.template == template]

def license_text(self, license: str) -> str | None:
"""The text of a license: from the config, or bundled with tfmanager."""
from ..add import BUNDLED_LICENSES
Expand Down Expand Up @@ -291,6 +309,8 @@ def _check(data: dict) -> list[str]:
if set(item['describe']) != wanted:
problems.append(f'participants {item["id"]}: describe exactly {sorted(wanted)}.')
for item in data.get('edits', []):
if item.get('create') and item.get('remove'):
problems.append(f'edits {item["id"]}: a file it creates has nothing to remove.')
both = set(item.get('set', {})) & set(item.get('remove', []))
if both:
problems.append(f'edits {item["id"]}: sets and removes {", ".join(sorted(both))}.')
Expand Down Expand Up @@ -451,6 +471,41 @@ def _license_table(data: dict, texts: list[LicenseText]) -> tuple[list[License],
return entries, problems


def _atlas_rows(data: dict, table: list[License]) -> tuple[list[Atlas], list[str]]:
"""The rows of the atlases tables: one per atlas, each with a license, people as "Family I"."""
from ..validate.atlases import PERSON

licensed = {(item.template, item.atlas) for item in table if item.atlas}
rows, problems, seen = [], [], set()
for item in data.get('atlases', []):
key = (item['template'], item['atlas'])
where = f'atlases {item["template"]} {item["atlas"]}'
if key in seen:
problems.append(f'{where}: listed twice.')
seen.add(key)
if key not in licensed:
problems.append(f'{where}: no entry of licenses.table gives its license.')
for column in ('authors', 'curators'):
for person in item.get(column, []):
if not PERSON.match(person):
problems.append(f'{where}: {column} {person!r} is not "Family I".')
if item.get('derived_from_atlas') == item['atlas']:
problems.append(f'{where}: derived from itself.')
columns = {
k: v for k, v in item.items() if k not in ('template', 'atlas', 'evidence', 'why')
}
rows.append(
Atlas(
template=item['template'],
atlas=item['atlas'],
columns=columns,
evidence=item['evidence'],
why=item.get('why', ''),
)
)
return rows, problems


def load_config(path: str | Path | None = None, version: str = '2.0.0') -> Config:
"""Load and check a config (by default, the one shipped for ``version``).

Expand Down Expand Up @@ -486,6 +541,8 @@ def load_config(path: str | Path | None = None, version: str = '2.0.0') -> Confi
problems += found
table, found = _license_table(data, texts)
problems += found
atlases, found = _atlas_rows(data, table)
problems += found
if problems:
raise ConfigError('\n'.join(problems))
# The digest covers the files the config cites (tables, license texts)
Expand Down Expand Up @@ -520,6 +577,7 @@ def load_config(path: str | Path | None = None, version: str = '2.0.0') -> Confi
why=e['why'],
set=e.get('set', {}),
remove=tuple(e.get('remove', ())),
create=e.get('create', False),
)
for e in data.get('edits', [])
),
Expand Down Expand Up @@ -557,6 +615,7 @@ def load_config(path: str | Path | None = None, version: str = '2.0.0') -> Confi
),
license_texts=tuple(texts),
licenses=tuple(table),
atlases=tuple(atlases),
digest=digest.hexdigest(),
)

Expand Down
Loading