Repository navigation
feat(migrate): new names of the Archive (rules, res keys, decisions, guards) #21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
67b80c5
feat(rules): TF118 redundant-entity; surface probseg and midthickness
oesteban 8785f95
feat(migrate): header facts of every volume
oesteban 79450a5
feat(migrate): new names of the Archive (rules, res keys, decisions, …
oesteban 1961c18
test: pin TF118 on the legacy Archive (54 warnings)
oesteban ba9b4ce
fix(migrate): a decision cannot remove or invent a suffix or an exten…
oesteban File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| 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' | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.