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.time;
18
19 import org.hipparchus.util.FastMath;
20 import org.orekit.errors.OrekitIllegalArgumentException;
21 import org.orekit.errors.OrekitInternalError;
22 import org.orekit.errors.OrekitMessages;
23 import org.orekit.utils.ImmutableTimeStampedCache;
24 import org.orekit.utils.SortedListTrimmer;
25
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.List;
30 import java.util.Optional;
31 import java.util.stream.Collectors;
32 import java.util.stream.Stream;
33
34 /**
35 * Abstract class for time interpolator.
36 *
37 * @param <T> interpolated time stamped type
38 *
39 * @author Vincent Cucchietti
40 */
41 public abstract class AbstractTimeInterpolator<T extends TimeStamped> implements TimeInterpolator<T> {
42
43 /** Default extrapolation time threshold: 1ms. */
44 public static final double DEFAULT_EXTRAPOLATION_THRESHOLD_SEC = 1e-3;
45
46 /** Default number of interpolation points. */
47 public static final int DEFAULT_INTERPOLATION_POINTS = 2;
48
49 /** The extrapolation threshold beyond which the propagation will fail. */
50 private final double extrapolationThreshold;
51
52 /** Neighbor size. */
53 private final int interpolationPoints;
54
55 /**
56 * Constructor.
57 *
58 * @param interpolationPoints number of interpolation points
59 * @param extrapolationThreshold extrapolation threshold beyond which the propagation will fail
60 */
61 protected AbstractTimeInterpolator(final int interpolationPoints, final double extrapolationThreshold) {
62 this.interpolationPoints = interpolationPoints;
63 this.extrapolationThreshold = extrapolationThreshold;
64 }
65
66 /**
67 * Method checking if given interpolator is compatible with given sample size.
68 *
69 * @param interpolator interpolator
70 * @param sampleSize sample size
71 */
72 public static void checkInterpolatorCompatibilityWithSampleSize(
73 final TimeInterpolator<? extends TimeStamped> interpolator,
74 final int sampleSize) {
75
76 // Retrieve all sub-interpolators (or a singleton list with given interpolator if there are no sub-interpolators)
77 for (final TimeInterpolator<?> subInterpolator :
78 interpolator.getSubInterpolators()) {
79 if (sampleSize < subInterpolator.getNbInterpolationPoints()) {
80 throw new OrekitIllegalArgumentException(OrekitMessages.NOT_ENOUGH_DATA, sampleSize);
81 }
82 }
83 }
84
85 /**
86 * {@inheritDoc}
87 * <p>
88 * The stream must hold elements in chronological order.
89 */
90 @Override
91 public T interpolate(final AbsoluteDate interpolationDate,
92 final Stream<? extends T> sample) {
93 return interpolate(interpolationDate, sample.collect(Collectors.toList()));
94 }
95
96 /**
97 * {@inheritDoc}
98 * <p>
99 * <strong>Precondition:</strong> {@code sample} must be sorted in chronological order. Passing an unsorted
100 * sample yields undefined neighbors and may throw
101 * {@link org.orekit.errors.TimeStampedCacheException}.
102 */
103 @Override
104 public T interpolate(final AbsoluteDate interpolationDate,
105 final Collection<? extends T> sample) {
106 final InterpolationData interpolationData = new InterpolationData(interpolationDate, sample);
107 return interpolate(interpolationData);
108 }
109
110 /**
111 * Get the central date to use to find neighbors while taking into account extrapolation threshold.
112 *
113 * @param date interpolation date
114 * @param cachedSamples cached samples
115 * @param threshold extrapolation threshold
116 * @param <T> type of element
117 *
118 * @return central date to use to find neighbors
119 * @since 12.0.1
120 */
121 public static <T extends TimeStamped> AbsoluteDate getCentralDate(final AbsoluteDate date,
122 final ImmutableTimeStampedCache<T> cachedSamples,
123 final double threshold) {
124 final AbsoluteDate minDate = cachedSamples.getEarliest().getDate();
125 final AbsoluteDate maxDate = cachedSamples.getLatest().getDate();
126 return getCentralDate(date, minDate, maxDate, threshold);
127 }
128
129 /**
130 * Get the central date to use to find neighbors while taking into account an extrapolation threshold.
131 *
132 * @param date interpolation date
133 * @param minDate earliest date in the sample.
134 * @param maxDate latest date in the sample.
135 * @param threshold extrapolation threshold
136 *
137 * @return central date to use to find neighbors
138 * @since 12.0.1
139 */
140 public static AbsoluteDate getCentralDate(final AbsoluteDate date,
141 final AbsoluteDate minDate,
142 final AbsoluteDate maxDate,
143 final double threshold) {
144 final AbsoluteDate central;
145
146 if (date.compareTo(minDate) < 0 && FastMath.abs(date.durationFrom(minDate)) <= threshold) {
147 // avoid TimeStampedCacheException as we are still within the tolerance before minDate
148 central = minDate;
149 } else if (date.compareTo(maxDate) > 0 && FastMath.abs(date.durationFrom(maxDate)) <= threshold) {
150 // avoid TimeStampedCacheException as we are still within the tolerance after maxDate
151 central = maxDate;
152 } else {
153 central = date;
154 }
155
156 return central;
157 }
158
159 /** {@inheritDoc} */
160 public List<TimeInterpolator<?>> getSubInterpolators() {
161 return Collections.singletonList(this);
162 }
163
164 /** {@inheritDoc} */
165 public int getNbInterpolationPoints() {
166 final List<TimeInterpolator<? extends TimeStamped>> subInterpolators = getSubInterpolators();
167 // In case the interpolator does not have sub interpolators
168 if (subInterpolators.size() == 1 && subInterpolators.getFirst() == this) {
169 return interpolationPoints;
170 }
171 // Otherwise find maximum number of interpolation points among sub interpolators
172 else {
173 final Optional<Integer> optionalMaxNbInterpolationPoints =
174 subInterpolators.stream().map(TimeInterpolator::getNbInterpolationPoints).max(Integer::compareTo);
175 if (optionalMaxNbInterpolationPoints.isPresent()) {
176 return optionalMaxNbInterpolationPoints.get();
177 } else {
178 // This should never happen
179 throw new OrekitInternalError(null);
180 }
181 }
182 }
183
184 /**
185 * Get the number of interpolation points for this instance only i.e., not taking into account sub-interpolators.
186 *
187 * @return required the number of interpolation points for this instance only i.e., not taking into account
188 * sub-interpolators.
189 */
190 public int getInternalNbInterpolationPoints() {
191 return interpolationPoints;
192 }
193
194 /** {@inheritDoc} */
195 public double getExtrapolationThreshold() {
196 return extrapolationThreshold;
197 }
198
199 /**
200 * Add all lowest level sub interpolators to the sub interpolator list.
201 *
202 * @param subInterpolator optional sub interpolator to add
203 * @param subInterpolators list of sub interpolators
204 */
205 protected void addOptionalSubInterpolatorIfDefined(final TimeInterpolator<? extends TimeStamped> subInterpolator,
206 final List<TimeInterpolator<? extends TimeStamped>> subInterpolators) {
207 // Add all lowest level sub interpolators
208 if (subInterpolator != null) {
209 subInterpolators.addAll(subInterpolator.getSubInterpolators());
210 }
211 }
212
213 /**
214 * Interpolate instance from given interpolation data.
215 *
216 * @param interpolationData interpolation data
217 *
218 * @return interpolated instance from given interpolation data.
219 */
220 protected abstract T interpolate(InterpolationData interpolationData);
221
222 /**
223 * Get the time parameter which lies between [0:1] by normalizing the difference between interpolating time and previous
224 * date by the Δt between tabulated values.
225 *
226 * @param interpolatingTime time at which we want to interpolate a value (between previous and next tabulated dates)
227 * @param previousDate previous tabulated value date
228 * @param nextDate next tabulated value date
229 *
230 * @return time parameter which lies between [0:1]
231 */
232 protected double getTimeParameter(final AbsoluteDate interpolatingTime,
233 final AbsoluteDate previousDate,
234 final AbsoluteDate nextDate) {
235 return interpolatingTime.durationFrom(previousDate) / nextDate.getDate().durationFrom(previousDate);
236 }
237
238 /**
239 * Nested class used to store interpolation data.
240 * <p>
241 * It makes the interpolator thread safe.
242 */
243 public class InterpolationData {
244
245 /** Interpolation date. */
246 private final AbsoluteDate interpolationDate;
247
248 /** Neighbor list around interpolation date. */
249 private final List<T> neighborList;
250
251 /**
252 * Constructor (Collection variant).
253 * <p>
254 * If {@code sample} is already a {@link List}, it is used directly; otherwise it is copied into a new
255 * {@link ArrayList}. Forwards to {@link #InterpolationData(AbsoluteDate, List)} — see that constructor for
256 * the sorted-sample precondition.
257 *
258 * @param interpolationDate interpolation date
259 * @param sample time stamped sample (chronologically sorted)
260 */
261 protected InterpolationData(final AbsoluteDate interpolationDate, final Collection<? extends T> sample) {
262 this(interpolationDate, (sample instanceof List) ? (List<T>) sample : new ArrayList<>(sample));
263 }
264
265 /**
266 * Constructor.
267 * <p>
268 * <strong>Precondition:</strong> {@code sample} must be sorted in chronological order. Passing an unsorted
269 * sample yields undefined neighbors and may throw
270 * {@link org.orekit.errors.TimeStampedCacheException}. Prior implementations silently sorted the input;
271 * this is no longer the case.
272 *
273 * @param interpolationDate interpolation date
274 * @param sample time stamped sample (chronologically sorted)
275 */
276 protected InterpolationData(final AbsoluteDate interpolationDate,
277 final List<? extends T> sample) {
278
279 // Check if there is enough sample points
280 final int nbInterpolationPoints = getNbInterpolationPoints();
281 if (sample.size() < nbInterpolationPoints) {
282 throw new OrekitIllegalArgumentException(OrekitMessages.NOT_ENOUGH_CACHED_NEIGHBORS,
283 sample.size(), nbInterpolationPoints);
284 }
285
286 // Shortcut to see if sample size is equal to number of interpolation points
287 if (sample.size() == nbInterpolationPoints) {
288 this.neighborList = Collections.unmodifiableList(sample);
289 } else {
290 final AbsoluteDate central = getCentralDate(interpolationDate,
291 sample.get(0).getDate(),
292 sample.get(sample.size() - 1).getDate(),
293 extrapolationThreshold);
294
295 // Trimmer returns a sublist view, so wrap (don't copy) for immutability.
296 final SortedListTrimmer trimmer = new SortedListTrimmer(nbInterpolationPoints);
297 this.neighborList = Collections.unmodifiableList(trimmer.getNeighborsSubList(central, sample));
298 }
299
300 this.interpolationDate = interpolationDate;
301 }
302
303 /** Get interpolation date.
304 * @return interpolation date
305 */
306 public AbsoluteDate getInterpolationDate() {
307 return interpolationDate;
308 }
309
310 /** Get neighbor list.
311 * @return neighbor list
312 */
313 public List<T> getNeighborList() {
314 return neighborList;
315 }
316
317 }
318 }