Esempio n. 1
0
def getGearySubNet():

    projectFolder = os.path.join(mainFolder, 'dynameqNetwork_gearySubset')
    prefix = 'smallTestNet' 

    scenario = dta.DynameqScenario(dta.Time(0,0), dta.Time(12,0))
    scenario.read(projectFolder, prefix) 
    net = dta.DynameqNetwork(scenario) 
    net.read(projectFolder, prefix)

    simStartTimeInMin = 0
    simEndTimeInMin = 60
    simTimeStepInMin = 15
    
    net._simStartTimeInMin = simStartTimeInMin
    net._simEndTimeInMin = simEndTimeInMin
    net._simTimeStepInMin = simTimeStepInMin

    for link in net.iterLinks():
        if link.isVirtualLink():
            continue
        link.simTimeStepInMin = simTimeStepInMin
        link.simStartTimeInMin = simStartTimeInMin
        link.simEndTimeInMin = simEndTimeInMin
        for mov in link.iterOutgoingMovements():
            mov.simTimeStepInMin = simTimeStepInMin
            mov.simStartTimeInMin = simStartTimeInMin
            mov.simEndTimeInMin = simEndTimeInMin

    for link in net.iterLinks():
        if link.isVirtualLink():
            continue
        if link.isConnector():
            continue
        link._label  = str(link.getId())

        link.setObsCount(0, 60, random.randint(150, 450))
        
        for mov in link.iterOutgoingMovements():
            
            mov.setObsCount(0, 60, random.randint(50, 150))
            
            for start, end in izip(range(0, 60, 15), range(15, 61, 15)):
                mov.setSimOutVolume(start, end, random.randint(20, 50))
                mov.setSimInVolume(start, end, random.randint(20, 50))
                mov.cost = link.euclideanLength()
                randInt = random.randint(2,4) 
                tt = mov.getFreeFlowTTInMin() * float(randInt)
                mov.setSimTTInMin(start, end, tt)

    
    return net 
        elif opt == "-l":
            OUTPUT_LINK_SHAPEFILE = arg

    # The SanFrancisco network will use feet for vehicle lengths and coordinates, and miles for link lengths
    dta.VehicleType.LENGTH_UNITS = "feet"
    dta.Node.COORDINATE_UNITS = "feet"
    dta.RoadLink.LENGTH_UNITS = "miles"

    dta.setupLogging("createSFNetworkFromCubeNetwork.INFO.log",
                     "createSFNetworkFromCubeNetwork.DEBUG.log",
                     logToConsole=True)

    # The rest of San Francisco currently exists as a Cube network.  Initialize it from
    # the Cube network files (which have been exported to dbfs.)
    # This is where we define the :py:class:`dta.Scenario`
    sanfranciscoScenario = dta.DynameqScenario(dta.Time(14, 30),
                                               dta.Time(21, 30))

    # We will have 4 vehicle classes: Car_NoToll, Car_Toll, Truck_NoToll, Truck_Toll
    # We will provide demand matrices for each of these classes
    sanfranciscoScenario.addVehicleClass("Car_NoToll")
    sanfranciscoScenario.addVehicleClass("Car_Toll")
    sanfranciscoScenario.addVehicleClass("Truck_NoToll")
    sanfranciscoScenario.addVehicleClass("Truck_Toll")
    # Transit is an implicit type

    # length is in feet (from above), response time is in seconds, maxSpeed is in mi/hour
    # We have only 2 vehicle types                      Type        VehicleClass    Length  RespTime    MaxSpeed    SpeedRatio
    sanfranciscoScenario.addVehicleType(
        dta.VehicleType("Car", "Car_NoToll", 21, 1, 100.0, 100.0))
    sanfranciscoScenario.addVehicleType(
Esempio n. 3
0
    def toTransitLine(self,
                      dtaNetwork,
                      dtaRouteId,
                      MODE_TO_LITYPE,
                      MODE_TO_VTYPE,
                      headwayIndex,
                      startTime,
                      demandDurationInMin,
                      doShortestPath=True,
                      maxShortestPathLen=4):
        """
        Convert this instance to an equivalent DTA transit line(s).  Returns list of instances of 
        :py:class:`TransitLine`.
        
        Links on the route are checked against the given *dtaNetwork* (an instance of :py:class:`Network`).
        If *doShortestPath* is True, then a shortest path is searched for on the *dtaNetwork* and that
        is included (so this is assuming that the calling instance is missing some nodes; this can happen, for example, 
        if the DTA network has split links for centroid connectors, etc.).
        If *doShortestPath* is True then any shortest path segments longer than *maxShortestPathLen*
        are dropped (e.g. if they're Light rail segments underground) and a second 

        Other arguments:
        
        * *dtaRouteId* is the id number for the new :py:class:`TransitLine` instance.
        * *MODE_TO_LITYPE* maps the :py:attr:`TPPlusTransitRoute.mode` attribute (strings) to a line type
          (either :py:attr:`TransitLine.LINE_TYPE_BUS` or :py:attr:`TransitLine.LINE_TYPE_TRAM`)
        * *MODE_TO_VTYPE* maps the :py:attr:`TPPlusTransitRoute.mode` attribute (strings) to a 
          :py:class:`VehicleType` name
        * *headwayIndex* is the index into the frequencies to use for the headway (for use with
          :py:meth:`TPPlusTransitRoute.getHeadway`)
        * *startTime* is the start time for the bus line (and instance of :py:class:`Time`),
          and *demandDurationInMin* is used for calculating the number of transit vehicle
          departures that will be dispatched.
        
        Note that the start time for the :py:class:`TransitLine` instance will be randomized within 
        [*startTime*, *startTime* + the headway).        
        """

        transitLines = []

        dNodeSequence = []
        for tNode in self.iterTransitNodes():
            if not dtaNetwork.hasNodeForId(tNode.nodeId):
                dta.DtaLogger.debug(
                    'Node id %d does not exist in the Dynameq network' %
                    tNode.nodeId)
                continue
            dNode = dtaNetwork.getNodeForId(tNode.nodeId)
            dNodeSequence.append(dNode)

        if len(dNodeSequence) == 0:
            dta.DtaLogger.error(
                'Tpplus route %-15s cannot be converted to Dynameq because '
                'none of its nodes is in the Dynameq network' % self.name)

        if len(dNodeSequence) == 1:
            dta.DtaLogger.error(
                'Tpplus route %-15s cannot be converted to Dyanmeq because only '
                'one of its nodes is in the Dynameq network' % self.name)

        # randomize the start time within [startTime, startTime+headway)
        headway_secs = int(60 * self.getHeadway(headwayIndex))
        rand_offset_secs = random.randint(0, headway_secs - 1)
        # need a datetime version of this to add the delta
        start_datetime = datetime.datetime(1, 1, 1, startTime.hour,
                                           startTime.minute, startTime.second)
        random_start = start_datetime + datetime.timedelta(
            seconds=rand_offset_secs)

        dRoute = dta.TransitLine(
            net=dtaNetwork,
            id=dtaRouteId,
            label=self.name,
            litype=MODE_TO_LITYPE[self.mode],
            vtype=MODE_TO_VTYPE[self.mode],
            stime=dta.Time(random_start.hour, random_start.minute,
                           random_start.second),
            level=0,
            active=dta.TransitLine.LINE_ACTIVE,
            hway=self.getHeadway(headwayIndex),
            dep=int(
                float(demandDurationInMin) / self.getHeadway(headwayIndex)))
        transitLines.append(dRoute)

        for dNodeA, dNodeB in itertools.izip(dNodeSequence, dNodeSequence[1:]):

            if dtaNetwork.hasLinkForNodeIdPair(dNodeA.getId(), dNodeB.getId()):
                dLink = dtaNetwork.getLinkForNodeIdPair(
                    dNodeA.getId(), dNodeB.getId())
                dSegment = dRoute.addSegment(dLink,
                                             0,
                                             label='%d_%d' %
                                             (dNodeA.getId(), dNodeB.getId()))

                tNodeB = self.getTransitNode(dNodeB.getId())
                dSegment.dwell = 60 * self.getTransitDelay(dNodeB.getId())
            else:
                # if we're not doing shortest path, nothing to do -- just move on
                if not doShortestPath: continue

                # dta.DtaLogger.debug('Running the SP from node %d to %d' % (dNodeA.getId(), dNodeB.getId()))
                try:
                    dta.ShortestPaths.labelSettingWithLabelsOnNodes(
                        dtaNetwork, dNodeA, dNodeB)
                    assert (dNodeB.label < sys.maxint)
                except:
                    dta.DtaLogger.error("Error: %s" % str(sys.exc_info()))
                    dta.DtaLogger.error(
                        "Tpplus route %-15s No shortest path found from %d to %d"
                        % (self.name, dNodeA.getId(), dNodeB.getId()))
                    continue

                pathNodes = dta.ShortestPaths.getShortestPathBetweenNodes(
                    dNodeA, dNodeB)

                # Warn on this because it's a little odd
                if len(pathNodes) - 1 > maxShortestPathLen:
                    pathnodes_str = ""
                    for pathNode in pathNodes:
                        pathnodes_str += "%d " % pathNode.getId()
                    dta.DtaLogger.warn(
                        'Tpplus route %-15s shortest path from %d to %d is long: %s; dropping'
                        % (self.name, dNodeA.getId(), dNodeB.getId(),
                           pathnodes_str))
                    # make a new TransitLine for the next portion
                    dRoute = dta.TransitLine(
                        net=dtaNetwork,
                        id=dtaRouteId + 1,
                        label="%s_%d" % (self.name, len(transitLines)),
                        litype=MODE_TO_LITYPE[self.mode],
                        vtype=MODE_TO_VTYPE[self.mode],
                        stime=dta.Time(random_start.hour, random_start.minute,
                                       random_start.second),
                        level=0,
                        active=dta.TransitLine.LINE_ACTIVE,
                        hway=self.getHeadway(headwayIndex),
                        dep=int(
                            float(demandDurationInMin) /
                            self.getHeadway(headwayIndex)))
                    transitLines.append(dRoute)
                    continue

                nodeNumList = [dNodeA.getId()]
                for pathNodeA, pathNodeB in itertools.izip(
                        pathNodes, pathNodes[1:]):
                    nodeNumList.append(pathNodeB.getId())
                    dLink = dtaNetwork.getLinkForNodeIdPair(
                        pathNodeA.getId(), pathNodeB.getId())
                    dSegment = dRoute.addSegment(
                        dLink,
                        0,
                        label='%d_%d' % (dNodeA.getId(), dNodeB.getId()))

            # add delay
            tNodeB = self.getTransitNode(dNodeB.getId())
            dSegment.dwell = 60 * self.getTransitDelay(dNodeB.getId())

        dRoute.isPathValid()
        return transitLines
            OUTPUT_LINK_SHAPEFILE = arg

    # The SanFrancisco network will use feet for vehicle lengths and coordinates, and miles for link lengths
    dta.VehicleType.LENGTH_UNITS = "feet"
    dta.Node.COORDINATE_UNITS = "feet"
    dta.RoadLink.LENGTH_UNITS = "miles"

    dta.setupLogging("createSFNetworkFromCubeNetwork.INFO.log",
                     "createSFNetworkFromCubeNetwork.DEBUG.log",
                     logToConsole=True)

    # The rest of San Francisco currently exists as a Cube network.  Initialize it from
    # the Cube network files (which have been exported to dbfs.)
    # This is where we define the :py:class:`dta.Scenario`
    sanfranciscoScenario = dta.DynameqScenario(dta.Time(05, 30),
                                               dta.Time(12, 30))

    # We will have 4 vehicle classes: Car_NoToll, Car_Toll, Truck_NoToll, Truck_Toll
    # We will provide demand matrices for each of these classes
    sanfranciscoScenario.addVehicleClass("Car_NoToll")
    sanfranciscoScenario.addVehicleClass("Car_Toll")
    sanfranciscoScenario.addVehicleClass("Truck_NoToll")
    sanfranciscoScenario.addVehicleClass("Truck_Toll")
    # Transit is an implicit type

    # length is in feet (from above), response time is in seconds, maxSpeed is in mi/hour
    # We have only 2 vehicle types                      Type        VehicleClass    Length  RespTime    MaxSpeed    SpeedRatio
    sanfranciscoScenario.addVehicleType(
        dta.VehicleType("Car", "Car_NoToll", 21, 1, 100.0, 100.0))
    sanfranciscoScenario.addVehicleType(
        dta.VehicleType("Car", "Car_Toll", 21, 1, 100.0, 100.0))
Esempio n. 5
0
    dtaTransitLineId = 1
    for transit_file in TRANSIT_LINES:
        dta.DtaLogger.info("===== Processing %s ======" % transit_file)

        for tpplusRoute in dta.TPPlusTransitRoute.read(net, transit_file):
            # ignore if there's no frequency for this time period
            if tpplusRoute.getHeadway(1) == 0: continue

            dtaTransitLines = tpplusRoute.toTransitLine(
                net,
                dtaTransitLineId,
                MODE_TO_LITYPE,
                MODE_TO_VTYPE,
                headwayIndex=1,
                startTime=dta.Time(6, 30),
                demandDurationInMin=3 * 60)

            for dtaTransitLine in dtaTransitLines:
                # ignore if no segments for the DTA network
                if dtaTransitLine.getNumSegments() == 0: continue

                # check if the movements are allowed
                dtaTransitLine.checkMovementsAreAllowed(enableMovement=True)

                output_file.write(dtaTransitLine.getDynameqStr())
                dtaTransitLineId += 1

    output_file.close()

    net.write(".", "sf_trn")