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

Raise if get_map can't find any maps instead of logging and returning None #618

Merged
merged 4 commits into from
Nov 26, 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
4 changes: 2 additions & 2 deletions .github/workflows/siibra-testing.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ jobs:
python-version: ["3.12", "3.11", "3.10", "3.9", "3.8", "3.7"]

unit-tests-fast:
if: ${{ github.event_name != 'pull_request' }}
if: ${{ github.event.pull_request == null }}
needs: "use-custom-cfg"
uses: ./.github/workflows/_unittest.yaml
with:
Expand All @@ -92,7 +92,7 @@ jobs:
python-version: ["3.12", "3.11", "3.10", "3.9", "3.8", "3.7"]

e2e-tests-fast:
if: ${{ github.event_name != 'pull_request' }}
if: ${{ github.event.pull_request == null }}
needs: "use-custom-cfg"
uses: ./.github/workflows/_e2e.yaml
with:
Expand Down
32 changes: 22 additions & 10 deletions siibra/core/parcellation.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,20 @@

from ..commons import logger, MapType, Species
from ..volumes import parcellationmap
from ..exceptions import NoMapMatchingValues

from typing import Union, List, Dict
import re
from typing import Union, List, Dict, TYPE_CHECKING
try:
from typing import Literal
except ImportError:
# support python 3.7
from typing_extensions import Literal


if TYPE_CHECKING:
from .space import Space

Check warning on line 32 in siibra/core/parcellation.py

View check run for this annotation

Codecov / codecov/patch

siibra/core/parcellation.py#L32

Added line #L32 was not covered by tests

# NOTE : such code could be used to automatically resolve
# multiple matching parcellations for a short spec to the newset version:
# try:
Expand Down Expand Up @@ -140,7 +149,12 @@
self._CACHED_MATCHES[spec] = True
return super().matches(spec)

def get_map(self, space=None, maptype: Union[str, MapType] = MapType.LABELLED, spec: str = ""):
def get_map(
self,
space: Union[str, "Space"],
maptype: Union[Literal['labelled', 'statistical'], MapType] = MapType.LABELLED,
spec: str = ""
):
"""
Get the maps for the parcellation in the requested template space.

Expand All @@ -153,8 +167,8 @@
Parameters
----------
space: Space or str
template space specification
maptype: MapType
reference space specification such as name, id, or a `Space` instance.
maptype: MapType or str
Type of map requested (e.g., statistical or labelled).
Use MapType.STATISTICAL to request probability maps.
Defaults to MapType.LABELLED.
Expand All @@ -169,26 +183,24 @@
A ParcellationMap representing the volumetric map or
a SparseMap representing the list of statistical maps.
"""
if not isinstance(maptype, MapType):
if isinstance(maptype, str):
maptype = MapType[maptype.upper()]
assert isinstance(maptype, MapType), "Possible values of `maptype` are `MapType`s, 'labelled', 'statistical'."

candidates = [
m for m in parcellationmap.Map.registry()
if m.space.matches(space)
and m.maptype == maptype
and m.parcellation
and m.parcellation.matches(self)
]
if len(candidates) == 0:
logger.error(f"No {maptype} map in {space} available for {str(self)}")
return None
raise NoMapMatchingValues(f"No '{maptype}' map in '{space}' available for {str(self)}")
if len(candidates) > 1:
spec_candidates = [
c for c in candidates if all(w.lower() in c.name.lower() for w in spec.split())
]
if len(spec_candidates) == 0:
logger.warning(f"'{spec}' does not match any options from {[c.name for c in candidates]}.")
return None
raise NoMapMatchingValues(f"'{spec}' does not match any options from {[c.name for c in candidates]}.")

Check warning on line 203 in siibra/core/parcellation.py

View check run for this annotation

Codecov / codecov/patch

siibra/core/parcellation.py#L203

Added line #L203 was not covered by tests
if len(spec_candidates) > 1:
logger.warning(
f"Multiple maps are available in this specification of space, parcellation, and map type.\n"
Expand Down
4 changes: 4 additions & 0 deletions siibra/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,7 @@ class ZeroVolumeBoundingBox(Exception):

class NoneCoordinateSuppliedError(ValueError):
pass


class NoMapMatchingValues(ValueError):
pass
21 changes: 12 additions & 9 deletions test/core/test_parcellation.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from siibra.core.region import Region
from siibra.commons import Species
import siibra
from siibra.exceptions import NoMapMatchingValues

correct_json = {
"name": "foobar",
Expand Down Expand Up @@ -82,7 +83,7 @@ def test_attr(self):
INCORRECT_MAP_TYPE = "incorrect_type"


class InputMap(NamedTuple):
class InputMapType(NamedTuple):
input: Union[str, MapType]
alias: MapType

Expand Down Expand Up @@ -121,10 +122,11 @@ def setUpClass(cls) -> None:
[None, "space arg", DummySpace()],
# input, maptype
[
InputMap(None, MapType.LABELLED),
InputMap("labelled", MapType.LABELLED),
InputMap(MapType.LABELLED, MapType.LABELLED),
InputMap(INCORRECT_MAP_TYPE, None),
InputMapType(None, None),
InputMapType("labelled", MapType.LABELLED),
InputMapType("Laballlled", None),
InputMapType(MapType.LABELLED, MapType.LABELLED),
InputMapType(INCORRECT_MAP_TYPE, None),
],
# volume configuration
product(
Expand All @@ -148,12 +150,11 @@ def setUpClass(cls) -> None:
)
)
def test_get_map(
self, space, maptype_input: InputMap, vol_spec: Tuple[MapConfig, MapConfig]
self, space, maptype_input: InputMapType, vol_spec: Tuple[MapConfig, MapConfig]
):
from siibra.volumes import Map

ExpectedException = None
expected_return_idx = None

for idx, vol_s in enumerate(vol_spec):
if (
Expand All @@ -163,9 +164,11 @@ def test_get_map(
):
expected_return_idx = idx
break
else:
ExpectedException = NoMapMatchingValues

if maptype_input.alias is None:
ExpectedException = KeyError
ExpectedException = AssertionError if maptype_input.input is None else KeyError

with patch.object(Map, "registry") as map_registry_mock:
registry_return = [
Expand Down Expand Up @@ -196,7 +199,7 @@ def test_get_map(
if expected_return_idx is not None:
self.assertIs(map, registry_return[expected_return_idx])
else:
self.assertIsNone(map)
self.assertRaises(ExpectedException)

@parameterized.expand(
[
Expand Down
Loading