From 81fbd617f79465dcf780a0f3ee26e5464de21d5f Mon Sep 17 00:00:00 2001
From: Luc Maisonobe <luc@orekit.org>
Date: Wed, 25 Feb 2015 15:50:16 +0100
Subject: [PATCH] Attempt to find an escape solution in some inverse location
 cases.

---
 .../rugged/linesensor/SensorMeanPlaneCrossing.java       | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/src/main/java/org/orekit/rugged/linesensor/SensorMeanPlaneCrossing.java b/src/main/java/org/orekit/rugged/linesensor/SensorMeanPlaneCrossing.java
index ce2d0659..7357b189 100644
--- a/src/main/java/org/orekit/rugged/linesensor/SensorMeanPlaneCrossing.java
+++ b/src/main/java/org/orekit/rugged/linesensor/SensorMeanPlaneCrossing.java
@@ -308,17 +308,24 @@ public class SensorMeanPlaneCrossing {
         Transform scToInert   = midScToInert;
         boolean atMin         = false;
         boolean atMax         = false;
+        double deltaL         = Double.NaN;
         for (int i = 0; i < maxEval; ++i) {
 
             final FieldVector3D<DerivativeStructure> targetDirection =
                     evaluateLine(crossingLine, targetPV, bodyToInert, scToInert);
             final DerivativeStructure beta = FieldVector3D.angle(targetDirection, meanPlaneNormal);
 
-            final double deltaL = (0.5 * FastMath.PI - beta.getValue()) / beta.getPartialDerivative(1);
+            final double previousDeltaL = deltaL;
+            deltaL = (0.5 * FastMath.PI - beta.getValue()) / beta.getPartialDerivative(1);
             if (FastMath.abs(deltaL) <= accuracy) {
                 // return immediately, without doing any additional evaluation!
                 return new CrossingResult(sensor.getDate(crossingLine), crossingLine, targetDirection);
             }
+            if (FastMath.abs(deltaL + previousDeltaL) <= 0.01 * FastMath.abs(deltaL)) {
+                // we are stuck in a loop between two values!
+                // try to escape from the loop by targeting the middle point
+                deltaL = 0.5 * deltaL;
+            }
             crossingLine += deltaL;
 
             if (crossingLine < minLine) {
-- 
GitLab