PositionAngleDetector.java

  1. /* Copyright 2002-2024 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_MAXCHECK}) 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_MAXCHECK, 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(AdaptableInterval.of(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 maxCheck maximum checking interval
  96.      * @param threshold convergence threshold (s)
  97.      * @param maxIter maximum number of iterations in the event time search
  98.      * @param handler event handler to call at event occurrences
  99.      * @param orbitType orbit type defining the angle type
  100.      * @param positionAngleType type of position angle
  101.      * @param angle fixed angle to be crossed
  102.      * @exception OrekitIllegalArgumentException if orbit type is {@link OrbitType#CARTESIAN}
  103.      */
  104.     protected PositionAngleDetector(final AdaptableInterval maxCheck, final double threshold,
  105.                                     final int maxIter, final EventHandler handler,
  106.                                     final OrbitType orbitType, final PositionAngleType positionAngleType,
  107.                                     final double angle)
  108.         throws OrekitIllegalArgumentException {

  109.         super(maxCheck, threshold, maxIter, handler);

  110.         this.orbitType        = orbitType;
  111.         this.positionAngleType = positionAngleType;
  112.         this.angle            = angle;
  113.         this.offsetEstimators = null;

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

  132.     }

  133.     /** {@inheritDoc} */
  134.     @Override
  135.     protected PositionAngleDetector create(final AdaptableInterval newMaxCheck, final double newThreshold,
  136.                                            final int newMaxIter,
  137.                                            final EventHandler newHandler) {
  138.         return new PositionAngleDetector(newMaxCheck, newThreshold, newMaxIter, newHandler,
  139.                                          orbitType, positionAngleType, angle);
  140.     }

  141.     /** Get the orbit type defining the angle type.
  142.      * @return orbit type defining the angle type
  143.      */
  144.     public OrbitType getOrbitType() {
  145.         return orbitType;
  146.     }

  147.     /** Get the type of position angle.
  148.      * @return type of position angle
  149.      */
  150.     public PositionAngleType getPositionAngleType() {
  151.         return positionAngleType;
  152.     }

  153.     /** Get the fixed angle to be crossed (radians).
  154.      * @return fixed angle to be crossed (radians)
  155.      */
  156.     public double getAngle() {
  157.         return angle;
  158.     }

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

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

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

  180.         // angle difference
  181.         OffsetEstimator estimator = offsetEstimators.get(s.getDate());
  182.         double          delta     = estimator.delta(orbit);

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

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

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

  201.         }

  202.         return delta;

  203.     }

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

  206.         /** Target angle. */
  207.         private final double target;

  208.         /** Sign correction to offset. */
  209.         private final double sign;

  210.         /** Reference angle. */
  211.         private final double r0;

  212.         /** Slope of the linearized model. */
  213.         private final double r1;

  214.         /** Reference date. */
  215.         private final AbsoluteDate t0;

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

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

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

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

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

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

  266.         }

  267.     }

  268. }