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
19 changes: 17 additions & 2 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,27 @@ Unreleased
with 1 when there are files to write.
* ``tfmgr add`` writes the generated files of the template before validating it.
* New command ``tfmgr migrate headers ARCHIVE [--needs] [-o TSV]`` reads, with nibabel, the
facts of image headers that the migration to TemplateFlow 2.0 needs (grids of volumes
without ``res``, volumes of 4D probabilistic segmentations, GIFTI intents), from an
facts of image headers that the migration to TemplateFlow 2.0 needs (the grid of every
volume, volumes of 4D probabilistic segmentations, GIFTI intents), from an
Archive checkout whose image data are present (``--needs`` lists the files to fetch).
The table is keyed by md5, so migration plans need no image data; the facts of the
Archive are shipped with tfmanager (``migrate/data/headers-2.0.0.tsv``). Snapshots of
templates, from the v2 skeleton zip or from a checkout, have the same fingerprint.
* The new names of the migration to TemplateFlow 2.0: ``tfmanager.migrate.names`` renames
the files of a template (rules R01 to R20, then R99) from its snapshot, the header facts
and the decisions of ``migrate/config/2.0.0.yaml`` (atlas labels, renames of single
templates, ``res`` keys). Every volume takes the ``res`` key of its grid: blocks that no
file matches are rebuilt from their files, and volumes off their block take a new key.
Findings M101 to M113 block a plan (uncovered names come with a decision to fill in),
and ``migrate.renames`` merges and checks a template's ``.renames.tsv`` as the template
action reads it. A test pins the renames of the Archive
(``tests/data/renames-2.0.0.tsv``).
* 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
``desc-brain`` and the ``desc-tissues`` of tissue maps are always kept.
* ``probseg`` and ``midthickness`` take ``.shape.gii`` (probabilities and vertex areas on
a surface).
* New internals for ``tfmgr generate`` and ``tfmgr migrate``: ``GitTree`` reads a template
from a git commit without checking it out, ``collect_archive`` gathers what the
Archive's files and checks need from its templates, and ``renames_problems`` checks a
Expand Down
2 changes: 2 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ tfmanager =
schema/*.json
schema/*.yaml
migrate/data/*.tsv
migrate/config/*.yaml
migrate/config/*.json

[options.packages.find]
exclude =
Expand Down
172 changes: 172 additions & 0 deletions tfmanager/migrate/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
"""The decisions of a migration (``migrate/config/<version>.yaml``), checked before use."""

from __future__ import annotations

import hashlib
import json
import re
from dataclasses import dataclass, field
from importlib.resources import files
from pathlib import Path

import jsonschema
import yaml

from ..ruleset import load_ruleset
from ..validate.names import VERSION_LABEL

CONFIG_DIR = files('tfmanager.migrate') / 'config'
NAME_KEYS = ('suffix', 'extension')


class ConfigError(ValueError):
"""A config that breaks its schema or contradicts itself."""


@dataclass(frozen=True)
class Rename:
"""A decision about files of one template (``renames``)."""

id: str
template: str
match: dict
count: int
why: str
set: dict = field(default_factory=dict)
remove: bool = False

def matches(self, entities: dict, suffix: str | None, extension: str) -> bool:
have = {**entities, 'suffix': suffix, 'extension': extension}
for key, want in self.match.items():
value = have.get(key)
if want is None and value is not None:
return False
if isinstance(want, str) and value != want:
return False
if isinstance(want, list) and value not in want:
return False
return True


@dataclass(frozen=True)
class Config:
version: str
policies: dict
atlas_labels: tuple[dict, ...] = ()
renames: tuple[Rename, ...] = ()
res_assign: dict = field(default_factory=dict)
"""``tpl-<label>/<path>`` -> ``{'res': key, 'why': ...}``."""
digest: str = ''

def atlas_label(self, template: str, label: str) -> str | None:
for item in self.atlas_labels:
if item['template'] == template and item['from'] == label:
return item['to']
return None

def renames_for(self, template: str) -> list[Rename]:
return [r for r in self.renames if r.template == template]

def assigned(self, template: str) -> dict[str, str]:
prefix = f'{template}/'
return {
path.removeprefix(prefix): item['res']
for path, item in self.res_assign.items()
if path.startswith(prefix)
}


def _schema() -> dict:
return json.loads((CONFIG_DIR / 'schema.json').read_text())


def _check(data: dict) -> list[str]:
"""Problems a schema cannot see."""
rs = load_ruleset()
extensions = {e for suffix in rs.suffixes.values() for e in suffix['extensions']}
problems = []
seen = set()
for item in data.get('atlas_labels', []):
key = (item['template'], item['from'])
if key in seen:
problems.append(f'atlas_labels: {item["from"]} listed twice for {item["template"]}.')
seen.add(key)
to = item['to']
if not rs.entities['atlas'].valid(to) or not to[:1].isupper() or VERSION_LABEL.match(to):
problems.append(f'atlas_labels: {to!r} is not an atlas name.')
froms = {(i['template'], i['from']) for i in data.get('atlas_labels', [])}
for item in data.get('atlas_labels', []):
if (item['template'], item['to']) in froms:
problems.append(f'atlas_labels: {item["to"]} is renamed again (a chain).')
ids = [r['id'] for r in data.get('renames', [])]
for dup in sorted({i for i in ids if ids.count(i) > 1}):
problems.append(f'renames: the id {dup} is used twice.')
for item in data.get('renames', []):
for part in ('match', 'set'):
for key, value in item.get(part, {}).items():
if key in NAME_KEYS:
# A name always keeps a suffix and an extension (null: the schema says no)
if part == 'set' and key == 'suffix' and value not in rs.suffixes:
problems.append(f'renames {item["id"]}: unknown suffix {value!r}.')
if part == 'set' and key == 'extension' and value not in extensions:
problems.append(f'renames {item["id"]}: unknown extension {value!r}.')
continue
Comment thread
oesteban marked this conversation as resolved.
Resolved
entity = rs.entities.get(key)
if entity is None:
problems.append(f'renames {item["id"]}: unknown entity {key!r}.')
elif part == 'set' and value is not None and not entity.valid(value):
problems.append(f'renames {item["id"]}: {key}-{value} is not valid.')
return 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``)."""
text = Path(path).read_text() if path else (CONFIG_DIR / f'{version}.yaml').read_text()
data = yaml.safe_load(text)
try:
jsonschema.validate(data, _schema())
except jsonschema.ValidationError as exc:
where = '/'.join(str(p) for p in exc.absolute_path)
raise ConfigError(f'{where or "config"}: {exc.message}') from exc
problems = _check(data)
if problems:
raise ConfigError('\n'.join(problems))
return Config(
version=data['version'],
policies=data['policies'],
atlas_labels=tuple(data.get('atlas_labels', [])),
renames=tuple(
Rename(
id=r['id'],
template=r['template'],
match=r['match'],
count=r['count'],
why=r['why'],
set=r.get('set', {}),
remove=r.get('remove', False),
)
for r in data.get('renames', [])
),
res_assign=dict(data.get('res_assign', {})),
digest=hashlib.sha256(text.encode()).hexdigest(),
)


def proposal(template: str, match: dict, count: int, n: int = 1) -> str:
"""A ``renames`` entry to fill in, for files no rule covers (M101).

>>> print(proposal('tpl-X', {'suffix': 'roi', 'extension': '.shape.gii'}, 4), end='')
- id: X-1
template: tpl-X
match: {suffix: "roi", extension: ".shape.gii"}
set: {} # the new entities, suffix or extension (or remove: true)
count: 4
why: ...
"""
body = ', '.join(f'{k}: {json.dumps(v)}' for k, v in match.items())
ident = re.sub(r'[^A-Za-z0-9-]', '-', template.removeprefix('tpl-'))
return (
f'- id: {ident}-{n}\n template: {template}\n match: {{{body}}}\n'
' set: {} # the new entities, suffix or extension (or remove: true)\n'
f' count: {count}\n why: ...\n'
)
144 changes: 144 additions & 0 deletions tfmanager/migrate/config/2.0.0.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
# Migration of the Archive to TemplateFlow 2.0: the decisions the rules need.
#
# Every entry says why (with evidence), and the engine checks that each one still matches
# the files it was written for (M108). Paths are relative to the Archive (tpl-<label>/...).
version: 2.0.0

policies:
# A new res key is the voxel size when it is an integer, isotropic and free; otherwise the
# smallest free index.
res_key: zoom

# R01: atlas labels that are versions or typos become names (author and year)
atlas_labels:
- template: tpl-WHS
from: v3
to: Osen2019
evidence: >-
Version 3 of the Waxholm Space atlas of the Sprague Dawley rat brain is the release of
Osen, Imad, Wennberg, Papp and Leergaard (2019), "Waxholm Space atlas of the rat brain
auditory system: Three-dimensional delineations based on structural and diffusion
tensor magnetic resonance imaging", NeuroImage
(https://doi.org/10.1016/j.neuroimage.2019.05.016, per Crossref), cited by the
template's description.
- template: tpl-Fischer344
from: v4
to: Goerzen2020
evidence: >-
Zenodo record 10.5281/zenodo.3555555, "An MRI-Derived Neuroanatomical Atlas of the
Fischer 344 Rat Brain", version v4 (2020-06-18), by Goerzen, Fowler, Devenyi, Germann
et al., described in Scientific Reports (2020,
https://doi.org/10.1038/s41598-020-63965-x).
- template: tpl-MNI152NLin2009cSym
from: CerebA
to: CerebrA
evidence: >-
A typo in the name of the lookup table only: the image of the same atlas is
tpl-MNI152NLin2009cSym_res-1_atlas-CerebrA_dseg.nii.gz.

# Decisions about single templates, applied before the rules (which still apply after them).
# `match` selects files by entity (a value, a list of values, or null for an absent entity),
# `suffix` and `extension`; `set` writes entities (null removes one), `suffix` and
# `extension`; `remove: true` removes the files (rows `n/a`: their old names keep serving).
renames:
- id: dhcpAsym-parcellation
template: tpl-dhcpAsym
match: {suffix: label, extension: .gii}
set: {suffix: dseg, extension: .label.gii}
count: 18
why: >-
17-label parcellations (int32, LABEL intent) with no suffix; the same DrawEM regions
as dhcpVol's desc-structures. Plain dseg: nothing else in dhcpAsym to tell apart.
- id: dhcpAsym-cortex
template: tpl-dhcpAsym
match: {suffix: roi, extension: .shape.gii}
set: {label: cortex, suffix: probseg}
count: 18
why: >-
An averaged cortex ROI (float32 from 0 to 1, non-zero exactly where the parcellation
is): a probability of cortex on the surface (probseg takes .shape.gii in 2.0).
- id: tissues-RESILIENT
template: tpl-RESILIENT
match: {atlas: WHS, desc: Cerebrum3TissueLabels, suffix: dseg}
set: {atlas: null, desc: tissues}
count: 4
why: >-
Tissue maps are not atlases: desc-tissues, as dhcpVol. What atlas-WHS and
desc-Cerebrum3TissueLabels said goes into the JSON sidecar.
- id: tissues-Fischer344
template: tpl-Fischer344
match: {atlas: null, desc: null, suffix: dseg}
set: {desc: tissues}
count: 1
why: >-
A tissue map with no table: for each label, at least 96% of its voxels have their
highest probability in one of the template's probsegs (1 GM, 2 WM, 3 CSF, 4 other).
- id: tissues-NMT31Sym
template: tpl-NMT31Sym
match: {desc: tissue}
set: {desc: tissues}
count: 2
why: The tissue maps of the Archive are desc-tissues (plural).
- id: tissues-NKI
template: tpl-NKI
match: {desc: '6'}
set: {desc: tissues}
count: 2
why: >-
Six tissue classes (CSF, cortical GM, subcortical GM, WM, brainstem, cerebellum),
per its lookup table.
- id: tissues4-OASIS30ANTs
template: tpl-OASIS30ANTs
match: {desc: '4'}
set: {desc: tissues4}
count: 2
why: Four tissue classes (CSF, cortical GM, subcortical GM, WM), per its lookup table.
- id: tissues6-OASIS30ANTs
template: tpl-OASIS30ANTs
match: {desc: '6'}
set: {desc: tissues6}
count: 2
why: Six tissue classes, per its lookup table (desc-tissues4 is the other tissue map).
- id: drop-desc-fMRIPrep
template: tpl-MNI152NLin2009cAsym
match: {desc: fMRIPrep}
set: {desc: null}
count: 1
why: The desc tells this file apart from no other; its meaning goes into the JSON sidecar.
- id: drop-desc-DC
template: tpl-MouseIn
match: {desc: DC}
set: {desc: null}
count: 1
why: The desc tells this file apart from no other; its meaning goes into the JSON sidecar.
- id: drop-desc-reg
template: tpl-dhcpAsym
match: {desc: reg}
set: {desc: null}
count: 2
why: The desc tells these files apart from no other; its meaning goes into the JSON sidecar.
- id: drop-desc-avgseg
template: tpl-UNCInfant
match: {desc: avgseg}
set: {desc: null}
count: 3
why: The desc tells these files apart from no other; its meaning goes into the JSON sidecar.
- id: NMT31Sym-stacks
template: tpl-NMT31Sym
match: {atlas: [CHARM, SARM], desc: null, scale: null, suffix: dseg}
remove: true
count: 6
why: >-
5D images (x, y, z, 1, 6) whose six volumes equal the six level images, and their
tables; the level images have their own tables.

# Keys of files whose grid is known to be wrong (a data fix follows), or ambiguous (M109)
res_assign:
tpl-Fischer344/tpl-Fischer344_hemi-L_desc-brain_mask.nii.gz:
res: '1'
why: >-
Stored with x and z swapped (data and affine); transposed back, it covers the brain
mask of res-1 (Dice 0.997). The transpose is a data fix of the template's 2.0 PR.
tpl-Fischer344/tpl-Fischer344_hemi-R_desc-brain_mask.nii.gz:
res: '1'
why: As its hemi-L twin.
Loading