Skip to content

Commit 7e82f0c

Browse files
Merge pull request #28 from scverse/feature/coordspaces
coordinate systems
2 parents 5afe438 + 6bcd59b commit 7e82f0c

4 files changed

Lines changed: 170 additions & 3 deletions

File tree

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,4 @@ __pycache__/
2525

2626
# data
2727
spatialdata-sandbox
28+
*.zarr/

‎README.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
## Work in progress ⚠
2-
- To get involved in the discussion you are welcome to join our Zulip workspace and/or our community meetings every second week; [more info here](https://imagesc.zulipchat.com/#narrow/stream/329057-scverse).
3-
- **This repository doesn't contain the latest version of the code**; we aim at a beta release in the following months. If interested in a demo/early beta, please reach out to us.
4-
- Links to the OME-NGFF specification: [0.4](https://ngff.openmicroscopy.org/latest/), [0.5-dev (tables)](https://github.com/ome/ngff/pull/64), [0.5-dev (transformations and coordinate systems)](https://github.com/ome/ngff/pull/138)
2+
3+
- To get involved in the discussion you are welcome to join our Zulip workspace and/or our community meetings every second week; [more info here](https://imagesc.zulipchat.com/#narrow/stream/329057-scverse).
4+
- **This repository doesn't contain the latest version of the code**; we aim at a beta release in the following months. If interested in a demo/early beta, please reach out to us.
5+
- Links to the OME-NGFF specification: [0.4](https://ngff.openmicroscopy.org/latest/), [0.5-dev (tables)](https://github.com/ome/ngff/pull/64), [0.5-dev (transformations and coordinate systems)](https://github.com/ome/ngff/pull/138)
6+
57
# spatialdata
68

79
[![Tests][badge-tests]][link-tests]
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
import json
2+
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
3+
4+
__all__ = ["CoordinateSystem"]
5+
6+
Axis_t = Dict[str, str]
7+
CoordSystem_t = Dict[str, Union[str, List[Dict[str, str]]]]
8+
AXIS_ORDER = ["t", "c", "z", "y", "x"]
9+
10+
11+
class Axis:
12+
name: str
13+
type: str
14+
unit: Optional[str]
15+
16+
def __init__(self, name: str, type: str, unit: Optional[str] = None):
17+
self.name = name
18+
self.type = type
19+
self.unit = unit
20+
21+
def to_dict(self) -> Axis_t:
22+
d = {"name": self.name, "type": self.type}
23+
if self.unit is not None:
24+
d["unit"] = self.unit
25+
return d
26+
27+
28+
class CoordinateSystem:
29+
def __init__(self, name: Optional[str] = None, axes: Optional[List[Axis]] = None):
30+
self._name = name
31+
self._axes = axes if axes is not None else []
32+
33+
@staticmethod
34+
def from_dict(coord_sys: CoordSystem_t) -> "CoordinateSystem":
35+
if "name" not in coord_sys.keys():
36+
raise ValueError("`coordinate_system` MUST have a name.")
37+
if "axes" not in coord_sys.keys():
38+
raise ValueError("`coordinate_system` MUST have axes.")
39+
40+
if TYPE_CHECKING:
41+
assert isinstance(coord_sys["name"], str)
42+
assert isinstance(coord_sys["axes"], list)
43+
name = coord_sys["name"]
44+
45+
# sorted_axes = sorted(coord_sys["axes"], key=lambda x: AXIS_ORDER.index(x["name"]))
46+
axes = []
47+
for axis in coord_sys["axes"]:
48+
# for axis in sorted_axes:
49+
if "name" not in axis.keys():
50+
raise ValueError("Each axis MUST have a name.")
51+
if "type" not in axis.keys():
52+
raise ValueError("Each axis MUST have a type.")
53+
if "unit" not in axis.keys():
54+
if not axis["type"] in ["channel", "array"]:
55+
raise ValueError("Each axis is either of type channel either MUST have a unit.")
56+
kw = {}
57+
if "unit" in axis.keys():
58+
kw = {"unit": axis["unit"]}
59+
axes.append(Axis(name=axis["name"], type=axis["type"], **kw))
60+
return CoordinateSystem(name=name, axes=axes)
61+
62+
def to_dict(self) -> CoordSystem_t:
63+
out: Dict[str, Any] = {"name": self.name, "axes": [axis.to_dict() for axis in self._axes]}
64+
# if TYPE_CHECKING:
65+
# assert isinstance(out["axes"], list)
66+
return out
67+
68+
def from_array(self, array: Any) -> None:
69+
raise NotImplementedError()
70+
71+
@staticmethod
72+
def from_json(data: Union[str, bytes]) -> "CoordinateSystem":
73+
coord_sys = json.loads(data)
74+
return CoordinateSystem.from_dict(coord_sys)
75+
76+
def to_json(self, **kwargs: Any) -> str:
77+
out = self.to_dict()
78+
return json.dumps(out, **kwargs)
79+
80+
def __eq__(self, other: Any) -> bool:
81+
if not isinstance(other, CoordinateSystem):
82+
return False
83+
return self.to_dict() == other.to_dict()
84+
85+
@property
86+
def name(self) -> Optional[str]:
87+
return self._name
88+
89+
@property
90+
def axes_names(self) -> List[str]:
91+
return [ax.name for ax in self._axes]
92+
93+
@property
94+
def axes_types(self) -> List[str]:
95+
return [ax.type for ax in self._axes]
96+
97+
def __hash__(self) -> int:
98+
return hash(frozenset(self.to_dict()))
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import copy
2+
import json
3+
4+
import pytest
5+
6+
from spatialdata._core.coordinate_system import Axis, CoordinateSystem
7+
8+
input_dict = {
9+
"name": "volume_micrometers",
10+
"axes": [
11+
{"name": "x", "type": "space", "unit": "micrometer"},
12+
{"name": "y", "type": "space", "unit": "micrometer"},
13+
{"name": "z", "type": "space", "unit": "micrometer"},
14+
],
15+
}
16+
17+
18+
def test_coordinate_system_instantiation_and_properties():
19+
coord_sys = CoordinateSystem.from_dict(input_dict)
20+
assert coord_sys.name == "volume_micrometers"
21+
assert [ax.name for ax in coord_sys._axes] == ["x", "y", "z"]
22+
assert coord_sys.axes_names == ["x", "y", "z"]
23+
24+
assert [ax.type for ax in coord_sys._axes] == ["space", "space", "space"]
25+
assert coord_sys.axes_types == ["space", "space", "space"]
26+
27+
output_dict = coord_sys.to_dict()
28+
assert input_dict == output_dict
29+
30+
axes = [
31+
Axis(name="x", type="space", unit="micrometer"),
32+
Axis(name="y", type="space", unit="micrometer"),
33+
Axis(name="z", type="space", unit="micrometer"),
34+
]
35+
coord_manual = CoordinateSystem(
36+
name="volume_micrometers",
37+
axes=axes,
38+
)
39+
40+
assert coord_manual.to_dict() == coord_sys.to_dict()
41+
42+
43+
def test_coordinate_system_exceptions():
44+
input_dict1 = copy.deepcopy(input_dict)
45+
input_dict1["axes"][0].pop("name")
46+
coord_sys = CoordinateSystem()
47+
with pytest.raises(ValueError):
48+
coord_sys.from_dict(input_dict1)
49+
50+
input_dict2 = copy.deepcopy(input_dict)
51+
input_dict2["axes"][0].pop("type")
52+
coord_sys = CoordinateSystem()
53+
with pytest.raises(ValueError):
54+
coord_sys.from_dict(input_dict2)
55+
56+
# not testing the cases with axis.type in ['channel', 'array'] as all the more complex checks are handled by the
57+
# validation schema
58+
59+
60+
def test_coordinate_system_roundtrip():
61+
input_json = json.dumps(input_dict)
62+
cs = CoordinateSystem.from_json(input_json)
63+
output_json = cs.to_json()
64+
assert input_json == output_json
65+
cs2 = CoordinateSystem.from_json(output_json)
66+
assert cs == cs2

0 commit comments

Comments
 (0)