Skip to content

transforms

Functions for coordinate transforms.

There are 6 relevant coordinate systems here, belonging to two sets of three. Each set is a global, a primary, and a secondary coordinate system; where primary and secondary are internal to those mirrors. The two sets of coordinates are the optical coordinates and the coordinates used by vertex. We denote these six coordinate systems as follows:

- opt_global
- opt_primary
- opt_secondary
- va_global
- va_primary
- va_secondary

affine_basis_transform(aff, sft, cfrom, cto, src_or_dst=True)

Take an affine transform defined in one coordinate system and move it to another. The valid coordinate systems are the same as in coord_transform.

Parameters:

Name Type Description Default
aff NDArray[float32]

Affine matrix to tranform. Should be a (3, 3) array.

required
sft NDArray[float32]

Shift vector to tranform. Should be a (3,) array.

required
cfrom str

The coordinate system that aff and sft is currently in.

required
cto str

The coordinate system to put aff and sft into.

required
src_or_dst bool

If True then the coordinate transform is done on the source points that we are affine transforming. This is equivalent to doing aff@(coord_transform(src)) + sft. If False then the coordinate transform is done on the destination points obtained by the affine transform. This is equivalent to doing coord_transform(aff@src + sft)

True

Returns:

Name Type Description
aff_transformed NDArray[float32]

aff transformed into cto.

sft_transformed NDArray[float32]

sft transformed into cto.

Source code in lat_alignment/transforms.py
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
def affine_basis_transform(
    aff: NDArray[np.float32],
    sft: NDArray[np.float32],
    cfrom: str,
    cto: str,
    src_or_dst: bool = True,
) -> tuple[NDArray[np.float32], NDArray[np.float32]]:
    """
    Take an affine transform defined in one coordinate system and move it to another.
    The valid coordinate systems are the same as in `coord_transform`.

    Parameters
    ----------
    aff : NDArray[np.float32]
        Affine matrix to tranform.
        Should be a `(3, 3)` array.
    sft : NDArray[np.float32]
        Shift vector to tranform.
        Should be a `(3,)` array.
    cfrom : str
        The coordinate system that `aff` and `sft` is currently in.
    cto : str
        The coordinate system to put `aff` and `sft` into.
    src_or_dst : bool, default: True
        If `True` then the coordinate transform is done on the source
        points that we are affine transforming.
        This is equivalent to doing `aff@(coord_transform(src)) + sft`.
        If `False` then the coordinate transform is done on the destination
        points obtained by the affine transform.
        This is equivalent to doing `coord_transform(aff@src + sft)`

    Returns
    -------
    aff_transformed : NDArray[np.float32]
        `aff` transformed into `cto`.
    sft_transformed : NDArray[np.float32]
        `sft` transformed into `cto`.
    """
    # Make a grid of reference points
    line = np.array((-1, 0, 1), np.float32)
    x, y, z = np.meshgrid(line, line, line)
    xyz = np.column_stack((x.ravel(), y.ravel(), z.ravel()))

    # Apply the affine transform
    xyz_transformed = apply_transform(xyz, aff, sft)

    # Move to the new coordinate system
    if src_or_dst:
        xyz = coord_transform(xyz, cfrom, cto)
    else:
        xyz_transformed = coord_transform(xyz_transformed, cfrom, cto)

    # Get the new affine transform
    aff, sft = get_affine(xyz, xyz_transformed)

    return aff, sft

align_photo(labels, coords, reference, *, plot=True, mirror='primary', max_dist=100.0)

Align photogrammetry data and then put it into mirror coordinates.

Parameters:

Name Type Description Default
labels NDArray[str_]

The labels of each photogrammetry point. Should have shape (npoint,).

required
coords NDArray[float32]

The coordinates of each photogrammetry point. Should have shape (npoint, 3).

required
reference dict

Reference dictionary. Should contain a key called coords that specifies the coordinate system that the reference points are in. The rest of the keys should be optical elements (ie: "primary") pointing to a list of reference points to use. Each point given should be a tuple with two elements. The first element is a tuple with the (x, y, z) coordinates of the point in the global coordinate system. The second is a list of nearby coded targets that can be used to identify the point.

required
plot bool

If True show a diagnostic plot of how well the reference points are aligned.

True
mirror str

The mirror that these points belong to. Should be either: 'primary' or 'secondary'.

'primary'
max_dist float

Max distance in mm that the reference poing can be from the target point used to locate it.

100

Returns:

Name Type Description
labels NDArray[str_]

The labels of each photogrammetry point. Invar points are not included.

coords_transformed NDArray[float32]

The transformed coordinates. Invar points are not included.

msk NDArray[bool_]

Mask to removes invar points

alignment tuple[NDArray[float32], NDArray[float32]]

The transformation that aligned the points. The first element is a rotation matrix and the second is the shift.

Source code in lat_alignment/transforms.py
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
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
456
457
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
485
486
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
def align_photo(
    labels: NDArray[np.str_],
    coords: NDArray[np.float32],
    reference: dict,
    *,
    plot: bool = True,
    mirror: str = "primary",
    max_dist: float = 100.0,
) -> tuple[
    NDArray[np.str_],
    NDArray[np.float32],
    NDArray[np.bool_],
    tuple[NDArray[np.float32], NDArray[np.float32]],
]:
    """
    Align photogrammetry data and then put it into mirror coordinates.

    Parameters
    ----------
    labels : NDArray[np.str_]
        The labels of each photogrammetry point.
        Should have shape `(npoint,)`.
    coords : NDArray[np.float32]
        The coordinates of each photogrammetry point.
        Should have shape `(npoint, 3)`.
    reference : dict
        Reference dictionary.
        Should contain a key called `coords` that specifies the
        coordinate system that the reference points are in.
        The rest of the keys should be optical elements (ie: "primary")
        pointing to a list of reference points to use.
        Each point given should be a tuple with two elements.
        The first element is a tuple with the (x, y, z) coordinates
        of the point in the global coordinate system.
        The second is a list of nearby coded targets that can be used
        to identify the point.
    plot : bool, default: True
        If True show a diagnostic plot of how well the reference points
        are aligned.
    mirror : str, default: 'primary'
        The mirror that these points belong to.
        Should be either: 'primary' or 'secondary'.
    max_dist : float, default: 100
        Max distance in mm that the reference poing can be from the target
        point used to locate it.

    Returns
    -------
    labels : NDArray[np.str_]
        The labels of each photogrammetry point.
        Invar points are not included.
    coords_transformed : NDArray[np.float32]
        The transformed coordinates.
        Invar points are not included.
    msk : NDArray[np.bool_]
        Mask to removes invar points
    alignment : tuple[NDArray[np.float32], NDArray[np.float32]]
        The transformation that aligned the points.
        The first element is a rotation matrix and
        the second is the shift.
    """
    logger.info("\tAligning with reference points for %s", mirror)
    if mirror not in ["primary", "secondary"]:
        raise ValueError(f"Invalid mirror: {mirror}")
    if len(reference) == 0:
        raise ValueError("Invalid or empty reference")
    if mirror not in reference:
        raise ValueError("Mirror not found in reference dict")
    if "coords" not in reference:
        raise ValueError("Reference coordinate system not specified")
    if mirror == "primary":
        transform = partial(
            coord_transform, cfrom=reference["coords"], cto="opt_primary"
        )
    else:
        transform = partial(
            coord_transform, cfrom=reference["coords"], cto="opt_secondary"
        )

    # Lets find the points we can use
    trg_idx = np.where(np.char.find(labels, "TARGET") >= 0)[0]
    ref = []
    pts = []
    invars = []
    for rpoint, codes in reference[mirror]:
        have = np.isin(codes, labels)
        if np.sum(have) == 0:
            continue
        coded = coords[np.where(labels == codes[np.where(have)[0][0]])[0][0]]
        # Find the closest point
        dist = np.linalg.norm(coords[trg_idx] - coded, axis=-1)
        if np.min(dist) > max_dist:
            continue
        ref += [rpoint]
        pts += [coords[trg_idx][np.argmin(dist)]]
        invars += [labels[trg_idx][np.argmin(dist)]]
    if len(ref) < 4:
        raise ValueError(f"Only {len(ref)} reference points found! Can't align!")
    logger.debug(
        "\t\tFound %d reference points in measurements with labels:\n\t\t\t%s",
        len(pts),
        str(invars),
    )
    pts = np.vstack(pts)
    ref = np.vstack(ref)
    pts = np.vstack((pts, np.mean(pts, 0)))
    ref = np.vstack((ref, np.mean(ref, 0)))
    ref = transform(ref)
    logger.debug("\t\tReference points in mirror coords:\n%s", str(ref[:-1]))
    triu_idx = np.triu_indices(len(pts), 1)
    scale_fac = np.nanmedian(make_edm(ref)[triu_idx] / make_edm(pts)[triu_idx])
    logger.debug("\t\tScale factor of %f applied", scale_fac)
    pts *= scale_fac

    rot, sft = get_rigid(pts, ref, method="mean")
    pts_t = apply_transform(pts, rot, sft)

    if plot:
        plt.scatter(pts_t[:, 0], pts_t[:, 1], color="b")
        plt.scatter(ref[:, 0], ref[:, 1], color="r")
        plt.show()
    logger.info(
        "\t\tRMS of reference points after alignment: %f",
        np.sqrt(np.mean((pts_t - ref) ** 2)),
    )
    coords_transformed = apply_transform(coords, rot, sft)

    msk = ~np.isin(labels, invars)

    return labels[msk], coords_transformed[msk], msk, (rot, sft)

coord_transform(coords, cfrom, cto)

Transform between the six defined mirror coordinates:

- opt_global
- opt_primary
- opt_secondary
- va_global
- va_primary
- va_secondary

Parameters:

Name Type Description Default
coords NDArray[float32]

Coordinates to transform. Should be a (npoint, 3) array.

required
cfrom str

The coordinate system that coords is currently in.

required
cto str

The coordinate system to put coords into.

required

Returns:

Name Type Description
coords_transformed NDArray[float32]

coords transformed into cto.

Source code in lat_alignment/transforms.py
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
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
def coord_transform(
    coords: NDArray[np.float32], cfrom: str, cto: str
) -> NDArray[np.float32]:
    """
    Transform between the six defined mirror coordinates:

        - opt_global
        - opt_primary
        - opt_secondary
        - va_global
        - va_primary
        - va_secondary

    Parameters
    ----------
    coords : NDArray[np.float32]
        Coordinates to transform.
        Should be a `(npoint, 3)` array.
    cfrom : str
        The coordinate system that `coords` is currently in.
    cto : str
        The coordinate system to put `coords` into.

    Returns
    -------
    coords_transformed : NDArray[np.float32]
        `coords` transformed into `cto`.
    """
    if cfrom == cto:
        return coords
    match f"{cfrom}-{cto}":
        case "opt_global-opt_primary":
            return _opt_global_to_opt_primary(coords)
        case "opt_global-opt_secondary":
            return _opt_global_to_opt_secondary(coords)
        case "opt_primary-opt_global":
            return _opt_primary_to_opt_global(coords)
        case "opt_secondary-opt_global":
            return _opt_secondary_to_opt_global(coords)
        case "opt_primary-opt_secondary":
            return _opt_primary_to_opt_secondary(coords)
        case "opt_secondary-opt_primary":
            return _opt_secondary_to_opt_primary(coords)
        case "va_global-va_primary":
            return _va_global_to_va_primary(coords)
        case "va_global-va_secondary":
            return _va_global_to_va_secondary(coords)
        case "va_primary-va_global":
            return _va_primary_to_va_global(coords)
        case "va_secondary-va_global":
            return _va_secondary_to_va_global(coords)
        case "va_primary-va_secondary":
            return _va_primary_to_va_secondary(coords)
        case "va_secondary-va_primary":
            return _va_secondary_to_va_primary(coords)
        case "opt_global-va_global":
            return _opt_global_to_va_global(coords)
        case "opt_global-va_primary":
            return _opt_global_to_va_primary(coords)
        case "opt_global-va_secondary":
            return _opt_global_to_va_secondary(coords)
        case "opt_primary-va_global":
            return _opt_primary_to_va_global(coords)
        case "opt_primary-va_primary":
            return _opt_primary_to_va_primary(coords)
        case "opt_primary-va_secondary":
            return _opt_primary_to_va_secondary(coords)
        case "opt_secondary-va_global":
            return _opt_secondary_to_va_global(coords)
        case "opt_secondary-va_primary":
            return _opt_secondary_to_va_primary(coords)
        case "opt_secondary-va_secondary":
            return _opt_secondary_to_va_secondary(coords)
        case "va_global-opt_global":
            return _va_global_to_opt_global(coords)
        case "va_global-opt_primary":
            return _va_global_to_opt_primary(coords)
        case "va_global-opt_secondary":
            return _va_global_to_opt_secondary(coords)
        case "va_primary-opt_global":
            return _va_primary_to_opt_global(coords)
        case "va_primary-opt_primary":
            return _va_primary_to_opt_primary(coords)
        case "va_primary-opt_secondary":
            return _va_primary_to_opt_secondary(coords)
        case "va_secondary-opt_global":
            return _va_secondary_to_opt_global(coords)
        case "va_secondary-opt_primary":
            return _va_secondary_to_opt_primary(coords)
        case "va_secondary-opt_secondary":
            return _va_secondary_to_opt_secondary(coords)
        case _:
            raise ValueError("Invalid coordinate system provided!")