View Javadoc
1   /*
2    * Copyright (C) 2015 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.estimators;
17  
18  import com.irurueta.geometry.CoincidentLinesException;
19  import com.irurueta.geometry.DualConic;
20  import com.irurueta.geometry.Line2D;
21  import com.irurueta.numerical.robust.LMedSRobustEstimator;
22  import com.irurueta.numerical.robust.LMedSRobustEstimatorListener;
23  import com.irurueta.numerical.robust.RobustEstimator;
24  import com.irurueta.numerical.robust.RobustEstimatorException;
25  import com.irurueta.numerical.robust.RobustEstimatorMethod;
26  
27  import java.util.List;
28  
29  /**
30   * Finds the best dual conic for provided collection of 2D lines using LMedS
31   * algorithm.
32   */
33  @SuppressWarnings("DuplicatedCode")
34  public class LMedSDualConicRobustEstimator extends DualConicRobustEstimator {
35      /**
36       * Default value to be used for stop threshold. Stop threshold can be used
37       * to keep the algorithm iterating in case that best estimated threshold
38       * using median of residuals is not small enough. Once a solution is found
39       * that generates a threshold below this value, the algorithm will stop.
40       * The stop threshold can be used to prevent the LMedS algorithm iterating
41       * too many times in cases where samples have a very similar accuracy.
42       * For instance, in cases where proportion of outliers is very small (close
43       * to 0%), and samples are very accurate (i.e. 1e-6), the algorithm would
44       * iterate for a long time trying to find the best solution when indeed
45       * there is no need to do that if a reasonable threshold has already been
46       * reached.
47       * Because of this behaviour the stop threshold can be set to a value much
48       * lower than the one typically used in RANSAC, and yet the algorithm could
49       * still produce even smaller thresholds in estimated results.
50       */
51      public static final double DEFAULT_STOP_THRESHOLD = 1e-9;
52  
53      /**
54       * Minimum allowed stop threshold value.
55       */
56      public static final double MIN_STOP_THRESHOLD = 0.0;
57  
58      /**
59       * Threshold to be used to keep the algorithm iterating in case that best
60       * estimated threshold using median of residuals is not small enough. Once
61       * a solution is found that generates a threshold below this value, the
62       * algorithm will stop.
63       * The stop threshold can be used to prevent the LMedS algorithm iterating
64       * too many times in cases where samples have a very similar accuracy.
65       * For instance, in cases where proportion of outliers is very small (close
66       * to 0%), and samples are very accurate (i.e. 1e-6), the algorithm would
67       * iterate for a long time trying to find the best solution when indeed
68       * there is no need to do that if a reasonable threshold has already been
69       * reached.
70       * Because of this behaviour the stop threshold can be set to a value much
71       * lower than the one typically used in RANSAC, and yet the algorithm could
72       * still produce even smaller thresholds in estimated results.
73       */
74      private double stopThreshold;
75  
76      /**
77       * Constructor.
78       */
79      public LMedSDualConicRobustEstimator() {
80          super();
81          stopThreshold = DEFAULT_STOP_THRESHOLD;
82      }
83  
84      /**
85       * Constructor with points.
86       *
87       * @param lines 2D lines to estimate a dual conic.
88       * @throws IllegalArgumentException if provided list of lines don't have
89       *                                  a size greater or equal than MINIMUM_SIZE.
90       */
91      public LMedSDualConicRobustEstimator(final List<Line2D> lines) {
92          super(lines);
93          stopThreshold = DEFAULT_STOP_THRESHOLD;
94      }
95  
96      /**
97       * Constructor.
98       *
99       * @param listener listener to be notified of events such as when estimation
100      *                 starts, ends or its progress significantly changes.
101      */
102     public LMedSDualConicRobustEstimator(final DualConicRobustEstimatorListener listener) {
103         super(listener);
104         stopThreshold = DEFAULT_STOP_THRESHOLD;
105     }
106 
107     /**
108      * Constructor.
109      *
110      * @param listener listener to be notified of events such as when estimation
111      *                 starts, ends or its progress significantly changes.
112      * @param lines    2D lines to estimate a dual conic.
113      * @throws IllegalArgumentException if provided list of lines don't have a
114      *                                  size greater or equal than MINIMUM_SIZE.
115      */
116     public LMedSDualConicRobustEstimator(
117             final DualConicRobustEstimatorListener listener, final List<Line2D> lines) {
118         super(listener, lines);
119         stopThreshold = DEFAULT_STOP_THRESHOLD;
120     }
121 
122     /**
123      * Returns threshold to be used to keep the algorithm iterating in case that
124      * best estimated threshold using median of residuals is not small enough.
125      * Once a solution is found that generates a threshold below this value, the
126      * algorithm will stop.
127      * The stop threshold can be used to prevent the LMedS algorithm iterating
128      * too many times in cases where samples have a very similar accuracy.
129      * For instance, in cases where proportion of outliers is very small (close
130      * to 0%), and samples are very accurate (i.e. 1e-6), the algorithm would
131      * iterate for a long time trying to find the best solution when indeed
132      * there is no need to do that if a reasonable threshold has already been
133      * reached.
134      * Because of this behaviour the stop threshold can be set to a value much
135      * lower than the one typically used in RANSAC, and yet the algorithm could
136      * still produce even smaller thresholds in estimated results.
137      *
138      * @return stop threshold to stop the algorithm prematurely when a certain
139      * accuracy has been reached.
140      */
141     public double getStopThreshold() {
142         return stopThreshold;
143     }
144 
145     /**
146      * Sets threshold to be used to keep the algorithm iterating in case that
147      * best estimated threshold using median of residuals is not small enough.
148      * Once a solution is found that generates a threshold below this value, the
149      * algorithm will stop.
150      * The stop threshold can be used to prevent the LMedS algorithm iterating
151      * too many times in cases where samples have a very similar accuracy.
152      * For instance, in cases where proportion of outliers is very small (close
153      * to 0%), and samples are very accurate (i.e. 1e-6), the algorithm would
154      * iterate for a long time trying to find the best solution when indeed
155      * there is no need to do that if a reasonable threshold has already been
156      * reached.
157      * Because of this behaviour the stop threshold can be set to a value much
158      * lower than the one typically used in RANSAC, and yet the algorithm could
159      * still produce even smaller thresholds in estimated results.
160      *
161      * @param stopThreshold stop threshold to stop the algorithm prematurely
162      *                      when a certain accuracy has been reached.
163      * @throws IllegalArgumentException if provided value is zero or negative.
164      * @throws LockedException          if robust estimator is locked because an
165      *                                  estimation is already in progress.
166      */
167     public void setStopThreshold(final double stopThreshold) throws LockedException {
168         if (isLocked()) {
169             throw new LockedException();
170         }
171         if (stopThreshold <= MIN_STOP_THRESHOLD) {
172             throw new IllegalArgumentException();
173         }
174 
175         this.stopThreshold = stopThreshold;
176     }
177 
178     /**
179      * Estimates a dual conic using a robust estimator and the best set of 2D
180      * lines that fit into the locus of the estimated dual conic found using the
181      * robust estimator.
182      *
183      * @return a dual conic.
184      * @throws LockedException          if robust estimator is locked because an
185      *                                  estimation is already in progress.
186      * @throws NotReadyException        if provided input data is not enough to start
187      *                                  the estimation.
188      * @throws RobustEstimatorException if estimation fails for any reason
189      *                                  (i.e. numerical instability, no solution available, etc).
190      */
191     @Override
192     public DualConic estimate() throws LockedException, NotReadyException, RobustEstimatorException {
193         if (isLocked()) {
194             throw new LockedException();
195         }
196         if (!isReady()) {
197             throw new NotReadyException();
198         }
199 
200         final var innerEstimator = new LMedSRobustEstimator<>(new LMedSRobustEstimatorListener<DualConic>() {
201 
202             @Override
203             public int getTotalSamples() {
204                 return lines.size();
205             }
206 
207             @Override
208             public int getSubsetSize() {
209                 return DualConicRobustEstimator.MINIMUM_SIZE;
210             }
211 
212             @Override
213             public void estimatePreliminarSolutions(final int[] samplesIndices, final List<DualConic> solutions) {
214                 final var line1 = lines.get(samplesIndices[0]);
215                 final var line2 = lines.get(samplesIndices[1]);
216                 final var line3 = lines.get(samplesIndices[2]);
217                 final var line4 = lines.get(samplesIndices[3]);
218                 final var line5 = lines.get(samplesIndices[4]);
219 
220                 try {
221                     final var dualConic = new DualConic(line1, line2, line3, line4, line5);
222                     solutions.add(dualConic);
223                 } catch (final CoincidentLinesException e) {
224                     // if points are coincident, no solution is added
225                 }
226             }
227 
228             @Override
229             public double computeResidual(final DualConic currentEstimation, final int i) {
230                 return residual(currentEstimation, lines.get(i));
231             }
232 
233             @Override
234             public boolean isReady() {
235                 return LMedSDualConicRobustEstimator.this.isReady();
236             }
237 
238             @Override
239             public void onEstimateStart(final RobustEstimator<DualConic> estimator) {
240                 if (listener != null) {
241                     listener.onEstimateStart(LMedSDualConicRobustEstimator.this);
242                 }
243             }
244 
245             @Override
246             public void onEstimateEnd(final RobustEstimator<DualConic> estimator) {
247                 if (listener != null) {
248                     listener.onEstimateEnd(LMedSDualConicRobustEstimator.this);
249                 }
250             }
251 
252             @Override
253             public void onEstimateNextIteration(final RobustEstimator<DualConic> estimator, final int iteration) {
254                 if (listener != null) {
255                     listener.onEstimateNextIteration(LMedSDualConicRobustEstimator.this, iteration);
256                 }
257             }
258 
259             @Override
260             public void onEstimateProgressChange(final RobustEstimator<DualConic> estimator, final float progress) {
261                 if (listener != null) {
262                     listener.onEstimateProgressChange(LMedSDualConicRobustEstimator.this, progress);
263                 }
264             }
265         });
266 
267         try {
268             locked = true;
269             innerEstimator.setConfidence(confidence);
270             innerEstimator.setMaxIterations(maxIterations);
271             innerEstimator.setProgressDelta(progressDelta);
272             innerEstimator.setStopThreshold(stopThreshold);
273             return innerEstimator.estimate();
274         } catch (final com.irurueta.numerical.LockedException e) {
275             throw new LockedException(e);
276         } catch (final com.irurueta.numerical.NotReadyException e) {
277             throw new NotReadyException(e);
278         } finally {
279             locked = false;
280         }
281     }
282 
283     /**
284      * Returns method being used for robust estimation.
285      *
286      * @return method being used for robust estimation.
287      */
288     @Override
289     public RobustEstimatorMethod getMethod() {
290         return RobustEstimatorMethod.LMEDS;
291     }
292 }