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
8 changes: 8 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@ Unreleased
==========
* Python 3.13 or newer, following `SPEC 0 <https://scientific-python.org/specs/spec-0000/>`__
(tested on 3.13 to 3.15).
* New command ``tfmgr generate atlases|cohorts|templates|dataset|all [--check] [PATH]``
writes the files generated from metadata: the atlas descriptions and the cohorts table
of a template, and templates.tsv and dataset_description.json at the root of the
Archive. dataset_description.json follows BIDS 1.11 (``DatasetType: derivative``,
``License: LicenseRef-TemplateFlow-PerTemplate``), and its ``TemplateFlowVersion``
becomes 2.0.0 once every template is at 2.0.0. ``--check`` changes nothing and exits
with 1 when there are files to write.
* ``tfmgr add`` writes the generated files of the template before validating it.
* 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
21 changes: 19 additions & 2 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,23 @@ and values are only checked with ``--level content``, which needs ``tfmanager[co
and the images' data. The command exits with 1 when there are errors, and 2 when it
could not run.

Generating files
----------------
Some files are generated from the metadata, and ``tfmgr validate`` reports them when they
are missing or out of date. ``tfmgr generate`` writes them::

tfmgr generate all tpl-MyTemplate # atlas descriptions and cohorts table
tfmgr generate all path/to/templateflow # templates.tsv and dataset_description.json
tfmgr generate all tpl-MyTemplate --check # list what would change; change nothing

In a template, ``atlases`` writes an ``atlas-<label>_description.json`` for each row of
``tpl-<label>_atlases.tsv``, and ``cohorts`` writes ``tpl-<label>_cohorts.tsv`` (and its
sidecar) from the ``cohort`` block of template_description.json. At the root of the
Archive, ``templates`` writes templates.tsv and ``dataset`` writes dataset_description.json,
whose ``TemplateFlowVersion`` becomes 2.0.0 once every template is at 2.0.0. Files no
longer generated are deleted. With ``--check``, the command exits with 1 when there are
files to write.

Checking and fixing images
--------------------------
``tfmgr sanitize`` works like a linter on the images of a template (rules TF701 to
Expand Down Expand Up @@ -46,8 +63,8 @@ Adding a template needs DataLad, the GitHub CLI (``gh``) and the TemplateFlow cl

``tfmgr add`` asks for the metadata that template_description.json misses (with an SPDX
license identifier), copies the template into a DataLad dataset without changing it
(``--fix`` and ``--fix-unsafe`` apply ``tfmgr sanitize`` fixes to the copies), and checks
it with ``tfmgr validate --mode strict --level content``: errors stop it before anything
(``--fix`` and ``--fix-unsafe`` apply ``tfmgr sanitize`` fixes to the copies), writes the
generated files (as ``tfmgr generate all``), and checks it with ``tfmgr validate --mode strict --level content``: errors stop it before anything
is uploaded. The data then go to GIN, the dataset to GitHub, and a pull request proposes
the template to the Archive. Each step is recorded in a work directory (by default in
the user's cache directory; ``--workdir`` sets another one), so a run that fails resumes
Expand Down
18 changes: 17 additions & 1 deletion tfmanager/add.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@

1. ``copy``: the source folder is copied, byte for byte, into a DataLad dataset, with the
template's metadata and LICENSE (``--fix``/``--fix-unsafe`` then apply
``tfmgr sanitize`` to the copies);
``tfmgr sanitize`` to the copies), and the generated files are written (atlas
descriptions and the cohorts table, as ``tfmgr generate all`` does);
2. ``validate``: the TemplateFlow rules, strict and with image content: errors stop the
run here, before anything is uploaded;
3. ``save``: ``datalad save``;
Expand Down Expand Up @@ -421,6 +422,21 @@ def step_copy(self, state: State) -> None:
self.echo(f' fixed {path}: {", ".join(codes)}')
for line in updated:
self.echo(f' updated {line}')
self.generate(dataset)

def generate(self, dataset: Path) -> None:
"""Write the atlas descriptions and the cohorts table (``tfmgr generate all``)."""
from .generate import GenerateError, pending, template_outputs, write_outputs
from .tree import DirectoryTree

try:
outputs = template_outputs(DirectoryTree(dataset))
except GenerateError as exc:
raise AddError(str(exc)) from exc
changes = pending(dataset, outputs)
write_outputs(dataset, outputs, changes)
for change in changes:
self.echo(f' {change.action}d {change.path}')

def step_validate(self, state: State) -> None:
from .tree import DirectoryTree
Expand Down
56 changes: 56 additions & 0 deletions tfmanager/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,62 @@ def validate(paths, mode, level, fmt, archive, show_info, trusted, output):
raise SystemExit(1 if summary(issues)['error'] else 0)


@cli.command()
@click.argument('kind', type=click.Choice(('atlases', 'cohorts', 'templates', 'dataset', 'all')))
@click.argument('path', type=click.Path(exists=True, file_okay=False), default='.', required=False)
@click.option(
'--check',
is_flag=True,
help='Change nothing: list the files to write, and exit with 1 if there are any.',
)
def generate(kind, path, check):
"""Write the files generated from metadata.

In a template (PATH is a tpl-<label> directory): `atlases` writes an atlas
description for each row of tpl-<label>_atlases.tsv, `cohorts` writes the cohorts
table from template_description.json, and `all` does both. At the root of the
Archive: `templates` writes templates.tsv, `dataset` writes dataset_description.json,
`all` does both, and `atlases` or `cohorts` apply to every template. Files no longer
generated are deleted.

Exits with 1 when --check finds files to write, and with 2 on errors.
"""
from . import generate as gen
from .tree import DirectoryTree
from .validate.archive import template_dirs

root = Path(path).resolve()
try:
if root.name.startswith('tpl-'):
if kind in gen.ARCHIVE_KINDS:
raise gen.GenerateError(f'{kind}: generated at the root of the Archive.')
kinds = gen.TEMPLATE_KINDS if kind == 'all' else (kind,)
jobs = [('', root, gen.template_outputs(DirectoryTree(root), kinds))]
elif kind in gen.TEMPLATE_KINDS:
jobs = [
(f'{t.name}/', t, gen.template_outputs(DirectoryTree(t), (kind,)))
for t in template_dirs(root)
]
else:
kinds = gen.ARCHIVE_KINDS if kind == 'all' else (kind,)
jobs = [('', root, gen.archive_outputs(root, kinds))]
found = 0
for prefix, where, outputs in jobs:
changes = gen.pending(where, outputs)
found += len(changes)
if not check:
gen.write_outputs(where, outputs, changes)
for change in changes:
verb = f'would {change.action}' if check else f'{change.action}d'
click.echo(f'{verb} {prefix}{change.path}')
except (gen.GenerateError, OSError) as exc:
click.echo(f'tfmgr generate failed: {exc}', err=True)
raise SystemExit(2) from exc
if not found:
click.echo('Up to date.')
raise SystemExit(1 if check and found else 0)


@cli.command()
@click.argument(
'template_dir', type=click.Path(exists=True, file_okay=False), default='.', required=False
Expand Down
217 changes: 214 additions & 3 deletions tfmanager/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,32 @@
- ``tpl-<label>_cohorts.tsv`` is generated from the ``cohort`` block of
template_description.json.
- ``templates.tsv`` (root of the Archive) is generated from every template_description.json.
- ``dataset_description.json`` (root of the Archive) describes the Archive; its
``TemplateFlowVersion`` becomes 2.0.0 once every template is at 2.0.0.
"""

from __future__ import annotations

import json
from collections.abc import Iterable
import os
import re
from collections.abc import Iterable, Mapping
from dataclasses import dataclass, field
from pathlib import Path

from .naming import parse
from .tables import NA, Table, dump_json, json_cell, write_tsv
from .tree import Tree, visible
from .ruleset import TEMPLATEFLOW_VERSION
from .tables import NA, Table, dump_json, json_cell, read_tsv, write_tsv
from .tree import DirectoryTree, Tree, visible

#: A generated atlas description, at the root of a template
DESCRIPTION = re.compile(r'^atlas-([0-9a-zA-Z+]+)_description\.json$')
#: What ``tfmgr generate`` writes in a template, and at the root of the Archive
TEMPLATE_KINDS = ('atlases', 'cohorts')
ARCHIVE_KINDS = ('templates', 'dataset')
#: Root files of the Archive
TEMPLATES_TSV = 'templates.tsv'
DATASET_DESCRIPTION = 'dataset_description.json'

#: atlases.tsv column -> atlas-<label>_description.json field (BIDS 1.11)
ATLAS_FIELDS = {
Expand Down Expand Up @@ -216,3 +231,199 @@ def collect_archive(trees: Iterable[Tree]) -> ArchiveIndex:
if key in f.entities:
index.targets.append((f'{tree.name}/{path}', f.entities[key]))
return index


class GenerateError(ValueError):
"""The files cannot be generated (malformed metadata, uninstalled templates)."""


@dataclass(frozen=True)
class Change:
"""A generated file to create, update or delete."""

path: str
action: str # 'create', 'update' or 'delete'


def _unreadable(tree: Tree, path: str) -> str:
"""Why a file that the generators need cannot be read."""
if not tree.exists(path):
return 'missing'
if tree.is_annexed(path):
return 'annexed (files are generated from metadata in git)'
return 'too large'


def _atlas_outputs(tree: Tree) -> dict[str, str]:
"""The atlas descriptions the atlases table generates (none without a table)."""
path = f'{tree.name}_atlases.tsv'
if not tree.exists(path):
return {}
data = tree.read_bytes(path)
if data is None:
raise GenerateError(f'{tree.name}/{path}: {_unreadable(tree, path)}.')
table = read_tsv(data)
if 'atlas_id' not in table.columns:
raise GenerateError(f'{tree.name}/{path}: no atlas_id column.')
try:
expected = atlas_descriptions(table)
except (TypeError, ValueError, AttributeError) as exc:
raise GenerateError(
f'{tree.name}/{path}: cannot generate the descriptions ({exc}).'
) from exc
for name in expected:
if not DESCRIPTION.match(name):
raise GenerateError(f'{tree.name}/{path}: not an atlas label: {name}.')
return expected


def _cohort_outputs(tree: Tree) -> tuple[str, str] | None:
"""The cohorts table and its sidecar, or ``None`` when the template has no cohorts."""
where = f'{tree.name}/template_description.json'
data = tree.read_bytes('template_description.json')
if data is None:
raise GenerateError(f'{where}: {_unreadable(tree, "template_description.json")}.')
try:
description = json.loads(data)
except ValueError as exc:
raise GenerateError(f'{where}: not JSON ({exc}).') from exc
if not isinstance(description, dict):
raise GenerateError(f'{where}: not a JSON object.')
block = description.get('cohort')
if block is not None and not isinstance(block, dict):
raise GenerateError(f'{where}: "cohort" is not an object.')
try:
return cohorts_table(description)
except (TypeError, ValueError, AttributeError) as exc:
raise GenerateError(f'{where}: cannot read its cohorts ({exc}).') from exc


def template_outputs(tree: Tree, kinds: Iterable[str] = TEMPLATE_KINDS) -> dict[str, str | None]:
"""The generated files of a template: ``{path: content}``, ``None`` to delete one.

``atlases``: an ``atlas-<label>_description.json`` for each row of the atlases table,
and none without a table (descriptions no row generates are deleted). ``cohorts``:
``tpl-<label>_cohorts.tsv`` and its sidecar, from the ``cohort`` block of
template_description.json (deleted when there is none).

Files are deleted only when readable metadata says they are not generated: a
description or atlases table that cannot be read (annexed, not JSON, not an object,
without an ``atlas_id`` column...) raises :class:`GenerateError`.
"""
kinds = set(kinds)
outputs: dict[str, str | None] = {}
if 'atlases' in kinds:
expected = _atlas_outputs(tree)
for path in tree.files():
if DESCRIPTION.match(path) and path not in expected:
outputs[path] = None
outputs.update(expected)
if 'cohorts' in kinds:
cohorts = _cohort_outputs(tree)
paths = (f'{tree.name}_cohorts.tsv', f'{tree.name}_cohorts.json')
if cohorts is None:
outputs.update((path, None) for path in paths if tree.exists(path))
else:
outputs.update(zip(paths, cohorts, strict=True))
return outputs


def dataset_description(at_version: bool, current: Mapping | None = None) -> str:
"""The Archive's dataset_description.json.

``TemplateFlowVersion`` is the rule set's version when ``at_version`` (every template
of the Archive is at that version), and otherwise stays as it is: the Archive's checks
become strict when it changes. No tfmanager version is recorded, so that the file does
not change when tfmanager does.
"""
from .ruleset import load_ruleset

current = current or {}
version = TEMPLATEFLOW_VERSION if at_version else current.get('TemplateFlowVersion', '1.0.0')
return dump_json(
{
'Name': 'TemplateFlow',
'BIDSVersion': load_ruleset().bids_version,
'DatasetType': 'derivative',
'TemplateFlowVersion': version,
'License': 'LicenseRef-TemplateFlow-PerTemplate',
'GeneratedBy': [
{'Name': 'tfmanager', 'CodeURL': 'https://github.com/templateflow/python-manager'}
],
'ReferencesAndLinks': ['https://doi.org/10.1038/s41592-022-01681-2'],
}
)


def archive_outputs(
root: str | os.PathLike, kinds: Iterable[str] = ARCHIVE_KINDS
) -> dict[str, str]:
"""The generated files at the root of an Archive checkout.

Every template registered in ``.gitmodules`` must be installed: the table would
otherwise leave it out.
"""
from .validate.archive import submodules, template_dirs
from .validate.core import is_legacy

root = Path(root)
kinds = set(kinds)
names = {p.name for p in template_dirs(root)} | submodules(root)
absent = sorted(n for n in names if not (root / n).is_dir() or not any((root / n).iterdir()))
if absent:
raise GenerateError(f'Templates not installed: {", ".join(absent)}.')
index = collect_archive(DirectoryTree(root / name) for name in sorted(names))
outputs = {}
if 'templates' in kinds:
outputs[TEMPLATES_TSV] = templates_table(index.descriptions, index.atlases)
if 'dataset' in kinds:
current = None
if (root / DATASET_DESCRIPTION).is_file():
try:
current = json.loads((root / DATASET_DESCRIPTION).read_text())
except ValueError as exc:
raise GenerateError(f'{DATASET_DESCRIPTION}: {exc}') from exc
at_version = len(index.descriptions) == len(names) and not any(
is_legacy(d) for d in index.descriptions.values()
)
outputs[DATASET_DESCRIPTION] = dataset_description(at_version, current)
return outputs


def _current(path: Path) -> bytes | None:
"""Content of a regular file (never through a symlink), else ``None``."""
if path.is_symlink() or not path.is_file():
return None
return path.read_bytes()


def pending(root: str | os.PathLike, outputs: Mapping[str, str | None]) -> list[Change]:
"""What writing ``outputs`` under ``root`` would change."""
root = Path(root)
changes = []
for path, content in sorted(outputs.items()):
target = root / path
present = target.is_symlink() or target.exists()
if content is None:
if present:
changes.append(Change(path, 'delete'))
elif not present:
changes.append(Change(path, 'create'))
elif _current(target) != content.encode():
changes.append(Change(path, 'update'))
return changes


def write_outputs(
root: str | os.PathLike, outputs: Mapping[str, str | None], changes: Iterable[Change]
) -> None:
"""Apply ``changes``: each file is replaced atomically (an annex link included)."""
root = Path(root)
for change in changes:
target = root / change.path
if change.action == 'delete':
target.unlink()
continue
tmp = target.parent / f'.tfmgr-{target.name}'
tmp.write_bytes(outputs[change.path].encode())
os.replace(tmp, target)
9 changes: 9 additions & 0 deletions tfmanager/tests/test_add.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,15 @@ def test_add_resumes_where_it_failed(template, tmp_path, datalad, commands):
assert datalad.calls == []


def test_generated_files_are_written(template, tmp_path, datalad, commands):
(template / 'atlas-Smith2020_description.json').unlink()
_add(template, tmp_path / 'work').run() # strict validation fails without it (TF607)
dataset = tmp_path / 'work' / f'tpl-{LABEL}'
assert json.loads((dataset / 'atlas-Smith2020_description.json').read_text())['Name'] == (
'The Smith atlas'
)


def test_validation_errors_stop_before_uploading(template, tmp_path, datalad, commands):
(template / f'tpl-{LABEL}_T1w_res-1.nii.gz').write_bytes(b'')
with pytest.raises(AddError, match='TF100'):
Expand Down
Loading