blob: 476578c3fedfab1c78eefacdc3a17dd4be68f830 [file] [log] [blame]
Jeff Thompsonfa306642013-06-17 15:06:57 -07001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
2/*
3 * Copyright (c) 2013, Regents of the University of California
4 * Alexander Afanasyev
5 * Zhenkai Zhu
6 *
7 * BSD license, See the LICENSE file for more information
8 *
9 * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
10 * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
11 */
12
13#ifndef RANDOM_INTERVAL_GENERATOR_H
14#define RANDOM_INTERVAL_GENERATOR_H
15
16#include "interval-generator.h"
17
18#include <boost/random/mersenne_twister.hpp>
19#include <boost/random/uniform_real.hpp>
20#include <boost/random/variate_generator.hpp>
21#include <boost/date_time/posix_time/posix_time_types.hpp>
22
23// generates intervals with uniform distribution
24class RandomIntervalGenerator : public IntervalGenerator
25{
26public:
27 typedef enum
28 {
29 UP = 1,
30 DOWN = 2,
31 EVEN = 3
32 } Direction;
33
34public:
35 // percent is random-range/interval; e.g. if interval is 10 and you wish the random-range to be 2
36 // e.g. 9 ~ 11, percent = 0.2
37 // direction shifts the random range; e.g. in the above example, UP would produce a range of
38 // 10 ~ 12, DOWN of 8 ~ 10, and EVEN of 9 ~ 11
39 RandomIntervalGenerator(double interval, double percent, Direction direction = EVEN)
40 // : m_rng(time(NULL))
41 : m_rng (static_cast<int> (boost::posix_time::microsec_clock::local_time().time_of_day ().total_nanoseconds ()))
42 , m_dist(0.0, fractional(percent))
43 , m_random(m_rng, m_dist)
44 , m_direction(direction)
45 , m_percent(percent)
46 , m_interval(interval)
47 { }
48
49 virtual ~RandomIntervalGenerator(){}
50
51 virtual double
52 nextInterval() _OVERRIDE
53 {
54 double percent = m_random();
55 double interval = m_interval;
56 switch (m_direction)
57 {
58 case UP: interval = m_interval * (1.0 + percent); break;
59 case DOWN: interval = m_interval * (1.0 - percent); break;
60 case EVEN: interval = m_interval * (1.0 - m_percent/2.0 + percent); break;
61 default: break;
62 }
63
64 return interval;
65 }
66
67private:
68 inline double fractional(double x) { double dummy; return abs(modf(x, &dummy)); }
69
70private:
71 typedef boost::mt19937 RNG_TYPE;
72 RNG_TYPE m_rng;
73 boost::uniform_real<> m_dist;
74 boost::variate_generator<RNG_TYPE &, boost::uniform_real<> > m_random;
75 Direction m_direction;
76 double m_percent;
77 double m_interval;
78
79};
80#endif // RANDOM_INTERVAL_GENERATOR_H