AttitudesSequence.java

  1. /* Copyright 2002-2025 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.attitudes;

  18. import java.util.ArrayList;
  19. import java.util.Arrays;
  20. import java.util.List;
  21. import java.util.stream.Stream;

  22. import org.hipparchus.CalculusFieldElement;
  23. import org.hipparchus.Field;
  24. import org.hipparchus.ode.events.Action;
  25. import org.orekit.errors.OrekitException;
  26. import org.orekit.errors.OrekitMessages;
  27. import org.orekit.frames.Frame;
  28. import org.orekit.propagation.SpacecraftState;
  29. import org.orekit.propagation.events.EventDetector;
  30. import org.orekit.propagation.events.FieldEventDetector;
  31. import org.orekit.time.AbsoluteDate;
  32. import org.orekit.time.FieldAbsoluteDate;
  33. import org.orekit.time.FieldTimeInterpolator;
  34. import org.orekit.time.TimeInterpolator;
  35. import org.orekit.utils.AngularDerivativesFilter;
  36. import org.orekit.utils.FieldPVCoordinatesProvider;
  37. import org.orekit.utils.PVCoordinatesProvider;
  38. import org.orekit.utils.TimeStampedAngularCoordinates;
  39. import org.orekit.utils.TimeStampedAngularCoordinatesHermiteInterpolator;
  40. import org.orekit.utils.TimeStampedFieldAngularCoordinates;
  41. import org.orekit.utils.TimeStampedFieldAngularCoordinatesHermiteInterpolator;

  42. /** This classes manages a sequence of different attitude providers that are activated
  43.  * in turn according to switching events. It includes non-zero transition durations between subsequent modes.
  44.  * @author Luc Maisonobe
  45.  * @since 5.1
  46.  * @see AttitudesSwitcher
  47.  */
  48. public class AttitudesSequence extends AbstractSwitchingAttitudeProvider {

  49.     /** Switching events list. */
  50.     private final List<Switch> switches;

  51.     /** Constructor for an initially empty sequence.
  52.      */
  53.     public AttitudesSequence() {
  54.         super();
  55.         switches = new ArrayList<>();
  56.     }

  57.     /** Add a switching condition between two attitude providers.
  58.      * <p>
  59.      * The {@code past} and {@code future} attitude providers are defined with regard
  60.      * to the natural flow of time. This means that if the propagation is forward, the
  61.      * propagator will switch from {@code past} provider to {@code future} provider at
  62.      * event occurrence, but if the propagation is backward, the propagator will switch
  63.      * from {@code future} provider to {@code past} provider at event occurrence. The
  64.      * transition between the two attitude laws is not instantaneous, the switch event
  65.      * defines the start of the transition (i.e. when leaving the {@code past} attitude
  66.      * law and entering the interpolated transition law). The end of the transition
  67.      * (i.e. when leaving the interpolating transition law and entering the {@code future}
  68.      * attitude law) occurs at switch time plus {@code transitionTime}.
  69.      * </p>
  70.      * <p>
  71.      * An attitude provider may have several different switch events associated to
  72.      * it. Depending on which event is triggered, the appropriate provider is
  73.      * switched to.
  74.      * </p>
  75.      * <p>
  76.      * If the underlying detector has an event handler associated to it, this handler
  77.      * will be triggered (i.e. its {@link org.orekit.propagation.events.handlers.EventHandler#eventOccurred(SpacecraftState,
  78.      * EventDetector, boolean) eventOccurred} method will be called), <em>regardless</em>
  79.      * of the event really triggering an attitude switch or not. As an example, if an
  80.      * eclipse detector is used to switch from day to night attitude mode when entering
  81.      * eclipse, with {@code switchOnIncrease} set to {@code false} and {@code switchOnDecrease}
  82.      * set to {@code true}. Then a handler set directly at eclipse detector level would
  83.      * be triggered at both eclipse entry and eclipse exit, but attitude switch would
  84.      * occur <em>only</em> at eclipse entry. Note that for the sake of symmetry, the
  85.      * transition start and end dates should match for both forward and backward propagation.
  86.      * This implies that for backward propagation, we have to compensate for the {@code
  87.      * transitionTime} when looking for the event. An unfortunate consequence is that the
  88.      * {@link org.orekit.propagation.events.handlers.EventHandler#eventOccurred(SpacecraftState, EventDetector, boolean)
  89.      * eventOccurred} method may appear to be called out of sync with respect to the
  90.      * propagation (it will be called when propagator reaches transition end, despite it
  91.      * refers to transition start, as per {@code transitionTime} compensation), and if the
  92.      * method returns {@link Action#STOP}, it will stop at the end of the
  93.      * transition instead of at the start. For these reasons, it is not recommended to
  94.      * set up an event handler for events that are used to switch attitude. If an event
  95.      * handler is needed for other purposes, a second handler should be registered to
  96.      * the propagator rather than relying on the side effects of attitude switches.
  97.      * </p>
  98.      * <p>
  99.      * The smoothness of the transition between past and future attitude laws can be tuned
  100.      * using the {@code transitionTime} and {@code transitionFilter} parameters. The {@code
  101.      * transitionTime} parameter specifies how much time is spent to switch from one law to
  102.      * the other law. It should be larger than the event {@link EventDetector#getThreshold()
  103.      * convergence threshold} in order to ensure attitude continuity. The {@code
  104.      * transitionFilter} parameter specifies the attitude time derivatives that should match
  105.      * at the boundaries between past attitude law and transition law on one side, and
  106.      * between transition law and future law on the other side.
  107.      * {@link AngularDerivativesFilter#USE_R} means only the rotation should be identical,
  108.      * {@link AngularDerivativesFilter#USE_RR} means both rotation and rotation rate
  109.      * should be identical, {@link AngularDerivativesFilter#USE_RRA} means both rotation,
  110.      * rotation rate and rotation acceleration should be identical. During the transition,
  111.      * the attitude law is computed by interpolating between past attitude law at switch time
  112.      * and future attitude law at current intermediate time.
  113.      * </p>
  114.      * @param past attitude provider applicable for times in the switch event occurrence past
  115.      * @param future attitude provider applicable for times in the switch event occurrence future
  116.      * @param switchEvent event triggering the attitude providers switch
  117.      * @param switchOnIncrease if true, switch is triggered on increasing event
  118.      * @param switchOnDecrease if true, switch is triggered on decreasing event
  119.      * @param transitionTime duration of the transition between the past and future attitude laws
  120.      * @param transitionFilter specification of transition law time derivatives that
  121.      * should match past and future attitude laws
  122.      * @param switchHandler handler to call for notifying when switch occurs (may be null)
  123.      * @param <T> class type for the switch event
  124.      * @since 13.0
  125.      */
  126.     public <T extends EventDetector> void addSwitchingCondition(final AttitudeProvider past,
  127.                                                                 final AttitudeProvider future,
  128.                                                                 final T switchEvent,
  129.                                                                 final boolean switchOnIncrease,
  130.                                                                 final boolean switchOnDecrease,
  131.                                                                 final double transitionTime,
  132.                                                                 final AngularDerivativesFilter transitionFilter,
  133.                                                                 final AttitudeSwitchHandler switchHandler) {

  134.         // safety check, for ensuring attitude continuity
  135.         if (transitionTime < switchEvent.getThreshold()) {
  136.             throw new OrekitException(OrekitMessages.TOO_SHORT_TRANSITION_TIME_FOR_ATTITUDES_SWITCH,
  137.                                       transitionTime, switchEvent.getThreshold());
  138.         }

  139.         // if it is the first switching condition, assume first active law is the past one
  140.         if (getActivated() == null) {
  141.             resetActiveProvider(past);
  142.         }

  143.         // add the switching condition
  144.         switches.add(new Switch(switchEvent, switchOnIncrease, switchOnDecrease,
  145.                                 past, future, transitionTime, transitionFilter, switchHandler));

  146.     }

  147.     @Override
  148.     public Stream<EventDetector> getEventDetectors() {
  149.         return Stream.concat(switches.stream().map(Switch.class::cast), getEventDetectors(getParametersDrivers()));
  150.     }

  151.     @Override
  152.     public <T extends CalculusFieldElement<T>> Stream<FieldEventDetector<T>> getFieldEventDetectors(final Field<T> field) {
  153.         final Stream<FieldEventDetector<T>> switchesStream = switches.stream().map(sw -> getFieldEventDetector(field, sw));
  154.         return Stream.concat(switchesStream, getFieldEventDetectors(field, getParametersDrivers()));
  155.     }

  156.     /**
  157.      * Gets a deep copy of the switches stored in this instance.
  158.      *
  159.      * @return deep copy of the switches stored in this instance
  160.      */
  161.     public List<Switch> getSwitches() {
  162.         return new ArrayList<>(switches);
  163.     }

  164.     /** Switch specification. Handles the transition. */
  165.     public class Switch extends AbstractAttitudeSwitch {

  166.         /** Duration of the transition between the past and future attitude laws. */
  167.         private final double transitionTime;

  168.         /** Order at which the transition law time derivatives should match past and future attitude laws. */
  169.         private final AngularDerivativesFilter transitionFilter;

  170.         /** Propagation direction. */
  171.         private boolean forward;

  172.         /**
  173.          * Simple constructor.
  174.          *
  175.          * @param event event
  176.          * @param switchOnIncrease if true, switch is triggered on increasing event
  177.          * @param switchOnDecrease if true, switch is triggered on decreasing event otherwise switch is triggered on
  178.          * decreasing event
  179.          * @param past attitude provider applicable for times in the switch event occurrence past
  180.          * @param future attitude provider applicable for times in the switch event occurrence future
  181.          * @param transitionTime duration of the transition between the past and future attitude laws
  182.          * @param transitionFilter order at which the transition law time derivatives should match past and future attitude
  183.          * laws
  184.          * @param switchHandler handler to call for notifying when switch occurs (may be null)
  185.          */
  186.         private Switch(final EventDetector event, final boolean switchOnIncrease, final boolean switchOnDecrease,
  187.                        final AttitudeProvider past, final AttitudeProvider future, final double transitionTime,
  188.                        final AngularDerivativesFilter transitionFilter, final AttitudeSwitchHandler switchHandler) {
  189.             super(event, switchOnIncrease, switchOnDecrease, past, future, switchHandler);
  190.             this.transitionTime   = transitionTime;
  191.             this.transitionFilter = transitionFilter;
  192.         }

  193.         /** {@inheritDoc} */
  194.         @Override
  195.         public void init(final SpacecraftState s0, final AbsoluteDate t) {
  196.             super.init(s0, t);

  197.             // reset the transition parameters (this will be done once for each switch,
  198.             //  despite doing it only once would have sufficient; it's not really a problem)
  199.             forward = t.durationFrom(s0.getDate()) >= 0.0;
  200.             if (getActivated().getSpansNumber() > 1) {
  201.                 // remove transitions that will be overridden during upcoming propagation
  202.                 if (forward) {
  203.                     setActivated(getActivated().extractRange(AbsoluteDate.PAST_INFINITY, s0.getDate().shiftedBy(transitionTime)));
  204.                 } else {
  205.                     setActivated(getActivated().extractRange(s0.getDate().shiftedBy(-transitionTime), AbsoluteDate.FUTURE_INFINITY));
  206.                 }
  207.             }

  208.         }

  209.         /** {@inheritDoc} */
  210.         @Override
  211.         public double g(final SpacecraftState s) {
  212.             return getDetector().g(forward ? s : s.shiftedBy(-transitionTime));
  213.         }

  214.         /** {@inheritDoc} */
  215.         public Action eventOccurred(final SpacecraftState s, final EventDetector detector, final boolean increasing) {

  216.             final AbsoluteDate date = s.getDate();
  217.             if (getActivated().get(date) == (forward ? getPast() : getFuture()) &&
  218.                 (increasing && isSwitchOnIncrease() || !increasing && isSwitchOnDecrease())) {

  219.                 if (forward) {

  220.                     // prepare transition
  221.                     final AbsoluteDate transitionEnd = date.shiftedBy(transitionTime);
  222.                     getActivated().addValidAfter(new TransitionProvider(s.getAttitude(), transitionEnd), date, false);

  223.                     // prepare future law after transition
  224.                     getActivated().addValidAfter(getFuture(), transitionEnd, false);

  225.                     // notify about the switch
  226.                     if (getSwitchHandler() != null) {
  227.                         getSwitchHandler().switchOccurred(getPast(), getFuture(), s);
  228.                     }

  229.                     return getDetector().getHandler().eventOccurred(s, getDetector(), increasing);

  230.                 } else {

  231.                     // estimate state at transition start, according to the past attitude law
  232.                     final double dt = -transitionTime;
  233.                     final AbsoluteDate shiftedDate = date.shiftedBy(dt);
  234.                     final SpacecraftState shiftedState = s.shiftedBy(dt);
  235.                     final Attitude sAttitude;
  236.                     if (s.isOrbitDefined()) {
  237.                         sAttitude = getPast().getAttitude(shiftedState.getOrbit(), shiftedDate, s.getFrame());
  238.                     } else {
  239.                         sAttitude = getPast().getAttitude(shiftedState.getAbsPVA(), shiftedDate, s.getFrame());
  240.                     }
  241.                     final SpacecraftState sState    = shiftedState.withAttitude(sAttitude).withMass(s.getMass());

  242.                     // prepare transition
  243.                     getActivated().addValidBefore(new TransitionProvider(sAttitude, date), date, false);

  244.                     // prepare past law before transition
  245.                     getActivated().addValidBefore(getPast(), shiftedDate, false);

  246.                     // notify about the switch
  247.                     if (getSwitchHandler() != null) {
  248.                         getSwitchHandler().switchOccurred(getFuture(), getPast(), sState);
  249.                     }

  250.                     return getDetector().getHandler().eventOccurred(sState, getDetector(), increasing);

  251.                 }

  252.             } else {
  253.                 // trigger the underlying event despite no attitude switch occurred
  254.                 return getDetector().getHandler().eventOccurred(s, getDetector(), increasing);
  255.             }

  256.         }

  257.         /** Provider for transition phases.
  258.          * @since 9.2
  259.          */
  260.         private class TransitionProvider implements AttitudeProvider {

  261.             /** Attitude at preceding transition. */
  262.             private final Attitude transitionPreceding;

  263.             /** Date of final switch to following attitude law. */
  264.             private final AbsoluteDate transitionEnd;

  265.             /** Simple constructor.
  266.              * @param transitionPreceding attitude at preceding transition
  267.              * @param transitionEnd date of final switch to following attitude law
  268.              */
  269.             TransitionProvider(final Attitude transitionPreceding, final AbsoluteDate transitionEnd) {
  270.                 this.transitionPreceding = transitionPreceding;
  271.                 this.transitionEnd       = transitionEnd;
  272.             }

  273.             /** {@inheritDoc} */
  274.             public Attitude getAttitude(final PVCoordinatesProvider pvProv,
  275.                                         final AbsoluteDate date, final Frame frame) {

  276.                 // Create sample
  277.                 final TimeStampedAngularCoordinates start =
  278.                         transitionPreceding.withReferenceFrame(frame).getOrientation();
  279.                 final TimeStampedAngularCoordinates end =
  280.                         getFuture().getAttitude(pvProv, transitionEnd, frame).getOrientation();
  281.                 final List<TimeStampedAngularCoordinates> sample =  Arrays.asList(start, end);

  282.                 // Create interpolator
  283.                 final TimeInterpolator<TimeStampedAngularCoordinates> interpolator =
  284.                         new TimeStampedAngularCoordinatesHermiteInterpolator(sample.size(), transitionFilter);

  285.                 // interpolate between the two boundary attitudes
  286.                 final TimeStampedAngularCoordinates interpolated = interpolator.interpolate(date, sample);

  287.                 return new Attitude(frame, interpolated);

  288.             }

  289.             /** {@inheritDoc} */
  290.             public <S extends CalculusFieldElement<S>> FieldAttitude<S> getAttitude(final FieldPVCoordinatesProvider<S> pvProv,
  291.                                                                                     final FieldAbsoluteDate<S> date,
  292.                                                                                     final Frame frame) {

  293.                 // create sample
  294.                 final TimeStampedFieldAngularCoordinates<S> start =
  295.                         new TimeStampedFieldAngularCoordinates<>(date.getField(),
  296.                                                                  transitionPreceding.withReferenceFrame(frame).getOrientation());
  297.                 final TimeStampedFieldAngularCoordinates<S> end =
  298.                         getFuture().getAttitude(pvProv,
  299.                                            new FieldAbsoluteDate<>(date.getField(), transitionEnd),
  300.                                            frame).getOrientation();
  301.                 final List<TimeStampedFieldAngularCoordinates<S>> sample = Arrays.asList(start, end);

  302.                 // create interpolator
  303.                 final FieldTimeInterpolator<TimeStampedFieldAngularCoordinates<S>, S> interpolator =
  304.                         new TimeStampedFieldAngularCoordinatesHermiteInterpolator<>(sample.size(), transitionFilter);

  305.                 // interpolate between the two boundary attitudes
  306.                 final TimeStampedFieldAngularCoordinates<S> interpolated = interpolator.interpolate(date, sample);

  307.                 return new FieldAttitude<>(frame, interpolated);
  308.             }

  309.         }

  310.     }

  311. }