diff --git a/CHANGES.rst b/CHANGES.rst index 0ecf643..284e45f 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,5 +1,14 @@ Unreleased ========== +Index values are not zero-padded. + +* New rule TF117 zero-padded-index: ``res``, ``cohort``, ``scale`` and ``inv`` values + are written without leading zeros (``res-1``, not ``res-01``), in file names and in + the ``res`` and ``cohort`` keys of template_description.json. Issues on file names + suggest the new name. Templates older than 2.0 get a warning. + +26.0.0rc2 (December 2, 2026) +============================ ``tfmgr sanitize`` becomes a linter, and ``tfmgr add`` stops changing data silently. * ``tfmgr sanitize`` reports the image rules (TF701 to TF711) and fixes what it can: diff --git a/tfmanager/ruleset.py b/tfmanager/ruleset.py index 88a1d93..42191c9 100644 --- a/tfmanager/ruleset.py +++ b/tfmanager/ruleset.py @@ -52,6 +52,8 @@ class Entity: """Regular expression the Python client reads (unanchored, applied to the value).""" dtype: str = 'str' enum: tuple[str, ...] = () + format: str = '' + """``index`` or ``label`` (empty when the entity has its own ``pattern``).""" def valid(self, value: str) -> bool: if self.enum: @@ -61,6 +63,10 @@ def valid(self, value: str) -> bool: def queryable(self, value: str) -> bool: return re.fullmatch(self.client, value) is not None + def padded(self, value: str) -> bool: + """Whether ``value`` is an index with leading zeros (``01``).""" + return self.format == 'index' and len(value) > 1 and value.startswith('0') + @dataclass(frozen=True) class RuleSet: @@ -120,10 +126,8 @@ def load_ruleset() -> RuleSet: entities = {} for key, spec in ent_spec['entities'].items(): - if 'pattern' in spec: - pattern = spec['pattern'] - else: - pattern = FORMATS[spec.get('format', 'label')] + fmt = '' if 'pattern' in spec else spec.get('format', 'label') + pattern = spec['pattern'] if 'pattern' in spec else FORMATS[fmt] entities[key] = Entity( key=key, name=bids_names.get(key, key), @@ -132,6 +136,7 @@ def load_ruleset() -> RuleSet: client=spec['client'], dtype=spec.get('dtype', 'str'), enum=tuple(spec.get('enum', ())), + format=fmt, ) order = _entity_order(bids, set(entities), ent_spec.get('inserts', [])) missing = set(entities) - set(order) diff --git a/tfmanager/schema/rules.yaml b/tfmanager/schema/rules.yaml index 907c6c0..8ec9f51 100644 --- a/tfmanager/schema/rules.yaml +++ b/tfmanager/schema/rules.yaml @@ -95,6 +95,12 @@ TF116: severity: error summary: The path has characters other than letters, digits, `-`, `_`, `+` and `.`. fix: Rename the file. +TF117: + slug: zero-padded-index + severity: error + legacy: warning + summary: An index value (`res`, `cohort`, `scale`, `inv`) has leading zeros. + fix: Write index values without zero padding (`res-1`, not `res-01`), in file names and in the `res` and `cohort` keys of template_description.json. TF201: slug: unexpected-directory severity: error diff --git a/tfmanager/tests/test_validate.py b/tfmanager/tests/test_validate.py index 0c49a90..1c1165c 100644 --- a/tfmanager/tests/test_validate.py +++ b/tfmanager/tests/test_validate.py @@ -60,6 +60,8 @@ def test_auto_mode_is_legacy_before_2_0(): ({f'{T}_res-1_desc-a b_T1w.nii.gz': None}, 'TF116'), ({f'{T}_hemi-X_den-32k_sulc.shape.gii': None}, 'TF105'), ({f'{T}_label-a_b_probseg.nii.gz': None}, 'TF100'), + ({f'{T}_res-01_T1w.nii.gz': None}, 'TF117'), + ({f'{T}_atlas-Smith2020_scale-064_res-1_dseg.nii.gz': None}, 'TF117'), ] @@ -74,6 +76,20 @@ def test_order_suggestion(): assert issue.suggestion == f'{T}_atlas-Smith2020_res-1_dseg.nii.gz' +def test_padding_suggestion(): + tree = make_tree(**{f'{T}_res-02_atlas-Smith2020_dseg.nii.gz': None}) + (issue,) = [i for i in validate_template(tree, mode='strict') if i.code == 'TF117'] + assert issue.suggestion == f'{T}_atlas-Smith2020_res-2_dseg.nii.gz' + assert issue.severity == 'error' + legacy = validate_template(tree, mode='legacy') + assert {i.severity for i in legacy if i.code == 'TF117'} == {'warning'} + + +def test_unpadded_values_pass(): + tree = make_tree(**{f'{T}_res-10_T1w.nii.gz': None, f'{T}_res-0_T1w.nii.gz': None}) + assert 'TF117' not in codes(tree) + + def test_legacy_downgrades_names(): tree = make_tree(**{f'{T}_res-1_atlas-Smith2020_dseg.nii.gz': None}) issues = validate_template(tree, mode='legacy') @@ -136,6 +152,11 @@ def test_scripts_and_docs_allowed(): ({'res': {**description()['res'], '3': description()['res']['1']}}, 'TF330'), ({'res': {'01': description()['res']['1'], '2': description()['res']['2']}}, 'TF330'), ({'cohort': {'1': {'age': [20, 40], 'units': 'years'}}}, 'TF332'), + ({'res': {'01': description()['res']['1'], '2': description()['res']['2']}}, 'TF117'), + ( + {'cohort': {'01': {'age': [20, 40], 'units': 'years', 'res': {'02': {}}}}}, + 'TF117', + ), ({'License': None}, 'TF501'), ({'License': 'CC-BY-4'}, 'TF502'), ({'License': 'GPL-2.0'}, 'TF503'), diff --git a/tfmanager/validate/metadata.py b/tfmanager/validate/metadata.py index a2c9cb4..dbc6cf0 100644 --- a/tfmanager/validate/metadata.py +++ b/tfmanager/validate/metadata.py @@ -170,6 +170,30 @@ def check_blocks(ctx: Context): ) +@check('metadata') +def check_padded_keys(ctx: Context): + """TF117: zero-padded keys of the res and cohort blocks.""" + desc = ctx.description + if desc is None: + return + cohorts = desc.get('cohort') + blocks = {'res': desc.get('res'), 'cohort': cohorts} + if isinstance(cohorts, dict): + for key, cohort in cohorts.items(): + if isinstance(cohort, dict): + blocks[f'cohort.{key}.res'] = cohort.get('res') + for name, block in blocks.items(): + if not isinstance(block, dict): + continue + padded = sorted(k for k in block if len(k) > 1 and k.isdigit() and k.startswith('0')) + if padded: + ctx.report( + 'TF117', + 'template_description.json', + f'{name} keys {", ".join(repr(k) for k in padded)}.', + ) + + @check('metadata') def check_readme(ctx: Context): """TF340, TF341: the methods summary.""" diff --git a/tfmanager/validate/names.py b/tfmanager/validate/names.py index b15cdd8..308a885 100644 --- a/tfmanager/validate/names.py +++ b/tfmanager/validate/names.py @@ -6,6 +6,7 @@ import io import re from collections import defaultdict +from dataclasses import replace from ..naming import serialize from .core import Context, check @@ -31,7 +32,7 @@ def check_paths(ctx: Context): @check('names') def check_names(ctx: Context): - """TF100-TF111, TF113: entities, values, suffixes and extensions.""" + """TF100-TF111, TF113, TF117: entities, values, suffixes and extensions.""" rs = ctx.ruleset rank = {key: i for i, key in enumerate(rs.order)} extensions = rs.extensions @@ -72,6 +73,20 @@ def check_names(ctx: Context): f'The client cannot query {entity.query}={value!r} ' f'(it reads {key} as {entity.client!r}).', ) + padded = { + k: v.lstrip('0') or '0' + for k, v in f.entities.items() + if k in rs.entities and rs.entities[k].valid(v) and rs.entities[k].padded(v) + } + if padded: + unpadded = replace(f, entities={**f.entities, **padded}) + ctx.report( + 'TF117', + path, + ', '.join(f'{k}-{f.entities[k]}' for k in padded) + '.', + suggestion=f'{f.dirname + "/" if f.dirname else ""}' + f'{serialize(unpadded, list(rs.order))}', + ) atlas = f.entities.get('atlas') if atlas and (not atlas[:1].isupper() or VERSION_LABEL.match(atlas)): ctx.report('TF113', path, f'atlas-{atlas}.')