genai_test / utils /dataset_verifier.py
Kyo-Kai's picture
Upload 2 files
1f94288 verified
import os
import math
import random
import numpy as np
import matplotlib.pyplot as plt
from collections import defaultdict
def compute_sequence_lengths(dataset_folder="dataset", show_details=False):
"""
Compute and print min/max sequence lengths (nodes, elements) across all trusses in the dataset.
Uses only min/max n_div files per mode for efficiency.
Args:
dataset_folder (str): Path to the dataset folder containing .npz files.
Returns:
Dict with keys 'min_nodes', 'max_nodes', 'min_elements', 'max_elements'.
"""
npz_files = [f for f in os.listdir(dataset_folder) if f.endswith('.npz')]
if not npz_files:
raise ValueError(f"No .npz files found in '{dataset_folder}'.")
# First pass: compute min/max n_div per mode
min_max_div = defaultdict(lambda: (float('inf'), float('-inf')))
for f in npz_files:
parts = f[:-4].rsplit('_', 2) # e.g., ['truss_pratt', '15', '39']
if len(parts) == 3 and parts[0].startswith('truss_'):
mode = parts[0][6:] # Remove 'truss_'
n_div = int(parts[1])
min_d, max_d = min_max_div[mode]
min_max_div[mode] = (min(min_d, n_div), max(max_d, n_div))
# Second pass: collect one file per min/max per mode
min_div_files = defaultdict(list)
max_div_files = defaultdict(list)
for f in npz_files:
parts = f[:-4].rsplit('_', 2)
if len(parts) == 3 and parts[0].startswith('truss_'):
mode = parts[0][6:]
n_div = int(parts[1])
if n_div == min_max_div[mode][0]:
min_div_files[mode].append(f)
if n_div == min_max_div[mode][1]:
max_div_files[mode].append(f)
# # Print min/max n_div per mode
# print("Per truss type min/max segments (n_div):")
# for mode in sorted(min_max_div):
# mn, mx = min_max_div[mode]
# print(f"{mode}: {mn} - {mx}")
# Compute overall min/max sequence lengths by loading one min/max file per mode
min_n_nod = float('inf')
max_n_nod = 0
min_n_ele = float('inf')
max_n_ele = 0
for mode in sorted(min_max_div):
# For min
if min_div_files[mode]:
min_file = min_div_files[mode][0] # Pick first
data_min = np.load(os.path.join(dataset_folder, min_file))
min_n_nod = min(min_n_nod, int(data_min['n_nod_tot']))
min_n_ele = min(min_n_ele, int(data_min['n_ele_tot']))
data_min.close()
# For max
if max_div_files[mode]:
max_file = max_div_files[mode][0] # Pick first
data_max = np.load(os.path.join(dataset_folder, max_file))
max_n_nod = max(max_n_nod, int(data_max['n_nod_tot']))
max_n_ele = max(max_n_ele, int(data_max['n_ele_tot']))
data_max.close()
print(f"Overall min sequence lengths: nodes={min_n_nod}, elements={min_n_ele}")
print(f"Overall max sequence lengths: nodes={max_n_nod}, elements={max_n_ele}")
# Additionally print out for one structure type how the keys inside look like
if show_details == True:
example_mode = next(iter(max_div_files))
example_file = max_div_files[example_mode][0]
example_data = np.load(os.path.join(dataset_folder, example_file))
print(f"\nExample data keys from '{example_file}': {example_data.files}")
for key in example_data.files:
print(f" - {key}: shape {example_data[key].shape}, dtype {example_data[key].dtype}")
example_data.close()
return {
'min_nodes': min_n_nod,
'max_nodes': max_n_nod,
'min_elements': min_n_ele,
'max_elements': max_n_ele
}
def load_and_visualize_random_truss(dataset_folder="dataset", num_samples=1, display_equal=False, save_fig=False):
"""
Load random truss(es) from dataset_folder and visualize them with one shared legend on top.
Legend handles are robust and spacing is tight.
"""
npz_files = [f for f in os.listdir(dataset_folder) if f.endswith(".npz")]
if not npz_files:
raise ValueError(f"No .npz files found in '{dataset_folder}'.")
samples = []
random.shuffle(npz_files)
npz_files = npz_files[:num_samples]
# Layout logic
if num_samples >= 3:
n_cols = 3
elif num_samples == 2:
n_cols = 2
else:
n_cols = 1
n_rows = math.ceil(num_samples / n_cols)
fig, axes = plt.subplots(n_rows, n_cols, figsize=(5 * n_cols, 3.5 * n_rows))
axes = np.atleast_1d(axes).flatten()
# Predefine legend proxy handles
proxy_handles = {
"Bottom Nodes": plt.Line2D([], [], marker="o", color="blue", ls="", markersize=6),
"Top Nodes": plt.Line2D([], [], marker="o", color="red", ls="", markersize=6),
"Beams": plt.Line2D([], [], color="green", lw=2),
"Columns": plt.Line2D([], [], color="black", lw=3),
"Rods": plt.Line2D([], [], color="purple", lw=1.5, ls="--"),
}
for i, filename in enumerate(npz_files):
filepath = os.path.join(dataset_folder, filename)
data = np.load(filepath)
nodal_coord = data["nodal_coord"]
ele_nod = data["ele_nod"]
truss_mode = str(data["truss_mode"])
n_div = int(data["n_div"])
angle = float(data["angle"])
n_beams = int(data["n_beams"])
n_columns = int(data["n_columns"])
n_rods = int(data["n_rods"])
n_ele_tot = int(data["n_ele_tot"])
ax = axes[i]
ax.set_xlim(-0.05, 1.05)
# Adjust y-limits due to small range
ymin, ymax = nodal_coord[:, 1].min(), nodal_coord[:, 1].max()
yrange = ymax - ymin
if yrange < 0.05:
yrange = 0.05
ax.set_ylim(ymin - 0.1 * yrange, ymax + 0.15 * yrange)
if display_equal == True:
ax.set_aspect("equal")
ax.set_title(f"{truss_mode} (n_div={n_div}, angle={angle:.0f}°)")
ax.grid(True, alpha=0.3)
# Plot nodes
bottom_mask = np.abs(nodal_coord[:, 1]) < 1e-6
ax.scatter(nodal_coord[bottom_mask, 0], nodal_coord[bottom_mask, 1], c="blue", s=45)
ax.scatter(nodal_coord[~bottom_mask, 0], nodal_coord[~bottom_mask, 1], c="red", s=45)
# Plot elements
for j in range(n_ele_tot):
node1, node2 = ele_nod[j]
x1, y1 = nodal_coord[node1]
x2, y2 = nodal_coord[node2]
if j < n_beams:
ax.plot([x1, x2], [y1, y2], "g-", lw=2)
elif j < n_beams + n_columns:
ax.plot([x1, x2], [y1, y2], "k-", lw=3)
else:
ax.plot([x1, x2], [y1, y2], "purple", ls="--", lw=1.5)
samples.append({k: data[k] for k in data.files})
# Hide unused axes
for j in range(num_samples, len(axes)):
axes[j].axis("off")
# Add shared legend at top (compact spacing)
fig.legend(
proxy_handles.values(),
proxy_handles.keys(),
loc="upper center",
ncol=len(proxy_handles),
frameon=False,
fontsize=9,
handlelength=2.5,
columnspacing=1.5,
borderaxespad=0.1, # shrink gap between legend and figure
handletextpad=0.4,
)
plt.subplots_adjust(top=0.92, hspace=0.35, wspace=0.25)
if save_fig:
out_path = os.path.join(dataset_folder, f"random_truss_grid_{num_samples}.png")
plt.savefig(out_path, dpi=150, bbox_inches="tight")
print(f"Saved figure to {out_path}")
plt.show()
return samples