Esempio n. 1
0
    def _create_random_pedestrian(self):
        if (len(self.pedestrians) <= c.LIMIT_OF_PEDESTRIANS):
            rand = randint(0, 1)
            ped = 0
            if rand == 0:
                ped = Pedestrian.create_random(0, self.width)
            else:
                ped = Pedestrian.create_random(self.width, 0)
            self.pedestrians.append(ped)

        self.random_pedestrian()
Esempio n. 2
0
def loadPedestrians(filename):
    json_data = None
    ped_list = []
    with open(filename, "rt") as fd:
        json_data = json.load(fd)
    for json_ped in json_data:
        ped_list.append(Pedestrian(json_ped))
    return ped_list
Esempio n. 3
0
 def parse(self, line):
     if Driver.parse(line, self.agents, self.animator):
         return True
     if Traffic_signal.parse(line, self.agents, self.animator):
         return True
     if Pedestrian.parse(line, self.agents, self.animator):
         return True
     return False
Esempio n. 4
0
    def generate_pedestrian(self, num_entrance_nodes, num_destination_nodes):
        # TODO: add random number generator.
        entrance_node = self.grid.entrance_nodes[random.randrange(
            0, num_entrance_nodes - 1)]
        destination_node = self.grid.destination_nodes[random.randrange(
            0, num_destination_nodes - 1)]

        # TODO: set speed (third argument) dynamically by drawing from a distribution.
        new_ped = Pedestrian(entrance_node, destination_node, 1,
                             self.grid.node_dict)

        return new_ped
Esempio n. 5
0
def pedestrian_main():
    history = 20
    bs = cv.createBackgroundSubtractorKNN(True)
    bs.setHistory(history)
    cv.namedWindow('surveillance')
    pedestrians = {}
    first_frame = True
    frames = 0
    camera = cv.VideoCapture(0)
    while (cv.waitKey(1) == -1):
        grabbed, frame = camera.read()
        if (grabbed is False):
            break
        fgmask = bs.apply(frame)
        if (frames < history):
            frames += 1
            continue
        thresh = cv.threshold(fgmask.copy(), 127, 255, cv.THRESH_BINARY)[1]
        thresh = cv.erode(thresh,
                          cv.getStructuringElement(cv.MORPH_ELLIPSE, (3, 3)),
                          2)
        dilate = cv.dilate(thresh,
                           cv.getStructuringElement(cv.MORPH_ELLIPSE, (8, 3)),
                           2)

        img, cnts, hier = cv.findContours(dilate, cv.RETR_EXTERNAL,
                                          cv.CHAIN_APPROX_SIMPLE)
        cnt = 0
        for c in cnts:
            if (cv.contourArea(c) > 500):
                x, y, w, h = cv.boundingRect(c)
                cv.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 1)
                if (first_frame == True):
                    pedestrians[cnt] = Pedestrian(cnt, frame, (x, y, w, h))
                cnt += 1
        for i, p in pedestrians:
            p.update(frame)

        first_frame = False
        frames += 1

        cv.imshow('surveillance', frame)
    cv.destroyAllWindows()
    def __init__(self, travPop, pedNet, transSys, popExp, param):

        self.pedestrianDict = dict()

        for pedID, rawPed in travPop.items():
            persMem = popExp.memoryDict[pedID]

            origNode = rawPed.origNode
            destNode = rawPed.destNode

            transferStation = rawPed.transferStation

            depTime = rawPed.depTime
            assert (depTime >=
                    0), "traveler %s has negative depTime (%s) %s" % (
                        pedID, depTime, travPop[pedID])

            trainList = rawPed.trainList

            self.pedestrianDict[pedID] = Pedestrian(origNode, destNode,
                                                    depTime, trainList,
                                                    transferStation, pedNet,
                                                    transSys, persMem, param)
def run_simulation(city, num_peds):
    print("Generating {} random pedestrians".format(num_peds))
    pedestrians = Pedestrian.generate_random_pedestrians(num_peds, city)

    """
    We create a count of how many times a node (CityLocation object) appears in 
    the shortest simple paths of pedestrians, indicating a "hot spot" in the grid. We also
    examine the number of times that a node is occupied by a pedestrian
    on a path at the "same time," i.e. in the same index position in a pathway, as another
    node. This indicates frequent "collisions" of pedestrians at the same place at same time.
    We exclude start and destination nodes from this count.
    """

    intersect_dict = {}

    for ped in pedestrians:
        shortest_path = ped.shortest_path
        node_position = 1
        for short_path_node in shortest_path[1:-1]:
            count = intersect_dict.get(short_path_node, 0)
            intersect_dict[short_path_node] = count + 1
            node_position += 1

    return sorted(intersect_dict.items(), key=lambda x: x[1], reverse=True)
Esempio n. 8
0
	def render(self, screen):
		Pedestrian.render(self, screen)
Esempio n. 9
0
def compute_prob_neighbors(geometry: Geometry, grid: Grid, ped: Pedestrian,
                           floorfield, weight_direction: bool):
    prob = {}

    # compute visible area
    x, y = grid.get_coordinates(ped.i(), ped.j())
    vis = geometry.visible_area(x, y)

    # compute voronoi polygons of neighbors
    neighbor_voronoi_polygons = compute_voronoi_neighbors(geometry, grid, ped)

    intersections = []

    weight_distance = compute_point_distance(geometry, grid,
                                             [ped.i(), ped.j()])
    weight_prob = distance_to_prob_dec(weight_distance, 40, 0.15)

    weighted_floorfield = weight_prob * floorfield

    inside = grid.get_inside_polygon_cells(geometry, vis.exterior.coords)

    # sum up every cell in neighbor polygon to neighbor cell
    # sum is weighted by distance, closer = more important
    for key, polygon in neighbor_voronoi_polygons.items():
        if key == Neighbors.self:
            intersections.append(polygon)
            prob[key] = floorfield.filled(0)[ped.i()][ped.j()]

        elif polygon is not None:
            p = Polygon(polygon.coords)
            inter = p.intersection(vis)

            points = []
            if inter.geom_type == 'Polygon':
                points = inter.exterior.coords
            elif inter.geom_type == 'GeometryCollection':
                for i in inter.geoms:
                    if i.geom_type == 'Polygon':
                        for ppp in i.exterior.coords:
                            points.append([ppp[0], ppp[1]])
            elif inter.geom_type == 'MultiPolygon':
                for i in inter.geoms:
                    if i.geom_type == 'Polygon':
                        for ppp in i.exterior.coords:
                            points.append([ppp[0], ppp[1]])
            else:
                print(inter)

            if len(points) == 0:
                prob[key] = 0
            else:
                intersection = sg.Polygon(points)
                intersections.append(intersection)

                inside_cells = grid.get_inside_polygon_cells(geometry, points)
                combination = inside_cells * weighted_floorfield

                prob[key] = np.ma.max(combination, fill_value=0)

    # weight cells by moving direction
    if weight_direction:
        weights = {}
        for key, p in prob.items():
            weights[key] = weighted_neighbors[ped.direction][key]
        weights = normalize_dict(weights)
        for key, p in prob.items():
            prob[key] = p * weights[key]

    prob = normalize_dict(prob)
    return prob
Esempio n. 10
0
 def readNextRow(self):
     """ read in pedestrian data of the next time step.
     """
     
     if self._csvReader == None:
         sys.exit("No CSV file is opened.")
     
     self._timestep = self._timestep + 1
     timestep = self._timestep
     # read in one row of data
     dataEntry = self._readNextRow()
     
     if timestep == 0:
         self.timebase = dataEntry.at['time_stamp']
     
     # self.time is relative to the first timestamp in csv
     self.time = dataEntry.at['time_stamp'] - self.timebase
     print('Time: ' + str(self.time) + 's')
     
     # Loop over rows of data from the csv file
     pedNum = 0 # Num of peds in this frame
     curPeds = dict()
     while True:
         # add the new entry to curPeds
         id = dataEntry.at['ped_id']
         # Check if this pedestrian is in the ROI
         # In _transformAndCrop, dataEntry will be changed
         isInRoi = self._transformAndCrop(dataEntry) 
         if id in self.peds:
             # This pedestrian already exists in peds, so update it
             self.peds[id].update(dataEntry)
             self.peds[id].states[timestep]._isInRoi = isInRoi
         else:
             # Otherwise, a new pedestrian needs to be constructed
             self.peds[id] = Pedestrian(dataEntry, self)
             self.peds[id].states[timestep]._isInRoi = isInRoi
         
         curPeds[id] = self.peds[id]
         
         pedNum = pedNum + 1
         dataEntry_1 = dataEntry
         
         # read the next row
         dataEntry = self._readNextRow()
         
         # If EOF is reached, jump out of the loop
         if dataEntry.empty:
             break
         # If the next row has a different timestamp, jump out of the loop
         if dataEntry_1.at['time_stamp'] != dataEntry.at['time_stamp']:
             break
     if pedNum > 0:
         print('Num of peds: ' + str(pedNum))
         
     self.pedList[timestep] = curPeds
     # Loop over all pedestrians in curPeds
     for id in list(curPeds):
         ped = self.peds[id]
         # Calculate features
         ped.calculate(curPeds)
     
     # Determine return value
     if dataEntry.empty:
         return False # EOF has been reached
     else:
         return True
Esempio n. 11
0
 def __init__(self):
     Pedestrian.__init__(self)
     self.view_range = self.radius + 10
Esempio n. 12
0
    while d_frame[0,0]==data_no_headers.values[0,0]:
        ind=ind+1
        data_no_headers = pd.read_csv("atc-20121114.csv", names = headers, skiprows=ind, nrows=1)
        if d_frame[0,0]==data_no_headers.values[0,0]:
            d_frame = np.concatenate((d_frame,data_no_headers.values), axis=0)

    return d_frame
ped_list = []
a = read_next_frame()
print(a.shape)
a_row = a.shape[0]
#a_col = a.shape[1]
print(a_row)
for count in range(0,a.shape[0]):
   t1 = Pedestrian(a[count,1],a[count,2],a[count,3],a[count,4],a[count,5],a[count,6],a[count,7],a[count,0])
   ped_list.append(t1)
   print(count)

for count1 in range(0,20000):
    a = read_next_frame()
    for count in range(0,a.shape[0]):
        indx = contains(ped_list,a[count,1])
        if indx>=0:
            ped_list[indx].add_point(a[count,2],a[count,3],a[count,4],a[count,5],a[count,6],a[count,7],a[count,0])
        if indx==-1:
            t1= Pedestrian(a[count,1],a[count,2],a[count,3],a[count,4],a[count,5],a[count,6],a[count,7],a[count,0])
            t1.updated = 1
            ped_list.append(t1)
    print (len(ped_list))
    b = 0
Esempio n. 13
0
def main_sim(threshold1, threshold2, threshold3, threshold4, threshold5,
             threshold6, threshold7):
    pygame.init()

    # Set Simulator changeable variable
    itlsMode = True  # Use ITLS mode or Normal Light
    simulatorSpeed = 1  # Simulator speed (default = 1)
    totalCarNum = 2000 / 6  # How many car generate in the sim period (2000 to 3000)
    totalPedNum = 623 / 6  # How many pedestrian generate in the sim period (623)
    totalGrandMotherNum = 12 / 6  # How many grandmother generate in the sim period
    simTimePeriod = 3600 / 6  # How long the simulation run (in sec)

    carMaxNumAtJunction = threshold1  # Max number of pedstrain wait at junction (default = 15)
    carLightGreenMinTime = threshold2  #The least Carlight Green time last (default = 10)
    carMaxWaitingtimeAtJunction = threshold3  # Switch light if a car wait more than x sec (default = 30)(Must Be > 16)

    pedMaxNumAtJunction = threshold4  # Max number of pedstrain wait at junction (default = 20)
    pedLightGreenMinTime = threshold5  # The least Carlight Green time last (default = 10)
    pedMaxWaitingtimeAtJunction = threshold6  # Switch light if a ped wait more than x sec (default = 30)

    pedLightFlashLongerTime = threshold7  # Exetend Flashing Green Time for pedLight (default = 6)

    carLightGreenMaxTime = simTimePeriod  # Car green light max time (For fixing bug only)
    pedLightGreenMaxTime = simTimePeriod  # Car green light max time (For fixing bug only)

    # No need to change (just calculation)
    carGenRate = (simTimePeriod *
                  30) / totalCarNum  # sec * frames / total carNum
    pedGenRate = (simTimePeriod *
                  30) / totalPedNum  # sec * frames / total carNum
    grandMotherGenRate = (simTimePeriod * 30) / totalGrandMotherNum

    # Set Simulator counting variable
    clock = pygame.time.Clock()
    running = True
    waitingTime = 0
    carLight = "green"
    pedLight = "red"
    frameCount = 0
    simTime = 0

    # 1400 / (3600 * 30)

    # Traffic elements
    carArray = []
    pedArray = []
    carLineArray = []
    carArray2 = []
    carArray3 = []
    carArray4 = []
    carLineArray2 = []
    carLineArray3 = []
    carLineArray4 = []

    # Count TrafficModel Time
    countCarLightTime = True  # For Carlight switch
    countPedLightTime = True  # For Pedlight switch
    countCarWaitAtJunctionTime = True  # For counting car waiting at junction
    countPedWaitAtJunctionTime = False  # For counting ped waiting at junction
    carWaitingtimeAtJunctionTimeStamp = 0
    pedWaitingtimeAtJunctionTimeStamp = 0
    carWaitingtimeAtJunction = 0
    pedWaitingtimeAtJunction = 0
    totalCarWaitingTime = 0
    totalPedWaitingTime = 0

    simStartTime = 0
    if __name__ == "__main__":

        # count real time
        simStartTime = time.time()

        # Simulation Start
        while running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT or event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    running = False
            # set simulation time period
            if int(simTime) == simTimePeriod:
                running = False

            # count Frame pass in scale
            simTime = frameCount / 30
            frameCount += 1 * simulatorSpeed
            # Draw screen
            Background.screen.fill((255, 255, 255))
            Background.screen.blit(Background.image, (0, 0))

            # Draw title
            sys_font = pygame.font.SysFont("None", 30)
            rendered = sys_font.render(
                "Traffic Model(Intelligent Traffic Light System)", 0,
                Color.black)
            Background.screen.blit(
                rendered, (Background.res_x * 0.05, Background.res_y * 0.05))
            # Draw road description(carLight, pedStart)
            sys_font = pygame.font.SysFont("None", 15)
            rendered = sys_font.render("carLight", 0, Color.black)
            Background.screen.blit(
                rendered, (Background.res_x * 0.375, Background.res_y * 0.725))
            rendered = sys_font.render("pedStart", 0, Color.black)
            Background.screen.blit(
                rendered, (Background.res_x * 0.3, Background.res_y * 0.725))
            # Draw video record area line
            pygame.draw.rect(
                Background.screen, (200, 0, 0),
                (Background.res_x * 0.498, Background.res_y * 0.48, 5, 200))
            rendered = sys_font.render("Car Record Line", 0, Color.black)
            # Draw video record area words
            sys_font = pygame.font.SysFont("None", 15)
            Background.screen.blit(
                rendered, (Background.res_x * 0.47, Background.res_y * 0.455))
            # Draw data area
            pygame.draw.rect(
                Background.screen, (180, 180, 180),
                (Background.res_x * 0.49, Background.res_y * 0.75, 450, 150))
            rendered = sys_font.render("Car Record Line", 0, Color.black)
            sys_font = pygame.font.SysFont("None", 20)
            rendered = sys_font.render("ITLS data: ", 0, Color.black)
            Background.screen.blit(
                rendered, (Background.res_x * 0.5, Background.res_y * 0.76))
            # Draw simulation time
            sys_font = pygame.font.SysFont("None", 20)
            rendered = sys_font.render(
                "Simulation time: " + str(round(simTime, 2)) + " sec.", 0,
                Color.black)
            Background.screen.blit(
                rendered, (Background.res_x * 0.05, Background.res_y * 0.15))
            # Draw simulation running speed
            rendered = sys_font.render(
                "Simulation running at " + str(simulatorSpeed) + "X speed.", 0,
                Color.black)
            Background.screen.blit(
                rendered, (Background.res_x * 0.05, Background.res_y * 0.1))
            # Car traffic light1 signal switching
            carTrafficLightSignalSwitching(carLight, Background.screen,
                                           Background.res_x, Background.res_y,
                                           Color.green, Color.yellow,
                                           Color.red)

            # ped traffic light1 signal switching
            pedTrafficLightSignalSwitching(pedLight, Background.screen,
                                           Background.res_x, Background.res_y,
                                           Color.green, Color.darkGreen,
                                           Color.black, Color.red,
                                           simStartTime, simTime)

            # Count traffic flow at junction
            carCountAtCarLight = 0
            pedCountAtPedStart = 0
            for wCar in carArray:
                if 520 > wCar.x > 370:
                    carCountAtCarLight += 1
            for ped in pedArray:
                if ped.y == Background.pedStart0YAry[
                        0] and ped.pedStartNum == 0:
                    pedCountAtPedStart += 1
                if ped.y == Background.pedStart0YAry[
                        1] and ped.pedStartNum == 1:
                    pedCountAtPedStart += 1
            sys_font = pygame.font.SysFont("None", 16)
            rendered = sys_font.render(
                "Car at carLight: " + str(carCountAtCarLight), 0, Color.black)
            Background.screen.blit(
                rendered, (Background.res_x * 0.51, Background.res_y * 0.79))
            rendered = sys_font.render(
                "Ped at pedStart: " + str(pedCountAtPedStart), 0, Color.black)
            Background.screen.blit(
                rendered, (Background.res_x * 0.51, Background.res_y * 0.81))

            # CarLight ITLS
            if itlsMode == True:
                if countCarLightTime:
                    carLightChgTime = simTime
                    countCarLightTime = False
                if countPedLightTime:
                    pedLightChgTime = simTime
                    countPedLightTime = False

                if (carCountAtCarLight > 0
                    ) and (countCarWaitAtJunctionTime == True) and (
                        carLight
                        == "red"):  # At least one car waiting at intersection
                    carWaitingtimeAtJunctionTimeStamp = simTime
                    countCarWaitAtJunctionTime = False

                if (countCarWaitAtJunctionTime == False) and (carLight
                                                              == "red"):
                    carWaitingtimeAtJunction = simTime - carWaitingtimeAtJunctionTimeStamp
                else:
                    carWaitingtimeAtJunction = 0
                if (pedCountAtPedStart >
                        0) and (countPedWaitAtJunctionTime == True) and (
                            (pedLight == "red") or
                            (pedLight == "flashingGreen")
                        ):  # At least one ped waiting at intersection
                    pedWaitingtimeAtJunctionTimeStamp = simTime
                    countPedWaitAtJunctionTime = False

                if (countPedWaitAtJunctionTime
                        == False) and (pedCountAtPedStart > 0) and (
                            (pedLight == "red") or
                            (pedLight == "flashingGreen")):
                    pedWaitingtimeAtJunction = simTime - pedWaitingtimeAtJunctionTimeStamp
                else:
                    pedWaitingtimeAtJunction = 0

                if (carLight == "green" and (
                    ((simTime - carLightChgTime >= carLightGreenMinTime) and
                     ((pedCountAtPedStart >= pedMaxNumAtJunction) or
                      (pedWaitingtimeAtJunction > pedMaxWaitingtimeAtJunction))
                     ) or (simTime - carLightChgTime >= carLightGreenMaxTime))
                    ):  # CarLight switch to red conditiion
                    carLight = "greenToYellow"
                    # print("carLight switched to yellow.")
                    # print("carLight status: " + carLight1 + ".\n")
                    countCarLightTime = True

                elif carLight == "greenToYellow" and simTime - carLightChgTime >= 3:  # Light yellow last for 3 second
                    carLight = "red"
                    pedLight = "green"
                    # print("carLight switched to red.")
                    # print("carLight status: " + carLight + ".\n")
                    countCarLightTime = True
                    countCarWaitAtJunctionTime = True
                    countPedLightTime = True

                elif (pedLight == "green" and (
                    ((simTime - pedLightChgTime >= carLightGreenMinTime) and
                     ((carCountAtCarLight >= carMaxNumAtJunction) or
                      (carWaitingtimeAtJunction > carMaxWaitingtimeAtJunction))
                     ) or (simTime - pedLightChgTime >= pedLightGreenMaxTime))
                      ):  # CarLight switch to red conditiion

                    pedLight = "flashingGreen"
                    countPedWaitAtJunctionTime = True
                    countPedLightTime = True

                elif pedLight == "flashingGreen" and simTime - pedLightChgTime > 10:
                    if pedLightIsWalking(pedArray, Background.pedStart0YAry):
                        pedLight = "flashingGreenLonger"
                    else:
                        pedLight = "red"
                        carLight = "redToYellow"
                        countCarLightTime = True

                elif pedLight == "flashingGreenLonger" and simTime - pedLightChgTime > (
                        10 + pedLightFlashLongerTime):
                    pedLight = "red"
                    carLight = "redToYellow"
                    countCarLightTime = True

                elif carLight == "redToYellow" and simTime - carLightChgTime >= 3:
                    carLight = "green"
                    # print("carLight switched to green.")
                    # print("carLight status: " + carLight + ".\n")
                    countCarLightTime = True

            # Normal Traffic Light Switching
            if itlsMode == False:

                if countCarLightTime:
                    carLightChgTime = simTime
                    countCarLightTime = False

                if carLight == "green" and simTime - carLightChgTime >= 86:  # 86
                    carLight = "greenToYellow"
                    # print("carLight1 switched to yellow.")
                    # print("carLight1 status: " + carLight1 + ".\n")
                    countCarLightTime = True

                elif carLight == "greenToYellow" and simTime - carLightChgTime >= 3:
                    carLight = "red"
                    # print("carLight1 switched to red.")
                    # print("carLight1 status: " + carLight1 + ".\n")
                    countCarLightTime = True

                elif carLight == "red" and simTime - carLightChgTime >= 39:  # 39
                    carLight = "redToYellow"
                    # print("carLight1 switched to yellow")
                    # print("carLight1 status: " + carLight1 + ".\n")
                    countCarLightTime = True

                elif carLight == "redToYellow" and simTime - carLightChgTime >= 3:
                    carLight = "green"
                    # print("carLight1 switched to green")
                    # print("carLight1 status: " + carLight1 + ".\n")
                    countCarLightTime = True

                # Ped light normal switch
                if countPedLightTime:
                    pedLightChgTime = simTime
                    countPedLightTime = False

                if pedLight == "red" and simTime - pedLightChgTime >= 92:  # 92
                    pedLight = "green"
                    # print("pedLight1 switched to green.")
                    # print("pedLight1 status: " + pedLight1 + ".\n")
                    countPedLightTime = True

                elif pedLight == "green" and simTime - pedLightChgTime >= 23:  # 23
                    pedLight = "flashingGreen"
                    # print("pedLight1 switched to red.")
                    # print("pedLight1 status: " + pedLight1 + ".\n")
                    countPedLightTime = True

                elif pedLight == "flashingGreen" and simTime - pedLightChgTime >= 10:  # 10
                    pedLight = "bufferRed"
                    # print("pedLight1 switched to yellow")
                    # print("pedLight1 status: " + pedLight1 + ".\n")
                    countPedLightTime = True

                elif pedLight == "bufferRed" and simTime - pedLightChgTime >= 6:  # 3 + 3
                    pedLight = "red"
                    # print("pedLight1 switched to yellow")
                    # print("pedLight1 status: " + pedLight1 + ".\n")
                    countPedLightTime = True

            # Put car on the road
            if random.randint(0, int(carGenRate / simulatorSpeed / 2)) == 1:
                line = random.randint(0, 3)
                if random.randint(0, 10) == 1:
                    c = Car(Background.res_x - 100, Background.yArray[line],
                            random.uniform(2, 4) * simulatorSpeed, 0, line,
                            True)  # The place that car start
                else:
                    c = Car(Background.res_x - 100, Background.yArray[line],
                            random.uniform(2, 4) * simulatorSpeed, 0, line,
                            False)  # The place that car start

                carArray.append(c)
                carLineArray.append([line, c, c.isBus])

            for c in carArray:
                if c.x > 100 and c.isBus:  # The place that car out
                    c.busStart(Background.screen, Color.darkBlue)
                elif c.x > 100 and not (c.isBus):
                    c.carStart(Background.screen, Color.darkBlue)

                if isTooCloseToCarInFront(carLineArray, c) and c.x > 150:
                    c.speed = 1.5 * simulatorSpeed
                else:
                    c.speed = random.uniform(3, 4) * simulatorSpeed

                if isCarCollided(carLineArray, c) and c.x > 150:
                    c.x -= 0
                    c.waitingTime += 1 * simulatorSpeed

                # Car postition
                else:
                    # 1st part Route movement
                    if c.x >= 588:
                        c.x -= c.speed
                    # 2nd part Route movement
                    elif 588 > c.x > 395:
                        c.x -= c.speed * 0.97  # slope of cars
                        c.y += c.speed * 0.03
                    # Check 3rd part carlight junction movement
                    elif 395 >= c.x > 360:
                        if carLight == "green":
                            if pedLightIsWalking(pedArray,
                                                 Background.pedStart0YAry):
                                c.x -= 0
                                c.waitingTime += 1 * simulatorSpeed
                            else:
                                c.x -= c.speed * 0.97
                                c.y += c.speed * 0.03
                        elif carLight == "greenToYellow" or carLight == "redToYellow":
                            if c.x >= 360:
                                c.x -= 0
                                c.waitingTime += 1 * simulatorSpeed
                            else:
                                c.x -= c.speed * 0.97
                                c.y += c.speed * 0.03
                        elif carLight == "red":
                            c.x -= 0
                            c.waitingTime += 1 * simulatorSpeed
                    # 4rd part Route movement
                    elif 360 >= c.x > 100:
                        c.x -= c.speed * 0.91
                        c.y += c.speed * 0.09

            # Put Car on the road 6th line(For demo)
            if random.randint(0,
                              int(carGenRate / simulatorSpeed / 2 * 5)) == 1:
                line2 = 1
                c2 = Car(Background.res_x - 100, Background.yArray2[1],
                         random.uniform(2, 4) * simulatorSpeed, 0, line2,
                         False)  # The place that car start
                carArray2.append(c2)
                carLineArray2.append([line2, c2])

            for c2 in carArray2:
                if c2.x > 100 and c2.y > 400:  # The place that car out
                    c2.carStartImg(Background.screen)

                if line56IsCarCollided(carLineArray2, c2) and (c2.x > 150
                                                               and c2.y > 400):
                    print("collided")
                    pygame.draw.rect(Background.screen, (200, 0, 0),
                                     (500, 400, 150, 1))
                    c2.x -= 0
                else:

                    # Car postition

                    # 1st part Route movement
                    if c2.x >= 588 and 400 <= c2.y:
                        c2.x -= c2.speed
                    # 2nd part Route movement
                    elif 588 > c2.x > 470 and 400 <= c2.y:
                        c2.x -= 4 * 0.97  # slope of cars
                        c2.y += 4 * 0.03
                    # Check 3rd part carlight junction movement
                    elif 470 >= c2.x > 465 and 400 <= c2.y:
                        if carLight == "green":
                            if pedLightIsWalking(pedArray,
                                                 Background.pedStart0YAry):
                                c2.x -= 0
                                c2.waitingTime += 1 * simulatorSpeed
                            else:
                                c2.x -= 4 * 0.97
                                c2.y += 4 * 0.03
                        elif carLight == "greenToYellow" or carLight == "redToYellow":
                            if c2.x >= 360:
                                c2.x -= 0
                                c2.waitingTime += 1 * simulatorSpeed
                            else:
                                c2.x -= 4 * 0.97
                                c2.y += 4 * 0.03
                        elif carLight == "red":
                            c2.x -= 0
                            c2.waitingTime += 1 * simulatorSpeed
                    # 4th part Route movement
                    elif 465 >= c2.x >= 440 and 400 <= c2.y:
                        pygame.draw.rect(Background.screen, (200, 0, 0),
                                         (500, 370, 150, 1))
                        c2.x -= 4 * 0.37
                        c2.y += 4 * -0.63
                    elif 470 >= c2.x >= 410 and 400 >= c2.y >= 360:
                        c2.carStartImgAndRotate(Background.screen)
                        c2.x -= 4 * 0.5
                        c2.y += 4 * -0.5
                    elif 120 <= c2.y <= 360:
                        c2.carStartImgAndRotate2(Background.screen)
                        c2.x -= 4 * -0.39
                        c2.y += 4 * -0.61

            # Put Car on the road 5th line(For demo)
            if random.randint(0, int(carGenRate / simulatorSpeed * 5)) == 1:
                line3 = 0
                c3 = Car(Background.res_x - 100, Background.yArray2[0],
                         random.uniform(2, 4) * simulatorSpeed, 0, line3,
                         False)  # The place that car start
                carArray3.append(c3)
                carLineArray3.append([line3, c3])

            for c3 in carArray3:
                if c3.x > 100 and c3.y > 415:  # The place that car out
                    c3.carStartImg(Background.screen)
                if line56IsCarCollided(carLineArray3, c3) and (c3.x > 150
                                                               and c3.y > 400):
                    print("collided")
                    pygame.draw.rect(Background.screen, (200, 0, 0),
                                     (500, 400, 150, 1))
                    c3.x -= 0

                else:

                    # Car postition

                    # 1st part Route movement
                    if c3.x >= 588 and 415 <= c3.y:
                        c3.x -= c3.speed
                    # 2nd part Route movement
                    elif 588 > c3.x > 470 and 415 <= c3.y:
                        c3.x -= 4 * 0.97  # slope of cars
                        c3.y += 4 * 0.03
                    # Check 3rd part carlight junction movement
                    elif 470 >= c3.x > 443 and 415 <= c3.y:
                        if carLight == "green":
                            if pedLightIsWalking(pedArray,
                                                 Background.pedStart0YAry):
                                c3.x -= 0
                                c3.waitingTime += 1 * simulatorSpeed
                            else:
                                c3.x -= 4.5 * 0.97
                                c3.y += 4.5 * 0.03
                        elif carLight == "greenToYellow" or carLight == "redToYellow":
                            if c3.x >= 360:
                                c3.x -= 0
                                c3.waitingTime += 1 * simulatorSpeed
                            else:
                                c3.x -= 4.5 * 0.97
                                c3.y += 4.5 * 0.03
                        elif carLight == "red":
                            c3.x -= 0
                            c3.waitingTime += 1 * simulatorSpeed
                    # 4th part Route movement
                    elif 445 >= c3.x >= 430 and 415 <= c3.y:
                        pygame.draw.rect(Background.screen, (200, 0, 0),
                                         (500, 370, 150, 1))
                        c3.x -= 4.5 * 0.34
                        c3.y += 4.5 * -0.63
                    elif 470 >= c3.x >= 350 and 415 >= c3.y >= 360:
                        c3.carStartImgAndRotate(Background.screen)
                        c3.x -= 4.5 * 0.40
                        c3.y += 4.5 * -0.65
                    elif 120 <= c3.y <= 360:
                        c3.carStartImgAndRotate2(Background.screen)
                        c3.x -= 4.5 * -0.39
                        c3.y += 4.5 * -0.61

            # Put Car on left in rd
            if random.randint(0, int(carGenRate / simulatorSpeed * 10)) == 1:
                line4 = 0
                c4 = Car(50, 453, 3 * simulatorSpeed, 0, line4,
                         False)  # The place that car start
                carArray4.append(c4)
                carLineArray4.append([line4, c4])

            for c4 in carArray4:
                if c4.x >= 50 and c4.y >= 434:  # The place that car out
                    c4.carStartImg(Background.screen)

                    c4.x += 5 * 0.93
                    c4.y -= 5 * 0.07

                elif c4.x >= 50 and 434 >= c4.y >= 370:
                    c4.carStartImgAndRotate2(Background.screen)
                    c4.x += 5 * 0.50
                    c4.y += 5 * -0.50
                elif 120 <= c4.y <= 370:
                    c4.carStartImgAndRotate2(Background.screen)
                    c4.x += 5 * 0.4
                    c4.y -= 5 * 0.6

            # Put Ped on the road (For demo)

            # Put pedestrian on the road
            if random.randint(0, int(pedGenRate / simulatorSpeed * 5)) == 1:
                line = random.randint(0, 3)
                pedStartNum = random.randint(0, 1)

                c = Pedestrian(Background.pedStart0XAry[line],
                               Background.pedStart0YAry[pedStartNum],
                               random.uniform(0.2, 0.4) * simulatorSpeed, 0,
                               line, pedStartNum)
                pedArray.append(c)
            # Put Grand mother on the road
            if random.randint(0, int(
                    grandMotherGenRate /
                    simulatorSpeed)) == 1:  # Put Grandmother on the road
                line = random.randint(0, 3)
                pedStartNum = random.randint(0, 1)

                c = Pedestrian(Background.pedStart0XAry[line],
                               Background.pedStart0YAry[pedStartNum],
                               random.uniform(0.09, 0.1) * simulatorSpeed, 0,
                               line, pedStartNum)
                pedArray.append(c)

            for p in pedArray:
                # pedStart0 to pedStart1
                if p.y >= Background.pedStart0YAry[1] and p.pedStartNum == 0:
                    p.pedStart(Background.screen, Color.lightBlue)
                    # Check Traffic light
                    if pedLight == "red" and p.y == Background.pedStart0YAry[0]:
                        p.y -= 0
                        p.waitingTime += 1 * simulatorSpeed
                    elif pedLight == "green" or p.y != Background.pedStart0YAry[
                            0]:
                        p.y -= p.speed

                # pedStart1 to pedStart0
                if p.y <= Background.pedStart0YAry[0] and p.pedStartNum == 1:
                    p.pedStart(Background.screen, Color.lightBlue)
                    # Check Traffic light
                    if pedLight == "red" and p.y == Background.pedStart0YAry[1]:
                        p.y += 0
                        p.waitingTime += 1 * simulatorSpeed
                    elif pedLight == "green" or p.y != Background.pedStart0YAry[
                            1]:
                        p.y += p.speed

            # Print pedestrian number
            for ped in pedArray:
                if ped.y == Background.pedStart0YAry[
                        0] and ped.pedStartNum == 0:
                    Background.pedStart[0] += 1
                if ped.y == Background.pedStart0YAry[
                        1] and ped.pedStartNum == 1:
                    Background.pedStart[1] += 1

            sys_font = pygame.font.SysFont("None", 16)

            rendered = sys_font.render(str(Background.pedStart[0]), 0,
                                       (35, 20, 245))
            Background.screen.blit(
                rendered, (Background.res_x * 0.335, Background.res_y * 0.71))

            rendered = sys_font.render(str(Background.pedStart[1]), 0,
                                       (35, 20, 245))
            Background.screen.blit(
                rendered, (Background.res_x * 0.335, Background.res_y * 0.546))

            rendered = sys_font.render(str(Background.pedStart[2]), 0,
                                       (35, 20, 245))
            Background.screen.blit(
                rendered, (Background.res_x * 0.34, Background.res_y * 0.505))

            Background.pedStart[0] = 0
            Background.pedStart[1] = 0

            sys_font = pygame.font.SysFont("None", 16)
            rendered = sys_font.render(
                "Pedestrain waiting time at junction counter(for ITLS switching): "
                + str(round(pedWaitingtimeAtJunction, 2)), 0, (0, 0, 0))
            Background.screen.blit(
                rendered, (Background.res_x * 0.51, Background.res_y * 0.83))

            sys_font = pygame.font.SysFont("None", 16)
            rendered = sys_font.render(
                "Car waiting time at junction counter(for ITLS switching): " +
                str(round(carWaitingtimeAtJunction, 2)), 0, (0, 0, 0))
            Background.screen.blit(
                rendered, (Background.res_x * 0.51, Background.res_y * 0.85))

            sys_font = pygame.font.SysFont("None", 16)
            rendered = sys_font.render("carlight status: " + carLight, 0,
                                       (0, 0, 0))
            Background.screen.blit(
                rendered, (Background.res_x * 0.51, Background.res_y * 0.87))

            rendered = sys_font.render("pedlight status: " + pedLight, 0,
                                       (0, 0, 0))
            Background.screen.blit(
                rendered, (Background.res_x * 0.51, Background.res_y * 0.89))

            rendered = sys_font.render(
                "pervious carlight time: " + str(carLightChgTime), 0,
                (0, 0, 0))
            Background.screen.blit(
                rendered, (Background.res_x * 0.7, Background.res_y * 0.87))

            rendered = sys_font.render(
                "pervious pedlight time: " + str(pedLightChgTime), 0,
                (0, 0, 0))
            Background.screen.blit(
                rendered, (Background.res_x * 0.7, Background.res_y * 0.89))

            # Update Game
            clock.tick(30)
            pygame.display.update()
    # Print Simulation data
    print()
    print("Simulation has run for " + str(time.time() - simStartTime) +
          " second(s) real time")

    print("Simulation has run for " + str(simTime) +
          " second(s) simulating time")
    print(str(frameCount) + " of frames has pass ")

    print("Total car number on the street: " + str(len(carArray)))
    for car in carArray:
        totalCarWaitingTime += car.waitingTime
    print("Average car watiting time: " +
          str(totalCarWaitingTime / len(carArray) / 30) + " seconds")

    print("Total pedestrian number on the street: " + str(len(pedArray)))
    for ped in pedArray:
        totalPedWaitingTime += ped.waitingTime
    print("Average pedestrian watiting time: " +
          str(totalPedWaitingTime / len(carArray) / 30) + " seconds")

    # Save data to file

    book = openpyxl.load_workbook('result.xlsx')
    sheet = book.active

    # K1 default = 1
    countSave = sheet['U1']
    countSave.value += 1

    sheet['U1'] = countSave.value
    sheet[str('A' + str(countSave.value))] = countSave.value - 1
    sheet[str('B' + str(countSave.value))] = simTime
    sheet[str('C' + str(countSave.value))] = len(carArray)
    sheet[str('D' + str(countSave.value))] = len(pedArray)
    sheet[str('E' +
              str(countSave.value))] = totalCarWaitingTime / len(carArray) / 30
    sheet[str('F' +
              str(countSave.value))] = totalPedWaitingTime / len(pedArray) / 30

    sheet[str('G' + str(countSave.value)
              )] = carMaxNumAtJunction  # Max number of car wait at junction
    sheet[str(
        'H' + str(countSave.value)
    )] = carMaxWaitingtimeAtJunction  # Switch light if a car wait more than x sec (Must Be > 16)
    sheet[str('I' + str(countSave.value)
              )] = carLightGreenMinTime  #The least Carlight Green time last

    sheet[str(
        'J' + str(countSave.value)
    )] = pedMaxNumAtJunction  # Max number of pedstrain wait at junction
    sheet[str(
        'K' + str(countSave.value)
    )] = pedMaxWaitingtimeAtJunction  # Switch light if a ped wait more than x sec
    sheet[str('L' + str(countSave.value)
              )] = pedLightGreenMinTime  #The least Carlight Green time last

    sheet[str(
        'M' + str(countSave.value)
    )] = pedLightFlashLongerTime  # Exetend Flashing Green Time for pedLight

    book.save("result2.xlsx")
Esempio n. 14
0
from city import City
from pedestrian import Pedestrian

city = City.generate_random_city(10, 10)
#city.print(True, True)
pedestrians = Pedestrian.generate_random_pedestrians(50, city)


Esempio n. 15
0
 def generate_pedestrian(self, **kwargs):
     self.pedestrians.append(Pedestrian())
     self.pedestrians[-1].set_status(**kwargs)
Esempio n. 16
0
                        else:
                            c.x -= c.speed * 0.95
                            c.y += c.speed * 0.05
                    elif carLight1 == "red":
                        c.x -= 0
                        c.waitingTime += 1
                # 4rd part Route movement
                elif 590 >= c.x > 150:
                    c.x -= c.speed * 0.9
                    c.y += c.speed * 0.1

        # Put pedestrian on the road
        if random.randint(0, 10) == 1:
            line = random.randint(0, 3)
            pedStartNum = random.randint(0, 1)
            c = Pedestrian(pedStart0XAry[line], pedStart0YAry[pedStartNum],
                           random.uniform(1, 1.5), 0, line, pedStartNum)
            pedArray.append(c)

        for p in pedArray:
            # pedStart0 to pedStart1
            if p.y >= pedStart0YAry[1] and p.pedStartNum == 0:
                p.pedStart(screen, lightBlue)
                # Check Traffic light
                if pedLight1 == "red" and p.y == pedStart0YAry[0]:
                    p.y -= 0
                    p.waitingTime += 1
                elif pedLight1 == "green" or p.y != pedStart0YAry[0]:
                    p.y -= p.speed

            # pedStart1 to pedStart0
            if p.y <= pedStart0YAry[0] and p.pedStartNum == 1:
Esempio n. 17
0
	def __init__(self):
		Pedestrian.__init__(self)
Esempio n. 18
0
from hunter import Hunter

pygame.init()
score_value = 0
font = pygame.font.Font('freesansbold.ttf', 28)


def show_score():
    score = font.render('Score : ' + str(score_value), True, (255, 0, 0))
    Screen.screen.blit(score, (10, 10))


if __name__ == '__main__':
    run = True

    ai = [Pedestrian()]
    vampire_hunter = Hunter()

    while run:

        if int(time()) % 5 == 0 and len(ai) < 3:
            ai.append(Pedestrian())

        Screen.load()

        deletion_list = []

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            elif event.type == pygame.KEYDOWN:
Esempio n. 19
0
# Connecting to the database
Database.initialise(user='******',
                    password='******',
                    host='localhost',
                    database='cph_network1')

start_time = time.time()

#with CursorFromConnectionFromPool() as cursor:
#    cursor.execute("SET search_path = current, public;")

# Initiating the transport classes
train = Train()
metro = Metro()
bus = Bus()
pedestrian = Pedestrian(1.39)  # 1.39 m/s = 5 km/h

# Importing shapefiles into the db, only run this the first time or in case of changed shapefiles
# 0 = current network, 1 = future network
import_shp_to_db.import_shp_to_db(0)

# Importing connector costs into a table in postgres, only run the first time or if the connector costs have changed
import_conn_to_db.import_conn_to_db()

# Updates all of the calculated costs
train.update_time_calc_costs(2, 2, 20)
metro.update_time_calc_costs(2, 2, 20)
bus.update_time_calc_costs()

# Applying moving costs to the objects
train.update_moving_costs()