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
18 changes: 18 additions & 0 deletions .github/workflows/pythonapp.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,24 @@ on:
branches: [ master ]

jobs:
test:
runs-on: ubuntu-26.04
strategy:
matrix:
python-version: ['3.10', '3.12']
steps:
- uses: actions/checkout@v7
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python-version }}
- name: Install with test dependencies
run: python -m pip install ".[test]" ruff
- name: Lint
run: ruff check .
- name: Test
run: python -m pytest -o addopts="" --doctest-modules tfmanager

build:

runs-on: ubuntu-26.04
Expand Down
13 changes: 13 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
Unreleased
==========
TemplateFlow 2.0 rule set and validator.

* New ``tfmgr validate`` checks templates (directories, Archive checkouts or skeleton zips)
against the TemplateFlow 2.0 rule set: names in BIDS 1.11 order, layout, metadata,
lookup tables, SPDX licenses, atlases and, with ``--level content``, image headers and
values. Rules have stable codes (``TF101``...) and slugs; ``--mode legacy`` (the
default for templates older than TemplateFlowVersion 2.0.0) reports naming problems
as warnings. Output as text, JSON, GitHub annotations or Markdown.
* The rule set lives in ``tfmanager/schema/`` as YAML and JSON Schema, with a vendored
copy of the BIDS 1.11.0 schema; the website renders its documentation from them.
* The core package no longer needs DataLad, nibabel or the TemplateFlow client: install
``tfmanager[add]`` to add templates, ``tfmanager[content]`` for image checks.

Farewell to OSF: OSF no longer accepts uploads, and the TemplateFlow submission
pipeline now stores the data of new templates on GIN (https://gin.g-node.org).

Expand Down
18 changes: 18 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,21 @@ The TemplateFlow Archive manager
================================
This tool eases the processes of adding new templates and updating
existing one in the `TemplateFlow Archive <https://github.com/templateflow/templateflow>`__.

Validating a template
---------------------
``tfmgr validate`` checks templates against the TemplateFlow rule set
(``tfmanager/schema/``)::

pip install tfmanager
tfmgr validate tpl-MyTemplate # a template directory
tfmgr validate path/to/templateflow # every template of an Archive checkout
tfmgr validate --format json -o report.json tpl-MyTemplate

Templates older than TemplateFlowVersion 2.0.0 are checked in legacy mode, where naming
problems are warnings (``--mode strict`` or ``--mode legacy`` override it). Image headers
and values are only checked with ``--level content``, which needs ``tfmanager[content]``
and the images' data. The command exits with 1 when there are errors, and 2 when it
could not run.

Adding a template needs DataLad and the TemplateFlow client: ``pip install tfmanager[add]``.
12 changes: 12 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,15 @@ write_to_template = """\
__version__ = "{version}"
"""
fallback_version = "0.0"

[tool.ruff]
line-length = 99
extend-exclude = ["docs", "tfmanager/_version.py"]

[tool.ruff.format]
quote-style = "single"

[tool.ruff.lint]
select = ["E", "F", "W", "I", "UP", "B"]
# cli.py, io.py and utils.py predate the linter
per-file-ignores = { "{setup.py,tfmanager/cli.py,tfmanager/io.py,tfmanager/utils.py}" = ["E", "W", "I", "UP", "B"] }
24 changes: 19 additions & 5 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,18 @@ setup_requires =
setuptools_scm >= 8
toml
install_requires =
click
datalad >= 0.16
nibabel
numpy
templateflow >= 0.4.2
click >= 8
jsonschema >= 4.18
license-expression >= 30.3
pyyaml >= 6
toml
packages = find:

[options.package_data]
tfmanager =
data/*.LICENSE
schema/*.json
schema/*.yaml

[options.packages.find]
exclude =
Expand All @@ -46,6 +47,19 @@ console_scripts =
tfmgr=tfmanager.cli:cli

[options.extras_require]
# Adding templates (tfmgr add, sanitize) and image checks (tfmgr validate --level content)
add =
datalad >= 0.16
nibabel
numpy
templateflow >= 0.4.2
content =
nibabel
numpy
test =
bidsschematools == 1.2.0
pytest
%(content)s
doc =
nbsphinx
packaging
Expand Down
58 changes: 58 additions & 0 deletions tfmanager/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,64 @@ def add(
del os.environ["DATALAD_CREDENTIAL_GIN_TOKEN"]


@cli.command()
@click.argument("paths", nargs=-1, type=click.Path(exists=True))
@click.option(
"--mode",
type=click.Choice(("auto", "strict", "legacy")),
default="auto",
show_default=True,
help="strict: TemplateFlow 2.0 rules; legacy: naming problems are warnings; "
"auto: legacy for templates older than TemplateFlowVersion 2.0.0.",
)
@click.option(
"--level",
type=click.Choice(("names", "metadata", "content")),
default="metadata",
show_default=True,
help="content opens images (needs their data and tfmanager[content]).",
)
@click.option(
"--format",
"fmt",
type=click.Choice(("human", "json", "github", "markdown")),
default="human",
show_default=True,
)
@click.option("--archive/--no-archive", default=None, help="Also check the Archive (TF8xx).")
@click.option("--show-info", is_flag=True, help="Also show informational issues.")
@click.option(
"--trusted",
is_flag=True,
help="Follow git-annex links to open image data (do not use on untrusted clones).",
)
@click.option("-o", "--output", type=click.Path(dir_okay=False, writable=True))
def validate(paths, mode, level, fmt, archive, show_info, trusted, output):
"""Validate templates against the TemplateFlow rule set.

PATHS are template directories (tpl-<label>), Archive checkouts, or skeleton zips
(default: the current directory). Exits with 1 if there are errors, 2 on usage errors.
"""
from .validate import render, summary, validate_path

issues, meta = [], {}
try:
for path in paths or (getcwd(),):
found, meta = validate_path(
path, mode=mode, level=level, archive=archive, trusted=trusted
)
issues += found
except Exception as exc: # an internal error must not read as "errors found"
click.echo(f"tfmgr validate failed: {exc!r}", err=True)
raise SystemExit(2) from exc
text = render(issues, fmt=fmt, meta=meta, show_info=show_info)
if output:
Path(output).write_text(text + "\n")
else:
click.echo(text)
raise SystemExit(1 if summary(issues)["error"] else 0)


@cli.command()
@click.argument("template_dir", type=click.Path(exists=True), default=getcwd())
@click.option("--normalize/--no-normalize", default=True)
Expand Down
173 changes: 173 additions & 0 deletions tfmanager/generate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
"""Files generated from a template's metadata.

The same functions write the files (``tfmgr generate``) and check that the committed copies
are up to date (rules TF410, TF607 and TF801).

- ``tpl-<label>_atlases.tsv`` is written by people; each of its rows generates an
``atlas-<label>_description.json`` (BIDS 1.11).
- ``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.
"""

from __future__ import annotations

from .tables import NA, Table, dump_json, json_cell, write_tsv

#: atlases.tsv column -> atlas-<label>_description.json field (BIDS 1.11)
ATLAS_FIELDS = {
'name': 'Name',
'license': 'License',
'description': 'Description',
'authors': 'Authors',
'curators': 'Curators',
'funding': 'Funding',
'references_and_links': 'ReferencesAndLinks',
'species': 'Species',
'sample_size': 'SampleSize',
'derived_from': 'DerivedFrom',
'level_type': 'LevelType',
'rrid': 'RRID',
}
#: Columns of atlases.tsv: BIDS (bids-specification#2286), then TemplateFlow's
ATLAS_COLUMNS = {
'atlas_id': 'required',
'name': 'required',
'license': 'required',
'description': 'recommended',
'authors': 'recommended',
'curators': 'optional',
'funding': 'optional',
'references_and_links': 'recommended',
'species': 'optional',
'sample_size': 'optional',
'derived_from': 'optional',
'level_type': 'optional',
'rrid': 'optional',
'readme': 'recommended',
'derived_from_atlas': 'optional',
}
#: Columns whose cells hold JSON arrays
ATLAS_ARRAYS = {'authors', 'curators', 'funding', 'references_and_links'}

COHORT_COLUMNS = [
'cohort_id',
'description',
'age_min',
'age_max',
'age_units',
'sample_size',
'sex',
]
COHORT_SIDECAR = {
'cohort_id': {'Description': 'Cohort identifier (cohort-<index> in file names).'},
'description': {'Description': 'Readable name of the cohort.'},
'age_min': {'Description': 'Lowest age of the cohort.'},
'age_max': {'Description': 'Highest age of the cohort.'},
'age_units': {
'Description': 'Units of age_min and age_max.',
'Levels': {
'weeks': 'Weeks (gestational, for neonates)',
'months': 'Months',
'years': 'Years',
},
},
'sample_size': {'Description': 'Number of participants averaged into the cohort.'},
'sex': {'Description': 'Sex of the participants.'},
}

TEMPLATE_COLUMNS = ['template_id', 'description', 'species', 'license', 'cohorts', 'atlases']


def atlas_label(atlas_id: str) -> str:
return atlas_id.removeprefix('atlas-')


def atlas_description(row: dict[str, str]) -> dict:
"""The atlas description (BIDS 1.11) generated from a row of atlases.tsv."""
out = {}
for column, key in ATLAS_FIELDS.items():
value = row.get(column, NA)
if value in ('', NA, None):
continue
if column in ATLAS_ARRAYS or column == 'species':
value = json_cell(value)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep malformed atlas arrays from aborting validation

When an atlas TSV array cell starts with [ but is not valid JSON, the earlier check reports TF604, but json_cell raises ValueError while generating the expected description. The CLI then exits with an internal error rather than returning the validation findings; avoid generating from invalid cells or handle the parse failure here.

Useful? React with 👍 / 👎.

elif column == 'sample_size':
try:
value = int(value) if value.isdigit() else float(value)
except ValueError:
pass # reported by TF604
out[key] = value
return out


def atlas_descriptions(table: Table) -> dict[str, str]:
"""``{path: content}`` of the atlas descriptions generated from atlases.tsv."""
return {
f'atlas-{atlas_label(row["atlas_id"])}_description.json': dump_json(atlas_description(row))
for row in table.rows
if row.get('atlas_id', NA) not in ('', NA)
}


def _cohort_description(key: str, cohort: dict) -> str:
if cohort.get('name'):
return cohort['name']
age = cohort.get('age') or []
units = cohort.get('units', '')
if len(age) == 2 and age[0] != age[1]:
return f'Ages {_num(age[0])}-{_num(age[1])} {units}'.strip()
if age:
return f'Age {_num(age[0])} {units}'.strip()
return f'Cohort {key}'


def _num(value):
return int(value) if isinstance(value, float) and value.is_integer() else value


def cohorts_table(description: dict) -> tuple[str, str] | None:
"""``(tsv, json)`` of the cohorts table, or ``None`` when the template has no cohorts."""
cohorts = description.get('cohort') or {}
if not cohorts:
return None
rows = []
for key in sorted(cohorts, key=lambda k: (int(k) if k.isdigit() else 1e9, k)):
cohort = cohorts[key] or {}
age = cohort.get('age') or [None, None]
if len(age) == 1:
age = [age[0], age[0]]
rows.append(
{
'cohort_id': f'cohort-{key}',
'description': _cohort_description(key, cohort),
'age_min': _num(age[0]) if age[0] is not None else None,
'age_max': _num(age[1]) if age[1] is not None else None,
'age_units': cohort.get('units'),
'sample_size': cohort.get('samplesize'),
'sex': cohort.get('sex'),
}
)
return write_tsv(COHORT_COLUMNS, rows), dump_json(COHORT_SIDECAR)


def templates_table(
descriptions: dict[str, dict], atlases: dict[str, list[str]] | None = None
) -> str:
"""templates.tsv from ``{template label: template_description}``."""
atlases = atlases or {}
rows = []
for label in sorted(descriptions, key=str.lower):
desc = descriptions[label]
species = desc.get('Species')
rows.append(
{
'template_id': f'tpl-{label}',
'description': desc.get('Name'),
'species': species,
'license': desc.get('License'),
'cohorts': len(desc.get('cohort') or {}) or None,
'atlases': sorted(atlases.get(label, [])) or None,
}
)
return write_tsv(TEMPLATE_COLUMNS, rows)
Loading