pysdic.Transformation#

The pysdic.Transformation provides a standardized way to manage parametric transformations \(T\) from \(\mathbb{R}^{n_i}\) to \(\mathbb{R}^{n_o}\), where the transformation is defined by a set of parameters \(\vec{p} \in \mathbb{R}^{n_p}\).

\[\vec{x_o} = T(\vec{x_i}; \vec{p})\]

Transformation class#

class Transformation(*args, **kwargs)[source]#

Bases: LockableMixin, RequiresOptionalMixin, JsonSerializerMixin, Hdf5SerializerMixin

Abstract base class representing a spatial parametric transformation \(T\) that maps points \(\vec{x_i}\) from an input space \(\mathbb{R}^{n_i}\) to an output space \(\mathbb{R}^{n_o}\). The transformation is defined by a set of parameters \(\vec{p} \in \mathbb{R}^{n_p}\) that control the mapping.

\[\vec{x_o} = T(\vec{x_i}; \vec{p})\]

Note

  • A parameter is a variable for which the transformation can be differentiated with respect to, and is typically optimized during fitting or registration processes.

  • The parameters are copied when they are set and are exposed as read-only views to prevent accidental modifications.

  • The parameters can be locked (see pysdic.core.lockable.LockableMixin) when the transformation is owned by another object of the package that assumes they do not change (for example a pysdic.ReparametrizedTransformation). A locked transformation refuses parameters = ... and set_parameters (unless override_lock=True): is_locked and locked_message tell whether it is locked and why. A copy is always unlocked.

All transformations can depend on constants, which are fixed values that influence the transformation but are not subject to optimization or differentiation.

A transformation can be applied to input points \(\vec{x_i} \in \mathbb{R}^{n_i}\) using the apply method, which returns a pysdic.TransformationResult object containing the transformed points \(\vec{x_o} \in \mathbb{R}^{n_o}\) and the Jacobian matrices \(\mathbf{J}_x = \frac{\partial T}{\partial \vec{x_i}}\) (if requested) and \(\mathbf{J}_p = \frac{\partial T}{\partial \vec{p}}\) (if requested).

A transformation can also define an inverse map \(T^{-1}\) using the invert method, which returns a pysdic.TransformationResult object containing the inverted points \(\vec{x_i} \in \mathbb{R}^{n_i}\) and the Jacobian matrices \(\mathbf{J}_x = \frac{\partial T^{-1}}{\partial \vec{x_o}}\) (if requested) and \(\mathbf{J}_p = \frac{\partial T^{-1}}{\partial \vec{p}}\) (if requested).

See also

Note

When \(n_i \neq n_o\), the map \(T\) cannot be bijective and \(T^{-1}\) denotes a left inverse or a right inverse of \(T\) (see the flags is_left_invertible and is_right_invertible below).

Note

The transformation acts independently on each point: the output point \(\vec{x_o}\) only depends on the corresponding input point \(\vec{x_i}\) and on the parameters \(\vec{p}\).

See also

To change the parametric space of the transformation (ie \(\vec{p} = P(\vec{p_i})\)), use the following classes:

See also

To compose transformations (ie \(T = T_2 \circ T_1\)), use the following classes:

  • Class pysdic.ComposedTransformation to allow multiple transformations to be composed together.

  • The syntax T2 @ T1 which is equivalent to ComposedTransformation([T1, T2]).

Parameters:

parameters (Optional[ArrayLike] (default: None)) – A 1D array of shape \((n_p,)\) containing the parameters \(\vec{p}\) of the transformation. If None, the parameters are not set (and the transformation is not set up) unless \(n_p = 0\).

Capability flags#

Each transformation declares its capabilities with the following boolean class/instance attributes. All flags default to False.

  • _has_apply: the method _apply is implemented (i.e. \(T\) can be evaluated).

  • _has_apply_dx: the method _apply can compute \(\frac{\partial T}{\partial \vec{x_i}}\).

  • _has_apply_dp: the method _apply can compute \(\frac{\partial T}{\partial \vec{p}}\).

  • _has_invert: the method _invert is implemented (i.e. \(T^{-1}\) can be evaluated).

  • _has_invert_dx: the method _invert can compute \(\frac{\partial T^{-1}}{\partial \vec{x_o}}\).

  • _has_invert_dp: the method _invert can compute \(\frac{\partial T^{-1}}{\partial \vec{p}}\).

  • _is_left_invertible: invert is a left inverse of apply, i.e. \(T^{-1}(T(\vec{x_i})) = \vec{x_i}\) for all \(\vec{x_i} \in \mathbb{R}^{n_i}\).

  • _is_right_invertible: invert is a right inverse of apply, i.e. \(T(T^{-1}(\vec{x_o})) = \vec{x_o}\) for all \(\vec{x_o} \in \mathbb{R}^{n_o}\).

The flags must be consistent:

  • _has_apply_dx and _has_apply_dp require _has_apply.

  • _has_invert_dx and _has_invert_dp require _has_invert.

  • _is_left_invertible and _is_right_invertible require both _has_apply and _has_invert.

The consistency is checked at initialization by Transformation.__init__. The flags _is_left_invertible and _is_right_invertible are declarations that can be verified numerically with the methods check_left_invertible and check_right_invertible.

Implementation details#

  • All subclasses must have an __init__ method taking parameters as an argument and calling super().__init__(parameters=parameters) at the end, once the constants are set (the number of parameters can depend on the constants). Optional class-methods can be implemented for specific constructions.

  • Subclasses with _has_apply=True must implement the method _apply, and subclasses with _has_invert=True must implement the method _invert. These methods are called by the public methods apply and invert respectively, which handle the validation of the inputs and outputs of the transformation with optional Jacobian computation. If a flag is False, the corresponding method does not need to be implemented.

  • All subclasses must implement the properties input_dim and output_dim to return the input and output dimensions of the transformation.

  • All subclasses must implement the property n_parameters to return the number of parameters \(n_p\) of the transformation (must not depend on the parameters array).

  • All subclasses must implement the method _to_dict, _from_dict, and _copy called by the public methods, from_dict, to_dict and copy will handle copying and the serialization and deserialization of the constants of the transformation.

  • All subclasses must set the capability flags described above, either as class attributes (if they do not depend on the constants) or as instance attributes before calling super().__init__() (if they depend on the constants).

  • Subclasses that cannot work without an optional package declare it in the class attribute _required_optionals (e.g. _required_optionals = ("pyzernike",)): an ImportError is raised when the class is instantiated if the package is missing, and the class method is_available() returns False (see pysdic._optionals.RequiresOptionalMixin).

Here is a minimal example of how to implement a simple subclass of pysdic.Transformation representing a 2D scaled translation \(\vec{x_o} = \mathbf{S} \vec{x_i} + \vec{p}\) with the translation \(\vec{p}\) as parameters and the diagonal scaling factors \(\mathbf{S} = \text{diag}(s_x, s_y)\) as constants:

class ScaledTranslation2D(Transformation):

    _has_apply = True
    _has_apply_dx = True
    _has_apply_dp = True
    _has_invert = True
    _has_invert_dx = True
    _has_invert_dp = True
    _is_left_invertible = True
    _is_right_invertible = True

    def __init__(
        self,
        parameters: Optional[ArrayLike] = None,
        scales: ArrayLike = (1.0, 1.0),
    ):
        scales = numpy.array(scales, dtype=float, copy=True)
        if scales.shape != (2,) or numpy.any(scales == 0.0):
            raise ValueError("scales must be 2 non-zero values to be invertible.")
        scales.flags.writeable = False
        self._scales = scales
        super().__init__(parameters=parameters)  # Check the flags and set the parameters

    @property
    def scales(self) -> numpy.ndarray:
        return self._scales  # Read-only constant

    @property
    def n_parameters(self) -> int:
        return 2  # translation in x and y

    @property
    def input_dim(self) -> int:
        return 2  # 2D input points

    @property
    def output_dim(self) -> int:
        return 2  # 2D output points

    def _to_dict(self) -> Dict[str, Any]:
        return {"scales": self.scales.tolist()}  # 'parameters' is added automatically

    @classmethod
    def _from_dict(cls, data: Dict[str, Any]) -> ScaledTranslation2D:
        return cls(parameters=data["parameters"], scales=data["scales"])

    def _copy(self) -> ScaledTranslation2D:
        return self.__class__(parameters=self.parameters, scales=self.scales)

    def _apply(self, x_i: numpy.ndarray, *, dx: bool = False, dp: bool = False, **kwargs):
        n_points = x_i.shape[0]
        x_o = x_i * self.scales + self.parameters  # (n_points, 2)
        jacobian_dx = numpy.tile(numpy.diag(self.scales), (n_points, 1, 1)) if dx else None  # (n_points, 2, 2)
        jacobian_dp = numpy.tile(numpy.eye(2), (n_points, 1, 1)) if dp else None  # (n_points, 2, 2)
        return x_o, jacobian_dx, jacobian_dp

    def _invert(self, x_o: numpy.ndarray, *, dx: bool = False, dp: bool = False, **kwargs):
        n_points = x_o.shape[0]
        x_i = (x_o - self.parameters) / self.scales  # (n_points, 2)
        jacobian_dx = numpy.tile(numpy.diag(1.0 / self.scales), (n_points, 1, 1)) if dx else None  # (n_points, 2, 2)
        jacobian_dp = numpy.tile(-numpy.diag(1.0 / self.scales), (n_points, 1, 1)) if dp else None  # (n_points, 2, 2)
        return x_i, jacobian_dx, jacobian_dp

The implementation can then be verified numerically:

T = ScaledTranslation2D(parameters=[1.0, 2.0], scales=[2.0, 3.0])
T.apply([[1.0, 1.0]]).x                              # array([[3., 5.]])
T.check_apply_dx([[1.0, 1.0]], raise_error=True)     # True
T.check_apply_dp([[1.0, 1.0]], raise_error=True)     # True
T.check_left_invertible([[1.0, 1.0]], check_dx=True, check_dp=True)  # True

Implemented methods and attributes#

The following sections provide an overview of the attributes and methods defined in the pysdic.Transformation class.

Attributes#

The pysdic.Transformation defines the following attributes:

Transformation.input_dim

[Get] the input dimension \(n_i\) of the transformation.

Transformation.is_locked

[Get] Whether the object is locked.

Transformation.is_setup

[Get] whether the transformation is fully set up and ready to be applied or inverted.

Transformation.locked_message

[Get] The reason why the object is locked.

Transformation.n_parameters

[Get] the number of parameters \(n_p\) of the transformation.

Transformation.output_dim

[Get] the output dimension \(n_o\) of the transformation.

Transformation.parameters

[Get] or [Set] the parameters of the transformation.

The capabilities of a transformation are exposed by the following read-only flags:

Transformation.has_apply

[Get] whether the transformation implements the apply method.

Transformation.has_apply_dx

[Get] whether the apply method can compute the Jacobian with respect to input points.

Transformation.has_apply_dp

[Get] whether the apply method can compute the Jacobian with respect to parameters.

Transformation.has_invert

[Get] whether the transformation implements the invert method.

Transformation.has_invert_dx

[Get] whether the invert method can compute the Jacobian with respect to output points.

Transformation.has_invert_dp

[Get] whether the invert method can compute the Jacobian with respect to parameters.

Transformation.is_invertible

[Get] whether the transformation is invertible (i.e. both left and right invertible).

Transformation.is_left_invertible

[Get] whether the invert method is a left inverse of the apply method.

Transformation.is_right_invertible

[Get] whether the invert method is a right inverse of the apply method.

Methods#

The pysdic.Transformation defines the following methods:

Transformation.copy()

Create a copy of the transformation.

Transformation.set_parameters(value, *[, ...])

Set the parameters of the transformation, with an option to override the lock.

Note

A locked transformation (see Transformation.is_locked) cannot be modified with Transformation.set_parameters() unless override_lock=True is given. The lock is managed internally by the objects that own the transformation.

Applying the transformation methods#

To perform the transformation from \(\mathbb{R}^{n_i}\) to \(\mathbb{R}^{n_o}\) (apply) or its inverse map from \(\mathbb{R}^{n_o}\) to \(\mathbb{R}^{n_i}\) (invert), use the following methods:

Transformation.apply(x_i, *[, dx, dp])

Apply the transformation to the given points \(\vec{x_i} \in \mathbb{R}^{n_i}\) to return the transformed points \(\vec{x_o} \in \mathbb{R}^{n_o}\).

Transformation.invert(x_o, *[, dx, dp])

Apply the inverse map \(T^{-1}\) to the given output points \(\vec{x_o} \in \mathbb{R}^{n_o}\) to return the corresponding input points \(\vec{x_i} \in \mathbb{R}^{n_i}\).

The output of the transformation is a pysdic.TransformationResult object, which contains the transformed points (x) and the Jacobian matrices with respect to the points (jacobian_dx) and to the parameters (jacobian_dp) if requested.

Note

You can also use the __call__ method to apply the transformation, which is an alias for the apply method: transformation(x_i).

Note

Two transformations can be composed with the syntax T2 @ T1, which is equivalent to ComposedTransformation([T1, T2]) (see pysdic.ComposedTransformation).

Numerical checks#

The implementation of a transformation (Jacobians and inverse map) can be verified numerically with the following methods:

Transformation.check_apply_dx(x_i, *[, eps, ...])

Check the Jacobian of the apply method with respect to the input points against central finite differences at the given input points \(\vec{x_i}\).

Transformation.check_apply_dp(x_i, *[, eps, ...])

Check the Jacobian of the apply method with respect to the parameters against central finite differences at the given input points \(\vec{x_i}\) and the current parameters \(\vec{p}\).

Transformation.check_invert_dx(x_o, *[, ...])

Check the Jacobian of the invert method with respect to the output points against central finite differences at the given output points \(\vec{x_o}\).

Transformation.check_invert_dp(x_o, *[, ...])

Check the Jacobian of the invert method with respect to the parameters against central finite differences at the given output points \(\vec{x_o}\) and the current parameters \(\vec{p}\).

Transformation.check_left_invertible(x_i, *)

Check numerically that the invert method is a left inverse of the apply method at the given input points \(\vec{x_i}\).

Transformation.check_right_invertible(x_o, *)

Check numerically that the invert method is a right inverse of the apply method at the given output points \(\vec{x_o}\).

Serialization methods#

The pysdic.Transformation inherits serialization methods from the following mixin classes:

See also

The documentation Serialization Mixins for more details on the available serialization methods and formats.

Transformation.from_dict(data)

Create a transformation instance from a dictionary.

Transformation.to_dict()

Serialize the transformation to a dictionary.