File size: 8,464 Bytes
1ca7ae2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 | """
Utilities for the OpenFOAM simulation.
Also look into /openfoam and oclerc/improved_car_dataset/Preprocessing
"""
import os, os.path
import shutil
import re
import trimesh
import numpy as np
RE_FLOAT = '-?[0-9]+\.?[0-9]*' # signed float
RE_VECTOR = f'\(\s*{RE_FLOAT}\s*{RE_FLOAT}\s*{RE_FLOAT}\s*\)' # 3d vector of signed floats
CONFIG_FILE = "include/config"
CAR_STL_FILE = "constant/triSurface/car.stl"
####################################################################################################
# Simulation setup
####################################################################################################
def find_highest_point(mesh, epsilon=0.05):
"""Find point close to max height and the further front."""
height = mesh.bounds[1, 2]
close_p = mesh.vertices[:,2] > height - epsilon
verts = mesh.vertices[close_p]
return verts[verts[:,0].argmin()]
def get_vr4(mesh):
# From DRIVAER template
_vr4_min, _vr4_max = np.array([3.2, -1., -0.3]), np.array([6.2, 1.0, 1.0])
vr4_min, vr4_max = _vr4_min.copy(), _vr4_max.copy()
# x: start on highest point, then end on offset to the car
vr4_min[0] = find_highest_point(mesh)[0]
x_offset = 2.395022 # from DRIVAER
vr4_max[0] = mesh.bounds[1,0] + x_offset
# y: resize based on ratio to DRIVAER
ratio_y = mesh.extents[1] / 2.02998 # from DRIVAER
vr4_y = (_vr4_max[1] - _vr4_min[1]) * ratio_y
vr4_min[1], vr4_max[1] = -vr4_y / 2, vr4_y / 2
# z: to car height
vr4_max[2] = mesh.bounds[1,2]
return vr4_min, vr4_max
def get_vr3(mesh, vr4):
# From DRIVAER template
_vr3_min, _vr3_max = np.array([2.5, -1.5, -0.3]), np.array([7.5, 1.5, 1.4])
vr3_min, vr3_max = _vr3_min.copy(), _vr3_max.copy()
# x: start on highest point, then constant offset to vr4
vr3_min[0] = find_highest_point(mesh)[0]
x_offset = 1.3 # from DRIVAER
vr3_max[0] = vr4[1][0] + x_offset
# y: constant offset to vr4
y_offset = 0.5
vr3_min[1] = vr4[0][1] - y_offset
vr3_max[1] = vr4[1][1] + y_offset
# z: height of car + constant offset
z_offset = 0.300101 # from DRIVAER
vr3_max[2] = mesh.bounds[1,2] + z_offset
return vr3_min, vr3_max
def get_vr2(mesh, vr3):
# From DRIVAER template
_vr2_min, _vr2_max = np.array([-2.0, -2.0, -0.3]), np.array([9.0, 2.0, 1.7])
vr2_min, vr2_max = _vr2_min.copy(), _vr2_max.copy()
# x: same offset to front and to vr3
front_x_offset = 1.192151 # between DRIVAER and vr2
back_x_offset = 1.5 # between vr3 and 2
vr2_min[0] = mesh.bounds[0,0] - front_x_offset
vr2_max[0] = vr3[1][0] + back_x_offset
# y: constant offset to vr3
y_offset = 0.5
vr2_min[1] = vr3[0][1] - y_offset
vr2_max[1] = vr3[1][1] + y_offset
# z: constant offset to vr3
z_offset = 0.3
vr2_max[2] = vr3[1][2] + z_offset
return vr2_min, vr2_max
def get_vr1(mesh):
# From DRIVAER template
_vr1_min, _vr1_max = np.array([-7.5, -3.0, -0.3]), np.array([25.0, 3.0, 3.7])
vr1_min, vr1_max = _vr1_min.copy(), _vr1_max.copy()
# Fixed
return vr1_min, vr1_max
def get_all_vr(mesh):
vr4_min, vr4_max = get_vr4(mesh)
vr3_min, vr3_max = get_vr3(mesh, (vr4_min, vr4_max))
vr2_min, vr2_max = get_vr2(mesh, (vr3_min, vr3_max))
vr1_min, vr1_max = get_vr1(mesh)
return (vr4_min, vr4_max), (vr3_min, vr3_max), (vr2_min, vr2_max), (vr1_min, vr1_max)
def find_Aref(mesh, ray_per_dim=512):
"""Approximate frontal area by intersecting rays."""
y_min, y_max = mesh.bounds[:,1]
z_min, z_max = mesh.bounds[:,2]
yz_area = (y_max - y_min) * (z_max - z_min)
YZ = np.stack(np.meshgrid(
np.linspace(y_min, y_max, ray_per_dim),
np.linspace(z_min, z_max, ray_per_dim),
), axis=-1).reshape(-1, 2)
YZ = np.concatenate([np.full_like(YZ[:,0:1], -2), YZ], axis=1)
intersections = mesh.ray.intersects_any(YZ, [[1,0,0]]* len(YZ))
return yz_area * intersections.mean()
def vector2str(vector):
return " ".join(["("] + [f"{x:.2f}" for x in vector]+ [")"])
def edit_config(configpath, aref, vr1_min, vr1_max, vr2_min, vr2_max, vr3_min, vr3_max, vr4_min, vr4_max):
with open(configpath, 'r') as f:
content = f.read()
# Automatic edition of Aref
content = re.sub(f'Aref\s*{RE_FLOAT}\s*;', f'Aref {aref:.6f};', content)
# Automatic edition of vri's
content = re.sub(f'vr1_min\s*{RE_VECTOR}\s*;', f'vr1_min {vector2str(vr1_min)};', content)
content = re.sub(f'vr1_max\s*{RE_VECTOR}\s*;', f'vr1_max {vector2str(vr1_max)};', content)
content = re.sub(f'vr2_min\s*{RE_VECTOR}\s*;', f'vr2_min {vector2str(vr2_min)};', content)
content = re.sub(f'vr2_max\s*{RE_VECTOR}\s*;', f'vr2_max {vector2str(vr2_max)};', content)
content = re.sub(f'vr3_min\s*{RE_VECTOR}\s*;', f'vr3_min {vector2str(vr3_min)};', content)
content = re.sub(f'vr3_max\s*{RE_VECTOR}\s*;', f'vr3_max {vector2str(vr3_max)};', content)
content = re.sub(f'vr4_min\s*{RE_VECTOR}\s*;', f'vr4_min {vector2str(vr4_min)};', content)
content = re.sub(f'vr4_max\s*{RE_VECTOR}\s*;', f'vr4_max {vector2str(vr4_max)};', content)
with open(configpath, 'w') as f:
f.write(content)
def copy_template(dst, src="/mnt/cvlab/scratch/cvlab/home/hantzhan/cfd_workflow/template/"):
shutil.copytree(src, dst)
def setup_simulation(simdir, aref_ray=512):
"""Correctly transform the car and compute the config parameters."""
# 1. Verify the existence of a mesh
if not os.path.isfile(os.path.join(simdir, CAR_STL_FILE)):
print(f"File does not exist! ({simdir}) Skipping...")
return
car = trimesh.load(os.path.join(simdir, CAR_STL_FILE))
# 2. Frontal area
aref_pred = find_Aref(car, ray_per_dim=aref_ray)
# 3. Refinement regions
(vr4_min, vr4_max), (vr3_min, vr3_max), (vr2_min, vr2_max), (vr1_min, vr1_max) = get_all_vr(car)
# Edit the config file
edit_config(os.path.join(simdir, "include/config"),
aref_pred,
vr1_min, vr1_max, vr2_min, vr2_max,
vr3_min, vr3_max, vr4_min, vr4_max)
####################################################################################################
# Utilities
####################################################################################################
def get_Cd_sim(simdir, itercheck=2500, average=1000, load_always=False):
"""
Get the drag coefficient from the simulation directory.
itercheck: int (optional)
If given, will verify if the max iteration is the given int.
average: int
If not None, will return the average Cd over the last `average` iters.
load_always: bool
If True, will load the data even if the simulation is not finished.
If return value is negative, then an error has been raised:
-1: Unknown error.
-2: Experiment is not finished.
-3: Problem in loading the force coeff data.
"""
try:
if not os.path.isdir(os.path.join(simdir, "postProcessing")):
print(f"{simdir} might not be finished (no 'postProcessing' folder).")
return -2
# Get data in tabular form
try:
data = []
with open(os.path.join(simdir, "postProcessing/car/0/forceCoeffs.dat")) as file:
for line in file:
if line[0] == '#':
# The last commented line should correspond to column names
names = line[1:].split()
else:
data.append(line.split())
data = np.array(data).astype(float)
if itercheck is not None and len(data)-1 != itercheck:
print(f"WARNING ({simdir}): iteration number is incorrect ({len(data)-1}!={itercheck})!")
if not load_always:
return -2
except ValueError as err:
print(f"Cannot load data from {simdir}: {err}")
return -3
# Extract the drag coeff (optionally average over the last iters)
col = names.index('Cd') if 'Cd' in names else 2
if average is not None:
cd = data[-average:, col].mean()
else:
cd = data[:, col]
return cd
except Exception as err:
print(f"Unknown exception for {simdir}: {err}")
return -1 |