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

[python] Update coordinate space <-> JSON converters #3114

Merged
merged 2 commits into from
Oct 2, 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
2 changes: 1 addition & 1 deletion apis/python/src/tiledbsoma/_point_cloud_dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -514,7 +514,7 @@ def coordinate_space(self, value: CoordinateSpace) -> None:
raise ValueError(
f"Cannot change axis names of a point cloud dataframe. Existing "
f"axis names are {self._coord_space.axis_names}. New coordinate "
f"space has axis names {self._coord_space.axis_names}."
f"space has axis names {value.axis_names}."
)
self.metadata[SOMA_COORDINATE_SPACE_METADATA_KEY] = coordinate_space_to_json(
value
Expand Down
47 changes: 34 additions & 13 deletions apis/python/src/tiledbsoma/_spatial_util.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import json
from typing import Dict, Optional, Tuple
from typing import Any, Dict, Optional, Tuple, Type

import numpy as np
import pyarrow as pa
Expand All @@ -26,31 +26,52 @@ def coordinate_space_to_json(coord_space: somacore.CoordinateSpace) -> str:


def transform_from_json(data: str) -> somacore.CoordinateTransform:
"""Creates a coordinate transform from a json string."""
"""Convert a JSON string representing a CoordinateTransform"""

raw = json.loads(data)

try:
transform_type = raw.pop("transform_type")
except KeyError as ke:
raise KeyError("Missing required key 'transform_type'.") from ke
except KeyError:
raise KeyError(
"'transform_type' not found when attempting to convert "
"JSON to CoordinateTransform child class"
)

try:
kwargs = raw.pop("transform")
except KeyError as ke:
raise KeyError("Missing reequired key 'transform'.") from ke
if transform_type == "IdentityTransform":
return somacore.IdentityTransform(**kwargs)
elif transform_type == "AffineTransform":
return somacore.AffineTransform(**kwargs)
else:
raise KeyError(f"Unrecognized transform type '{transform_type}'.")
except KeyError:
raise KeyError(
"'transform' kwargs options not found when attempting to "
"convert JSON to CoordinateTransform child class"
)

coord_transform_init: Dict[str, Type[somacore.CoordinateTransform]] = {
"AffineTransform": somacore.AffineTransform,
"ScaleTransform": somacore.ScaleTransform,
"UniformScaleTransform": somacore.UniformScaleTransform,
"IdentityTransform": somacore.IdentityTransform,
}

try:
return coord_transform_init[transform_type](**kwargs)
except KeyError:
raise KeyError(f"Unrecognized transform type key '{transform_type}'")


def transform_to_json(transform: somacore.CoordinateTransform) -> str:
kwargs = {
"""Representing a CoordinateTransform as a JSON string"""

kwargs: Dict[str, Any] = {
"input_axes": transform.input_axes,
"output_axes": transform.output_axes,
}
if isinstance(transform, somacore.IdentityTransform):
pass
elif isinstance(transform, somacore.UniformScaleTransform):
kwargs["scale"] = transform.scale
elif isinstance(transform, somacore.ScaleTransform):
kwargs["scale_factors"] = transform.scale_factors.tolist()
elif isinstance(transform, somacore.AffineTransform):
kwargs["matrix"] = transform.augmented_matrix.tolist()
else:
Expand Down
Loading