Skip to content
Closed
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
50 changes: 49 additions & 1 deletion opengeodeweb_back_schemas.json
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -1518,13 +1560,19 @@
},
"binary_light_viewable": {
"type": "string"
},
"heights_unchanged": {
"type": "boolean"
}
},
"required": [
"id"
],
"additionalProperties": false
}
},
"heights_unchanged": {
"type": "boolean"
}
},
"required": [],
Expand Down
7 changes: 6 additions & 1 deletion opengeodeweb_back_typed_schemas.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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;
}

Expand Down
44 changes: 42 additions & 2 deletions src/opengeodeweb_back/crs/crs_assignment.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
coordinate_system,
coordinates_implausible,
geographic_info,
heights_datum,
known_info,
)

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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
148 changes: 145 additions & 3 deletions src/opengeodeweb_back/crs/crs_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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
Expand All @@ -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],
Expand Down Expand Up @@ -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))
Expand Down
4 changes: 2 additions & 2 deletions src/opengeodeweb_back/routes/basemap/blueprint_basemap.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
Loading
Loading