def __init__(self,
                 origNode,
                 destNode,
                 depTime,
                 trainList,
                 transferStation=None):

        assert( (origNode is not None) and (destNode is not None) and (depTime is not None) ),\
            "%s (%.2f) to %s" % (origNode, depTime, destNode)

        #recover or resample faulty gate IDs
        if origNode not in Parameter.rocktGateIDSetIn:
            if origNode in Parameter.rocktGateIDCorrectionDict.keys():
                origNode = Parameter.rocktGateIDCorrectionDict[origNode]
            elif origNode in Parameter.utrechtCorruptedGateIDs:
                origNode = weightedChoice(Parameter.utrechtGateFrequencyDict)

        if origNode in Parameter.rocktInGateResampleDict.keys():
            sampleGateDict = Parameter.rocktInGateResampleDict[origNode]
            origNode = weightedChoice(sampleGateDict)

        assert (
            origNode
            in Parameter.rocktGateIDSetIn), "origNode (%s) invalid" % origNode

        #recover or resample faulty gate IDs
        if destNode not in Parameter.rocktGateIDSetOut:
            if destNode in Parameter.rocktGateIDCorrectionDict.keys():
                destNode = Parameter.rocktGateIDCorrectionDict[destNode]
            elif destNode in Parameter.utrechtCorruptedGateIDs:
                destNode = weightedChoice(Parameter.utrechtGateFrequencyDict)
        assert (
            destNode
            in Parameter.rocktGateIDSetOut), "destNode (%s) invalid" % destNode

        self.origNode = 'G' + str(origNode)  #append NS gate node names by G
        self.destNode = 'G' + str(destNode)  #append NS gate node names by G

        self.depTime = float(depTime)  #check if departure time is numeric
        assert (depTime >= 0), "negative depTime not allowed (%s)" % depTime

        self.transferStation = transferStation

        if isinstance(trainList, int):
            self.trainList = list()
            self.trainList.append(trainList)
        elif isinstance(trainList, list):
            self.trainList = trainList
        else:
            print("Warning: Could not read trainList.")
Exemplo n.º 2
0
    def assignVehicle(self, boardLinkID, trainName, trainDict,
                      streamIDDictRev):
        #dictionary containing for each vehID an assignment probability
        vehIDAssgFrac = self.getBoardAssgFrac(boardLinkID, trainName,
                                              trainDict, streamIDDictRev)

        return weightedChoice(vehIDAssgFrac)
Exemplo n.º 3
0
    def getLinkList(self, origLinkID, destLinkID, pedNet, popMemory):
        #discrete choice approach

        linkList = list()

        origNode = pedNet.getLinkDestNode(origLinkID)
        destNode = pedNet.getLinkOrigNode(destLinkID)

        #if (origNode,destNode) not in popMemory.odPathDict:
        #shortestNodeList = pedNet.getShortestPath(origNode,destNode)
        #print("OD pair (%s,%s) is not connected. Shortest path: %s" % (origNode,destNode,shortestNodeList))

        pathSet = popMemory.odPathDict[origNode, destNode]

        #at least one path must exist
        assert (len(pathSet) > 0)

        if (len(pathSet) == 1):
            pathID = next(iter(pathSet))

        else:

            pathIDUtilDict = dict()

            for curPathID in pathSet:
                pathIDUtilDict[
                    curPathID] = self.personalMemory.getExpPathUtility(
                        curPathID)

            pathID = weightedChoice(pathIDUtilDict, normalize=True)

            if self.chosenPathID is None:
                self.chosenPathID = pathID
            else:
                raise Exception(
                    "Error: Only a single choice per pedestrian allowed for learning. \
                    The pathSet %s contains more than one element." %
                    str(pathSet))

        nodeList = popMemory.pathDict[pathID]

        #shortest route from downstream node of origLink to upstream node of destLink
        #nodeList = pedNet.getShortestPath(origNode,destNode)

        for linkNum in range(0, len(nodeList) - 1):
            upNode = nodeList[linkNum]
            downNode = nodeList[linkNum + 1]

            linkID = pedNet.getLinkID(upNode, downNode)

            linkList.append(linkID)

        #add destLinkID to linkList
        linkList.append(destLinkID)

        return linkList
Exemplo n.º 4
0
    def propagate(self, simEnv, pedNet, transSys, popMemory):

        curActNumber = 0

        curEpisodeID = None
        #curEpisodeStartTime = 0
        curEpisodeUtility = 0

        self.totalTravelUtility = 0
        self.totalWalkUtility = 0
        self.totalWaitUtility = 0
        self.totalRideUtility = 0
        self.totalPenalty = 0  #for missed trains, or chance to miss train

        while (curActNumber < len(self.activitySequence)):
            curActivity = self.activitySequence[curActNumber]

            actType = curActivity.actType
            param = curActivity.param

            #episodes: choosePathAndWalk + waitAndBoard, choosePathAndWalk + Exit, rideAndAlight

            if ('init' == actType):

                #delay pedestrian by his departure time
                yield simEnv.timeout(param['depTime'])
                timeDep = simEnv.now

                #initialize pedestrian on desired link
                linkID = param['linkID']

                #get area of origin link
                origArea = pedNet.getAreaFromLinkID(linkID)
                self.resReqEvent = origArea.getResReqEvent()

                #try to get slot on area and update current link
                yield self.resReqEvent
                self.curLinkID = linkID

                #no delay between planned and actual initialization time
                timeAdmitted = simEnv.now

                if (timeAdmitted > timeDep):
                    delayStr = "Late initialization by %.1f on link (%s,%s), admitted at %.1f instead of %.1f"\
                    % (timeAdmitted-timeDep, pedNet.streamIDDict[self.curLinkID], timeAdmitted, timeDep)

                    print(delayStr)

            elif ('choosePathAndWalk' == actType):

                assert ('linkIDSet' in param)
                destLinkIDSet = param['linkIDSet']

                #set of all feasible paths to any of the destLinkIDs
                pathIDset = set()

                origNode = pedNet.getLinkOrigNode(self.curLinkID)

                for destLinkID in destLinkIDSet:
                    destNode = pedNet.getLinkDestNode(destLinkID)
                    curPathIDSet = popMemory.getPathSet(
                        origNode, destNode, pedNet)

                    pathIDset.update(curPathIDSet)

                #at least one path must exist
                assert (len(pathIDset) > 0)

                #dictionary of logsum of utility of all decision paths that are compatible with a given path ID
                pathIDUtilDict = dict()

                #previous episode: update choice set for correct computation of logsum
                if len(self.episodeIDList) > 0:
                    updateChoiceTree = True
                    prevEpisode = self.personalMemory.episodeDict[
                        self.episodeIDList[-1]]
                else:
                    updateChoiceTree = False

                #simple path choice model that neglects correlation/overlap
                #reasonable approximation for paid areas with unique path between any OD (no path choice would be even needed)
                for pathID in pathIDset:
                    pathIDUtilDict[
                        pathID] = self.personalMemory.getPathPotential(
                            curActNumber, pathID)

                    if updateChoiceTree:
                        #probability of availability of a path is always one
                        prevEpisode.nextEpisodeDict[(curActNumber, pathID)] = 1

                chosenPathID = weightedChoice(pathIDUtilDict, normalize=True)

                curEpisodeID = (curActNumber, chosenPathID)
                self.episodeIDList.append(curEpisodeID)
                self.personalMemory.initializeEpisode(curEpisodeID)
                #curEpisodeStartTime = simEnv.now
                curEpisodeUtility = 0

                timeLinkAdmission = simEnv.now  #register time at which pedestrian has been admitted to current link

                linkList = popMemory.getLinkList(chosenPathID, pedNet)

                if not linkList:
                    #if linkList is empty, transfer on same boarding area
                    #change pedestrian from alighting to boarding link
                    alightLinkName = pedNet.streamIDDict[self.curLinkID]
                    boardLinkName = alightLinkName[::-1]
                    boardLinkID = pedNet.streamIDDictRev[boardLinkName]

                    linkList = [boardLinkID]

                assert (linkList), "linkList must not be empty"

                for nextLinkID in linkList:
                    curAreaID = pedNet.getAreaIDFromLinkID(self.curLinkID)
                    curArea = pedNet.getArea(curAreaID)
                    curArea.resource.updateCost(
                    )  #required for pedestrians alighting from train

                    nextAreaID = pedNet.getAreaIDFromLinkID(nextLinkID)

                    #if changing area, need to book slot in new area and release old
                    if (curAreaID != nextAreaID):
                        nextArea = pedNet.getArea(nextAreaID)

                        #get interface
                        interfaceID = pedNet.getInterfaceID(
                            curAreaID, nextAreaID)

                        if interfaceID is not None:
                            interface = pedNet.getInterface(interfaceID)

                            #get wait time needed to enforce flow capacity at interface
                            interfaceWaitTime = interface.getWaitTime(simEnv)

                            #wait at interface, while remaining registered on current area
                            yield simEnv.timeout(interfaceWaitTime)

                        elif Parameter.showWarnings:
                            pedNet.interfaceDebugSet.add(
                                "No interface between areas %s and %s available."
                                % (curAreaID, nextAreaID))

                        #once interface passed, prepare accessing of area
                        nextAreaResReqEvent = nextArea.getResReqEvent()

                        #try to get slot on area, release previous area, and update area request handler
                        yield nextAreaResReqEvent
                        curArea.getRelease(self.resReqEvent)
                        self.resReqEvent = nextAreaResReqEvent

                    #add walking cost to travel cost of episode
                    if simEnv.now != timeLinkAdmission:
                        curArea.resource.updateCost()
                        walkingCost = curArea.getWalkingCost(
                            timeLinkAdmission, simEnv.now)
                        curEpisodeUtility -= walkingCost

                        #register time of admittance to new link
                        timeLinkAdmission = simEnv.now

                    #update link
                    self.curLinkID = nextLinkID

                    if Parameter.textOutput or self.param.isFinalInstance:
                        self.logEntry(pedNet, transSys, simEnv)

                    #book pedestrian during walking
                    yield simEnv.timeout(self.getStreamTravelTime(pedNet))

                #generate time stamp in cumulative area travel cost and add cost for last link traversal
                curArea = pedNet.getArea(
                    pedNet.getAreaIDFromLinkID(self.curLinkID))
                curArea.resource.updateCost()
                walkingCost = curArea.getWalkingCost(timeLinkAdmission,
                                                     simEnv.now)
                curEpisodeUtility -= walkingCost

                self.totalWalkUtility += curEpisodeUtility

            elif ('waitAndBoard' == actType):

                trainName = param['trainID']
                train = transSys.trainDict[trainName]

                assert(self.curLinkID in pedNet.boardingLinkPlatformDict.keys()), \
                    "link %s %s not a boarding link, pedestrian awaiting train %s may have got lost at time %.2f. \nLogBook of affected traveler:\n%s\nActivity Sequence:\n%s" % \
                    (self.curLinkID, pedNet.streamIDDict[self.curLinkID], trainName, simEnv.now, ''.join('{}: {}\n'.format(*logEntry) for logEntry in self.logBook), "".join("{}: {}\n".format(k, v) for k, v in self.activitySequence.items()) )

                curPlatformName = pedNet.boardingLinkPlatformDict[
                    self.curLinkID]

                curAreaID = pedNet.getAreaIDFromLinkID(self.curLinkID)
                curArea = pedNet.getArea(curAreaID)

                timePlatformArrival = simEnv.now

                #if train already departed
                if (train.getDepartureEvent(curPlatformName).processed):
                    #print('Missed my train. Will leave the simulation.')

                    #penalize missing the train with a high travel cost
                    curEpisodeUtility -= Parameter.costMissedTrain
                    self.totalPenalty -= Parameter.costMissedTrain

                    #increase walking speed multiplier
                    self.personalMemory.speedMultiplier = min(
                        self.personalMemory.speedMultiplier *
                        Parameter.speedMultiplierIncrease,
                        Parameter.maxSpeedMultiplier)

                    #add entry in log book
                    self.logBook.append(
                        [simEnv.now, "Missed train. Leaving simulation."])

                    if Parameter.showWarnings and self.personalMemory.speedMultiplier == Parameter.maxSpeedMultiplier:
                        print(
                            "Missed train %s: Reached platform %s %.1fs late, train left at %.1f. (Using maximum speed multiplier %.1f)."
                            %
                            (trainName, curPlatformName, timePlatformArrival -
                             train.getDepTimeForPlatform(curPlatformName),
                             train.getDepTimeForPlatform(curPlatformName),
                             self.personalMemory.speedMultiplier))

                    #leave simulation
                    curArea.getRelease(self.resReqEvent)
                    simEnv.exit()

                else:
                    yield train.getArrivalEvent(curPlatformName)

                    platform = pedNet.platformDict[curPlatformName]

                    #add available set of vehicles to choice set of current episode
                    curEpisode = self.personalMemory.episodeDict[
                        self.episodeIDList[-1]]


                    vehIDAssgFrac = platform.getBoardAssgFrac(self.curLinkID, trainName,\
                        transSys.trainDict, pedNet.streamIDDictRev)

                    #Availability of car given by assignment probability (no active choice!)
                    for vehID, vehChoiceProb in vehIDAssgFrac.items():
                        curEpisode.nextEpisodeDict[(curActNumber + 1,
                                                    vehID)] = vehChoiceProb

                    #on lateral platform sectors, train cars may not cover full sector length
                    #given a uniform distribution along a sector represented by a boarding link, service probability given by
                    trainServiceProbability = platform.boardLinkServiceProbability[
                        trainName][self.curLinkID]

                    #penalty due to limited service (requiring walking) approximated by transfer penalty
                    penaltyNoLocalTrainService = (
                        1 - trainServiceProbability) * Parameter.penaltyTrans

                    #penalize additional walking
                    curEpisodeUtility -= penaltyNoLocalTrainService
                    self.totalPenalty -= penaltyNoLocalTrainService

                    #get train vehicle from boarding link (weighted random choice)
                    trainVehID = platform.assignVehicle(
                        self.curLinkID, trainName, transSys.trainDict,
                        pedNet.streamIDDictRev)
                    #weightedChoice(platform.linkVehAssg[train.numVehicles,self.curLinkID])
                    trainVehicle = train.vehicleDict[trainVehID]

                    #once train has arrived, queue up to board
                    with trainVehicle.requestBoarding(
                    ) as boardReq:  #generate request event
                        #wait for access
                        yield boardReq

                        #check out from area
                        curArea.getRelease(self.resReqEvent)
                        self.curLinkID = None
                        self.ridingTrainName = param['trainID']
                        self.curVehID = trainVehID

                        #waiting cost
                        #account for waiting cost except if pedestrian arrived before simulation started
                        if not timePlatformArrival < self.param.dateStartSec:
                            waitingCost = curArea.getWaitingCost(
                                timePlatformArrival, simEnv.now)
                            curEpisodeUtility -= waitingCost
                            self.totalWaitUtility -= waitingCost

                        #transfer cost: can be applied upfront as number of transfers is known in advance
                        #curEpisodeUtility -= Parameter.penaltyTrans

                        #block door while boarding
                        boardingTime = trainVehicle.boardServTime()
                        yield simEnv.timeout(boardingTime)

                        #consider boarding time in travel cost (probably negligible)
                        boardWaitCost = boardingTime * Parameter.betaIVTZero  #assume boarding time waited as IVT
                        curEpisodeUtility -= boardWaitCost
                        self.totalWaitUtility -= boardWaitCost

                        #increment passenger count
                        trainVehicle.cabin.passengerLoad += 1
                        if self.auxiliaryPassenger:
                            trainVehicle.cabin.loadAuxiliaryPassengers += 1
                        else:
                            trainVehicle.cabin.loadTrackedPassengers += 1

                    if Parameter.textOutput or self.param.isFinalInstance:
                        self.logEntry(pedNet, transSys, simEnv)

                self.personalMemory.memorizeEpisode(curEpisodeID,
                                                    curEpisodeUtility)
                self.totalTravelUtility += curEpisodeUtility

            elif ('rideAndAlight' == actType):

                assert (self.ridingTrainName is not None
                        and self.curVehID is not None)

                train = transSys.trainDict[self.ridingTrainName]
                trainVehicle = train.vehicleDict[self.curVehID]

                curEpisodeID = (curActNumber, self.curVehID)
                self.personalMemory.initializeEpisode(curEpisodeID)
                self.episodeIDList.append(curEpisodeID)
                #curEpisodeStartTime = simEnv.now
                curEpisodeUtility = 0
                timeRideStart = simEnv.now

                #cabin request and train arrival event
                self.seatReqEvent = trainVehicle.cabin.request()
                arrEvent = train.getArrivalEvent(param['platformName'])
                assert(arrEvent.processed is False), \
                    "Train %s should not have arrived yet on %s at %.2f. Passenger details: %s." %\
                    (self.ridingTrainName, param['platformName'], simEnv.now, self.activitySequence)

                #wait for free cabin or train arrival
                nextEvent = yield self.seatReqEvent | arrEvent

                #if no space available until arrival
                if arrEvent in nextEvent:
                    timeTrainArrival = simEnv.now

                    #manually compute standing cost
                    trainVehicle.cabin.updateCost()

                    ridingCost = trainVehicle.getRidingCostStanding(
                        timeRideStart, timeTrainArrival)
                    curEpisodeUtility -= ridingCost

                #if a seating space is available
                else:
                    timeSeated = simEnv.now
                    self.seated = True

                    ridingCost = trainVehicle.getRidingCostStanding(
                        timeRideStart, timeSeated)
                    curEpisodeUtility -= ridingCost

                    if Parameter.textOutput or self.param.isFinalInstance:
                        self.logEntry(pedNet, transSys, simEnv)

                    #wait for vehicle to arrive
                    yield arrEvent
                    timeTrainArrival = simEnv.now

                    #charge travel cost during seated part
                    trainVehicle.cabin.updateCost()
                    ridingCost = trainVehicle.getRidingCostSeated(
                        timeSeated, timeTrainArrival)
                    curEpisodeUtility -= ridingCost

                #once arrived, leave cabin or revoke cabin request event
                trainVehicle.cabin.release(self.seatReqEvent)
                self.seated = False
                if Parameter.textOutput or self.param.isFinalInstance:
                    self.logEntry(pedNet, transSys, simEnv)

                #get alighting link
                #alightLinkID = self.getAlightingLinkID(param['platformName'],transSys,pedNet) #obsolete
                alightingPlatformName = param['platformName']
                alightingPlatform = pedNet.platformDict[alightingPlatformName]
                alightLinkID = alightingPlatform.assignAlightLink(self.ridingTrainName, \
                    transSys.trainDict, self.curVehID, pedNet.streamIDDictRev)

                alightAreaID = pedNet.getAreaIDFromLinkID(alightLinkID)
                alightArea = pedNet.getArea(alightAreaID)
                alightAreaResReqEvent = alightArea.getResReqEvent()

                #once train has arrived, queue up to alight
                with trainVehicle.requestAlighting(
                ) as alightReq:  #generate request event
                    yield alightReq  #wait for access
                    alightingTime = trainVehicle.alightServTime()
                    yield simEnv.timeout(
                        alightingTime)  #block door while boarding

                    #once able to use door, request space on area
                    yield alightAreaResReqEvent
                    self.ridingTrainName = None
                    self.curVehID = None
                    self.resReqEvent = alightAreaResReqEvent

                    #decrement passenger count
                    assert (trainVehicle.cabin.passengerLoad > 0)
                    trainVehicle.cabin.passengerLoad -= 1
                    if self.auxiliaryPassenger:
                        trainVehicle.cabin.loadAuxiliaryPassengers -= 1
                    else:
                        trainVehicle.cabin.loadTrackedPassengers -= 1

                    #update link
                    self.curLinkID = alightLinkID

                #charge travel cost during alighting, requiring updating of cost
                trainVehicle.cabin.updateCost()
                timeOnPlatform = simEnv.now
                ridingCost = trainVehicle.getRidingCostStanding(
                    timeTrainArrival, timeOnPlatform)
                curEpisodeUtility -= ridingCost

                self.personalMemory.memorizeEpisode(curEpisodeID,
                                                    curEpisodeUtility)
                self.totalTravelUtility += curEpisodeUtility
                self.totalRideUtility += curEpisodeUtility

            elif ('exit' == actType):
                #release current area
                curAreaID = pedNet.getAreaIDFromLinkID(self.curLinkID)
                curArea = pedNet.getArea(curAreaID)
                curArea.getRelease(self.resReqEvent)

                #set current link to None
                self.curLinkID = None

                #memorize episode and update travel cost
                self.personalMemory.memorizeEpisode(curEpisodeID,
                                                    curEpisodeUtility)
                self.totalTravelUtility += curEpisodeUtility

                #display pedestrian state (debugging)
                if Parameter.textOutput or self.param.isFinalInstance:
                    self.logEntry(pedNet, transSys, simEnv)

            else:
                raise KeyError('unknown actType ' + actType)

            curActNumber += 1

        simEnv.exit()
Exemplo n.º 5
0
    def synthesizeTwoLegTravelers(self, trentoTrains):

        for overstapperFilePath in Parameter.overstapperFiles:

            overstapperRawDataFiltered = self.loadOverstapperData(
                overstapperFilePath, trentoTrains)

            for _, overstapperEntry in overstapperRawDataFiltered.iterrows():

                stationID = overstapperEntry["stationID"]
                feedingTrainNumber = overstapperEntry["feedingTrain"]
                connectingTrainNumber = overstapperEntry["connectingTrain"]
                arrTimeFeedingTrainRaw = overstapperEntry[
                    "arrTimeFeedingTrain"]
                numTravelers = overstapperEntry["numTravelers"]

                transferStation = Parameter.stationNameDict[stationID]

                feedingTrainModeled = False
                connectingTrainModeled = False

                #feeding train in trento train dict if served by at least one relevant platform
                if feedingTrainNumber in trentoTrains.trainDict.keys():
                    trentoFeedingTrain = trentoTrains.trainDict[
                        feedingTrainNumber]

                    #check if train served by modeled platform in current station
                    if transferStation in trentoFeedingTrain.stationNameSequence:
                        assert (
                            feedingTrainNumber in self.trainDict
                        ), "Train %s unknown in ROCKT InUit data." % feedingTrainNumber

                        feedingTrain = self.trainDict[feedingTrainNumber]
                        feedingTrainModeled = True

                #connecting train in trento train dict if served by at least one relevant platform
                if connectingTrainNumber in trentoTrains.trainDict.keys():
                    trentoConnectingTrain = trentoTrains.trainDict[
                        connectingTrainNumber]

                    #consider connecting train only if also served by modeled platform in current station
                    if transferStation in trentoConnectingTrain.stationNameSequence:
                        assert (
                            connectingTrainNumber in self.trainDict
                        ), "Train %s unknown in ROCKT InUit data." % connectingTrainNumber

                        connectingTrain = self.trainDict[connectingTrainNumber]
                        connectingTrainModeled = True

                #both trains served on modeled platform
                if (feedingTrainModeled and connectingTrainModeled):

                    #synthesize individual travelers
                    while (numTravelers > random()):

                        numTravelers -= 1

                        #draw origin node and time
                        origTime, origNode, origStation = feedingTrain.sampleOriginStationAndEntranceGate(
                            transferStation)

                        #draw destination node
                        destNode, destStation = connectingTrain.sampleDestinationStationAndExitGate(
                            transferStation)

                        curTraveler = RocktTraveler(
                            origNode, destNode, origTime,
                            [feedingTrainNumber, connectingTrainNumber])
                        curTraveler.setTransferStation(transferStation)

                        self.travelerSet.add(curTraveler)

                        #add two travelers to OD table for validation
                        feedingTrain.addSynthesizedPassenger(
                            origStation, transferStation)
                        connectingTrain.addSynthesizedPassenger(
                            transferStation, destStation)

                #only feeding train served by modeled platform:
                #consider as incoming passenger (instead of transfer)
                elif feedingTrainModeled:

                    #synthesize individual travelers
                    while (numTravelers > random()):

                        numTravelers -= 1

                        #draw origin node and time
                        origTime, origNode, origStation = feedingTrain.sampleOriginStationAndEntranceGate(
                            transferStation)

                        ##draw exit gate in transfer station which becomes final destination
                        #destNode = feedingTrain.chooseExitGate(transferStation)

                        #destNode set to virtual transfer desk asking as gate
                        destNode = weightedChoice(
                            Parameter.transferGate[transferStation])

                        curTraveler = RocktTraveler(origNode, destNode,
                                                    origTime,
                                                    feedingTrainNumber)
                        self.travelerSet.add(curTraveler)

                        #add traveler to OD table for validation
                        feedingTrain.addSynthesizedPassenger(
                            origStation, transferStation)

                #only connecting train served by modeled platform:
                #consider as outgoing passenger (instead of transfer)
                elif connectingTrainModeled:

                    arrTimeFeedingTrain = datetime.strptime(
                        arrTimeFeedingTrainRaw, '%Y-%m-%dT%H:%M:%S')
                    origTime = (arrTimeFeedingTrain -
                                self.midnightCaseStudy).total_seconds()
                    assert (origTime > 0)

                    #synthesize individual travelers
                    while (numTravelers > random()):

                        numTravelers -= 1

                        ##draw entrance gate
                        #origNode = connectingTrain.chooseEntranceGate(transferStation)
                        origNode = weightedChoice(
                            Parameter.transferGate[transferStation])

                        #draw destination station and node
                        destNode, destStation = connectingTrain.sampleDestinationStationAndExitGate(
                            transferStation)

                        curTraveler = RocktTraveler(origNode, destNode,
                                                    origTime,
                                                    connectingTrainNumber)
                        self.travelerSet.add(curTraveler)

                        #add traveler to OD table for validation
                        connectingTrain.addSynthesizedPassenger(
                            transferStation, destStation)

                #neither feeding nor connecting train served by modeled platform:
                else:
                    #discard concerned passengers
                    continue


#     def checkConsisteny(self, trentoTrains):
#
#         print("\nConsistency Check:")
#
#         boardInTrainStationDict = dict()
#         alightOutTrainStationDict = dict()
#
#         boardTransferTrainStationDict = dict()
#         alightTransferTrainStationDict = dict()
#
#         boardAuxiliaryTrainStationDict = dict()
#         alightAuxiliaryTrainStationDict = dict()
#
#         gateValidationDict = {'61001':'AsdZ-Minerva', '61002':'AsdZ-Minerva', '61003':'AsdZ-Minerva'}
#
#         gateValidationFlow = dict()
#
#
#         for traveler in self.travelerSet:
#
#             origNode = traveler.origNode[1:]
#             destNode = traveler.destNode[1:]
#
#             depTime = traveler.depTime
#
#             trainList = traveler.trainList
#             transferStation = traveler.transferStation
#
#             origTrain = trainList[0]
#             destTrain = trainList[-1]
#
#             if origNode in gateValidationDict.keys():
#
#                 validationGroup = gateValidationDict[origNode]
#
#                 if validationGroup not in gateValidationFlow:
#                     gateValidationFlow[validationGroup] = dict()
#
#                 if depTime not in gateValidationFlow[validationGroup].keys():
#                     gateValidationFlow[validationGroup][depTime] = 0
#
#                 gateValidationFlow[validationGroup][depTime] += 1
#
#
#             if origTrain not in boardInTrainStationDict.keys():
#                 boardInTrainStationDict[origTrain] = dict()
#                 boardAuxiliaryTrainStationDict[origTrain] = dict()
#
#             boardInStationDict = boardInTrainStationDict[origTrain]
#             boardAuxiliaryStationDict = boardAuxiliaryTrainStationDict[origTrain]
#
#             auxiliary = False
#
#             if origNode == 'up':
#                 origStation = 'upstream'
#             elif origNode[0:5] == 'Trans':
#                 auxiliary = True
#                 statNameRaw = origNode[5:]
#
#                 if statNameRaw in Parameter.stationNameDict.values():
#                     origStation=statNameRaw
#                 else:
#                     assert(statNameRaw[:-1] == 'Utrecht'), "invalid station name: %s" % statNameRaw[:-1]
#                     origStation = 'Utrecht'
#
#             elif int(origNode[0:3]) in Parameter.stationNameDict.keys():
#                 origStation = Parameter.stationNameDict[ int(origNode[0:3]) ]
#
#             elif int(origNode[0:2]) in Parameter.stationNameDict.keys():
#                 origStation = Parameter.stationNameDict[ int(origNode[0:2]) ]
#
#             else:
#                 print("Could not identify origin station (%s)" % origNode)
#
#
#             if origStation not in boardInStationDict:
#                 boardInStationDict[origStation] = 0
#                 boardAuxiliaryStationDict[origStation] = 0
#
#             if auxiliary == False:
#                 boardInStationDict[origStation] += 1
#             else:
#                 boardAuxiliaryStationDict[origStation] += 1
#
#             if destTrain not in alightOutTrainStationDict.keys():
#                 alightOutTrainStationDict[destTrain] = dict()
#                 alightAuxiliaryTrainStationDict[destTrain] = dict()
#
#             alightOutStationDict = alightOutTrainStationDict[destTrain]
#             alightAuxiliaryStationDict = alightAuxiliaryTrainStationDict[destTrain]
#
#             auxiliary=False
#
#             if destNode == 'down':
#                 destStation = 'downstream'
#             elif destNode[0:5] == 'Trans':
#                 auxiliary = True
#                 statNameRaw = destNode[5:]
#
#                 if statNameRaw in Parameter.stationNameDict.values():
#                     destStation=statNameRaw
#                 else:
#                     assert(statNameRaw[:-1] == 'Utrecht'), "invalid station name: %s" % statNameRaw[:-1]
#                     destStation = 'Utrecht'
#             elif int(destNode[0:3]) in Parameter.stationNameDict.keys():
#                     destStation = Parameter.stationNameDict[ int(destNode[0:3]) ]
#
#             elif int(destNode[0:2]) in Parameter.stationNameDict.keys():
#                     destStation = Parameter.stationNameDict[ int(destNode[0:2]) ]
#
#             else:
#                 print("Could not identify destination station (%s)" % destNode)
#
#
#             if destStation not in alightOutStationDict:
#                 alightOutStationDict[destStation] = 0
#                 alightAuxiliaryStationDict[destStation] = 0
#
#             if auxiliary == False:
#                 alightOutStationDict[destStation] += 1
#             else:
#                 alightAuxiliaryStationDict[destStation] += 1
#
#             if transferStation is not None:
#                 assert(len(trainList) == 2)
#
#                 if origTrain not in alightTransferTrainStationDict:
#                     alightTransferTrainStationDict[origTrain] = dict()
#
#                 alightTransferStationDict = alightTransferTrainStationDict[origTrain]
#
#                 if transferStation not in alightTransferStationDict.keys():
#                     alightTransferStationDict[transferStation] = 0
#
#                 alightTransferStationDict[transferStation] += 1
#
#
#                 if destTrain not in boardTransferTrainStationDict:
#                     boardTransferTrainStationDict[destTrain] = dict()
#
#                 boardTransferStationDict = boardTransferTrainStationDict[destTrain]
#
#                 if transferStation not in boardTransferStationDict.keys():
#                     boardTransferStationDict[transferStation] = 0
#
#                 boardTransferStationDict[transferStation] += 1
#
#         self.consistencyProtocol = dict()
#
#         for trainNumber, train in self.trainDict.items():
#
#             curStr = "%d (boardOut/alightIn/boardTrans/alightTrans):" % trainNumber
#
#             for stationName in Parameter.stationNameDict.values():
#                 curStr += " %s: " % stationName
#
#                 compare boardings
#                 if stationName in train.boardOutgoing.keys():
#                     boardOutRaw =  train.boardOutgoing[stationName]
#
#                     if trainNumber in boardInTrainStationDict.keys() and stationName in boardInTrainStationDict[trainNumber].keys():
#                         boardOutSynth = boardInTrainStationDict[trainNumber][stationName]
#                     else:
#                         boardOutSynth = 0
#
#                     curStr += "%+.1f%% (%d instead of %.1f) / " % ((boardOutSynth/boardOutRaw-1)*100,boardOutSynth,boardOutRaw)
#
#                 compare alightings
#                 if stationName in train.alightIncoming.keys():
#                     alightInRaw =  train.alightIncoming[stationName]
#
#                     if trainNumber in alightOutTrainStationDict.keys() and stationName in alightOutTrainStationDict[trainNumber].keys():
#                         alightInSynth = alightOutTrainStationDict[trainNumber][stationName]
#                     else:
#                         alightInSynth = 0
#
#                     curStr += "%+.1f%% (%d instead of %.1f) / " % ((alightInSynth/alightInRaw-1)*100,alightInSynth,alightInRaw)
#
#                 compare transfer boardings
#                 if stationName in train.boardTransfer.keys():
#                     boardTransferRaw = train.boardTransfer[stationName]
#
#                     boardTransferSynth = 0
#
#                     if trainNumber in boardTransferTrainStationDict.keys() and stationName in boardTransferTrainStationDict[trainNumber].keys():
#                         boardTransferSynth += boardTransferTrainStationDict[trainNumber][stationName]
#
#                     if trainNumber in boardAuxiliaryTrainStationDict.keys() and stationName in boardAuxiliaryTrainStationDict[trainNumber].keys():
#                         boardTransferSynth += boardAuxiliaryTrainStationDict[trainNumber][stationName]
#
#                     curStr += "%+.1f%% (%d instead of %.1f) / " % ((boardTransferSynth/boardTransferRaw-1)*100,boardTransferSynth,boardTransferRaw)
#
#                 compare transfer alightings
#                 if stationName in train.alightTransfer.keys():
#                     alightTransferRaw = train.alightTransfer[stationName]
#
#                     alightTransferSynth = 0
#
#                     if trainNumber in alightTransferTrainStationDict.keys() and stationName in alightTransferTrainStationDict[trainNumber].keys():
#                         alightTransferSynth += alightTransferTrainStationDict[trainNumber][stationName]
#
#                     if trainNumber in alightAuxiliaryTrainStationDict.keys() and stationName in alightAuxiliaryTrainStationDict[trainNumber].keys():
#                         alightTransferSynth += alightAuxiliaryTrainStationDict[trainNumber][stationName]
#
#                     curStr += "%+.1f%% (%d instead of %.1f)" % ((alightTransferSynth/alightTransferRaw-1)*100,alightTransferSynth,alightTransferRaw)
#
#             self.consistencyProtocol[trainNumber] = curStr
#
#         print(self.consistencyProtocol)
#
#         for validatorName, validatorFlowDict in gateValidationFlow.items():
#
#             print("checking gate in-flow at %s [paused]" % validatorName)
#
#             timeStamps,flowObs = zip(*( sorted( validatorFlowDict.items() ) ))
#
#             cumFlow = np.cumsum(flowObs)
#
#             plotting cumulative flow
#             figCum, axCum = plt.subplots()
#
#             plt.ylabel('cumulative flow')
#             plt.title(validatorName)
#
#             plt.step(timeStamps, cumFlow, where='post', label='synthesizedDemand', color='blue')
#
#             plt.legend()
#
#             plt.show()
Exemplo n.º 6
0
    def assignAlightLink(self, trainName, trainDict, vehID, streamIDDictRev):
        #dictionary of alighting links and corresponding assignment probabilities
        alightLinkAssgFrac = self.getAlightAssgFrac(trainName, trainDict,
                                                    vehID, streamIDDictRev)

        return weightedChoice(alightLinkAssgFrac)