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  
19  import java.util.ArrayList;
20  import java.util.Collections;
21  import java.util.List;
22  
23  import org.hipparchus.ode.events.Action;
24  import org.orekit.errors.OrekitIllegalArgumentException;
25  import org.orekit.errors.OrekitMessages;
26  import org.orekit.propagation.SpacecraftState;
27  import org.orekit.propagation.events.handlers.EventHandler;
28  import org.orekit.propagation.events.handlers.StopOnEvent;
29  import org.orekit.time.AbsoluteDate;
30  import org.orekit.time.TimeStamped;
31  
32  /** Finder for date events.
33   * <p>This class finds date events (i.e. occurrence of some predefined dates).</p>
34   * <p>As of version 5.1, it is an enhanced date detector:</p>
35   * <ul>
36   *   <li>it can be defined without prior date ({@link #DateDetector(TimeStamped...)})</li>
37   *   <li>several dates can be added ({@link #addEventDate(AbsoluteDate)})</li>
38   * </ul>
39   * <p>The gap between the added dates must be more than the minGap.</p>
40   * <p>The default implementation behavior is to {@link Action#STOP stop}
41   * propagation at the first event date occurrence. This can be changed by calling
42   * {@link #withHandler(EventHandler)} after construction.</p>
43   * @see org.orekit.propagation.Propagator#addEventDetector(EventDetector)
44   * @author Luc Maisonobe
45   * @author Pascal Parraud
46   */
47  public class DateDetector extends AbstractDetector<DateDetector> implements TimeStamped {
48  
49      /** Default value for max check.
50       * @since 12.0
51       */
52      public static final double DEFAULT_MAX_CHECK = 1.0e10;
53  
54      /** Default value for minimum gap between added dates.
55       * @since 12.0
56       */
57      public static final double DEFAULT_MIN_GAP = 1.0;
58  
59      /** Default value for convergence threshold.
60       * @since 12.0
61       */
62      public static final double DEFAULT_THRESHOLD = 1.0e-13;
63  
64      /** Minimum gap between added dates.
65       * @since 12.0
66       */
67      private final double minGap;
68  
69      /** Last date for g computation. */
70      private AbsoluteDate gDate;
71  
72      /** List of event dates. */
73      private final ArrayList<EventDate> eventDateList;
74  
75      /** Current event date. */
76      private int currentIndex;
77  
78      /** Build a new instance.
79       * <p>First event dates are set here, but others can be
80       * added later with {@link #addEventDate(AbsoluteDate)}.</p>
81       * @param dates list of event dates
82       * @see #addEventDate(AbsoluteDate)
83       * @since 12.0
84       */
85      public DateDetector(final TimeStamped... dates) {
86          this(AdaptableInterval.of(DEFAULT_MAX_CHECK), DEFAULT_THRESHOLD, DEFAULT_MAX_ITER, new StopOnEvent(), DEFAULT_MIN_GAP, dates);
87      }
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 minGap minimum gap between added dates (s)
100      * @param dates list of event dates
101      * @since 12.0
102      */
103     protected DateDetector(final AdaptableInterval maxCheck, final double threshold, final int maxIter,
104                            final EventHandler handler, final double minGap, final TimeStamped... dates) {
105         super(maxCheck, threshold, maxIter, handler);
106         this.currentIndex  = -1;
107         this.gDate         = null;
108         this.eventDateList = new ArrayList<DateDetector.EventDate>(dates.length);
109         for (final TimeStamped ts : dates) {
110             addEventDate(ts.getDate());
111         }
112         this.minGap        = minGap;
113     }
114 
115     /**
116      * Setup minimum gap between added dates.
117      * @param newMinGap new minimum gap between added dates
118      * @return a new detector with updated configuration (the instance is not changed)
119      * @since 12.0
120      */
121     public DateDetector withMinGap(final double newMinGap) {
122         return new DateDetector(getMaxCheckInterval(), getThreshold(), getMaxIterationCount(),
123                                 getHandler(), newMinGap,
124                                 eventDateList.toArray(new EventDate[eventDateList.size()]));
125     }
126 
127     /** {@inheritDoc} */
128     @Override
129     protected DateDetector create(final AdaptableInterval newMaxCheck, final double newThreshold,
130                                   final int newMaxIter, final EventHandler newHandler) {
131         return new DateDetector(newMaxCheck, newThreshold, newMaxIter, newHandler, minGap,
132                                 eventDateList.toArray(new EventDate[eventDateList.size()]));
133     }
134 
135     /** Get all event dates currently managed, in chronological order.
136      * @return all event dates currently managed, in chronological order
137      * @since 11.1
138      */
139     public List<TimeStamped> getDates() {
140         return Collections.unmodifiableList(eventDateList);
141     }
142 
143     /** Compute the value of the switching function.
144      * This function measures the difference between the current and the target date.
145      * @param s the current state information: date, kinematics, attitude
146      * @return value of the switching function
147      */
148     public double g(final SpacecraftState s) {
149         gDate = s.getDate();
150         if (currentIndex < 0) {
151             return -1.0;
152         } else {
153             final EventDate event = getClosest(gDate);
154             return event.isgIncrease() ? gDate.durationFrom(event.getDate()) : event.getDate().durationFrom(gDate);
155         }
156     }
157 
158     /** Get the current event date according to the propagator.
159      * @return event date
160      */
161     public AbsoluteDate getDate() {
162         return currentIndex < 0 ? null : eventDateList.get(currentIndex).getDate();
163     }
164 
165     /** Add an event date.
166      * <p>The date to add must be:</p>
167      * <ul>
168      *   <li>less than the smallest already registered event date minus the maxCheck</li>
169      *   <li>or more than the largest already registered event date plus the maxCheck</li>
170      * </ul>
171      * @param target target date
172      * @throws IllegalArgumentException if the date is too close from already defined interval
173      * @see #DateDetector(TimeStamped...)
174      */
175     public void addEventDate(final AbsoluteDate target) throws IllegalArgumentException {
176         final boolean increasing;
177         if (currentIndex < 0) {
178             increasing = (gDate == null) ? true : target.durationFrom(gDate) > 0.0;
179             currentIndex = 0;
180             eventDateList.add(new EventDate(target, increasing));
181         } else {
182             final int          lastIndex = eventDateList.size() - 1;
183             final AbsoluteDate firstDate = eventDateList.get(0).getDate();
184             final AbsoluteDate lastDate  = eventDateList.get(lastIndex).getDate();
185             if (firstDate.durationFrom(target) > minGap) {
186                 increasing = !eventDateList.get(0).isgIncrease();
187                 eventDateList.add(0, new EventDate(target, increasing));
188                 currentIndex++;
189             } else if (target.durationFrom(lastDate) > minGap) {
190                 increasing = !eventDateList.get(lastIndex).isgIncrease();
191                 eventDateList.add(new EventDate(target, increasing));
192             } else {
193                 throw new OrekitIllegalArgumentException(OrekitMessages.EVENT_DATE_TOO_CLOSE,
194                                                          target,
195                                                          firstDate,
196                                                          lastDate,
197                                                          minGap,
198                                                          firstDate.durationFrom(target),
199                                                          target.durationFrom(lastDate));
200             }
201         }
202     }
203 
204     /** Get the closest EventDate to the target date.
205      * @param target target date
206      * @return current EventDate
207      */
208     private EventDate getClosest(final AbsoluteDate target) {
209         final double dt = target.durationFrom(eventDateList.get(currentIndex).getDate());
210         if (dt < 0.0 && currentIndex > 0) {
211             boolean found = false;
212             while (currentIndex > 0 && !found) {
213                 if (target.durationFrom(eventDateList.get(currentIndex - 1).getDate()) < eventDateList.get(currentIndex).getDate().durationFrom(target)) {
214                     currentIndex--;
215                 } else {
216                     found = true;
217                 }
218             }
219         } else if (dt > 0.0 && currentIndex < eventDateList.size() - 1) {
220             final int maxIndex = eventDateList.size() - 1;
221             boolean found = false;
222             while (currentIndex < maxIndex && !found) {
223                 if (target.durationFrom(eventDateList.get(currentIndex + 1).getDate()) > eventDateList.get(currentIndex).getDate().durationFrom(target)) {
224                     currentIndex++;
225                 } else {
226                     found = true;
227                 }
228             }
229         }
230         return eventDateList.get(currentIndex);
231     }
232 
233     /** Event date specification. */
234     private static class EventDate implements TimeStamped {
235 
236         /** Event date. */
237         private final AbsoluteDate eventDate;
238 
239         /** Flag for g function way around event date. */
240         private final boolean gIncrease;
241 
242         /** Simple constructor.
243          * @param date date
244          * @param increase if true, g function increases around event date
245          */
246         EventDate(final AbsoluteDate date, final boolean increase) {
247             this.eventDate = date;
248             this.gIncrease = increase;
249         }
250 
251         /** Getter for event date.
252          * @return event date
253          */
254         public AbsoluteDate getDate() {
255             return eventDate;
256         }
257 
258         /** Getter for g function way at event date.
259          * @return g function increasing flag
260          */
261         public boolean isgIncrease() {
262             return gIncrease;
263         }
264 
265     }
266 
267 }