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 kinematic portion of the transform from the instance to another
272      * frame. The returned transform is kinematic in the sense that it includes
273      * translations and rotations, with rates, but cannot transform an acceleration vector.
274      *
275      * <p>This method is often more performant than {@link
276      * #getTransformTo(Frame, AbsoluteDate)} when accelerations 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 kinematic transform from the instance to the destination frame
283      * @since 12.1
284      */
285     public KinematicTransform getKinematicTransformTo(final Frame destination, final AbsoluteDate date) {
286         return getTransformTo(
287             destination,
288             KinematicTransform.getIdentity(),
289             frame -> frame.getTransformProvider().getKinematicTransform(date),
290             (t1, t2) -> KinematicTransform.compose(date, t1, t2),
291             KinematicTransform::getInverse);
292     }
293 
294     /**
295      * Get the static portion of the transform from the instance to another
296      * frame. The returned transform is static in the sense that it includes
297      * translations and rotations, but not rates.
298      *
299      * <p>This method is often more performant than {@link
300      * #getTransformTo(Frame, AbsoluteDate)} when rates are not needed.
301      *
302      * @param destination destination frame to which we want to transform
303      *                    vectors
304      * @param date        the date (can be null if it is sure than no date
305      *                    dependent frame is used)
306      * @return static transform from the instance to the destination frame
307      * @since 11.2
308      */
309     public StaticTransform getStaticTransformTo(final Frame destination,
310                                                 final AbsoluteDate date) {
311         return getTransformTo(
312                 destination,
313                 StaticTransform.getIdentity(),
314                 frame -> frame.getTransformProvider().getStaticTransform(date),
315                 (t1, t2) -> StaticTransform.compose(date, t1, t2),
316                 StaticTransform::getInverse);
317     }
318 
319     /**
320      * Get the static portion of the transform from the instance to another
321      * frame. The returned transform is static in the sense that it includes
322      * translations and rotations, but not rates.
323      *
324      * <p>This method is often more performant than {@link
325      * #getTransformTo(Frame, FieldAbsoluteDate)} when rates are not needed.
326      *
327      * <p>A first check is made on the FieldAbsoluteDate because "fielded" transforms have low-performance.<br>
328      * The date field is checked with {@link FieldElement#isZero()}.<br>
329      * If true, the un-fielded version of the transform computation is used.
330      *
331      * @param <T>         type of the elements
332      * @param destination destination frame to which we want to transform
333      *                    vectors
334      * @param date        the date (<em>must</em> be non-null, which is a more stringent condition
335      *                    than in {@link #getStaticTransformTo(Frame, AbsoluteDate)})
336      * @return static transform from the instance to the destination frame
337      * @since 12.0
338      */
339     public <T extends CalculusFieldElement<T>> FieldStaticTransform<T> getStaticTransformTo(final Frame destination,
340                                                 final FieldAbsoluteDate<T> date) {
341         if (date.hasZeroField()) {
342             // If date field is Zero, then use the un-fielded version for performances
343             return FieldStaticTransform.of(date, getStaticTransformTo(destination, date.toAbsoluteDate()));
344 
345         } else {
346             // Use classic fielded function
347             return getTransformTo(destination,
348                                   FieldStaticTransform.getIdentity(date.getField()),
349                                   frame -> frame.getTransformProvider().getStaticTransform(date),
350                                   (t1, t2) -> FieldStaticTransform.compose(date, t1, t2),
351                                   FieldStaticTransform::getInverse);
352         }
353     }
354 
355     /**
356      * Get the kinematic portion of the transform from the instance to another
357      * frame. The returned transform is kinematic in the sense that it includes
358      * translations and rotations, with rates, but cannot transform an acceleration vector.
359      *
360      * <p>This method is often more performant than {@link
361      * #getTransformTo(Frame, AbsoluteDate)} when accelerations are not needed.
362      * @param <T>          Type of transform returned.
363      * @param destination destination frame to which we want to transform
364      *                    vectors
365      * @param date        the date (<em>must</em> be non-null, which is a more stringent condition
366      *      *                    than in {@link #getKinematicTransformTo(Frame, AbsoluteDate)})
367      * @return kinematic transform from the instance to the destination frame
368      * @since 12.1
369      */
370     public <T extends CalculusFieldElement<T>> FieldKinematicTransform<T> getKinematicTransformTo(final Frame destination,
371                                                                                                   final FieldAbsoluteDate<T> date) {
372         if (date.hasZeroField()) {
373             // If date field is Zero, then use the un-fielded version for performances
374             final KinematicTransform kinematicTransform = getKinematicTransformTo(destination, date.toAbsoluteDate());
375             return FieldKinematicTransform.of(date.getField(), kinematicTransform);
376 
377         } else {
378             // Use classic fielded function
379             return getTransformTo(destination,
380                     FieldKinematicTransform.getIdentity(date.getField()),
381                     frame -> frame.getTransformProvider().getKinematicTransform(date),
382                     (t1, t2) -> FieldKinematicTransform.compose(date, t1, t2),
383                     FieldKinematicTransform::getInverse);
384         }
385     }
386 
387     /**
388      * Generic get transform method that builds the transform from {@code this}
389      * to {@code destination}.
390      *
391      * @param destination  destination frame to which we want to transform
392      *                     vectors
393      * @param identity     transform of the given type.
394      * @param getTransform method to get a transform from a frame.
395      * @param compose      method to combine two transforms.
396      * @param inverse      method to invert a transform.
397      * @param <T>          Type of transform returned.
398      * @return composite transform.
399      */
400     private <T> T getTransformTo(final Frame destination,
401                                  final T identity,
402                                  final Function<Frame, T> getTransform,
403                                  final BiFunction<T, T, T> compose,
404                                  final Function<T, T> inverse) {
405 
406         if (this == destination) {
407             // shortcut for special case that may be frequent
408             return identity;
409         }
410 
411         // common ancestor to both frames in the frames tree
412         final Frame common = findCommon(this, destination);
413 
414         // transform from common to instance
415         T commonToInstance = identity;
416         for (Frame frame = this; frame != common; frame = frame.parent) {
417             commonToInstance = compose.apply(getTransform.apply(frame), commonToInstance);
418         }
419 
420         // transform from destination up to common
421         T commonToDestination = identity;
422         for (Frame frame = destination; frame != common; frame = frame.parent) {
423             commonToDestination = compose.apply(getTransform.apply(frame), commonToDestination);
424         }
425 
426         // transform from instance to destination via common
427         return compose.apply(inverse.apply(commonToInstance), commonToDestination);
428 
429     }
430 
431     /** Get the provider for transform from parent frame to instance.
432      * @return provider for transform from parent frame to instance
433      */
434     public TransformProvider getTransformProvider() {
435         return transformProvider;
436     }
437 
438     /** Find the deepest common ancestor of two frames in the frames tree.
439      * @param from origin frame
440      * @param to destination frame
441      * @return an ancestor frame of both <code>from</code> and <code>to</code>
442      */
443     private static Frame findCommon(final Frame from, final Frame to) {
444 
445         // select deepest frames that could be the common ancestor
446         Frame currentF = from.depth > to.depth ? from.getAncestor(from.depth - to.depth) : from;
447         Frame currentT = from.depth > to.depth ? to : to.getAncestor(to.depth - from.depth);
448 
449         // go upward until we find a match
450         while (currentF != currentT) {
451             currentF = currentF.parent;
452             currentT = currentT.parent;
453         }
454 
455         return currentF;
456 
457     }
458 
459     /** Determine if a Frame is a child of another one.
460      * @param potentialAncestor supposed ancestor frame
461      * @return true if the potentialAncestor belongs to the
462      * path from instance to the root frame, excluding itself
463      */
464     public boolean isChildOf(final Frame potentialAncestor) {
465         if (depth <= potentialAncestor.depth) {
466             return false;
467         }
468         return getAncestor(depth - potentialAncestor.depth) == potentialAncestor;
469     }
470 
471     /** Get the unique root frame.
472      * @return the unique instance of the root frame
473      */
474     public static Frame getRoot() {
475         return LazyRootHolder.INSTANCE;
476     }
477 
478     /** Get a new version of the instance, frozen with respect to a reference frame.
479      * <p>
480      * Freezing a frame consist in computing its position and orientation with respect
481      * to another frame at some freezing date and fixing them so they do not depend
482      * on time anymore. This means the frozen frame is fixed with respect to the
483      * reference frame.
484      * </p>
485      * <p>
486      * One typical use of this method is to compute an inertial launch reference frame
487      * by freezing a {@link TopocentricFrame topocentric frame} at launch date
488      * with respect to an inertial frame. Another use is to freeze an equinox-related
489      * celestial frame at a reference epoch date.
490      * </p>
491      * <p>
492      * Only the frame returned by this method is frozen, the instance by itself
493      * is not affected by calling this method and still moves freely.
494      * </p>
495      * @param reference frame with respect to which the instance will be frozen
496      * @param freezingDate freezing date
497      * @param frozenName name of the frozen frame
498      * @return a frozen version of the instance
499      */
500     public Frame getFrozenFrame(final Frame reference, final AbsoluteDate freezingDate,
501                                 final String frozenName) {
502         return new Frame(reference, reference.getTransformTo(this, freezingDate).freeze(),
503                          frozenName, reference.isPseudoInertial());
504     }
505 
506     // We use the Initialization on demand holder idiom to store
507     // the singletons, as it is both thread-safe, efficient (no
508     // synchronization) and works with all versions of java.
509 
510     /** Holder for the root frame singleton. */
511     private static class LazyRootHolder {
512 
513         /** Unique instance. */
514         private static final Frame INSTANCE = new Frame(Predefined.GCRF.getName(), true) {
515 
516             /** Serializable UID. */
517             private static final long serialVersionUID = -2654403496396721543L;
518 
519             /** Replace the instance with a data transfer object for serialization.
520              * <p>
521              * This intermediate class serializes nothing.
522              * </p>
523              * @return data transfer object that will be serialized
524              */
525             private Object writeReplace() {
526                 return new DataTransferObject();
527             }
528 
529         };
530 
531         /** Private constructor.
532          * <p>This class is a utility class, it should neither have a public
533          * nor a default constructor. This private constructor prevents
534          * the compiler from generating one automatically.</p>
535          */
536         private LazyRootHolder() {
537         }
538 
539     }
540 
541     /** Internal class used only for serialization. */
542     private static class DataTransferObject implements Serializable {
543 
544         /** Serializable UID. */
545         private static final long serialVersionUID = 4067764035816491212L;
546 
547         /** Simple constructor.
548          */
549         private DataTransferObject() {
550         }
551 
552         /** Replace the deserialized data transfer object with a {@link FactoryManagedFrame}.
553          * @return replacement {@link FactoryManagedFrame}
554          */
555         private Object readResolve() {
556             return getRoot();
557         }
558 
559     }
560 
561 }