Project_Fatigue / Fatigue_Life_Combined_master /Visuize /visualize_combined_result.py
SachinSaud's picture
Upload folder using huggingface_hub
2350ba1 verified
import pyvista as pv
import pandas as pd
import numpy as np
from pathlib import Path
import sys
# Add the parent directory to the Python path to find other modules
sys.path.append(str(Path(__file__).resolve().parent.parent))
def visualize_sample(eval_dir, sample_idx):
"""
Finds the geometry and prediction files for a specific sample,
and creates a 3D visualization comparing ground truth and prediction.
Args:
eval_dir (str): The path to the directory containing the evaluation output.
sample_idx (int): The index of the sample to visualize (e.g., 0, 1, 2...).
"""
eval_path = Path(eval_dir)
# --- 1. Find and Load the Correct Files ---
geometry_file = eval_path / f"geometry_sample_{sample_idx}.npz"
prediction_file = eval_path / f"prediction_sample_{sample_idx}.csv"
if not geometry_file.is_file():
raise FileNotFoundError(f"Geometry file not found: {geometry_file}")
if not prediction_file.is_file():
raise FileNotFoundError(f"Prediction CSV file not found: {prediction_file}")
print(f"Loading geometry from: {geometry_file}")
print(f"Loading predictions from: {prediction_file}")
geom_data = np.load(geometry_file)
df = pd.read_csv(prediction_file)
# --- 2. Extract and Prepare Data ---
positions = geom_data['mesh_pos']
connectivity = geom_data['cells']
ground_truth_life = df['ground_truth_life'].values
predicted_life = df['final_predicted_life'].values
# --- 3. Build the PyVista Unstructured Grid ---
num_cells = connectivity.shape[0]
padding = np.full((num_cells, 1), 4)
cells_for_pyvista = np.hstack((padding, connectivity)).flatten()
# --- THIS IS THE FIX ---
# Create an array of cell types with the same length as the number of cells.
# Each element specifies that the corresponding cell is a tetrahedron.
cell_types = np.full(num_cells, pv.CellType.TETRA, dtype=np.uint8)
# Create the grid object using the new cell_types array
grid = pv.UnstructuredGrid(cells_for_pyvista, cell_types, positions)
# --- END OF FIX ---
grid["Ground Truth Life"] = ground_truth_life
grid["Predicted Life"] = predicted_life
# --- 4. Create and Configure the Plot ---
plotter = pv.Plotter(shape=(1, 2), window_size=[1600, 800])
min_val = min(ground_truth_life.min(), predicted_life.min())
max_val = max(ground_truth_life.max(), predicted_life.max())
clim = [min_val, max_val]
# Subplot 1: Ground Truth
plotter.subplot(0, 0)
plotter.add_text("Ground Truth Life", font_size=15)
plotter.add_mesh(grid, scalars="Ground Truth Life", cmap="viridis", show_edges=False, clim=clim, log_scale=True)
plotter.add_axes()
plotter.set_background("white")
# Subplot 2: Prediction
plotter.subplot(0, 1)
plotter.add_text("Predicted Life (Combined Model)", font_size=15)
plotter.add_mesh(grid.copy(), scalars="Predicted Life", cmap="viridis", show_edges=False, clim=clim, log_scale=True)
plotter.add_axes()
plotter.set_background("white")
plotter.link_views()
plotter.camera_position = 'xy'
#output_filename = eval_path / f"visualization_sample_{sample_idx}.png"
#plotter.screenshot(output_filename)
#print(f"\nSaved visualization to {output_filename}")
print("Showing interactive plot. Close the window to exit.")
plotter.show()
def main():
"""
Main function to define the file paths and run the visualizer.
"""
# --- USER ACTION REQUIRED ---
evaluation_directory = "/home/gd_user1/AnK/project_PINN/Project_Fatigue/Fatigue_Life_Combined/combined_test_results_pre_masking"
sample_index = 0
# --- END OF USER ACTION SECTION ---
visualize_sample(evaluation_directory, sample_index)
if __name__ == "__main__":
main()