Commit 53b044d4 authored by Georgios Dagkakis's avatar Georgios Dagkakis Committed by Sebastien Robin

simulation objects added

parent 5fe492cb
This diff is collapsed.
'''
Created on 6 Feb 2013
@author: George
'''
'''
models the exit of the model
'''
from SimPy.Simulation import *
import xlwt
import scipy.stats as stat
#The exit object
class Exit(Process):
def __init__(self, id, name):
Process.__init__(self)
self.predecessorIndex=0 #holds the index of the predecessor from which the Exit will take an entity next
self.id=id
self.objName=name
self.type="Exit"
self.previous=[] #list with the previous objects in the flow
self.nextIds=[] #list with the ids of the next objects in the flow. For the exit it is always empty!
self.previousIds=[] #list with the ids of the previous objects in the flow
#lists to hold statistics of multiple runs
self.Exits=[]
self.Lifespan=[]
def initialize(self):
Process.__init__(self)
self.Res=Resource(capacity=infinity)
self.numOfExits=0
self.totalLifespan=0
def Run(self):
while 1:
yield waituntil, self, self.canAcceptAndIsRequested #wait until the Queue can accept an entity
#and one predecessor requests it
self.getEntity()
self.numOfExits+=1 #increase the exits by one
#sets the routing in element for the Exit
def defineRouting(self, p):
self.previous=p
#checks if the Exit can accept an entity
def canAccept(self):
return True #the exit always can accept an entity
#checks if the Exit can accept an entity and there is an entity waiting for it
def canAcceptAndIsRequested(self):
if(len(self.previous)==1):
return self.previous[0].haveToDispose()
isRequested=False
for i in range(len(self.previous)):
if(self.previous[i].haveToDispose()):
isRequested=True
self.predecessorIndex=i
return isRequested
#gets an entity from the predecessor
def getEntity(self):
'''
#A=self.previous[0].Res.activeQ[0]
name=self.previous[0].Res.activeQ[0].name #get the name of the entity for the trace
self.totalLifespan+=now()-self.previous[0].Res.activeQ[0].startTime #Add the entity's lifespan to the total one.
self.previous[0].removeEntity() #remove the entity from the previous object
#del A
'''
name=self.previous[self.predecessorIndex].Res.activeQ[0].name #get the name of the entity for the trace
self.totalLifespan+=now()-self.previous[self.predecessorIndex].Res.activeQ[0].startTime #Add the entity's lifespan to the total one.
self.previous[self.predecessorIndex].removeEntity() #remove the entity from the previous object
self.outputTrace(name)
#actions to be taken after the simulation ends
def postProcessing(self, MaxSimtime):
from Globals import G
self.Exits.append(self.numOfExits)
try:
self.Lifespan.append(((self.totalLifespan)/self.numOfExits)/G.Base)
except ZeroDivisionError:
self.Lifespan.append(0)
#outputs message to the trace.xls. Format is (Simulation Time | Entity Name | "generated")
def outputTrace(self, message):
from Globals import G
if(G.trace=="Yes"): #output only if the user has selected to
#handle the 3 columns
G.traceSheet.write(G.traceIndex,0,str(now()))
G.traceSheet.write(G.traceIndex,1,message)
G.traceSheet.write(G.traceIndex,2,"exited the system")
G.traceIndex+=1 #increment the row
#if we reach row 65536 we need to create a new sheet (excel limitation)
if(G.traceIndex==65536):
G.traceIndex=0
G.sheetIndex+=1
G.traceSheet=G.traceFile.add_sheet('sheet '+str(G.sheetIndex), cell_overwrite_ok=True)
#outputs data to "output.xls"
def outputResultsXL(self, MaxSimtime):
from Globals import G
if(G.numberOfReplications==1): #if we had just one replication output the results to excel
G.outputSheet.write(G.outputIndex,0, "The Throughput is:")
G.outputSheet.write(G.outputIndex,1,self.numOfExits)
G.outputIndex+=1
G.outputSheet.write(G.outputIndex,0, "The average lifespan of an entity is:")
G.outputSheet.write(G.outputIndex,1,((self.totalLifespan)/self.numOfExits)/G.Base)
G.outputIndex+=1
else: #if we had multiple replications we output confidence intervals to excel
#for some outputs the results may be the same for each run (eg model is stochastic but failures fixed
#so failurePortion will be exactly the same in each run). That will give 0 variability and errors.
#so for each output value we check if there was difference in the runs' results
#if yes we output the Confidence Intervals. if not we output just the fix value
G.outputSheet.write(G.outputIndex,0, "CI "+str(G.confidenceLevel*100)+"% for the mean Throughput is:")
if self.checkIfArrayHasDifValues(self.Exits):
G.outputSheet.write(G.outputIndex,1,stat.bayes_mvs(self.Exits, G.confidenceLevel)[0][1][0])
G.outputSheet.write(G.outputIndex,2,stat.bayes_mvs(self.Exits, G.confidenceLevel)[0][0])
G.outputSheet.write(G.outputIndex,3,stat.bayes_mvs(self.Exits, G.confidenceLevel)[0][1][1])
else:
G.outputSheet.write(G.outputIndex,1,self.Exits[0])
G.outputSheet.write(G.outputIndex,2,self.Exits[0])
G.outputSheet.write(G.outputIndex,3,self.Exits[0])
G.outputIndex+=1
G.outputSheet.write(G.outputIndex,0, "CI "+str(G.confidenceLevel*100)+"% for the mean Lifespan of an entity is:")
if self.checkIfArrayHasDifValues(self.Lifespan):
G.outputSheet.write(G.outputIndex,1,stat.bayes_mvs(self.Lifespan, G.confidenceLevel)[0][1][0])
G.outputSheet.write(G.outputIndex,2,stat.bayes_mvs(self.Lifespan, G.confidenceLevel)[0][0])
G.outputSheet.write(G.outputIndex,3,stat.bayes_mvs(self.Lifespan, G.confidenceLevel)[0][1][1])
else:
G.outputSheet.write(G.outputIndex,1,self.Lifespan[0])
G.outputSheet.write(G.outputIndex,2,self.Lifespan[0])
G.outputSheet.write(G.outputIndex,3,self.Lifespan[0])
G.outputIndex+=1
G.outputIndex+=1
#takes the array and checks if all its values are identical (returns false) or not (returns true)
#needed because if somebody runs multiple runs in deterministic case it would crash!
def checkIfArrayHasDifValues(self, array):
difValuesFlag=False
for i in range(1, len(array)):
if(array[i]!=array[1]):
difValuesFlag=True
return difValuesFlag
\ No newline at end of file
'''
Created on 9 Nov 2012
@author: George
'''
'''
models the failures that servers can have
'''
from SimPy.Simulation import *
import math
from RandomNumberGenerator import RandomNumberGenerator
class Failure(Process):
def __init__(self, victim, dist, MTTF, MTTR, availability, index, repairman):
Process.__init__(self)
self.distType=dist #the distribution that the failure duration follows
self.MTTF=MTTF #the MTTF
self.MTTR=MTTR #the MTTR
self.availability=availability #the availability
self.victim=victim #the victim of the failure (work center)
self.name="F"+str(index)
self.repairman=repairman #the resource that may be needed to fix the failure
#if now resource is needed this will be "None"
self.type="Failure"
self.id=0
if(self.distType=="Availability"):
#the following are used if we have availability defined (as in plant)
#the erlang is a special case of Gamma.
#To model the Mu and sigma that is given in plant as alpha and beta for gamma you should do the following:
#beta=(sigma^2)/Mu
#alpha=Mu/beta
self.AvailabilityMTTF=MTTR*(float(availability)/100)/(1-(float(availability)/100))
self.sigma=0.707106781185547*MTTR
self.theta=(pow(self.sigma,2))/float(MTTR)
self.beta=self.theta
self.alpha=(float(MTTR)/self.theta)
self.rngTTF=RandomNumberGenerator(self, "Exp")
self.rngTTF.avg=self.AvailabilityMTTF
self.rngTTR=RandomNumberGenerator(self, "Erlang")
self.rngTTR.alpha=self.alpha
self.rngTTR.beta=self.beta
else: #if the distribution is fixed
self.rngTTF=RandomNumberGenerator(self, self.distType)
self.rngTTF.avg=MTTF
self.rngTTR=RandomNumberGenerator(self, self.distType)
self.rngTTR.avg=MTTR
def Run(self):
while 1:
#yield hold,self,self.calcTimeToFailure()
yield hold,self,self.rngTTF.generateNumber() #wait until a failure happens
try:
#print self.name
if(len(self.victim.Res.activeQ)>0):
self.interrupt(self.victim) #when a Machine gets failure while in process it is interrupted
self.victim.Up=False
self.victim.timeLastFailure=now()
#print str(now())+":M"+str(self.victim.id)+" is down"
self.outputTrace("is down")
except AttributeError:
print "AttributeError1"
failTime=now()
if(self.repairman!="None"): #if the failure needs a resource to be fixed, the machine waits until the
#resource is available
yield request,self,self.repairman.Res
timeRepairStarted=now()
self.repairman.timeLastRepairStarted=now()
#yield hold,self,self.calcTimeToRepair() #wait until the repairing process is over
yield hold,self,self.rngTTR.generateNumber() #wait until the repairing process is over
self.victim.totalFailureTime+=now()-failTime
try:
if(len(self.victim.Res.activeQ)>0):
reactivate(self.victim) #since repairing is over, the Machine is reactivated
self.victim.Up=True
#print str(now())+":M"+str(self.victim.id)+" is up"
self.outputTrace("is up")
if(self.repairman!="None"): #if a resource was used, it is now released
yield release,self,self.repairman.Res
self.repairman.totalWorkingTime+=now()-timeRepairStarted
#print "reactivating "+str(self.victim.currentEntity)
except AttributeError:
print "AttributeError2"
'''
#calculates the time until the next failure
def calcTimeToFailure(self):
from Globals import G
if self.distType=="Fixed": #in a fixed distribution every TTF should be equal to MTTF
TTF=self.MTTF
elif self.distType=="Availability": #if we have availability defined, TTF should follow the exponential distribution
TTF=G.Rnd.expovariate(float(1)/self.AvailabilityMTTF)
#print self.name+" TTF="+str(TTF)
return TTF
#calculates the time that it is needed for the repair
def calcTimeToRepair(self):
from Globals import G
if self.distType=="Fixed": #in a fixed distribution every TTR should be equal to MTTR
TTR=self.MTTR
elif self.distType=="Availability": #if we have availability defined, TTR should follow the Erlang distribution
TTR=G.Rnd.gammavariate(self.alpha,self.beta)
#print self.name+" TTR="+str(TTR)
return TTR
'''
#outputs message to the trace.xls. Format is (Simulation Time | Machine Name | message)
def outputTrace(self, message):
from Globals import G
if(G.trace=="Yes"): #output only if the user has selected to
#handle the 3 columns
G.traceSheet.write(G.traceIndex,0,str(now()))
G.traceSheet.write(G.traceIndex,1, self.victim.objName)
G.traceSheet.write(G.traceIndex,2,message)
G.traceIndex+=1 #increment the row
#if we reach row 65536 we need to create a new sheet (excel limitation)
if(G.traceIndex==65536):
G.traceIndex=0
G.sheetIndex+=1
G.traceSheet=G.traceFile.add_sheet('sheet '+str(G.sheetIndex), cell_overwrite_ok=True)
#outputs data to "output.xls"
def outputResultsXL(self, MaxSimtime):
pass
\ No newline at end of file
'''
Created on 18 Feb 2013
@author: George
'''
'''
models a frame entity. This can flow through the system and carry parts
'''
from SimPy.Simulation import *
from Globals import G
#The entity object
class Frame(object):
type="Frame"
numOfParts=4 #the number of parts that the frame can take
def __init__(self, name):
self.name=name
self.currentStop=None #contains the current object that the material is in
self.creationTime=0
self.startTime=0 #holds the startTime for the lifespan
self.Res=Resource(self.numOfParts)
'''
Created on 8 Nov 2012
@author: George
'''
'''
carries some global variables
'''
from SimPy.Simulation import *
from Machine import Machine
from Queue import Queue
from Repairman import Repairman
import xlwt
import xlrd
from random import Random, expovariate, gammavariate, normalvariate
# globals
class G:
seed=1450 #the seed of the random number generator
Rnd = Random(seed) #random number generator
ObjList=[] #a list that holds all the simulation objects
numberOfReplications=1 #the number of replications default=1
confidenceLevel=0.9 #the confidence level default=90%
Base=1 #the Base time unit. Default =1 minute
maxSimTime=0 #the total simulation time
#data for the trace output in excel
trace="" #this is written from input. If it is "Yes" then you write to trace, else we do not
traceIndex=0 #index that shows in what row we are
sheetIndex=1 #index that shows in what sheet we are
traceFile = xlwt.Workbook() #create excel file
traceSheet = traceFile.add_sheet('sheet '+str(sheetIndex), cell_overwrite_ok=True) #create excel sheet
#the output excel
outputIndex=0 #index that shows in what row we are
sheetIndex=1 #index that shows in what sheet we are
outputFile = xlwt.Workbook() #create excel file
outputSheet = outputFile.add_sheet('sheet '+str(sheetIndex), cell_overwrite_ok=True) #create excel sheet
This diff is collapsed.
'''
Created on 6 Feb 2013
@author: George
'''
'''
models a part entity that flows through the system
'''
from SimPy.Simulation import *
from Globals import G
#The entity object
class Part(object):
type="Part"
def __init__(self, name):
self.name=name
self.currentStop=None #contains the current object that the material is in
self.creationTime=0
self.startTime=0 #holds the startTime for the lifespan
def __del__(self):
pass
#print self.name, now()
'''
Created on 8 Nov 2012
@author: George
'''
'''
Models a FIFO queue where entities can wait in order to get into a server
'''
from SimPy.Simulation import *
#the Queue object
class Queue(Process):
def __init__(self, id, name, capacity, dummy):
Process.__init__(self)
self.predecessorIndex=0 #holds the index of the predecessor from which the Queue will take an entity next
self.successorIndex=0 #holds the index of the successor where the Queue will dispose an entity next
self.id=id
self.objName=name
self.capacity=capacity
self.nameLastEntityEntered="" #keeps the name of the last entity that entered in the queue
self.timeLastEntityEntered=0 #keeps the time of the last entity that entered in the queue
self.next=[] #list with the next objects in the flow
self.previous=[] #list with the previous objects in the flow
self.nextIds=[] #list with the ids of the next objects in the flow
self.previousIds=[] #list with the ids of the previous objects in the flow
self.type="Queue" #String that shows the type of object
self.isDummy=dummy #Boolean that shows if it is the dummy first Queue
def initialize(self):
Process.__init__(self)
self.Res=Resource(self.capacity)
self.nameLastEntityEntered="" #keeps the name of the last entity that entered in the queue
self.timeLastEntityEntered=0 #keeps the time of the last entity that entered in the queue
def Run(self):
while 1:
yield waituntil, self, self.canAcceptAndIsRequested #wait until the Queue can accept an entity
#and one predecessor requests it
self.getEntity()
#if entity just got to the dummyQ set its startTime as the current time
if self.isDummy:
self.Res.activeQ[0].startTime=now()
#sets the routing in and out elements for the queue
def defineRouting(self, p, n):
self.next=n
self.previous=p
#checks if the Q has one available place
def checkIfQHasPlace(self):
return len(self.Q.activeQ)<self.capacity
#checks if the Queue can accept an entity
#it checks also who called it and returns TRUE only to the predecessor that will give the entity.
#this is kind of slow I think got to check
def canAccept(self):
if(len(self.previous)==1):
return len(self.Res.activeQ)<self.capacity
if len(self.Res.activeQ)==self.capacity:
return False
#identify the caller method
frame = sys._getframe(1)
arguments = frame.f_code.co_argcount
if arguments == 0:
print "Not called from a method"
return
caller_calls_self = frame.f_code.co_varnames[0]
thecaller = frame.f_locals[caller_calls_self]
#return true only to the predecessor from which the queue will take
flag=False
if thecaller is self.previous[self.predecessorIndex]:
flag=True
return len(self.Res.activeQ)<self.capacity and flag
#checks if the Queue can dispose an entity to the following object
#it checks also who called it and returns TRUE only to the successor that will give the entity.
#this is kind of slow I think got to check
def haveToDispose(self):
if(len(self.next)==1):
return len(self.Res.activeQ)>0
#if the Queue is empty it returns false right away
if(len(self.Res.activeQ)==0):
return False
#identify the caller method
frame = sys._getframe(1)
arguments = frame.f_code.co_argcount
if arguments == 0:
print "Not called from a method"
return
caller_calls_self = frame.f_code.co_varnames[0]
thecaller = frame.f_locals[caller_calls_self]
#give the entity to the successor that is waiting for the most time.
#plant does not do this in every occasion!
maxTimeWaiting=0
for i in range(len(self.next)):
if(self.next[i].canAccept()):
timeWaiting=now()-self.next[i].timeLastEntityLeft
if(timeWaiting>maxTimeWaiting or maxTimeWaiting==0):
maxTimeWaiting=timeWaiting
self.successorIndex=i
#return true only to the predecessor from which the queue will take
flag=False
if thecaller is self.next[self.successorIndex]:
flag=True
return len(self.Res.activeQ)>0 and flag
#checks if the Queue can accept an entity and there is an entity in some predecessor waiting for it
#also updates the predecessorIndex to the one that is to be taken
def canAcceptAndIsRequested(self):
if(len(self.previous)==1):
return len(self.Res.activeQ)<self.capacity and self.previous[0].haveToDispose()
isRequested=False
maxTimeWaiting=0
for i in range(len(self.previous)):
if(self.previous[i].haveToDispose()):
isRequested=True
#timeWaiting=now()-(self.previous[i].timeLastEntityEnded+self.previous[i].downTimeInTryingToReleaseCurrentEntity)
if(self.previous[i].downTimeInTryingToReleaseCurrentEntity>0):
timeWaiting=now()-self.previous[i].timeLastFailureEnded
else:
timeWaiting=now()-self.previous[i].timeLastEntityEnded
#if more than one predecessor have to dispose take the part from the one that is blocked longer
if(timeWaiting>=maxTimeWaiting): #or maxTimeWaiting==0):
self.predecessorIndex=i
maxTimeWaiting=timeWaiting
return len(self.Res.activeQ)<self.capacity and isRequested
#gets an entity from the predecessor that the predecessor index points to
def getEntity(self):
self.Res.activeQ=[self.previous[self.predecessorIndex].Res.activeQ[0]]+self.Res.activeQ #get the entity from the previous object
#and put it in front of the activeQ
self.previous[self.predecessorIndex].removeEntity() #remove the entity from the previous object
#removes an entity from the Queue (this is FIFO for now)
def removeEntity(self):
self.Res.activeQ.pop(0)
#actions to be taken after the simulation ends
def postProcessing(self, MaxSimtime):
pass #no actions for the Queue
#outputs message to the trace.xls. Format is (Simulation Time | Entity Name | message)
def outputTrace(self, message):
from Globals import G
if(G.trace=="Yes"): #output only if the user has selected to
#handle the 3 columns
G.traceSheet.write(G.traceIndex,0,str(now()))
G.traceSheet.write(G.traceIndex,1,self.Res.activeQ[0].name)
G.traceSheet.write(G.traceIndex,2,message)
G.traceIndex+=1 #increment the row
#if we reach row 65536 we need to create a new sheet (excel limitation)
if(G.traceIndex==65536):
G.traceIndex=0
G.sheetIndex+=1
G.traceSheet=G.traceFile.add_sheet('sheet '+str(G.sheetIndex), cell_overwrite_ok=True)
#outputs data to "output.xls"
def outputResultsXL(self, MaxSimtime):
pass
\ No newline at end of file
'''
Created on 15 Feb 2013
@author: George
'''
'''
Models a LIFO queue where entities can wait in order to get into a server
'''
from Queue import Queue
class QueueLIFO(Queue):
#gets an entity from the predecessor
def getEntity(self):
self.Res.activeQ=[self.previous[0].Res.activeQ[0]]+self.Res.activeQ #get the entity from the previous object
#and put it in front of the activeQ
self.previous[0].removeEntity() #remove the entity from the previous object
\ No newline at end of file
'''
Created on 14 Feb 2013
@author: George
'''
'''
holds methods for generations of numbers from different distributions
'''
class RandomNumberGenerator(object):
def __init__(self, obj, type):
self.distType=type
self.avg=0
self.stdev=0
self.min=0
self.max=0
#self.availability=0
self.alpha=0
self.beta=0
self.object=obj
def generateNumber(self):
from Globals import G
number=0
if(self.distType=="Fixed"): #if the distribution is Fixed
number=self.avg
elif(self.distType=="Exp"): #if the distribution is Exponential
number=G.Rnd.expovariate(1.0/(self.avg))
elif(self.distType=="Normal"): #if the distribution is Normal
while 1:
number=G.Rnd.normalvariate(self.avg, self.stdev)
if number>self.max or number<self.min and max!=0: #if the number is out of bounds repeat the process #if max=0 this means that we did not have time "time" bounds
continue
else: #if the number is in the limits stop the process
break
elif self.distType=="Erlang": #if the distribution is erlang
number=G.Rnd.gammavariate(self.alpha,self.beta)
else:
print "unknown distribution error in "+str(self.object.type)+str(self.object.id)
return number
\ No newline at end of file
'''
Created on 14 Nov 2012
@author: George
'''
'''
models a repairman that can fix a machine when it gets failures
'''
from SimPy.Simulation import *
import xlwt
import scipy.stats as stat
#the resource that repairs the machines
class Repairman(object):
def __init__(self, id, name, capacity):
self.id=id
self.objName=name
self.capacity=capacity #repairman is an instance of resource
self.type="Repairman"
#lists to hold statistics of multiple runs
self.Waiting=[]
self.Working=[]
def initialize(self):
self.totalWorkingTime=0 #holds the total working time
self.totalWaitingTime=0 #holds the total waiting time
self.timeLastRepairStarted=0 #holds the time that the last repair was started
self.Res=Resource(self.capacity)
#checks if the worker is available
def checkIfWorkerIsAvailable(self):
return len(self.W.activeQ)<self.capacity
#actions to be taken after the simulation ends
def postProcessing(self, MaxSimtime):
#if the repairman is currently working we have to count the time of this work
if len(self.Res.activeQ)>0:
self.totalWorkingTime+=now()-self.timeLastRepairStarted
#Repairman was idle when he was not in any other state
self.totalWaitingTime=MaxSimtime-self.totalWorkingTime
self.Waiting.append(100*self.totalWaitingTime/MaxSimtime)
self.Working.append(100*self.totalWorkingTime/MaxSimtime)
#outputs data to "output.xls"
def outputResultsXL(self, MaxSimtime):
from Globals import G
if(G.numberOfReplications==1): #if we had just one replication output the results to excel
G.outputSheet.write(G.outputIndex,0, "The percentage of working of "+self.objName +" is:")
G.outputSheet.write(G.outputIndex,1,100*self.totalWorkingTime/MaxSimtime)
G.outputIndex+=1
G.outputSheet.write(G.outputIndex,0, "The percentage of waiting of "+self.objName +" is:")
G.outputSheet.write(G.outputIndex,1,100*self.totalWaitingTime/MaxSimtime)
G.outputIndex+=1
else: #if we had multiple replications we output confidence intervals to excel
#for some outputs the results may be the same for each run (eg model is stochastic but failures fixed
#so failurePortion will be exactly the same in each run). That will give 0 variability and errors.
#so for each output value we check if there was difference in the runs' results
#if yes we output the Confidence Intervals. if not we output just the fix value
G.outputSheet.write(G.outputIndex,0, "CI "+str(G.confidenceLevel*100)+"% for the mean percentage of Working of "+self.objName +" is:")
if self.checkIfArrayHasDifValues(self.Working):
G.outputSheet.write(G.outputIndex,1,stat.bayes_mvs(self.Working, G.confidenceLevel)[0][1][0])
G.outputSheet.write(G.outputIndex,2,stat.bayes_mvs(self.Working, G.confidenceLevel)[0][0])
G.outputSheet.write(G.outputIndex,3,stat.bayes_mvs(self.Working, G.confidenceLevel)[0][1][1])
else:
G.outputSheet.write(G.outputIndex,1,self.Working[0])
G.outputSheet.write(G.outputIndex,2,self.Working[0])
G.outputSheet.write(G.outputIndex,3,self.Working[0])
G.outputIndex+=1
G.outputSheet.write(G.outputIndex,0, "CI "+str(G.confidenceLevel*100)+"% for the mean percentage of Waiting of "+self.objName +" is:")
if self.checkIfArrayHasDifValues(self.Waiting):
G.outputSheet.write(G.outputIndex,1,stat.bayes_mvs(self.Waiting, G.confidenceLevel)[0][1][0])
G.outputSheet.write(G.outputIndex,2,stat.bayes_mvs(self.Waiting, G.confidenceLevel)[0][0])
G.outputSheet.write(G.outputIndex,3,stat.bayes_mvs(self.Waiting, G.confidenceLevel)[0][1][1])
else:
G.outputSheet.write(G.outputIndex,1,self.Waiting[0])
G.outputSheet.write(G.outputIndex,2,self.Waiting[0])
G.outputSheet.write(G.outputIndex,3,self.Waiting[0])
G.outputIndex+=1
G.outputIndex+=1
#takes the array and checks if all its values are identical (returns false) or not (returns true)
#needed because if somebody runs multiple runs in deterministic case it would crash!
def checkIfArrayHasDifValues(self, array):
difValuesFlag=False
for i in range(1, len(array)):
if(array[i]!=array[1]):
difValuesFlag=True
return difValuesFlag
\ No newline at end of file
'''
Created on 8 Nov 2012
@author: George
'''
'''
models the source object that generates the entities
'''
from SimPy.Simulation import *
from Part import Part
from RandomNumberGenerator import RandomNumberGenerator
#The Source object is a Process
class Source(Process):
def __init__(self, id, name, dist, time, item):
Process.__init__(self)
self.id=id
self.objName=name
self.distType=dist #label that sets the distribution type
self.interArrivalTime=time #the mean interarrival time
self.totalInterArrivalTime=0 #the total interarrival time
self.numberOfArrivals=0 #the number of entities that were created
self.next=[] #list with the next objects in the flow
self.nextIds=[] #list with the ids of the next objects in the flow
self.previousIds=[] #list with the ids of the previous objects in the flow. For the source it is always empty!
self.type="Source" #String that shows the type of object
#self.waitToDispose=False
self.rng=RandomNumberGenerator(self, self.distType)
self.rng.avg=time
self.item=item #the type of object that the Source will generate
#self.Res=Resource(capacity=infinity)
def initialize(self):
Process.__init__(self)
self.Res=Resource(capacity=infinity)
self.Res.activeQ=[]
self.Res.waitQ=[]
def Run(self):
i=0
if(self.distType=="Fixed"): #if the distribution type is fixed
from Globals import G
while 1:
#self.waitToDispose=True
self.numberOfArrivals+=1 #we have one new arrival
#entity=Entity("Ent"+str(i))
entity=self.item(self.item.type+"_"+self.objName+"_"+str(i)) #create the Entity object and assign its name
entity.creationTime=now() #assign the current simulation time as the Entity's creation time
self.outputTrace(self.item.type+"_"+self.objName+"_"+str(i)) #output the trace
self.Res.activeQ.append(entity) #append the entity to the resource
i+=1
#yield hold,self,self.interArrivalTime #one entity at every interArrivalTime
yield hold,self,self.rng.generateNumber()
elif(self.distType=="Exp"): #if the distribution type is exponential
from Globals import G
while 1:
#self.waitToDispose=True
self.numberOfArrivals+=1 #we have one new arrival
#entity=Entity("Ent"+str(i)) #create the Entity object and assign its name
entity=self.item(self.item.type+str(i)) #create the Entity object and assign its name
entity.creationTime=now() #assign the current simulation time as the Entity's creation time
self.outputTrace(self.item.type+str(i)) #output the trace
i+=1
self.Res.activeQ.append(entity) #append the entity to the resource
timeTillNextArrival=G.Rnd.expovariate(1.0/(self.interArrivalTime)) #create a random number that follows the
#exponential distribution
#yield hold,self,timeTillNextArrival #one entity at every interArrivalTime
yield hold,self,self.rng.generateNumber()
self.totalInterArrivalTime+=timeTillNextArrival
else: #if the distribution type is something else it is an error
print "Distribution Error in Source "+str(self.id)
#sets the routing out element for the Source
def defineRouting(self, n):
self.next=n
#actions to be taken after the simulation ends
def postProcessing(self, MaxSimtime):
pass #no actions for the Source
#checks if the Source can dispose an entity to the following object
def haveToDispose(self):
#return self.waitToDispose
return len(self.Res.activeQ)>0
#removes an entity from the Source
def removeEntity(self):
self.Res.activeQ.pop(0)
#if(len(self.Res.activeQ)==0):
#self.waitToDispose=False
#outputs message to the trace.xls. Format is (Simulation Time | Entity Name | "generated")
def outputTrace(self, message):
from Globals import G
if(G.trace=="Yes"): #output only if the user has selected to
#handle the 3 columns
G.traceSheet.write(G.traceIndex,0,str(now()))
G.traceSheet.write(G.traceIndex,1,message)
G.traceSheet.write(G.traceIndex,2,"generated")
G.traceIndex+=1 #increment the row
#if we reach row 65536 we need to create a new sheet (excel limitation)
if(G.traceIndex==65536):
G.traceIndex=0
G.sheetIndex+=1
G.traceSheet=G.traceFile.add_sheet('sheet '+str(G.sheetIndex), cell_overwrite_ok=True)
#outputs data to "output.xls"
def outputResultsXL(self, MaxSimtime):
pass
'''
Created on 8 Nov 2012
@author: George
'''
'''
script for making the project into a standalone .exe file
this fails since I used sciPy
'''
from distutils.core import setup
import py2exe
setup(
options = {
"py2exe":{
#"dll_excludes": [ "HID.DLL", "libmmd.dll","w9xpopen.exe"],
#"MSVCP90.dll","libifcoremd.dll",
}
},
console=['Line01.py'])
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment