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.frames;
18  
19  import java.io.Serializable;
20  import java.util.function.BiFunction;
21  import java.util.function.Function;
22  
23  import org.hipparchus.CalculusFieldElement;
24  import org.hipparchus.FieldElement;
25  import org.orekit.errors.OrekitIllegalArgumentException;
26  import org.orekit.errors.OrekitMessages;
27  import org.orekit.time.AbsoluteDate;
28  import org.orekit.time.FieldAbsoluteDate;
29  
30  
31  /** Tridimensional references frames class.
32   *
33   * <h2> Frame Presentation </h2>
34   * <p>This class is the base class for all frames in OREKIT. The frames are
35   * linked together in a tree with some specific frame chosen as the root of the tree.
36   * Each frame is defined by {@link Transform transforms} combining any number
37   * of translations and rotations from a reference frame which is its
38   * parent frame in the tree structure.</p>
39   * <p>When we say a {@link Transform transform} t is <em>from frame<sub>A</sub>
40   * to frame<sub>B</sub></em>, we mean that if the coordinates of some absolute
41   * vector (say the direction of a distant star for example) has coordinates
42   * u<sub>A</sub> in frame<sub>A</sub> and u<sub>B</sub> in frame<sub>B</sub>,
43   * then u<sub>B</sub>={@link
44   * Transform#transformVector(org.hipparchus.geometry.euclidean.threed.Vector3D)
45   * t.transformVector(u<sub>A</sub>)}.
46   * <p>The transforms may be constant or varying, depending on the implementation of
47   * the {@link TransformProvider transform provider} used to define the frame. For simple
48   * fixed transforms, using {@link FixedTransformProvider} is sufficient. For varying
49   * transforms (time-dependent or telemetry-based for example), it may be useful to define
50   * specific implementations of {@link TransformProvider transform provider}.</p>
51   *
52   * @author Guylaine Prat
53   * @author Luc Maisonobe
54   * @author Pascal Parraud
55   */
56  public class Frame implements Serializable {
57  
58      /** Serializable UID. */
59      private static final long serialVersionUID = -6981146543760234087L;
60  
61      /** Parent frame (only the root frame doesn't have a parent). */
62      private final Frame parent;
63  
64      /** Depth of the frame with respect to tree root. */
65      private final int depth;
66  
67      /** Provider for transform from parent frame to instance. */
68      private final TransformProvider transformProvider;
69  
70      /** Instance name. */
71      private final String name;
72  
73      /** Indicator for pseudo-inertial frames. */
74      private final boolean pseudoInertial;
75  
76      /** Private constructor used only for the root frame.
77       * @param name name of the frame
78       * @param pseudoInertial true if frame is considered pseudo-inertial
79       * (i.e. suitable for propagating orbit)
80       */
81      private Frame(final String name, final boolean pseudoInertial) {
82          parent              = null;
83          depth               = 0;
84          transformProvider   = new FixedTransformProvider(Transform.IDENTITY);
85          this.name           = name;
86          this.pseudoInertial = pseudoInertial;
87      }
88  
89      /** Build a non-inertial frame from its transform with respect to its parent.
90       * <p>calling this constructor is equivalent to call
91       * <code>{link {@link #Frame(Frame, Transform, String, boolean)
92       * Frame(parent, transform, name, false)}</code>.</p>
93       * @param parent parent frame (must be non-null)
94       * @param transform transform from parent frame to instance
95       * @param name name of the frame
96       * @exception IllegalArgumentException if the parent frame is null
97       */
98      public Frame(final Frame parent, final Transform transform, final String name)
99          throws IllegalArgumentException {
100         this(parent, transform, name, false);
101     }
102 
103     /** Build a non-inertial frame from its transform with respect to its parent.
104      * <p>calling this constructor is equivalent to call
105      * <code>{link {@link #Frame(Frame, Transform, String, boolean)
106      * Frame(parent, transform, name, false)}</code>.</p>
107      * @param parent parent frame (must be non-null)
108      * @param transformProvider provider for transform from parent frame to instance
109      * @param name name of the frame
110      * @exception IllegalArgumentException if the parent frame is null
111      */
112     public Frame(final Frame parent, final TransformProvider transformProvider, final String name)
113         throws IllegalArgumentException {
114         this(parent, transformProvider, name, false);
115     }
116 
117     /** Build a frame from its transform with respect to its parent.
118      * <p>The convention for the transform is that it is from parent
119      * frame to instance. This means that the two following frames
120      * are similar:</p>
121      * <pre>
122      * Frame frame1 = new Frame(FramesFactory.getGCRF(), new Transform(t1, t2));
123      * Frame frame2 = new Frame(new Frame(FramesFactory.getGCRF(), t1), t2);
124      * </pre>
125      * @param parent parent frame (must be non-null)
126      * @param transform transform from parent frame to instance
127      * @param name name of the frame
128      * @param pseudoInertial true if frame is considered pseudo-inertial
129      * (i.e. suitable for propagating orbit)
130      * @exception IllegalArgumentException if the parent frame is null
131      */
132     public Frame(final Frame parent, final Transform transform, final String name,
133                  final boolean pseudoInertial)
134         throws IllegalArgumentException {
135         this(parent, new FixedTransformProvider(transform), name, pseudoInertial);
136     }
137 
138     /** Build a frame from its transform with respect to its parent.
139      * <p>The convention for the transform is that it is from parent
140      * frame to instance. This means that the two following frames
141      * are similar:</p>
142      * <pre>
143      * Frame frame1 = new Frame(FramesFactory.getGCRF(), new Transform(t1, t2));
144      * Frame frame2 = new Frame(new Frame(FramesFactory.getGCRF(), t1), t2);
145      * </pre>
146      * @param parent parent frame (must be non-null)
147      * @param transformProvider provider for transform from parent frame to instance
148      * @param name name of the frame
149      * @param pseudoInertial true if frame is considered pseudo-inertial
150      * (i.e. suitable for propagating orbit)
151      * @exception IllegalArgumentException if the parent frame is null
152      */
153     public Frame(final Frame parent, final TransformProvider transformProvider, final String name,
154                  final boolean pseudoInertial)
155         throws IllegalArgumentException {
156 
157         if (parent == null) {
158             throw new OrekitIllegalArgumentException(OrekitMessages.NULL_PARENT_FOR_FRAME, name);
159         }
160         this.parent            = parent;
161         this.depth             = parent.depth + 1;
162         this.transformProvider = transformProvider;
163         this.name              = name;
164         this.pseudoInertial    = pseudoInertial;
165 
166     }
167 
168     /** Get the name.
169      * @return the name
170      */
171     public String getName() {
172         return this.name;
173     }
174 
175     /** Check if the frame is pseudo-inertial.
176      * <p>Pseudo-inertial frames are frames that do have a linear motion and
177      * either do not rotate or rotate at a very low rate resulting in
178      * neglectible inertial forces. This means they are suitable for orbit
179      * definition and propagation using Newtonian mechanics. Frames that are
180      * <em>not</em> pseudo-inertial are <em>not</em> suitable for orbit
181      * definition and propagation.</p>
182      * @return true if frame is pseudo-inertial
183      */
184     public boolean isPseudoInertial() {
185         return pseudoInertial;
186     }
187 
188     /** New definition of the java.util toString() method.
189      * @return the name
190      */
191     public String toString() {
192         return this.name;
193     }
194 
195     /** Get the parent frame.
196      * @return parent frame
197      */
198     public Frame getParent() {
199         return parent;
200     }
201 
202     /** Get the depth of the frame.
203      * <p>
204      * The depth of a frame is the number of parents frame between
205      * it and the frames tree root. It is 0 for the root frame, and
206      * the depth of a frame is the depth of its parent frame plus one.
207      * </p>
208      * @return depth of the frame
209      */
210     public int getDepth() {
211         return depth;
212     }
213 
214     /** Get the n<sup>th</sup> ancestor of the frame.
215      * @param n index of the ancestor (0 is the instance, 1 is its parent,
216      * 2 is the parent of its parent...)
217      * @return n<sup>th</sup> ancestor of the frame (must be between 0
218      * and the depth of the frame)
219      * @exception IllegalArgumentException if n is larger than the depth
220      * of the instance
221      */
222     public Frame getAncestor(final int n) throws IllegalArgumentException {
223 
224         // safety check
225         if (n > depth) {
226             throw new OrekitIllegalArgumentException(OrekitMessages.FRAME_NO_NTH_ANCESTOR,
227                                                      name, depth, n);
228         }
229 
230         // go upward to find ancestor
231         Frame current = this;
232         for (int i = 0; i < n; ++i) {
233             current = current.parent;
234         }
235 
236         return current;
237 
238     }
239 
240     /** Get the transform from the instance to another frame.
241      * @param destination destination frame to which we want to transform vectors
242      * @param date the date (can be null if it is sure than no date dependent frame is used)
243      * @return transform from the instance to the destination frame
244      */
245     public Transform getTransformTo(final Frame destination, final AbsoluteDate date) {
246         return getTransformTo(
247                 destination,
248                 Transform.IDENTITY,
249                 frame -> frame.getTransformProvider().getTransform(date),
250                 (t1, t2) -> new Transform(date, t1, t2),
251                 Transform::getInverse);
252     }
253 
254     /** Get the transform from the instance to another frame.
255      * @param destination destination frame to which we want to transform vectors
256      * @param date the date (<em>must</em> be non-null, which is a more stringent condition
257      *      *                than in {@link #getTransformTo(Frame, FieldAbsoluteDate)})
258      * @param <T> the type of the field elements
259      * @return transform from the instance to the destination frame
260      */
261     public <T extends CalculusFieldElement<T>> FieldTransform<T> getTransformTo(final Frame destination, final FieldAbsoluteDate<T> date) {
262 
263         return getTransformTo(destination,
264                               FieldTransform.getIdentity(date.getField()),
265                               frame -> frame.getTransformProvider().getTransform(date),
266                               (t1, t2) -> new FieldTransform<>(date, t1, t2),
267                               FieldTransform::getInverse);
268     }
269 
270     /**
271      * Get the static portion of the transform from the instance to another
272      * frame. The returned transform is static in the sense that it includes
273      * translations and rotations, but not rates.
274      *
275      * <p>This method is often more performant than {@link
276      * #getTransformTo(Frame, AbsoluteDate)} when rates are not needed.
277      *
278      * @param destination destination frame to which we want to transform
279      *                    vectors
280      * @param date        the date (can be null if it is sure than no date
281      *                    dependent frame is used)
282      * @return static transform from the instance to the destination frame
283      * @since 11.2
284      */
285     public StaticTransform getStaticTransformTo(final Frame destination,
286                                                 final AbsoluteDate date) {
287         return getTransformTo(
288                 destination,
289                 StaticTransform.getIdentity(),
290                 frame -> frame.getTransformProvider().getStaticTransform(date),
291                 (t1, t2) -> StaticTransform.compose(date, t1, t2),
292                 StaticTransform::getInverse);
293     }
294 
295     /**
296      * Get the static portion of the transform from the instance to another
297      * frame. The returned transform is static in the sense that it includes
298      * translations and rotations, but not rates.
299      *
300      * <p>This method is often more performant than {@link
301      * #getTransformTo(Frame, FieldAbsoluteDate)} when rates are not needed.
302      *
303      * <p>A first check is made on the FieldAbsoluteDate because "fielded" transforms have low-performance.<br>
304      * The date field is checked with {@link FieldElement#isZero()}.<br>
305      * If true, the un-fielded version of the transform computation is used.
306      *
307      * @param <T>         type of the elements
308      * @param destination destination frame to which we want to transform
309      *                    vectors
310      * @param date        the date (<em>must</em> be non-null, which is a more stringent condition
311      *                    than in {@link #getStaticTransformTo(Frame, AbsoluteDate)})
312      * @return static transform from the instance to the destination frame
313      * @since 12.0
314      */
315     public <T extends CalculusFieldElement<T>> FieldStaticTransform<T> getStaticTransformTo(final Frame destination,
316                                                 final FieldAbsoluteDate<T> date) {
317         if (date.hasZeroField()) {
318             // If date field is Zero, then use the un-fielded version for performances
319             return FieldStaticTransform.of(date, getStaticTransformTo(destination, date.toAbsoluteDate()));
320 
321         } else {
322             // Use classic fielded function
323             return getTransformTo(destination,
324                                   FieldStaticTransform.getIdentity(date.getField()),
325                                   frame -> frame.getTransformProvider().getStaticTransform(date),
326                                   (t1, t2) -> FieldStaticTransform.compose(date, t1, t2),
327                                   FieldStaticTransform::getInverse);
328         }
329     }
330 
331     /**
332      * Generic get transform method that builds the transform from {@code this}
333      * to {@code destination}.
334      *
335      * @param destination  destination frame to which we want to transform
336      *                     vectors
337      * @param identity     transform of the given type.
338      * @param getTransform method to get a transform from a frame.
339      * @param compose      method to combine two transforms.
340      * @param inverse      method to invert a transform.
341      * @param <T>          Type of transform returned.
342      * @return composite transform.
343      */
344     private <T> T getTransformTo(final Frame destination,
345                                  final T identity,
346                                  final Function<Frame, T> getTransform,
347                                  final BiFunction<T, T, T> compose,
348                                  final Function<T, T> inverse) {
349 
350         if (this == destination) {
351             // shortcut for special case that may be frequent
352             return identity;
353         }
354 
355         // common ancestor to both frames in the frames tree
356         final Frame common = findCommon(this, destination);
357 
358         // transform from common to instance
359         T commonToInstance = identity;
360         for (Frame frame = this; frame != common; frame = frame.parent) {
361             commonToInstance = compose.apply(getTransform.apply(frame), commonToInstance);
362         }
363 
364         // transform from destination up to common
365         T commonToDestination = identity;
366         for (Frame frame = destination; frame != common; frame = frame.parent) {
367             commonToDestination = compose.apply(getTransform.apply(frame), commonToDestination);
368         }
369 
370         // transform from instance to destination via common
371         return compose.apply(inverse.apply(commonToInstance), commonToDestination);
372 
373     }
374 
375     /** Get the provider for transform from parent frame to instance.
376      * @return provider for transform from parent frame to instance
377      */
378     public TransformProvider getTransformProvider() {
379         return transformProvider;
380     }
381 
382     /** Find the deepest common ancestor of two frames in the frames tree.
383      * @param from origin frame
384      * @param to destination frame
385      * @return an ancestor frame of both <code>from</code> and <code>to</code>
386      */
387     private static Frame findCommon(final Frame from, final Frame to) {
388 
389         // select deepest frames that could be the common ancestor
390         Frame currentF = from.depth > to.depth ? from.getAncestor(from.depth - to.depth) : from;
391         Frame currentT = from.depth > to.depth ? to : to.getAncestor(to.depth - from.depth);
392 
393         // go upward until we find a match
394         while (currentF != currentT) {
395             currentF = currentF.parent;
396             currentT = currentT.parent;
397         }
398 
399         return currentF;
400 
401     }
402 
403     /** Determine if a Frame is a child of another one.
404      * @param potentialAncestor supposed ancestor frame
405      * @return true if the potentialAncestor belongs to the
406      * path from instance to the root frame, excluding itself
407      */
408     public boolean isChildOf(final Frame potentialAncestor) {
409         if (depth <= potentialAncestor.depth) {
410             return false;
411         }
412         return getAncestor(depth - potentialAncestor.depth) == potentialAncestor;
413     }
414 
415     /** Get the unique root frame.
416      * @return the unique instance of the root frame
417      */
418     public static Frame getRoot() {
419         return LazyRootHolder.INSTANCE;
420     }
421 
422     /** Get a new version of the instance, frozen with respect to a reference frame.
423      * <p>
424      * Freezing a frame consist in computing its position and orientation with respect
425      * to another frame at some freezing date and fixing them so they do not depend
426      * on time anymore. This means the frozen frame is fixed with respect to the
427      * reference frame.
428      * </p>
429      * <p>
430      * One typical use of this method is to compute an inertial launch reference frame
431      * by freezing a {@link TopocentricFrame topocentric frame} at launch date
432      * with respect to an inertial frame. Another use is to freeze an equinox-related
433      * celestial frame at a reference epoch date.
434      * </p>
435      * <p>
436      * Only the frame returned by this method is frozen, the instance by itself
437      * is not affected by calling this method and still moves freely.
438      * </p>
439      * @param reference frame with respect to which the instance will be frozen
440      * @param freezingDate freezing date
441      * @param frozenName name of the frozen frame
442      * @return a frozen version of the instance
443      */
444     public Frame getFrozenFrame(final Frame reference, final AbsoluteDate freezingDate,
445                                 final String frozenName) {
446         return new Frame(reference, reference.getTransformTo(this, freezingDate).freeze(),
447                          frozenName, reference.isPseudoInertial());
448     }
449 
450     // We use the Initialization on demand holder idiom to store
451     // the singletons, as it is both thread-safe, efficient (no
452     // synchronization) and works with all versions of java.
453 
454     /** Holder for the root frame singleton. */
455     private static class LazyRootHolder {
456 
457         /** Unique instance. */
458         private static final Frame INSTANCE = new Frame(Predefined.GCRF.getName(), true) {
459 
460             /** Serializable UID. */
461             private static final long serialVersionUID = -2654403496396721543L;
462 
463             /** Replace the instance with a data transfer object for serialization.
464              * <p>
465              * This intermediate class serializes nothing.
466              * </p>
467              * @return data transfer object that will be serialized
468              */
469             private Object writeReplace() {
470                 return new DataTransferObject();
471             }
472 
473         };
474 
475         /** Private constructor.
476          * <p>This class is a utility class, it should neither have a public
477          * nor a default constructor. This private constructor prevents
478          * the compiler from generating one automatically.</p>
479          */
480         private LazyRootHolder() {
481         }
482 
483     }
484 
485     /** Internal class used only for serialization. */
486     private static class DataTransferObject implements Serializable {
487 
488         /** Serializable UID. */
489         private static final long serialVersionUID = 4067764035816491212L;
490 
491         /** Simple constructor.
492          */
493         private DataTransferObject() {
494         }
495 
496         /** Replace the deserialized data transfer object with a {@link FactoryManagedFrame}.
497          * @return replacement {@link FactoryManagedFrame}
498          */
499         private Object readResolve() {
500             return getRoot();
501         }
502 
503     }
504 
505 }