Commit d9d19ad4 authored by Georgios Dagkakis's avatar Georgios Dagkakis

LineGenerationJSON to use the ManPyEnvironment

parent 44488617
...@@ -56,26 +56,24 @@ import cProfile ...@@ -56,26 +56,24 @@ import cProfile
# =========================================================================== # ===========================================================================
# reads general simulation inputs # reads general simulation inputs
# =========================================================================== # ===========================================================================
def readGeneralInput(): def readGeneralInput(environment,JSONData):
general=G.JSONData['general'] # read the dict with key 'general' general=JSONData['general'] # read the dict with key 'general'
G.numberOfReplications=int(general.get('numberOfReplications', '1')) # read the number of replications / default 1 environment.numberOfReplications=int(general.get('numberOfReplications', '1')) # read the number of replications / default 1
G.maxSimTime=float(general.get('maxSimTime', '100')) # get the maxSimTime / default 100 environment.maxSimTime=float(general.get('maxSimTime', '100')) # get the maxSimTime / default 100
G.trace=general.get('trace', 'No') # get trace in order to check if trace is requested environment.trace=general.get('trace', 'No') # get trace in order to check if trace is requested
G.console=general.get('console', 'No') # get console flag in order to check if console print is requested environment.console=general.get('console', 'No') # get console flag in order to check if console print is requested
G.confidenceLevel=float(general.get('confidenceLevel', '0.95')) # get the confidence level environment.confidenceLevel=float(general.get('confidenceLevel', '0.95')) # get the confidence level
G.seed = general.get('seed') # the seed for random number generation environment.seed = general.get('seed') # the seed for random number generation
G.extraPropertyDict=general.get('extraPropertyDict', {}) # a dict to put extra properties that are environment.extraPropertyDict=general.get('extraPropertyDict', {}) # a dict to put extra properties that are
# generic for the model # generic for the model
# =========================================================================== # ===========================================================================
# creates first the object interruptions # creates first the object interruptions
# and then the core objects # and then the core objects
# =========================================================================== # ===========================================================================
def createObjectResourcesAndCoreObjects(): def createObjectResourcesAndCoreObjects(environment,json_data):
json_data = G.JSONData
#Read the json data #Read the json data
# nodes = json_data['nodes'] # read from the dictionary the dicts with key 'nodes'
nodes = json_data['graph']["node"] # read from the dictionary the dicts with key 'nodes' nodes = json_data['graph']["node"] # read from the dictionary the dicts with key 'nodes'
edges = json_data['graph']["edge"] # read from the dictionary the dicts with key 'edges' edges = json_data['graph']["edge"] # read from the dictionary the dicts with key 'edges'
...@@ -103,41 +101,41 @@ def createObjectResourcesAndCoreObjects(): ...@@ -103,41 +101,41 @@ def createObjectResourcesAndCoreObjects():
''' '''
define the lists of each object type define the lists of each object type
''' '''
G.SourceList=[] environment.SourceList=[]
G.MachineList=[] environment.MachineList=[]
G.ExitList=[] environment.ExitList=[]
G.QueueList=[] environment.QueueList=[]
G.RepairmanList=[] environment.RepairmanList=[]
G.AssemblyList=[] environment.AssemblyList=[]
G.DismantleList=[] environment.DismantleList=[]
G.ConveyerList=[] environment.ConveyerList=[]
G.MachineJobShopList=[] environment.MachineJobShopList=[]
G.QueueJobShopList=[] environment.QueueJobShopList=[]
G.ExitJobShopList=[] environment.ExitJobShopList=[]
G.BatchDecompositionList=[] environment.BatchDecompositionList=[]
G.BatchSourceList=[] environment.BatchSourceList=[]
G.BatchReassemblyList=[] environment.BatchReassemblyList=[]
G.RoutingQueueList=[] environment.RoutingQueueList=[]
G.LineClearanceList=[] environment.LineClearanceList=[]
G.EventGeneratorList=[] environment.EventGeneratorList=[]
G.OperatorsList = [] environment.OperatorsList = []
G.OperatorManagedJobsList = [] environment.OperatorManagedJobsList = []
G.OperatorPoolsList = [] environment.OperatorPoolsList = []
G.BrokersList = [] environment.BrokersList = []
G.OperatedMachineList = [] environment.OperatedMachineList = []
G.BatchScrapMachineList=[] environment.BatchScrapMachineList=[]
G.OrderDecompositionList=[] environment.OrderDecompositionList=[]
G.ConditionalBufferList=[] environment.ConditionalBufferList=[]
G.MouldAssemblyBufferList=[] environment.MouldAssemblyBufferList=[]
G.MouldAssemblyList=[] environment.MouldAssemblyList=[]
G.MachineManagedJobList=[] environment.MachineManagedJobList=[]
G.QueueManagedJobList=[] environment.QueueManagedJobList=[]
G.ObjectResourceList=[] environment.ObjectResourceList=[]
G.CapacityStationBufferList=[] environment.CapacityStationBufferList=[]
G.AllocationManagementList=[] environment.AllocationManagementList=[]
G.CapacityStationList=[] environment.CapacityStationList=[]
G.CapacityStationExitList=[] environment.CapacityStationExitList=[]
G.CapacityStationControllerList=[] environment.CapacityStationControllerList=[]
''' '''
loop through all the model resources loop through all the model resources
...@@ -221,6 +219,7 @@ def createObjectResourcesAndCoreObjects(): ...@@ -221,6 +219,7 @@ def createObjectResourcesAndCoreObjects():
inputDict=dict(element) inputDict=dict(element)
# create the CoreObject # create the CoreObject
coreObject=objectType(**inputDict) coreObject=objectType(**inputDict)
coreObject.env=environment.SimPyEnvironment
# update the nextIDs list of the object # update the nextIDs list of the object
coreObject.nextIds=getSuccessorList(element['id']) coreObject.nextIds=getSuccessorList(element['id'])
# (Below is only for Dismantle for now) # (Below is only for Dismantle for now)
...@@ -231,27 +230,26 @@ def createObjectResourcesAndCoreObjects(): ...@@ -231,27 +230,26 @@ def createObjectResourcesAndCoreObjects():
# loop through all the core objects # loop through all the core objects
# to read predecessors # to read predecessors
for element in G.ObjList: for element in environment.ObjList:
#loop through all the nextIds of the object #loop through all the nextIds of the object
for nextId in element.nextIds: for nextId in element.nextIds:
#loop through all the core objects to find the on that has the id that was read in the successorList #loop through all the core objects to find the on that has the id that was read in the successorList
for possible_successor in G.ObjList: for possible_successor in environment.ObjList:
if possible_successor.id==nextId: if possible_successor.id==nextId:
possible_successor.previousIds.append(element.id) possible_successor.previousIds.append(element.id)
# =========================================================================== # ===========================================================================
# creates the object interruptions # creates the object interruptions
# =========================================================================== # ===========================================================================
def createObjectInterruptions(): def createObjectInterruptions(environment,json_data):
G.ObjectInterruptionList=[] environment.ObjectInterruptionList=[]
G.ScheduledMaintenanceList=[] environment.ScheduledMaintenanceList=[]
G.FailureList=[] environment.FailureList=[]
G.BreakList=[] environment.BreakList=[]
G.ShiftSchedulerList=[] environment.ShiftSchedulerList=[]
G.EventGeneratorList=[] environment.EventGeneratorList=[]
G.CapacityStationControllerList=[] environment.CapacityStationControllerList=[]
G.PeriodicMaintenanceList=[] environment.PeriodicMaintenanceList=[]
json_data = G.JSONData
#Read the json data #Read the json data
nodes = json_data['graph']["node"] # read from the dictionary the dicts with key 'nodes' nodes = json_data['graph']["node"] # read from the dictionary the dicts with key 'nodes'
...@@ -360,24 +358,23 @@ def createObjectInterruptions(): ...@@ -360,24 +358,23 @@ def createObjectInterruptions():
# =========================================================================== # ===========================================================================
# creates the entities that are wip # creates the entities that are wip
# =========================================================================== # ===========================================================================
def createWIP(): def createWIP(environment,json_data):
G.JobList=[] environment.JobList=[]
G.WipList=[] environment.WipList=[]
G.EntityList=[] environment.EntityList=[]
G.PartList=[] environment.PartList=[]
G.OrderComponentList=[] environment.OrderComponentList=[]
G.DesignList=[] # list of the OrderDesigns in the system environment.DesignList=[] # list of the OrderDesigns in the system
G.OrderList=[] environment.OrderList=[]
G.MouldList=[] environment.MouldList=[]
G.BatchList=[] environment.BatchList=[]
G.SubBatchList=[] environment.SubBatchList=[]
G.CapacityEntityList=[] environment.CapacityEntityList=[]
G.CapacityProjectList=[] environment.CapacityProjectList=[]
# entities that just finished processing in a station # entities that just finished processing in a station
# and have to enter the next machine # and have to enter the next machine
G.pendingEntities=[] environment.pendingEntities=[]
#Read the json data
json_data = G.JSONData
# read from the dictionary the dicts with key 'BOM' (if there are any) # read from the dictionary the dicts with key 'BOM' (if there are any)
input=json_data.get('input',{}) input=json_data.get('input',{})
bom=input.get('BOM',None) bom=input.get('BOM',None)
...@@ -552,20 +549,20 @@ def createWIP(): ...@@ -552,20 +549,20 @@ def createWIP():
# =========================================================================== # ===========================================================================
# defines the topology (predecessors and successors for all the objects) # defines the topology (predecessors and successors for all the objects)
# =========================================================================== # ===========================================================================
def setTopology(): def setTopology(environment):
#loop through all the objects #loop through all the objects
for element in G.ObjList: for element in environment.ObjList:
next=[] next=[]
previous=[] previous=[]
for j in range(len(element.previousIds)): for j in range(len(element.previousIds)):
for q in range(len(G.ObjList)): for q in range(len(environment.ObjList)):
if G.ObjList[q].id==element.previousIds[j]: if environment.ObjList[q].id==element.previousIds[j]:
previous.append(G.ObjList[q]) previous.append(environment.ObjList[q])
for j in range(len(element.nextIds)): for j in range(len(element.nextIds)):
for q in range(len(G.ObjList)): for q in range(len(environment.ObjList)):
if G.ObjList[q].id==element.nextIds[j]: if environment.ObjList[q].id==element.nextIds[j]:
next.append(G.ObjList[q]) next.append(environment.ObjList[q])
if element.type=="Source": if element.type=="Source":
element.defineRouting(next) element.defineRouting(next)
...@@ -577,13 +574,13 @@ def setTopology(): ...@@ -577,13 +574,13 @@ def setTopology():
nextPart=[] nextPart=[]
nextFrame=[] nextFrame=[]
for j in range(len(element.nextPartIds)): for j in range(len(element.nextPartIds)):
for q in range(len(G.ObjList)): for q in range(len(environment.ObjList)):
if G.ObjList[q].id==element.nextPartIds[j]: if environment.ObjList[q].id==element.nextPartIds[j]:
nextPart.append(G.ObjList[q]) nextPart.append(environment.ObjList[q])
for j in range(len(element.nextFrameIds)): for j in range(len(element.nextFrameIds)):
for q in range(len(G.ObjList)): for q in range(len(environment.ObjList)):
if G.ObjList[q].id==element.nextFrameIds[j]: if environment.ObjList[q].id==element.nextFrameIds[j]:
nextFrame.append(G.ObjList[q]) nextFrame.append(environment.ObjList[q])
element.defineRouting(previous, next) element.defineRouting(previous, next)
element.definePartFrameRouting(nextPart, nextFrame) element.definePartFrameRouting(nextPart, nextFrame)
else: else:
...@@ -592,18 +589,18 @@ def setTopology(): ...@@ -592,18 +589,18 @@ def setTopology():
# =========================================================================== # ===========================================================================
# initializes all the objects that are in the topology # initializes all the objects that are in the topology
# =========================================================================== # ===========================================================================
def initializeObjects(): def initializeObjects(environment):
for element in G.ObjList + G.ObjectResourceList + G.EntityList + G.ObjectInterruptionList+G.RouterList: for element in environment.ObjList + environment.ObjectResourceList + environment.EntityList + environment.ObjectInterruptionList+environment.RouterList:
element.initialize() element.initialize()
# =========================================================================== # ===========================================================================
# activates all the objects # activates all the objects
# =========================================================================== # ===========================================================================
def activateObjects(): def activateObjects(environment):
for element in G.ObjectInterruptionList: for element in environment.ObjectInterruptionList:
G.env.process(element.run()) environment.env.process(element.run())
for element in G.ObjList: for element in environment.ObjList:
G.env.process(element.run()) environment.env.process(element.run())
# =========================================================================== # ===========================================================================
# the main script that is ran # the main script that is ran
...@@ -611,114 +608,113 @@ def activateObjects(): ...@@ -611,114 +608,113 @@ def activateObjects():
def main(argv=[], input_data=None): def main(argv=[], input_data=None):
argv = argv or sys.argv[1:] argv = argv or sys.argv[1:]
environment=ManPyEnvironment() environment=ManPyEnvironment()
print environment
#create an empty list to store all the objects in #create an empty list to store all the objects in
G.ObjList=[] environment.ObjList=[]
G.RouterList=[] environment.RouterList=[]
if input_data is None: if input_data is None:
# user passes the topology filename as first argument to the program # user passes the topology filename as first argument to the program
filename = argv[0] filename = argv[0]
try: # try to open the file with the inputs try: # try to open the file with the inputs
G.JSONFile=open(filename, "r") # global variable holding the file to be opened JSONFile=open(filename, "r") # global variable holding the file to be opened
except IOError: except IOError:
print "%s could not be open" % filename print "%s could not be open" % filename
return "ERROR" return "ERROR"
G.InputData=G.JSONFile.read() # pass the contents of the input file to the global var InputData InputData=JSONFile.read() # pass the contents of the input file to the global var InputData
else: else:
G.InputData = input_data InputData = input_data
start=time.time() # start counting execution time start=time.time() # start counting execution time
#read the input from the JSON file and create the line #read the input from the JSON file and create the line
G.JSONData=json.loads(G.InputData) # create the dictionary JSONData JSONData=json.loads(InputData) # create the dictionary JSONData
readGeneralInput() readGeneralInput(environment,JSONData)
createObjectResourcesAndCoreObjects() createObjectResourcesAndCoreObjects(environment,JSONData)
createObjectInterruptions() createObjectInterruptions(environment,JSONData)
setTopology() setTopology(environment)
#run the experiment (replications) #run the experiment (replications)
for i in xrange(G.numberOfReplications): for i in xrange(environment.numberOfReplications):
G.env=simpy.Environment() # initialize the environment environment.env=simpy.Environment() # initialize the environment
G.maxSimTime=float(G.JSONData['general'].get('maxSimTime', '100')) # read the maxSimTime in each replication environment.maxSimTime=float(JSONData['general'].get('maxSimTime', '100')) # read the maxSimTime in each replication
# since it may be changed for infinite ones # since it may be changed for infinite ones
if G.RouterList: if environment.RouterList:
G.RouterList[0].isActivated=False environment.RouterList[0].isActivated=False
G.RouterList[0].isInitialized=False environment.RouterList[0].isInitialized=False
if G.seed: if environment.seed:
G.Rnd=Random('%s%s' % (G.seed, i)) environment.Rnd=Random('%s%s' % (G.seed, i))
G.numpyRnd.random.seed(G.seed) environment.numpyRnd.random.seed(G.seed)
else: else:
G.Rnd=Random() environment.Rnd=Random()
G.numpyRnd.random.seed() environment.numpyRnd.random.seed()
createWIP() createWIP(environment,JSONData)
initializeObjects() initializeObjects(environment)
Globals.setWIP(G.EntityList) Globals.setWIP(environment.EntityList)
activateObjects() activateObjects(environment)
# if the simulation is ran until no more events are scheduled, # if the simulation is ran until no more events are scheduled,
# then we have to find the end time as the time the last entity ended. # then we have to find the end time as the time the last entity ended.
if G.maxSimTime==-1: if environment.maxSimTime==-1:
# If someone does it for a model that has always events, then it will run forever! # If someone does it for a model that has always events, then it will run forever!
G.env.run(until=float('inf')) environment.env.run(until=float('inf'))
# identify from the exits what is the time that the last entity has ended. # identify from the exits what is the time that the last entity has ended.
endList=[] endList=[]
for exit in G.ExitList: for exit in environment.ExitList:
endList.append(exit.timeLastEntityLeft) endList.append(exit.timeLastEntityLeft)
# identify the time of the last event # identify the time of the last event
if float(max(endList))!=0 and G.env.now==float('inf'): #do not let G.maxSimTime=0 so that there will be no crash if float(max(endList))!=0 and G.env.now==float('inf'): #do not let G.maxSimTime=0 so that there will be no crash
G.maxSimTime=float(max(endList)) environment.maxSimTime=float(max(endList))
else: else:
print "simulation ran for 0 time, something may have gone wrong" print "simulation ran for 0 time, something may have gone wrong"
logger.info("simulation ran for 0 time, something may have gone wrong") logger.info("simulation ran for 0 time, something may have gone wrong")
#else we simulate until the given maxSimTime #else we simulate until the given maxSimTime
else: else:
G.env.run(until=G.maxSimTime) environment.env.run(until=environment.maxSimTime)
#carry on the post processing operations for every object in the topology #carry on the post processing operations for every object in the topology
for element in G.ObjList+G.ObjectResourceList+G.RouterList: for element in environment.ObjList+environment.ObjectResourceList+environment.RouterList:
element.postProcessing() element.postProcessing()
# added for debugging, print the Route of the Jobs on the same G.traceFile # added for debugging, print the Route of the Jobs on the same G.traceFile
PrintRoute.outputRoute() PrintRoute.outputRoute(environment)
#output trace to excel #output trace to excel
if(G.trace=="Yes"): if(environment.trace=="Yes"):
ExcelHandler.outputTrace('trace'+str(i)) ExcelHandler.outputTrace('trace'+str(i))
import StringIO import StringIO
traceStringIO = StringIO.StringIO() traceStringIO = StringIO.StringIO()
G.traceFile.save(traceStringIO) environment.traceFile.save(traceStringIO)
encodedTrace=traceStringIO.getvalue().encode('base64') encodedTrace=traceStringIO.getvalue().encode('base64')
ExcelHandler.resetTrace() ExcelHandler.resetTrace()
G.outputJSON['_class'] = 'Dream.Simulation'; environment.outputJSON['_class'] = 'Dream.Simulation';
G.outputJSON['general'] ={}; environment.outputJSON['general'] ={};
G.outputJSON['general']['_class'] = 'Dream.Configuration'; environment.outputJSON['general']['_class'] = 'Dream.Configuration';
G.outputJSON['general']['totalExecutionTime'] = (time.time()-start); environment.outputJSON['general']['totalExecutionTime'] = (time.time()-start);
G.outputJSON['elementList'] =[]; environment.outputJSON['elementList'] =[];
#output data to JSON for every object in the topology #output data to JSON for every object in the topology
for object in G.ObjectResourceList + G.EntityList + G.ObjList+G.RouterList: for object in environment.ObjectResourceList + environment.EntityList + environment.ObjList+environment.RouterList:
object.outputResultsJSON() object.outputResultsJSON()
# output the trace as encoded if it is set on # output the trace as encoded if it is set on
if G.trace=="Yes": if environment.trace=="Yes":
# XXX discuss names on this # XXX discuss names on this
jsonTRACE = {'_class': 'Dream.Simulation', jsonTRACE = {'_class': 'Dream.Simulation',
'id': 'TraceFile', 'id': 'TraceFile',
'results': {'trace':encodedTrace} 'results': {'trace':encodedTrace}
} }
G.outputJSON['elementList'].append(jsonTRACE) environment.outputJSON['elementList'].append(jsonTRACE)
outputJSONString=json.dumps(G.outputJSON, indent=True) outputJSONString=json.dumps(environment.outputJSON, indent=True)
if 0: if 0:
G.outputJSONFile=open('outputJSON.json', mode='w') environment.outputJSONFile=open('outputJSON.json', mode='w')
G.outputJSONFile.write(outputJSONString) environment.outputJSONFile.write(outputJSONString)
if not input_data: if not input_data:
# Output on stdout # Output on stdout
print outputJSONString print outputJSONString
...@@ -726,10 +722,10 @@ def main(argv=[], input_data=None): ...@@ -726,10 +722,10 @@ def main(argv=[], input_data=None):
return return
# XXX result_list is not needed here, we could replace result by result_list # XXX result_list is not needed here, we could replace result by result_list
G.JSONData['result'] = {'result_list': [G.outputJSON]} environment.JSONData['result'] = {'result_list': [G.outputJSON]}
#logger.info("execution time="+str(time.time()-start)) #logger.info("execution time="+str(time.time()-start))
return json.dumps(G.JSONData, indent=True) return json.dumps(environment.JSONData, indent=True)
if __name__ == '__main__': if __name__ == '__main__':
......
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