1   /* Copyright 2002-2022 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.Field;
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 (can be null if it is sure than no date dependent frame is used)
257      * @param <T> the type of the field elements
258      * @return transform from the instance to the destination frame
259      */
260     public <T extends CalculusFieldElement<T>> FieldTransform<T> getTransformTo(final Frame destination, final FieldAbsoluteDate<T> date) {
261         final Field<T> field = date.getField();
262         return getTransformTo(
263                 destination,
264                 FieldTransform.getIdentity(field),
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      * Generic get transform method that builds the transform from {@code this}
297      * to {@code destination}.
298      *
299      * @param destination  destination frame to which we want to transform
300      *                     vectors
301      * @param identity     transform of the given type.
302      * @param getTransform method to get a transform from a frame.
303      * @param compose      method to combine two transforms.
304      * @param inverse      method to invert a transform.
305      * @param <T>          Type of transform returned.
306      * @return composite transform.
307      */
308     private <T> T getTransformTo(final Frame destination,
309                                  final T identity,
310                                  final Function<Frame, T> getTransform,
311                                  final BiFunction<T, T, T> compose,
312                                  final Function<T, T> inverse) {
313 
314         if (this == destination) {
315             // shortcut for special case that may be frequent
316             return identity;
317         }
318 
319         // common ancestor to both frames in the frames tree
320         final Frame common = findCommon(this, destination);
321 
322         // transform from common to instance
323         T commonToInstance = identity;
324         for (Frame frame = this; frame != common; frame = frame.parent) {
325             commonToInstance = compose.apply(getTransform.apply(frame), commonToInstance);
326         }
327 
328         // transform from destination up to common
329         T commonToDestination = identity;
330         for (Frame frame = destination; frame != common; frame = frame.parent) {
331             commonToDestination = compose.apply(getTransform.apply(frame), commonToDestination);
332         }
333 
334         // transform from instance to destination via common
335         return compose.apply(inverse.apply(commonToInstance), commonToDestination);
336 
337     }
338 
339     /** Get the provider for transform from parent frame to instance.
340      * @return provider for transform from parent frame to instance
341      */
342     public TransformProvider getTransformProvider() {
343         return transformProvider;
344     }
345 
346     /** Find the deepest common ancestor of two frames in the frames tree.
347      * @param from origin frame
348      * @param to destination frame
349      * @return an ancestor frame of both <code>from</code> and <code>to</code>
350      */
351     private static Frame findCommon(final Frame from, final Frame to) {
352 
353         // select deepest frames that could be the common ancestor
354         Frame currentF = from.depth > to.depth ? from.getAncestor(from.depth - to.depth) : from;
355         Frame currentT = from.depth > to.depth ? to : to.getAncestor(to.depth - from.depth);
356 
357         // go upward until we find a match
358         while (currentF != currentT) {
359             currentF = currentF.parent;
360             currentT = currentT.parent;
361         }
362 
363         return currentF;
364 
365     }
366 
367     /** Determine if a Frame is a child of another one.
368      * @param potentialAncestor supposed ancestor frame
369      * @return true if the potentialAncestor belongs to the
370      * path from instance to the root frame, excluding itself
371      */
372     public boolean isChildOf(final Frame potentialAncestor) {
373         if (depth <= potentialAncestor.depth) {
374             return false;
375         }
376         return getAncestor(depth - potentialAncestor.depth) == potentialAncestor;
377     }
378 
379     /** Get the unique root frame.
380      * @return the unique instance of the root frame
381      */
382     public static Frame getRoot() {
383         return LazyRootHolder.INSTANCE;
384     }
385 
386     /** Get a new version of the instance, frozen with respect to a reference frame.
387      * <p>
388      * Freezing a frame consist in computing its position and orientation with respect
389      * to another frame at some freezing date and fixing them so they do not depend
390      * on time anymore. This means the frozen frame is fixed with respect to the
391      * reference frame.
392      * </p>
393      * <p>
394      * One typical use of this method is to compute an inertial launch reference frame
395      * by freezing a {@link TopocentricFrame topocentric frame} at launch date
396      * with respect to an inertial frame. Another use is to freeze an equinox-related
397      * celestial frame at a reference epoch date.
398      * </p>
399      * <p>
400      * Only the frame returned by this method is frozen, the instance by itself
401      * is not affected by calling this method and still moves freely.
402      * </p>
403      * @param reference frame with respect to which the instance will be frozen
404      * @param freezingDate freezing date
405      * @param frozenName name of the frozen frame
406      * @return a frozen version of the instance
407      */
408     public Frame getFrozenFrame(final Frame reference, final AbsoluteDate freezingDate,
409                                 final String frozenName) {
410         return new Frame(reference, reference.getTransformTo(this, freezingDate).freeze(),
411                          frozenName, reference.isPseudoInertial());
412     }
413 
414     // We use the Initialization on demand holder idiom to store
415     // the singletons, as it is both thread-safe, efficient (no
416     // synchronization) and works with all versions of java.
417 
418     /** Holder for the root frame singleton. */
419     private static class LazyRootHolder {
420 
421         /** Unique instance. */
422         private static final Frame INSTANCE = new Frame(Predefined.GCRF.getName(), true) {
423 
424             /** Serializable UID. */
425             private static final long serialVersionUID = -2654403496396721543L;
426 
427             /** Replace the instance with a data transfer object for serialization.
428              * <p>
429              * This intermediate class serializes nothing.
430              * </p>
431              * @return data transfer object that will be serialized
432              */
433             private Object writeReplace() {
434                 return new DataTransferObject();
435             }
436 
437         };
438 
439         /** Private constructor.
440          * <p>This class is a utility class, it should neither have a public
441          * nor a default constructor. This private constructor prevents
442          * the compiler from generating one automatically.</p>
443          */
444         private LazyRootHolder() {
445         }
446 
447     }
448 
449     /** Internal class used only for serialization. */
450     private static class DataTransferObject implements Serializable {
451 
452         /** Serializable UID. */
453         private static final long serialVersionUID = 4067764035816491212L;
454 
455         /** Simple constructor.
456          */
457         private DataTransferObject() {
458         }
459 
460         /** Replace the deserialized data transfer object with a {@link FactoryManagedFrame}.
461          * @return replacement {@link FactoryManagedFrame}
462          */
463         private Object readResolve() {
464             return getRoot();
465         }
466 
467     }
468 
469 }