kanydao commited on
Commit
4cf5aa9
·
verified ·
1 Parent(s): ad9f621

Archive CFD workflow 2026-10-12: _seiler_ref (part 2)

Browse files
Files changed (20) hide show
  1. cfd_workflow_20261012/_seiler_ref/drivernet_hunyuan_code/cmd/trellis/0_trellis_gen.sh +2 -0
  2. cfd_workflow_20261012/_seiler_ref/drivernet_hunyuan_code/cmd/trellis/1_give_force.sh +2 -0
  3. cfd_workflow_20261012/_seiler_ref/drivernet_hunyuan_code/cmd/trellis/2_trellis_ours_opt.sh +2 -0
  4. cfd_workflow_20261012/_seiler_ref/drivernet_hunyuan_code/cmd/trellis/3_trellis_physiopt.sh +2 -0
  5. cfd_workflow_20261012/_seiler_ref/drivernet_hunyuan_code/src/drivernet.py +232 -0
  6. cfd_workflow_20261012/_seiler_ref/drivernet_hunyuan_code/src/mesh.py +314 -0
  7. cfd_workflow_20261012/_seiler_ref/drivernet_hunyuan_code/src/optimization.py +258 -0
  8. cfd_workflow_20261012/_seiler_ref/drivernet_hunyuan_code/src/utils.py +375 -0
  9. cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/._run_all_shm.sh +0 -0
  10. cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/U +88 -0
  11. cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/k +60 -0
  12. cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/nut +59 -0
  13. cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/omega +62 -0
  14. cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/p +56 -0
  15. cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/U +88 -0
  16. cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/k +60 -0
  17. cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/nut +59 -0
  18. cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/omega +62 -0
  19. cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/p +55 -0
  20. cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/README.md +2 -0
cfd_workflow_20261012/_seiler_ref/drivernet_hunyuan_code/cmd/trellis/0_trellis_gen.sh ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # cd physiopt_new
2
+ python scripts/sample_trellis.py --image input/0001.png --out_folder output/trellis_gen/0001
cfd_workflow_20261012/_seiler_ref/drivernet_hunyuan_code/cmd/trellis/1_give_force.sh ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # cd physiopt_new
2
+ python scripts/force_web_ui.py --out output/trellis_gen/0001/force_config.json --share --z_up
cfd_workflow_20261012/_seiler_ref/drivernet_hunyuan_code/cmd/trellis/2_trellis_ours_opt.sh ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # cd physiopt_new
2
+ python scripts/viewer_trellis_web_alternate.py --input output/trellis_gen/0001/slat_00.pt --force_config output/trellis_gen/0001/force_config.json --use_physics --res 64 --lr 0.001 --outer_cycles 20 --phys_steps_per_cycle 10 --sds_timestep 0.5 --lagrange_max 10.0 --guidance_scale 3.0 --sds_weight_start 0 --sds_weight_end 0 --sds_use_uncond --sds_target_z0_ema_beta 0.0 --compliance_threshold_ratio 0.1 --youngs_modulus_scale 1.0 --projection_mode inpaint --inpaint_dilate_rings 1 --inpaint_change_threshold 0.1 --inpaint_cfg_strength 5.0 --inpaint_t_start 0.4 --out_folder output/trellis_gen/0001/realforce_alternate --input_coord_system trellis_z_up
cfd_workflow_20261012/_seiler_ref/drivernet_hunyuan_code/cmd/trellis/3_trellis_physiopt.sh ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # cd physiopt_new
2
+ python scripts/viewer_trellis_web_physiopt.py --input output/trellis_gen/0001/slat_00.pt --force_config output/trellis_gen/0001/force_config.json --share --out_folder output/trellis_gen/0001/realforce_physiopt
cfd_workflow_20261012/_seiler_ref/drivernet_hunyuan_code/src/drivernet.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Module for DrivAerNet++ related utilities.
3
+
4
+ See https://github.com/Mohamedelrefaie/DrivAerNet
5
+ """
6
+
7
+ import numpy as np
8
+ import trimesh
9
+
10
+ MESHRAWDIR = "/mnt/cvlab/scratch/cvlab/home/hantzhan/code_jk/fk-doob-physgen/code/data/drivaernet_plus/meshes/3DMeshesSTL/"
11
+ ANNOTDIR = "/scratch/cvlab/datasets/datasets_/drivaernet/Annotations/"
12
+ PRESSUREDIR = "/mnt/cvlab/scratch/cvlab/home/hantzhan/code_jk/fk-doob-physgen/code/data/drivaernet_plus/pressure/PressureVTK/"
13
+
14
+ # Normalization from DrivAerNet++ space to [-0.9, 0.9]^3 cube
15
+ # with x' = s * (R @ x + T)
16
+ T = np.array([(4.1 - 1.05) / 2,
17
+ -0.7,
18
+ 0.0])
19
+ R = np.array([[-1, 0, 0],
20
+ [ 0, 0, 1],
21
+ [ 0, 1, 0]])
22
+ S = 2 * 0.9 / (4.1 + 1.05)
23
+
24
+ BACK_ANNOTS = { # name of the annotation parts corresponding to the back of the car
25
+ "E": ["body_2", "windows_1", "body_roof", "body_tail_1"],
26
+ "F": ["body_1", "windows_1", "body_roof_1", "body_tail_1"],
27
+ "N": ["body_2", "windows_1", "body_roof_1", "body_tail_1"],
28
+ }
29
+
30
+
31
+ def load_clean(path):
32
+ """
33
+ Load a DrivAerNet++ mesh and clean it (normalization + face reorientation).
34
+ """
35
+ mesh = trimesh.load(path)
36
+ mesh = normalize_drivaernet(mesh)
37
+ mesh = reorient(mesh, drivaernet_world=False)
38
+ return mesh
39
+
40
+ def load_clean_bodyback(mesh_path, annot_path, back_type, return_mesh=False):
41
+ """
42
+ Load a DrivAerNet++ example by parts (body / back separation) and normalize it.
43
+
44
+ Args:
45
+ mesh_path: path to the DrivAerNet++ mesh file.
46
+ annot_path: path to the DrivAerNet++ annotation file.
47
+ back_type: car type, one of "E", "F", or "N". (or the full instance name)
48
+ return_mesh: whether to also return the full mesh.
49
+ """
50
+ mesh = trimesh.load(mesh_path)
51
+ annot = trimesh.load(annot_path)
52
+ parts_fit = fit_annot_to_mesh(annot.geometry, mesh)
53
+ # Normalize / clean the meshes into our world space
54
+ mesh = reorient(normalize_drivaernet(mesh), drivaernet_world=False)
55
+ parts_fit = {k: normalize_drivaernet(p) for k, p in parts_fit.items()}
56
+ # Separate body and back
57
+ body, back = split_body_back(back_type, parts_fit, drivaernet_world=False)
58
+ wheels = split_body_wheels(mesh, drivaernet_world=False)[1:]
59
+ parts = [body, back] + wheels
60
+ if return_mesh:
61
+ return parts, mesh
62
+ else:
63
+ return parts
64
+
65
+
66
+ # Normalization
67
+ ###############
68
+
69
+ _R_transform = np.concatenate([R, np.zeros((3, 1))], axis=1)
70
+ _R_transform = np.concatenate([_R_transform, np.array([[0, 0, 0, 1]])], axis=0)
71
+ def normalize_drivaernet(mesh):
72
+ """Normalize mesh/points from DrivAerNet++ space to [-0.9, 0.9]^3 cube.
73
+
74
+ Args:
75
+ mesh: a trimesh object or a (N, 3) array of points.
76
+
77
+ Returns:
78
+ Normalized trimesh object or points.
79
+ """
80
+ if isinstance(mesh, trimesh.Trimesh):
81
+ mesh = mesh.copy()
82
+ mesh.apply_transform(_R_transform)
83
+ mesh.apply_translation(T)
84
+ mesh.apply_scale(S)
85
+ return mesh
86
+ else: # assume it's a (N, 3) array of points
87
+ points = mesh @ R.T
88
+ points = points + T
89
+ points = points * S
90
+ return points
91
+
92
+ def denormalize_drivaernet(mesh):
93
+ """Denormalize mesh/points from [-0.9, 0.9]^3 cube to DrivAerNet++ space.
94
+
95
+ Args:
96
+ mesh: a trimesh object or a (N, 3) array of points.
97
+
98
+ Returns:
99
+ Denormalized trimesh object or points.
100
+ """
101
+ if isinstance(mesh, trimesh.Trimesh):
102
+ mesh.apply_scale(1 / S)
103
+ mesh.apply_translation(-T)
104
+ mesh.apply_transform(_R_transform.T)
105
+ return mesh
106
+ else: # assume it's a (N, 3) array of points
107
+ points = mesh / S
108
+ points = points - T
109
+ points = points @ R
110
+ return points
111
+
112
+ def fit_annot_to_mesh(annot, mesh):
113
+ """Rescale and translate annotation mesh to fit the DrivAerNet++ mesh.
114
+ Must be in the original DrivAerNet++ space!
115
+
116
+ Args:
117
+ annot: dict of trimesh objects of annotation.
118
+ mesh: a trimesh object of DrivAerNet++.
119
+
120
+ Returns:
121
+ Rescaled and translated annotation mesh.
122
+ """
123
+ # Annotations are the half body without wheels
124
+ body = split_body_wheels(mesh)[0]
125
+ # Rescale the annotations from mm to m
126
+ annot = {k: a.copy().apply_scale(1e-3) for k, a in annot.items()}
127
+ # Rescale like the (half-)body
128
+ scale = body.extents / trimesh.util.concatenate(annot.values()).extents
129
+ scale[1] /= 2 # annots are only half a car along the y-axis
130
+ annot = {k: a.apply_scale(scale) for k, a in annot.items()}
131
+ # Translate to the body center
132
+ translation = body.bounds.mean(0) - trimesh.util.concatenate(annot.values()).bounds.mean(0)
133
+ translation[1] = 0 - trimesh.util.concatenate(annot.values()).bounds[1, 1] # annots are only half a car
134
+ annot = {k: a.apply_translation(translation) for k, a in annot.items()}
135
+ return annot
136
+
137
+
138
+ # Face orientation
139
+ ##################
140
+
141
+ def reorient(mesh, drivaernet_world=True):
142
+ """
143
+ Reorient faces of DrivAerNet++ mesh to have outward normals.
144
+ Only the left wheels are correctly oriented in the original meshes.
145
+ NOTE: the F_D instances (from DrivAerNet) are already correctly oriented.
146
+ However, as they don't have parts, we are not considering them here.
147
+ """
148
+ parts = split_body_wheels(mesh, drivaernet_world=drivaernet_world)
149
+ parts = reorient_parts(parts)
150
+ return trimesh.util.concatenate(parts)
151
+
152
+ def reorient_parts(parts):
153
+ """
154
+ Reorient faces of DrivAerNet++ mesh parts to have outward normals.
155
+ Only the left wheels are correctly oriented in the original meshes.
156
+ """
157
+ for i, part in enumerate(parts):
158
+ if i in [1, 3]: # left wheels
159
+ continue
160
+ part.invert()
161
+ return parts
162
+
163
+
164
+ # Mesh parts
165
+ ############
166
+
167
+ def split_body_wheels(mesh, drivaernet_world=True):
168
+ """
169
+ Split DrivAerNet++ mesh into body and wheels parts.
170
+ Wheel order: FL, FR, RL, RR.
171
+
172
+ Args:
173
+ mesh: a trimesh object of DrivAerNet++.
174
+ drivaernet_world: whether the mesh is in DrivAerNet++ world space,
175
+ or normalized space.
176
+
177
+ Returns:
178
+ list of 5 meshes.
179
+ """
180
+ parts = mesh.split()
181
+ assert len(parts) == 5, "Expected 5 parts (body + 4 wheels)."
182
+
183
+ # Identify the body as the largest part (bbox-wise)
184
+ body_idx = np.argmax([np.prod(p.extents) for p in parts])
185
+ body = parts[body_idx]
186
+ wheels = [parts[i] for i in range(5) if i != body_idx]
187
+
188
+ # Sort wheels by position (x, y) for drivaernet world, (-x, z) otherwise
189
+ # Front then rear wheels
190
+ wheels.sort(key=lambda w: w.bounds.mean(0)[0],
191
+ reverse=not drivaernet_world)
192
+ # Left then right wheels in each axle
193
+ ax = 1 if drivaernet_world else 2
194
+ if wheels[0].bounds.mean(0)[ax] > wheels[1].bounds.mean(0)[ax]:
195
+ wheels[0], wheels[1] = wheels[1], wheels[0]
196
+ if wheels[2].bounds.mean(0)[ax] > wheels[3].bounds.mean(0)[ax]:
197
+ wheels[2], wheels[3] = wheels[3], wheels[2]
198
+
199
+ return [body] + wheels
200
+
201
+ def split_body_back(back_type, annot, drivaernet_world=True):
202
+ """
203
+ Split DrivAerNet++ annotation parts into body and back parts.
204
+
205
+ Args:
206
+ back_type: car type, one of "E", "F", or "N". (or the full instance name)
207
+ annot: dict of trimesh objects, named as in the annotation STL file.
208
+ drivaernet_world: whether the annots are in DrivAerNet++ or normalized space.
209
+
210
+ Returns:
211
+ body and back meshes.
212
+ """
213
+ back_type = back_type[0] # in case full instance name is given
214
+ body, back = [], []
215
+ for key, part in annot.items():
216
+ if key in BACK_ANNOTS[back_type]:
217
+ back.append(part)
218
+ else:
219
+ body.append(part)
220
+ body = trimesh.util.concatenate(body)
221
+ back = trimesh.util.concatenate(back)
222
+ # Mirror them as the annotations are given for the left half of the car
223
+ body2 = body.copy()
224
+ back2 = back.copy()
225
+ ax = 1 if drivaernet_world else 2
226
+ body2.vertices[:, ax] = -body2.vertices[:, ax]
227
+ back2.vertices[:, ax] = -back2.vertices[:, ax]
228
+ body2.invert()
229
+ back2.invert()
230
+ body = trimesh.util.concatenate([body, body2])
231
+ back = trimesh.util.concatenate([back, back2])
232
+ return body, back
cfd_workflow_20261012/_seiler_ref/drivernet_hunyuan_code/src/mesh.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Module for creating and dealing with meshes.
3
+ """
4
+
5
+ import time
6
+
7
+ import numpy as np
8
+ import trimesh
9
+ from skimage.measure import marching_cubes
10
+ import torch
11
+
12
+ from .utils import make_grid, compute_sdf, get_device
13
+
14
+
15
+ @torch.no_grad()
16
+ def create_mesh(model, idx, latents=None, N=256, max_batch=32**3, verbose=False, grid_filler=False, device=get_device(),
17
+ occ_tau=0.1, **model_kwargs):
18
+ """
19
+ Reconstruct the mesh from the latent vector(s).
20
+
21
+ Args:
22
+ model (nn.Module): INR model.
23
+ latent (torch.Tensor): latent vector(s) of the shape to mesh.
24
+ N (int): resolution of the grid.
25
+ max_batch (int): maximum batch size for predictions.
26
+ verbose (bool): enable verbosity.
27
+ grid_filler (bool or SdfGridFiller): whether to use an SdfGridFiller.
28
+ device (str or Device): device to use.
29
+ occ_tau (float): temperature scaling for occupancy (if relevant).
30
+ model_kwargs (dict): additional keyword arguments for the model, such as pose.
31
+ """
32
+ use_occ = hasattr(model, 'use_occ') and model.use_occ # whether to use occupancy instead of SDF
33
+ # Compute the SDF values on a grid (fast or exact)
34
+ if not use_occ and isinstance(grid_filler, SdfGridFiller):
35
+ sdf_grid = grid_filler.fill_grid(grid_filler.make_sdf_func(model, idx, latents=latents, max_batch=max_batch, **model_kwargs), verbose=verbose)
36
+ N = grid_filler.N_max
37
+ elif not use_occ and grid_filler:
38
+ gf = SdfGridFiller(N, device="cpu")
39
+ sdf_grid = gf.fill_grid(gf.make_sdf_func(model, idx, latents=latents, max_batch=max_batch, **model_kwargs), device="cpu", verbose=verbose)
40
+ else:
41
+ sdf_grid = compute_sdf_grid(model, idx, latents=latents, N=N, max_batch=max_batch, verbose=verbose, device=device, **model_kwargs)
42
+ # Marching cubes
43
+ if use_occ:
44
+ level, gradient_direction = 0.5, 'ascent'
45
+ sdf_grid = torch.sigmoid(sdf_grid * occ_tau) # temperature scaling to smoothen Marching-Cubes results
46
+ else:
47
+ level, gradient_direction = 0., 'descent'
48
+ mesh = convert_sdf_grid_to_mesh(sdf_grid, voxel_size=2. / (N - 1), level=level, gradient_direction=gradient_direction)
49
+ return mesh
50
+
51
+
52
+ @torch.no_grad()
53
+ def create_parts(model, latent, N=256, max_batch=32**3, verbose=False, grid_filler=False, device=get_device(),
54
+ occ_tau=0.1, **model_kwargs):
55
+ """
56
+ Reconstruct the individual parts from the latent vector(s).
57
+
58
+ Args:
59
+ model (nn.Module): INR model.
60
+ latent (torch.Tensor): latent vector(s) of the shape to mesh.
61
+ N (int): resolution of the grid.
62
+ max_batch (int): maximum batch size for predictions.
63
+ verbose (bool): enable verbosity.
64
+ grid_filler (bool or SdfGridFiller): whether to use an SdfGridFiller.
65
+ device (str or Device): device to use.
66
+ occ_tau (float): temperature scaling for occupancy (if relevant).
67
+ model_kwargs (dict): additional keyword arguments for the model, such as pose.
68
+ """
69
+ use_occ = hasattr(model, 'use_occ') and model.use_occ # whether to use occupancy instead of SDF
70
+ # Compute the SDF values on a grid (fast or exact)
71
+ if use_occ or not grid_filler:
72
+ sdf_grid = compute_sdf_grid(model, latent, N=N, return_parts=True, max_batch=max_batch,
73
+ verbose=verbose, device=device, **model_kwargs)
74
+ else:
75
+ if not isinstance(grid_filler, SdfGridFiller):
76
+ grid_filler = SdfGridFiller(N, device="cpu")
77
+ sdf_grid = torch.stack([
78
+ grid_filler.fill_grid(grid_filler.make_sdf_func(model, latent, max_batch, i, **model_kwargs), device="cpu", verbose=verbose)
79
+ for i in range(model.n_parts)
80
+ ], dim=-1)
81
+ N = grid_filler.N_max
82
+ # Marching cubes
83
+ if use_occ:
84
+ level, gradient_direction = 0.5, 'ascent'
85
+ sdf_grid = torch.sigmoid(sdf_grid * occ_tau) # temperature scaling to smoothen Marching-Cubes results
86
+ else:
87
+ level, gradient_direction = 0., 'descent'
88
+ parts = [convert_sdf_grid_to_mesh(sdf_grid[..., i], voxel_size=2. / (N - 1), level=level, gradient_direction=gradient_direction)
89
+ for i in range(sdf_grid.shape[-1])]
90
+ return parts
91
+
92
+
93
+ def compute_sdf_grid(model, idx, latents=None, N=256, max_batch=32**3, bbox=[(-1., -1., -1.), (1., 1., 1.)],
94
+ return_parts=False, verbose=False, device=get_device(), **model_kwargs):
95
+ """
96
+ Compute the SDF values over a grid in the given bounding box.
97
+
98
+ Args:
99
+ model (nn.Module): INR model.
100
+ latent (torch.Tensor): latent vector(s) of the shape.
101
+ N (int): resolution of the grid.
102
+ max_batch (int): maximum batch size for predictions.
103
+ bbox (list): bounding box of the grid, a list of the min and max coordinates.
104
+ return_parts (bool): whether to return the parts SDFs.
105
+ verbose (bool): enable verbosity.
106
+ device (str or Device): device to use.
107
+ model_kwargs (dict): additional keyword arguments for the model, such as pose.
108
+ """
109
+ # Create points on a grid
110
+ xyz = make_grid(bbox, N, device=device)
111
+
112
+ # Predict the SDF values on the grid
113
+ sdf = compute_sdf(model, idx, xyz, return_parts=return_parts, max_batch=max_batch, verbose=verbose, latents=latents, device=device, **model_kwargs)
114
+ return sdf.squeeze(-1)
115
+
116
+
117
+ def convert_sdf_grid_to_mesh(sdf_grid, voxel_size=1., voxel_origin=[-1., -1., -1.], level=0.,
118
+ gradient_direction='descent', trimesh_process=True):
119
+ """
120
+ Convert the grid of SDF values to a mesh.
121
+
122
+ Args:
123
+ sdf_grid (torch.Tensor or np.ndarray): grid of SDF values.
124
+ voxel_size (float or list): size of the voxels.
125
+ voxel_origin (list): origin of the voxel grid.
126
+ level (float): level to extract the mesh.
127
+ gradient_direction (str): direction of the gradient ('descent' for SDF, 'ascent' for OCC).
128
+ trimesh_process (bool): whether to process the mesh with trimesh.
129
+ """
130
+ if not isinstance(sdf_grid, np.ndarray):
131
+ sdf_grid = sdf_grid.detach().cpu().numpy()
132
+ if isinstance(voxel_size, (int, float)):
133
+ voxel_size = [voxel_size] * 3
134
+
135
+ try:
136
+ verts, faces, _, _ = marching_cubes(sdf_grid, level=level, spacing=voxel_size,
137
+ gradient_direction=gradient_direction)
138
+ verts += np.array(voxel_origin)
139
+ except ValueError: # no surface within range
140
+ verts, faces = None, None
141
+
142
+ return trimesh.Trimesh(verts, faces, process=trimesh_process)
143
+
144
+
145
+ class SdfGridFiller():
146
+ """
147
+ Smart grid filler that starts at low resolution and go up by querying coordinates
148
+ where the SDF is low instead of the whole grid.
149
+
150
+ Adapted from Benoit Guillard.
151
+ """
152
+
153
+ def __init__(self, N_max, device=get_device()):
154
+ """
155
+ Initialize the grid filler.
156
+
157
+ Construct grid and precompute sparse masks, from 32 to N_max.
158
+
159
+ Args:
160
+ -----
161
+ N_max : int
162
+ Maximum resolution of the grid.
163
+ device: str or Device (default=cuda if available)
164
+ Device where the xyz coords are stored (trade-off memory vs computation).
165
+ """
166
+ # Save attributes
167
+ self.N_max = N_max
168
+
169
+ # Create the coords grid (N,N,N,3) where 3 = x,y,z
170
+ xyz = make_grid([(-1., -1., -1.), (1., 1., 1.)], N_max)
171
+ xyz.pin_memory()
172
+ self.xyz = xyz.reshape(-1, 3).to(device)
173
+
174
+ # Precompute binary masks for sparsely adressing the above grid
175
+ self.N_levels = [32 * (2**i) for i in range(int(np.log2(N_max) - 4))] # Minimum level = 32
176
+ mask = torch.zeros((N_max, N_max, N_max), dtype=bool, pin_memory=True)
177
+ # Fill dictionaries with precomputed masks
178
+ self.masks_coarse = {}
179
+ self.masks_coarse_no_recompute = {}
180
+ self.idxs_coarse_neighbors_blocks = {}
181
+ for i, N in enumerate(self.N_levels):
182
+ step = N_max // N
183
+ #### 1: Subsample coarsely
184
+ mask_coarse = mask.clone()
185
+ mask_coarse[::step, ::step, ::step] = True
186
+ # (N_max**3) array, with True only for indices of the coarse sampling (N**3 locations):
187
+ mask_coarse = mask_coarse.reshape(-1)
188
+ self.masks_coarse[i] = mask_coarse.clone().to(self.xyz.device)
189
+
190
+ #### 2: Compute the idxs of neighboring blocks
191
+ neighbors_block_coarse = mask.clone()
192
+ neighbors_block_coarse[:step, :step, :step] = True
193
+ neighbors_block_coarse = neighbors_block_coarse.reshape(-1)
194
+ # Shape (N_max**3 // N, N): idxs_coarse_neighbors_blocks[i] represents the (N_max // N)**3 indexes covered by coarse point i
195
+ idxs_coarse_neighbors_blocks = torch.where(mask_coarse)[0].reshape(-1,1) + torch.where(neighbors_block_coarse)[0].reshape(1,-1)
196
+ self.idxs_coarse_neighbors_blocks[i] = idxs_coarse_neighbors_blocks.clone().to(self.xyz.device)
197
+
198
+ #### 3: If at a level >0, do not recompute already queried SDFs
199
+ if i > 0:
200
+ mask_coarse_no_recompute = mask_coarse.clone()
201
+ mask_coarse_no_recompute[self.masks_coarse[i-1]] = False
202
+ self.masks_coarse_no_recompute[i] = mask_coarse_no_recompute.clone().to(self.xyz.device)
203
+
204
+
205
+ @torch.no_grad()
206
+ def fill_grid(self, sdf_func, return_queries=False, device=get_device(), verbose=False):
207
+ """
208
+ Fill the SDF grid by increasing resolution.
209
+
210
+ Args:
211
+ -----
212
+ sdf_func: callable (N, 3) -> (N)
213
+ Function that takes a batch of coordinates and returns the SDF values.
214
+ return_queries: bool (default=False)
215
+ Also return the number of queried points.
216
+ device: str (default="cuda:0" if available)
217
+ Device where the SDF grid is stored.
218
+
219
+ Returns:
220
+ --------
221
+ sdf_values: torch.Tensor, shape (N_max, N_max, N_max)
222
+ The SDF values on the grid.
223
+ queries_number: int (optional, if return_queries)
224
+ The number of queries made to the network.
225
+ """
226
+ if verbose:
227
+ start_time = time.time()
228
+ if return_queries:
229
+ queries_number = 0
230
+
231
+ sdf_values = torch.zeros(len(self.xyz), device=device)
232
+ close_surface_masks = {}
233
+ idxs_coarse_neighbors_blocks_LOCAL = {}
234
+ for level, N in enumerate(self.N_levels):
235
+ # Prepare masks based on previous levels
236
+ if level == 0:
237
+ mask_coarse = self.masks_coarse[level]
238
+ idxs_coarse_neighbors_blocks = self.idxs_coarse_neighbors_blocks[level].clone()
239
+ mask_coarse_no_recompute = self.masks_coarse[level]
240
+ else:
241
+ # Mask using previous queries
242
+ # binary mask
243
+ mask_coarse = self.masks_coarse[level].clone()
244
+ for l in range(level):
245
+ mask_coarse[idxs_coarse_neighbors_blocks_LOCAL[l][~close_surface_masks[l]]] = False
246
+ # idx tensor
247
+ if N < self.N_max:
248
+ idxs_coarse_neighbors_blocks = self.idxs_coarse_neighbors_blocks[level].clone()
249
+ idxs_coarse_neighbors_blocks = idxs_coarse_neighbors_blocks[mask_coarse[self.masks_coarse[level]]]
250
+ else:
251
+ idxs_coarse_neighbors_blocks = self.idxs_coarse_neighbors_blocks[level]
252
+ # The no_recompute version does not re-query the decoder for nodes that have already been (1/8th is saved)
253
+ mask_coarse_no_recompute = self.masks_coarse_no_recompute[level].clone()
254
+ for l in range(level):
255
+ mask_coarse_no_recompute[idxs_coarse_neighbors_blocks_LOCAL[l][~close_surface_masks[l]]] = False
256
+
257
+ idxs_coarse_neighbors_blocks_LOCAL[level] = idxs_coarse_neighbors_blocks
258
+ # Query the network
259
+ if return_queries:
260
+ queries_number += mask_coarse_no_recompute.sum().item() # count the total number of network queries
261
+ xyz = self.xyz[mask_coarse_no_recompute]
262
+ # Query + fill grid
263
+ sdf_values[mask_coarse_no_recompute] = sdf_func(xyz).detach().to(device)
264
+
265
+ # Prepare next levels queries
266
+ if N < self.N_max:
267
+ ## Which samples are close to the surface? (NOTE: where do current thresholds come from?)
268
+ STEP_SIZE = 2. / N
269
+ close_surface_mask = (torch.abs(sdf_values[mask_coarse.to(device)]) < 1.5 * 1.7 * STEP_SIZE)
270
+ close_surface_masks[level] = close_surface_mask
271
+ # For those far of the surface, we can ignore them for the future
272
+ # and copy the high value to their neighbors
273
+ sdf_values[idxs_coarse_neighbors_blocks[~close_surface_mask]] = sdf_values[mask_coarse.to(device)][~close_surface_mask].unsqueeze(-1)
274
+
275
+ sdf_values = sdf_values.reshape(self.N_max, self.N_max, self.N_max)
276
+ if verbose:
277
+ print(f"sdf-prediction took {time.time() - start_time:.3f}s.")
278
+ if return_queries:
279
+ return sdf_values, queries_number
280
+ return sdf_values
281
+
282
+
283
+ @torch.no_grad()
284
+ def make_sdf_func(self, model, idx, latents=None, max_batch=32**3, part_idx=None, device=get_device(), **model_kwargs):
285
+ """Make an SDF function out of a model and latent vector."""
286
+ if idx.dim() == 0:
287
+ idx = idx.unsqueeze(0).to(device)
288
+
289
+ def sdf_func(xyz, latents=latents, max_batch=max_batch):
290
+ model.eval()
291
+
292
+ # Prepare data
293
+ xyz_all = xyz.view(-1, 3)
294
+ n_points = len(xyz_all)
295
+ sdf = torch.zeros(n_points, device=device)
296
+ # Predict SDF on a subset of points at a time
297
+ for i in range(0, n_points, max_batch):
298
+ xyz_subset = xyz_all[i : i + max_batch].to(device).unsqueeze(0)
299
+ if part_idx is not None:
300
+ sdf[i : i + max_batch] = model(idx, xyz_subset, latents=latents, return_parts=True, **model_kwargs).squeeze().detach().to(device)
301
+ else:
302
+ sdf[i : i + max_batch] = model(idx, xyz_subset, latents=latents, **model_kwargs).squeeze().detach().to(device)
303
+
304
+ return sdf.view(xyz.shape[:-1])
305
+
306
+ return sdf_func
307
+
308
+
309
+ @torch.no_grad()
310
+ def make_mesh(self, sdf_func, return_queries=False, device=get_device(), verbose=False):
311
+ """Mesh an SDF function."""
312
+ sdf_grid = self.fill_grid(sdf_func, return_queries=return_queries,
313
+ device=device, verbose=verbose)
314
+ return convert_sdf_grid_to_mesh(sdf_grid, voxel_size=2. / (self.N_max - 1))
cfd_workflow_20261012/_seiler_ref/drivernet_hunyuan_code/src/optimization.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import trimesh
2
+ import numpy as np
3
+ import torch
4
+ import json
5
+ import sys
6
+ import os
7
+
8
+ from src.mesh import SdfGridFiller, create_mesh
9
+
10
+ sys.path.append("/mnt/cvlab/scratch/cvlab/home/hantzhan/surrogates/Transolver/")
11
+ from TransolverNeMo.transolver import Transolver # type: ignore
12
+
13
+
14
+ DEFAULT_SPECS_PATH = {"Transolver_Drivernet": "/mnt/cvlab/scratch/cvlab/home/hantzhan/surrogates/Transolver/experiments/drivaernet/transolver_S/specs.json"}
15
+ DEFAULT_MODEL_PATH = {"Transolver_Drivernet": "/mnt/cvlab/scratch/cvlab/home/hantzhan/surrogates/Transolver/experiments/drivaernet/transolver_S/model/model_100.pth"}
16
+
17
+ DATASET_CONSTANTS = {
18
+ "DriverNet": {
19
+ "RHO": 1.184,
20
+ "MAGUINF": 30.,
21
+ "P_MAX": 2000,
22
+ "P_MEAN": -93.39186,
23
+ "P_STD": 120.2923,
24
+ "CD_MEAN": 0.26285287093925974,
25
+ "CD_STD": 0.020127521964890926,
26
+ "T_TRANSFORM": np.array([(4.1 - 1.05) / 2, -0.7, 0.0]),
27
+ "R_TRANSFORM": np.array([[-1, 0, 0], [0, 0, 1], [0, 1, 0]]),
28
+ "S_TRANSFORM": 2 * 0.9 / (4.1 + 1.05)
29
+ }
30
+ }
31
+
32
+ RHO=1.184
33
+ MAGUINF=30
34
+ P_MAX=2000
35
+ P_MEAN= -93.39186
36
+ P_STD= 120.2923
37
+ CD_MEAN= 0.26285287093925974
38
+ CD_STD= 0.020127521964890926
39
+ T_DRIVAERNET= torch.tensor([(4.1 - 1.05) / 2, -0.7, 0.0]).to("cuda").float()
40
+ R_DRIVAERNET= torch.tensor([[-1, 0, 0], [0, 0, 1], [0, 1, 0]]).to("cuda").float()
41
+ S_DRIVAERNET= 2 * 0.9 / (4.1 + 1.05)
42
+
43
+ def load_surr_model(device: str = "cuda"):
44
+ surr_specs = {"SurrogateType" : "Transolver_Drivernet",
45
+ "OptimizationArgs" : {
46
+ "drag_weight": 1,
47
+ "VoxelGrid": [64, 64, 64],
48
+ "norm_drag": True,
49
+ "Aref_init": 1,
50
+ "drivernet": True
51
+ }}
52
+ model_path = DEFAULT_MODEL_PATH["Transolver_Drivernet"]
53
+ specs_path = DEFAULT_SPECS_PATH["Transolver_Drivernet"]
54
+ if not os.path.exists(specs_path) or not os.path.exists(model_path):
55
+ raise FileNotFoundError(f"File not found: {specs_path} or {model_path}")
56
+
57
+ with open(specs_path, 'r') as f:
58
+ surr_specs = json.load(f)
59
+
60
+ surr_model = Transolver(**surr_specs["ModelParameters"], use_te=False).to(device)
61
+ state_dict = torch.load(model_path, map_location=device)
62
+ surr_model.load_state_dict(state_dict)
63
+
64
+ surr_model.eval()
65
+ for p in surr_model.parameters():
66
+ p.requires_grad = False
67
+ return surr_specs, surr_model
68
+
69
+ # def surr_predict_mesh(mesh, model, verts=None, device="cuda", max_points=500_000):
70
+ # verts = verts.to(device) if verts is not None else torch.from_numpy(mesh.vertices).float().clone().to(device)
71
+ # normals = torch.from_numpy(mesh.vertex_normals).float().clone().to(device)
72
+ # if max_points is not None and len(verts) > max_points:
73
+ # indices = torch.randperm(len(verts))[:max_points]
74
+ # verts = verts[indices]
75
+ # normals = normals[indices]
76
+ # # Denormalize into DrivAerNet++ space (expected by the surrogate)
77
+
78
+ # verts = (verts / S_DRIVAERNET - T_DRIVAERNET) @ R_DRIVAERNET
79
+ # normals = normals @ R_DRIVAERNET
80
+ # data = torch.cat([verts, normals, torch.zeros_like(verts[..., :1])], dim=-1).unsqueeze(0)
81
+ # out = model(torch.empty_like(data[..., :0]), data)
82
+ # if hasattr(model, "scalar_decoder") and model.scalar_decoder:
83
+ # return out[0][0, ..., 0] * P_STD + P_MEAN, out[1][0, ..., 0] * CD_STD + CD_MEAN
84
+ # else:
85
+ # return out[0, ..., 0] * P_STD + P_MEAN
86
+
87
+ def surr_predict_mesh(mesh, model, verts=None, device="cuda", max_points=500_000):
88
+ verts = verts.to(device) if verts is not None else torch.from_numpy(mesh.vertices).float().clone().to(device)
89
+ normals = torch.from_numpy(mesh.vertex_normals).float().clone().to(device)
90
+
91
+ if max_points is not None and len(verts) > max_points:
92
+ indices = torch.randperm(len(verts))[:max_points]
93
+ verts = verts[indices]
94
+ normals = normals[indices]
95
+
96
+ # ==========================================
97
+ # FUSION DES TRANSFORMATIONS (Sans gradients)
98
+ # ==========================================
99
+ with torch.no_grad():
100
+ v_min, _ = verts.min(dim=0)
101
+ v_max, _ = verts.max(dim=0)
102
+ bbox_center = (v_max + v_min) / 2.0
103
+ max_extent = (v_max - v_min).max()
104
+
105
+ # 1. Mise à l'échelle combinée (Hunyuan -> 0.9 -> DrivAer)
106
+ scale_factor = 1.8 / max_extent
107
+ combined_scale = scale_factor / S_DRIVAERNET
108
+
109
+ # 2. Matrice d'inversion X
110
+ F = torch.tensor([[-1., 0., 0.],
111
+ [ 0., 1., 0.],
112
+ [ 0., 0., 1.]], device=device)
113
+
114
+ # 3. MATRICE COMBINÉE M (Echelle + Flip + Rotation)
115
+ # On multiplie les matrices : Scale * (Flip @ Rotation)
116
+ M = combined_scale * (F @ R_DRIVAERNET)
117
+
118
+ # 4. TRANSLATION COMBINÉE T (Centrage + Translation DrivAer + Rotation)
119
+ flip_vector = torch.tensor([-1., 1., 1.], device=device)
120
+ center_scaled_flipped = bbox_center * combined_scale * flip_vector
121
+ T_final = - (center_scaled_flipped + T_DRIVAERNET) @ R_DRIVAERNET
122
+
123
+ # 5. Matrice pour les normales (Seulement Flip + Rotation, l'échelle uniforme ne change pas la direction)
124
+ M_normals = F @ R_DRIVAERNET
125
+
126
+ # ==========================================
127
+ # APPLICATION EN UNE FOIS (Avec gradients)
128
+ # ==========================================
129
+
130
+ verts_drivaer = verts @ M + T_final
131
+ normals_drivaer = normals @ M_normals
132
+
133
+ # ==========================================
134
+ # Prédiction du modèle
135
+ # ==========================================
136
+ data = torch.cat([verts_drivaer, normals_drivaer, torch.zeros_like(verts_drivaer[..., :1])], dim=-1).unsqueeze(0)
137
+ out = model(torch.empty_like(data[..., :0]), data)
138
+
139
+ if hasattr(model, "scalar_decoder") and model.scalar_decoder:
140
+ return out[0][0, ..., 0] * P_STD + P_MEAN, out[1][0, ..., 0] * CD_STD + CD_MEAN
141
+ else:
142
+ return out[0, ..., 0] * P_STD + P_MEAN
143
+
144
+
145
+ def get_vector_areas(vertices, faces):
146
+ """
147
+ Get the vector areas of the mesh defined by its vertices and faces:
148
+ s_i = n_i * a_i = AB x AC / 2
149
+ with n_i the normal and a_i the surface of the face; ABC are the vertices of the
150
+ triangle and 'x' is the cross operator.
151
+ """
152
+ return torch.cross(vertices[faces[:,1]] - vertices[faces[:,0]],
153
+ vertices[faces[:,2]] - vertices[faces[:,0]]) / 2
154
+
155
+
156
+ def find_Aref(mesh, ray_per_dim=512):
157
+ """Approximate frontal area by intersecting rays."""
158
+ y_min, y_max = mesh.bounds[:,1]
159
+ z_min, z_max = mesh.bounds[:,2]
160
+ yz_area = (y_max - y_min) * (z_max - z_min)
161
+ YZ = np.stack(np.meshgrid(
162
+ np.linspace(y_min, y_max, ray_per_dim),
163
+ np.linspace(z_min, z_max, ray_per_dim),
164
+ indexing='xy'
165
+ ), axis=-1).reshape(-1, 2)
166
+ YZ = np.concatenate([np.full_like(YZ[:,0:1], 2), YZ], axis=1)
167
+
168
+ intersections = mesh.ray.intersects_any(YZ, [[-1,0,0]]* len(YZ))
169
+ return yz_area * intersections.mean()
170
+
171
+
172
+ def get_drag_loss(p, verts, faces, rho, magUInf, Aref=None, norm=False):
173
+ """
174
+ Compute the (pressure) drag coefficient of the mesh and its pressure field.
175
+ Note: rho and magUInf are now explicit required arguments.
176
+ """
177
+ p_faces = p[faces].mean(-1, keepdims=True)
178
+ vector_areas = get_vector_areas(verts, faces)
179
+ p_force = - rho * p_faces * vector_areas
180
+ Fd = torch.abs(p_force[:, 0].sum())
181
+ if norm:
182
+ Aref = find_Aref(trimesh.Trimesh(verts.detach().cpu().numpy(), faces.detach().cpu().numpy()), 256) if Aref is None else Aref
183
+ return 2 * Fd / (rho * magUInf * magUInf * Aref)
184
+ else:
185
+ return Fd
186
+
187
+
188
+ def get_Aref_init(model, idx_sample, device, latents=None):
189
+ """
190
+ Compute the reference area A_ref for a given shape represented by an SDF model.
191
+
192
+ The reference area is estimated from the initial mesh extracted from the SDF
193
+ and is typically used to normalize aerodynamic quantities (e.g. drag coefficient).
194
+
195
+ Args:
196
+ model: Trained SDF model.
197
+ idx_sample: Index (or latent code index) of the shape to evaluate.
198
+ device: Torch device ("cpu" or "cuda").
199
+
200
+ Returns:
201
+ Aref_init (float): Reference area of the initial shape.
202
+ """
203
+ grid_filler = SdfGridFiller(N_max = 128, device=device)
204
+
205
+ mesh_init = create_mesh(model, idx=idx_sample, latents=latents, N=grid_filler.N_max, grid_filler=grid_filler)
206
+
207
+ Aref_init = find_Aref(mesh_init, 256)
208
+ return Aref_init
209
+
210
+
211
+ def compute_drag(xyz, model, index_samples, latents=None, device="cuda", only_drag=False, **kwargs):
212
+ # Extract kwargs
213
+ surr_model = kwargs.get("surr_model")
214
+ grid_filler = kwargs.get("grid_filler")
215
+ Aref_init = kwargs.get("Aref_init", None)
216
+ norm_drag = kwargs.get("norm_drag", True)
217
+
218
+ const = DATASET_CONSTANTS["DriverNet"]
219
+ # Build mesh from SDF
220
+ mesh = grid_filler.make_mesh(
221
+ grid_filler.make_sdf_func(model, index_samples, latents=latents)
222
+ )
223
+ verts = torch.from_numpy(mesh.vertices).float().to(device).requires_grad_(True)
224
+ faces = torch.from_numpy(mesh.faces).to(device)
225
+
226
+ # Forward drag prediction
227
+ p_pred = surr_predict_mesh(mesh=mesh, model=surr_model, device=device, verts=verts)
228
+
229
+ # Pass the correct physical constants to the drag calculation
230
+ drag = get_drag_loss(
231
+ p_pred, verts, faces,
232
+ rho=const["RHO"],
233
+ magUInf=const["MAGUINF"],
234
+ Aref=Aref_init,
235
+ norm=norm_drag
236
+ )
237
+
238
+ target_drag = kwargs.get("target_drag", None)
239
+ if target_drag is not None:
240
+ if not isinstance(target_drag, torch.Tensor):
241
+ target_drag = torch.tensor([target_drag], device=device, dtype=torch.float32)
242
+
243
+ loss_drag_optim = torch.pow(drag - target_drag, 2)
244
+ else:
245
+ loss_drag_optim = drag
246
+ # ---------------------------------------------------------
247
+
248
+ if not only_drag:
249
+ dL_dv = torch.autograd.grad(loss_drag_optim, verts, retain_graph=True)[0].detach()
250
+
251
+ sdf_pred = model(index_samples, verts.unsqueeze(0), latents=latents)
252
+ grad_sdf = torch.autograd.grad(sdf_pred.sum(), verts, retain_graph=True)[0]
253
+ normals = grad_sdf / (grad_sdf.norm(dim=1, keepdim=True) + 1e-8)
254
+ dL_ds = - torch.sum(dL_dv * normals, dim=-1, keepdim=True)
255
+ loss = torch.sum(dL_ds.detach() * sdf_pred)
256
+ return loss, drag
257
+ else:
258
+ return drag
cfd_workflow_20261012/_seiler_ref/drivernet_hunyuan_code/src/utils.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utilities module.
3
+ """
4
+
5
+ import sys
6
+ import random
7
+ import logging
8
+ import io
9
+ import time
10
+ import colorsys
11
+
12
+ import numpy as np
13
+ import matplotlib.pyplot as plt
14
+ from matplotlib import colormaps
15
+ from PIL import Image
16
+ import igl
17
+ import torch
18
+
19
+ import torch.nn.functional as F
20
+
21
+ ###########
22
+ # General #
23
+ ###########
24
+
25
+ def set_seed(seed):
26
+ """Set the manual seeds for python, numpy, and pytorch."""
27
+ random.seed(seed)
28
+ np.random.seed(seed)
29
+ torch.manual_seed(seed)
30
+ torch.cuda.manual_seed_all(seed)
31
+
32
+
33
+ def get_device():
34
+ """Get the device to use for computation."""
35
+ if torch.cuda.is_available():
36
+ device = torch.device("cuda")
37
+ elif torch.backends.mps.is_available() and torch.backends.mps.is_built():
38
+ device = torch.device("mps")
39
+ else:
40
+ device = torch.device("cpu")
41
+ return device
42
+
43
+
44
+ def unwrap_model(model):
45
+ """Return the underlying model if wrapped in DataParallel or DDP."""
46
+ if isinstance(model, (torch.nn.DataParallel, torch.nn.parallel.DistributedDataParallel)):
47
+ return model.module
48
+ return model
49
+
50
+
51
+ def configure_logging(args=None, logfile=None):
52
+ logger = logging.getLogger()
53
+
54
+ if logger.hasHandlers():
55
+ logger.handlers.clear()
56
+ if args is None:
57
+ logger.setLevel(logging.INFO)
58
+ elif "debug" in args and args.debug:
59
+ logger.setLevel(logging.DEBUG)
60
+ elif "verbose" in args and not args.verbose:
61
+ logger.setLevel(logging.WARNING)
62
+ else:
63
+ logger.setLevel(logging.INFO)
64
+
65
+ # Edit display of level names
66
+ for level, levelname in zip([logging.CRITICAL, logging.ERROR, logging.WARNING, logging.DEBUG],
67
+ ['CRITICAL', 'ERROR', 'WARNING', 'DEBUG']):
68
+ logging.addLevelName(level, levelname + ': ')
69
+ logging.addLevelName(logging.INFO, '')
70
+ formatter = logging.Formatter("%(levelname)s%(message)s")
71
+
72
+ # Log in stream
73
+ logger_handler = logging.StreamHandler()
74
+ logger_handler.setFormatter(formatter)
75
+ logger.addHandler(logger_handler)
76
+
77
+ # Log in file
78
+ if logfile is not None:
79
+ file_logger_handler = logging.FileHandler(logfile)
80
+ file_logger_handler.setFormatter(formatter)
81
+ logger.addHandler(file_logger_handler)
82
+
83
+ # Automatically log exceptions
84
+ def handle_exception(exc_type, exc_value, exc_traceback):
85
+ if issubclass(exc_type, KeyboardInterrupt):
86
+ sys.__excepthook__(exc_type, exc_value, exc_traceback)
87
+ return
88
+ logger.critical("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
89
+ sys.excepthook = handle_exception
90
+
91
+ # Deal with verbose loggers
92
+ plt.set_loglevel(level='info')
93
+ pil_logger = logging.getLogger('PIL')
94
+ pil_logger.setLevel(logging.INFO)
95
+
96
+
97
+ #######
98
+ # SDF #
99
+ #######
100
+
101
+ def compute_sdf(model, idx, xyz, latents=None, return_parts=False, max_batch=32**3, verbose=False, device=get_device(), **model_kwargs):
102
+ """
103
+ Compute the SDF values for a single shape at the given positions.
104
+
105
+ Args:
106
+ -----
107
+ model: nn.Module
108
+ The model to evaluate.
109
+ latent: torch.Tensor, shape (1, latent_size)
110
+ The latent vector of the shape.
111
+ xyz: torch.Tensor, shape ([N], 3)
112
+ The positions to evaluate the SDF at.
113
+ return_parts: bool
114
+ Whether to return the SDFs for each part.
115
+ max_batch: int (default=32**3)
116
+ The maximum number of points to evaluate at once.
117
+ verbose: bool (default=False)
118
+ If True, print the time taken for the computation.
119
+ device: str (default="cuda:0" if available)
120
+ The device to use to store the final SDF values.
121
+ **model_kwargs: (optional)
122
+ Additional key-worded arguments to pass to the model.
123
+
124
+ Returns:
125
+ --------
126
+ sdf: torch.Tensor, shape ([N], 1) or ([N], n_parts, 1) if return_parts
127
+ The SDF values at the given positions.
128
+ """
129
+ if verbose:
130
+ start_time = time.time()
131
+ model.eval()
132
+
133
+ # Prepare data
134
+ xyz_all = xyz.view(-1, 3)
135
+ if not xyz_all.is_cuda:
136
+ xyz_all = xyz_all.pin_memory()
137
+ n_points = len(xyz_all)
138
+ if return_parts:
139
+ sdf = torch.zeros(n_points, model.n_parts, device=device)
140
+ else:
141
+ sdf = torch.zeros(n_points, device=device)
142
+
143
+ # Predict SDF on a subset of points at a time
144
+ if idx.dim() == 0:
145
+ idx = idx.unsqueeze(0)
146
+ for i in range(0, n_points, max_batch):
147
+ xyz_subset = xyz_all[i : i + max_batch].to(device).unsqueeze(0)
148
+ if return_parts:
149
+ sdf[i : i + max_batch] = model(idx, xyz_subset, latents=latents, return_parts=True, **model_kwargs).squeeze().detach().to(device)
150
+ else:
151
+ sdf[i : i + max_batch] = model(idx, xyz_subset, latents=latents, **model_kwargs).squeeze().detach().to(device)
152
+
153
+ if verbose:
154
+ print(f"sdf-prediction took {time.time() - start_time:.3f}s.")
155
+ if return_parts:
156
+ return sdf.view(xyz.shape[:-1] + (model.n_parts, 1))
157
+ return sdf.view(xyz.shape[:-1] + (1,))
158
+
159
+
160
+ def clamp_sdf(sdf, clampD, ref=None):
161
+ """
162
+ Clamp the SDF, optionally based on a reference.
163
+ If ref is given, then the clamping is dependent on it:
164
+ e.g., sdf is clamped by +clampD only where ref >= +clampD.
165
+ """
166
+ if ref is None:
167
+ return torch.clamp(sdf, -clampD, clampD)
168
+ sdf = torch.where(ref > clampD, torch.clamp(sdf, max=clampD), sdf)
169
+ sdf = torch.where(ref < -clampD, torch.clamp(sdf, min=-clampD), sdf)
170
+ return sdf
171
+
172
+
173
+ def compute_gradients(sdf: torch.Tensor) -> torch.Tensor:
174
+ """
175
+ Compute spatial gradients of a batched SDF tensor using finite differences.
176
+
177
+ Parameters
178
+ ----------
179
+ sdf : torch.Tensor
180
+ Tensor of shape (B, 1, D, H, W) representing the scalar field (e.g., SDF values).
181
+
182
+ Returns
183
+ -------
184
+ grad : torch.Tensor
185
+ Tensor of shape (B, 3, D, H, W) containing gradients along x, y, z axes.
186
+ """
187
+ if sdf.dim() != 5:
188
+ raise ValueError(f"sdf must have shape (B, 1, D, H, W), got {tuple(sdf.shape)}")
189
+
190
+ # Pad for central differences (replicate border to keep same shape)
191
+ sdf_padded = F.pad(sdf, (1, 1, 1, 1, 1, 1), mode='replicate')
192
+
193
+ # Finite differences
194
+ gx = (sdf_padded[:, :, 1:-1, 1:-1, 2:] - sdf_padded[:, :, 1:-1, 1:-1, :-2]) / 2.0
195
+ gy = (sdf_padded[:, :, 1:-1, 2:, 1:-1] - sdf_padded[:, :, 1:-1, :-2, 1:-1]) / 2.0
196
+ gz = (sdf_padded[:, :, 2:, 1:-1, 1:-1] - sdf_padded[:, :, :-2, 1:-1, 1:-1]) / 2.0
197
+
198
+ grad = torch.cat([gx, gy, gz], dim=1) # (B, 3, D, H, W)
199
+ return grad
200
+
201
+
202
+ def make_grid(bbox, N, device=None):
203
+ """Create points on a regular grid."""
204
+ if isinstance(N, int):
205
+ N = [N] * len(bbox[0])
206
+ coords = []
207
+ for i in range(len(bbox[0])):
208
+ coords.append(torch.linspace(bbox[0][i], bbox[1][i], N[i], device=device))
209
+ coords = torch.meshgrid(*coords, indexing='ij')
210
+ coords = torch.stack(coords, dim=-1)
211
+ return coords
212
+
213
+
214
+ def make_grid2d(bbox, N, axis=0, value=0., device=None):
215
+ """
216
+ Create points on a regular grid of a 2D slice of a 3D world.
217
+
218
+ axis: int (default=0)
219
+ The axis index of the normal to the plane, e.g. 0 for x.
220
+ value: float (default=0.)
221
+ The second is the "fill" value along that axis, e.g. 0. for the x_i=0. plane.
222
+ """
223
+ assert axis in [0, 1, 2]
224
+
225
+ if isinstance(N, int):
226
+ N = [N] * 2
227
+ x1 = torch.linspace(bbox[0][0], bbox[1][0], N[0], device=device)
228
+ x2 = torch.linspace(bbox[0][1], bbox[1][1], N[1], device=device)
229
+ grid = torch.meshgrid(x1, x2, indexing='ij')
230
+ plane = torch.zeros_like(grid[0]) + value
231
+ if axis == 0:
232
+ xyz = torch.stack((plane, grid[0], grid[1]), dim=-1)
233
+ elif axis == 1:
234
+ xyz = torch.stack((grid[0], plane, grid[1]), dim=-1)
235
+ elif axis == 2:
236
+ xyz = torch.stack((grid[0], grid[1], plane), dim=-1)
237
+ return xyz
238
+
239
+
240
+ def make_grid_image(bbox, N_max, axis=1, value=0., device=None):
241
+ """
242
+ Create points on a regular grid of a 2D slice, with number of pixels adapting from bbox.
243
+
244
+ axis: int (default=0)
245
+ The axis index of the normal to the plane, e.g. 0 for x.
246
+ value: float (default=0.)
247
+ The second is the "fill" value along that axis, e.g. 0. for the x_i=0. plane.
248
+ """
249
+ assert axis in [0, 1, 2]
250
+
251
+ # Get resolution per axis
252
+ if not isinstance(bbox, np.ndarray):
253
+ bbox = np.array(bbox)
254
+ extent = np.abs(bbox[1] - bbox[0])
255
+ ratio = extent.min() / extent.max()
256
+ N_min = np.round(N_max * ratio).astype(int)
257
+ N = [N_max, N_min] if extent[0] > extent[1] else [N_min, N_max]
258
+
259
+ x1 = torch.linspace(bbox[0][0], bbox[1][0], N[0], device=device)
260
+ x2 = torch.linspace(bbox[0][1], bbox[1][1], N[1], device=device)
261
+ grid = torch.meshgrid(x1, x2, indexing='ij')
262
+ plane = torch.zeros_like(grid[0]) + value
263
+ if axis == 0:
264
+ xyz = torch.stack((plane, grid[0], grid[1]), dim=-1)
265
+ elif axis == 1:
266
+ xyz = torch.stack((grid[0], plane, grid[1]), dim=-1)
267
+ elif axis == 2:
268
+ xyz = torch.stack((grid[0], grid[1], plane), dim=-1)
269
+ return xyz
270
+
271
+
272
+ def get_sdf_mesh(mesh, xyz):
273
+ """Return the SDF of the mesh at the queried positions, using IGL."""
274
+ sdf = igl.signed_distance(xyz.reshape(-1, 3), mesh.vertices, mesh.faces)[0]
275
+ return sdf.reshape(xyz.shape[:-1])
276
+
277
+ def get_winding_number_mesh(mesh, xyz, method='fast'):
278
+ """Return the winding number of the mesh at the queried positions, using IGL."""
279
+ if method == 'fast':
280
+ wn = igl.fast_winding_number(mesh.vertices, mesh.faces, xyz.reshape(-1, 3).astype(mesh.vertices.dtype))
281
+ else:
282
+ wn = igl.winding_number(mesh.vertices, mesh.faces, xyz.reshape(-1, 3).astype(mesh.vertices.dtype))
283
+ return wn.reshape(xyz.shape[:-1])
284
+
285
+
286
+ ##########
287
+ # Meshes #
288
+ ##########
289
+
290
+ def get_color_mesh(mesh, vertex_values, vmin=None, vmax=None, cmap=colormaps['viridis'], symmetric=False):
291
+ """Return a new mesh with the vertex colors set according to the values."""
292
+ if isinstance(cmap, str):
293
+ cmap = colormaps[cmap]
294
+ vmin = vertex_values.min() if vmin is None else vmin
295
+ vmax = vertex_values.max() if vmax is None else vmax
296
+ if symmetric:
297
+ vmax = max(abs(vmin), abs(vmax))
298
+ vmin = -vmax
299
+ mesh = mesh.copy()
300
+ vertex_values = (vertex_values - vmin) / (vmax - vmin)
301
+ mesh.visual.vertex_colors = cmap(vertex_values)
302
+ return mesh
303
+
304
+
305
+ def get_color_parts(parts, colors=None, cmap=None):
306
+ """Color the parts of a mesh."""
307
+ if cmap is not None:
308
+ if isinstance(cmap, str):
309
+ cmap = colormaps[cmap]
310
+ colors = cmap(np.linspace(0, 1, len(parts)))
311
+ elif colors is None:
312
+ colors = generate_n_colors(len(parts))
313
+ parts = parts.copy()
314
+ for part, color in zip(parts, colors):
315
+ part.visual.face_colors = color
316
+ return parts
317
+
318
+
319
+ ###########
320
+ # PyTorch #
321
+ ###########
322
+
323
+ def get_gradient(inputs, outputs, retain_graph=True):
324
+ grads = torch.autograd.grad(
325
+ outputs.sum(), inputs,
326
+ create_graph=True,
327
+ retain_graph=retain_graph,
328
+ only_inputs=True
329
+ )
330
+ if isinstance(inputs, torch.Tensor):
331
+ grads = grads[0]
332
+ return grads
333
+
334
+
335
+ def index_extract(tensor, indices):
336
+ """
337
+ Extract the elements of a tensor at the given indices.
338
+
339
+ Args:
340
+ tensor: torch.Tensor, shape ([B], N, [M]) to extract from
341
+ indices: torch.Tensor, shape ([B], 1) of indices
342
+ Returns:
343
+ torch.Tensor, shape ([B], [M]) of extracted elements
344
+ (note the removed dimension)
345
+ """
346
+ indices = indices.squeeze(-1)
347
+ dim = indices.ndim
348
+
349
+ # Work of flatten tensors
350
+ out = tensor.flatten(0, dim - 1)
351
+ indices = indices.flatten()
352
+ out = out[torch.arange(out.shape[0], device=out.device), indices]
353
+ return out.view(*tensor.shape[:dim], *tensor.shape[dim + 1:])
354
+
355
+
356
+ #########
357
+ # Misc. #
358
+ #########
359
+
360
+ def fig2img(fig):
361
+ """Convert a figure to an image."""
362
+ buf = io.BytesIO()
363
+ fig.savefig(buf)
364
+ buf.seek(0)
365
+ img = Image.open(buf)
366
+ return img
367
+
368
+
369
+ def generate_n_colors(n, s=0.5, v=0.9):
370
+ """Generate N distinct colors in HSV space."""
371
+ colors = []
372
+ for i in range(n):
373
+ h = i / n
374
+ colors.append(colorsys.hsv_to_rgb(h, s, v))
375
+ return np.array(colors)
cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/._run_all_shm.sh ADDED
Binary file (4.1 kB). View file
 
cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/U ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*--------------------------------*- C++ -*----------------------------------*\
2
+ | ========= | |
3
+ | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
4
+ | \\ / O peration | Version: 7 |
5
+ | \\ / A nd | Web: www.OpenFOAM.com |
6
+ | \\/ M anipulation | |
7
+ \*---------------------------------------------------------------------------*/
8
+ FoamFile
9
+ {
10
+ version 2.0;
11
+ format ascii;
12
+ class volVectorField;
13
+ object U;
14
+ }
15
+ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
16
+
17
+ dimensions [ 0 1 -1 0 0 0 0 ];
18
+ internalField uniform (30 0.0 0.0);
19
+
20
+ boundaryField
21
+ {
22
+ #includeEtc "caseDicts/setConstraintTypes"
23
+ inlet
24
+ {
25
+
26
+ type fixedValue;
27
+ value uniform ( 30.0 0.0 0.0 );
28
+
29
+ /*
30
+ type uniformFixedValue;
31
+ uniformValue table
32
+ (
33
+ (0 (5 0 0))
34
+ //(20 (10 0 0))
35
+ //(40 (15 0 0))
36
+ //(60 (20 0 0))
37
+ //(80 (25 0 0))
38
+ (100 (30 0 0))
39
+ );
40
+ */
41
+
42
+ }
43
+
44
+ outlet
45
+ {
46
+ //type zeroGradient;
47
+ //value uniform ( 0.0 0.0 0.0 );
48
+
49
+ type inletOutlet;
50
+ inletValue uniform (30 0 0);
51
+ value uniform (30 0 0);
52
+ }
53
+
54
+ sides
55
+ {
56
+ type slip;
57
+ }
58
+
59
+ ground
60
+ {
61
+ type fixedValue;
62
+ value uniform ( 30.0 0.0 0.0 );
63
+
64
+ /*
65
+ type uniformFixedValue;
66
+ uniformValue table
67
+ (
68
+ (0 (5 0 0))
69
+ //(20 (10 0 0))
70
+ //(40 (15 0 0))
71
+ //(60 (20 0 0))
72
+ //(80 (25 0 0))
73
+ (100 (30 0 0))
74
+ );
75
+ */
76
+ }
77
+
78
+ top
79
+ {
80
+ type slip;
81
+ }
82
+
83
+ car
84
+ {
85
+ type fixedValue;
86
+ value uniform ( 0 0 0);
87
+ }
88
+ }
cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/k ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*--------------------------------*- C++ -*----------------------------------*\
2
+ | ========= | |
3
+ | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
4
+ | \\ / O peration | Version: 7 |
5
+ | \\ / A nd | Web: www.OpenFOAM.com |
6
+ | \\/ M anipulation | |
7
+ \*---------------------------------------------------------------------------*/
8
+ FoamFile
9
+ {
10
+ version 2.0;
11
+ format ascii;
12
+ class volScalarField;
13
+ object k;
14
+ }
15
+ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
16
+
17
+ dimensions [ 0 2 -2 0 0 0 0 ];
18
+ internalField uniform 3.375;
19
+
20
+ boundaryField
21
+ {
22
+ #includeEtc "caseDicts/setConstraintTypes"
23
+ inlet
24
+ {
25
+ type fixedValue;
26
+ value uniform 3.375;
27
+ }
28
+
29
+ outlet
30
+ {
31
+ type zeroGradient;
32
+ }
33
+
34
+ sides
35
+ {
36
+ //type kqRWallFunction;
37
+ //value uniform 1e-20;
38
+ type slip;
39
+ }
40
+
41
+ ground
42
+ {
43
+ type kqRWallFunction;
44
+ value uniform 3.375;
45
+ }
46
+
47
+ top
48
+ {
49
+ //type kqRWallFunction;
50
+ //value uniform 1e-20;
51
+ type slip;
52
+ }
53
+
54
+ car
55
+ {
56
+ type kqRWallFunction;
57
+ value uniform 3.375;
58
+ }
59
+
60
+ }
cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/nut ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*--------------------------------*- C++ -*----------------------------------*\
2
+ | ========= | |
3
+ | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
4
+ | \\ / O peration | Version: 7 |
5
+ | \\ / A nd | Web: www.OpenFOAM.com |
6
+ | \\/ M anipulation | |
7
+ \*---------------------------------------------------------------------------*/
8
+ FoamFile
9
+ {
10
+ version 2.0;
11
+ format ascii;
12
+ class volScalarField;
13
+ object nut;
14
+ }
15
+ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
16
+
17
+ dimensions [ 0 2 -1 0 0 0 0 ];
18
+ internalField uniform 0.0001;
19
+
20
+ boundaryField
21
+ {
22
+ #includeEtc "caseDicts/setConstraintTypes"
23
+ inlet
24
+ {
25
+ type zeroGradient;
26
+ }
27
+
28
+ outlet
29
+ {
30
+ type zeroGradient;
31
+ }
32
+
33
+ sides
34
+ {
35
+ //type nutUSpaldingWallFunction;
36
+ //value uniform 0.001;
37
+ type slip;
38
+ }
39
+
40
+ ground
41
+ {
42
+ type nutUSpaldingWallFunction;
43
+ value uniform 0.0001;
44
+ }
45
+
46
+ top
47
+ {
48
+ //type nutUSpaldingWallFunction;
49
+ //value uniform 0.001;
50
+ type slip;
51
+ }
52
+
53
+ car
54
+ {
55
+ type nutUSpaldingWallFunction;
56
+ value uniform 0.0001;
57
+ }
58
+
59
+ }
cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/omega ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*--------------------------------*- C++ -*----------------------------------*\
2
+ | ========= | |
3
+ | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
4
+ | \\ / O peration | Version: 7 |
5
+ | \\ / A nd | Web: www.OpenFOAM.com |
6
+ | \\/ M anipulation | |
7
+ \*---------------------------------------------------------------------------*/
8
+ FoamFile
9
+ {
10
+ version 2.0;
11
+ format ascii;
12
+ class volScalarField;
13
+ object omega;
14
+ }
15
+ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
16
+
17
+ dimensions [ 0 0 -1 0 0 0 0 ];
18
+ internalField uniform 9000;
19
+
20
+ boundaryField
21
+ {
22
+ #includeEtc "caseDicts/setConstraintTypes"
23
+ inlet
24
+ {
25
+ type fixedValue;
26
+ value uniform 9000;
27
+ }
28
+
29
+ outlet
30
+ {
31
+ type zeroGradient;
32
+ }
33
+
34
+ sides
35
+ {
36
+ //type omegaWallFunction;
37
+ //value uniform 1;
38
+ type slip;
39
+ }
40
+
41
+ ground
42
+ {
43
+ type omegaWallFunction;
44
+ //value uniform 9000;
45
+ value uniform 500000;
46
+ }
47
+
48
+ top
49
+ {
50
+ //type omegaWallFunction;
51
+ //value uniform 1;
52
+ type slip;
53
+ }
54
+
55
+ car
56
+ {
57
+ type omegaWallFunction;
58
+ //value uniform 9000;
59
+ value uniform 500000;
60
+ }
61
+
62
+ }
cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/p ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*--------------------------------*- C++ -*----------------------------------*\
2
+ | ========= | |
3
+ | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
4
+ | \\ / O peration | Version: 7 |
5
+ | \\ / A nd | Web: www.OpenFOAM.com |
6
+ | \\/ M anipulation | |
7
+ \*---------------------------------------------------------------------------*/
8
+ FoamFile
9
+ {
10
+ version 2.0;
11
+ format ascii;
12
+ class volScalarField;
13
+ object p;
14
+ }
15
+ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
16
+
17
+ dimensions [ 0 2 -2 0 0 0 0 ];
18
+ internalField uniform 0.0;
19
+
20
+ boundaryField
21
+ {
22
+ #includeEtc "caseDicts/setConstraintTypes"
23
+ inlet
24
+ {
25
+ type zeroGradient;
26
+ }
27
+
28
+ outlet
29
+ {
30
+ type fixedValue;
31
+ value uniform 0.0;
32
+ }
33
+
34
+ sides
35
+ {
36
+ //type zeroGradient;
37
+ type slip;
38
+ }
39
+
40
+ ground
41
+ {
42
+ type zeroGradient;
43
+ }
44
+
45
+ top
46
+ {
47
+ //type zeroGradient;
48
+ type slip;
49
+ }
50
+
51
+ car
52
+ {
53
+ type zeroGradient;
54
+ }
55
+
56
+ }
cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/U ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*--------------------------------*- C++ -*----------------------------------*\
2
+ | ========= | |
3
+ | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
4
+ | \\ / O peration | Version: 7 |
5
+ | \\ / A nd | Web: www.OpenFOAM.com |
6
+ | \\/ M anipulation | |
7
+ \*---------------------------------------------------------------------------*/
8
+ FoamFile
9
+ {
10
+ version 2.0;
11
+ format ascii;
12
+ class volVectorField;
13
+ object U;
14
+ }
15
+ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
16
+
17
+ dimensions [ 0 1 -1 0 0 0 0 ];
18
+ internalField uniform (30 0.0 0.0);
19
+
20
+ boundaryField
21
+ {
22
+ #includeEtc "caseDicts/setConstraintTypes"
23
+ inlet
24
+ {
25
+
26
+ type fixedValue;
27
+ value uniform ( 30.0 0.0 0.0 );
28
+
29
+ /*
30
+ type uniformFixedValue;
31
+ uniformValue table
32
+ (
33
+ (0 (5 0 0))
34
+ //(20 (10 0 0))
35
+ //(40 (15 0 0))
36
+ //(60 (20 0 0))
37
+ //(80 (25 0 0))
38
+ (100 (30 0 0))
39
+ );
40
+ */
41
+
42
+ }
43
+
44
+ outlet
45
+ {
46
+ //type zeroGradient;
47
+ //value uniform ( 0.0 0.0 0.0 );
48
+
49
+ type inletOutlet;
50
+ inletValue uniform (30 0 0);
51
+ value uniform (30 0 0);
52
+ }
53
+
54
+ sides
55
+ {
56
+ type slip;
57
+ }
58
+
59
+ ground
60
+ {
61
+ type fixedValue;
62
+ value uniform ( 30.0 0.0 0.0 );
63
+
64
+ /*
65
+ type uniformFixedValue;
66
+ uniformValue table
67
+ (
68
+ (0 (5 0 0))
69
+ //(20 (10 0 0))
70
+ //(40 (15 0 0))
71
+ //(60 (20 0 0))
72
+ //(80 (25 0 0))
73
+ (100 (30 0 0))
74
+ );
75
+ */
76
+ }
77
+
78
+ top
79
+ {
80
+ type slip;
81
+ }
82
+
83
+ car
84
+ {
85
+ type fixedValue;
86
+ value uniform ( 0 0 0);
87
+ }
88
+ }
cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/k ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*--------------------------------*- C++ -*----------------------------------*\
2
+ | ========= | |
3
+ | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
4
+ | \\ / O peration | Version: 7 |
5
+ | \\ / A nd | Web: www.OpenFOAM.com |
6
+ | \\/ M anipulation | |
7
+ \*---------------------------------------------------------------------------*/
8
+ FoamFile
9
+ {
10
+ version 2.0;
11
+ format ascii;
12
+ class volScalarField;
13
+ object k;
14
+ }
15
+ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
16
+
17
+ dimensions [ 0 2 -2 0 0 0 0 ];
18
+ internalField uniform 3.375;
19
+
20
+ boundaryField
21
+ {
22
+ #includeEtc "caseDicts/setConstraintTypes"
23
+ inlet
24
+ {
25
+ type fixedValue;
26
+ value uniform 3.375;
27
+ }
28
+
29
+ outlet
30
+ {
31
+ type zeroGradient;
32
+ }
33
+
34
+ sides
35
+ {
36
+ //type kqRWallFunction;
37
+ //value uniform 1e-20;
38
+ type slip;
39
+ }
40
+
41
+ ground
42
+ {
43
+ type kqRWallFunction;
44
+ value uniform 3.375;
45
+ }
46
+
47
+ top
48
+ {
49
+ //type kqRWallFunction;
50
+ //value uniform 1e-20;
51
+ type slip;
52
+ }
53
+
54
+ car
55
+ {
56
+ type kqRWallFunction;
57
+ value uniform 3.375;
58
+ }
59
+
60
+ }
cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/nut ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*--------------------------------*- C++ -*----------------------------------*\
2
+ | ========= | |
3
+ | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
4
+ | \\ / O peration | Version: 7 |
5
+ | \\ / A nd | Web: www.OpenFOAM.com |
6
+ | \\/ M anipulation | |
7
+ \*---------------------------------------------------------------------------*/
8
+ FoamFile
9
+ {
10
+ version 2.0;
11
+ format ascii;
12
+ class volScalarField;
13
+ object nut;
14
+ }
15
+ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
16
+
17
+ dimensions [ 0 2 -1 0 0 0 0 ];
18
+ internalField uniform 0.0001;
19
+
20
+ boundaryField
21
+ {
22
+ #includeEtc "caseDicts/setConstraintTypes"
23
+ inlet
24
+ {
25
+ type zeroGradient;
26
+ }
27
+
28
+ outlet
29
+ {
30
+ type zeroGradient;
31
+ }
32
+
33
+ sides
34
+ {
35
+ //type nutUSpaldingWallFunction;
36
+ //value uniform 0.001;
37
+ type slip;
38
+ }
39
+
40
+ ground
41
+ {
42
+ type nutUSpaldingWallFunction;
43
+ value uniform 0.0001;
44
+ }
45
+
46
+ top
47
+ {
48
+ //type nutUSpaldingWallFunction;
49
+ //value uniform 0.001;
50
+ type slip;
51
+ }
52
+
53
+ car
54
+ {
55
+ type nutUSpaldingWallFunction;
56
+ value uniform 0.0001;
57
+ }
58
+
59
+ }
cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/omega ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*--------------------------------*- C++ -*----------------------------------*\
2
+ | ========= | |
3
+ | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
4
+ | \\ / O peration | Version: 7 |
5
+ | \\ / A nd | Web: www.OpenFOAM.com |
6
+ | \\/ M anipulation | |
7
+ \*---------------------------------------------------------------------------*/
8
+ FoamFile
9
+ {
10
+ version 2.0;
11
+ format ascii;
12
+ class volScalarField;
13
+ object omega;
14
+ }
15
+ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
16
+
17
+ dimensions [ 0 0 -1 0 0 0 0 ];
18
+ internalField uniform 9000;
19
+
20
+ boundaryField
21
+ {
22
+ #includeEtc "caseDicts/setConstraintTypes"
23
+ inlet
24
+ {
25
+ type fixedValue;
26
+ value uniform 9000;
27
+ }
28
+
29
+ outlet
30
+ {
31
+ type zeroGradient;
32
+ }
33
+
34
+ sides
35
+ {
36
+ //type omegaWallFunction;
37
+ //value uniform 1;
38
+ type slip;
39
+ }
40
+
41
+ ground
42
+ {
43
+ type omegaWallFunction;
44
+ //value uniform 9000;
45
+ value uniform 500000;
46
+ }
47
+
48
+ top
49
+ {
50
+ //type omegaWallFunction;
51
+ //value uniform 1;
52
+ type slip;
53
+ }
54
+
55
+ car
56
+ {
57
+ type omegaWallFunction;
58
+ //value uniform 9000;
59
+ value uniform 500000;
60
+ }
61
+
62
+ }
cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/p ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*--------------------------------*- C++ -*----------------------------------*\
2
+ | ========= | |
3
+ | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
4
+ | \\ / O peration | Version: 7 |
5
+ | \\ / A nd | Web: www.OpenFOAM.com |
6
+ | \\/ M anipulation | |
7
+ \*---------------------------------------------------------------------------*/
8
+ FoamFile
9
+ {
10
+ version 2.0;
11
+ format ascii;
12
+ class volScalarField;
13
+ object p;
14
+ }
15
+ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
16
+
17
+ dimensions [ 0 2 -2 0 0 0 0 ];
18
+ internalField uniform 0.0;
19
+
20
+ boundaryField
21
+ {
22
+ inlet
23
+ {
24
+ type zeroGradient;
25
+ }
26
+
27
+ outlet
28
+ {
29
+ type fixedValue;
30
+ value uniform 0.0;
31
+ }
32
+
33
+ sides
34
+ {
35
+ //type zeroGradient;
36
+ type slip;
37
+ }
38
+
39
+ ground
40
+ {
41
+ type zeroGradient;
42
+ }
43
+
44
+ top
45
+ {
46
+ //type zeroGradient;
47
+ type slip;
48
+ }
49
+
50
+ car
51
+ {
52
+ type zeroGradient;
53
+ }
54
+
55
+ }
cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/README.md ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Experiment
2
+ Template.