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
17 changes: 17 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,23 @@ Unreleased
joins names and content: a renamed file whose bytes change gets an ``n/a`` row, so its
old name keeps its old bytes. The config's ``edits`` correct fields of JSON files. A test
pins the ``res`` blocks of the migrated Archive (``tests/data/res-2.0.0.tsv``).
* The tables of the migration to TemplateFlow 2.0 (``tfmanager.migrate.lookups``): lookup
tables take the BIDS columns ``index``, ``name``, ``abbreviation``, ``color`` (``#rrggbb``)
and ``mapping``, in UTF-8 with tabs and ``n/a``, rows sorted by index (T01). The config's
``tables.layouts`` say how each other layout converts and describe the columns it keeps
in the table's JSON sidecar; the fsaverage tables are rebuilt from the label tables of
their GIFTI files. ``tables.sources`` writes tables from cited upstream files (T02), and
``participants`` converts participants tables to ``participant_id`` (``sub-`` and the
letters and digits of the original, kept in ``source_id``), merging the rows of a
participant imaged more than once (T03). Descriptions of columns no table has are
removed.
* Every lookup table is checked against its images: label values without a row (M206) and,
for 4D probabilistic segmentations, rows that are not the volumes 1 to N block a plan;
segmentations without a table (M202), rows that label nothing (M207) and values stored
as non-integers (M208) are notes. New command ``tfmgr migrate labels ARCHIVE [--needs]
-o DIR`` reads the label values of every segmentation, and the label tables of GIFTI
files, into two tables keyed by md5, shipped with tfmanager
(``migrate/data/labels-2.0.0.tsv``, ``labeltables-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
Expand Down
73 changes: 73 additions & 0 deletions tfmanager/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,79 @@ def headers(archive, templates, needs, output):
click.echo(text, nl=False)


@migrate.command()
@click.argument('archive', type=click.Path(exists=True, file_okay=False), default='.')
@click.option(
'-t', '--template', 'templates', multiple=True, help='Only this template (tpl-<label>).'
)
@click.option(
'--needs',
is_flag=True,
help='List the files whose facts are needed but whose data are absent, and stop.',
)
@click.option(
'-o',
'--output',
type=click.Path(file_okay=False, writable=True),
help='Write labels-2.0.0.tsv and labeltables-2.0.0.tsv into this directory.',
)
def labels(archive, templates, needs, output):
"""Read the label values of segmentations, from an Archive checkout.

The files are the volumes and .label.gii files named dseg: the migration checks the
lookup tables that apply to them against their values, and rebuilds the tables of
surface atlases from the label tables of their GIFTI files. Their data must be present
(git-annex): fetch the files --needs lists, e.g. with `datalad get`.

Exits with 1 when data are missing, and with 2 on errors (tfmanager[content] is needed
to read the data).
"""
from .migrate.labels import BUNDLED, Labels, dump, needed, read_labels, table_id
from .migrate.snapshot import load_checkout
from .tree import DirectoryTree

if not needs and not output:
raise click.UsageError('Give -o DIR (or --needs).')
root = Path(archive)
names = templates or sorted(
p.name for p in root.iterdir() if p.name.startswith('tpl-') and (p / '.git').exists()
)
wanted, absent = [], []
for name in names:
snapshot = load_checkout(root / name)
tree = DirectoryTree(root / name, trusted=True)
for path in needed(snapshot):
wanted.append((f'{name}/{path}', snapshot.entries[path].md5))
if tree.local_path(path) is None:
absent.append(f'{name}/{path}')
if needs:
for path in absent:
click.echo(path)
click.echo(f'{len(wanted)} files needed, {len(absent)} without data.', err=True)
return
if absent:
click.echo(f'{len(absent)} files have no data, e.g. {absent[0]}.', err=True)
click.echo('List them with --needs and fetch them (datalad get).', err=True)
raise SystemExit(1)
found, tables = [], {}
try:
for path, md5 in wanted:
facts, table = read_labels(root / path)
tid = None
if table is not None:
tid = table_id(table)
tables[tid] = table
found.append(Labels(path=path, md5=md5, table=tid, **facts))
except (ImportError, ValueError, OSError) as exc:
click.echo(f'tfmgr migrate labels failed: {exc}', err=True)
raise SystemExit(2) from exc
out = Path(output)
out.mkdir(parents=True, exist_ok=True)
for name, text in zip(BUNDLED, dump(found, tables), strict=True):
(out / name).write_text(text)
click.echo(f'{len(found)} files read, {len(tables)} GIFTI label tables.', err=True)


@cli.command()
@click.argument(
'template_dir', type=click.Path(exists=True, file_okay=False), default='.', required=False
Expand Down
213 changes: 210 additions & 3 deletions tfmanager/migrate/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
import yaml

from ..ruleset import load_ruleset
from ..tables import read_tsv
from ..validate.names import VERSION_LABEL
from ..validate.tables import LOOKUP_COLUMNS

CONFIG_DIR = files('tfmanager.migrate') / 'config'
NAME_KEYS = ('suffix', 'extension')
Expand Down Expand Up @@ -66,6 +68,73 @@ def apply(self, data: dict) -> dict:
return out


@dataclass(frozen=True)
class Layout:
"""How to convert lookup tables of one layout to BIDS columns (``tables.layouts``)."""

id: str
count: dict
"""``{template: number of tables}`` this layout converts."""
header: tuple[str, ...] | None
"""The columns as the tables have them (``None``: no header line)."""
why: str
columns: dict = field(default_factory=dict)
"""New column -> old column, ``{rgb: [r, g, b]}`` or ``{from: old, values: {old: new}}``."""
paths: tuple[str, ...] = ()
"""Only these tables (new names, relative to the template)."""
fields: tuple[str, ...] = ()
"""Names of the fields of headerless tables (split at white space)."""
split_hemi: dict = field(default_factory=dict)
"""``{L: old column, R: old column}``: one row per label, with ``hemi``."""
rebuild: str | None = None
"""``gifti``: rows from the label tables of the GIFTI files the table applies to."""
prefer: dict = field(default_factory=dict)
"""Entities of the GIFTI files whose label table wins when they disagree."""
describe: dict = field(default_factory=dict)
evidence: str = ''

def matches(self, template: str, path: str, header: tuple[str, ...] | None) -> bool:
if template not in self.count or (self.paths and path not in self.paths):
return False
return self.header is None if header is None else self.header == header


@dataclass(frozen=True)
class Source:
"""A lookup table written from its upstream source (``tables.sources``)."""

id: str
template: str
path: str
"""The table's name in the template."""
file: str
"""Its content, under ``tables/`` next to the config."""
evidence: str
why: str
data: bytes = b''
replace: bool = False
"""Whether it replaces a table of the template (otherwise, the template has none)."""
describe: dict = field(default_factory=dict)


@dataclass(frozen=True)
class Participants:
"""How to convert a template's participants table (``participants``)."""

id: str
template: str
header: tuple[str, ...]
columns: dict
"""New column -> old column (``source_id`` gives ``participant_id``)."""
describe: dict
why: str
repeats: str | None = None
"""A column counting the rows of a participant, merged into one (none: rows are unique)."""
set: dict = field(default_factory=dict)
"""``{source_id: {column: value}}``: corrections, with their evidence."""
evidence: str = ''


@dataclass(frozen=True)
class Config:
version: str
Expand All @@ -76,6 +145,9 @@ class Config:
"""``tpl-<label>/<path>`` -> ``{'res': key, 'why': ...}``."""
gitattributes: str = ''
edits: tuple[Edit, ...] = ()
layouts: tuple[Layout, ...] = ()
sources: tuple[Source, ...] = ()
participants: tuple[Participants, ...] = ()
digest: str = ''

def atlas_label(self, template: str, label: str) -> str | None:
Expand All @@ -90,6 +162,15 @@ def renames_for(self, template: str) -> list[Rename]:
def edits_for(self, template: str) -> list[Edit]:
return [e for e in self.edits if e.template == template]

def layouts_for(self, template: str) -> list[Layout]:
return [layout for layout in self.layouts if template in layout.count]

def sources_for(self, template: str) -> list[Source]:
return [s for s in self.sources if s.template == template]

def participants_for(self, template: str) -> Participants | None:
return next((p for p in self.participants if p.template == template), None)

def assigned(self, template: str) -> dict[str, str]:
prefix = f'{template}/'
return {
Expand Down Expand Up @@ -121,10 +202,33 @@ def _check(data: dict) -> list[str]:
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).')
for part in ('renames', 'edits'):
ids = [r['id'] for r in data.get(part, [])]
parts = {
'renames': data.get('renames', []),
'edits': data.get('edits', []),
'tables.layouts': data.get('tables', {}).get('layouts', []),
'tables.sources': data.get('tables', {}).get('sources', []),
'participants': data.get('participants', []),
}
for part, items in parts.items():
ids = [r['id'] for r in items]
for dup in sorted({i for i in ids if ids.count(i) > 1}):
problems.append(f'{part}: the id {dup} is used twice.')
for item in parts['tables.layouts']:
problems += [f'tables.layouts {item["id"]}: {p}' for p in _check_layout(item, rs)]
templates = [p['template'] for p in parts['participants']]
for dup in sorted({t for t in templates if templates.count(t) > 1}):
problems.append(f'participants: {dup} is listed twice.')
for item in parts['participants']:
unknown = sorted(set(item['columns'].values()) - set(item['header']))
if unknown:
problems.append(f'participants {item["id"]}: no column {", ".join(unknown)}.')
wanted = (set(item['columns']) | {item.get('repeats')}) - {'source_id', None}
for source, values in item.get('set', {}).items():
unknown = sorted(set(values) - set(item['columns']) - {'source_id'})
if unknown:
problems.append(f'participants {item["id"]}: set {source}: no {unknown}.')
if set(item['describe']) != wanted:
problems.append(f'participants {item["id"]}: describe exactly {sorted(wanted)}.')
for item in data.get('edits', []):
both = set(item.get('set', {})) & set(item.get('remove', []))
if both:
Expand All @@ -147,8 +251,62 @@ def _check(data: dict) -> list[str]:
return problems


def _check_layout(item: dict, rs) -> list[str]:
"""Problems of a ``tables.layouts`` entry."""
problems = []
header, fields = item['header'], item.get('fields')
if header is None and not (fields and item.get('paths')):
problems.append('a table without header needs fields and paths.')
if header is not None and fields:
problems.append('fields are for tables without header.')
have = set(header or fields or ())
split = item.get('split_hemi', {})
missing = set(split.values()) - have
if split:
have = (have - set(split.values())) | {'index', 'hemi'}
for spec in item.get('columns', {}).values():
if isinstance(spec, str):
missing |= {spec} - have
elif 'rgb' in spec:
missing |= set(spec['rgb']) - have
else:
missing |= {spec['from']} - have
if missing:
problems.append(f'no column {", ".join(sorted(missing))} in the header.')
extra = {c for c in item.get('columns', {}) if c not in LOOKUP_COLUMNS}
if item.get('rebuild') is None and set(item.get('describe', {})) != extra:
problems.append(f'describe exactly the extra columns {sorted(extra)}.')
unknown = sorted(set(item.get('prefer', {})) - set(rs.entities))
if unknown:
problems.append(f'prefer: unknown entities {", ".join(unknown)}.')
return problems


def _source_data(item: dict, base) -> tuple[bytes, list[str]]:
"""The content of a ``tables.sources`` entry, and its problems."""
if '..' in item['file'].split('/'):
return b'', [f'tables.sources {item["id"]}: {item["file"]} leaves tables/.']
path = base / 'tables' / item['file']
try:
data = path.read_bytes()
except OSError:
return b'', [f'tables.sources {item["id"]}: no file tables/{item["file"]}.']
table = read_tsv(data)
problems = [f'tables.sources {item["id"]}: {p}.' for p in table.problems]
if table.columns[:2] != ['index', 'name']:
problems.append(f'tables.sources {item["id"]}: the columns start with index, name.')
extra = sorted(set(table.columns) - set(LOOKUP_COLUMNS) - set(item.get('describe', {})))
if extra:
problems.append(f'tables.sources {item["id"]}: describe {", ".join(extra)}.')
return data, 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``)."""
"""Load and check a config (by default, the one shipped for ``version``).

The tables of ``tables.sources`` are read from ``tables/`` next to the config.
"""
base = Path(path).parent if path else CONFIG_DIR
text = Path(path).read_text() if path else (CONFIG_DIR / f'{version}.yaml').read_text()
data = yaml.safe_load(text)
try:
Expand All @@ -157,6 +315,23 @@ def load_config(path: str | Path | None = None, version: str = '2.0.0') -> Confi
where = '/'.join(str(p) for p in exc.absolute_path)
raise ConfigError(f'{where or "config"}: {exc.message}') from exc
problems = _check(data)
sources = []
for item in data.get('tables', {}).get('sources', []):
content, found = _source_data(item, base)
problems += found
sources.append(
Source(
id=item['id'],
template=item['template'],
path=item['path'],
file=item['file'],
evidence=item['evidence'],
why=item['why'],
data=content,
replace=item.get('replace', False),
describe=dict(item.get('describe', {})),
)
)
if problems:
raise ConfigError('\n'.join(problems))
return Config(
Expand Down Expand Up @@ -188,6 +363,38 @@ def load_config(path: str | Path | None = None, version: str = '2.0.0') -> Confi
)
for e in data.get('edits', [])
),
layouts=tuple(
Layout(
id=item['id'],
count=dict(item['count']),
header=None if item['header'] is None else tuple(item['header']),
why=item['why'],
columns=dict(item.get('columns', {})),
paths=tuple(item.get('paths', ())),
fields=tuple(item.get('fields', ())),
split_hemi=dict(item.get('split_hemi', {})),
rebuild=item.get('rebuild'),
prefer=dict(item.get('prefer', {})),
describe=dict(item.get('describe', {})),
evidence=item.get('evidence', ''),
)
for item in data.get('tables', {}).get('layouts', [])
),
sources=tuple(sources),
participants=tuple(
Participants(
id=item['id'],
template=item['template'],
header=tuple(item['header']),
columns=dict(item['columns']),
describe=dict(item['describe']),
why=item['why'],
repeats=item.get('repeats'),
set=dict(item.get('set', {})),
evidence=item.get('evidence', ''),
)
for item in data.get('participants', [])
),
digest=hashlib.sha256(text.encode()).hexdigest(),
)

Expand Down
Loading