ImmutableTimeStampedCache.java

  1. /* Contributed in the public domain.
  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.ArrayList;
  19. import java.util.Collection;
  20. import java.util.Collections;
  21. import java.util.List;
  22. import java.util.stream.Stream;

  23. import org.hipparchus.exception.LocalizedCoreFormats;
  24. import org.hipparchus.util.FastMath;
  25. import org.orekit.errors.OrekitException;
  26. import org.orekit.errors.OrekitIllegalArgumentException;
  27. import org.orekit.errors.OrekitIllegalStateException;
  28. import org.orekit.errors.OrekitMessages;
  29. import org.orekit.errors.TimeStampedCacheException;
  30. import org.orekit.time.AbsoluteDate;
  31. import org.orekit.time.ChronologicalComparator;
  32. import org.orekit.time.TimeStamped;

  33. /**
  34.  * A cache of {@link TimeStamped} data that provides concurrency through
  35.  * immutability. This strategy is suitable when all of the cached data is stored
  36.  * in memory. (For example, {@link org.orekit.time.UTCScale UTCScale}) This
  37.  * class then provides convenient methods for accessing the data.
  38.  *
  39.  * @author Evan Ward
  40.  * @param <T>  the type of data
  41.  */
  42. public class ImmutableTimeStampedCache<T extends TimeStamped>
  43.     implements TimeStampedCache<T> {

  44.     /**
  45.      * An empty immutable cache that always throws an exception on attempted
  46.      * access.
  47.      */
  48.     @SuppressWarnings("rawtypes")
  49.     private static final ImmutableTimeStampedCache EMPTY_CACHE =
  50.         new EmptyTimeStampedCache<TimeStamped>();

  51.     /**
  52.      * the cached data. Be careful not to modify it after the constructor, or
  53.      * return a reference that allows mutating this list.
  54.      */
  55.     private final List<T> data;

  56.     /**
  57.      * the maximum size list to return from {@link #getNeighbors(AbsoluteDate, int)}.
  58.      * @since 12.0
  59.      */
  60.     private final int maxNeighborsSize;

  61.     /** Earliest date.
  62.      * @since 12.0
  63.      */
  64.     private final AbsoluteDate earliestDate;

  65.     /** Latest date.
  66.      * @since 12.0
  67.      */
  68.     private final AbsoluteDate latestDate;

  69.     /**
  70.      * Create a new cache with the given neighbors size and data.
  71.      *
  72.      * @param maxNeighborsSize the maximum size of the list returned from
  73.      *        {@link #getNeighbors(AbsoluteDate, int)}. Must be less than or equal to
  74.      *        {@code data.size()}.
  75.      * @param data the backing data for this cache. The list will be copied to
  76.      *        ensure immutability. To guarantee immutability the entries in
  77.      *        {@code data} must be immutable themselves. There must be more data
  78.      *        than {@code maxNeighborsSize}.
  79.      * @throws IllegalArgumentException if {@code neightborsSize > data.size()}
  80.      *         or if {@code neighborsSize} is negative
  81.      */
  82.     public ImmutableTimeStampedCache(final int maxNeighborsSize,
  83.                                      final Collection<? extends T> data) {
  84.         // parameter check
  85.         if (maxNeighborsSize > data.size()) {
  86.             throw new OrekitIllegalArgumentException(OrekitMessages.NOT_ENOUGH_CACHED_NEIGHBORS,
  87.                                                      data.size(), maxNeighborsSize);
  88.         }
  89.         if (maxNeighborsSize < 1) {
  90.             throw new OrekitIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_SMALL,
  91.                                                      maxNeighborsSize, 0);
  92.         }

  93.         // assign instance variables
  94.         this.maxNeighborsSize = maxNeighborsSize;
  95.         // sort and copy data first
  96.         this.data = new ArrayList<>(data);
  97.         Collections.sort(this.data, new ChronologicalComparator());

  98.         this.earliestDate = this.data.get(0).getDate();
  99.         this.latestDate   = this.data.get(this.data.size() - 1).getDate();

  100.     }

  101.     /**
  102.      * private constructor for {@link #EMPTY_CACHE}.
  103.      */
  104.     private ImmutableTimeStampedCache() {
  105.         this.data             = null;
  106.         this.maxNeighborsSize = 0;
  107.         this.earliestDate     = AbsoluteDate.ARBITRARY_EPOCH;
  108.         this.latestDate       = AbsoluteDate.ARBITRARY_EPOCH;
  109.     }

  110.     /** {@inheritDoc} */
  111.     public Stream<T> getNeighbors(final AbsoluteDate central, final int n) {

  112.         if (n > maxNeighborsSize) {
  113.             throw new OrekitException(OrekitMessages.NOT_ENOUGH_DATA, maxNeighborsSize);
  114.         }

  115.         // find central index
  116.         final int i = findIndex(central);

  117.         // check index in in the range of the data
  118.         if (i < 0) {
  119.             final AbsoluteDate earliest = this.getEarliest().getDate();
  120.             throw new TimeStampedCacheException(OrekitMessages.UNABLE_TO_GENERATE_NEW_DATA_BEFORE,
  121.                     earliest, central, earliest.durationFrom(central));
  122.         } else if (i >= this.data.size()) {
  123.             final AbsoluteDate latest = this.getLatest().getDate();
  124.             throw new TimeStampedCacheException(OrekitMessages.UNABLE_TO_GENERATE_NEW_DATA_AFTER,
  125.                     latest, central, central.durationFrom(latest));
  126.         }

  127.         // force unbalanced range if necessary
  128.         int start = FastMath.max(0, i - (n - 1) / 2);
  129.         final int end = FastMath.min(this.data.size(), start + n);
  130.         start = end - n;

  131.         // return list without copying
  132.         return this.data.subList(start, end).stream();
  133.     }

  134.     /**
  135.      * Find the index, i, to {@link #data} such that {@code data[i] <= t} and
  136.      * {@code data[i+1] > t} if {@code data[i+1]} exists.
  137.      *
  138.      * @param t the time
  139.      * @return the index of the data at or just before {@code t}, {@code -1} if
  140.      *         {@code t} is before the first entry, or {@code data.size()} if
  141.      *         {@code t} is after the last entry.
  142.      */
  143.     private int findIndex(final AbsoluteDate t) {

  144.         // left bracket of search algorithm
  145.         int    iInf  = 0;
  146.         double dtInf = t.durationFrom(earliestDate);
  147.         if (dtInf < 0) {
  148.             // before first entry
  149.             return -1;
  150.         }

  151.         // right bracket of search algorithm
  152.         int    iSup  = data.size() - 1;
  153.         double dtSup = t.durationFrom(latestDate);
  154.         if (dtSup > 0) {
  155.             // after last entry
  156.             return data.size();
  157.         }

  158.         // search entries, using linear interpolation
  159.         // this should take only 2 iterations for near linear entries (most frequent use case)
  160.         // regardless of the number of entries
  161.         // this is much faster than binary search for large number of entries
  162.         while (iSup - iInf > 1) {
  163.             final int    iInterp = (int) FastMath.rint((iInf * dtSup - iSup * dtInf) / (dtSup - dtInf));
  164.             final int    iMed    = FastMath.max(iInf + 1, FastMath.min(iInterp, iSup - 1));
  165.             final double dtMed   = t.durationFrom(data.get(iMed).getDate());
  166.             if (dtMed < 0) {
  167.                 iSup  = iMed;
  168.                 dtSup = dtMed;
  169.             } else {
  170.                 iInf  = iMed;
  171.                 dtInf = dtMed;
  172.             }
  173.         }

  174.         // at this point data[iInf] <= t <= data[iSup], but the javadoc for this method
  175.         // says the upper bound is exclusive, so check for equality to make a half open
  176.         // interval.
  177.         if (dtSup == 0.0) {
  178.             return iSup;
  179.         }
  180.         return iInf;
  181.     }

  182.     /** {@inheritDoc} */
  183.     public int getMaxNeighborsSize() {
  184.         return maxNeighborsSize;
  185.     }

  186.     /** {@inheritDoc} */
  187.     public T getEarliest() {
  188.         return this.data.get(0);
  189.     }

  190.     /** {@inheritDoc} */
  191.     public T getLatest() {
  192.         return this.data.get(this.data.size() - 1);
  193.     }

  194.     /**
  195.      * Get all of the data in this cache.
  196.      *
  197.      * @return a sorted collection of all data passed in the
  198.      *         {@link #ImmutableTimeStampedCache(int, Collection) constructor}.
  199.      */
  200.     public List<T> getAll() {
  201.         return Collections.unmodifiableList(this.data);
  202.     }

  203.     /** {@inheritDoc} */
  204.     @Override
  205.     public String toString() {
  206.         return "Immutable cache with " + this.data.size() + " entries";
  207.     }

  208.     /**
  209.      * An empty immutable cache that always throws an exception on attempted
  210.      * access.
  211.      */
  212.     private static class EmptyTimeStampedCache<T extends TimeStamped> extends ImmutableTimeStampedCache<T> {

  213.         /** {@inheritDoc} */
  214.         @Override
  215.         public Stream<T> getNeighbors(final AbsoluteDate central) {
  216.             throw new TimeStampedCacheException(OrekitMessages.NO_CACHED_ENTRIES);
  217.         }

  218.         /** {@inheritDoc} */
  219.         @Override
  220.         public int getMaxNeighborsSize() {
  221.             return 0;
  222.         }

  223.         /** {@inheritDoc} */
  224.         @Override
  225.         public T getEarliest() {
  226.             throw new OrekitIllegalStateException(OrekitMessages.NO_CACHED_ENTRIES);
  227.         }

  228.         /** {@inheritDoc} */
  229.         @Override
  230.         public T getLatest() {
  231.             throw new OrekitIllegalStateException(OrekitMessages.NO_CACHED_ENTRIES);
  232.         }

  233.         /** {@inheritDoc} */
  234.         @Override
  235.         public List<T> getAll() {
  236.             return Collections.emptyList();
  237.         }

  238.         /** {@inheritDoc} */
  239.         @Override
  240.         public String toString() {
  241.             return "Empty immutable cache";
  242.         }

  243.     }

  244.     /**
  245.      * Get an empty immutable cache, cast to the correct type.
  246.      * @param <TS>  the type of data
  247.      * @return an empty {@link ImmutableTimeStampedCache}.
  248.      */
  249.     @SuppressWarnings("unchecked")
  250.     public static final <TS extends TimeStamped> ImmutableTimeStampedCache<TS> emptyCache() {
  251.         return (ImmutableTimeStampedCache<TS>) EMPTY_CACHE;
  252.     }

  253. }