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}\).
Transformation class#
- class Transformation(*args, **kwargs)[source]#
Bases:
LockableMixin,RequiresOptionalMixin,JsonSerializerMixin,Hdf5SerializerMixinAbstract 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
parametersare 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 apysdic.ReparametrizedTransformation). A locked transformation refusesparameters = ...andset_parameters(unlessoverride_lock=True):is_lockedandlocked_messagetell 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
applymethod, which returns apysdic.TransformationResultobject 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
invertmethod, which returns apysdic.TransformationResultobject 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
Class
pysdic.TransformationResultfor the result returned by theapplyandinvertmethods.
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_invertibleandis_right_invertiblebelow).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:
Class
pysdic.Parametrizationfor the parametrizations that can encode the parameters of a transformation.Class
pysdic.ReparametrizedTransformationto allow a transformation to be associated with a parametrization to encode its parameters.
See also
To compose transformations (ie \(T = T_2 \circ T_1\)), use the following classes:
Class
pysdic.ComposedTransformationto allow multiple transformations to be composed together.The syntax
T2 @ T1which is equivalent toComposedTransformation([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_applyis implemented (i.e. \(T\) can be evaluated)._has_apply_dx: the method_applycan compute \(\frac{\partial T}{\partial \vec{x_i}}\)._has_apply_dp: the method_applycan compute \(\frac{\partial T}{\partial \vec{p}}\)._has_invert: the method_invertis implemented (i.e. \(T^{-1}\) can be evaluated)._has_invert_dx: the method_invertcan compute \(\frac{\partial T^{-1}}{\partial \vec{x_o}}\)._has_invert_dp: the method_invertcan compute \(\frac{\partial T^{-1}}{\partial \vec{p}}\)._is_left_invertible:invertis a left inverse ofapply, i.e. \(T^{-1}(T(\vec{x_i})) = \vec{x_i}\) for all \(\vec{x_i} \in \mathbb{R}^{n_i}\)._is_right_invertible:invertis a right inverse ofapply, 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_dxand_has_apply_dprequire_has_apply._has_invert_dxand_has_invert_dprequire_has_invert._is_left_invertibleand_is_right_invertiblerequire both_has_applyand_has_invert.
The consistency is checked at initialization by
Transformation.__init__. The flags_is_left_invertibleand_is_right_invertibleare declarations that can be verified numerically with the methodscheck_left_invertibleandcheck_right_invertible.Implementation details#
All subclasses must have an
__init__method takingparametersas an argument and callingsuper().__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=Truemust implement the method_apply, and subclasses with_has_invert=Truemust implement the method_invert. These methods are called by the public methodsapplyandinvertrespectively, which handle the validation of the inputs and outputs of the transformation with optional Jacobian computation. If a flag isFalse, the corresponding method does not need to be implemented.All subclasses must implement the properties
input_dimandoutput_dimto return the input and output dimensions of the transformation.All subclasses must implement the property
n_parametersto 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_copycalled by the public methods,from_dict,to_dictandcopywill 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",)): anImportErroris raised when the class is instantiated if the package is missing, and the class methodis_available()returns False (seepysdic._optionals.RequiresOptionalMixin).
Here is a minimal example of how to implement a simple subclass of
pysdic.Transformationrepresenting 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:
[Get] the input dimension \(n_i\) of the transformation. |
|
[Get] Whether the object is locked. |
|
[Get] whether the transformation is fully set up and ready to be applied or inverted. |
|
[Get] The reason why the object is locked. |
|
[Get] the number of parameters \(n_p\) of the transformation. |
|
[Get] the output dimension \(n_o\) of the transformation. |
|
[Get] or [Set] the parameters of the transformation. |
The capabilities of a transformation are exposed by the following read-only flags:
[Get] whether the transformation implements the apply method. |
|
[Get] whether the apply method can compute the Jacobian with respect to input points. |
|
[Get] whether the apply method can compute the Jacobian with respect to parameters. |
|
[Get] whether the transformation implements the invert method. |
|
[Get] whether the invert method can compute the Jacobian with respect to output points. |
|
[Get] whether the invert method can compute the Jacobian with respect to parameters. |
|
[Get] whether the transformation is invertible (i.e. both left and right invertible). |
|
[Get] whether the invert method is a left inverse of the apply method. |
|
[Get] whether the invert method is a right inverse of the apply method. |
Methods#
The pysdic.Transformation defines the following methods:
Create a copy of the transformation. |
|
|
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:
|
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}\). |
|
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:
|
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}\). |
|
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}\). |
|
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}\). |
|
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}\). |
Check numerically that the invert method is a left inverse of the apply method at the given input points \(\vec{x_i}\). |
|
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.
|
Create a transformation instance from a dictionary. |
Serialize the transformation to a dictionary. |