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

Commit

Permalink
Merge pull request #30 from bids-standard/schema_entities
Browse files Browse the repository at this point in the history
Change get_metadata to return long-name
  • Loading branch information
adelavega authored Feb 27, 2023
2 parents 323a347 + 9ef1672 commit b94864d
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 22 deletions.
23 changes: 12 additions & 11 deletions bids/layout/layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
)

from ancpbids import CustomOpExpr, EntityExpr, AllExpr, ValidationPlugin, load_dataset, validate_dataset, \
write_derivative
write_derivative, DatasetOptions
from ancpbids.query import query, query_entities, FnMatchExpr, AnyExpr
from ancpbids.utils import deepupdate, resolve_segments, convert_to_relative, parse_bids_name

Expand Down Expand Up @@ -274,7 +274,6 @@ def __init__(
root = root.absolute()

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

self.dataset = load_dataset(root, ignore=ignore)
options = DatasetOptions(ignore=ignore)

self.dataset = load_dataset(root, options=options)
self.schema = self.dataset.get_schema()
self.validationReport = None

Expand Down Expand Up @@ -420,7 +421,7 @@ def parse_file_entities(self, filename, scope=None, entities=None,
results = parse_bids_name(filename)

entities = results.pop('entities')
schema_entities = {e.literal_: e.name for e in list(self.schema.EntityEnum)}
schema_entities = {e.value['name']: e.name for e in list(self.schema.EntityEnum)}
entities = {schema_entities[k]: v for k, v in entities.items()}
results = {**entities, **results}

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

# Provide some suggestions if target is specified and invalid.
if return_type in ("dir", "id"):
# Resolve proper target names to their "key", e.g., session to ses
# XXX should we allow ses?
target_match = [e for e in self.dataset._schema.EntityEnum
if target in [e.name, e.literal_]]
potential = list(self.get_entities().keys())
if (not target_match) or target_match[0].name not in potential:
if target is None:
raise TargetError(f'If return_type is "id" or "dir", a valid target '
'entity must also be specified.')
self_entities = self.get_entities()
if target not in self_entities:
potential = list(self_entities.keys())
suggestions = difflib.get_close_matches(target, potential)
if suggestions:
message = "Did you mean one of: {}?".format(suggestions)
else:
message = "Valid targets are: {}".format(potential)
raise TargetError(f"Unknown target '{target}'. {message}")
target = target_match[0].name

folder = self.dataset
result = query(folder, return_type, target, scope, extension, suffix, regex_search, **entities)
if return_type == 'file':
Expand Down
13 changes: 7 additions & 6 deletions bids/layout/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from typing import Union
from pathlib import Path
import json
from ancpbids.model_v1_8_0 import Artifact
from ancpbids.model_v1_8_0 import Artifact, Dataset
from ancpbids.utils import parse_bids_name

from ..utils import listify
Expand Down Expand Up @@ -37,12 +37,14 @@ def from_filename(cls, filename):
break
return cls(path)

def __init__(self, file_ref: Union[str, os.PathLike, Artifact]):
def __init__(self, file_ref: Union[str, os.PathLike, Artifact], schema = None):
self._path = None
self._artifact = None
self._schema = schema
if isinstance(file_ref, (str, os.PathLike)):
self._path = Path(file_ref)
elif isinstance(file_ref, Artifact):
self._schema = file_ref.get_schema()
self._artifact = file_ref

@property
Expand Down Expand Up @@ -105,7 +107,7 @@ def get_associations(self, kind=None, include_parents=False):
def get_metadata(self):
"""Return all metadata associated with the current file. """
md = BIDSMetadata(self.path)
md.update(self.get_entities(metadata=True))
md.update(self._artifact.get_metadata())
return md

@property
Expand Down Expand Up @@ -138,10 +140,9 @@ def get_entities(self, metadata=False, values='tags'):
"""
try:
entities = self._artifact.get_entities()

# Convert literal entity values to their names
# schema_entities = {e.literal_: e.name for e in list(self.schema.EntityEnum)}
# entities = {schema_entities[k]: v for k, v in entities.items()}
known_entities = {e.value['name']: e.name for e in list(self._schema.EntityEnum)}
entities = {known_entities[k] if k in known_entities else k: v for k, v in entities.items()}
entities['suffix'] = self._artifact.suffix
entities['extension'] = self._artifact.extension

Expand Down
10 changes: 5 additions & 5 deletions bids/layout/tests/test_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ def test_get_with_bad_target(layout_7t_trt):
msg = str(exc.value)
assert 'subject' in msg and 'reconstruction' in msg and 'proc' in msg
with pytest.raises(TargetError) as exc:
layout_7t_trt.get(target='sub')
layout_7t_trt.get(target='subject')
msg = str(exc.value)
assert 'subject' in msg and 'reconstruction' not in msg

Expand Down Expand Up @@ -282,7 +282,7 @@ def test_bids_json(layout_7t_trt):


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

Expand Down Expand Up @@ -322,7 +322,7 @@ def test_get_val_enum_any_optional(layout_7t_trt, layout_ds005):


def test_get_return_sorted(layout_7t_trt):
paths = layout_7t_trt.get(target='sub', return_type='file')
paths = layout_7t_trt.get(target='subject', return_type='file')
assert natural_sort(paths) == paths


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


def test_layout_with_multi_derivs(layout_ds005_multi_derivs):
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ dependencies = [
"bids-validator",
"num2words",
"click >=8.0",
"ancpbids @ git+https://github.com/adelavega/ancp-bids.git",
]
dynamic = ["version"]

Expand Down

0 comments on commit b94864d

Please sign in to comment.