Skip to content

Coordinate models and values using concepts from comp-rob2b and ones introduced for use by the SECORO group.

Classes:

Functions:

CoordPolicyProtocol

Bases: Protocol

Choose one coordinate among a relation's candidates; context travels in **kwargs.

IFrameRelationCoord

IFrameRelationCoord(coord_id, relation, graph)

Bases: ModelBase

Model object for a PoseCoordinate or OrientationCoordinate

Attributes:

  • relation (IFrameRelationModel) –

    geometric relation described by the coordinate

  • as_seen_by (FrameModel) –

    frame from which the coordinate is observed

Parameters:

  • coord_id (URIRef) –

    URI of the coordinate node in the graph

  • relation (IFrameRelationModel) –

    geometric relation model, e.g. Pose or Orientation

  • graph (Graph) –

    RDF graph for loading attributes

Source code in src/rdf_utils/models/geom_coord.py
125
126
127
128
129
130
131
132
133
134
135
def __init__(self, coord_id: URIRef, relation: IFrameRelationModel, graph: Graph) -> None:
    super().__init__(node_id=coord_id, graph=graph)
    self.relation = relation

    seen_by_id = graph.value(subject=self.id, predicate=URI_GEOM_PRED_SEEN_BY)
    if not isinstance(seen_by_id, URIRef):
        raise ConstraintViolation(
            "geometry",
            f"Coordinate '{self.id}' does not link to a URI via 'as-seen-by': {seen_by_id}",
        )
    self.as_seen_by = FrameModel(frame_id=seen_by_id, graph=graph)

OrientCoordModel

OrientCoordModel(coord_id, graph, orientation=None)

Bases: IFrameRelationCoord

Model object for an OrientationCoordinate.

Parameters:

  • coord_id (URIRef) –

    URI of the OrientationCoordinate in the graph

  • graph (Graph) –

    RDF graph for loading attributes

  • orientation (OrientationModel | None, default: None ) –

    optional preloaded Orientation relation; must match the coordinate's of-orientation URI

Source code in src/rdf_utils/models/geom_coord.py
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
def __init__(
    self, coord_id: URIRef, graph: Graph, orientation: OrientationModel | None = None
) -> None:
    orient_id = graph.value(subject=coord_id, predicate=URI_GEOM_PRED_OF_ORIENT)
    if not isinstance(orient_id, URIRef):
        raise ConstraintViolation(
            "geometry",
            f"OrientationCoordinate '{coord_id}' does not link to a URI via 'of-orientation': {orient_id}",
        )
    if orientation is None:
        orientation = OrientationModel(orn_id=orient_id, graph=graph)
    elif orientation.id != orient_id:
        raise ConstraintViolation(
            "geometry",
            f"OrientationCoordinate '{coord_id}' receives orientation arg ({orientation}) with mismatching "
            f"'of-orientation' URI: {orient_id} != {orientation.id}",
        )

    super().__init__(coord_id=coord_id, relation=orientation, graph=graph)

    if URI_GEOM_TYPE_ORIENT_COORD not in self.types:
        raise TypeError(f"'{self.id}' is not an OrientationCoordinate")
    if URI_GEOM_TYPE_ORIENT_REF not in self.types:
        raise TypeError(f"'{self.id}' is not an OrientationReference")

PoseCoordModel

PoseCoordModel(coord_id, graph, pose=None, *, coord_policy=None)

Bases: IFrameRelationCoord

Model object for a PoseCoordinate.

The position and orientation components may be supplied directly by a combined coordinate node or resolved from the Pose's referenced Position and Orientation. Each resolved relation must have exactly one coordinate, unless a coord_policy is given to pick among several. Direct transformation-matrix representations are not currently supported; they may be added as an alternative to component-coordinate resolution.

Attributes:

Parameters:

  • coord_id (URIRef) –

    URI of the PoseCoordinate in the graph

  • graph (Graph) –

    RDF graph for loading attributes

  • pose (PoseModel | None, default: None ) –

    optional preloaded Pose relation; must match the coordinate's of-pose URI

  • coord_policy (CoordPolicyProtocol | None, default: None ) –

    picks one Position/Orientation coordinate when the relation has several

Source code in src/rdf_utils/models/geom_coord.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
def __init__(
    self,
    coord_id: URIRef,
    graph: Graph,
    pose: PoseModel | None = None,
    *,
    coord_policy: CoordPolicyProtocol | None = None,
) -> None:
    pose_id = graph.value(subject=coord_id, predicate=URI_GEOM_PRED_OF_POSE)
    if not isinstance(pose_id, URIRef):
        raise ConstraintViolation(
            "geometry",
            f"PoseCoordinate '{coord_id}' does not link to a URI via 'of-pose': {pose_id}",
        )
    if pose is None:
        pose = PoseModel(pose_id=pose_id, graph=graph)
    elif pose_id != pose.id:
        raise ConstraintViolation(
            "geometry",
            f"PoseCoordinate '{coord_id}' receives pose arg ({pose}) with mismatching "
            f"'of-pose' URI: {pose_id} != {pose.id}",
        )

    super().__init__(coord_id=coord_id, relation=pose, graph=graph)

    if URI_GEOM_TYPE_POSE_COORD not in self.types:
        raise TypeError(f"'{self.id}' is not a PoseCoordinate")
    if URI_GEOM_TYPE_POSE_REF not in self.types:
        raise TypeError(f"'{self.id}' is not a PoseReference")

    coordinate_types = self.types & {
        URI_GEOM_TYPE_POSE_COORD,
        URI_GEOM_TYPE_POSITION_COORD,
        URI_GEOM_TYPE_ORIENT_COORD,
    }
    if URI_GEOM_TYPE_POSITION_COORD in coordinate_types:
        if pose.position is None:
            raise ConstraintViolation(
                "geometry",
                f"PoseCoordinate {self.id} is a PositionCoordinate but does not link to a Position",
            )
        if self.id not in pose.position.coordinate_ids:
            raise ConstraintViolation(
                "geometry",
                f"PoseCoordinate {self.id} is a PositionCoordinate but does not reference "
                f"Position {pose.position.id}: {pose.position.coordinate_ids}",
            )
        position_coord_id = self.id
    else:
        position_coord_id = (
            None
            if pose.position is None
            else select_coordinate(
                pose.position, graph, coord_policy, coord_id=self.id, component="position"
            )
        )
        if position_coord_id is None:
            raise ConstraintViolation(
                "geometry",
                f"PoseCoordinate {self.id} is not a Position Coord and "
                f"does not link to a valid coord for Position {pose.position}",
            )

    if URI_GEOM_TYPE_ORIENT_COORD in coordinate_types:
        if pose.orientation is None:
            raise ConstraintViolation(
                "geometry",
                f"PoseCoordinate {self.id} is an OrientationCoordinate but does not link to an Orientation",
            )
        if self.id not in pose.orientation.coordinate_ids:
            raise ConstraintViolation(
                "geometry",
                f"PoseCoordinate {self.id} is an OrientationCoordinate but does not reference "
                f"Orientation {pose.orientation.id}: {pose.orientation.coordinate_ids}",
            )
        orientation_coord_id = self.id
    else:
        orientation_coord_id = (
            None
            if pose.orientation is None
            else select_coordinate(
                pose.orientation, graph, coord_policy, coord_id=self.id, component="orientation"
            )
        )
        if orientation_coord_id is None:
            raise ConstraintViolation(
                "geometry",
                f"PoseCoordinate {self.id} is not an Orientation Coord and "
                f"does not link to a valid coord for Orientation {pose.orientation}",
            )

    self.position_coord = PositionCoordModel(position_coord_id, graph, position=pose.position)
    self.orientation_coord = OrientCoordModel(
        coord_id=orientation_coord_id, graph=graph, orientation=pose.orientation
    )

PositionCoordModel

PositionCoordModel(coord_id, graph, position=None)

Bases: ModelBase

Model object for a PositionCoordinate.

Attributes:

  • position (PositionModel) –

    Position relation to which the coordinate supplies values

  • as_seen_by (URIRef) –

    URI of the coordinate's reference frame

  • unit (URIRef) –

    supported QUDT length unit used by the coordinate values

Parameters:

  • coord_id (URIRef) –

    URI of the PositionCoordinate in the graph

  • graph (Graph) –

    RDF graph for loading attributes

  • position (PositionModel | None, default: None ) –

    optional preloaded Position relation; must match the coordinate's of-position URI

Source code in src/rdf_utils/models/geom_coord.py
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
def __init__(
    self, coord_id: URIRef, graph: Graph, position: PositionModel | None = None
) -> None:
    super().__init__(node_id=coord_id, graph=graph)

    if URI_GEOM_TYPE_POSITION_COORD not in self.types:
        raise TypeError(f"'{self.id}' is not a PositionCoordinate")

    seen_by_id = graph.value(subject=self.id, predicate=URI_GEOM_PRED_SEEN_BY)
    if not isinstance(seen_by_id, URIRef):
        raise ConstraintViolation(
            "geometry",
            f"PositionCoordinate '{self.id}' does not link to a URI via 'as-seen-by': {seen_by_id}",
        )
    self.as_seen_by = seen_by_id

    if URI_GEOM_TYPE_POSITION_REF not in self.types:
        raise TypeError(f"'{self.id}' is not a PositionReference")

    position_id = graph.value(subject=self.id, predicate=URI_GEOM_PRED_OF_POSITION)
    if not isinstance(position_id, URIRef):
        raise ConstraintViolation(
            "geometry",
            f"PositionCoordinate '{self.id}' does not link to a URI via 'of-position': {position_id}",
        )

    if position is None:
        position = PositionModel(position_id=position_id, graph=graph)
    elif position.id != position_id:
        raise ConstraintViolation(
            "geometry",
            f"PositionCoordinate '{coord_id}' receives position arg ({position}) with mismatching "
            f"'of-position' URI: {position_id} != {position.id}",
        )
    self.position = position

    units = LENGTH_UNITS.intersection(graph.objects(self.id, URI_QUDT_PRED_UNIT))
    if len(units) != 1:
        raise ConstraintViolation(
            "geometry",
            f"PositionCoordinate {self.id} must have one supported length unit, found {units}",
        )
    unit = next(iter(units))
    self.unit = unit

get_coord_vectorxyz

get_coord_vectorxyz(coord_model, graph)

Extract coordinates for a VectorXYZ model.

Parameters:

  • coord_model (ModelBase) –

    coordinate model object

  • graph (Graph) –

    RDF graph to look for coordinate attributes

Returns:

  • tuple[float, float, float] | None –

    tuple containing (x, y, z) coordinates, or None when no values are present

Source code in src/rdf_utils/models/geom_coord.py
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
def get_coord_vectorxyz(coord_model: ModelBase, graph: Graph) -> tuple[float, float, float] | None:
    """Extract coordinates for a VectorXYZ model.

    Parameters:
        coord_model: coordinate model object
        graph: RDF graph to look for coordinate attributes

    Returns:
        tuple containing (x, y, z) coordinates, or None when no values are present
    """
    if URI_GEOM_TYPE_VECTOR_XYZ not in coord_model.types:
        raise ValueError(f"Coordinate '{coord_model.id}' is not of type 'VectorXYZ'")

    values: list[float] = []
    for predicate in (URI_GEOM_PRED_X, URI_GEOM_PRED_Y, URI_GEOM_PRED_Z):
        nodes = list(graph.objects(coord_model.id, predicate))
        if not nodes:
            continue
        if len(nodes) != 1 or not isinstance(nodes[0], Literal):
            raise ConstraintViolation(
                "geometry",
                f"Coordinate {coord_model.id} must have zero or one float literal for "
                f"{predicate}, found: {nodes}",
            )
        value = nodes[0].toPython()
        if not isinstance(value, float) or not np.isfinite(value):
            raise ConstraintViolation(
                "geometry",
                f"Coordinate {coord_model.id} must have one finite float for {predicate}, "
                f"found: {value}",
            )
        values.append(value)

    if not values:
        return None
    if len(values) != 3:
        raise ConstraintViolation(
            "geometry", f"Coordinate {coord_model.id} does not have 3 XYZ values: {values}"
        )
    return (values[0], values[1], values[2])

get_direction_cosine_matrix

get_direction_cosine_matrix(coord_model, graph)

Extract a DirectionCosineXYZ matrix from a graph.

Parameters:

  • coord_model (IFrameRelationCoord) –

    pose or orientation coordinate model

  • graph (Graph) –

    RDF graph to look for coordinate attributes

Returns:

  • ndarray | None –

    3x3 direction-cosine matrix, or None when no values are present

Source code in src/rdf_utils/models/geom_coord.py
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
def get_direction_cosine_matrix(
    coord_model: IFrameRelationCoord, graph: Graph
) -> np.ndarray | None:
    """Extract a DirectionCosineXYZ matrix from a graph.

    Parameters:
        coord_model: pose or orientation coordinate model
        graph: RDF graph to look for coordinate attributes

    Returns:
        3x3 direction-cosine matrix, or None when no values are present
    """
    if URI_GEOM_TYPE_DIRECTION_COSINE_XYZ not in coord_model.types:
        raise ValueError(f"Coordinate '{coord_model.id}' is not a DirectionCosineXYZ")

    rows = []
    for pred in (
        URI_GEOM_PRED_DIRECTION_COSINE_X,
        URI_GEOM_PRED_DIRECTION_COSINE_Y,
        URI_GEOM_PRED_DIRECTION_COSINE_Z,
    ):
        row_nodes = list(graph.objects(coord_model.id, pred))
        if not row_nodes:
            # allow no value
            continue

        if len(row_nodes) != 1 or not isinstance(row_nodes[0], BNode):
            raise ConstraintViolation(
                "geometry",
                f"Coordinate {coord_model.id} must have one RDF list for {pred}",
            )
        try:
            row = np.asarray(load_list_re(graph, row_nodes[0], parse_uri=False), dtype=float)
        except (TypeError, ValueError, RuntimeError) as error:
            raise ConstraintViolation(
                "geometry", f"Coordinate {coord_model.id} has invalid values for {pred}"
            ) from error
        if row.shape != (3,) or not np.isfinite(row).all():
            raise ConstraintViolation(
                "geometry",
                f"Coordinate {coord_model.id} must have three finite values for {pred}",
            )
        rows.append(row)

    if not rows:
        return None

    if len(rows) != 3:
        raise ConstraintViolation(
            "geometry",
            f"Coordinate {coord_model.id} does not have 3 direction cosines, found: {len(rows)}",
        )

    matrix = np.asarray(rows)
    if not np.allclose(matrix @ matrix.T, np.eye(3)):
        raise ConstraintViolation(
            "geometry", f"Coordinate {coord_model.id} must be an orthogonal matrix"
        )
    return matrix

get_euler_angles_abg

get_euler_angles_abg(coord_model, graph)

Extract coordinates for an AnglesAlphaBetaGamma model.

Parameters:

  • coord_model (IFrameRelationCoord) –

    coordinate model object, either PoseCoordModel or OrientCoordModel

  • graph (Graph) –

    RDF graph to look for coordinate attributes

Returns:

Source code in src/rdf_utils/models/geom_coord.py
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
def get_euler_angles_abg(
    coord_model: IFrameRelationCoord, graph: Graph
) -> tuple[str, bool, URIRef, tuple[float, float, float]] | None:
    """Extract coordinates for an AnglesAlphaBetaGamma model.

    Parameters:
        coord_model: coordinate model object, either PoseCoordModel or OrientCoordModel
        graph: RDF graph to look for coordinate attributes

    Returns:
        A tuple containing the Euler axes sequence, whether the rotation is
        intrinsic, the angle unit, and the three angle values; or None when
        no angle values are present.
    """
    if URI_GEOM_TYPE_ANGLES_ABG not in coord_model.types:
        raise ValueError(f"Coordinate '{coord_model.id}' is not an AnglesAlphaBetaGamma")

    seq, is_intrinsic = get_euler_angles_params(coord_model=coord_model, graph=graph)

    angles = []
    for predicate in (URI_GEOM_PRED_ALPHA, URI_GEOM_PRED_BETA, URI_GEOM_PRED_GAMMA):
        nodes = list(graph.objects(coord_model.id, predicate))
        if not nodes:
            continue

        if len(nodes) != 1:
            raise ConstraintViolation(
                "geometry",
                f"Euler Coordinate {coord_model.id} must have zero or one value for {predicate}, found {nodes}",
            )

        if not isinstance(nodes[0], Literal):
            raise ConstraintViolation(
                "geometry",
                f"Coordinate {coord_model.id} must have one finite float for {predicate}, found: {nodes[0]}",
            )
        value = nodes[0].toPython()
        if not isinstance(value, float) or not np.isfinite(value):
            raise ConstraintViolation(
                "geometry",
                f"Coordinate {coord_model.id} must have one finite float for {predicate}, found: {value}",
            )
        angles.append(value)

    if not angles:
        return None

    if len(angles) != 3:
        # This implies one of the angles was skipped but not all
        raise ConstraintViolation(
            "geometry",
            f"Euler Coordinate {coord_model.id} expected 0 or 3 values for alpha/beta/gamma, found {angles}",
        )

    angle_units = set(graph.objects(coord_model.id, URI_QUDT_PRED_UNIT)) & {
        URI_QUDT_UNIT_DEG,
        URI_QUDT_UNIT_RAD,
    }
    if len(angle_units) != 1:
        raise ConstraintViolation(
            "geometry",
            f"Euler Coordinate '{coord_model.id}' must have one angle unit, found {angle_units}",
        )

    angle_unit = angle_units.pop()
    if not isinstance(angle_unit, URIRef):
        raise ConstraintViolation(
            "geometry", f"Euler Coordinate '{coord_model.id}' must have a URIRef angle unit"
        )

    return seq, is_intrinsic, angle_unit, (angles[0], angles[1], angles[2])

get_euler_angles_params

get_euler_angles_params(coord_model, graph)

Extract parameters for an EulerAngles model.

Parameters:

  • coord_model (IFrameRelationCoord) –

    coordinate model object, either PoseCoordModel or OrientCoordModel

  • graph (Graph) –

    RDF graph to look for coordinate attributes

Returns:

  • tuple[str, bool] –

    tuple containing axes sequence of the Euler angles and whether the rotation is intrinsic

Source code in src/rdf_utils/models/geom_coord.py
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
def get_euler_angles_params(coord_model: IFrameRelationCoord, graph: Graph) -> tuple[str, bool]:
    """Extract parameters for an EulerAngles model.

    Parameters:
        coord_model: coordinate model object, either PoseCoordModel or OrientCoordModel
        graph: RDF graph to look for coordinate attributes

    Returns:
        tuple containing axes sequence of the Euler angles and whether the rotation is intrinsic
    """
    if URI_GEOM_TYPE_EULER_ANGLES not in coord_model.types:
        raise ValueError(f"Coordinate '{coord_model.id}' is not an EulerAngles")

    if URI_GEOM_TYPE_INTRINSIC in coord_model.types:
        is_intrinsic = True
    elif URI_GEOM_TYPE_EXTRINSIC in coord_model.types:
        is_intrinsic = False
    else:
        raise ConstraintViolation(
            domain="geometry",
            message=f"EulerAngles coord '{coord_model.id}' does not have 'Intrinsic' or 'Extrinsic' type",
        )

    seq_node = graph.value(subject=coord_model.id, predicate=URI_GEOM_PRED_AXES_SEQ)
    if not isinstance(seq_node, Literal) or not isinstance(seq_node.value, str):
        raise ConstraintViolation(
            "geometry",
            f"Coordinate '{coord_model.id}' must have an 'axes-sequence' string: {seq_node}",
        )

    return seq_node.value, is_intrinsic

get_or_sample_coord_vectorxyz

get_or_sample_coord_vectorxyz(coord_model, graph, rng=None, materialize_sample=False)

Get or sample coordinates for a VectorXYZ model.

Explicit XYZ values take precedence. When they are absent, a SampledQuantity requires rng and a three-dimensional distribution.

Parameters:

  • coord_model (ModelBase) –

    coordinate model object

  • graph (Graph) –

    RDF graph containing the coordinate or distribution

  • rng (Generator | None, default: None ) –

    random generator required for a sampled coordinate

  • materialize_sample (bool, default: False ) –

    whether to write newly sampled values to the graph

Returns:

Source code in src/rdf_utils/models/geom_coord.py
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
def get_or_sample_coord_vectorxyz(
    coord_model: ModelBase,
    graph: Graph,
    rng: np.random.Generator | None = None,
    materialize_sample: bool = False,
) -> tuple[float, float, float]:
    """Get or sample coordinates for a VectorXYZ model.

    Explicit XYZ values take precedence. When they are absent, a
    SampledQuantity requires ``rng`` and a three-dimensional distribution.

    Parameters:
        coord_model: coordinate model object
        graph: RDF graph containing the coordinate or distribution
        rng: random generator required for a sampled coordinate
        materialize_sample: whether to write newly sampled values to the graph

    Returns:
        tuple containing (x, y, z) coordinates
    """
    values = get_coord_vectorxyz(coord_model, graph)
    if values is not None:
        return values

    if URI_DISTRIB_TYPE_SAMPLED_QUANTITY not in coord_model.types:
        raise ConstraintViolation("geometry", f"Coordinate {coord_model.id} has no XYZ values")

    if rng is None:
        raise ConstraintViolation(
            "geometry", f"Coordinate {coord_model.id} requires a random generator"
        )

    distribution = distrib_from_sampled_quantity(coord_model.id, graph)
    dimension = distribution.get_attr(URI_DISTRIB_PRED_DIM)
    if dimension != 3:
        raise ConstraintViolation(
            "geometry",
            f"Coordinate {coord_model.id} distribution must have dimension 3, found {dimension}",
        )

    sample = np.asarray(sample_from_distrib(distribution, rng=rng), dtype=float)
    if sample.shape != (3,):
        raise ConstraintViolation(
            "geometry",
            f"Coordinate {coord_model.id} sample must have shape (3,), found {sample.shape}",
        )

    values = (float(sample[0]), float(sample[1]), float(sample[2]))
    if materialize_sample:
        set_coord_vectorxyz(coord_model, values, graph)

    return values

get_or_sample_orientation_coord

get_or_sample_orientation_coord(coord_model, graph, rng=None, materialize_sample=False)

Get an explicit orientation or sample a UniformRotation distribution.

Explicit EulerAngles, DirectionCosineXYZ, or Quaternion values take precedence. When they are absent, a SampledQuantity requires rng and a UniformRotation distribution.

Parameters:

  • coord_model (IFrameRelationCoord) –

    pose or orientation coordinate model

  • graph (Graph) –

    RDF graph containing the coordinate or distribution

  • rng (Generator | None, default: None ) –

    random generator required for a sampled coordinate

  • materialize_sample (bool, default: False ) –

    whether to write the sampled rotation to the graph

Returns:

  • Rotation –

    explicit or sampled orientation as a SciPy Rotation

Source code in src/rdf_utils/models/geom_coord.py
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
def get_or_sample_orientation_coord(
    coord_model: IFrameRelationCoord,
    graph: Graph,
    rng: np.random.Generator | None = None,
    materialize_sample: bool = False,
) -> Rotation:
    """Get an explicit orientation or sample a UniformRotation distribution.

    Explicit EulerAngles, DirectionCosineXYZ, or Quaternion values take
    precedence. When they are absent, a SampledQuantity requires ``rng`` and
    a UniformRotation distribution.

    Parameters:
        coord_model: pose or orientation coordinate model
        graph: RDF graph containing the coordinate or distribution
        rng: random generator required for a sampled coordinate
        materialize_sample: whether to write the sampled rotation to the graph

    Returns:
        explicit or sampled orientation as a SciPy Rotation
    """
    rotation = get_orientation_coord_vals(coord_model, graph)
    if rotation is not None:
        return rotation

    if URI_DISTRIB_TYPE_SAMPLED_QUANTITY not in coord_model.types:
        raise ConstraintViolation(
            "geometry",
            f"Coordinate {coord_model.id} is not a SampledQuantity and has no orientation values",
        )

    if rng is None:
        raise ConstraintViolation(
            "geometry", f"Sampled coordinate {coord_model.id} requires a random generator"
        )

    distribution = distrib_from_sampled_quantity(coord_model.id, graph)
    if URI_DISTRIB_TYPE_UNIFORM_ROT not in distribution.types:
        raise ConstraintViolation(
            "geometry", f"Coordinate {coord_model.id} requires a UniformRotation distribution"
        )

    rotation = sample_from_distrib(distribution, rng=rng)
    if not isinstance(rotation, Rotation):
        raise ConstraintViolation(
            "geometry", f"Coordinate {coord_model.id} distribution did not return a Rotation"
        )

    if materialize_sample:
        set_orientation_coord(coord_model, rotation, graph)

    return rotation

get_orientation_coord_vals

get_orientation_coord_vals(coord_model, graph)

Parse orientation coordinate in a graph into a SciPy Rotation.

Handles and convert different orientation coordinate types into a SciPy Rotation

Parameters:

  • coord_model (IFrameRelationCoord) –

    pose or orientation coordinate model

  • graph (Graph) –

    RDF graph to look for coordinate attributes

Returns:

Source code in src/rdf_utils/models/geom_coord.py
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
def get_orientation_coord_vals(coord_model: IFrameRelationCoord, graph: Graph) -> Rotation | None:
    """Parse orientation coordinate in a graph into a SciPy Rotation.

    Handles and convert different orientation coordinate types into a
    [SciPy Rotation](scipy.spatial.transform.Rotation)

    Parameters:
        coord_model: pose or orientation coordinate model
        graph: RDF graph to look for coordinate attributes

    Returns:
        corresponding [SciPy Rotation](scipy.spatial.transform.Rotation), or None when no
        orientation values are present
    """
    representation = _orientation_representation(coord_model)
    if representation == URI_GEOM_TYPE_EULER_ANGLES:
        values = get_euler_angles_abg(coord_model=coord_model, graph=graph)
        if values is None:
            return None

        seq, is_intrinsic, unit, angles = values
        if is_intrinsic:
            seq = seq.upper()
        try:
            return Rotation.from_euler(seq=seq, angles=angles, degrees=(unit == URI_QUDT_UNIT_DEG))
        except ValueError as error:
            raise ConstraintViolation(
                "geometry", f"Coordinate {coord_model.id} has invalid Euler values: {error}"
            ) from error

    if representation == URI_GEOM_TYPE_DIRECTION_COSINE_XYZ:
        matrix = get_direction_cosine_matrix(coord_model, graph)
        if matrix is None:
            return None
        try:
            return Rotation.from_matrix(matrix)
        except ValueError as error:
            raise ConstraintViolation(
                "geometry", f"Coordinate {coord_model.id} has invalid direction cosines: {error}"
            ) from error

    if representation == URI_GEOM_TYPE_QUATERNION:
        quaternion = get_quaternion_xyzw(coord_model, graph)
        if quaternion is None:
            return None
        try:
            return Rotation.from_quat(quaternion)
        except ValueError as error:
            raise ConstraintViolation(
                "geometry", f"Coordinate {coord_model.id} has invalid quaternion values: {error}"
            ) from error

    return None

get_orientation_coords

get_orientation_coords(graph, orientations, *, coord_policy=None)

Yield each Orientation relation with its OrientationCoordinate models.

An Orientation sampled by several coordinates yields all of them, unless a coord_policy or a graph-declared evaluator on the Orientation narrows it to the one it picks.

Parameters:

  • graph (Graph) –

    RDF graph containing the coordinates

  • orientations (list[OrientationModel]) –

    Orientation relations whose coordinates to load

  • coord_policy (CoordPolicyProtocol | None, default: None ) –

    picks one coordinate of an Orientation sampled by several

Yields:

Source code in src/rdf_utils/models/geom_coord.py
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
def get_orientation_coords(
    graph: Graph,
    orientations: list[OrientationModel],
    *,
    coord_policy: CoordPolicyProtocol | None = None,
) -> Generator[tuple[OrientationModel, list[OrientCoordModel]], None, None]:
    """Yield each Orientation relation with its OrientationCoordinate models.

    An Orientation sampled by several coordinates yields all of them, unless a ``coord_policy``
    or a graph-declared evaluator on the Orientation narrows it to the one it picks.

    Parameters:
        graph: RDF graph containing the coordinates
        orientations: Orientation relations whose coordinates to load
        coord_policy: picks one coordinate of an Orientation sampled by several

    Yields:
        each Orientation relation paired with its loaded coordinates
    """
    for orientation in orientations:
        yield (
            orientation,
            [
                OrientCoordModel(coord_id=cid, graph=graph, orientation=orientation)
                for cid in _narrowed_coord_ids(orientation, graph, coord_policy)
            ],
        )

get_pose_coord_vals

get_pose_coord_vals(coord_model, graph, rng=None, materialize_sample=False)

Get the rigid transform represented by a PoseCoordinate.

Without rng, the coordinate must have explicit position and orientation values. With rng, missing values may be sampled from SampledQuantity distributions.

Parameters:

  • coord_model (PoseCoordModel) –

    PoseCoordinate model containing position and orientation coordinates

  • graph (Graph) –

    RDF graph containing the coordinate values

  • rng (Generator | None, default: None ) –

    optional random generator that enables sampled coordinates

  • materialize_sample (bool, default: False ) –

    whether to write newly sampled values to the graph

Returns:

  • RigidTransform –

    rigid transform containing the Pose translation, in metres, and rotation

Source code in src/rdf_utils/models/geom_coord.py
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
def get_pose_coord_vals(
    coord_model: PoseCoordModel,
    graph: Graph,
    rng: np.random.Generator | None = None,
    materialize_sample: bool = False,
) -> RigidTransform:
    """Get the rigid transform represented by a PoseCoordinate.

    Without ``rng``, the coordinate must have explicit position and orientation
    values. With ``rng``, missing values may be sampled from SampledQuantity
    distributions.

    Parameters:
        coord_model: PoseCoordinate model containing position and orientation coordinates
        graph: RDF graph containing the coordinate values
        rng: optional random generator that enables sampled coordinates
        materialize_sample: whether to write newly sampled values to the graph

    Returns:
        rigid transform containing the Pose translation, in metres, and rotation
    """
    if rng is None:
        translation = get_coord_vectorxyz(coord_model.position_coord, graph)
        if translation is None:
            raise ConstraintViolation(
                "geometry", f"Coordinate {coord_model.position_coord.id} has no XYZ values"
            )
        rotation = get_orientation_coord_vals(coord_model.orientation_coord, graph)
        if rotation is None:
            raise ConstraintViolation(
                "geometry",
                f"Coordinate {coord_model.orientation_coord.id} has no orientation values",
            )
    else:
        translation = get_or_sample_coord_vectorxyz(
            coord_model.position_coord,
            graph,
            rng=rng,
            materialize_sample=materialize_sample,
        )
        rotation = get_or_sample_orientation_coord(
            coord_model.orientation_coord,
            graph,
            rng=rng,
            materialize_sample=materialize_sample,
        )

    return RigidTransform.from_components(
        to_metres(translation, coord_model.position_coord.unit, coord_model.position_coord.id),
        rotation,
    )

get_pose_coords

get_pose_coords(graph, poses, *, coord_policy=None)

Yield each Pose relation with its PoseCoordinate models.

A Pose sampled by several coordinates yields all of them, unless a coord_policy or a graph-declared evaluator on the Pose narrows it to the one it picks; the policy is then propagated into that coordinate's own component resolution.

Parameters:

  • graph (Graph) –

    RDF graph containing the coordinates

  • poses (list[PoseModel]) –

    Pose relations whose coordinates to load

  • coord_policy (CoordPolicyProtocol | None, default: None ) –

    picks one coordinate of a Pose sampled by several

Yields:

Source code in src/rdf_utils/models/geom_coord.py
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
def get_pose_coords(
    graph: Graph,
    poses: list[PoseModel],
    *,
    coord_policy: CoordPolicyProtocol | None = None,
) -> Generator[tuple[PoseModel, list[PoseCoordModel]], None, None]:
    """Yield each Pose relation with its PoseCoordinate models.

    A Pose sampled by several coordinates yields all of them, unless a ``coord_policy`` or a
    graph-declared evaluator on the Pose narrows it to the one it picks; the policy is then
    propagated into that coordinate's own component resolution.

    Parameters:
        graph: RDF graph containing the coordinates
        poses: Pose relations whose coordinates to load
        coord_policy: picks one coordinate of a Pose sampled by several

    Yields:
        each Pose relation paired with its loaded coordinates
    """
    for pose in poses:
        yield (
            pose,
            [
                PoseCoordModel(coord_id=cid, graph=graph, pose=pose, coord_policy=coord_policy)
                for cid in _narrowed_coord_ids(pose, graph, coord_policy)
            ],
        )

get_position_coords

get_position_coords(graph, position_rels, *, coord_policy=None)

Yield each Position relation with its PositionCoordinate models.

A Position sampled by several coordinates yields all of them, unless a coord_policy or a graph-declared evaluator on the Position narrows it to the one it picks.

Parameters:

  • graph (Graph) –

    RDF graph containing the coordinates

  • position_rels (list[PositionModel]) –

    Position relations whose coordinates to load

  • coord_policy (CoordPolicyProtocol | None, default: None ) –

    picks one coordinate of a Position sampled by several

Yields:

Source code in src/rdf_utils/models/geom_coord.py
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
def get_position_coords(
    graph: Graph,
    position_rels: list[PositionModel],
    *,
    coord_policy: CoordPolicyProtocol | None = None,
) -> Generator[tuple[PositionModel, list[PositionCoordModel]], None, None]:
    """Yield each Position relation with its PositionCoordinate models.

    A Position sampled by several coordinates yields all of them, unless a ``coord_policy`` or a
    graph-declared evaluator on the Position narrows it to the one it picks.

    Parameters:
        graph: RDF graph containing the coordinates
        position_rels: Position relations whose coordinates to load
        coord_policy: picks one coordinate of a Position sampled by several

    Yields:
        each Position relation paired with its loaded coordinates
    """
    for position in position_rels:
        yield (
            position,
            [
                PositionCoordModel(coord_id=cid, graph=graph, position=position)
                for cid in _narrowed_coord_ids(position, graph, coord_policy)
            ],
        )

get_quaternion_xyzw

get_quaternion_xyzw(coord_model, graph)

Extract a scalar-last Quaternion from a graph.

Parameters:

  • coord_model (IFrameRelationCoord) –

    pose or orientation coordinate model

  • graph (Graph) –

    RDF graph to look for coordinate attributes

Returns:

  • ndarray | None –

    quaternion values in x, y, z, w order, or None when no values are present

Source code in src/rdf_utils/models/geom_coord.py
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
def get_quaternion_xyzw(coord_model: IFrameRelationCoord, graph: Graph) -> np.ndarray | None:
    """Extract a scalar-last Quaternion from a graph.

    Parameters:
        coord_model: pose or orientation coordinate model
        graph: RDF graph to look for coordinate attributes

    Returns:
        quaternion values in x, y, z, w order, or None when no values are present
    """
    if URI_GEOM_TYPE_QUATERNION not in coord_model.types:
        raise ValueError(f"Coordinate '{coord_model.id}' is not a Quaternion")

    values: list[float] = []
    for pred in (URI_GEOM_PRED_X, URI_GEOM_PRED_Y, URI_GEOM_PRED_Z, URI_GEOM_PRED_W):
        val_nodes = list(graph.objects(coord_model.id, pred))
        if not val_nodes:
            # allow no value
            continue

        if len(val_nodes) != 1 or not isinstance(val_nodes[0], Literal):
            raise ConstraintViolation(
                "geometry",
                f"Coordinate {coord_model.id} must have zero or one float literal for {pred}, found: {val_nodes}",
            )

        val = val_nodes[0].toPython()
        if not isinstance(val, float) or not np.isfinite(val):
            raise ConstraintViolation(
                "geometry",
                f"Coordinate {coord_model.id} must have one finite float for {pred}, found: {val}",
            )

        values.append(val)

    if not values:
        return None

    if len(values) != 4:
        raise ConstraintViolation(
            "geometry",
            f"Coordinate {coord_model.id} does not have 4 quaternion values, found: {values}",
        )

    return np.asarray(values)

get_rotation_between_frames

get_rotation_between_frames(of_frame, wrt_frame, graph, rng=None, materialize_samples=False, *, coord_policy=None)

Get the rotation between two frames.

Each Orientation along the path must have one OrientationCoordinate, unless a coord_policy is given to pick among several. Without rng, only explicit values are read. With rng, missing values may be sampled from a UniformRotation distribution.

Parameters:

  • of_frame (URIRef) –

    frame at the start of the path

  • wrt_frame (URIRef) –

    frame at the end of the path

  • graph (Graph) –

    RDF graph containing the Orientation relations and coordinates

  • rng (Generator | None, default: None ) –

    optional random generator that enables sampled coordinates

  • materialize_samples (bool, default: False ) –

    whether to write newly sampled values to the graph

  • coord_policy (CoordPolicyProtocol | None, default: None ) –

    picks one OrientationCoordinate when an Orientation has several

Returns:

  • Rotation | None –

    composed rotation, identity for the same frame, or None when no

  • Rotation | None –

    Orientation path exists

Source code in src/rdf_utils/models/geom_coord.py
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
def get_rotation_between_frames(
    of_frame: URIRef,
    wrt_frame: URIRef,
    graph: Graph,
    rng: np.random.Generator | None = None,
    materialize_samples: bool = False,
    *,
    coord_policy: CoordPolicyProtocol | None = None,
) -> Rotation | None:
    """Get the rotation between two frames.

    Each Orientation along the path must have one OrientationCoordinate, unless a
    ``coord_policy`` is given to pick among several. Without ``rng``, only explicit values are
    read. With ``rng``, missing values may be sampled from a UniformRotation distribution.

    Parameters:
        of_frame: frame at the start of the path
        wrt_frame: frame at the end of the path
        graph: RDF graph containing the Orientation relations and coordinates
        rng: optional random generator that enables sampled coordinates
        materialize_samples: whether to write newly sampled values to the graph
        coord_policy: picks one OrientationCoordinate when an Orientation has several

    Returns:
        composed rotation, identity for the same frame, or None when no
        Orientation path exists
    """
    path = find_orientation_path(of_frame, wrt_frame, graph)
    if path is None:
        return None

    result = Rotation.identity()
    for orientation, orient_coords in get_orientation_coords(
        graph=graph, orientations=path, coord_policy=coord_policy
    ):
        if len(orient_coords) != 1:
            raise ConstraintViolation(
                "geometry",
                f"Orientation {orientation.id} must have one coordinate, found {orient_coords}",
            )

        coordinate = orient_coords[0]
        if rng is None:
            rotation = get_orientation_coord_vals(coordinate, graph)
            if rotation is None:
                raise ConstraintViolation(
                    "geometry", f"Coordinate {coordinate.id} has no orientation values"
                )
        else:
            rotation = get_or_sample_orientation_coord(
                coordinate,
                graph,
                rng=rng,
                materialize_sample=materialize_samples,
            )
        result = rotation * result

    return result

get_transform_between_frames

get_transform_between_frames(of_frame, wrt_frame, graph, rng=None, materialize_samples=False, *, coord_policy=None)

Get the rigid transform between two frames.

Each Pose along the path must have exactly one PoseCoordinate resolving to both a PositionCoordinate and an OrientationCoordinate, unless a coord_policy is given, which narrows a Pose with several and is propagated into that coordinate's own component resolution. Position coordinates along the path must share one QUDT unit. Missing coordinate values may be sampled when an rng is supplied.

Parameters:

  • of_frame (URIRef) –

    frame at the start of the path

  • wrt_frame (URIRef) –

    frame at the end of the path

  • graph (Graph) –

    RDF graph containing Pose relations and coordinates

  • rng (Generator | None, default: None ) –

    optional random generator that enables sampled coordinates

  • materialize_samples (bool, default: False ) –

    whether to write newly sampled values to the graph

  • coord_policy (CoordPolicyProtocol | None, default: None ) –

    picks one PoseCoordinate, and its component coordinates, when several exist

Returns:

  • RigidTransform | None –

    composed rigid transform with its translation in metres, identity for

  • RigidTransform | None –

    the same frame, or None when no Pose path exists

Source code in src/rdf_utils/models/geom_coord.py
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
def get_transform_between_frames(
    of_frame: URIRef,
    wrt_frame: URIRef,
    graph: Graph,
    rng: np.random.Generator | None = None,
    materialize_samples: bool = False,
    *,
    coord_policy: CoordPolicyProtocol | None = None,
) -> RigidTransform | None:
    """Get the rigid transform between two frames.

    Each Pose along the path must have exactly one PoseCoordinate resolving to both a
    PositionCoordinate and an OrientationCoordinate, unless a ``coord_policy`` is given, which
    narrows a Pose with several and is propagated into that coordinate's own component
    resolution. Position coordinates along the path must share one QUDT unit. Missing coordinate
    values may be sampled when an ``rng`` is supplied.

    Parameters:
        of_frame: frame at the start of the path
        wrt_frame: frame at the end of the path
        graph: RDF graph containing Pose relations and coordinates
        rng: optional random generator that enables sampled coordinates
        materialize_samples: whether to write newly sampled values to the graph
        coord_policy: picks one PoseCoordinate, and its component coordinates, when several exist

    Returns:
        composed rigid transform with its translation in metres, identity for
        the same frame, or None when no Pose path exists
    """
    path = find_pose_path(of_frame, wrt_frame, graph)
    if path is None:
        return None

    result = RigidTransform.identity()
    unit = None
    for pose, pose_coords in get_pose_coords(graph=graph, poses=path, coord_policy=coord_policy):
        if len(pose_coords) != 1:
            raise ConstraintViolation(
                "geometry",
                f"Pose {pose.id} must have one coordinate, found {len(pose.coordinate_ids)}",
            )

        pose_coord = pose_coords[0]
        if unit is None:
            unit = pose_coord.position_coord.unit
        elif pose_coord.position_coord.unit != unit:
            raise ConstraintViolation(
                "geometry", "PositionCoordinates in a path must share one unit"
            )
        result = (
            get_pose_coord_vals(
                pose_coord,
                graph,
                rng=rng,
                materialize_sample=materialize_samples,
            )
            * result
        )

    return result

get_translation_between_points

get_translation_between_points(of_point, wrt_point, graph, rng=None, materialize_samples=False, *, coord_policy=None)

Get the XYZ translation between two points.

Each Position along the path must have one VectorXYZ PositionCoordinate, unless a coord_policy is given to pick among several, and all coordinates must share one QUDT unit. Without rng, every coordinate must have explicit XYZ values. With rng, missing XYZ values may be sampled from a SampledQuantity distribution.

Parameters:

  • of_point (URIRef) –

    point at the start of the path

  • wrt_point (URIRef) –

    point at the end of the path

  • graph (Graph) –

    RDF graph containing the Position relations and coordinates

  • rng (Generator | None, default: None ) –

    optional random generator that enables sampled coordinates

  • materialize_samples (bool, default: False ) –

    whether to write newly sampled XYZ values to the graph; ignored when no sampling occurs

  • coord_policy (CoordPolicyProtocol | None, default: None ) –

    picks one PositionCoordinate when a Position has several

Returns:

Source code in src/rdf_utils/models/geom_coord.py
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
def get_translation_between_points(
    of_point: URIRef,
    wrt_point: URIRef,
    graph: Graph,
    rng: np.random.Generator | None = None,
    materialize_samples: bool = False,
    *,
    coord_policy: CoordPolicyProtocol | None = None,
) -> tuple[float, float, float] | None:
    """Get the XYZ translation between two points.

    Each Position along the path must have one VectorXYZ PositionCoordinate, unless a
    ``coord_policy`` is given to pick among several, and all coordinates must share one QUDT unit.
    Without ``rng``, every coordinate must have explicit XYZ values. With ``rng``, missing XYZ
    values may be sampled from a SampledQuantity distribution.

    Parameters:
        of_point: point at the start of the path
        wrt_point: point at the end of the path
        graph: RDF graph containing the Position relations and coordinates
        rng: optional random generator that enables sampled coordinates
        materialize_samples: whether to write newly sampled XYZ values to the
                             graph; ignored when no sampling occurs
        coord_policy: picks one PositionCoordinate when a Position has several

    Returns:
        summed XYZ translation in metres, a zero vector for the same point, or
        None when no Position path exists
    """
    path = find_position_path(of_point, wrt_point, graph)
    if path is None:
        return None

    translation = [0.0, 0.0, 0.0]
    unit = None
    for position, coords in get_position_coords(
        graph=graph, position_rels=path, coord_policy=coord_policy
    ):
        if len(coords) != 1:
            raise ConstraintViolation(
                "geometry",
                f"Position {position.id} must have one coordinate, found: {coords}",
            )

        coordinate = coords[0]
        if unit is None:
            unit = coordinate.unit
        elif coordinate.unit != unit:
            raise ConstraintViolation(
                "geometry",
                "PositionCoordinates in a path must share one unit",
            )
        if rng is None:
            values = get_coord_vectorxyz(coordinate, graph)
            if values is None:
                raise ConstraintViolation(
                    "geometry", f"Coordinate {coordinate.id} has no XYZ values"
                )
        else:
            values = get_or_sample_coord_vectorxyz(
                coordinate,
                graph,
                rng=rng,
                materialize_sample=materialize_samples,
            )

        values = to_metres(values, coordinate.unit, coordinate.id)
        translation = [total + value for total, value in zip(translation, values)]

    return (translation[0], translation[1], translation[2])

select_coordinate

select_coordinate(relation, graph, coord_policy=None, **kwargs)

The one coordinate of relation to use, or None when the caller must decide: no candidate at all, or several with no policy to choose among them.

A caller-supplied coord_policy takes precedence -- it is for open queries a specification does not depend on. Absent one, a policy declared on the relation via geom-coord:has-coordinate-policy is resolved and used instead: declaring the choice in the graph is what a specification depends on.

Parameters:

  • relation (PositionModel | OrientationModel | PoseModel) –

    the relation whose coordinates to choose among

  • graph (Graph) –

    RDF graph containing the coordinates and any declared evaluator

  • coord_policy (CoordPolicyProtocol | None, default: None ) –

    picks one coordinate among several; takes precedence over the graph

  • **kwargs (Any, default: {} ) –

    passed through to the policy, e.g. coord_id/component for a Pose's components

Returns:

  • URIRef | None –

    the chosen coordinate's URI, or None when the caller must decide what to do

Source code in src/rdf_utils/models/geom_coord.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
def select_coordinate(
    relation: PositionModel | OrientationModel | PoseModel,
    graph: Graph,
    coord_policy: CoordPolicyProtocol | None = None,
    **kwargs: Any,
) -> URIRef | None:
    """The one coordinate of ``relation`` to use, or None when the caller must decide: no
    candidate at all, or several with no policy to choose among them.

    A caller-supplied ``coord_policy`` takes precedence -- it is for open queries a specification
    does not depend on. Absent one, a policy declared on the relation via ``geom-coord:has-coordinate-policy`` is resolved
    and used instead: declaring the choice in the graph is what a specification depends on.

    Parameters:
        relation: the relation whose coordinates to choose among
        graph: RDF graph containing the coordinates and any declared evaluator
        coord_policy: picks one coordinate among several; takes precedence over the graph
        **kwargs: passed through to the policy, e.g. ``coord_id``/``component`` for a Pose's
            components

    Returns:
        the chosen coordinate's URI, or None when the caller must decide what to do
    """
    candidates = list(relation.coordinate_ids)
    if len(candidates) == 1:
        return candidates[0]
    if not candidates:
        return None

    policy = coord_policy
    if policy is None:
        found = graph.value(
            subject=relation.id, predicate=URI_GEOM_PRED_HAS_COORD_POLICY, any=False
        )
        if found is not None:
            if not isinstance(found, URIRef):
                raise ConstraintViolation(
                    "geometry",
                    f"{relation.id} links to a non-URI policy via 'has-coordinate-policy': {found}",
                )
            policy = _resolve_coord_evaluator(graph, found)
    if policy is None:
        return None

    chosen = policy(candidates, graph=graph, relation=relation.id, **kwargs)
    if chosen not in relation.coordinate_ids:
        raise ConstraintViolation(
            "geometry",
            f"coord_policy returned '{chosen}', which is not a coordinate of relation "
            f"'{relation.id}': {candidates}",
        )
    return chosen

set_coord_vectorxyz

set_coord_vectorxyz(coord_model, values, graph)

Set coordinates for a VectorXYZ model.

Parameters:

Source code in src/rdf_utils/models/geom_coord.py
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
def set_coord_vectorxyz(
    coord_model: ModelBase,
    values: tuple[float, float, float],
    graph: Graph,
) -> None:
    """Set coordinates for a VectorXYZ model.

    Parameters:
        coord_model: coordinate model object
        values: x, y, and z coordinate values
        graph: RDF graph to update
    """
    if URI_GEOM_TYPE_VECTOR_XYZ not in coord_model.types or len(values) != 3:
        raise ConstraintViolation("geometry", "expected three values for a VectorXYZ model")
    for predicate, value in zip((URI_GEOM_PRED_X, URI_GEOM_PRED_Y, URI_GEOM_PRED_Z), values):
        graph.set((coord_model.id, predicate, Literal(float(value))))

set_orientation_coord

set_orientation_coord(coord_model, rotation, graph)

Write a rotation using the coordinate's declared representation.

Coordinates are written by representation types as follows: - EulerAngles: alpha, beta, and gamma values in their declared axes sequence and unit; - DirectionCosineXYZ: three RDF-list matrix rows; - Quaternion: scalar-last x, y, z, w order.

Parameters:

  • coord_model (IFrameRelationCoord) –

    pose or orientation coordinate model

  • rotation (Rotation) –

    SciPy Rotation to write

  • graph (Graph) –

    RDF graph to update

Source code in src/rdf_utils/models/geom_coord.py
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
def set_orientation_coord(
    coord_model: IFrameRelationCoord, rotation: Rotation, graph: Graph
) -> None:
    """Write a rotation using the coordinate's declared representation.

    Coordinates are written by representation types as follows:
    - EulerAngles: alpha, beta, and gamma values in their declared
      axes sequence and unit;
    - DirectionCosineXYZ: three RDF-list matrix rows;
    - Quaternion: scalar-last x, y, z, w order.

    Parameters:
        coord_model: pose or orientation coordinate model
        rotation: SciPy Rotation to write
        graph: RDF graph to update
    """
    representation = _orientation_representation(coord_model)
    if representation == URI_GEOM_TYPE_EULER_ANGLES:
        seq, is_intrinsic = get_euler_angles_params(coord_model, graph)
        units = [
            unit
            for unit in graph.objects(coord_model.id, URI_QUDT_PRED_UNIT)
            if unit in (URI_QUDT_UNIT_DEG, URI_QUDT_UNIT_RAD)
        ]
        if len(units) != 1:
            raise ConstraintViolation(
                "geometry", f"Coordinate {coord_model.id} must have one angle unit"
            )
        angles = rotation.as_euler(
            seq.upper() if is_intrinsic else seq,
            degrees=units[0] == URI_QUDT_UNIT_DEG,
        )
        for predicate, angle in zip(
            (URI_GEOM_PRED_ALPHA, URI_GEOM_PRED_BETA, URI_GEOM_PRED_GAMMA), angles
        ):
            graph.set((coord_model.id, predicate, Literal(float(angle))))
        return

    if representation == URI_GEOM_TYPE_DIRECTION_COSINE_XYZ:
        for predicate, row in zip(
            (
                URI_GEOM_PRED_DIRECTION_COSINE_X,
                URI_GEOM_PRED_DIRECTION_COSINE_Y,
                URI_GEOM_PRED_DIRECTION_COSINE_Z,
            ),
            rotation.as_matrix(),
        ):
            add_literal_list_pred(graph, coord_model.id, predicate, tuple(map(float, row)))
        return

    if representation == URI_GEOM_TYPE_QUATERNION:
        for predicate, value in zip(
            (URI_GEOM_PRED_X, URI_GEOM_PRED_Y, URI_GEOM_PRED_Z, URI_GEOM_PRED_W),
            rotation.as_quat(),
        ):
            graph.set((coord_model.id, predicate, Literal(float(value))))
        return

    raise ConstraintViolation(
        "geometry", f"Coordinate {coord_model.id} has no orientation representation"
    )

to_metres

to_metres(values, unit, coord_id)

Convert authored lengths to metres.

Orientations are already returned in radians whatever the authored unit, so lengths are returned in metres for the same reason: a caller cannot discover the unit from the value, and a composition mixes coordinates it did not author.

Parameters:

  • values (Iterable[float]) –

    authored lengths to convert

  • unit (URIRef | None) –

    QUDT length unit used by the values

  • coord_id (URIRef) –

    URI of the coordinate node, used in error messages

Returns:

  • list[float] –

    the lengths scaled into metres

Source code in src/rdf_utils/models/geom_coord.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def to_metres(values: Iterable[float], unit: URIRef | None, coord_id: URIRef) -> list[float]:
    """Convert authored lengths to metres.

    Orientations are already returned in radians whatever the authored unit, so
    lengths are returned in metres for the same reason: a caller cannot discover
    the unit from the value, and a composition mixes coordinates it did not author.

    Parameters:
        values: authored lengths to convert
        unit: QUDT length unit used by the values
        coord_id: URI of the coordinate node, used in error messages

    Returns:
        the lengths scaled into metres
    """
    if unit not in LENGTH_IN_METRES:
        raise ConstraintViolation(
            "geometry", f"Coordinate {coord_id} has no length unit to convert: {unit}"
        )
    scale = LENGTH_IN_METRES[unit]
    return [value * scale for value in values]