def updateStepRate(self, steps): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simualtionID = UserDataInterface().getSimulationid( cherrypy.request.login) #pass in this format interface = UserDataInterface() interface.updateSimulationStepRate(simualtionID, steps) return {'response': {'status': "success"}} else: return {'response': {'status': "failure"}}
def startSimulation(self): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true" and has_privileges(): simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) #pass in this format logging.info('Starting simulation for user: '******' with Simulation id: ' + str(simulationID)) cloudInterface = CloudInterface() logging.info('Fetching assigned VM for simulation id: ' + str(simulationID)) vm = cloudInterface.assignVM(simulationID) if vm is None: logging.warning('VM could not assigned for user: '******' with Simulation id: ' + str(simulationID)) return {'response': 'notavailable'} private_ip = vm['private_IP'] key_name = vm['key_name'] logging.info('Starting simulation for id: ' + str(simulationID) + ' on VM:' + private_ip) trafficsim(private_ip, key_name, simulationID, cherrypy.request.login).start() #t_sim.start() logging.info('Simulation start command sent..') return {'response': str(simulationID)} else: logging.warning('Unable to authenticate..') return {'response': "failure"}
def createVehiclesXml(self): """ Create Vehicle distribution and types and save them in vType file for each id in simulationID list. """ # Add vehicle type additional file # http://sumo.sourceforge.net/xsd/additional_file.xsd vehFile = open(self.vehicleTypeLoc, 'w') #vehFile.write("<additional xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://sumo.sf.net/xsd/additional_file.xsd\">\n") vehFile.write("<vTypeDistribution id=\"vehicledist1\">\n") #total_veh = 0 #for simID in self.simulationIDs: # vehicles = self.vehDAO.readVehicles(simID) # for veh in vehicles: # total_veh = total_veh + int(veh["vehicle_count"]) simIDs = self.simAssociationDAO.readAssociatedSimIDs(self.simulationID) #veh_index = 0 for simID in simIDs: # Connect db and pull up the vehicle information sim_record = UserDataInterface().getSimulationUserData(simID) vehicles = self.vehDAO.readVehicles(simID) for veh in vehicles: veh_id = veh["name"] + "_" + str(sim_record.get('group_id')) #veh_index = veh_index + 1 #probability = int(veh["vehicle_count"]) * 1.0 / total_veh vehFile.write("<vType ") vehFile.write("id=\"") vehFile.write(str(veh_id)) vehFile.write("\" ") vehFile.write("accel=\"") vehFile.write(str(convertFeetToMeter(float(veh["accel"])))) vehFile.write("\" ") vehFile.write("decel=\"") vehFile.write(str(convertFeetToMeter(float(veh["decel"])))) vehFile.write("\" ") vehFile.write("length=\"") vehFile.write(str(convertFeetToMeter(float(veh["length"])))) vehFile.write("\" ") vehFile.write("maxSpeed=\"") vehFile.write(str(convertMPHToMperSec(float( veh["max_speed"])))) vehFile.write("\" ") vehFile.write("sigma=\"") vehFile.write(str(veh["sigma"])) vehFile.write("\" ") vehFile.write("probability=\"") vehFile.write(str(veh["probability"])) vehFile.write("\">") # TODO: Need to design a new car following model or just have the default params here #vehFile.write("<carFollowing-Krauss accel=\"5.0\" decel=\"5.0\" sigma=\"0.50\"/>\n") vehFile.write("</vType>\n") vehFile.write("</vTypeDistribution>\n") #vehFile.write("</additional>\n") return True
def getGroupUrl(self, group_id): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": interface = UserDataInterface() simualtionID = interface.getSimulationid( cherrypy.request.login) #pass in this format groupinfo = interface.getSimulationUserData( simualtionID) #groupinfo["group_id"] studentgroup = self.studentGroupDAO.getCollaborationUrl(group_id) actual_time = datetime.now() last_update_time = datetime.strptime( studentgroup["last_update_time"], "%Y-%m-%d %H:%M:%S.%f") diff = (actual_time - last_update_time).total_seconds() #if has_role_of("admin"): if diff > 10: collaboration_url = studentgroup[ "collaboration_url_admin"] + "&group_name=" + group_id else: collaboration_url = studentgroup[ "collaboration_url"] + "?group_name=" + group_id return { 'response': { 'status': "success", 'collaboration_url': collaboration_url } } else: return {'response': {'status': "failure"}}
def readVehicles(self, rows=None, sidx=None, _search=None, searchField=None, searchOper=None, searchString=None, page=None, sord=None, nd=None): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) #pass in this format vehicles = self.vehDAO.readVehicles(simulationID) cell_list = [] for veh in vehicles: cell = { "id": str(veh["_id"]), "cell": [ str(veh["_id"]), str(veh["simulation_id"]), veh["name"], veh["accel"], veh["decel"], veh["sigma"], veh["max_speed"], veh["length"], veh["probability"] ] } cell_list.append(cell) #vehiclesJson ={"vehicles": cell_list} return {"vehicles": cell_list} else: return {'response': "failure"}
def createTrafficLightLogic(self, intersection_id, state0, state1, state2, state3, state4, state5, state6, state7, traffic_light_links, duration, oper=None, id=None): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) # Put phases into Green!0!1-Red!2!3!4-Green!5-... format # traffic_light_links : 0!1-2!3!4-5!6 indexes = traffic_light_links.split("-") state = state0 + "!" + indexes[0] + "-" + state1 + "!" + indexes[ 1] + "-" + state2 + "!" + indexes[ 2] + "-" + state3 + "!" + indexes[ 3] + "-" + state4 + "!" + indexes[ 4] + "-" + state5 + "!" + indexes[ 5] + "-" + state6 + "!" + indexes[ 6] + "-" + state7 + "!" + indexes[7] self.trafficLightDAO.createTrafficLightLogic( simulationID, intersection_id, state, duration) return {'response': {'status': "success"}} else: return {'response': "failure"}
def __init__(self, simulationID): logging.info('Initializing simulation for ID: ' + str(simulationID)) self.simulationID = simulationID self.sumoexeloc = SUMO_EXE_LOC self.sumoport = SUMO_PORT self.sumoautostart = SUMO_AUTO_START self.queueoutfile = QUEUE_OUT_FILE self.tripoutfile = TRIP_OUT_FILE self.routeoutfile = ROUTE_OUT_FILE self.sumomessagelog = SUMO_MESSAGE_LOG_FILE self.sumoerrorlog = SUMO_ERROR_LOG_FILE #self.simsleepperiod = float(SIM_SLEEP_PERIOD) self.sumoRouteLoc = SUMO_ROUTES_LOC self.turnDocLoc = SUMO_TURN_LOC self.closedLanesLoc = SUMO_CLOSED_LANES_LOC self.flowDocLoc = SUMO_FLOW_LOC self.routeSimEnd = ROUTE_SIM_END self.jtrrouterexeLoc = JTRROUTER_EXE_LOC self.trafficLightLoc = SUMO_TRAFFIC_LIGHT_LOC self.vehicleTypeLoc = SUMO_VEHICLE_TYPE_LOC self.inductionLoopLoc = SUMO_INDUCTION_LOOP_LOC interface = UserDataInterface() simdata = interface.getSimulationUserData(self.simulationID) print("initializing...") if simdata is None: print("Not able to initialize...") logging.error("Not able to initialize simulation: " + str(self.simulationID)) group_type = interface.getGroupType(simdata['group_id']) logging.info(str(simdata)) print str(simdata) problem_id = simdata['problem_id'] problem = ProblemsDAO().readProblem(problem_id) self.sumoNetLoc = problem['map_loc_prefix'] self.problemType = problem['type'] if (problem_id in ['6a', '6b', '6c']): self.closedLanesLoc = SUMO_NS_CLOSED_LANES_LOC if group_type == 'A': self.sumoconfloc = SUMO_CONFIG_LOC_A self.sumoNetLoc = self.sumoNetLoc + '_A' elif group_type == 'B': self.sumoconfloc = SUMO_CONFIG_LOC_B self.sumoNetLoc = self.sumoNetLoc + '_B' #elif group_type == 'C': # self.sumoconfloc = SUMO_CONFIG_LOC_C # self.sumoNetLoc = SUMO_NET_LOC_C #elif group_type == 'D': # self.sumoconfloc = SUMO_CONFIG_LOC_D # self.sumoNetLoc = SUMO_NET_LOC_D else: self.sumoconfloc = SUMO_CONFIG_LOC self.sumoNetLoc = self.sumoNetLoc + SUMO_NET_LOC_SUFFIX
def updateFlow(self, point_name, flow_rate): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) self.flowsDAO.updateFlow(simulationID, point_name, flow_rate) return {'response': {'status': "success"}} else: return {'response': "failure"}
def copySimVersionToCurrent(self, sim_id): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": currentSimulationID = UserDataInterface().getSimulationid( cherrypy.request.login) interface = SimulationBackupInterface(currentSimulationID) interface.copySimulationToCurrent(sim_id, cherrypy.request.login) return {'response': {'status': "success"}} else: return {'response': "failure"}
def setMaxSpeed(self, laneID, maxSpeed): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simualtionID = UserDataInterface().getSimulationid( cherrypy.request.login) #pass in this format #cherrypy.t_sim = trafficsim(e_queue, simualtionID) #e_queue.enqueue(cherrypy.t_sim.setMaxSpeed, [str(laneID), float(maxSpeed)], {}) return {'response': {'status': "success", 'speed': maxSpeed}} else: return {'response': {'status': "failure"}}
def readAllFlows(self): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": user_id = cherrypy.request.login interface = UserDataInterface() simulationID = interface.getSimulationid(cherrypy.request.login) problem_id = self.problemsDAO.getProblemID(simulationID) user_mode = interface.getUserMode(user_id) # Find duplicates and discard them from the list # At the collaboration mode first discard duplicated flow points # then flow points with removable column equals to 1 from the remaining list ''' temp_flows = copy.deepcopy(flows) duplicates = {} for flow in temp_flows: if flow["point_name"] in duplicates.keys(): duplicates[flow["point_name"]] += 1 else: duplicates[flow["point_name"]] = 1 ''' cell_list = [] if (problem_id in ['3', '8']): pointList = ['A', 'B', 'Iwest', 'Lnorth'] elif (problem_id in ['6a', '6b', '6c']): pointList = ['A', 'Iwest'] else: pointList = ['A', 'B', 'C', 'D', 'Jnorth', 'Lnorth'] simIDs = self.simAssociationDAO.readAssociatedSimIDs(simulationID) for simID in simIDs: flows = self.flowsDAO.readAllFlows(simID) for flow in flows: cell = { "id": str(flow["_id"]), "simulation_id": str(flow["simulation_id"]), "point_name": flow["point_name"], "intersection_id": flow["intersection_id"], "latitude": flow["latitude"], "longitude": flow["longitude"], "flow_rate": flow["flow_rate"] } #cell = {"point_name": flow["point_name"]} if user_mode == "COLAB": # If there are duplicates in COLAB mode remove those points #if duplicates[flow["point_name"]] == 1 and flow["removable"] == "0": if any(flow["point_name"] in s for s in pointList): cell_list.append(cell) else: if any(flow["point_name"] in s for s in pointList): if flow["removable"] == "0": cell_list.append(cell) return {'response': {'status': "success", 'flows': cell_list}} else: return {'response': "failure"}
def saveSimVersion(self, sim_id, sim_label, shared_with): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": # no need to get sim id from user simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) interface = SimulationBackupInterface(simulationID) return interface.saveSimulationWithUserInput( sim_label, shared_with, cherrypy.request.login) else: return {'response': "failure"}
def updateTurnProbability(self, edge_id, left_turn, right_turn, go_straight): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) self.turnProbabilityDAO.updateTurnProbability( simulationID, edge_id, left_turn, right_turn, go_straight) return {'response': {'status': "success"}} else: return {'response': "failure"}
def updateGroupUrl(self, group_id, user_id, problem_id, collaboration_url): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": self.studentGroupDAO.updateCollaborationUrl( group_id, collaboration_url) simulationID = UserDataInterface().getSimulationid(user_id) self.colabLogDAO.createLog(simulationID, user_id, problem_id) return {'response': {'status': "success"}} else: return {'response': {'status': "failure"}}
def updateProblem(self, problem_id): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": username = cherrypy.request.login simulationID = UserDataInterface().getSimulationid(username) interface = UserDataInterface() usermode = interface.getUserMode(username) if (usermode == 'COLAB' and (not interface.checkIfMasterSim(simulationID))): return {'response': "not_admin"} self.problemsDAO.updateProblem(simulationID, problem_id) problem = self.problemsDAO.readProblem(problem_id) return { 'response': { 'status': "success", 'title': problem["title"], 'problem_type': problem["type"] } } else: return {'response': "failure"}
def createReason(self, desc): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) #pass in this format user_id = cherrypy.request.login problem_id = self.problemsDAO.getProblemID(simulationID) self.reasonDAO.createReason(simulationID, user_id, problem_id, desc) return {'response': {'status': "success"}} else: return {'response': "failure"}
def getProblemID(self): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) problem_id = self.problemsDAO.getProblemID(simulationID) return { 'response': { 'status': "success", 'problem_id': problem_id } } else: return {'response': "failure"}
def restoreSimulationRate(self): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true" and has_privileges(): interface = UserDataInterface() simulationID = interface.getSimulationid( cherrypy.request.login) #pass in this format logging.info('Restoring simulation rate for user: '******' with Simulation id: ' + str(simulationID)) interface.restoreSimulationStepRate(simulationID) return {'response': "success"} else: return {'response': "failure"}
def readFlow(self, point_name): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) flow = self.flowsDAO.readFlow(simulationID, point_name) return { 'response': { 'status': "success", 'flow_rate': str(flow["flow_rate"]) } } else: return {'response': "failure"}
def readTurnProbability(self, edge_id): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) turn = self.turnProbabilityDAO.readTurnProbability( simulationID, edge_id) return { 'response': { 'status': "success", 'left_turn': turn["left_turn"], 'right_turn': turn["right_turn"], 'go_straight': turn["go_straight"] } } else: return {'response': "failure"}
def readSimulations(self, rows=None, sidx=None, _search=None, searchField=None, searchOper=None, searchString=None, page=None, sord=None, nd=None): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": result = UserDataInterface().getSimulationHistoryTable( cherrypy.request.login) return {"sim_versions": result} else: return {'response': "failure"}
def __init__(self, vmIP, key_name, simulationID, userID): threading.Thread.__init__(self) logging.info('Initializing trafficsim from SimID' + str(simulationID)); self.userInterface = UserDataInterface() self.simulationID = simulationID self.strSimulationID = str(simulationID) self.userID = userID self.vmIP = vmIP self.keyName = key_name self.sumoport = SUMO_PORT datafolder = GENERATED_DATA_FOLDER + self.strSimulationID self.trafficdataxml = datafolder + TRAFFIC_DATA_XML self.trafficsignaldataxml = datafolder + TRAFFIC_SIGNAL_DATA_XML self.running = False self.traciinst = None print("..initialized")
def getQueueResult(self, sim_id, loop_id): interface = UserDataInterface() currentSimulationID = interface.getSimulationid(cherrypy.request.login) if str(currentSimulationID) == sim_id: # just a hack for now sim_id = ObjectId( interface.getSimulationFolder(ObjectId(sim_id), (cherrypy.request.login))) sim_exec_id = interface.getActiveSimulationExecId(sim_id) if (sim_exec_id is None): return {'response': {'status': "nosimexec"}} simInterface = SimulationExecutionInterface(sim_exec_id, sim_id) execResult = simInterface.getSimulationExecutionDetails() if execResult.get('simendtime') is not None: result = simInterface.getQueueResult(loop_id) return {'response': {'status': "success", 'resultdata': result}} else: return {'response': {'status': "notloaded"}}
def createVehicle(self, name, accel, decel, sigma, max_speed, length, probability, oper=None, id=None): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) #pass in this format self.vehDAO.createVehicle(simulationID, name, accel, decel, sigma, max_speed, length, probability) return {'response': {'status': "success"}} else: return {'response': "failure"}
def getGroupData(self): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": interface = UserDataInterface() username = cherrypy.request.login simulationID = interface.getSimulationid( username) #pass in this format siminfo = interface.getSimulationUserData(simulationID) simFolderId = interface.getSimulationFolder(simulationID, username) problem_id = self.problemsDAO.getProblemID(simulationID) problem = self.problemsDAO.readProblem(problem_id) interface.ensureSimulationExists(simFolderId) sim_folder = str(simFolderId) userDetails = interface.getUserDetails(username) firstname = userDetails.get('firstname') lastname = userDetails.get('lastname') groupname = userDetails.get('groupname') # In COLAB mode, rest of the junctions are returned in addition to the # one that a group is associated with assoc_junctions = interface.getJunctionsofOtherGroups( simulationID, username) logging.info('Returning login data for user: '******'response': { 'status': "success", 'siminfo': siminfo, 'sim_id': str(simulationID), 'sim_folder': sim_folder, 'username': cherrypy.request.login, 'firstname': firstname, 'lastname': lastname, 'groupname': groupname, 'assoc_junctions': assoc_junctions, 'problem_id': problem_id, 'problem_type': problem['type'] } } logging.info(response_data) return response_data else: return {'response': {'status': "failure"}}
def setMode(self, user_mode=None): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": username = cherrypy.request.login interface = UserDataInterface() simulationID = interface.getSimulationid(username) logging.info('simulationID: ' + str(simulationID) + ' , username: '******', usermode: ' + user_mode) interface.setUserMode(username, user_mode) cloudInterface = CloudInterface() simFolderId = interface.getSimulationFolder(simulationID, username) interface.ensureSimulationExists(simFolderId) return { 'response': { 'status': "success", 'sim_folder': str(simFolderId), 'sim_id': str(simulationID) } } else: return {'response': "failure"}
def readTrafficLightLogic(self, intersection_id, light_index, rows=None, sidx=None, _search=None, searchField=None, searchOper=None, searchString=None, page=None, sord=None, nd=None): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) traffic_light_logic = self.trafficLightDAO.readTrafficLightLogic( simulationID, intersection_id) # Split phase info and return. Format is in Green!0!1-Red!2!3!4-Green!5-... cell_list = [] for tll in traffic_light_logic: links = tll["state"].split("-") state = "" cell = [] cell.append(str(tll["intersection_id"])) for link in links: state = link.split("!") cell.append(state[0]) cell.append(tll["duration"]) #cell = {"id":str(tll["_id"]), "cell": [str(tll["intersection_id"]), states, tll["duration"]]} cell_indv = {"id": str(tll["_id"]), "cell": cell} cell_list.append(cell_indv) logicJson = {"logic": cell_list} return logicJson else: return {'response': "failure"}
def createFlowsXml(self): """ Retrieves flows for a simulation and creates flow.xml file for SUMO """ flowFile = open(self.flowDocLoc, 'w') simIDs = list( self.simAssociationDAO.readAssociatedSimIDs(self.simulationID)) #simID = simIDs[0] flowFile.write("<flows>\n") # Connect db and pull up the flows # intersectionIDs = self.simulationDAO.getIntersectionIDs(simID) # for intID in intersectionIDs: interface = UserDataInterface() simdata = interface.getSimulationUserData(self.simulationID) user_mode = simdata['mode'] problem_id = simdata['problem_id'] if (problem_id in ['3', '8']): pointList = ['A', 'B', 'Iwest', 'Lnorth'] elif (problem_id in ['6a', '6b', '6c']): pointList = ['A', 'Iwest'] else: pointList = ['A', 'B', 'C', 'D', 'Jnorth', 'Lnorth'] flows = [] simIDs = self.simAssociationDAO.readAssociatedSimIDs(self.simulationID) for simID in simIDs: temp_flows = self.flowsDAO.readAllFlows(simID) for flow in temp_flows: if user_mode == "COLAB": if any(flow["point_name"] in s for s in pointList): flows.append(flow) else: if any(flow["point_name"] in s for s in pointList): if flow["removable"] == "0": flows.append(flow) ''' temp_flows = [] for simID in simIDs: logging.info('Simulation ID:' + str(simID)) temp = list(self.flowsDAO.readAllFlows(simID)) temp_flows.extend(temp) flows = [] duplicates = {} for flow in temp_flows: logging.info('Flow Point Name: ' + flow["point_name"]) if flow["point_name"] in duplicates.keys(): duplicates[flow["point_name"]] += 1 else: duplicates[flow["point_name"]] = 1 # If there are duplicates in COLAB mode remove those points # If point appended list only one time and if it is not a removable # point then add it to the flows list if duplicates[flow["point_name"]] == 1 and flow["removable"] == "0": flows.append(flow) ''' for flow in flows: flowFile.write("<flow id=\"flow_") flowFile.write(str(flow["from_edge_id"])) flowFile.write("\" from=\"") flowFile.write(str(flow["from_edge_id"])) flowFile.write("\" via=\"") flowFile.write(str(flow["via_edge_id"])) flowFile.write("\" ") flowFile.write(" begin=\"0\" end=\"300\"") flowFile.write(" vehsPerHour=\"") flowFile.write(str(flow["flow_rate"])) flowFile.write("\" type=\"vehicledist1\"") flowFile.write("/>\n") flowFile.write("</flows>\n")
def checkStartStatus(self): interface = UserDataInterface() simulationID = interface.getSimulationid(cherrypy.request.login) return {'response': interface.getSimulationRunningState(simulationID)}
def has_privileges(): mode = UserDataInterface().getUserMode(cherrypy.request.login) if (mode == 'COLAB'): return has_role_of('super') return True