Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FIX: Make lists and dicts hashable #1112

Merged
merged 3 commits into from
Dec 13, 2024
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
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ dependencies = [
"num2words >=0.5.5",
"click >=8.0",
"universal_pathlib >=0.2.2",
"frozendict >=2",
]
dynamic = ["version"]

Expand Down
29 changes: 19 additions & 10 deletions src/bids/layout/layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from sqlalchemy.sql.expression import cast
from bids_validator import BIDSValidator

from ..utils import listify, natural_sort
from ..utils import listify, natural_sort, hashablefy
from ..external import inflect
from ..exceptions import (
BIDSDerivativesValidationError,
Expand Down Expand Up @@ -645,6 +645,13 @@
A list of BIDSFiles (default) or strings (see return_type).
"""

if (
not return_type.startswith(("obj", "file"))
and return_type not in ("id", "dir")
):
raise ValueError(f"Invalid return_type <{return_type}> specified (must be one "

Check warning on line 652 in src/bids/layout/layout.py

View check run for this annotation

Codecov / codecov/patch

src/bids/layout/layout.py#L652

Added line #L652 was not covered by tests
"of 'object', 'file', 'filename', 'id', or 'dir').")

if absolute_paths is False:
absolute_path_deprecation_warning()

Expand Down Expand Up @@ -691,6 +698,9 @@
message = "Valid targets are: {}".format(potential)
raise TargetError(("Unknown target '{}'. " + message)
.format(target))
elif target is None and return_type in ['id', 'dir']:
raise TargetError('If return_type is "id" or "dir", a valid '

Check warning on line 702 in src/bids/layout/layout.py

View check run for this annotation

Codecov / codecov/patch

src/bids/layout/layout.py#L702

Added line #L702 was not covered by tests
'target entity must also be specified.')

results = []
for l in layouts:
Expand Down Expand Up @@ -718,18 +728,22 @@

if return_type.startswith('file'):
results = natural_sort([f.path for f in results])

elif return_type in ['id', 'dir']:
if target is None:
raise TargetError('If return_type is "id" or "dir", a valid '
'target entity must also be specified.')

metadata = target not in self.get_entities(metadata=False)

if return_type == 'id':
ent_iter = (
hashablefy(res.get_entities(metadata=metadata))
for res in results if target in res.entities
)
results = list(dict.fromkeys(
res.entities[target] for res in results
if target in res.entities and isinstance(res.entities[target], Hashable)
ents[target] for ents in ent_iter if target in ents
))

results = natural_sort(list(set(results)))
elif return_type == 'dir':
template = entities[target].directory
if template is None:
Expand All @@ -752,12 +766,7 @@
for f in results
if re.search(template, f._dirname.as_posix())
]

results = natural_sort(list(set(matches)))

else:
raise ValueError("Invalid return_type specified (must be one "
"of 'tuple', 'filename', 'id', or 'dir'.")
else:
results = natural_sort(results, 'path')

Expand Down
21 changes: 21 additions & 0 deletions src/bids/layout/tests/test_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -776,6 +776,27 @@ def test_get_tr(layout_7t_trt):
assert sum([t in tr for t in [3.0, 4.0]]) == 2


def test_get_nonhashable_metadata(layout_ds117):
"""Test nonhashable metadata values (#683)."""
assert layout_ds117.get_IntendedFor(subject=['01'])[0] == (
"ses-mri/func/sub-01_ses-mri_task-facerecognition_run-01_bold.nii.gz",
"ses-mri/func/sub-01_ses-mri_task-facerecognition_run-02_bold.nii.gz",
"ses-mri/func/sub-01_ses-mri_task-facerecognition_run-03_bold.nii.gz",
"ses-mri/func/sub-01_ses-mri_task-facerecognition_run-04_bold.nii.gz",
"ses-mri/func/sub-01_ses-mri_task-facerecognition_run-05_bold.nii.gz",
"ses-mri/func/sub-01_ses-mri_task-facerecognition_run-06_bold.nii.gz",
"ses-mri/func/sub-01_ses-mri_task-facerecognition_run-07_bold.nii.gz",
"ses-mri/func/sub-01_ses-mri_task-facerecognition_run-08_bold.nii.gz",
"ses-mri/func/sub-01_ses-mri_task-facerecognition_run-09_bold.nii.gz",
)

landmarks = layout_ds117.get_AnatomicalLandmarkCoordinates(subject=['01'])[0]
assert landmarks["Nasion"] == (43, 111, 95)
assert landmarks["LPA"] == (140, 74, 16)
assert landmarks["RPA"] == (143, 74, 173)



def test_to_df(layout_ds117):
# Only filename entities
df = layout_ds117.to_df()
Expand Down
21 changes: 21 additions & 0 deletions src/bids/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,36 @@

import re
import os
from pathlib import Path
from frozendict import frozendict as _frozendict
from upath import UPath as Path


# Monkeypatch to print out frozendicts *as if* they were dictionaries.
class frozendict(_frozendict):
"""A hashable dictionary type."""

def __repr__(self):
"""Override frozendict representation."""
return repr({k: v for k, v in self.items()})


def listify(obj):
''' Wraps all non-list or tuple objects in a list; provides a simple way
to accept flexible arguments. '''
return obj if isinstance(obj, (list, tuple, type(None))) else [obj]


def hashablefy(obj):
''' Make dictionaries and lists hashable or raise. '''
if isinstance(obj, list):
return tuple([hashablefy(o) for o in obj])

if isinstance(obj, dict):
return frozendict({k: hashablefy(v) for k, v in obj.items()})
return obj


def matches_entities(obj, entities, strict=False):
''' Checks whether an object's entities match the input. '''
if strict and set(obj.entities.keys()) != set(entities.keys()):
Expand Down
Loading