diff --git a/opengeodeweb_back_schemas.json b/opengeodeweb_back_schemas.json index 00b14e0a..f58f88f0 100644 --- a/opengeodeweb_back_schemas.json +++ b/opengeodeweb_back_schemas.json @@ -2721,6 +2721,124 @@ "additionalProperties": false } }, + "model_physical_properties": { + "$id": "opengeodeweb_back/model_physical_properties", + "route": "/model_physical_properties", + "methods": [ + "POST" + ], + "type": "object", + "properties": { + "id": { + "title": "DataId", + "type": "string", + "minLength": 32, + "maxLength": 32 + } + }, + "required": [ + "id" + ], + "additionalProperties": false, + "response": { + "type": "object", + "properties": { + "physical_properties": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "component_type": { + "type": "string", + "enum": [ + "Corner", + "Line", + "Surface", + "Block" + ] + }, + "attribute_id": { + "type": "string" + }, + "attribute_name": { + "type": "string" + }, + "element_type": { + "type": "string", + "enum": [ + "vertex", + "edge", + "polygon", + "polyhedron" + ] + }, + "nb_items": { + "type": "integer", + "minimum": 1 + }, + "components": { + "type": "array", + "items": { + "type": "object", + "properties": { + "geode_id": { + "title": "GeodeId", + "type": "string", + "minLength": 36, + "maxLength": 36 + }, + "min_values": { + "type": "array", + "items": { + "type": [ + "number", + "null" + ] + } + }, + "max_values": { + "type": "array", + "items": { + "type": [ + "number", + "null" + ] + } + } + }, + "required": [ + "geode_id", + "min_values", + "max_values" + ], + "additionalProperties": false, + "title": "PhysicalPropertyComponent" + } + } + }, + "required": [ + "name", + "component_type", + "attribute_id", + "attribute_name", + "element_type", + "nb_items", + "components" + ], + "additionalProperties": false, + "title": "PhysicalProperty" + } + } + }, + "required": [ + "physical_properties" + ], + "additionalProperties": false + } + }, "model_component_vertex_attribute_range": { "$id": "opengeodeweb_back/model_component_vertex_attribute_range", "route": "/model_component_vertex_attribute_range", diff --git a/opengeodeweb_back_typed_schemas.d.ts b/opengeodeweb_back_typed_schemas.d.ts index 129ec1d3..089425d7 100644 --- a/opengeodeweb_back_typed_schemas.d.ts +++ b/opengeodeweb_back_typed_schemas.d.ts @@ -376,6 +376,34 @@ export interface PingResponse { message: string; } +export interface ModelPhysicalPropertiesParams { + id: DataId; +} + +export interface ModelPhysicalPropertiesResponse { + physical_properties: PhysicalProperty[]; +} + +export interface PhysicalProperty { + attribute_id: string; + attribute_name: string; + component_type: ComponentType; + components: PhysicalPropertyComponent[]; + element_type: ElementType; + name: string; + nb_items: number; +} + +export type ComponentType = "Corner" | "Line" | "Surface" | "Block"; + +export interface PhysicalPropertyComponent { + geode_id: GeodeId; + max_values: Array; + min_values: Array; +} + +export type ElementType = "vertex" | "edge" | "polygon" | "polyhedron"; + export interface ModelComponentVertexAttributeRangeParams { attribute_name: AttributeName; component_ids: GeodeId[]; @@ -641,6 +669,7 @@ export interface Schemas { readonly polygon_attribute_range: (typeof json)["opengeodeweb_back"]["polygon_attribute_range"] & TypedSchema; readonly polygon_attribute_names: (typeof json)["opengeodeweb_back"]["polygon_attribute_names"] & TypedSchema; readonly ping: (typeof json)["opengeodeweb_back"]["ping"] & TypedSchema; + readonly model_physical_properties: (typeof json)["opengeodeweb_back"]["model_physical_properties"] & TypedSchema; readonly model_component_vertex_attribute_range: (typeof json)["opengeodeweb_back"]["model_component_vertex_attribute_range"] & TypedSchema; readonly model_component_vertex_attribute_names: (typeof json)["opengeodeweb_back"]["model_component_vertex_attribute_names"] & TypedSchema; readonly model_component_polyhedron_attribute_range: (typeof json)["opengeodeweb_back"]["model_component_polyhedron_attribute_range"] & TypedSchema; diff --git a/requirements.txt b/requirements.txt index aefa233f..597e5178 100644 --- a/requirements.txt +++ b/requirements.txt @@ -84,4 +84,3 @@ werkzeug==3.1.8 # flask # flask-cors -opengeodeweb-microservice==1.*,>=1.5.0rc1 diff --git a/src/opengeodeweb_back/routes/blueprint_routes.py b/src/opengeodeweb_back/routes/blueprint_routes.py index 14fc73cd..2d8e55b1 100644 --- a/src/opengeodeweb_back/routes/blueprint_routes.py +++ b/src/opengeodeweb_back/routes/blueprint_routes.py @@ -783,6 +783,115 @@ def model_component_polyhedron_attribute_range( ) +def _element_attribute_managers( + mesh: og.VertexSet, +) -> list[tuple[str, og.AttributeManager]]: + """Attribute managers of a component mesh, its elements before its vertices.""" + managers: list[tuple[str, og.AttributeManager]] = [] + for element_type in ("polyhedron", "polygon", "edge"): + method = getattr(mesh, f"{element_type}_attribute_manager", None) + if method is not None: + managers.append((element_type, method())) + managers.append(("vertex", mesh.vertex_attribute_manager())) + return managers + + +def _physical_property_component( + component_id: og.uuid, + attribute_manager: og.AttributeManager, + attribute_id: og.uuid, + nb_items: int, +) -> schemas.model_physical_properties.PhysicalPropertyComponent: + min_values: list[float | None] = [] + max_values: list[float | None] = [] + for item_index in range(nb_items): + values, _ = _extract_valid_values_from_attribute( + attribute_manager, attribute_id, item_index + ) + # An item without any value (e.g. a free displacement axis) is None: NaN is not JSON + min_values.append(min(values) if values else None) + max_values.append(max(values) if values else None) + return schemas.model_physical_properties.PhysicalPropertyComponent( + geode_id=component_id.string(), + min_values=min_values, + max_values=max_values, + ) + + +def _physical_property( + model: GeodeBRep, + name: og.PhysicalPropertyName, +) -> schemas.model_physical_properties.PhysicalProperty | None: + """The components carrying a physical property, with their value range per item. + + The attribute is searched on the element managers first, then on the vertices: the + physical property only records the component type, not the mesh element. The first + component carrying it sets the element: the others are only read on that element, a + component carrying it on another one is left out. + """ + info = model.brep.physical_property_info(name) + component_type = info.component_type.get() + attribute_id = info.attribute_id + element_type: str | None = None + attribute_name = "" + nb_items = 1 + components: list[schemas.model_physical_properties.PhysicalPropertyComponent] = [] + for registry_type, component_ids in model.mesh_components().items(): + if registry_type.get() != component_type: + continue + for component_id in component_ids: + component = model.component(component_id) + if not isinstance(component, ComponentMesh): + continue + for element, attribute_manager in _element_attribute_managers(component.mesh()): + if element_type is not None and element != element_type: + continue + attribute = attribute_manager.find_generic_attribute(attribute_id) + if attribute is None: + continue + if element_type is None: + element_type = element + attribute_name = attribute.name() or name.name + nb_items = attribute.nb_items() + components.append( + _physical_property_component( + component_id, attribute_manager, attribute_id, nb_items + ) + ) + break + if element_type is None: + return None + return schemas.model_physical_properties.PhysicalProperty( + name=name.name, + component_type=schemas.model_physical_properties.ComponentType(component_type), + attribute_id=attribute_id.string(), + attribute_name=attribute_name, + element_type=schemas.model_physical_properties.ElementType(element_type), + nb_items=nb_items, + components=components, + ) + + +@typed_route(routes, schemas.model_physical_properties_route) +def model_physical_properties( + params: schemas.ModelPhysicalProperties, +) -> schemas.ModelPhysicalPropertiesResponse: + """Physical properties of a model and the values of the components carrying them.""" + geode_object = geode_functions.load_geode_object(params.id) + if not isinstance(geode_object, GeodeModel): + flask.abort(400, f"{params.id} is not a GeodeModel") + physical_properties: list[schemas.model_physical_properties.PhysicalProperty] = [] + # Only BReps (and the models built on them) carry physical properties + if isinstance(geode_object, GeodeBRep): + for name in og.PhysicalPropertyName: + if not geode_object.brep.has_physical_property(name): + continue + physical_property = _physical_property(geode_object, name) + if physical_property is not None: + physical_properties.append(physical_property) + return schemas.ModelPhysicalPropertiesResponse(physical_properties=physical_properties) + + @typed_route(routes, schemas.horizon_stack_info_route) def horizon_stack_info(params: schemas.HorizonStackInfo) -> schemas.HorizonStackInfoResponse: """Horizons and stratigraphic units of a horizon stack, top to bottom.""" diff --git a/src/opengeodeweb_back/routes/schemas/__init__.py b/src/opengeodeweb_back/routes/schemas/__init__.py index f80b6964..c84576fa 100644 --- a/src/opengeodeweb_back/routes/schemas/__init__.py +++ b/src/opengeodeweb_back/routes/schemas/__init__.py @@ -11,6 +11,7 @@ from .polygon_attribute_range import * from .polygon_attribute_names import * from .ping import * +from .model_physical_properties import * from .model_component_vertex_attribute_range import * from .model_component_vertex_attribute_names import * from .model_component_polyhedron_attribute_range import * diff --git a/src/opengeodeweb_back/routes/schemas/model_physical_properties.json b/src/opengeodeweb_back/routes/schemas/model_physical_properties.json new file mode 100644 index 00000000..cd09bc17 --- /dev/null +++ b/src/opengeodeweb_back/routes/schemas/model_physical_properties.json @@ -0,0 +1,111 @@ +{ + "route": "/model_physical_properties", + "methods": [ + "POST" + ], + "type": "object", + "properties": { + "id": { + "title": "DataId" + } + }, + "required": [ + "id" + ], + "additionalProperties": false, + "response": { + "type": "object", + "properties": { + "physical_properties": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "component_type": { + "type": "string", + "enum": [ + "Corner", + "Line", + "Surface", + "Block" + ] + }, + "attribute_id": { + "type": "string" + }, + "attribute_name": { + "type": "string" + }, + "element_type": { + "type": "string", + "enum": [ + "vertex", + "edge", + "polygon", + "polyhedron" + ] + }, + "nb_items": { + "type": "integer", + "minimum": 1 + }, + "components": { + "type": "array", + "items": { + "type": "object", + "properties": { + "geode_id": { + "title": "GeodeId" + }, + "min_values": { + "type": "array", + "items": { + "type": [ + "number", + "null" + ] + } + }, + "max_values": { + "type": "array", + "items": { + "type": [ + "number", + "null" + ] + } + } + }, + "required": [ + "geode_id", + "min_values", + "max_values" + ], + "additionalProperties": false, + "title": "PhysicalPropertyComponent" + } + } + }, + "required": [ + "name", + "component_type", + "attribute_id", + "attribute_name", + "element_type", + "nb_items", + "components" + ], + "additionalProperties": false, + "title": "PhysicalProperty" + } + } + }, + "required": [ + "physical_properties" + ], + "additionalProperties": false + } +} diff --git a/src/opengeodeweb_back/routes/schemas/model_physical_properties.py b/src/opengeodeweb_back/routes/schemas/model_physical_properties.py new file mode 100644 index 00000000..0b132b4d --- /dev/null +++ b/src/opengeodeweb_back/routes/schemas/model_physical_properties.py @@ -0,0 +1,71 @@ +from opengeodeweb_microservice.schema_types import DataId, GeodeId +from pathlib import Path +from opengeodeweb_microservice.schemas import Route, load_schema +from typing import List, Optional +from dataclasses_json import DataClassJsonMixin +from opengeodeweb_microservice.schemas import print_dataclass +from enum import Enum +from dataclasses import dataclass + + +@dataclass +class ModelPhysicalProperties(DataClassJsonMixin): + def __post_init__(self) -> None: + print_dataclass(self) + + id: DataId + + +class ComponentType(Enum): + BLOCK = "Block" + CORNER = "Corner" + LINE = "Line" + SURFACE = "Surface" + + +@dataclass +class PhysicalPropertyComponent(DataClassJsonMixin): + def __post_init__(self) -> None: + print_dataclass(self) + + geode_id: GeodeId + max_values: List[Optional[float]] + min_values: List[Optional[float]] + + +class ElementType(Enum): + EDGE = "edge" + POLYGON = "polygon" + POLYHEDRON = "polyhedron" + VERTEX = "vertex" + + +@dataclass +class PhysicalProperty(DataClassJsonMixin): + def __post_init__(self) -> None: + print_dataclass(self) + + attribute_id: str + attribute_name: str + component_type: ComponentType + components: List[PhysicalPropertyComponent] + element_type: ElementType + name: str + nb_items: int + + +@dataclass +class ModelPhysicalPropertiesResponse(DataClassJsonMixin): + def __post_init__(self) -> None: + print_dataclass(self) + + physical_properties: List[PhysicalProperty] + + +model_physical_properties_route = Route( + schema=load_schema(Path(__file__)), + params=ModelPhysicalProperties, + response=ModelPhysicalPropertiesResponse, +) + +__all__ = ["ModelPhysicalProperties", "ModelPhysicalPropertiesResponse", "model_physical_properties_route"] diff --git a/src/opengeodeweb_back/typed_route.py b/src/opengeodeweb_back/typed_route.py index 851fe018..e92a8221 100644 --- a/src/opengeodeweb_back/typed_route.py +++ b/src/opengeodeweb_back/typed_route.py @@ -78,7 +78,8 @@ def view() -> flask.Response: f"expected {route.response.__name__}" ) raise TypeError(msg) - payload = _drop_none(result.to_dict()) + # encode_json turns the enums of the schemas into their values + payload = _drop_none(result.to_dict(encode_json=True)) if flask.current_app.debug or flask.current_app.testing: validate_response(payload) return flask.make_response(payload, 200) diff --git a/tests/test_routes.py b/tests/test_routes.py index 3f0cc3e2..056452e3 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -3,6 +3,7 @@ # Standard library imports import contextlib import json +import math import os import shutil import sqlite3 @@ -38,6 +39,8 @@ from opengeodeweb_back.routes.blueprint_routes import extract_valid_attribute_values if TYPE_CHECKING: + from collections.abc import Generator + from flask.testing import FlaskClient from werkzeug.test import TestResponse @@ -1097,3 +1100,114 @@ def test_apply_time_series_errors(client: FlaskClient) -> None: point_set_id = point_set["id"] response = client.post(route, json={"id": point_set_id, "filename": filename}) assert response.status_code == 400 + + +PHYSICAL_PROPERTIES_FILE = "cube_physical_properties.og_brep" +POROSITY = 0.25 + + +def _write_physical_properties_brep(path: Path) -> None: + """cube.og_brep with a porosity on its Block and a displacement on two of its Surfaces. + + The displacement attribute is named "displacement", not like the physical property, and + its x and z components are free (NaN). The last Surface also carries it, on its vertices + instead of its polygons: the route leaves it out. + """ + [brep] = og.load_brep(str(path.parent / "cube.og_brep")) + builder = og.BRepBuilder(brep) + + porosity_id = og.uuid() + porosity_values = og.AttributeValuesDouble() + porosity_values.default_value = POROSITY + for block in brep.blocks(): + block.mesh().polyhedron_attribute_manager().create_attribute_variable_double( + "porosity", porosity_id, porosity_values, og.AttributeProperties() + ) + builder.set_physical_property( + og.PhysicalPropertyName.porosity, og.Block3D.component_type_static(), porosity_id + ) + + displacement_id = og.uuid() + displacement_values = og.AttributeValuesArrayDouble3() + displacement_values.default_value = [math.nan, 0.0, math.nan] + surfaces = list(brep.surfaces()) + for surface in surfaces[:2]: + surface.mesh().polygon_attribute_manager().create_attribute_variable_arraydouble3( + "displacement", displacement_id, displacement_values, og.AttributeProperties() + ) + surfaces[-1].mesh().vertex_attribute_manager().create_attribute_variable_arraydouble3( + "displacement", displacement_id, displacement_values, og.AttributeProperties() + ) + builder.set_physical_property( + og.PhysicalPropertyName.boundary_displacement, + og.Surface3D.component_type_static(), + displacement_id, + ) + og.save_brep(brep, str(path)) + + +@pytest.fixture +def physical_properties_brep() -> Generator[str]: + path = data_dir / PHYSICAL_PROPERTIES_FILE + _write_physical_properties_brep(path) + yield PHYSICAL_PROPERTIES_FILE + path.unlink(missing_ok=True) + + +def test_model_physical_properties(client: FlaskClient, physical_properties_brep: str) -> None: + route = "/opengeodeweb_back/model_physical_properties" + [model] = test_utils.check_save_viewable_file(client, "BRep", physical_properties_brep) + model_id: str = model["id"] + block_ids = [ + component["geode_id"] + for component in model["mesh_components"] + if component["type"] == "Block" + ] + + response = client.post(route, json={"id": model_id}) + assert response.status_code == 200 + properties = { + physical_property["name"]: physical_property + for physical_property in response.get_json()["physical_properties"] + } + assert set(properties) == {"porosity", "boundary_displacement"} + + porosity = properties["porosity"] + assert porosity["component_type"] == "Block" + assert porosity["element_type"] == "polyhedron" + assert porosity["attribute_name"] == "porosity" + assert porosity["nb_items"] == 1 + assert [component["geode_id"] for component in porosity["components"]] == block_ids + for component in porosity["components"]: + assert component["min_values"] == [POROSITY] + assert component["max_values"] == [POROSITY] + + displacement = properties["boundary_displacement"] + assert displacement["component_type"] == "Surface" + assert displacement["element_type"] == "polygon" + # The attribute keeps its own name, the front colors the model with it + assert displacement["attribute_name"] == "displacement" + assert displacement["nb_items"] == 3 + # The Surface carrying it on its vertices is left out: the property is on polygons + assert len(displacement["components"]) == 2 + for component in displacement["components"]: + # Free components have no value: null, as NaN is not JSON + assert component["min_values"] == [None, 0.0, None] + assert component["max_values"] == [None, 0.0, None] + + def get_full_data() -> test_utils.JsonData: + return {"id": model_id} + + test_utils.test_route_wrong_params(client, route, get_full_data) + + +def test_model_physical_properties_without_any(client: FlaskClient) -> None: + route = "/opengeodeweb_back/model_physical_properties" + model_id, _ = _load_brep_components(client) + response = client.post(route, json={"id": model_id}) + assert response.status_code == 200 + assert response.get_json()["physical_properties"] == [] + + [point_set] = test_utils.check_save_viewable_file(client, "PointSet3D", "test.og_pts3d") + response = client.post(route, json={"id": point_set["id"]}) + assert response.status_code == 400