-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimulationRunner.py
317 lines (262 loc) · 12 KB
/
SimulationRunner.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
'''
Contains the functions needed to run a single simulation
'''
import json
from random import *
import multiprocessing
import os
import numpy as np
import logging
import time
import sys
import traceback
import gc
#import tracemalloc
from EconAgent import *
from NetworkClasses import *
from ConnectionNetwork import *
from TradeClasses import *
from SimulationManager import *
import utils
def launchSimulation(simManagerSeed, settingsDict):
try:
simManager = simManagerSeed.spawnManager()
simManager.runSim(settingsDict)
except KeyboardInterrupt:
curr_proc = multiprocessing.current_process()
print("###################### INTERUPT {} ######################".format(curr_proc))
simManager.terminate()
try:
curr_proc.terminate()
except Exception as e:
print("### {} Error when terminating proc {}".format(e, curr_proc))
#print(traceback.format_exc())
def launchAgents(launchDict, allAgentDict, procName, managerId, managementPipe, outputDir="OUTPUT", logLevel="WARNING"):
'''
Instantiate all agents in launchDict, then wait for a kill message from Simulation Manager before exiting
'''
try:
outputDirPath = outputDir
logger = utils.getLogger("{}:{}".format(__name__, procName), console="INFO", outputdir=os.path.join(outputDirPath, "LOGS"), fileLevel=logLevel)
curr_proc = multiprocessing.current_process()
logger.info("{} started".format(procName))
logger.debug("launchAgents() start")
logger.debug("launchDict = {}".format(launchDict))
logger.debug("allAgentDict = {}".format(allAgentDict))
logger.debug("procName = {}".format(procName))
logger.debug("managerId = {}".format(managerId))
logger.debug("managementPipe = {}".format(managementPipe))
try:
#Instantiate agents
logger.info("Instantiating agents")
procAgentDict = {}
for agentId in launchDict:
logger.debug("Instantiating {}".format(launchDict[agentId]))
agentObj = launchDict[agentId].spawnAgent()
procAgentDict[agentId] = agentObj
procAgentList = list(procAgentDict.keys())
#All agents instantiated. Notify manager
managerPacket = NetworkPacket(senderId=procName, destinationId=managerId, msgType=PACKET_TYPE.PROC_READY)
networkPacket = NetworkPacket(senderId=procName, destinationId=managerId, msgType=PACKET_TYPE.CONTROLLER_MSG, payload=managerPacket)
managementPipe.sendPipe.send(networkPacket)
#Memory leak finder
# tracemalloc.start(10)
# warmupSnapshot = None
#Wait for manager to end us
stepCounter = -1
garbageCollectionFrequency = 20
while True:
logger.debug("Monitoring network link")
incommingPacket = managementPipe.recvPipe.recv()
logger.debug("INBOUND {}".format(incommingPacket))
if ((incommingPacket.msgType == PACKET_TYPE.PROC_STOP) or (incommingPacket.msgType == PACKET_TYPE.KILL_ALL_BROADCAST)):
logger.info("Stoppinng process")
networkPacket = NetworkPacket(senderId=procName, msgType=PACKET_TYPE.KILL_PIPE_NETWORK)
logger.debug("OUTBOUND {}".format(networkPacket))
managementPipe.sendPipe.send(networkPacket)
break
elif ((incommingPacket.msgType == PACKET_TYPE.TICK_GRANT) or (incommingPacket.msgType == PACKET_TYPE.TICK_GRANT_BROADCAST)):
#This is the start of a new step.
stepCounter += 1
if (stepCounter%garbageCollectionFrequency == 0):
#Manually call the garbage collector to prevent persistent memory leaks
logger.debug("Running garbage collector")
gc.collect()
# #Memory leak finder
# warmupStep = 50
# snapshotStep = 500
# if (stepCounter == warmupStep):
# gc.collect()
# warmupSnapshot = tracemalloc.take_snapshot()
# logger.debug("Allocation snapshot taken")
# elif (stepCounter == snapshotStep):
# gc.collect()
# #top_stats = tracemalloc.take_snapshot().compare_to(warmupSnapshot, 'lineno')
# top_stats = tracemalloc.take_snapshot().compare_to(warmupSnapshot, 'traceback')
# logger.debug("Allocation snapshot taken")
# allocatingLines = []
# statNumber = 50
# logger.debug("### Top {} new memory allocations\n".format(statNumber))
# statCounter = 0
# for stat in top_stats[:statNumber]:
# allocatingLines.append(str(stat))
# statString = "## {} ##\n{}".format(statCounter, stat)
# for line in stat.traceback.format():
# statString = statString + "\n{}".format(line)
# logger.debug(statString)
# statCounter += 1
except Exception as e:
logger.error("Error while instantiating agents")
logger.error(traceback.format_exc())
#Notify manager of error
managerPacket = NetworkPacket(senderId=procName, destinationId=managerId, msgType=PACKET_TYPE.PROC_ERROR, payload=traceback.format_exc())
networkPacket = NetworkPacket(senderId=procName, destinationId=managerId, msgType=PACKET_TYPE.CONTROLLER_MSG, payload=managerPacket)
managementPipe.sendPipe.send(networkPacket)
return
except KeyboardInterrupt:
curr_proc = multiprocessing.current_process()
print("###################### INTERUPT {} ######################".format(curr_proc))
controllerMsg = NetworkPacket(senderId=procName, msgType=PACKET_TYPE.STOP_TRADING)
networkPacket = NetworkPacket(senderId=procName, msgType=PACKET_TYPE.CONTROLLER_MSG_BROADCAST, payload=controllerMsg)
logger.critical("OUTBOUND {}".format(networkPacket))
managementPipe.sendPipe.send(networkPacket)
time.sleep(1)
networkPacket = NetworkPacket(senderId=procName, msgType=PACKET_TYPE.KILL_ALL_BROADCAST)
logger.critical("OUTBOUND {}".format(networkPacket))
managementPipe.sendPipe.send(networkPacket)
networkPacket = NetworkPacket(senderId=procName, msgType=PACKET_TYPE.KILL_PIPE_NETWORK)
logger.critical("OUTBOUND {}".format(networkPacket))
managementPipe.sendPipe.send(networkPacket)
time.sleep(1)
try:
curr_proc.terminate()
except Exception as e:
print("### {} Error when terminating proc {}".format(e, curr_proc))
#print(traceback.format_exc())
def RunSimulation(settingsDict, logLevel="INFO", outputDir=None):
'''
Run's a single simulation with the specified settings
'''
#Set output directory
outputDirPath = outputDir
if not (outputDirPath):
outputDirPath = os.path.join("OUTPUT", utils.getTimeStamp())
utils.createFolderPath(outputDirPath)
print("Output directory = {}".format(outputDirPath))
logger = utils.getLogger("SimulationRunner:RunSimulation", outputdir=os.path.join(outputDirPath, "LOGS"))
logger.info("settingsDict={}".format(settingsDict))
logger.info("Output directory = {}".format(os.path.abspath(outputDirPath)))
utils.dictToJsonFile({"settings": settingsDict}, os.path.join(outputDirPath, "settings.json"))
childProcesses = []
try:
######################
# Parse All Items
######################
logger.info("Parsing items")
itemDir = "Items"
if ("ItemSettings" in settingsDict):
itemDir = settingsDict["ItemSettings"]
#Congregate items into into a single dict
allItemsDict = utils.loadItemDict(itemDir)
########################################
# Create AgentSeeds for each subprocess
########################################
managerId = "simManager"
if ((not "SimulationSteps" in settingsDict) or (not "TicksPerStep" in settingsDict)):
logger.error("Missing \"SimulationSteps\" and/or \"TicksPerStep\" from settings. Won't run simulation")
logger.debug("SimulationSteps = {}".format(settingsDict["SimulationSteps"]))
print("SimulationSteps = {}".format(settingsDict["SimulationSteps"]))
logger.debug("TicksPerStep = {}".format(settingsDict["TicksPerStep"]))
print("TicksPerStep = {}".format(settingsDict["TicksPerStep"]))
#Setup spawn and process dicts
spawnDict = {}
procDict = {}
allAgentDict = {}
if not ("AgentNumProcesses" in settingsDict):
logger.error("\"AgentNumProcesses\" missing from settings. Won't run simulation")
return None
numProcess = settingsDict["AgentNumProcesses"]
logger.debug("AgentNumProcesses={}".format(numProcess))
print("Agent Processes = {}\n".format(numProcess))
for procNum in range(numProcess):
spawnDict[procNum] = {}
procName = "Simulation_Proc{}".format(procNum)
procDict[procName] = True
#Create agent seeds
procCounter = 0
for agentName in settingsDict["AgentSpawns"]:
for agentType in settingsDict["AgentSpawns"][agentName]:
agentSettings = settingsDict["AgentSpawns"][agentName][agentType]
if not ("quantity" in agentSettings):
logger.error("\"quantity\" missing from \"{}\" settings. Won't run simulation".format(agentType))
return None
numAgents = agentSettings["quantity"]
logger.debug("{}.{} Agents = {}".format(agentName, agentType, numAgents))
print("{}.{} Agents = {}".format(agentName, agentType, numAgents))
for i in range(numAgents):
agentId = "{}.{}.{}".format(agentName, agentType, i)
procNum = procCounter%numProcess
procCounter += 1
spawnSettings = {}
if ("settings" in agentSettings):
spawnSettings = agentSettings["settings"]
agentSeed = AgentSeed(agentId, agentType, ticksPerStep=settingsDict["TicksPerStep"], settings=spawnSettings, simManagerId=managerId, itemDict=allItemsDict, fileLevel=logLevel, outputDir=outputDirPath)
spawnDict[procNum][agentId] = agentSeed
allAgentDict[agentId] = agentSeed.agentInfo
print("\n")
###########################
# Setup Simulation Manager
###########################
checkpointFrequency = None
if ("CheckpointFrequency" in settingsDict):
try:
checkpointFrequency = int(settingsDict["CheckpointFrequency"])
except:
raise ValueError("Invalid CheckpointFrequency \"{}\"\n{}".format(settingsDict["CheckpointFrequency"], traceback.format_exc()))
initialCheckpoint = None
if ("InitialCheckpoint" in settingsDict):
try:
initialCheckpoint = os.path.normpath(settingsDict["InitialCheckpoint"])
except:
raise ValueError("Invalid InitialCheckpoint \"{}\"\n{}".format(settingsDict["InitialCheckpoint"], traceback.format_exc()))
simManagerSeed = SimulationManagerSeed(managerId, allAgentDict, procDict, outputDir=outputDirPath, logLevel=logLevel, checkpointFrequency=checkpointFrequency, initialCheckpoint=initialCheckpoint)
##########################
# Setup ConnectionNetwork
##########################
xactNetwork = ConnectionNetwork(itemDict=allItemsDict, simManagerId=managerId, simulationSettings=settingsDict, outputDir=outputDirPath, logLevel=logLevel)
xactNetwork.addConnection(agentId=managerId, networkLink=simManagerSeed.networkLink)
for procNum in spawnDict:
for agentId in spawnDict[procNum]:
xactNetwork.addConnection(agentId=agentId, networkLink=spawnDict[procNum][agentId].networkLink)
##########################
# Launch subprocesses
##########################
#Launch agent processes
for procNum in spawnDict:
procName = "Simulation_Proc{}".format(procNum)
networkPipeRecv, managementPipeSend = multiprocessing.Pipe()
managementPipeRecv, networkPipeSend = multiprocessing.Pipe()
networkLink = Link(sendPipe=networkPipeSend, recvPipe=networkPipeRecv)
managementLink = Link(sendPipe=managementPipeSend, recvPipe=managementPipeRecv)
xactNetwork.addConnection(agentId=procName, networkLink=networkLink)
proc = multiprocessing.Process(target=launchAgents, args=(spawnDict[procNum], allAgentDict, procName, managerId, managementLink, outputDirPath, logLevel))
childProcesses.append(proc)
proc.start()
#Launch connection network
xactNetwork.startMonitors()
##########################
# Start simulation
##########################
managerProc = multiprocessing.Process(target=launchSimulation, args=(simManagerSeed, settingsDict))
childProcesses.append(managerProc)
managerProc.start()
managerProc.join() #DO NOT use a join statment here, or anywhere else in this function. It breaks interrupt handling. #Past me, I must ignore your advice and renable this. Thanks for the warning
#launchSimulation(simManagerSeed, settingsDict)
except KeyboardInterrupt:
for proc in childProcesses:
try:
print("### TERMINATE {}".format(proc.name))
proc.terminate()
print("### TERMINATED {}".format(proc.name))
except Exception as e:
print("### FAILED_TERMINANE, error = {}".format(e))