Exemple #1
0
class XTMFMatrixCalculator(_m.Tool()):

    #---Parameters---
    Scenario = _m.Attribute(_m.InstanceType)
    xtmf_ScenarioNumber = _m.Attribute(str)
    xtmf_expression = _m.Attribute(str)
    xtmf_result = _m.Attribute(str)

    def __init__(self):
        self.Scenario = _MODELLER.scenario

    def __call__(self, xtmf_ScenarioNumber, xtmf_expression, xtmf_result):

        self.Scenario = _MODELLER.emmebank.scenario(xtmf_ScenarioNumber)
        if (self.Scenario is None):
            raise Exception("Scenario %s was not found!" % xtmf_ScenarioNumber)

        self.expression = xtmf_expression
        self.result = xtmf_result

        spec = self.matrix_calculator_spec()

        report = matrixCalculator(spec, self.Scenario)
        return ""

    def matrix_calculator_spec(self):
        spec = {
            "result": self.result,
            "expression": self.expression,
            "type": "MATRIX_CALCULATION"
        }
        return spec
 def GetToolParameterTypes(self, tool):
     # get the names of the parameters
     parameterNames = inspect.getargspec(tool.__call__)[0][1:]
     ret = []
     for param in parameterNames:
         try:
             paramVar = eval("tool.__class__." + str(param))
         except:
             _m.logbook_write("A parameter with the name '" + param + "' does not exist in the executing EMME tool!  Make sure that the EMME tool defines this attribute as a class variable.")
             self.SendParameterError("A parameter with the name '" + param + "' does not exist in the executing EMME tool!  Make sure that the EMME tool defines this attribute as a class variable.")
             return None
         typeOfParam = paramVar.type
         if typeOfParam == _m.Attribute(float).type:
             ret.append("float")
         elif typeOfParam == _m.Attribute(int).type:
             ret.append("int")
         elif typeOfParam == _m.Attribute(str).type:
             ret.append("string")
         elif typeOfParam == _m.Attribute(bool).type:
             ret.append("bool")
         else:
             _m.logbook_write(param + " uses a type unsupported by the ModellerBridge '" + str(typeOfParam) + "'!")
             self.SendParameterError(param + " uses a type unsupported by the ModellerBridge '" + str(typeOfParam) + "'!")
             return None
     return ret 
class CopyScenario(_m.Tool()):
    version = '0.0.1'
    xtmf_JSON = _m.Attribute(str)
    xtmf_logbook_level = _m.Attribute(str)

    def page(self):
        pb = _m.ToolPageBuilder(self,
                                title="Copy Scenario",
                                runnable=False,
                                description="Cannot be called from Modeller.",
                                branding_text="XTMF")

        return pb.render()

    def run(self):
        pass

    def __call__(self, xtmf_JSON, xtmf_logbook_level):
        logbook = _m.logbook_level()
        if xtmf_logbook_level == "NONE":
            _m.logbook_level(_m.LogbookLevel.NONE)
        parameters = json.loads(xtmf_JSON)
        FromScenario = parameters['from_scenario']
        ToScenario = parameters['to_scenario']
        CopyStrategy = parameters['copy_strategy']
        try:
            self._execute(FromScenario, ToScenario, CopyStrategy)
        except Exception, e:
            raise Exception(_traceback.format_exc(e))
Exemple #4
0
class RunMacro(_m.Tool()):

    ScenarioNumber = _m.Attribute(int)
    MacroFile = _m.Attribute(str)
    Args = _m.Attribute(str)

    def page(self):
        pb = _m.ToolPageBuilder(self,
                                title="Run a macro",
                                runnable=False,
                                description="Cannot be called from Modeller.",
                                branding_text="XTMF")

        return pb.render()

    def run(self):
        pass

    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)
        except Exception, e:
            raise Exception(_traceback.format_exc(e))
class CopyScenario(_m.Tool()):
    version = '0.0.1'
    batch_file = _m.Attribute(str)
    scenario_number = _m.Attribute(int)

    def page(self):
        pb = _m.ToolPageBuilder(self,
                                title="Import VDF Batch File",
                                runnable=False,
                                description="Cannot be called from Modeller.",
                                branding_text="XTMF")

        return pb.render()

    def run(self):
        pass

    def __call__(self, batch_file, scenario_number):
        try:
            project = _MODELLER.emmebank
            scenario = project.scenario(str(scenario_number))
            process(transaction_file=batch_file,
                    scenario=scenario,
                    throw_on_error=True)
        except Exception as e:
            raise Exception(_traceback.format_exc())
class AddNodeWeights(_m.Tool()):

    version = '0.1.0'
    tool_run_msg = ""
    report_html = ""
    Scenario = _m.Attribute(_m.InstanceType)
    MassAttribute = _m.Attribute(_m.InstanceType)

    def __init__(self):
        self.Scenario = _MODELLER.scenario
        self._tracker = _util.ProgressTracker(5)

    def page(self):
        pb = _tmgTPB.TmgToolPageBuilder(
            self,
            title="Add Node Weights v%s" % self.version,
            description="Adds node weights to existing network nodes \
                                for use in centroid generation. Higher weights are \
                                more likely to be connected to centroid connectors in CCGEN.\
                                <br><br>The node weights are assigned as follows: \
                                <br> <ul style=\"list-style-type:none\">\
                                <li><b>1</b>: default value \
                                <li><b>2</b>: nodes at intersections with transit stop(s) \
                                <li><b>3</b>: mid-block nodes without any transit stops \
                                <li><b>4</b>: mid-block nodes with transit stop(s) \
                                <li><b>5</b>: dead-end nodes without any transit stops \
                                <li><b>6</b>: dead-end nodes with transit stop(s)</ul>\
                                ",
            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",
                               allow_none=False)

        pb.add_select_attribute(
            tool_attribute_name="MassAttribute",
            filter='NODE',
            allow_none=True,
            title="Node weight attribute",
            note="Attribute which node weights will be stored in.")

        return pb.render()

    @_m.method(return_type=unicode)
    def tool_run_msg_status(self):
        return self.tool_run_msg

    def run(self):
        self.tool_run_msg = ""
        '''Run is called from Modeller.'''

        try:
            self._execute()
        except Exception, e:
            self.tool_run_msg = _m.PageBuilder.format_exception(
                e, _traceback.format_exc(e))
            raise
Exemple #7
0
class ImportCordonCounts(_m.Tool()):
    
    version = '1.0.0'
    tool_run_msg = ""
    number_of_tasks = 1
    Scenario = _m.Attribute(_m.InstanceType)
    CordonTruthTable = _m.Attribute(str)
    
    
    def __init__(self):
        #---Init internal variables
        self.TRACKER = _util.ProgressTracker(self.number_of_tasks) #init the ProgressTracker
        
        #---Set the defaults of parameters used by Modeller
        self.Scenario = _mm.scenario #Default is primary scenario
                
    def page(self):
        pb = _tmgTPB.TmgToolPageBuilder(self, title="Populate Cordon Count Data v%s" %self.version,
                     description="Loads the cordon count results from a file for the \
                         purpose of validating traffic assignment. An extra attribute \
                         is created that stores the cordon counts on the relevant links.\
                         The difference in assigned volumes and counts can be visualized\
                         using the Link Layer in Desktop. (Bar Value = Volau - @cord).",
                     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='Scenario',
                               allow_none=False)        
    
        
        pb.add_header("CORDON DATA FILE")
        
        pb.add_select_file(tool_attribute_name='CordonTruthTable',
                           window_type='file', file_filter='*.csv',
                           title="Cordon Count File",
                           note="Requires three columns:\
                               <ul><li>countpost_id</li>\
                               <li>link id (form of inode-jnode)</li>\
                               <li>cordon_count</li></ul>")
                        
        return pb.render()
    
    def __call__(self, Scen, TruthTable):
        self.tool_run_msg = ""
        self.TRACKER.reset()

        self.Scenario = Scen
        self.CordonTruthTable = TruthTable
        
        try:            
            self._Execute()
        except Exception, e:
            self.tool_run_msg = _m.PageBuilder.format_exception(
                e, _traceback.format_exc(e))
            raise
        
        self.tool_run_msg = _m.PageBuilder.format_info("Done.")
class ReverseTransitLines(_m.Tool()):
    
    version = '1.0.0'
    tool_run_msg = ""
    number_of_tasks = 1 # For progress reporting, enter the integer number of tasks here
    
    #---PARAMETERS
    
    Scenario = _m.Attribute(_m.InstanceType) # common variable or parameter
    LineSelectorExpression = _m.Attribute(str)
    
    def __init__(self):
        #---Init internal variables
        self.TRACKER = _util.ProgressTracker(self.number_of_tasks) #init the ProgressTracker
        
        #---Set the defaults of parameters used by Modeller
        self.Scenario = _MODELLER.scenario #Default is primary scenario
        self.LineSelectorExpression = 'mode=r'
    
    ##########################################################################################################
    #---
    #---MODELLER INTERACE METHODS
    
    def page(self):
        pb = _tmgTPB.TmgToolPageBuilder(self, title="Reverse Transit Lines v%s" %self.version,
                     description="Reverses the itineraries of a subset of transit lines. It will \
                         try to preserve the line ID of the original line by appending or \
                         modifying the final character. Reports to the Logbook which new lines \
                         are reversed copies of which other lines.",
                     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='Scenario:',
                               allow_none=False)
        
        pb.add_text_box(tool_attribute_name= 'LineSelectorExpression',
                        size=100, multi_line= True,
                        title= "Line selector expression",
                        note= "Write a network calculator expression to select lines to reverse.")
        
        return pb.render()
    
    def run(self):
        self.tool_run_msg = ""
        self.TRACKER.reset()
        
        try:
            self._Execute()
        except Exception, e:
            self.tool_run_msg = _m.PageBuilder.format_exception(
                e, _traceback.format_exc(e))
            raise
        
        self.tool_run_msg = _m.PageBuilder.format_info("Done.")
class ReturnBoardingsAndWAW(_m.Tool()):

    version = '0.1.1'
    tool_run_msg = ""
    number_of_tasks = 1  # For progress reporting, enter the integer number of tasks here

    # Tool Input Parameters
    #    Only those parameters necessary for Modeller and/or XTMF to dock with
    #    need to be placed here. Internal parameters (such as lists and dicts)
    #    get initialized during construction (__init__)

    xtmf_ScenarioNumber = _m.Attribute(int)  # parameter used by XTMF only
    xtmf_LineAggregationFile = _m.Attribute(str)
    xtmf_ExportWAW = _m.Attribute(bool)

    NumberOfProcessors = _m.Attribute(int)

    def __init__(self):
        #---Init internal variables
        self.TRACKER = _util.ProgressTracker(
            self.number_of_tasks)  #init the ProgressTracker

        self.NumberOfProcessors = cpu_count()

    def page(self):
        pb = _m.ToolPageBuilder(self,
                                title="Return Boardings",
                                description="Cannot be called from Modeller.",
                                runnable=False,
                                branding_text="XTMF")

        return pb.render()

    ##########################################################################################################

    def __call__(self, xtmf_ScenarioNumber, xtmf_LineAggregationFile,
                 xtmf_ExportWAW):

        _m.logbook_write("Extracting boarding results")

        #---1 Set up scenario
        scenario = _m.Modeller().emmebank.scenario(xtmf_ScenarioNumber)
        if (scenario == 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.xtmf_LineAggregationFile = xtmf_LineAggregationFile
        self.xtmf_ExportWAW = xtmf_ExportWAW

        try:
            return self._Execute(scenario)
        except Exception, e:
            msg = str(e) + "\n" + _traceback.format_exc(e)
            raise Exception(msg)
Exemple #10
0
class ExportCountStationLocation(_m.Tool()):

    version = '0.1.1'
    tool_run_msg = ""
    number_of_tasks = 1
    Scenario = _m.Attribute(_m.InstanceType)
    CordonExportFile = _m.Attribute(str)

    def __init__(self):
        #---Init internal variables
        self.TRACKER = _util.ProgressTracker(
            self.number_of_tasks)  #init the ProgressTracker

        #---Set the defaults of parameters used by Modeller
        self.Scenario = _mm.scenario  #Default is primary scenario

    def page(self):
        pb = _tmgTPB.TmgToolPageBuilder(
            self,
            title="Export Count Station-Link Correspondence File v%s" %
            self.version,
            description="Exports a link and countpost correspondence file.\
                         Contained witin, is the link on which each countpost is found.\
                         Assumes that count stations are defined by '@stn1'.",
            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_header("EXPORT CORDON DATA FILE")

        pb.add_select_file(tool_attribute_name='CordonExportFile',
                           window_type='save_file',
                           file_filter='*.csv',
                           title="Cordon Count File",
                           note="Select Export Location:\
                               <ul><li>countpost_id</li>\
                               <li>link id (inode-jnode)</li>\
                               </ul>")

        return pb.render()

    def __call__(self, Scen, TruthTable):
        self.tool_run_msg = ""
        self.TRACKER.reset()

        self.Scenario = Scen
        self.CordonTruthTable = TruthTable

        try:
            self._Execute()
        except Exception, e:
            self.tool_run_msg = _m.PageBuilder.format_exception(
                e, _traceback.format_exc(e))
            raise

        self.tool_run_msg = _m.PageBuilder.format_info("Done.")
Exemple #11
0
class ShptoEmmeMap(_m.Tool()):
    version = '0.0.1'
    tool_run_msg = ""
    number_of_tasks = 1

    #Tool Parameters
    ShpFileName = _m.Attribute(str)
    MappingFileName = _m.Attribute(str)

    def __init__(self):
        #---Init internal variables
        self.TRACKER = _util.ProgressTracker(
            self.number_of_tasks)  #init the ProgressTracker

    def page(self):

        pb = _tmgTPB.TmgToolPageBuilder(
            self,
            title="GTFS Stops to Emme Node File v%s" % self.version,
            description=
            "Takes a shapefile and creates a mapping file that shows \
                             the node in the EMME network which it corresponds to. \
                             EXPERIMENTAL",
            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_file(tool_attribute_name="ShpFileName",
                           window_type='file',
                           file_filter="*.shp",
                           title="stops.shp file")

        pb.add_select_file(tool_attribute_name="MappingFileName",
                           window_type='save_file',
                           title="Map file to export")
        '''pb.add_select_file(tool_attribute_name="MappingfileName",
                           window_type='save_file',
                           title="Map file to export")'''
        return pb.render()

    def __call__(self, StopFileName, MappingFileName):
        self.StopsFileName = StopFileName
        self.MappingFileName = MappingFileName

        self.tool_run_msg = ""
        self.TRACKER.reset()

        try:
            self._Execute()
        except Exception, e:
            self.tool_run_msg = _m.PageBuilder.format_exception(
                e, _traceback.format_exc(e))
            raise

        self.tool_run_msg = _m.PageBuilder.format_info("Done.")
Exemple #12
0
class NodeEMMEmap(_m.Tool()):
    version = '0.0.1'
    tool_run_msg = ""
    number_of_tasks = 1

    #Tool Parameters
    FileName = _m.Attribute(str)
    MappingFileName = _m.Attribute(str)

    def __init__(self):
        #---Init internal variables
        self.TRACKER = _util.ProgressTracker(
            self.number_of_tasks)  #init the ProgressTracker

    def page(self):

        pb = _tmgTPB.TmgToolPageBuilder(
            self,
            title="GTFS Stops to Emme Node File v%s" % self.version,
            description=
            "Takes the <b>stops.txt</b> file and creates a mapping file that shows \
                             the node in the EMME network which it corresponds to.",
            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_file(
            tool_attribute_name="FileName",
            window_type='file',
            file_filter="*.txt *.shp",
            title=
            "The shp or stops.txt file that contains the stops information. Please note that the stops.txt file format should \
                           follow GTFS rules. The shp files also needs to contain the DBF field 'StopID'"
        )

        pb.add_select_file(tool_attribute_name="MappingFileName",
                           window_type='save_file',
                           title="Map file to export in csv format")
        '''pb.add_select_file(tool_attribute_name="MappingfileName",
                           window_type='save_file',
                           title="Map file to export")'''
        return pb.render()

    def run(self):
        self.tool_run_msg = ""
        self.TRACKER.reset()

        try:
            self._Execute()
        except Exception, e:
            self.tool_run_msg = _m.PageBuilder.format_exception(
                e, _traceback.format_exc(e))
            raise

        self.tool_run_msg = _m.PageBuilder.format_info("Done")
Exemple #13
0
class BKRCastExportAllAttributes(_modeller.Tool()):
    '''
    
    '''
    version = "1.0"  # this is the version
    default_path = ""
    tool_run_message = ""
    scenarios_list = _modeller.Attribute(_modeller.ListType)
    sola_specs_box = _modeller.Attribute(_modeller.StringType)

    def page(self):
        pb = _modeller.ToolPageBuilder(
            self,
            title="BKRCast Network Interface",
            description="SOLA Assignment on Multiple Scenarios",
            branding_text=
            "Modeling and Analysis Group -- City of Bellevue Transportation")
        pb.add_select_scenario("scenarios_list", title="Select scenarios")
        pb.add_sola_traffic_assignment_spec("sola_specs_box",
                                            title="Select specs")

        if self.tool_run_message != "":
            pb.tool_run_status(self.tool_run_msg_status)

        return pb.render()

    @_modeller.method(return_type=_modeller.UnicodeType)
    def tool_run_msg_status(self):
        return self.tool_run_message

    @property
    def current_scenario(self):
        return _modeller.Modeller().desktop.data_explorer(
        ).primary_scenario.core_scenario

    @property
    def current_emmebank(self):
        return self.current_scenario.emmebank

    def set_primary_scenario(self, scenarioID):
        '''set the scenario identified by scenarioID to the primary scenario.
        '''
        scenario = self.current_emmebank.scenario(scenarioID)
        _modeller.Modeller().desktop.data_explorer().replace_primary_scenario(
            scenario)

    def run(self):
        self.tool_run_message = ""
        try:
            self.__call__()
            run_message = "All attributes exported"
            self.tool_run_message += _modeller.PageBuilder.format_info(
                run_message)
        except Exception, e:
            self.tool_run_message += _modeller.PageBuilder.format_exception(
                e, _traceback.format_exc(e))
Exemple #14
0
class CheckScenarioFunctions(_m.Tool()):

    version = '0.0.1'
    tool_run_msg = ""
    number_of_tasks = 1  # For progress reporting, enter the integer number of tasks here

    # Tool Input Parameters
    #    Only those parameters neccessary for Modeller and/or XTMF to dock with
    #    need to be placed here. Internal parameters (such as lists and dicts)
    #    get intitialized during construction (__init__)

    xtmf_ScenarioNumber = _m.Attribute(int)  # parameter used by XTMF only
    Scenario = _m.Attribute(_m.InstanceType)  # common variable or parameter

    def __init__(self):
        #---Init internal variables
        self.TRACKER = _util.ProgressTracker(
            self.number_of_tasks)  #init the ProgressTracker

        #---Set the defaults of parameters used by Modeller
        self.Scenario = _MODELLER.scenario  #Default is primary scenario

    def page(self):
        pb = _tmgTPB.TmgToolPageBuilder(
            self,
            title="Check Scenario Functions v%s" % self.version,
            description=
            "Loads a scenario and checks that all referenced functions \
                         (link VDF, transit segment TTF, and turn TPF) are defined in the \
                         emmebank. It will raise an error listing all missing functions.",
            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='Scenario:',
                               allow_none=False)

        return pb.render()

    ##########################################################################################################

    def run(self):
        self.tool_run_msg = ""
        self.TRACKER.reset()

        try:
            self._Execute()
        except Exception, e:
            self.tool_run_msg = _m.PageBuilder.format_exception(
                e, _traceback.format_exc(e))
            raise

        self.tool_run_msg = _m.PageBuilder.format_info("Run complete.")
Exemple #15
0
class ConvertVDFs(_m.Tool()):

    version = '0.2.0'
    tool_run_msg = ""

    #---Special instance types
    scenario = _m.Attribute(_m.InstanceType)  #
    makeChangesPermanent = _m.Attribute(bool)  #

    def __init__(self):
        self.networkCalculator = _m.Modeller().tool(
            "inro.emme.network_calculation.network_calculator")

    def page(self):
        pb = _m.ToolPageBuilder(
            self,
            title="Convert VDFs v%s" % self.version,
            description=
            "Converts link classification types (stored as VDF ids) from \
                                DMG2001 to NCS11.",
            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 a scenario",
                               allow_none=False)

        pb.add_checkbox(
            tool_attribute_name="makeChangesPermanent",
            title="Make changes permanent?",
            note=
            "If unchecked, new VDF values will be stored in link extra attribute '@vdf'."
        )

        return pb.render()

    ##########################################################################################################

    def run(self):
        self.tool_run_msg = ""

        if self.makeChangesPermanent == None:  # Fix the checkbox problem
            self.makeChangesPermanent = False

        try:
            self._execute()
        except Exception, e:
            self.tool_run_msg = _m.PageBuilder.format_exception(
                e, _traceback.format_exc(e))
            raise

        self.tool_run_msg = _m.PageBuilder.format_info("Tool complete.")
class ExtractSelectLineMatrix(_m.Tool()):

    version = '0.2.0'
    tool_run_msg = ""
    number_of_tasks = 1  # For progress reporting, enter the integer number of tasks here

    #---Variable definitions
    xtmf_ScenarioNumber = _m.Attribute(int)
    xtmf_MatrixResultNumber = _m.Attribute(int)
    MatrixResultId = _m.Attribute(str)
    Scenario = _m.Attribute(_m.InstanceType)

    def __init__(self):
        #---Init internal variables
        self.TRACKER = _util.ProgressTracker(
            self.number_of_tasks)  #init the ProgressTracker

        #---Set the defaults of parameters used by Modeller
        self.Scenario = _MODELLER.scenario  #Default is primary scenario

    def page(self):
        pb = _tmgTPB.TmgToolPageBuilder(
            self,
            title="Extract Select Line Matrix",
            description="Extracts a select-line matrix for transit lines flagged\
                         by <b>@lflag</b>.",
            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='Scenario:',
                               allow_none=False)

        pb.add_select_new_matrix(tool_attribute_name='MatrixResultId',
                                 overwrite_existing=True,
                                 title="Result Matrix")

        return pb.render()

    def run(self):
        self.tool_run_msg = ""

        try:
            self._execute()
        except Exception, e:
            self.tool_run_msg = _m.PageBuilder.format_exception(
                e, _traceback.format_exc(e))
            raise

        self.tool_run_msg = _m.PageBuilder.format_info(
            "Analysis complete. Results stored in matrix %s." %
            self.MatrixResultId)
Exemple #17
0
class AdjacentNodes(_m.Tool()):

    north_angle = _m.Attribute(float)
    export_file = _m.Attribute(unicode)
    scenario = _m.Attribute(_m.InstanceType)
    tool_run_msg = ""

    def __init__(self):
        self.north_angle = 90

    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 run(self):
        self.tool_run_msg = ""
        try:
            self(self.north_angle, self.export_file, self.scenario)
            self.tool_run_msg = _m.PageBuilder.format_info("Tool completed.")
        except Exception, e:
            self.tool_run_msg += _m.PageBuilder.format_exception(
                e, _traceback.format_exc(e))
            raise
class ExportGtfsStopsAsShapefile(_m.Tool()):
    
    version = '0.0.1'
    tool_run_msg = ""
    number_of_tasks = 1 # For progress reporting, enter the integer number of tasks here
    
    # Tool Input Parameters
    #    Only those parameters neccessary for Modeller and/or XTMF to dock with
    #    need to be placed here. Internal parameters (such as lists and dicts)
    #    get intitialized during construction (__init__)
    
    GtfsFolderName = _m.Attribute(str)
    ShapefileName = _m.Attribute(str)
    
    def __init__(self):
        #---Init internal variables
        self.TRACKER = _util.ProgressTracker(self.number_of_tasks) #init the ProgressTracker
        
    
    def page(self):
        pb = _tmgTPB.TmgToolPageBuilder(self, title="Export GTFS Stops As Shapefile v%s" %self.version,
                     description="Converts the <b>stops.txt</b> file to a shapefile, flagging which \
                             modes it serves as well.",
                     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_file(tool_attribute_name="GtfsFolderName",
                           window_type='directory',
                           title="GTFS Folder")
        
        pb.add_select_file(tool_attribute_name="ShapefileName",
                           window_type='save_file',
                           title="Shapefile to export")
        
        return pb.render()
    
    ##########################################################################################################
        
    def run(self):
        self.tool_run_msg = ""
        self.TRACKER.reset()
        
        try:
            self._Execute()
        except Exception, e:
            self.tool_run_msg = _m.PageBuilder.format_exception(
                e, _traceback.format_exc(e))
            raise
        
        self.tool_run_msg = _m.PageBuilder.format_info("Done")
class ExportMatrix(_m.Tool()):

    MatrixId = _m.Attribute(int)
    Filename = _m.Attribute(str)
    ScenarioNumber = _m.Attribute(int)

    def __init__(self):
        self._tracker = _util.ProgressTracker(1)

    def page(self):
        pb = _m.ToolPageBuilder(self,
                                title="Export a matrix",
                                runnable=False,
                                description="Cannot be called from Modeller.",
                                branding_text="XTMF")

        return pb.render()

    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(e))

    @_m.method(return_type=_m.TupleType)
    def percent_completed(self):
        return self._tracker.getProgress()
Exemple #20
0
class ImportBoardingPenalties(_m.Tool()):

    BoardingsFile = _m.Attribute(str)
    Scenario = _m.Attribute(_m.InstanceType)
    ScenarioNumber = _m.Attribute(int)

    def __init__(self):
        try:
            self.netCalcTool = _m.Modeller().tool(
                "inro.emme.standard.network_calculation.network_calculator")
        except Exception, e:
            self.netCalcTool = _m.Modeller().tool(
                "inro.emme.network_calculation.network_calculator")
class CalculateStationFrequency(_m.Tool()):

    Scenario = _m.Attribute(_m.InstanceType)
    ScenarioId = _m.Attribute(str)
    Mode = _m.Attribute(str)
    ModeType = _m.Attribute(_m.InstanceType)
    FileName = _m.Attribute(str)
    tool_run_msg = ""

    def page(self):
        pb = _m.ToolPageBuilder(
            self,
            title="CalculateStationFrequency",
            description=
            "Calculates the number of transit vehicles passing by station centroids.",
            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",
                               allow_none=False)

        pb.add_select_mode(
            tool_attribute_name="ModeType",
            title="Select mode",
            filter=["TRANSIT"],
            note="Select a mode with station centroids (e.g., subway)",
            allow_none=False)

        pb.add_select_file(tool_attribute_name="FileName",
                           window_type="save_file",
                           file_filter="*.txt",
                           start_path="C:/",
                           title="Save file",
                           note="Select a text file to save.")
        #_m.Modeller().desktop.project_file_name()

        return pb.render()

    def run(self):
        self.tool_run_msg = ""

        try:
            s = self(self.Scenario.id, self.ModeType.id, self.FileName)
            self.tool_run_msg = _m.PageBuilder.format_info(s)
        except Exception, e:
            self.tool_run_msg = _m.PageBuilder.format_exception(
                e, _traceback.format_exc(e))
            raise
Exemple #22
0
class DeleteMatrix(_m.Tool()):
    version = '0.0.1'
    Scenario = _m.Attribute(int)

    def page(self):
        pb = _m.ToolPageBuilder(self,
                                title="Delete Matrix",
                                runnable=False,
                                description="Cannot be called from Modeller.",
                                branding_text="XTMF")

        return pb.render()

    def run(self):
        pass

    def __call__(self, Scenario):
        try:
            self._execute(Scenario)
        except Exception as e:
            raise Exception(_traceback.format_exc())

    def _execute(self, Scenario):
        project = _MODELLER.emmebank
        scenario = project.scenario(str(Scenario))
        if scenario is None:
            print "A delete was requested for scenario " + str(
                Scenario) + " but the scenario does not exist."
            return
        if scenario.delete_protected == True:
            scenario.delete_protected = False
        project.delete_scenario(scenario.id)
class CheckConnectorSpeeds(_m.Tool()):

    Scenario = _m.Attribute(_m.InstanceType)
    tool_run_msg = ""

    @_m.method(return_type=unicode)
    def tool_run_msg_status(self):
        return self.tool_run_msg

    def page(self):
        pb = _m.ToolPageBuilder(
            self,
            title="Check connector speeds",
            description=
            "Checks that all connectors are set to 40 km/hr as per NCS11.<br><br>\
                                 Reports any errors in the logbook.",
            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",
                               allow_none=False)

        return pb.render()

    def run(self):
        self.tool_run_msg = ""
        try:
            self()
        except Exception, e:
            self.tool_run_msg = _m.PageBuilder.format_exception(
                e, _traceback.format_exc(e))
            raise
Exemple #24
0
class CheckLinkLanes(_m.Tool()):

    Scenario = _m.Attribute(_m.InstanceType)
    tool_run_msg = ""

    @_m.method(return_type=unicode)
    def tool_run_msg_status(self):
        return self.tool_run_msg

    def page(self):
        pb = _m.ToolPageBuilder(
            self,
            title="Check Link lanes",
            description=
            "Checks that special link type (centroid connectors, transit-only links) \
                                 meet NCS11 requirements.<br><br> Reports any errors in the logbook.",
            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",
                               allow_none=False)

        return pb.render()

    def run(self):
        self.tool_run_msg = ""
        try:
            self()
        except Exception, e:
            self.tool_run_msg = _m.PageBuilder.format_exception(
                e, _traceback.format_exc(e))
            raise
Exemple #25
0
class ExportNetworkPackage(_m.Tool()):
    version = '1.2.1'
    tool_run_msg = ""
    number_of_tasks = 11  # For progress reporting, enter the integer number of tasks here

    xtmf_JSON = _m.Attribute(str)
    xtmf_logbook_level = _m.Attribute(str)

    def __init__(self):
        # Init internal variables
        self.TRACKER = _util.ProgressTracker(
            self.number_of_tasks)  # init the ProgressTracker

        # Set the defaults of parameters used by Modeller
        self.Scenario = _MODELLER.scenario  # Default is primary scenario
        self.ExportMetadata = ""

    def page(self):
        return ""

    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)
        finally:
class BKRCastExportNetwork(_modeller.Tool()):
    '''
    this tool is to populate AM, MD and PM peak hour network and their associated network
    input files in EMME punch file format.
    Files will be produced:
      base network file, link shape file, turn file, and transit lines for AM, MD, PM and NI.
    1.1.0: populate vdf functions for four TOD.
    1.1.1: populate sc_headway.csv
    1.1.2: remove future bike links with modes == "wk" and @biketype == 0
    '''
    version = "1.1.2"  # this is the version
    default_path = ""
    tool_run_message = ""
    outputFolder = _modeller.Attribute(_modeller.InstanceType)

    def page(self):
        pb = _modeller.ToolPageBuilder(
            self,
            title="BKRCast Network Interface",
            description="Populate networks from master network",
            branding_text=
            "Modeling and Analysis Group -- City of Bellevue Transportation")
        pb.add_select_file("outputFolder",
                           "directory",
                           "",
                           self.default_path,
                           title="Select the directory for output files")

        if self.tool_run_message != "":
            pb.tool_run_status(self.tool_run_msg_status)

        return pb.render()

    @_modeller.method(return_type=_modeller.UnicodeType)
    def tool_run_msg_status(self):
        return self.tool_run_message

    @property
    def current_scenario(self):
        return _modeller.Modeller().desktop.data_explorer(
        ).primary_scenario.core_scenario

    @property
    def current_emmebank(self):
        return self.current_scenario.emmebank

    def run(self):
        self.tool_run_message = ""
        try:
            self.__call__()
            run_message = "Network exported"
            self.tool_run_message += _modeller.PageBuilder.format_info(
                run_message)
        except Exception, e:
            self.tool_run_message += _modeller.PageBuilder.format_exception(
                e, _traceback.format_exc(e))
Exemple #27
0
class ConvertVehicles(_m.Tool()):

    version = '0.1.2'
    tool_run_msg = ""

    #---Variable definitions
    ScenarioNumber = _m.Attribute(int)

    #---Special instance types
    scenario = _m.Attribute(_m.InstanceType)  #

    def page(self):
        pb = _m.ToolPageBuilder(
            self,
            title="Convert Vehicles v%s" % self.version,
            description="Converts vehicle definitions and properties \
                                    according to NCS11 definitions.",
            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",
                               allow_none=False)

        return pb.render()

    ##########################################################################################################

    def run(self):
        self.tool_run_msg = ""
        '''Run is called from Modeller.'''
        self.isRunningFromXTMF = False

        try:
            self._execute()
        except Exception, e:
            self.tool_run_msg = _m.PageBuilder.format_exception(
                e, _traceback.format_exc(e))
            raise

        self.tool_run_msg = _m.PageBuilder.format_info("Run complete.")
Exemple #28
0
class CopyScenario(_m.Tool()):
    version = '0.0.1'
    FromScenario = _m.Attribute(int)
    ToScenario = _m.Attribute(int)
    CopyStrategy = _m.Attribute(bool)

    def page(self):
        pb = _m.ToolPageBuilder(self,
                                title="Copy Scenario",
                                runnable=False,
                                description="Cannot be called from Modeller.",
                                branding_text="XTMF")

        return pb.render()

    def run(self):
        pass

    def __call__(self, FromScenario, ToScenario, CopyStrategy):
        try:
            self._execute(FromScenario, ToScenario, CopyStrategy)
        except Exception as e:
            raise Exception(_traceback.format_exc(e))

    def _execute(self, FromScenario, ToScenario, CopyStrategy):
        if FromScenario == ToScenario:
            print "A copy was requested to from scenario " + str(FromScenario) + " to " + str(ToScenario) \
                + ".  This was not executed."
            return
        project = _MODELLER.emmebank
        original = project.scenario(str(FromScenario))
        if original is None:
            raise Exception("The base scenario '"+str(FromScenario)+"' does not exist in order to copy to scenario '" \
                            + str(ToScenario)+"'!")
        dest = project.scenario(str(ToScenario))
        if dest is not None:
            project.delete_scenario(dest.id)
        if CopyStrategy == True:
            project.copy_scenario(original.id, str(ToScenario), True, True,
                                  True)
        else:
            project.copy_scenario(original.id, str(ToScenario), True, False,
                                  True)
class Calculate_fitness(_m.Tool()):
    version = '1.0.0'
    tool_run_msg = ""
    number_of_tasks = 1

    EMME2TTS_file = _m.Attribute(str)
    Obs_paths_file = _m.Attribute(str)
    EMME_paths_file = _m.Attribute(str)
    fitness_csv_file = _m.Attribute(str)
    beta = _m.Attribute(float)

    def __init__(self):
        #---Init internal variables
        self.TRACKER = _util.ProgressTracker(
            self.number_of_tasks)  #init the ProgressTracker

        #---Set the defaults of parameters used by Modeller
        self.Scenario = _MODELLER.scenario  #Default is primary scenario

    def page(self):
        pb = _m.ToolPageBuilder(self,
                                title="Calculate Fitness",
                                description="Cannot be called from Modeller.",
                                runnable=False,
                                branding_text="XTMF")

        return pb.render()

    def __call__(self, EMME2TTS_file, Obs_paths_file, EMME_paths_file,
                 fitness_csv_file, beta):
        print "Calculating Fitness"
        #EMME2TTS = convert_id("2011_Emme2TTS_Line.csv")
        #ObservedPaths = read_obs_paths("TripDataObsAM.csv")
        #EMMEpath_details = read_EMME_paths("pathDetails", EMME2TTS)

        EMME2TTS = convert_id(EMME2TTS_file)
        ObservedPaths = read_obs_paths(Obs_paths_file)
        EMMEpath_details = read_EMME_paths(EMME_paths_file, EMME2TTS)
        calculate_fitness(EMMEpath_details, ObservedPaths, fitness_csv_file,
                          beta)

    def _Execute(EMME_paths_file, Obs_paths_file, EMME2TTSfile, beta):
        self.TRACKER.completeTask()
Exemple #30
0
class MoveNetowrks(_m.Tool()):
    
    Scenarios = _m.Attribute(_m.ListType)
    tool_run_msg = ""
    
    def page(self):
        pb = _m.ToolPageBuilder(self, title="Move Networks",
                     description="Moves selected networks up by 4,000,000 meters; essentially \
                             adding a 7th digit to the y-coordinate to make the projection \
                             compatible with UTM-17N.<br>\
                             <br><b>This tool is irreversible. Make sure to copy your \
                             scenarios prior to running!</b>",
                     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="Scenarios",
                               title="Select scenarios",
                               allow_none=False)
        
        return pb.render()
    
    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, 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, e:
            self.tool_run_msg = _m.PageBuilder.format_exception(
                e, _traceback.format_exc(e))
            raise