Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
51 changes: 49 additions & 2 deletions backend/ibex/data_source/imas_python_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -678,6 +678,43 @@ def _leaf_node_coordinates_contain_time(self, leaf_node_path: str, coordinates_t

return False

def _generate_grid_quantity_alias(self, grid_node: IDSNumericArray):
"""
Generates alias and unit for selected grid node. Assumes grid_node.name == "dimX" X=(1...N)
:param grid_node: IDSNode (named dimX, X = [1...N])
:return:
"""
result = {"alias": None, "unit_alias": None}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should better use keys named "axis_labels" and "units", speking of alias here is going to be confusing in the long term as in the DD identifiers alias metadata has another meaning

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unit alias won't work until new version of DD and IMAS-Python is released.
Code extracting them is left for the future.

Will rename alias->axis_label and unit_alias->unit

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unit alias won't work until new version of DD and IMAS-Python is released. Code extracting them is left for the future.

In DD units are there already (only axis_label is missing but you are not using it) since 4.1.0, in IMAS-Python, the identifiers API has been extended to allow access to units since 2.3.0 which was released last week.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done
Ready for further review

if grid_node._parent is None or grid_node._parent._parent is None:
return result
if not re.search(r"dim[1-9]", grid_node.metadata.name):
return result

# assume grid_node is located inside XXX/grid/<node> and grid_type is located in XXX/grid_type
grid_type_index = grid_node._parent._parent.grid_type.index
if grid_type_index == imas.ids_defs.EMPTY_INT:
return result

dim_index = int(grid_node.metadata.name[-1]) - 1 # dim1->0, dim2->1 etc...
# Extract units
try:
units = imas.identifiers.poloidal_plane_coordinates_identifier(grid_type_index).units.split(",")
result["unit_alias"] = units[dim_index]
except (ValueError, KeyError, AttributeError):
result["unit_alias"] = None

# Extract axis labels
try:
axis_labels = imas.identifiers.poloidal_plane_coordinates_identifier(grid_type_index).axis_labels.split(",")
result["alias"] = axis_labels[dim_index]
except AttributeError:
description = imas.identifiers.poloidal_plane_coordinates_identifier(grid_type_index).description
match = re.findall(r"(\w+)=(dim[1-9])", description)
axis_labels = {v: k for k, v in match}
result["alias"] = axis_labels.get(grid_node.metadata.name, None)

return result

def get_geometry_overlay_nodes(
self,
uri: str,
Expand Down Expand Up @@ -982,10 +1019,20 @@ def get_plot_data(self, plot_data_query: PlotDataRequestModel) -> dict:
except ValueError:
coord_data_shape = "irregular"

coord_name = coord.split("/")[-1]
alias = None
alias_unit = None
if re.search(r"dim[1-9]", coord_name):
alias_dict = self._generate_grid_quantity_alias(first_value)
alias = alias_dict["alias"]
alias_unit = alias_dict["unit_alias"]

coord_name = alias if alias else coord_name
units = alias_unit if alias_unit else first_value.metadata.units
c = {
"name": coord.split("/")[-1],
"name": coord_name,
"target": f"#{ids}/{target}",
"unit": first_value.metadata.units,
"unit": units,
"shape": coord_data_shape, # coord_data could be np.ndarray or list[np.ndarray]
"downsampled_shape": coord_data_shape,
"ndim": first_value.metadata.ndim,
Expand Down
2 changes: 1 addition & 1 deletion backend/ibex/endpoints/schemas/response_data_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class PlotDataCoordinateModel(BaseModel):
target: str = Field(
description="Which node coordinate is it", examples=["#equilibrium/time_slice[0]/profiles_2d[0]/psi"]
)
unit: str = Field(description="Data units", examples=[""])
unit: str = Field(description="Data units", examples=["m", "mixed"])
shape: list[int] | str = Field(description="Shape of the data", examples=[[129]])
downsampled_shape: list[int] | str = Field(description="Shape of the data after downsampling", examples=[[129]])
ndim: int = Field(description="Number of data dimensions stored in node", examples=[1])
Expand Down
5 changes: 5 additions & 0 deletions backend/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,16 @@ def entry_path(tmp_path_factory):
)
profiles_2d.grid.dim1 = np.array([0, 1, 2], dtype=float)
profiles_2d.grid.dim2 = np.array([0, 1, 2], dtype=float)
profiles_2d.grid.volume_element = np.array([[1.0, 2.0, 3.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]], dtype=float)
i += 10

# ===== for data smoothing (must be time-based) =====
core_profiles.global_quantities.ip = np.array([1.0, 2.0, 3.0, 4.0, 5.0])

# for coordinate aliases/units
core_profiles.profiles_2d[0].grid_type = 1
core_profiles.profiles_2d[1].grid_type = 2

entry.put(core_profiles)

# ===== for geometry overlay =====
Expand Down
29 changes: 27 additions & 2 deletions backend/tests/test_data_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,13 +147,13 @@ def test_plot_data_2d(entry_path):
assert time_coordinate["description"] == "Generic time"

dim1_coordinate = response_body["data"]["coordinates"][0]
assert dim1_coordinate["name"] == "dim1"
assert dim1_coordinate["name"] == "R" # alias for dim1
assert dim1_coordinate["target"] == "#core_profiles/profiles_2d[:]/ion[:]/temperature"
assert dim1_coordinate["shape"] == [5, 3]
assert dim1_coordinate["path"] == "#core_profiles/profiles_2d[:]/grid/dim1"

dim2_coordinate = response_body["data"]["coordinates"][1]
assert dim2_coordinate["name"] == "dim2"
assert dim2_coordinate["name"] == "Z" # alias for dim2
assert dim2_coordinate["target"] == "#core_profiles/profiles_2d[:]/ion[:]/temperature"
assert dim2_coordinate["shape"] == [5, 3]
assert dim2_coordinate["path"] == "#core_profiles/profiles_2d[:]/grid/dim2"
Expand Down Expand Up @@ -205,3 +205,28 @@ def test_plot_data_requires_savgol_window_length_and_polyorder(entry_path):
)
assert response.status_code == 422
assert "savgol_smoothing_polyorder is required" in response.text


def test_plot_data_coordinate_aliases(entry_path):

parameters = {
"uri": f"imas:hdf5?path={entry_path}#core_profiles/profiles_2d[0]/grid/volume_element",
}
response = pytest.test_client.get("/data/plot_data", params=parameters)
response_body = response.json()

assert response.status_code == 200

dim1_coordinate = response_body["data"]["coordinates"][0]
assert dim1_coordinate["name"].lower() == "r"

parameters = {
"uri": f"imas:hdf5?path={entry_path}#core_profiles/profiles_2d[1]/grid/volume_element",
}
response = pytest.test_client.get("/data/plot_data", params=parameters)
response_body = response.json()

assert response.status_code == 200

dim1_coordinate = response_body["data"]["coordinates"][0]
assert dim1_coordinate["name"].lower() == "rho"
Loading