<jupyter_start><jupyter_text>Experiment 1: base lineuse the media of traffic flow per lane of the given dataset as our target traffic flow.* auto_prob = 0* car_prob = 0.8* speed_limit = 60 MPH = 96 KMH* flow_in = 1.31 v/s = 4725 v/h* flow_in_ramp = 0.44 v/s = 1575 v/h* flow_in_total = 1.75 v/s = 6300 v/h* mile_post_dist = 0.821 mile = 1.31 kmsimulation 1 hour to see a tyical rush hour in the morning or afternoon.**Taeget:** average speed of average speed in each time step.**Result:** v = 5.25 m/s = 18.9 KMH<jupyter_code>import pandas as pd
data = pd.read_csv('../../../data/2017_MCM_Problem_C_Data.csv')
data['mile post'] = data['endMilepost'] - data['startMilepost']
data['ratio'] = data['Average daily traffic counts Year_2015'] / (data['Number of Lanes DECR MP direction '] + data['Number of Lanes INCR MP direction'])
data.head()
data.sort_values(by=['ratio'], ascending=False)
prob_auto, prob_car = 0, 0.8
flow_in = 1.31
road_length = 1310
dt = 0.5
prob_ramp = 0.25
num_lane = 3

cf = CarFactory(prob_auto, prob_car)
road = StreetRamp(num_lane, road_length, cf, prob_ramp, dt=dt)
speed_avg = []

for i in range(1, int(3600 / dt)):
    road.update(flow_in)
    speed_avg.append(np.mean([car.vel for car in road.street]))
    if i % 100 == 0:
        road.report()
#     if i % 400 == 0:
#         fig = generate_fig(road)
#         plot(fig, image='png', filename='image{:04d}.html'.format(int(i/400)), image_filename='image{:04d}'.format(int(i/400)))
mean_speed = np.mean(speed_avg)
mean_speed * 3.6<jupyter_output><empty_output><jupyter_text>Experiment 2: Relationship: Auto car ratio v.s. Average speedchange the ratio of AutoCar, and look for the average speed change* car_prob = 0.8* speed_limit = 60 MPH = 96 KMH* flow_in = 1.31 v/s = 4725 v/h* flow_in_ramp = 0.44 v/s = 1575 v/h* flow_in_total = 1.75 v/s = 6300 v/h* mile_post_dist = 0.821 mile = 1.31 km<jupyter_code>def speed_auto(auto, num_lane):
    prob_auto, prob_car = auto, 0.8
    flow_in = 1.31
    road_length = 1310
    dt = 0.5
    prob_ramp = 0.25

    cf = CarFactory(prob_auto, prob_car)
    road = StreetRamp(num_lane, road_length, cf, prob_ramp, dt=dt)
    speed_avg = []

    for i in range(1, int(500 / dt)):
        road.update(flow_in)
        speed_avg.append(np.mean([car.vel for car in road.street]))
        if i % 500 == 0:
            road.report()
#         if i % 400 == 0:
#             fig = generate_fig(road)
#             plot(fig, image='png', filename='image{:04d}.html'.format(int(i/400)), image_filename='image{:04d}'.format(int(i/400)))
    return np.mean(speed_avg)
auto_ratio = np.arange(0, 1.01, 0.1)
performance3 = []
for auto in auto_ratio:
    print("############################################")
    print("auto car ratio = {:2.2f}".format(auto))
    print("############################################")
    performance3.append(speed_auto(auto, 3))
def speed_auto_dedicate(auto, num_lane):
    prob_auto, prob_car = auto, 0.8
    flow_in = 1.31
    road_length = 1310
    dt = 0.5
    prob_ramp = 0.25

    road = StreetAuto(num_lane, road_length, prob_auto, prob_ramp, dt=dt)
    speed_avg = []

    for i in range(1, int(500 / dt)):
        road.update(flow_in)
        avg1 = np.sum([car.vel for car in road.main_road.street])
        avg2 = np.sum([car.vel for car in road.auto_road.street])
        avg = (avg1 + avg2)/(1+len(road.main_road.street) + len(road.auto_road.street))
        if i % 500 == 0:
            road.report()
#         if i % 400 == 0:
#             fig = generate_fig(road)
#             plot(fig, image='png', filename='image{:04d}.html'.format(int(i/400)), image_filename='image{:04d}'.format(int(i/400)))
    return avg
auto_ratio = np.arange(0, 1.01, 0.1)
performance3_dedicate = []
for auto in auto_ratio:
    print("############################################")
    print("auto car ratio = {:2.2f}".format(auto))
    print("############################################")
    performance3_dedicate.append(speed_auto_dedicate(auto, 3))
plt.plot(auto_ratio, performance3, label='no dedicate lanes')
plt.plot(auto_ratio, performance3_dedicate, label='with dedicate lanes')
plt.title('3 main lane + 1 on ramp')
plt.xlabel('autonomous car ratio')
plt.ylabel('average speed (m/s)')
plt.legend()
auto_ratio = np.arange(0, 1.01, 0.1)
performance2 = []
for auto in auto_ratio:
    print("############################################")
    print("auto car ratio = {:2.2f}".format(auto))
    print("############################################")
    performance2.append(speed_auto(auto, 2))
auto_ratio = np.arange(0, 1.01, 0.1)
performance2_dedicate = []
for auto in auto_ratio:
    print("############################################")
    print("auto car ratio = {:2.2f}".format(auto))
    print("############################################")
    performance2_dedicate.append(speed_auto_dedicate(auto, 2))
plt.plot(auto_ratio, performance2, label='no dedicate lanes')
plt.plot(auto_ratio, performance2_dedicate, label='with dedicate lanes')
plt.title('2 main lane + 1 on ramp')
plt.xlabel('autonomous car ratio')
plt.ylabel('average speed (m/s)')
plt.legend()
auto_ratio = np.arange(0, 1.01, 0.1)
performance4 = []
for auto in auto_ratio:
    print("############################################")
    print("auto car ratio = {:2.2f}".format(auto))
    print("############################################")
    performance4.append(speed_auto(auto, 4))
auto_ratio = np.arange(0, 1.01, 0.1)
performance4_dedicate = []
for auto in auto_ratio:
    print("############################################")
    print("auto car ratio = {:2.2f}".format(auto))
    print("############################################")
    performance4_dedicate.append(speed_auto_dedicate(auto, 4))
plt.plot(auto_ratio, performance4, label='no dedicate lanes')
plt.plot(auto_ratio, performance4_dedicate, label='with dedicate lanes')
plt.title('4 main lane + 1 on ramp')
plt.xlabel('autonomous car ratio')
plt.ylabel('average speed (m/s)')
plt.legend()
auto_ratio = np.arange(0, 1.01, 0.1)
performance5 = []
for auto in auto_ratio:
    print("############################################")
    print("auto car ratio = {:2.2f}".format(auto))
    print("############################################")
    performance5.append(speed_auto(auto, 5))
auto_ratio = np.arange(0, 1.01, 0.1)
performance5_dedicate = []
for auto in auto_ratio:
    print("############################################")
    print("auto car ratio = {:2.2f}".format(auto))
    print("############################################")
    performance5_dedicate.append(speed_auto_dedicate(auto, 5))
plt.plot(auto_ratio, performance5, label='no dedicate lanes')
plt.plot(auto_ratio, performance5_dedicate, label='with dedicate lanes')
plt.title('5 main lane + 1 on ramp')
plt.xlabel('autonomous car ratio')
plt.ylabel('average speed (m/s)')
plt.legend()<jupyter_output><empty_output><jupyter_text>Experiment 3: average speed v.s. number of lanes<jupyter_code>def speed_human_lane(lane):
    prob_auto, prob_car = 0, 0.8
    flow_in = 1.31
    road_length = 1310
    dt = 0.5
    prob_ramp = 0.25
    num_lane = lane

    cf = CarFactory(prob_auto, prob_car)
    road = StreetRamp(num_lane, road_length, cf, prob_ramp, dt=dt)
    speed_avg = []

    for i in range(1, int(500 / dt)):
        road.update(flow_in)
        speed_avg.append(np.mean([car.vel for car in road.street]))
        if i % 200 == 0:
            road.report()
    return np.mean(speed_avg)
lanes = [1,2,3,4,5,6,7,8]
performance_lane = []
for lane in lanes:
    print("############################################")
    print("auto car ratio = {:2d}".format(lane))
    print("############################################")
    performance_lane.append(speed_human_lane(lane))
plt.plot(lanes, performance_lane)
plt.title('performance v.s. number of lanes')
plt.xlabel('number of lanes')
plt.ylabel('average speed (m/s)')
plt.axhline(y=25, color='r', linestyle='--')
plt.legend()<jupyter_output><empty_output><jupyter_text>Experiment 4: Snapshot on the point of intersection (dedicate lane v.s. mixed)<jupyter_code>## no dedicate lane
prob_auto, prob_car = 0.38, 0.8
flow_in = 1.31
road_length = 1310
dt = 0.5
prob_ramp = 0.25
num_lane = 4

cf = CarFactory(prob_auto, prob_car)
road = StreetRamp(num_lane, road_length, cf, prob_ramp, dt=dt)

for i in range(1, int(250 / dt)):
    road.update(flow_in)
fig = generate_fig(road)
py.iplot(fig)
prob_auto, prob_car = 0.38, 0.8
flow_in = 1.31
road_length = 1310
dt = 0.5
prob_ramp = 0.25
num_lane = 4

road = StreetAuto(num_lane, road_length, prob_auto, prob_ramp, dt=dt)
speed_avg = []

for i in range(1, int(250 / dt)):
    road.update(flow_in)
road1 = road.main_road
road2 = road.auto_road

traces = []
for car in road1.street:
    trace = go.Scatter(x = [car.pos, car.pos+car.length],
                       y = [car.lane + 1, car.lane + 1],
                       mode = 'lines',
                       marker = dict( color = color_map['{}'.format(int(car.vel / (5.5)))]
                                       ))
    traces.append(trace)
    
for car in road2.street:
    trace = go.Scatter(x = [car.pos, car.pos+car.length],
                       y = [-car.lane + 2 + 4, -car.lane + 2 + 4],
                       mode = 'lines',
                       marker = dict( color = color_map['{}'.format(int(car.vel / (5.5)))]
                                       ))
    traces.append(trace)
    
# lane seperation
trace = go.Scatter(x = [0, road.main_road.road_length],
                   y = [4.5, 4.5],
                   mode = 'lines',
                   marker = dict( color = 'rgb(0,0,0)')
                  )
traces.append(trace)
                                    

layout = go.Layout(title='traffic simulation at time {:6.1f}s'.format(road.main_road.time),
                   xaxis=dict(title='distance (meters)'),
                   yaxis=dict(title='lane number',
                                showgrid=True,
                                zeroline=False,
                                showline=False,
                                showticklabels=True),
                   showlegend=False)
fig = go.Figure(data= traces, layout=layout)
py.iplot(fig)<jupyter_output><empty_output><jupyter_text>Experiment 5: real world analysis2030 year 25% auto car<jupyter_code>48400 * 0.04 * 2 / 3600
def speed_avg_real(busy, lane, prob_auto=0):
    flow_in = busy * lane * 0.04 / 3600
    prob_car = 0.8
    road_length = 1310
    dt = 0.5
    prob_ramp = 0.2

    cf = CarFactory(prob_auto, prob_car)
    road = StreetRamp(lane, road_length, cf, prob_ramp, dt=dt)
    speed_avg = []

    for i in range(1, int(500 / dt)):
        road.update(flow_in)
        speed_avg.append(np.mean([car.vel for car in road.street]))
        if i % 500 == 0:
            road.report()
    return np.average(speed_avg)
def speed_avg_real_df(df):
    speeds = []
    for busy, lane in zip(df['ratio'], df['Number of Lanes INCR MP direction']):
        print('+++++++++++++++++++++++++++++++++++++++')
        print('busy={}, lane={}'.format( busy, lane))
        speeds.append(speed_avg_real(busy, lane))
    return speeds
df = data.sort_values(by=['ratio'], ascending=False).iloc[:30]
speeds = speed_avg_real_df(df)
sns.distplot(speeds)
plt.title('distribution of average speed for top 30 busy zone')
plt.xlabel('average speed m/s')
plt.ylabel('density')
speeds
df = data.sort_values(by=['ratio'], ascending=False).iloc[:20]
def speed_avg_real_df_auto(df):
    speeds = []
    for busy, lane in zip(df['ratio'], df['Number of Lanes INCR MP direction']):
        print('+++++++++++++++++++++++++++++++++++++++')
        print('busy={}, lane={}'.format( busy, lane))
        speeds.append(speed_avg_real(busy, lane, prob_auto=0.25))
    return speeds
speeds = speed_avg_real_df_auto(df)
sns.distplot(speeds)
plt.title('future performance distribution for top 30 busy zone')
plt.xlabel('average speed m/s')
plt.ylabel('density')<jupyter_output><empty_output><jupyter_text>Sensitivity Anlysis<jupyter_code>road.carfatory.lane_change_human_car
def speed_auto_p_factor(auto, num_lane, p_fator):
    prob_auto, prob_car = auto, 0.8
    flow_in = 1.31
    road_length = 1310
    dt = 0.5
    prob_ramp = 0.25

    cf = CarFactory(prob_auto, prob_car)
    cf.lane_change_human_car.p *= p_fator
    cf.lane_change_human_truck.p *= p_fator
    road = StreetRamp(num_lane, road_length, cf, prob_ramp, dt=dt)
    speed_avg = []

    for i in range(1, int(500 / dt)):
        road.update(flow_in)
        speed_avg.append(np.mean([car.vel for car in road.street]))
        if i % 500 == 0:
            road.report()
    return np.mean(speed_avg)
def sensitivity_p(p_factor):
    auto_ratio = np.arange(0, 1.01, 0.1)
    performance = []
    for auto in auto_ratio:
        print("############################################")
        print("auto car ratio = {:2.2f}".format(auto))
        print("############################################")
        performance.append( speed_auto_p_factor(auto, 3, p_factor))
    return performance
speeds = [sensitivity_p(p) for p in [0.6, 0.8, 1, 1.2, 1.4]]
np.arange(0.85, 1.16, 0.05)
plt.plot(np.arange(0, 1.01, 0.1), speeds[3], 'b', label='origin')
plt.plot(np.arange(0, 1.01, 0.1), speeds[0], 'C1', label='15%')
plt.plot(np.arange(0, 1.01, 0.1), speeds[6], 'C1')
plt.plot(np.arange(0, 1.01, 0.1), speeds[1], 'C2', label='10%')
plt.plot(np.arange(0, 1.01, 0.1), speeds[5], 'C2')
plt.title('sensitivity analysis on human politeness fator')
plt.xlabel('autonomous car proportion')
plt.ylabel('average speed (m/s)')
plt.legend()
def speed_auto_a(auto, num_lane, a_factor):
    prob_auto, prob_car = auto, 0.8
    flow_in = 1.31
    road_length = 1310
    dt = 0.5
    prob_ramp = 0.25

    cf = CarFactory(prob_auto, prob_car)
    cf.car_auto_IDM.a *= a_factor
    cf.car_human_IDM.a *= a_factor
    cf.truck_auto_IDM.a *= a_factor
    cf.truck_human_IDM.a *= a_factor
    road = StreetRamp(num_lane, road_length, cf, prob_ramp, dt=dt)
    speed_avg = []

    for i in range(1, int(500 / dt)):
        road.update(flow_in)
        speed_avg.append(np.mean([car.vel for car in road.street]))
        if i % 500 == 0:
            road.report()
    return np.mean(speed_avg)
def sensitivity_a(a_factor):
    auto_ratio = np.arange(0, 1.01, 0.1)
    performance = []
    for auto in auto_ratio:
        print("############################################")
        print("auto car ratio = {:2.2f}".format(auto))
        print("############################################")
        performance.append( speed_auto_a(auto, 3, a_factor))
    return performance
a_range = [0.6, 0.8, 1, 1.2, 1.4]
speeds = [sensitivity_a(a) for a in a_range]
plt.plot(np.arange(0, 1.01, 0.1), speeds[2], 'b', label='origin')
plt.plot(np.arange(0, 1.01, 0.1), speeds[0], 'C1', label='15%')
plt.plot(np.arange(0, 1.01, 0.1), speeds[4], 'C1')
plt.plot(np.arange(0, 1.01, 0.1), speeds[1], 'C2', label='10%')
plt.plot(np.arange(0, 1.01, 0.1), speeds[3], 'C2')
plt.title('sensitivity analysis on car/truck acceleration')
plt.xlabel('autonomous car proportion')
plt.ylabel('average speed (m/s)')
plt.legend()
len(speeds)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.21105893246907864, 'fraction_numerical': 0.04259540974932204, 'mean_word_length': 3.5080500894454385, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '158533', 'license': 'MIT', 'n_tokens_mistral': 5816, 'n_tokens_neox': 5257, 'n_words': 1190, 'path': 'src/example.ipynb', 'repo_name': 'Horacehxw/traffic_simulation', 'size': '15119'}