Exemplo n.º 1
0
def wagen1_plot(c: Config):
    """Plot of wagen1 compared to given specification."""
    plt.landscape()

    wheel_print = (0.31, 0.25)
    wheel_prints = []
    for w_i in range(len(truck1.axle_distances) + 1):
        if w_i in [1, 2]:
            wheel_prints.append([wheel_print, wheel_print])
        else:
            wheel_prints.append([wheel_print])

    plt.subplot(1, 2, 1)
    xlim, ylim = topview_vehicle(truck1, wheel_prints=wheel_prints)
    plt.title("Truck 1 specification")
    plt.xlabel("Width (m)")
    plt.ylabel("Length (m)")

    plt.subplot(1, 2, 2)
    topview_vehicle(truck1, xlim=xlim, ylim=ylim)
    plt.title("Truck 1 in simulation")
    plt.xlabel("Width (m)")
    plt.ylabel("Length (m)")

    plt.savefig(c.get_image_path("vehicles", "wagen-1", bridge=False) + ".pdf")
    plt.close()
Exemplo n.º 2
0
def temperature_effect_date(c: Config, month: str, vert: bool):
    temp = __init__.load(name=month)
    point = Point(x=51, y=0, z=-8.4)
    plt.landscape()

    def plot_hours():
        if not vert:
            return
        label_set = False
        for dt in temp["datetime"]:
            if np.isclose(float(dt.hour + dt.minute), 0):
                label = None
                if not label_set:
                    label = "Time at vertical line = 00:00"
                    label_set = True
                plt.axvline(x=dt, linewidth=1, color="black", label=label)

    # Plot the temperature.
    plt.subplot(2, 1, 1)
    plot_hours()
    plt.scatter(
        temp["datetime"],
        temp["temp"],
        c=temp["missing"],
        cmap=mpl.cm.get_cmap("bwr"),
        s=1,
    )
    plt.ylabel("Temperature (°C)")
    plt.xlabel("Date")
    plt.gcf().autofmt_xdate()
    plt.title(f"Temperature in {str(month[0]).upper()}{month[1:]}")
    plt.legend()
    # Plot the effect at a point.
    response_type = ResponseType.YTranslation
    plt.subplot(2, 1, 2)
    plot_hours()
    effect = __init__.effect(
        c=c, response_type=response_type, points=[point], temps=temp["temp"]
    )[0]
    plt.scatter(
        temp["datetime"],
        effect * 1000,
        c=temp["missing"],
        cmap=mpl.cm.get_cmap("bwr"),
        s=1,
    )
    plt.ylabel(f"{response_type.name()} (mm)")
    plt.xlabel("Date")
    plt.gcf().autofmt_xdate()
    plt.title(f"{response_type.name()} to unit thermal loading in {month}")
    # Save.
    plt.tight_layout()
    plt.savefig(c.get_image_path("classify/temperature", f"{month}.png"))
    plt.savefig(c.get_image_path("classify/temperature", f"{month}.pdf"))
    plt.close()
Exemplo n.º 3
0
def plot_distributions(
    response_array: List[float],
    response_type: ResponseType,
    titles: List[str],
    save: str,
    cols: int = 5,
    expected: List[List[float]] = None,
    xlim: Optional[Tuple[float, float]] = None,
):
    # Transpose so points are indexed first.
    response_array = response_array.T
    # response_array, unit_str = resize_and_units(response_array, response_type)
    num_points = response_array.shape[0]
    amax, amin = np.amax(response_array), np.amin(response_array)

    # Determine the number of rows.
    rows = int(num_points / cols)
    if rows != num_points / cols:
        print_w(
            f"Cols don't divide number of points {num_points}, cols = {cols}")
        rows += 1

    # Plot fem.
    for i in range(num_points):
        plt.subplot(rows, cols, i + 1)
        plt.xlim((amin, amax))
        plt.title(titles[i])
        label = None
        if expected is not None:
            if response_array.shape != expected.shape:
                expected = expected.T
                expected, _ = resize_and_units(expected, response_type)
            assert response_array.shape == expected.shape
            label = chisquare(response_array[i], expected[i])
        plt.hist(response_array[i], label=label)
        if label is not None:
            plt.legend()
        if xlim is not None:
            plt.xlim(xlim)

    plt.savefig(save)
    plt.close()
Exemplo n.º 4
0
def experiment_noise(c: Config):
    """Plot displacement and strain noise from dynamic test 1"""
    ################
    # Displacement #
    ################
    plt.portrait()
    # Find points of each sensor.
    displa_labels = ["U13", "U26", "U29"]
    displa_points = []
    for displa_label in displa_labels:
        sensor_x, sensor_z = _displa_sensor_xz(displa_label)
        displa_points.append(Point(x=sensor_x, y=0, z=sensor_z))
    # For each sensor plot and estimate noise.
    side = 700
    for s_i, displa_label in enumerate(displa_labels):
        # First plot the signal, and smoothed signal.
        plt.subplot(len(displa_points), 2, (s_i * 2) + 1)
        with open(f"validation/experiment/D1a-{displa_label}.txt") as f:
            data = list(map(float, f.readlines()))
        # Find the center of the plot, minimum point in first 15000 points.
        data_center = 0
        for i in range(15000):
            if data[i] < data[data_center]:
                data_center = i
        data = data[data_center - side:data_center + side]
        smooth = savgol_filter(data, 31, 3)
        plt.plot(data, linewidth=1)
        plt.plot(smooth, linewidth=1)
        plt.ylim(-0.8, 0.3)
        plt.title(f"{displa_label} in dynamic test")
        # Then plot subtraction of smoothed from noisey.
        plt.subplot(len(displa_points), 2, (s_i * 2) + 2)
        noise = data - smooth
        plt.plot(noise, label=f"σ = {np.around(np.std(noise), 4)}")
        plt.legend()
        plt.title(f"Noise from {displa_label}")
    plt.tight_layout()
    plt.savefig(c.get_image_path("params", "noise-displa.pdf"))
    plt.close()

    ##########
    # Strain #
    ##########

    plt.portrait()
    # Find points of each sensor.
    strain_labels = ["T1", "T10", "T11"]
    strain_points = []
    for strain_label in strain_labels:
        sensor_x, sensor_z = _strain_sensor_xz(strain_label)
        strain_points.append(Point(x=sensor_x, y=0, z=sensor_z))
    # For each sensor plot and estimate noise.
    side = 700
    xmin, xmax = np.inf, -np.inf
    for s_i, strain_label in enumerate(strain_labels):
        # First plot the signal, and smoothed signal.
        plt.subplot(len(strain_points), 2, (s_i * 2) + 1)
        with open(f"validation/experiment/D1a-{strain_label}.txt") as f:
            data = list(map(float, f.readlines()))
        # Find the center of the plot, minimum point in first 15000 points.
        data_center = 0
        for i in range(15000):
            if data[i] < data[data_center]:
                data_center = i
        data = data[data_center - side:data_center + side]
        smooth = savgol_filter(data, 31, 3)
        plt.plot(data, linewidth=1)
        plt.plot(smooth, linewidth=1)
        plt.title(f"{strain_label} in dynamic test")
        # Then plot subtraction of smoothed from noisey.
        plt.subplot(len(strain_points), 2, (s_i * 2) + 2)
        noise = data - smooth
        plt.plot(noise, label=f"σ = {np.around(np.std(noise), 4)}")
        plt.legend()
        plt.title(f"Noise from {strain_label}")
    plt.tight_layout()
    plt.savefig(c.get_image_path("params", "noise-strain.pdf"))
    plt.close()
Exemplo n.º 5
0
def events(c: Config, x: float, z: float):
    """Plot events due to normal traffic."""
    point = Point(x=x, y=0, z=z)
    # 10 seconds of 'normal' traffic.
    max_time = 10
    traffic_scenario = normal_traffic(c=c, lam=5, min_d=2)
    # Create the 'TrafficSequence' and 'TrafficArray'.
    traffic_sequence = traffic_scenario.traffic_sequence(
        bridge=c.bridge, max_time=max_time
    )
    traffic_array = to_traffic_array(
        c=c, traffic_sequence=traffic_sequence, max_time=max_time
    )
    # Find when the simulation has warmed up, and when 'TrafficArray' begins.
    warmed_up_at = traffic_sequence[0][0].time_left_bridge(c.bridge)
    traffic_array_starts = (int(warmed_up_at / c.sensor_hz) + 1) * c.sensor_hz
    print(f"warmed up at = {warmed_up_at}")
    print(f"traffic_array_starts = {traffic_array_starts}")
    traffic_array_ends = traffic_array_starts + (len(traffic_array) * c.sensor_hz)
    print(f"traffic_array_ends = {traffic_array_ends}")
    point_lane_ind = c.bridge.closest_lane(z)
    vehicles = list(set(ts[0] for ts in traffic_sequence))
    print(len(vehicles))
    print(vehicles[0])
    vehicles = sorted(
        set(ts[0] for ts in traffic_sequence if ts[0].lane == point_lane_ind),
        key=lambda v: -v.init_x_frac,
    )
    print(len(vehicles))
    print(vehicles[0])
    event_indices = []
    vehicle_times = [v.time_at(x=x - 2, bridge=c.bridge) for v in vehicles]
    for v, t in zip(vehicles, vehicle_times):
        print(f"Vehicle {v.init_x_frac} {v.mps} at time {t}")
        start_time = int(t / c.sensor_hz) * c.sensor_hz
        print(f"start_time = {start_time}")
        ta_start_time = np.around(start_time - traffic_array_starts, 8)
        print(f"ta start time = {ta_start_time}")
        ta_start_index = int(ta_start_time / c.sensor_hz)
        print(f"ta start index = {ta_start_index}")
        ta_end_index = ta_start_index + int(c.event_time_s / c.sensor_hz)
        print(f"ta end index = {ta_end_index}")
        if ta_start_index >= 0 and ta_end_index < len(traffic_array):
            event_indices.append((ta_start_index, ta_end_index))
    print(event_indices)
    responses = (
        responses_to_traffic_array(
            c=c,
            traffic_array=traffic_array,
            response_type=ResponseType.YTranslation,
            damage_scenario=healthy_scenario,
            points=[point],
            sim_runner=OSRunner(c),
        )
        * 1000
    )
    # fem = add_displa_noise(fem)
    print(responses.shape)
    plt.portrait()
    for event_ind, (event_start, event_end) in enumerate(event_indices):
        plt.subplot(len(event_indices), 1, event_ind + 1)
        plt.plot(responses[event_start : event_end + 1])
    plt.tight_layout()
    plt.savefig(c.get_image_path("classify/events", "events.pdf"))
    plt.close()
Exemplo n.º 6
0
def time_series_plot(c: Config, n: float):
    """Plot 24min time series of cracking, for multiple cracked bridges.

    For each bridge (hard-coded), a time series of strain fem is plotted.
    For each bridge it is initially in healthy condition, and the crack occurs
    halfway through.

    Args:
        n: float, meters in front of the crack zone where to place sensor.

    """

    # First construct one day (24 minutes) of traffic.
    total_mins = 24
    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,
    )
    traffic_array.shape

    # Temperatures for one day.
    temps_day = temperature.from_to_mins(
        temperature.load("holly-springs"),
        datetime.fromisoformat(f"2019-07-03T00:00"),
        datetime.fromisoformat(f"2019-07-03T23:59"),
    )
    print(f"len temps = {len(temps_day['solar'])}")
    print(f"len temps = {len(temps_day['temp'])}")

    # Then generate some cracking time series.
    damages = [
        HealthyDamage(),
        transverse_crack(),
        transverse_crack(length=14.0, at_x=48.0),
    ]
    sensors = [
        Point(x=52, z=-8.4),  # Sensor in middle of lane.
        Point(x=damages[1].crack_area(c.bridge)[0] - n,
              z=-8.4),  # Sensor in front of crack zone.
        Point(x=damages[2].crack_area(c.bridge)[0] - n,
              z=-8.4),  # Sensor in front of crack zone.
    ]
    [print(f"Sensor {i} = {sensors[i]}") for i in range(len(sensors))]
    time_series = [
        crack_time_series(
            c=c,
            traffic_array=traffic_array,
            traffic_array_mins=total_mins,
            sensor=sensor,
            crack_frac=0.5,
            damage=damage,
            temps=temps_day["temp"],
            solar=temps_day["solar"],
        ) for damage, sensor in zip(damages, sensors)
    ]
    plt.portrait()
    for i, (y_trans, strain) in enumerate(time_series):
        x = np.arange(len(strain)) * c.sensor_hz / 60
        x_m = sensors[i].x
        damage_str = "Healthy Bridge"
        if i == 1:
            damage_str = "0.5 m crack zone"
        if i == 2:
            damage_str = "14 m crack zone"
        plt.subplot(len(time_series), 2, i * 2 + 1)
        plt.plot(x, y_trans * 1000, color="tab:blue")
        if i < len(time_series) - 1:
            plt.tick_params(axis="x", bottom=False, labelbottom=False)
        else:
            plt.xlabel("Hours")
        plt.title(f"At x = {x_m} m\n{damage_str}")
        plt.ylabel("Y trans. (mm)")

        plt.subplot(len(time_series), 2, i * 2 + 2)
        plt.plot(x, strain * 1e6, color="tab:orange")
        if i < len(time_series) - 1:
            plt.tick_params(axis="x", bottom=False, labelbottom=False)
        else:
            plt.xlabel("Hours")
        plt.title(f"At x = {x_m} m,\n{damage_str}")
        plt.ylabel("Microstrain XXB")
    plt.tight_layout()
    plt.savefig(c.get_image_path("crack", "time-series-q5.pdf"))
    plt.close()