1   /* Copyright 2002-2026 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  
19  import org.hipparchus.CalculusFieldElement;
20  import org.hipparchus.Field;
21  import org.hipparchus.ode.events.Action;
22  import org.hipparchus.util.FastMath;
23  import org.hipparchus.util.MathUtils;
24  import org.orekit.frames.Frame;
25  import org.orekit.orbits.FieldOrbit;
26  import org.orekit.orbits.KeplerianOrbit;
27  import org.orekit.orbits.Orbit;
28  import org.orekit.orbits.OrbitType;
29  import org.orekit.orbits.PositionAngleType;
30  import org.orekit.propagation.FieldSpacecraftState;
31  import org.orekit.propagation.events.functions.NodeEventFunction;
32  import org.orekit.propagation.events.handlers.EventHandler;
33  import org.orekit.propagation.events.handlers.FieldEventHandler;
34  import org.orekit.propagation.events.handlers.FieldStopOnEvent;
35  import org.orekit.propagation.events.handlers.FieldStopOnIncreasing;
36  import org.orekit.propagation.events.intervals.FieldAdaptableInterval;
37  
38  /** Finder for node crossing events.
39   * <p>This class finds equator crossing events (i.e. ascending
40   * or descending node crossing).</p>
41   * <p>The default implementation behavior is to {@link Action#CONTINUE continue}
42   * propagation at descending node crossing and to {@link Action#STOP stop} propagation
43   * at ascending node crossing. This can be changed by calling
44   * {@link #withHandler(FieldEventHandler)} after construction.</p>
45   * <p>Beware that node detection will fail for almost equatorial orbits. If
46   * for example a node detector is used to trigger an {@link
47   * org.orekit.forces.maneuvers.ImpulseManeuver ImpulseManeuver} and the maneuver
48   * turn the orbit plane to equator, then the detector may completely fail just
49   * after the maneuver has been performed! This is a real case that has been
50   * encountered during validation ...</p>
51   * @see org.orekit.propagation.FieldPropagator#addEventDetector(FieldEventDetector)
52   * @author Luc Maisonobe
53   * @param <T> type of the field elements
54   */
55  public class FieldNodeDetector<T extends CalculusFieldElement<T>> extends FieldAbstractDetector<FieldNodeDetector<T>, T> {
56  
57      /** Frame in which the equator is defined. */
58      private final Frame frame;
59  
60      /** Build a new instance with default detection settings and stopping handler.
61       * @param field field
62       * @param frame frame in which the equator is defined (typical
63       * values are {@link org.orekit.frames.FramesFactory#getEME2000() EME<sub>2000</sub>} or
64       * {@link org.orekit.frames.FramesFactory#getITRF(org.orekit.utils.IERSConventions, boolean) ITRF})
65       * @since 13.1.2
66       */
67      public FieldNodeDetector(final Field<T> field, final Frame frame) {
68          this(new FieldEventDetectionSettings<>(field, EventDetectionSettings.getDefaultEventDetectionSettings()),
69                  new FieldStopOnEvent<>(), frame);
70      }
71  
72      /** Build a new instance.
73       * <p>The orbit is used only to set an upper bound for the max check interval
74       * to period/3 and to set the convergence threshold according to orbit size.</p>
75       * @param orbit initial orbit
76       * @param frame frame in which the equator is defined (typical
77       * values are {@link org.orekit.frames.FramesFactory#getEME2000() EME<sub>2000</sub>} or
78       * {@link org.orekit.frames.FramesFactory#getITRF(org.orekit.utils.IERSConventions, boolean) ITRF})
79       */
80      public FieldNodeDetector(final FieldOrbit<T> orbit, final Frame frame) {
81          this(orbit.getKeplerianPeriod().multiply(1.0e-13), orbit, frame);
82      }
83  
84      /** Build a new instance.
85       * <p>The orbit is used only to set an upper bound for the max check interval
86       * to period/3.</p>
87       * @param threshold convergence threshold (s)
88       * @param orbit initial orbit
89       * @param frame frame in which the equator is defined (typical
90       * values are {@link org.orekit.frames.FramesFactory#getEME2000() EME<sub>2000</sub>} or
91       * {@link org.orekit.frames.FramesFactory#getITRF(org.orekit.utils.IERSConventions, boolean) ITRF})
92       */
93      public FieldNodeDetector(final T threshold, final FieldOrbit<T> orbit, final Frame frame) {
94          this(new FieldEventDetectionSettings<>(FieldAdaptableInterval.of(orbit.getA().getField().getZero().newInstance(2 * estimateNodesTimeSeparation(orbit.toOrbit()) / 3).getReal()),
95              threshold, DEFAULT_MAX_ITER), new FieldStopOnIncreasing<>(), frame);
96      }
97  
98      /** Constructor with detection settings and handler.
99       * @param detectionSettings event detection settings
100      * @param handler event handler to call at event occurrences
101      * @param frame frame in which the equator is defined (typical
102      * values are {@link org.orekit.frames.FramesFactory#getEME2000() EME<sub>2000</sub>} or
103      * {@link org.orekit.frames.FramesFactory#getITRF(org.orekit.utils.IERSConventions, boolean) ITRF})
104      * @since 13.0
105      */
106     protected FieldNodeDetector(final FieldEventDetectionSettings<T> detectionSettings,
107                                 final FieldEventHandler<T> handler, final Frame frame) {
108         this(new NodeEventFunction(frame), detectionSettings, handler);
109     }
110 
111     /** Protected constructor with full parameters.
112      * <p>
113      * This constructor is not public as users are expected to use the builder
114      * API with the various {@code withXxx()} methods to set up the instance
115      * in a readable manner without using a huge amount of parameters.
116      * </p>
117      * @param nodeEventFunction event function
118      * @param detectionSettings event detection settings
119      * @param handler event handler to call at event occurrences
120      * values are {@link org.orekit.frames.FramesFactory#getEME2000() EME<sub>2000</sub>} or
121      * {@link org.orekit.frames.FramesFactory#getITRF(org.orekit.utils.IERSConventions, boolean) ITRF})
122      * @since 14.0
123      */
124     protected FieldNodeDetector(final NodeEventFunction nodeEventFunction,
125                                 final FieldEventDetectionSettings<T> detectionSettings,
126                                 final FieldEventHandler<T> handler) {
127         super(nodeEventFunction, detectionSettings, handler);
128         this.frame = nodeEventFunction.getFrame();
129     }
130 
131     /** {@inheritDoc} */
132     @Override
133     protected FieldNodeDetector<T> create(final FieldEventDetectionSettings<T> detectionSettings,
134                                           final FieldEventHandler<T> newHandler) {
135         return new FieldNodeDetector<>((NodeEventFunction) getEventFunction(), detectionSettings, newHandler);
136     }
137 
138     /** Find time separation between nodes.
139      * <p>
140      * The estimation of time separation is based on Keplerian motion, it is only
141      * used as a rough guess for a safe setting of default max check interval for
142      * event detection.
143      * </p>
144      * @param orbit initial orbit
145      * @return minimum time separation between nodes
146      */
147     private static double estimateNodesTimeSeparation(final Orbit orbit) {
148 
149         final KeplerianOrbit keplerian = (KeplerianOrbit) OrbitType.KEPLERIAN.convertType(orbit);
150 
151         // mean anomaly of ascending node
152         final double ascendingM  =  new KeplerianOrbit(keplerian.getA(), keplerian.getE(),
153                                                        keplerian.getI(),
154                                                        keplerian.getPerigeeArgument(),
155                                                        keplerian.getRightAscensionOfAscendingNode(),
156                                                        -keplerian.getPerigeeArgument(), PositionAngleType.TRUE,
157                                                        keplerian.getFrame(), keplerian.getDate(),
158                                                        keplerian.getMu()).getMeanAnomaly();
159 
160         // mean anomaly of descending node
161         final double descendingM =  new KeplerianOrbit(keplerian.getA(), keplerian.getE(),
162                                                        keplerian.getI(),
163                                                        keplerian.getPerigeeArgument(),
164                                                        keplerian.getRightAscensionOfAscendingNode(),
165                                                        FastMath.PI - keplerian.getPerigeeArgument(), PositionAngleType.TRUE,
166                                                        keplerian.getFrame(), keplerian.getDate(),
167                                                        keplerian.getMu()).getMeanAnomaly();
168 
169         // differences between mean anomalies
170         final double delta1 = MathUtils.normalizeAngle(ascendingM, descendingM + FastMath.PI) - descendingM;
171         final double delta2 = 2 * FastMath.PI - delta1;
172 
173         // minimum time separation between the two nodes
174         return FastMath.min(delta1, delta2) / keplerian.getKeplerianMeanMotion();
175 
176     }
177 
178     /** Get the frame in which the equator is defined.
179      * @return the frame in which the equator is defined
180      */
181     public Frame getFrame() {
182         return frame;
183     }
184 
185     /** Compute the value of the switching function.
186      * This function computes the Z position in the defined frame.
187      * @param s the current state information: date, kinematics, attitude
188      * @return value of the switching function
189      */
190     @Override
191     public T g(final FieldSpacecraftState<T> s) {
192         return getEventFunction().value(s);
193     }
194 
195     /** {@inheritDoc} */
196     @Override
197     public NodeDetector toEventDetector(final EventHandler eventHandler) {
198         return new NodeDetector((NodeEventFunction) getEventFunction(),
199                 getDetectionSettings().toEventDetectionSettings(), eventHandler);
200     }
201 }