Download tasks/037/simulate.py from OrlaLabs/PhyCAD-Bench: direct link, hf CLI and curl.
- Browser
- Download file 11.6 kB
-
https://huggingface.co/datasets/OrlaLabs/PhyCAD-Bench/resolve/main/tasks/037/simulate.py
- Command line
-
hf download hf://datasets/OrlaLabs/PhyCAD-Bench/tasks/037/simulate.py
-
curl -L -o simulate.py https://huggingface.co/datasets/OrlaLabs/PhyCAD-Bench/resolve/main/tasks/037/simulate.py
11.6 kB
| """Solve the air-domain potential and compare the electrode tip field.""" | |
| import argparse | |
| import hashlib | |
| import json | |
| import math | |
| import subprocess | |
| import sys | |
| import tempfile | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parent | |
| def measure(step: Path, setup: dict) -> dict: | |
| import cadquery as cq | |
| import gmsh | |
| shape = cq.importers.importStep(str(step)).val() | |
| if shape.ShapeType() != "Solid" or len(shape.Solids()) != 1 or not shape.isValid(): | |
| raise ValueError("Expected one valid electrode solid") | |
| mount = cq.Solid.makeBox(10, 10, 10, cq.Vector(0, -5, -5)) | |
| box = cq.Solid.makeBox(*setup["air_box_size_mm"], | |
| cq.Vector(*setup["air_box_min_mm"])) | |
| air = box.cut(shape) | |
| if not air.isValid() or len(air.Solids()) != 1: | |
| raise ValueError("Electrode must leave one valid air volume") | |
| result = { | |
| "step_sha256": hashlib.sha256(step.read_bytes()).hexdigest(), | |
| "volume_mm3": shape.Volume(), | |
| "mount_missing_mm3": max(0.0, mount.Volume() - mount.intersect(shape).Volume()), | |
| "envelope_excess_mm3": max(0.0, shape.Volume() - shape.intersect( | |
| cq.Solid.makeBox(50, 10, 10, cq.Vector(0, -5, -5))).Volume()), | |
| "tip_position_error_mm": abs(shape.BoundingBox().xmax - 50), | |
| "meshes": {}, | |
| } | |
| with tempfile.TemporaryDirectory() as directory: | |
| air_step = Path(directory) / "air.step" | |
| cq.exporters.export(air, str(air_step)) | |
| gmsh.initialize() | |
| try: | |
| gmsh.option.setNumber("General.Terminal", 0) | |
| gmsh.model.add("electrode_air") | |
| gmsh.model.occ.importShapes(str(air_step)) | |
| gmsh.model.occ.synchronize() | |
| if len(gmsh.model.getEntities(3)) != 1: | |
| raise ValueError("Air STEP import must yield one volume") | |
| electrode_faces = [] | |
| ground_faces = [] | |
| for _, tag in gmsh.model.getEntities(2): | |
| x, y, z = gmsh.model.occ.getCenterOfMass(2, tag) | |
| if abs(x - 70) < 1e-4: | |
| ground_faces.append(tag) | |
| elif not any(abs(a - b) < 1e-4 for a, b in ( | |
| (x, -10), (y, -15), (y, 15), (z, -15), (z, 15))): | |
| electrode_faces.append(tag) | |
| if not electrode_faces or not ground_faces: | |
| raise ValueError("Missing electrode or ground boundary") | |
| for size in setup["mesh_sizes_mm"]: | |
| gmsh.model.mesh.clear() | |
| gmsh.option.setNumber("Mesh.CharacteristicLengthMin", size) | |
| gmsh.option.setNumber("Mesh.CharacteristicLengthMax", size) | |
| gmsh.option.setNumber("Mesh.Algorithm3D", 1) | |
| gmsh.model.mesh.generate(3) | |
| tags, coordinates, _ = gmsh.model.mesh.getNodes() | |
| nodes = {str(int(tag)): [coordinates[3 * i + axis] / 1000 | |
| for axis in range(3)] | |
| for i, tag in enumerate(tags)} | |
| types, _, element_nodes = gmsh.model.mesh.getElements(3) | |
| tets = [] | |
| for kind, connectivity in zip(types, element_nodes): | |
| if kind != 4: | |
| raise ValueError(f"Expected first-order tetrahedra, got {kind}") | |
| tets.extend([[int(value) for value in connectivity[i:i + 4]] | |
| for i in range(0, len(connectivity), 4)]) | |
| def boundary_nodes(faces): | |
| return sorted({int(node) for face in faces | |
| for node in gmsh.model.mesh.getNodes( | |
| 2, face, includeBoundary=True)[0]}) | |
| electrode = boundary_nodes(electrode_faces) | |
| ground = boundary_nodes(ground_faces) | |
| if not nodes or not tets or len(electrode) < 4 or len(ground) < 4: | |
| raise ValueError("Incomplete air mesh or electrode boundaries") | |
| if set(electrode) & set(ground): | |
| raise ValueError("Electrode and ground boundaries overlap") | |
| result["meshes"][str(size)] = { | |
| "nodes": nodes, "tets": tets, | |
| "electrode": electrode, "ground": ground, | |
| } | |
| finally: | |
| gmsh.finalize() | |
| return result | |
| def dynamics(meshes: dict, setup: dict) -> dict: | |
| import numpy as np | |
| import pychrono as ch | |
| import pychrono.fea as fea | |
| results = {} | |
| for size, data in meshes.items(): | |
| system = ch.ChSystemSMC() | |
| system.SetGravitationalAcceleration(ch.ChVector3d(0, 0, 0)) | |
| system.SetSolver(ch.ChSolverSparseLU()) | |
| mesh = fea.ChMesh() | |
| material = fea.ChContinuumElectrostatics() | |
| material.SetPermittivity(setup["relative_permittivity"]) | |
| electrode, ground = set(data["electrode"]), set(data["ground"]) | |
| nodes = {} | |
| for key, point in data["nodes"].items(): | |
| node = fea.ChNodeFEAxyzP(ch.ChVector3d(*point)) | |
| if int(key) in electrode: | |
| node.SetFieldVal(setup["electrode_voltage_V"]) | |
| node.SetFixed(True) | |
| elif int(key) in ground: | |
| node.SetFieldVal(setup["ground_voltage_V"]) | |
| node.SetFixed(True) | |
| else: | |
| node.SetFieldVal(0) | |
| mesh.AddNode(node) | |
| nodes[int(key)] = node | |
| for a, b, c, d in data["tets"]: | |
| element = fea.ChElementTetraCorot_4_P() | |
| element.SetNodes(nodes[a], nodes[b], nodes[c], nodes[d]) | |
| element.SetMaterial(material) | |
| mesh.AddElement(element) | |
| system.Add(mesh) | |
| system.DoStaticLinear() | |
| fields = [] | |
| for tet in data["tets"]: | |
| points = np.array([data["nodes"][str(key)] for key in tet]) | |
| center = points.mean(axis=0) | |
| if not (setup["gap_x_min_m"] <= center[0] <= setup["gap_x_max_m"] | |
| and math.hypot(center[1], center[2]) <= setup["gap_radius_m"]): | |
| continue | |
| voltages = np.array([nodes[key].GetFieldVal() for key in tet]) | |
| edges = points[1:] - points[0] | |
| gradient = np.linalg.solve(edges, voltages[1:] - voltages[0]) | |
| volume = abs(np.linalg.det(edges)) / 6 | |
| fields.append((float(np.linalg.norm(gradient)), float(volume))) | |
| if len(fields) < 10 or not all(math.isfinite(field) and volume > 0 | |
| for field, volume in fields): | |
| raise ValueError("Fixed gap has too few valid tetrahedra") | |
| fields.sort() | |
| total_volume = sum(volume for _, volume in fields) | |
| quantiles = {} | |
| for q in (0.5, 0.75, 0.9, 0.95, 0.99): | |
| cumulative = 0.0 | |
| for field, volume in fields: | |
| cumulative += volume | |
| if cumulative >= q * total_volume: | |
| quantiles[str(q)] = field | |
| break | |
| mean_field = sum(field * volume for field, volume in fields) / total_volume | |
| rms_field = math.sqrt(sum(field * field * volume for field, volume in fields) | |
| / total_volume) | |
| potentials = [node.GetFieldVal() for node in nodes.values()] | |
| results[size] = { | |
| "gap_field_p99_V_m": quantiles[str(setup["gap_field_quantile"])], | |
| "gap_field_quantiles_V_m": quantiles, | |
| "gap_field_mean_V_m": mean_field, | |
| "gap_field_rms_V_m": rms_field, | |
| "gap_tetrahedron_count": len(fields), | |
| "node_count": len(nodes), | |
| "tetrahedron_count": len(data["tets"]), | |
| "electrode_node_count": len(electrode), | |
| "ground_node_count": len(ground), | |
| "minimum_potential_V": min(potentials), | |
| "maximum_potential_V": max(potentials), | |
| } | |
| return results | |
| def invoke(python: str, phase: str, payload: dict) -> dict: | |
| run = subprocess.run([python, str(Path(__file__).resolve()), "--phase", phase], | |
| input=json.dumps(payload), text=True, capture_output=True) | |
| if run.returncode: | |
| raise RuntimeError(f"{phase} failed:\n{run.stderr[-1600:]}") | |
| return json.loads(run.stdout) | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--cad-python", default=sys.executable) | |
| parser.add_argument("--physics-python", default=sys.executable) | |
| parser.add_argument("--phase", choices=("measure", "dynamics")) | |
| args = parser.parse_args() | |
| if args.phase: | |
| payload = json.load(sys.stdin) | |
| result = (measure(Path(payload["step"]), payload["setup"]) | |
| if args.phase == "measure" else | |
| dynamics(payload["meshes"], payload["setup"])) | |
| print(json.dumps(result)) | |
| return | |
| setup = json.loads((ROOT / "setup.json").read_text()) | |
| results = {} | |
| for name in ("before", "after"): | |
| properties = invoke(args.cad_python, "measure", { | |
| "step": str(ROOT / f"{name}.step"), "setup": setup}) | |
| meshes = properties.pop("meshes") | |
| results[name] = { | |
| "step_properties": properties, | |
| "simulation_result": invoke(args.physics_python, "dynamics", { | |
| "meshes": meshes, "setup": setup}), | |
| } | |
| before, after = results["before"], results["after"] | |
| bp, ap = before["step_properties"], after["step_properties"] | |
| bs, gs = before["simulation_result"], after["simulation_result"] | |
| sizes = [str(size) for size in setup["mesh_sizes_mm"]] | |
| baseline = [bs[size]["gap_field_p99_V_m"] for size in sizes] | |
| candidate = [gs[size]["gap_field_p99_V_m"] for size in sizes] | |
| reductions = [1 - a / b for a, b in zip(candidate, baseline)] | |
| checks = { | |
| "baseline_gap_field_measurable": min(baseline) >= | |
| setup["minimum_baseline_gap_field_V_m"], | |
| "gap_field_reduced_both_meshes": min(reductions) >= | |
| setup["required_relative_gap_field_reduction"], | |
| "candidate_gap_field_limit": max(candidate) <= | |
| setup["maximum_candidate_gap_field_V_m"], | |
| "mesh_field_stable": all(abs(values[1] / values[0] - 1) <= | |
| setup["maximum_relative_mesh_field_change"] | |
| for values in (baseline, candidate)), | |
| "improvement_stable": max(reductions) - min(reductions) <= | |
| setup["maximum_reduction_spread"], | |
| "potential_bounds": all( | |
| abs(gs[size]["minimum_potential_V"] - setup["ground_voltage_V"]) < 1e-6 | |
| and abs(gs[size]["maximum_potential_V"] - | |
| setup["electrode_voltage_V"]) < 1e-6 for size in sizes), | |
| "volume_fixed": abs(ap["volume_mm3"] / bp["volume_mm3"] - 1) <= | |
| setup["maximum_relative_volume_change"], | |
| "mount_fixed": ap["mount_missing_mm3"] <= | |
| setup["maximum_mount_missing_mm3"], | |
| "envelope_fixed": ap["envelope_excess_mm3"] <= | |
| setup["maximum_envelope_excess_mm3"], | |
| "tip_fixed": ap["tip_position_error_mm"] <= | |
| setup["maximum_tip_position_error_mm"], | |
| } | |
| after["comparison_to_before"] = { | |
| "relative_gap_field_reductions": reductions, | |
| "checks": checks, "passed": all(checks.values()), | |
| } | |
| for name, result in results.items(): | |
| (ROOT / f"{name}.results.json").write_text(json.dumps(result, indent=2) + "\n") | |
| print(f"Gap field p99: {baseline} -> {candidate} V/m") | |
| print(f"Task passed: {all(checks.values())}") | |
| if not all(checks.values()): | |
| raise SystemExit(1) | |
| if __name__ == "__main__": | |
| main() | |