Package SimPy :: Module MonitorTest |
[hide private]
[frames] | no frames]

# Source Code for Module SimPy.MonitorTest

      1  #!/usr / bin / env python
      2  DEVELOPING = False
      3  if DEVELOPING:
      4     from Simulation import *
      5  else:
      6     from SimPy.Simulation import *
      7  from random import *
      8  # ------------------------------------------------------------
      9  #from SimPy.SimPlot import SimPlot
     10  import unittest
     11  # $Revision: 163 $ $Date: 2008-12-15 12:47:44 +0100 (Mo, 15 Dez 2008) $
     12  """MonitorTest.py
     13  Testing Monitor, Tally.
     14  This may be included in SimPyTest eventually.
     15
     16  Change history:
     17  2004 05 03 corrected test for Monitored queues (gav)
     18  2005 09 06 added tests for Tally (kgm)
     19  2007 12 04 adding twVariance for both Monitor and Tally (gav)
     20  2007 12 05 changed name to timeVariance (gav)
     21
     22  """
     23  __version__ = '2.0 $Revision: 163 $ $Date: 2008-12-15 12:47:44 +0100 (Mo, 15 Dez 2008) $'
     24
     25  ## ------------------------------------------------------------
     26 -class Thing(Process):
     27     """ Thing process for testing Monitors in simulation"""
     28 -   def __init__(self, M = None, name = 'Thing',sim=None):
     29          Process.__init__(self,name=name,sim=sim)
     30          self.y = 0.0
     31          self.M = M
     32
     33 -   def execute(self):
     34          DEBUG = 0
     35          self.y = 0.0
     36          if DEBUG: print self.name, self.sim.now(),self.y
     37          self.M.observe(self.y)
     38
     39          yield hold, self, 10.0
     40          self.y = 10
     41          if DEBUG: print self.name, self.sim.now(),self.y
     42          self.M.observe(self.y)
     43
     44          yield hold, self, 10.0
     45          self.y = 5
     46          if DEBUG: print self.name, self.sim.now(),self.y
     47          self.M.observe(self.y)
     48
     49  ## ------------------------------------------------------------
     50
     51 -class makeMtestCase(unittest.TestCase):
     52      """ Test Monitor
     53      """
     54
     55 -    def setUp(self):
     56          self.M = Monitor(name = 'First')
     57          for i in range(10):
     58              self.M.observe(2 * i, i)
     59          self.T = Tally(name = 'tallier')
     60          self.M2 = Monitor(name = 'second')
     61          T = [0, 1,4, 5]
     62          Y = [1, 2,1, 0]
     63          for t, y in zip(T, Y):
     64             self.M2.observe(y, t)
     65          assert self.M2.tseries() == T, 'wrong M2'
     66          assert self.M2.yseries() == Y, 'wrong M2'
     67
     68
     69 -    def testObserve(self):
     70          """Test Monitor - observe"""
     71          m = self.M
     72          #for i in m.series():
     73          #   print i
     74          assert m == [[i, 2 * i] for i in range(10)],'series wrong'
     75          assert m.name == 'First', 'name wrong'
     76          assert m.tseries() == list(range(10)),'tseries wrong:%s' % (m.tseries(),)
     77          assert m.yseries() == [2 * i for i in range(10)],'yseries wrong:%s' % (m.yseries(),)
     78          assert m.total() == 90, 'total wrong:%s'%m.total()
     79          assert m.mean() == 9.0, 'mean wrong:%s'%m.mean()
     80          assert m.var() == (4 * 285.-(90 * 90 / 10.0)) / 10.0, 'sample var wrong: %s' % (m.var(),)
     81
     82 -    def testObserveNoTime(self):
     83          """Test Monitor - observe with time being picked up from now()"""
     84          s=Simulation()
     85          s.initialize()
     86          m = Monitor(name = 'No time',sim=s)
     87          t = Thing(m,sim=s)
     88          s.activate(t, t.execute(),0.0)
     89          s.simulate(until = 20.0)
     90          assert m.yseries() == [0, 10, 5],'yseries wrong:%s' % (m.yseries(),)
     91          assert m.tseries() == [0, 10, 20],'tseries wrong:%s' % (m.tseries(),)
     92          assert m.total() == 15, 'total wrong:%s'%m.total()
     93          assert m.timeAverage(10.0) == 5.0, 'time average is wrong: %s'%m.timeAverage(10.0)
     94
     95 -    def testObserveTally(self):
     96          """Test Monitor - observe without time values"""
     97          m = self.T
     98          for i in range(10):
     99             m.observe(2 * i)
    100          assert m == [[0, 2 * i] for i in range(10)],'series wrong'
    101          assert m.total() == 90, 'total wrong:%s'%m.total()
    102          assert m.mean() == 9.0, 'mean wrong:%s'%m.mean()
    103          assert m.var() == (4 * 285.-(90 * 90 / 10.0)) / 10.0, 'sample var wrong: %s' % (m.var(),)
    104
    105 -    def testtimeAverage(self):
    106         """ test time averages """
    107         # old version
    108         m = self.M
    109         assert m == [[i, 2 * i] for i in range(10)],'series wrong'
    110         assert m.timeAverage(10.0) == 9.0, 'time average is wrong: %s'%m.timeAverage(10)
    111         m2 = self.M2
    112         assert m2.timeAverage(5.0) == 8.0 / 5, 'm2 time average is wrong: %s'%m2.timeAverage(5)
    113         # now the new recursive version
    114         #m = self.M
    115         #assert m.newtimeAverage(10.0) == 9.0, 'm1: new time average wrong: %s'%m.newtimeAverage(10)
    116         #m2 = self.M2
    117         #assert m2.newtimeAverage(5.0) == 8.0 / 5, 'm2: new time average wrong: %s'%m2.newtimeAverage(5.0)
    118
    119
    120 -    def testtimeVariance(self):
    121         """ test time - weighted variance """
    122         m = self.M
    123         assert m == [[i, 2 * i] for i in range(10)],'series wrong'
    124         assert abs(m.timeVariance(10.0) - 33) < 0.0001, 'time - weighted variance is wrong: %s'%m.timeVariance(10.0)
    125         m2 = self.M2
    126         assert abs(m2.timeVariance(5) - 6.0 / 25) < 0.0001, 'time - weighted variance is wrong: %s'%m2.timeVariance(5)
    127
    128 -    def testreset(self):
    129         """ test time averages """
    130         m = self.M
    131         m.reset(t = 10.0)
    132         assert m.startTime == 10.0, 'reset time  wrong'
    133         assert m == [],'reset series wrong: %s' % (m,)
    134
    135
    136 -    def testTally(self):
    137          """Test Monitor - tally"""
    138          m = Monitor(name = 'First')
    139          S = []
    140          for i in range(10):
    141              m.tally(i)
    142              S.append([0, i])
    143          assert m == S, 'Stored series is wrong: %s' % (m,)
    144          assert m.name == 'First', 'Tally name wrong'
    145          assert m.total() == 45, 'Tally total wrong'
    146          assert m.mean() == 4.5, 'Tally mean wrong'
    147          assert m.var()  == (285 - (45 * 45 / 10.0)) / 10.0, 'Tally sample var wrong %s' % (m.var(),)
    148
    149
    150 -    def testAccumulate(self):
    151          """Test Monitor - accumulate"""
    152          #print 'Monitor version ' + __version__
    153          m2 = Monitor(name = 'Second')
    154          assert m2.startTime == 0, 'accum startTime wrong'
    155          for i in range(5):
    156              m2.accum(10, i)  # this is (y, t)
    157          # print 'debug', m2.data
    158          assert m2.total() == 50, 'accum total wrong:%s' % (m2.total(),)
    159          assert m2.startTime == 0, 'accum startTime wrong'
    160          assert m2.timeAverage(5.0) == 10.0, 'accum timeAverage wrong:%s' % (m2.timeAverage(10.0),)
    161          ## test reset
    162          m2.reset(10)
    163          assert m2 == [],'accum reset list wrong:%s' % (m2,)
    164          assert m2.total() == 0.0, 'accum reset total wrong'
    165          assert m2.startTime == 10, 'accum startTime wrong'
    166
    167 -    def testAccumulateInTime(self):
    168          """Test Monitor - accumulate over simulation time"""
    169          #print 'Monitor version ' + __version__
    170          s=Simulation()
    171          s.initialize()
    172          m3 = Monitor(name = 'third',sim=s)
    173          T3 = Thing(name = 'Job', M = m3,sim=s)
    174          assert m3.startTime == 0, 'Accumulate startTime wrong'
    175          s.activate(T3, T3.execute(),0.0)
    176          s.simulate(until = 30.0)
    177          assert m3.startTime == 0, 'Accumulate startTime wrong'
    178
    179 -    def testListStuff(self):
    180         """Test some Monitor list operations"""
    181         shouldBe = [[i, 2 * i] for i in range(10)]
    182         assert shouldBe == self.M, 'M list is wrong'
    183         assert [2, 4] == self.M[2], 'indexing wrong:%s' % (self.M[2],)
    184         self.M[0] = [10, 10]
    185         assert [10, 10] == self.M[0], 'item replacement wrong:%s' % (self.M[0],)
    186         self.M.reverse()
    187         assert [10, 10] == self.M[-1], 'list reverse wrong:%s' % (self.M[-1],)
    188         self.M.sort()
    189         assert [1, 2] == self.M[0], 'list sort wrong:%s' % (self.M[0],)
    190         assert 10 == len(self.M), 'list length wrong'
    191         assert [2, 4] in self.M, 'item in list wrong'
    192
    193
    194 -    def testhistogram(self):
    195         """Test Monitor histogram"""
    196         m = Monitor(name = 'First')
    197         for y in [-5, 0, 5, 15, 99, 105, 120]:m.observe(y)
    198         h = m.histogram(low = 0.0, high = 100.0, nbins = 10)
    199         shouldBe = list(zip(*h)[1])
    200         assert shouldBe == [1, 2,1, 0,0, 0,0, 0,0, 0,1, 2], 'm histogram is wrong: %s' % (shouldBe,)
    201
    202 -def makeMSuite():
    203      suite = unittest.TestSuite()
    204      testObserve = makeMtestCase('testObserve')
    205      testObserveNoTime = makeMtestCase('testObserveNoTime')
    206      testObserveTally = makeMtestCase('testObserveTally')
    207      testtimeAverage = makeMtestCase('testtimeAverage')
    208      testtimeVariance = makeMtestCase('testtimeVariance')
    209      testreset = makeMtestCase('testreset')
    210      testTally = makeMtestCase('testTally')
    211      testAccumulate = makeMtestCase('testAccumulate')
    212      testAccumulateInTime = makeMtestCase('testAccumulateInTime')
    213      testListStuff = makeMtestCase('testListStuff')
    214      testhistogram = makeMtestCase('testhistogram')
    215      suite.addTests([testObserve, testObserveNoTime,
    216                      testObserveTally,
    217                      testtimeAverage,
    218                      testtimeVariance,
    219                      testreset,
    220                      testTally, testAccumulate,
    221                      testAccumulateInTime,
    222                      testListStuff,
    223                      testhistogram,
    224                      ])
    225      return suite
    226
    227  ## -----------------------------------------------------------------------
    228  ## Tally test cases
    229  ## -----------------------------------------------------------------------
    230 -class makeTtestCase(unittest.TestCase):
    231      """ Test Tally
    232      """
    233
    234 -    def setUp(self):
    235          self.T = Tally(name = 'First')
    236          for i in range(10):
    237              self.T.observe(2 * i, i)
    238          self.TT = Tally(name = 'tallier')
    239          self.T2 = Tally(name = 'tally2')
    240          T = [0, 1,4, 5]
    241          Y = [1, 2,1, 0]
    242          for t, y in zip(T, Y):
    243             self.T2.observe(y, t)
    244
    245
    246 -    def testObserve(self):
    247          """Test Tally - observe"""
    248          t = self.T
    249          #for i in m.series():
    250          #   print i
    251          assert t.name == 'First', 'name wrong'
    252          assert t.total() == 90, 'total wrong:%s'%m.total()
    253          assert t.mean() == 9.0, 'mean wrong:%s'%m.mean()
    254          assert t.var() == (4 * 285.-(90 * 90 / 10.0)) / 10.0, 'sample var wrong: %s' % (t.var(),)
    255
    256 -    def testObserveNoTime(self):
    257          """Test Tally - observe with time being picked up from now()"""
    258          s=Simulation()
    259          s.initialize()
    260          ta = Tally(name = 'No time',sim=s)
    261          t = Thing(ta,sim=s)
    262          s.activate(t, t.execute(),0.0)
    263          s.simulate(until = 20.0)
    264          assert ta.total() == 15, 'total wrong:%s'%ta.total()
    265          assert ta.timeAverage(10.0) == 5.0, 'time average is wrong: %s'%ta.timeAverage(10.0)
    266
    267 -    def testtimeAverage(self):
    268         """ test time averages """
    269         ta = self.T
    270         assert ta.timeAverage(10.0) == 9.0, 'time average is wrong: %s'%ta.timeAverage(10.0)
    271
    272 -    def testtimeVariance(self):
    273         """ test time - weighted Variance for Tally """
    274         ta = self.T
    275         assert abs(ta.timeVariance(10.0) - 33) < 0.00001, 'time - weighted variance is wrong: %s'%ta.timeVariance(10.0)
    276         t2 = self.T2
    277         assert abs(t2.timeVariance(5) - 6.0 / 25) < 0.0001, 'time - weighted variance is wrong: %s'%t2.timeVariance(5)
    278
    279
    280 -    def testreset(self):
    281         """ test time averages """
    282         ta = self.T
    283         ta.reset(t = 10.0)
    284         assert ta.startTime == 10.0, 'reset time  wrong'
    285
    286 -    def testhistogram(self):
    287         """Test some Monitor list operations"""
    288         ta = Monitor(name = 'First')
    289         for y in [-5, 0, 5, 15, 99, 105, 120]:ta.observe(y)
    290         ta.setHistogram(low = 0.0, high = 100.0, nbins = 10)
    291         h = ta.histogram()
    292         shouldBe = list(zip(*h)[1])
    293         assert shouldBe == [1, 2,1, 0,0, 0,0, 0,0, 0,1, 2], 'm histogram is wrong: %s' % (shouldBe,)
    294
    295 -def makeTSuite():
    296      suite = unittest.TestSuite()
    297      testObserve = makeTtestCase('testObserve')
    298      testObserveNoTime = makeTtestCase('testObserveNoTime')
    299      testtimeAverage = makeTtestCase('testtimeAverage')
    300      testtimeVariance = makeTtestCase('testtimeVariance')
    301      testreset = makeTtestCase('testreset')
    302      testhistogram = makeTtestCase('testhistogram')
    303      suite.addTests([testObserve, testObserveNoTime,
    304                      testtimeAverage,
    305                      testtimeVariance,
    306                      testreset,
    307                      testhistogram,
    308                      ])
    309      return suite
    310
    311  ## -----------------------------------------------------------------------
    312  ## Test cases to test equivalence of Monitor and Tally
    313  ## for monitored Resource instances
    314  ## -----------------------------------------------------------------------
    315
    316 -class Actor(Process):
    317      """Process used in MakeEquivTestCase"""
    318 -    def __init__(self,sim=None):
    319          Process.__init__(self,sim=sim)
    320 -    def act(self, res):
    321          while True:
    322              yield request, self, res
    323              yield hold, self, 1
    324              yield release, self, res
    325
    326 -class makeEquivTestCase(unittest.TestCase):
    327      """To test that the histograms produced in monitoring
    328      a Resource instance's queues are equivalent
    329      """
    330 -    def testResHistogram(self):
    331          s=Simulation()
    332          s.initialize()
    333          r = Resource(monitored = True, monitorType = Monitor,
    334                       name = 'TheResource / Monitor',sim=s)
    335          r.waitMon.setHistogram(high = 3, nbins = 3)
    336          r.actMon.setHistogram(high = 3, nbins = 3)
    337
    338          for i in range (5):
    339            a = Actor(sim=s)
    340            s.activate(a, a.act(r))
    341          s.simulate(until = 20)
    342          mHistoAct = r.actMon.getHistogram()
    343          mHistoWait = r.waitMon.getHistogram()
    344
    345          s=Simulation()
    346          s.initialize()
    347          r = Resource(monitored = True, monitorType = Tally,
    348                       name = 'TheResource / Tally',sim=s)
    349          r.waitMon.setHistogram(high = 3, nbins = 3)
    350          r.actMon.setHistogram(high = 3, nbins = 3)
    351          for i in range (5):
    352            a = Actor(sim=s)
    353            s.activate(a, a.act(r))
    354          s.simulate(until = 20)
    355          tHistoAct = r.actMon.getHistogram()
    356          tHistoWait = r.waitMon.getHistogram()
    357
    358          assert mHistoAct == tHistoAct, 'actMon histograms are different'
    359          assert mHistoWait == tHistoWait, 'waitMon histograms are different'
    360
    361 -def makeEquivSuite():
    362      suite = unittest.TestSuite()
    363      testResHistogram = makeEquivTestCase('testResHistogram')
    364      suite.addTests([testResHistogram
    365                      ])
    366      return suite
    367
    368  ## -----------------------------------------------------------------------
    369
    370  if __name__ == '__main__':
    371      print 'MonitorTest.py %s'%__version__
    372      alltests = unittest.TestSuite((makeMSuite(),
    373  ##                                   makeHSuite(),
    374                                     makeTSuite(),
    375                                     makeEquivSuite()
    376                                     ))
    377      runner = unittest.TextTestRunner()
    378      runner.run(alltests)
    379