A Discrete-Event Network Simulator
API
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
random-variable.cc
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 //
3 // Copyright (c) 2006 Georgia Tech Research Corporation
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License version 2 as
7 // published by the Free Software Foundation;
8 //
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with this program; if not, write to the Free Software
16 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 //
18 // Author: Rajib Bhattacharjea<raj.b@gatech.edu>
19 // Author: Hadi Arbabi<marbabi@cs.odu.edu>
20 //
21 
22 #include <iostream>
23 
24 #include <math.h>
25 #include <stdlib.h>
26 #include <sys/time.h> // for gettimeofday
27 #include <unistd.h>
28 #include <iostream>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <fcntl.h>
32 #include <sstream>
33 #include <vector>
34 
35 #include "assert.h"
36 #include "random-variable.h"
37 #include "rng-seed-manager.h"
38 #include "rng-stream.h"
39 #include "fatal-error.h"
40 
41 using namespace std;
42 
43 namespace ns3 {
44 
45 // -----------------------------------------------------------------------------
46 // -----------------------------------------------------------------------------
47 // RandomVariableBase methods
48 
49 
51 {
52 public:
55  virtual ~RandomVariableBase ();
56  virtual double GetValue () = 0;
57  virtual uint32_t GetInteger ();
58  virtual RandomVariableBase* Copy (void) const = 0;
59  RngStream *GetStream(void);
60 private:
61  RngStream* m_generator; // underlying generator being wrapped
62 };
63 
64 RandomVariableBase::RandomVariableBase ()
65  : m_generator (0)
66 {
67 }
68 
70  : m_generator (0)
71 {
72  if (r.m_generator != 0)
73  {
77  }
78 }
79 
81 {
82  delete m_generator;
83 }
84 
86 {
87  return (uint32_t)GetValue ();
88 }
89 
90 RngStream *
92 {
93  if (m_generator == 0)
94  {
98  }
99  return m_generator;
100 }
101 
102 // -------------------------------------------------------
103 
105  : m_variable (0)
106 {
107 }
109  : m_variable (o.m_variable->Copy ())
110 {
111 }
113  : m_variable (variable.Copy ())
114 {
115 }
118 {
119  if (&o == this)
120  {
121  return *this;
122  }
123  delete m_variable;
124  m_variable = o.m_variable->Copy ();
125  return *this;
126 }
128 {
129  delete m_variable;
130 }
131 double
133 {
134  return m_variable->GetValue ();
135 }
136 
137 uint32_t
139 {
140  return m_variable->GetInteger ();
141 }
142 
145 {
146  return m_variable;
147 }
148 
149 
152 
153 // -----------------------------------------------------------------------------
154 // -----------------------------------------------------------------------------
155 // UniformVariableImpl
156 
158 {
159 public:
165 
171  UniformVariableImpl (double s, double l);
172 
174 
175  double GetMin (void) const;
176  double GetMax (void) const;
177 
181  virtual double GetValue ();
182 
186  virtual double GetValue (double s, double l);
187 
188  virtual RandomVariableBase* Copy (void) const;
189 
190 private:
191  double m_min;
192  double m_max;
193 };
194 
196  : m_min (0),
197  m_max (1.0)
198 {
199 }
200 
202  : m_min (s),
203  m_max (l)
204 {
205 }
206 
208  : RandomVariableBase (c),
209  m_min (c.m_min),
210  m_max (c.m_max)
211 {
212 }
213 
214 double
216 {
217  return m_min;
218 }
219 double
221 {
222  return m_max;
223 }
224 
225 
227 {
228  RngStream *generator = GetStream ();
229  return m_min + generator->RandU01 () * (m_max - m_min);
230 }
231 
232 double UniformVariableImpl::GetValue (double s, double l)
233 {
234  RngStream *generator = GetStream ();
235  return s + generator->RandU01 () * (l - s);
236 }
237 
239 {
240  return new UniformVariableImpl (*this);
241 }
242 
245 {
246 }
249 {
250 }
251 
252 double UniformVariable::GetValue (void) const
253 {
254  return this->RandomVariable::GetValue ();
255 }
256 
257 double UniformVariable::GetValue (double s, double l)
258 {
259  return ((UniformVariableImpl*)Peek ())->GetValue (s,l);
260 }
261 
262 uint32_t UniformVariable::GetInteger (uint32_t s, uint32_t l)
263 {
264  NS_ASSERT (s <= l);
265  return static_cast<uint32_t> ( GetValue (s, l + 1) );
266 }
267 
268 // -----------------------------------------------------------------------------
269 // -----------------------------------------------------------------------------
270 // ConstantVariableImpl methods
271 
273 {
274 
275 public:
280 
286  ConstantVariableImpl (double c);
287 
288 
290 
295  void NewConstant (double c);
296 
300  virtual double GetValue ();
301  virtual uint32_t GetInteger ();
302  virtual RandomVariableBase* Copy (void) const;
303 private:
304  double m_const;
305 };
306 
308  : m_const (0)
309 {
310 }
311 
313  : m_const (c)
314 {
315 }
316 
318  : RandomVariableBase (c),
319  m_const (c.m_const)
320 {
321 }
322 
324 {
325  m_const = c;
326 }
327 
329 {
330  return m_const;
331 }
332 
334 {
335  return (uint32_t)m_const;
336 }
337 
339 {
340  return new ConstantVariableImpl (*this);
341 }
342 
345 {
346 }
349 {
350 }
351 void
353 {
354  *this = ConstantVariable (c);
355 }
356 
357 // -----------------------------------------------------------------------------
358 // -----------------------------------------------------------------------------
359 // SequentialVariableImpl methods
360 
361 
363 {
364 
365 public:
377  SequentialVariableImpl (double f, double l, double i = 1, uint32_t c = 1);
378 
389  SequentialVariableImpl (double f, double l, const RandomVariable& i, uint32_t c = 1);
390 
392 
397  virtual double GetValue ();
398  virtual RandomVariableBase* Copy (void) const;
399 private:
400  double m_min;
401  double m_max;
403  uint32_t m_consecutive;
404  double m_current;
406 };
407 
408 SequentialVariableImpl::SequentialVariableImpl (double f, double l, double i, uint32_t c)
409  : m_min (f),
410  m_max (l),
411  m_increment (ConstantVariable (i)),
412  m_consecutive (c),
413  m_current (f),
414  m_currentConsecutive (0)
415 {
416 }
417 
418 SequentialVariableImpl::SequentialVariableImpl (double f, double l, const RandomVariable& i, uint32_t c)
419  : m_min (f),
420  m_max (l),
421  m_increment (i),
422  m_consecutive (c),
423  m_current (f),
424  m_currentConsecutive (0)
425 {
426 }
427 
429  : RandomVariableBase (c),
430  m_min (c.m_min),
431  m_max (c.m_max),
432  m_increment (c.m_increment),
433  m_consecutive (c.m_consecutive),
434  m_current (c.m_current),
435  m_currentConsecutive (c.m_currentConsecutive)
436 {
437 }
438 
440 {
441 }
442 
444 { // Return a sequential series of values
445  double r = m_current;
447  { // Time to advance to next
450  if (m_current >= m_max)
451  {
452  m_current = m_min + (m_current - m_max);
453  }
454  }
455  return r;
456 }
457 
459 {
460  return new SequentialVariableImpl (*this);
461 }
462 
463 SequentialVariable::SequentialVariable (double f, double l, double i, uint32_t c)
464  : RandomVariable (SequentialVariableImpl (f, l, i, c))
465 {
466 }
467 SequentialVariable::SequentialVariable (double f, double l, const RandomVariable& i, uint32_t c)
468  : RandomVariable (SequentialVariableImpl (f, l, i, c))
469 {
470 }
471 
472 // -----------------------------------------------------------------------------
473 // -----------------------------------------------------------------------------
474 // ExponentialVariableImpl methods
475 
477 {
478 public:
484 
490  explicit ExponentialVariableImpl (double m);
491 
503  ExponentialVariableImpl (double m, double b);
504 
506 
510  virtual double GetValue ();
511  virtual RandomVariableBase* Copy (void) const;
512 
513 private:
514  double m_mean; // Mean value of RV
515  double m_bound; // Upper bound on value (if non-zero)
516 };
517 
519  : m_mean (1.0),
520  m_bound (0)
521 {
522 }
523 
525  : m_mean (m),
526  m_bound (0)
527 {
528 }
529 
531  : m_mean (m),
532  m_bound (b)
533 {
534 }
535 
537  : RandomVariableBase (c),
538  m_mean (c.m_mean),
539  m_bound (c.m_bound)
540 {
541 }
542 
544 {
545  RngStream *generator = GetStream ();
546  while (1)
547  {
548  double r = -m_mean*log (generator->RandU01 ());
549  if (m_bound == 0 || r <= m_bound)
550  {
551  return r;
552  }
553  // otherwise, try again
554  }
555 }
556 
558 {
559  return new ExponentialVariableImpl (*this);
560 }
561 
564 {
565 }
568 {
569 }
572 {
573 }
574 
575 // -----------------------------------------------------------------------------
576 // -----------------------------------------------------------------------------
577 // ParetoVariableImpl methods
579 {
580 public:
586 
593  explicit ParetoVariableImpl (double m);
594 
602  ParetoVariableImpl (double m, double s);
603 
616  ParetoVariableImpl (double m, double s, double b);
617 
624  ParetoVariableImpl (std::pair<double, double> params);
625 
638  ParetoVariableImpl (std::pair<double, double> params, double b);
639 
641 
645  virtual double GetValue ();
646  virtual RandomVariableBase* Copy () const;
647 
648 private:
649  double m_scale; // Scale value of RV
650  double m_shape; // Shape parameter
651  double m_bound; // Upper bound on value (if non-zero)
652 };
653 
655  : m_scale (0.5 / 1.5),
656  m_shape (1.5),
657  m_bound (0)
658 {
659 }
660 
662  : m_scale (m * 0.5 / 1.5),
663  m_shape (1.5),
664  m_bound (0)
665 {
666 }
667 
669  : m_scale (m * (s - 1.0) / s),
670  m_shape (s),
671  m_bound (0)
672 {
673 }
674 
675 ParetoVariableImpl::ParetoVariableImpl (double m, double s, double b)
676  : m_scale (m * (s - 1.0) / s),
677  m_shape (s),
678  m_bound (b)
679 {
680 }
681 
682 ParetoVariableImpl::ParetoVariableImpl (std::pair<double, double> params)
683  : m_scale (params.first),
684  m_shape (params.second),
685  m_bound (0)
686 {
687 }
688 
689 ParetoVariableImpl::ParetoVariableImpl (std::pair<double, double> params, double b)
690  : m_scale (params.first),
691  m_shape (params.second),
692  m_bound (b)
693 {
694 }
695 
697  : RandomVariableBase (c),
698  m_scale (c.m_scale),
699  m_shape (c.m_shape),
700  m_bound (c.m_bound)
701 {
702 }
703 
705 {
706  RngStream *generator = GetStream ();
707  while (1)
708  {
709  double r = (m_scale * ( 1.0 / pow (generator->RandU01 (), 1.0 / m_shape)));
710  if (m_bound == 0 || r <= m_bound)
711  {
712  return r;
713  }
714  // otherwise, try again
715  }
716 }
717 
719 {
720  return new ParetoVariableImpl (*this);
721 }
722 
725 {
726 }
729 {
730 }
731 ParetoVariable::ParetoVariable (double m, double s)
733 {
734 }
735 ParetoVariable::ParetoVariable (double m, double s, double b)
736  : RandomVariable (ParetoVariableImpl (m, s, b))
737 {
738 }
739 ParetoVariable::ParetoVariable (std::pair<double, double> params)
741 {
742 }
743 ParetoVariable::ParetoVariable (std::pair<double, double> params, double b)
744  : RandomVariable (ParetoVariableImpl (params, b))
745 {
746 }
747 
748 // -----------------------------------------------------------------------------
749 // -----------------------------------------------------------------------------
750 // WeibullVariableImpl methods
751 
753 {
754 public:
760 
761 
767  WeibullVariableImpl (double m);
768 
775  WeibullVariableImpl (double m, double s);
776 
788  WeibullVariableImpl (double m, double s, double b);
789 
791 
795  virtual double GetValue ();
796  virtual RandomVariableBase* Copy (void) const;
797 
798 private:
799  double m_mean; // Mean value of RV
800  double m_alpha; // Shape parameter
801  double m_bound; // Upper bound on value (if non-zero)
802 };
803 
805  m_alpha (1),
806  m_bound (0)
807 {
808 }
810  : m_mean (m),
811  m_alpha (1),
812  m_bound (0)
813 {
814 }
816  : m_mean (m),
817  m_alpha (s),
818  m_bound (0)
819 {
820 }
821 WeibullVariableImpl::WeibullVariableImpl (double m, double s, double b)
822  : m_mean (m),
823  m_alpha (s),
824  m_bound (b)
825 {
826 }
828  : RandomVariableBase (c),
829  m_mean (c.m_mean),
830  m_alpha (c.m_alpha),
831  m_bound (c.m_bound)
832 {
833 }
834 
836 {
837  RngStream *generator = GetStream ();
838  double exponent = 1.0 / m_alpha;
839  while (1)
840  {
841  double r = m_mean * pow ( -log (generator->RandU01 ()), exponent);
842  if (m_bound == 0 || r <= m_bound)
843  {
844  return r;
845  }
846  // otherwise, try again
847  }
848 }
849 
851 {
852  return new WeibullVariableImpl (*this);
853 }
854 
857 {
858 }
861 {
862 }
865 {
866 }
867 WeibullVariable::WeibullVariable (double m, double s, double b)
868  : RandomVariable (WeibullVariableImpl (m, s, b))
869 {
870 }
871 
872 // -----------------------------------------------------------------------------
873 // -----------------------------------------------------------------------------
874 // NormalVariableImpl methods
875 
876 class NormalVariableImpl : public RandomVariableBase // Normally Distributed random var
877 
878 {
879 public:
880  static const double INFINITE_VALUE;
886 
893  NormalVariableImpl (double m, double v, double b = INFINITE_VALUE);
894 
896 
900  virtual double GetValue ();
901  virtual RandomVariableBase* Copy (void) const;
902 
903  double GetMean (void) const;
904  double GetVariance (void) const;
905  double GetBound (void) const;
906 
907 private:
908  double m_mean; // Mean value of RV
909  double m_variance; // Mean value of RV
910  double m_bound; // Bound on value's difference from the mean (absolute value)
911  bool m_nextValid; // True if next valid
912  double m_next; // The algorithm produces two values at a time
913 };
914 
915 const double NormalVariableImpl::INFINITE_VALUE = 1e307;
916 
918  : m_mean (0.0),
919  m_variance (1.0),
920  m_bound (INFINITE_VALUE),
921  m_nextValid (false)
922 {
923 }
924 
925 NormalVariableImpl::NormalVariableImpl (double m, double v, double b)
926  : m_mean (m),
927  m_variance (v),
928  m_bound (b),
929  m_nextValid (false)
930 {
931 }
932 
934  : RandomVariableBase (c),
935  m_mean (c.m_mean),
936  m_variance (c.m_variance),
937  m_bound (c.m_bound),
938  m_nextValid (false)
939 {
940 }
941 
943 {
944  RngStream *generator = GetStream ();
945  if (m_nextValid)
946  { // use previously generated
947  m_nextValid = false;
948  return m_next;
949  }
950  while (1)
951  { // See Simulation Modeling and Analysis p. 466 (Averill Law)
952  // for algorithm; basically a Box-Muller transform:
953  // http://en.wikipedia.org/wiki/Box-Muller_transform
954  double u1 = generator->RandU01 ();
955  double u2 = generator->RandU01 ();
956  double v1 = 2 * u1 - 1;
957  double v2 = 2 * u2 - 1;
958  double w = v1 * v1 + v2 * v2;
959  if (w <= 1.0)
960  { // Got good pair
961  double y = sqrt ((-2 * log (w)) / w);
962  m_next = m_mean + v2 * y * sqrt (m_variance);
963  // if next is in bounds, it is valid
964  m_nextValid = fabs (m_next - m_mean) <= m_bound;
965  double x1 = m_mean + v1 * y * sqrt (m_variance);
966  // if x1 is in bounds, return it
967  if (fabs (x1 - m_mean) <= m_bound)
968  {
969  return x1;
970  }
971  // otherwise try and return m_next if it is valid
972  else if (m_nextValid)
973  {
974  m_nextValid = false;
975  return m_next;
976  }
977  // otherwise, just run this loop again
978  }
979  }
980 }
981 
983 {
984  return new NormalVariableImpl (*this);
985 }
986 
987 double
989 {
990  return m_mean;
991 }
992 
993 double
995 {
996  return m_variance;
997 }
998 
999 double
1001 {
1002  return m_bound;
1003 }
1004 
1007 {
1008 }
1011 {
1012 }
1013 NormalVariable::NormalVariable (double m, double v, double b)
1014  : RandomVariable (NormalVariableImpl (m, v, b))
1015 {
1016 }
1017 
1018 // -----------------------------------------------------------------------------
1019 // -----------------------------------------------------------------------------
1021 {
1022 public:
1026  explicit EmpiricalVariableImpl ();
1027 
1028  virtual ~EmpiricalVariableImpl ();
1033  virtual double GetValue ();
1034  virtual RandomVariableBase* Copy (void) const;
1040  virtual void CDF (double v, double c); // Value, prob <= Value
1041 
1042 private:
1043  class ValueCDF
1044  {
1045 public:
1046  ValueCDF ();
1047  ValueCDF (double v, double c);
1048  ValueCDF (const ValueCDF& c);
1049  double value;
1050  double cdf;
1051  };
1052  virtual void Validate (); // Insure non-decreasing emiprical values
1053  virtual double Interpolate (double, double, double, double, double);
1054  bool validated; // True if non-decreasing validated
1055  std::vector<ValueCDF> emp; // Empicical CDF
1056 };
1057 
1058 
1059 // ValueCDF methods
1061  : value (0.0),
1062  cdf (0.0)
1063 {
1064 }
1066  : value (v),
1067  cdf (c)
1068 {
1069 }
1071  : value (c.value),
1072  cdf (c.cdf)
1073 {
1074 }
1075 
1076 // -----------------------------------------------------------------------------
1077 // -----------------------------------------------------------------------------
1078 // EmpiricalVariableImpl methods
1080  : validated (false)
1081 {
1082 }
1083 
1085  : RandomVariableBase (c),
1086  validated (c.validated),
1087  emp (c.emp)
1088 {
1089 }
1090 
1092 {
1093 }
1094 
1096 { // Return a value from the empirical distribution
1097  // This code based (loosely) on code by Bruce Mah (Thanks Bruce!)
1098  RngStream *generator = GetStream ();
1099  if (emp.size () == 0)
1100  {
1101  return 0.0; // HuH? No empirical data
1102  }
1103  if (!validated)
1104  {
1105  Validate (); // Insure in non-decreasing
1106  }
1107  double r = generator->RandU01 ();
1108  if (r <= emp.front ().cdf)
1109  {
1110  return emp.front ().value; // Less than first
1111  }
1112  if (r >= emp.back ().cdf)
1113  {
1114  return emp.back ().value; // Greater than last
1115  }
1116  // Binary search
1117  std::vector<ValueCDF>::size_type bottom = 0;
1118  std::vector<ValueCDF>::size_type top = emp.size () - 1;
1119  while (1)
1120  {
1121  std::vector<ValueCDF>::size_type c = (top + bottom) / 2;
1122  if (r >= emp[c].cdf && r < emp[c + 1].cdf)
1123  { // Found it
1124  return Interpolate (emp[c].cdf, emp[c + 1].cdf,
1125  emp[c].value, emp[c + 1].value,
1126  r);
1127  }
1128  // Not here, adjust bounds
1129  if (r < emp[c].cdf)
1130  {
1131  top = c - 1;
1132  }
1133  else
1134  {
1135  bottom = c + 1;
1136  }
1137  }
1138 }
1139 
1141 {
1142  return new EmpiricalVariableImpl (*this);
1143 }
1144 
1145 void EmpiricalVariableImpl::CDF (double v, double c)
1146 { // Add a new empirical datapoint to the empirical cdf
1147  // NOTE. These MUST be inserted in non-decreasing order
1148  emp.push_back (ValueCDF (v, c));
1149 }
1150 
1152 {
1153  ValueCDF prior;
1154  for (std::vector<ValueCDF>::size_type i = 0; i < emp.size (); ++i)
1155  {
1156  ValueCDF& current = emp[i];
1157  if (current.value < prior.value || current.cdf < prior.cdf)
1158  { // Error
1159  cerr << "Empirical Dist error,"
1160  << " current value " << current.value
1161  << " prior value " << prior.value
1162  << " current cdf " << current.cdf
1163  << " prior cdf " << prior.cdf << endl;
1164  NS_FATAL_ERROR ("Empirical Dist error");
1165  }
1166  prior = current;
1167  }
1168  validated = true;
1169 }
1170 
1171 double EmpiricalVariableImpl::Interpolate (double c1, double c2,
1172  double v1, double v2, double r)
1173 { // Interpolate random value in range [v1..v2) based on [c1 .. r .. c2)
1174  return (v1 + ((v2 - v1) / (c2 - c1)) * (r - c1));
1175 }
1176 
1179 {
1180 }
1182  : RandomVariable (variable)
1183 {
1184 }
1185 void
1186 EmpiricalVariable::CDF (double v, double c)
1187 {
1188  EmpiricalVariableImpl *impl = dynamic_cast<EmpiricalVariableImpl *> (Peek ());
1189  NS_ASSERT (impl);
1190  impl->CDF (v, c);
1191 }
1192 
1193 
1194 // -----------------------------------------------------------------------------
1195 // -----------------------------------------------------------------------------
1196 // IntegerValue EmpiricalVariableImpl methods
1198 {
1199 public:
1201 
1202  virtual RandomVariableBase* Copy (void) const;
1206  virtual uint32_t GetInteger ();
1207 private:
1208  virtual double Interpolate (double, double, double, double, double);
1209 };
1210 
1211 
1213 {
1214 }
1215 
1217 {
1218  return (uint32_t)GetValue ();
1219 }
1220 
1222 {
1223  return new IntEmpiricalVariableImpl (*this);
1224 }
1225 
1226 double IntEmpiricalVariableImpl::Interpolate (double c1, double c2,
1227  double v1, double v2, double r)
1228 { // Interpolate random value in range [v1..v2) based on [c1 .. r .. c2)
1229  return ceil (v1 + ((v2 - v1) / (c2 - c1)) * (r - c1));
1230 }
1231 
1234 {
1235 }
1236 
1237 // -----------------------------------------------------------------------------
1238 // -----------------------------------------------------------------------------
1239 // DeterministicVariableImpl
1241 {
1242 
1243 public:
1255  explicit DeterministicVariableImpl (double* d, uint32_t c);
1256 
1257  virtual ~DeterministicVariableImpl ();
1261  virtual double GetValue ();
1262  virtual RandomVariableBase* Copy (void) const;
1263 private:
1264  uint32_t count;
1265  uint32_t next;
1266  double* data;
1267 };
1268 
1270  : count (c),
1271  next (c),
1272  data (d)
1273 { // Nothing else needed
1274 }
1275 
1277 {
1278 }
1279 
1281 {
1282  if (next == count)
1283  {
1284  next = 0;
1285  }
1286  return data[next++];
1287 }
1288 
1290 {
1291  return new DeterministicVariableImpl (*this);
1292 }
1293 
1296 {
1297 }
1298 
1299 // -----------------------------------------------------------------------------
1300 // -----------------------------------------------------------------------------
1301 // LogNormalVariableImpl
1303 {
1304 public:
1309  LogNormalVariableImpl (double mu, double sigma);
1310 
1314  virtual double GetValue ();
1315  virtual RandomVariableBase* Copy (void) const;
1316 
1317 private:
1318  double m_mu;
1319  double m_sigma;
1320 };
1321 
1322 
1324 {
1325  return new LogNormalVariableImpl (*this);
1326 }
1327 
1329  : m_mu (mu),
1330  m_sigma (sigma)
1331 {
1332 }
1333 
1334 // The code from this function was adapted from the GNU Scientific
1335 // Library 1.8:
1336 /* randist/lognormal.c
1337  *
1338  * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough
1339  *
1340  * This program is free software; you can redistribute it and/or modify
1341  * it under the terms of the GNU General Public License as published by
1342  * the Free Software Foundation; either version 2 of the License, or (at
1343  * your option) any later version.
1344  *
1345  * This program is distributed in the hope that it will be useful, but
1346  * WITHOUT ANY WARRANTY; without even the implied warranty of
1347  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
1348  * General Public License for more details.
1349  *
1350  * You should have received a copy of the GNU General Public License
1351  * along with this program; if not, write to the Free Software
1352  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
1353  */
1354 /* The lognormal distribution has the form
1355 
1356  p(x) dx = 1/(x * sqrt(2 pi sigma^2)) exp(-(ln(x) - zeta)^2/2 sigma^2) dx
1357 
1358  for x > 0. Lognormal random numbers are the exponentials of
1359  gaussian random numbers */
1360 double
1362 {
1363  RngStream *generator = GetStream ();
1364  double u, v, r2, normal, z;
1365 
1366  do
1367  {
1368  /* choose x,y in uniform square (-1,-1) to (+1,+1) */
1369 
1370  u = -1 + 2 * generator->RandU01 ();
1371  v = -1 + 2 * generator->RandU01 ();
1372 
1373  /* see if it is in the unit circle */
1374  r2 = u * u + v * v;
1375  }
1376  while (r2 > 1.0 || r2 == 0);
1377 
1378  normal = u * sqrt (-2.0 * log (r2) / r2);
1379 
1380  z = exp (m_sigma * normal + m_mu);
1381 
1382  return z;
1383 }
1384 
1385 LogNormalVariable::LogNormalVariable (double mu, double sigma)
1386  : RandomVariable (LogNormalVariableImpl (mu, sigma))
1387 {
1388 }
1389 
1390 // -----------------------------------------------------------------------------
1391 // -----------------------------------------------------------------------------
1392 // GammaVariableImpl
1394 {
1395 public:
1400  GammaVariableImpl (double alpha, double beta);
1401 
1405  virtual double GetValue ();
1406 
1411  double GetValue (double alpha, double beta);
1412 
1413  virtual RandomVariableBase* Copy (void) const;
1414 
1415 private:
1416  double m_alpha;
1417  double m_beta;
1419 };
1420 
1421 
1423 {
1424  return new GammaVariableImpl (m_alpha, m_beta);
1425 }
1426 
1427 GammaVariableImpl::GammaVariableImpl (double alpha, double beta)
1428  : m_alpha (alpha),
1429  m_beta (beta)
1430 {
1431 }
1432 
1433 double
1435 {
1436  return GetValue (m_alpha, m_beta);
1437 }
1438 
1439 /*
1440  The code for the following generator functions was adapted from ns-2
1441  tools/ranvar.cc
1442 
1443  Originally the algorithm was devised by Marsaglia in 2000:
1444  G. Marsaglia, W. W. Tsang: A simple method for gereating Gamma variables
1445  ACM Transactions on mathematical software, Vol. 26, No. 3, Sept. 2000
1446 
1447  The Gamma distribution density function has the form
1448 
1449  x^(alpha-1) * exp(-x/beta)
1450  p(x; alpha, beta) = ----------------------------
1451  beta^alpha * Gamma(alpha)
1452 
1453  for x > 0.
1454 */
1455 double
1456 GammaVariableImpl::GetValue (double alpha, double beta)
1457 {
1458  RngStream *generator = GetStream ();
1459 
1460  if (alpha < 1)
1461  {
1462  double u = generator->RandU01 ();
1463  return GetValue (1.0 + alpha, beta) * pow (u, 1.0 / alpha);
1464  }
1465 
1466  double x, v, u;
1467  double d = alpha - 1.0 / 3.0;
1468  double c = (1.0 / 3.0) / sqrt (d);
1469 
1470  while (1)
1471  {
1472  do
1473  {
1474  x = m_normal.GetValue ();
1475  v = 1.0 + c * x;
1476  }
1477  while (v <= 0);
1478 
1479  v = v * v * v;
1480  u = generator->RandU01 ();
1481  if (u < 1 - 0.0331 * x * x * x * x)
1482  {
1483  break;
1484  }
1485  if (log (u) < 0.5 * x * x + d * (1 - v + log (v)))
1486  {
1487  break;
1488  }
1489  }
1490 
1491  return beta * d * v;
1492 }
1493 
1495  : RandomVariable (GammaVariableImpl (1.0, 1.0))
1496 {
1497 }
1498 
1499 GammaVariable::GammaVariable (double alpha, double beta)
1500  : RandomVariable (GammaVariableImpl (alpha, beta))
1501 {
1502 }
1503 
1504 double GammaVariable::GetValue (void) const
1505 {
1506  return this->RandomVariable::GetValue ();
1507 }
1508 
1509 double GammaVariable::GetValue (double alpha, double beta) const
1510 {
1511  return ((GammaVariableImpl*)Peek ())->GetValue (alpha, beta);
1512 }
1513 
1514 // -----------------------------------------------------------------------------
1515 // -----------------------------------------------------------------------------
1516 // ErlangVariableImpl
1517 
1519 {
1520 public:
1525  ErlangVariableImpl (unsigned int k, double lambda);
1526 
1530  virtual double GetValue ();
1531 
1536  double GetValue (unsigned int k, double lambda);
1537 
1538  virtual RandomVariableBase* Copy (void) const;
1539 
1540 private:
1541  unsigned int m_k;
1542  double m_lambda;
1543 };
1544 
1545 
1547 {
1548  return new ErlangVariableImpl (m_k, m_lambda);
1549 }
1550 
1551 ErlangVariableImpl::ErlangVariableImpl (unsigned int k, double lambda)
1552  : m_k (k),
1553  m_lambda (lambda)
1554 {
1555 }
1556 
1557 double
1559 {
1560  return GetValue (m_k, m_lambda);
1561 }
1562 
1563 /*
1564  The code for the following generator functions was adapted from ns-2
1565  tools/ranvar.cc
1566 
1567  The Erlang distribution density function has the form
1568 
1569  x^(k-1) * exp(-x/lambda)
1570  p(x; k, lambda) = ---------------------------
1571  lambda^k * (k-1)!
1572 
1573  for x > 0.
1574 */
1575 double
1576 ErlangVariableImpl::GetValue (unsigned int k, double lambda)
1577 {
1578  // XXX: Fixme: do not create a new
1579  // RNG stream every time the function is called !
1580  ExponentialVariable exponential (lambda);
1581 
1582  double result = 0;
1583  for (unsigned int i = 0; i < k; ++i)
1584  {
1585  result += exponential.GetValue ();
1586  }
1587 
1588  return result;
1589 }
1590 
1592  : RandomVariable (ErlangVariableImpl (1, 1.0))
1593 {
1594 }
1595 
1596 ErlangVariable::ErlangVariable (unsigned int k, double lambda)
1597  : RandomVariable (ErlangVariableImpl (k, lambda))
1598 {
1599 }
1600 
1601 double ErlangVariable::GetValue (void) const
1602 {
1603  return this->RandomVariable::GetValue ();
1604 }
1605 
1606 double ErlangVariable::GetValue (unsigned int k, double lambda) const
1607 {
1608  return ((ErlangVariableImpl*)Peek ())->GetValue (k, lambda);
1609 }
1610 
1611 // -----------------------------------------------------------------------------
1612 // -----------------------------------------------------------------------------
1613 // TriangularVariableImpl methods
1615 {
1616 public:
1622 
1630  TriangularVariableImpl (double s, double l, double mean);
1631 
1633 
1637  virtual double GetValue ();
1638  virtual RandomVariableBase* Copy (void) const;
1639 
1640 private:
1641  double m_min;
1642  double m_max;
1643  double m_mode; // easier to work with the mode internally instead of the mean
1644  // they are related by the simple: mean = (min+max+mode)/3
1645 };
1646 
1648  : m_min (0),
1649  m_max (1),
1650  m_mode (0.5)
1651 {
1652 }
1653 
1654 TriangularVariableImpl::TriangularVariableImpl (double s, double l, double mean)
1655  : m_min (s),
1656  m_max (l),
1657  m_mode (3.0 * mean - s - l)
1658 {
1659 }
1660 
1662  : RandomVariableBase (c),
1663  m_min (c.m_min),
1664  m_max (c.m_max),
1665  m_mode (c.m_mode)
1666 {
1667 }
1668 
1670 {
1671  RngStream *generator = GetStream ();
1672  double u = generator->RandU01 ();
1673  if (u <= (m_mode - m_min) / (m_max - m_min) )
1674  {
1675  return m_min + sqrt (u * (m_max - m_min) * (m_mode - m_min) );
1676  }
1677  else
1678  {
1679  return m_max - sqrt ( (1 - u) * (m_max - m_min) * (m_max - m_mode) );
1680  }
1681 }
1682 
1684 {
1685  return new TriangularVariableImpl (*this);
1686 }
1687 
1690 {
1691 }
1692 TriangularVariable::TriangularVariable (double s, double l, double mean)
1693  : RandomVariable (TriangularVariableImpl (s,l,mean))
1694 {
1695 }
1696 
1697 // -----------------------------------------------------------------------------
1698 // -----------------------------------------------------------------------------
1699 // ZipfVariableImpl
1701 {
1702 public:
1707  ZipfVariableImpl (long n, double alpha);
1708 
1712  ZipfVariableImpl ();
1713 
1717  virtual double GetValue ();
1718  virtual RandomVariableBase* Copy (void) const;
1719 
1720 private:
1721  long m_n;
1722  double m_alpha;
1723  double m_c; // the normalization constant
1724 };
1725 
1726 
1728 {
1729  return new ZipfVariableImpl (m_n, m_alpha);
1730 }
1731 
1733  : m_n (1),
1734  m_alpha (0),
1735  m_c (1)
1736 {
1737 }
1738 
1739 
1741  : m_n (n),
1742  m_alpha (alpha),
1743  m_c (0)
1744 {
1745  // calculate the normalization constant c
1746  for (int i = 1; i <= n; i++)
1747  {
1748  m_c += (1.0 / pow ((double)i,alpha));
1749  }
1750  m_c = 1.0 / m_c;
1751 }
1752 
1753 double
1755 {
1756  RngStream *generator = GetStream ();
1757 
1758  double u = generator->RandU01 ();
1759  double sum_prob = 0,zipf_value = 0;
1760  for (int i = 1; i <= m_n; i++)
1761  {
1762  sum_prob += m_c / pow ((double)i,m_alpha);
1763  if (sum_prob > u)
1764  {
1765  zipf_value = i;
1766  break;
1767  }
1768  }
1769  return zipf_value;
1770 }
1771 
1774 {
1775 }
1776 
1777 ZipfVariable::ZipfVariable (long n, double alpha)
1778  : RandomVariable (ZipfVariableImpl (n, alpha))
1779 {
1780 }
1781 
1782 
1783 // -----------------------------------------------------------------------------
1784 // -----------------------------------------------------------------------------
1785 // ZetaVariableImpl
1787 {
1788 public:
1792  ZetaVariableImpl (double alpha);
1793 
1797  ZetaVariableImpl ();
1798 
1802  virtual double GetValue ();
1803  virtual RandomVariableBase* Copy (void) const;
1804 
1805 private:
1806  double m_alpha;
1807  double m_b; // just for calculus simplifications
1808 };
1809 
1810 
1812 {
1813  return new ZetaVariableImpl (m_alpha);
1814 }
1815 
1817  : m_alpha (3.14),
1818  m_b (pow (2.0, 2.14))
1819 {
1820 }
1821 
1822 
1824  : m_alpha (alpha),
1825  m_b (pow (2.0, alpha - 1.0))
1826 {
1827 }
1828 
1829 /*
1830  The code for the following generator functions is borrowed from:
1831  L. Devroye: Non-Uniform Random Variate Generation, Springer-Verlag, New York, 1986.
1832  page 551
1833  */
1834 double
1836 {
1837  RngStream *generator = GetStream ();
1838 
1839  double u, v;
1840  double X, T;
1841  double test;
1842 
1843  do
1844  {
1845  u = generator->RandU01 ();
1846  v = generator->RandU01 ();
1847  X = floor (pow (u, -1.0 / (m_alpha - 1.0)));
1848  T = pow (1.0 + 1.0 / X, m_alpha - 1.0);
1849  test = v * X * (T - 1.0) / (m_b - 1.0);
1850  }
1851  while ( test > (T / m_b) );
1852 
1853  return X;
1854 }
1855 
1858 {
1859 }
1860 
1862  : RandomVariable (ZetaVariableImpl (alpha))
1863 {
1864 }
1865 
1866 
1867 std::ostream & operator << (std::ostream &os, const RandomVariable &var)
1868 {
1869  RandomVariableBase *base = var.Peek ();
1870  ConstantVariableImpl *constant = dynamic_cast<ConstantVariableImpl *> (base);
1871  if (constant != 0)
1872  {
1873  os << "Constant:" << constant->GetValue ();
1874  return os;
1875  }
1876  UniformVariableImpl *uniform = dynamic_cast<UniformVariableImpl *> (base);
1877  if (uniform != 0)
1878  {
1879  os << "Uniform:" << uniform->GetMin () << ":" << uniform->GetMax ();
1880  return os;
1881  }
1882  NormalVariableImpl *normal = dynamic_cast<NormalVariableImpl *> (base);
1883  if (normal != 0)
1884  {
1885  os << "Normal:" << normal->GetMean () << ":" << normal->GetVariance ();
1886  double bound = normal->GetBound ();
1888  {
1889  os << ":" << bound;
1890  }
1891  return os;
1892  }
1893  // XXX: support other distributions
1894  os.setstate (std::ios_base::badbit);
1895  return os;
1896 }
1897 std::istream & operator >> (std::istream &is, RandomVariable &var)
1898 {
1899  std::string value;
1900  is >> value;
1901  std::string::size_type tmp;
1902  tmp = value.find (":");
1903  if (tmp == std::string::npos)
1904  {
1905  is.setstate (std::ios_base::badbit);
1906  return is;
1907  }
1908  std::string type = value.substr (0, tmp);
1909  value = value.substr (tmp + 1, value.npos);
1910  if (type == "Constant")
1911  {
1912  istringstream iss (value);
1913  double constant;
1914  iss >> constant;
1915  var = ConstantVariable (constant);
1916  }
1917  else if (type == "Uniform")
1918  {
1919  if (value.size () == 0)
1920  {
1921  var = UniformVariable ();
1922  }
1923  else
1924  {
1925  tmp = value.find (":");
1926  if (tmp == value.npos)
1927  {
1928  NS_FATAL_ERROR ("bad Uniform value: " << value);
1929  }
1930  istringstream issA (value.substr (0, tmp));
1931  istringstream issB (value.substr (tmp + 1, value.npos));
1932  double a, b;
1933  issA >> a;
1934  issB >> b;
1935  var = UniformVariable (a, b);
1936  }
1937  }
1938  else if (type == "Normal")
1939  {
1940  if (value.size () == 0)
1941  {
1942  var = NormalVariable ();
1943  }
1944  else
1945  {
1946  tmp = value.find (":");
1947  if (tmp == value.npos)
1948  {
1949  NS_FATAL_ERROR ("bad Normal value: " << value);
1950  }
1951  std::string::size_type tmp2;
1952  std::string sub = value.substr (tmp + 1, value.npos);
1953  tmp2 = sub.find (":");
1954  if (tmp2 == value.npos)
1955  {
1956  istringstream issA (value.substr (0, tmp));
1957  istringstream issB (sub);
1958  double a, b;
1959  issA >> a;
1960  issB >> b;
1961  var = NormalVariable (a, b);
1962  }
1963  else
1964  {
1965  istringstream issA (value.substr (0, tmp));
1966  istringstream issB (sub.substr (0, tmp2));
1967  istringstream issC (sub.substr (tmp2 + 1, value.npos));
1968  double a, b, c;
1969  issA >> a;
1970  issB >> b;
1971  issC >> c;
1972  var = NormalVariable (a, b, c);
1973  }
1974  }
1975  }
1976  else
1977  {
1978  NS_FATAL_ERROR ("RandomVariable deserialization not implemented for " << type);
1979  // XXX: support other distributions.
1980  }
1981  return is;
1982 }
1983 
1984 } // namespace ns3