View Javadoc
1   /*
2    * Copyright (C) 2017 Alberto Irurueta Carro (alberto@irurueta.com)
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *         http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package com.irurueta.geometry.refiners;
17  
18  import com.irurueta.algebra.AlgebraException;
19  import com.irurueta.algebra.Matrix;
20  import com.irurueta.geometry.AffineTransformation3D;
21  import com.irurueta.geometry.Plane;
22  import com.irurueta.geometry.estimators.LockedException;
23  import com.irurueta.geometry.estimators.NotReadyException;
24  import com.irurueta.numerical.EvaluationException;
25  import com.irurueta.numerical.GradientEstimator;
26  import com.irurueta.numerical.fitting.LevenbergMarquardtMultiDimensionFitter;
27  import com.irurueta.numerical.fitting.LevenbergMarquardtMultiDimensionFunctionEvaluator;
28  import com.irurueta.numerical.robust.InliersData;
29  
30  import java.util.BitSet;
31  import java.util.List;
32  
33  /**
34   * A 3D affine transformation refiner using plane correspondences.
35   * This class takes into account an initial estimation, inlier line matches
36   * and their residuals to find a solution that minimizes error of inliers in
37   * LMSE terms.
38   * Typically, a refiner is used by a robust estimator, however it can also be
39   * useful in some other situations.
40   */
41  @SuppressWarnings("DuplicatedCode")
42  public class PlaneCorrespondenceAffineTransformation3DRefiner extends AffineTransformation3DRefiner<Plane, Plane> {
43  
44      /**
45       * Plane to be reused when computing residuals.
46       */
47      private final Plane residualTestPlane = new Plane();
48  
49      /**
50       * Constructor.
51       */
52      public PlaneCorrespondenceAffineTransformation3DRefiner() {
53      }
54  
55      /**
56       * Constructor.
57       *
58       * @param initialEstimation           initial estimation to be set.
59       * @param keepCovariance              true if covariance of estimation must be kept after
60       *                                    refinement, false otherwise.
61       * @param inliers                     set indicating which of the provided matches are inliers.
62       * @param residuals                   residuals for matched samples.
63       * @param numInliers                  number of inliers on initial estimation.
64       * @param samples1                    1st set of paired samples.
65       * @param samples2                    2nd set of paired samples.
66       * @param refinementStandardDeviation standard deviation used for
67       *                                    Levenberg-Marquardt fitting.
68       */
69      public PlaneCorrespondenceAffineTransformation3DRefiner(
70              final AffineTransformation3D initialEstimation, final boolean keepCovariance,
71              final BitSet inliers, final double[] residuals, final int numInliers, final List<Plane> samples1,
72              final List<Plane> samples2, final double refinementStandardDeviation) {
73          super(initialEstimation, keepCovariance, inliers, residuals, numInliers, samples1, samples2,
74                  refinementStandardDeviation);
75      }
76  
77      /**
78       * Constructor.
79       *
80       * @param initialEstimation           initial estimation to be set.
81       * @param keepCovariance              true if covariance of estimation must be kept after
82       *                                    refinement, false otherwise.
83       * @param inliersData                 inlier data, typically obtained from a robust
84       *                                    estimator.
85       * @param samples1                    1st set of paired samples.
86       * @param samples2                    2nd set of paired samples.
87       * @param refinementStandardDeviation standard deviation used for
88       *                                    Levenberg-Marquardt fitting.
89       */
90      public PlaneCorrespondenceAffineTransformation3DRefiner(
91              final AffineTransformation3D initialEstimation, final boolean keepCovariance, final InliersData inliersData,
92              final List<Plane> samples1, final List<Plane> samples2, final double refinementStandardDeviation) {
93          super(initialEstimation, keepCovariance, inliersData, samples1, samples2, refinementStandardDeviation);
94      }
95  
96      /**
97       * Refines provided initial estimation.
98       * This method always sets a value into provided result instance regardless
99       * of the fact that error has actually improved in LMSE terms or not.
100      *
101      * @param result instance where refined estimation will be stored.
102      * @return true if result improves (error decreases) in LMSE terms respect
103      * to initial estimation, false if no improvement has been achieved.
104      * @throws NotReadyException if not enough input data has been provided.
105      * @throws LockedException   if estimator is locked because refinement is
106      *                           already in progress.
107      * @throws RefinerException  if refinement fails for some reason (e.g. unable
108      *                           to converge to a result).
109      */
110     @Override
111     public boolean refine(final AffineTransformation3D result) throws NotReadyException, LockedException,
112             RefinerException {
113         if (isLocked()) {
114             throw new LockedException();
115         }
116         if (!isReady()) {
117             throw new NotReadyException();
118         }
119 
120         locked = true;
121 
122         if (listener != null) {
123             listener.onRefineStart(this, initialEstimation);
124         }
125 
126         final var initialTotalResidual = totalResidual(initialEstimation);
127 
128         try {
129             final var initParams = new double[AffineTransformation3D.INHOM_COORDS * AffineTransformation3D.INHOM_COORDS
130                     + AffineTransformation3D.NUM_TRANSLATION_COORDS];
131             // copy values for A matrix
132             System.arraycopy(initialEstimation.getA().getBuffer(), 0, initParams, 0,
133                     AffineTransformation3D.INHOM_COORDS * AffineTransformation3D.INHOM_COORDS);
134             // copy values for translation
135             System.arraycopy(initialEstimation.getTranslation(), 0, initParams,
136                     AffineTransformation3D.INHOM_COORDS * AffineTransformation3D.INHOM_COORDS,
137                     AffineTransformation3D.NUM_TRANSLATION_COORDS);
138 
139             // output values to be fitted/optimized will contain residuals
140             final var y = new double[numInliers];
141             // input values will contain 2 sets of 2D points to compute residuals
142             final var nDims = 2 * Plane.PLANE_NUMBER_PARAMS;
143             final var x = new Matrix(numInliers, nDims);
144             final var nSamples = inliers.length();
145             var pos = 0;
146             for (var i = 0; i < nSamples; i++) {
147                 if (inliers.get(i)) {
148                     // sample is inlier
149                     final var inputPlane = samples1.get(i);
150                     final var outputPlane = samples2.get(i);
151                     inputPlane.normalize();
152                     outputPlane.normalize();
153                     x.setElementAt(pos, 0, inputPlane.getA());
154                     x.setElementAt(pos, 1, inputPlane.getB());
155                     x.setElementAt(pos, 2, inputPlane.getC());
156                     x.setElementAt(pos, 3, inputPlane.getD());
157                     x.setElementAt(pos, 4, outputPlane.getA());
158                     x.setElementAt(pos, 5, outputPlane.getB());
159                     x.setElementAt(pos, 6, outputPlane.getC());
160                     x.setElementAt(pos, 7, outputPlane.getD());
161 
162                     y[pos] = residuals[i];
163                     pos++;
164                 }
165             }
166 
167             final var evaluator = new LevenbergMarquardtMultiDimensionFunctionEvaluator() {
168 
169                 private final Plane inputPlane = new Plane();
170 
171                 private final Plane outputPlane = new Plane();
172 
173                 private final AffineTransformation3D transformation = new AffineTransformation3D();
174 
175                 private final GradientEstimator gradientEstimator = new GradientEstimator(params -> {
176                     // copy values for A matrix
177                     System.arraycopy(params, 0, transformation.getA().getBuffer(), 0,
178                             AffineTransformation3D.INHOM_COORDS * AffineTransformation3D.INHOM_COORDS);
179                     // copy values for translation
180                     System.arraycopy(params,
181                             AffineTransformation3D.INHOM_COORDS * AffineTransformation3D.INHOM_COORDS,
182                             transformation.getTranslation(), 0, AffineTransformation3D.NUM_TRANSLATION_COORDS);
183 
184                     return residual(transformation, inputPlane, outputPlane);
185                 });
186 
187                 @Override
188                 public int getNumberOfDimensions() {
189                     return nDims;
190                 }
191 
192                 @Override
193                 public double[] createInitialParametersArray() {
194                     return initParams;
195                 }
196 
197                 @Override
198                 public double evaluate(final int i, final double[] point, final double[] params,
199                                        final double[] derivatives) throws EvaluationException {
200                     inputPlane.setParameters(point[0], point[1], point[2], point[3]);
201                     outputPlane.setParameters(point[4], point[5], point[6], point[7]);
202 
203                     // copy values for A matrix
204                     System.arraycopy(params, 0, transformation.getA().getBuffer(), 0,
205                             AffineTransformation3D.INHOM_COORDS * AffineTransformation3D.INHOM_COORDS);
206                     // copy values for translation
207                     System.arraycopy(params,
208                             AffineTransformation3D.INHOM_COORDS * AffineTransformation3D.INHOM_COORDS,
209                             transformation.getTranslation(), 0, AffineTransformation3D.NUM_TRANSLATION_COORDS);
210 
211                     final var y = residual(transformation, inputPlane, outputPlane);
212                     gradientEstimator.gradient(params, derivatives);
213 
214                     return y;
215                 }
216             };
217 
218             final var fitter = new LevenbergMarquardtMultiDimensionFitter(evaluator, x, y,
219                     getRefinementStandardDeviation());
220 
221             fitter.fit();
222 
223             // obtain estimated params
224             final var params = fitter.getA();
225 
226             // update transformation
227 
228             // copy values for A matrix
229             System.arraycopy(params, 0, result.getA().getBuffer(), 0,
230                     AffineTransformation3D.INHOM_COORDS * AffineTransformation3D.INHOM_COORDS);
231             // copy values for translation
232             System.arraycopy(params, AffineTransformation3D.INHOM_COORDS * AffineTransformation3D.INHOM_COORDS,
233                     result.getTranslation(), 0, AffineTransformation3D.NUM_TRANSLATION_COORDS);
234 
235             if (keepCovariance) {
236                 // keep covariance
237                 covariance = fitter.getCovar();
238             }
239 
240             final var finalTotalResidual = totalResidual(result);
241             final var errorDecreased = finalTotalResidual < initialTotalResidual;
242 
243             if (listener != null) {
244                 listener.onRefineEnd(this, initialEstimation, result, errorDecreased);
245             }
246 
247             return errorDecreased;
248 
249         } catch (final Exception e) {
250             throw new RefinerException(e);
251         } finally {
252             locked = false;
253         }
254     }
255 
256     /**
257      * Computes the residual between the affine transformation and a pair of
258      * matched planes.
259      *
260      * @param transformation a transformation.
261      * @param inputPlane     input 3D plane.
262      * @param outputPlane    output 3D plane.
263      * @return residual.
264      */
265     private double residual(final AffineTransformation3D transformation, final Plane inputPlane,
266                             final Plane outputPlane) {
267         try {
268             inputPlane.normalize();
269             outputPlane.normalize();
270 
271             transformation.transform(inputPlane, residualTestPlane);
272             return 1.0 - Math.abs(outputPlane.dotProduct(residualTestPlane));
273         } catch (final AlgebraException e) {
274             return 1.0;
275         }
276     }
277 
278     /**
279      * Computes total residual among all provided inlier samples.
280      *
281      * @param transformation a transformation.
282      * @return total residual.
283      */
284     private double totalResidual(final AffineTransformation3D transformation) {
285         var result = 0.0;
286 
287         final var nSamples = inliers.length();
288         for (var i = 0; i < nSamples; i++) {
289             if (inliers.get(i)) {
290                 // sample is inlier
291                 final var inputPlane = samples1.get(i);
292                 final var outputPlane = samples2.get(i);
293                 inputPlane.normalize();
294                 outputPlane.normalize();
295                 result += residual(transformation, inputPlane, outputPlane);
296             }
297         }
298 
299         return result;
300     }
301 }