PositionAngleDetector.java

  1. /* Copyright 2002-2025 CS GROUP
  2.  * Licensed to CS GROUP (CS) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * CS licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *   http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.orekit.propagation.events;

  18. import java.util.function.Function;

  19. import org.hipparchus.analysis.UnivariateFunction;
  20. import org.hipparchus.analysis.solvers.BracketingNthOrderBrentSolver;
  21. import org.hipparchus.util.FastMath;
  22. import org.hipparchus.util.MathUtils;
  23. import org.orekit.errors.OrekitIllegalArgumentException;
  24. import org.orekit.errors.OrekitMessages;
  25. import org.orekit.orbits.CircularOrbit;
  26. import org.orekit.orbits.EquinoctialOrbit;
  27. import org.orekit.orbits.KeplerianOrbit;
  28. import org.orekit.orbits.Orbit;
  29. import org.orekit.orbits.OrbitType;
  30. import org.orekit.orbits.PositionAngleType;
  31. import org.orekit.propagation.SpacecraftState;
  32. import org.orekit.propagation.events.handlers.EventHandler;
  33. import org.orekit.propagation.events.handlers.StopOnEvent;
  34. import org.orekit.time.AbsoluteDate;
  35. import org.orekit.utils.TimeSpanMap;

  36. /** Detector for in-orbit position angle.
  37.  * <p>
  38.  * The detector is based on anomaly for {@link OrbitType#KEPLERIAN Keplerian}
  39.  * orbits, latitude argument for {@link OrbitType#CIRCULAR circular} orbits,
  40.  * or longitude argument for {@link OrbitType#EQUINOCTIAL equinoctial} orbits.
  41.  * It does not support {@link OrbitType#CARTESIAN Cartesian} orbits. The
  42.  * angles can be either {@link PositionAngleType#TRUE true}, {@link PositionAngleType#MEAN
  43.  * mean} or {@link PositionAngleType#ECCENTRIC eccentric} angles.
  44.  * </p>
  45.  * @author Luc Maisonobe
  46.  * @since 7.1
  47.  */
  48. public class PositionAngleDetector extends AbstractDetector<PositionAngleDetector> {

  49.     /** Orbit type defining the angle type. */
  50.     private final OrbitType orbitType;

  51.     /** Type of position angle. */
  52.     private final PositionAngleType positionAngleType;

  53.     /** Fixed angle to be crossed. */
  54.     private final double angle;

  55.     /** Position angle extraction function. */
  56.     private final Function<Orbit, Double> positionAngleExtractor;

  57.     /** Estimators for the offset angle, taking care of 2π wrapping and g function continuity. */
  58.     private TimeSpanMap<OffsetEstimator> offsetEstimators;

  59.     /** Build a new detector.
  60.      * <p>The new instance uses default values for maximal checking interval
  61.      * ({@link #DEFAULT_MAX_CHECK}) and convergence threshold ({@link
  62.      * #DEFAULT_THRESHOLD}).</p>
  63.      * @param orbitType orbit type defining the angle type
  64.      * @param positionAngleType type of position angle
  65.      * @param angle fixed angle to be crossed
  66.      * @exception OrekitIllegalArgumentException if orbit type is {@link OrbitType#CARTESIAN}
  67.      */
  68.     public PositionAngleDetector(final OrbitType orbitType, final PositionAngleType positionAngleType,
  69.                                  final double angle)
  70.         throws OrekitIllegalArgumentException {
  71.         this(DEFAULT_MAX_CHECK, DEFAULT_THRESHOLD, orbitType, positionAngleType, angle);
  72.     }

  73.     /** Build a detector.
  74.      * <p> This instance uses by default the {@link StopOnEvent} handler </p>
  75.      * @param maxCheck maximal checking interval (s)
  76.      * @param threshold convergence threshold (s)
  77.      * @param orbitType orbit type defining the angle type
  78.      * @param positionAngleType type of position angle
  79.      * @param angle fixed angle to be crossed
  80.      * @exception OrekitIllegalArgumentException if orbit type is {@link OrbitType#CARTESIAN}
  81.      */
  82.     public PositionAngleDetector(final double maxCheck, final double threshold,
  83.                                  final OrbitType orbitType, final PositionAngleType positionAngleType,
  84.                                  final double angle)
  85.         throws OrekitIllegalArgumentException {
  86.         this(new EventDetectionSettings(maxCheck, threshold, DEFAULT_MAX_ITER), new StopOnEvent(),
  87.              orbitType, positionAngleType, angle);
  88.     }

  89.     /** Protected constructor with full parameters.
  90.      * <p>
  91.      * This constructor is not public as users are expected to use the builder
  92.      * API with the various {@code withXxx()} methods to set up the instance
  93.      * in a readable manner without using a huge amount of parameters.
  94.      * </p>
  95.      * @param detectionSettings event detection settings
  96.      * @param handler event handler to call at event occurrences
  97.      * @param orbitType orbit type defining the angle type
  98.      * @param positionAngleType type of position angle
  99.      * @param angle fixed angle to be crossed
  100.      * @exception OrekitIllegalArgumentException if orbit type is {@link OrbitType#CARTESIAN}
  101.      * @since 13.0
  102.      */
  103.     protected PositionAngleDetector(final EventDetectionSettings detectionSettings, final EventHandler handler,
  104.                                     final OrbitType orbitType, final PositionAngleType positionAngleType,
  105.                                     final double angle)
  106.         throws OrekitIllegalArgumentException {

  107.         super(detectionSettings, handler);

  108.         this.orbitType        = orbitType;
  109.         this.positionAngleType = positionAngleType;
  110.         this.angle            = angle;
  111.         this.offsetEstimators = null;

  112.         switch (orbitType) {
  113.             case KEPLERIAN:
  114.                 positionAngleExtractor = o -> ((KeplerianOrbit) orbitType.convertType(o)).getAnomaly(positionAngleType);
  115.                 break;
  116.             case CIRCULAR:
  117.                 positionAngleExtractor = o -> ((CircularOrbit) orbitType.convertType(o)).getAlpha(positionAngleType);
  118.                 break;
  119.             case EQUINOCTIAL:
  120.                 positionAngleExtractor = o -> ((EquinoctialOrbit) orbitType.convertType(o)).getL(positionAngleType);
  121.                 break;
  122.             default:
  123.                 final String sep = ", ";
  124.                 throw new OrekitIllegalArgumentException(OrekitMessages.ORBIT_TYPE_NOT_ALLOWED,
  125.                                                          orbitType,
  126.                                                          OrbitType.KEPLERIAN   + sep +
  127.                                                          OrbitType.CIRCULAR    + sep +
  128.                                                          OrbitType.EQUINOCTIAL);
  129.         }

  130.     }

  131.     /** {@inheritDoc} */
  132.     @Override
  133.     protected PositionAngleDetector create(final EventDetectionSettings detectionSettings,
  134.                                            final EventHandler newHandler) {
  135.         return new PositionAngleDetector(detectionSettings, newHandler, orbitType, positionAngleType, angle);
  136.     }

  137.     /** Get the orbit type defining the angle type.
  138.      * @return orbit type defining the angle type
  139.      */
  140.     public OrbitType getOrbitType() {
  141.         return orbitType;
  142.     }

  143.     /** Get the type of position angle.
  144.      * @return type of position angle
  145.      */
  146.     public PositionAngleType getPositionAngleType() {
  147.         return positionAngleType;
  148.     }

  149.     /** Get the fixed angle to be crossed (radians).
  150.      * @return fixed angle to be crossed (radians)
  151.      */
  152.     public double getAngle() {
  153.         return angle;
  154.     }

  155.     /** {@inheritDoc} */
  156.     @Override
  157.     public void init(final SpacecraftState s0, final AbsoluteDate t) {
  158.         super.init(s0, t);
  159.         offsetEstimators = new TimeSpanMap<>(new OffsetEstimator(s0.getOrbit(), +1.0));
  160.     }

  161.     /** Compute the value of the detection function.
  162.      * <p>
  163.      * The value is the angle difference between the spacecraft and the fixed
  164.      * angle to be crossed, with some sign tweaks to ensure continuity.
  165.      * These tweaks imply the {@code increasing} flag in events detection becomes
  166.      * irrelevant here! As an example, the angle always increase in a Keplerian
  167.      * orbit, but this g function will increase and decrease so it
  168.      * will cross the zero value once per orbit, in increasing and decreasing
  169.      * directions on alternate orbits..
  170.      * </p>
  171.      * @param s the current state information: date, kinematics, attitude
  172.      * @return angle difference between the spacecraft and the fixed
  173.      * angle, with some sign tweaks to ensure continuity
  174.      */
  175.     public double g(final SpacecraftState s) {

  176.         final Orbit orbit = s.getOrbit();

  177.         // angle difference
  178.         OffsetEstimator estimator = offsetEstimators.get(s.getDate());
  179.         double          delta     = estimator.delta(orbit);

  180.         // we use a value greater than π for handover in order to avoid
  181.         // several switches to be estimated as the calling propagator
  182.         // and Orbit.shiftedBy have different accuracy. It is sufficient
  183.         // to have a handover roughly opposite to the detected position angle
  184.         while (FastMath.abs(delta) >= 3.5) {
  185.             // we are too far away from the current estimator, we need to set up a new one
  186.             // ensuring that we do have a crossing event in the current orbit
  187.             // and we ensure sign continuity with the current estimator

  188.             // find when the previous estimator becomes invalid
  189.             final AbsoluteDate handover = estimator.dateForOffset(FastMath.copySign(FastMath.PI, delta), orbit);

  190.             // perform handover to a new estimator at this date
  191.             estimator = new OffsetEstimator(orbit, delta);
  192.             delta     = estimator.delta(orbit);
  193.             if (isForward()) {
  194.                 offsetEstimators.addValidAfter(estimator, handover.getDate(), false);
  195.             } else {
  196.                 offsetEstimators.addValidBefore(estimator, handover.getDate(), false);
  197.             }

  198.         }

  199.         return delta;

  200.     }

  201.     /** Local class for estimating offset angle, handling 2π wrap-up and sign continuity. */
  202.     private class OffsetEstimator {

  203.         /** Target angle. */
  204.         private final double target;

  205.         /** Sign correction to offset. */
  206.         private final double sign;

  207.         /** Reference angle. */
  208.         private final double r0;

  209.         /** Slope of the linearized model. */
  210.         private final double r1;

  211.         /** Reference date. */
  212.         private final AbsoluteDate t0;

  213.         /** Simple constructor.
  214.          * @param orbit current orbit
  215.          * @param currentSign desired sign of the offset at current orbit time (magnitude is ignored)
  216.          */
  217.         OffsetEstimator(final Orbit orbit, final double currentSign) {
  218.             r0     = positionAngleExtractor.apply(orbit);
  219.             target = MathUtils.normalizeAngle(angle, r0);
  220.             sign   = FastMath.copySign(1.0, (r0 - target) * currentSign);
  221.             r1     = orbit.getKeplerianMeanMotion();
  222.             t0     = orbit.getDate();
  223.         }

  224.         /** Compute offset from reference angle.
  225.          * @param orbit current orbit
  226.          * @return offset between current angle and reference angle
  227.          */
  228.         public double delta(final Orbit orbit) {
  229.             final double rawAngle        = positionAngleExtractor.apply(orbit);
  230.             final double linearReference = r0 + r1 * orbit.getDate().durationFrom(t0);
  231.             final double linearizedAngle = MathUtils.normalizeAngle(rawAngle, linearReference);
  232.             return sign * (linearizedAngle - target);
  233.         }

  234.         /** Find date at which offset reaches specified value.
  235.          * <p>
  236.          * This computation is an approximation because it relies on
  237.          * {@link Orbit#shiftedBy(double)} only.
  238.          * </p>
  239.          * @param offset target value for offset angle
  240.          * @param orbit current orbit
  241.          * @return approximate date at which offset reached specified value
  242.          */
  243.         public AbsoluteDate dateForOffset(final double offset, final Orbit orbit) {

  244.             // bracket the search
  245.             final double period = orbit.getKeplerianPeriod();
  246.             final double delta0 = delta(orbit);
  247.             final double searchInf;
  248.             final double searchSup;
  249.             if ((delta0 - offset) * sign >= 0) {
  250.                 // the date is before current orbit
  251.                 searchInf = -period;
  252.                 searchSup = 0;
  253.             } else {
  254.                 // the date is after current orbit
  255.                 searchInf = 0;
  256.                 searchSup = +period;
  257.             }

  258.             // find the date as an offset from current orbit
  259.             final BracketingNthOrderBrentSolver solver = new BracketingNthOrderBrentSolver(getThreshold(), 5);
  260.             final UnivariateFunction            f      = dt -> delta(orbit.shiftedBy(dt)) - offset;
  261.             final double                        root   = solver.solve(getMaxIterationCount(), f, searchInf, searchSup);

  262.             return orbit.getDate().shiftedBy(root);

  263.         }

  264.     }

  265. }