Datasets:

ArXiv:
DOI:
License:
yirens's picture
Add files using upload-large-folder tool
a6eea8c verified
Raw
History Blame Contribute Delete
17.4 kB
# Provided parser functions for CFD results
# (c) Yiren Shen, Dec 1 2025
# Distributed under license LGPLv2.1
# General Python Imports
import sys
import os
import importlib.util
import numpy as np
from copy import deepcopy
import pickle
import pandas as pd
import glob
import vtk
from vtk.util.numpy_support import vtk_to_numpy
from datetime import datetime
def load_single_file(filepath):
"""
Load a VTK file (.vtk or .vtu format) and return the data object.
Input: String, the filepath of the VTK file.
Output: vtk.vtkUnstructuredGrid or vtk.vtkXMLUnstructuredGrid, the data object.
"""
if not os.path.exists(filepath):
raise FileNotFoundError(f"File not found: {filepath}")
file_ext = os.path.splitext(filepath)[1].lower()
if file_ext == '.vtk':
reader = vtk.vtkUnstructuredGridReader()
reader.SetFileName(filepath)
reader.Update()
return reader.GetOutput()
elif file_ext == '.vtu':
reader = vtk.vtkXMLUnstructuredGridReader()
reader.SetFileName(filepath)
reader.Update()
return reader.GetOutput()
else:
raise ValueError(f"Unsupported file format: {file_ext}. Expected .vtk or .vtu")
def get_cell_areas(surface_vtk_file):
"""
Get the cell areas from a surface vtk file.
Returns a numpy array with shape (N, 5) where columns are: [point_id, point_area, x, y, z]
Input: String, the filepath of the VTK file.
Output: numpy array with shape (N, 5) where columns are: [point_id, point_area, x, y, z]
"""
# Check if VTK file exists
if not os.path.exists(surface_vtk_file):
raise FileNotFoundError(f"VTK file not found: {surface_vtk_file}")
# Load the .vtk file
data = load_single_file(surface_vtk_file)
# Step 1: Calculate Cell Areas
cell_areas = vtk.vtkDoubleArray()
cell_areas.SetName("CellArea")
cell_areas.SetNumberOfComponents(1)
cell_areas.SetNumberOfTuples(data.GetNumberOfCells())
for i in range(data.GetNumberOfCells()):
cell = data.GetCell(i)
if isinstance(cell, vtk.vtkTriangle):
p0, p1, p2 = [cell.GetPoints().GetPoint(j) for j in range(3)]
area = vtk.vtkTriangle().TriangleArea(p0, p1, p2)
cell_areas.SetValue(i, area)
elif isinstance(cell, vtk.vtkQuad):
p0, p1, p2, p3 = [cell.GetPoints().GetPoint(j) for j in range(4)]
quad_area = vtk.vtkQuad().QuadArea(p0, p1, p2, p3)
cell_areas.SetValue(i, quad_area)
data.GetCellData().AddArray(cell_areas)
# Step 2: Transfer Cell Data to Points, SU2 uses point-centered data structure
point_areas = vtk.vtkDoubleArray()
point_areas.SetName("PointArea")
point_areas.SetNumberOfComponents(1)
point_areas.SetNumberOfTuples(data.GetNumberOfPoints())
area_sum = np.zeros(data.GetNumberOfPoints())
count = np.zeros(data.GetNumberOfPoints())
# append cell areas to points, and disect the cell areas to get area associated with points
for i in range(data.GetNumberOfCells()):
cell = data.GetCell(i)
area = cell_areas.GetValue(i)
for j in range(cell.GetNumberOfPoints()):
point_id = cell.GetPointId(j)
area_sum[point_id] += area
count[point_id] += 1
for i in range(data.GetNumberOfPoints()):
avg_area = area_sum[i] / count[i] if count[i] > 0 else 0
point_areas.SetValue(i, avg_area)
data.GetPointData().AddArray(point_areas)
# Get coordinates
coordinates = np.array([data.GetPoint(i) for i in range(data.GetNumberOfPoints())])
# Return as numpy array: point_id, point_area, x, y, z
result = np.array([[i, point_areas.GetValue(i), coordinates[i][0], coordinates[i][1], coordinates[i][2]]
for i in range(data.GetNumberOfPoints())])
return result
def load_cfd_data(filepath):
"""
Load the CFD data from a VTK file (.vtk or .vtu) and return mesh data and info.
Input: String, the filepath of the VTK file.
Output: vtk.vtkUnstructuredGrid or vtk.vtkXMLUnstructuredGrid, the data object.
Output: dictionary, the mesh info.
"""
data = load_single_file(filepath)
# Extract basic information about the mesh
points = data.GetPoints()
num_points = points.GetNumberOfPoints()
num_cells = data.GetNumberOfCells()
# Extract point data arrays
point_data = data.GetPointData()
point_data_arrays = {point_data.GetArrayName(i): point_data.GetArray(i) for i in range(point_data.GetNumberOfArrays())}
# Extract cell data arrays
cell_data = data.GetCellData()
cell_data_arrays = {cell_data.GetArrayName(i): cell_data.GetArray(i) for i in range(cell_data.GetNumberOfArrays())}
mesh_info = {
"num_points": num_points,
"num_cells": num_cells,
"point_data_arrays": list(point_data_arrays.keys()),
"cell_data_arrays": list(cell_data_arrays.keys())
}
return data, mesh_info
def get_xyz_and_connectivity(data):
"""
Extract xyz coordinates and cell connectivity from VTK data.
Input: vtk.vtkUnstructuredGrid or vtk.vtkXMLUnstructuredGrid, the data object.
Returns:
xyz_coordinates: numpy array of shape (N, 3) with x, y, z coordinates
connectivity: list of lists, each inner list contains point IDs for a cell
"""
points = data.GetPoints()
num_points = points.GetNumberOfPoints()
xyz_coordinates = np.array([points.GetPoint(i) for i in range(num_points)])
cells = data.GetCells()
connectivity = []
cells.InitTraversal()
id_list = vtk.vtkIdList()
while cells.GetNextCell(id_list):
connectivity.append([id_list.GetId(j) for j in range(id_list.GetNumberOfIds())])
return xyz_coordinates, connectivity
def compute_surface_normals(data, feature_angle=45.0):
"""
Equivalent to ParaView's 'Extract Surface' + 'Generate Surface Normals'.
Returns a vtkPolyData with normal vectors added as point data.
Input: vtk.vtkUnstructuredGrid or vtk.vtkXMLUnstructuredGrid, the data object.
Input: float, the feature angle for the normal generation.
Output: vtk.vtkPolyData, the data object with normal vectors added as point data.
"""
# Step 1: Extract surface (works for unstructured grids)
surface_filter = vtk.vtkGeometryFilter()
surface_filter.SetInputData(data)
surface_filter.Update()
# Step 2: Generate normals
normals = vtk.vtkPolyDataNormals()
normals.SetInputConnection(surface_filter.GetOutputPort())
normals.SetFeatureAngle(feature_angle)
normals.ConsistencyOn()
normals.SplittingOff() # optional: keep smooth normals across edges
normals.Update()
# Extract the output
surface_with_normals = normals.GetOutput()
# Debug info
print("Added Normals:")
pd = surface_with_normals.GetPointData()
if pd.GetNormals():
print(f"Normal array name: {pd.GetNormals().GetName()}")
else:
print("No normals found (check if mesh has proper connectivity).")
return surface_with_normals
if __name__ == "__main__":
# Test file
test_file = "./trainingSet/19240101DG/14.0degAOA/surface_flow.vtu"
print("=" * 70)
print("Unit Tests for Util.py Functions")
print("=" * 70)
all_tests_passed = True
# ========================================================================
# Test 1: load_single_file
# ========================================================================
print("\n" + "-" * 70)
print("Test 1: load_single_file")
print("-" * 70)
try:
data = load_single_file(test_file)
assert data is not None, "load_single_file returned None"
assert hasattr(data, 'GetPoints'), "Returned object is not a VTK data object"
num_points = data.GetNumberOfPoints()
num_cells = data.GetNumberOfCells()
print(f"O Successfully loaded VTK file")
print(f" Points: {num_points}, Cells: {num_cells}")
# Test error handling for non-existent file
try:
load_single_file("./nonexistent_file.vtk")
print("X Error: Should have raised FileNotFoundError for non-existent file")
all_tests_passed = False
except FileNotFoundError:
print("O Correctly raises FileNotFoundError for non-existent file")
except Exception as e:
print(f"X Error: {e}")
import traceback
traceback.print_exc()
all_tests_passed = False
# ========================================================================
# Test 2: load_cfd_data
# ========================================================================
print("\n" + "-" * 70)
print("Test 2: load_cfd_data")
print("-" * 70)
try:
data, mesh_info = load_cfd_data(test_file)
assert data is not None, "load_cfd_data returned None for data"
assert mesh_info is not None, "load_cfd_data returned None for mesh_info"
assert isinstance(mesh_info, dict), "mesh_info should be a dictionary"
required_keys = ["num_points", "num_cells", "point_data_arrays", "cell_data_arrays"]
for key in required_keys:
assert key in mesh_info, f"mesh_info missing key: {key}"
print(f"O Successfully loaded CFD data")
print(f" Mesh info:")
print(f" num_points: {mesh_info['num_points']}")
print(f" num_cells: {mesh_info['num_cells']}")
print(f" point_data_arrays: {len(mesh_info['point_data_arrays'])} arrays")
print(f" cell_data_arrays: {len(mesh_info['cell_data_arrays'])} arrays")
if mesh_info['point_data_arrays']:
print(f" Point data array names: {mesh_info['point_data_arrays']}")
if mesh_info['cell_data_arrays']:
print(f" Cell data array names: {mesh_info['cell_data_arrays']}")
except Exception as e:
print(f"X Error: {e}")
import traceback
traceback.print_exc()
all_tests_passed = False
# ========================================================================
# Test 3: get_xyz_and_connectivity
# ========================================================================
print("\n" + "-" * 70)
print("Test 3: get_xyz_and_connectivity")
print("-" * 70)
try:
# Load data first
data = load_single_file(test_file)
xyz_coordinates, connectivity = get_xyz_and_connectivity(data)
# Verify xyz_coordinates is numpy array
assert isinstance(xyz_coordinates, np.ndarray), f"Expected numpy array, got {type(xyz_coordinates)}"
assert xyz_coordinates.ndim == 2, f"Expected 2D array, got {xyz_coordinates.ndim}D"
assert xyz_coordinates.shape[1] == 3, f"Expected 3 columns (x,y,z), got {xyz_coordinates.shape[1]}"
# Verify connectivity is a list
assert isinstance(connectivity, list), f"Expected list, got {type(connectivity)}"
assert len(connectivity) > 0, "Connectivity list should not be empty"
num_points = xyz_coordinates.shape[0]
num_cells = len(connectivity)
print(f"O Successfully extracted coordinates and connectivity")
print(f" Coordinates shape: {xyz_coordinates.shape} (N={num_points} points, 3 columns)")
print(f" Connectivity: {num_cells} cells")
# Verify coordinates are finite
assert np.all(np.isfinite(xyz_coordinates)), "Found non-finite coordinates"
print(f"O All coordinates are finite")
print(f" Coordinate ranges:")
print(f" X: [{np.min(xyz_coordinates[:, 0]):.6f}, {np.max(xyz_coordinates[:, 0]):.6f}]")
print(f" Y: [{np.min(xyz_coordinates[:, 1]):.6f}, {np.max(xyz_coordinates[:, 1]):.6f}]")
print(f" Z: [{np.min(xyz_coordinates[:, 2]):.6f}, {np.max(xyz_coordinates[:, 2]):.6f}]")
# Verify connectivity point IDs are valid
max_point_id = max(max(cell) for cell in connectivity if len(cell) > 0)
assert max_point_id < num_points, f"Connectivity contains invalid point ID: {max_point_id} >= {num_points}"
print(f"O Connectivity point IDs are valid (max ID: {max_point_id} < {num_points})")
except Exception as e:
print(f"X Error: {e}")
import traceback
traceback.print_exc()
all_tests_passed = False
# ========================================================================
# Test 4: compute_surface_normals
# ========================================================================
print("\n" + "-" * 70)
print("Test 4: compute_surface_normals")
print("-" * 70)
try:
# Load data first
data = load_single_file(test_file)
surface_with_normals = compute_surface_normals(data, feature_angle=45.0)
assert surface_with_normals is not None, "compute_surface_normals returned None"
assert hasattr(surface_with_normals, 'GetPointData'), "Returned object is not a VTK PolyData object"
point_data = surface_with_normals.GetPointData()
normals_array = point_data.GetNormals()
print(f"O Successfully computed surface normals")
print(f" Output points: {surface_with_normals.GetNumberOfPoints()}")
print(f" Output cells: {surface_with_normals.GetNumberOfCells()}")
if normals_array:
print(f"O Normals array found: {normals_array.GetName()}")
print(f" Normals array size: {normals_array.GetNumberOfTuples()}")
# Verify normals are unit vectors (approximately)
normals_np = vtk_to_numpy(normals_array)
norms = np.linalg.norm(normals_np, axis=1)
# Normals should be approximately unit length (allow small tolerance)
assert np.allclose(norms, 1.0, atol=1e-6), "Normals are not unit vectors"
print(f"O Normals are unit vectors (magnitude ≈ 1.0)")
else:
print(" Warning: No normals array found (may be normal for some mesh types)")
except Exception as e:
print(f"X Error: {e}")
import traceback
traceback.print_exc()
all_tests_passed = False
# ========================================================================
# Test 5: get_cell_areas
# ========================================================================
print("\n" + "-" * 70)
print("Test 5: get_cell_areas")
print("-" * 70)
try:
result = get_cell_areas(test_file)
# Verify it's a numpy array
assert isinstance(result, np.ndarray), f"Expected numpy array, got {type(result)}"
print(f"O Return type is numpy array: {type(result)}")
# Check the shape
assert result.ndim == 2, f"Expected 2D array, got {result.ndim}D"
assert result.shape[1] == 5, f"Expected 5 columns, got {result.shape[1]}"
print(f"O Array shape: {result.shape} (N={result.shape[0]} points, 5 columns)")
# Check the length
num_points = result.shape[0]
print(f"O Number of points: {num_points}")
# Verify column structure: [point_id, point_area, x, y, z]
assert result.shape[1] == 5, "Expected 5 columns: [point_id, point_area, x, y, z]"
print(f"O Column structure: [point_id, point_area, x, y, z]")
# Check data types
print(f"O Data type: {result.dtype}")
# Basic validation: check that areas are non-negative
point_areas = result[:, 1]
assert np.all(point_areas >= 0), "Found negative point areas"
print(f"O All point areas are non-negative (min={np.min(point_areas):.6e}, max={np.max(point_areas):.6e})")
# Check that point IDs are sequential (0, 1, 2, ...)
point_ids = result[:, 0]
expected_ids = np.arange(num_points)
assert np.array_equal(point_ids, expected_ids), "Point IDs are not sequential"
print(f"O Point IDs are sequential (0 to {num_points-1})")
# Check that coordinates are finite
coords = result[:, 2:5]
assert np.all(np.isfinite(coords)), "Found non-finite coordinates"
print(f"O All coordinates are finite")
print(f" Coordinate ranges:")
print(f" X: [{np.min(coords[:, 0]):.6f}, {np.max(coords[:, 0]):.6f}]")
print(f" Y: [{np.min(coords[:, 1]):.6f}, {np.max(coords[:, 1]):.6f}]")
print(f" Z: [{np.min(coords[:, 2]):.6f}, {np.max(coords[:, 2]):.6f}]")
except FileNotFoundError as e:
print(f"X Error: {e}")
print(" Make sure the test file exists at the specified path.")
all_tests_passed = False
except Exception as e:
print(f"X Error: {e}")
import traceback
traceback.print_exc()
all_tests_passed = False
# ========================================================================
# Summary
# ========================================================================
print("\n" + "=" * 70)
if all_tests_passed:
print("O ALL TESTS PASSED!")
else:
print("X SOME TESTS FAILED")
print("=" * 70)