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

# Source Code for Module SimPy.MonitorTest

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