Ejemplo n.º 1
0
def motivation_number_runs():
    # 2. Simulating with identified simulation length, getting a reasonable number of runs.
    # Using simulation_length = 1500, and discarding the first 100 items as the system takes this time to warm-up
    run_sizes = [i for i in range(0, 10)]
    graph_type = 'Highway'
    sim_time_stats = []
    for run_size in run_sizes:
        # sim_time_stats.append[]
        for i in range(run_size):
            system = run_simulation(seed=None,
                                    end_time=1500,
                                    stats_step_size=50,
                                    graph_type=graph_type,
                                    tow_truck_mode=True)
            sim_time_stats[-1].append(system.time_statistics[-1])
    key = 'Average number of incidents'
    plot = plt.figure()
    plt.ylabel(key)
    plt.xlabel('Simulation Time')
    for idx, val in enumerate(run_sizes):
        run_time = run_sizes[idx]
        for run in sim_time_stats:
            for stat_tuple in run:
                plt.plot([stat_tuple[0]], [stat_tuple[1][key]], 'o')
    plt.show()
Ejemplo n.º 2
0
def motivation_simulation_length():
    # 1. Simulating for identifying a final simulation time
    # Using number of runs = 5
    graph_type = 'Highway'  # Toy1, Toy2, Highway
    # number_of_runs = 1
    number_of_runs = 5
    end_times = [i for i in range(51, 1600, 100)]
    # end_times = [150, 300, 450]
    # print(end_times)
    sim_time_stats = [[] for i in range(len(end_times))]
    for i, ival in enumerate(end_times):
        for j in range(number_of_runs):
            system = run_simulation(simulation_id=str(ival) + '-' + str(j),
                                    seed=None,
                                    end_time=ival,
                                    stats_step_size=50,
                                    graph_type=graph_type,
                                    tow_truck_mode=True,
                                    warm_up=100)
            sim_time_stats[i].append(
                (system.time_statistics['time'], system.final_statistics))

    # keys = ['number_of_ghost_cars_at_time', 'number_of_route_cars_at_time', 'number_of_current_incidents', 'Average number of incidents']
    # keys = ['number_of_current_incidents', 'Average number of incidents']
    keys = ['average_number_of_incidents']
    #
    for key in keys:
        plot = plt.figure()
        plt.ylabel(key)
        plt.xlabel('Simulation Time')
        for idx, end_time in enumerate(end_times):
            for sim_time_stat in sim_time_stats[idx]:
                plt.plot(end_time, sim_time_stat[1][key], 'bo')
        plt.show()
Ejemplo n.º 3
0
def test_no_obs():
    robot = Robot(1, -2, utils.to_radians(-60))
    ball = Ball(0, 0, 0, 0)
    result = main.run_simulation(robot,
                                 ball, [],
                                 simulation_delay=1000,
                                 enable_detection=False,
                                 drawable_obs_avoidance=True)
    assert result
Ejemplo n.º 4
0
def test_no_obs2():
    robot = Robot(constants.x_start, constants.y_start, constants.theta_start)
    ball = Ball(constants.WINDOW_CORNERS[2] - 1,
                constants.WINDOW_CORNERS[3] - 1, 0, 0)
    result = main.run_simulation(robot,
                                 ball, [],
                                 simulation_delay=1000,
                                 enable_detection=False)
    assert result
Ejemplo n.º 5
0
def stats_of_edges_served_by_tow_trucks():
    graph_type = 'Highway'
    edge_numbers = [0 for i in range(100)]
    for i in range(run_size):
        system = run_simulation('EdgesServed-',
                                seed=100 + i,
                                end_time=1600,
                                stats_step_size=50,
                                graph_type=graph_type,
                                tow_truck_mode=True,
                                warm_up=100)
        print(system.
              final_statistics['number_of_times_edges_served_by_tow_trucks'])
        edge_numbers = list(
            map(
                sum,
                zip(
                    edge_numbers, system.final_statistics[
                        'number_of_times_edges_served_by_tow_trucks'])))
    edge_numbers = [i / run_size for i in edge_numbers]
    print(edge_numbers)
    # edge_numbers = system.final_statistics['number_of_times_edges_served_by_tow_trucks']
    # edge_numbers = [0, 1, 0, 4, 5, 5, 1, 5, 4, 9, 3, 10, 6, 2, 4, 2, 5, 2, 3, 4, 6, 5, 4, 1, 6, 9, 5, 2, 9, 3, 5, 8, 6, 2, 2, 2, 4, 4, 3, 6, 2, 5, 1, 1, 4, 1, 2, 2, 2, 3, 3, 1, 3, 5, 2, 2, 3, 9, 8, 3, 3, 3, 4, 6, 0, 6, 3, 1, 4, 7, 5, 3, 2, 1, 3, 3, 2, 5, 3, 1, 4, 3, 4, 10, 2, 6, 3, 3, 2, 4, 1, 4, 7, 3, 2, 3, 1, 3, 1, 0]
    # graph, route_path = util.build_highway_graph()
    edge_num_dict = dict()
    for key, val in enumerate(edge_numbers):
        edge_num_dict[key] = val
    sorted_edge_nums = sorted(edge_num_dict.items(),
                              key=lambda kv: (kv[1], kv[0]),
                              reverse=True)[0:15]
    print(sorted_edge_nums)
    x = []
    y = []
    for edge in sorted_edge_nums:
        edge_id = edge[0]
        source_node = system.graph.edges[edge_id].source_id
        target_node = system.graph.edges[edge_id].target_id
        x.append(util.city_names[source_node] + '-' +
                 util.city_names[target_node])
        y.append(edge[1])

    plot = plt.figure()
    plt.xlabel('Highway link')
    plt.ylabel('Numbers of times reached by tow trucks')

    # plt.plot(incidents_x, incidents_y, 'bo')
    plt.bar(x, y)
    plt.xticks(x, x, rotation='vertical')
    plt.subplots_adjust(bottom=0.40)
    # plt.margins(0.2)
    # bottom, top = plt.ylim()
    # plt.ylim(bottom=0, top=top)
    # plt.xticks(incidents_x, incidents_x)
    plt.show()
Ejemplo n.º 6
0
 def execute_plot(self):
     result = run_simulation(self.compile_profile(),
                             self.param['Generations'].get(),
                             self.param['Rounds'].get())
     self.fig.clear()
     x_axis = result.pop('gens')
     self.f = self.fig.add_subplot(111)
     for strat in result:
         self.f.plot(x_axis, result[strat], label=strat)
     self.set_graph_params()
     self.f.legend()
     self.canvas.show()
Ejemplo n.º 7
0
def test_vshyvost():
    for seed in seeds:
        print(seed)
        constants.RANDOM_SEED = seed
        ball = Ball.create_randomized()
        obstacles = main._generate_obstacles(cnt=constants.OBSTACLES_COUNT)
        robot = Robot(constants.x_start, constants.y_start,
                      constants.theta_start)
        result = main.run_simulation(robot,
                                     ball,
                                     obstacles,
                                     enable_detection=True)

        assert result
Ejemplo n.º 8
0
def sim_runs():
    seed = int(time.time())

    with open(result_file, 'w') as fo:
        fo.write('Time_Steps,4_Door,2_Door,1_Door,1_Door,1_Door,1_Door\n')

    # 313 is the y coordinate for bottom row of cells on Armstead south sidewalk,
    # given in person sized cell coordinates.
    # The range for the x coordinates is 77 - 413, inclusive
    # The x coordinate for spring south sidewalk is 76, the y range is 314 - 493, inclusive
    # The x coordinate for west peachtree south sidewalk is 414, the y range is 314 - 493, inclusive # was 323
    for pos in door_pos:
        temp_list = [[
            list(coord_list[pos[0]]),
            list(coord_list[pos[0]]),
            list(coord_list[pos[0]]),
            list(coord_list[pos[0]])
        ], [list(coord_list[pos[1]]),
            list(coord_list[pos[1]])], [list(coord_list[pos[2]])],
                     [list(coord_list[pos[3]])], [list(coord_list[pos[4]])],
                     [list(coord_list[pos[5]])]]

        door_coords = temp_list

        #setup locations for 4 door and 2 door, they will always be next to each other
        coord = 0 if door_coords[0][0][2] else 1
        for i in range(1, 4):
            door_coords[0][i][coord] = door_coords[0][i - 1][coord] + 2
            door_coords[0][i][coord ^ 1] = door_coords[0][i - 1][coord ^ 1]

        coord = 0 if door_coords[1][0][2] else 1
        door_coords[1][1][coord] = door_coords[1][0][coord] + 2
        door_coords[1][1][coord ^ 1] = door_coords[1][0][coord ^ 1]

        #print door_coords
        #for i in xrange(7):
        #    for doorlist in door_coords[1:]:
        #        coord = 0 if doorlist[0][2] else 1
        #        for door in doorlist:
        #            door[coord] += 20

        # run simulations
        result = main.run_simulation(door_coords, seed)

        with open('timestep_results.csv', 'a') as fo:
            fo.write('%d,%d,%d,%d,%d,%d,%d\n' %
                     (result, pos[0], pos[1], pos[2], pos[3], pos[4], pos[5]))
Ejemplo n.º 9
0
def test_static_obs():
    robot = Robot(constants.x_start, constants.y_start, constants.theta_start)
    ball = Ball(constants.WINDOW_CORNERS[2] - 1,
                constants.WINDOW_CORNERS[3] - 1, 0, 0)

    obstacles = [
        MovingObstacle(ball.x - 0.5, ball.y - 0.5, 0, 0)
        # MovingObstacle.create_randomized(),
    ]

    result = main.run_simulation(robot,
                                 ball,
                                 obstacles,
                                 simulation_delay=1000,
                                 enable_detection=True,
                                 drawable_obs_avoidance=True)
    assert result
Ejemplo n.º 10
0
def test_static_hist():
    # robot = Robot(constants.x_start, constants.y_start + 1, 1.75)
    robot = Robot(constants.x_start, constants.y_start, 1.75)
    ball = Ball(constants.WINDOW_CORNERS[2] - 1,
                constants.WINDOW_CORNERS[3] - 1, 0, 0)

    obstacles = [
        # MovingObstacle(constants.x_start + 0.8, constants.y_start + 1.8, 0, 0),
        MovingObstacle(constants.x_start + 0.4, constants.y_start + 0.4, 0, 0)
        # MovingObstacle.create_randomized(),
    ]

    result = main.run_simulation(robot,
                                 ball,
                                 obstacles,
                                 simulation_delay=1000,
                                 enable_detection=True,
                                 drawable_obs_avoidance=True)
    assert result
def motivation_simulation_length():
    # 1. Simulating for identifying a final simulation time
    # Using number of runs = 5
    graph_type = 'Highway'  # Toy1, Toy2, Highway
    # number_of_runs = 1
    number_of_runs = 5
    end_times = [i for i in range(100, 1600, 100)]
    # end_times = [100, 150, 200]
    # print(end_times)
    sim_time_stats = [[] for i in range(len(end_times))]
    for i, ival in enumerate(end_times):
        for j in range(number_of_runs):
            system = run_simulation(simulation_id=str(ival) + '-' + str(j),
                                    seed=20 + i + j,
                                    end_time=ival,
                                    stats_step_size=50,
                                    graph_type=graph_type,
                                    tow_truck_mode=False,
                                    warm_up=100)
            # system = run_simulation(simulation_id=str(ival) + '-' + str(j), seed=20+i+j, end_time=ival, stats_step_size=50, graph_type=graph_type, tow_truck_mode=False)
            sim_time_stats[i].append(system.final_statistics)

    # keys = ['number_of_ghost_cars_at_time', 'number_of_route_cars_at_time', 'number_of_current_incidents', 'Average number of incidents']
    # keys = ['number_of_current_incidents', 'Average number of incidents']
    keys = ['average_number_of_incidents']

    for key in keys:
        plot = plt.figure()
        plt.ylabel(key)
        plt.xlabel('Simulation Time')
        # i = 0
        for idx, end_time in enumerate(end_times):
            for sim_time_stat in sim_time_stats[idx]:
                # i+=1
                plt.plot(end_time, sim_time_stat[key], 'bo')

        print(i)
        # left, right = plt.xlim()
        # plt.xlim(100, right)
        bottom, top = plt.ylim()
        plt.ylim(0, top)
        plt.show()
Ejemplo n.º 12
0
def motivation_number_tow_trucks():
    graph_type = 'Highway'  # Toy1, Toy2, Highway
    # number_of_runs = 1
    number_of_runs = 20
    tow_truck_numbers = [i for i in range(1, 26)]
    # tow_truck_numbers = [1, 6, 11, 16]
    # end_times = [150, 300, 450]
    # print(end_times)
    sim_time_stats = [[] for i in range(len(tow_truck_numbers))]
    for i, ival in enumerate(tow_truck_numbers):
        for j in range(number_of_runs):
            system = run_simulation(simulation_id=str('tow_truck_number-') +
                                    str(ival) + '-' + str(j),
                                    seed=None,
                                    end_time=1600,
                                    stats_step_size=50,
                                    graph_type=graph_type,
                                    tow_truck_mode=True,
                                    warm_up=100,
                                    number_of_tow_trucks=ival)
            sim_time_stats[i].append(
                (str(ival) + str(j), system.final_statistics))
    # keys = ['number_of_ghost_cars_at_time', 'number_of_route_cars_at_time', 'number_of_current_incidents', 'Average number of incidents']
    # keys = ['number_of_current_incidents', 'Average number of incidents']
    keys = ['average_number_of_incidents']

    for key in keys:
        plot = plt.figure()

        # plt.ylim()
        plt.xticks([i for i in range(1, 40, 5)], [i for i in range(1, 40, 5)])
        plt.ylabel(key)
        plt.xlabel('Number of tow trucks')
        for idx, tow_truck_number in enumerate(tow_truck_numbers):
            for sim_time_stat in sim_time_stats[idx]:
                plt.plot(tow_truck_number, sim_time_stat[1][key], 'bo')
        bottom, top = plt.ylim()
        plt.xlim(0, 25)
        plt.ylim(0, top)
        plt.show()
def motivation_number_runs():
    # 2. Simulating with identified simulation length, getting a reasonable number of runs.
    # Using simulation_length = 1500, and discarding the first 100 items as the system takes this time to warm-up
    run_sizes = [i for i in range(1, 50)]
    graph_type = 'Highway'
    run_size_stats = [[] for i in range(len(run_sizes))]
    trial_per_run_size = 5
    # sim_time_stats.append[]
    # for run_size in run_sizes:
    for index, run_size in enumerate(run_sizes):
        for trial in range(trial_per_run_size):
            values = []
            for run in range(run_size):
                system = run_simulation('Run-' + str(run_size) + '-' +
                                        str(trial),
                                        seed=run_size + run + trial,
                                        end_time=1600,
                                        stats_step_size=50,
                                        graph_type=graph_type,
                                        tow_truck_mode=False,
                                        warm_up=100)
                values.append(
                    system.final_statistics['average_number_of_incidents'])
            run_size_stats[index].append(mean(values))

    key = 'average_number_of_incidents'

    plot = plt.figure()
    plt.ylabel('Average number of Incidents')
    plt.xlabel('Run Size')
    for idx, run_size in enumerate(run_sizes):
        for value in run_size_stats[idx]:
            print('Run_size', run_size)
            print(value)
            plt.plot([run_size], value, 'bo')
    plt.show()
Ejemplo n.º 14
0
import os

if "LA_EXIT_ON_COMPLETE" in os.environ:
    from main import run_simulation
    run_simulation(os.environ['LA_INFILE'], os.environ['LA_OUTFILE'])
    import sys
    sys.exit()

if "LA_IS_SIMULATION" in os.environ:
    from main import run_simulation
if os.environ["LA_WITH_GUI"] == "YES":
    try:
        from matplotlib import pyplot as plt
        from IPython import get_ipython
        get_ipython().magic("matplotlib")
    except:
        print(
            "Matplotlib imported. To run matplotlib interractively with ipython, run the command \n\n>>> %matplotlib"
        )

from mirage import lens_analysis as la
from mirage.util import *
from mirage.parameters import *
import mirage

#Import general things
from astropy import units as u
import numpy as np
import math

# A few ipython things to manipulate the environment
Ejemplo n.º 15
0
import numpy as np

import matplotlib.pyplot as plt

from main import run_simulation
from utils import get_args

if __name__ == "__main__":
    args = get_args()

    args.no_plot = True
    args.no_print = True

    errs = []
    acc_ws = np.linspace(0, 1.0, 101)
    for acc_w in acc_ws:
        args.filter_acc_weight = acc_w
        errs.append(run_simulation(args))

    title = "Error vs. Accelerometer Weight"
    plt.figure(title)
    plt.title(title)
    plt.plot(acc_ws, errs)
    plt.xlabel("Accel. Weight")
    plt.ylabel("Mean Abs. Err. (rad)")
    plt.show()
Ejemplo n.º 16
0
 def test_first_example(self):
     input_array = '12345678'
     phases = 4
     result_expected = '01029498'
     result_actual = main.run_simulation(input_array, phases)[0:8]
     self.assertEqual(result_actual, result_expected)
Ejemplo n.º 17
0
def variance_of_performance_measures_with_tow_trucks():
    # tow_truck_numbers = [5, 10, 15, 16, 20]
    tow_truck_numbers = [i for i in range(1, 26)]
    # tow_truck_numbers = [20, 30]
    run_size_int = 5

    travel_x = []
    travel_y = []
    delays_x = []
    delays_y = []
    num_delays_x = []
    num_delays_y = []
    incidents_x = []
    incidents_y = []

    for tow_truck_number in tow_truck_numbers:
        travel_times_list = []
        number_delays_list = []
        delay_times_list = []
        average_number_of_incidents = []
        for run in range(run_size_int):
            graph_type = 'Highway'
            system = run_simulation('Variance-' + str(tow_truck_number) +
                                    str('-') + str(run),
                                    seed=40 + tow_truck_number + run,
                                    end_time=1600,
                                    stats_step_size=50,
                                    graph_type=graph_type,
                                    tow_truck_mode=True,
                                    warm_up=100,
                                    number_of_tow_trucks=tow_truck_number)
            travel_times_list.append(
                mean(system.final_statistics['route_travel_times']))
            delay_times_list.append(
                mean(system.final_statistics['route_delay_times']))
            number_delays_list.append(
                mean(system.final_statistics['route_number_delays']))
            average_number_of_incidents.append(
                system.final_statistics['average_number_of_incidents'])
        travel_y += travel_times_list
        travel_x += [tow_truck_number for i in range(run_size_int)]
        delays_y += delay_times_list
        delays_x += [tow_truck_number for i in range(run_size_int)]
        num_delays_y += number_delays_list
        num_delays_x += [tow_truck_number for i in range(run_size_int)]
        incidents_y += average_number_of_incidents
        incidents_x += [tow_truck_number for i in range(run_size_int)]

    print('Average travel times -', travel_y)
    print('Average delay times -', delays_y)
    print('Number of delays -', num_delays_y)
    print('Average number of incidents -', incidents_y)
    print('Tow truck numbers -', incidents_x)

    plot = plt.figure()
    plt.xlabel('Number of tow trucks')
    plt.ylabel('Average route travel time')
    plt.plot(travel_x, travel_y, 'bo')
    # bottom, top = plt.ylim()
    # plt.ylim(bottom=0, top=top)
    plt.xticks(incidents_x, incidents_x)
    plt.show()

    plot = plt.figure()
    plt.xlabel('Number of tow trucks')
    plt.ylabel('Average delay time')
    plt.plot(delays_x, delays_y, 'bo')
    # bottom, top = plt.ylim()
    # plt.ylim(bottom=0, top=top)
    plt.xticks(incidents_x, incidents_x)
    plt.show()

    plot = plt.figure()
    plt.xlabel('Number of tow trucks')
    plt.ylabel('Average number of delays')
    plt.plot(num_delays_x, num_delays_y, 'bo')
    bottom, top = plt.ylim()
    plt.ylim(bottom=0, top=top)
    plt.xticks(incidents_x, incidents_x)
    plt.show()

    plot = plt.figure()
    plt.xlabel('Number of tow trucks')
    plt.ylabel('Numbers of incidents (With tow trucks)')
    plt.plot(incidents_x, incidents_y, 'bo')
    bottom, top = plt.ylim()
    plt.ylim(bottom=0, top=top)
    plt.xticks(incidents_x, incidents_x)
    plt.show()
Ejemplo n.º 18
0
 def test_fourth_example(self):
     input_array = '69317163492948606335995924319873'
     phases = 100
     result_expected = '52432133'
     result_actual = main.run_simulation(input_array, phases)[0:8]
     self.assertEqual(result_actual, result_expected)
Ejemplo n.º 19
0
 def test_third_example(self):
     input_array = '19617804207202209144916044189917'
     phases = 100
     result_expected = '73745418'
     result_actual = main.run_simulation(input_array, phases)[0:8]
     self.assertEqual(result_actual, result_expected)
Ejemplo n.º 20
0
from main import run_simulation

color_map = ['g', 'y', 'r', 'b', 'm', 'k']
# green not infected
# yellow newly_infected
# red - infected
# blue  recovered
# purple immune
plt.figure(figsize=(10, 10))
# number of nodes
# generate graph

# return animation_bc_sir, ba, len(animation_bc_sir)
color_rules, G, size = run_simulation(
    'rc',
    0,
    0,
    0.1,
)

# generating input frames here, since my data is too big
# its important that the frames go as input and is not generated
# on the fly
colors = list()
count = 0
for x in range(size):
    frame_colors = list()
    length = len(color_rules[x])
    for i in range(length):
        node_color = color_map[color_rules[x][i]]
        node_color = color.to_hex(node_color)
        frame_colors.append(node_color)
Ejemplo n.º 21
0
import main
from system import System

DISPLAY = False

SYSTEM = System(DISPLAY)

for i in range(2):
    main.run_simulation(SYSTEM=SYSTEM, DISPLAY=DISPLAY)
def perf_measure_3():

    # For incidents: distribution of the number of incidents in the whole network, at any
    # arbitrary epoch. This is similar to the previous question, but now for the fraction of time
    # that exactly k incidents are taking place simultaneously in the network

    graph_type = 'Highway'
    system = run_simulation('Measure-3-vis',
                            seed=40,
                            end_time=1600,
                            stats_step_size=50,
                            graph_type=graph_type,
                            tow_truck_mode=False,
                            warm_up=100)
    times_fraction_per_number_of_incidents = system.final_statistics[
        'time_spent_per_current_number_of_incidents']
    # rounded_times = [round(i) for i in times_fraction_per_number_of_incidents]
    # print(rounded_times)
    # counts_number_delays = Counter(number_delays_list)
    # list_of_number_delays = []
    # for i in range(max(number_delays_list) + 1):
    #     list_of_number_delays.append(counts_number_delays[i])
    print('Counts of time spent per number of incidents',
          times_fraction_per_number_of_incidents)
    print('len', len(times_fraction_per_number_of_incidents))
    min_non_zero_incidents = 0
    max_non_zero_incidents = len(times_fraction_per_number_of_incidents)
    i = 0
    while i < len(times_fraction_per_number_of_incidents
                  ) and times_fraction_per_number_of_incidents[i] == 0:
        min_non_zero_incidents += 1
        i += 1
    i = len(times_fraction_per_number_of_incidents) - 1
    while i > 0 and times_fraction_per_number_of_incidents[i] == 0:
        max_non_zero_incidents -= 1
        i -= 1
    print('max_non_zero_incidents', max_non_zero_incidents)
    print('min_non_zero_incidents', min_non_zero_incidents)

    plot = plt.figure()
    plt.xlabel('Numbers of incidents')
    plt.ylabel('Fraction of time spent')
    plt.xlim(min_non_zero_incidents - 1, max_non_zero_incidents)
    plt.bar([i for i in range(len(times_fraction_per_number_of_incidents))], [
        j / sum(times_fraction_per_number_of_incidents)
        for j in times_fraction_per_number_of_incidents
    ])
    plt.show()

    average_number_of_incidents = []
    # CI calculation
    for i in range(run_size):
        system = run_simulation('Measure-3' + str(i),
                                seed=i,
                                end_time=1600,
                                stats_step_size=50,
                                graph_type=graph_type,
                                tow_truck_mode=False,
                                warm_up=100)
        print('Run -', i)
        average_number_of_incidents.append(
            system.final_statistics['average_number_of_incidents'])

    mean_number_of_incidents = sum(average_number_of_incidents) / len(
        average_number_of_incidents)
    std_number_of_incidents = std(average_number_of_incidents)
    print('Mean of Number of Incidents -', mean_number_of_incidents)
    print('Standard Deviation of Number of Incidents -',
          std_number_of_incidents)
    halfwidth_number_of_incidents = ci(std_number_of_incidents, run_size)
    print('Halfwidth of Number of Incidents -', halfwidth_number_of_incidents)
    print('Range - ', mean_number_of_incidents - halfwidth_number_of_incidents,
          mean_number_of_incidents + halfwidth_number_of_incidents)
def perf_measure_2():

    # 2. For the network: distribution of the number of delayed vehicles at any arbitrary epoch.
    # Formulated differently, we would like to see a table where you simulate for k = 0; 1; 2; : : :
    # the fraction of time that exactly k vehicles are being delayed (consider it as being stuck
    # in a traffic jam).
    # Note that, in order to determine the second performance measure (number of
    # delayed vehicles in the network), it actually matters how many vehicles are driving in the
    # whole network. So now you need to add random vehicles in the network that drive between
    # the highway junctions. This part does not have to be implemented very realistically. You
    # may even assume that vehicles enter the network randomly at each of the nodes, travel one
    # link, and then leave the network again. For these vehicles, no origin-destination routing is
    # required. Only vehicles travelling from A to B have a fixed route. Our advice is to keep
    # it simple: do not introduce too many model parameters, like number of vehicles per hour
    # travelling on each link. You are allowed to assume that this rate is equal for all links.

    graph_type = 'Highway'
    system = run_simulation('Measure-2-vis',
                            seed=40,
                            end_time=1600,
                            stats_step_size=50,
                            graph_type=graph_type,
                            tow_truck_mode=False,
                            warm_up=100)
    times_delayed_per_number_of_cars = system.final_statistics[
        'time_spent_delayed_per_current_number_of_all_cars']
    # print('Time spent per number of delayed cars', times_delayed_per_number_of_cars)
    print('len', len(times_delayed_per_number_of_cars))

    data = [(i, times_delayed_per_number_of_cars[i])
            for i in range(len(times_delayed_per_number_of_cars))]
    x, y, bin_width = group_into_bins(data)
    print('x', x)
    print('y', y)
    print('len(y)', len(y))
    min_non_zero_delayed_cars = 0
    max_non_zero_delayed_cars = len(y) - 1
    # comparison = 0
    i = 0
    while i < len(y) and y[i] == 0:
        min_non_zero_delayed_cars += 1
        i += 1
        # i = x[i+1]
    i = len(y) - 1
    while i > 0 and y[i] == 0:
        max_non_zero_delayed_cars -= 1
        i -= 1
    print('max_non_zero_delayed_cars', max_non_zero_delayed_cars)
    print('min_non_zero_delayed_cars', min_non_zero_delayed_cars)

    plt.xlabel('Numbers of delayed cars (with Tow Trucks)')
    plt.ylabel('Fraction of time spent')
    plt.xlim(x[min_non_zero_delayed_cars] - 1, x[max_non_zero_delayed_cars])
    plt.bar(x, [j / sum(y) for j in y], width=bin_width * 0.8)
    plt.show()

    average_number_of_delayed_cars = []
    # CI calculation
    for i in range(run_size):
        system = run_simulation('Measure-2' + str(i),
                                seed=i,
                                end_time=1600,
                                stats_step_size=50,
                                graph_type=graph_type,
                                tow_truck_mode=False,
                                warm_up=100)
        print('Run -', i)
        average_number_of_delayed_cars.append(
            system.final_statistics['average_time_of_delay_of_all_cars'])

    mean_number_of_delayed_cars = sum(average_number_of_delayed_cars) / len(
        average_number_of_delayed_cars)
    std_number_of_delayed_cars = std(average_number_of_delayed_cars)
    print('Mean of Delayed Cars -', mean_number_of_delayed_cars)
    print('Standard Deviation of Delayed Cars -', std_number_of_delayed_cars)
    halfwidth_number_of_delayed_cars = ci(std_number_of_delayed_cars, run_size)
    print('Halfwidth of Delayed Cars -', halfwidth_number_of_delayed_cars)
    print('Range - ',
          mean_number_of_delayed_cars - halfwidth_number_of_delayed_cars,
          mean_number_of_delayed_cars + halfwidth_number_of_delayed_cars)
Ejemplo n.º 24
0
def test_run_simulation_for_t0_gives_t4():
    assert run_simulation(t0, True, 4) == t4
Ejemplo n.º 25
0
    def prev_timestep(self):
        t_prev = int(self.TimeLabel.text()[2:]) - 1
        t_prev = t_prev if t_prev > 0 else 0
        state = self.reader.get_specific_timestep(t_prev - 1)
        self._show(state)
        state = self.reader.get_next_timestep()
        self._show(state)

    def stop(self):
        self.stop_autoplay = True

    def auto_play(self):
        self.stop_autoplay = False
        self.reader.reset()
        for state in self.reader:
            self._show(state)
            sleep(0.5)
            if self.stop_autoplay:
                break


if __name__ == "__main__":
    import sys
    run_simulation()
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
Ejemplo n.º 26
0
 def test_second_example(self):
     input_array = '80871224585914546619083218645595'
     phases = 100
     result_expected = '24176176'
     result_actual = main.run_simulation(input_array, phases)[0:8]
     self.assertEqual(result_actual, result_expected)
def perf_measure_1():
    # 1. For individual vehicles: distribution of the travel time (mean, standard deviation, plot
    # a histogram). Indicate which part of the travel time is caused by the delay. Present
    # results on the number of incidents they encounter on average (again: mean, standard
    # deviation, distribution).

    # Travel time on the route between A to B
    # Probability of minutes of time taken for the travel along the route. Ghost cars not necessary, or included.
    graph_type = 'Highway'
    system = run_simulation('Measure-1',
                            seed=30,
                            end_time=1600,
                            stats_step_size=50,
                            graph_type=graph_type,
                            tow_truck_mode=False,
                            warm_up=100)
    travel_times_list = system.final_statistics['route_travel_times']
    delay_times_list = system.final_statistics['route_delay_times']
    number_delays_list = system.final_statistics['route_number_delays']
    print('Travel Times List for Route Cars')
    print(travel_times_list)
    print(len(travel_times_list))

    # Graph 1
    rounded_travel_times_list = [round(i) for i in travel_times_list]
    max_travel_time = max(rounded_travel_times_list)
    counts_travel_times = Counter(rounded_travel_times_list)
    list_of_times = []
    print('Rounded Travel Times List', rounded_travel_times_list)
    for i in range(int(max_travel_time) + 1):
        list_of_times.append(counts_travel_times[i])
    print(list_of_times)  # Must be X-axis
    print('Count of travel times -', list_of_times)
    plot = plt.figure()
    plt.ylabel('Probability')
    plt.xlabel('Total Travel Time')
    plt.xlim(50, max_travel_time)
    plt.plot([i for i in range(len(list_of_times))],
             [j / sum(list_of_times) for j in list_of_times])
    plt.show()

    # Graph 2
    rounded_delay_times_list = [round(i) for i in delay_times_list]
    max_delay_time = max(rounded_delay_times_list)
    counts_delay_times = Counter(rounded_delay_times_list)
    list_of_delay_times = []
    print('Rounded Delay Times List', rounded_delay_times_list)
    for i in range(1, int(max_delay_time) + 1):
        list_of_delay_times.append(counts_delay_times[i])
    print(list_of_delay_times)  # Must be X-axis
    print('Count of delay times -', list_of_delay_times)
    plot = plt.figure()
    plt.ylabel('Probability')
    plt.xlabel('Total Delay Time')
    plt.xlim(1, max_delay_time)
    plt.plot([i for i in range(len(list_of_delay_times))],
             [j / sum(list_of_delay_times) for j in list_of_delay_times])
    plt.show()

    # Graph 3
    # Showing the distribution of the number of incidents in a single route travel
    print(number_delays_list)
    counts_number_delays = Counter(number_delays_list)
    list_of_number_delays = []
    for i in range(max(number_delays_list) + 1):
        list_of_number_delays.append(counts_number_delays[i])
    print('Counts of number of delays', list_of_number_delays)
    plot = plt.figure()
    plt.xlabel('Numbers of incidents')
    plt.ylabel('Probability')
    # plt.xlim(1, max_delay_time)
    plt.bar([i for i in range(len(list_of_number_delays))],
            [j / sum(list_of_number_delays) for j in list_of_number_delays])
    plt.show()

    # CI calculation
    travel_times_list = []
    delay_times_list = []
    number_delays_list = []
    for i in range(run_size):
        system = run_simulation('Measure-1',
                                seed=None,
                                end_time=1600,
                                stats_step_size=50,
                                graph_type=graph_type,
                                tow_truck_mode=False,
                                warm_up=100)
        travel_times_list += system.final_statistics['route_travel_times']
        delay_times_list += system.final_statistics['route_delay_times']
        number_delays_list += system.final_statistics['route_number_delays']
    print('\n')
    print('Number of Route Travel Times - ', len(travel_times_list))
    mean_route_travel_time = sum(travel_times_list) / len(travel_times_list)
    std_route_travel_time = std(travel_times_list)
    print('Mean of Route Travel Time -', mean_route_travel_time)
    print('Standard Deviation of Route Travel Time -', std_route_travel_time)
    halfwidth_route_travel_time = ci(std_route_travel_time, run_size)
    print('Halfwidth of Route Travel Time -', halfwidth_route_travel_time)
    print('Range - ', mean_route_travel_time - halfwidth_route_travel_time,
          mean_route_travel_time + halfwidth_route_travel_time)
    # Also do CI calculation
    print('\n')
    print('Number of Delay Travel Times - ', len(delay_times_list))
    mean_delay_time = sum(delay_times_list) / len(delay_times_list)
    std_delay_time = std(delay_times_list)
    print('Mean of Delay Travel Time -', mean_delay_time)
    print('Standard Deviation of Delay Travel Time -', std_delay_time)
    halfwidth_delay_time = ci(std_delay_time, run_size)
    print('Halfwidth of Delay Travel Time -', halfwidth_delay_time)
    print('Range - ', mean_delay_time - halfwidth_delay_time,
          mean_delay_time + halfwidth_delay_time)
    print('\n')
    print('Number of Delays - ', len(number_delays_list))
    mean_delay_number = sum(number_delays_list) / len(number_delays_list)
    std_delay_number = std(number_delays_list)
    print('Mean of Delay Travel Time -', mean_delay_number)
    print('Standard Deviation of Delay Travel Time -', std_delay_number)
    halfwidth_delay_number = ci(std_delay_number, run_size)
    print('Halfwidth of Delay Travel Time -', halfwidth_delay_number)
    print('Range - ', mean_delay_number - halfwidth_delay_number,
          mean_delay_number + halfwidth_delay_number)
Ejemplo n.º 28
0
import main

print("Starting test 0!")

main.run_simulation('test0_FAST.json')

main.run_simulation('test0_RENO.json')

print("Starting test1!")

main.run_simulation('test1_FAST.json')

main.run_simulation('test1_RENO.json')

print("Starting test2!")

main.run_simulation('test2_FAST.json')

main.run_simulation('test2_RENO.json')

print("Starting test3!")

main.run_simulation('test3.json')

print("Starting test4!")

main.run_simulation('test4.json')

print("Starting test5!")

main.run_simulation('test5_FAST.json')