pysdic.SDICCorrelationTerm#

SDICCorrelationTerm class#

class SDICCorrelationTerm(analysis, unknowns, integration_points, pairings, *, mode='rJ', gl_correction=None, gray_level_groups=None, weight=1.0, loss=None, loss_scale=1.0, filter_nans=True, sparse=True, use_cache=False)[source]#

The correlation term of a SDIC analysis: it optimizes jointly the displacements of the vertices of the mesh at the optimized frames and the parameters of transformations of the cameras of an analysis, by comparing the gray levels of material points between the views of several pairings. The pysolvegn.Term to give to pysolvegn.solve is the property term.

The term is built on an analysis and on a pysdic.SDICUnknowns (the optimized frames and transformations), both created by the user and shared with the other objects of the problem (pysdic.SDICTemporalRegularizationTerm, pysdic.SDICFixedParametrization). The unknowns are validated by the analysis (pysdic.SDICAnalysis.validate_unknowns()) at the creation of the term; use pysdic.check_same_problem() to check that all the objects of a problem share the same analysis and the same unknowns.

The same term covers the three usual problems of a SDIC analysis:

  • measurement: unknowns with optimized frames only (SDICUnknowns([1], [])), the cameras are fixed;

  • calibration: unknowns with optimized transformations only (SDICUnknowns([], [("extrinsic", 1)])), the displacements of all the frames are fixed;

  • joint optimization: both, to measure the displacements while refining some parameters of the cameras.

Residuals. The material points are given by integration points of the mesh (the same for all the pairings). For a pairing between the view \((f_1, v_1)\) and the view \((f_2, v_2)\) (see pysdic.Pairing), the residual of a point \(p\) (of weight \(w_p\)) and a channel is:

\[r_p = \sqrt{w_p} \left( [I_2 \circ P_2](\vec{X}_p + \vec{u}_{f_2}(\vec{X}_p)) - [I_1 \circ P_1](\vec{X}_p + \vec{u}_{f_1}(\vec{X}_p)) \right)\]

where \(P_1\), \(P_2\) are the projections of the cameras, \(I_1\), \(I_2\) the images of the views (see pysdic.View.image_project()) and \(\vec{u}_f(\vec{X}_p) = \sum_k N_k(\vec{\xi}_p) \vec{u}_{f,k}\) is interpolated from the displacements \(\vec{u}_{f,k}\) of the vertices with the shape functions \(N_k\) at the natural coordinates \(\vec{\xi}_p\) of the point. The weights \(\sqrt{w_p}\) make the cost an approximation of the integral of the squared gray level difference over the surface.

The residuals are stacked pairing by pairing, in Fortran order of \((N_p, C)\) for each pairing (row \(p + c N_p\), with \(C\) the number of channels of the images of the pairing).

Unknowns. The vector of unknowns is

\[\vec{p} = [\vec{p}_U, \vec{p}_T]\]
  • \(\vec{p}_U\): the displacements \((N_v, E)\) of the optimized frames of unknowns, each one flattened in Fortran order (all the \(x\) components, then all the \(y\) components, …) and concatenated in their order;

  • \(\vec{p}_T\): the parameters of the optimized transformations of unknowns, concatenated in their order.

The vectors are built by the analysis (pack(), unpack() and apply() of the term are pysdic.SDICAnalysis.pack_unknowns(), pysdic.SDICAnalysis.unpack_unknowns() and pysdic.SDICAnalysis.apply_unknowns() with unknowns):

  • without parametrization, the solver starts from the complete vector \(\vec{p}_0\) = analysis.pack_unknowns(unknowns), and the result is written with analysis.apply_unknowns(unknowns, result.parameters);

  • with a parametrization (e.g. pysdic.SDICFixedParametrization), the solver starts from the reduced vector \(\vec{q}_0\) = parametrization.reparametrized_pack(), and the result is written with parametrization.reparametrized_apply(result.parameters).

Warning

With a parametrization, always use parametrization.reparametrized_pack(), reparametrized_unpack(q) and reparametrized_apply(q): pack(), unpack() and apply() of the term (and the *_unknowns methods of the analysis) work on the complete vector \(\vec{p}\), not on the reduced vector \(\vec{q}\) of the solver.

Frames. The frames of the pairings that are not optimized are reference frames: their displacements are fixed during the optimization, and must be set when the term is created (see pysdic.SDICAnalysis.set_displacement() and pysdic.SDICAnalysis.set_zero_displacement()). They are read from the analysis at each evaluation: a displacement updated after the creation of the term (for example the result of a previous frame) is taken into account.

Immutability. The configuration of the term cannot be changed: with_unknowns(), with_pairings(), with_integration_points() and with_options() create a new term with the same configuration except the given changes (new caches and structures; the gray level groups given with gray_level_groups are shared). The objects of a problem must share the same analysis and unknowns objects: build the regularization and the parametrization on the same new unknowns (their with_unknowns), and check them with pysdic.check_same_problem().

State of the analysis. The term reads the analysis at each evaluation (displacements of the reference frames, parameters of the transformations), so it always reflects its current state. Its structure (mesh, views) cannot change (see pysdic.SDICAnalysis); a new analysis created with pysdic.SDICAnalysis.with_mesh() or pysdic.SDICAnalysis.with_views() needs a new term.

Integration points. The shape functions, the weights and the gray level neighborhoods of the integration points are computed once at the creation of the term (the neighborhoods can also be given, see gray_level_groups), and the integration points are locked (see pysdic.core.lockable.LockableMixin): they can still be used everywhere (for example by other terms) but not modified. Use a copy (integration_points.copy()) to get modifiable points.

Transformations. A transformation is given as a tuple (kind, index), with kind in "extrinsic", "distortion", "intrinsic" and index its index in the structure of its kind (see pysdic.SDICAnalysis.display_structure() and pysdic.SDICAnalysis.get_transformation()). A transformation is identified by its object: it can be used by several cameras (for example the same intrinsic for two views, or the same extrinsic at all the frames), and is then one unknown for all of them.

  • The optimized transformations must have parameters, must not be locked and must not be given twice.

  • The entries of the analysis must be independent: two different entries (kind, index) must not share a unit transformation (see pysdic.SDICAnalysis.check_consistency()).

  • Some parameters of a transformation can be kept fixed by building the cameras with a pysdic.ReparametrizedTransformation, which is then optimized.

  • At each evaluation, the parameters of the optimized transformations are set once for all the cameras that use them, then restored: the analysis is never modified by an evaluation. Apply the result with apply().

  • At each evaluation, the optimized transformations must still have parameters and must not have been locked after the creation of the term (an explicit error is raised otherwise).

Jacobian. For each view of a pairing, the Jacobian of its gray levels is:

with a sign \(-\) for the first view of the pairing and \(+\) for the second one. The contributions of a shared transformation, or of the same frame in a stereo pairing at an optimized frame, are summed in the same columns.

Pairings.

  • The pairings without unknown (no optimized frame and no optimized transformation in their views, e.g. between two reference frames for a measurement) are ignored.

  • Each optimized frame and each optimized transformation must appear in a (non-ignored) pairing.

  • The two views of a pairing must exist and have images with the same number of channels (see pysdic.SDICAnalysis.validate_pairing()).

  • The visibility of the points is not checked: the points hidden in a view still get the gray level of the image at their projection (see pysdic.compute_visibility() to remove them from the integration points).

Non-finite values. The points projected out of the ROI of an image (or out of the image) get non-finite gray levels or gradients. With filter_nans=True, the corresponding equations are set to zero (residual and Jacobian row) and a RuntimeWarning gives their number. An error is raised if all the equations are filtered.

Gray level corrections. The gray levels of the same material point can differ between two views (lighting, exposure, reflections, …). With gl_correction, an affine change of the gray levels is removed from the two views of each pairing before computing the residuals, with the mean \(m\) and the standard deviation \(s\) of groups of points (see pysdic.compute_gray_level_groups()):

  • "ZNSSD": both views are normalized, \(g' = \text{scale} \cdot (g - m) / s\) (see pysdic.znssd_correction()). Each pairing gets residuals of the same order of magnitude.

  • "matching": the second view is mapped onto the statistics of the first one, \(g_2' = \text{scale} \cdot ((g_2 - m_2) \, s_1 / s_2 + m_1)\) and \(g_1' = \text{scale} \cdot g_1\) (see pysdic.matching_correction()).

The groups only depend on the connectivity of the mesh and on the elements of the integration points. By default they are computed at the creation of the term (from gl_correction["neighborhood"]). When several terms are built with the same mesh and integration points (e.g. one term per frame), compute them once with pysdic.compute_gray_level_groups() and give them with gray_level_groups.

The derivative of the correction is either "approximate" (\(m\) and \(s\) constant, the Jacobians stay sparse) or "exact" (derivatives of \(m\) and \(s\) included, see pysdic.znssd_correction_exact() and pysdic.matching_correction_exact()). The exact derivative couples all the points of a group: with a global group ("neighborhood": None) it is dense and limited to small numbers of points.

Warning

With several pairings, the "matching" correction keeps the contrast of the first view of each pairing: the pairings no longer have the same weight in the optimization. Prefer "ZNSSD" when several pairings are combined.

Modes. The term can be built in two modes of pysolvegn:

  • "rJ": residuals \(\vec{r}\) and Jacobian \(J\) of all the equations. The robust losses of pysolvegn (loss, loss_scale) are available.

  • "gH": gradient \(J^T \vec{r}\), Hessian \(J^T J\) and cost \(\frac{1}{2} \|\vec{r}\|^2\) assembled pairing by pairing, without storing the full Jacobian (lower memory for many points). Only the "linear" loss is available.

Warning

Displacements and transformations are not always separable: for example, a rigid motion of the surface is equivalent to a rigid motion of the extrinsics of all the cameras. Optimize only the transformations that the pairings can determine (e.g. the extrinsic of the second camera relatively to the first one, with stereo pairings).

Parameters:
  • analysis (pysdic.SDICAnalysis) – The analysis. The displacements of the reference frames (the frames of the pairings that are not optimized) must be set.

  • unknowns (pysdic.SDICUnknowns) – The unknowns of the problem: the optimized frames and the optimized transformations (at least one of them), validated by the analysis.

  • integration_points (pysdic.IntegrationPoints) – The material points, all located in the mesh of the analysis (use remove_unlocated). Their weights weight the residuals (\(\sqrt{w_p}\)). They are locked by the term (not copied).

  • pairings (Sequence[pysdic.Pairing]) – The pairings of views to compare (a list or a tuple).

  • mode (str, optional (default: "rJ")) – The mode of the term, "rJ" or "gH".

  • gl_correction (Optional[Mapping[str, Any]], optional) –

    The gray level correction applied to the two views of each pairing, or None (default) for no correction. The keys (all optional) are:

    • "mode": "ZNSSD" (default, both views normalized) or "matching" (the second view mapped onto the first one).

    • "jacobian": "approximate" (default, constant statistics) or "exact".

    • "neighborhood": None (default, global statistics over all the points) or the size \(n \geq 0\) of the neighborhood of the elements for local statistics (0 for the element alone, 1 with the elements sharing a vertex, …).

    • "scale": the factor applied after the correction (strictly positive, default 1.0, e.g. 255 for readable gray levels).

  • gray_level_groups (Optional[pysdic.GrayLevelGroups], optional) – The groups of the gray level correction, computed once with pysdic.compute_gray_level_groups() for the same mesh and integration points, to share them between several terms. Requires gl_correction without the key "neighborhood" (the groups replace it). By default, the groups are computed by the term from gl_correction["neighborhood"].

  • weight (Real, optional (default: 1.0)) – The weight of the term in the pysolvegn problem.

  • loss (Optional[Union[str, Callable]], optional) – The loss function of the term (see pysolvegn.Term), only for the mode "rJ". None means "linear".

  • loss_scale (Real, optional (default: 1.0)) – The soft threshold of the loss function (strictly positive), in gray levels (after correction). Only for the mode "rJ".

  • filter_nans (bool, optional (default: True)) – If True, the equations with non-finite residuals or Jacobians are set to zero, with a RuntimeWarning.

  • sparse (bool, optional (default: True)) – If True, the Jacobian ("rJ") or the Hessian ("gH") is a scipy.sparse.csr_matrix, otherwise a dense array. Keep True when displacements are optimized; a dense array can be faster for a calibration with few parameters.

  • use_cache (bool, optional (default: False)) – The evaluation strategy of the functions of the term. If False, each function (residuals, Jacobian, …) computes only its own output, projecting the points again. If True, the first call for given parameters computes all the outputs of the mode at once (r and J, or g, H and the cost) and keeps them for the next calls with the same parameters: fewer projections, more memory. The cache key is a hash of the parameters, of the displacements of the reference frames and of the parameters of the transformations of the analysis that are not optimized. In addition, the projections of the reference views (views whose frame is not optimized and whose camera has no optimized transformation, e.g. the reference frame of a measurement) are kept between the evaluations: a reference view is projected again only when the displacement of its frame or the parameters of the transformations of its camera change. A change of the state of the analysis between two calls is never hidden by the caches. Only the parameters of the transformations are compared: their other attributes (e.g. the ellipse of a Zernike distortion) are fixed.

Raises:
  • TypeError – If an input has a wrong type (analysis must be a pysdic.SDICAnalysis and unknowns a pysdic.SDICUnknowns).

  • ValueError – If there is no unknown, the optimized frames or transformations are not used by the pairings, the pairings are not consistent, the integration points are not located in the mesh, a needed displacement is not set, a loss other than "linear" is used in mode "gH", an option of gl_correction is not valid, or gray_level_groups is given without gl_correction, with gl_correction["neighborhood"] or for other integration points.

  • IndexError – If a frame, a view or a transformation index does not exist.

Examples

Measurement. Measure the displacement of the frame 1 with two cameras, the frame 0 being the reference, then the frame 2 with new unknowns:

import pysolvegn
from pysdic import Pairing, SDICCorrelationTerm, SDICUnknowns

analysis.set_zero_displacement(0)
analysis.set_zero_displacement(1)  # Initial guess

unknowns = SDICUnknowns([1], [])
pairings = [Pairing(0, 0, 1, 0), Pairing(0, 1, 1, 1), Pairing.stereo(1, 0, 1)]
correlation = SDICCorrelationTerm(analysis, unknowns, integration_points, pairings,
                                  gl_correction={"mode": "ZNSSD", "scale": 255}, use_cache=True)

result = pysolvegn.solve(terms=[correlation.term], p0=analysis.pack_unknowns(unknowns), max_iteration=20)
analysis.apply_unknowns(unknowns, result.parameters)  # Displacement of the frame 1 written in the analysis

analysis.set_displacement(2, analysis.get_displacement(1))  # Initial guess of the frame 2
unknowns = SDICUnknowns([2], [])
correlation = correlation.with_unknowns(  # Unknowns and pairings changed together
    unknowns, pairings=[Pairing(0, 0, 2, 0), Pairing(0, 1, 2, 1), Pairing.stereo(2, 0, 1)]
)
result = pysolvegn.solve(terms=[correlation.term], p0=analysis.pack_unknowns(unknowns), max_iteration=20)
analysis.apply_unknowns(unknowns, result.parameters)

Calibration. Calibrate the extrinsic of the second camera of a stereo setup on the reference frame:

analysis.display_structure("extrinsic")  # Frame 0: [0, 1], ...
unknowns = SDICUnknowns([], [("extrinsic", 1)])
correlation = SDICCorrelationTerm(analysis, unknowns, integration_points, [Pairing.stereo(0, 0, 1)], sparse=False)
result = pysolvegn.solve(terms=[correlation.term], p0=analysis.pack_unknowns(unknowns), max_iteration=20)
analysis.apply_unknowns(unknowns, result.parameters)  # Updates all the cameras using the extrinsic

Shared gray level groups. Calibrate the distortion of each frame, the groups of the ZNSSD correction being computed once and shared by all the terms:

from pysdic import compute_gray_level_groups

groups = compute_gray_level_groups(analysis.mesh, integration_points, neighborhood=10)
correlation = None
for frame in frames:
    unknowns = SDICUnknowns([], [("distortion", index_of_the_distortion_of(frame))])
    pairings = [Pairing.stereo(frame, 0, 1)]
    if correlation is None:
        correlation = SDICCorrelationTerm(analysis, unknowns, integration_points, pairings,
                                          gl_correction={"mode": "ZNSSD"}, gray_level_groups=groups,
                                          sparse=False)
    else:
        correlation = correlation.with_unknowns(unknowns, pairings=pairings)
    result = pysolvegn.solve(terms=[correlation.term], p0=analysis.pack_unknowns(unknowns))
    analysis.apply_unknowns(unknowns, result.parameters)

Joint optimization. Measure the displacement of the frame 1 and refine the extrinsic of the second camera:

unknowns = SDICUnknowns([1], [("extrinsic", 1)])
pairings = [Pairing(0, 0, 1, 0), Pairing(0, 1, 1, 1), Pairing.stereo(0, 0, 1), Pairing.stereo(1, 0, 1)]
correlation = SDICCorrelationTerm(analysis, unknowns, integration_points, pairings)
result = pysolvegn.solve(terms=[correlation.term], p0=analysis.pack_unknowns(unknowns), max_iteration=20)
displacements, parameters = analysis.unpack_unknowns(unknowns, result.parameters)

Instantiation and new terms#

A SDICCorrelationTerm is created with the unknowns (a pysdic.SDICUnknowns created by the user), the integration points, the pairings and its options (mode, gray level correction, weight, loss, sparse matrices, caches). Its analysis is the analysis of the unknowns.

A term is immutable: the methods below create a new term with the same configuration except the given changes (new caches and structures; the gray level groups given with gray_level_groups are shared). The previous term stays valid on its own unknowns.

correlation_2 = correlation.with_unknowns(unknowns_2, pairings=pairings_2)  # Next frame
correlation_3 = correlation.with_options(weight=10.0, use_cache=True)

SDICCorrelationTerm.with_unknowns(unknowns, *)

A new term with other unknowns (e.g. the next frame of a measurement), the same integration points and options.

SDICCorrelationTerm.with_pairings(pairings)

A new term with other pairings, the same unknowns, integration points and options.

SDICCorrelationTerm.with_integration_points(...)

A new term with other integration points, the same unknowns, pairings and options.

SDICCorrelationTerm.with_options(**changes)

A new term with the same unknowns, integration points and pairings, and other options (any keyword parameter of the constructor), e.g. with_options(weight=10.0, use_cache=True).

Term and unknowns#

SDICCorrelationTerm.pack(), SDICCorrelationTerm.unpack() and SDICCorrelationTerm.apply() are those of SDICCorrelationTerm.unknowns: they work on the complete vector \(\vec{p}\) (total displacements).

Warning

With a parametrization, always use parametrization.reparametrized_pack(), reparametrized_unpack(q) and reparametrized_apply(q) on the vectors of the solver (see pysdic.SDICFixedParametrization).

SDICCorrelationTerm.term

The pysolvegn.Term, to give to pysolvegn.solve.

SDICCorrelationTerm.unknowns

The unknowns of the problem (given at the creation, shared with the other objects of the problem).

SDICCorrelationTerm.analysis

The analysis (given at the creation, shared with the other objects of the problem).

SDICCorrelationTerm.n_unknowns

The number of unknowns.

SDICCorrelationTerm.pack()

The complete vector of unknowns of the current state of the analysis: the initial parameters p0 without parametrization, see pysdic.SDICAnalysis.pack_unknowns().

SDICCorrelationTerm.unpack(parameters)

Split a complete vector of unknowns, see pysdic.SDICAnalysis.unpack_unknowns().

SDICCorrelationTerm.apply(parameters)

Write a complete vector of unknowns in the analysis, see pysdic.SDICAnalysis.apply_unknowns().

Residuals#

SDICCorrelationTerm.compute_residuals([...])

Compute the gray levels and the residuals of the integration points of the term in the views of pairings, for a vector of unknowns: what the term compares, with its gray level correction, without the weights of the points and without filtering the non-finite values (see pysdic.PairingResiduals).

Configuration#

Read-only properties (see the with_* methods to create a term with other values).

SDICCorrelationTerm.integration_points

The integration points (locked).

SDICCorrelationTerm.pairings

The pairings, including those without unknown (ignored by the term).

SDICCorrelationTerm.optimized_frames

The optimized frames of the unknowns.

SDICCorrelationTerm.optimized_transformations

The optimized transformations (kind, index) of the unknowns.

SDICCorrelationTerm.options

the keyword parameters of the constructor.

SDICCorrelationTerm.mode

The mode, "rJ" or "gH".

SDICCorrelationTerm.gl_correction

The gray level correction as given (a copy), or None.

SDICCorrelationTerm.gray_level_groups

The gray level groups given at the creation, or None.

SDICCorrelationTerm.weight

The weight of the term in the pysolvegn problem.

SDICCorrelationTerm.loss

The loss function of the term (mode "rJ").

SDICCorrelationTerm.loss_scale

The soft threshold of the loss function.

SDICCorrelationTerm.filter_nans

Whether the non-finite equations are set to zero.

SDICCorrelationTerm.sparse

Whether the Jacobian ("rJ") or the Hessian ("gH") is sparse.

SDICCorrelationTerm.use_cache

Whether the caches of the operators and of the reference projections are used.