| |
| |
| |
|
|
|
|
|
|
| |
| 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] |
| """ |
| |
| if not os.path.exists(surface_vtk_file): |
| raise FileNotFoundError(f"VTK file not found: {surface_vtk_file}") |
|
|
| |
| data = load_single_file(surface_vtk_file) |
|
|
| |
| 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) |
|
|
| |
| 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()) |
|
|
| |
| 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) |
|
|
| |
| coordinates = np.array([data.GetPoint(i) for i in range(data.GetNumberOfPoints())]) |
|
|
| |
| 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) |
|
|
| |
| points = data.GetPoints() |
| num_points = points.GetNumberOfPoints() |
| num_cells = data.GetNumberOfCells() |
|
|
| |
| point_data = data.GetPointData() |
| point_data_arrays = {point_data.GetArrayName(i): point_data.GetArray(i) for i in range(point_data.GetNumberOfArrays())} |
|
|
| |
| 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. |
| """ |
| |
| surface_filter = vtk.vtkGeometryFilter() |
| surface_filter.SetInputData(data) |
| surface_filter.Update() |
|
|
| |
| normals = vtk.vtkPolyDataNormals() |
| normals.SetInputConnection(surface_filter.GetOutputPort()) |
| normals.SetFeatureAngle(feature_angle) |
| normals.ConsistencyOn() |
| normals.SplittingOff() |
| normals.Update() |
|
|
| |
| surface_with_normals = normals.GetOutput() |
|
|
| |
| 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 = "./trainingSet/19240101DG/14.0degAOA/surface_flow.vtu" |
| |
| print("=" * 70) |
| print("Unit Tests for Util.py Functions") |
| print("=" * 70) |
| |
| all_tests_passed = True |
| |
| |
| |
| |
| 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}") |
| |
| |
| 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 |
| |
| |
| |
| |
| 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 |
| |
| |
| |
| |
| print("\n" + "-" * 70) |
| print("Test 3: get_xyz_and_connectivity") |
| print("-" * 70) |
| |
| try: |
| |
| data = load_single_file(test_file) |
| xyz_coordinates, connectivity = get_xyz_and_connectivity(data) |
| |
| |
| 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]}" |
| |
| |
| 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") |
| |
| |
| 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}]") |
| |
| |
| 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 |
| |
| |
| |
| |
| print("\n" + "-" * 70) |
| print("Test 4: compute_surface_normals") |
| print("-" * 70) |
| |
| try: |
| |
| 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()}") |
| |
| normals_np = vtk_to_numpy(normals_array) |
| norms = np.linalg.norm(normals_np, axis=1) |
| |
| 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 |
| |
| |
| |
| |
| print("\n" + "-" * 70) |
| print("Test 5: get_cell_areas") |
| print("-" * 70) |
| |
| try: |
| result = get_cell_areas(test_file) |
| |
| |
| assert isinstance(result, np.ndarray), f"Expected numpy array, got {type(result)}" |
| print(f"O Return type is numpy array: {type(result)}") |
| |
| |
| 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)") |
| |
| |
| num_points = result.shape[0] |
| print(f"O Number of points: {num_points}") |
| |
| |
| 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]") |
| |
| |
| print(f"O Data type: {result.dtype}") |
| |
| |
| 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})") |
| |
| |
| 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})") |
| |
| |
| 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 |
| |
| |
| |
| |
| print("\n" + "=" * 70) |
| if all_tests_passed: |
| print("O ALL TESTS PASSED!") |
| else: |
| print("X SOME TESTS FAILED") |
| print("=" * 70) |