PropagatorsParallelizer.java

  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.propagation;

  18. import java.util.ArrayList;
  19. import java.util.Collections;
  20. import java.util.List;
  21. import java.util.concurrent.ExecutionException;
  22. import java.util.concurrent.ExecutorService;
  23. import java.util.concurrent.Executors;
  24. import java.util.concurrent.Future;
  25. import java.util.concurrent.SynchronousQueue;
  26. import java.util.concurrent.TimeUnit;

  27. import org.hipparchus.exception.LocalizedCoreFormats;
  28. import org.hipparchus.util.FastMath;
  29. import org.orekit.errors.OrekitException;
  30. import org.orekit.propagation.sampling.MultiSatStepHandler;
  31. import org.orekit.propagation.sampling.OrekitStepHandler;
  32. import org.orekit.propagation.sampling.OrekitStepInterpolator;
  33. import org.orekit.time.AbsoluteDate;

  34. /** This class provides a way to propagate simultaneously several orbits.
  35.  *
  36.  * <p>
  37.  * Multi-satellites propagation is based on multi-threading. Therefore,
  38.  * care must be taken so that all propagators can be run in a multi-thread
  39.  * context. This implies that all propagators are built independently and
  40.  * that they rely on force models that are also built independently. An
  41.  * obvious mistake would be to reuse a maneuver force model, as these models
  42.  * need to cache the firing/not-firing status. Objects used by force models
  43.  * like atmosphere models for drag force or others may also cache intermediate
  44.  * variables, so separate instances for each propagator must be set up.
  45.  * </p>
  46.  * <p>
  47.  * This class <em>will</em> create new threads for running the propagators.
  48.  * It adds a new {@link MultiSatStepHandler global step handler} to manage
  49.  * the steps all at once, in addition to the existing individual step
  50.  * handlers that are preserved.
  51.  * </p>
  52.  * <p>
  53.  * All propagators remain independent of each other (they don't even know
  54.  * they are managed by the parallelizer) and advance their simulation
  55.  * time following their own algorithm. The parallelizer will block them
  56.  * at the end of each step and allow them to continue in order to maintain
  57.  * synchronization. The {@link MultiSatStepHandler global handler} will
  58.  * experience perfectly synchronized steps, but some propagators may already
  59.  * be slightly ahead of time as depicted in the following rendering; were
  60.  * simulation times flows from left to right:
  61.  * </p>
  62.  * <pre>
  63.  *    propagator 1   : -------------[++++current step++++]&gt;
  64.  *                                  |
  65.  *    propagator 2   : ----[++++current step++++]---------&gt;
  66.  *                                  |           |
  67.  *    ...                           |           |
  68.  *    propagator n   : ---------[++++current step++++]----&gt;
  69.  *                                  |           |
  70.  *                                  V           V
  71.  *    global handler : -------------[global step]---------&gt;
  72.  * </pre>
  73.  * <p>
  74.  * The previous sketch shows that propagator 1 has already computed states
  75.  * up to the end of the propagation, but propagators 2 up to n are still late.
  76.  * The global step seen by the handler will be the common part between all
  77.  * propagators steps. Once this global step has been handled, the parallelizer
  78.  * will let the more late propagator (here propagator 2) to go one step further
  79.  * and a new global step will be computed and handled, until all propagators
  80.  * reach the end.
  81.  * </p>
  82.  * <p>
  83.  * This class does <em>not</em> provide multi-satellite events. As events
  84.  * may truncate steps and even reset state, all events (including multi-satellite
  85.  * events) are handled at a very low level within each propagators and cannot be
  86.  * managed from outside by the parallelizer. For accurate handling of multi-satellite
  87.  * events, the event detector should be registered <em>within</em> the propagator
  88.  * of one satellite and have access to an independent propagator (typically an
  89.  * analytical propagator or an ephemeris) of the other satellite. As the embedded
  90.  * propagator will be called by the detector which itself is called by the first
  91.  * propagator, it should really be a dedicated propagator and should not also
  92.  * appear as one of the parallelized propagators, otherwise conflicts will appear here.
  93.  * </p>
  94.  * @author Luc Maisonobe
  95.  * @since 9.0
  96.  */

  97. public class PropagatorsParallelizer {

  98.     /** Waiting time to avoid getting stuck waiting for interrupted threads (ms). */
  99.     private static long MAX_WAIT = 10;

  100.     /** Underlying propagators. */
  101.     private final List<Propagator> propagators;

  102.     /** Global step handler. */
  103.     private final MultiSatStepHandler globalHandler;

  104.     /** Simple constructor.
  105.      * @param propagators list of propagators to use
  106.      * @param globalHandler global handler for managing all spacecrafts
  107.      * simultaneously
  108.      */
  109.     public PropagatorsParallelizer(final List<Propagator> propagators,
  110.                                    final MultiSatStepHandler globalHandler) {
  111.         this.propagators = propagators;
  112.         this.globalHandler = globalHandler;
  113.     }

  114.     /** Get an unmodifiable list of the underlying mono-satellite propagators.
  115.      * @return unmodifiable list of the underlying mono-satellite propagators
  116.      */
  117.     public List<Propagator> getPropagators() {
  118.         return Collections.unmodifiableList(propagators);
  119.     }

  120.     /** Propagate from a start date towards a target date.
  121.      * @param start start date from which orbit state should be propagated
  122.      * @param target target date to which orbit state should be propagated
  123.      * @return propagated states
  124.      */
  125.     public List<SpacecraftState> propagate(final AbsoluteDate start, final AbsoluteDate target) {

  126.         if (propagators.size() == 1) {
  127.             // special handling when only one propagator is used
  128.             propagators.get(0).getMultiplexer().add(new SinglePropagatorHandler(globalHandler));
  129.             return Collections.singletonList(propagators.get(0).propagate(start, target));
  130.         }

  131.         final double sign = FastMath.copySign(1.0, target.durationFrom(start));

  132.         // start all propagators in concurrent threads
  133.         final ExecutorService            executorService = Executors.newFixedThreadPool(propagators.size());
  134.         final List<PropagatorMonitoring> monitors        = new ArrayList<>(propagators.size());
  135.         for (final Propagator propagator : propagators) {
  136.             final PropagatorMonitoring monitor = new PropagatorMonitoring(propagator, start, target, executorService);
  137.             monitor.waitFirstStepCompletion();
  138.             monitors.add(monitor);
  139.         }

  140.         // main loop
  141.         AbsoluteDate previousDate = start;
  142.         final List<SpacecraftState> initialStates = new ArrayList<>(monitors.size());
  143.         for (final PropagatorMonitoring monitor : monitors) {
  144.             initialStates.add(monitor.parameters.initialState);
  145.         }
  146.         globalHandler.init(initialStates, target);
  147.         for (boolean isLast = false; !isLast;) {

  148.             // select the earliest ending propagator, according to propagation direction
  149.             PropagatorMonitoring selected = null;
  150.             AbsoluteDate selectedStepEnd  = null;
  151.             for (PropagatorMonitoring monitor : monitors) {
  152.                 final AbsoluteDate stepEnd = monitor.parameters.interpolator.getCurrentState().getDate();
  153.                 if (selected == null || sign * selectedStepEnd.durationFrom(stepEnd) > 0) {
  154.                     selected        = monitor;
  155.                     selectedStepEnd = stepEnd;
  156.                 }
  157.             }

  158.             // restrict steps to a common time range
  159.             for (PropagatorMonitoring monitor : monitors) {
  160.                 final OrekitStepInterpolator interpolator  = monitor.parameters.interpolator;
  161.                 final SpacecraftState        previousState = interpolator.getInterpolatedState(previousDate);
  162.                 final SpacecraftState        currentState  = interpolator.getInterpolatedState(selectedStepEnd);
  163.                 monitor.restricted                         = interpolator.restrictStep(previousState, currentState);
  164.             }

  165.             // handle all states at once
  166.             final List<OrekitStepInterpolator> interpolators = new ArrayList<>(monitors.size());
  167.             for (final PropagatorMonitoring monitor : monitors) {
  168.                 interpolators.add(monitor.restricted);
  169.             }
  170.             globalHandler.handleStep(interpolators);

  171.             if (selected.parameters.finalState == null) {
  172.                 // step handler can still provide new results
  173.                 // this will wait until either handleStep or finish are called
  174.                 selected.retrieveNextParameters();
  175.             } else {
  176.                 // this was the last step
  177.                 isLast = true;
  178.             }

  179.             previousDate = selectedStepEnd;

  180.         }

  181.         // stop all remaining propagators
  182.         executorService.shutdownNow();

  183.         // extract the final states
  184.         final List<SpacecraftState> finalStates = new ArrayList<>(monitors.size());
  185.         for (PropagatorMonitoring monitor : monitors) {
  186.             try {
  187.                 finalStates.add(monitor.future.get());
  188.             } catch (InterruptedException | ExecutionException e) {

  189.                 // sort out if exception was intentional or not
  190.                 monitor.manageException(e);

  191.                 // this propagator was intentionally stopped,
  192.                 // we retrieve the final state from the last available interpolator
  193.                 finalStates.add(monitor.parameters.interpolator.getInterpolatedState(previousDate));

  194.             }
  195.         }

  196.         globalHandler.finish(finalStates);

  197.         return finalStates;

  198.     }

  199.     /** Local exception to stop propagators. */
  200.     private static class PropagatorStoppingException extends OrekitException {

  201.         /** Serializable UID.*/
  202.         private static final long serialVersionUID = 20170629L;

  203.         /** Simple constructor.
  204.          * @param ie interruption exception
  205.          */
  206.         PropagatorStoppingException(final InterruptedException ie) {
  207.             super(ie, LocalizedCoreFormats.SIMPLE_MESSAGE, ie.getLocalizedMessage());
  208.         }

  209.     }

  210.     /** Local class for handling single propagator steps. */
  211.     private static class SinglePropagatorHandler implements OrekitStepHandler {

  212.         /** Global handler. */
  213.         private final MultiSatStepHandler globalHandler;

  214.         /** Simple constructor.
  215.          * @param globalHandler global handler to call
  216.          */
  217.         SinglePropagatorHandler(final MultiSatStepHandler globalHandler) {
  218.             this.globalHandler = globalHandler;
  219.         }


  220.         /** {@inheritDoc} */
  221.         @Override
  222.         public void init(final SpacecraftState s0, final AbsoluteDate t) {
  223.             globalHandler.init(Collections.singletonList(s0), t);
  224.         }

  225.         /** {@inheritDoc} */
  226.         @Override
  227.         public void handleStep(final OrekitStepInterpolator interpolator) {
  228.             globalHandler.handleStep(Collections.singletonList(interpolator));
  229.         }

  230.         /** {@inheritDoc} */
  231.         @Override
  232.         public void finish(final SpacecraftState finalState) {
  233.             globalHandler.finish(Collections.singletonList(finalState));
  234.         }

  235.     }

  236.     /** Local class for handling multiple propagator steps. */
  237.     private static class MultiplePropagatorsHandler implements OrekitStepHandler {

  238.         /** Previous container handed off. */
  239.         private ParametersContainer previous;

  240.         /** Queue for passing step handling parameters. */
  241.         private final SynchronousQueue<ParametersContainer> queue;

  242.         /** Simple constructor.
  243.          * @param queue queue for passing step handling parameters
  244.          */
  245.         MultiplePropagatorsHandler(final SynchronousQueue<ParametersContainer> queue) {
  246.             this.previous = new ParametersContainer(null, null, null);
  247.             this.queue    = queue;
  248.         }

  249.         /** Hand off container to parallelizer.
  250.          * @param container parameters container to hand-off
  251.          */
  252.         private void handOff(final ParametersContainer container) {
  253.             try {
  254.                 previous = container;
  255.                 queue.put(previous);
  256.             } catch (InterruptedException ie) {
  257.                 // use a dedicated exception to stop thread almost gracefully
  258.                 throw new PropagatorStoppingException(ie);
  259.             }
  260.         }

  261.         /** {@inheritDoc} */
  262.         @Override
  263.         public void init(final SpacecraftState s0, final AbsoluteDate t) {
  264.             handOff(new ParametersContainer(s0, null, null));
  265.         }

  266.         /** {@inheritDoc} */
  267.         @Override
  268.         public void handleStep(final OrekitStepInterpolator interpolator) {
  269.             handOff(new ParametersContainer(previous.initialState, interpolator, null));
  270.         }

  271.         /** {@inheritDoc} */
  272.         @Override
  273.         public void finish(final SpacecraftState finalState) {
  274.             handOff(new ParametersContainer(previous.initialState, previous.interpolator, finalState));
  275.         }

  276.     }

  277.     /** Container for parameters passed by propagators to step handlers. */
  278.     private static class ParametersContainer {

  279.         /** Initial state. */
  280.         private final SpacecraftState initialState;

  281.         /** Interpolator set up for last seen step. */
  282.         private final OrekitStepInterpolator interpolator;

  283.         /** Final state. */
  284.         private final SpacecraftState finalState;

  285.         /** Simple constructor.
  286.          * @param initialState initial state
  287.          * @param interpolator interpolator set up for last seen step
  288.          * @param finalState final state
  289.          */
  290.         ParametersContainer(final SpacecraftState initialState,
  291.                             final OrekitStepInterpolator interpolator,
  292.                             final SpacecraftState finalState) {
  293.             this.initialState = initialState;
  294.             this.interpolator = interpolator;
  295.             this.finalState   = finalState;
  296.         }

  297.     }

  298.     /** Container for propagator monitoring. */
  299.     private static class PropagatorMonitoring {

  300.         /** Queue for handing off step handler parameters. */
  301.         private final SynchronousQueue<ParametersContainer> queue;

  302.         /** Future for retrieving propagation return value. */
  303.         private final Future<SpacecraftState> future;

  304.         /** Last step handler parameters received. */
  305.         private ParametersContainer parameters;

  306.         /** Interpolator restricted to time range shared with other propagators. */
  307.         private OrekitStepInterpolator restricted;

  308.         /** Simple constructor.
  309.          * @param propagator managed propagator
  310.          * @param start start date from which orbit state should be propagated
  311.          * @param target target date to which orbit state should be propagated
  312.          * @param executorService service for running propagator
  313.          */
  314.         PropagatorMonitoring(final Propagator propagator, final AbsoluteDate start, final AbsoluteDate target,
  315.                              final ExecutorService executorService) {

  316.             // set up queue for handing off step handler parameters synchronization
  317.             // the main thread will let underlying propagators go forward
  318.             // by consuming the step handling parameters they will put at each step
  319.             queue = new SynchronousQueue<>();
  320.             propagator.getMultiplexer().add(new MultiplePropagatorsHandler(queue));

  321.             // start the propagator
  322.             future = executorService.submit(() -> propagator.propagate(start, target));

  323.         }

  324.         /** Wait completion of first step.
  325.          */
  326.         public void waitFirstStepCompletion() {

  327.             // wait until both the init method and the handleStep method
  328.             // of the current propagator step handler have been called,
  329.             // thus ensuring we have one step available to compare propagators
  330.             // progress with each other
  331.             while (parameters == null || parameters.initialState == null || parameters.interpolator == null) {
  332.                 retrieveNextParameters();
  333.             }

  334.         }

  335.         /** Retrieve next step handling parameters.
  336.          */
  337.         public void retrieveNextParameters() {
  338.             try {
  339.                 ParametersContainer params = null;
  340.                 while (params == null && !future.isDone()) {
  341.                     params = queue.poll(MAX_WAIT, TimeUnit.MILLISECONDS);
  342.                 }
  343.                 if (params == null) {
  344.                     // call Future.get just for the side effect of retrieving the exception
  345.                     // in case the propagator ended due to an exception
  346.                     future.get();
  347.                 }
  348.                 parameters = params;
  349.             } catch (InterruptedException | ExecutionException e) {
  350.                 manageException(e);
  351.                 parameters = null;
  352.             }
  353.         }

  354.         /** Convert exceptions.
  355.          * @param exception exception caught
  356.          */
  357.         private void manageException(final Exception exception) {
  358.             if (exception.getCause() instanceof PropagatorStoppingException) {
  359.                 // this was an expected exception, we deliberately shut down the propagators
  360.                 // we therefore explicitly ignore this exception
  361.                 return;
  362.             } else if (exception.getCause() instanceof OrekitException) {
  363.                 // unwrap the original exception
  364.                 throw (OrekitException) exception.getCause();
  365.             } else {
  366.                 throw new OrekitException(exception.getCause(),
  367.                                           LocalizedCoreFormats.SIMPLE_MESSAGE, exception.getLocalizedMessage());
  368.             }
  369.         }

  370.     }

  371. }