Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
Re: [sumo-user] Simulation aborts unexpectedly

Hi,
I obtained the same error with a reduced number of people.
Simulation crashes at around step 2900

On Fri, Jul 5, 2019 at 9:24 AM Jakob Erdmann <namdre.sumo@xxxxxxxxx> wrote:
Please provide (minimal) input files for reproducing the crash.
We try to fix any kind of crashing that comes to our attention. A list of crashes that have been fixed can be found at https://sumo.dlr.de/wiki/ChangeLog (search for 'crash').

Am Do., 4. Juli 2019 um 17:03 Uhr schrieb steniero <steniero@xxxxxxxxx>:
Hello,
I have run a simulation with pedestrian that have to enter in a shuttle. My simulation aborts unexpectedly. Do you have a list of cases why it happens?

I previously experienced the following case:if I have a pedestrian that waits for a bus at the stop and I remove this bus before it arrives or with the pedestrian onboard the simulation crashes and SUMO stops working (without sending any error message).

I checked that this does not happen but my simulation crashes anyway. Do you have any hint of the reason why it happens?

Thank you very much

Stefano
_______________________________________________
sumo-user mailing list
sumo-user@xxxxxxxxxxx
To change your delivery options, retrieve your password, or unsubscribe from this list, visit
https://www.eclipse.org/mailman/listinfo/sumo-user
_______________________________________________
sumo-user mailing list
sumo-user@xxxxxxxxxxx
To change your delivery options, retrieve your password, or unsubscribe from this list, visit
https://www.eclipse.org/mailman/listinfo/sumo-user
import os, sys

try:
        sys.path.append(os.path.join(os.path.dirname(
                __file__), '..', '..', '..', '..', "tools"))  # tutorial in tests
        sys.path.append(os.path.join(os.environ.get("SUMO_HOME", os.path.join(
                os.path.dirname(__file__), "..", "..", "..")), "tools"))  # tutorial in docs
        from sumolib import checkBinary  # noqa
except ImportError:
        sys.exit(
                "please declare environment variable 'SUMO_HOME' as the root directory of your sumo installation (it should contain folders 'bin', 'tools' and 'docs')")
import traci
import sumolib
import optparse
import time
import csv

from sumolib import checkBinary

import socket

socket.gethostbyname("localhost")

print("Fin qui tutto bene")

start = time.time()

class Shuttle:
        def __init__(self,
                     name):  # peopleToBeBoardedPerStopLap1 = list(), peopleToBeBoardedPerStopLap2 = list() peopleToBeBoardedPerStopLap3 = list(), peopleToBeDisembarkedPerStopLap1 = list(), peopleToBeDisembarkedPerStopLap2 = list(), peopleToBeDisembarkedPerStopLap3 = list(), lapCounter, flagOfReroute):
                self.name = name
                self.peopleToBeBoardedPerStopLap1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                                     0]  # list of people to be boarded for each stop in current lap
                self.peopleToBeBoardedPerStopLap2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                                     0]  # list of people to be boarded for each stop next lap
                self.peopleToBeBoardedPerStopLap3 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                self.peopleToBeDisembarkedPerStopLap1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                self.peopleToBeDisembarkedPerStopLap2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                self.peopleToBeDisembarkedPerStopLap3 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                self.peopleBoardedPerStopLap1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                self.peopleBoardedPerStopLap2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                self.peopleBoardedPerStopLap3 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                self.LapCounter = 0
                self.flagOfReroute = 0
                self.totPeopleSumPerSecond = 0
                self.totPeopleBoarded = 0
                self.removedAtStep = 0
                self.lastLap = 0
                self.removed = 0
                self.peopleBookedFromMETROLap1 = 0
                self.peopleBookedFromMETROLap2 = 0
                self.destinationFromMETROLap1 = "None"
                self.destinationFromMETROLap2 = "None"

class Pedestrian:
        def __init__(self, name):
                self.name = name
                self.originName = "None"
                self.origin = "None"
                self.destinationName = "None"
                self.destination = "None"
                self.initialInsertionStep = 0  # set by a procedure
                self.actualInsertionStep = 0  # the difference between initial and actual was a supplementary waiting for an available bus
                self.modalChoice = 0  # 0 - walks because it is more convenient     1 - walks because there is not an available bus and walking is acceptable        2- walks because of walking distance threshold     3 - takes the bus       4 - takes the superShuttle      5- finds no supershuttle
                self.busSelected = "None"
                self.timeWaitingWalking = 0
                self.timeWaitingAtTheStop = 0
                self.timeWaitingNOTAssigned = 0
                self.timeStuckInTraffic = 0
                self.timeWalking = 0
                self.timeRiding = 0
                self.forcastedTimeWalking = 0
                self.forcastedTimeOnFootIntermodal = 0
                self.forcastedTimeRiding = 0
                self.lastStep = 0
                self.inTheShuttle = 0
                self.lastWaitingStep = 0
                self.waitingStop = "None"
                self.waitingStopEDGE = "None"
                self.arrivalStop = "None"
                self.removed = 0
                self.notAssignedTAG = 0

class PeoplePresent:
        def __init__(self, name):
                self.name = name
                self.total = 0
                self.onFoot = 0                         #chose to go on foot
                self.byBus = 0                          #chose to go by bus
                self.walking = 0                        #isWalkingRightNow
                self.ridingOrWaitingAtTheStop = 0       #isRiding or Waiting Right Now

class Stop:
        def __init__(self, name):
                self.name = name
                self.peopleEmbarked = 0
                self.peopleDisembarked = 0

stopID = {
        "0": "busStop_8",
        "1": "busStop_9",
        "2": "busStop_10",
        "3": "busStop_11",
        "4": "busStop_12",
        "5": "busStop_13",
        "6": "busStop_14",
        "7": "busStop_16",
        "8": "busStop_18",
        "9": "busStop_19",
        "10": "busStop_2",
        "11": "busStop_4",
        "12": "busStop_7",
}

stopEdge = {
        "0": "-337386712#1",
        "1": "-344464993#2.98",
        "2": "-344464993#0",
        "3": "-340089945#16",
        "4": "-340089945#15.155",
        "5": "-340089945#13",
        "6": "-340089945#7",
        "7": "-340089945#0",
        "8": "-337386709#15",
        "9": "-337386709#14",
        "10": "-337386709#8",
        "11": "-337386709#4",
        "12": "gneE4",
}

stopIDRing3 = {
        "6": "busStop_8",
        "7": "busStop_9",
        "8": "busStop_10",
        "9": "busStop_11",
        "10": "busStop_12",
        "11": "busStop_13",
        "12": "busStop_14",
        "0": "busStop_16",
        "1": "busStop_18",
        "2": "busStop_19",
        "3": "busStop_2",
        "4": "busStop_4",
        "5": "busStop_7",
}

stopEdgeRing3 = {
        "6": "-337386712#1",
        "7": "-344464993#2.98",
        "8": "-344464993#0",
        "9": "-340089945#16",
        "10": "-340089945#15.155",
        "11": "-340089945#13",
        "12": "-340089945#7",
        "0": "-340089945#0",
        "1": "-337386709#15",
        "2": "-337386709#14",
        "3": "-337386709#8",
        "4": "-337386709#4",
        "5": "gneE4",
}

Origins = {
        "Metro1": "341721070.414",
        "Metro2": "gneE11",
        "P1": "341007291#0",
        "P2": "338790445",
        "P3": "gneE11",
}

Destinations = {
        "HT": "341013638#0",
        "Hospital": "341025295#0",
        "University": "341013639#7",
        "Cascina": "341010336#1",
        "Private1": "341512267",
        "Private2": "341512265",
        "Private3": "341025287#1",
        "Private4": "341025287#7",
}

lastShuttle = {
        "1" : "superShuttle0",
}

stopIDMETRO1 = "busStop_8"
stopEdgeMETRO1 = "-337386712#1"

stopIDMETRO2 = "busStop_16"
stopEdgeMETRO2 = "-340089945#0"

net = sumolib.net.readNet("MapModified.net.xml", withInternal=True)
edges = net.getEdges()
edgeLengths = {}
for edge in edges:
        key = str(edge.getID())
        edgeLengths[key] = str(edge.getLength())

stopsCounterDict = {}
for i in stopID:
        stopsCounterDict[stopID[i]] = Stop(stopID[i])
stopsCounterDict["M1"] = Stop(stopIDMETRO1)
stopsCounterDict["M2"] = Stop(stopIDMETRO2)

pedestrianSpeed = 1.3
numberOfStops = 13
numberOfPeopleInserted = 10000
rushHourDuration = 7200
offPeakHours = 7
shuttleSmallRingCapacity = 26
shuttleLargeRingCapacity = 26

shuttleSmallRingSAFETYCapacity = 40
shuttleLargeRingSAFETYCapacity = 40

stopDurationMetro = 15
stopDuration = 15

totalShuttleSmallRing = 10
totalShuttleBigRing = 45
totalShuttleThirdRing = 45
beginOfPeopleInsertion = 300
numberOfInitialPlatoons = 10

walkingThreshold = 600


print("Anche qui")


def get_options():
        optParser = optparse.OptionParser()
        optParser.add_option("--nogui", action="store_true",
                             default=False, help="run the commandline version of sumo")
        options, args = optParser.parse_args()
        return options


def get_route(step, initialEdge,
              finalEdge):  # gets the ring route automatically -- when the ring is finished, reassign the route by using taci.vehicle.setRoute(self, vehID, edgeList)
        ringRouteInfo = traci.simulation.findRoute(initialEdge, finalEdge, vType="shuttle", depart=step, routingMode=0)
        edgesList = ringRouteInfo.edges
        ringRouteEdges = list(edgesList)
        secondEdge = ringRouteEdges[1]
        ringRouteEdges.append(initialEdge)
        return ringRouteEdges, secondEdge

def insert_shuttles(progNum):
        listOfShuttles = list()
        count = 0
        while count < (totalShuttleSmallRing/numberOfInitialPlatoons):  # NUMBER OF SHUTTLES INSERTED
                shuttleName = "shuttle" + str(progNum)
                traci.vehicle.add(shuttleName, "ringRoute", typeID='shuttle', line=shuttleName, personCapacity=shuttleSmallRingCapacity)
                listOfShuttles.append(shuttleName)
                count += 1
                progNum += 1
        return listOfShuttles

def insert_secondRing_Shuttles(progNum, routeName):
        listOfLargeRingShuttles = list()
        count = 0
        while count < progNum:  # NUMBER OF SHUTTLES INSERTED
                shuttleName = "superShuttle" + str(count)
                traci.vehicle.add(shuttleName, routeName, typeID='bigShuttle', line=shuttleName, personCapacity=shuttleLargeRingSAFETYCapacity)
                listOfLargeRingShuttles.append(shuttleName)
                count += 1
        return listOfLargeRingShuttles

def insert_thirdRing_Shuttles(progNum, routeName):
        listOfLargeRingShuttles = list()
        count = 0
        while count < progNum:  # NUMBER OF SHUTTLES INSERTED
                shuttleName = "thirdRingShuttle" + str(count)
                traci.vehicle.add(shuttleName, routeName, typeID='bigShuttle', line=shuttleName, personCapacity=shuttleLargeRingSAFETYCapacity)
                listOfLargeRingShuttles.append(shuttleName)
                count += 1
        return listOfLargeRingShuttles

def reroute(shuttle, shuttleCharacteristics, routeName):
        traci.vehicle.setRouteID(shuttle, routeName)
        shuttleCharacteristics[shuttle].peopleToBeBoardedPerStopLap1 = shuttleCharacteristics[
                shuttle].peopleToBeBoardedPerStopLap2
        shuttleCharacteristics[shuttle].peopleToBeBoardedPerStopLap2 = shuttleCharacteristics[
                shuttle].peopleToBeBoardedPerStopLap3
        shuttleCharacteristics[shuttle].peopleToBeBoardedPerStopLap3 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        shuttleCharacteristics[shuttle].peopleToBeDisembarkedPerStopLap1 = shuttleCharacteristics[
                shuttle].peopleToBeDisembarkedPerStopLap2
        shuttleCharacteristics[shuttle].peopleToBeDisembarkedPerStopLap2 = shuttleCharacteristics[
                shuttle].peopleToBeDisembarkedPerStopLap3
        shuttleCharacteristics[shuttle].peopleToBeDisembarkedPerStopLap3 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        shuttleCharacteristics[shuttle].peopleBoardedPerStopLap1 = shuttleCharacteristics[
                shuttle].peopleBoardedPerStopLap2
        shuttleCharacteristics[shuttle].peopleBoardedPerStopLap2 = shuttleCharacteristics[
                shuttle].peopleBoardedPerStopLap3
        shuttleCharacteristics[shuttle].peopleBoardedPerStopLap3 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        shuttleCharacteristics[shuttle].peopleBookedFromMETROLap1 = shuttleCharacteristics[shuttle].peopleBookedFromMETROLap2
        shuttleCharacteristics[shuttle].peopleBookedFromMETROLap2 = 0
        shuttleCharacteristics[shuttle].destinationFromMETROLap1 = shuttleCharacteristics[shuttle].destinationFromMETROLap2
        shuttleCharacteristics[shuttle].destinationFromMETROLap2 = "None"
        shuttleCharacteristics[shuttle].flagOfReroute = 1
        shuttleCharacteristics[shuttle].LapCounter += 1
        if routeName == "ringRoute":
                i = 0
                for stop in shuttleCharacteristics[shuttle].peopleToBeBoardedPerStopLap1:
                        if stop > 0:
                                traci.vehicle.setBusStop(shuttle, stopID[str(i)], duration= stopDuration, flags=0)
                        i += 1
                j = 0
                for stop in shuttleCharacteristics[shuttle].peopleToBeDisembarkedPerStopLap1:
                        if stop > 0:
                                traci.vehicle.setBusStop(shuttle, stopID[str(j)], duration= stopDuration, flags=0)
                        j += 1
        elif routeName == "bigRingRoute":
                if shuttleCharacteristics[shuttle].peopleBookedFromMETROLap1 != 0:
                        traci.vehicle.setBusStop(shuttle, stopIDMETRO1, duration= stopDurationMetro, flags=0)
                j = 0
                for stop in shuttleCharacteristics[shuttle].peopleToBeDisembarkedPerStopLap1:
                        if stop > 0:
                                traci.vehicle.setBusStop(shuttle, stopID[str(j)], duration=stopDuration, flags=0)
                        j += 1
        elif routeName == "ringRoute3":
                if shuttleCharacteristics[shuttle].peopleBookedFromMETROLap1 != 0:
                        traci.vehicle.setBusStop(shuttle, stopIDMETRO2, duration= stopDurationMetro, flags=0)
                j = 0
                for stop in shuttleCharacteristics[shuttle].peopleToBeDisembarkedPerStopLap1:
                        if stop > 0:
                                traci.vehicle.setBusStop(shuttle, stopIDRing3[str(j)], duration= stopDuration, flags=0)
                        j += 1

def insert_pupini(step, beginningOfOurTrip, endOfOurTrip, pupinoName, listOfSmallRingShuttles, listOfLargeRingShuttles, listOfThirdRingShuttles, listOfShuttles, shuttleCharacteristics, pedestrianDict):  # inserts a pupino and makes it choose the modality
        traci.person.add(pupinoName, beginningOfOurTrip, pos=0, depart=step, typeID='DEFAULT_PEDTYPE')
        routeWalking = traci.simulation.findIntermodalRoute(beginningOfOurTrip, endOfOurTrip, modes='',
                                                            depart=step,
                                                            routingMode=0,
                                                            speed=1.0, walkFactor=-1.0, departPos=0.0,
                                                            arrivalPos=-1073741824.0, departPosLat=0.0,
                                                            pType='',
                                                            vType='',
                                                            destStop='')
        edgesRouteWalking = list(routeWalking[0].edges)
        if pedestrianDict[pupinoName].originName == "Metro1":
                evaluate_Large_Ring(step, beginningOfOurTrip, endOfOurTrip, pupinoName, listOfLargeRingShuttles,
                                    listOfShuttles, shuttleCharacteristics, pedestrianDict, edgesRouteWalking)
        elif pedestrianDict[pupinoName].originName == "Metro2":
                evaluate_Third_Ring(step, beginningOfOurTrip, endOfOurTrip, pupinoName, listOfThirdRingShuttles,
                                    listOfShuttles, shuttleCharacteristics, pedestrianDict, edgesRouteWalking)
        else:
                evaluate_Small_Ring(step, beginningOfOurTrip, endOfOurTrip, pupinoName, listOfSmallRingShuttles,
                                    listOfShuttles, shuttleCharacteristics, pedestrianDict, edgesRouteWalking)


def evaluate_Third_Ring(step, beginningOfOurTrip, endOfOurTrip, pupinoName, listOfThirdRingShuttles, listOfShuttles,
                  shuttleCharacteristics, pedestrianDict, edgesRouteWalking):
        totWalking = 0
        for edge in edgesRouteWalking:
                length = float(edgeLengths[edge])
                totWalking += length
        timeWalking = totWalking / pedestrianSpeed
        if timeWalking < walkingThreshold:
                print ("Let''s walk")
                pedestrianDict[pupinoName].modalChoice = 2
                traci.person.appendWalkingStage(pupinoName, edgesRouteWalking, 10, duration=-1, speed=-1, stopID='')
                pedestrianDict[pupinoName].forcastedTimeWalking = timeWalking
                successfulInsertion = 1
        else:
                minStart = 99999
                stationStartMin = "1000"
                minArrival = 99999
                stationArrivalMin = "1000"
                travelTimeShuttle = 0
                routeWalkingToMETRO2 = traci.simulation.findIntermodalRoute(beginningOfOurTrip, stopEdgeMETRO2,
                                                                                   modes='',
                                                                                   depart=step, routingMode=0,
                                                                                   speed=1.0, walkFactor=-1.0,
                                                                                   departPos=0.0,
                                                                                   arrivalPos=-1073741824.0,
                                                                                   departPosLat=0.0,
                                                                                   pType='', vType='',
                                                                                   destStop='')
                totWalkingToMETRO2 = 0
                edgesRouteWalkingToMETRO2 = list(routeWalkingToMETRO2[0].edges)
                for edge in edgesRouteWalkingToMETRO2:
                        length = float(edgeLengths[edge])
                        totWalkingToMETRO2 += length
                timeToWalkMETRO2 = totWalkingToMETRO2/pedestrianSpeed
                destinationWithTheShuttle = "Nowhere"
                if pedestrianDict[pupinoName].destinationName == "Private1":
                        destinationWithTheShuttle = "1"
                        destinationWithTheShuttleRing3 = "7"
                elif pedestrianDict[pupinoName].destinationName == "Private2":
                        destinationWithTheShuttle = "3"
                        destinationWithTheShuttleRing3 = "9"
                elif pedestrianDict[pupinoName].destinationName == "Private3" or pedestrianDict[pupinoName].destinationName == "Private4":
                        destinationWithTheShuttle = "5"
                        destinationWithTheShuttleRing3 = "11"
                elif pedestrianDict[pupinoName].destinationName == "University" or pedestrianDict[pupinoName].destinationName == "HT":
                        destinationWithTheShuttle = "8"
                        destinationWithTheShuttleRing3 = "1"
                elif pedestrianDict[pupinoName].destinationName == "Cascina" or pedestrianDict[pupinoName].destinationName == "Hospital":
                        destinationWithTheShuttle = "11"
                        destinationWithTheShuttleRing3 = "4"
                pedestrianDict[pupinoName].arrivalStop = destinationWithTheShuttleRing3
                routeFromStopToDestination = traci.simulation.findIntermodalRoute(
                        stopEdge[destinationWithTheShuttle], pedestrianDict[pupinoName].destination, modes='',
                        depart=0,
                        routingMode=0,
                        speed=1.0, walkFactor=-1.0, departPos=0.0,
                        arrivalPos=-1073741824.0, departPosLat=0.0,
                        pType='',
                        vType='',
                        destStop='')
                edgesFromStopToDestination = list(routeFromStopToDestination[0].edges)
                totWalkingFromStopToDestination = 0
                for edge in edgesFromStopToDestination:
                        length = float(edgeLengths[edge])
                        totWalkingFromStopToDestination += length
                timeFromStopToDestination = totWalkingFromStopToDestination / pedestrianSpeed
                routeWithShuttle = traci.simulation.findRoute(stopEdgeMETRO2, stopEdge[destinationWithTheShuttle],
                                                              vType='shuttle', routingMode=0)
                travelTimeShuttle = routeWithShuttle.travelTime
                totalTimeWalkingIntermodal = timeToWalkMETRO2 + timeFromStopToDestination
                timeIntermodal = timeToWalkMETRO2 + timeFromStopToDestination + travelTimeShuttle
                pedestrianDict[pupinoName].forcastedTimeWalking = timeWalking
                pedestrianDict[pupinoName].forcastedTimeOnFootIntermodal = totalTimeWalkingIntermodal
                pedestrianDict[pupinoName].forcastedTimeRiding = travelTimeShuttle
                if timeWalking < timeIntermodal:
                        print ("Let's walk")
                        traci.person.appendWalkingStage(pupinoName, edgesRouteWalking, 10, duration=-1, speed=-1,
                                                        stopID='')
                        successfulInsertion = 1
                        pedestrianDict[pupinoName].modalChoice = 0
                else:
                        print ("Let's take the bus")
                        successfulInsertion, walkingChoice, selectedShuttle = takeTheSuperShuttle(stopIDMETRO2, stopEdgeMETRO2, stopID[destinationWithTheShuttle], destinationWithTheShuttleRing3, stopEdge[destinationWithTheShuttle], pupinoName, edgesRouteWalkingToMETRO2, edgesFromStopToDestination, listOfThirdRingShuttles, step, timeToWalkMETRO2, shuttleCharacteristics, edgesRouteWalking, "METRO2", pedestrianDict)
                        pedestrianDict[pupinoName].modalChoice = walkingChoice
                        pedestrianDict[pupinoName].busSelected = selectedShuttle
                        if walkingChoice == 6:
                                pedestrianDict[pupinoName].waitingStopEDGE = stopEdgeMETRO2
                return successfulInsertion

def evaluate_Large_Ring(step, beginningOfOurTrip, endOfOurTrip, pupinoName, listOfLargeRingShuttles, listOfShuttles,
                  shuttleCharacteristics, pedestrianDict, edgesRouteWalking):
        totWalking = 0
        for edge in edgesRouteWalking:
                length = float(edgeLengths[edge])
                totWalking += length
        timeWalking = totWalking / pedestrianSpeed
        if timeWalking < walkingThreshold:
                print ("Let''s walk")
                pedestrianDict[pupinoName].modalChoice = 2
                traci.person.appendWalkingStage(pupinoName, edgesRouteWalking, 10, duration=-1, speed=-1, stopID='')
                pedestrianDict[pupinoName].forcastedTimeWalking = timeWalking
                successfulInsertion = 1
        else:
                minStart = 99999
                stationStartMin = "1000"
                minArrival = 99999
                stationArrivalMin = "1000"
                travelTimeShuttle = 0
                routeWalkingToMETRO1 = traci.simulation.findIntermodalRoute(beginningOfOurTrip, stopEdgeMETRO1,
                                                                                   modes='',
                                                                                   depart=step, routingMode=0,
                                                                                   speed=1.0, walkFactor=-1.0,
                                                                                   departPos=0.0,
                                                                                   arrivalPos=-1073741824.0,
                                                                                   departPosLat=0.0,
                                                                                   pType='', vType='',
                                                                                   destStop='')
                totWalkingToMETRO1 = 0
                edgesRouteWalkingToMETRO1 = list(routeWalkingToMETRO1[0].edges)
                for edge in edgesRouteWalkingToMETRO1:
                        length = float(edgeLengths[edge])
                        totWalkingToMETRO1 += length
                timeToWalkMETRO1 = totWalkingToMETRO1/pedestrianSpeed
                destinationWithTheShuttle = "Nowhere"
                if pedestrianDict[pupinoName].destinationName == "Private1":
                        destinationWithTheShuttle = "1"
                elif pedestrianDict[pupinoName].destinationName == "Private2":
                        destinationWithTheShuttle = "3"
                elif pedestrianDict[pupinoName].destinationName == "Private3" or pedestrianDict[pupinoName].destinationName == "Private4":
                        destinationWithTheShuttle = "5"
                elif pedestrianDict[pupinoName].destinationName == "University" or pedestrianDict[pupinoName].destinationName == "HT":
                        destinationWithTheShuttle = "8"
                elif pedestrianDict[pupinoName].destinationName == "Cascina" or pedestrianDict[pupinoName].destinationName == "Hospital":
                        destinationWithTheShuttle = "11"
                pedestrianDict[pupinoName].arrivalStop = destinationWithTheShuttle
                routeFromStopToDestination = traci.simulation.findIntermodalRoute(
                        stopEdge[destinationWithTheShuttle], pedestrianDict[pupinoName].destination, modes='',
                        depart=0,
                        routingMode=0,
                        speed=1.0, walkFactor=-1.0, departPos=0.0,
                        arrivalPos=-1073741824.0, departPosLat=0.0,
                        pType='',
                        vType='',
                        destStop='')
                edgesFromStopToDestination = list(routeFromStopToDestination[0].edges)
                totWalkingFromStopToDestination = 0
                for edge in edgesFromStopToDestination:
                        length = float(edgeLengths[edge])
                        totWalkingFromStopToDestination += length
                timeFromStopToDestination = totWalkingFromStopToDestination / pedestrianSpeed
                routeWithShuttle = traci.simulation.findRoute(stopEdgeMETRO1, stopEdge[destinationWithTheShuttle],
                                                              vType='shuttle', routingMode=0)
                travelTimeShuttle = routeWithShuttle.travelTime
                totalTimeWalkingIntermodal = timeToWalkMETRO1 + timeFromStopToDestination
                timeIntermodal = timeToWalkMETRO1 + timeFromStopToDestination + travelTimeShuttle
                pedestrianDict[pupinoName].forcastedTimeWalking = timeWalking
                pedestrianDict[pupinoName].forcastedTimeOnFootIntermodal = totalTimeWalkingIntermodal
                pedestrianDict[pupinoName].forcastedTimeRiding = travelTimeShuttle
                if timeWalking < timeIntermodal:
                        print ("Let's walk")
                        traci.person.appendWalkingStage(pupinoName, edgesRouteWalking, 10, duration=-1, speed=-1,
                                                        stopID='')
                        successfulInsertion = 1
                        pedestrianDict[pupinoName].modalChoice = 0
                else:
                        print ("Let's take the bus")
                        successfulInsertion, walkingChoice, selectedShuttle = takeTheSuperShuttle(stopIDMETRO1, stopEdgeMETRO1, stopID[destinationWithTheShuttle], destinationWithTheShuttle, stopEdge[destinationWithTheShuttle], pupinoName, edgesRouteWalkingToMETRO1, edgesFromStopToDestination, listOfLargeRingShuttles, step, timeToWalkMETRO1, shuttleCharacteristics, edgesRouteWalking, "METRO1", pedestrianDict)
                        pedestrianDict[pupinoName].modalChoice = walkingChoice
                        pedestrianDict[pupinoName].busSelected = selectedShuttle
                        if walkingChoice == 4:
                                pedestrianDict[pupinoName].waitingStopEDGE = stopEdgeMETRO1
                return successfulInsertion

"""QUESTA E' PER L'ESTENSIONE"""
"""def evaluate_Large_Ring(step, beginningOfOurTrip, endOfOurTrip, pupinoName, listOfLargeRingShuttles, listOfShuttles, shuttleCharacteristics, pedestrianDict, edgesRouteWalking):
        totWalkingToMETRO = 0
        totWalkingFromStopToDestination = 0
        routeToStopMETRO = traci.simulation.findIntermodalRoute(
                pedestrianDict[pupinoName].origin, "gneE30", modes='',
                depart=0,
                routingMode=0,
                speed=1.0, walkFactor=-1.0, departPos=0.0,
                arrivalPos=-1073741824.0, departPosLat=0.0,
                pType='',
                vType='',
                destStop='')
        edgesToMETRO = list(routeToStopMETRO[0].edges)
        for edge in edgesToMETRO:
                length = float(edgeLengths[edge])
                totWalkingToMETRO += length
        timeToMETRO = totWalkingToMETRO / pedestrianSpeed
        destinationWithTheShuttle = "Nowhere"
        if pedestrianDict[pupinoName].destinationName == "Private1":
                destinationWithTheShuttle = "0"
        elif pedestrianDict[pupinoName].destinationName == "Private2" or pedestrianDict[
                pupinoName].destinationName == "Private3" or pedestrianDict[pupinoName].destinationName == "Private4":
                destinationWithTheShuttle = "2"
        elif pedestrianDict[pupinoName].destinationName == "University" or pedestrianDict[
                pupinoName].destinationName == "HT":
                destinationWithTheShuttle = "4"
        elif pedestrianDict[pupinoName].destinationName == "Cascina" or pedestrianDict[
                pupinoName].destinationName == "Hospital":
                destinationWithTheShuttle = "6"
        routeFromStopToDestination = traci.simulation.findIntermodalRoute(
                stopEdge[destinationWithTheShuttle], pedestrianDict[pupinoName].destination, modes='',
                depart=0,
                routingMode=0,
                speed=1.0, walkFactor=-1.0, departPos=0.0,
                arrivalPos=-1073741824.0, departPosLat=0.0,
                pType='',
                vType='',
                destStop='')
        edgesFromStopToDestination = list(routeFromStopToDestination[0].edges)
        for edge in edgesFromStopToDestination:
                length = float(edgeLengths[edge])
                totWalkingFromStopToDestination += length
        timeFromStopToDestination = totWalkingFromStopToDestination / pedestrianSpeed

        print ("Let's take the bus")
        successfulInsertion, walkingChoice, selectedShuttle = takeTheSuperShuttle(stopIDMETRO1, stopEdgeMETRO1, stopID[destinationWithTheShuttle], destinationWithTheShuttle, stopEdge[destinationWithTheShuttle], pupinoName, edgesToMETRO, edgesFromStopToDestination, listOfLargeRingShuttles, step, timeToMETRO, shuttleCharacteristics, edgesRouteWalking, "METRO1")
        pedestrianDict[pupinoName].modalChoice = walkingChoice
        pedestrianDict[pupinoName].busSelected = selectedShuttle
        if walkingChoice == 4:
                pedestrianDict[pupinoName].waitingStop = stopEdgeMETRO1
        return successfulInsertion"""

def takeTheSuperShuttle(stopIDMETRO, stopEdgeMETRO, arrivalStopID, destinationWithTheShuttle, arrivalStop, pupinoName, edgesToMETRO,
                   edgesFromStopToDestination, listOfLargeRingShuttles, step, timeToMETRO, shuttleCharacteristics, edgesRouteWalking, comingFrom, pedestrianDict):
        selectedShuttle, shuttleAvailable = chooseSuperShuttle(listOfLargeRingShuttles, timeToMETRO, destinationWithTheShuttle, shuttleCharacteristics, stopEdgeMETRO)
        successfulInsertion = 0
        if shuttleAvailable == 1:
                traci.person.appendWalkingStage(pupinoName, edgesToMETRO, 10, duration=-1, speed=-1, stopID='')
                traci.person.appendDrivingStage(pupinoName, arrivalStop, selectedShuttle, stopID = '')
                traci.person.appendWalkingStage(pupinoName, edgesFromStopToDestination, 10, duration=-1, speed=-1, stopID='')
                isInCurrentRoute = 0  # if the stop is in the next lap I get an error
                currentEdge = traci.vehicle.getRoadID(selectedShuttle)
                currentEdgePassed = 0
                for edge in traci.vehicle.getRoute(selectedShuttle):
                        if edge == currentEdge:
                                currentEdgePassed = 1
                        if stopEdgeMETRO == edge and currentEdgePassed == 1:
                                isInCurrentRoute = 1
                if isInCurrentRoute == 1:
                        traci.vehicle.setBusStop(selectedShuttle, stopIDMETRO, duration= stopDurationMetro, flags=0)
                        traci.vehicle.setBusStop(selectedShuttle, arrivalStopID, duration= stopDuration, flags=0)
                successfulInsertion = 1
                stopsCounterDict[arrivalStopID].peopleDisembarked += 1
                if pedestrianDict[pupinoName].originName == "Metro1":
                        walkingChoice = 4
                        stopsCounterDict["M1"].peopleEmbarked += 1
                elif pedestrianDict[pupinoName].originName == "Metro2":
                        walkingChoice = 6
                        stopsCounterDict["M2"].peopleEmbarked += 1
        elif shuttleAvailable == 0:
                traci.person.appendWalkingStage(pupinoName, edgesToMETRO, 10, duration=-1, speed=-1, stopID='')
                traci.person.appendWaitingStage(pupinoName, 100000, description='waiting', stopID='')
                pedestrianDict[pupinoName].notAssignedTAG = 1
                print (pupinoName + " is waiting at station " + stopEdgeMETRO)
                walkingChoice = 1
                pedestrianDict[pupinoName].waitingStopEDGE = stopEdge
                if pedestrianDict[pupinoName].originName == "Metro1":
                        stopsCounterDict["M1"].peopleEmbarked += 1
                elif pedestrianDict[pupinoName].originName == "Metro2":
                        stopsCounterDict["M2"].peopleEmbarked += 1
                stopsCounterDict[arrivalStopID].peopleDisembarked += 1
                successfulInsertion = 1
                if pedestrianDict[pupinoName].originName == "Metro1":
                        walkingChoice = 5
                elif pedestrianDict[pupinoName].originName == "Metro2":
                        walkingChoice = 7
        return successfulInsertion, walkingChoice, selectedShuttle


#NO SHARING
def chooseSuperShuttle(listOfLargeRingShuttles, timeToMETRO, destinationWithTheShuttle, shuttleCharacteristics, stopEdgeMETRO):
        #stationStart = int(stationStartStr)
        stationStop = int(destinationWithTheShuttle)
        min = 9999
        closestGoodShuttle = 'None'
        minFound = 0
        for shuttleName in listOfLargeRingShuttles:
                isInCurrentRoute = 0
                currentEdge = traci.vehicle.getRoadID(shuttleName)
                currentEdgePassed = 0
                isNotAJunction = 0
                for edge in traci.vehicle.getRoute(shuttleName):
                        if edge == currentEdge:
                                isNotAJunction = 1
                if isNotAJunction == 0:
                        continue
                for edge in traci.vehicle.getRoute(shuttleName):
                        if edge == currentEdge:
                                currentEdgePassed = 1
                        if stopEdgeMETRO == edge and currentEdgePassed == 1:
                                isInCurrentRoute = 1
                if isInCurrentRoute == 1:
                        busFull = 0
                        if shuttleCharacteristics[shuttleName].peopleBookedFromMETROLap1 == shuttleLargeRingCapacity:
                                busFull = 1
                else:
                        busFull = 0
                        if shuttleCharacteristics[shuttleName].peopleBookedFromMETROLap2 == shuttleLargeRingCapacity:
                                busFull = 1
                if busFull == 1:
                        continue
                else:
                        # valutare i tempi di arrivo allo stop
                        position = traci.vehicle.getRoadID(shuttleName)
                        routeShuttleToStop = traci.simulation.findRoute(position, stopEdgeMETRO,
                                                                        vType='shuttle', routingMode=0)
                        travelTimeShuttle = (routeShuttleToStop.travelTime) * 1.1

                        if timeToMETRO < travelTimeShuttle:
                                    if travelTimeShuttle < min:
                                            min = travelTimeShuttle
                                            closestGoodShuttle = shuttleName
                                            minFound = 1
        if minFound == 1:
                isInCurrentRoute = 0
                currentEdge = traci.vehicle.getRoadID(closestGoodShuttle)
                currentEdgePassed = 0
                for edge in traci.vehicle.getRoute(closestGoodShuttle):
                        if edge == currentEdge:
                                currentEdgePassed = 1
                        if stopEdgeMETRO == edge and currentEdgePassed == 1:
                                isInCurrentRoute = 1
                if isInCurrentRoute == 1:
                        for i in range(0, stationStop + 1):
                                        shuttleCharacteristics[closestGoodShuttle].peopleBoardedPerStopLap1[i] += 1
                        shuttleCharacteristics[closestGoodShuttle].peopleBookedFromMETROLap1 += 1
                        shuttleCharacteristics[closestGoodShuttle].peopleToBeDisembarkedPerStopLap1[stationStop] += 1
                else:  # if it is the next lap, every order should be made the next lap (it could have be done with a matrix)
                        for i in range(0, stationStop + 1):
                                shuttleCharacteristics[closestGoodShuttle].peopleBoardedPerStopLap2[i] += 1
                        shuttleCharacteristics[closestGoodShuttle].peopleBookedFromMETROLap2 += 1
                        shuttleCharacteristics[closestGoodShuttle].peopleToBeDisembarkedPerStopLap2[stationStop] += 1
                shuttleCharacteristics[closestGoodShuttle].totPeopleBoarded += 1
        else:
                print ("Shuttle Not Found")  # CHE FARE IN QUESTO CASO?????????????????????????????????????????????????
        return closestGoodShuttle, minFound

#RIDE SHARING
"""def chooseSuperShuttle(listOfLargeRingShuttles, timeToMETRO, destinationWithTheShuttle, shuttleCharacteristics, stopFromMETRO):
        #stationStart = int(stationStartStr)
        stationStop = int(destinationWithTheShuttle)
        min = 9999
        closestGoodShuttle = 'None'
        minFound = 0
        for shuttleName in listOfLargeRingShuttles:
                if minFound == 0:
                                isInCurrentRoute = 0
                                currentEdge = traci.vehicle.getRoadID(shuttleName)
                                currentEdgePassed = 0
                                isNotAJunction = 0
                                for edge in traci.vehicle.getRoute(shuttleName):
                                        if edge == currentEdge:
                                                isNotAJunction = 1
                                if isNotAJunction == 0:
                                        continue
                                for edge in traci.vehicle.getRoute(shuttleName):
                                        if edge == currentEdge:
                                                currentEdgePassed = 1
                                        if stopFromMETRO == edge and currentEdgePassed == 1:
                                                isInCurrentRoute = 1
                                if isInCurrentRoute == 1:
                                        if shuttleCharacteristics[shuttleName].destinationFromMETROLap1 == destinationWithTheShuttle:
                                                busFull = 0
                                                if shuttleCharacteristics[shuttleName].peopleBookedFromMETROLap1 == shuttleLargeRingCapacity:
                                                        busFull = 1
                                                if busFull == 1:
                                                        continue
                                                else:
                                                        position = traci.vehicle.getRoadID(shuttleName)
                                                        routeShuttleToStop = traci.simulation.findRoute(position, stopFromMETRO,vType='shuttle', routingMode=0)
                                                        travelTimeShuttle = (routeShuttleToStop.travelTime) * 1.05
                                                        if timeToMETRO < travelTimeShuttle:
                                                                if travelTimeShuttle < min:
                                                                        min = travelTimeShuttle
                                                                        closestGoodShuttle = shuttleName
                                                                        minFound = 1
                                else:
                                        if shuttleCharacteristics[shuttleName].destinationFromMETROLap2 == destinationWithTheShuttle:
                                                busFull = 0
                                                if shuttleCharacteristics[shuttleName].peopleBookedFromMETROLap2 == shuttleLargeRingCapacity:
                                                        busFull = 1
                                                if busFull == 1:
                                                        continue
                                                else:
                                                        position = traci.vehicle.getRoadID(shuttleName)
                                                        routeShuttleToStop = traci.simulation.findRoute(position, stopFromMETRO, vType='shuttle', routingMode=0)
                                                        travelTimeShuttle = (routeShuttleToStop.travelTime) * 1.05
                                                        if timeToMETRO < travelTimeShuttle:
                                                                if travelTimeShuttle < min:
                                                                        min = travelTimeShuttle
                                                                        closestGoodShuttle = shuttleName
                                                                        minFound = 1
        if minFound == 0:
                for shuttleName in listOfLargeRingShuttles:
                        #if shuttleCharacteristics[shuttleName].destinationFromMETRO == "None":
                                isInCurrentRoute = 0
                                currentEdge = traci.vehicle.getRoadID(shuttleName)
                                currentEdgePassed = 0
                                isNotAJunction = 0
                                for edge in traci.vehicle.getRoute(shuttleName):
                                        if edge == currentEdge:
                                                isNotAJunction = 1
                                if isNotAJunction == 0:
                                        continue
                                for edge in traci.vehicle.getRoute(shuttleName):
                                        if edge == currentEdge:
                                                currentEdgePassed = 1
                                        if stopFromMETRO == edge and currentEdgePassed == 1:
                                                isInCurrentRoute = 1
                                if isInCurrentRoute == 1:
                                        busTaken = 0
                                        if shuttleCharacteristics[shuttleName].peopleBookedFromMETROLap1 != 0:
                                                busTaken = 1
                                else:
                                        busTaken = 0
                                        if shuttleCharacteristics[shuttleName].peopleBookedFromMETROLap2 != 0:
                                                busTaken = 1
                                if busTaken == 1:
                                        continue
                                else:
                                        # valutare i tempi di arrivo allo stop
                                        position = traci.vehicle.getRoadID(shuttleName)
                                        routeShuttleToStop = traci.simulation.findRoute(position, stopFromMETRO,
                                                                                vType='shuttle', routingMode=0)
                                        travelTimeShuttle = (routeShuttleToStop.travelTime) * 1.05
                                        if timeToMETRO < travelTimeShuttle:
                                                    if travelTimeShuttle < min:
                                                            min = travelTimeShuttle
                                                            closestGoodShuttle = shuttleName
                                                            minFound = 1
        if minFound == 1:
                isInCurrentRoute = 0
                currentEdge = traci.vehicle.getRoadID(closestGoodShuttle)
                currentEdgePassed = 0
                for edge in traci.vehicle.getRoute(closestGoodShuttle):
                        if edge == currentEdge:
                                currentEdgePassed = 1
                        if stopFromMETRO == edge and currentEdgePassed == 1:
                                isInCurrentRoute = 1
                if isInCurrentRoute == 1:
                        if shuttleCharacteristics[closestGoodShuttle].destinationFromMETROLap1 == "None":
                                shuttleCharacteristics[closestGoodShuttle].destinationFromMETROLap1 = destinationWithTheShuttle
                        for i in range(0, stationStop + 1):
                                        shuttleCharacteristics[closestGoodShuttle].peopleBoardedPerStopLap1[i] += 1
                        shuttleCharacteristics[closestGoodShuttle].peopleBookedFromMETROLap1 += 1
                        shuttleCharacteristics[closestGoodShuttle].peopleToBeDisembarkedPerStopLap1[stationStop] += 1
                else:  # if it is the next lap, every order should be made the next lap (it could have be done with a matrix)
                        if shuttleCharacteristics[closestGoodShuttle].destinationFromMETROLap2 == "None":
                                shuttleCharacteristics[closestGoodShuttle].destinationFromMETROLap2 = destinationWithTheShuttle
                        for i in range(0, stationStop + 1):
                                shuttleCharacteristics[closestGoodShuttle].peopleBoardedPerStopLap2[i] += 1
                        shuttleCharacteristics[closestGoodShuttle].peopleBookedFromMETROLap2 += 1
                        shuttleCharacteristics[closestGoodShuttle].peopleToBeDisembarkedPerStopLap2[stationStop] += 1
                shuttleCharacteristics[closestGoodShuttle].totPeopleBoarded += 1
        else:
                print ("Shuttle Not Found")  # CHE FARE IN QUESTO CASO?????????????????????????????????????????????????
        return closestGoodShuttle, minFound"""

def evaluate_Small_Ring(step, beginningOfOurTrip, endOfOurTrip, pupinoName, listOfSmallRingShuttles, listOfShuttles,
                  shuttleCharacteristics, pedestrianDict, edgesRouteWalking):
        totWalking = 0
        for edge in edgesRouteWalking:
                length = float(edgeLengths[edge])
                totWalking += length
        timeWalking = totWalking / pedestrianSpeed
        if timeWalking < walkingThreshold:
                print ("Let''s walk")
                pedestrianDict[pupinoName].modalChoice = 2
                traci.person.appendWalkingStage(pupinoName, edgesRouteWalking, 10, duration=-1, speed=-1, stopID='')
                pedestrianDict[pupinoName].forcastedTimeWalking = timeWalking
                successfulInsertion = 1
        else:
                minStart = 99999
                stationStartMin = "1000"
                minArrival = 99999
                stationArrivalMin = "1000"
                travelTimeShuttle = 0
                for i in range(0, numberOfStops):  # here we check the closest starting stop
                        routeWalkingToStop1 = traci.simulation.findIntermodalRoute(beginningOfOurTrip, stopEdge[str(i)],
                                                                                   modes='',
                                                                                   depart=step, routingMode=0,
                                                                                   speed=1.0, walkFactor=-1.0,
                                                                                   departPos=0.0,
                                                                                   arrivalPos=-1073741824.0,
                                                                                   departPosLat=0.0,
                                                                                   pType='', vType='',
                                                                                   destStop='')
                        totWalkingToStop1 = 0
                        edgesRouteWalkingToStop1 = list(routeWalkingToStop1[0].edges)
                        for edge in edgesRouteWalkingToStop1:
                                length = float(edgeLengths[edge])
                                totWalkingToStop1 += length
                        if totWalkingToStop1 < minStart:
                                minStart = totWalkingToStop1
                                stationStartMin = str(i)
                                edgesToStopMIN = edgesRouteWalkingToStop1
                                timeToWalkStop1 = totWalkingToStop1/pedestrianSpeed
                for i in range(0, numberOfStops):  # here we check minimum travel time
                        arrivalStop = stopEdge[str(i)]
                        if arrivalStop == stationStartMin:
                                continue
                        routeWalkingFromStop2 = traci.simulation.findIntermodalRoute(arrivalStop, endOfOurTrip,
                                                                                     modes='',
                                                                                     depart=step, routingMode=0,
                                                                                     speed=1.0, walkFactor=-1.0,
                                                                                     departPos=0.0,
                                                                                     arrivalPos=-1073741824.0,
                                                                                     departPosLat=0.0,
                                                                                     pType='', vType='',
                                                                                     destStop='')
                        totWalkingFromStop2 = 0
                        edgesRouteWalkingFromStop2 = list(routeWalkingFromStop2[0].edges)
                        for edge in edgesRouteWalkingFromStop2:
                                length = float(edgeLengths[edge])
                                totWalkingFromStop2 += length
                        routeWithShuttle = traci.simulation.findRoute(stopEdge[stationStartMin], arrivalStop,
                                                              vType='shuttle', routingMode=0)
                        travelTimeShuttleTest = routeWithShuttle.travelTime
                        """OOOOOHH RICORDATI QUESTO TEMPO CHE VA CORRETTO!!!"""
                        totalTimeWalkingIntermodalTest = (minStart + totWalkingFromStop2) / pedestrianSpeed
                        timeIntermodal = totalTimeWalkingIntermodalTest + travelTimeShuttleTest
                        if timeIntermodal < minArrival:
                                minArrival = timeIntermodal
                                stationArrivalMin = str(i)
                                travelTimeShuttle = travelTimeShuttleTest
                                totalTimeWalkingIntermodal = totalTimeWalkingIntermodalTest
                                edgesFromStopMIN = edgesRouteWalkingFromStop2
                timeIntermodalMin = totalTimeWalkingIntermodal + travelTimeShuttle
                pedestrianDict[pupinoName].forcastedTimeWalking = timeWalking
                pedestrianDict[pupinoName].forcastedTimeOnFootIntermodal = totalTimeWalkingIntermodal
                pedestrianDict[pupinoName].forcastedTimeRiding = travelTimeShuttle
                if timeWalking < timeIntermodalMin:
                        print ("Let's walk")
                        traci.person.appendWalkingStage(pupinoName, edgesRouteWalking, 10, duration=-1, speed=-1,
                                                        stopID='')
                        successfulInsertion = 1
                        pedestrianDict[pupinoName].modalChoice = 0
                else:
                        print ("Let's take the bus")
                        successfulInsertion, walkingChoice, selectedShuttle = takeTheShuttle(stationStartMin, stationArrivalMin, stopEdge[stationStartMin], stopEdge[stationArrivalMin], endOfOurTrip, pupinoName, edgesToStopMIN, edgesFromStopMIN, listOfSmallRingShuttles, step, timeToWalkStop1, stationStartMin, stationArrivalMin, shuttleCharacteristics, timeWalking, edgesRouteWalking, pedestrianDict)
                        pedestrianDict[pupinoName].modalChoice = walkingChoice
                        pedestrianDict[pupinoName].busSelected = selectedShuttle
                        if walkingChoice == 3:
                                pedestrianDict[pupinoName].waitingStopEDGE = stopEdge[stationStartMin]
                return successfulInsertion

def takeTheShuttle(startStopID, arrivalStopID, originStop, arrivalStop, endOfOurTrip, pupinoName, edgesToStop1,
                   edgesFromStop2, listOfShuttles, step, timeToWalkStop1, stationStartMin, stationArrivalMin,
                   shuttleCharacteristics, timeWalking, edgesRouteWalking, pedestrianDict):
        selectedShuttle, shuttleAvailable = chooseShuttle(listOfShuttles, timeToWalkStop1, stationStartMin,
                                                          stationArrivalMin, shuttleCharacteristics)
        successfulInsertion = 0
        if shuttleAvailable == 1:
                traci.person.appendWalkingStage(pupinoName, edgesToStop1, 10, duration=-1, speed=-1, stopID='')
                traci.person.appendDrivingStage(pupinoName, arrivalStop, selectedShuttle)
                traci.person.appendWalkingStage(pupinoName, edgesFromStop2, 10, duration=-1, speed=-1, stopID='')
                isInCurrentRoute = 0  # if the stop is in the next lap I get an error
                currentEdge = traci.vehicle.getRoadID(selectedShuttle)
                currentEdgePassed = 0
                for edge in traci.vehicle.getRoute(selectedShuttle):
                        if edge == currentEdge:
                                currentEdgePassed = 1
                        if stopEdge[startStopID] == edge and currentEdgePassed == 1:
                                isInCurrentRoute = 1
                if isInCurrentRoute == 1:
                        traci.vehicle.setBusStop(selectedShuttle, stopID[startStopID], duration= stopDuration, flags=0)
                        if int(startStopID) < int(arrivalStopID):
                                traci.vehicle.setBusStop(selectedShuttle, stopID[arrivalStopID], duration= stopDuration, flags=0)
                successfulInsertion = 1
                walkingChoice = 3
                stopsCounterDict[stopID[startStopID]].peopleEmbarked += 1
                stopsCounterDict[stopID[arrivalStopID]].peopleDisembarked += 1
        elif shuttleAvailable == 0:
                traci.person.appendWalkingStage(pupinoName, edgesToStop1, 10, duration=-1, speed=-1, stopID='')
                traci.person.appendWaitingStage(pupinoName, 100000, description='waiting', stopID='')
                pedestrianDict[pupinoName].notAssignedTAG = 1
                print (pupinoName + " is waiting at station " + originStop)
                walkingChoice = 1
                pedestrianDict[pupinoName].waitingStop = startStopID
                pedestrianDict[pupinoName].arrivalStop = arrivalStopID
                stopsCounterDict[stopID[startStopID]].peopleEmbarked += 1
                stopsCounterDict[stopID[arrivalStopID]].peopleDisembarked += 1

                """qui poi nel run devi mettere che se e waiting, che aggiunga il tempo ad un nuovo counter, quindi aggiungilo anche nel dizionario, 
                e poi aggiungi anche che se e marchiato come waiting, che si metta alla ricerca di uno shuttle finche non lo trova"""


        """elif shuttleAvailable == 0 and timeWalking < 6000:
                traci.person.appendWalkingStage(pupinoName, edgesRouteWalking, 10, duration=-1, speed=-1, stopID='')
                successfulInsertion = 1
                walkingChoice = 1
        elif shuttleAvailable == 0 and timeWalking > 6000:
                successfulInsertion = 0
                walkingChoice = 1"""
        return successfulInsertion, walkingChoice, selectedShuttle

def chooseShuttle(listOfShuttles, timeToWalkStop1, stationStartStr, stationStopStr, shuttleCharacteristics):
        stationStart = int(stationStartStr)
        stationStop = int(stationStopStr)
        min = 9999
        closestGoodShuttle = 'None'
        minFound = 0
        for shuttleName in listOfShuttles:
                isInCurrentRoute = 0
                currentEdge = traci.vehicle.getRoadID(shuttleName)
                currentEdgePassed = 0
                isNotAJunction = 0
                for edge in traci.vehicle.getRoute(shuttleName):
                        if edge == currentEdge:
                                isNotAJunction = 1
                if isNotAJunction == 0:
                        continue
                for edge in traci.vehicle.getRoute(shuttleName):
                        if edge == currentEdge:
                                currentEdgePassed = 1
                        if stopEdge[stationStartStr] == edge and currentEdgePassed == 1:
                                isInCurrentRoute = 1
                if isInCurrentRoute == 1:
                        busFull = 0
                        if stationStop > stationStart:  # case origin and destination are within the same lap
                                for i in range(stationStart, stationStop + 1):
                                        probe = shuttleCharacteristics[shuttleName].peopleBoardedPerStopLap1[i]
                                        if (shuttleCharacteristics[shuttleName].peopleBoardedPerStopLap1[i]) == shuttleSmallRingCapacity:
                                                busFull = 1
                        if stationStop < stationStart:  # case the arrival is in the next lap
                                for i in range(stationStart, numberOfStops):
                                        if (shuttleCharacteristics[shuttleName].peopleBoardedPerStopLap1[i]) == shuttleSmallRingCapacity:
                                                busFull = 1
                                for i in range(0, stationStop + 1):
                                        if (shuttleCharacteristics[shuttleName].peopleBoardedPerStopLap2[i]) == shuttleSmallRingCapacity:
                                                busFull = 1
                else:
                        busFull = 0
                        if stationStop > stationStart:  # case origin and destination are within the same lap
                                for i in range(stationStart, stationStop + 1):
                                        probe = shuttleCharacteristics[shuttleName].peopleBoardedPerStopLap2[i]
                                        if (shuttleCharacteristics[shuttleName].peopleBoardedPerStopLap2[i]) == shuttleSmallRingCapacity:
                                                busFull = 1
                        if stationStop < stationStart:  # case the arrival is in the next lap
                                for i in range(stationStart, numberOfStops):
                                        if (shuttleCharacteristics[shuttleName].peopleBoardedPerStopLap2[i]) == shuttleSmallRingCapacity:
                                                busFull = 1
                                for i in range(0, stationStop + 1):
                                        if (shuttleCharacteristics[shuttleName].peopleBoardedPerStopLap3[i]) == shuttleSmallRingCapacity:
                                                busFull = 1
                if busFull == 1:
                        continue
                else:
                        # valutare i tempi di arrivo allo stop
                        position = traci.vehicle.getRoadID(shuttleName)
                        routeShuttleToStop = traci.simulation.findRoute(position, stopEdge[stationStartStr],
                                                                        vType='shuttle', routingMode=0)
                        travelTimeShuttle = (routeShuttleToStop.travelTime) * 1.3
                        """OOOOOHH RICORDATI QUESTO TEMPO CHE VA CORRETTO!!!"""
                        if timeToWalkStop1 < travelTimeShuttle:
                                if travelTimeShuttle < min:
                                        min = travelTimeShuttle
                                        closestGoodShuttle = shuttleName
                                        minFound = 1
        if minFound == 1:
                isInCurrentRoute = 0
                currentEdge = traci.vehicle.getRoadID(closestGoodShuttle)
                currentEdgePassed = 0
                for edge in traci.vehicle.getRoute(closestGoodShuttle):
                        if edge == currentEdge:
                                currentEdgePassed = 1
                        if stopEdge[stationStartStr] == edge and currentEdgePassed == 1:
                                isInCurrentRoute = 1
                if isInCurrentRoute == 1:
                        if stationStop > stationStart:  # case origin and destination are within the same lap
                                for i in range(stationStart, stationStop + 1):
                                        shuttleCharacteristics[closestGoodShuttle].peopleBoardedPerStopLap1[i] += 1
                                shuttleCharacteristics[closestGoodShuttle].peopleToBeBoardedPerStopLap1[
                                        stationStart] += 1
                                shuttleCharacteristics[closestGoodShuttle].peopleToBeDisembarkedPerStopLap1[
                                        stationStop] += 1
                        if stationStop < stationStart:  # case the arrival is in the next lap
                                for i in range(stationStart, numberOfStops):
                                        shuttleCharacteristics[closestGoodShuttle].peopleBoardedPerStopLap1[i] += 1
                                shuttleCharacteristics[closestGoodShuttle].peopleToBeBoardedPerStopLap1[
                                        stationStart] += 1
                                for i in range(0, stationStop + 1):
                                        shuttleCharacteristics[closestGoodShuttle].peopleBoardedPerStopLap2[i] += 1
                                shuttleCharacteristics[closestGoodShuttle].peopleToBeDisembarkedPerStopLap2[
                                        stationStop] += 1
                else:  # if it is the next lap, every order should be made the next lap (it could have be done with a matrix)
                        if stationStop > stationStart:  # case origin and destination are within the same lap
                                for i in range(stationStart, stationStop + 1):
                                        shuttleCharacteristics[closestGoodShuttle].peopleBoardedPerStopLap2[i] += 1
                                shuttleCharacteristics[closestGoodShuttle].peopleToBeBoardedPerStopLap2[
                                        stationStart] += 1
                                shuttleCharacteristics[closestGoodShuttle].peopleToBeDisembarkedPerStopLap2[
                                        stationStop] += 1
                        if stationStop < stationStart:  # case the arrival is in the next lap
                                for i in range(stationStart, numberOfStops):
                                        shuttleCharacteristics[closestGoodShuttle].peopleBoardedPerStopLap2[i] += 1
                                shuttleCharacteristics[closestGoodShuttle].peopleToBeBoardedPerStopLap2[
                                        stationStart] += 1
                                for i in range(0, stationStop + 1):
                                        shuttleCharacteristics[closestGoodShuttle].peopleBoardedPerStopLap3[i] += 1
                                shuttleCharacteristics[closestGoodShuttle].peopleToBeDisembarkedPerStopLap3[
                                        stationStop] += 1
                shuttleCharacteristics[closestGoodShuttle].totPeopleBoarded += 1
        else:
                print ("Shuttle Not Found")  # CHE FARE IN QUESTO CASO?????????????????????????????????????????????????
        return closestGoodShuttle, minFound

def reassign(pupinoName, stage, pedestrianDict, listOfSmallRingShuttles, shuttleCharacteristics, step, listOfLargeRingShuttles, listOfThirdRingShuttles):
        if pedestrianDict[pupinoName].originName == "Metro1":
                """if stage == 2:
                        currentEdge = traci.person.getRoadID(pupinoName)
                        routeWalkingToMETRO1 = traci.simulation.findIntermodalRoute(currentEdge, stopEdgeMETRO1,
                                                                                   modes='',
                                                                                   depart=step, routingMode=0,
                                                                                   speed=1.0, walkFactor=-1.0,
                                                                                   departPos=0.0,
                                                                                   arrivalPos=-1073741824.0,
                                                                                   departPosLat=0.0,
                                                                                   pType='', vType='',
                                                                                   destStop='')
                        totWalkingToMETRO1 = 0
                        edgesRouteWalkingToMETRO1 = list(routeWalkingToMETRO1[0].edges)
                        for edge in edgesRouteWalkingToMETRO1:
                                length = float(edgeLengths[edge])
                                totWalkingToMETRO1 += length
                        timeToMETRO1 = totWalkingToMETRO1 / pedestrianSpeed
                elif stage == 1:"""
                timeToMETRO1 = 20
                selectedShuttle, shuttleAvailable = chooseSuperShuttle(listOfLargeRingShuttles, timeToMETRO1,
                                                                       pedestrianDict[pupinoName].arrivalStop,
                                                                       shuttleCharacteristics, stopEdgeMETRO1)
                if shuttleAvailable == 1:
                        """if stage == 2:
                                traci.person.removeStage(pupinoName, 1)
                        elif stage == 1:"""
                        traci.person.removeStage(pupinoName, 0)
                        traci.person.appendDrivingStage(pupinoName, stopEdge[pedestrianDict[pupinoName].arrivalStop], selectedShuttle)
                        routeWalkingFromStop2 = traci.simulation.findIntermodalRoute(stopEdge[pedestrianDict[pupinoName].arrivalStop], pedestrianDict[pupinoName].destination,
                                modes='',
                                depart=step, routingMode=0,
                                speed=1.0, walkFactor=-1.0,
                                departPos=0.0,
                                arrivalPos=-1073741824.0,
                                departPosLat=0.0,
                                pType='', vType='',
                                destStop='')
                        edgesRouteWalkingFromStop2 = list(routeWalkingFromStop2[0].edges)
                        traci.person.appendWalkingStage(pupinoName, edgesRouteWalkingFromStop2, 10, duration=-1,
                                                        speed=-1,
                                                        stopID='')
                        isInCurrentRoute = 0  # if the stop is in the next lap I get an error
                        currentEdge = traci.vehicle.getRoadID(selectedShuttle)
                        currentEdgePassed = 0
                        for edge in traci.vehicle.getRoute(selectedShuttle):
                                if edge == currentEdge:
                                        currentEdgePassed = 1
                                if stopEdgeMETRO1 == edge and currentEdgePassed == 1:
                                        isInCurrentRoute = 1
                        if isInCurrentRoute == 1:
                                traci.vehicle.setBusStop(selectedShuttle,
                                                         stopIDMETRO1,
                                                         duration=stopDuration, flags=0)
                                traci.vehicle.setBusStop(selectedShuttle, stopID[pedestrianDict[pupinoName].arrivalStop], duration=stopDuration, flags=0)
                        stopsCounterDict["M1"].peopleEmbarked += 1
                        stopsCounterDict[stopID[pedestrianDict[pupinoName].arrivalStop]].peopleDisembarked += 1
                        pedestrianDict[pupinoName].notAssignedTAG = 0
                        print ("TAKEN!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
                        pedestrianDict[pupinoName].busSelected = selectedShuttle
        elif pedestrianDict[pupinoName].originName == "Metro2":
                """if stage == 2:
                        currentEdge = traci.person.getRoadID(pupinoName)
                        routeWalkingToMETRO2 = traci.simulation.findIntermodalRoute(currentEdge, stopEdgeMETRO2,
                                                                                   modes='',
                                                                                   depart=step, routingMode=0,
                                                                                   speed=1.0, walkFactor=-1.0,
                                                                                   departPos=0.0,
                                                                                   arrivalPos=-1073741824.0,
                                                                                   departPosLat=0.0,
                                                                                   pType='', vType='',
                                                                                   destStop='')
                        totWalkingToMETRO2 = 0
                        edgesRouteWalkingToMETRO2 = list(routeWalkingToMETRO2[0].edges)
                        for edge in edgesRouteWalkingToMETRO2:
                                length = float(edgeLengths[edge])
                                totWalkingToMETRO2 += length
                        timeToMETRO2 = totWalkingToMETRO2 / pedestrianSpeed
                elif stage == 1:"""
                timeToMETRO2 = 20
                selectedShuttle, shuttleAvailable = chooseSuperShuttle(listOfThirdRingShuttles, timeToMETRO2,
                                                                       pedestrianDict[pupinoName].arrivalStop,
                                                                       shuttleCharacteristics, stopEdgeMETRO1)
                if shuttleAvailable == 1:
                        """if stage == 2:
                                traci.person.removeStage(pupinoName, 1)
                        elif stage == 1:"""
                        traci.person.removeStage(pupinoName, 0)
                        traci.person.appendDrivingStage(pupinoName, stopEdgeRing3[pedestrianDict[pupinoName].arrivalStop], selectedShuttle)
                        routeWalkingFromStop2 = traci.simulation.findIntermodalRoute(stopEdgeRing3[pedestrianDict[pupinoName].arrivalStop], pedestrianDict[pupinoName].destination,
                                modes='',
                                depart=step, routingMode=0,
                                speed=1.0, walkFactor=-1.0,
                                departPos=0.0,
                                arrivalPos=-1073741824.0,
                                departPosLat=0.0,
                                pType='', vType='',
                                destStop='')
                        edgesRouteWalkingFromStop2 = list(routeWalkingFromStop2[0].edges)
                        traci.person.appendWalkingStage(pupinoName, edgesRouteWalkingFromStop2, 10, duration=-1,
                                                        speed=-1,
                                                        stopID='')
                        isInCurrentRoute = 0  # if the stop is in the next lap I get an error
                        currentEdge = traci.vehicle.getRoadID(selectedShuttle)
                        currentEdgePassed = 0
                        for edge in traci.vehicle.getRoute(selectedShuttle):
                                if edge == currentEdge:
                                        currentEdgePassed = 1
                                if stopEdgeMETRO2 == edge and currentEdgePassed == 1:
                                        isInCurrentRoute = 1
                        if isInCurrentRoute == 1:
                                traci.vehicle.setBusStop(selectedShuttle,
                                                         stopIDMETRO2,
                                                         duration=stopDuration, flags=0)
                                traci.vehicle.setBusStop(selectedShuttle, stopIDRing3[pedestrianDict[pupinoName].arrivalStop], duration=stopDuration, flags=0)
                        stopsCounterDict["M2"].peopleEmbarked += 1
                        stopsCounterDict[stopIDRing3[pedestrianDict[pupinoName].arrivalStop]].peopleDisembarked += 1
                        pedestrianDict[pupinoName].notAssignedTAG = 0
                        print ("TAKEN!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
                        pedestrianDict[pupinoName].busSelected = selectedShuttle
        else:
                """if stage == 2:
                        currentEdge = traci.person.getRoadID(pupinoName)
                        routeWalkingToStop1 = traci.simulation.findIntermodalRoute(currentEdge, stopEdge[pedestrianDict[pupinoName].waitingStop],
                                                                                   modes='',
                                                                                   depart=step, routingMode=0,
                                                                                   speed=1.0, walkFactor=-1.0,
                                                                                   departPos=0.0,
                                                                                   arrivalPos=-1073741824.0,
                                                                                   departPosLat=0.0,
                                                                                   pType='', vType='',
                                                                                   destStop='')
                        totWalkingToStop1 = 0
                        edgesRouteWalkingToStop1 = list(routeWalkingToStop1[0].edges)
                        for edge in edgesRouteWalkingToStop1:
                                length = float(edgeLengths[edge])
                                totWalkingToStop1 += length
                        timeToWalkStop1 = totWalkingToStop1 / pedestrianSpeed
                elif stage == 1:"""
                timeToWalkStop1 = 20
                selectedShuttle, shuttleAvailable = chooseShuttle(listOfSmallRingShuttles, timeToWalkStop1, pedestrianDict[pupinoName].waitingStop, pedestrianDict[pupinoName].arrivalStop,shuttleCharacteristics)
                if shuttleAvailable == 1:
                        """if stage == 2:
                                traci.person.removeStage(pupinoName, 1)
                        elif stage == 1:"""
                        traci.person.removeStage(pupinoName, 0)
                        traci.person.appendDrivingStage(pupinoName, stopEdge[pedestrianDict[pupinoName].arrivalStop], selectedShuttle)
                        routeWalkingFromStop2 = traci.simulation.findIntermodalRoute(stopEdge[pedestrianDict[pupinoName].arrivalStop], pedestrianDict[pupinoName].destination,
                                        modes='',
                                        depart=step, routingMode=0,
                                        speed=1.0, walkFactor=-1.0,
                                        departPos=0.0,
                                        arrivalPos=-1073741824.0,
                                        departPosLat=0.0,
                                        pType='', vType='',
                                        destStop='')
                        edgesRouteWalkingFromStop2 = list(routeWalkingFromStop2[0].edges)
                        traci.person.appendWalkingStage(pupinoName, edgesRouteWalkingFromStop2, 10, duration=-1,
                                                                speed=-1,
                                                                stopID='')

                        isInCurrentRoute = 0  # if the stop is in the next lap I get an error
                        currentEdge = traci.vehicle.getRoadID(selectedShuttle)
                        currentEdgePassed = 0
                        for edge in traci.vehicle.getRoute(selectedShuttle):
                                if edge == currentEdge:
                                        currentEdgePassed = 1
                                if stopEdge[pedestrianDict[pupinoName].waitingStop] == edge and currentEdgePassed == 1:
                                        isInCurrentRoute = 1
                        if isInCurrentRoute == 1:
                                traci.vehicle.setBusStop(selectedShuttle,
                                                         stopID[pedestrianDict[pupinoName].waitingStop],
                                                         duration=stopDuration, flags=0)
                                if int(pedestrianDict[pupinoName].waitingStop) < int(pedestrianDict[pupinoName].arrivalStop):
                                        traci.vehicle.setBusStop(selectedShuttle, stopID[pedestrianDict[pupinoName].arrivalStop], duration=stopDuration, flags=0)
                        stopsCounterDict[stopID[pedestrianDict[pupinoName].waitingStop]].peopleEmbarked += 1
                        stopsCounterDict[stopID[pedestrianDict[pupinoName].arrivalStop]].peopleDisembarked += 1
                        pedestrianDict[pupinoName].notAssignedTAG = 0
                        print ("TAKEN!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
                        pedestrianDict[pupinoName].busSelected = selectedShuttle

def pedestrianODAssignment(pedestrianDict):
        for i in range(numberOfPeopleInserted):
                pupinosName = "pupino" + str(i)
                pedestrianDict[pupinosName] = Pedestrian(pupinosName)
        count = 0
        for i in range(int(numberOfPeopleInserted / 100)):
                for j in range(100):
                        pupinosName = "pupino" + str(count)
                        if j < 36:
                                pedestrianDict[pupinosName].origin = Origins["Metro1"]
                                pedestrianDict[pupinosName].originName = "Metro1"
                        elif j >= 36 and j < 78:
                                pedestrianDict[pupinosName].origin = Origins["Metro2"]
                                pedestrianDict[pupinosName].originName = "Metro2"
                        elif j >= 78 and j < 88:
                                pedestrianDict[pupinosName].origin = Origins["P1"]
                                pedestrianDict[pupinosName].originName = "P1"
                        elif j >= 88 and j < 91:
                                pedestrianDict[pupinosName].origin = Origins["P2"]
                                pedestrianDict[pupinosName].originName = "P2"
                        else:
                                pedestrianDict[pupinosName].origin = Origins["P3"]
                                pedestrianDict[pupinosName].originName = "P3"
                        count += 1
        j = 0
        k = 0
        l = 0
        m = 0
        n = 0
        for i in range(numberOfPeopleInserted):
                pupinosName = "pupino" + str(i)
                if pedestrianDict[pupinosName].originName == "Metro1":
                        if j < 1:
                                pedestrianDict[pupinosName].destination = Destinations["HT"]
                                pedestrianDict[pupinosName].destinationName = "HT"
                        elif j >= 1 and j < 23:
                                pedestrianDict[pupinosName].destination = Destinations["Hospital"]
                                pedestrianDict[pupinosName].destinationName = "Hospital"
                        elif j >= 23 and j < 35:
                                pedestrianDict[pupinosName].destination = Destinations["University"]
                                pedestrianDict[pupinosName].destinationName = "University"
                        elif j >= 35 and j < 39:
                                pedestrianDict[pupinosName].destination = Destinations["Cascina"]
                                pedestrianDict[pupinosName].destinationName = "Cascina"
                        elif j >= 39 and j < 63:
                                pedestrianDict[pupinosName].destination = Destinations["Private1"]
                                pedestrianDict[pupinosName].destinationName = "Private1"
                        elif j >= 63 and j < 87:
                                pedestrianDict[pupinosName].destination = Destinations["Private2"]
                                pedestrianDict[pupinosName].destinationName = "Private2"
                        elif j >= 87 and j < 93:
                                pedestrianDict[pupinosName].destination = Destinations["Private3"]
                                pedestrianDict[pupinosName].destinationName = "Private3"
                        elif j >= 93:
                                pedestrianDict[pupinosName].destination = Destinations["Private4"]
                                pedestrianDict[pupinosName].destinationName = "Private4"
                        j += 1
                        if j > 100:
                                j = 0
                if pedestrianDict[pupinosName].originName == "Metro2":
                        if n < 3:
                                pedestrianDict[pupinosName].destination = Destinations["HT"]
                                pedestrianDict[pupinosName].destinationName = "HT"
                        elif n >= 3 and n < 8:
                                pedestrianDict[pupinosName].destination = Destinations["Hospital"]
                                pedestrianDict[pupinosName].destinationName = "Hospital"
                        elif n >= 8 and n < 49:
                                pedestrianDict[pupinosName].destination = Destinations["University"]
                                pedestrianDict[pupinosName].destinationName = "University"
                        elif n >= 49 and n < 50:
                                pedestrianDict[pupinosName].destination = Destinations["Cascina"]
                                pedestrianDict[pupinosName].destinationName = "Cascina"
                        elif n >= 50 and n < 55:
                                pedestrianDict[pupinosName].destination = Destinations["Private1"]
                                pedestrianDict[pupinosName].destinationName = "Private1"
                        elif n >= 55 and n < 60:
                                pedestrianDict[pupinosName].destination = Destinations["Private2"]
                                pedestrianDict[pupinosName].destinationName = "Private2"
                        elif n >= 60 and n < 80:
                                pedestrianDict[pupinosName].destination = Destinations["Private3"]
                                pedestrianDict[pupinosName].destinationName = "Private3"
                        elif n >= 80:
                                pedestrianDict[pupinosName].destination = Destinations["Private4"]
                                pedestrianDict[pupinosName].destinationName = "Private4"
                        n += 1
                        if n > 100:
                                n = 0
                if pedestrianDict[pupinosName].originName == "P1":
                        if k < 1:
                                pedestrianDict[pupinosName].destination = Destinations["HT"]
                                pedestrianDict[pupinosName].destinationName = "HT"
                        elif k >= 1 and k < 29:
                                pedestrianDict[pupinosName].destination = Destinations["Hospital"]
                                pedestrianDict[pupinosName].destinationName = "Hospital"
                        elif k >= 29 and k < 39:
                                pedestrianDict[pupinosName].destination = Destinations["University"]
                                pedestrianDict[pupinosName].destinationName = "University"
                        elif k >= 39 and k < 43:
                                pedestrianDict[pupinosName].destination = Destinations["Cascina"]
                                pedestrianDict[pupinosName].destinationName = "Cascina"
                        elif k >= 43 and k < 74:
                                pedestrianDict[pupinosName].destination = Destinations["Private1"]
                                pedestrianDict[pupinosName].destinationName = "Private1"
                        elif k >= 74 and k < 82:
                                pedestrianDict[pupinosName].destination = Destinations["Private2"]
                                pedestrianDict[pupinosName].destinationName = "Private2"
                        elif k >= 82 and k < 91:
                                pedestrianDict[pupinosName].destination = Destinations["Private3"]
                                pedestrianDict[pupinosName].destinationName = "Private3"
                        elif k >= 91:
                                pedestrianDict[pupinosName].destination = Destinations["Private4"]
                                pedestrianDict[pupinosName].destinationName = "Private4"
                        k += 1
                        if k > 100:
                                k = 0
                if pedestrianDict[pupinosName].originName == "P2":

                        if l < 3:
                                pedestrianDict[pupinosName].destination = Destinations["HT"]
                                pedestrianDict[pupinosName].destinationName = "HT"
                        elif l >= 3 and l < 38:
                                pedestrianDict[pupinosName].destination = Destinations["University"]
                                pedestrianDict[pupinosName].destinationName = "University"
                        elif l >= 38 and l < 40:
                                pedestrianDict[pupinosName].destination = Destinations["Cascina"]
                                pedestrianDict[pupinosName].destinationName = "Cascina"
                        elif l >= 40 and l < 42:
                                pedestrianDict[pupinosName].destination = Destinations["Private1"]
                                pedestrianDict[pupinosName].destinationName = "Private1"
                        elif l >= 42 and l < 63:
                                pedestrianDict[pupinosName].destination = Destinations["Private2"]
                                pedestrianDict[pupinosName].destinationName = "Private2"
                        elif l >= 63 and l < 83:
                                pedestrianDict[pupinosName].destination = Destinations["Private3"]
                                pedestrianDict[pupinosName].destinationName = "Private3"
                        elif l >= 83:
                                pedestrianDict[pupinosName].destination = Destinations["Private4"]
                                pedestrianDict[pupinosName].destinationName = "Private4"
                        l += 1
                        if l > 100:
                                l = 0
                if pedestrianDict[pupinosName].originName == "P3":
                        if m < 3:
                                pedestrianDict[pupinosName].destination = Destinations["HT"]
                                pedestrianDict[pupinosName].destinationName = "HT"
                        elif m >= 3 and m < 38:
                                pedestrianDict[pupinosName].destination = Destinations["University"]
                                pedestrianDict[pupinosName].destinationName = "University"
                        elif m >= 38 and m < 40:
                                pedestrianDict[pupinosName].destination = Destinations["Cascina"]
                                pedestrianDict[pupinosName].destinationName = "Cascina"
                        elif m >= 40 and m < 42:
                                pedestrianDict[pupinosName].destination = Destinations["Private1"]
                                pedestrianDict[pupinosName].destinationName = "Private1"
                        elif m >= 42 and m < 63:
                                pedestrianDict[pupinosName].destination = Destinations["Private2"]
                                pedestrianDict[pupinosName].destinationName = "Private2"
                        elif m >= 63 and m < 83:
                                pedestrianDict[pupinosName].destination = Destinations["Private3"]
                                pedestrianDict[pupinosName].destinationName = "Private3"
                        elif m >= 83:
                                pedestrianDict[pupinosName].destination = Destinations["Private4"]
                                pedestrianDict[pupinosName].destinationName = "Private4"
                        m += 1
                        if m > 100:
                                m = 0
        count = 0
        for i in range(rushHourDuration):
                for j in range(
                        int((numberOfPeopleInserted * 0.8) / rushHourDuration)):  # NUMBER OF PEOPLE INSERTED PER SECOND
                        pupinosName = "pupino" + str(count)
                        pedestrianDict[pupinosName].initialInsertionStep = (i + beginOfPeopleInsertion)
                        count += 1

        # t = int((numberOfPeopleInserted * 0.2)/(offPeakHours*3600))
        for j in range(
                numberOfPeopleInserted - int(numberOfPeopleInserted * 0.8)):  # NUMBER OF PEOPLE INSERTED PER SECOND
                pupinosName = "pupino" + str(count)

                pedestrianDict[pupinosName].initialInsertionStep = (beginOfPeopleInsertion + rushHourDuration + j * 2)
                count += 1

def run():
        pedestrianDict = {}
        pedestrianODAssignment(pedestrianDict)
        print ("Ho fatto il dizionario dei pedoni")

        PedestrianInput = open('PedestrianInputFile.csv', 'wb')
        csvPedestrianInput = csv.writer(PedestrianInput)
        headerPedestrianInput = list()
        headerPedestrianInput.append("Pedestrian_Name")
        headerPedestrianInput.append("Origin")
        headerPedestrianInput.append("Destination")
        headerPedestrianInput.append("Initial_Insertion")
        csvPedestrianInput.writerow(headerPedestrianInput)

        for key in pedestrianDict:
                rowList = list()
                rowList.append(pedestrianDict[key].name)
                rowList.append(pedestrianDict[key].origin)
                rowList.append(pedestrianDict[key].destination)
                rowList.append(pedestrianDict[key].initialInsertionStep)
                csvPedestrianInput.writerow(rowList)
        print ("Ho stampato l'input")
        peoplePresentDict = {}
        ringRouteEdges = list()
        shuttleCharacteristics = {}
        step = 0
        initialEdge = "gneE1"
        finalEdge = "gneE0"
        initialEdgeSecondRing = "gneE1"
        finalEdgeSecondRing = "gneE0"
        initialEdgeThirdRing = "-340089945#2.172"
        finalEdgeThirdRing = "-340089945#2.151"
        ringRouteEdges, secondEdge = get_route(step, initialEdge, finalEdge)
        traci.route.add("ringRoute", ringRouteEdges)
        ringRouteEdgesLargeRing, secondEdgeLargeRing = get_route(step, initialEdgeSecondRing, finalEdgeSecondRing)
        traci.route.add("bigRingRoute", ringRouteEdgesLargeRing)
        ringRouteEdgesThirdRing, secondEdgeThirdRing = get_route(step, initialEdgeThirdRing, finalEdgeThirdRing)
        traci.route.add("ringRoute3", ringRouteEdgesThirdRing)
        listOfShuttles = list()
        listOfSmallRingShuttles = list()
        listOfLargeRingShuttles = list()
        listOfThirdRingShuttles = list()
        k = 0

        ringEdgesList = list()
        for edge in ringRouteEdges:
               ringEdgesList.append(edge)
        del ringEdgesList[-1]

        edgesSpeed = {}
        for edge in ringEdgesList:
                edgesSpeed[edge] = list()
                edgesSpeed[edge].append(edge)
                edgesSpeed[edge].append(edgeLengths[edge])

        edgesPresence = {}
        for edge in ringEdgesList:
                edgesPresence[edge] = list()
                edgesPresence[edge].append(edge)
                edgesPresence[edge].append(edgeLengths[edge])

        while step < 50000:
                print ("Step " + str(step))
                peoplePresentDict[step] = PeoplePresent(step)
                if step == ((beginOfPeopleInsertion/numberOfInitialPlatoons)*k) and step != 300:
                        temporaryList = insert_shuttles(numberOfInitialPlatoons*(k))
                        for i in temporaryList:
                                listOfShuttles.append(i)
                                listOfSmallRingShuttles.append(i)
                        if k < numberOfInitialPlatoons:
                                k += 1
                if step == 10:
                        listOfLargeRingShuttles = insert_secondRing_Shuttles(totalShuttleBigRing, "bigRingRoute")
                        for i in listOfLargeRingShuttles:
                                listOfShuttles.append(i)
                if step == 10:
                        listOfThirdRingShuttles = insert_thirdRing_Shuttles(totalShuttleThirdRing, "ringRoute3")
                        for i in listOfThirdRingShuttles:
                                listOfShuttles.append(i)
                if step <= beginOfPeopleInsertion:
                        for i in listOfShuttles:  # Creates the shuttle dictionary
                                shuttleCharacteristics[i] = Shuttle(i)
                if step >= 1:
                        for shuttle in listOfSmallRingShuttles:
                                if shuttleCharacteristics[shuttle].flagOfReroute == 0:  # if the flag is 1 it means it has already been rerouted, otherwise it is to be rerouted
                                        if traci.vehicle.getRoadID(shuttle) == initialEdge:
                                                reroute(shuttle, shuttleCharacteristics, "ringRoute")
                                elif shuttleCharacteristics[shuttle].flagOfReroute == 1:
                                        if traci.vehicle.getRoadID(shuttle) == secondEdge:
                                                shuttleCharacteristics[shuttle].flagOfReroute = 0
                                shuttleCharacteristics[shuttle].totPeopleSumPerSecond += traci.vehicle.getPersonNumber(shuttle)
                        for shuttle in listOfLargeRingShuttles:
                                if shuttleCharacteristics[shuttle].flagOfReroute == 0:  # if the flag is 1 it means it has already been rerouted, otherwise it is to be rerouted
                                        if traci.vehicle.getRoadID(shuttle) == initialEdgeSecondRing:
                                                reroute(shuttle, shuttleCharacteristics, "bigRingRoute")
                                elif shuttleCharacteristics[shuttle].flagOfReroute == 1:
                                        if traci.vehicle.getRoadID(shuttle) == secondEdgeLargeRing:
                                                shuttleCharacteristics[shuttle].flagOfReroute = 0
                                shuttleCharacteristics[shuttle].totPeopleSumPerSecond += traci.vehicle.getPersonNumber(shuttle)
                        for shuttle in listOfThirdRingShuttles:
                                if shuttleCharacteristics[shuttle].flagOfReroute == 0:  # if the flag is 1 it means it has already been rerouted, otherwise it is to be rerouted
                                        if traci.vehicle.getRoadID(shuttle) == initialEdgeThirdRing:
                                                reroute(shuttle, shuttleCharacteristics, "ringRoute3")
                                elif shuttleCharacteristics[shuttle].flagOfReroute == 1:
                                        if traci.vehicle.getRoadID(shuttle) == secondEdgeThirdRing:
                                                shuttleCharacteristics[shuttle].flagOfReroute = 0
                                shuttleCharacteristics[shuttle].totPeopleSumPerSecond += traci.vehicle.getPersonNumber(shuttle)
                                # QUI BISOGNA ANCHE VALUTARE SE IL PUPINO E' STATO INSERITO CORRETTAMENTE, ALTRIMENTI VA REINSERITO
                        listOfPedestrianInSimulation = traci.person.getIDList()
                        for pedestrian in listOfPedestrianInSimulation:
                                if pedestrianDict[pedestrian].removed == 0:
                                        stage = traci.person.getStage(pedestrian)
                                        if pedestrianDict[pedestrian].notAssignedTAG == 1 and stage == 1:
                                                reassign(pedestrian, stage, pedestrianDict, listOfSmallRingShuttles, shuttleCharacteristics, step, listOfLargeRingShuttles, listOfThirdRingShuttles)
                                        if stage == 1:
                                                pedestrianDict[pedestrian].timeWaitingNOTAssigned += 1
                                        if stage == 2:
                                                pedestrianDict[pedestrian].timeWalking  += 1
                                                if traci.person.getSpeed(pedestrian) < 0.1:
                                                        pedestrianDict[pedestrian].timeWaitingWalking += 1
                                                peoplePresentDict[step].walking += 1
                                        elif stage == 3:
                                                pedestrianDict[pedestrian].timeRiding += 1
                                                if traci.person.getSpeed(pedestrian) < 0.1:
                                                        if pedestrianDict[pedestrian].inTheShuttle == 1:
                                                                pedestrianDict[pedestrian].timeStuckInTraffic += 1
                                                        elif pedestrianDict[pedestrian].inTheShuttle == 0:
                                                                pedestrianDict[pedestrian].timeWaitingAtTheStop += 1
                                                                pedestrianEdge = traci.person.getRoadID(pedestrian)
                                                                if pedestrianEdge != pedestrianDict[pedestrian].waitingStopEDGE:
                                                                        pedestrianDict[pedestrian].inTheShuttle = 1
                                                peoplePresentDict[step].ridingOrWaitingAtTheStop += 1
                                        if pedestrianDict[pedestrian].modalChoice == 0 or pedestrianDict[pedestrian].modalChoice == 1 or pedestrianDict[pedestrian].modalChoice == 2:
                                                peoplePresentDict[step].onFoot += 1
                                        elif pedestrianDict[pedestrian].modalChoice == 3:
                                                peoplePresentDict[step].byBus += 1
                                        pedestrianDict[pedestrian].lastStep = step
                                        peoplePresentDict[step].total += 1
                                        if pedestrianDict[pedestrian].timeWaitingAtTheStop == 1500 or pedestrianDict[pedestrian].timeRiding == 1500:
                                                pedestrianDict[pedestrian].removed = 1
                                if pedestrianDict[pedestrian].removed == 1:
                                        traci.person.removeStages(pedestrian)
                        count = 0
                        if step <= (rushHourDuration+ beginOfPeopleInsertion) * 1.05:
                                for i in range(count, numberOfPeopleInserted):
                                        pupinosName = "pupino" + str(i)
                                        if pedestrianDict[pupinosName].initialInsertionStep == step:
                                                inserted = insert_pupini(step, pedestrianDict[pupinosName].origin,
                                                                         pedestrianDict[pupinosName].destination, pupinosName,
                                                                         listOfSmallRingShuttles, listOfLargeRingShuttles,
                                                                         listOfThirdRingShuttles, listOfShuttles,
                                                                         shuttleCharacteristics, pedestrianDict)
                                                count = i

                #here we have a dictionary with edges as keys, the result will be a list of speeds for each edge, when exported in xls rows will be transposed into columns, FIRST VALUE IS THE LENGHT IN METERS
                if step < (rushHourDuration + offPeakHours*3600 + beginOfPeopleInsertion):
                        for edge in ringEdgesList:
                                edgesPresence[edge].append(traci.edge.getLastStepVehicleNumber(edge))
                                if traci.edge.getLastStepVehicleNumber(edge) > 0:
                                        edgesSpeed[edge].append(traci.edge.getLastStepMeanSpeed(edge))
                                else:
                                        edgesSpeed[edge].append("NO")



                # MODAL CHOICE
                # CALCULATE AVG SPEED
                if step > ((rushHourDuration + offPeakHours*3600 + beginOfPeopleInsertion) * 1.05):
                        for shuttle in listOfSmallRingShuttles:
                                if shuttleCharacteristics[shuttle].peopleBoardedPerStopLap1 == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] and shuttleCharacteristics[shuttle].peopleBoardedPerStopLap2 == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] and shuttleCharacteristics[shuttle].peopleBoardedPerStopLap3 == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] and shuttleCharacteristics[shuttle].removed == 0:
                                        shuttleCharacteristics[shuttle].removed = 1
                                        shuttleCharacteristics[shuttle].removedAtStep = step
                                        shuttleCharacteristics[shuttle].lastLap = shuttleCharacteristics[shuttle].LapCounter
                        for shuttle in listOfLargeRingShuttles:
                                if shuttleCharacteristics[shuttle].peopleBookedFromMETROLap1 == 0 and shuttleCharacteristics[shuttle].peopleBookedFromMETROLap2 == 0 and shuttleCharacteristics[shuttle].removed == 0:
                                        shuttleCharacteristics[shuttle].removed = 1
                                        shuttleCharacteristics[shuttle].removedAtStep = step
                                        shuttleCharacteristics[shuttle].lastLap = shuttleCharacteristics[shuttle].LapCounter
                        for shuttle in listOfThirdRingShuttles:
                                if shuttleCharacteristics[shuttle].peopleBookedFromMETROLap1 == 0 and shuttleCharacteristics[shuttle].peopleBookedFromMETROLap2 == 0 and shuttleCharacteristics[shuttle].removed == 0:
                                        shuttleCharacteristics[shuttle].removed = 1
                                        shuttleCharacteristics[shuttle].removedAtStep = step
                                        shuttleCharacteristics[shuttle].lastLap = shuttleCharacteristics[shuttle].LapCounter

                step += 1
                traci.simulationStep()

        for edge in ringRouteEdges:
                csvSpeeds.writerow(edgesSpeed[edge])
        for edge in ringRouteEdges:
                csvPresence.writerow(edgesPresence[edge])


        

        traci.close()
        sys.stdout.flush()

# MAIN
if __name__ == "__main__":
        options = get_options()

        # this script has been called from the command line. It will start sumo as a
        # server, then connect and run
        if options.nogui:
                sumoBinary = checkBinary('sumo')
        else:
                sumoBinary = checkBinary('sumo-gui')

        sumoCmd = [sumoBinary, "-c", "Area.sumocfg", "--pedestrian.model", "striping", "--ignore-route-errors"]
        traci.start(sumoCmd)
        run()

        end = time.time()
        simulationTime = end-start

        print ("Time of the simulation" + str(simulationTime))
        rowList = list()
        rowList.append(simulationTime)
        csvDuration.writerow(rowList)






Back to the top