Пример #1
0
    def export_sumoxml(self, filepath=None, encoding='UTF-8'):
        """
        Export stops to SUMO stop xml file.
        """
        print 'export_sumoxml', filepath, len(self)
        if len(self) == 0:
            return None

        if filepath is None:
            filepath = self.get_stopfilepath()

        try:
            fd = open(filepath, 'w')
        except:
            print 'WARNING in write_obj_to_xml: could not open', filepath
            return False
        #xmltag, xmltag_item, attrname_id = self.xmltag
        fd.write('<?xml version="1.0" encoding="%s"?>\n' % encoding)
        indent = 0
        #fd.write(xm.begin('routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://sumo.sf.net/xsd/routes_file.xsd"',indent))

        fd.write(xm.begin('additional', indent))

        self.write_xml(fd, indent+2)

        fd.write(xm.end('additional', indent))
        fd.close()
        return filepath
Пример #2
0
    def export_xml(self, fd, indent=0):
        # <edgeRelations>
        # <interval begin="0" end="3600">
        # <edgeRelation from="myEdge0" to="myEdge1" probability="0.2"/>
        # <edgeRelation from="myEdge0" to="myEdge2" probability="0.7"/>
        # <edgeRelation from="myEdge0" to="myEdge3" probability="0.1"/>

        # ... any other edges ...

        # </interval>

        # ... some further intervals ...

        # </edgeRelations>

        fromedge_to_turnprobs = {}
        for _id in self.get_ids():
            id_fromedge = self.ids_fromedge[_id]
            if not fromedge_to_turnprobs.has_key(id_fromedge):
                fromedge_to_turnprobs[id_fromedge] = []
            fromedge_to_turnprobs[id_fromedge].append((self.ids_toedge[_id], self.probabilities[_id]))

        ids_sumoeges = self.get_edges().ids_sumo

        fd.write(xm.begin('edgeRelations', indent))
        for id_fromedge in fromedge_to_turnprobs.keys():

            for id_toedge, turnprob in fromedge_to_turnprobs[id_fromedge]:
                fd.write(xm.start('edgeRelation', indent+2))
                fd.write(xm.num('from', ids_sumoeges[id_fromedge]))
                fd.write(xm.num('to', ids_sumoeges[id_toedge]))
                fd.write(xm.num('probability', turnprob))
                fd.write(xm.stopit())

        fd.write(xm.end('edgeRelations', indent))
Пример #3
0
    def export_sumoxml(self, filepath=None, encoding='UTF-8'):
        """
        Export trips to SUMO xml file.
        """
        if filepath == None:
            filepath = self.get_tripfilepath()
        print 'export_sumoxml', filepath
        try:
            fd = open(filepath, 'w')
        except:
            print 'WARNING in write_obj_to_xml: could not open', filepath
            return False
        #xmltag, xmltag_item, attrname_id = self.xmltag
        fd.write('<?xml version="1.0" encoding="%s"?>\n' % encoding)
        fd.write(xm.begin('routes'))
        indent = 2

        #ids_modes_used = set(self.parent.vtypes.ids_mode[self.ids_vtype.get_value()])
        #----------------------
        # write vtypes, pedestrian included
        ids_vtypes = set(self.individualvehicles.value.ids_vtype.get_value())
        # print '  vtypes',vtypes
        #vtypes = vtypes.union(ptlines.get_vtypes())
        # print '  vtypes',vtypes
        ids_vtypes.add(MODES['pedestrian'])
        self.parent.vtypes.write_xml(fd, indent=indent,
                                     ids=ids_vtypes,
                                     is_print_begin_end=False)

        self._export_plans(fd, indent)

        fd.write(xm.end('routes'))
        fd.close()
        return filepath
Пример #4
0
    def export_polyxml(self, filepath=None, encoding="UTF-8"):
        """
        Export landuse facilities to SUMO poly.xml file.
        """
        if filepath == None:
            if self.parent is not None:
                filepath = self.parent.get_rootfilepath() + ".poly.xml"
            else:
                filepath = os.path.join(os.getcwd(), "landuse.poly.xml")

        print "export_polyxml", filepath
        try:
            fd = open(filepath, "w")
        except:
            print "WARNING in export_poly_xml: could not open", filepath
            return False

        # xmltag, xmltag_item, attrname_id = self.xmltag
        xmltag_poly = "additional"
        fd.write('<?xml version="1.0" encoding="%s"?>\n' % encoding)
        fd.write(xm.begin(xmltag_poly))
        indent = 2

        fd.write(xm.start("location", indent + 2))
        # print '  groups:',self.parent.net.get_attrsman().get_groups()
        for attrconfig in self.parent.net.get_attrsman().get_group("location"):
            # print '    locationconfig',attrconfig.attrname
            attrconfig.write_xml(fd)
        fd.write(xm.stopit())

        self.facilities.write_xml(fd, indent=indent + 2, is_print_begin_end=False)

        fd.write(xm.end(xmltag_poly))
        fd.close()
        return filepath
Пример #5
0
    def write_xml(self, fd=None, indent=0):
        ft = self.generate_odflows()
        scenario = self.parent.parent
        ids_zone_sumo = scenario.landuse.zones.ids_sumo
        get_vtype_for_mode = scenario.demand.vtypes.get_vtype_for_mode
        ids = ft.get_ids()
        fd.write(xm.begin('trips', indent))
        self.parent.vtypes.write_xml(
            fd,
            indent=indent,
            #ids = ids_vtype_selected,
            is_print_begin_end=False)

        for id_flow, time_start, time_end, id_mode, id_orig_sumo, id_dest_sumo, tripnumber in zip(
                ids, ft.times_start[ids], ft.times_end[ids], ft.ids_mode[ids],
                ids_zone_sumo[ft.ids_orig[ids]],
                ids_zone_sumo[ft.ids_dest[ids]], ft.tripnumbers[ids]):

            # <flow id="f" begin="0" end="100" number="23" fromTaz="taz1" toTaz="taz2"/>

            fd.write(xm.start('flow', indent + 2))
            fd.write(xm.num('id', id_flow))
            fd.write(xm.num('begin', time_start))
            fd.write(xm.num('end', time_end))
            fd.write(xm.num('number', tripnumber))

            fd.write(xm.num('fromTaz', id_orig_sumo))
            fd.write(xm.num('toTaz', id_dest_sumo))
            fd.write(
                xm.num('type',
                       get_vtype_for_mode(id_mode=id_mode, is_sumoid=True)))

            fd.write(xm.stopit())

        fd.write(xm.end('trips', indent))
Пример #6
0
    def export_sumoxml(self, filepath=None, encoding='UTF-8'):
        """
        Export trips to SUMO xml file.
        """
        if filepath == None:
            filepath = self.get_tripfilepath()
        print 'export_sumoxml', filepath
        try:
            fd = open(filepath, 'w')
        except:
            print 'WARNING in write_obj_to_xml: could not open', filepath
            return False
        #xmltag, xmltag_item, attrname_id = self.xmltag
        fd.write('<?xml version="1.0" encoding="%s"?>\n' % encoding)
        fd.write(xm.begin('routes'))
        indent = 2

        #ids_modes_used = set(self.parent.vtypes.ids_mode[self.ids_vtype.get_value()])
        #----------------------
        # write vtypes, pedestrian included
        ids_vtypes = set(self.individualvehicles.value.ids_vtype.get_value())
        # print '  vtypes',vtypes
        #vtypes = vtypes.union(ptlines.get_vtypes())
        # print '  vtypes',vtypes
        ids_vtypes.add(MODES['pedestrian'])
        self.parent.vtypes.write_xml(fd,
                                     indent=indent,
                                     ids=ids_vtypes,
                                     is_print_begin_end=False)

        self._export_plans(fd, indent)

        fd.write(xm.end('routes'))
        fd.close()
        return filepath
Пример #7
0
    def export_xml(self, fd, indent=0):
        #<fromEdge id="myEdge0">
        # <toEdge id="myEdge1" probability="0.2"/>
        # <toEdge id="myEdge2" probability="0.7"/>
        # <toEdge id="myEdge3" probability="0.1"/>
        #</fromEdge>

        fromedge_to_turnprobs = {}
        for _id in self.get_ids():
            id_fromedge = self.ids_fromedge[_id]
            if not fromedge_to_turnprobs.has_key(id_fromedge):
                fromedge_to_turnprobs[id_fromedge] = []
            fromedge_to_turnprobs[id_fromedge].append(
                (self.ids_toedge[_id], self.probabilities[_id]))

        ids_sumoeges = self.get_edges().ids_sumo

        for id_fromedge in fromedge_to_turnprobs.keys():
            fd.write(
                xm.begin('fromEdge' + xm.num('id', ids_sumoeges[id_fromedge]),
                         indent))
            for id_toedge, turnprob in fromedge_to_turnprobs[id_fromedge]:
                fd.write(xm.start('toEdge', indent + 2))
                fd.write(
                    xm.num('id', ids_sumoeges[id_toedge]) +
                    xm.num('probability', turnprob))
                fd.write(xm.stopit())
            fd.write(xm.end('fromEdge', indent))
Пример #8
0
    def write_xml(self, fd=None, indent=0):
        # <detectors>
        #    <detectorDefinition id="<DETECTOR_ID>" lane="<LANE_ID>" pos="<POS>"/>
        #    ... further detectors ...
        # </detectors>
        print 'Detectors.write_xml'
        fd.write(xm.begin('detectors', indent))

        ids = self.get_ids()
        scenario = self.get_scenario()
        get_sumoinfo_from_id_lane = scenario.net.lanes.get_sumoinfo_from_id_lane
        for id_detector, ids_lane, pos in zip(
            ids,
            self.ids_lanes[ids],
            self.positions[ids],
        ):

            print '  write id_detector', id_detector, 'ids_lane', ids_lane
            if ids_lane is not None:
                ind_lane = 0
                for id_lane in ids_lane:
                    fd.write(xm.start('detectorDefinition', indent=indent+2))
                    fd.write(xm.num('id', self.get_id_xml_detector(id_detector, ind_lane)))
                    fd.write(xm.num('lane', get_sumoinfo_from_id_lane(id_lane)))
                    fd.write(xm.num('pos', pos))

                    fd.write(xm.stopit())  # ends detector defs
                    ind_lane += 1
        fd.write(xm.end('detectors', indent))
Пример #9
0
    def export_sumoxml(self, filepath=None, encoding='UTF-8'):
        """
        Export stops to SUMO stop xml file.
        """
        print 'export_sumoxml', filepath, len(self)
        if len(self) == 0:
            return None

        if filepath is None:
            filepath = self.get_stopfilepath()

        try:
            fd = open(filepath, 'w')
        except:
            print 'WARNING in write_obj_to_xml: could not open', filepath
            return False
        #xmltag, xmltag_item, attrname_id = self.xmltag
        fd.write('<?xml version="1.0" encoding="%s"?>\n' % encoding)
        indent = 0
        #fd.write(xm.begin('routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.sf.net/xsd/routes_file.xsd"',indent))

        fd.write(xm.begin('additional', indent))

        self.write_xml(fd, indent+2)

        fd.write(xm.end('additional', indent))
        fd.close()
        return filepath
Пример #10
0
    def export_trips_xml(self,
                         filepath=None,
                         encoding='UTF-8',
                         ids_vtype_exclude=[]):
        """
        Export trips to SUMO xml file.
        Method takes care of sorting trips by departure time.
        """
        if filepath == None:
            filepath = self.get_tripfilepath()
        print 'export_trips_xml', filepath
        try:
            fd = open(filepath, 'w')
        except:
            print 'WARNING in write_obj_to_xml: could not open', filepath
            return False

        xmltag, xmltag_item, attrname_id = self.xmltag
        fd.write('<?xml version="1.0" encoding="%s"?>\n' % encoding)
        fd.write(xm.begin(xmltag))
        indent = 2

        ids_trip = self.times_depart.get_ids_sorted()
        ids_vtype = self.ids_vtype[ids_trip]
        #ids_vtypes_exclude = self.ids_vtype.get_ids_from_indices(vtypes_exclude)

        inds_selected = np.ones(len(ids_vtype), np.bool)
        for id_vtype in ids_vtype_exclude:
            inds_selected[ids_vtype == id_vtype] = False
        ids_trip_selected = ids_trip[inds_selected]
        ids_vtype_selected = set(ids_vtype[inds_selected])
        #ids_vtypes_selected = set(ids_vtypes).difference(ids_vtypes_exclude)

        self.parent.vtypes.write_xml(fd,
                                     indent=indent,
                                     ids=ids_vtype_selected,
                                     is_print_begin_end=False)

        self.write_xml(fd,
                       indent=indent,
                       ids=ids_trip_selected,
                       attrconfigs_excluded=[self.routes, self.ids_routes],
                       is_print_begin_end=False)

        fd.write(xm.end(xmltag))
        fd.close()
        return filepath
Пример #11
0
    def export_trips_xml(self, filepath=None, encoding='UTF-8',
                         ids_vtype_exclude=[]):
        """
        Export trips to SUMO xml file.
        Method takes care of sorting trips by departure time.
        """
        if filepath is None:
            filepath = self.get_tripfilepath()
        print 'export_trips_xml', filepath
        try:
            fd = open(filepath, 'w')
        except:
            print 'WARNING in write_obj_to_xml: could not open', filepath
            return False

        xmltag, xmltag_item, attrname_id = self.xmltag
        fd.write('<?xml version="1.0" encoding="%s"?>\n' % encoding)
        fd.write(xm.begin(xmltag))
        indent = 2

        ids_trip = self.times_depart.get_ids_sorted()
        ids_vtype = self.ids_vtype[ids_trip]
        #ids_vtypes_exclude = self.ids_vtype.get_ids_from_indices(vtypes_exclude)

        inds_selected = np.ones(len(ids_vtype), np.bool)
        for id_vtype in ids_vtype_exclude:
            inds_selected[ids_vtype == id_vtype] = False
        ids_trip_selected = ids_trip[inds_selected]
        ids_vtype_selected = set(ids_vtype[inds_selected])
        #ids_vtypes_selected = set(ids_vtypes).difference(ids_vtypes_exclude)

        self.parent.vtypes.write_xml(fd, indent=indent,
                                     ids=ids_vtype_selected,
                                     is_print_begin_end=False)

        self.write_xml(fd,     indent=indent,
                       ids=ids_trip_selected,
                       attrconfigs_excluded=[self.routes, self.ids_routes],
                       is_print_begin_end=False)

        fd.write(xm.end(xmltag))
        fd.close()
        return filepath
Пример #12
0
    def export_xml(self, fd, indent=0):
        # <fromEdge id="myEdge0">
        # <toEdge id="myEdge1" probability="0.2"/>
        # <toEdge id="myEdge2" probability="0.7"/>
        # <toEdge id="myEdge3" probability="0.1"/>
        # </fromEdge>

        fromedge_to_turnprobs = {}
        for _id in self.get_ids():
            id_fromedge = self.ids_fromedge[_id]
            if not fromedge_to_turnprobs.has_key(id_fromedge):
                fromedge_to_turnprobs[id_fromedge] = []
            fromedge_to_turnprobs[id_fromedge].append((self.ids_toedge[_id], self.probabilities[_id]))

        ids_sumoeges = self.get_edges().ids_sumo

        for id_fromedge in fromedge_to_turnprobs.keys():
            fd.write(xm.begin("fromEdge" + xm.num("id", ids_sumoeges[id_fromedge]), indent))
            for id_toedge, turnprob in fromedge_to_turnprobs[id_fromedge]:
                fd.write(xm.start("toEdge", indent + 2))
                fd.write(xm.num("id", ids_sumoeges[id_toedge]) + xm.num("probability", turnprob))
                fd.write(xm.stopit())
            fd.write(xm.end("fromEdge", indent))
Пример #13
0
    def write_xml(self, fd, indent=0, is_print_begin_end=True):
        xmltag, xmltag_item, attrname_id = self.xmltag
        layer_default = -1
        fill_default = 1
        ids_landusetype = self.ids_landusetype
        landusecolors = self.get_landusetypes().colors

        if is_print_begin_end:
            fd.write(xm.begin(xmltag, indent))

        attrsconfigs_write = [self.ids_sumo, self.osmkeys, self.shapes]
        for _id in self.get_ids():
            fd.write(xm.start(xmltag_item, indent + 2))
            for attrsconfig in attrsconfigs_write:
                attrsconfig.write_xml(fd, _id)

            landusecolors.write_xml(fd, ids_landusetype[_id])
            fd.write(xm.num("layer", layer_default))
            fd.write(xm.num("fill", fill_default))

            fd.write(xm.stopit())

        if is_print_begin_end:
            fd.write(xm.end(xmltag, indent))
Пример #14
0
    def export_routes_xml(self, filepath=None, method_routechoice=None, encoding='UTF-8'):
        """
        Export routes to SUMO xml file.
        Method takes care of sorting trips by departure time.
        """
        if method_routechoice is None:
            method_routechoice = self.get_route_first

        if filepath is None:
            filepath = self.get_routefilepath()
        print 'export_routes_xml', filepath
        try:
            fd = open(filepath, 'w')
        except:
            print 'WARNING in write_obj_to_xml: could not open', filepath
            return False

        xmltag_routes, xmltag_veh, attrname_id = ("routes", "vehicle", "ids_sumo")
        xmltag_trip = "trip"
        xmltag_rou = "route"

        fd.write('<?xml version="1.0" encoding="%s"?>\n' % encoding)
        fd.write(xm.begin(xmltag_routes))
        indent = 2

        #ids_modes_used = set(self.parent.vtypes.ids_mode[self.ids_vtype.get_value()])
        self.parent.vtypes.write_xml(fd, indent=indent,
                                     ids=set(self.ids_vtype.get_value()),
                                     is_print_begin_end=False
                                     )

        ids_mode = self.parent.vtypes.ids_mode
        id_pedestrian = MODES['pedestrian']
        routes = self.routes.get_value()

        # here we could write the route info
        # but we do write it inside each trip so that it can be parsed
        # in the same way as duarouter output
        # routes.write_xml(   fd, indent=indent,
        #                    attrconfigs_excluded = [routes.costs, routes.probabilities],
        #                    is_print_begin_end = False)

        # let's write trip info manually
        tripconfigs = [self.ids_vtype,
                       self.times_depart,
                       self.ids_edge_depart,
                       self.ids_edge_arrival,
                       self.inds_lane_depart,
                       self.positions_depart,
                       self.speeds_depart,
                       self.inds_lane_arrival,
                       self.positions_arrival,
                       self.speeds_arrival,
                       ]

        routeconfigs = [routes.ids_edges,
                        routes.colors,
                        ]

        attrconfig_id = getattr(self.get_attrsman(), attrname_id)
        xmltag_id = attrconfig_id.xmltag

        for id_trip in self.times_depart.get_ids_sorted():

            if ids_mode[self.ids_vtype[id_trip]] == id_pedestrian:
                self.write_persontrip_xml(fd, id_trip,
                                          method_routechoice=method_routechoice,
                                          indent=indent+2)

            else:
                id_route = method_routechoice(id_trip)
                if id_route >= 0:  # a valid route has been found
                    # init vehicle route only if valid route exists
                    fd.write(xm.start(xmltag_veh, indent+2))
                else:
                    # init trip instead of route
                    fd.write(xm.start(xmltag_trip, indent+2))

                # print '   make tag and id',_id
                fd.write(xm.num(xmltag_id, attrconfig_id[id_trip]))

                # print ' write columns',len(scalarcolconfigs)>0,len(idcolconfig_include_tab)>0,len(objcolconfigs)>0
                for attrconfig in tripconfigs:
                    # print '    attrconfig',attrconfig.attrname
                    attrconfig.write_xml(fd, id_trip)

                if id_route >= 0:  # a valid route has been found
                    # write route id
                    #fd.write(xm.num('route', id_route ))

                    # instead of route id we write entire route here
                    fd.write(xm.stop())
                    fd.write(xm.start(xmltag_rou, indent+4))
                    for attrconfig in routeconfigs:
                        # print '    attrconfig',attrconfig.attrname
                        attrconfig.write_xml(fd, id_route)

                    # end route and vehicle
                    fd.write(xm.stopit())
                    fd.write(xm.end(xmltag_veh, indent+2))

                else:
                    # end trip without route
                    fd.write(xm.stopit())

        fd.write(xm.end(xmltag_routes))
        fd.close()
        return filepath
Пример #15
0
    def export_flows_and_turns(self,
                               flowfilepath,
                               turnsfilepath,
                               id_mode,
                               indent=0):
        """
        Create the flow file and turn ratios file for a specific mode.
        In the SUMOpy tunflow data structure, each mode has its own 
        flow and turnratio data.
        """
        print '\n\n' + 79 * '_'
        print 'export_flows_and_turns id_mode=', id_mode, 'ids_vtype=', self.parent.vtypes.select_by_mode(
            id_mode)
        print '  write flows', flowfilepath
        fd = open(flowfilepath, 'w')
        fd.write(xm.begin('flows', indent))

        # write all possible vtypes for this mode
        self.parent.vtypes.write_xml(
            fd,
            indent=indent,
            ids=self.parent.vtypes.select_by_mode(id_mode),
            is_print_begin_end=False)

        id_flow = 0
        ids_allsourceedges = []
        time_start_min = +np.inf
        time_end_max = -np.inf
        for id_inter in self.get_ids():
            time_start = self.times_start[id_inter]
            time_end = self.times_end[id_inter]
            fd.write(
                xm.begin(
                    'interval' + xm.num('begin', time_start) +
                    xm.num('end', time_end), indent + 2))
            ids_sourceedge, id_flow = self.turnflowmodes[
                id_inter].export_flows_xml(fd, id_mode, id_flow, indent + 4)
            # print '  got ids_sourceedge, id_flow',ids_sourceedge, id_flow
            ids_allsourceedges += ids_sourceedge

            if len(ids_sourceedge) > 0:
                # print '  extend total time interval only for intervals with
                # flow'
                if time_start < time_start_min:
                    time_start_min = time_start

                if time_end > time_end_max:
                    time_end_max = time_end

            fd.write(xm.end('interval', indent + 2))

        fd.write(xm.end('flows', indent))
        fd.close()

        # print '  write turndefs', turnsfilepath
        fd = open(turnsfilepath, 'w')
        fd.write(xm.begin('turns', indent))

        for id_inter in self.get_ids():
            time_start = self.times_start[id_inter]
            time_end = self.times_end[id_inter]
            fd.write(
                xm.begin(
                    'interval' + xm.num('begin', time_start) +
                    xm.num('end', time_end), indent + 2))
            self.turnflowmodes[id_inter].export_turns_xml(
                fd, id_mode, indent + 4)
            fd.write(xm.end('interval', indent + 2))

        #  take sink edges from sink zones
        ids_sinkedge = self.get_sinkedges()  # it's a set
        # ...and remove source edges, otherwise vehicle will be inserted and
        # immediately removed
        # print '  ids_sinkedge',ids_sinkedge
        # print '  ids_allsourceedges',ids_allsourceedges
        ids_sinkedge = ids_sinkedge.difference(ids_allsourceedges)

        ids_sumoedge = self.get_edges().ids_sumo
        # print '  determined sink edges',list(ids_sinkedge)
        if len(ids_sinkedge) > 0:
            fd.write(xm.start('sink'))
            fd.write(xm.arr('edges', ids_sumoedge[list(ids_sinkedge)]))
            fd.write(xm.stopit())

        fd.write(xm.end('turns', indent))
        fd.close()
        if len(ids_allsourceedges) == 0:
            time_start_min = 0
            time_end_max = 0

        return time_start_min, time_end_max
Пример #16
0
    def export_routes_xml(self, filepath=None, method_routechoice=None, encoding='UTF-8'):
        """
        Export routes to SUMO xml file.
        Method takes care of sorting trips by departure time.
        """
        if method_routechoice == None:
            method_routechoice = self.get_route_first

        if filepath == None:
            filepath = self.get_routefilepath()
        print 'export_routes_xml', filepath
        try:
            fd = open(filepath, 'w')
        except:
            print 'WARNING in write_obj_to_xml: could not open', filepath
            return False

        xmltag_routes, xmltag_veh, attrname_id = (
            "routes", "vehicle", "ids_sumo")
        xmltag_trip = "trip"
        xmltag_rou = "route"

        fd.write('<?xml version="1.0" encoding="%s"?>\n' % encoding)
        fd.write(xm.begin(xmltag_routes))
        indent = 2

        #ids_modes_used = set(self.parent.vtypes.ids_mode[self.ids_vtype.get_value()])
        self.parent.vtypes.write_xml(fd, indent=indent,
                                     ids=set(self.ids_vtype.get_value()),
                                     is_print_begin_end=False
                                     )

        ids_mode = self.parent.vtypes.ids_mode
        id_pedestrian = MODES['pedestrian']
        routes = self.routes.get_value()

        # here we could write the route info
        # but we do write it inside each trip so that it can be parsed
        # in the same way as duarouter output
        # routes.write_xml(   fd, indent=indent,
        #                    attrconfigs_excluded = [routes.costs, routes.probabilities],
        #                    is_print_begin_end = False)

        # let's write trip info manually
        tripconfigs = [self.ids_vtype,
                       self.times_depart,
                       self.ids_edge_depart,
                       self.ids_edge_arrival,
                       self.inds_lane_depart,
                       self.positions_depart,
                       self.speeds_depart,
                       self.inds_lane_arrival,
                       self.positions_arrival,
                       self.speeds_arrival,
                       ]

        routeconfigs = [routes.ids_edges,
                        routes.colors,
                        ]

        attrconfig_id = getattr(self.get_attrsman(), attrname_id)
        xmltag_id = attrconfig_id.xmltag

        for id_trip in self.times_depart.get_ids_sorted():

            if ids_mode[self.ids_vtype[id_trip]] == id_pedestrian:
                self.write_persontrip_xml(fd, id_trip,
                                          method_routechoice=method_routechoice,
                                          indent=indent + 2)

            else:
                id_route = method_routechoice(id_trip)
                if id_route >= 0:  # a valid route has been found
                    # init vehicle route only if valid route exists
                    fd.write(xm.start(xmltag_veh, indent + 2))
                else:
                    # init trip instead of route
                    fd.write(xm.start(xmltag_trip, indent + 2))

                # print '   make tag and id',_id
                fd.write(xm.num(xmltag_id, attrconfig_id[id_trip]))

                # print ' write
                # columns',len(scalarcolconfigs)>0,len(idcolconfig_include_tab)>0,len(objcolconfigs)>0
                for attrconfig in tripconfigs:
                    # print '    attrconfig',attrconfig.attrname
                    attrconfig.write_xml(fd, id_trip)

                if id_route >= 0:  # a valid route has been found
                    # write route id
                    #fd.write(xm.num('route', id_route ))

                    # instead of route id we write entire route here
                    fd.write(xm.stop())
                    fd.write(xm.start(xmltag_rou, indent + 4))
                    for attrconfig in routeconfigs:
                        # print '    attrconfig',attrconfig.attrname
                        attrconfig.write_xml(fd, id_route)

                    # end route and vehicle
                    fd.write(xm.stopit())
                    fd.write(xm.end(xmltag_veh, indent + 2))

                else:
                    # end trip without route
                    fd.write(xm.stopit())

        fd.write(xm.end(xmltag_routes))
        fd.close()
        return filepath
Пример #17
0
    def export_amitranxml(self, filepath=None, encoding='UTF-8'):
        """
        Export flows to Amitran format that defines the demand per OD pair in time slices for every vehicle type.
        """
        print 'export_amitranxml', filepath, len(self)

        if len(self) == 0:
            return None

        if filepath is None:
            filepath = self.get_amitranfilepath()

        try:
            fd = open(filepath, 'w')
        except:
            print 'WARNING in export_sumoxml: could not open', filepath
            return False

        indent = 0

        ft = self.generate_odflows()
        scenario = self.parent.parent
        ids_zone_sumo = scenario.landuse.zones.ids_sumo
        get_vtype_for_mode = scenario.demand.vtypes.get_vtype_for_mode
        ids = ft.get_ids()
        fd.write(xm.begin('demand', indent))
        # self.parent.vtypes.write_xml(   fd, indent=indent,
        #                                #ids = ids_vtype_selected,
        #                                is_print_begin_end = False)

        # <demand>
        #   <actorConfig id="0">
        #       <timeSlice duration="86400000" startTime="0">
        #           <odPair amount="100" destination="2" origin="1"/>
        #       </timeSlice>
        #   </actorConfig>
        # </demand>

        for id_flow, time_start, time_end, id_mode, id_orig_sumo, id_dest_sumo, tripnumber in zip(
                ids, ft.times_start[ids], ft.times_end[ids], ft.ids_mode[ids],
                ids_zone_sumo[ft.ids_orig[ids]],
                ids_zone_sumo[ft.ids_dest[ids]], ft.tripnumbers[ids]):

            fd.write(xm.start('actorConfig', indent + 2))
            fd.write(
                xm.num('id', get_vtype_for_mode(id_mode=id_mode,
                                                is_sumoid=True)))
            fd.write(xm.stop())

            fd.write(xm.start('timeSlice', indent + 4))
            fd.write(xm.num('duration', int(time_end - time_start)))
            fd.write(xm.num('startTime', int(time_start)))
            fd.write(xm.stop())

            fd.write(xm.start('odPair', indent + 6))
            fd.write(xm.num('origin', id_orig_sumo))
            fd.write(xm.num('destination', id_dest_sumo))
            fd.write(xm.num('amount', int(tripnumber)))
            fd.write(xm.stopit())

            fd.write(xm.end('timeSlice', indent + 4))

            fd.write(xm.end('actorConfig', indent + 2))

        fd.write(xm.end('demand', indent))

        fd.close()
        return filepath
Пример #18
0
    def export_flows_and_turns(self, flowfilepath, turnsfilepath, id_mode, indent=0):
        """
        Create the flow file and turn ratios file for a specific mode.
        In the SUMOpy tunflow data structure, each mode has its own 
        flow and turnratio data.
        """
        print "\n\n" + 79 * "_"
        print "export_flows_and_turns id_mode=", id_mode, "ids_vtype=", self.parent.vtypes.select_by_mode(id_mode)
        print "  write flows", flowfilepath
        fd = open(flowfilepath, "w")
        fd.write(xm.begin("flows", indent))

        # write all possible vtypes for this mode
        self.parent.vtypes.write_xml(
            fd, indent=indent, ids=self.parent.vtypes.select_by_mode(id_mode), is_print_begin_end=False
        )

        id_flow = 0
        ids_allsourceedges = []
        time_start_min = +np.inf
        time_end_max = -np.inf
        for id_inter in self.get_ids():
            time_start = self.times_start[id_inter]
            time_end = self.times_end[id_inter]
            fd.write(xm.begin("interval" + xm.num("begin", time_start) + xm.num("end", time_end), indent + 2))
            ids_sourceedge, id_flow = self.turnflowmodes[id_inter].export_flows_xml(fd, id_mode, id_flow, indent + 4)
            # print '  got ids_sourceedge, id_flow',ids_sourceedge, id_flow
            ids_allsourceedges += ids_sourceedge

            if len(ids_sourceedge) > 0:
                # print '  extend total time interval only for intervals with
                # flow'
                if time_start < time_start_min:
                    time_start_min = time_start

                if time_end > time_end_max:
                    time_end_max = time_end

            fd.write(xm.end("interval", indent + 2))

        fd.write(xm.end("flows", indent))
        fd.close()

        # print '  write turndefs', turnsfilepath
        fd = open(turnsfilepath, "w")
        fd.write(xm.begin("turns", indent))

        for id_inter in self.get_ids():
            time_start = self.times_start[id_inter]
            time_end = self.times_end[id_inter]
            fd.write(xm.begin("interval" + xm.num("begin", time_start) + xm.num("end", time_end), indent + 2))
            self.turnflowmodes[id_inter].export_turns_xml(fd, id_mode, indent + 4)
            fd.write(xm.end("interval", indent + 2))

        #  take sink edges from sink zones
        ids_sinkedge = self.get_sinkedges()  # it's a set
        # ...and remove source edges, otherwise vehicle will be inserted and
        # immediately removed
        # print '  ids_sinkedge',ids_sinkedge
        # print '  ids_allsourceedges',ids_allsourceedges
        ids_sinkedge = ids_sinkedge.difference(ids_allsourceedges)

        ids_sumoedge = self.get_edges().ids_sumo
        # print '  determined sink edges',list(ids_sinkedge)
        if len(ids_sinkedge) > 0:
            fd.write(xm.start("sink"))
            fd.write(xm.arr("edges", ids_sumoedge[list(ids_sinkedge)]))
            fd.write(xm.stopit())

        fd.write(xm.end("turns", indent))
        fd.close()
        if len(ids_allsourceedges) == 0:
            time_start_min = 0
            time_end_max = 0

        return time_start_min, time_end_max
Пример #19
0
    def write_xml(self, fd, indent=0):
        """
        Write simpla xml config file
        """
        print 'Simplaconfig.write_xml'
        fd.write(xm.begin(self.xmltag, indent))
        attrsman = self.get_attrsman()
        vtypes = self.parent.get_scenario().demand.vtypes
        ids_sumo_vtypes = vtypes.ids_sumo
        # <controlRate value="0.5" />
        # <maxPlatoonGap value="15.0" />
        # <catchupDist value="100.0" />
        # <switchImpatienceFactor value="0.1" />
        # <platoonSplitTime value="3.0" />
        # <lcMode original="597" leader="597" follower="514" catchup="514" catchupFollower="514" />
        # <speedFactor original="1.0" leader="1.0" follower="2.0" catchup="2.5" catchupFollower="3.0" />
        # <verbosity value="1" />
        # <vTypeMap original="passenger1" leader="leaderVTypeID" follower="followerVTypeID" catchup="catchupVTypeID" catchupFollower="catchupFollowerVTypeID" />

        #ids_plattypes = ['catchup','follower','original']
        #ids_plattypes = self._typemap.keys()
        #ids_vtypes_plat_sumo = []
        # for id_mode in self.ids_platoonmodes:
        #    ids_vtype_sumo= ids_sumo_vtypes[vtypes.select_by_mode(id_mode=id_mode)]
        #    #print '  id_mode',id_mode,'ids_vtype',ids_vtype.tolist()
        #    for id_vtype_sumo in ids_vtype_sumo:
        #        if id_vtype in ids_plattypes
        #            #if id_vtype_sumo.split('_')[-1] not in plattypes:
        #            ids_vtypes_plat_sumo.append(id_vtype_sumo)

        ids_vtypes_plat_sumo = ids_sumo_vtypes[self._typemap.keys()]
        fd.write(xm.start('vehicleSelectors', indent+2))
        fd.write(xm.arr('value', ids_vtypes_plat_sumo, sep=','))
        fd.write(xm.stopit())

        fd.write(xm.start('lcMode', indent+2))
        fd.write(xm.num('leader', self.lanechangemode_leader))
        fd.write(xm.num('follower', self.lanechangemode_follower))
        fd.write(xm.num('catchup', self.lanechangemode_catchup))
        fd.write(xm.num('catchupFollower', self.lanechangemode_catchup_follower))
        fd.write(xm.stopit())

        fd.write(xm.start('speedFactor', indent+2))
        fd.write(xm.num('original', 1.0))
        fd.write(xm.num('leader', self.speedfactor_leader))
        fd.write(xm.num('follower', self.speedfactor_follower))
        fd.write(xm.num('catchup', self.speedfactor_catchup))
        fd.write(xm.num('catchupFollower', self.speedfactor_catchup_follower))
        fd.write(xm.stopit())

        for plattypes in self._typemap.values():
            fd.write(xm.start('vTypeMap', indent+2))
            for plattype, id_vtype in plattypes.iteritems():
                fd.write(xm.num(plattype, ids_sumo_vtypes[id_vtype]))
            fd.write(xm.stopit())

        for attrconfig in attrsman.get_configs():
            if attrconfig.xmltag is not None:
                if (attrconfig.xmltag == 'switchImpatienceFactor') & (attrconfig.get_value() < 0):
                    pass
                else:
                    fd.write(xm.start(attrconfig.xmltag, indent+2))
                    fd.write(xm.num('value', attrconfig.format_value()))
                    fd.write(xm.stopit())

        fd.write(xm.end(self.xmltag, indent))