File size: 11,637 Bytes
99510bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
"""Compare first bending mode and static deflection from STEP tetrahedra."""

import argparse
import hashlib
import json
import math
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent


def measure(step: Path, setup: dict) -> dict:
    import cadquery as cq
    import gmsh
    from OCP.BRepGProp import BRepGProp
    from OCP.GProp import GProp_GProps

    shape = cq.importers.importStep(str(step)).val()
    if shape.ShapeType() != "Solid" or not shape.isValid() or len(shape.Solids()) != 1:
        raise ValueError(f"Expected one valid solid: {step}")
    props = GProp_GProps()
    BRepGProp.VolumeProperties_s(shape.wrapped, props)
    if props.Mass() <= 0:
        raise ValueError("Beam volume must be positive")
    pad0 = cq.Solid.makeBox(10, 20, 10, cq.Vector(0, -10, -5))
    pad1 = cq.Solid.makeBox(10, 20, 10, cq.Vector(90, -10, -5))
    slabs = [cq.Solid.makeBox(10, 20, 20, cq.Vector(x, -10, -10))
             for x in (0, 90)]
    envelope = cq.Solid.makeBox(100, 20, 12, cq.Vector(0, -10, -6))
    pads = (pad0, pad1)
    pad_overlap = sum(pad.intersect(shape).Volume() for pad in pads)
    slab_overlap = sum(slab.intersect(shape).Volume() for slab in slabs)
    result = {
        "step_sha256": hashlib.sha256(step.read_bytes()).hexdigest(),
        "volume_mm3": props.Mass(),
        "mass_kg": props.Mass() * setup["material_density_kg_m3"] * 1e-9,
        "end_pad_missing_mm3": max(0.0, sum(p.Volume() for p in pads) - pad_overlap),
        "end_pad_excess_mm3": max(0.0, slab_overlap - pad_overlap),
        "envelope_excess_mm3": max(0.0, shape.Volume() -
                                   shape.intersect(envelope).Volume()),
        "meshes": {},
    }
    gmsh.initialize()
    try:
        gmsh.option.setNumber("General.Terminal", 0)
        gmsh.model.add("resonance_beam")
        gmsh.model.occ.importShapes(str(step))
        gmsh.model.occ.synchronize()
        if len(gmsh.model.getEntities(3)) != 1:
            raise ValueError("STEP import must produce one volume")
        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)])
            if not nodes or not tets:
                raise ValueError("Gmsh produced an empty mesh")
            result["meshes"][str(size)] = {"nodes": nodes, "tets": tets}
    finally:
        gmsh.finalize()
    return result


def dynamics(meshes: dict, setup: dict) -> dict:
    import pychrono as ch
    import pychrono.fea as fea
    import numpy as np
    from scipy.sparse import coo_matrix, diags
    from scipy.sparse.linalg import eigsh

    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.ChContinuumElastic()
        material.SetYoungModulus(setup["young_modulus_Pa"])
        material.SetPoissonRatio(setup["poisson_ratio"])
        material.SetDensity(setup["material_density_kg_m3"])
        keys = list(data["nodes"])
        node_index = {int(key): i for i, key in enumerate(keys)}
        tip_ids = [key for key, point in data["nodes"].items()
                   if abs(point[0] - 0.1) < 1e-8]
        fixed_ids = [key for key, point in data["nodes"].items()
                     if abs(point[0]) < 1e-8]
        if len(tip_ids) < 4 or len(fixed_ids) < 4:
            raise ValueError("Mesh is missing a clamp or load face")
        nodes = {}
        for key, point in data["nodes"].items():
            node = fea.ChNodeFEAxyz(ch.ChVector3d(*point))
            if key in fixed_ids:
                node.SetFixed(True)
            if key in tip_ids:
                node.SetForce(ch.ChVector3d(
                    0, 0, setup["tip_force_N"] / len(tip_ids)))
            mesh.AddNode(node)
            nodes[int(key)] = node
        elements = []
        for a, b, c, d in data["tets"]:
            element = fea.ChElementTetraCorot_4()
            element.SetNodes(nodes[a], nodes[b], nodes[c], nodes[d])
            element.SetMaterial(material)
            mesh.AddElement(element)
            elements.append(((a, b, c, d), element))
        system.Add(mesh)
        system.Setup()
        rows, columns, values = [], [], []
        nodal_mass = np.zeros(len(keys))
        for tetrahedron, element in elements:
            stiffness = element.GetStiffnessMatrix()
            dofs = [3 * node_index[key] + axis
                    for key in tetrahedron for axis in range(3)]
            for i in range(12):
                for j in range(12):
                    value = stiffness.GetItem(i, j)
                    if value:
                        rows.append(dofs[i])
                        columns.append(dofs[j])
                        values.append(value)
            points = np.array([data["nodes"][str(key)]
                               for key in tetrahedron])
            volume = abs(np.dot(points[1] - points[0],
                                np.cross(points[2] - points[0],
                                         points[3] - points[0]))) / 6
            if volume <= 0:
                raise ValueError("Invalid tetrahedron volume")
            for key in tetrahedron:
                nodal_mass[node_index[key]] += (
                    setup["material_density_kg_m3"] * volume / 4)
        matrix_size = 3 * len(keys)
        full_stiffness = coo_matrix(
            (values, (rows, columns)),
            shape=(matrix_size, matrix_size)).tocsr()
        active = [3 * i + axis for i, key in enumerate(keys)
                  if not nodes[int(key)].IsFixed() for axis in range(3)]
        stiffness = full_stiffness[active, :][:, active]
        mass = diags(np.repeat(nodal_mass, 3)[active])
        eigenvalues, _ = eigsh(stiffness, k=3, M=mass,
                              sigma=0, which="LM")
        if min(eigenvalues) <= 0:
            raise ValueError("Beam mode is not positive")
        first_frequency = math.sqrt(min(eigenvalues)) / (2 * math.pi)
        system.DoStaticLinear()
        deflections = [data["nodes"][key][2] - nodes[int(key)].GetPos().z
                       for key in tip_ids]
        mean_deflection = sum(deflections) / len(deflections)
        if (not math.isfinite(mean_deflection) or mean_deflection <= 0 or
                not math.isfinite(first_frequency)):
            raise ValueError("Invalid beam mode or static deflection")
        results[size] = {
            "first_bending_frequency_hz": first_frequency,
            "static_tip_deflection_m": mean_deflection,
            "node_count": len(nodes),
            "tetrahedron_count": len(data["tets"]),
            "clamped_node_count": len(fixed_ids),
            "loaded_node_count": len(tip_ids),
        }
    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 = results["before"]
    after = 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]["first_bending_frequency_hz"] for size in sizes]
    candidate = [gs[size]["first_bending_frequency_hz"] for size in sizes]
    baseline_static = [bs[size]["static_tip_deflection_m"] for size in sizes]
    candidate_static = [gs[size]["static_tip_deflection_m"] for size in sizes]
    checks = {
        "baseline_inside_forcing_band": all(
            setup["forcing_band_hz"][0] <= value <=
            setup["forcing_band_hz"][1] for value in baseline),
        "first_mode_above_forcing_band": min(candidate) >=
        setup["minimum_candidate_first_frequency_hz"],
        "static_deflection_limited": max(candidate_static) <=
        setup["maximum_candidate_static_tip_deflection_m"],
        "mesh_response_stable": all(
            abs(values[1] / values[0] - 1) <= limit
            for values, limit in (
                (baseline, setup["maximum_relative_mesh_frequency_change"]),
                (candidate, setup["maximum_relative_mesh_frequency_change"]),
                (baseline_static,
                 setup["maximum_relative_mesh_deflection_change"]),
                (candidate_static,
                 setup["maximum_relative_mesh_deflection_change"]))),
        "mass_fixed": abs(ap["mass_kg"] / bp["mass_kg"] - 1) <=
        setup["maximum_relative_mass_change"],
        "end_pads_fixed": ap["end_pad_missing_mm3"] <=
        setup["maximum_end_pad_missing_mm3"] and
        ap["end_pad_excess_mm3"] <= setup["maximum_end_pad_excess_mm3"],
        "envelope_fixed": ap["envelope_excess_mm3"] <=
        setup["maximum_envelope_excess_mm3"],
    }
    after["comparison_to_before"] = {
        "baseline_first_frequencies_hz": baseline,
        "candidate_first_frequencies_hz": candidate,
        "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"First mode: {baseline} -> {candidate} Hz")
    print(f"Static tip deflection: {baseline_static} -> {candidate_static} m")
    print(f"Task passed: {all(checks.values())}")
    if not all(checks.values()):
        raise SystemExit(1)


if __name__ == "__main__":
    main()