Skip to content
This repository was archived by the owner on Aug 8, 2024. It is now read-only.

Commit b94864d

Browse files
authored
Merge pull request #30 from bids-standard/schema_entities
Change get_metadata to return long-name
2 parents 323a347 + 9ef1672 commit b94864d

File tree

4 files changed

+25
-22
lines changed

4 files changed

+25
-22
lines changed

bids/layout/layout.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
)
1919

2020
from ancpbids import CustomOpExpr, EntityExpr, AllExpr, ValidationPlugin, load_dataset, validate_dataset, \
21-
write_derivative
21+
write_derivative, DatasetOptions
2222
from ancpbids.query import query, query_entities, FnMatchExpr, AnyExpr
2323
from ancpbids.utils import deepupdate, resolve_segments, convert_to_relative, parse_bids_name
2424

@@ -274,7 +274,6 @@ def __init__(
274274
root = root.absolute()
275275

276276
if ignore is None:
277-
# If there is no .bidsignore file, apply default ignore patterns
278277
if not (Path(root) / '.bidsignore').exists():
279278
ignore = ['.*', 'models', 'stimuli', 'code', 'sourcedata']
280279
warnings.warn(
@@ -290,7 +289,9 @@ def __init__(
290289
DeprecationWarning
291290
)
292291

293-
self.dataset = load_dataset(root, ignore=ignore)
292+
options = DatasetOptions(ignore=ignore)
293+
294+
self.dataset = load_dataset(root, options=options)
294295
self.schema = self.dataset.get_schema()
295296
self.validationReport = None
296297

@@ -420,7 +421,7 @@ def parse_file_entities(self, filename, scope=None, entities=None,
420421
results = parse_bids_name(filename)
421422

422423
entities = results.pop('entities')
423-
schema_entities = {e.literal_: e.name for e in list(self.schema.EntityEnum)}
424+
schema_entities = {e.value['name']: e.name for e in list(self.schema.EntityEnum)}
424425
entities = {schema_entities[k]: v for k, v in entities.items()}
425426
results = {**entities, **results}
426427

@@ -601,19 +602,19 @@ def get(self, return_type: str = 'object', target: str = None, scope: str = None
601602

602603
# Provide some suggestions if target is specified and invalid.
603604
if return_type in ("dir", "id"):
604-
# Resolve proper target names to their "key", e.g., session to ses
605-
# XXX should we allow ses?
606-
target_match = [e for e in self.dataset._schema.EntityEnum
607-
if target in [e.name, e.literal_]]
608-
potential = list(self.get_entities().keys())
609-
if (not target_match) or target_match[0].name not in potential:
605+
if target is None:
606+
raise TargetError(f'If return_type is "id" or "dir", a valid target '
607+
'entity must also be specified.')
608+
self_entities = self.get_entities()
609+
if target not in self_entities:
610+
potential = list(self_entities.keys())
610611
suggestions = difflib.get_close_matches(target, potential)
611612
if suggestions:
612613
message = "Did you mean one of: {}?".format(suggestions)
613614
else:
614615
message = "Valid targets are: {}".format(potential)
615616
raise TargetError(f"Unknown target '{target}'. {message}")
616-
target = target_match[0].name
617+
617618
folder = self.dataset
618619
result = query(folder, return_type, target, scope, extension, suffix, regex_search, **entities)
619620
if return_type == 'file':

bids/layout/models.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from typing import Union
55
from pathlib import Path
66
import json
7-
from ancpbids.model_v1_8_0 import Artifact
7+
from ancpbids.model_v1_8_0 import Artifact, Dataset
88
from ancpbids.utils import parse_bids_name
99

1010
from ..utils import listify
@@ -37,12 +37,14 @@ def from_filename(cls, filename):
3737
break
3838
return cls(path)
3939

40-
def __init__(self, file_ref: Union[str, os.PathLike, Artifact]):
40+
def __init__(self, file_ref: Union[str, os.PathLike, Artifact], schema = None):
4141
self._path = None
4242
self._artifact = None
43+
self._schema = schema
4344
if isinstance(file_ref, (str, os.PathLike)):
4445
self._path = Path(file_ref)
4546
elif isinstance(file_ref, Artifact):
47+
self._schema = file_ref.get_schema()
4648
self._artifact = file_ref
4749

4850
@property
@@ -105,7 +107,7 @@ def get_associations(self, kind=None, include_parents=False):
105107
def get_metadata(self):
106108
"""Return all metadata associated with the current file. """
107109
md = BIDSMetadata(self.path)
108-
md.update(self.get_entities(metadata=True))
110+
md.update(self._artifact.get_metadata())
109111
return md
110112

111113
@property
@@ -138,10 +140,9 @@ def get_entities(self, metadata=False, values='tags'):
138140
"""
139141
try:
140142
entities = self._artifact.get_entities()
141-
142143
# Convert literal entity values to their names
143-
# schema_entities = {e.literal_: e.name for e in list(self.schema.EntityEnum)}
144-
# entities = {schema_entities[k]: v for k, v in entities.items()}
144+
known_entities = {e.value['name']: e.name for e in list(self._schema.EntityEnum)}
145+
entities = {known_entities[k] if k in known_entities else k: v for k, v in entities.items()}
145146
entities['suffix'] = self._artifact.suffix
146147
entities['extension'] = self._artifact.extension
147148

bids/layout/tests/test_layout.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,7 @@ def test_get_with_bad_target(layout_7t_trt):
236236
msg = str(exc.value)
237237
assert 'subject' in msg and 'reconstruction' in msg and 'proc' in msg
238238
with pytest.raises(TargetError) as exc:
239-
layout_7t_trt.get(target='sub')
239+
layout_7t_trt.get(target='subject')
240240
msg = str(exc.value)
241241
assert 'subject' in msg and 'reconstruction' not in msg
242242

@@ -282,7 +282,7 @@ def test_bids_json(layout_7t_trt):
282282

283283

284284
def test_get_return_type_dir(layout_7t_trt):
285-
res_relpath = layout_7t_trt.get(target='sub', return_type='dir')
285+
res_relpath = layout_7t_trt.get(target='subject', return_type='dir')
286286
target_relpath = ["sub-{:02d}".format(i) for i in range(1, 11)]
287287
assert all([tp in res_relpath for tp in target_relpath])
288288

@@ -322,7 +322,7 @@ def test_get_val_enum_any_optional(layout_7t_trt, layout_ds005):
322322

323323

324324
def test_get_return_sorted(layout_7t_trt):
325-
paths = layout_7t_trt.get(target='sub', return_type='file')
325+
paths = layout_7t_trt.get(target='subject', return_type='file')
326326
assert natural_sort(paths) == paths
327327

328328

@@ -335,8 +335,8 @@ def test_layout_with_derivs(layout_ds005_derivs):
335335
event_file = "sub-01_task-mixedgamblestask_run-01_desc-extra_events.tsv"
336336
deriv_files = [f.name for f in files]
337337
assert event_file in deriv_files
338-
entities = deriv.query_entities()
339-
assert 'sub' in entities
338+
entities = deriv.query_entities(long_form=True)
339+
assert 'subject' in entities
340340

341341

342342
def test_layout_with_multi_derivs(layout_ds005_multi_derivs):

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ dependencies = [
3131
"bids-validator",
3232
"num2words",
3333
"click >=8.0",
34+
"ancpbids @ git+https://github.com/adelavega/ancp-bids.git",
3435
]
3536
dynamic = ["version"]
3637

0 commit comments

Comments
 (0)