Exemple #1
0
def cracked_concrete_plot(c: Config):
    response_types = [ResponseType.YTranslation, ResponseType.Strain]
    sensor_point = Point(x=51.8, y=0, z=-8.4)
    # Generate traffic data.
    total_mins = 2
    total_seconds = total_mins * 60
    traffic_scenario = normal_traffic(c=c, lam=5, min_d=2)
    traffic_sequence, traffic, traffic_array = load_traffic(
        c=c,
        traffic_scenario=traffic_scenario,
        max_time=total_seconds,
    )
    # Split the traffic array in half, the crack will happen halfway through.
    half_i = int(len(traffic_array) / 2)
    traffic_array_0, traffic_array_1 = traffic_array[:half_i], traffic_array[
        half_i:]
    assert len(traffic_array_0) + len(traffic_array_1) == len(traffic_array)
    # Collect fem due to traffic.
    responses = []
    for rt in response_types:
        responses_healthy_cracked = []
        for ds, ta in [
            (healthy_damage, traffic_array_0),
            (transverse_crack(), traffic_array_1),
        ]:
            print(
                f"Sections in damage scenario = {len(ds.use(c)[0].bridge.sections)}"
            )
            responses_healthy_cracked.append(
                responses_to_traffic_array(
                    c=c,
                    traffic_array=ta,
                    response_type=rt,
                    damage_scenario=ds,
                    points=[sensor_point],
                ).T[0])  # Responses from a single point.
        responses.append(np.concatenate(responses_healthy_cracked))
    responses = np.array(responses)
    # Plot the cracked time series.
    x0 = np.arange(half_i) * c.sensor_hz / 60
    x1 = np.arange(half_i, len(responses[0])) * c.sensor_hz / 60
    plt.landscape()
    plt.subplot(2, 1, 1)
    plt.plot(x0, responses[0][:half_i] * 1000, label="Healthy")
    plt.plot(x1, responses[0][half_i:] * 1000, label="Cracked")
    plt.legend()
    plt.ylabel("Y translation (mm)")
    plt.xlabel("Time (minutes)")
    # plt.plot(np.arange(half_i, len(fem[0])), fem[0][half_i:])
    plt.subplot(2, 1, 2)
    plt.plot(x0, responses[1][:half_i], label="Healthy")
    plt.plot(x1, responses[1][half_i:], label="Cracked")
    plt.legend()
    plt.ylabel("Microstrain")
    plt.xlabel("Time (minutes)")
    # plt.plot(np.arange(half_i, len(fem[1])), fem[1][half_i:])
    plt.savefig(c.get_image_path("verify/cracked", "crack-time-series.pdf"))
Exemple #2
0
 def legend():
     plt.legend(
         loc="upper right",
         borderpad=0.2,
         labelspacing=0.2,
         borderaxespad=0,
         handletextpad=0.2,
         columnspacing=0.2,
     )
Exemple #3
0
def plot_qs(Q, mu, strats):
    spec = GridSpec(4, 1)
    fig = plt.figure(figsize=(12, 12))
    for i in range(4):
        fig.add_subplot(spec[i])
        for s, strat in enumerate(strats):
            q = Q[s, :, :, 1, i] / Q[s, :, :, 0, i]
            q[Q[s, :, :, 0, i] == 0] = 0
            plt.plot(q.mean(axis=0), label=strat.__name__, c=colors[s])
        plt.axhline(mu[i], ls='--')
        plt.ylabel("Estimated value of\nAction {}".format(i))
        plt.legend(framealpha=0.5, fontsize=10)
Exemple #4
0
def compare_load_positions(c: Config):
    """Compare load positions (normal vs. buckets)."""
    c.il_num_loads = 10
    num_times = 1000

    # Wagen 1 from the experimental campaign.
    point = Point(x=c.bridge.x_max / 2, y=0, z=-8.4)
    end_time = uni_axle_vehicle.time_left_bridge(bridge=c.bridge)
    vehicle_times = list(np.linspace(0, end_time, num_times))
    plt.portrait()

    pw_loads = [
        flatten(uni_axle_vehicle.to_point_load_pw(time=time, bridge=c.bridge),
                PointLoad) for time in vehicle_times
    ]
    pw_load_xs = [[c.bridge.x(l.x_frac) for l in pw_loads[time_ind]]
                  for time_ind in range(len(pw_loads))]
    plt.subplot(3, 1, 1)
    # for l in pw_load_xs:
    #     print(l)
    plt.plot([l[0] for l in pw_load_xs])
    plt.plot([l[1] for l in pw_load_xs])

    wt_loads = [
        flatten(uni_axle_vehicle.to_wheel_track_loads(c=c, time=time),
                PointLoad) for time in vehicle_times
    ]
    wt_load_xs = [[c.bridge.x(l.x_frac) for l in wt_loads[time_ind]]
                  for time_ind in range(len(wt_loads))]
    plt.subplot(3, 1, 2)
    plt.scatter(vehicle_times, [l[0] for l in wt_load_xs], label="0")
    plt.scatter(vehicle_times, [l[1] for l in wt_load_xs], label="1")
    plt.legend()

    wt_load_kn = [[l.kn for l in wt_loads[time_ind]]
                  for time_ind in range(len(wt_loads))]
    plt.subplot(3, 1, 3)
    for l in wt_load_kn:
        print(l)
    plt.scatter(vehicle_times, [l[0] for l in wt_load_kn], label="0")
    plt.scatter(vehicle_times, [l[1] for l in wt_load_kn], label="1")
    plt.legend()

    plt.tight_layout()
    plt.savefig(c.get_image_path("verification", "compare-load-positions.pdf"))
    plt.close()
Exemple #5
0
def multiplot(A, R, strats):
    nA = int(A.max() + 1)
    spec = GridSpec(nA + 1,
                    2,
                    width_ratios=[4, 1],
                    height_ratios=[3] + [1] * nA)
    fig = plt.figure(figsize=(12, 12))

    ax = fig.add_subplot(spec[0])
    for s, strat in enumerate(strats):
        plt.plot(R[s].mean(axis=0),
                 label=strat.__name__,
                 alpha=.4,
                 c=colors[s])
    ax.set_xlabel("Epoch")
    plt.ylabel("Average reward")
    plt.title("Average reward over {} runs".format(len(A[0])))
    plt.legend(loc="lower right", fontsize=(10))

    axx = ax
    for i in range(nA):
        axx = fig.add_subplot(spec[2 + 2 * i], sharex=axx)
        for s, strat in enumerate(strats):
            plt.plot(100 * (A[s, :, :] == i).mean(axis=0),
                     c=colors[s],
                     alpha=.4)
        plt.ylabel('% Act. {}'.format(i))

    fig.add_subplot(spec[1], sharey=ax)
    bp = plt.boxplot(R.mean(axis=2).T)
    for box, color in zip(bp['boxes'], colors):
        box.set_color(color)
    plt.xticks([])
    plt.title("Average\nreward")

    fig.add_subplot(spec[1:-1, -1], sharey=ax)
    bp = plt.boxplot(R[:, :, -100:].mean(axis=2).T,
                     labels=[x.__name__ for x in strats])
    for box, color in zip(bp['boxes'], colors):
        box.set_color(color)
    plt.xticks(rotation='vertical', fontsize=(10))
    plt.title("Last 100 epochs")
Exemple #6
0
    colors = "rgbky"

    for si, sigma in enumerate([SIGMA1, SIGMA2, SIGMA3]):
        t0 = time()
        Q, R, A = multistrat(mu=MU,
                             sigma=sigma,
                             strategies=strats,
                             epochs=5000)

        fig = plt.figure(figsize=(12, 5))

        ax = fig.add_subplot(spec[0])
        for i, s in enumerate(strats):
            plt.plot(R[i].mean(axis=0),
                     label=s.__name__,
                     alpha=0.5,
                     c=colors[i])
        plt.legend(fontsize=10, loc="lower right")
        plt.title("Average reward over {} runs".format(len(R[0])))

        fig.add_subplot(spec[1], sharey=ax)
        bp = plt.boxplot(R.mean(axis=2).T, labels=[s.__name__ for s in strats])
        for box, color in zip(bp['boxes'], colors):
            box.set_color(color)
        plt.xticks([])
        plt.ylim(3)

        name = "Ex_2_sigma{}".format(si + 1)
        print name, time() - t0, "s"
        show(name)
Exemple #7
0
def top_view_plot(c: Config, max_time: int, skip: int, damage_scenario):
    response_type = ResponseType.YTranslation
    # Create the traffic.
    traffic_scenario = normal_traffic(c=c, lam=5, min_d=2)
    traffic_sequence, traffic, traffic_array = load_traffic(
        c=c,
        traffic_scenario=traffic_scenario,
        max_time=max_time,
    )
    assert len(traffic) == traffic_array.shape[0]
    # Points on the deck to collect fem.
    deck_points = [
        Point(x=x, y=0, z=z) for x in np.linspace(
            c.bridge.x_min, c.bridge.x_max, num=int(c.bridge.length * 2))
        for z in np.linspace(
            c.bridge.z_min, c.bridge.z_max, num=int(c.bridge.width * 2))
        # for x in np.linspace(c.bridge.x_min, c.bridge.x_max, num=30)
        # for z in np.linspace(c.bridge.z_min, c.bridge.z_max, num=10)
    ]
    point = Point(x=21, y=0, z=-8.4)  # Point to plot
    deck_points.append(point)
    # Traffic array to fem array.
    responses_array = responses_to_traffic_array(
        c=c,
        traffic_array=traffic_array,
        damage_scenario=damage_scenario,
        points=deck_points,
        response_type=response_type,
    )
    # Temperature effect July 1st.
    temps_2019 = temperature.load("holly-springs")
    temps_2019["temp"] = temperature.resize(temps_2019["temp"])
    effect_2019 = temperature.effect(
        c=c,
        response_type=response_type,
        points=deck_points,
        temps=temps_2019["temp"],
        solar=temps_2019["solar"],
        len_per_hour=60,
    ).T
    # The effect is ordered by time series and then by points. (104910, 301)
    assert len(effect_2019) == len(temps_2019)
    july_2019_i, july_2019_j = temperature.from_to_indices(
        temps_2019,
        datetime.fromisoformat(f"2019-10-01T00:00"),
        datetime.fromisoformat(f"2019-10-01T23:59"),
    )
    temp_effect = []
    for i in range(len(deck_points)):
        temp_effect.append(
            temperature.apply(
                # Effect for July 1st, for the current point..
                effect=effect_2019.T[i][july_2019_i:july_2019_j],
                # ..for the length of the time series.
                responses=responses_array,
            ))
    temp_effect = np.array(temp_effect)
    plt.subplot(2, 1, 1)
    plt.plot(effect_2019.T[-1])
    plt.subplot(2, 1, 2)
    plt.plot(temp_effect[-1])
    plt.show()
    # Determine response due to pier settlement.
    pd_response_at_point = 0
    if isinstance(damage_scenario, PierDispDamage):
        pd_expt = list(
            DCMatrix.load(c=c,
                          response_type=response_type,
                          fem_runner=OSRunner(c)))
        for pier_displacement in damage_scenario.pier_disps:
            pd_sim_responses = pd_expt[pier_displacement.pier]
            pd_response_at_point += pd_sim_responses.at_deck(
                point, interp=False) * (pier_displacement.displacement /
                                        c.pd_unit_disp)
    # Resize fem if applicable to response type.
    resize_f, units = resize_units(response_type.units())
    if resize_f is not None:
        responses_array = resize_f(responses_array)
        temp_effect = resize_f(temp_effect.T).T
        print(np.mean(temp_effect[-1]))
        pd_response_at_point = resize_f(pd_response_at_point)
    responses_w_temp = responses_array + temp_effect.T
    # Determine levels of the colourbar.
    amin, amax = np.amin(responses_array), np.amax(responses_array)
    # amin, amax = min(amin, -amax), max(-amin, amax)
    levels = np.linspace(amin, amax, 25)
    # All vehicles, for colour reference.
    all_vehicles = flatten(traffic, Vehicle)
    # Iterate through each time index and plot results.
    warmed_up_at = traffic_sequence[0][0].time_left_bridge(c.bridge)
    # Plot for each time step.
    for t_ind in range(len(responses_array))[::skip]:
        plt.landscape()
        # Plot the bridge top view.
        plt.subplot2grid((3, 1), (0, 0), rowspan=2)
        top_view_bridge(c.bridge, compass=False, lane_fill=False, piers=True)
        top_view_vehicles(
            bridge=c.bridge,
            mv_vehicles=flatten(traffic[t_ind], Vehicle),
            time=warmed_up_at + t_ind * c.sensor_hz,
            all_vehicles=all_vehicles,
        )
        responses = Responses(
            response_type=response_type,
            responses=[(responses_array[t_ind][p_ind], deck_points[p_ind])
                       for p_ind in range(len(deck_points))],
            units=units,
        )
        plot_contour_deck(c=c,
                          responses=responses,
                          levels=levels,
                          mm_legend=False)
        plt.scatter(
            [point.x],
            [point.z],
            label=f"Sensor in bottom plot",
            marker="o",
            color="red",
            zorder=10,
        )
        plt.legend(loc="upper right")
        plt.title(
            f"{response_type.name()} after {np.around(t_ind * c.sensor_hz, 4)} seconds"
        )
        # Plot the fem at a point.
        plt.subplot2grid((3, 1), (2, 0))
        time = t_ind * c.sensor_hz
        plt.axvline(x=time,
                    color="black",
                    label=f"Current time = {np.around(time, 4)} s")
        plt.plot(
            np.arange(len(responses_array)) * c.sensor_hz,
            responses_w_temp.T[-1],
            color="red",
            label="Total effect",
        )
        if isinstance(damage_scenario, PierDispDamage):
            plt.plot(
                np.arange(len(responses_array)) * c.sensor_hz,
                np.ones(temp_effect[-1].shape) * pd_response_at_point,
                color="green",
                label="Pier settlement effect",
            )
        plt.plot(
            np.arange(len(responses_array)) * c.sensor_hz,
            temp_effect[-1],
            color="blue",
            label="Temperature effect",
        )
        plt.ylabel(f"{response_type.name()} ({responses.units})")
        plt.xlabel("Time (s)")
        plt.title(f"{response_type.name()} at sensor in top plot")
        plt.legend(loc="upper right", framealpha=1)
        # Finally save the image.
        name = f"{damage_scenario.name}-{response_type.name()}-{t_ind}"
        plt.tight_layout()
        plt.savefig(c.get_image_path("classify/top-view", f"{name}.pdf"))
        plt.savefig(c.get_image_path("classify/top-view/png", f"{name}.png"))
        plt.close()
Exemple #8
0
def stress_strength_plot(c: Config, top: bool):
    """Plot the difference of tensile strength and stress under load."""
    original_c = c
    plt.portrait()
    response_type = ResponseType.StrainT if top else ResponseType.Strain
    settlement = 3
    temp_bottom, temp_top = 21, 30
    deck_points = [
        Point(x=x, y=0, z=z) for x in np.linspace(
            # c.bridge.x_min, c.bridge.x_max, num=10
            c.bridge.x_min,
            c.bridge.x_max,
            num=int(c.bridge.length * 3),
        ) for z in np.linspace(
            # c.bridge.z_min, c.bridge.z_max, num=10
            c.bridge.z_min,
            c.bridge.z_max,
            num=int(c.bridge.width * 3),
        )
    ]

    # Pier settlement.
    plt.subplot(3, 1, 1)
    c, sim_params = pier_disp_damage([(9, settlement / 1000)]).use(original_c)
    responses = (load_fem_responses(
        c=c,
        sim_runner=OSRunner(c),
        response_type=response_type,
        sim_params=sim_params,
    ).resize().to_stress(c.bridge))
    top_view_bridge(bridge=c.bridge, compass=False, abutments=True, piers=True)
    plot_contour_deck(c=c, responses=responses, decimals=2)
    plt.legend(loc="upper right", borderaxespad=0)
    plt.title(f"{settlement} mm pier settlement")
    print("Calculated stress from pier settlement")

    # Temperature effect.
    plt.subplot(3, 1, 2)
    c = original_c
    print(f"deck_points.shape = {np.array(deck_points).shape}")
    temp_effect = temperature.effect(
        c=c,
        response_type=response_type,
        points=deck_points,
        temps_bt=([temp_bottom], [temp_top]),
    ).T[0]
    print(f"temp_effect.shape = {np.array(temp_effect).shape}")
    responses = (Responses(
        response_type=response_type,
        responses=[(temp_effect[p_ind], deck_points[p_ind])
                   for p_ind in range(len(deck_points))
                   if not np.isnan(temp_effect[p_ind])],
    ).without(remove=without.edges(c=c, radius=2)).to_stress(c.bridge))
    top_view_bridge(c.bridge, compass=False, abutments=True, piers=True)
    plot_contour_deck(c=c, responses=responses, decimals=2)
    plt.legend(loc="upper right", borderaxespad=0)
    plt.title(f"T_bot, T_top = {temp_bottom}°C, {temp_top}°C")
    # plt.title(f"{top_str} stress\nbottom, top = {temp_bottom}, {temp_top}")
    print("Calculated stress from temperature")

    # Cracked concrete.
    plt.subplot(3, 1, 3)
    time = wagen1.time_at(x=52, bridge=c.bridge)
    print(f"wagen1.total_kn() = {wagen1.kn}")
    wagen1.kn = 400
    loads = wagen1.to_wheel_track_loads(c=c, time=time, flat=True)
    c, sim_params = transverse_crack().use(original_c)

    c, sim_params = HealthyDamage().use(original_c)
    sim_params.ploads = loads
    responses = (load_fem_responses(
        c=c,
        sim_runner=OSRunner(c),
        response_type=response_type,
        sim_params=sim_params,
    ).resize().to_stress(c.bridge))
    top_view_bridge(bridge=c.bridge, compass=False, abutments=True, piers=True)
    plot_contour_deck(c=c, responses=responses, decimals=2)
    plt.legend(loc="upper right", borderaxespad=0)
    # plt.title(f"Top stress: cracked concrete\nunder a {int(wagen1.kn)} kN vehicles")
    plt.title(f"{int(wagen1.total_kn())} kN vehicle")

    plt.suptitle(f"Stress {response_type.ss_direction()} for 3 scenarios")
    equal_lims("x", 3, 1)
    plt.tight_layout(rect=[0, 0.03, 1, 0.95])
    plt.savefig(
        original_c.get_image_path(
            "validation", f"stress-strength-{response_type.name()}.pdf"))
    plt.close()