diff --git a/opengeodeweb_back_schemas.json b/opengeodeweb_back_schemas.json index e3a1dc63..e43f9835 100644 --- a/opengeodeweb_back_schemas.json +++ b/opengeodeweb_back_schemas.json @@ -1399,10 +1399,52 @@ ], "additionalProperties": false } + }, + "vertical_list": { + "type": "array", + "items": { + "title": "CRS", + "type": "object", + "properties": { + "authority": { + "type": "string", + "minLength": 1 + }, + "code": { + "type": "string", + "minLength": 1 + }, + "name": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "authority", + "code", + "name" + ], + "additionalProperties": false + } + }, + "compoundable": { + "type": "array", + "items": { + "type": "string" + } + }, + "horizontal_parts": { + "type": "object", + "additionalProperties": { + "type": "string" + } } }, "required": [ - "crs_list" + "crs_list", + "vertical_list", + "compoundable", + "horizontal_parts" ], "additionalProperties": false } @@ -1518,6 +1560,9 @@ }, "binary_light_viewable": { "type": "string" + }, + "heights_unchanged": { + "type": "boolean" } }, "required": [ @@ -1525,6 +1570,9 @@ ], "additionalProperties": false } + }, + "heights_unchanged": { + "type": "boolean" } }, "required": [], diff --git a/opengeodeweb_back_typed_schemas.d.ts b/opengeodeweb_back_typed_schemas.d.ts index a3d1d297..e1e892da 100644 --- a/opengeodeweb_back_typed_schemas.d.ts +++ b/opengeodeweb_back_typed_schemas.d.ts @@ -155,7 +155,10 @@ export interface CRSGeographicListParams { } export interface CRSGeographicListResponse { - crs_list: CRS[]; + compoundable: string[]; + crs_list: CRS[]; + horizontal_parts: { [key: string]: string }; + vertical_list: CRS[]; } export interface CRSConvertGeographicParams { @@ -169,12 +172,14 @@ export interface CRSConvertGeographicParams { export interface CRSConvertGeographicResponse { binary_light_viewable?: string; crs?: CRS; + heights_unchanged?: boolean; linked?: CRSConvertGeographicResponseLinked[]; } export interface CRSConvertGeographicResponseLinked { binary_light_viewable?: string; crs?: CRS; + heights_unchanged?: boolean; id: DataId; } diff --git a/src/opengeodeweb_back/crs/crs_assignment.py b/src/opengeodeweb_back/crs/crs_assignment.py index 04b2365f..2be701e7 100644 --- a/src/opengeodeweb_back/crs/crs_assignment.py +++ b/src/opengeodeweb_back/crs/crs_assignment.py @@ -18,6 +18,7 @@ coordinate_system, coordinates_implausible, geographic_info, + heights_datum, known_info, ) @@ -53,10 +54,26 @@ def _keep_original_coordinates(geode_object: CrsGeodeObject) -> None: geode_object.create_crs("assigned", identity, identity) +def _already_in( + geode_object: CrsGeodeObject, + info: og_geosciences.GeographicCoordinateSystemInfo, + code: str, +) -> bool: + """A 2D data asked "A+B" while in A: it has no heights, so there is nothing to change.""" + active = geographic_info(geode_object.crs_manager()) + return ( + info.code != code + and active is not None + and active.authority_code() == info.authority_code() + ) + + def _assign( geode_object: CrsGeodeObject, authority: str, code: str ) -> og_geosciences.GeographicCoordinateSystemInfo: info = known_info(geode_object, authority, code) + if _already_in(geode_object, info, code): + return info prepare_crs_name(geode_object, info.authority_code()) _keep_original_coordinates(geode_object) geode_object.assign_crs(info.authority_code(), info) @@ -101,11 +118,33 @@ def assign_all( return entries -def convert(geode_object: CrsGeodeObject, authority: str, code: str) -> None: - if geographic_info(geode_object.crs_manager()) is None: +def _sample_height(geode_object: CrsGeodeObject) -> float | None: + for mesh in geode_object.crs_meshes(): + if mesh.nb_vertices() > 0: + return float(mesh.point(0).value(2)) + return None + + +def convert(geode_object: CrsGeodeObject, authority: str, code: str) -> bool: + """Convert to the CRS. True when the heights changed datum but kept their values. + + PROJ has no geoid grid: a change of vertical datum usually leaves the heights as they are. + The heights are compared, as PROJ still applies the offsets that need no grid. + """ + source = geographic_info(geode_object.crs_manager()) + if source is None: msg = "Assign a geographic CRS before converting" raise CrsError(msg) info = known_info(geode_object, authority, code) + if _already_in(geode_object, info, code): + return False + source_heights = heights_datum(source) + datum_changed = ( + geode_object.is_3d() + and source_heights is not None + and source_heights != heights_datum(info) + ) + height_before = _sample_height(geode_object) if datum_changed else None prepare_crs_name(geode_object, info.authority_code()) try: geode_object.convert_crs(info.authority_code(), info) @@ -115,3 +154,4 @@ def convert(geode_object: CrsGeodeObject, authority: str, code: str) -> None: logger.exception("Conversion to %s failed", info.authority_code()) msg = f"Coordinates cannot be converted to {info.authority_code()}: {error}" raise CrsError(msg) from error + return height_before is not None and _sample_height(geode_object) == height_before diff --git a/src/opengeodeweb_back/crs/crs_functions.py b/src/opengeodeweb_back/crs/crs_functions.py index e27cdcaf..460cce9e 100644 --- a/src/opengeodeweb_back/crs/crs_functions.py +++ b/src/opengeodeweb_back/crs/crs_functions.py @@ -103,7 +103,7 @@ def known_geographic_info( geode_object: CrsGeodeObject, authority: str, code: str ) -> og_geosciences.GeographicCoordinateSystemInfo | None: """The listed CRS for authority:code, None when PROJ does not know it.""" - return geographic_coordinate_systems(geode_object.is_3d()).get(f"{authority}:{code}") + return resolve_geographic_info(geode_object.is_3d(), authority, code) def geographic_info( @@ -187,7 +187,10 @@ def _query_proj_database(query: str, parameters: tuple[str, ...]) -> list[tuple[ def area_of_use(authority: str, code: str) -> list[tuple[float, float, float, float]]: """Extents where PROJ declares the CRS usable, empty when unknown.""" rows = _query_proj_database(AREA_OF_USE_QUERY, (authority, code)) or [] - return [(float(s), float(n), float(w), float(e)) for s, n, w, e in rows] + # Some extents of proj.db have no bounds: they say nothing about where the CRS is used + return [ + (float(s), float(n), float(w), float(e)) for s, n, w, e in rows if None not in (s, n, w, e) + ] @functools.cache @@ -197,6 +200,144 @@ def vertical_coordinate_systems() -> frozenset[str]: return frozenset(f"{authority}:{code}" for authority, code in rows) +@functools.cache +def compoundable_coordinate_systems() -> frozenset[str]: + """CRS without heights, which a vertical CRS can complete, as "AUTHORITY:CODE".""" + rows = ( + _query_proj_database( + "SELECT auth_name, code FROM projected_crs WHERE auth_name = 'EPSG' UNION " + "SELECT auth_name, code FROM geodetic_crs " + "WHERE auth_name = 'EPSG' AND type = 'geographic 2D'", + (), + ) + or [] + ) + return frozenset(f"{authority}:{code}" for authority, code in rows) + + +@functools.cache +def vertical_coordinate_system_list() -> list[tuple[str, str, str]]: + """(authority, code, name) of the vertical CRS offered to complete a CRS with heights.""" + rows = ( + _query_proj_database( + "SELECT auth_name, code, name FROM vertical_crs " + "WHERE auth_name = 'EPSG' AND deprecated = 0 " + "ORDER BY auth_name, name", + (), + ) + or [] + ) + return [(str(authority), str(code), str(name)) for authority, code, name in rows] + + +@functools.cache +def horizontal_parts() -> dict[str, str]: + """X/Y part of each registered compound CRS, both as "AUTHORITY:CODE".""" + rows = ( + _query_proj_database( + "SELECT auth_name, code, horiz_crs_auth_name, horiz_crs_code FROM compound_crs", () + ) + or [] + ) + return { + f"{authority}:{code}": f"{h_authority}:{h_code}" + for authority, code, h_authority, h_code in rows + } + + +@functools.cache +def _registered_heights() -> dict[str, str]: + """Vertical part of each registered compound CRS, both as "AUTHORITY:CODE".""" + rows = ( + _query_proj_database( + "SELECT auth_name, code, vertical_crs_auth_name, vertical_crs_code FROM compound_crs", + (), + ) + or [] + ) + return { + f"{authority}:{code}": f"{v_authority}:{v_code}" + for authority, code, v_authority, v_code in rows + } + + +@functools.cache +def _geographic_3d() -> frozenset[str]: + rows = ( + _query_proj_database( + "SELECT auth_name, code FROM geodetic_crs WHERE type = 'geographic 3D'", () + ) + or [] + ) + return frozenset(f"{authority}:{code}" for authority, code in rows) + + +# Geographic 3D CRS carry heights above the ellipsoid, without a vertical CRS +ELLIPSOIDAL_HEIGHTS = "ellipsoidal" + + +def heights_datum(info: og_geosciences.GeographicCoordinateSystemInfo) -> str | None: + """What the heights of a CRS are measured from, None when it does not say.""" + if "+" in info.code: + return f"{info.authority}:{info.code.split('+', 1)[1]}" + key = info.authority_code() + if key in _registered_heights(): + return _registered_heights()[key] + if key in _geographic_3d(): + return ELLIPSOIDAL_HEIGHTS + return None + + +@functools.cache +def _vertical_name(authority: str, code: str) -> str | None: + rows = _query_proj_database( + "SELECT name FROM vertical_crs WHERE auth_name = ? AND code = ?", (authority, code) + ) + return str(rows[0][0]) if rows else None + + +# PROJ only reads "AUTHORITY:A+B" codes for EPSG: another authority could not be converted +COMPOUND_AUTHORITY = "EPSG" + + +def horizontal_code(code: str) -> str: + """The X/Y part of a compound "A+B" code, the code itself otherwise.""" + return code.split("+", 1)[0] + + +def resolve_geographic_info( + is_3d: bool, # noqa: FBT001 positional like geographic_coordinate_systems + authority: str, + code: str, +) -> og_geosciences.GeographicCoordinateSystemInfo | None: + """The CRS for authority:code, None when it is not known. + + "A+B" composes a listed CRS without heights (A) with a vertical CRS (B): PROJ crashes on an + unknown CRS, so each part is checked first. A 2D data has no heights: it gets A. + """ + listed = geographic_coordinate_systems(is_3d) + if "+" not in code: + return listed.get(f"{authority}:{code}") + parts = code.split("+") + compound_part_count = 2 + if authority != COMPOUND_AUTHORITY or len(parts) != compound_part_count or not all(parts): + return None + horizontal, vertical = parts + horizontal_info = listed.get(f"{authority}:{horizontal}") + vertical_name = _vertical_name(authority, vertical) + if ( + horizontal_info is None + or vertical_name is None + or f"{authority}:{horizontal}" not in compoundable_coordinate_systems() + ): + return None + if not is_3d: + return horizontal_info + return og_geosciences.GeographicCoordinateSystemInfo( + authority, code, f"{horizontal_info.name} + {vertical_name}" + ) + + def _overlaps( latitudes: tuple[float, float], longitudes: tuple[float, float], @@ -237,7 +378,8 @@ def coordinates_implausible( abs(value) <= MAX_LONGITUDE for value in longitudes ): return True - areas = area_of_use(info.authority, info.code) + # Heights do not place the data: only the X/Y part has an area of use + areas = area_of_use(info.authority, horizontal_code(info.code)) if not areas: return False latitude_range = (min(latitudes), max(latitudes)) diff --git a/src/opengeodeweb_back/routes/basemap/blueprint_basemap.py b/src/opengeodeweb_back/routes/basemap/blueprint_basemap.py index 064904ea..e7a70d7c 100644 --- a/src/opengeodeweb_back/routes/basemap/blueprint_basemap.py +++ b/src/opengeodeweb_back/routes/basemap/blueprint_basemap.py @@ -13,7 +13,7 @@ # Local application imports from opengeodeweb_back import geode_functions, utils_functions from opengeodeweb_back.basemap import basemap_mesh, basemap_providers, basemap_tiles -from opengeodeweb_back.crs.crs_functions import geographic_coordinate_systems +from opengeodeweb_back.crs.crs_functions import resolve_geographic_info from opengeodeweb_back.routes.basemap import schemas from opengeodeweb_back.typed_route import typed_route @@ -52,7 +52,7 @@ def padded(bounds: tuple[float, float, float, float]) -> tuple[float, float, flo def _crs(params: CRS) -> og_geosciences.GeographicCoordinateSystemInfo: key = f"{params.authority}:{params.code}" # The basemap is a 3D mesh: only list the CRS a 3D object accepts - crs = geographic_coordinate_systems(True).get(key) # noqa: FBT003 + crs = resolve_geographic_info(True, params.authority, params.code) # noqa: FBT003 if crs is None: flask.abort(400, f"Unknown CRS {key}") return crs diff --git a/src/opengeodeweb_back/routes/crs/blueprint_crs.py b/src/opengeodeweb_back/routes/crs/blueprint_crs.py index 275b41f5..48da10e9 100644 --- a/src/opengeodeweb_back/routes/crs/blueprint_crs.py +++ b/src/opengeodeweb_back/routes/crs/blueprint_crs.py @@ -13,11 +13,14 @@ from opengeodeweb_back.crs.crs_functions import ( CRS_GEODE_OBJECTS, CrsError, + compoundable_coordinate_systems, geographic_coordinate_systems, geographic_info, + horizontal_parts, known_info, linked_objects, load_crs_object, + vertical_coordinate_system_list, ) from opengeodeweb_back.routes.crs import schemas from opengeodeweb_back.schema_types import CRS @@ -59,11 +62,27 @@ def _saved_response(data_id: str, data: Data, geode_object: CrsGeodeObject) -> d @typed_route(routes, schemas.geographic_list_route) def geographic_list(params: schemas.GeographicList) -> schemas.GeographicListResponse: geode_object = geode_functions.geode_object_from_string(params.geode_object_type) - crs_list = [ - CRS(name=info.name, code=info.code, authority=info.authority) - for info in geographic_coordinate_systems(geode_object.is_3d()).values() - ] - return schemas.GeographicListResponse(crs_list=crs_list) + listed = geographic_coordinate_systems(geode_object.is_3d()) + # Sent for every dimension: the front keeps one list for all its dialogs, and the back + # Ignores the heights of a 2D data + return schemas.GeographicListResponse.from_dict( + { + "crs_list": [ + {"authority": info.authority, "code": info.code, "name": info.name} + for info in listed.values() + ], + "vertical_list": [ + {"authority": authority, "code": code, "name": name} + for authority, code, name in vertical_coordinate_system_list() + ], + "compoundable": sorted(compoundable_coordinate_systems().intersection(listed)), + "horizontal_parts": { + compound: horizontal + for compound, horizontal in horizontal_parts().items() + if compound in listed + }, + } + ) @typed_route(routes, schemas.active_route) @@ -105,13 +124,25 @@ def convert_geographic(params: schemas.ConvertGeographic) -> schemas.ConvertGeog data, geode_object = load_crs_object(params.id) linked = linked_objects(params.id, params.linked_ids) # Every data is converted in memory before any file is written - crs_assignment.convert(geode_object, params.authority, params.code) - for _, _, linked_object in linked: - crs_assignment.convert(linked_object, params.authority, params.code) - response = _saved_response(params.id, data, geode_object) + unchanged: set[str] = set() + for data_id, converted_object in [ + (params.id, geode_object), + *((linked_id, linked_object) for linked_id, _, linked_object in linked), + ]: + if crs_assignment.convert(converted_object, params.authority, params.code): + unchanged.add(data_id) + + def converted(data_id: str, data: Data, converted_object: CrsGeodeObject) -> dict[str, Any]: + entry = _saved_response(data_id, data, converted_object) + # Only said when true: the front warns that these heights kept their values + if data_id in unchanged: + entry["heights_unchanged"] = True + return entry + + response = converted(params.id, data, geode_object) if linked: response["linked"] = [ - {"id": linked_id, **_saved_response(linked_id, linked_data, linked_object)} + {"id": linked_id, **converted(linked_id, linked_data, linked_object)} for linked_id, linked_data, linked_object in linked ] return schemas.ConvertGeographicResponse.from_dict(response) diff --git a/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.json b/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.json index 262a6f30..a8f2aadd 100644 --- a/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.json +++ b/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.json @@ -57,6 +57,9 @@ }, "binary_light_viewable": { "type": "string" + }, + "heights_unchanged": { + "type": "boolean" } }, "required": [ @@ -64,6 +67,9 @@ ], "additionalProperties": false } + }, + "heights_unchanged": { + "type": "boolean" } }, "required": [], diff --git a/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.py b/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.py index 465c3446..bb7d3142 100644 --- a/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.py +++ b/src/opengeodeweb_back/routes/crs/schemas/convert_geographic.py @@ -48,6 +48,7 @@ def __post_init__(self) -> None: id: DataId binary_light_viewable: Optional[str] = None crs: Optional[LinkedCRS] = None + heights_unchanged: Optional[bool] = None @dataclass @@ -57,6 +58,7 @@ def __post_init__(self) -> None: binary_light_viewable: Optional[str] = None crs: Optional[ConvertGeographicResponseCRS] = None + heights_unchanged: Optional[bool] = None linked: Optional[List[Linked]] = None diff --git a/src/opengeodeweb_back/routes/crs/schemas/geographic_list.json b/src/opengeodeweb_back/routes/crs/schemas/geographic_list.json index e9b72504..f1400724 100644 --- a/src/opengeodeweb_back/routes/crs/schemas/geographic_list.json +++ b/src/opengeodeweb_back/routes/crs/schemas/geographic_list.json @@ -21,10 +21,31 @@ "items": { "title": "CRS" } + }, + "vertical_list": { + "type": "array", + "items": { + "title": "CRS" + } + }, + "compoundable": { + "type": "array", + "items": { + "type": "string" + } + }, + "horizontal_parts": { + "type": "object", + "additionalProperties": { + "type": "string" + } } }, "required": [ - "crs_list" + "crs_list", + "vertical_list", + "compoundable", + "horizontal_parts" ], "additionalProperties": false } diff --git a/src/opengeodeweb_back/routes/crs/schemas/geographic_list.py b/src/opengeodeweb_back/routes/crs/schemas/geographic_list.py index e3af1b35..ea00d1fe 100644 --- a/src/opengeodeweb_back/routes/crs/schemas/geographic_list.py +++ b/src/opengeodeweb_back/routes/crs/schemas/geographic_list.py @@ -1,8 +1,7 @@ from opengeodeweb_microservice.database.data_types import GeodeObjectType -from opengeodeweb_back.schema_types import CRS from pathlib import Path from opengeodeweb_microservice.schemas import Route, load_schema -from typing import List +from typing import List, Dict from dataclasses_json import DataClassJsonMixin from opengeodeweb_microservice.schemas import print_dataclass from dataclasses import dataclass @@ -16,12 +15,35 @@ def __post_init__(self) -> None: geode_object_type: GeodeObjectType +@dataclass +class CRSListElement(DataClassJsonMixin): + def __post_init__(self) -> None: + print_dataclass(self) + + authority: str + code: str + name: str + + +@dataclass +class VerticalListElement(DataClassJsonMixin): + def __post_init__(self) -> None: + print_dataclass(self) + + authority: str + code: str + name: str + + @dataclass class GeographicListResponse(DataClassJsonMixin): def __post_init__(self) -> None: print_dataclass(self) - crs_list: List[CRS] + compoundable: List[str] + crs_list: List[CRSListElement] + horizontal_parts: Dict[str, str] + vertical_list: List[VerticalListElement] geographic_list_route = Route( diff --git a/tests/test_basemap.py b/tests/test_basemap.py index dc2ad4b6..80498a20 100644 --- a/tests/test_basemap.py +++ b/tests/test_basemap.py @@ -198,6 +198,18 @@ def test_bounds_to_3857_paris() -> None: assert 6_200_000 < y_min < y_max < 6_300_000 +def test_bounds_to_3857_north_east_crs() -> None: + # EPSG:2193 declares its axes north, east: x/y must still be read as east, north + nztm = og_geosciences.GeographicCoordinateSystemInfo( + "EPSG", "2193", "NZGD2000 / New Zealand Transverse Mercator 2000" + ) + pukekohe = (1_751_000.0, 5_874_000.0, 1_781_000.0, 5_900_000.0) + x_min, y_min, x_max, y_max = basemap_mesh.bounds_to_3857(pukekohe, nztm) + # Pukekohe is around 174.9 E, 37.2 S: x ~ 19 470 km, y ~ -4 460 km in Web Mercator + assert 19_400_000 < x_min < x_max < 19_500_000 + assert -4_500_000 < y_min < y_max < -4_420_000 + + def test_bounds_already_in_web_mercator() -> None: bounds = (260_000.0, 6_250_000.0, 265_000.0, 6_255_000.0) assert basemap_mesh.bounds_to_3857(bounds, basemap_mesh.WEB_MERCATOR) == bounds diff --git a/tests/test_crs_functions.py b/tests/test_crs_functions.py index d02f1822..4c77db52 100644 --- a/tests/test_crs_functions.py +++ b/tests/test_crs_functions.py @@ -15,3 +15,12 @@ def test_convert_xy_corners_to_wgs84_is_longitude_then_latitude() -> None: corners = crs_functions.convert_xy_corners(bounds, LAMBERT, crs_functions.WGS84) # Paris, around 2.3 E, 48.9 N assert corners[0] == pytest.approx((2.3321836844072203, 48.856172858823854)) + + +def test_resolve_compound_crs_for_the_basemap() -> None: + # The basemap is a 3D mesh: a compound CRS resolves like for any 3D data + info = crs_functions.resolve_geographic_info(True, "EPSG", "2193+7839") # noqa: FBT003 + assert info is not None + assert info.authority_code() == "EPSG:2193+7839" + assert crs_functions.resolve_geographic_info(False, "EPSG", "2193+7839").code == "2193" # noqa: FBT003 + assert crs_functions.resolve_geographic_info(True, "EPSG", "2193+9999") is None # noqa: FBT003 diff --git a/tests/test_crs_routes.py b/tests/test_crs_routes.py index a330712d..0019c6df 100644 --- a/tests/test_crs_routes.py +++ b/tests/test_crs_routes.py @@ -40,6 +40,15 @@ def get_full_data() -> test_utils.JsonData: assert type(crs_list) is list for crs in crs_list: assert type(crs) is dict + # What the CRS selector needs to compose heights, and to compare compound CRS + body = response.get_json() + assert {"authority": "EPSG", "code": "7839", "name": "NZVD2016 height"} in body["vertical_list"] + assert "EPSG:2193" in body["compoundable"] + assert "EPSG:9528" not in body["compoundable"] + assert body["horizontal_parts"]["EPSG:5698"] == "EPSG:2154" + # Only EPSG pairs can be composed + assert all(code.startswith("EPSG:") for code in body["compoundable"]) + assert all(crs["authority"] == "EPSG" for crs in body["vertical_list"]) # Test all params test_utils.test_route_wrong_params(client, route, get_full_data) @@ -130,6 +139,8 @@ def get_full_data() -> test_utils.JsonData: # The front rebuilds its local actor from the new light viewable assert type(response.get_json()["binary_light_viewable"]) is str assert response.get_json()["crs"] == UTM + # Neither CRS has heights: nothing to report + assert "heights_unchanged" not in response.get_json() response = client.post(active_route, json={"id": point_set_id}) assert response.get_json() == {"crs_name": "EPSG:32631", "crs_info": UTM} assert _first_point(client, point_set_id) != lambert_point @@ -574,6 +585,73 @@ def test_vertical_crs_not_offered(client: FlaskClient) -> None: assert response.status_code == 400 +NZTM_NZVD = { + "authority": "EPSG", + "code": "2193+7839", + "name": "NZGD2000 / New Zealand Transverse Mercator 2000 + NZVD2016 height", +} + + +def test_assign_compound_crs(client: FlaskClient) -> None: + route = "/opengeodeweb_back/crs/assign_geographic" + # Pukekohe model centre: NZTM metres, NZVD2016 heights + point_set_id = _create_point_set(client, [{"x": 1765750, "y": 5887250, "z": 100}]) + response = client.post(route, json={"id": point_set_id, **NZTM_NZVD}) + assert response.status_code == 200 + assert response.get_json()["crs"] == NZTM_NZVD + assert response.get_json()["implausible"] is False + # A 2D data has no heights: it takes the horizontal part + [point_set_2d] = test_utils.check_save_viewable_file(client, "PointSet2D", "test.og_pts2d") + response = client.post(route, json={"id": point_set_2d["id"], **NZTM_NZVD}) + assert response.get_json()["crs"]["code"] == "2193" + # Already in it: assigning or converting to the compound again changes nothing + response = client.post(route, json={"id": point_set_2d["id"], **NZTM_NZVD}) + assert response.status_code == 200 + assert response.get_json()["crs"]["code"] == "2193" + response = client.post( + "/opengeodeweb_back/crs/convert_geographic", json={"id": point_set_2d["id"], **NZTM_NZVD} + ) + assert response.status_code == 200 + assert response.get_json()["crs"]["code"] == "2193" + + +def test_convert_reports_heights_unchanged(client: FlaskClient) -> None: + assign_route = "/opengeodeweb_back/crs/assign_geographic" + convert_route = "/opengeodeweb_back/crs/convert_geographic" + point_set_id = _create_point_set(client, [{"x": 1765750, "y": 5887250, "z": 100}]) + client.post(assign_route, json={"id": point_set_id, **NZTM_NZVD}) + nztm = { + "authority": "EPSG", + "code": "2193", + "name": "NZGD2000 / New Zealand Transverse Mercator 2000", + } + # Same X/Y, the NZVD2016 heights lose their datum: PROJ leaves them as they are + response = client.post(convert_route, json={"id": point_set_id, **nztm}) + assert response.status_code == 200 + assert response.get_json()["heights_unchanged"] is True + # Back to the compound: the source heights had no datum, nothing to report + response = client.post(convert_route, json={"id": point_set_id, **NZTM_NZVD}) + assert response.status_code == 200 + assert "heights_unchanged" not in response.get_json() + + +def test_assign_invalid_compound_crs(client: FlaskClient) -> None: + route = "/opengeodeweb_back/crs/assign_geographic" + point_set_id = _create_point_set(client) + # Unknown vertical, horizontal part already with heights, malformed, parts swapped + for code in ("2193+9999", "9528+7839", "2193+", "+7839", "2193+7839+5720", "7839+2193"): + response = client.post( + route, json={"id": point_set_id, "authority": "EPSG", "code": code, "name": "x"} + ) + assert response.status_code == 400, code + # PROJ only reads compound codes of EPSG: an ESRI pair could never be converted afterwards + response = client.post( + route, + json={"id": point_set_id, "authority": "ESRI", "code": "103699+115876", "name": "x"}, + ) + assert response.status_code == 400 + + def test_assign_only_rewrites_the_native_file(client: FlaskClient) -> None: [point_set] = test_utils.check_save_viewable_file(client, "PointSet3D", "test.og_pts3d") point_set_id = point_set["id"] @@ -605,6 +683,17 @@ def test_proj_finds_its_database() -> None: assert (Path(os.environ["PROJ_DATA"]) / "proj.db").is_file() +def test_assign_crs_without_area_of_use(client: FlaskClient) -> None: + # proj.db gives some CRS an extent without bounds: the check must not fail on them + sad69 = {"authority": "EPSG", "code": "29118", "name": "SAD69 / UTM zone 18N"} + point_set_id = _create_point_set(client, [{"x": 500000, "y": 100000, "z": 0}]) + response = client.post( + "/opengeodeweb_back/crs/assign_geographic", json={"id": point_set_id, **sad69} + ) + assert response.status_code == 200 + assert response.get_json()["crs"] == sad69 + + def test_assign_geographic_plausibility(client: FlaskClient) -> None: route = "/opengeodeweb_back/crs/assign_geographic" for point, implausible in (