def make_geom_plots(c: Config): """Make plots of the geometry (with some vehicles) of each bridge.""" from plot.geom import top_view_bridge from plot.load import top_view_vehicles # First create some vehicles. mk = lambda init_x_frac, lane, length: MvVehicle( kn=100 * length, axle_distances=[length], axle_width=2, kmph=40, lane=lane, init_x_frac=init_x_frac, ) mv_vehicles = [[], [mk(0.1, 0, 2.5), mk(0.4, 0, 4), mk(0, 1, 7)]] # Create a plot for each set of vehicles. for i, set_mv_vehicles in enumerate(mv_vehicles): # First the top view. plt.close() top_view_bridge(c.bridge) top_view_vehicles(bridge=c.bridge, mv_vehicles=set_mv_vehicles, time=2) plt.savefig(c.get_image_path("geom", f"top-view-{i + 1}")) # Then the side view. plt.close()
def draw(path, srv): filename = os.path.join(path, srv["preprocessed_filename"]) df = pd.read_csv(filename, sep="\t", index_col='time', parse_dates=True) bins = defaultdict(list) for i, col in enumerate(df.columns): serie = df[col].dropna() if pd.algos.is_monotonic_float64(serie.values, False)[0]: serie = serie.diff()[1:] p_value = adfuller(serie, autolag='AIC')[1] if math.isnan(p_value): continue nearest = 0.05 * round(p_value/0.05) bins[nearest].append(serie) for bin, members in bins.items(): series = [serie.name for serie in members] if len(members) <= 10: columns = series else: columns = random.sample(series, 10) subset = df[columns] name = "%s_adf_confidence_%.2f.png" % (srv["name"], bin) print(name) axes = subset.plot(subplots=True) plt.savefig(os.path.join(path, name)) plt.close("all")
def draw_speedup(df): data = defaultdict(list) X = "Resource usage" Y = "Speedup" HUE = "Simulation time [min]" periods = [1, 10, 20, 30, 60] for period in periods: df2 = df[df.original_wall_time < (period * 60)] data[X].extend(["CPU time"] * len(df2)) data[HUE].extend([period] * len(df2)) data[Y].extend(df2.original_cpu_time / df2.replay_cpu_time) data[X].extend(["Maximum resident memory time"] * len(df2)) data[HUE].extend([period] * len(df2)) data[Y].extend(df2.original_maxrss / df2.replay_maxrss) df3 = pd.DataFrame(data) writer = pd.ExcelWriter('cpu_speedup.xlsx') df3[df3[X] == "CPU time"].to_excel(writer, "Sheet1") writer.save() sns.barplot(x=X, y=Y, hue=HUE, data=df3[df3[X] == "CPU time"]) plt.savefig("cpu-speedup.png") plt.close() df3 = pd.DataFrame(data) sns.barplot(x=X, y=Y, hue=HUE, data=df3[df3[X] == "Maximum resident memory time"]) plt.savefig("memory-speedup.pdf") plt.close()
def draw(path): data = metadata.load(path) adf_dist_path = os.path.join(path, "adf_distribution.png") if os.path.exists(adf_dist_path): print("path exists %s, skip" % adf_dist_path) #return p_values = {'c': [], 'ct': [], 'ctt': []} for srv in data["services"]: do_adfuller(path, srv, p_values) measurement = os.path.dirname(os.path.join(path, '')) ax = plt.subplots(1)[1] ax.yaxis.grid() labels = [ "constant", "constant + trend", "constant, and linear and quadratic trend" ] ax.hist(p_values.values(), 22, histtype='bar', align='mid', label=labels, alpha=0.4) ax.set_xlabel( "Distribution of p-value for Augmented Dickey-Fuller test for %s" % measurement) ax.legend() plt.savefig(adf_dist_path) print(adf_dist_path)
def write(df, name): fig, axes = plt.subplots(ncols=2, nrows=3, figsize=(20, 10)) draw_series_combined(df, name, axes[0, 0]) axes[0, 1].axis('off') axes[0, 1].legend(*axes[0, 0].get_legend_handles_labels(), loc='upper left', ncol=2) draw_series_seperate(df, axes[2, 0]) if df.centroid.notnull().any() and df.centroid.var() != 0: distances = [] for c in df.columns[1:]: distances.append(_sbd(df.centroid, df[c])[0]) draw_lag(df, axes[2, 1]) draw_sbd_bar_plot(distances, axes[1, 0]) draw_sbd_dist_plot(distances, axes[1, 1]) try: plt.tight_layout() plt.savefig(name, dpi=200) plt.close("all") except Exception as e: import pdb pdb.set_trace() print("graph %s failed %s" % (name, e))
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"))
def draw_pairplot(df): df.replay_solver_time = df.replay_solver_time / 1000000 sns.pairplot(df, vars=[ "replay_allocations", "replay_solver_time", "replay_constraint_size", "replay_path_length" ]) plt.savefig("pairplot.pdf") plt.close()
def draw_path_length(df): df.replay_solver_time = df.replay_solver_time / 1000000 sns.regplot(x="replay_path_length", y="replay_solver_time", data=df) plt.savefig("replay-path-length-1.pdf") plt.close() sns.regplot(x="replay_path_length", y="replay_cpu_time", data=df) plt.savefig("replay-path-length-2.pdf") plt.close()
def imshow_il(c: Config, il_matrix: ILMatrix, num_loads: int, num_sensors: int, save: str): """Plot a matrix of influence line for multiple response positions. Args: c: Config, global configuration object. il_matrix: ILExpt, fem for a number of unit load simulations. num_loads: int, number of loading positions/influence lines to plot. num_sensors: int, number of sensor positions in x direction to plot. """ load_fracs = np.linspace(0, 1, num_loads) sensor_fracs = np.linspace(0, 1, num_sensors) matrix = [] for load_frac in load_fracs: matrix.append([]) for sensor_frac in sensor_fracs: value = il_matrix.response_to( x_frac=sensor_frac, z_frac=il_matrix.load_z_frac, load_x_frac=load_frac, load=c.il_unit_load_kn, ) # print_d(D, f"value = {value}, il_frac = {il_frac}, load_x_frac = {load_x_frac}") matrix[-1].append(value) units = il_matrix.response_type.units() if il_matrix.response_type.units() == "m": matrix = np.array(matrix) * 1000 units = "mm" print(np.amax(np.array(matrix))) print(np.amin(np.array(matrix))) plt.imshow(matrix, aspect="auto") clb = plt.colorbar() clb.ax.set_title(units) plt.title( f"Influence lines for {num_sensors} response positions along z =" + f" {c.bridge.z(il_matrix.load_z_frac):.2f}" + f" {il_matrix.response_type.units()}") plt.xlabel("Response x position (m)") locs = [int(i) for i in np.linspace(0, num_sensors - 1, 5)] labels = [f"{c.bridge.x(sensor_fracs[i]):.2f}" for i in locs] plt.xticks(locs, labels) locs = [int(i) for i in np.linspace(0, num_loads - 1, 5)] labels = [f"{c.bridge.x(load_fracs[i]):.2f}" for i in locs] plt.yticks(locs, labels) plt.ylabel("Load x position (m)") if save: plt.savefig(save) plt.close()
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()
def uls_contour_plot(c: Config, x_i: int, z_i: int, response_type: ResponseType): wheel_xs = c.bridge.wheel_track_xs(c) wheel_x = wheel_xs[x_i] wheel_zs = c.bridge.wheel_track_zs(c) wheel_z = wheel_zs[z_i] print_i(f"Wheel (x, z) = ({wheel_x}, {wheel_z})") plt.landscape() plt.subplot(2, 1, 1) healthy = list( ILMatrix.load_wheel_track( c=c, response_type=response_type, fem_runner=OSRunner(c), load_z_frac=c.bridge.z_frac(wheel_z), run_only=False, indices=[x_i], ))[0].resize() top_view_bridge(bridge=c.bridge, compass=False, abutments=True, piers=True) plot_contour_deck(c=c, responses=healthy, sci_format=True, decimals=6) plt.title("Healthy") c = transverse_crack().use(c)[0] cracked = list( ILMatrix.load_wheel_track( c=c, response_type=response_type, fem_runner=OSRunner(c), load_z_frac=c.bridge.z_frac(wheel_z), run_only=False, indices=[x_i], ))[0].resize() plt.subplot(2, 1, 2) top_view_bridge(bridge=c.bridge, compass=False, abutments=True, piers=True) plot_contour_deck(c=c, responses=cracked, sci_format=True, decimals=6) plt.title("Cracked") plt.tight_layout() plt.savefig( c.get_image_path( "verification", safe_str( f"uls-contour-x-{wheel_x}-z-{wheel_z}-{response_type.name()}") + ".pdf", ))
def centroids(path): metadata = load_metadata(path) d = {} for srv in metadata["services"]: name = "%s/%s-cluster-1_1.tsv" % (path, srv["name"]) df = pd.read_csv(name, sep="\t", index_col='time', parse_dates=True) d[srv["name"]] = df.centroid df2 = pd.DataFrame(d) df2 = df2.fillna(method="bfill", limit=1e9) df2 = df2.fillna(method="ffill", limit=1e9) fig = df2.plot() handles, labels = fig.get_legend_handles_labels() fig.grid('on') lgd = fig.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5, -0.1)) plt.savefig("graph.png", bbox_extra_artists=(lgd, ), bbox_inches='tight') plt.close("all")
def matrix_subplots( c: Config, resp_matrix: ResponsesMatrix, num_subplots: int, num_x: int, z_frac: float, rows: int = 4, save: str = None, plot_func=None, ): """For each subplot plot matrix fem using the given function.""" cols = int(num_subplots / rows) if cols != num_subplots / rows: print_w(f"Rows don't divide number of simulations, cols = {cols}" + f", sims = {num_subplots / rows}" + f", num_subplots = {num_subplots}, rows = {rows}") cols += 1 y_min, y_max = 0, 0 # Plot each IL and bridge deck side. for i, response_frac in enumerate(np.linspace(0, 1, rows * cols)): plt.subplot(rows, cols, i + 1) plot_bridge_deck_side(c.bridge, show=False, equal_axis=False) rs = plot_func(c, resp_matrix, i, response_frac, z_frac=z_frac, num_x=num_x) plt.axvline(x=c.bridge.x(x_frac=response_frac), color="red") # Keep track of min and max on y axis (only when non-zero fem). if any(rs): _y_min, _y_max = plt.gca().get_ylim() y_min, y_max = min(y_min, _y_min), max(y_max, _y_max) # Ensure y_min == -y_max. y_min = min(y_min, -y_max) y_max = max(-y_min, y_max) for i, _ in enumerate(np.linspace(0, 1, rows * cols)): plt.subplot(rows, cols, i + 1) plt.ylim(y_min, y_max) plt.tight_layout() if save: plt.savefig(save) plt.close()
def build_with_refinement(refinement_radii): sim_params = SimParams( response_types=[response_type], ploads=[pload], refinement_radii=refinement_radii, ) # Build and save the model file. if build: build_model_3d( c=min_config, expt_params=ExptParams([sim_params]), os_runner=OSRunner(min_config), ) # Load and plot fem. if plot: sim_responses = load_fem_responses( c=min_config, sim_runner=OSRunner(min_config), response_type=response_type, sim_params=sim_params, run=True, ) for scatter in [True, False]: top_view_bridge(min_config.bridge, abutments=True, piers=True, lanes=True) plot_contour_deck( c=min_config, responses=sim_responses, scatter=scatter, levels=100, ) plt.title(f"{refinement_radii}") plt.savefig( min_config.get_image_path( "debugging", safe_str( f"{response_type.name()}-{refinement_radii}-scatter-{scatter}" ) + ".pdf", )) plt.close()
def plot_il( c: Config, resp_matrix: ILMatrix, expt_index: int, response_frac: float, z_frac: float, num_x: int, save: str = None, ): """Plot the IL for a response at some position.""" x_fracs = np.linspace(0, 1, num_x) rs = [ resp_matrix.response_to( x_frac=response_frac, z_frac=z_frac, load_x_frac=load_x_frac, load=c.il_unit_load_kn, ) for load_x_frac in x_fracs ] xs = [c.bridge.x(x_frac=x_frac) for x_frac in x_fracs] units = resp_matrix.response_type.units() if units == "m": rs = np.array(rs) * 1000 units = "mm" else: sci_format_y_axis() plt.plot(xs, rs) x, z = c.bridge.x(response_frac), c.bridge.z(resp_matrix.load_z_frac) name = resp_matrix.response_type.name() plt.title(f"{name.capitalize()} at x = {x:.2f}m, z = {z:.2f}m" + f"\n to {c.il_unit_load_kn}kN load moving along" + f" z = {c.bridge.z(resp_matrix.load_z_frac):.2f}m") plt.xlabel(f"X position of {c.il_unit_load_kn}kN load") plt.ylabel(f"{name.capitalize()} ({units})") if save: plt.savefig(save) plt.close() return rs
def plot_dc( c: Config, resp_matrix: ResponsesMatrix, expt_index: int, response_frac: float, num_x: int, interp_sim: bool, interp_response: bool, save: str = None, show: bool = False, ): """Plot the IL for a response at some position. This function ignores the interp_sim as it just return the response due to the displacement load which was placed in the simulation, and is determined by the expt_index parameter. The ignored parameters exist just so the function definition is consistent with plot_il and can be passed to the same functions. """ print_w(f"plt.matrices.plot_dc: expt_index = {expt_index}") fem_responses = resp_matrix.expt_responses[expt_index] xs = fem_responses.xs rs = [ resp_matrix.expt_responses[expt_index].at(x_frac=c.bridge.x_frac(x), interpolate=interp_sim) for x in xs ] response_name = resp_matrix.response_type.name() response_units = resp_matrix.response_type.units() plt.title(f"{response_name.capitalize()} at simulation {expt_index}") plt.xlabel(f"x-axis (m)") plt.ylabel(f"{response_name.capitalize()} ({response_units})") sci_format_y_axis() plt.plot(xs, rs) if save: plt.savefig(save) if show: plt.show() if save or show: plt.close() return rs
def docker_usage(path): data = metadata.load(path) for service in data["services"]: name = "%s/%s-usage.png" % (path, service["name"]) if os.path.exists(name): print("skip " + name) continue filename = os.path.join(path, service["filename"]) df = pd.read_csv(filename, sep="\t", index_col='time', parse_dates=True) if df["usage_percent"].size == 0: continue fields = [ "usage_percent", "cache", "rx_bytes", "io_service_bytes_recursive_read", "io_serviced_recursive_write" ] fig = df[fields].plot(subplots=True) plt.savefig(name) plt.close("all")
def draw_bugs_found(df): data = defaultdict(list) df = df.groupby( df.application).apply(aggregate_replay_cpu_time).reset_index() X = "Method" Y = "Number of found bugs" HUE = "CPU time budget [min]" periods = [1, 10, 20, 30, 60] for period in periods: df2 = df[df.original_cpu_time < (period * 60)] data[X].append("Klee") data[Y].append(len(df2)) data[HUE].append(period) df3 = df[df.replay_cpu_time < (period * 60)] data[X].append("Replay Klee") data[Y].append(len(df3)) data[HUE].append(period) df4 = pd.DataFrame(data) sns.barplot(x=HUE, y=Y, hue=X, data=df4) plt.savefig("found-bugs-after-time.pdf") plt.close()
def draw(path): data = metadata.load(path) p_values_pearson = [] p_values_shapiro = [] norm_dist_path = os.path.join(path, "normtest_distribution.png") if os.path.exists(norm_dist_path): print("path exists %s, skip" % norm_dist_path) #return for srv in data["services"]: filename = os.path.join(path, srv["filename"]) df = load_timeseries(filename, srv) columns = [] for c in df.columns: if (not df[c].isnull().all()) and df[c].var() != 0: columns.append(c) df = df[columns] n = len(columns) if n == 0: continue fig, axis = plt.subplots(n, 2) fig.set_figheight(n * 4) fig.set_figwidth(30) for i, col in enumerate(df.columns): serie = df[col].dropna() sns.boxplot(x=serie, ax=axis[i, 0]) statistic_1, p_value_1 = normaltest(serie) p_values_pearson.append(p_value_1) statistic_2, p_value_2 = shapiro(serie) p_values_shapiro.append(p_value_2) templ = """Pearson's normtest: statistic: %f p-value: %E -> %s Shapiro-Wilk test for normality: statistic: %f p-value: %E -> %s """ outcome_1 = "not normal distributed" if p_value_1 < 0.05 else "normal distributed" outcome_2 = "not normal distributed" if p_value_2 < 0.05 else "normal distributed" text = templ % (statistic_1, p_value_1, outcome_1, statistic_2, p_value_2, outcome_2) axis[i, 1].axis('off') axis[i, 1].text(0.05, 0.05, text, fontsize=18) plot_path = os.path.join(path, "%s_normtest.png" % srv["name"]) plt.savefig(plot_path) print(plot_path) fig, axis = plt.subplots(2) fig.set_figheight(8) measurement = os.path.dirname(os.path.join(path, '')) name = "Distribution of p-value for Pearson's normtest for %s" % measurement plot = sns.distplot(pd.Series(p_values_pearson, name=name), rug=True, kde=False, norm_hist=False, ax=axis[0]) name = "Distribution of p-value for Shapiro-Wilk's normtest for %s" % measurement plot = sns.distplot(pd.Series(p_values_shapiro, name=name), rug=True, kde=False, norm_hist=False, ax=axis[1]) fig.savefig(norm_dist_path) print(norm_dist_path)
def truck_1_time_series(c: Config): """Time series of 3 sensors to Truck 1's movement.""" side_s = 7 side = int(side_s * (1 / c.sensor_hz)) assert wagen1.x_at(time=0, bridge=c.bridge) == 0 # Get times and loads for Truck 1. end_time = wagen1.time_left_bridge(c.bridge) wagen1_times = np.linspace(-end_time, end_time * 2, int((end_time * 3) / c.sensor_hz)) print_i("Calculating Truck 1 loads") wagen1_loads = [ flatten(wagen1.to_wheel_track_loads(c=c, time=time), PointLoad) # flatten(wagen1.to_point_load_pw(time=time, bridge=c.bridge), PointLoad) for time in wagen1_times ] print_i("Calculated Truck 1 loads") def set_labels(ylabel: str, xlabel: str): for i, y, x in [ (1, True, False), (2, False, False), (3, True, False), (4, False, False), (5, True, True), (6, False, True), ]: plt.subplot(3, 2, i) ax = plt.gca() if y: plt.ylabel(ylabel) else: ax.axes.yaxis.set_ticklabels([]) if x: plt.xlabel(xlabel) ax.axes.xaxis.set_ticklabels([]) ymin, ymax = np.inf, -np.inf for i in range(1, 6 + 1): plt.subplot(3, 2, i) ymin = min(ymin, plt.ylim()[0]) ymax = max(ymax, plt.ylim()[1]) for i in range(1, 6 + 1): plt.subplot(3, 2, i) plt.ylim((ymin, ymax)) ################ # Vert. trans. # ################ plt.portrait() # Find points of each sensor. displa_labels = ["U13", "U26", "U29"] displa_points = [ Point(x=sensor_x, y=0, z=sensor_z) for sensor_x, sensor_z in [displa_sensor_xz(displa_label) for displa_label in displa_labels] ] # Ensure points and truck are on the same lane. assert all(p.z < 0 for p in displa_points) # Results from simulation. responses_truck1 = responses_to_traffic_array( c=c, traffic_array=loads_to_traffic_array(c=c, loads=wagen1_loads), response_type=ResponseType.YTranslation, damage_scenario=healthy_scenario, points=displa_points, ).T for s_i, sensor_responses in enumerate(responses_truck1): plt.subplot(len(displa_points), 2, (s_i * 2) + 1) # Find the center of the plot, minimum point in the data. data_center = 0 for i in range(len(sensor_responses)): if sensor_responses[i] < sensor_responses[data_center]: data_center = i # sensor_responses = add_displa_noise(sensor_responses) * 1000 sensor_responses = sensor_responses * 1000 plt.plot(sensor_responses[data_center - side:data_center + side]) plt.title(f"{displa_labels[s_i]} in simulation") # Results from experiment. side = int(side / ((1 / c.sensor_hz) / 100)) print_i(f"{side} points each side of center") for s_i, displa_label in enumerate(displa_labels): plt.subplot(len(displa_points), 2, (s_i * 2) + 2) with open(f"validation/experiment/D1a-{displa_label}.txt") as f: data = list(map(float, f.readlines())) side_expt = int(side_s * (len(data) / 240)) # 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 plt.plot(data[data_center - side_expt:data_center + side_expt]) plt.title(f"{displa_label} in dynamic test") set_labels("Y translation (mm)", "Time") plt.tight_layout() plt.savefig( c.get_image_path("validation/truck-1", "time-series-vert-trans.pdf")) plt.close() ########## # Strain # ########## plt.portrait() # Find points of each sensor. strain_labels = ["T1", "T10", "T11"] strain_points = [ Point(x=sensor_x, y=0, z=sensor_z) for sensor_x, sensor_z in [strain_sensor_xz(strain_label) for strain_label in strain_labels] ] # Results from simulation. responses_truck1 = responses_to_traffic_array( c=c, traffic_array=loads_to_traffic_array(c=c, loads=wagen1_loads), response_type=ResponseType.Strain, damage_scenario=healthy_scenario, points=strain_points, ).T for s_i, sensor_responses in enumerate(responses_truck1): plt.subplot(len(strain_points), 2, (s_i * 2) + 1) # Find the center of the plot, minimum point in the data. data_center = 0 for i in range(len(sensor_responses)): if sensor_responses[i] > sensor_responses[data_center]: data_center = i # sensor_responses = add_strain_noise(sensor_responses) # plt.plot(sensor_responses) plt.plot(sensor_responses[data_center - side:data_center + side]) # plt.plot(sensor_responses[data_center - side : data_center + side]) plt.title(f"{strain_labels[s_i]} in simulation") # Results from experiment. print_i(f"{side} points each side of center") for s_i, strain_label in enumerate(strain_labels): plt.subplot(len(strain_points), 2, (s_i * 2) + 2) with open(f"validation/experiment/D1a-{strain_label}.txt") as f: data = list(map(float, f.readlines())) side_expt = int(side_s * (len(data) / 240)) # 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 # plt.plot(data) plt.plot(data[data_center - side_expt:data_center + side_expt]) # plt.plot(data[data_center - side_expt : data_center + side_expt]) plt.title(f"{strain_label} in dynamic test") set_labels("Microstrain", "Time") plt.tight_layout() plt.savefig( c.get_image_path("validation/truck-1", "time-series-strain.pdf")) plt.close()
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()
def plot_events_from_traffic( c: Config, bridge: Bridge, bridge_scenario: DamageScenario, traffic_name: str, traffic: "Traffic", start_time: float, time_step: float, response_type: ResponseType, points: List[Point], fem_runner: FEMRunner, cols: int = 4, save: str = None, ): """Plot events from a traffic simulation on a bridge.""" # Determine rows, cols and events per row. time_per_event = int(c.time_end / time_step) events = events_from_traffic( c=c, traffic=traffic, bridge_scenario=bridge_scenario, points=points, response_types=[response_type], fem_runner=fem_runner, start_time=start_time, time_step=time_step, ) print( f"event time = {c.time_end}, time step = {time_step}, time per event = {time_per_event}" ) print(f"num traffic = {len(traffic)}") print(f"num events = {len(events)}") for p, point in enumerate(points): events_ = events[p][0] # Currently only one response type. # First determine rows and max/min response. rows = math.ceil(len(events_) / cols) y_min, y_max = np.inf, -np.inf for event in events_: y_min = min(y_min, np.min(event.get_time_series(noise=True))) y_max = max(y_max, np.max(event.get_time_series(noise=True))) y_min = min(y_min, -y_max) y_max = max(y_max, -y_min) assert isinstance(y_min, float) assert isinstance(y_max, float) y_min, y_max = np.min([y_min, -y_max]), np.max([y_max, -y_min]) print_i(f"rows, cols = {rows}, {cols}") # Plot each event, including overlap. event_index = 0 for row in range(rows): if event_index >= len(events_): break for col in range(cols): if event_index >= len(events_): break event = events_[event_index] print_i(f"row, col = {row}, {col}") plt.subplot2grid((rows, cols), (row, col)) end_overlap = event.overlap if event_index < len( events_) - 1 else 0 plot_event( c=c, event=event, start_index=event.start_index, response_type=response_type, at=point, overlap=(event.overlap, end_overlap), y_min=y_min, y_max=y_max, ) event_index += 1 if save: plt.savefig(f"{save}-at-{pstr(str(point))}") plt.close()
def compare_axles(c: Config): """Compare fem between uniaxle vehicles and Truck 1.""" assert c.il_num_loads == 600 point = Point(x=c.bridge.x_max / 2, y=0, z=-8.4) end_time = wagen1.time_left_bridge(bridge=c.bridge) num_times = int(end_time / c.sensor_hz) wagen1_times = np.linspace(0, end_time, num_times) plt.portrait() wagen1_loads = [ flatten(wagen1.to_wheel_track_loads(c=c, time=time), PointLoad) for time in wagen1_times ] responses_ulm = responses_to_traffic_array( c=c, traffic_array=loads_to_traffic_array(c=c, loads=wagen1_loads), response_type=ResponseType.YTranslation, damage_scenario=healthy_scenario, points=[point], sim_runner=OSRunner(c), ) plt.subplot(3, 1, 1) plt.title( f"{num_times} fem with ULS = {c.il_num_loads} (Wagen 1 (4 axles))") plt.plot(wagen1_times, np.array(responses_ulm).reshape(-1, 1)) bi_axle_loads = [ flatten(bi_axle_vehicle.to_wheel_track_loads(c=c, time=time), PointLoad) for time in wagen1_times ] responses_ulm = responses_to_traffic_array( c=c, traffic_array=loads_to_traffic_array(c=c, loads=bi_axle_loads), response_type=ResponseType.YTranslation, damage_scenario=healthy_scenario, points=[point], sim_runner=OSRunner(c), ) plt.subplot(3, 1, 2) plt.title(f"{num_times} fem with ULS = {c.il_num_loads} (2 axles)") plt.plot(wagen1_times, np.array(responses_ulm).reshape(-1, 1)) uni_axle_loads = [ flatten(uni_axle_vehicle.to_wheel_track_loads(c=c, time=time), PointLoad) for time in wagen1_times ] responses_ulm = responses_to_traffic_array( c=c, traffic_array=loads_to_traffic_array(c=c, loads=uni_axle_loads), response_type=ResponseType.YTranslation, damage_scenario=healthy_scenario, points=[point], sim_runner=OSRunner(c), ) plt.subplot(3, 1, 3) plt.title(f"{num_times} fem with ULS = {c.il_num_loads} (1 axle)") plt.plot(wagen1_times, np.array(responses_ulm).reshape(-1, 1)) plt.tight_layout() plt.savefig(c.get_image_path("system-verification", "compare-axles.pdf"))
def wagen_1_contour_plot( c: Config, x: int, crack_x: float, response_type: ResponseType, scatter: bool, run: bool, length: float, outline: bool, wheels: bool, temp: bool, ): original_c = c LOADS = False temp_bottom, temp_top = [17, 25] time = wagen1.time_at(x=x, bridge=c.bridge) def plot_wheels(): if wheels: wagen1.plot_wheels(c=c, time=time, label="Truck 1 wheels", zorder=100) center = c.bridge.x_max / 2 min_x, max_x = center - 20, center + 20 min_z, max_z = c.bridge.z_min, c.bridge.z_max def zoom_in(): plt.ylim(min_z, max_z) plt.xlim(min_x, max_x) loads = wagen1.to_wheel_track_loads(c=c, time=time, flat=True) crack_f = lambda: transverse_crack(length=length, at_x=crack_x) c = healthy_damage_w_transverse_crack_nodes(crack_f).use(original_c)[0] deck_shells = get_bridge_shells(c.bridge)[0] healthy_responses = load_fem_responses( c=c, sim_params=SimParams(ploads=loads), response_type=response_type, sim_runner=OSRunner(c), run=run, ).at_shells(deck_shells) # Convert fem to one per shell. if response_type in [ResponseType.Strain, ResponseType.StrainZZB]: # Resize by E-6 from microstrain to strain to match temperature units. healthy_responses = healthy_responses.resize() before_temp = healthy_responses.at_deck(Point(x=51, z=-8.4), interp=False) if temp: healthy_deck_points = healthy_responses.deck_points() # Point of fem. temp_effect = temperature.effect( c=c, response_type=response_type, points=healthy_deck_points, temps_bt=([temp_bottom], [temp_top]), ).T[0] # Temperature effect at existing response points. healthy_responses = healthy_responses.add(temp_effect, healthy_deck_points) after_temp = healthy_responses.at_deck(Point(x=51, z=-8.4), interp=False) print_i(f"Healthy, before/after = {before_temp}, {after_temp}") if response_type in [ResponseType.Strain, ResponseType.StrainZZB]: healthy_responses = healthy_responses.map(lambda x: x * 1e6) else: healthy_responses = healthy_responses.resize() # Responses in cracked scenario. c = crack_f().use(original_c)[0] crack_responses = load_fem_responses( c=c, sim_params=SimParams(ploads=loads), response_type=response_type, sim_runner=OSRunner(c), run=run, ).at_shells(deck_shells) if response_type in [ResponseType.Strain, ResponseType.StrainZZB]: # Resize by E-6 from microstrain to strain to match temperature units. crack_responses = crack_responses.resize() before_temp = crack_responses.at_deck(Point(x=51, z=-8.4), interp=False) if temp: crack_deck_points = crack_responses.deck_points() # Point of fem. temp_effect = temperature.effect( c=c, response_type=response_type, points=healthy_deck_points, temps_bt=([temp_bottom], [temp_top]), ).T[0] # Temperature effect at existing response points. crack_responses = crack_responses.add(temp_effect, healthy_deck_points) after_temp = crack_responses.at_deck(Point(x=51, z=-8.4), interp=False) print_i(f"Crack, before/after = {before_temp}, {after_temp}") if response_type in [ResponseType.Strain, ResponseType.StrainZZB]: crack_responses = crack_responses.map(lambda x: x * 1e6) else: crack_responses = crack_responses.resize() # Limit to points in crack zone. without_cm = 35 print(f"Avoid {without_cm} cm around crack zone") _without_crack_zone = crack_f().without(c.bridge, without_cm / 100) without_crack_zone = lambda p: not _without_crack_zone(p) if response_type in [ResponseType.Strain, ResponseType.StrainZZB]: healthy_responses = healthy_responses.without(without_crack_zone) crack_responses = crack_responses.without(without_crack_zone) # Norm calculation. vmin = min(healthy_responses.values()) vmax = max(healthy_responses.values()) vmin = min(vmin, min(crack_responses.values())) vmax = max(vmax, max(crack_responses.values())) norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax) print(f"Norm min/max = {vmin}, {vmax}") plt.portrait() plt.subplot(3, 1, 1) plot_contour_deck( c=c, responses=healthy_responses, ploads=loads if LOADS else [], scatter=scatter, norm=norm, decimals=2, ) c_x_start, c_z_start, c_x_end, c_z_end = list( map(round_m, crack_f().crack_area(c.bridge))) def plot_outline(label="Crack zone"): if outline: plt.gca().add_patch( mpl.patches.Rectangle( (c_x_start, c_z_start), c_x_end - c_x_start, c_z_end - c_z_start, fill=not scatter, edgecolor="black", facecolor="white", alpha=1, label=label, )) top_view_bridge(bridge=c.bridge, compass=False, abutments=True, piers=True) plot_outline(label="Responses not considered") plot_wheels() zoom_in() def legend(): plt.legend( loc="upper right", borderpad=0.2, labelspacing=0.2, borderaxespad=0, handletextpad=0.2, columnspacing=0.2, ) legend() plt.title(f"Healthy bridge") plt.xlabel("") plt.tick_params(bottom=False, labelbottom=False) plt.subplot(3, 1, 2) plot_contour_deck( c=c, responses=crack_responses, ploads=loads if LOADS else [], scatter=scatter, norm=norm, decimals=2, ) top_view_bridge(bridge=c.bridge, compass=False, abutments=True, piers=True) plot_outline() plot_wheels() zoom_in() legend() plt.title(f"Cracked bridge") plt.xlabel("") plt.tick_params(bottom=False, labelbottom=False) plt.subplot(3, 1, 3) responses = [] for x in healthy_responses.deck_xs: for z in healthy_responses.zs[x][0]: responses.append(( bridge_sim.sim.responses.responses[0][x][0][z] - crack_responses.at_deck(Point(x=x, z=z), interp=False), Point(x=x, z=z), )) # try: # fem.append(( # healthy_responses.fem[0][x][0][z] # - crack_responses.fem[0][x][0][z], # Point(x=x, z=z) # )) # except KeyError: # pass # diff_responses = responses = Responses( response_type=response_type, responses=responses, units=healthy_responses.units, ) plot_contour_deck( c=c, responses=diff_responses, ploads=loads if LOADS else [], cmap=mpl.cm.get_cmap("PiYG"), scatter=scatter, decimals=2, ) print("********") print("********") print("********") grid_x, grid_z = 600, 200 grid_points = list( filter( lambda p: not without_crack_zone(p), [ Point(x=x, y=0, z=z) for x in np.linspace(c.bridge.x_min, c.bridge.x_max, grid_x) for z in np.linspace(c.bridge.z_min, c.bridge.z_max, grid_z) ], )) print(f"Amount grid points = {len(grid_points)}") grid_x_len = c.bridge.length / grid_x grid_z_len = c.bridge.width / grid_z grid_area = grid_x_len * grid_z_len print(f"Grid area = {grid_area}") print("Interpolating diff fem") interp_diff_responses = diff_responses.at_decks(grid_points) count_interp = len(interp_diff_responses) interp_diff_responses = interp_diff_responses[~np. isnan(interp_diff_responses)] print( f"Removed {count_interp - len(interp_diff_responses)} of {count_interp} fem, remaining = {len(interp_diff_responses)}" ) print("Finished interpolating diff fem") count_min, count_max = 0, 0 d_min, d_max = min(diff_responses.values()), max(diff_responses.values()) print(f"diff min, max = {d_min}, {d_max}") d_min08, d_max08 = d_min * 0.8, d_max * 0.8 for interp_r in interp_diff_responses: if interp_r < d_min08: count_min += 1 if interp_r > d_max08: count_max += 1 print(f"Count = {count_min}, {count_max}") save_path = original_c.get_image_path( "verification", safe_str( f"truck1-contour-x-{x}{crack_x}{length}-{response_type.name()}-{temp}" ), ) with open(save_path + ".txt", "w") as f: f.write(f"{count_min}, {count_max}\n") f.write(f"{count_min * grid_area}, {count_max * grid_area}") print(f"Wrote results to {save_path}.txt") top_view_bridge(bridge=c.bridge, compass=False, abutments=True, piers=True) plot_outline() plot_wheels() zoom_in() legend() temp_str = f"\nT_bot = {temp_bottom} °C, T_top = {temp_top} °C" if temp else "" plt.title(f"Difference of healthy & cracked bridge") rt_name = (f"Microstrain {response_type.ss_direction()}" if response_type in [ResponseType.Strain, ResponseType.StrainZZB ] else response_type.name()) plt.suptitle(f"{rt_name}: Truck 1 on healthy & cracked bridge{temp_str}") plt.tight_layout(rect=[0, 0.03, 1, 0.93 if temp else 0.95]) plt.savefig(save_path + ".pdf")
def compare_responses(c: Config): """Compare fem to Truck 1, direct simulation and matmul.""" assert c.il_num_loads == 600 num_times = 50 close_times = 200 # Running time: # responses_to_vehicles_d: num_times * 8 # responses_to_vehicles_d: 4 * il_num_loads # responses_to_loads_m: 0 (4 * il_num_loads) # responses_to_loads_m: 0 (4 * il_num_loads) # Wagen 1 from the experimental campaign. point = Point(x=c.bridge.x_max - (c.bridge.length / 2), y=0, z=-8.4) end_time = wagen1.time_left_bridge(bridge=c.bridge) wagen1_times = list(np.linspace(0, end_time, num_times)) more_wagen1_times = list( np.linspace( wagen1.time_at(x=point.x - 2, bridge=c.bridge), wagen1.time_at(x=point.x + 2, bridge=c.bridge), close_times, )) wagen1_times = sorted(wagen1_times + more_wagen1_times) plt.portrait() # Start with fem from direct simulation. responses_not_binned = responses_to_vehicles_d( c=c, response_type=ResponseType.YTranslation, points=[point], mv_vehicles=[wagen1], times=wagen1_times, sim_runner=OSRunner(c), binned=False, ) plt.subplot(4, 1, 1) plt.title(f"{len(wagen1_times)} fem") plt.plot(wagen1_times, responses_not_binned) # Then fem from direct simulation with binning. c.shorten_paths = True responses_binned = responses_to_vehicles_d( c=c, response_type=ResponseType.YTranslation, points=[point], mv_vehicles=[wagen1], times=wagen1_times, sim_runner=OSRunner(c), binned=True, ) c.shorten_paths = False plt.subplot(4, 1, 2) plt.title(f"{len(wagen1_times)} fem (binned)") plt.plot(wagen1_times, responses_binned) xlim = plt.xlim() num_times = int(end_time / c.sensor_hz) wagen1_times = np.linspace(0, end_time, num_times) # Then from 'TrafficArray' we get fem, without binning. wagen1_loads = [ flatten(wagen1.to_point_load_pw(time=time, bridge=c.bridge), PointLoad) for time in wagen1_times ] responses_ulm = responses_to_traffic_array( c=c, traffic_array=loads_to_traffic_array(c=c, loads=wagen1_loads), response_type=ResponseType.YTranslation, damage_scenario=healthy_scenario, points=[point], sim_runner=OSRunner(c), ) plt.subplot(4, 1, 3) plt.title(f"{num_times} fem with ULS = {c.il_num_loads} traffic_array") plt.plot(wagen1_times, np.array(responses_ulm).reshape(-1, 1)) plt.xlim(xlim) # # Then from 'TrafficArray' we get fem, with binning. wagen1_loads = [ flatten(wagen1.to_wheel_track_loads(c=c, time=time), PointLoad) for time in wagen1_times ] responses_ulm_binned = responses_to_traffic_array( c=c, traffic_array=loads_to_traffic_array(c=c, loads=wagen1_loads), response_type=ResponseType.YTranslation, damage_scenario=healthy_scenario, points=[point], sim_runner=OSRunner(c), ) plt.subplot(4, 1, 4) plt.title( f"{num_times} fem from {c.il_num_loads} il_num_loads\ntraffic_array binned" ) plt.plot(wagen1_times, np.array(responses_ulm_binned).reshape(-1, 1)) plt.xlim(xlim) plt.tight_layout() plt.savefig( c.get_image_path("system-verification", "compare-time-series.pdf"))
def cluster_damage(c: Config, mins: float): # 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=mins * 60, ) point = Point(x=21, y=0, z=-8.4) # Point to investigate. # Collect vertical translation and strain for all scenarios scenarios. responses_y = [] responses_s = [] for damage_scenario in [ healthy_damage, pier_disp_damage([(5, 0.5 / 1000)]) ]: responses_y.append( responses_to_traffic_array( c=c, traffic_array=traffic_array, response_type=ResponseType.YTranslation, damage_scenario=damage_scenario, points=[point], sim_runner=OSRunner(c), ).T[0] * 1000) assert len(responses_y[-1]) == len(traffic_array) responses_s.append( responses_to_traffic_array( c=c, traffic_array=traffic_array, response_type=ResponseType.Strain, damage_scenario=damage_scenario, points=[point], sim_runner=OSRunner(c), ).T[0]) assert len(responses_s[-1]) == len(traffic_array) # Calculate features per scenarios. damage_features = [] damage_labels = [] for damage_ind in range(len(responses_y)): y = responses_y[damage_ind] s = responses_s[damage_ind] for response_ind in range(len(y)): damage_features.append([y[response_ind], s[response_ind]]) damage_labels.append(damage_ind) damage_features = np.array(damage_features) damage_labels = np.array(damage_labels) print_i(f"Dimensions of feature array = {damage_features.shape}") # Plot the reference data. plt.landscape() plt.scatter(damage_features[:, 0], damage_features[:, 1], c=damage_labels) plt.title("Reference") plt.tight_layout() plt.savefig(c.get_image_path("classify/cluster", "cluster-ref.pdf")) plt.close() # Plot the gaussian mixture results. gmm = mixture.GaussianMixture(n_components=2).fit(damage_features) labels = flip(l=gmm.predict(damage_features), ref=damage_labels) plt.landscape() plt.scatter(damage_features[:, 0], damage_features[:, 1], c=labels) plt.title("Gaussian mixture n = 2") plt.tight_layout() plt.savefig(c.get_image_path("classify/cluster", "cluster-model.pdf")) plt.close() # Plot and print the accuracy. # https://matplotlib.org/3.1.1/gallery/text_labels_and_annotations/custom_legends.html acc = abs(labels - damage_labels) total = defaultdict(lambda: 0) correct = defaultdict(lambda: 0) for ind, label in enumerate(damage_labels): total[label] += 1 if acc[ind] == 0: correct[label] += 1 for k, t in total.items(): print_i(f"k = {k}: {correct[k]} / {t} = {correct[k] / t}") plt.scatter(damage_features[:, 0], damage_features[:, 1], c=acc) plt.tight_layout() plt.savefig(c.get_image_path("classify/cluster", "cluster-acc.pdf")) plt.close()
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()