Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2011-2015 Rinde van Lon, iMinds-DistriNet, KU Leuven
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *         http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package com.github.rinde.rinsim.scenario.generator;
 
 import static com.google.common.base.Preconditions.checkArgument;
 
 import java.util.List;
 
 
 
Utilities for generating time series.

Author(s):
Rinde van Lon
 
 public final class TimeSeries {
   private TimeSeries() {}

  
Creates a homogenous Poisson process of the specified length. The intensity is calculated as numEvents / length.

Parameters:
length The length of Poisson process, all generated times will be in the interval [0,length).
numEvents The number of events that will be generated (on average).
Returns:
A newly constructed Poisson process TimeSeries.TimeSeriesGenerator.
 
   public static TimeSeriesGenerator homogenousPoisson(double length,
       int numEvents) {
     checkArgument(length > 0d);
     checkArgument(numEvents > 0);
     return new PoissonProcess(lengthnumEvents / length);
   }

  
Creates a non-homogenous Poisson process of the specified length. The intensity is specified by the IntensityFunctions.IntensityFunction. The non-homogenous Poisson process is implemented using the thinning method as described in [1].

References

  1. Lewis, P.A.W. and Shedler, G.S. Simulation of nonhomogenous Poisson processes by thinning. Naval Research Logistic Quarterly 26, (1979), 403–414.

Parameters:
length The length of Poisson process, all generated times will be in the interval [0,length).
function The intensity function.
Returns:
A newly constructed non-homogenous Poisson process TimeSeries.TimeSeriesGenerator.
 
   public static TimeSeriesGenerator nonHomogenousPoisson(double length,
       IntensityFunction function) {
     checkArgument(length > 0d);
     checkArgument(function.getMax() > 0d);
     return new NonHomogenous(lengthfunction);
   }

  
Creates a non-homogenous Poisson process of the specified length. The intensity is specified by the com.github.rinde.rinsim.util.StochasticSupplier. Each time TimeSeries.TimeSeriesGenerator.generate(long) is called, a new IntensityFunctions.IntensityFunction is requested from the com.github.rinde.rinsim.util.StochasticSupplier. The non-homogenous Poisson process is implemented using the thinning method as described in [1].

References

  1. Lewis, P.A.W. and Shedler, G.S. Simulation of nonhomogenous Poisson processes by thinning. Naval Research Logistic Quarterly 26, (1979), 403–414.

Parameters:
length The length of Poisson process, all generated times will be in the interval [0,length).
functionSupplier The intensity function supplier.
Returns:
A newly constructed non-homogenous Poisson process TimeSeries.TimeSeriesGenerator.
  public static TimeSeriesGenerator nonHomogenousPoisson(double length,
      StochasticSupplier<IntensityFunctionfunctionSupplier) {
    checkArgument(length > 0d);
    return new SuppliedNonHomogenous(lengthfunctionSupplier);
  }

  
Creates a TimeSeries.TimeSeriesGenerator using a uniform distribution for the inter arrival times of events.

Parameters:
length The length of the time series, all generated times will be in the interval [0,length).
numEvents The total number of events in the time series (on average).
maxDeviation The maximum deviation from the mean for the uniform distribution.
Returns:
A TimeSeries.TimeSeriesGenerator based on a uniform distribution.
  public static TimeSeriesGenerator uniform(double lengthint numEvents,
      double maxDeviation) {
    checkArgument(length > 0d);
    checkArgument(numEvents > 0);
    checkArgument(maxDeviation > 0d);
    final double average = length / numEvents;
    return new UniformTimeSeries(lengthaverage,
        StochasticSuppliers.constant(maxDeviation));
  }

  
Creates a TimeSeries.TimeSeriesGenerator using a uniform distribution for the inter arrival times of events. The spread of the uniform distribution is defined by the maxDeviation com.github.rinde.rinsim.util.StochasticSupplier, this means that each time a time series is generated a different max deviation settings is used.

Parameters:
length The length of the time series, all generated times will be in the interval [0,length).
numEvents The total number of events in the time series (on average).
maxDeviation A supplier that is used for max deviation values.
Returns:
A TimeSeries.TimeSeriesGenerator based on a uniform distribution, each time series that is generated has a different max deviation drawn from the supplier.
  public static TimeSeriesGenerator uniform(double lengthint numEvents,
      StochasticSupplier<DoublemaxDeviation) {
    checkArgument(length > 0d);
    checkArgument(numEvents > 0);
    final double average = length / numEvents;
    return new UniformTimeSeries(lengthaverage, StochasticSuppliers.checked(
        maxDeviation, Range.atLeast(0d)));
  }

  
Creates a TimeSeries.TimeSeriesGenerator that uses a truncated normal distribution for the inter arrival times of events. The normal distribution is truncated at a lower bound of 0 since it is not allowed (it makes no sense) to have negative inter arrival times. For more information about the normal distribution see com.github.rinde.rinsim.util.StochasticSuppliers.normal().

Parameters:
length The length of the time series, all generated times will be in the interval [0,length).
numEvents The total number of events in the time series (on average).
sd The standard deviation of the normal distribution.
Returns:
A TimeSeries.TimeSeriesGenerator based on a normal distribution.
  public static TimeSeriesGenerator normal(double lengthint numEvents,
      double sd) {
    checkArgument(length > 0d);
    checkArgument(numEvents > 0);
    final double average = length / numEvents;
    return toTimeSeries(length, StochasticSuppliers.normal()
        .mean(average)
        .std(sd)
        .lowerBound(0d)
        .redrawWhenOutOfBounds()
        .scaleMean()
        .buildDouble());
  }

  
Converts a com.github.rinde.rinsim.util.StochasticSupplier of java.lang.Doubles into a TimeSeries.TimeSeriesGenerator. Each time in the time series is created by t[n] = t[n-1] + ss.get(..), here ss is the java.lang.Double supplier.

Parameters:
length The length of the time series, all generated times will be in the interval [0,length).
interArrivalTimesSupplier The supplier to use for computing event inter arrival times.
Returns:
A new TimeSeries.TimeSeriesGenerator based on the supplier.
  public static TimeSeriesGenerator toTimeSeries(double length,
      StochasticSupplier<DoubleinterArrivalTimesSupplier) {
    return new SupplierTimeSeries(lengthinterArrivalTimesSupplier);
  }

  
Decorates the specified TimeSeries.TimeSeriesGenerator such that it only generates time series which conform to the specified com.google.common.base.Predicate. Predicates can be combined by using the methods provided by com.google.common.base.Predicates. Note that when an impossible com.google.common.base.Predicate is specified, such as com.google.common.base.Predicates.alwaysFalse() the resulting TimeSeries.TimeSeriesGenerator will enter an infinite loop.

Parameters:
tsg The TimeSeries.TimeSeriesGenerator to filter.
predicate All returned TimeSeries.TimeSeriesGenerators will conform to this predicate.
Returns:
A filtered generator.
      Predicate<List<Double>> predicate) {
    return new FilteredTSG(tsgpredicate);
  }

  
Creates a com.google.common.base.Predicate for a specified number of events. This predicate only accepts time series with exactly num events.

Parameters:
num The number of events a time series should have.
Returns:
A newly created predicate.
  public static Predicate<List<Double>> numEventsPredicate(final int num) {
    return new Predicate<List<Double>>() {
      @Override
      public boolean apply(@Nullable List<Doubleinput) {
        assert input != null;
        return input.size() == num;
      }
    };
  }

  
Generator of a time series.

Author(s):
Rinde van Lon
  public interface TimeSeriesGenerator {
    
Should generate a time series.

Parameters:
seed The random seed to use.
Returns:
An immutable list of times in ascending order, may contain duplicates.
    ImmutableList<Doublegenerate(long seed);
  }
  static class FilteredTSG implements TimeSeriesGenerator {
    private final TimeSeriesGenerator delegate;
    private final Predicate<List<Double>> predicate;
    private final RandomGenerator rng;
       = tsg;
       = pred;
       = new MersenneTwister();
    }
    @Override
    public ImmutableList<Doublegenerate(long seed) {
      .setSeed(seed);
      while (true) {
        final ImmutableList<DoubletimeSeries = .generate(
            .nextLong());
        if (.apply(timeSeries)) {
          return timeSeries;
        }
      }
    }
  }
  static class PoissonProcess implements TimeSeriesGenerator {

    
Random generator used for drawing random numbers.
    protected final RandomGenerator rng;
    final double length;
    final double intensity;
    PoissonProcess(double lendouble intens) {
       = len;
       = intens;
       = new MersenneTwister();
    }

    
All times will be in the interval [0,length)

Returns:
The upper bound of the interval.
    public double getLength() {
      return ;
    }
    // internal use only!
    Iterator<Doubleiterator() {
      return new TimeSeriesIterator(new ExponentialDistribution(,
          1d / ,
          );
    }
    @Override
    public ImmutableList<Doublegenerate(long seed) {
      .setSeed(seed);
      return ImmutableList.copyOf(iterator());
    }
  }
  static class NonHomogenous extends PoissonProcess {
    final IntensityFunction lambd;
    NonHomogenous(double lIntensityFunction func) {
      super(lfunc.getMax());
       = func;
    }
    @Override
    public Iterator<Doubleiterator() {
      return Iterators.filter(super.iterator(), new NHPredicate());
    }
  }
  static class SuppliedNonHomogenous implements TimeSeriesGenerator {
    final double length;
    final RandomGenerator rng;
    SuppliedNonHomogenous(double l,
        StochasticSupplier<IntensityFunctionfuncSup) {
       = l;
       = funcSup;
       = new MersenneTwister();
    }
    @Override
    public ImmutableList<Doublegenerate(long seed) {
      .setSeed(seed);
      final TimeSeriesGenerator tsg = new NonHomogenous(,
          .get(.nextLong()));
      return tsg.generate(.nextLong());
    }
  }
  static class SupplierTimeSeries implements TimeSeriesGenerator {
    private final double length;
    private final StochasticSupplier<Doublesupplier;
    SupplierTimeSeries(double lenStochasticSupplier<Doublesup) {
       = len;
       = sup;
    }
    @Override
    public ImmutableList<Doublegenerate(long seed) {
      return ImmutableList.copyOf(new SupplierIterator(,
          new MersenneTwister(seed)));
    }
  }
  static class SupplierIterator extends AbstractSequentialIterator<Double> {
    private final double length;
    private final StochasticSupplier<Doublesupplier;
    private final RandomGenerator randomNumberGenerator;
    SupplierIterator(double lenStochasticSupplier<Doublesup,
        RandomGenerator rng) {
      super(next(0d, lensuprng));
       = len;
       = sup;
       = rng;
    }
    @SuppressWarnings("null")
    @Nullable
    @Override
    protected Double computeNext(Double previous) {
      return next(previous);
    }
    @Nullable
    static Double next(Double prevdouble len,
        StochasticSupplier<DoublesupplierRandomGenerator rng) {
      final double nextVal = prev + getValue(supplierrng);
      if (nextVal < len) {
        return nextVal;
      }
      return null;
    }
    static double getValue(StochasticSupplier<DoubleedRandomGenerator rng) {
      final double sample = ed.get(rng.nextLong());
      checkArgument(
          sample >= 0d,
          "A StochasticSupplier used in a TimeSeries may not return negative values, was: %s.",
          sample);
      return sample;
    }
  }
  static class UniformTimeSeries implements TimeSeriesGenerator {
    static final double SMALLEST_DEVIATION = .0000001;
    private final RandomGenerator rng;
    private final double length;
    private final double average;
    UniformTimeSeries(double lendouble avgStochasticSupplier<Doubledev) {
       = new MersenneTwister();
       = len;
       = avg;
       = dev;
    }
    @Override
    public ImmutableList<Doublegenerate(long seed) {
      .setSeed(seed);
      double deviation = .get(.nextLong());
      deviation = Math.min(deviation);
      final double lowerBound =  - deviation;
      final double upperBound =  + deviation;
      if (deviation < ) {
        return ImmutableList.copyOf(new FixedTimeSeriesIterator(,
            ));
      }
      return ImmutableList.copyOf(new TimeSeriesIterator(
          new UniformRealDistribution(lowerBoundupperBound), ));
    }
  }
  static class NormalTimeSeries implements TimeSeriesGenerator {
    private final double length;
    private final RealDistribution distribution;
    NormalTimeSeries(double lendouble avgdouble sd) {
       = len;
       = new NormalDistribution(avgsd);
    }
    @Override
    public ImmutableList<Doublegenerate(long seed) {
      return ImmutableList.copyOf(new TimeSeriesIterator(
          ));
    }
  }
  static class FixedTimeSeriesIterator extends
    private final double length;
    private final double average;
    protected FixedTimeSeriesIterator(RandomGenerator rngdouble len,
        double avg) {
      super(rng.nextDouble() * avg);
       = len;
       = avg;
    }
    @SuppressWarnings("null")
    @Nullable
    @Override
    protected Double computeNext(Double prev) {
      final double nextVal = prev + ;
      if (nextVal < ) {
        return nextVal;
      }
      return null;
    }
  }
    private final RealDistribution ed;
    private final double length;
    TimeSeriesIterator(RealDistribution distrdouble len) {
      super(next(0d, lendistr));
       = len;
       = distr;
    }
    @SuppressWarnings("null")
    @Nullable
    @Override
    protected Double computeNext(Double previous) {
      return next(previous);
    }
    @Nullable
    static Double next(Double prevdouble lenRealDistribution ed) {
      final double nextVal = prev + getFirstPositive(ed);
      if (nextVal < len) {
        return nextVal;
      }
      return null;
    }
    static double getFirstPositive(RealDistribution ed) {
      double sample = ed.sample();
      while (sample < 0) {
        sample = ed.sample();
      }
      return sample;
    }
  }
  static class NHPredicate implements Predicate<Double> {
    private final RandomGenerator rng;
    private final IntensityFunction lambda;
    private final double lambdaMax;
       = r;
       = l;
       = .getMax();
    }
    @Override
    public boolean apply(@Nullable Double input) {
      assert input != null;
      return .nextDouble() <= .apply(input) / ;
    }
  }
New to GrepCode? Check out our FAQ X