TimeSpanMap.java

  1. /* Copyright 2002-2023 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.utils;

  18. import java.util.function.Consumer;

  19. import org.orekit.time.AbsoluteDate;
  20. import org.orekit.time.TimeStamped;

  21. /** Container for objects that apply to spans of time.
  22.  * <p>
  23.  * Time span maps can be seen either as an ordered collection of
  24.  * {@link Span time spans} or as an ordered collection
  25.  * of {@link Transition transitions}. Both views are dual one to
  26.  * each other. A time span extends from one transition to the
  27.  * next one, and a transition separates one time span from the
  28.  * next one. Each time span contains one entry that is valid during
  29.  * the time span; this entry may be null if nothing is valid during
  30.  * this time span.
  31.  * </p>
  32.  * <p>
  33.  * Typical uses of {@link TimeSpanMap} are to hold piecewise data, like for
  34.  * example an orbit count that changes at ascending nodes (in which case the
  35.  * entry would be an {@link Integer}), or a visibility status between several
  36.  * objects (in which case the entry would be a {@link Boolean}) or a drag
  37.  * coefficient that is expected to be estimated daily or three-hourly (this is
  38.  * how {@link org.orekit.forces.drag.TimeSpanDragForce TimeSpanDragForce} is
  39.  * implemented).
  40.  * </p>
  41.  * <p>
  42.  * Time span maps are built progressively. At first, they contain one
  43.  * {@link Span time span} only whose validity extends from past infinity to
  44.  * future infinity. Then new entries are added one at a time, associated with
  45.  * transition dates, in order to build up the complete map. The transition dates
  46.  * can be either the start of validity (when calling {@link #addValidAfter(Object,
  47.  * AbsoluteDate, boolean)}), or the end of the validity (when calling {@link
  48.  * #addValidBefore(Object, AbsoluteDate, boolean)}). Entries are often added at one
  49.  * end only (and mainly in chronological order), but this is not required. It is
  50.  * possible for example to first set up a map that cover a large range (say one day),
  51.  * and then to insert intermediate dates using for example propagation and event
  52.  * detectors to carve out some parts. This is akin to the way Binary Space Partitioning
  53.  * Trees work.
  54.  * </p>
  55.  * <p>
  56.  * Since 11.1, this class is thread-safe
  57.  * </p>
  58.  * @param <T> Type of the data.
  59.  * @author Luc Maisonobe
  60.  * @since 7.1
  61.  */
  62. public class TimeSpanMap<T> {

  63.     /** Reference to last accessed data. */
  64.     private Span<T> current;

  65.     /** Number of time spans. */
  66.     private int nbSpans;

  67.     /** Create a map containing a single object, initially valid throughout the timeline.
  68.      * <p>
  69.      * The real validity of this first entry will be truncated as other
  70.      * entries are either {@link #addValidBefore(Object, AbsoluteDate, boolean)
  71.      * added before} it or {@link #addValidAfter(Object, AbsoluteDate, boolean)
  72.      * added after} it.
  73.      * </p>
  74.      * @param entry entry (initially valid throughout the timeline)
  75.      */
  76.     public TimeSpanMap(final T entry) {
  77.         current = new Span<>(entry);
  78.         nbSpans = 1;
  79.     }

  80.     /** Get the number of spans.
  81.      * <p>
  82.      * The number of spans is always at least 1. The number of transitions
  83.      * is always 1 less than the number of spans.
  84.      * </p>
  85.      * @return number of spans
  86.      * @since 11.1
  87.      */
  88.     public synchronized int getSpansNumber() {
  89.         return nbSpans;
  90.     }

  91.     /** Add an entry valid before a limit date.
  92.      * <p>
  93.      * As an entry is valid, it truncates or overrides the validity of the neighboring
  94.      * entries already present in the map.
  95.      * </p>
  96.      * <p>
  97.      * If the map already contains transitions that occur earlier than {@code latestValidityDate},
  98.      * the {@code erasesEarlier} parameter controls what to do with them. Lets consider
  99.      * the time span [tₖ ; tₖ₊₁[ associated with entry eₖ that would have been valid at time
  100.      * {@code latestValidityDate} prior to the call to the method (i.e. tₖ &lt;
  101.      * {@code latestValidityDate} &lt; tₖ₊₁).
  102.      * </p>
  103.      * <ul>
  104.      *  <li>if {@code erasesEarlier} is {@code true}, then all earlier transitions
  105.      *      up to and including tₖ are erased, and the {@code entry} will be valid from past infinity
  106.      *      to {@code latestValidityDate}</li>
  107.      *  <li>if {@code erasesEarlier} is {@code false}, then all earlier transitions
  108.      *      are preserved, and the {@code entry} will be valid from tₖ
  109.      *      to {@code latestValidityDate}</li>
  110.      *  </ul>
  111.      * <p>
  112.      * In both cases, the existing entry eₖ time span will be truncated and will be valid
  113.      * only from {@code latestValidityDate} to tₖ₊₁.
  114.      * </p>
  115.      * @param entry entry to add
  116.      * @param latestValidityDate date before which the entry is valid
  117.      * @param erasesEarlier if true, the entry erases all existing transitions
  118.      * that are earlier than {@code latestValidityDate}
  119.      * @return span with added entry
  120.      * @since 11.1
  121.      */
  122.     public synchronized Span<T> addValidBefore(final T entry, final AbsoluteDate latestValidityDate, final boolean erasesEarlier) {

  123.         // update current reference to transition date
  124.         locate(latestValidityDate);

  125.         if (erasesEarlier) {

  126.             // drop everything before date
  127.             current.start = null;

  128.             // update count
  129.             nbSpans = 0;
  130.             for (Span<T> span = current; span != null; span = span.next()) {
  131.                 ++nbSpans;
  132.             }

  133.         }

  134.         final Span<T> span = new Span<>(entry);

  135.         final Transition<T> start = current.getStartTransition();
  136.         if (start != null && start.getDate().equals(latestValidityDate)) {
  137.             // the transition at start of the current span is at the exact same date
  138.             // we update it, without adding a new transition
  139.             if (start.previous() != null) {
  140.                 start.previous().setAfter(span);
  141.             }
  142.             start.setBefore(span);
  143.         } else {

  144.             if (current.getStartTransition() != null) {
  145.                 current.getStartTransition().setAfter(span);
  146.             }

  147.             // we need to add a new transition somewhere inside the current span
  148.             insertTransition(latestValidityDate, span, current);

  149.         }

  150.         // we consider the last added transition as the new current one
  151.         current = span;

  152.         return span;

  153.     }

  154.     /** Add an entry valid after a limit date.
  155.      * <p>
  156.      * As an entry is valid, it truncates or overrides the validity of the neighboring
  157.      * entries already present in the map.
  158.      * </p>
  159.      * <p>
  160.      * If the map already contains transitions that occur later than {@code earliestValidityDate},
  161.      * the {@code erasesLater} parameter controls what to do with them. Lets consider
  162.      * the time span [tₖ ; tₖ₊₁[ associated with entry eₖ that would have been valid at time
  163.      * {@code earliestValidityDate} prior to the call to the method (i.e. tₖ &lt;
  164.      * {@code earliestValidityDate} &lt; tₖ₊₁).
  165.      * </p>
  166.      * <ul>
  167.      *  <li>if {@code erasesLater} is {@code true}, then all later transitions
  168.      *      from and including tₖ₊₁ are erased, and the {@code entry} will be valid from
  169.      *      {@code earliestValidityDate} to future infinity</li>
  170.      *  <li>if {@code erasesLater} is {@code false}, then all later transitions
  171.      *      are preserved, and the {@code entry} will be valid from {@code earliestValidityDate}
  172.      *      to tₖ₊₁</li>
  173.      *  </ul>
  174.      * <p>
  175.      * In both cases, the existing entry eₖ time span will be truncated and will be valid
  176.      * only from tₖ to {@code earliestValidityDate}.
  177.      * </p>
  178.      * @param entry entry to add
  179.      * @param earliestValidityDate date after which the entry is valid
  180.      * @param erasesLater if true, the entry erases all existing transitions
  181.      * that are later than {@code earliestValidityDate}
  182.      * @return span with added entry
  183.      * @since 11.1
  184.      */
  185.     public synchronized Span<T> addValidAfter(final T entry, final AbsoluteDate earliestValidityDate, final boolean erasesLater) {

  186.         // update current reference to transition date
  187.         locate(earliestValidityDate);

  188.         if (erasesLater) {

  189.             // drop everything after date
  190.             current.end = null;

  191.             // update count
  192.             nbSpans = 0;
  193.             for (Span<T> span = current; span != null; span = span.previous()) {
  194.                 ++nbSpans;
  195.             }

  196.         }

  197.         final Span<T> span = new Span<>(entry);
  198.         if (current.getEndTransition() != null) {
  199.             current.getEndTransition().setBefore(span);
  200.         }

  201.         final Transition<T> start = current.getStartTransition();
  202.         if (start != null && start.getDate().equals(earliestValidityDate)) {
  203.             // the transition at start of the current span is at the exact same date
  204.             // we update it, without adding a new transition
  205.             start.setAfter(span);
  206.         } else {
  207.             // we need to add a new transition somewhere inside the current span
  208.             insertTransition(earliestValidityDate, current, span);
  209.         }

  210.         // we consider the last added transition as the new current one
  211.         current = span;

  212.         return span;

  213.     }

  214.     /** Add an entry valid between two limit dates.
  215.      * <p>
  216.      * As an entry is valid, it truncates or overrides the validity of the neighboring
  217.      * entries already present in the map.
  218.      * </p>
  219.      * @param entry entry to add
  220.      * @param earliestValidityDate date after which the entry is valid
  221.      * @param latestValidityDate date before which the entry is valid
  222.      * @return span with added entry
  223.      * @since 11.1
  224.      */
  225.     public synchronized Span<T> addValidBetween(final T entry, final AbsoluteDate earliestValidityDate, final AbsoluteDate latestValidityDate) {

  226.         // handle special cases
  227.         if (AbsoluteDate.PAST_INFINITY.equals(earliestValidityDate)) {
  228.             if (AbsoluteDate.FUTURE_INFINITY.equals(latestValidityDate)) {
  229.                 // we wipe everything in the map
  230.                 current = new Span<>(entry);
  231.                 return current;
  232.             } else {
  233.                 // we wipe from past infinity
  234.                 return addValidBefore(entry, latestValidityDate, true);
  235.             }
  236.         } else if (AbsoluteDate.FUTURE_INFINITY.equals(latestValidityDate)) {
  237.             // we wipe up to future infinity
  238.             return addValidAfter(entry, earliestValidityDate, true);
  239.         } else {

  240.             // locate spans at earliest and latest dates
  241.             locate(earliestValidityDate);
  242.             Span<T> latest = current;
  243.             while (latest.getEndTransition() != null && latest.getEnd().isBeforeOrEqualTo(latestValidityDate)) {
  244.                 latest = latest.next();
  245.                 --nbSpans;
  246.             }
  247.             if (latest == current) {
  248.                 // the interval splits one transition in the middle, we need to duplicate the instance
  249.                 latest = new Span<>(current.data);
  250.                 if (current.getEndTransition() != null) {
  251.                     current.getEndTransition().setBefore(latest);
  252.                 }
  253.             }

  254.             final Span<T> span = new Span<>(entry);

  255.             // manage earliest transition
  256.             final Transition<T> start = current.getStartTransition();
  257.             if (start != null && start.getDate().equals(earliestValidityDate)) {
  258.                 // the transition at start of the current span is at the exact same date
  259.                 // we update it, without adding a new transition
  260.                 start.setAfter(span);
  261.             } else {
  262.                 // we need to add a new transition somewhere inside the current span
  263.                 insertTransition(earliestValidityDate, current, span);
  264.             }

  265.             // manage latest transition
  266.             insertTransition(latestValidityDate, span, latest);

  267.             // we consider the last added transition as the new current one
  268.             current = span;

  269.             return span;

  270.         }

  271.     }

  272.     /** Get the entry valid at a specified date.
  273.      * <p>
  274.      * The expected complexity is O(1) for successive calls with
  275.      * neighboring dates, which is the more frequent use in propagation
  276.      * or orbit determination applications, and O(n) for random calls.
  277.      * </p>
  278.      * @param date date at which the entry must be valid
  279.      * @return valid entry at specified date
  280.      * @see #getSpan(AbsoluteDate)
  281.      */
  282.     public synchronized T get(final AbsoluteDate date) {
  283.         return getSpan(date).getData();
  284.     }

  285.     /** Get the time span containing a specified date.
  286.      * <p>
  287.      * The expected complexity is O(1) for successive calls with
  288.      * neighboring dates, which is the more frequent use in propagation
  289.      * or orbit determination applications, and O(n) for random calls.
  290.      * </p>
  291.      * @param date date belonging to the desired time span
  292.      * @return time span containing the specified date
  293.      * @since 9.3
  294.      */
  295.     public synchronized Span<T> getSpan(final AbsoluteDate date) {
  296.         locate(date);
  297.         return current;
  298.     }

  299.     /** Locate the time span containing a specified date.
  300.      * <p>
  301.      * The {@link current} field is updated to the located span.
  302.      * After the method returns, {@code current.getStartTransition()} is either
  303.      * null or its date is before or equal to date, and {@code
  304.      * current.getEndTransition()} is either null or its date is after date.
  305.      * </p>
  306.      * @param date date belonging to the desired time span
  307.      */
  308.     private synchronized void locate(final AbsoluteDate date) {

  309.         while (current.getStart().isAfter(date)) {
  310.             // current span is too late
  311.             current = current.previous();
  312.         }

  313.         while (current.getEnd().isBeforeOrEqualTo(date)) {

  314.             final Span<T> next = current.next();
  315.             if (next == null) {
  316.                 // this happens when date is FUTURE_INFINITY
  317.                 return;
  318.             }

  319.             // current span is too early
  320.             current = next;

  321.         }

  322.     }

  323.     /** Insert a transition.
  324.      * @param date transition date
  325.      * @param before span before transition
  326.      * @param after span after transition
  327.      * @since 11.1
  328.      */
  329.     private void insertTransition(final AbsoluteDate date, final Span<T> before, final Span<T> after) {
  330.         final Transition<T> transition = new Transition<>(date);
  331.         transition.setBefore(before);
  332.         transition.setAfter(after);
  333.         ++nbSpans;
  334.     }

  335.     /** Get the first (earliest) transition.
  336.      * @return first (earliest) transition, or null if there are no transitions
  337.      * @since 11.1
  338.      */
  339.     public synchronized Transition<T> getFirstTransition() {
  340.         return getFirstSpan().getEndTransition();
  341.     }

  342.     /** Get the last (latest) transition.
  343.      * @return last (latest) transition, or null if there are no transitions
  344.      * @since 11.1
  345.      */
  346.     public synchronized Transition<T> getLastTransition() {
  347.         return getLastSpan().getStartTransition();
  348.     }

  349.     /** Get the first (earliest) span.
  350.      * @return first (earliest) span
  351.      * @since 11.1
  352.      */
  353.     public synchronized Span<T> getFirstSpan() {
  354.         Span<T> span = current;
  355.         while (span.getStartTransition() != null) {
  356.             span = span.previous();
  357.         }
  358.         return span;
  359.     }

  360.     /** Get the last (latest) span.
  361.      * @return last (latest) span
  362.      * @since 11.1
  363.      */
  364.     public synchronized Span<T> getLastSpan() {
  365.         Span<T> span = current;
  366.         while (span.getEndTransition() != null) {
  367.             span = span.next();
  368.         }
  369.         return span;
  370.     }

  371.     /** Extract a range of the map.
  372.      * <p>
  373.      * The object returned will be a new independent instance that will contain
  374.      * only the transitions that lie in the specified range.
  375.      * </p>
  376.      * <p>
  377.      * Consider for example a map containing objects O₀ valid before t₁, O₁ valid
  378.      * between t₁ and t₂, O₂ valid between t₂ and t₃, O₃ valid between t₃ and t₄,
  379.      * and O₄ valid after t₄. then calling this method with a {@code start}
  380.      * date between t₁ and t₂ and a {@code end} date between t₃ and t₄
  381.      * will result in a new map containing objects O₁ valid before t₂, O₂
  382.      * valid between t₂ and t₃, and O₃ valid after t₃. The validity of O₁
  383.      * is therefore extended in the past, and the validity of O₃ is extended
  384.      * in the future.
  385.      * </p>
  386.      * @param start earliest date at which a transition is included in the range
  387.      * (may be set to {@link AbsoluteDate#PAST_INFINITY} to keep all early transitions)
  388.      * @param end latest date at which a transition is included in the r
  389.      * (may be set to {@link AbsoluteDate#FUTURE_INFINITY} to keep all late transitions)
  390.      * @return a new instance with all transitions restricted to the specified range
  391.      * @since 9.2
  392.      */
  393.     public synchronized TimeSpanMap<T> extractRange(final AbsoluteDate start, final AbsoluteDate end) {

  394.         Span<T> span = getSpan(start);
  395.         final TimeSpanMap<T> range = new TimeSpanMap<>(span.getData());
  396.         while (span.getEndTransition() != null && span.getEndTransition().getDate().isBeforeOrEqualTo(end)) {
  397.             span = span.next();
  398.             range.addValidAfter(span.getData(), span.getStartTransition().getDate(), false);
  399.         }

  400.         return range;

  401.     }

  402.     /**
  403.      * Performs an action for each non-null element of map.
  404.      * <p>
  405.      * The action is performed chronologically.
  406.      * </p>
  407.      * @param action action to perform on the non-null elements
  408.      * @since 10.3
  409.      */
  410.     public synchronized void forEach(final Consumer<T> action) {
  411.         for (Span<T> span = getFirstSpan(); span != null; span = span.next()) {
  412.             if (span.getData() != null) {
  413.                 action.accept(span.getData());
  414.             }
  415.         }
  416.     }

  417.     /** Class holding transition times.
  418.      * <p>
  419.      * This data type is dual to {@link Span}, it is
  420.      * focused on one transition date, and gives access to
  421.      * surrounding valid data whereas {@link Span} is focused
  422.      * on one valid data, and gives access to surrounding
  423.      * transition dates.
  424.      * </p>
  425.      * @param <S> Type of the data.
  426.      */
  427.     public static class Transition<S> implements TimeStamped {

  428.         /** Transition date. */
  429.         private AbsoluteDate date;

  430.         /** Entry valid before the transition. */
  431.         private Span<S> before;

  432.         /** Entry valid after the transition. */
  433.         private Span<S> after;

  434.         /** Simple constructor.
  435.          * @param date transition date
  436.          */
  437.         private Transition(final AbsoluteDate date) {
  438.             this.date = date;
  439.         }

  440.         /** Set the span valid before transition.
  441.          * @param before span valid before transition (must be non-null)
  442.          */
  443.         void setBefore(final Span<S> before) {
  444.             this.before = before;
  445.             before.end  = this;
  446.         }

  447.         /** Set the span valid after transition.
  448.          * @param after span valid after transition (must be non-null)
  449.          */
  450.         void setAfter(final Span<S> after) {
  451.             this.after  = after;
  452.             after.start = this;
  453.         }

  454.         /** Get the transition date.
  455.          * @return transition date
  456.          */
  457.         @Override
  458.         public AbsoluteDate getDate() {
  459.             return date;
  460.         }

  461.         /** Get the previous transition.
  462.          * @return previous transition, or null if this transition was the first one
  463.          * @since 11.1
  464.          */
  465.         public Transition<S> previous() {
  466.             return before.getStartTransition();
  467.         }

  468.         /** Get the next transition.
  469.          * @return next transition, or null if this transition was the last one
  470.          * @since 11.1
  471.          */
  472.         public Transition<S> next() {
  473.             return after.getEndTransition();
  474.         }

  475.         /** Get the entry valid before transition.
  476.          * @return entry valid before transition
  477.          * @see #getSpanBefore()
  478.          */
  479.         public S getBefore() {
  480.             return before.getData();
  481.         }

  482.         /** Get the {@link Span} valid before transition.
  483.          * @return {@link Span} valid before transition
  484.          * @since 11.1
  485.          */
  486.         public Span<S> getSpanBefore() {
  487.             return before;
  488.         }

  489.         /** Get the entry valid after transition.
  490.          * @return entry valid after transition
  491.          * @see #getSpanAfter()
  492.          */
  493.         public S getAfter() {
  494.             return after.getData();
  495.         }

  496.         /** Get the {@link Span} valid after transition.
  497.          * @return {@link Span} valid after transition
  498.          * @since 11.1
  499.          */
  500.         public Span<S> getSpanAfter() {
  501.             return after;
  502.         }

  503.     }

  504.     /** Holder for one time span.
  505.      * <p>
  506.      * This data type is dual to {@link Transition}, it
  507.      * is focused on one valid data, and gives access to
  508.      * surrounding transition dates whereas {@link Transition}
  509.      * is focused on one transition date, and gives access to
  510.      * surrounding valid data.
  511.      * </p>
  512.      * @param <S> Type of the data.
  513.      * @since 9.3
  514.      */
  515.     public static class Span<S> {

  516.         /** Valid data. */
  517.         private final S data;

  518.         /** Start of validity for the data (null if span extends to past infinity). */
  519.         private Transition<S> start;

  520.         /** End of validity for the data (null if span extends to future infinity). */
  521.         private Transition<S> end;

  522.         /** Simple constructor.
  523.          * @param data valid data
  524.          */
  525.         private Span(final S data) {
  526.             this.data = data;
  527.         }

  528.         /** Get the data valid during this time span.
  529.          * @return data valid during this time span
  530.          */
  531.         public S getData() {
  532.             return data;
  533.         }

  534.         /** Get the previous time span.
  535.          * @return previous time span, or null if this time span was the first one
  536.          * @since 11.1
  537.          */
  538.         public Span<S> previous() {
  539.             return start == null ? null : start.getSpanBefore();
  540.         }

  541.         /** Get the next time span.
  542.          * @return next time span, or null if this time span was the last one
  543.          * @since 11.1
  544.          */
  545.         public Span<S> next() {
  546.             return end == null ? null : end.getSpanAfter();
  547.         }

  548.         /** Get the start of this time span.
  549.          * @return start of this time span (will be {@link AbsoluteDate#PAST_INFINITY}
  550.          * if {@link #getStartTransition()} returns null)
  551.          * @see #getStartTransition()
  552.          */
  553.         public AbsoluteDate getStart() {
  554.             return start == null ? AbsoluteDate.PAST_INFINITY : start.getDate();
  555.         }

  556.         /** Get the transition at start of this time span.
  557.          * @return transition at start of this time span (null if span extends to past infinity)
  558.          * @see #getStart()
  559.          * @since 11.1
  560.          */
  561.         public Transition<S> getStartTransition() {
  562.             return start;
  563.         }

  564.         /** Get the end of this time span.
  565.          * @return end of this time span (will be {@link AbsoluteDate#FUTURE_INFINITY}
  566.          * if {@link #getEndTransition()} returns null)
  567.          * @see #getEndTransition()
  568.          */
  569.         public AbsoluteDate getEnd() {
  570.             return end == null ? AbsoluteDate.FUTURE_INFINITY : end.getDate();
  571.         }

  572.         /** Get the transition at end of this time span.
  573.          * @return transition at end of this time span (null if span extends to future infinity)
  574.          * @see #getEnd()
  575.          * @since 11.1
  576.          */
  577.         public Transition<S> getEndTransition() {
  578.             return end;
  579.         }

  580.     }

  581. }