def _Execute(self): with _m.logbook_trace(name="{classname} v{version}".format( classname=(self.__class__.__name__), version=self.version), attributes=self._GetAtts()): try: networkCalculationTool = _m.Modeller().tool( "inro.emme.network_calculation.network_calculator") except Exception, e: networkCalculationTool = _m.Modeller().tool( "inro.emme.standard.network_calculation.network_calculator" ) with self._lineAttributeMANAGER() as flagAttributeId: with _m.logbook_trace("Flagging slected lines"): self.TRACKER.runTool(networkCalculationTool, self._GetNetCalcSpec(flagAttributeId), self.Scenario) network = self.Scenario.get_network() flaggedLines = [ line for line in network.transit_lines() if line[flagAttributeId] == 1 ] self.TRACKER.startProcess(len(flaggedLines)) for line in flaggedLines: self._ProcessLine(line) self.TRACKER.completeSubtask() self.TRACKER.completeTask() self.Scenario.publish_network(network) return len(flaggedLines)
def _transitFunctionsMANAGER(self): #Code here is executed upon entry functionChanger = None #Use the standard tools; it is faster and more verbose. try: functionChanger = _m.Modeller().tool("inro.emme.data.function.change_function") except Exception as e: functionChanger = _m.Modeller().tool("inro.emme.standard.data.function.change_function") expressionArchive = {} with _m.logbook_trace("Modifying transit time functions."): for f in self.databank.functions(): if f.type == "TRANSIT_TIME": expressionArchive[f.id] = f.expression functionChanger(f, f.expression + " + (us3 * %s)" %(self._appliedFareFactor)) #f.expression += " + (us3 * %s)" %(self._appliedFareFactor) try: yield # Code here is executed upon clean exit finally: # Code here is executed in all cases. with _m.logbook_trace("Resetting transit time functions."): for item in expressionArchive.iteritems(): f = self.databank.function(item[0]) functionChanger(f, item[1])
def __init__(self): try: self.netCalcTool = _m.Modeller().tool( "inro.emme.standard.network_calculation.network_calculator") except Exception as e: self.netCalcTool = _m.Modeller().tool( "inro.emme.network_calculation.network_calculator")
def __call__(self, MatrixId, Filename, ScenarioNumber): with _m.logbook_trace("Exporting matrix %s to XTMF" %MatrixId): scenario = _m.Modeller().emmebank.scenario(ScenarioNumber) if (scenario is None): raise Exception("Scenario %s was not found!" %ScenarioNumber) try: tool = None try: tool = _m.Modeller().tool('inro.emme.standard.data.matrix.export_matrices') except Exception as e: tool = _m.Modeller().tool('inro.emme.data.matrix.export_matrices') mtx = _m.Modeller().emmebank.matrix("mf%s" %MatrixId) if mtx is None: raise Exception("No matrix found with id '%s'" %MatrixId) self._tracker.runTool(tool, export_file=Filename, field_separator=' ', matrices=[mtx], full_matrix_line_format="ONE_ENTRY_PER_LINE", export_format="PROMPT_DATA_FORMAT", scenario=scenario, skip_default_values=False) except Exception as e: raise Exception(_traceback.format_exc())
def _execute(self): with _m.logbook_trace(name="Extract Travel Time Matrices v%s" % self.version, attributes={ "Scenario": self.scenario.id, "Modes": str(self._modeList), "IVTT Matrix": self.ivttMatrix.id, "Walk Time Matrix": self.walkMatrix.id, "Wait Time Matrix": self.waitMatrix.id, "Boarding Time Matrix": self.boardingMatrix.id, "Is running from XTMF?": str(self.isRunningFromXTMF), "self": self.__MODELLER_NAMESPACE__ }): self._assignmentCheck() try: matrixAnalysisTool = _m.Modeller().tool( 'inro.emme.transit_assignment.extended.matrix_results') except Exception as e: matrixAnalysisTool = _m.Modeller().tool( 'inro.emme.standard.transit_assignment.extended.matrix_results' ) matrixAnalysisTool(self._getAnalysisSpec(), self.scenario)
def _demandMatrixMANAGER(self): #Code here is executed upon entry with _m.logbook_trace("Initializing temporary demand matrix"): id=None if self.demandMatrix is None: self.demandMatrix = _util.initializeMatrix(id, matrix_type='SCALAR', name='trscal', description='Scalar matrix to get transit times') self._tracker.completeTask() else: cachedMatrix = self.demandMatrix self.demandMatrix = _util.initializeMatrix(matrix_type='FULL', description="Constrained full matrix for station-to-station assignment") _m.logbook_write("Created temporary constrained full demand matrix '%s'" %id) try: matrixCalcTool = _m.Modeller().tool("inro.emme.standard.matrix_calculation.matrix_calculator") except Exception as e: matrixCalcTool = _m.Modeller().tool("inro.emme.matrix_calculation.matrix_calculator") self._tracker.runTool(matrixCalcTool, self._getConstraintSpec(cachedMatrix, self.demandMatrix), scenario=self.scenario) #TASK 1 try: yield # Code here is executed upon clean exit finally: # Code here is executed in all cases. id = self.demandMatrix.id _m.Modeller().emmebank.delete_matrix(id) _m.logbook_write("Temporary matrix %s deleted." %id)
def _execute(self): with _m.logbook_trace(name="Extract select line matrix v%s" % self.version, attributes={ "Scenario": self.Scenario.id, "Result Matrix": self.MatrixResultId, "self": self.__MODELLER_NAMESPACE__ }): resultMatrix = _util.initializeMatrix( self.MatrixResultId, name='slctOD', description="Transit select line analysis result") try: strategyAnalysisTool = _m.Modeller().tool( 'inro.emme.standard.transit_assignment.extended.strategy_based_analysis' ) except Exception as e: strategyAnalysisTool = _m.Modeller().tool( 'inro.emme.transit_assignment.extended.strategy_based_analysis' ) self.TRACKER.runTool(strategyAnalysisTool, self._getAnalysisSpec(), self.Scenario)
def _execute(self): with _m.logbook_trace(name="Extract cost matrix v%s" % self.version, attributes={ "Scenario": self.scenario.id, "Result Matrix": self.matrixResult.id, "Is running from XTMF?": str(self.isRunningFromXTMF), "self": self.__MODELLER_NAMESPACE__ }): try: self.strategyAnalysisTool = _m.Modeller().tool( 'inro.emme.standard.transit_assignment.extended.strategy_based_analysis' ) except Exception as e: self.strategyAnalysisTool = _m.Modeller().tool( 'inro.emme.transit_assignment.extended.strategy_based_analysis' ) self.strategyAnalysisTool(self._getStrategyAnalysisSpec(), self.scenario)
def __init__(self): # Set up all Emme tools and data structures self.databank = _m.Modeller().emmebank try: self.transitAssignmentTool = _m.Modeller().tool("inro.emme.standard.transit_assignment.extended_transit_assignment") except Exception as e: self.transitAssignmentTool = _m.Modeller().tool("inro.emme.transit_assignment.extended_transit_assignment")
def run(self): self.tool_run_msg = "" try: with _m.logbook_trace(name="Move Networks", attributes=self._getAtts()): calculator = None try: calculator = _m.Modeller().tool("inro.emme.network_calculation.network_calculator") except Exception as e: calculator = _m.Modeller().tool("inro.emme.standard.network_calculation.network_calculator") spec = { "result": "yi", "expression": "yi + 4000000", "aggregation": None, "selections": { "node": "all" }, "type": "NETWORK_CALCULATION" } for scenario in self.Scenarios: _m.logbook_write("Changing scenario %s" %scenario.id) calculator(spec, scenario=scenario) self.tool_run_msg = _m.PageBuilder.format_info("Tool complete.") except Exception as e: self.tool_run_msg = _m.PageBuilder.format_exception( e, _traceback.format_exc(e)) raise
def page(self): pb = _m.ToolPageBuilder( self, title="Check Link VDFs", description= "Produces a worksheet to view all link VDFs in a scenario. It is recommended that you open the default worksheet prior to running this tool.", branding_text="- TMG Toolbox") if self.tool_run_msg != "": # to display messages in the page pb.tool_run_status(self.tool_run_msg_status) pb.add_select_scenario(tool_attribute_name="Scenario", title="Select scenario", note="Select a scenario to view") try: root = os.path.dirname(_m.Modeller().desktop.project_filename()) except Exception as e: root = os.path.dirname(_m.Modeller().desktop.project_file_name()) pb.add_select_file( tool_attribute_name="WorksheetFile", window_type="file", file_filter="*.emw", start_path=root, title="Emme worksheet file", note= "Optional. If provided, this tool will add layers to the worksheet file selected." ) return pb.render()
def page(self): pb = _m.ToolPageBuilder( self, title="List adjacent nodes", description= "Exports the nodes specified by a selection expression to " "a text file, with a list of the adjacent nodes " "sorted North South East and West.<br>" "Note: can only export nodes with four or less adjacent nodes.", branding_text="INRO - Emme") if self.tool_run_msg != "": pb.tool_run_status(self.tool_run_msg_status) pb.add_text_box( "north_angle", size=10, title="North Angle:", note= "Angle which is North, counterclockwise relative to the horizontal axis." ) pb.add_select_file("export_file", window_type="save_file", start_path=os.path.dirname( _m.Modeller().desktop.project_file_name()), title="Export file:") if not self.scenario: self.scenario = _m.Modeller().desktop.data_explorer().\ primary_scenario.core_scenario pb.add_select_scenario("scenario", title="Scenario:") return pb.render()
def _calculateUL1(self): _m.logbook_write("Calculating UL1 for tuv links.") networkCalculator = None #Use the standard tools; it is faster and more verbose. try: networkCalculator = _m.Modeller().tool( "inro.emme.network_calculation.network_calculator") except Exception as e: networkCalculator = _m.Modeller().tool( "inro.emme.standard.network_calculation.network_calculator") # link.data1 = 60 / link.length + self._appliedFareFactor * link.__getattribute__('@tfare') / self.WalkPerception spec = { "result": "ul1", "expression": "(60 * length / {0}) + ({1} * @tfare / {2})".format( self.WalkSpeed, self._appliedFareFactor, self.WalkPerception), "aggregation": None, "selections": { "link": "modes=tuv" }, "type": "NETWORK_CALCULATION" } networkCalculator(spec, scenario=self.scenario)
def exportTransit(self, tempFileName, scen, selection): NAMESPACE = "inro.emme.data.network.transit.export_transit_lines" export_transitlines = _modeller.Modeller().tool(NAMESPACE) emmebank_dir = os.path.dirname(_modeller.Modeller().emmebank.path) line_file = os.path.join(emmebank_dir, tempFileName) export_transitlines(export_file=line_file, selection=selection, scenario=scen)
def _calculateUL1(self): _m.logbook_write("Calculating UL1 for tuv links.") networkCalculator = None #Use the standard tools; it is faster and more verbose. try: networkCalculator = _m.Modeller().tool( "inro.emme.network_calculation.network_calculator") except Exception, e: networkCalculator = _m.Modeller().tool( "inro.emme.standard.network_calculation.network_calculator")
def _transitFunctionsMANAGER(self): #Code here is executed upon entry functionChanger = None #Use the standard tools; it is faster and more verbose. try: functionChanger = _m.Modeller().tool( "inro.emme.data.function.change_function") except Exception, e: functionChanger = _m.Modeller().tool( "inro.emme.standard.data.function.change_function")
def _execute(self): with _m.logbook_trace(name="Flag premium buses v%s" % self.version, attributes={ "Scenario": str(self.scenario.id), "Flag GO Buses": self.FlagGO, "Flag TTC Premium Buses": self.FlagPremTTC, "Flag VIVA Buses": self.FlagVIVA, "Flag ZUM": self.FlagZum, "Is running from XTMF?": str(self.isRunningFromXTMF), "self": self.__MODELLER_NAMESPACE__ }): #---0. Set up all Emme tools and data structures try: self.netWorkCalculationTool = _m.Modeller().tool( "inro.emme.standard.network_calculation.network_calculator" ) _m.logbook_write(name="Emme 3.4.2 Tool Names used") except Exception as e: self.netWorkCalculationTool = _m.Modeller().tool( "inro.emme.network_calculation.network_calculator") _m.logbook_write(name="Emme 4.0.3 Tool Names used") #---Initialize the flag attribute self._initFlagAttribute() self.counter = 0 #---Get network network = self.scenario.get_network() #---Set up the list of functions functions = [] if self.FlagGO: functions.append(self._flagGoBuses) if self.FlagPremTTC: functions.append(self._flagTTCPremiumBuses) if self.FlagVIVA: functions.append(self._flagVIVABuses) if self.FlagZum: functions.append(self._flagZumBuses) #---Execute for line in network.transit_lines(): for f in functions: f(line) #---Publish self.scenario.publish_network(network)
def __init__(self): #---0. Set up all Emme tools and data structures self.databank = _m.Modeller().emmebank try: self.matrixCalcTool = _m.Modeller().tool( "inro.emme.standard.matrix_calculation.matrix_calculator") self.transitAssignmentTool = _m.Modeller().tool( "inro.emme.standard.transit_assignment.extended_transit_assignment" ) self.matrixAnalysisTool = _m.Modeller().tool( 'inro.emme.standard.transit_assignment.extended.matrix_results' ) self.strategyAnalysisTool = _m.Modeller().tool( 'inro.emme.standard.transit_assignment.extended.strategy_based_analysis' ) except Exception as e: self.matrixCalcTool = _m.Modeller().tool( "inro.emme.matrix_calculation.matrix_calculator") self.transitAssignmentTool = _m.Modeller().tool( "inro.emme.transit_assignment.extended_transit_assignment") self.matrixAnalysisTool = _m.Modeller().tool( 'inro.emme.transit_assignment.extended.matrix_results') self.strategyAnalysisTool = _m.Modeller().tool( 'inro.emme.transit_assignment.extended.strategy_based_analysis' )
def _peek(self, file): batch = open(file) for line in batch.readlines(): if line.startswith('a'): id = self._parseMatrixHeader(line) mtx = _m.Modeller().emmebank.matrix(id) if mtx is not None: _m.Modeller().emmebank.delete_matrix(id) return
def getAvailableScenarioNumber(): ''' Returns: The number of an available scenario. Raises an exception if the _DATABANK is full. ''' for i in range(0, _m.Modeller().emmebank.dimensions['scenarios']): if _m.Modeller().emmebank.scenario(i + 1) == None: return (i + 1) raise inro.emme.core.exception.CapacityError( "No new scenarios are available: databank is full!")
def __call__(self): current_scen = self.current_scenario specs = _json.loads(self.sola_specs_box) with _modeller.logbook_trace( name="SOLA Assignment on Multiple Scenarios", value=""): NAMESPACE = 'inro.emme.traffic_assignment.sola_traffic_assignment' sola_assign = _modeller.Modeller().tool(NAMESPACE) for scen in self.scenarios_list: _modeller.Modeller().desktop.data_explorer( ).replace_primary_scenario(scen) sola_assign(specs)
def __call__(self): current_scen = self.current_scenario #export extra attributes with _modeller.logbook_trace(name = "Path Based Assignment on Multiple Scenarios", value = ""): NAMESPACE = 'inro.emme.traffic_assignment.path_based_traffic_assignment' path_assign = _modeller.Modeller().tool(NAMESPACE) specs = _json.loads(self.path_specs_box) for scen in self.scenarios_list: _modeller.Modeller().desktop.data_explorer().replace_primary_scenario(scen) path_assign(specs)
def __call__(self, ScenarioNumber, MacroFile, Args): try: # Get the run macro tool tool = None try: tool = _m.Modeller().tool('inro.emme.standard.prompt.run_macro' ) #Emme 3.4.2 namespace except Exception, e: tool = _m.Modeller().tool( 'inro.emme.prompt.run_macro') #Emme 4.0.3 namespace tool(macro_name=MacroFile, macro_arguments=Args, scenario=ScenarioNumber)
def _demandMatrixMANAGER(self): #Code here is executed upon entry usingScalar = False if self.demandMatrix is None: _m.logbook_write("Initializing temporary scalar demand matrix.") #def initializeMatrix(id=None, default=0, name="", description="", matrix_type='FULL'): self.demandMatrix = _util.initializeMatrix( matrix_type='SCALAR', name='trscal', description="Scalar matrix to get transit times") if self.demandMatrix is None: raise Exception( "Could not create temporary scalar demand matrix!") usingScalar = True try: yield # Code here is executed upon clean exit finally: # Code here is executed in all cases. if usingScalar == True: _m.logbook_write("Deleting temporary scalar demand matrix.") _m.Modeller().emmebank.delete_matrix(self.demandMatrix.id)
def __call__(self, xtmf_JSON, xtmf_logbook_level): logbook = _m.logbook_level() if xtmf_logbook_level == "NONE": _m.logbook_level(_m.LogbookLevel.NONE) # xtmf_ScenarioNumber, ExportFile, xtmf_AttributeIdString parameters = json.loads(xtmf_JSON) self.ExportFile = parameters["export_file"] self.Scenario = _m.Modeller().emmebank.scenario( parameters["scenario_number"]) if self.Scenario is None: raise Exception("Scenario %s was not found!" % xtmf_ScenarioNumber) xtmf_AttributeIdString = parameters["extra_attributes"] if xtmf_AttributeIdString.lower() == 'all': self.ExportAllFlag = True # if true, self.AttributeIdsToExport gets set in execute else: cells = xtmf_AttributeIdString.split(',') self.AttributeIdsToExport = [ str(c.strip()) for c in cells if c.strip() ] # Clean out null values try: self._execute() except Exception, e: msg = str(e) + "\n" + _traceback.format_exc(e) raise Exception(msg)
def open_emme_project(my_project): #Open the Time Period Specific Project passed to the function and load the Input Dictionary my_desktop = app.start_dedicated(True, "cth", my_project) my_modeller = _m.Modeller(my_desktop) return (my_modeller)
def __call__(self, xtmf_ScenarioNumber, ResultAttributeId, TollZoneAttributeId, LightZoneToll, RegularZoneToll): #---1 Set up scenario self.Scenario = _m.Modeller().emmebank.scenario(xtmf_ScenarioNumber) if (self.Scenario == None): raise Exception("Scenario %s was not found!" %xtmf_ScenarioNumber) linkAtts = set([att.id for att in self.Scenario.extra_attributes() if att.type == 'LINK']) if not ResultAttributeId in linkAtts: raise NullPointerException("'%s' is not a valid link attribute" %ResultAttributeId) if not TollZoneAttributeId in linkAtts: raise NullPointerException("'%s' is not a valid link attribute" %TollZoneAttributeId) self.ResultAttributeId = ResultAttributeId self.TollZoneAttributeId = TollZoneAttributeId self.LightZoneToll = LightZoneToll self.RegularZoneToll = RegularZoneToll try: self._Execute() except Exception, e: msg = str(e) + "\n" + _traceback.format_exc(e) raise Exception(msg)
def __call__(self, xtmf_ScenarioNumber, xtmf_LineAggregationFile, xtmf_OutputDirectory): _m.logbook_write("Extracting boarding results") #---1 Set up scenario scenario = _m.Modeller().emmebank.scenario(xtmf_ScenarioNumber) self.scenarioNumber = xtmf_ScenarioNumber if (scenario is None): raise Exception("Scenario %s was not found!" % xtmf_ScenarioNumber) if not scenario.has_transit_results: raise Exception( "Scenario %s does not have transit assignment results" % xtmf_ScenarioNumber) self.NumberOfProcessors = cpu_count() self.xtmf_LineAggregationFile = xtmf_LineAggregationFile self.xtmf_OutputDirectory = xtmf_OutputDirectory #self.xtmf_CheckAggregationFlag = xtmf_CheckAggregationFlag try: return self._Execute(scenario) except Exception as e: msg = str(e) + "\n" + _traceback.format_exc() raise Exception(msg)
def _ConvertStops(self, stops): convertedStops = {} # find what zone system the file is using fullzonestring = _m.Modeller().desktop.project.spatial_reference_file if EMME_VERSION >= (4, 3, 0): with open(fullzonestring, 'r') as zoneFile: zoneString = zoneFile.read() hemisphere = zoneString[28:29] prjzone = int(zoneString[26:28]) else: hemisphere = fullzonestring[-5:-4] prjzone = int(fullzonestring[-7:-5]) # put try and exception statements here? if hemisphere.lower() == 's': p = Proj("+proj=utm +ellps=WGS84 +zone=%d +south" % prjzone) else: p = Proj("+proj=utm +ellps=WGS84 +zone=%d" % prjzone) stoplons = () stoplats = () for stop in stops.keys(): templons = (float(stops[stop][0]), ) templats = (float(stops[stop][1]), ) x, y = p(templons, templats) convertedStops[stop] = x + y convertedStops[stop] = (float(convertedStops[stop][0]), float(convertedStops[stop][1])) return convertedStops
def __call__(self, ScenarioNumber, ModeString, InVehicleTimeMatrixNumber, WalkTimeMatrixNumber, WaitTimeMatrixNumber, BoardingTimeMatrixNumber): self.scenario = _m.Modeller().emmebank.scenario(ScenarioNumber) if self.scenario is None: raise Exception("Could not find scenario %s!" % ScenarioNumber) # Initialize the result matrices self._initBoard("mf%s" % BoardingTimeMatrixNumber) self._initIVTT("mf%s" % InVehicleTimeMatrixNumber) self._initWait("mf%s" % WaitTimeMatrixNumber) self._initWalk("mf%s" % WalkTimeMatrixNumber) # Convert the mode string to a list of characters for i in range(0, len(ModeString)): self._modeList.append(ModeString[i]) self.isRunningFromXTMF = True #Execute the tool try: self._execute() except Exception as e: raise Exception(_traceback.format_exc(e))