def __init__(self, ident='shapedata', parent=None, name='Shapefile data',
                 filepath="",
                 projparams_shape="+init=EPSG:23032",
                 offset=[0.0, 0.0],
                 shapetype=3,
                 log=None, **kwargs):

        self._init_objman(ident=ident,
                          parent=parent,
                          name=name,
                          version=0.0,
                          **kwargs)

        self.add(cm.AttrConf('filepath', filepath,
                             groupnames=['params', ],
                             perm='rw',
                             name='Shape file',
                             wildcards='Shape files (*.shp)|*.shp',
                             metatype='filepath',
                             info="""Shape file path.""",
                             ))

        self.add(cm.AttrConf('_projparams', projparams_shape,
                             groupnames=['params', ],
                             perm='rw',
                             name='Projection',
                             info='Projection parameters'
                             ))

        self.add(cm.AttrConf('_offset', offset,
                             groupnames=['params', ],
                             perm='r',
                             name='Offset',
                             info='Offset in WEP coordinates'
                             ))

        self.add(cm.AttrConf('shapetype', shapetype,
                             groupnames=['params', ],
                             choices=SHAPETYPES,
                             perm='rw',
                             name='Shape Type',
                             info='Shape  type.'
                             ))

        # todo: make these init dependent on shapetype
        if shapetype == 1:  # 'Point':1,

            self.add_col(am.ArrayConf('coords',  np.zeros(3, dtype=np.float32),
                                      dtype=np.float32,
                                      groupnames=['_private'],
                                      perm='rw',
                                      name='Coords',
                                      unit='m',
                                      info='Point coordinates.',
                                      ))
        else:
            self.add_col(am.ListArrayConf('shapes',
                                          groupnames=['_private'],
                                          perm='rw',
                                          name='Shape',
                                          unit='deg',
                                          info='Shape is a list of coordinates.',
                                          #is_plugin = True,
                                          xmltag='shape',
                                          ))

        self._log = log

        self._init_attributes()
        self._init_constants()
Ejemplo n.º 2
0
    def __init__(self,
                 ident='shapefileimporter',
                 parent=None,
                 name='Shape file importer',
                 filepath='',
                 coordsattr='',
                 attrnames_to_shapeattrs={},
                 info='Import of shape files in parent datastructure.',
                 logger=None,
                 **kwargs):

        print 'ShapefileImporter.__init__', filepath  # ,projparams_target_default, projparams_shape
        self._init_common(
            ident,
            parent=parent,
            name=name,
            logger=logger,
            info=info,
        )

        attrsman = self.set_attrsman(cm.Attrsman(self))

        self.filepath = attrsman.add(
            cm.AttrConf(
                'filepath',
                filepath,
                groupnames=['options'],
                perm='rw',
                name='Shape file',
                wildcards='Shape file (*.shp)|*.shp|All files (*.*)|*.*',
                metatype='filepath',
                info=
                """File path of shape file. Note that only the file with the extention ".shp" needs to be selected. Attention: all file extensions must be in small letters, for example .shp .dbf, shx, etc""",
            ))

        # print 'self.filepath',self.filepath
        attrsman_parent = parent.get_attrsman()
        self._coordsconfig = attrsman_parent.get_config(coordsattr)

        for attrname, shapeattr_default in attrnames_to_shapeattrs.iteritems():
            config = attrsman_parent.get_config(attrname)
            fieldname = 'fieldname_' + attrname
            setattr(
                self, fieldname,
                attrsman.add(
                    cm.AttrConf(
                        fieldname,
                        shapeattr_default,
                        groupnames=['options', 'field names'],
                        perm='rw',
                        attrname_orig=attrname,
                        name='Field for ' + config.get_name(),
                        info='Field name for the following attribute: ' +
                        config.get_info(),
                    )))

        self.projparams_shape = attrsman.add(
            cm.AttrConf(
                'projparams_shape',
                kwargs.get("projparams_shape", ''),
                groupnames=[
                    'options',
                ],
                perm='rw',
                name='Shape projection',
                info=
                'Projection4 parameters of shape data. If blank then shape file projection is used or if not present, projection will be guessed from shape coordinates.',
            ))

        # self.projparams_target = attrsman.add(cm.AttrConf(  'projparams_target', kwargs.get("projparams_target",''),
        #                                                groupnames = ['options',],
        #                                                perm='rw',
        #                                                name = 'Target projection',
        #                                                info = 'Projection4 parameters of target, where the coordinates are imported. These are typically the scenario coordinates.',
        #                                                ))

        self._projparams_target = kwargs.get("projparams_target", '')
        self.is_use_shapeproj = attrsman.add(
            cm.AttrConf(
                'is_use_shapeproj',
                kwargs.get("is_use_shapeproj", False),
                groupnames=[
                    'options',
                ],
                perm='rw',
                name='Use shapefile projection?',
                info=
                'If selected, projection in shape file will be used to interpret projection. If not selected, target projection will be used.',
            ))

        self.is_use_targetproj = attrsman.add(
            cm.AttrConf(
                'is_use_targetproj',
                kwargs.get("is_use_targetproj", True),
                groupnames=[
                    'options',
                ],
                perm='rw',
                name='Use target projection?',
                info=
                'If selected, target will be used to interpret projection.',
            ))

        self.is_probe_offset = attrsman.add(
            cm.AttrConf(
                'is_probe_offset',
                kwargs.get("is_probe_offset", False),
                groupnames=[
                    'options',
                ],
                perm='rw',
                name='Probe offset?',
                info=
                """With probe offset, a specific coordinate from the shap-map and the target-map will be used to calculate the offset. 
                                                                  This requires the coordinates of a dedicated point of the shape file and of the target.
                                                                  This method can be used if there is an unknon offset in the shape map coordinate system.
                                                                  """,
            ))

        self.x_probe_shape = attrsman.add(
            cm.AttrConf(
                'x_probe_shape',
                kwargs.get("x_probe_shape", 0.0),
                groupnames=[
                    'options',
                ],
                perm='rw',
                name='Probed x coord of shape',
                unit='m',
                info='Probed x coord of shape-map.',
            ))

        self.y_probe_shape = attrsman.add(
            cm.AttrConf(
                'y_probe_shape',
                kwargs.get("y_probe_shape", 0.0),
                groupnames=[
                    'options',
                ],
                perm='rw',
                name='Probed y coord shape',
                unit='m',
                info='Probed y coord of shape-map.',
            ))

        self.x_probe_target = attrsman.add(
            cm.AttrConf(
                'x_probe_target',
                kwargs.get("x_probe_target", 0.0),
                groupnames=[
                    'options',
                ],
                perm='rw',
                name='Probed x coord of target',
                unit='m',
                info='Probed x coord of target-map.',
            ))

        self.y_probe_target = attrsman.add(
            cm.AttrConf(
                'y_probe_target',
                kwargs.get("y_probe_target", 0.0),
                groupnames=[
                    'options',
                ],
                perm='rw',
                name='Probed y coord target',
                unit='m',
                info='Probed y coord of target-map.',
            ))

        self.is_autoffset = attrsman.add(
            cm.AttrConf(
                'is_autoffset',
                kwargs.get("is_autoffset", False),
                groupnames=[
                    'options',
                ],
                perm='rw',
                name='Auto offset?',
                info='If selected, offset will be determined automatically.',
            ))

        # self.offset = attrsman.add(cm.AttrConf(  'offset', kwargs.get("offset",np.array([0.0,0.0,0.0],dtype = np.float32)),
        #                                                groupnames = ['options',],
        #                                                perm='r',
        #                                                name = 'Offset',
        #                                                unit = 'm',
        #                                                info = 'Network offset in WEP coordinates',
        #                                                ))

        self._offset = kwargs.get("offset",
                                  np.array([0.0, 0.0, 0.0], dtype=np.float32))

        self.is_limit_to_boundaries = attrsman.add(
            cm.AttrConf(
                'is_limit_to_boundaries',
                kwargs.get("is_limit_to_boundaries", True),
                groupnames=[
                    'options',
                ],
                perm='rw',
                name='Limit to boundaries?',
                info='Import only shapes that fit into the given boundaries.',
            ))

        # self.boundaries = attrsman.add(cm.AttrConf(  'boundaries',kwargs.get('boundaries',np.array([0.0,0.0,0.0,0.0],dtype = np.float32)) ,
        #                                groupnames = ['options',],
        #                                perm='r',
        #                                name = 'Boundaries',
        #                                unit = 'm',
        #                                info = 'Area limiting boundaries',
        #                                ))
        self.boundaries = kwargs.get(
            'boundaries', np.array([0.0, 0.0, 0.0, 0.0], dtype=np.float32))
    def __init__(self,  filepath,
                 coordsconfig,
                 map_attrconfig2shapeattr=None,
                 attrconfigs=None,
                 ident='shapefileimporter', parent=None,
                 name='Shapefile importer',
                 info='Import of shape files',
                 logger=None,
                 **kwargs):

        self._filepath = filepath
        self._sf = get_shapefile(filepath)
        projparams_shape = get_proj4_from_shapefile(filepath)
        projparams_target_default = self.guess_targetproj()

        print 'ShapefileImporter.__init__', filepath  # ,projparams_target_default, projparams_shape
        self._init_common(ident,
                          parent=parent,
                          name=name,
                          logger=logger,
                          info='Import workouts and GPS points of a European cycling challange.',
                          )

        attrsman = self.set_attrsman(cm.Attrsman(self))

        # if projparams_target == '':
        #    projparams_target = ''
        #    is_guess_targetproj = True
        #    is_use_shapeproj = False

        #projparams_shape = projparams_shapefile

        self.make_fieldinfo()

        # self.id_mode = attrsman.add(am.AttrConf('id_mode',  modechoices['bicycle'],
        #                                groupnames = ['options'],
        #                                choices = modechoices,
        #                                name = 'Mode',
        #                                info = 'Transport mode to be matched.',
        #                                ))

        self.filepath = attrsman.add(
            cm.AttrConf('filepath', filepath,
                        groupnames=['parameters'],
                        perm='r',
                        name='Shape file',
                        wildcards='Shape file (*.shp)|*.shp',
                        metatype='filepath',
                        info="""File path of shape file.""",
                        ))

        self.projparams_shape = attrsman.add(cm.AttrConf('projparams_shape', projparams_shape,
                                                         groupnames=['parameters', ],
                                                         perm='rw',
                                                         name='Shape projection',
                                                         info='Projection4 parameters of shape data.',
                                                         ))

        self.is_guess_targetproj = attrsman.add(cm.AttrConf('is_guess_targetproj', kwargs.get("is_guess_targetproj", True),
                                                            groupnames=['parameters', ],
                                                            perm='r',
                                                            name='Guess target projection?',
                                                            info='If selected, target projection will be guessed based on coordinates of the shapefile.',
                                                            ))

        self.projparams_target = attrsman.add(cm.AttrConf('projparams_target', kwargs.get("projparams_target", projparams_target_default),
                                                          groupnames=['parameters', ],
                                                          perm='r',
                                                          name='Target projection',
                                                          info='Projection4 parameters of target, where the coordinates are imported. These are typically the scenario coordinates.',
                                                          ))

        self.is_use_shapeproj = attrsman.add(cm.AttrConf('is_use_shapeproj', kwargs.get("is_use_shapeproj", False),
                                                         groupnames=['parameters', ],
                                                         perm='r',
                                                         name='Use shapefile projection?',
                                                         info='If selected, projection in shape file will be used to interpret projection. If not selected, target projection will be used.',
                                                         ))

        self.is_use_targetproj = attrsman.add(cm.AttrConf('is_use_targetproj', kwargs.get("is_use_targetproj", True),
                                                          groupnames=['parameters', ],
                                                          perm='r',
                                                          name='Use target projection?',
                                                          info='If selected, target will be used to interpret projection.',
                                                          ))

        self.is_autoffset = attrsman.add(cm.AttrConf('is_autoffset', kwargs.get("is_autoffset", True),
                                                     groupnames=['parameters', ],
                                                     perm='r',
                                                     name='Auto offset?',
                                                     info='If selected, offset will be determined automatically.',
                                                     ))

        self.offset = attrsman.add(cm.AttrConf('offset', kwargs.get("offset", np.array([0.0, 0.0, 0.0], dtype=np.float32)),
                                               groupnames=['parameters', ],
                                               perm='r',
                                               name='Offset',
                                               info='Network offset in WEP coordinates',
                                               ))

        self._coordsconfig = coordsconfig

        if map_attrconfig2shapeattr is None:
            # generate attrconfs with group 'options'
            # and default attrconfmap
            self._map_attrconfig2shapeattr = {}

        else:
            self._map_attrconfig2shapeattr = map_attrconfig2shapeattr
Ejemplo n.º 4
0
    def add_plotoptions(self, **kwargs):

        attrsman = self.get_attrsman()
        plottypes = ['arrows', 'polygons']
        self.plottype = attrsman.add(
            cm.AttrConf(
                'plottype',
                kwargs.get('plottype', 'arrows'),
                choices=plottypes,
                groupnames=['options'],
                name='Plot types',
                info='Plot type representing the results.',
            ))

        self.is_show_title = attrsman.add(
            cm.AttrConf(
                'is_show_title',
                kwargs.get('is_show_title', True),
                groupnames=['options'],
                name='Show tile',
                info='Shows title and unit.',
            ))

        self.size_titlefont = attrsman.add(
            cm.AttrConf(
                'size_titlefont',
                kwargs.get('size_titlefont', 32),
                groupnames=['options'],
                name='Title fontsize',
                info='Title fontsize.',
            ))

        self.size_labelfont = attrsman.add(
            cm.AttrConf(
                'size_labelfont',
                kwargs.get('size_labelfont', 24),
                groupnames=['options'],
                name='Label fontsize',
                info='Label fontsize.',
            ))

        self.resultwidth = attrsman.add(
            cm.AttrConf(
                'resultwidth',
                kwargs.get('resultwidth', 10.0),
                groupnames=['options'],
                name='Result width',
                unit='m',
                info='Maximum width of graphical resuls on map.',
            ))

        self.length_arrowhead = attrsman.add(
            cm.AttrConf(
                'length_arrowhead',
                kwargs.get('length_arrowhead', 10.0),
                groupnames=['options'],
                name='Arrow length',
                unit='m',
                info='Length of arrowhead on result map.',
            ))

        self.is_widthvalue = attrsman.add(
            cm.AttrConf(
                'is_widthvalue',
                kwargs.get('is_widthvalue', False),
                groupnames=['options'],
                name='Value width?',
                info=
                'If True, the arrow width of the graphical representation is proportional to the result value.',
            ))

        self.is_colorvalue = attrsman.add(
            cm.AttrConf(
                'is_colorvalue',
                kwargs.get('is_colorvalue', True),
                groupnames=['options'],
                name='Value color?',
                info=
                'If True, the arrows of the graphical representation are filled with a colour representing the result value.',
            ))

        self.color_outline = attrsman.add(
            cm.AttrConf(
                'color_outline',
                kwargs.get('color_outline',
                           np.array([0.0, 0.0, 0.0, 0.95], dtype=np.float32)),
                groupnames=['options'],
                perm='wr',
                metatype='color',
                name='Outline color',
                info=
                'Outline color of result arrows in graphical representation. Only valid if no color-fill is chosen.',
            ))

        self.color_fill = attrsman.add(
            cm.AttrConf(
                'color_fill',
                kwargs.get('color_fill',
                           np.array([0.3, 0.3, 1.0, 0.95], dtype=np.float32)),
                groupnames=['options'],
                perm='wr',
                metatype='color',
                name='Fill color',
                info='Fill color of result arrows in graphical representation.',
            ))

        self.alpha_results = attrsman.add(
            cm.AttrConf(
                'alpha_results',
                kwargs.get('alpha_results', 0.8),
                groupnames=['options'],
                name='Result transparency',
                info=
                'Transparency of result arrows in graphical representation.',
            ))

        self.printformat = attrsman.add(
            cm.AttrConf(
                'printformat',
                kwargs.get('printformat', '%.1f'),
                choices=OrderedDict([
                    ('Show no values', ''),
                    ('x', '%.d'),
                    ('x.x', '%.1f'),
                    ('x.xx', '%.2f'),
                    ('x.xxx', '%.3f'),
                    ('x.xxxx', '%.4f'),
                ]),
                groupnames=['options'],
                name='Label formatting',
                info=
                'Print formatting of value label in graphical representation.',
            ))

        self.color_label = attrsman.add(
            cm.AttrConf(
                'color_label',
                kwargs.get('color_label',
                           np.array([0, 0, 0, 1], dtype=np.float32)),
                groupnames=['options'],
                perm='wr',
                metatype='color',
                name='Label color',
                info='Color of value label in graphical representation.',
            ))

        self.is_show_network = attrsman.add(
            cm.AttrConf(
                'is_show_network',
                kwargs.get('is_show_network', True),
                groupnames=['options'],
                name='Show network',
                info='Shows a schematic network in the background.',
            ))

        self.color_network = attrsman.add(
            cm.AttrConf(
                'color_network',
                kwargs.get('color_network',
                           np.array([0.8, 0.8, 0.8, 0.8], dtype=np.float32)),
                groupnames=['options'],
                perm='wr',
                metatype='color',
                name='Network color',
                info='Outline color of schematic network in the background.',
            ))

        self.color_nodes = attrsman.add(
            cm.AttrConf(
                'color_nodes',
                kwargs.get('color_nodes',
                           np.array([1, 1, 1, 1], dtype=np.float32)),
                groupnames=['options'],
                perm='wr',
                metatype='color',
                name='Nodes color',
                info=
                'Color of simplified nodes (or juctions in the background.',
            ))
        self.alpha_net = attrsman.add(
            cm.AttrConf(
                'alpha_net',
                kwargs.get('alpha_net', 0.5),
                groupnames=['options'],
                name='Net transparency',
                info=
                'Transparency of network (edges and nodes) in graphical representation.',
            ))

        self.is_show_facilities = attrsman.add(
            cm.AttrConf(
                'is_show_facilities',
                kwargs.get('is_show_facilities', True),
                groupnames=['options'],
                name='Show facilities',
                info=
                'Shows a schematic facilities (buildings, parks, etc.) in the background.',
            ))

        self.color_facilities = attrsman.add(
            cm.AttrConf(
                'color_facilities',
                kwargs.get('color_facilities',
                           np.array([1, 1, 1, 1], dtype=np.float32)),
                groupnames=['options'],
                perm='wr',
                metatype='color',
                name='Facilities color',
                info='Color of schematic facilities in the background.',
            ))

        self.alpha_facilities = attrsman.add(
            cm.AttrConf(
                'alpha_facilities',
                kwargs.get('alpha_facilities', 0.5),
                groupnames=['options'],
                name='Facility transparency',
                info='Transparency of facilities in graphical representation.',
            ))

        self.color_borders = attrsman.add(
            cm.AttrConf(
                'color_borders',
                kwargs.get('color_borders',
                           np.array([0.7, 0.7, 0.7, 0.8], dtype=np.float32)),
                groupnames=['options'],
                perm='wr',
                metatype='color',
                name='Border color',
                info=
                'Facility border (or building walls) color of schematic facilities in the background.',
            ))

        self.color_background = attrsman.add(
            cm.AttrConf(
                'color_background',
                kwargs.get('color_background',
                           np.array([1, 1, 1, 1], dtype=np.float32)),
                groupnames=['options'],
                perm='wr',
                metatype='color',
                name='Background color',
                info='Background color of schematic network in the background.',
            ))

        self.is_show_maps = attrsman.add(
            cm.AttrConf(
                'is_show_maps',
                kwargs.get('is_show_maps', False),
                groupnames=['options'],
                name='Show map?',
                info=
                'If True, shows map as background in graphical representation. This feature requires that maps have been previously downloaded.',
            ))

        self.alpha_maps = attrsman.add(
            cm.AttrConf(
                'alpha_maps',
                kwargs.get('alpha_maps', 0.5),
                groupnames=['options'],
                name='Map transparency',
                info=
                'Transparency of background maps in graphical representation.',
            ))

        self.is_grid = attrsman.add(
            cm.AttrConf(
                'is_grid',
                kwargs.get('is_grid', False),
                groupnames=['options'],
                name='Show grid?',
                info='If True, shows a grid on the graphical representation.',
            ))

        self.axis = None
Ejemplo n.º 5
0
    def __init__(self, mapmatching, logger=None, **kwargs):
        print 'EccTracesImporter.__init__', mapmatching.get_ident()
        self._init_common(
            'traceimporter',
            parent=mapmatching,
            name='ECC Trace Importer',
            logger=logger,
            info=
            'Import workouts and GPS points of a European cycling challange.',
        )

        attrsman = self.set_attrsman(cm.Attrsman(self))

        scenario = mapmatching.get_scenario()
        rootfilepath = scenario.get_rootfilepath()

        # here we ged classes not vehicle type
        # specific vehicle type within a class will be generated later
        modechoices = scenario.net.modes.names.get_indexmap()

        # print '  modechoices',modechoices
        self.id_mode = attrsman.add(
            am.AttrConf(
                'id_mode',
                modechoices['bicycle'],
                groupnames=['options'],
                choices=modechoices,
                name='Mode',
                info='Transport mode to be matched.',
            ))

        self.workoutsfilepath = attrsman.add(
            cm.AttrConf(
                'workoutsfilepath',
                kwargs.get('workoutsfilepath', rootfilepath + '.workouts.csv'),
                groupnames=['options'],
                perm='rw',
                name='Workout file',
                wildcards='CSV file (*.csv)|*.csv',
                metatype='filepath',
                info="""CSV text file with workout database.""",
            ))

        self.pointsfilepath = attrsman.add(
            cm.AttrConf(
                'pointsfilepath',
                kwargs.get('pointsfilepath', rootfilepath + '.points.csv'),
                groupnames=['options'],
                perm='rw',
                name='Points file',
                wildcards='CSV file (*.csv)|*.csv',
                metatype='filepath',
                info="CSV text file with GPS point database.",
            ))

        self.year = attrsman.add(
            cm.AttrConf(
                'year',
                kwargs.get('year', 2014),
                groupnames=['options'],
                choices={
                    '2014': 2014,
                    'from 2015': 2015
                },
                perm='rw',
                name='Year of challange',
                info=
                'Year of challange is used to identify the correct database format.',
            ))

        self.dist_trip_min = attrsman.add(
            cm.AttrConf(
                'dist_trip_min',
                kwargs.get('dist_trip_min', 100.0),
                groupnames=['options'],
                perm='rw',
                name='Min. trip distance',
                unit='m',
                info=
                'Minimum distance of one trip. Shorter trips will not be imported.',
            ))

        self.duration_trip_min = attrsman.add(
            cm.AttrConf(
                'duration_trip_min',
                kwargs.get('duration_trip_min', 30.0),
                groupnames=['options'],
                perm='rw',
                name='Min. trip duration',
                unit='s',
                info=
                'Minimum duration of one trip. Trips with shorter duration will not be imported.',
            ))

        self.speed_trip_min = attrsman.add(
            cm.AttrConf(
                'speed_trip_min',
                kwargs.get('speed_trip_min', 3.0),
                groupnames=['options'],
                perm='rw',
                name='Min. av. trip speed',
                unit='m/s',
                info=
                'Minimum average trip speed. Trips with lower average speed will not be imported.',
            ))

        self.speed_trip_max = attrsman.add(
            cm.AttrConf(
                'speed_trip_max',
                kwargs.get('speed_trip_max', 50.0),
                groupnames=['options'],
                perm='rw',
                name='Max. av. trip speed',
                unit='m/s',
                info=
                'Maximum average trip speed. Trips with higher average speed will not be imported.',
            ))

        self.sep_column_workout = attrsman.add(
            cm.AttrConf(
                'sep_column_workout',
                kwargs.get('sep_column_workout', ','),
                groupnames=['options'],
                perm='rw',
                name='Workoutdata seperator',
                info='Workout column seperator of CSV file',
            ))

        self.sep_column_points = attrsman.add(
            cm.AttrConf(
                'sep_column_points',
                kwargs.get('sep_column_points', ','),
                groupnames=['options'],
                perm='rw',
                name='Point data seperator',
                info='Pointdata column seperator of CSV file',
            ))
Ejemplo n.º 6
0
    def __init__(self, parent, mainframe=None):
        """
        To be overridden by specific tool.
        """
        self.init_common(
            'ptlineadder',
            parent,
            'Add PT line',
            info="""Tool to add public transport lines
                                1. Edit all parameters in the options panel.
                                2. Click on a sequence of public transport stops where the vehicle should stop. (Cycle overlapping stops with <SHIFT>+<LEFT MOUSE>, <LEFT MOUSE> to set final)
                                3. Optionally, click on a sequence of connected edges where the PT vehicle should run. (Cycle overlapping edges with <SHIFT>+<LEFT MOUSE>, <LEFT MOUSE> to set final)
                                4. Click Add Line to add the PT line.
                                The routing (Step 3) can be done automatically later. 
                                """,
            is_textbutton=False,
        )

        self._init_select(is_show_selected=False)

        # self.add_options_common()
        # make options

        self.add(
            cm.AttrConf(
                'linename',
                default='',
                groupnames=['options'],
                perm='rw',
                name='Line name',
                info=
                'This is the official name or number of the line. Note that the same line may have several line services for different service periods.',
            ))

        self.add(
            cm.AttrConf(
                'id_vtype',
                0,
                groupnames=['options'],
                choices={'None': 0},
                name='Veh. type ID',
                info='Vehicle type used to derve this line.',
                #xmltag = 'type',
            ))

        self.add(
            cm.AttrConf(
                'hour_offset',
                0,
                groupnames=['options'],
                name='Offset hours',
                unit='h',
                perm='rw',
                info=
                'Hour of the day when service starts. This time will be added to the begin time, which is fo fine tuning.',
            ))

        self.add(
            cm.AttrConf(
                'time_begin',
                0,
                groupnames=['options'],
                name='Begin time',
                unit='s',
                perm='rw',
                info='Time when service begins.',
            ))

        self.add(
            cm.AttrConf(
                'duration',
                0,
                groupnames=['options'],
                name='Duration',
                unit='s',
                perm='rw',
                info='Time duration in seconds.',
            ))

        # self.add(cm.AttrConf(  'time_end', 0,
        #                        groupnames = ['options'],
        #                        name = 'End time',
        #                        perm='rw',
        #                        unit = 's',
        #                        info = 'Time when service ends.',
        #                        ))

        self.add(
            cm.AttrConf(
                'period',
                0,
                groupnames=['options'],
                name='Interval',
                perm='rw',
                unit='s',
                info='Time interval between consecutive vehicles.',
            ))

        self.add(
            cm.AttrConf(
                'time_dwell',
                20,
                groupnames=['options'],
                perm='rw',
                name='Dwell time',
                untit='s',
                info=
                'Dwell time in a stop while passengers are boarding/alighting.'
            ))

        self.add(
            cm.AttrConf(
                'ids_stop',
                [],
                perm='r',
                #choices =  net.ptstops.stopnames.get_indexmap(),
                groupnames=['options'],
                name='PT stop IDs',
                info=
                'Sequence of IDs od stops or stations of a public transort line.',
            ))

        self.add(
            cm.AttrConf(
                'ids_edge',
                [],
                perm='r',
                groupnames=['options'],
                name='Edge IDs',
                info=
                'Sequence of edge IDs constituting this public transport line.',
                xmltag='edges',
            ))
Ejemplo n.º 7
0
    def __init__(self,  maps, logger=None, **kwargs):
        print 'MapsImporter.__init__', maps, maps.parent.get_ident()
        self._init_common('mapsimporter', name='Background maps importer',
                          logger=logger,
                          info='Downloads and converts background maps.',
                          )
        self._maps = maps

        attrsman = self.set_attrsman(cm.Attrsman(self))
        #self.net = attrsman.add(   cm.ObjConf( network.Network(self) ) )
        # self.status = attrsman.add(cm.AttrConf(
        #                            'status', 'preparation',
        #                            groupnames = ['_private','parameters'],
        #                            perm='r',
        #                            name = 'Status',
        #                            info = 'Process status: preparation-> running -> success|error.'
        #                            ))

        self.width_tile = attrsman.add(cm.AttrConf('width_tile', kwargs.get('width_tile', 500.0),
                                                   groupnames=['options'],
                                                   choices=OrderedDict([("500", 500.0),
                                                                        ("1000",
                                                                         1000.0),
                                                                        ("2000",
                                                                         2000.0),
                                                                        ("4000",
                                                                         4000.0),
                                                                        ("8000",
                                                                         8000.0),
                                                                        ]),
                                                   perm='rw',
                                                   name='Tile width',
                                                   unit='m',
                                                   info='Tile width in meter of quadratic tile. This is the real width of one tile that will be downloaded.',
                                                   ))

        self.size_tile = attrsman.add(cm.AttrConf('size_tile', kwargs.get('size_tile', 1280),
                                                  groupnames=['options'],
                                                  perm='rw',
                                                  name='Tile size',
                                                  info='Tile size in pixel. This is the size of one tile that will be downloaded and determins the map resolution. Maximum is 1280.',
                                                  ))

        self.n_tiles = attrsman.add(cm.FuncConf('n_tiles', 'get_n_tiles', 0,
                                                groupnames=['options'],
                                                name='Number of tiles',
                                                #info = 'Delete a row.',
                                                ))

        # self.add_option(  'maptype',kwargs.get('maptype','satellite'),
        #                     choices = ['satellite',]
        #                     perm='rw',
        #                     name = 'Map type',
        #                     info = 'Type of map to be downloaded.',
        #                     )
        # self.add_option(  'filetype',kwargs.get('filetype','png'),
        #                     choices = ['png',]
        #                     perm='rw',
        #                     name = 'File type',
        #                     info = 'Image file format to be downloaded.',
        #                     )

        # self.add_option(  'mapserver',kwargs.get('mapserver','google'),
        #                     choices = ['google',]
        #                     perm='rw',
        #                     name = 'Map server',
        #                     info = 'Map server from where to download. Some servers require username and password.',
        #                     )

        # self.add_option(  'username',kwargs.get('username',''),
        #                     perm='rw',
        #                     name = 'User',
        #                      info = 'User name of map server (if required).',
        #                     )

        # self.add_option(  'password',kwargs.get('password',''),
        #                     perm='rw',
        #                     name = 'User',
        #                     info = 'User name of map server (if required).',
        #                     )

        self.is_remove_orig = attrsman.add(cm.AttrConf('is_remove_orig', kwargs.get('is_remove_orig', True),
                                                       groupnames=['options'],
                                                       perm='rw',
                                                       name='Remove originals',
                                                       info='Remove original files. Original, untransformed files are not necessary, but can be kept.',
                                                       ))
Ejemplo n.º 8
0
    def __init__(self,
                 obj,
                 ident='csvimporter',
                 name='CSV importer',
                 info='Import data from a CSV file into object',
                 logger=None,
                 **kwargs):
        print 'CsvImporter.__init__'
        self._init_common(
            ident,
            parent=obj,
            name=name,
            logger=logger,
            info=info,
        )

        attrsman = self.set_attrsman(cm.Attrsman(self))
        self.csvfilepath = attrsman.add(
            cm.AttrConf(
                'csvfilepath',
                kwargs.get('csvfilepath', ''),
                groupnames=['options'],
                perm='rw',
                name='CSV file',
                wildcards='CSV file (*.csv)|*.csv|*.CSV',
                metatype='filepath',
                info="CSV plain text file path.",
            ))

        self.sep = attrsman.add(
            cm.AttrConf(
                'sep',
                kwargs.get('sep', ","),
                groupnames=[
                    'options',
                ],
                perm='rw',
                name='Separator',
                info="""Seperator used in SCV file. Exampe: ; , <space key>""",
            ))

        self.is_use_default_for_invalid = attrsman.add(
            cm.AttrConf(
                'is_use_default_for_invalid',
                kwargs.get('is_use_default_for_invalid', True),
                groupnames=[
                    'options',
                ],
                perm='rw',
                name='Use default for invalid',
                info="""Use default for invalid.""",
            ))

        for attrconf in obj.get_colconfigs():
            colattrname = self._get_colattrname(attrconf.attrname)
            setattr(
                self, colattrname,
                attrsman.add(
                    cm.AttrConf(
                        colattrname,
                        attrconf.attrname,
                        groupnames=['options', 'colnames'],
                        perm='rw',
                        attrname_orig=attrconf.attrname,
                        name='Column name for %s' % attrconf.get_name(),
                        info=
                        'Name of column in CSV file for column %s. Include also hyphens and other delimiters when present in CSV file.'
                        % attrconf.get_name(),
                    )))
Ejemplo n.º 9
0
    def _init_attributes(self):
        net = self.parent.get_net()

        # lanechange model is now centralized: all vehicle types have the same
        # lanechange model.
        if self.get_version() < 0.1:
            self.delete('lanechangemodels')
            self.delete('alignments_lat')
            self.delete('speeds_max_lat')
            self.delete('gaps_min_lat')

        self.add(
            cm.AttrConf(
                'lanechangemodel',
                LANECHANGEMODELS[0],
                groupnames=['parameters'],
                choices=LANECHANGEMODELS,
                name='Lanechange model',
                info=
                "Lanechange model. The choice of the lanechange model will also determine the choice of lanechange parameters. With model SL2015, sublanes will be simulated.",
                #xmltag = 'laneChangeModel',
            ))

        self.add_col(SumoIdsConf('vtype', name='Type name', perm='rw'))

        self.add_col(
            am.ArrayConf(
                'lengths',
                5.0,
                groupnames=['parameters'],
                name='Length',
                unit='m',
                info="The vehicle's netto-length",
                xmltag='length',
            ))

        self.add_col(
            am.ArrayConf(
                'widths',
                2.0,
                groupnames=['parameters'],
                name='Width',
                unit='m',
                info="The vehicle's  width.",
                xmltag='width',
            ))

        self.add_col(
            am.ArrayConf(
                'heights',
                1.5,
                groupnames=['parameters'],
                name='Height',
                unit='m',
                info="The vehicle's  height.",
                xmltag='height',
            ))

        self.add_col(
            am.ArrayConf(
                'numbers_persons_initial',
                1,
                groupnames=['parameters'],
                name='Passengers',
                info="Initial number of persons in the vehicle.",
                xmltag='personNumber',
            ))

        self.add_col(
            am.ArrayConf(
                'capacities_persons',
                1,
                groupnames=['parameters'],
                name='Capacity',
                info="Maximum number of persons that fit in a vehicle.",
                xmltag='personCapacity',
            ))

        self.add_col(
            am.ArrayConf(
                'numbers_container',
                0,
                groupnames=['parameters'],
                name='Containers',
                info="Initial number of containers on the vehicle.",
                xmltag='containerNumber',
            ))

        self.add_col(
            am.ArrayConf(
                'speeds_max',
                70.0,
                groupnames=['parameters'],
                name='Max. speed',
                unit='m/s',
                info="The vehicle's maximum velocity",
                xmltag='maxSpeed',
            ))

        self.add_col(
            am.ArrayConf(
                'accels',
                0.8,
                groupnames=['parameters'],
                name='Max. accel.',
                unit='m/s^2',
                info='The acceleration ability of vehicles of this type',
                xmltag='accel',
            ))

        self.add_col(
            am.ArrayConf(
                'decels',
                4.5,
                groupnames=['parameters'],
                name='Max. decel.',
                unit='m/s^2',
                info='The acceleration ability of vehicles of this type',
                xmltag='decel',
            ))

        self.add_col(
            am.ArrayConf(
                'taus',
                1.0,
                groupnames=['parameters'],
                name='Reaction',
                unit='s',
                info=
                "The driver's reaction time in s (actually the minimum time gap)",
                xmltag='tau',
            ))

        self.add_col(
            am.ArrayConf(
                'sigmas',
                0.5,
                groupnames=['parameters'],
                name='Driver',
                info=
                'The driver imperfection (between 0 and 1). Used only in follower models  SUMOKrauss, SKOrig',
                xmltag='sigma',
            ))

        self.add_col(
            am.ArrayConf(
                'dists_min',
                2.5,
                groupnames=['parameters'],
                name='Min. gap',
                unit='m',
                info="Minimum empty space after leader.",
                xmltag='minGap',
            ))

        self.add_col(
            am.ArrayConf(
                'times_boarding',
                0.5,
                groupnames=['parameters'],
                name='boarding time',
                unit='s',
                info="The time required by a person to board the vehicle.",
                xmltag='boardingDuration',
            ))

        self.add_col(
            am.ArrayConf(
                'times_loading',
                90.0,
                groupnames=['parameters'],
                name='loading time',
                unit='s',
                info="The time required by a person to board the vehicle.",
                xmltag='loadingDuration',
            ))

        self.add_col(
            am.IdsArrayConf(
                'ids_mode',
                net.modes,
                groupnames=['state'],
                choices=MODES,
                name='Mode',
                info='ID of transport mode.',
                xmltag='vClass',
            ))

        emissionclasses_xml = {}
        for key in EMISSIONCLASSES.keys():
            # yes, map onto itself, otherwise choice values are taken
            emissionclasses_xml[key] = key

        self.add_col(
            am.ArrayConf(
                'emissionclasses',
                'HBEFA3/HDV_D_EU4',
                dtype='object',
                groupnames=['parameters'],
                choices=get_inversemap(EMISSIONCLASSES),
                name='Emission',
                info=
                "HBEFA3 emission class, see sourceforge.net/apps/mediawiki/sumo/index.php?title=Simulation/Models/Emissions/HBEFA-based",
                xmltag='emissionClass',
                xmlmap=emissionclasses_xml,
            ))

        self.add_col(
            am.ArrayConf(
                'impatiences',
                -1000.0,
                groupnames=['parameters'],
                name='Impatience',
                info=
                "Impatience offset between -1000.0 and 1.0 (-100 or less equals off). Impatience grows at 1/teleport. If 1.0 is reached driver will disrigard priorities.",
                xmltag='impatience',
            ))

        self.add_col(
            am.ArrayConf(
                'shapes_gui',
                "passenger",
                dtype='object',
                groupnames=['parameters'],
                name='GUI shape',
                choices=GUISHAPES,
                info="How this vehicle is rendered.",
                xmltag='guiShape',
            ))

        self.add_col(
            am.ArrayConf(
                'colors',
                np.array((1.0, 1.0, 1.0, 1.0), np.float32),
                metatype='color',
                groupnames=['parameters'],
                name='Color',
                info=
                "This vehicle type's color as RGBA tuple with values from 0 to 1.0",
                xmltag='color',
            ))

        self.add_col(
            am.ArrayConf(
                'lanechange_strategies',
                1.0,
                groupnames=['parameters'],
                name='Lane strategy',
                info=
                "Lanechange model strategy factor. The eagerness for performing strategic lane changing. Higher values result in earlier lane-changing. default: 1.0, range [0-inf]",
                xmltag='lcStrategic',
            ))
        self.add_col(
            am.ArrayConf(
                'lanechange_coops',
                1.0,
                groupnames=['parameters'],
                name='Lane coop',
                info=
                "Lanechange model cooperative factor.The willingness for performing cooperative lane changing. Lower values result in reduced cooperation. default: 1.0, range [0-1]",
                xmltag='lcCooperative',
            ))

        self.add_col(
            am.ArrayConf(
                'lanechange_gains',
                1.0,
                groupnames=['parameters'],
                name='Lane gain',
                info=
                "Lanechange model gain factor.The eagerness for performing lane changing to gain speed. Higher values result in more lane-changing. default: 1.0, range [0-inf]",
                xmltag='lcSpeedGain',
            ))

        self.add_col(
            am.ArrayConf(
                'lanechange_rightkeepings',
                1.0,
                groupnames=['parameters'],
                name='Lane right',
                info=
                "Lanechange model keep right factor.The eagerness for following the obligation to keep right. Higher values result in earlier lane-changing. default: 1.0, range [0-inf]",
                xmltag='lcKeepRight',
            ))

        self.add_col(
            am.ArrayConf(
                'sublane_alignments_lat',
                ALIGNMMENTS_LAT[0],
                dtype='object',
                groupnames=['parameters'],
                choices=ALIGNMMENTS_LAT,
                name='sublane alignment',
                info='Lateral alignment within a lane. For sublane model only.',
                xmltag='latAlignment',
            ))

        self.add_col(
            am.ArrayConf(
                'sublane_speeds_max_lat',
                1.0,
                groupnames=['parameters'],
                name='Sublane max. speed',
                unit='m/s',
                info=
                "The vehicle's maximum velocity in lateral direction. For sublane model only.",
                xmltag='maxSpeedLat',
            ))

        self.add_col(
            am.ArrayConf(
                'sublane_gaps_min_lat',
                0.12,
                groupnames=['parameters'],
                name='Sublane min. gap',
                unit='m',
                info=
                "The vehicle's minimum distance to other vehicles in lateral direction. For sublane model only.",
                xmltag='minGapLat',
            ))

        self.add_col(
            am.ArrayConf(
                'sublane_alignments_eager',
                1.0,
                groupnames=['parameters'],
                name='Sublane eager',
                info=
                "The eagerness using the configured lateral alignment within the lane. Higher values result in increased willingness to sacrifice speed for alignment. default: 1.0, range [0-inf]. For sublane model only.",
                xmltag='lcSublane',
            ))

        self.add_col(
            am.ArrayConf(
                'sublane_pushyfactors',
                0.0,
                groupnames=['parameters'],
                name='Sublane pushy',
                info=
                "Willingness to encroach laterally on other drivers. default: 0.0, range 0 or 1. For sublane model only.",
                xmltag='lcPushy',
            ))
Ejemplo n.º 10
0
    def __init__(self, ident, demand, logger=None, **kwargs):
        print 'VpCreator.__init__'
        self._init_common(
            ident,
            parent=demand,
            name='Od plots',
            logger=logger,
            info='Plot od data.',
        )
        attrsman = self.set_attrsman(cm.Attrsman(self))

        self.is_plot_reallocation = attrsman.add(
            cm.AttrConf(
                'is_plot_reallocation',
                kwargs.get('is_plot_reallocation', True),
                groupnames=['options'],
                name='Plot re-allocation',
                info='Plot re-allocation.',
            ))
        self.is_plot_trip_density = attrsman.add(
            cm.AttrConf(
                'is_plot_trip_density',
                kwargs.get('is_plot_trip_density', True),
                groupnames=['options'],
                name='Plot trips density',
                info='Plot rtrips density.',
            ))
        self.is_net = attrsman.add(
            cm.AttrConf(
                'is_net',
                kwargs.get('is_net', True),
                groupnames=['options'],
                name='Plot net',
                info='Plot net.',
            ))
        self.is_save = attrsman.add(
            cm.AttrConf(
                'is_save',
                kwargs.get('is_save', False),
                groupnames=['options'],
                name='Save plots',
                info='Save plots.',
            ))
        ##        scenario = self.parent.get_scenario()
        ##        print scenario.demand.odintervals.get_ids()
        self.id_interval = attrsman.add(
            cm.AttrConf(
                'id_interval',
                kwargs.get('interval', 1),
                groupnames=['options'],
                ##                                        choices = scenario.demand.odintervals.ids,
                name='interval',
                info='interval.',
            ))
        ##        vtypes = scenario.demand.vtypes

        self.id_odmode = attrsman.add(
            cm.AttrConf(
                'id_odmode',
                kwargs.get('id_odmodes', 1),
                groupnames=['options'],
                name='id_odmodes',
                ##                                        choices = vtypes.get_modechoices(),
                info='id_odmodes.',
            ))
Ejemplo n.º 11
0
    def __init__(self,
                 ident,
                 parent,
                 persons,
                 edges,
                 datapathkey='tripdatapath',
                 is_add_default=True,
                 name='Person results',
                 info='Table with simulation results for each person.',
                 **kwargs):

        self._init_objman(
            ident=ident,
            parent=parent,  # main results object
            info=info,
            name=name,
            **kwargs)

        self.add(
            cm.AttrConf(
                'datapathkey',
                datapathkey,
                groupnames=['_private'],
                name='data pathkey',
                info="key of data path",
            ))

        self.add_col(
            am.IdsArrayConf(
                'ids_person',
                persons,
                groupnames=['state'],
                is_index=True,
                name='person ID',
                info='ID of person.',
            ))
        attrinfos = OrderedDict([
            ('times_travel_total', {
                'name': 'Total travel time',
                'unit': 's',
                'default': 0.0,
                'info':
                'Total travel time, including all trips and waiting times, but excluding activities.',
                'groupnames': ['tripdata']
            }),
            ('times_walk', {
                'name': 'Walking time',
                'unit': 's',
                'default': 0.0,
                'info': 'Time walking, excluding waiting time.',
                'groupnames': ['tripdata']
            }),
            ('times_ride', {
                'name': 'Riding time',
                'unit': 's',
                'default': 0.0,
                'info': 'Time riding on a vehicle, excluding waiting time.',
                'groupnames': ['tripdata']
            }),
            ('times_wait', {
                'name': 'Waiting time',
                'unit': 's',
                'default': 0.0,
                'info': 'Time waiting for a vehicle.',
                'groupnames': ['tripdata']
            }),
            ('times_activity', {
                'name': 'Activity time',
                'unit': 's',
                'default': 0.0,
                'info': 'Time having some activities.',
                'groupnames': ['tripdata']
            }),
            ('times_depart', {
                'name': 'Dep. time',
                'xmltag': 'depart',
                'unit': 's',
                'default': 0.0,
                'info': 'Time beginning firts trip or activity.',
                'groupnames': ['tripdata']
            }),
            ('times_arrival', {
                'name': 'Arr. time',
                'xmltag': 'arrival',
                'unit': 's',
                'default': 0.0,
                'info': 'Time ending last trip or activity.',
                'groupnames': ['tripdata']
            }),
        ])

        for attrname, kwargs in attrinfos.iteritems():
            self.add_resultattr(attrname, **kwargs)

        # this is a special for route info
        self.add_col(
            am.IdlistsArrayConf(
                'ids_edges',
                edges,
                name='Edge IDs',
                groupnames=['routeinfo'],
                info='List of edge IDs constituting the actually taken route.',
                xmltag='edges',
            ))
Ejemplo n.º 12
0
    def __init__(self, odintervals, **kwargs):
        # print 'AddOdWizzard',odintervals#,odintervals.times_start
        # print ' dir(odintervals)',dir(odintervals)
        zones = odintervals.get_zones()

        self._init_objman(
            'odm_adder',
            parent=odintervals,
            name='ODM Wizzard',
            info=
            'Wizzard to add origin zone to destination zone demand informations.',
        )

        self.add_odoptions_common(odintervals.parent.get_scenario().net.modes,
                                  odintervals.parent.activitytypes, **kwargs)

        ids_zone = zones.get_ids()
        zonechoices = {}
        for id_zone, name_zone in zip(ids_zone, zones.ids_sumo[ids_zone]):
            zonechoices[name_zone] = id_zone
        # print '  zonechoices',zonechoices
        # make for each possible pattern a field for prob
        # if len(zonechoices) > 0:
        self.add(
            cm.ListConf(
                'ids_zone_orig_filter',
                kwargs.get('ids_zone_orig_filter', []),
                groupnames=['options'],
                choices=zonechoices,
                name='Filter zones of origin',
                info=
                """Filters flows if its origin is in one of these zones. If no zone is given, then no filtering takes place.""",
            ))

        self.add(
            cm.ListConf(
                'ids_zone_dest_filter',
                kwargs.get('ids_zone_dest_filter', []),
                groupnames=['options'],
                choices=zonechoices,
                name='Filter zones of destination',
                info=
                """Filters flows if its destination is in one of these zones. If no zone is given, then no filtering takes place.""",
            ))

        self.add(
            cm.ListConf(
                'ids_zone_cross_filter',
                kwargs.get('ids_zone_cross_filter', []),
                groupnames=['options'],
                choices=zonechoices,
                name='Filter zones to cross',
                info=
                """Filters flows if a straight line between origin and destination crosses at least one of these zones. If no zone is given, then no filtering takes place.""",
            ))

        self.add(
            cm.AttrConf(
                'dist_min',
                kwargs.get('dist_min', -1.0),
                groupnames=['options'],
                name='Filter zones with min. dist.',
                unit='m',
                info=
                """Filters flows if the straight line between origin and destination is greater than the given minimum distance. If negative, then no filtering takes place.""",
            ))

        self.add(
            cm.AttrConf(
                'dist_max',
                kwargs.get('dist_max', -1.0),
                groupnames=['options'],
                name='Filter zones with max. dist.',
                unit='m',
                info=
                """Filters flows if the straight line between origin and destination is less than the given minimum distance. If negative, then no filtering takes place.""",
            ))

        self.add_col(
            am.ArrayConf(
                'names_orig',
                '',
                dtype='object',
                groupnames=['state'],
                choices=list(zones.ids_sumo.get_value()),
                name='Orig zone',
                info='Name of traffic assignment zone of origin of trip.',
            ))

        self.add_col(
            am.ArrayConf(
                'names_dest',
                '',
                dtype='object',
                groupnames=['state'],
                choices=list(zones.ids_sumo.get_value()),
                name='Dest zone',
                info='Name of traffic assignment zone of destination of trip.',
            ))

        self.add_col(
            am.ArrayConf(
                'tripnumbers',
                0,
                groupnames=['state'],
                perm='rw',
                name='Trips',
                info=
                'Number of trips from zone of origin to zone of destination.',
                xmltag='tripnumber',
            ))

        self.add(
            cm.FuncConf(
                'func_make_row',
                'on_add_row',
                None,
                groupnames=['rowfunctions', '_private'],
                name='New OD flow.',
                info='Add a new OD flow.',
            ))

        self.add(
            cm.FuncConf(
                'func_delete_row',
                'on_del_row',
                None,
                groupnames=['rowfunctions', '_private'],
                name='Del OD flow',
                info='Delete OD flow.',
            ))
Ejemplo n.º 13
0
    def __init__(self,
                 rootname,
                 name_scenario='myscenario',
                 description='',
                 parent=None,
                 workdirpath=None,
                 **kwargs):

        self._init_objman(ident='scenario',
                          parent=parent,
                          name='Scenario',
                          info='Main scenario instance.',
                          version=0.2,
                          **kwargs)

        attrsman = self.set_attrsman(cm.Attrsman(self))

        if workdirpath is not None:
            # create a directory if path is given, but does not exist
            if not os.path.isdir(workdirpath):
                os.mkdir(workdirpath)
        else:
            workdirpath = os.getcwd()
            #workdirpath = os.path.expanduser("~")

        self.name_scenario = attrsman.add(
            cm.AttrConf(
                'name_scenario',
                name_scenario,
                groupnames=['options'],
                perm='rw',
                name='Name',
                info='Scenario name, used for documentation purposes only.',
            ))

        self.description = attrsman.add(
            cm.AttrConf(
                'description',
                description,
                groupnames=['options'],
                perm='rw',
                name='Description',
                info='Short, free description of Scenario.',
            ))

        self.rootname = attrsman.add(
            cm.AttrConf(
                'rootname',
                rootname,
                groupnames=['options'],
                perm='r',
                is_save=True,
                name='Shortname',
                info=
                'Short name for scenario. This string is defined when saving the scenario. It is used as rootname for all files produced by this scenario. Please avoid special charracters, whitespace, accents etc. ASCII is recommented in order to remain compatible between operating systems.',
            ))

        self.workdirpath = attrsman.add(
            cm.AttrConf(
                'workdirpath',
                workdirpath,
                groupnames=['options'],
                perm='r',
                is_save=True,
                name='Workdir',
                metatype='dirpath',
                info=
                'Working directory for this scenario and can be changed when saving the scenario. Please avoid special charracters, whitespace, accents etc. ASCII is recommented in order to remain compatible between operating systems.',
            ))

        self.net = attrsman.add(cm.ObjConf(network.Network(self)))

        self.landuse = attrsman.add(cm.ObjConf(landuse.Landuse(self,
                                                               self.net)))

        self.demand = attrsman.add(cm.ObjConf(demand.Demand(self)))
        # if self.get_version()<0.2:
        #    self.delete('simulation')

        self._init_attributes()
Ejemplo n.º 14
0
    def __init__(self,
                 scenario,
                 is_export_net=True,
                 is_export_rou=True,
                 is_prompt_filepaths=False,
                 flowfilepath=None,
                 netfilepath=None,
                 ptstopsfilepath=None,
                 logger=None,
                 results=None,
                 **kwargs):

        self._init_common(
            'marouter',
            name='Macroscopic Router',
            parent=scenario,
            logger=logger,
            info='Macroscopic assignment generating route flows.',
        )

        self.init_cml('marouter')  # pass  no commad to generate options only

        self._results = results
        self.time_warmup = 0.0  # needed for compatibility with sumo process
        attrsman = self.get_attrsman()

        self.add_option(
            'assignmentmethod',
            kwargs.get('assignmentmethod', 'incremental'),
            groupnames=['options', 'processing'],
            cml='--assignment-method',
            choices={
                'Incremental all or nothing': 'incremental',
                'User equilibrium (not yet implemented)': 'UE',
                'Stochastic Use equilibrium': 'SUE'
            },
            name='Assignment method',
            info='Assignment method.',
            #is_enabled = lambda self: self.width_sublanes > 0,
        )

        simtime_start_default = scenario.demand.get_time_depart_first()
        # estimate end of simtime
        simtime_end_default = scenario.demand.get_time_depart_last()

        self.add_option(
            'simtime_start',
            kwargs.get('simtime_start', simtime_start_default),
            groupnames=['options', 'timing'],
            cml='--begin',
            name='Start time',
            perm='rw',
            info='Start time of simulation in seconds after midnight.',
            unit='s',
        )

        self.add_option(
            'simtime_end',
            kwargs.get('simtime_end', simtime_end_default),
            groupnames=['options', 'timing'],
            cml='--end',
            name='End time',
            perm='rw',
            info='End time of simulation in seconds after midnight.',
            unit='s',
        )

        self.add_option(
            'aggregationinterval',
            kwargs.get('aggregationinterval', 3600),
            groupnames=['options', 'processing'],
            cml='--aggregation-interval',
            name='Aggrigation interval',
            info=
            'Defines the time interval when aggregating single vehicle input.',
            untit='s',
        )

        self.add_option(
            'n_max_alternatives',
            kwargs.get('n_max_alternatives', 5),
            groupnames=['options', 'processing'],
            cml='--max-alternatives',
            name='Maximum route alternatives',
            info='Prune the number of alternatives to this integer.',
        )

        self.add_option(
            'is_interpolate_weights',
            kwargs.get('is_interpolate_weights', False),
            groupnames=['options', 'processing'],
            cml='--weights.interpolate',
            name='Interpolate edge weights',
            info='Interpolate edge weights at time interval boundaries.',
        )

        self.add_option(
            'is_expand_weights',
            kwargs.get('is_expand_weights', False),
            groupnames=['options', 'processing'],
            cml='--weights.expand',
            name='Expand edge weights',
            info='Expand edge weights at time interval boundaries.',
        )

        self.add_option(
            'routingalgorithm',
            kwargs.get('routingalgorithm', 'dijkstra'),
            groupnames=['options', 'processing'],
            choices=['dijkstra', 'astar', 'CH', 'CHWrapper'],
            cml='--routing-algorithm',
            name='Routing algorithm',
            info='Routing algorithm.',
        )

        self.add_option(
            'n_routing_threads',
            kwargs.get('n_routing_threads', 1),
            groupnames=['options', 'processing'],
            cml='--routing-threads',
            name='Number of routing threats',
            info='The number of parallel execution threads used for routing',
        )

        self.add_option(
            'is_additive_traffic',
            kwargs.get('is_additive_traffic', False),
            groupnames=['options', 'processing'],
            cml='--additive-traffic',
            name='Additive traffic',
            info='Keep traffic flows of all time slots in the net.',
        )

        self.add_option(
            'tolerance',
            kwargs.get('tolerance', 0.001),
            groupnames=['options', 'processing'],
            cml='--tolerance',
            name='SUE tolerance',
            info='Tolerance when checking for SUE stability.',
        )

        self.add_option(
            'penalty_leftturn',
            kwargs.get('penalty_leftturn', 0.0),
            groupnames=['options', 'processing'],
            cml='--left-turn-penalty',
            name='Left turn penalty',
            info=
            'Left-turn penalty to calculate link travel time when searching routes.',
        )

        self.add_option(
            'penalty_paths',
            kwargs.get('penalty_paths', 1.0),
            groupnames=['options', 'processing'],
            cml='--paths.penalty',
            name='Paths penalty',
            info=
            'Penalize existing routes with  this time to find secondary routes.',
            untit='s',
        )

        self.add_option(
            'c_upperbound',
            kwargs.get('c_upperbound', 0.5),
            groupnames=['options', 'processing'],
            cml='--upperbound ',
            name='Cost upperbound',
            info='Upper bound to determine auxiliary link cost.',
        )

        self.add_option(
            'c_lowerbound',
            kwargs.get('c_lowerbound', 0.15),
            groupnames=['options', 'processing'],
            cml='--lowerbound ',
            name='Cost lowerbound',
            info='Lower bound to determine auxiliary link cost.',
        )

        self.add_option(
            'n_iter_max',
            kwargs.get('n_iter_max', 20),
            groupnames=['options', 'processing'],
            cml='--max-iterations',
            name='Max. number of iterations',
            info=
            'maximal number of iterations for new route searching in incremental and stochastic user assignment.',
        )
        self.add_option(
            'n_iter_inner_max',
            kwargs.get('n_iter_inner_max', 1000),
            groupnames=['options', 'processing'],
            cml='--max-inner-iterations',
            name='Max. number of inner iterations',
            info=
            'Maximal number of inner iterations for user equilibrium calcuation in the stochastic user assignment.',
        )

        self.add_option(
            'routechoicemethod',
            kwargs.get('routechoicemethod', 'logit'),
            groupnames=['options', 'processing'],
            choices=['gawron', 'logit', 'lohse'],
            cml='--route-choice-method',
            name='Route choice method',
            info=
            'Route choice method. Logit recommended, no entered vehicles with Gavron.',
        )

        self.add_option(
            'beta_gavron',
            kwargs.get('beta_gavron', 0.3),
            groupnames=['options', 'processing'],
            cml='--gawron.beta',
            name="Gawron's beta",
            info=
            "Gawron's beta parameter, only valid if Gavron's route choice method is selected.",
            is_enabled=lambda self: self.routechoicemethod == 'gawron',
        )

        self.add_option(
            'a_gavron',
            kwargs.get('a_gavron', 0.05),
            groupnames=['options', 'processing'],
            cml='--gawron.a',
            name="Gawron's a",
            info=
            "Gawron's a parameter. Only valid if Gavron's route choice method is selected.",
            is_enabled=lambda self: self.routechoicemethod == 'gawron',
        )

        self.add_option(
            'beta_logit',
            kwargs.get('beta_logit', 0.15),
            groupnames=['options', 'processing'],
            cml='--logit.beta',
            name="C-Logits's beta",
            info=
            "C-logit's beta for the commonality factor. Only valid if Logit route choice method is selected",
            is_enabled=lambda self: self.routechoicemethod == 'logit',
        )

        self.add_option(
            'gamma_logit',
            kwargs.get('gamma_logit', 1.0),
            groupnames=['options', 'processing'],
            cml='--logit.gamma',
            name="C-Logits's gamma",
            info=
            "C-logit's gamma for the commonality factor. Only valid if Logit route choice method is selected",
            is_enabled=lambda self: self.routechoicemethod == 'logit',
        )

        self.add_option(
            'theta_logit',
            kwargs.get('theta_logit', 0.01),
            groupnames=['options', 'processing'],
            cml='--logit.theta',
            name="C-Logits's theta",
            info=
            "C-logit's theta. Only valid if Logit route choice method is selected",
            is_enabled=lambda self: self.routechoicemethod == 'logit',
        )

        self.add_option(
            'is_keep_all_routes',
            kwargs.get('is_keep_all_routes', False),
            groupnames=['options', 'processing'],
            cml='--keep-all-routes',
            name="keep all routes",
            info="Consider even routes with near zero probability.",
        )

        self.add_option(
            'is_skip_new_routes',
            kwargs.get('is_skip_new_routes', False),
            groupnames=['options', 'processing'],
            cml='--skip-new-routes',
            name="Skip new routes",
            info=
            "Only reuse routes from input routes, do not calculate new ones.",
        )

        self.add_option(
            'seed',
            1234,
            groupnames=['options', 'processing'],
            cml='--seed',
            name='Random seed',
            info=
            'Initialises the random number generator with the given value.',
        )

        self.add_option(
            'is_ignore_errors',
            kwargs.get('is_ignore_errors', True),
            groupnames=['options', 'processing'],
            cml='--ignore-errors',
            name="Ignore errors",
            info="Ignore errors.",
        )

        self.logfilepath = attrsman.add(
            cm.AttrConf(
                'logfilepath',
                kwargs.get('logfilepath', ''),
                groupnames=['options', 'misc'],
                perm='rw',
                name='Log file',
                wildcards='Log file (*.txt)|*.txt',
                metatype='filepath',
                info=
                "Writes all messages to Log filepath, implies verbous. If blank, no logfile is created",
            ))

        if ptstopsfilepath is None:
            self.ptstopsfilepath = scenario.net.ptstops.get_stopfilepath()

            self.is_export_ptstops = attrsman.add(
                cm.AttrConf(
                    'is_export_ptstops',
                    True,
                    groupnames=['input', 'options'],
                    perm='rw',
                    name='Export PT stops?',
                    info='Export PT stops before simulation?',
                ))
        else:
            self.ptstopsfilepath = ptstopsfilepath

        self.is_export_flow = attrsman.add(
            cm.AttrConf(
                'is_export_flow',
                kwargs.get('is_export_flow', True),
                groupnames=['input', 'options'],
                perm='rw',
                name='Export OD flows?',
                info=
                'Export OD flows before simulation? Needs to be done only once after OD flows changed.',
            ))

        if flowfilepath is None:
            self.flowfilepath = scenario.demand.odintervals.get_flowfilepath()

        else:
            self.is_export_flow = False
            self.flowfilepath = flowfilepath

        if netfilepath is None:
            self.netfilepath = scenario.net.get_filepath()

            self.is_export_net = attrsman.add(
                cm.AttrConf(
                    'is_export_net',
                    is_export_net,
                    groupnames=['input', 'options'],
                    perm='rw',
                    name='Export net?',
                    info=
                    'Export current network before simulation? Needs to be done only once after network has changed.',
                ))
        else:
            self.is_export_net = False
            self.netfilepath = netfilepath

        self.routeoutputfilepath = None
        self.flowoutputfilepath = None
    def __init__(self, odintervals):
        # print 'AddOdWizzard',odintervals#,odintervals.times_start
        # print ' ',dir(odintervals)
        zones = odintervals.get_zones()

        self._init_objman(
            'odm_adder',
            parent=odintervals,
            name='ODM Wizzard',
            info=
            'Wizzard to add origin zone to destination zone demand informations.',
        )

        self.add(
            am.AttrConf(
                't_start',
                0,
                groupnames=['state'],
                perm='rw',
                name='Start time',
                unit='s',
                info='Start time of interval',
            ))

        self.add(
            am.AttrConf(
                't_end',
                3600,
                groupnames=['state'],
                perm='rw',
                name='End time',
                unit='s',
                info='End time of interval',
            ))

        # here we ged classes not vehicle type
        # specific vehicle type within a class will be generated later
        self.add(
            am.AttrConf(
                'id_mode',
                MODES['passenger'],
                groupnames=['state'],
                choices=odintervals.parent.vtypes.get_modechoices(),
                name='ID mode',
                info='ID of transport mode.',
            ))

        self.add(
            cm.AttrConf(
                'scale',
                1.0,
                groupnames=['options'],
                perm='rw',
                name='Scale',
                info=
                'Scale demand by this factor before adding. Value od 1.0 means no scaling.'
            ))

        self.add_col(
            am.ArrayConf(
                'names_orig',
                '',
                dtype='object',
                groupnames=['state'],
                choices=list(zones.ids_sumo.get_value()),
                name='Orig zone',
                info='Name of traffic assignment zone of origin of trip.',
            ))

        self.add_col(
            am.ArrayConf(
                'names_dest',
                '',
                dtype='object',
                groupnames=['state'],
                choices=list(zones.ids_sumo.get_value()),
                name='Dest zone',
                info='Name of traffic assignment zone of destination of trip.',
            ))

        self.add_col(
            am.ArrayConf(
                'tripnumbers',
                0,
                groupnames=['state'],
                perm='rw',
                name='Trips',
                info=
                'Number of trips from zone with ID Orig to zone with ID Dest.',
                xmltag='tripnumber',
            ))

        self.add(
            cm.FuncConf(
                'func_make_row',
                'on_add_row',
                None,
                groupnames=['rowfunctions', '_private'],
                name='New row',
                info='Add a new row.',
            ))

        self.add(
            cm.FuncConf(
                'func_delete_row',
                'on_del_row',
                None,
                groupnames=['rowfunctions', '_private'],
                name='Del row',
                info='Delete a row.',
            ))
Ejemplo n.º 16
0
    def __init__(self, scenario,
                 results=None,
                 logger=None,
                 is_gui=False, is_runnow=False,
                 is_run_background=False, is_nohup=False,
                 workdirpath=None,
                 is_export_net=False,
                 is_export_poly=False,
                 is_export_rou=False,
                 method_routechoice=None,
                 **kwargs):
        self._init_common('sumo', name='SUMO',
                          logger=logger,
                          info='SUMO simulation of scenario.',
                          )
        self._results = results
        rootname = scenario.get_rootfilename()
        rootdirpath = scenario.get_workdirpath()
        self.configfilepath = os.path.join(rootdirpath, rootname + '.netc.xml')

        # if simresults == None:
        #    self.simresults = Simresults(scenario=scenario)

        self.init_cml('xxx', is_run_background=is_run_background,
                      is_nohup=is_nohup)  # pass main shell command
        attrsman = self.get_attrsman()

        # print '\nSumo.__init__',kwargs

        #self.scenario = scenario
        #self.settings = scenario.settings
        self.is_gui = attrsman.add(cm.AttrConf('is_gui', is_gui,
                                               groupnames=['options', 'misc'],
                                               name='run in gui mode',
                                               perm='rw',
                                               info='If selected show animation in window'
                                               ))

        if is_export_net:
            netfilepath = scenario.net.export_netxml()
            if netfilepath is not False:
                # export OK, network is not an option
                groupnames = ['input', '_private']
            else:
                # something went wrong with exporting
                netfilepath = os.path.join(rootdirpath, rootname + '.net.xml')
                groupnames = ['input', 'options']

        else:
            netfilepath = os.path.join(rootdirpath, rootname + '.net.xml')
            groupnames = ['input', '_private']

        self.netfilepath = attrsman.add(cm.AttrConf('netfilepath', netfilepath,
                                                    groupnames=groupnames,
                                                    perm='rw',
                                                    name='Netfile',
                                                    wildcards='SUMO net XML files (*.net.xml)|*.net.xml',
                                                    metatype='filepath',
                                                    info="""SUMO network xml file.""",
                                                    ))

        self.dirpath_results = attrsman.add(cm.AttrConf('dirpath_results', rootdirpath,
                                                        groupnames=['input'],
                                                        perm='rw',
                                                        name='Result directory',
                                                        metatype='dirpath',
                                                        info="""Directory where general SUMO simulation result files are placed.""",
                                                        ))

        if is_export_rou:
            routefilepaths = scenario.demand.trips.export_routes_xml(
                method_routechoice=method_routechoice)
            if routefilepaths is not False:
                # export OK, network is not an option
                groupnames = ['input', '_private']
            else:
                # something went wrong with exporting
                routefilepaths = kwargs.get(
                    'routefilepaths', scenario.demand.trips.get_routefilepath())
                groupnames = ['input', 'options']

        else:
            routefilepaths = kwargs.get(
                'routefilepaths', scenario.demand.trips.get_routefilepath())
            groupnames = ['input', 'options']

        self.routefilepaths = attrsman.add(cm.AttrConf('routefilepaths', routefilepaths,
                                                       groupnames=groupnames,
                                                       perm='rw',
                                                       name='Route file(s)',
                                                       wildcards='Typemap XML files (*.rou.xml)|*.rou.xml',
                                                       metatype='filepaths',
                                                       info='SUMO route xml file.\n'
                                                       + 'If multiple, comma separated files are given'
                                                       + ' then make sure the start time of trips'
                                                       + ' are in increasing chronological order.',
                                                       ))

        simtime_start_default = scenario.demand.trips.get_time_depart_first()
        # estimate end of simtime
        simtime_end_default = scenario.demand.trips.get_time_depart_last() + 600.0

        self.simtime_start = attrsman.add(cm.AttrConf('simtime_start', kwargs.get('simtime_start', simtime_start_default),
                                                      groupnames=[
                                                          'options', 'timing'],
                                                      name='Start time',
                                                      perm='rw',
                                                      info='Start time of simulation in seconds after midnight.',
                                                      unit='s',
                                                      ))

        self.simtime_end = attrsman.add(cm.AttrConf('simtime_end', kwargs.get('simtime_end', simtime_end_default),
                                                    groupnames=[
                                                        'options', 'timing'],
                                                    name='End time',
                                                    perm='rw',
                                                    info='End time of simulation in seconds after midnight.',
                                                    unit='s',
                                                    ))

        self.time_step = attrsman.add(cm.AttrConf('time_step', kwargs.get('time_step', 0.2),
                                                  groupnames=[
                                                      'options', 'timing'],
                                                  name='Time step',
                                                  perm='rw',
                                                  info='Basic simulation time step (1s by default).',
                                                  metatype='time',
                                                  unit='s',
                                                  ))

        self.time_to_teleport = attrsman.add(cm.AttrConf('time_to_teleport', kwargs.get('time_to_teleport', -1),
                                                         groupnames=[
                                                             'options', 'timing'],
                                                         name='teleport',
                                                         perm='rw',
                                                         info='Time to teleport in seconds, which is the time after'
                                                         + 'dedlocks get resolved by teleporting\n'
                                                         + '-1 means no teleporting takes place',
                                                         metatype='time',
                                                         unit='s',
                                                         ))

        self.time_sample = attrsman.add(cm.AttrConf('time_sample', kwargs.get('time_sample', 60),
                                                    groupnames=[
                                                        'options', 'timing'],
                                                    name='Output sample time',
                                                    perm='rw',
                                                    info='Common sampling time of output data.',
                                                    metatype='time',
                                                    unit='s',
                                                    ))

        # print '  ',scenario.demand.vtypes.lanechangemodel.get_value()
        if scenario.demand.vtypes.lanechangemodel.get_value() in ['SL2015', ]:
            width_sublanes_default = 1.0
        else:
            width_sublanes_default = -1.0

        self.width_sublanes = attrsman.add(cm.AttrConf('width_sublanes', kwargs.get('width_sublanes', width_sublanes_default),
                                                       groupnames=[
                                                           'options', 'edges'],
                                                       #cml = '--lateral-resolution',
                                                       perm='rw',
                                                       name='Sublane width',
                                                       unit='m',
                                                       info='Width of sublanes. Should be less than lane width. If negative the sublanes are disabeled.',
                                                       is_enabled=lambda self: self.width_sublanes > 0,
                                                       ))

        self.pedestrian_model = attrsman.add(cm.AttrConf('pedestrian_model', kwargs.get('pedestrian_model', 'striping'),
                                                         groupnames=[
                                                             'options', 'parameters'],
                                                         name='Pedestrian Model',
                                                         choices=[
                                                             'striping', 'nonInteracting', 'None'],
                                                         perm='rw',
                                                         info='Type of Pedestrian model.',
                                                         ))

        self.is_edgedata = attrsman.add(cm.AttrConf('is_edgedata', kwargs.get('is_edgedata', False),
                                                    groupnames=[
                                                        'options', 'output'],
                                                    name='Output edge data',
                                                    perm='rw',
                                                    info='If set, generate detailed data for all edges.'
                                                    ))

        self.is_routedata = attrsman.add(cm.AttrConf('is_routedata', kwargs.get('is_routedata', False),
                                                     groupnames=[
                                                         'options', 'output'],
                                                     name='Output route data',
                                                     perm='rw',
                                                     info='If set, generate detailed data for all routes.'
                                                     ))

        self.is_tripdata = attrsman.add(cm.AttrConf('is_tripdata', kwargs.get('is_tripdata', False),
                                                    groupnames=[
                                                        'options', 'output'],
                                                    name='Output trip data',
                                                    perm='rw',
                                                    info='If set, generate detailed data for all trips.'
                                                    ))

        self.is_edgenoise = attrsman.add(cm.AttrConf('is_edgenoise', kwargs.get('is_edgenoise', False),
                                                     groupnames=[
                                                         'options', 'output'],
                                                     name='Output edge noise',
                                                     perm='rw',
                                                     info='If set, generate noise information for all edges.'
                                                     ))

        self.is_edgesemissions = attrsman.add(cm.AttrConf('is_edgesemissions', kwargs.get('is_edgesemissions', False),
                                                          groupnames=[
                                                              'options', 'output'],
                                                          name='Output edge emissions',
                                                          perm='rw',
                                                          info='If set, generate emission information for all edges.'
                                                          ))

        outfile_prefix = kwargs.get('outfile_prefix', 'out')
        self.routesdatapath = attrsman.add(cm.AttrConf('routesdatapath', os.path.join(rootdirpath, rootname + '.' + outfile_prefix + '.roudata.xml'),
                                                       groupnames=[
                                                           'outputfiles', '_private'],
                                                       perm='r',
                                                       name='Route data file',
                                                       wildcards='Route data XML files (*.roudata.xml)|*.roudata.xml',
                                                       metatype='filepath',
                                                       info="""SUMO xml file with route output info.""",
                                                       #attrnames_data = ['depart','arrival'],
                                                       #element = 'vehicle',
                                                       #id_type = 'trip',
                                                       #reader = 'plain',
                                                       ))

        self.tripdatapath = attrsman.add(cm.AttrConf('tripdatapath', os.path.join(rootdirpath, rootname + '.' + outfile_prefix + '.tripdata.xml'),
                                                     groupnames=[
                                                         'outputfiles', '_private'],
                                                     perm='r',
                                                     name='Edge data file',
                                                     wildcards='Trip data XML files (*.tripdata.xml)|*.tripdata.xml',
                                                     metatype='filepath',
                                                     info="""SUMO xml file with trip output data.""",
                                                     attrnames_data=[
                                                         'depart', 'arrival', 'duration'],
                                                     #element = 'tripinfo',
                                                     #id_type = 'trip',
                                                     #reader = 'plain',
                                                     ))

        self.edgedatapath = attrsman.add(cm.AttrConf('edgedatapath', os.path.join(rootdirpath, rootname + '.' + outfile_prefix + '.edgedata.xml'),
                                                     groupnames=[
                                                         'outputfiles', '_private'],
                                                     perm='r',
                                                     name='Edge data file',
                                                     wildcards='Edge data XML files (*.edgedata.xml)|*.edgedata.xml',
                                                     metatype='filepath',
                                                     info="""SUMO xml file with edge output data.""",
                                                     ))

        self.edgenoisepath = attrsman.add(cm.AttrConf('edgenoisepath', os.path.join(rootdirpath, rootname + '.' + outfile_prefix + '.edgenoise.xml'),
                                                      groupnames=[
                                                          'outputfiles', '_private'],
                                                      perm='r',
                                                      name='Edge noise file',
                                                      wildcards='Edge noise XML files (*.edgenoise.xml)|*.edgenoise.xml',
                                                      metatype='filepath',
                                                      info="""SUMO xml file with edge noise data.""",
                                                      #attrnames_averaged = ['noise'],
                                                      #element = 'edge',
                                                      #id_type = 'edge',
                                                      #reader = 'interval',
                                                      ))

        self.edgeemissionspath = attrsman.add(cm.AttrConf('edgeemissionspath', os.path.join(rootdirpath, rootname + '.' + outfile_prefix + '.edgeemissions.xml'),
                                                          groupnames=[
                                                              'outputfiles', '_private'],
                                                          perm='r',
                                                          name='Edge noise file',
                                                          wildcards='Edge noise XML files (*.edgeemissions.xml)|*.edgeemissions.xml',
                                                          metatype='filepath',
                                                          info="""SUMO xml file with edge emission data.""",
                                                          attrnames_data=[
                                                              'fuel_abs', 'CO_abs', 'CO2_abs', 'NOx_abs', 'PMx_abs'],
                                                          attrnames_averaged=[
                                                              'fuel_normed', 'CO_normed', 'CO2_normed', ],
                                                          element='edge',
                                                          id_type='edge',
                                                          reader='interval',
                                                          ))

        self.is_exclude_emptyedges = attrsman.add(cm.AttrConf('is_exclude_emptyedges', kwargs.get('is_exclude_emptyedges', True),
                                                              name='No empty edges',
                                                              perm='rw',
                                                              groupnames=[
                                                                  'options', 'misc'],
                                                              info='Excludes empty edges from being sampled.',
                                                              ))

        self.is_exclude_emptylanes = attrsman.add(cm.AttrConf('is_exclude_emptylanes', kwargs.get('is_exclude_emptylanes', True),
                                                              name='No empty lanes',
                                                              perm='rw',
                                                              groupnames=[
                                                                  'options', 'misc'],
                                                              info='Excludes empty edges from being sampled.',
                                                              ))

        self.seed = attrsman.add(cm.AttrConf('seed', kwargs.get('seed', 0),
                                             name='Seed',
                                             perm='rw',
                                             groupnames=['options', 'misc'],
                                             info='Ransdom seed.',
                                             ))

        self.is_include_poly = attrsman.add(cm.AttrConf('is_include_poly', kwargs.get('is_include_poly', True),
                                                        name='Include buildings',
                                                        perm='rw',
                                                        groupnames=[
                                                            'options', 'misc'],
                                                        info='Include building polynomials. Only for visualization purposes.',
                                                        ))

        # print '  is_export_poly',is_export_poly
        if is_export_poly:
            polyfilepath = scenario.landuse.export_polyxml()
            # print '  export_polyxml',polyfilepath
            if polyfilepath is not False:
                # export OK,  not an option
                groupnames = ['input', '_private']
            else:
                # something went wrong with exporting
                polyfilepath = os.path.join(
                    rootdirpath, rootname + '.poly.xml')
                groupnames = ['input', 'options']

        else:
            polyfilepath = os.path.join(rootdirpath, rootname + '.poly.xml')
            groupnames = ['input', 'options']

        self.polyfilepath = attrsman.add(cm.AttrConf('polyfilepath', polyfilepath,
                                                     groupnames=groupnames,
                                                     perm='rw',
                                                     name='Poly file',
                                                     wildcards='Poly XML files (*.poly.xml)|*.poly.xml',
                                                     metatype='filepath',
                                                     info='SUMO polynomial xml file',
                                                     ))

        # print '  is_export_poly,is_include_poly,
        # filepath_poly',is_export_poly, self.is_include_poly,
        # self.polyfilepath

        if is_runnow:
            self.run()
Ejemplo n.º 17
0
    def __init__(
            self,
            virtualpop,
            name='Plot strategy results with Matplotlib',
            info="Creates plots of different strategy results using matplotlib",
            logger=None,
            **kwargs):

        self._init_common('strategyresultplotter',
                          parent=virtualpop,
                          name=name,
                          info=info,
                          logger=logger)

        print 'StrategyPlotter.__init__', self.parent
        attrsman = self.get_attrsman()

        self.is_strategy_share = attrsman.add(
            cm.AttrConf(
                'is_strategy_share',
                kwargs.get('is_strategy_share', True),
                groupnames=['options', 'plots'],
                name='Plot strategy shares',
                plotfunction=self.plot_strategy_share,
                info='Plot share of currently chosen strategies.',
            ))

        self.is_strategy_time_est_mean = attrsman.add(
            cm.AttrConf(
                'is_strategy_time_est_mean',
                kwargs.get('is_strategy_time_est_mean', True),
                groupnames=['options', 'plots'],
                name='Plot strategy mean est times',
                plotfunction=self.plot_strategy_times_est,
                info='Plot strategy mean est times.',
            ))

        self.is_strategy_timefactors_est = attrsman.add(
            cm.AttrConf(
                'is_strategy_timefactors_est',
                kwargs.get('is_strategy_timefactors_est', True),
                groupnames=['options', 'plots'],
                name='Plot strategy times factors',
                plotfunction=self.plot_strategy_timefactors_est,
                info=self.plot_strategy_timefactors_est.__doc__,
            ))

        self.is_strategy_timefactors_exec = attrsman.add(
            cm.AttrConf(
                'is_strategy_timefactors_exec',
                kwargs.get('is_strategy_timefactors_exec', True),
                groupnames=['options', 'plots'],
                name='Plot strategy exec times factors',
                plotfunction=self.plot_strategy_timefactors_exec,
                info=self.plot_strategy_timefactors_exec.__doc__,
            ))

        # other
        # self.n_bins = attrsman.add(cm.AttrConf(  'n_bins', kwargs.get('n_bins',10),
        #                                groupnames = ['options'],
        #                                name = 'Bin number',
        #                                info = 'Number of bins for histograms.',
        #                                ))

        self.timeint_bins = attrsman.add(
            cm.AttrConf(
                'timeint_bins',
                kwargs.get('timeint_bins', 0.5),
                groupnames=['options'],
                name='Bin time int.',
                unit='s',
                info='Size of time intervals in histograms.',
            ))

        # self.add_plotoptions(**kwargs)
        self.is_title = attrsman.add(
            cm.AttrConf(
                'is_title',
                kwargs.get('is_title', True),
                groupnames=['options'],
                name='Show title',
                info='Show title of diagrams.',
            ))

        self.size_titlefont = attrsman.add(
            cm.AttrConf(
                'size_titlefont',
                kwargs.get('size_titlefont', 32),
                groupnames=['options'],
                name='Title fontsize',
                info='Title fontsize.',
            ))

        self.size_labelfont = attrsman.add(
            cm.AttrConf(
                'size_labelfont',
                kwargs.get('size_labelfont', 24),
                groupnames=['options'],
                name='Label fontsize',
                info='Label fontsize.',
            ))

        self.width_line = attrsman.add(
            cm.AttrConf(
                'width_line',
                kwargs.get('width_line', 2),
                groupnames=['options'],
                perm='wr',
                name='Line width',
                info='Width of plotted lines.',
            ))

        self.color_line = attrsman.add(
            cm.AttrConf(
                'color_line',
                kwargs.get('color_line',
                           np.array([0, 0, 0, 1], dtype=np.float32)),
                groupnames=['options'],
                perm='wr',
                metatype='color',
                name='Line color',
                info='Color of line in various diagrams.',
            ))

        self.color_chart = attrsman.add(
            cm.AttrConf(
                'color_chart',
                kwargs.get('color_chart',
                           np.array([0.3, 0.1, 0.9, 1], dtype=np.float32)),
                groupnames=['options'],
                perm='wr',
                metatype='color',
                name='Chart color',
                info='Main Color of chart bars.',
            ))

        self.is_grid = attrsman.add(
            cm.AttrConf(
                'is_grid',
                kwargs.get('is_grid', True),
                groupnames=['options'],
                name='Show grid?',
                info='If True, shows a grid on the graphical representation.',
            ))

        self.add_save_options(**kwargs)
Ejemplo n.º 18
0
    def __init__(
            self,
            scenario,
            results=None,
            logger=None,
            guimode='sumopy',  # sumo,
            is_runnow=False,
            is_run_background=False,
            is_nohup=False,
            workdirpath=None,
            is_export_net=True,
            is_export_poly=True,
            is_export_rou=True,
            is_prompt_filepaths=False,
            routefilepaths=None,
            netfilepath=None,
            ptstopsfilepath=None,
            polyfilepath=None,
            logfilepath='',
            **kwargs):

        self._init_common(
            'sumo',
            parent=scenario,
            name='SUMO',
            logger=logger,
            info='SUMO micro simulation of scenario.',
        )
        self._results = results
        rootname = scenario.get_rootfilename()
        rootdirpath = scenario.get_workdirpath()
        self.configfilepath = os.path.join(rootdirpath, rootname + '.netc.xml')

        # if simresults  is None:
        #    self.simresults = Simresults(scenario=scenario)

        self.init_cml('xxx',
                      is_run_background=is_run_background,
                      is_nohup=is_nohup)  # pass main shell command
        attrsman = self.get_attrsman()

        # print '\nSumo.__init__',kwargs

        #self.scenario = scenario
        #self.settings = scenario.settings
        self.guimode = attrsman.add(
            cm.AttrConf(
                'guimode',
                guimode,
                groupnames=['options', 'misc'],
                choices=[
                    'sumopy', 'sumopy+map', 'native', 'openscene', 'nogui'
                ],
                name='GUI mode',
                perm='rw',
                info=
                'Gui mode:  sumopy = sumopy style, sumopy+map = sumopy theme with backround map, native = Native SUMO gui, openscene = Open street graph, nogui = run without gui window'
            ))

        simtime_start_default = scenario.demand.get_time_depart_first()
        # estimate end of simtime
        simtime_end_default = scenario.demand.get_time_depart_last()

        self.simtime_start = attrsman.add(
            cm.AttrConf(
                'simtime_start',
                kwargs.get('simtime_start', simtime_start_default),
                groupnames=['options', 'timing'],
                name='Start time',
                perm='rw',
                info='Start time of simulation in seconds after midnight.',
                unit='s',
            ))

        self.simtime_end = attrsman.add(
            cm.AttrConf(
                'simtime_end',
                kwargs.get('simtime_end', simtime_end_default),
                groupnames=['options', 'timing'],
                name='End time',
                perm='rw',
                info='End time of simulation in seconds after midnight.',
                unit='s',
            ))

        self.time_warmup = attrsman.add(
            cm.AttrConf(
                'time_warmup',
                kwargs.get('time_warmup', 0.0),
                groupnames=['options', 'timing'],
                name='Warmup time',
                perm='rw',
                info='Start recording results after this time.',
                metatype='time',
                unit='s',
            ))

        self.time_step = attrsman.add(
            cm.AttrConf(
                'time_step',
                kwargs.get('time_step', 0.2),
                groupnames=['options', 'timing'],
                name='Time step',
                perm='rw',
                info='Basic simulation time step (1s by default).',
                metatype='time',
                unit='s',
            ))

        self.time_to_teleport = attrsman.add(
            cm.AttrConf(
                'time_to_teleport',
                kwargs.get('time_to_teleport', -1),
                groupnames=['options', 'timing'],
                name='teleport',
                perm='rw',
                info='Time to teleport in seconds, which is the time after' +
                'dedlocks get resolved by teleporting\n' +
                '-1 means no teleporting takes place',
                metatype='time',
                unit='s',
            ))

        self.time_sample = attrsman.add(
            cm.AttrConf(
                'time_sample',
                kwargs.get('time_sample', 60),
                groupnames=['options', 'timing'],
                name='Output sample time',
                perm='rw',
                info='Common sampling time of output data.',
                metatype='time',
                unit='s',
            ))

        self.is_dynaroute = attrsman.add(
            cm.AttrConf(
                'is_dynaroute',
                kwargs.get('is_dynaroute', False),
                groupnames=['options', 'timing'],
                name='Dynamic routing',
                perm='rw',
                info=
                'Routing is always performed during the simulation, based on current edge travel times. This option corrisponds to the so called one shot assignment.',
            ))

        # print '  ',scenario.demand.vtypes.lanechangemodel.get_value()
        if scenario.demand.vtypes.lanechangemodel.get_value() in [
                'SL2015',
        ]:
            width_sublanes_default = 1.0
        else:
            width_sublanes_default = -1.0

        self.width_sublanes = attrsman.add(
            cm.AttrConf(
                'width_sublanes',
                kwargs.get('width_sublanes', width_sublanes_default),
                groupnames=['options', 'edges'],
                #cml = '--lateral-resolution',
                perm='rw',
                name='Sublane width',
                unit='m',
                info=
                'Width of sublanes. Should be less than lane width. If negative the sublanes are disabeled.',
                is_enabled=lambda self: self.width_sublanes > 0,
            ))

        self.pedestrian_model = attrsman.add(
            cm.AttrConf(
                'pedestrian_model',
                kwargs.get('pedestrian_model', 'striping'),
                groupnames=['options', 'parameters'],
                name='Pedestrian Model',
                choices=['striping', 'nonInteracting', 'None'],
                perm='rw',
                info='Type of Pedestrian model.',
            ))

        self.width_pedestrian_striping = attrsman.add(
            cm.AttrConf(
                'width_pedestrian_striping',
                kwargs.get('width_pedestrian_striping', 0.35),
                groupnames=['options', 'parameters'],
                name='Ped. stripe width',
                unit='m',
                perm='rw',
                info=
                "Width of parallel stripes for segmenting a sidewalk (meters) for use with model 'striping'",
            ))

        self.slowdownfactor_pedestrian_striping = attrsman.add(
            cm.AttrConf(
                'slowdownfactor_pedestrian_striping',
                kwargs.get('slowdownfactor_pedestrian_striping', 0.2),
                groupnames=['options', 'parameters'],
                name='Ped. slowdown',
                perm='rw',
                info=
                "Factor for random slow-downs [0,1] for use with model 'striping'",
            ))

        self.jamtime_pedestrian_striping = attrsman.add(
            cm.AttrConf(
                'jamtime_pedestrian_striping',
                kwargs.get('jamtime_pedestrian_striping', 10),
                groupnames=['options', 'parameters'],
                name='Ped. jamtime',
                unit='s',
                perm='rw',
                info=
                "Factor for random slow-downs [0,1] for use with model 'striping'",
            ))

        self.is_edgedata = attrsman.add(
            cm.AttrConf('is_edgedata',
                        kwargs.get('is_edgedata', False),
                        groupnames=['options', 'output'],
                        name='Output edge data',
                        perm='rw',
                        info='If set, generate detailed data for all edges.'))

        self.is_routedata = attrsman.add(
            cm.AttrConf('is_routedata',
                        kwargs.get('is_routedata', False),
                        groupnames=['options', 'output'],
                        name='Output route data',
                        perm='rw',
                        info='If set, generate detailed data for all routes.'))

        self.is_tripdata = attrsman.add(
            cm.AttrConf('is_tripdata',
                        kwargs.get('is_tripdata', False),
                        groupnames=['options', 'output'],
                        name='Output trip data',
                        perm='rw',
                        info='If set, generate detailed data for all trips.'))

        self.is_edgenoise = attrsman.add(
            cm.AttrConf(
                'is_edgenoise',
                kwargs.get('is_edgenoise', False),
                groupnames=['options', 'output'],
                name='Output edge noise',
                perm='rw',
                info='If set, generate noise information for all edges.'))

        self.is_edgesemissions = attrsman.add(
            cm.AttrConf(
                'is_edgesemissions',
                kwargs.get('is_edgesemissions', False),
                groupnames=['options', 'output'],
                name='Output edge emissions',
                perm='rw',
                info='If set, generate emission information for all edges.'))

        outfile_prefix = kwargs.get('outfile_prefix', 'out')
        self.routesdatapath = attrsman.add(
            cm.AttrConf(
                'routesdatapath',
                os.path.join(rootdirpath,
                             rootname + '.' + outfile_prefix + '.roudata.xml'),
                groupnames=['outputfiles', '_private'],
                perm='r',
                name='Route data file',
                wildcards='Route data XML files (*.roudata.xml)|*.roudata.xml',
                metatype='filepath',
                info="""SUMO xml file with route output info.""",
                #attrnames_data = ['depart','arrival'],
                #element = 'vehicle',
                #id_type = 'trip',
                #reader = 'plain',
            ))

        self.tripdatapath = attrsman.add(
            cm.AttrConf(
                'tripdatapath',
                os.path.join(rootdirpath, rootname + '.' + outfile_prefix +
                             '.tripdata.xml'),
                groupnames=['outputfiles', '_private'],
                perm='r',
                name='Edge data file',
                wildcards='Trip data XML files (*.tripdata.xml)|*.tripdata.xml',
                metatype='filepath',
                info="""SUMO xml file with trip output data.""",
                attrnames_data=['depart', 'arrival', 'duration'],
                #element = 'tripinfo',
                #id_type = 'trip',
                #reader = 'plain',
            ))

        self.edgedatapath = attrsman.add(
            cm.AttrConf(
                'edgedatapath',
                os.path.join(rootdirpath, rootname + '.' + outfile_prefix +
                             '.edgedata.xml'),
                groupnames=['outputfiles', '_private'],
                perm='r',
                name='Edge data file',
                wildcards='Edge data XML files (*.edgedata.xml)|*.edgedata.xml',
                metatype='filepath',
                info="""SUMO xml file with edge output data.""",
            ))

        self.edgenoisepath = attrsman.add(
            cm.AttrConf(
                'edgenoisepath',
                os.path.join(
                    rootdirpath,
                    rootname + '.' + outfile_prefix + '.edgenoise.xml'),
                groupnames=['outputfiles', '_private'],
                perm='r',
                name='Edge noise file',
                wildcards=
                'Edge noise XML files (*.edgenoise.xml)|*.edgenoise.xml',
                metatype='filepath',
                info="""SUMO xml file with edge noise data.""",
                #attrnames_averaged = ['noise'],
                #element = 'edge',
                #id_type = 'edge',
                #reader = 'interval',
            ))

        self.edgeemissionspath = attrsman.add(
            cm.AttrConf(
                'edgeemissionspath',
                os.path.join(
                    rootdirpath,
                    rootname + '.' + outfile_prefix + '.edgeemissions.xml'),
                groupnames=['outputfiles', '_private'],
                perm='r',
                name='Edge noise file',
                wildcards=
                'Edge noise XML files (*.edgeemissions.xml)|*.edgeemissions.xml',
                metatype='filepath',
                info="""SUMO xml file with edge emission data.""",
                attrnames_data=[
                    'fuel_abs', 'CO_abs', 'CO2_abs', 'NOx_abs', 'PMx_abs'
                ],
                attrnames_averaged=[
                    'fuel_normed',
                    'CO_normed',
                    'CO2_normed',
                ],
                element='edge',
                id_type='edge',
                reader='interval',
            ))

        # self.is_ignore_accidents = attrsman.add(cm.AttrConf(  'is_ignore_accidents', kwargs.get('is_ignore_accidents',False),
        #                                                        name = 'ignore accidents',
        #                                                        perm = 'rw',
        #                                                        groupnames = ['options','misc'],
        #                                                        info = 'Ignore accidents.',
        #                                                        ))

        self.is_collission_check_junctions = attrsman.add(
            cm.AttrConf(
                'is_collission_check_junctions',
                kwargs.get('is_collission_check_junctions', True),
                name='Collission check junctions',
                perm='rw',
                groupnames=['options', 'misc'],
                info='Perform collission check at junctions.',
            ))

        self.collission_action = attrsman.add(
            cm.AttrConf(
                'collission_action',
                kwargs.get('collission_action', 'warn'),
                name='Collission action',
                choices=['none', 'warn', 'teleport', 'remove'],
                perm='rw',
                groupnames=['options', 'misc'],
                info='Specifioes what to do when a collission occurs.',
            ))

        self.is_exclude_emptyedges = attrsman.add(
            cm.AttrConf(
                'is_exclude_emptyedges',
                kwargs.get('is_exclude_emptyedges', True),
                name='No empty edges',
                perm='rw',
                groupnames=['options', 'misc'],
                info='Excludes empty edges from being sampled.',
            ))

        self.is_exclude_emptylanes = attrsman.add(
            cm.AttrConf(
                'is_exclude_emptylanes',
                kwargs.get('is_exclude_emptylanes', True),
                name='No empty lanes',
                perm='rw',
                groupnames=['options', 'misc'],
                info='Excludes empty edges from being sampled.',
            ))

        self.seed = attrsman.add(
            cm.AttrConf(
                'seed',
                kwargs.get('seed', 0),
                name='Seed',
                perm='rw',
                groupnames=['options', 'misc'],
                info='Random seed.',
            ))

        self.is_include_poly = attrsman.add(
            cm.AttrConf(
                'is_include_poly',
                kwargs.get('is_include_poly', True),
                name='Include buildings?',
                perm='rw',
                groupnames=['options', 'misc'],
                info=
                'Include building polynomials. Only for visualization purposes.',
            ))

        self.is_start = attrsman.add(
            cm.AttrConf(
                'is_start',
                kwargs.get('is_start', False),
                groupnames=['options', 'misc'],
                perm='rw',
                name='Start immediately',
                info=
                'Immediate start of simulation, without waiting to press the start button in GUI mode.',
                is_enabled=lambda self: self.guimode is not 'nogui',
            ))

        self.is_quit_on_end = attrsman.add(
            cm.AttrConf(
                'is_quit_on_end',
                kwargs.get('is_quit_on_end', False),
                groupnames=['options', 'misc'],
                perm='rw',
                name='Quit on end',
                info='Quits the GUI when the simulation stops.',
                is_enabled=lambda self: self.guimode is not 'nogui',
            ))

        self.logfilepath = attrsman.add(
            cm.AttrConf(
                'logfilepath',
                logfilepath,
                groupnames=['options', 'misc'],
                perm='rw',
                name='Log file',
                wildcards='Log file (*.txt)|*.txt',
                metatype='filepath',
                info=
                "Writes all messages to Log filepath, implies verbous. If blank, no logfile is created",
            ))

        if ptstopsfilepath is None:
            ptstopsfilepath = scenario.net.ptstops.get_stopfilepath()

            self.is_export_ptstops = attrsman.add(
                cm.AttrConf(
                    'is_export_ptstops',
                    True,
                    groupnames=['input', 'options'],
                    perm='rw',
                    name='Export PT stops?',
                    info='Export PT stops before simulation?',
                ))

        if routefilepaths is None:
            routefilepaths = scenario.demand.get_routefilepath()

            self.is_export_rou = attrsman.add(
                cm.AttrConf(
                    'is_export_rou',
                    is_export_rou,
                    groupnames=['input', 'options'],
                    perm='rw',
                    name='Export routes?',
                    info=
                    'Export current routes before simulation? Needs to be done only once after demand has changed.',
                ))
        else:
            self.is_export_rou = False

        if netfilepath is None:
            netfilepath = scenario.net.get_filepath()

            self.is_export_net = attrsman.add(
                cm.AttrConf(
                    'is_export_net',
                    is_export_net,
                    groupnames=['input', 'options'],
                    perm='rw',
                    name='Export net?',
                    info=
                    'Export current network before simulation? Needs to be done only once after network has changed.',
                ))
        else:
            self.is_export_net = False

        if polyfilepath is None:
            polyfilepath = scenario.landuse.get_filepath()
            self.is_export_poly = attrsman.add(
                cm.AttrConf(
                    'is_export_poly',
                    is_export_poly,
                    groupnames=['input', 'options'],
                    perm='rw',
                    name='Export buildings?',
                    info=
                    'Export current buildings before simulation? Needs to be done only once after buildings have changed.',
                ))
        else:
            self.is_export_poly = False

        if is_prompt_filepaths:
            filepathgroupnames = ['input', 'options']
        else:
            filepathgroupnames = ['input', '_private']

        self.dirpath_results = attrsman.add(
            cm.AttrConf(
                'dirpath_results',
                rootdirpath,
                groupnames=filepathgroupnames,
                perm='rw',
                name='Result directory',
                metatype='dirpath',
                info=
                """Directory where general SUMO simulation result files are placed.""",
            ))

        self.netfilepath = attrsman.add(
            cm.AttrConf(
                'netfilepath',
                netfilepath,
                groupnames=filepathgroupnames,
                perm='rw',
                name='Netfile',
                wildcards='SUMO net XML files (*.net.xml)|*.net.xml',
                metatype='filepath',
                info="""SUMO network xml file.""",
            ))

        self.ptstopsfilepath = attrsman.add(
            cm.AttrConf(
                'ptstopsfilepath',
                ptstopsfilepath,
                groupnames=filepathgroupnames,
                perm='rw',
                name='Stop file',
                wildcards='SUMO XML files (*.add.xml)|*.add.xml',
                metatype='filepath',
                info=
                """SUMO additional xml file with info on public transport stops.""",
            ))

        self.routefilepaths = attrsman.add(
            cm.AttrConf(
                'routefilepaths',
                routefilepaths,
                groupnames=filepathgroupnames,
                perm='rw',
                name='Route file(s)',
                wildcards='Typemap XML files (*.rou.xml)|*.rou.xml',
                metatype='filepaths',
                info='SUMO route xml file.\n' +
                'If multiple, comma separated files are given' +
                ' then make sure the start time of trips' +
                ' are in increasing chronological order.',
            ))

        self.polyfilepath = attrsman.add(
            cm.AttrConf(
                'polyfilepath',
                polyfilepath,
                groupnames=filepathgroupnames,
                perm='rw',
                name='Poly file',
                wildcards='Poly XML files (*.poly.xml)|*.poly.xml',
                metatype='filepath',
                info='SUMO polynomial xml file',
            ))

        # print '  is_export_poly,is_include_poly, filepath_poly',is_export_poly, self.is_include_poly, self.polyfilepath

        self._init_special(**kwargs)

        if is_runnow:
            self.run()
Ejemplo n.º 19
0
    def __init__(self, parent, mainframe=None):
        """
        To be overridden by specific tool.
        """
        self.init_common(
            'turnflowadder',
            parent,
            'Add turn-flow',
            info="""Tool to at generated flows and turn flows at intersections:
                                Select an edge with <LEFT CLICK> on the Network editor to specify a <From Edge>. 
                                Optionally enter the number of vehicles to be generated on <From Edge> and press button "Add flow".
                                Cycle through the possible adjacent edges by <SHIFT>+<LEFT MOUSE>.
                                <LEFT CLICK> when the desired <To Edge> is highlighted.  
                                Enter the number of vehicles turning from <From Edge> to <To edge> and press button "Add turns".
                                Continue cycling by <SHIFT>+<LEFT MOUSE> and adding more turnflows.
                                Or press "Clear" button to clear all edges and start defining flows for a new intersection.
                                """,
            is_textbutton=False,
        )

        self._init_select(is_show_selected=False)

        self.add_options_common()
        # make options

        self.add(
            cm.AttrConf(
                'id_fromedge',
                -1,
                groupnames=['options'],
                name='From edge ID',
                perm='r',
                info=
                'This is the reference edge for the generated flows as well as turn-flows into adjason edges.',
            ))

        self.add(
            cm.AttrConf(
                'flow_generated',
                0,
                groupnames=['options'],
                perm='rw',
                name='Gen. flow',
                info=
                'Absolute number of vehicles which are generated on "from edge" during the specified time interval.',
                xmltag='number',
            ))

        self.add(
            cm.AttrConf(
                'id_toedge',
                -1,
                groupnames=['options'],
                name='To edge ID',
                perm='r',
                info=
                'Target Edge ID for the specified turnflows. Click on edge to specify.',
            ))

        self.add(
            cm.AttrConf(
                'turnflow',
                0,
                groupnames=['options'],
                perm='rw',
                name='Turn flow',
                info=
                'Number of trips from edge of origin to edge of destination during the specified time interval. <SHIFT>+<LEFT MOUSE> to cycle through all possible edges. <LEFT MOUSE> to select.',
            ))
Ejemplo n.º 20
0
    def add_odoptions_common(self, modes=None, activitytypes=None):
        # print 'add_odoptions_common',modes
        self.add(
            am.AttrConf(
                't_start',
                0,
                groupnames=['options'],
                perm='rw',
                name='Start time',
                unit='s',
                info='Start time of interval',
            ))

        self.add(
            am.AttrConf(
                't_end',
                3600,
                groupnames=['options'],
                perm='rw',
                name='End time',
                unit='s',
                info='End time of interval',
            ))

        # here we ged classes not vehicle type
        # specific vehicle type within a class will be generated later
        if modes is None:
            modechoices = {'': -1}
        else:
            modechoices = modes.names.get_indexmap()
        # print '  modechoices',modechoices
        self.add(
            am.AttrConf(
                'id_mode',
                -1,
                groupnames=['options'],
                choices=modechoices,
                name='Mode',
                info='Transport mode.',
            ))

        self.add(
            cm.AttrConf(
                'scale',
                1.0,
                groupnames=['options'],
                perm='rw',
                name='Scale',
                info=
                'Scale demand by this factor before adding. Value od 1.0 means no scaling.'
            ))

        if activitytypes is None:
            activitytypechoices = {'': -1}
            id_act_orig = -1
            id_act_dest = -1
        else:
            activitytypechoices = activitytypes.names.get_indexmap()
            id_act_orig = activitytypes.names.get_id_from_index('home')
            id_act_dest = activitytypes.names.get_id_from_index('work')

        self.add(
            cm.AttrConf(
                'id_activitytype_orig',
                id_act_orig,
                groupnames=['options'],
                choices=activitytypechoices,
                perm='rw',
                name='Activity at orig.',
                info='Activity type at origin.',
            ))

        self.add(
            cm.AttrConf(
                'id_activitytype_dest',
                id_act_dest,
                groupnames=['options'],
                choices=activitytypechoices,
                perm='rw',
                name='Activity at dest.',
                info='Activity type at destination.',
            ))
Ejemplo n.º 21
0
    def __init__(self,
                 ident,
                 parent,
                 trips,
                 edges,
                 datapathkey='tripdatapath',
                 is_add_default=True,
                 name='Trip results',
                 info='Table with simulation results for each trip made.',
                 **kwargs):

        self._init_objman(
            ident=ident,
            parent=parent,  # main results object
            info=info,
            name=name,
            **kwargs)

        self.add(
            cm.AttrConf(
                'datapathkey',
                datapathkey,
                groupnames=['_private'],
                name='data pathkey',
                info="key of data path",
            ))

        self.add_col(
            am.IdsArrayConf(
                'ids_trip',
                trips,
                groupnames=['state'],
                is_index=True,
                name='ID trip',
                info='ID of trip.',
            ))
        attrinfos = OrderedDict([
            ('duration', {
                'name': 'Duration',
                'xmltag': 'duration',
                'unit': 's',
                'default': 0,
                'info': 'Trip duration',
                'groupnames': ['tripdata']
            }),
            ('depart', {
                'name': 'Dep. time',
                'xmltag': 'depart',
                'unit': 's',
                'default': 0,
                'info': 'Departure time',
                'groupnames': ['tripdata'],
                'is_average': True
            }),
            ('arrival', {
                'name': 'Arr. time',
                'xmltag': 'arrival',
                'unit': 's',
                'default': 0,
                'info': 'Arrival time',
                'groupnames': ['tripdata'],
                'is_average': True
            }),
            ('routeLength', {
                'name': 'Length',
                'xmltag': 'routeLength',
                'unit': 'm',
                'default': 0.0,
                'info': 'Route length',
                'groupnames': ['tripdata']
            }),
            ('departdelays', {
                'name': 'Dep. delay',
                'xmltag': 'departDelay',
                'unit': 's',
                'default': 0,
                'info':
                'The time the vehicle had to wait before it could start his journey',
                'groupnames': ['tripdata'],
                'is_average': True
            }),
            ('waittimes', {
                'name': 'Wait time',
                'xmltag': 'waitingTime',
                'unit': 's',
                'default': 0,
                'info':
                'The time in which the vehicle speed was below 0.1m/s (scheduled stops do not count) ',
                'groupnames': ['tripdata'],
                'is_average': True
            }),
            ('stoptimes', {
                'name': 'Stop time',
                'xmltag': 'stopTime',
                'unit': 's',
                'default': 0,
                'info':
                'The time in which the vehicle was taking a planned stop',
                'groupnames': ['tripdata'],
                'is_average': True
            }),
            ('timelosses', {
                'name': 'Timeloss',
                'xmltag': 'timeLoss',
                'unit': 's',
                'default': 0,
                'info':
                'The time lost due to driving below the ideal speed. (ideal speed includes the individual speedFactor; slowdowns due to intersections etc. will incur timeLoss, scheduled stops do not count)',
                'groupnames': ['tripdata'],
                'is_average': True
            }),
            ('departPos', {
                'name': 'depart pos',
                'xmltag': 'departPos',
                'unit': 'm',
                'default': 0.0,
                'info': 'depart position',
                'groupnames': ['tripdata'],
                'is_average': True
            }),
            ('arrivalPos', {
                'name': 'arrival pos',
                'xmltag': 'arrivalPos',
                'unit': 'm',
                'default': 0.0,
                'info': 'arrival position',
                'groupnames': ['tripdata'],
                'is_average': True
            }),
            ('speedfactors', {
                'name': 'Speedfactor',
                'xmltag': 'speedFactor',
                'default': 0.0,
                'info':
                'The individual speed factor of the vehicle (possibly drawn from a speed distribution at the start of the simulation)',
                'groupnames': ['tripdata'],
            }),
            ('are_vaporized', {
                'name': 'vaporized',
                'xmltag': 'vaporized',
                'default': False,
                'info':
                'Whether the vehicle was removed from the simulation before reaching its destination',
                'groupnames': ['tripdata'],
            }),
            ('waitSteps', {
                'name': 'wait steps',
                'xmltag': 'waitingCount',
                'unit': None,
                'default': 0,
                'info':
                'Count of time steps, the vehicle has been waiting during its trip',
                'groupnames': ['tripdata']
            }),
            ('rerouteNo', {
                'name': 'reroute No',
                'xmltag': 'rerouteNo',
                'unit': None,
                'default': 0,
                'info': 'Number of re-routes',
                'groupnames': ['tripdata']
            }),
            ('waitSteps', {
                'name': 'wait steps',
                'xmltag': 'waitSteps',
                'unit': None,
                'default': 0,
                'info':
                'Time steps, the vehicle has been waiting during its trip',
                'groupnames': ['tripdata']
            }),
        ])

        for attrname, kwargs in attrinfos.iteritems():
            self.add_resultattr(attrname, **kwargs)

        # this is special for route info
        self.add_col(
            am.IdlistsArrayConf(
                'ids_edges',
                edges,
                name='Edge IDs',
                groupnames=['routeinfo'],
                info='List of edge IDs constituting the actually taken route.',
                xmltag='edges',
            ))
Ejemplo n.º 22
0
    def __init__(self,
                 results,
                 name='Plot PRT stop results with Matplotlib',
                 info="Creates plots of PRT stop results using matplotlib",
                 logger=None,
                 **kwargs):

        self._init_common('stopresultsplotter',
                          parent=results,
                          name=name,
                          info=info,
                          logger=logger)

        print 'StopresultsPlotter.__init__', results, self.parent, len(
            self.get_stopresults())
        attrsman = self.get_attrsman()

        stops = self.get_stopresults().get_prtstops()
        choices_stop = {}
        for id_stop in stops.get_ids():
            choices_stop[str(id_stop)] = id_stop

        self.id_stop_plot = attrsman.add(
            cm.AttrConf(
                'id_stop_plot',
                kwargs.get('id_stop_plot',
                           stops.get_ids()[0]),
                groupnames=['options'],
                choices=choices_stop,
                name='ID stop plot',
                info='Plot results of PRT stop with this ID.',
            ))

        self.is_title = attrsman.add(
            cm.AttrConf(
                'is_title',
                kwargs.get('is_title', False),
                groupnames=['options'],
                name='Show title',
                info='Show title of diagrams.',
            ))

        self.size_titlefont = attrsman.add(
            cm.AttrConf(
                'size_titlefont',
                kwargs.get('size_titlefont', 32),
                groupnames=['options'],
                name='Title fontsize',
                info='Title fontsize.',
            ))

        self.size_labelfont = attrsman.add(
            cm.AttrConf(
                'size_labelfont',
                kwargs.get('size_labelfont', 24),
                groupnames=['options'],
                name='Label fontsize',
                info='Label fontsize.',
            ))

        self.width_line = attrsman.add(
            cm.AttrConf(
                'width_line',
                kwargs.get('width_line', 2),
                groupnames=['options'],
                perm='wr',
                name='Line width',
                info='Width of plotted lines.',
            ))

        self.color_line = attrsman.add(
            cm.AttrConf(
                'color_line',
                kwargs.get('color_line',
                           np.array([0, 0, 1, 1], dtype=np.float32)),
                groupnames=['options'],
                perm='wr',
                metatype='color',
                name='Line color',
                info='Color of line in various diagrams.',
            ))

        self.printformat = attrsman.add(
            cm.AttrConf(
                'printformat',
                kwargs.get('printformat', '%.1f'),
                choices=OrderedDict([
                    ('Show no values', ''),
                    ('x', '%.d'),
                    ('x.x', '%.1f'),
                    ('x.xx', '%.2f'),
                    ('x.xxx', '%.3f'),
                    ('x.xxxx', '%.4f'),
                ]),
                groupnames=['options'],
                name='Label formatting',
                info=
                'Print formatting of value label in graphical representation.',
            ))

        self.color_label = attrsman.add(
            cm.AttrConf(
                'color_label',
                kwargs.get('color_label',
                           np.array([0, 0, 0, 1], dtype=np.float32)),
                groupnames=['options'],
                perm='wr',
                metatype='color',
                name='Label color',
                info='Color of value label in graphical representation.',
            ))

        self.is_grid = attrsman.add(
            cm.AttrConf(
                'is_grid',
                kwargs.get('is_grid', True),
                groupnames=['options'],
                name='Show grid?',
                info='If True, shows a grid on the graphical representation.',
            ))
        self.color_background = attrsman.add(
            cm.AttrConf(
                'color_background',
                kwargs.get('color_background',
                           np.array([1, 1, 1, 1], dtype=np.float32)),
                groupnames=['options'],
                perm='wr',
                metatype='color',
                name='Background color',
                info='Background color of schematic network in the background.',
            ))
Ejemplo n.º 23
0
    def __init__(self,
                 results,
                 name='Plot results with Matplotlib',
                 info="Creates plots of different results using matplotlib",
                 logger=None):

        self._init_common('resultplotter',
                          parent=results,
                          name=name,
                          info=info,
                          logger=logger)

        print 'Resultplotter.__init__', results, self.parent
        attrsman = self.get_attrsman()

        # edgeresultes....
        attrnames_edgeresults = {}
        edgeresultattrconfigs = self.parent.edgeresults.get_group_attrs(
            'results')
        edgeresultattrnames = edgeresultattrconfigs.keys()
        edgeresultattrnames.sort()
        for attrname in edgeresultattrnames:
            attrconfig = edgeresultattrconfigs[attrname]

            attrnames_edgeresults[
                attrconfig.format_symbol()] = attrconfig.attrname

        #attrnames_edgeresults = {'Entered':'entered'}
        self.edgeattrname = attrsman.add(
            cm.AttrConf(
                'edgeattrname',
                'entered',
                choices=attrnames_edgeresults,
                groupnames=['options'],
                name='Edge Quantity',
                info='The edge related quantity to be plotted.',
            ))

        self.is_show_network = attrsman.add(
            cm.AttrConf(
                'is_show_network',
                False,
                groupnames=['options'],
                name='Show network',
                info='Shows a schematic network in the background.',
            ))

        self.is_show_title = attrsman.add(
            cm.AttrConf(
                'is_show_title',
                True,
                groupnames=['options'],
                name='Show tile',
                info='Shows title and unit.',
            ))

        self.resultwidth = attrsman.add(
            cm.AttrConf(
                'resultwidth',
                10.0,
                groupnames=['options'],
                name='Result width',
                unit='m',
                info='Maximum width of graphical resuls on map.',
            ))

        self.length_arrowhead = attrsman.add(
            cm.AttrConf(
                'length_arrowhead',
                10.0,
                groupnames=['options'],
                name='Arrow length',
                unit='m',
                info='Length of arrowhead on result map.',
            ))

        self.is_widthvalue = attrsman.add(
            cm.AttrConf(
                'is_widthvalue',
                False,
                groupnames=['options'],
                name='Value width?',
                info=
                'If True, the arrow width of the graphical representation is proportional to the result value.',
            ))

        self.is_colorvalue = attrsman.add(
            cm.AttrConf(
                'is_colorvalue',
                True,
                groupnames=['options'],
                name='Value color?',
                info=
                'If True, the arrows of the graphical representation are filled with a colour representing the result value.',
            ))

        self.color_outline = attrsman.add(
            cm.AttrConf(
                'color_outline',
                np.array([0.0, 0.0, 0.0, 0.95], dtype=np.float32),
                groupnames=['options'],
                perm='wr',
                metatype='color',
                name='Outline color',
                info=
                'Outline color of result arrows in graphical representation. Only valid if no color-fill is chosen.',
            ))

        self.color_fill = attrsman.add(
            cm.AttrConf(
                'color_fill',
                np.array([0.3, 0.3, 1.0, 0.95], dtype=np.float32),
                groupnames=['options'],
                perm='wr',
                metatype='color',
                name='Fill color',
                info=
                'Fill color of result arrows in graphical representation. Only valid if no color-fill is chosen.',
            ))

        self.alpha_results = attrsman.add(
            cm.AttrConf(
                'alpha_results',
                0.8,
                groupnames=['options'],
                name='Result transparency',
                info=
                'Transparency of result arrows in graphical representation.',
            ))

        self.printformat = attrsman.add(
            cm.AttrConf(
                'printformat',
                '%.1f',
                choices=OrderedDict([
                    ('Show no values', ''),
                    ('x', '%.d'),
                    ('x.x', '%.1f'),
                    ('x.xx', '%.2f'),
                    ('x.xxx', '%.3f'),
                    ('x.xxxx', '%.4f'),
                ]),
                groupnames=['options'],
                name='Value formatting',
                info=
                'Value formatting of displayed text in graphical representation.',
            ))

        self.is_grid = attrsman.add(
            cm.AttrConf(
                'is_grid',
                False,
                groupnames=['options'],
                name='Show grid?',
                info='If True, shows a grid on the graphical representation.',
            ))

        self.axis = None
Ejemplo n.º 24
0
    def init_options_ptstops(self, **kwargs):

        attrsman = self.get_attrsman()
        self.is_import_ptstops = attrsman.add(cm.AttrConf('is_import_ptstops', kwargs.get('is_import_stops', False),
                                                          groupnames=['options', 'ptstops'],
                                                          perm='rw',
                                                          name='Import PT stops?',
                                                          info='Should PT stops be imported?',
                                                          ))

        self.add_option('dist_search_footway_access_ptstops', kwargs.get('dist_search_footway_access_ptstops', 20.0),
                        groupnames=['options', 'ptstops'],
                        cml='--osm.stop-output.footway-access-distance',
                        perm='rw',
                        unit='m',
                        name='Search dist. PT stop footway access',
                        info='The search radius for finding suitable road accesses for rail stops',
                        is_enabled=lambda self: self.is_import_ptstops,
                        )

        self.add_option('n_footway_accesses_max', kwargs.get('n_footway_accesses_max', 10),
                        groupnames=['options', 'ptstops'],
                        cml='--osm.stop-output.footway-max-accesses',
                        perm='rw',
                        name='Maximum number of footway accesses',
                        info='The maximum roud accesses registered per rail stops',
                        is_enabled=lambda self: self.is_import_ptstops,
                        )

        self.add_option('length_default_ptstops', kwargs.get('length_default_ptstops', 20.0),
                        groupnames=['options', 'ptstops'],
                        cml='--osm.stop-output.length',
                        perm='rw',
                        unit='m',
                        name='Default length PT stops',
                        info='The default length of a public transport stop.',
                        is_enabled=lambda self: self.is_import_ptstops,
                        )

        self.add_option('length_default_busstops', kwargs.get('length_default_busstops', 20.0),
                        groupnames=['options', 'ptstops'],
                        cml='--osm.stop-output.length.bus',
                        perm='rw',
                        unit='m',
                        name='Default length bus stops',
                        info='The default length of bus stops.',
                        is_enabled=lambda self: self.is_import_ptstops,
                        )

        self.add_option('length_default_tramstops', kwargs.get('length_default_tramstops', 50.0),
                        groupnames=['options', 'ptstops'],
                        cml='--osm.stop-output.length.tram',
                        perm='rw',
                        unit='m',
                        name='Default length tram stops',
                        info='The default length of tram stops.',
                        is_enabled=lambda self: self.is_import_ptstops,
                        )

        self.add_option('length_default_trainstops', kwargs.get('length_default_trainstops', 100.0),
                        groupnames=['options', 'ptstops'],
                        cml='--osm.stop-output.length.train',
                        perm='rw',
                        unit='m',
                        name='Default length train stops',
                        info='The default length of train stops.',
                        is_enabled=lambda self: self.is_import_ptstops,
                        )