Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e8b0831884 | ||
|
|
bc75fd08d1 | ||
|
|
ce8e23d05b | ||
|
|
94f7e8533a | ||
|
|
ebf8c655ee | ||
|
|
9f6afe7a89 | ||
|
|
a953dc6216 | ||
|
|
72696614c2 | ||
|
|
0bb1c2462f | ||
|
|
788edbbddd | ||
|
|
1b57e2e672 | ||
|
|
9a8ae50bca | ||
|
|
188f2d5fc4 | ||
|
|
217628ead4 | ||
|
|
8848ef9e7c | ||
|
|
5c5516aae0 | ||
|
|
6a604c24b6 | ||
|
|
a30d0b5c5b | ||
|
|
ecf947c090 | ||
|
|
6c2b2509e7 | ||
|
|
9ba6224bb7 | ||
|
|
c09ccc8a59 | ||
|
|
908dae180b | ||
|
|
11a69d8171 | ||
|
|
d012c84ee5 | ||
|
|
779a7ce93c |
No files matched your search
@@ -41,6 +41,6 @@ body:
|
||||
id: version
|
||||
attributes:
|
||||
label: Version and platform
|
||||
placeholder: "v0.5.5 (or commit), macOS 15 arm64"
|
||||
placeholder: "v0.5.7 (or commit), macOS 15 arm64"
|
||||
validations:
|
||||
required: true
|
||||
@@ -14,7 +14,9 @@ is committed and listed here with its exports.
|
||||
|
||||
| File | Author | Source | Licence |
|
||||
|---|---|---|---|
|
||||
| docs/media/claude-mcp.mp4, docs/media/claude-mcp.gif | FieldCraft contributors | Original: a screen recording of Claude Code driving FieldCraft over MCP, edited with ffmpeg (title and end cards from docs/media/og.png) | MIT OR Apache-2.0 |
|
||||
| docs/media/ibeam-analysis.mp4, docs/media/ibeam-analysis.gif | FieldCraft contributors | Original: the FieldCraft window captured during an MCP session, generated by `tools/demo-video/make.py` | MIT OR Apache-2.0 |
|
||||
| docs/media/og.svg, docs/media/og.png | FieldCraft contributors | Original social-preview image (1280 × 640): the application icon's cube layer (assets/app-icon/FieldCraft.icon/Assets/02-part.svg) beside the name and tagline set in Inter (OFL, crates/ui-egui/fonts) | MIT OR Apache-2.0 |
|
||||
| docs/media/bracket-partition.png, docs/media/bracket-hex.png, docs/media/bracket-stress.png, docs/media/setup-symbols.png | FieldCraft contributors | Original: FieldCraft renders (headless MCP screenshots and a window capture) of corpus parts and the cantilever sample | MIT OR Apache-2.0 |
|
||||
| crates/decks/tests/golden/nastran/*.bdf | FieldCraft contributors | Written by our Nastran writer from our own test models (crates/decks/tests/nastran.rs) | MIT OR Apache-2.0 |
|
||||
| assets/icons/assembly.instance.svg, assets/icons/assembly.instance.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/assembly.instance.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
@@ -166,6 +168,7 @@ is committed and listed here with its exports.
|
||||
| crates/geometry/src/tagged_mesh.rs (package and part reading, transforms, units, caps) | SolidCraft `crates/io/src/threemf.rs` | MIT OR Apache-2.0 |
|
||||
| crates/render/src/camera.rs, crates/render/src/raster.rs | SolidCraft `crates/render/src/camera.rs`, `raster.rs` | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/src/gpu.rs, crates/ui-egui/src/theme.rs (tokens and their values), crates/ui-egui/src/control.rs, crates/ui-egui/src/lib.rs (input injection, screenshots), crates/ui-egui/src/toolbar.rs (workspace switcher, tabs, panels with drop-downs, fitting), crates/ui-egui/src/appbar.rs (application bar; the mark is drawn from assets/app-icon/icon-small.svg's coordinates), crates/ui-egui/src/titlebar.rs (caption buttons, drag and resize zones; SolidCraft took it from VectorCraft), crates/ui-egui/src/frame.rs (windows, heading bands), crates/ui-egui/src/browser.rs (row drawing), crates/ui-egui/src/palette.rs (command line and search), crates/ui-egui/src/timeline.rs (timeline strip, transport), crates/ui-egui/src/viewport.rs (navigation bar, orientation gizmo), crates/ui-egui/src/files.rs (background opening, file pickers as host services) | SolidCraft `crates/ui-egui/src/` (titlebar.rs also VectorCraft `crates/ui-egui/src/titlebar.rs`) | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/src/fields.rs (form rows: a label column of fixed width, then the field) | SolidCraft `crates/ui-egui/src/dialogs.rs` | MIT OR Apache-2.0 |
|
||||
| crates/io/src/fs.rs (atomic writes) | SolidCraft `crates/io/src/safe_write.rs` | MIT OR Apache-2.0 |
|
||||
| crates/io/src/recovery.rs (recovery folder, entries, locks) | SolidCraft `crates/engine/src/recovery.rs` | MIT OR Apache-2.0 |
|
||||
| apps/fieldcraft/src/control_server.rs | SolidCraft `apps/solidcraft/src/control_server.rs` | MIT OR Apache-2.0 |
|
||||
|
||||
@@ -1237,7 +1237,7 @@ checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693"
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft"
|
||||
version = "0.5.5"
|
||||
version = "0.5.7"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -1252,7 +1252,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-cli"
|
||||
version = "0.5.5"
|
||||
version = "0.5.7"
|
||||
dependencies = [
|
||||
"fieldcraft-engine",
|
||||
"fieldcraft-io",
|
||||
@@ -1262,7 +1262,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-decks"
|
||||
version = "0.5.5"
|
||||
version = "0.5.7"
|
||||
dependencies = [
|
||||
"fieldcraft-model",
|
||||
"serde_json",
|
||||
@@ -1271,7 +1271,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-engine"
|
||||
version = "0.5.5"
|
||||
version = "0.5.7"
|
||||
dependencies = [
|
||||
"fieldcraft-decks",
|
||||
"fieldcraft-explicit",
|
||||
@@ -1293,7 +1293,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-explicit"
|
||||
version = "0.5.5"
|
||||
version = "0.5.7"
|
||||
dependencies = [
|
||||
"fieldcraft-fem",
|
||||
"fieldcraft-model",
|
||||
@@ -1304,7 +1304,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-fem"
|
||||
version = "0.5.5"
|
||||
version = "0.5.7"
|
||||
dependencies = [
|
||||
"fieldcraft-model",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1312,7 +1312,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-geometry"
|
||||
version = "0.5.5"
|
||||
version = "0.5.7"
|
||||
dependencies = [
|
||||
"fieldcraft-model",
|
||||
"quick-xml",
|
||||
@@ -1328,7 +1328,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-io"
|
||||
version = "0.5.5"
|
||||
version = "0.5.7"
|
||||
dependencies = [
|
||||
"fieldcraft-model",
|
||||
"log",
|
||||
@@ -1341,7 +1341,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-lbm"
|
||||
version = "0.5.5"
|
||||
version = "0.5.7"
|
||||
dependencies = [
|
||||
"fieldcraft-mesh",
|
||||
"fieldcraft-model",
|
||||
@@ -1351,7 +1351,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-mcp"
|
||||
version = "0.5.5"
|
||||
version = "0.5.7"
|
||||
dependencies = [
|
||||
"fieldcraft-engine",
|
||||
"fieldcraft-io",
|
||||
@@ -1362,7 +1362,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-mesh"
|
||||
version = "0.5.5"
|
||||
version = "0.5.7"
|
||||
dependencies = [
|
||||
"fieldcraft-model",
|
||||
"num-bigint",
|
||||
@@ -1374,7 +1374,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-model"
|
||||
version = "0.5.5"
|
||||
version = "0.5.7"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -1383,14 +1383,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-parallel"
|
||||
version = "0.5.5"
|
||||
version = "0.5.7"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-render"
|
||||
version = "0.5.5"
|
||||
version = "0.5.7"
|
||||
dependencies = [
|
||||
"fieldcraft-model",
|
||||
"png",
|
||||
@@ -1400,7 +1400,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-solver"
|
||||
version = "0.5.5"
|
||||
version = "0.5.7"
|
||||
dependencies = [
|
||||
"fieldcraft-fem",
|
||||
"fieldcraft-mesh",
|
||||
@@ -1412,7 +1412,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-testkit"
|
||||
version = "0.5.5"
|
||||
version = "0.5.7"
|
||||
dependencies = [
|
||||
"fieldcraft-engine",
|
||||
"fieldcraft-geometry",
|
||||
@@ -1423,7 +1423,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-ui-egui"
|
||||
version = "0.5.5"
|
||||
version = "0.5.7"
|
||||
dependencies = [
|
||||
"craft-ui",
|
||||
"egui",
|
||||
@@ -1442,7 +1442,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-web"
|
||||
version = "0.5.5"
|
||||
version = "0.5.7"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"eframe",
|
||||
@@ -4986,7 +4986,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.5.5"
|
||||
version = "0.5.7"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*", "apps/*", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.5.5"
|
||||
version = "0.5.7"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
|
||||
@@ -14,6 +14,10 @@ the wider material and multiphysics library. See [ROADMAP.md](ROADMAP.md).
|
||||
[help wanted](https://github.com/jyviko/fieldcraft/labels/help%20wanted) and read
|
||||
[CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
|
||||

|
||||
|
||||
*Claude driving FieldCraft through its [MCP server](docs/mcp.md): one prompt, and it opens the part, meshes it, defines and solves the analysis, then checks the tip deflection against beam theory. Real session, waits shortened. [Full video](docs/media/claude-mcp.mp4).*
|
||||
|
||||

|
||||
|
||||
An AI agent drives FieldCraft over [MCP](docs/mcp.md), each stage captioned with the tool it
|
||||
@@ -27,10 +31,12 @@ theory with shear 0.177 mm).
|
||||
[](https://github.com/jyviko/fieldcraft/releases/latest)
|
||||
[](https://github.com/jyviko/fieldcraft/releases/latest)
|
||||
[](https://github.com/jyviko/fieldcraft/releases/latest)
|
||||
[](https://jyviko.github.io/fieldcraft/)
|
||||
|
||||
- **macOS:** open the `.dmg` and drag FieldCraft into Applications (Apple silicon and Intel).
|
||||
- **Windows:** unzip and run `fieldcraft.exe`.
|
||||
- **Linux:** the `.AppImage` (allow it to run as a program), or the `.tar.gz`.
|
||||
- **Browser:** [try it at jyviko.github.io/fieldcraft](https://jyviko.github.io/fieldcraft/), no install.
|
||||
- **Command line:** `fieldcraft-cli` ships in every package; AI agents connect to it over MCP
|
||||
([docs/mcp.md](docs/mcp.md)).
|
||||
|
||||
|
||||
@@ -33,15 +33,15 @@ pressure) is a degree of freedom of the existing DOF framework, not a separate s
|
||||
| M4 Own solver and first results | Element library per docs/elements.md (1D and 2D first); Linear static and modal solver (tet4/10, wedge6, hex8, hex20; sparse direct, Lanczos), verified against analytic solutions (solver: done — `fieldcraft-fem` kernels, `fieldcraft-solver` with nested dissection, sparse Cholesky and block Lanczos, `solve.static`/`solve.frequency`/`solve.probe`, patch, cantilever, Lamé, Kirsch and beam-frequency tests; reference points with kinematic and distributing couplings and moments by master–slave constraint elimination, verified by rigid motion, clamping, Saint-Venant tension, bending and tube torsion; 1D elements I: rod2/rod3 trusses, point masses, rotary inertia, springs and dashpots in both solvers and all three decks, verified by the method of joints, the three-bar truss, spring–mass, two-mass chain and torsional pendulum frequencies, and damped decay; 2D elements: plane stress, plane strain and axisymmetric tri3, tri6, quad4 (incompatible modes QM6), quad8 with two degrees of freedom per node, centrifugal loads, `mesh.planar` 2D meshes of polygons and planar faces, verified by patch tests, Kirsch, Lamé (plane strain and axisymmetric), rotating discs and cylinders, and a plane stress cantilever; deck mapping to Abaqus CPS/CPE/CAX, Nastran membranes, LS-DYNA ELFORM 12/13); shells and beams (done: quad4 MITC4 and tri3 MITC3 flat shells with a Hughes–Brezzi drilling rotation, two-node Timoshenko beams with profile properties and orientations, six degrees of freedom at shell and beam nodes shared with solids and trusses, section forces and surface stresses, verified by shell patch tests, Navier's plate, cantilever and portal-frame beams, and the Scordelis–Lo and pinched-cylinder benchmarks); results display (done: `results.*` commands, deformed shape to scale, banded contours of displacement, von Mises, principal and component stresses with a legend, mode shapes with their frequencies and animation, probing a node by clicking it, reaction force and moment sums per set, stale results marked after an edit; explicit steps: field frames by slider or animation with contours per frame, energy histories plotted) | started |
|
||||
| M5 Structured hex | 2D quad meshing of faces (`fieldcraft-mesh::quad`: transfinite mapped meshes, free all-quad meshes of polygons with holes on prescribed boundary nodes, exact planar quad validity, shared `SizeField` and even edge divisions; done for planar faces); mapped hex of six-sided regions (trivariate TFI, curved faces) and sweep meshing (multi-level extrusions with imprinted cross-sections, revolutions, one-to-one sweeps through linking faces; interval assignment, hex8/hex20 on the geometry, B-rep face tags, `mesh.hex.generate`/`sweep`/`mapped`: done, 16 of 21 corpus parts all-hex); conforming interfaces between cells (done: `mesh.hex.blocks` meshes a part split with SolidCraft's Split Body into mapped blocks as one conforming mesh — composite faces for seams and tangent faces, interval assignment over all cells, shared faces meshed once, grading off holes and fillets, free-internal-face check; the filleted bracket in 30 cells, hex20 within 0.1 % of a fine tet10 tip deflection); sweepable cells in a conforming mesh and tet–hex transition; automatic decomposition into sweepable and mappable regions, proposed as SolidCraft splits | started |
|
||||
| M6 Automatic hex | Octree/grid all-hex for any part (first version: done — `fieldcraft-mesh::octree`, `mesh.hex.octree`: 3-refinement grid with conforming templates refined by curvature, thickness and narrow faces, a core cleared to a manifold boundary, feature map onto it, padding and a pillow per patch capturing every sharp curve, foldover-free fitting, certified validity, B-rep face tags; the corpus hex column and the filleted-bracket oracle case; next: transitions for concave refined regions so thin and curved parts stop over-refining); hex-dominant by tet recombination; polycube for blocky parts; layers through thin walls; mesh editing and orphan-mesh import | started |
|
||||
| M7 Assemblies, contact and friction | Needs M15. Part instances from SolidCraft occurrences; tie between non-matching meshes (mortar); implicit contact: surface-to-surface mortar and node-to-surface, penalty and augmented Lagrange, self-contact, automatic pair detection with a bounding-volume search shared with explicit contact; friction: Coulomb with stick–slip, static/kinetic, anisotropic, pressure-, rate- and temperature-dependent coefficients; contact output (pressure, slip, status); thermal contact conductance and frictional heating; wear (Archard); bolt pretension, connectors with behaviour (elastic, damped, stops, locks); amplitudes, multiple steps, restart; nonlinear steps in all three decks. Verified by Hertz (sphere and cylinder), the Cattaneo–Mindlin partial-slip problem, the sliding block, NAFEMS contact benchmarks | planned |
|
||||
| M7 Assemblies, contact and friction | Needs M15. Part instances from SolidCraft occurrences; tie between non-matching meshes (mortar); implicit contact: surface-to-surface mortar and node-to-surface, penalty and augmented Lagrange, self-contact, automatic pair detection (the model's contact definitions, `interaction.contact.*` with `find`, the deck mapping, `fieldcraft_fem::contact`'s closest-point projection and bucket grid, and the explicit solver's segmentation and friction return map are in place to reuse; the implicit solver refuses contact by name until then); friction: Coulomb with stick–slip, static/kinetic, anisotropic, pressure-, rate- and temperature-dependent coefficients; contact output (pressure, slip, status); thermal contact conductance and frictional heating; wear (Archard); bolt pretension, connectors with behaviour (elastic, damped, stops, locks); amplitudes, multiple steps, restart; nonlinear steps in all three decks. Verified by Hertz (sphere and cylinder), the Cattaneo–Mindlin partial-slip problem, the sliding block, NAFEMS contact benchmarks | planned |
|
||||
| M8 Materials, explicit, shells, composites | Plasticity, hyperelasticity, damage data per solver; explicit dynamics decks (Abaqus/Explicit, LS-DYNA); midsurface shells; composite layups and material orientations, continuum shells on swept hex; hybrid (mixed u–p) hex8/hex20/tet10 for nearly incompressible materials (done); heat transfer (solids done: steady and θ-method transient conduction with flux, convection and sources, thermal strain in static steps (solids and 2D) and explicit dynamics (with plasticity), coupled temperature–displacement, `solve.heat`; deck output, 2D/shell/beam conduction planned) | started |
|
||||
| M9 Post-processing and deck readers | Results readers for public formats (Nastran OP2, LS-DYNA d3plot, Abaqus `.fil`); XY and path plots, cuts, display groups, free-body forces; deck readers that keep unknown keywords; mesh convergence studies | planned |
|
||||
| M10 Explicit dynamics | Shared element and material kernels with the implicit solver (`fem`); central-difference solver with lumped mass, stable time step, one-point hex8 with hourglass control and nodal-pressure tet4, bulk viscosity, energy accounting (X1 core: done — `fieldcraft-explicit`, `explicit_dynamic` steps with initial velocities, prescribed motion and planar rigid walls, `solve.explicit`/`solve.history`, small-strain linear elastic; bar wave, rigid-wall impact, energy balance and cantilever-period tests); large-deformation materials (X2: done — updated Lagrangian elements, Jaumann/Hughes–Winget and Green–Naghdi/Flanagan–Taylor rates, J2 bilinear/table plasticity, Johnson–Cook strength with heating and damage, erosion; materials gain `plastic`, `damage`, `erosion` with `model.material.plasticity`/`damage`; Dienes shear, rigid rotation, J2 uniaxial and Taylor-bar tests); contact (global search, penalty with friction, rigid walls); runs on hex and tet meshes | started |
|
||||
| M10 Explicit dynamics | Shared element and material kernels with the implicit solver (`fem`); central-difference solver with lumped mass, stable time step, one-point hex8 with hourglass control and nodal-pressure tet4, bulk viscosity, energy accounting (X1 core: done — `fieldcraft-explicit`, `explicit_dynamic` steps with initial velocities, prescribed motion and planar rigid walls, `solve.explicit`/`solve.history`, small-strain linear elastic; bar wave, rigid-wall impact, energy balance and cantilever-period tests); large-deformation materials (X2: done — updated Lagrangian elements, Jaumann/Hughes–Winget and Green–Naghdi/Flanagan–Taylor rates, J2 bilinear/table plasticity, Johnson–Cook strength with heating and damage, erosion; materials gain `plastic`, `damage`, `erosion` with `model.material.plasticity`/`damage`; Dienes shear, rigid rotation, J2 uniaxial and Taylor-bar tests); contact (X3: done — `interaction.contact.pair`/`general`/`find`, segment-to-segment penalty contact both ways with polygon clipping (passes the contact patch test on non-matching meshes), pairs, general (all exterior faces) and self contact, bucket-grid search, deterministic on any thread count, a penalty from the masses and the stable increment that never shortens it, Coulomb friction with exponential decay by a return map, friction on rigid walls, contact energy and friction dissipation in the balance, initial penetrations adjusted or refused; Abaqus `*CONTACT PAIR`/`*CONTACT`/`*FRICTION` and LS-DYNA automatic contacts in the decks; verified by colliding bars, sliding blocks, the patch test and Hertz's sphere impact); hyperelastic materials (neo-Hookean, Mooney–Rivlin, Yeoh) on the shared material point with average nodal pressure tets, and opt-in mass scaling with the added mass reported: done; runs on hex and tet meshes | started |
|
||||
| M11 Equations of state and shells | Polynomial, ideal-gas, Mie–Grüneisen, JWL with programmed burn, tabulated; energy coupling; shock verification (Rankine–Hugoniot, Sod, Noh, Sedov); Belytschko–Lin–Tsay shells with self-contact on quad meshes | planned |
|
||||
| M12 CFD: lattice Boltzmann | D3Q19/D3Q27 on grids voxelised from the face-tagged surface; TRT, regularised and cumulant collision; interpolated walls, inlets and outlets; LES (Smagorinsky, WALE) with wall models; thermal LBM and conjugate heat transfer with the structure's thermal solver; non-Newtonian viscosity (power-law, Carreau–Yasuda, Cross, Herschel–Bulkley, Bingham) and temperature-dependent viscosity; porous media (Brinkman, Darcy–Forchheimer); multiphase and free surface (M13); validation by the lid-driven cavity, backward-facing step, cylinder wake (Strouhal) and turbulent channel; octree refinement shared with the hex mesher; wgpu backend (deterministic per device, checked against the CPU) (CPU core: done — `fieldcraft-lbm` with D3Q19 TRT and Guo forcing, halfway bounce-back and moving walls, slip and periodic faces, Zou–He velocity and pressure faces, exact voxelisation of obstacle bodies, momentum-exchange forces per face; fluid materials, fluid domains and fluid steps in the model; `model.fluid_domain.*`, `solve.fluid`; verified by Poiseuille channel and pipe, Couette, Taylor–Green decay, sphere-array Stokes drag and mass conservation; Schäfer–Turek 2D-1 as a benchmark) | started |
|
||||
| M13 Fluid–structure interaction | Immersed-boundary coupling of the lattice Boltzmann fluid with the explicit or implicit structure; interface force transfer; sub-cycling; Aitken then interface quasi-Newton coupling; free-surface flow | planned |
|
||||
| M14 Blast and impact fluids | EOS-driven fluids in the explicit solver: ALE multi-material or SPH, with fluid–structure contact | planned |
|
||||
| M15 Nonlinear implicit core | Newton–Raphson with line search, automatic increments and cutbacks, convergence on force, displacement and energy; geometric nonlinearity (total and updated Lagrangian, large rotations for shells and beams, follower pressure); every `fem` material behind one interface with its consistent tangent (plasticity, damage and thermal strain from the explicit solver reused implicitly); arc-length (Riks) for snap-through; linear buckling (eigen) with preload stress stiffening, and imperfections from buckling modes; nonlinear stabilisation; restart. Verified by the elastica, Lee's frame, the snap-through arch, the hinged cylindrical shell and plastic collapse loads (solids core: done — `nonlinear_static` steps with automatic increments and cutbacks, Newton–Raphson with the consistent tangent, force, displacement and energy convergence and an optional line search; a material point interface (Kirchhoff stress and spatial tangent from F, with history) with St Venant–Kirchhoff and compressible neo-Hookean; total Lagrangian tet4, tet10, wedge6, hex8, hex20 (full and reduced), hybrid hex8/hex20/tet10 by the three-field mixed form, plane strain and axisymmetric elements; follower pressure with its symmetrised load stiffness; Cauchy stress and logarithmic strain, increment history and frames, `solve.nonlinear`; Abaqus and LS-DYNA decks; verified by the patch and objectivity tests, uniaxial stretch, the elastica and tube inflation by a follower pressure (finite-strain Cook's membrane pending its transcribed reference; J2 plasticity on the interface: Simo's exponential return map at finite strain and the radial return at small strain, both with consistent tangents and the return shared with explicit dynamics, bilinear isotropic and kinematic (small strain), tabulated and Johnson–Cook (rate-independent) hardening, hybrid elements included, load paths for cyclic loading, a tangent predictor for path-dependent materials, verified by uniaxial tension to large strain, Hill's thick cylinder (plastic zone and collapse pressure), a cantilever's collapse and the Bauschinger effect, with quadratic Newton convergence; Mooney–Rivlin and Yeoh options (decoupled, hybrid elements), verified in Treloar's three modes and by a stretched tube's inflation; thermal strain by the multiplicative split at finite strain and the additive one at small strain, with temperatures from temperature loads or the step's own conduction, verified by free and constrained expansion and a heated bar held past yield. Next: incompatible modes (EAS), kinematic hardening at finite strain, shells and beams, linear buckling, arc-length with an indefinite factorization) | started |
|
||||
| M15 Nonlinear implicit core | Newton–Raphson with line search, automatic increments and cutbacks, convergence on force, displacement and energy; geometric nonlinearity (total and updated Lagrangian, large rotations for shells and beams, follower pressure); every `fem` material behind one interface with its consistent tangent (plasticity, damage and thermal strain from the explicit solver reused implicitly); arc-length (Riks) for snap-through; linear buckling (eigen) with preload stress stiffening, and imperfections from buckling modes; nonlinear stabilisation; restart. Verified by the elastica, Lee's frame, the snap-through arch, the hinged cylindrical shell and plastic collapse loads (solids core: done — `nonlinear_static` steps with automatic increments and cutbacks, Newton–Raphson with the consistent tangent, force, displacement and energy convergence and an optional line search; a material point interface (Kirchhoff stress and spatial tangent from F, with history) with St Venant–Kirchhoff and compressible neo-Hookean; total Lagrangian tet4, tet10, wedge6, hex8, hex20 (full and reduced), hybrid hex8/hex20/tet10 by the three-field mixed form, plane strain and axisymmetric elements; follower pressure with its symmetrised load stiffness; Cauchy stress and logarithmic strain, increment history and frames, `solve.nonlinear`; Abaqus and LS-DYNA decks; verified by the patch and objectivity tests, uniaxial stretch, the elastica and tube inflation by a follower pressure (finite-strain Cook's membrane pending its transcribed reference; J2 plasticity on the interface: Simo's exponential return map at finite strain and the radial return at small strain, both with consistent tangents and the return shared with explicit dynamics, bilinear isotropic and kinematic (small strain), tabulated and Johnson–Cook (rate-independent) hardening, hybrid elements included, load paths for cyclic loading, a tangent predictor for path-dependent materials, verified by uniaxial tension to large strain, Hill's thick cylinder (plastic zone and collapse pressure), a cantilever's collapse and the Bauschinger effect, with quadratic Newton convergence; Mooney–Rivlin and Yeoh options (decoupled, hybrid elements), verified in Treloar's three modes and by a stretched tube's inflation; thermal strain by the multiplicative split at finite strain and the additive one at small strain, with temperatures from temperature loads or the step's own conduction, verified by free and constrained expansion and a heated bar held past yield. a supernodal symmetric indefinite LDLᵀ factorization (bounded Bunch–Kaufman within supernodes, inertia) on which Newton continues through indefinite tangents, so nearly incompressible hybrid elements (ν = 0.4999) converge under prescribed displacement; linear buckling steps (linear preload, initial-stress stiffness of solids and 2D elements, block Lanczos in the K inner product, the shifted buckling transformation on LDLᵀ with an inertia count, `solve.buckle`, Abaqus `*BUCKLE`), verified by Euler columns and Bryan's plate; imperfections from buckling modes; arc-length (Riks–Crisfield, cylindrical or spherical) with limit and bifurcation points from the tangent's inertia, verified by the snap-through of a shallow arch. Next: Lee's frame and the hinged cylindrical shell (with shells), the follower pressure's full tangent (LU), incompatible modes (EAS), kinematic hardening at finite strain, shells and beams) | started |
|
||||
| M16 Structural dynamics | Implicit transient (Newmark, HHT-α, generalised-α); modal superposition transient; steady-state harmonic (direct and modal), with Rayleigh, modal, structural and material damping; random vibration from PSDs and response spectrum (SRSS, CQC); complex eigenvalues with damping; rotating machinery (Campbell diagrams, gyroscopic terms); substructures (Craig–Bampton) | planned |
|
||||
| M17 Constitutive library and material library | Elastic: transversely isotropic, fully anisotropic (21 constants), temperature-dependent. Elastomers: hyperelastic neo-Hookean, Mooney–Rivlin, Yeoh (these three done, in nonlinear steps), Ogden, Arruda–Boyce, Gent, Marlow, with Mullins softening and finite-strain viscoelasticity (Prony series; parallel networks after Bergström–Boyce), foams. Viscoelasticity: small- and finite-strain Prony series, time–temperature superposition (WLF, Arrhenius), storage and loss moduli for harmonic steps. Viscoplasticity and creep: Norton power law, time and strain hardening, Perzyna, Anand, Chaboche combined hardening. Plasticity: Hill anisotropic, Drucker–Prager, Mohr–Coulomb, Cam-clay, crushable foam, concrete damaged plasticity, Gurson. Fluids: Newtonian and non-Newtonian viscosity shared with M12. Material library: curated, cited data sets (steels, aluminium and titanium alloys, polymers, elastomers, composites, tissues) with units and temperature dependence; calibration from test data (uniaxial, biaxial, shear, relaxation, DMA) by least squares with Drucker stability checks; user materials as a safe Rust trait | planned |
|
||||
| M18 Composites and anisotropy | Material orientations (rectangular, cylindrical, spherical, from geometry edges and faces, per-element fields, draping of fibres over curved parts); layups on shells and continuum shells, ply stacks on swept hex; classical lamination theory checks; ply stresses and strains through the thickness; failure indices (Tsai–Wu, Tsai–Hill, Hashin, Puck, LaRC) and progressive damage; homogenisation (rule of mixtures, Mori–Tanaka, RVEs with periodic boundary conditions); delamination through M20's cohesive zones. Verified by laminate closed forms and the NAFEMS composite benchmarks | planned |
|
||||
@@ -77,7 +77,7 @@ What exists and what is missing, by area; each gap is in a milestone above.
|
||||
| Area | Today | Missing |
|
||||
|---|---|---|
|
||||
| Solution procedures | Linear static, nonlinear static (solids with geometric and material nonlinearity: hyperelasticity, J2 plasticity), frequency (Lanczos), steady and transient heat, coupled temperature–displacement, explicit dynamics, LBM flow | Nonlinear shells and beams, arc-length, buckling (M15); implicit, harmonic, random and spectrum dynamics (M16) |
|
||||
| Contact, friction, adhesion | Explicit planar rigid walls (frictionless); couplings, springs, dashpots | Implicit and explicit deformable contact, tie, friction laws, thermal contact, wear (M7); cohesive adhesion and debonding (M20) |
|
||||
| Contact, friction, adhesion | Explicit deformable contact (pairs, general, self; segment to segment, penalty) with Coulomb friction and exponential decay; rigid walls with friction; couplings, springs, dashpots | Implicit contact, tie, anisotropic and pressure- or temperature-dependent friction, thermal contact, wear, eroding contact (M7, M10); cohesive adhesion and debonding (M20) |
|
||||
| Materials | Isotropic and orthotropic elasticity, density, thermal, J2 plasticity (bilinear, table, Johnson–Cook), Johnson–Cook damage and erosion, compressible neo-Hookean, Mooney–Rivlin and Yeoh hyperelasticity, Newtonian fluids | Elastomers beyond Yeoh (Ogden, Arruda–Boyce and the rest), viscoelasticity, viscoplasticity and creep, anisotropic and pressure-dependent plasticity, non-Newtonian viscosity, a cited material library and calibration (M17) |
|
||||
| Composites and anisotropy | Orthotropic constants | Orientations, layups, ply results, failure criteria, homogenisation (M18) |
|
||||
| Coupled fields | Thermal–structural (one way and coupled) | Piezoelectric, poroelastic, electro-thermal, acoustics (M19) |
|
||||
|
||||
@@ -15,6 +15,7 @@ use serde_json::json;
|
||||
const USAGE: &str = "\
|
||||
usage:
|
||||
fieldcraft-cli commands list every command with its parameters
|
||||
fieldcraft-cli commands --json the same as JSON, each command's parameters as JSON Schema
|
||||
fieldcraft-cli run <script.json> run a script (a JSON array of {\"command\", \"params\"})
|
||||
and print the model summary
|
||||
fieldcraft-cli features print docs/features.md (every capability, ready or
|
||||
@@ -36,6 +37,10 @@ const MAX_SCRIPT_BYTES: u64 = 256 * 1024 * 1024;
|
||||
fn main() -> ExitCode {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let result = match args.first().map(String::as_str) {
|
||||
Some("commands") if args.get(1).map(String::as_str) == Some("--json") => {
|
||||
let all: Vec<_> = fieldcraft_engine::commands().iter().map(fieldcraft_engine::CommandSpec::listing).collect();
|
||||
serde_json::to_string_pretty(&all).map(|text| println!("{text}")).map_err(|e| e.to_string())
|
||||
}
|
||||
Some("commands") => {
|
||||
for c in fieldcraft_engine::commands() {
|
||||
println!("{:<24} {:<18} {}", c.id, c.label, c.params);
|
||||
|
||||
@@ -5,9 +5,23 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
|
||||
<title>FieldCraft</title>
|
||||
<meta name="description" content="Open-source CAE modeling in Rust: mesh a part, set up the analysis and solve it, in your browser.">
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:site_name" content="FieldCraft">
|
||||
<meta property="og:title" content="FieldCraft">
|
||||
<meta property="og:description" content="Open-source CAE built in Rust: structures, heat, fluids, and MCP for AI agents.">
|
||||
<meta property="og:url" content="https://jyviko.github.io/fieldcraft/">
|
||||
<meta property="og:image" content="https://jyviko.github.io/fieldcraft/og.png">
|
||||
<meta property="og:image:width" content="1280">
|
||||
<meta property="og:image:height" content="640">
|
||||
<meta property="og:image:alt" content="FieldCraft: Open-source CAE built in Rust">
|
||||
<meta name="twitter:card" content="summary_large_image">
|
||||
<meta name="twitter:title" content="FieldCraft">
|
||||
<meta name="twitter:description" content="Open-source CAE built in Rust: structures, heat, fluids, and MCP for AI agents.">
|
||||
<meta name="twitter:image" content="https://jyviko.github.io/fieldcraft/og.png">
|
||||
<link data-trunk rel="rust" data-bin="fieldcraft-web" data-wasm-opt="z" data-weak-refs />
|
||||
<link data-trunk rel="icon" type="image/svg+xml" href="../../assets/app-icon/icon-small.svg" />
|
||||
<link data-trunk rel="copy-file" href="../../assets/app-icon/icon.iconset/[email protected]" data-target-path="icons" />
|
||||
<link data-trunk rel="copy-file" href="../../docs/media/og.png" />
|
||||
<link rel="apple-touch-icon" href="icons/[email protected]">
|
||||
<style>
|
||||
html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background: #262c37; }
|
||||
|
||||
@@ -13,8 +13,20 @@
|
||||
//!
|
||||
//! In order: heading, nodes (mesh nodes, then reference points), elements grouped by element type,
|
||||
//! sets (a node set, an element set and an element-face surface per model set, each written when
|
||||
//! the set resolves to some), materials, sections, couplings, the initial state's boundary
|
||||
//! conditions, then the steps.
|
||||
//! the set resolves to some), materials, sections, couplings, contact, the initial state's
|
||||
//! boundary conditions, then the steps.
|
||||
//!
|
||||
//! # Contact
|
||||
//!
|
||||
//! Each contact is a `*SURFACE INTERACTION` with its friction (`*FRICTION`, or
|
||||
//! `*FRICTION, EXPONENTIAL DECAY` with the static and kinetic coefficients and the decay
|
||||
//! coefficient, the same law). A pair is `*CONTACT PAIR, TYPE=SURFACE TO SURFACE` with the
|
||||
//! secondary surface first, and `ADJUST=0.0` when initially overclosed nodes are adjusted. General
|
||||
//! contact is the model's one `*CONTACT` definition: `*CONTACT INCLUSIONS, ALL EXTERIOR` for every
|
||||
//! exterior face, a surface with a blank partner for self contact, and a
|
||||
//! `*CONTACT PROPERTY ASSIGNMENT` line per contact. FieldCraft's penalty scale and its refusal of
|
||||
//! initial overclosure have no Abaqus counterpart and are noted in comments (Abaqus chooses its
|
||||
//! own penalty and resolves overclosure in the first increment).
|
||||
//!
|
||||
//! # Steps and the activity table
|
||||
//!
|
||||
@@ -130,8 +142,8 @@ use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use fieldcraft_model::{
|
||||
BeamProfile, BoundaryCondition, CouplingKind, Elastic, Element, ElementKind, Hardening, Hyperelastic, Integration, Load, Model, OutputVariable,
|
||||
Plastic, Procedure, Resolved, Section, SectionKind, Step, Symmetry, Target,
|
||||
BeamProfile, BoundaryCondition, ContactSurfaces, CouplingKind, Elastic, Element, ElementKind, Hardening, Hyperelastic, InitialPenetration,
|
||||
Integration, Load, Model, OutputVariable, Plastic, Procedure, Resolved, Section, SectionKind, Step, Symmetry, Target,
|
||||
};
|
||||
|
||||
use crate::{Error, Result, unsupported};
|
||||
@@ -174,6 +186,7 @@ pub fn write_resolved(model: &Model, r: &Resolved) -> Result<String> {
|
||||
d.sections(model)?;
|
||||
d.discrete_properties(&discrete)?;
|
||||
d.couplings(model, r);
|
||||
d.contacts(model, r)?;
|
||||
d.steps(model, r)?;
|
||||
Ok(d.out)
|
||||
}
|
||||
@@ -957,6 +970,78 @@ impl Deck {
|
||||
}
|
||||
}
|
||||
|
||||
/// One surface interaction (the friction) per contact, then its pair, and every general
|
||||
/// contact in the model's one `*CONTACT` definition.
|
||||
fn contacts(&mut self, model: &Model, r: &Resolved) -> Result<()> {
|
||||
if model.contacts().is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut taken: BTreeSet<String> = model.sets().keys().map(|n| n.to_ascii_uppercase()).collect();
|
||||
taken.extend(coupling_surfaces(model, r).into_values().map(|n| n.to_ascii_uppercase()));
|
||||
self.comment("Contact: a surface interaction (Coulomb friction) per contact, contact pairs, general contact");
|
||||
let mut general = Vec::new();
|
||||
for (name, c) in model.contacts() {
|
||||
let interaction = crate::unique_name(&format!("{name}-interaction"), &mut taken);
|
||||
self.line(&format!("*SURFACE INTERACTION, NAME={interaction}"));
|
||||
let f = c.friction;
|
||||
if f.decay > 0.0 {
|
||||
self.line("*FRICTION, EXPONENTIAL DECAY");
|
||||
self.numbers_line("", &[f.static_coefficient, f.kinetic_coefficient(), f.decay])?;
|
||||
} else {
|
||||
self.line("*FRICTION");
|
||||
self.numbers_line("", &[f.static_coefficient])?;
|
||||
}
|
||||
if c.penalty_scale != 1.0 {
|
||||
self.comment(&format!(
|
||||
"contact `{name}`: penalty scale {} of FieldCraft's explicit penalty stiffness; Abaqus chooses its own",
|
||||
c.penalty_scale
|
||||
));
|
||||
}
|
||||
match &c.surfaces {
|
||||
ContactSurfaces::Pair { main, secondary } => {
|
||||
// ADJUST=0.0 moves the secondary nodes that start inside the main surface
|
||||
// onto it, strain-free; Abaqus has no refusal of initial overclosure.
|
||||
let adjust = match c.initial_penetration {
|
||||
InitialPenetration::Adjust => ", ADJUST=0.0",
|
||||
InitialPenetration::Refuse => {
|
||||
self.comment(&format!(
|
||||
"contact `{name}`: FieldCraft refuses initially overclosed nodes; Abaqus resolves them in the first increment"
|
||||
));
|
||||
""
|
||||
}
|
||||
};
|
||||
self.line(&format!("*CONTACT PAIR, INTERACTION={interaction}, TYPE=SURFACE TO SURFACE{adjust}"));
|
||||
self.line(&format!("{secondary}, {main}"));
|
||||
}
|
||||
ContactSurfaces::General { surface } => general.push((surface.clone(), interaction)),
|
||||
}
|
||||
}
|
||||
if general.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
// General contact: every surface against itself (a blank second surface), or every
|
||||
// exterior face; each with its interaction.
|
||||
self.line("*CONTACT");
|
||||
if general.iter().any(|(s, _)| s.is_none()) {
|
||||
self.line("*CONTACT INCLUSIONS, ALL EXTERIOR");
|
||||
}
|
||||
let named: Vec<&str> = general.iter().filter_map(|(s, _)| s.as_deref()).collect();
|
||||
if !named.is_empty() {
|
||||
self.line("*CONTACT INCLUSIONS");
|
||||
for s in &named {
|
||||
self.line(&format!("{s},"));
|
||||
}
|
||||
}
|
||||
self.line("*CONTACT PROPERTY ASSIGNMENT");
|
||||
for (surface, interaction) in &general {
|
||||
match surface {
|
||||
Some(s) => self.line(&format!("{s}, {s}, {interaction}")),
|
||||
None => self.line(&format!(", , {interaction}")),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn boundary_lines<'n>(&mut self, model: &Model, r: &Resolved, names: impl IntoIterator<Item = &'n String>) -> Result<()> {
|
||||
for name in names {
|
||||
let Some(bc) = model.boundary_condition(name) else { continue };
|
||||
@@ -1106,10 +1191,38 @@ impl Deck {
|
||||
Procedure::Fluid { .. } => return Err(crate::fluid_step(FORMAT, &step.name)),
|
||||
Procedure::Static {} | Procedure::NonlinearStatic(_) => {
|
||||
if let Procedure::NonlinearStatic(n) = &step.procedure {
|
||||
if n.imperfection.is_some() {
|
||||
return Err(Error::Unsupported {
|
||||
format: FORMAT,
|
||||
what: format!(
|
||||
"step `{}`: an imperfection from a buckling mode (FieldCraft computes the mode when it solves)",
|
||||
step.name
|
||||
),
|
||||
});
|
||||
}
|
||||
let nlgeom = if n.nonlinear_geometry { "YES" } else { "NO" };
|
||||
self.line(&format!("*STEP, NAME={}, NLGEOM={nlgeom}, INC={}", step.name, n.max_increments));
|
||||
self.line("*STATIC");
|
||||
self.numbers_line("", &[n.initial_increment, 1.0, n.min_increment, n.max_increment])?;
|
||||
if let Some(arc) = &n.arc_length {
|
||||
// Riks: initial arc, period, minimum and maximum arcs, the load
|
||||
// proportionality factor and the displacement that end the step.
|
||||
if arc.constraint != fieldcraft_model::ArcConstraint::Cylindrical {
|
||||
return Err(Error::Unsupported {
|
||||
format: FORMAT,
|
||||
what: format!("step `{}`: a spherical arc-length constraint", step.name),
|
||||
});
|
||||
}
|
||||
self.line("*STATIC, RIKS");
|
||||
self.numbers_line("", &[n.initial_increment, 1.0, n.min_increment, n.max_increment, arc.max_load_factor])?;
|
||||
if let Some(l) = &arc.displacement_limit {
|
||||
self.out.pop();
|
||||
let _ = write!(self.out, ", {}, {}, ", l.node, l.direction);
|
||||
push_number(&mut self.out, l.displacement)?;
|
||||
self.out.push('\n');
|
||||
}
|
||||
} else {
|
||||
self.line("*STATIC");
|
||||
self.numbers_line("", &[n.initial_increment, 1.0, n.min_increment, n.max_increment])?;
|
||||
}
|
||||
if n.line_search {
|
||||
self.line("*CONTROLS, PARAMETERS=LINE SEARCH");
|
||||
self.line("5,");
|
||||
@@ -1131,6 +1244,34 @@ impl Deck {
|
||||
base_bcs.clone_from(&step.boundary_conditions);
|
||||
base_loads.clone_from(&step.loads);
|
||||
}
|
||||
Procedure::Buckle { modes, shift } => {
|
||||
// Abaqus's buckling base state is the end of the previous general step;
|
||||
// FieldCraft's steps all start from the undeformed, unloaded model.
|
||||
if !base_loads.is_empty()
|
||||
|| steps
|
||||
.iter()
|
||||
.take_while(|s| !std::ptr::eq(*s, step))
|
||||
.any(|s| !matches!(s.procedure, Procedure::Frequency { .. } | Procedure::Buckle { .. }))
|
||||
{
|
||||
return Err(Error::Unsupported {
|
||||
format: FORMAT,
|
||||
what: format!(
|
||||
"step `{}`: a buckling step after a general step (Abaqus would buckle from that step's loaded state)",
|
||||
step.name
|
||||
),
|
||||
});
|
||||
}
|
||||
if shift.is_some() {
|
||||
return Err(Error::Unsupported { format: FORMAT, what: format!("step `{}`: a buckling shift", step.name) });
|
||||
}
|
||||
self.line(&format!("*STEP, NAME={}", step.name));
|
||||
self.line("*BUCKLE, EIGENSOLVER=LANCZOS");
|
||||
self.line(&format!("{modes}"));
|
||||
self.step_boundaries(model, r, &base_bcs, &step.boundary_conditions)?;
|
||||
let loads = StepLoads::new(model, r, step, &everything);
|
||||
self.step_loads(&loads, written)?;
|
||||
written = loads.written();
|
||||
}
|
||||
Procedure::Frequency { modes, min_hz, max_hz } => {
|
||||
self.line(&format!("*STEP, NAME={}", step.name));
|
||||
self.line("*FREQUENCY, EIGENSOLVER=LANCZOS");
|
||||
|
||||
@@ -22,6 +22,12 @@
|
||||
//! - couplings: kinematic as `*CONSTRAINED_NODAL_RIGID_BODY` (the reference point first in its
|
||||
//! node set), distributing as `*CONSTRAINED_INTERPOLATION` (the reference point dependent on
|
||||
//! the set's translations, equal weights);
|
||||
//! - contact: a pair as `*CONTACT_AUTOMATIC_SURFACE_TO_SURFACE` between segment sets (the
|
||||
//! secondary surface first), general contact as `*CONTACT_AUTOMATIC_SINGLE_SURFACE` on a segment
|
||||
//! set or on every part (`surfatyp` 5); the static and kinetic coefficients and the decay
|
||||
//! coefficient (`fs`, `fd`, `dc`: the same exponential decay law) and the penalty scale on both
|
||||
//! sides (`sfsa`, `sfsb`, a factor on LS-DYNA's own default stiffness). LS-DYNA moves nodes
|
||||
//! that start inside the other surface out, as `adjust` does; a refusal is noted in a comment;
|
||||
//! - per step: `*CONTROL_IMPLICIT_GENERAL`, `*CONTROL_IMPLICIT_SOLUTION` (linear) or
|
||||
//! `*CONTROL_IMPLICIT_EIGENVALUE`, `*CONTROL_TERMINATION` (a static step is one implicit step
|
||||
//! from time 0 to 1 with every load ramped by one curve, `*DEFINE_CURVE`); a nonlinear static
|
||||
@@ -69,8 +75,8 @@ mod elements;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use fieldcraft_model::{
|
||||
BoundaryCondition, CouplingKind, Diagnostic, Dofs, Elastic, Element, ElementKind, Hardening, Load, Material, Model, OutputVariable, Plastic,
|
||||
Procedure, Resolved, ResolvedDirection, Section, SectionKind, Step, Target,
|
||||
BoundaryCondition, ContactSurfaces, CouplingKind, Diagnostic, Dofs, Elastic, Element, ElementKind, Hardening, InitialPenetration, Load, Material,
|
||||
Model, OutputVariable, Plastic, Procedure, Resolved, ResolvedDirection, Section, SectionKind, Step, Target,
|
||||
};
|
||||
|
||||
use crate::{Error, Result};
|
||||
@@ -177,6 +183,7 @@ fn write_with(model: &Model, r: &Resolved) -> Result<Written> {
|
||||
element_cards(&mut d, &plan)?;
|
||||
sets(&mut d, model, r, &plan)?;
|
||||
couplings(&mut d, model, r, &plan)?;
|
||||
contacts(&mut d, model, &plan)?;
|
||||
discrete(&mut d, model, r, &plan)?;
|
||||
if let Some(parts) = &plan.gravity_parts {
|
||||
d.line("*SET_PART_LIST");
|
||||
@@ -269,6 +276,10 @@ fn plan<'a>(model: &'a Model, r: &Resolved) -> Result<Plan<'a>> {
|
||||
node_sets.insert(c.set.as_str());
|
||||
}
|
||||
}
|
||||
// Contact surfaces are segment sets.
|
||||
for c in model.contacts().values() {
|
||||
segment_sets.extend(c.surfaces.sets());
|
||||
}
|
||||
let mut gravity_sets: BTreeSet<Option<&str>> = BTreeSet::new();
|
||||
for step in model.steps() {
|
||||
if matches!(step.procedure, Procedure::ExplicitDynamic(_)) {
|
||||
@@ -689,6 +700,42 @@ fn couplings(d: &mut Deck, model: &Model, r: &Resolved, plan: &Plan) -> Result<(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Contacts (see the module docs): a pair as an automatic surface-to-surface contact between the
|
||||
/// segment sets, general contact as an automatic single-surface contact.
|
||||
fn contacts(d: &mut Deck, model: &Model, plan: &Plan) -> Result<()> {
|
||||
for (name, c) in model.contacts() {
|
||||
let sid = |set: &str| plan.sets.get(set).copied().ok_or_else(|| broken(format!("contact `{name}`: set `{set}`")));
|
||||
d.comment(&format!("contact `{name}`"));
|
||||
if c.initial_penetration == InitialPenetration::Refuse {
|
||||
d.comment("FieldCraft refuses nodes that start inside the other surface; LS-DYNA moves them out (as `adjust` does)");
|
||||
}
|
||||
match &c.surfaces {
|
||||
ContactSurfaces::Pair { main, secondary } => {
|
||||
d.line("*CONTACT_AUTOMATIC_SURFACE_TO_SURFACE");
|
||||
d.header(&["surfa", "surfb", "surfatyp", "surfbtyp"]);
|
||||
d.card([Field::from(sid(secondary)?), Field::from(sid(main)?), Field::from(0), Field::from(0)]);
|
||||
}
|
||||
ContactSurfaces::General { surface: Some(s) } => {
|
||||
d.line("*CONTACT_AUTOMATIC_SINGLE_SURFACE");
|
||||
d.header(&["surfa", "surfb", "surfatyp"]);
|
||||
d.card([Field::from(sid(s)?), Field::Blank, Field::from(0)]);
|
||||
}
|
||||
ContactSurfaces::General { surface: None } => {
|
||||
// SURFATYP 5: every part.
|
||||
d.line("*CONTACT_AUTOMATIC_SINGLE_SURFACE");
|
||||
d.header(&["surfa", "surfb", "surfatyp"]);
|
||||
d.card([Field::from(0), Field::Blank, Field::from(5)]);
|
||||
}
|
||||
}
|
||||
let f = c.friction;
|
||||
d.header(&["fs", "fd", "dc"]);
|
||||
d.card([Field::from(f.static_coefficient), Field::from(f.kinetic_coefficient()), Field::from(f.decay)]);
|
||||
d.header(&["sfsa", "sfsb"]);
|
||||
d.card([Field::from(c.penalty_scale), Field::from(c.penalty_scale)]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Point masses, springs and dashpots (see the module docs).
|
||||
fn discrete(d: &mut Deck, model: &Model, r: &Resolved, plan: &Plan) -> Result<()> {
|
||||
if r.masses.is_empty() && r.springs.is_empty() {
|
||||
@@ -827,6 +874,15 @@ fn write_step(d: &mut Deck, model: &Model, r: &Resolved, plan: &Plan, step: &Ste
|
||||
d.card([Field::from(1)]);
|
||||
}
|
||||
Procedure::NonlinearStatic(n) => {
|
||||
if n.arc_length.is_some() {
|
||||
return Err(Error::Unsupported { format: FORMAT, what: format!("step `{}`: arc-length control", step.name) });
|
||||
}
|
||||
if n.imperfection.is_some() {
|
||||
return Err(Error::Unsupported {
|
||||
format: FORMAT,
|
||||
what: format!("step `{}`: an imperfection from a buckling mode (FieldCraft computes the mode when it solves)", step.name),
|
||||
});
|
||||
}
|
||||
// Nonlinear with a stiffness reformation every iteration (full Newton), at most
|
||||
// `max_iterations` per increment; LS-DYNA's own convergence norms and line search.
|
||||
d.line("*CONTROL_IMPLICIT_SOLUTION");
|
||||
@@ -852,7 +908,7 @@ fn write_step(d: &mut Deck, model: &Model, r: &Resolved, plan: &Plan, step: &Ste
|
||||
d.card([Field::Blank, Field::Blank, Field::Blank, Field::Blank, Field::from(1)]);
|
||||
}
|
||||
}
|
||||
Procedure::ExplicitDynamic(_) | Procedure::HeatTransfer { .. } | Procedure::CoupledTemperatureDisplacement {} => {
|
||||
Procedure::ExplicitDynamic(_) | Procedure::HeatTransfer { .. } | Procedure::CoupledTemperatureDisplacement {} | Procedure::Buckle { .. } => {
|
||||
return Err(Error::Unsupported { format: FORMAT, what: format!("step `{}`: {} steps", step.name, step.procedure.name()) });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,6 +280,9 @@ fn solution(steps: &[&Step]) -> std::result::Result<u32, String> {
|
||||
if let Some(s) = steps.iter().find(|s| matches!(s.procedure, Procedure::ExplicitDynamic(_))) {
|
||||
return Err(format!("step `{}`: explicit dynamic steps (Nastran's linear solutions have none)", s.name));
|
||||
}
|
||||
if let Some(s) = steps.iter().find(|s| matches!(s.procedure, Procedure::Buckle { .. })) {
|
||||
return Err(format!("step `{}`: buckling steps (Nastran's SOL 105; this writer writes SOL 101 and 103 so far)", s.name));
|
||||
}
|
||||
if let Some(s) = steps.iter().find(|s| matches!(s.procedure, Procedure::NonlinearStatic(_))) {
|
||||
return Err(format!("step `{}`: nonlinear static steps (Nastran's SOL 400; this writer writes SOL 101 and 103 so far)", s.name));
|
||||
}
|
||||
@@ -331,6 +334,9 @@ impl<'m> Deck<'m> {
|
||||
self.plan_constraints()?;
|
||||
self.plan_loads()?;
|
||||
self.problems.extend(crate::thermal_items(self.model));
|
||||
for name in self.model.contacts().keys() {
|
||||
self.problems.insert(format!("contact `{name}` (Nastran's linear solutions SOL 101 and 103 have no contact)"));
|
||||
}
|
||||
for sub in &mut self.subcases {
|
||||
if matches!(sub.step.procedure, Procedure::Frequency { .. }) {
|
||||
sub.method = Some(next_id(&mut self.next_sid)?);
|
||||
|
||||
@@ -828,3 +828,42 @@ fn nonlinear_plastic_steps_and_what_is_refused() {
|
||||
m.add_step(step("Again", Procedure::NonlinearStatic(NonlinearStatic::default()), &["clamp"], &["end"]), None).unwrap();
|
||||
assert!(unsupported(&m).contains("plastic material `Steel` in a deck of 2 general steps"));
|
||||
}
|
||||
|
||||
/// A buckling step is `*BUCKLE` with its loads as the perturbation loads; after a general step
|
||||
/// (Abaqus's base state would be that step's) and with a shift it is refused by name.
|
||||
#[test]
|
||||
fn buckling_steps() {
|
||||
let mut m = cantilever_mesh();
|
||||
m.add_load("end", Load::Force { target: Target::Set("tip".into()), vector: [-100.0, 0.0, 0.0], distribution: Distribution::Total }).unwrap();
|
||||
m.add_step(step("Buckle", Procedure::Buckle { modes: 4, shift: None }, &["clamp"], &["end"]), None).unwrap();
|
||||
let deck = abaqus::write(&m).unwrap();
|
||||
assert!(deck.contains("*BUCKLE, EIGENSOLVER=LANCZOS\n4\n") && deck.contains("*CLOAD"), "{deck}");
|
||||
let mut shifted = m.clone();
|
||||
shifted.replace_step(step("Buckle", Procedure::Buckle { modes: 4, shift: Some(2.0) }, &["clamp"], &["end"])).unwrap();
|
||||
assert!(abaqus::write(&shifted).unwrap_err().to_string().contains("shift"));
|
||||
m.add_step(step("Bend", Procedure::Static {}, &["clamp"], &["end"]), Some("Buckle")).unwrap();
|
||||
assert!(abaqus::write(&m).unwrap_err().to_string().contains("after a general step"));
|
||||
assert!(fieldcraft_decks::lsdyna::write(&m).is_err() && fieldcraft_decks::nastran::write(&m).is_err());
|
||||
}
|
||||
|
||||
/// An arc-length step is `*STATIC, RIKS` with the arcs, the maximum load factor and the
|
||||
/// displacement that end it; a spherical constraint is refused, and LS-DYNA refuses the step.
|
||||
#[test]
|
||||
fn arc_length_steps() {
|
||||
use fieldcraft_model::{ArcConstraint, ArcLength, DisplacementLimit, NonlinearStatic};
|
||||
let mut m = cantilever_mesh();
|
||||
m.add_load("end", Load::Force { target: Target::Set("tip".into()), vector: [0.0, 0.0, -100.0], distribution: Distribution::Total }).unwrap();
|
||||
let arc = ArcLength {
|
||||
max_load_factor: 3.0,
|
||||
displacement_limit: Some(DisplacementLimit { node: 2, direction: 3, displacement: -5.0 }),
|
||||
..ArcLength::default()
|
||||
};
|
||||
let settings = NonlinearStatic { arc_length: Some(arc.clone()), ..NonlinearStatic::default() };
|
||||
m.add_step(step("Snap", Procedure::NonlinearStatic(settings), &["clamp"], &["end"]), None).unwrap();
|
||||
let deck = abaqus::write(&m).unwrap();
|
||||
assert!(deck.contains("*STATIC, RIKS\n0.1, 1.0, 1.0E-5, 1.0, 3.0, 2, 3, -5.0\n"), "{deck}");
|
||||
assert!(fieldcraft_decks::lsdyna::write(&m).is_err());
|
||||
let spherical = NonlinearStatic { arc_length: Some(ArcLength { constraint: ArcConstraint::Spherical, ..arc }), ..NonlinearStatic::default() };
|
||||
m.replace_step(step("Snap", Procedure::NonlinearStatic(spherical), &["clamp"], &["end"])).unwrap();
|
||||
assert!(abaqus::write(&m).is_err());
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//! Contact definitions in every deck format: Abaqus surface interactions, contact pairs and
|
||||
//! general contact; LS-DYNA automatic contacts; Nastran refuses them by name.
|
||||
|
||||
use fieldcraft_decks::{Error, abaqus, lsdyna, nastran};
|
||||
use fieldcraft_model::{
|
||||
BoundaryCondition, Contact, ContactSurfaces, Elastic, ElementFace, ElementKind, Friction, InitialPenetration, Material, Model, Procedure,
|
||||
Section, SectionKind, Set, Step, Target, UnitSystem,
|
||||
};
|
||||
|
||||
/// Two unit hex8 cubes, the second on top of the first (separate nodes), with face sets for the
|
||||
/// touching faces and a static step.
|
||||
fn model() -> Model {
|
||||
let mut m = Model::default();
|
||||
m.set_units(UnitSystem::MmTonneS);
|
||||
let corners = [[0., 0., 0.], [1., 0., 0.], [1., 1., 0.], [0., 1., 0.], [0., 0., 1.], [1., 0., 1.], [1., 1., 1.], [0., 1., 1.]];
|
||||
for cube in 0..2u32 {
|
||||
for (i, c) in corners.iter().enumerate() {
|
||||
m.set_node(8 * cube + i as u32 + 1, [c[0], c[1], c[2] + cube as f64]).unwrap();
|
||||
}
|
||||
m.set_element(cube + 1, ElementKind::Hex8, (8 * cube + 1..=8 * cube + 8).collect()).unwrap();
|
||||
}
|
||||
m.add_set("all", Set { elements: vec![1, 2], ..Set::default() }).unwrap();
|
||||
m.add_set("lower", Set { faces: vec![ElementFace { element: 1, face: 2 }], ..Set::default() }).unwrap();
|
||||
m.add_set("upper", Set { faces: vec![ElementFace { element: 2, face: 1 }], ..Set::default() }).unwrap();
|
||||
m.add_set("base", Set { nodes: vec![1, 2, 3, 4], ..Set::default() }).unwrap();
|
||||
m.add_material(
|
||||
"Steel",
|
||||
Material { elastic: Some(Elastic::Isotropic { young: 210_000.0, poisson: 0.3 }), density: Some(7.85e-9), ..Material::default() },
|
||||
)
|
||||
.unwrap();
|
||||
m.add_section("all", Section { set: "all".into(), material: "Steel".into(), kind: SectionKind::Solid {}, formulation: Default::default() })
|
||||
.unwrap();
|
||||
m.add_boundary_condition("fix", BoundaryCondition::Fixed { target: Target::Set("base".into()) }).unwrap();
|
||||
let mut step = Step::new("Load", Procedure::Static {});
|
||||
step.boundary_conditions.insert("fix".into());
|
||||
m.add_step(step, None).unwrap();
|
||||
let pair = Contact {
|
||||
friction: Friction { static_coefficient: 0.3, kinetic: Some(0.2), decay: 5.0 },
|
||||
initial_penetration: InitialPenetration::Adjust,
|
||||
..Contact::new(ContactSurfaces::Pair { main: "lower".into(), secondary: "upper".into() })
|
||||
};
|
||||
m.add_contact("stack", pair).unwrap();
|
||||
m.add_contact("everything", Contact { friction: Friction::coulomb(0.1), ..Contact::new(ContactSurfaces::General { surface: None }) }).unwrap();
|
||||
m.add_contact("fold", Contact { penalty_scale: 0.5, ..Contact::new(ContactSurfaces::General { surface: Some("upper".into()) }) }).unwrap();
|
||||
m
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn abaqus_writes_interactions_pairs_and_general_contact() {
|
||||
let deck = abaqus::write(&model()).unwrap();
|
||||
for expected in [
|
||||
"*SURFACE, TYPE=ELEMENT, NAME=lower\n1, S2\n",
|
||||
"*SURFACE INTERACTION, NAME=stack-interaction\n*FRICTION, EXPONENTIAL DECAY\n0.3, 0.2, 5.0\n",
|
||||
"*CONTACT PAIR, INTERACTION=stack-interaction, TYPE=SURFACE TO SURFACE, ADJUST=0.0\nupper, lower\n",
|
||||
"*SURFACE INTERACTION, NAME=everything-interaction\n*FRICTION\n0.1\n",
|
||||
"*SURFACE INTERACTION, NAME=fold-interaction\n*FRICTION\n0.0\n",
|
||||
"*CONTACT\n*CONTACT INCLUSIONS, ALL EXTERIOR\n*CONTACT INCLUSIONS\nupper,\n*CONTACT PROPERTY ASSIGNMENT\n, , everything-interaction\nupper, upper, fold-interaction\n",
|
||||
"** contact `fold`: penalty scale 0.5",
|
||||
] {
|
||||
assert!(deck.contains(expected), "{expected}\n{deck}");
|
||||
}
|
||||
// Model data: before the first step.
|
||||
assert!(deck.find("*CONTACT PAIR") < deck.find("*STEP"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lsdyna_writes_automatic_contacts_on_segment_sets() {
|
||||
let deck = lsdyna::write(&model()).unwrap().text;
|
||||
let after = |keyword: &str| -> Vec<String> {
|
||||
let at = deck.find(keyword).unwrap_or_else(|| panic!("{keyword}\n{deck}"));
|
||||
deck[at..].lines().skip(1).filter(|l| !l.starts_with('$')).take(3).map(|l| l.split_whitespace().collect::<Vec<_>>().join(" ")).collect()
|
||||
};
|
||||
// Sets are numbered in name order: all 1, base 2, lower 3, upper 4.
|
||||
assert_eq!(after("*CONTACT_AUTOMATIC_SURFACE_TO_SURFACE"), ["4 3 0 0", "0.3 0.2 5.0", "1.0 1.0"], "{deck}");
|
||||
let single: Vec<&str> = deck.match_indices("*CONTACT_AUTOMATIC_SINGLE_SURFACE").map(|(i, _)| &deck[i..]).collect();
|
||||
assert_eq!(single.len(), 2, "{deck}");
|
||||
let cards = |text: &str| -> Vec<String> {
|
||||
text.lines().skip(1).filter(|l| !l.starts_with('$')).take(3).map(|l| l.split_whitespace().collect::<Vec<_>>().join(" ")).collect()
|
||||
};
|
||||
// `everything` (every part), then `fold` (the upper face's segment set).
|
||||
assert_eq!(cards(single[0]), ["0 5", "0.1 0.1 0.0", "1.0 1.0"], "{deck}");
|
||||
assert_eq!(cards(single[1]), ["4 0", "0.0 0.0 0.0", "0.5 0.5"], "{deck}");
|
||||
for set in ["lower", "upper"] {
|
||||
assert!(deck.contains(&format!("*SET_SEGMENT_TITLE\n{set}\n")), "{set}\n{deck}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nastran_refuses_contact_by_name() {
|
||||
match nastran::write(&model()) {
|
||||
Err(Error::Unsupported { what, .. }) => {
|
||||
for name in ["everything", "fold", "stack"] {
|
||||
assert!(what.contains(&format!("contact `{name}`")), "{what}");
|
||||
}
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
@@ -415,9 +415,29 @@ pub static CATALOGUE: &[Capability] = &[
|
||||
&["model.coupling.edit", "model.coupling.delete"],
|
||||
),
|
||||
soon("interaction.tie", "Tie", Interactions, "Constraints", "M7", "Tie non-matching meshes together"),
|
||||
soon("interaction.contact.general", "General Contact", Interactions, "Contact", "M7", "Contact between everything that touches, with friction"),
|
||||
soon("interaction.contact.pair", "Contact Pair", Interactions, "Contact", "M7", "Contact between two surfaces"),
|
||||
soon("interaction.contact.find", "Find Contacts", Interactions, "Contact", "M7", "Detect contact pairs automatically"),
|
||||
ready_more(
|
||||
"interaction.contact.general",
|
||||
"General Contact",
|
||||
Interactions,
|
||||
"Contact",
|
||||
"Contact between everything that may touch, or self contact of a surface, with friction (explicit dynamics)",
|
||||
&["interaction.contact.edit", "interaction.contact.delete"],
|
||||
),
|
||||
ready_more(
|
||||
"interaction.contact.pair",
|
||||
"Contact Pair",
|
||||
Interactions,
|
||||
"Contact",
|
||||
"Contact between two surfaces, with friction (explicit dynamics)",
|
||||
&["interaction.contact.edit", "interaction.contact.delete"],
|
||||
),
|
||||
ready(
|
||||
"interaction.contact.find",
|
||||
"Find Contacts",
|
||||
Interactions,
|
||||
"Contact",
|
||||
"Find the parts of the mesh that touch, and make contact pairs of them",
|
||||
),
|
||||
soon("interaction.rigid_wall", "Rigid Wall", Interactions, "Contact", "M10", "Rigid walls for explicit dynamics"),
|
||||
soon("interaction.bolt", "Bolt Load", Interactions, "Connectors", "M7", "Bolt pretension"),
|
||||
ready_more(
|
||||
@@ -450,8 +470,8 @@ pub static CATALOGUE: &[Capability] = &[
|
||||
"Static",
|
||||
Solve,
|
||||
"Implicit",
|
||||
"Linear static (or coupled temperature–displacement) solve of a step with FieldCraft's own solver; nonlinear static and heat transfer in the drop-down",
|
||||
&["solve.nonlinear", "solve.heat"],
|
||||
"Linear static (or coupled temperature–displacement) solve of a step with FieldCraft's own solver; nonlinear static, buckling and heat transfer in the drop-down",
|
||||
&["solve.nonlinear", "solve.buckle", "solve.heat"],
|
||||
),
|
||||
ready("solve.frequency", "Frequency", Solve, "Implicit", "Natural frequencies and mode shapes of a frequency step"),
|
||||
ready(
|
||||
|
||||
@@ -18,6 +18,7 @@ pub const BLOCK: CommandSpec = CommandSpec {
|
||||
id: "mesh.block",
|
||||
label: "Mesh Block",
|
||||
params: r#"{"body": "Plate", "kind": "hex8|hex20|tet4|tet10|wedge6", "corners": [[x, y, z] × 8] (hex8 order: 1-2-3-4 counter-clockwise seen from 5-6-7-8), "divisions": [n12, n14, n15] (elements along 1→2, 1→4, 1→5), "bias": [1, 1, 1] (optional: last over first element size along each direction), "edges": [{"corners": [1, 2], "arc": {"center": [x, y, z]}} | {"corners": [2, 3], "ellipse": {"center": [x, y, z], "axes": [[a], [b]] (perpendicular)}} | {"corners": [5, 6], "name": "tip_edge"}] (optional: curved edges, the shorter arc between the corners, and edge names), "faces": {"1": "bottom", "4": "tip"} (optional: names of block faces, numbered as hex8 faces: 1 = 1-2-3-4, 2 = 5-6-7-8, 3 = 1-2-6-5, 4 = 2-3-7-6, 5 = 3-4-8-7, 6 = 4-1-5-8), "vertices": {"1": "A"} (optional: names of corners), "merge": distance (optional, default 1e-6 of the block's diagonal; 0 never joins)} — adds a mapped mesh of the block (transfinite interpolation of its edges; quadratic nodes on the curves), uses existing nodes within `merge` of new ones so blocks that share a face join (the shared face must have the same elements on both sides, or nothing changes), and tags the elements with the body and element faces, edges and nodes with the named faces, edges and vertices. 2D: "kind": "quad4|quad8|tri3|tri6", four "corners" at z = 0 (counter-clockwise from +z), "divisions": [n12, n14], "bias": [r, r], "face": "area" (the face of the body the elements fill, default `area`), edges and vertices numbered among the four corners; for plane stress, plane strain and axisymmetric sections"#,
|
||||
form: Some(super::forms::BLOCK),
|
||||
kind: CommandKind::Model,
|
||||
run: block_mesh,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,363 @@
|
||||
//! `interaction.contact.*`: contact definitions (pairs of surfaces, general contact) and the
|
||||
//! search for surfaces that touch.
|
||||
//!
|
||||
//! A contact's surfaces are sets of element faces ([`fieldcraft_model::contact`]). The commands
|
||||
//! take the friction, penalty scale and initial-penetration choice of the model's form; `edit`
|
||||
//! replaces a definition with the model's JSON form, `delete` removes it.
|
||||
//!
|
||||
//! `find` looks for the bodies of the mesh that touch: the solid elements are split into
|
||||
//! connected parts (elements sharing a node belong to the same part), and a node of one part's
|
||||
//! exterior faces within `tolerance` of an exterior face of another part makes the two parts
|
||||
//! touch there. Each touching pair is reported with the faces of each side that are close to the
|
||||
//! other; with `create`, each becomes two face sets and a contact pair.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use fieldcraft_fem::contact::{Grid, bounds, closest_point};
|
||||
use fieldcraft_model::{Contact, ContactSurfaces, ElementFace, Friction, InitialPenetration, Model, Set};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{name, opt};
|
||||
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
|
||||
|
||||
/// The options every contact takes, from the parameters.
|
||||
fn contact(p: &Value, surfaces: ContactSurfaces) -> Result<Contact> {
|
||||
Ok(Contact {
|
||||
surfaces,
|
||||
friction: opt::<Friction>(p, "friction")?.unwrap_or(Friction::NONE),
|
||||
penalty_scale: opt::<f64>(p, "penalty_scale")?.unwrap_or(1.0),
|
||||
initial_penetration: opt::<InitialPenetration>(p, "initial_penetration")?.unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// A required name-valued parameter.
|
||||
fn text<'a>(p: &'a Value, key: &str) -> Result<&'a str> {
|
||||
p.get(key).and_then(Value::as_str).ok_or_else(|| EngineError::Params(format!("`{key}` must be a set name")))
|
||||
}
|
||||
|
||||
pub const PAIR: CommandSpec = CommandSpec {
|
||||
id: "interaction.contact.pair",
|
||||
label: "Contact Pair",
|
||||
params: concat!(
|
||||
r#"{"name": "impact", "main": "plate" (a set of element faces), "secondary": "ball" (another), "#,
|
||||
r#""friction": {"static": 0.3, "kinetic": 0.2, "decay": 10} (Coulomb, μ = μk + (μs − μk) e^(−decay × slip rate); default frictionless), "penalty_scale": 1 (0 < scale ≤ 1: a factor on the stiffest penalty that leaves the time increment alone), "initial_penetration": "adjust" (move nodes that start inside onto the surface, strain-free, and report them) | "refuse" (refuse the analysis, naming the first)"#,
|
||||
r#"} — contact between two surfaces, each one's nodes kept out of the other's faces (explicit dynamics; fails if the name is taken)"#
|
||||
),
|
||||
form: Some(super::forms::CONTACT_PAIR),
|
||||
kind: CommandKind::Model,
|
||||
run: |s: &mut Session, p: &Value| {
|
||||
let n = name(p)?;
|
||||
let surfaces = ContactSurfaces::Pair { main: text(p, "main")?.to_string(), secondary: text(p, "secondary")?.to_string() };
|
||||
s.model.add_contact(n, contact(p, surfaces)?)?;
|
||||
Ok(json!({"name": n}))
|
||||
},
|
||||
};
|
||||
|
||||
pub const GENERAL: CommandSpec = CommandSpec {
|
||||
id: "interaction.contact.general",
|
||||
label: "General Contact",
|
||||
params: concat!(
|
||||
r#"{"name": "all", "surface": "skin" (optional: a set of element faces, each in contact with every other: self contact; default every exterior face of the solids), "#,
|
||||
r#""friction": {"static": 0.3, "kinetic": 0.2, "decay": 10} (Coulomb, μ = μk + (μs − μk) e^(−decay × slip rate); default frictionless), "penalty_scale": 1 (0 < scale ≤ 1: a factor on the stiffest penalty that leaves the time increment alone), "initial_penetration": "adjust" (move nodes that start inside onto the surface, strain-free, and report them) | "refuse" (refuse the analysis, naming the first)"#,
|
||||
r#"} — single-surface contact of everything that may touch (explicit dynamics; fails if the name is taken)"#
|
||||
),
|
||||
form: Some(super::forms::CONTACT_GENERAL),
|
||||
kind: CommandKind::Model,
|
||||
run: |s: &mut Session, p: &Value| {
|
||||
let n = name(p)?;
|
||||
let surface = match p.get("surface") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => Some(text(p, "surface")?.to_string()),
|
||||
};
|
||||
s.model.add_contact(n, contact(p, ContactSurfaces::General { surface })?)?;
|
||||
Ok(json!({"name": n}))
|
||||
},
|
||||
};
|
||||
|
||||
pub const EDIT: CommandSpec = CommandSpec {
|
||||
id: "interaction.contact.edit",
|
||||
label: "Edit Contact",
|
||||
params: r#"{"name": "impact", "surfaces": {"type": "pair", "main": "plate", "secondary": "ball"} | {"type": "general", "surface": "skin" (optional)}, "friction": {…}, "penalty_scale": 1, "initial_penetration": "adjust|refuse"} — replaces the contact of that name (the model's form; see interaction.contact.pair)"#,
|
||||
form: Some(super::forms::CONTACT_EDIT),
|
||||
kind: CommandKind::Model,
|
||||
run: |s: &mut Session, p: &Value| {
|
||||
let n = name(p)?;
|
||||
let mut obj = p.as_object().cloned().ok_or_else(|| EngineError::Params("the parameters of a contact are a JSON object".into()))?;
|
||||
obj.remove("name");
|
||||
let c: Contact = serde_json::from_value(Value::Object(obj)).map_err(|e| EngineError::Params(format!("contact: {e}")))?;
|
||||
s.model.replace_contact(n, c)?;
|
||||
Ok(json!({"name": n}))
|
||||
},
|
||||
};
|
||||
|
||||
pub const DELETE: CommandSpec = CommandSpec {
|
||||
id: "interaction.contact.delete",
|
||||
label: "Delete Contact",
|
||||
params: r#"{"name": "impact"}"#,
|
||||
form: Some(super::forms::CONTACT_DELETE),
|
||||
kind: CommandKind::Model,
|
||||
run: |s: &mut Session, p: &Value| {
|
||||
s.model.remove_contact(name(p)?)?;
|
||||
Ok(Value::Null)
|
||||
},
|
||||
};
|
||||
|
||||
pub const FIND: CommandSpec = CommandSpec {
|
||||
id: "interaction.contact.find",
|
||||
label: "Find Contacts",
|
||||
params: concat!(
|
||||
r#"{"tolerance": 0.1 (distance within which surfaces touch; default a tenth of the mean exterior face size), "create": false (true: add two face sets and a contact pair per touching pair of parts, named find-N-main, find-N-secondary and find-N), "#,
|
||||
r#""friction", "penalty_scale", "initial_penetration" (of the created pairs, as interaction.contact.pair)} — the parts of the mesh (solid elements connected through their nodes) whose exterior faces come within the tolerance of each other"#
|
||||
),
|
||||
form: Some(super::forms::CONTACT_FIND),
|
||||
kind: CommandKind::Model,
|
||||
run: find,
|
||||
};
|
||||
|
||||
/// Most touching part pairs `find` reports.
|
||||
pub const MAX_FOUND: usize = fieldcraft_model::contact::MAX_CONTACTS;
|
||||
|
||||
/// Most point–face checks `find` makes.
|
||||
pub const MAX_CHECKS: usize = 200_000_000;
|
||||
|
||||
/// The connected parts of the solid elements: per element label, its part (numbered from 0 in
|
||||
/// the order of their lowest element label).
|
||||
fn parts(model: &Model) -> BTreeMap<u32, usize> {
|
||||
// Union–find over the node labels of the solid elements.
|
||||
let solids: Vec<(u32, &[u32])> =
|
||||
model.elements().iter().filter(|(_, e)| e.kind.dimension() == 3).map(|(l, e)| (*l, e.nodes.as_slice())).collect();
|
||||
let mut index: BTreeMap<u32, usize> = BTreeMap::new();
|
||||
for (_, nodes) in &solids {
|
||||
for n in *nodes {
|
||||
let next = index.len();
|
||||
index.entry(*n).or_insert(next);
|
||||
}
|
||||
}
|
||||
let mut parent: Vec<usize> = (0..index.len()).collect();
|
||||
fn root(parent: &mut [usize], mut i: usize) -> usize {
|
||||
while let Some(&p) = parent.get(i) {
|
||||
if p == i {
|
||||
break;
|
||||
}
|
||||
let grand = parent.get(p).copied().unwrap_or(p);
|
||||
if let Some(slot) = parent.get_mut(i) {
|
||||
*slot = grand;
|
||||
}
|
||||
i = grand;
|
||||
}
|
||||
i
|
||||
}
|
||||
for (_, nodes) in &solids {
|
||||
let mut it = nodes.iter().filter_map(|n| index.get(n).copied());
|
||||
let Some(first) = it.next() else { continue };
|
||||
for other in it {
|
||||
let (a, b) = (root(&mut parent, first), root(&mut parent, other));
|
||||
if a != b {
|
||||
let (lo, hi) = (a.min(b), a.max(b));
|
||||
if let Some(slot) = parent.get_mut(hi) {
|
||||
*slot = lo;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Number the parts in element order.
|
||||
let mut numbers: BTreeMap<usize, usize> = BTreeMap::new();
|
||||
let mut out = BTreeMap::new();
|
||||
for (label, nodes) in &solids {
|
||||
let Some(r) = nodes.first().and_then(|n| index.get(n).copied()).map(|i| root(&mut parent, i)) else { continue };
|
||||
let next = numbers.len();
|
||||
out.insert(*label, *numbers.entry(r).or_insert(next));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn find(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let model = &s.model;
|
||||
let faces = model.exterior_faces();
|
||||
let part_of = parts(model);
|
||||
// Each exterior face's corner coordinates and part.
|
||||
let mut face_xyz: Vec<Vec<[f64; 3]>> = Vec::with_capacity(faces.len());
|
||||
for f in &faces {
|
||||
let labels = model.face_nodes(*f).unwrap_or_default();
|
||||
let corners = if labels.len() == 3 || labels.len() == 6 { 3 } else { 4 };
|
||||
face_xyz.push(labels.iter().take(corners).filter_map(|l| model.node(*l)).map(|n| n.xyz).collect());
|
||||
}
|
||||
let size = {
|
||||
let sizes: Vec<f64> = face_xyz
|
||||
.iter()
|
||||
.filter_map(|x| {
|
||||
let b = bounds(x, 0.0);
|
||||
let d = (0..3).map(|k| b[1][k] - b[0][k]).fold(0.0, f64::max);
|
||||
d.is_finite().then_some(d)
|
||||
})
|
||||
.collect();
|
||||
if sizes.is_empty() { 0.0 } else { sizes.iter().sum::<f64>() / sizes.len() as f64 }
|
||||
};
|
||||
let tolerance = opt::<f64>(p, "tolerance")?.unwrap_or(0.1 * size);
|
||||
if !(tolerance >= 0.0 && tolerance.is_finite()) {
|
||||
return Err(EngineError::Params(format!("`tolerance` must be a finite distance ≥ 0, got {tolerance}")));
|
||||
}
|
||||
let create = opt::<bool>(p, "create")?.unwrap_or(false);
|
||||
let options = contact(p, ContactSurfaces::General { surface: None })?;
|
||||
options.validate()?;
|
||||
|
||||
let boxes: Vec<_> = face_xyz.iter().map(|x| bounds(x, tolerance)).collect();
|
||||
let grid = Grid::new(&boxes, 4 * faces.len() + 64);
|
||||
let part = |c: usize| faces.get(c).and_then(|f| part_of.get(&f.element).copied());
|
||||
// Each face's centroid and outward normal there.
|
||||
let centroid = |x: &[[f64; 3]]| -> [f64; 3] { [0, 1, 2].map(|k| x.iter().map(|p| p[k]).sum::<f64>() / x.len().max(1) as f64) };
|
||||
let normals: Vec<Option<[f64; 3]>> = face_xyz.iter().map(|x| closest_point(x, centroid(x)).map(|q| q.normal)).collect();
|
||||
// (lower part, higher part) → the faces of each side that touch the other: a face whose
|
||||
// centroid or a corner is within the tolerance of a face of the other part facing it
|
||||
// (normals more than 60° apart from parallel).
|
||||
let mut touching: BTreeMap<(usize, usize), [std::collections::BTreeSet<usize>; 2]> = BTreeMap::new();
|
||||
let mut checks = 0usize;
|
||||
for (c, xyz) in face_xyz.iter().enumerate() {
|
||||
let (Some(k), Some(normal)) = (part(c), normals.get(c).copied().flatten()) else { continue };
|
||||
for point in xyz.iter().copied().chain(std::iter::once(centroid(xyz))) {
|
||||
let candidates = grid.candidates(point);
|
||||
checks += candidates.len();
|
||||
if checks > MAX_CHECKS {
|
||||
return Err(EngineError::Params(format!(
|
||||
"the tolerance {tolerance:e} puts too many faces near each other (more than {MAX_CHECKS} checks); lower it"
|
||||
)));
|
||||
}
|
||||
for &d in candidates {
|
||||
let d = d as usize;
|
||||
let Some(other) = part(d).filter(|o| *o != k) else { continue };
|
||||
let facing = normals.get(d).copied().flatten().is_some_and(|n| (0..3).map(|i| n[i] * normal[i]).sum::<f64>() < -0.5);
|
||||
let near = facing && face_xyz.get(d).and_then(|x| closest_point(x, point)).is_some_and(|q| q.distance <= tolerance);
|
||||
if near {
|
||||
let key = (k.min(other), k.max(other));
|
||||
touching.entry(key).or_default()[usize::from(k != key.0)].insert(c);
|
||||
if touching.len() > MAX_FOUND {
|
||||
return Err(EngineError::Params(format!("more than {MAX_FOUND} pairs of parts touch; lower the tolerance")));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let face_list = |set: &std::collections::BTreeSet<usize>| -> Vec<ElementFace> { set.iter().filter_map(|c| faces.get(*c).copied()).collect() };
|
||||
let mut found = Vec::new();
|
||||
let mut created = Vec::new();
|
||||
for (n, ((a, b), sides)) in touching.iter().enumerate() {
|
||||
let (main, secondary) = (face_list(&sides[0]), face_list(&sides[1]));
|
||||
let mut entry = json!({"parts": [a, b], "faces": [main.len(), secondary.len()]});
|
||||
if create {
|
||||
let names = [format!("find-{}-main", n + 1), format!("find-{}-secondary", n + 1), format!("find-{}", n + 1)];
|
||||
created.push((names, main, secondary));
|
||||
entry["contact"] = json!(format!("find-{}", n + 1));
|
||||
}
|
||||
found.push(entry);
|
||||
}
|
||||
let part_count = part_of.values().max().map_or(0, |m| m + 1);
|
||||
for ([main_name, secondary_name, contact_name], main, secondary) in created {
|
||||
s.model.add_set(&main_name, Set { faces: main, ..Set::default() })?;
|
||||
s.model.add_set(&secondary_name, Set { faces: secondary, ..Set::default() })?;
|
||||
let surfaces = ContactSurfaces::Pair { main: main_name, secondary: secondary_name };
|
||||
s.model.add_contact(&contact_name, Contact { surfaces, ..options.clone() })?;
|
||||
}
|
||||
Ok(json!({"parts": part_count, "exterior_faces": faces.len(), "tolerance": tolerance, "touching": found}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Two unit cubes of 2×2×2 hex8 each, the second resting on the first (separate nodes), and
|
||||
/// a third cube far away.
|
||||
fn stacked(s: &mut Session) {
|
||||
let mut next_node = 1u32;
|
||||
let mut next_element = 1u32;
|
||||
for (z0, x0) in [(0.0, 0.0), (1.0, 0.0), (0.0, 10.0)] {
|
||||
let base = next_node;
|
||||
for k in 0..3 {
|
||||
for j in 0..3 {
|
||||
for i in 0..3 {
|
||||
let xyz = [x0 + 0.5 * i as f64, 0.5 * j as f64, z0 + 0.5 * k as f64];
|
||||
s.execute("mesh.node.add", &json!({"label": next_node, "xyz": xyz})).unwrap();
|
||||
next_node += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let n = |i: u32, j: u32, k: u32| base + i + 3 * j + 9 * k;
|
||||
for k in 0..2 {
|
||||
for j in 0..2 {
|
||||
for i in 0..2 {
|
||||
let nodes = [
|
||||
n(i, j, k),
|
||||
n(i + 1, j, k),
|
||||
n(i + 1, j + 1, k),
|
||||
n(i, j + 1, k),
|
||||
n(i, j, k + 1),
|
||||
n(i + 1, j, k + 1),
|
||||
n(i + 1, j + 1, k + 1),
|
||||
n(i, j + 1, k + 1),
|
||||
];
|
||||
s.execute("mesh.element.add", &json!({"label": next_element, "kind": "hex8", "nodes": nodes})).unwrap();
|
||||
next_element += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contacts_are_created_edited_and_deleted() {
|
||||
let mut s = Session::default();
|
||||
stacked(&mut s);
|
||||
s.execute("model.set.create", &json!({"name": "a", "faces": [{"element": 5, "face": 2}]})).unwrap();
|
||||
s.execute("model.set.create", &json!({"name": "b", "faces": [{"element": 9, "face": 1}]})).unwrap();
|
||||
s.execute("interaction.contact.pair", &json!({"name": "ab", "main": "a", "secondary": "b", "friction": {"static": 0.2}})).unwrap();
|
||||
let c = s.model.contact("ab").unwrap();
|
||||
assert_eq!(c.friction, Friction::coulomb(0.2));
|
||||
assert!(s.execute("interaction.contact.pair", &json!({"name": "ab", "main": "a", "secondary": "b"})).is_err(), "taken");
|
||||
assert!(s.execute("interaction.contact.pair", &json!({"name": "aa", "main": "a", "secondary": "a"})).is_err(), "self pair");
|
||||
assert!(s.execute("interaction.contact.pair", &json!({"name": "x", "main": "a", "secondary": "nope"})).is_err());
|
||||
assert!(s.execute("interaction.contact.pair", &json!({"name": "x", "main": "a", "secondary": "b", "penalty_scale": 2})).is_err());
|
||||
assert!(s.execute("interaction.contact.pair", &json!({"name": "x", "main": "a", "secondary": "b", "friction": {"static": -1}})).is_err());
|
||||
s.execute("interaction.contact.general", &json!({"name": "all"})).unwrap();
|
||||
s.execute("interaction.contact.general", &json!({"name": "self", "surface": "a", "initial_penetration": "refuse"})).unwrap();
|
||||
assert_eq!(s.model.contact("self").unwrap().initial_penetration, InitialPenetration::Refuse);
|
||||
s.execute("interaction.contact.edit", &json!({"name": "all", "surfaces": {"type": "general", "surface": "b"}, "penalty_scale": 0.5}))
|
||||
.unwrap();
|
||||
assert_eq!(s.model.contact("all").unwrap().surfaces, ContactSurfaces::General { surface: Some("b".into()) });
|
||||
assert!(s.execute("interaction.contact.edit", &json!({"name": "nope", "surfaces": {"type": "general"}})).is_err());
|
||||
assert!(s.execute("model.set.delete", &json!({"name": "a"})).unwrap_err().to_string().contains("contact `ab`"));
|
||||
s.execute("model.set.create", &json!({"name": "n", "nodes": [1, 2]})).unwrap();
|
||||
s.execute("interaction.contact.general", &json!({"name": "bad", "surface": "n"})).unwrap();
|
||||
let check = s.execute("model.check", &json!({})).unwrap();
|
||||
assert!(check.to_string().contains("set `n` has no element faces"), "{check}");
|
||||
for n in ["ab", "all", "self", "bad"] {
|
||||
s.execute("interaction.contact.delete", &json!({"name": n})).unwrap();
|
||||
}
|
||||
assert!(s.model.contacts().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_reports_and_creates_the_touching_parts() {
|
||||
let mut s = Session::default();
|
||||
stacked(&mut s);
|
||||
let r = s.execute("interaction.contact.find", &json!({})).unwrap();
|
||||
assert_eq!(r["parts"], 3, "{r}");
|
||||
assert_eq!(r["exterior_faces"], 3 * 24, "{r}");
|
||||
// The two stacked cubes touch over four faces each; the far one touches nothing.
|
||||
assert_eq!(r["touching"], json!([{"parts": [0, 1], "faces": [4, 4]}]), "{r}");
|
||||
assert!(s.model.contacts().is_empty(), "nothing created without `create`");
|
||||
let r = s.execute("interaction.contact.find", &json!({"create": true, "friction": {"static": 0.1}})).unwrap();
|
||||
assert_eq!(r["touching"][0]["contact"], "find-1");
|
||||
let c = s.model.contact("find-1").unwrap();
|
||||
assert_eq!(c.friction, Friction::coulomb(0.1));
|
||||
let main = s.model.resolve_set("find-1-main").unwrap();
|
||||
assert!(main.faces.iter().all(|f| (5..=8).contains(&f.element) && f.face == 2) && main.faces.len() == 4, "{main:?}");
|
||||
let secondary = s.model.resolve_set("find-1-secondary").unwrap();
|
||||
assert!(secondary.faces.iter().all(|f| (9..=12).contains(&f.element) && f.face == 1) && secondary.faces.len() == 4, "{secondary:?}");
|
||||
// A tight tolerance on a gap finds nothing; a second create reuses no names.
|
||||
assert!(s.execute("interaction.contact.find", &json!({"create": true})).is_err(), "the names are taken");
|
||||
for bad in [json!({"tolerance": -1}), json!({"tolerance": "x"}), json!({"tolerance": f64::MAX, "create": "yes"})] {
|
||||
assert!(s.execute("interaction.contact.find", &bad).is_err(), "{bad}");
|
||||
}
|
||||
let empty = s.execute("interaction.contact.find", &json!({"tolerance": 0})).unwrap();
|
||||
assert_eq!(empty["touching"].as_array().map(Vec::len), Some(1), "touching faces are at distance 0: {empty}");
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ pub const WRITE: CommandSpec = CommandSpec {
|
||||
id: "deck.write",
|
||||
label: "Write Solver Deck",
|
||||
params: r#"{"format": "abaqus|nastran|lsdyna", "path": "part.inp", "steps": ["Load"]} — writes the model as a solver deck (formats: fieldcraft_decks::FORMATS); `steps` (optional) writes only those steps, as a Nastran run needs (static or frequency steps, not both); LS-DYNA writes several steps as *CASE analyses (run it with CASE); fails naming every error of the model check and everything the format cannot express"#,
|
||||
form: Some(super::forms::DECK),
|
||||
kind: CommandKind::Session,
|
||||
run: write,
|
||||
};
|
||||
|
||||
@@ -25,12 +25,13 @@ fn fields<T: DeserializeOwned>(p: &Value, what: &str) -> Result<T> {
|
||||
|
||||
/// Create, edit and delete commands for one kind of definition.
|
||||
macro_rules! definition_commands {
|
||||
($what:literal, $ty:ty, $id:literal, $label:literal, $doc:literal, $add:ident, $replace:ident, $remove:ident,
|
||||
($what:literal, $ty:ty, $id:literal, $label:literal, $doc:literal, $form:expr, $delete_form:expr, $add:ident, $replace:ident, $remove:ident,
|
||||
$CREATE:ident, $EDIT:ident, $DELETE:ident) => {
|
||||
pub const $CREATE: CommandSpec = CommandSpec {
|
||||
id: concat!("model.", $id, ".create"),
|
||||
label: concat!("New ", $label),
|
||||
params: concat!($doc, " — fails if the name is taken"),
|
||||
form: Some($form),
|
||||
kind: CommandKind::Model,
|
||||
run: |s: &mut Session, p: &Value| {
|
||||
let n = name(p)?;
|
||||
@@ -42,6 +43,7 @@ macro_rules! definition_commands {
|
||||
id: concat!("model.", $id, ".edit"),
|
||||
label: concat!("Edit ", $label),
|
||||
params: concat!($doc, " — replaces the existing definition of that name"),
|
||||
form: Some($form),
|
||||
kind: CommandKind::Model,
|
||||
run: |s: &mut Session, p: &Value| {
|
||||
let n = name(p)?;
|
||||
@@ -53,6 +55,7 @@ macro_rules! definition_commands {
|
||||
id: concat!("model.", $id, ".delete"),
|
||||
label: concat!("Delete ", $label),
|
||||
params: r#"{"name": "…"} — refused while another definition refers to it"#,
|
||||
form: Some($delete_form),
|
||||
kind: CommandKind::Model,
|
||||
run: |s: &mut Session, p: &Value| {
|
||||
s.model.$remove(name(p)?)?;
|
||||
@@ -68,6 +71,8 @@ definition_commands!(
|
||||
"set",
|
||||
"Set",
|
||||
r#"{"name": "root", "geometry": [{"body": "Body1", "face": "F2:top"}, {"body": "Body1", "edge": "…"}, {"body": "Body1", "vertex": "…"}, {"body": "Body1"}], "nodes": [labels], "elements": [labels], "faces": [{"element": 1, "face": 3}], "edges": [{"element": 1, "edge": 2}]} — any of the member lists (element edges: where a 2D model's surface loads act); geometry members resolve against the mesh's geometry tags after every remesh (a face name also selects its split pieces `name#0`, `name#1`, …)"#,
|
||||
super::forms::SET,
|
||||
super::forms::SET_DELETE,
|
||||
add_set,
|
||||
replace_set,
|
||||
remove_set,
|
||||
@@ -82,6 +87,8 @@ definition_commands!(
|
||||
"material",
|
||||
"Material",
|
||||
r#"{"name": "Steel", "elastic": {"type": "isotropic", "young": 210000, "poisson": 0.3} | {"type": "engineering_constants", "young": [E1, E2, E3], "poisson": [ν12, ν13, ν23], "shear": [G12, G13, G23]}, "density": 7.85e-9, "fluid": {"type": "newtonian", "viscosity": 1.0e-9} (dynamic viscosity; a fluid needs a density), "plastic": {…} (see model.material.plasticity), "damage": {…}, "erosion": {…} (see model.material.damage), "hyperelastic": {"type": "neo_hookean"} | {"type": "mooney_rivlin", "c01": 0.1} (C10 = μ/2 − C01) | {"type": "yeoh", "c20": -0.01, "c30": 0.001} (C10 = μ/2) (large strain in nonlinear steps, from the isotropic constants: μ = E/(2(1 + ν)), κ = E/(3(1 − 2ν)); without it an elastic material is St Venant–Kirchhoff there)} — in the model's unit system (model.units), never converted"#,
|
||||
super::forms::MATERIAL,
|
||||
super::forms::MATERIAL_DELETE,
|
||||
add_material,
|
||||
replace_material,
|
||||
remove_material,
|
||||
@@ -103,6 +110,7 @@ pub const MATERIAL_PLASTICITY: CommandSpec = CommandSpec {
|
||||
id: "model.material.plasticity",
|
||||
label: "Plasticity",
|
||||
params: r#"{"name": "Steel", "plastic": {"type": "bilinear", "yield_stress": 250, "hardening_modulus": 1000, "hardening": "isotropic|kinematic"} | {"type": "table", "points": [{"strain": 0, "stress": 250}, {"strain": 0.1, "stress": 300}]} | {"type": "johnson_cook", "a": 792, "b": 510, "n": 0.26, "c": 0.014, "m": 1.03, "reference_strain_rate": 1, "room_temperature": 294, "melt_temperature": 1793, "specific_heat": 4.77e8, "taylor_quinney": 0.9} | null} — von Mises plasticity of an isotropic material (null removes it); explicit dynamics uses it, the linear solver the elastic constants alone"#,
|
||||
form: Some(super::forms::MATERIAL_PLASTICITY),
|
||||
kind: CommandKind::Model,
|
||||
run: |s: &mut Session, p: &Value| {
|
||||
change_material(s, p, |m, p| {
|
||||
@@ -116,6 +124,7 @@ pub const MATERIAL_DAMAGE: CommandSpec = CommandSpec {
|
||||
id: "model.material.damage",
|
||||
label: "Damage",
|
||||
params: r#"{"name": "Steel", "damage": {"type": "johnson_cook", "d1": 0.05, "d2": 3.44, "d3": -2.12, "d4": 0.002, "d5": 0.61} | null, "erosion": {"plastic_strain": 1.0} | null} — damage to failure and element erosion of a plastic material (each key optional; null removes it); a failed element is eroded in explicit dynamics"#,
|
||||
form: Some(super::forms::MATERIAL_DAMAGE),
|
||||
kind: CommandKind::Model,
|
||||
run: |s: &mut Session, p: &Value| {
|
||||
change_material(s, p, |m, p| {
|
||||
@@ -141,6 +150,8 @@ definition_commands!(
|
||||
"section",
|
||||
"Section",
|
||||
r#"{"name": "web", "set": "all", "material": "Steel", "kind": {"type": "solid"} | {"type": "shell", "thickness": 2, "offset": 0 (-0.5..=0.5 of the thickness), "points": 5} | {"type": "beam", "profile": {"type": "rectangle", "width", "height"} | {"type": "circle", "radius"} | {"type": "pipe", "radius", "thickness"} | {"type": "i", "height", "width", "web", "flange"} | {"type": "box", "width", "height", "thickness"}, "orientation": [x, y, z]} | {"type": "rod", "area": 10} | {"type": "plane_stress", "thickness": 1} | {"type": "plane_strain", "thickness": 1 (default)} | {"type": "axisymmetric"} (2D: elements in the XY plane; axisymmetric about Y with x the radius, forces totals over the circumference), "formulation": {"integration": "full|reduced", "incompatible_modes": false, "hybrid": false}}"#,
|
||||
super::forms::SECTION,
|
||||
super::forms::SECTION_DELETE,
|
||||
add_section,
|
||||
replace_section,
|
||||
remove_section,
|
||||
@@ -155,6 +166,8 @@ definition_commands!(
|
||||
"reference_point",
|
||||
"Reference Point",
|
||||
r#"{"name": "RP", "xyz": [x, y, z], "label": 0} — label: its node label in decks (default: the highest free label, kept through remeshes)"#,
|
||||
super::forms::REFERENCE_POINT,
|
||||
super::forms::REFERENCE_POINT_DELETE,
|
||||
add_reference_point,
|
||||
replace_reference_point,
|
||||
remove_reference_point,
|
||||
@@ -169,6 +182,8 @@ definition_commands!(
|
||||
"coupling",
|
||||
"Coupling",
|
||||
r#"{"name": "pad", "reference_point": "RP", "set": "hole", "kind": "kinematic|distributing", "dofs": [1, 2, 3, 4, 5, 6] (default all)}"#,
|
||||
super::forms::COUPLING,
|
||||
super::forms::COUPLING_DELETE,
|
||||
add_coupling,
|
||||
replace_coupling,
|
||||
remove_coupling,
|
||||
@@ -183,6 +198,8 @@ definition_commands!(
|
||||
"mass",
|
||||
"Point Mass",
|
||||
r#"{"name": "motor", "target": {"set": "…"} | {"reference_point": "…"}, "mass": 2.5 | [mx, my, mz] (per global direction), "inertia": [I11, I22, I33, I12, I13, I23] (tensor about the node in global axes; needs rotations: a reference point)} — at every node of the target, each with the full value"#,
|
||||
super::forms::MASS,
|
||||
super::forms::MASS_DELETE,
|
||||
add_mass,
|
||||
replace_mass,
|
||||
remove_mass,
|
||||
@@ -197,6 +214,8 @@ definition_commands!(
|
||||
"spring",
|
||||
"Spring or Dashpot",
|
||||
r#"{"name": "mount", "type": "spring", "stiffness": 1000 | "type": "dashpot", "coefficient": 5, "first": {"set": "…"} | {"reference_point": "…"}, "second": (optional; without it each node of `first` connects to the ground; with it each end is one node), "direction": {"dof": 1..6} (4–6: torsional) | {"vector": [x, y, z]} | "line" (along the two ends, two-point only)} — dashpots act in dynamic steps; static and frequency steps ignore them"#,
|
||||
super::forms::SPRING,
|
||||
super::forms::SPRING_DELETE,
|
||||
add_spring,
|
||||
replace_spring,
|
||||
remove_spring,
|
||||
@@ -211,6 +230,8 @@ definition_commands!(
|
||||
"boundary_condition",
|
||||
"Boundary Condition",
|
||||
r#"{"name": "clamp", "type": "fixed", "target": {"set": "root"} | {"reference_point": "RP"}} | {"name", "type": "displacement", "target", "values": [u1, u2, u3, ur1, ur2, ur3] (null leaves a degree of freedom free)} | {"name", "type": "symmetry", "target", "plane": "x|y|z" (the plane's normal)} — active in the steps that list it (model.step.activate)"#,
|
||||
super::forms::BOUNDARY_CONDITION,
|
||||
super::forms::BOUNDARY_CONDITION_DELETE,
|
||||
add_boundary_condition,
|
||||
replace_boundary_condition,
|
||||
remove_boundary_condition,
|
||||
@@ -225,6 +246,8 @@ definition_commands!(
|
||||
"load",
|
||||
"Load",
|
||||
r#"{"name": "push", "type": "force|moment", "target": {"set": "…"} | {"reference_point": "…"}, "vector": [x, y, z], "distribution": "total" (default: the vector is the total, split by area over the set's faces, or equally over its nodes) | "per_node" (at every node: depends on the mesh)} | {"name", "type": "traction", "set", "vector" (per area, on the set's faces)} | {"name", "type": "pressure", "set", "magnitude" (positive pushes in)} | {"name", "type": "gravity", "acceleration": [x, y, z], "set" (optional, default the whole model)} | {"name", "type": "body_force", "set", "vector" (per volume)} | {"name", "type": "centrifugal", "angular_velocity" (rad per time unit), "point": [x, y, z] (on the axis), "axis": [x, y, z], "set" (optional)} — 2D models: in-plane vectors, surface loads on element edges; active in the steps that list it (model.step.activate)"#,
|
||||
super::forms::LOAD,
|
||||
super::forms::LOAD_DELETE,
|
||||
add_load,
|
||||
replace_load,
|
||||
remove_load,
|
||||
@@ -239,6 +262,8 @@ definition_commands!(
|
||||
"fluid_domain",
|
||||
"Fluid Domain",
|
||||
r#"{"name": "Flow", "material": "Water" (a density and fluid behaviour), "min": [x, y, z], "max": [x, y, z], "spacing": 1.0 (cubic cells; every extent a whole number of spacings), "faces": {"x_min": {"type": "velocity", "velocity": [u, v, w], "profile": "uniform|parabolic"}, "x_max": {"type": "pressure", "pressure": 0}, "y_min": {"type": "wall"} | {"type": "moving_wall", "velocity": [u, v, w] (in the face's plane)} | {"type": "slip"} | {"type": "periodic"} (in opposite pairs), …} (default walls), "obstacles": ["Body1"] (solid bodies of the design or imported surfaces, by name), "surfaces": [{"face": {"body": "Body1", "face": "F2:top"}, "condition": {"type": "moving_wall", "velocity": [u, v, w]}}] (obstacle faces are walls unless listed), "initial_velocity": [u, v, w], "acceleration": [x, y, z] (gravity or a driving force per mass), "tolerance": 0.1 (obstacle triangulation; default a tenth of the spacing)}"#,
|
||||
super::forms::FLUID_DOMAIN,
|
||||
super::forms::FLUID_DOMAIN_DELETE,
|
||||
add_fluid_domain,
|
||||
replace_fluid_domain,
|
||||
remove_fluid_domain,
|
||||
@@ -251,6 +276,7 @@ pub const FLUID_BOUNDARY: CommandSpec = CommandSpec {
|
||||
id: "model.fluid_domain.boundary",
|
||||
label: "Inlet, Outlet or Wall",
|
||||
params: r#"{"domain": "Flow", "at": "x_min" (a box face) | {"body": "Body1", "face": "F2:top"} (an obstacle face), "condition": {"type": "velocity", "velocity": [u, v, w], "profile": "uniform|parabolic"} | {"type": "pressure", "pressure": 0} | {"type": "wall"} | {"type": "moving_wall", "velocity": [u, v, w]} | {"type": "slip"} | {"type": "periodic"}} — sets one boundary's condition (obstacle faces take walls and moving walls)"#,
|
||||
form: Some(super::forms::FLUID_BOUNDARY),
|
||||
kind: CommandKind::Model,
|
||||
run: fluid_boundary,
|
||||
};
|
||||
@@ -266,7 +292,8 @@ fn fluid_boundary(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub const STEP_CREATE: CommandSpec = CommandSpec {
|
||||
id: "model.step.create",
|
||||
label: "New Step",
|
||||
params: r#"{"name": "Bend", "procedure": {"type": "static"} | {"type": "nonlinear_static", "nonlinear_geometry": true, "initial_increment": 0.1, "min_increment": 1e-5, "max_increment": 1.0 (fractions of the step), "max_increments": 100, "max_iterations": 16 (per increment), "tolerances": {"force": 1e-6, "displacement": 1e-5, "energy": 1e-10}, "line_search": false, "load_path": [[0, 0], [0.5, 1], [1, 0]] (optional: the load factor against the step fraction, piecewise linear from [0, 0] to fraction 1; increments end at its points)} (loads and prescribed displacements are the load factor times their values; it ramps from 0 to 1 without a load path) | {"type": "frequency", "modes": 10, "min_hz": 0, "max_hz": 500} | {"type": "fluid", "domain": "Flow", "end_time": 1.0 | "steps": 1000, "time_step": (default: chosen for Mach 0.087 and τ ≤ 1), "frames": 10, "magic": 0.1875 (the two-relaxation-time Λ)} | {"type": "explicit_dynamic", "end_time": 0.001, "dt_scale": 0.9, "max_increments": 10000000, "output_interval", "history_interval", "history_nodes": "set", "initial_velocities": [{"set", "velocity": [vx, vy, vz]}], "rigid_walls": [{"set", "point", "normal"}], "hourglass": {"type": "viscous|stiffness", "coefficient": 0.1}, "bulk_viscosity": {"linear": 0.06, "quadratic": 1.5}}, "output": ["displacement", "reaction_force", "stress", "strain"] (default by procedure), "boundary_conditions": [names], "loads": [names] (active in this step; nothing carries over between steps), "before": "step" (default: last)}"#,
|
||||
params: r#"{"name": "Bend", "procedure": {"type": "static"} | {"type": "nonlinear_static", "nonlinear_geometry": true, "initial_increment": 0.1, "min_increment": 1e-5, "max_increment": 1.0 (fractions of the step), "max_increments": 100, "max_iterations": 16 (per increment), "tolerances": {"force": 1e-6, "displacement": 1e-5, "energy": 1e-10}, "line_search": false, "load_path": [[0, 0], [0.5, 1], [1, 0]] (optional: the load factor against the step fraction, piecewise linear from [0, 0] to fraction 1; increments end at its points)} (loads and prescribed displacements are the load factor times their values; it ramps from 0 to 1 without a load path) | {"type": "frequency", "modes": 10, "min_hz": 0, "max_hz": 500} | {"type": "fluid", "domain": "Flow", "end_time": 1.0 | "steps": 1000, "time_step": (default: chosen for Mach 0.087 and τ ≤ 1), "frames": 10, "magic": 0.1875 (the two-relaxation-time Λ)} | {"type": "explicit_dynamic", "end_time": 0.001, "dt_scale": 0.9, "max_increments": 10000000, "output_interval", "history_interval", "history_nodes": "set", "initial_velocities": [{"set", "velocity": [vx, vy, vz]}], "rigid_walls": [{"set", "point", "normal", "friction": {"static": 0.3, "kinetic": 0.2, "decay": 10} (Coulomb; default frictionless)}], "hourglass": {"type": "viscous|stiffness", "coefficient": 0.1}, "bulk_viscosity": {"linear": 0.06, "quadratic": 1.5}, "mass_scaling": {"target_increment": 1e-6, "set": "…" (optional, default every element)} (opt-in: elements below the target increment get the density that reaches it; the added mass is reported)}, "output": ["displacement", "reaction_force", "stress", "strain"] (default by procedure), "boundary_conditions": [names], "loads": [names] (active in this step; nothing carries over between steps), "before": "step" (default: last)}"#,
|
||||
form: Some(super::forms::STEP_CREATE),
|
||||
kind: CommandKind::Model,
|
||||
run: step_create,
|
||||
};
|
||||
@@ -275,6 +302,7 @@ pub const STEP_EDIT: CommandSpec = CommandSpec {
|
||||
id: "model.step.edit",
|
||||
label: "Edit Step",
|
||||
params: r#"{"name": "Bend", "procedure", "output", "boundary_conditions", "loads"} — as model.step.create; what is left out keeps its value"#,
|
||||
form: Some(super::forms::STEP_EDIT),
|
||||
kind: CommandKind::Model,
|
||||
run: step_edit,
|
||||
};
|
||||
@@ -283,6 +311,7 @@ pub const STEP_DELETE: CommandSpec = CommandSpec {
|
||||
id: "model.step.delete",
|
||||
label: "Delete Step",
|
||||
params: r#"{"name": "Bend"}"#,
|
||||
form: Some(super::forms::STEP_DELETE),
|
||||
kind: CommandKind::Model,
|
||||
run: |s, p| s.model.remove_step(name(p)?).map(|_| Value::Null).map_err(Into::into),
|
||||
};
|
||||
@@ -291,12 +320,19 @@ pub const STEP_ACTIVATE: CommandSpec = CommandSpec {
|
||||
id: "model.step.activate",
|
||||
label: "Activate in Step",
|
||||
params: r#"{"step": "Bend", "boundary_conditions": [names], "loads": [names], "active": true} — switches the listed items on (or off with false) in that step only"#,
|
||||
form: Some(super::forms::STEP_ACTIVATE),
|
||||
kind: CommandKind::Model,
|
||||
run: step_activate,
|
||||
};
|
||||
|
||||
pub const ACTIVITY: CommandSpec =
|
||||
CommandSpec { id: "model.activity", label: "Step Table", params: "{}", kind: CommandKind::Model, run: |s, _| Ok(activity(&s.model)) };
|
||||
pub const ACTIVITY: CommandSpec = CommandSpec {
|
||||
id: "model.activity",
|
||||
label: "Step Table",
|
||||
params: "{}",
|
||||
form: Some(&[]),
|
||||
kind: CommandKind::Model,
|
||||
run: |s, _| Ok(activity(&s.model)),
|
||||
};
|
||||
|
||||
fn step_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let n = name(p)?;
|
||||
|
||||
@@ -36,6 +36,7 @@ pub const UNDO: CommandSpec = CommandSpec {
|
||||
id: "edit.undo",
|
||||
label: "Undo",
|
||||
params: r#"{"count"?: 1} — takes back the last command that changed the model (it leaves the journal and can be redone); `count` takes back that many, as far as the history reaches"#,
|
||||
form: Some(super::forms::COUNT),
|
||||
kind: CommandKind::Session,
|
||||
run: |s, p| repeat(s, p, Session::undo),
|
||||
};
|
||||
@@ -44,6 +45,7 @@ pub const REDO: CommandSpec = CommandSpec {
|
||||
id: "edit.redo",
|
||||
label: "Redo",
|
||||
params: r#"{"count"?: 1} — runs the last undone command's change again; `count` redoes that many, as far as there are undone commands"#,
|
||||
form: Some(super::forms::COUNT),
|
||||
kind: CommandKind::Session,
|
||||
run: |s, p| repeat(s, p, Session::redo),
|
||||
};
|
||||
|
||||
@@ -23,6 +23,7 @@ pub const OPEN: CommandSpec = CommandSpec {
|
||||
id: "file.open",
|
||||
label: "Open Model",
|
||||
params: r#"{"path": "bracket.fieldcraft"} — opens the model, its mesh and its journal, and opens its design and imported meshes again from their files (one that is missing or changed is listed in `warnings`; the model still opens); unsaved changes of the current model are discarded and the undo history starts empty"#,
|
||||
form: Some(super::forms::FILE_OPEN),
|
||||
kind: CommandKind::Session,
|
||||
run: open,
|
||||
};
|
||||
@@ -31,6 +32,7 @@ pub const SAVE: CommandSpec = CommandSpec {
|
||||
id: "file.save",
|
||||
label: "Save Model",
|
||||
params: r#"{"path"?: "bracket.fieldcraft"} — saves to `path`, else to the file the model was opened from or last saved to; written atomically, the previous version kept as `<file>.bak`"#,
|
||||
form: Some(super::forms::FILE_SAVE),
|
||||
kind: CommandKind::Session,
|
||||
run: save,
|
||||
};
|
||||
@@ -39,6 +41,7 @@ pub const SAVE_AS: CommandSpec = CommandSpec {
|
||||
id: "file.save_as",
|
||||
label: "Save Model As",
|
||||
params: r#"{"path": "bracket.fieldcraft"} — saves to a new file, which becomes the model's file"#,
|
||||
form: Some(super::forms::FILE_SAVE_AS),
|
||||
kind: CommandKind::Session,
|
||||
run: save_as,
|
||||
};
|
||||
@@ -47,6 +50,7 @@ pub const RECOVERY_LIST: CommandSpec = CommandSpec {
|
||||
id: "file.recovery.list",
|
||||
label: "Recoverable Models",
|
||||
params: r#"{"dir"?: "…"} — models autosaved by apps that crashed or closed with unsaved changes, newest first (default folder: FIELDCRAFT_RECOVERY_DIR or the per-user data folder)"#,
|
||||
form: Some(super::forms::RECOVERY_LIST),
|
||||
kind: CommandKind::Session,
|
||||
run: recovery_list,
|
||||
};
|
||||
@@ -55,6 +59,7 @@ pub const RECOVER: CommandSpec = CommandSpec {
|
||||
id: "file.recover",
|
||||
label: "Recover Model",
|
||||
params: r#"{"id": "…", "dir"?: "…"} — opens an autosaved model (an id from file.recovery.list) with its original file path, as unsaved changes; the autosave stays until file.recovery.discard"#,
|
||||
form: Some(super::forms::RECOVER),
|
||||
kind: CommandKind::Session,
|
||||
run: recover,
|
||||
};
|
||||
@@ -63,6 +68,7 @@ pub const RECOVERY_DISCARD: CommandSpec = CommandSpec {
|
||||
id: "file.recovery.discard",
|
||||
label: "Discard Recovered Model",
|
||||
params: r#"{"id": "…"} or {"all": true}; "dir"?: "…" — deletes autosaves of apps that are no longer running"#,
|
||||
form: Some(super::forms::RECOVERY_DISCARD),
|
||||
kind: CommandKind::Session,
|
||||
run: recovery_discard,
|
||||
};
|
||||
@@ -71,6 +77,7 @@ pub const SAMPLE: CommandSpec = CommandSpec {
|
||||
id: "file.sample",
|
||||
label: "Open Sample",
|
||||
params: r#"{"name": "parts|cantilever|impact"} — opens a sample model (fieldcraft_engine::sample) in place of the current one, unsaved changes discarded; `cantilever` and `impact` are ready to solve (solve.run)"#,
|
||||
form: Some(super::forms::SAMPLE),
|
||||
kind: CommandKind::Session,
|
||||
run: open_sample,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,995 @@
|
||||
//! The commands' parameter schemas ([`crate::schema`]), area by area. Each describes the JSON
|
||||
//! the command's `run` reads, as its `params` doc string does in words.
|
||||
|
||||
use crate::schema::Collection as C;
|
||||
use crate::schema::Dim as D;
|
||||
use crate::schema::*;
|
||||
|
||||
// ---- Shared pieces ----
|
||||
|
||||
/// `{"set": …}` or `{"reference_point": …}`.
|
||||
const TARGET_OPTIONS: &[Field] = &[reference("set", "Set", C::Set), reference("reference_point", "Reference point", C::ReferencePoint)];
|
||||
const fn target(key: &'static str, label: &'static str) -> Field {
|
||||
either(key, label, TARGET_OPTIONS)
|
||||
}
|
||||
|
||||
/// The name of an existing definition, for delete commands.
|
||||
macro_rules! existing {
|
||||
($label:literal, $c:expr) => {
|
||||
&[reference("name", $label, $c).req()]
|
||||
};
|
||||
}
|
||||
|
||||
pub const SET_DELETE: &[Field] = existing!("Set", C::Set);
|
||||
pub const MATERIAL_DELETE: &[Field] = existing!("Material", C::Material);
|
||||
pub const SECTION_DELETE: &[Field] = existing!("Section", C::Section);
|
||||
pub const REFERENCE_POINT_DELETE: &[Field] = existing!("Reference point", C::ReferencePoint);
|
||||
pub const COUPLING_DELETE: &[Field] = existing!("Coupling", C::Coupling);
|
||||
pub const MASS_DELETE: &[Field] = existing!("Point mass", C::Mass);
|
||||
pub const SPRING_DELETE: &[Field] = existing!("Spring", C::Spring);
|
||||
pub const BOUNDARY_CONDITION_DELETE: &[Field] = existing!("Boundary condition", C::BoundaryCondition);
|
||||
pub const LOAD_DELETE: &[Field] = existing!("Load", C::Load);
|
||||
pub const FLUID_DOMAIN_DELETE: &[Field] = existing!("Fluid domain", C::FluidDomain);
|
||||
pub const CONTACT_DELETE: &[Field] = existing!("Contact", C::Contact);
|
||||
pub const STEP_DELETE: &[Field] = existing!("Step", C::Step);
|
||||
pub const SET_RESOLVE: &[Field] = existing!("Set", C::Set);
|
||||
|
||||
// ---- Model definitions ----
|
||||
|
||||
pub const SET: &[Field] = &[
|
||||
NAME,
|
||||
rows(
|
||||
"geometry",
|
||||
"Geometry",
|
||||
&[
|
||||
reference("body", "Body", C::Body).req(),
|
||||
text("face", "Face").hint("persistent face name"),
|
||||
text("edge", "Edge"),
|
||||
text("vertex", "Vertex"),
|
||||
],
|
||||
)
|
||||
.hint("whole bodies, or their faces, edges or vertices"),
|
||||
json("nodes", "Nodes").hint("[labels]"),
|
||||
json("elements", "Elements").hint("[labels]"),
|
||||
json("faces", "Element faces").hint("[{\"element\", \"face\"}]"),
|
||||
json("edges", "Element edges").hint("[{\"element\", \"edge\"}]"),
|
||||
];
|
||||
|
||||
const ELASTIC: Field = variants(
|
||||
"elastic",
|
||||
"Elasticity",
|
||||
&[
|
||||
variant(
|
||||
"isotropic",
|
||||
"Isotropic",
|
||||
&[num("young", "Young's modulus", D::Stress).req(), range("poisson", "Poisson's ratio", D::None, -1.0, 0.5).req()],
|
||||
),
|
||||
variant(
|
||||
"engineering_constants",
|
||||
"Orthotropic",
|
||||
&[
|
||||
vector("young", "E1, E2, E3", D::Stress, &["E1", "E2", "E3"]).req(),
|
||||
vector("poisson", "ν12, ν13, ν23", D::None, &["ν12", "ν13", "ν23"]).req(),
|
||||
vector("shear", "G12, G13, G23", D::Stress, &["G12", "G13", "G23"]).req(),
|
||||
],
|
||||
),
|
||||
],
|
||||
)
|
||||
.def(r#"{"type": "isotropic"}"#);
|
||||
|
||||
const HARDENING: &[(&str, &str)] = &[("isotropic", "Isotropic"), ("kinematic", "Kinematic")];
|
||||
|
||||
const PLASTIC: Field = variants(
|
||||
"plastic",
|
||||
"Plasticity",
|
||||
&[
|
||||
variant(
|
||||
"bilinear",
|
||||
"Bilinear",
|
||||
&[
|
||||
positive("yield_stress", "Yield stress", D::Stress).req(),
|
||||
num("hardening_modulus", "Hardening modulus", D::Stress).def("0"),
|
||||
choice("hardening", "Hardening", HARDENING).def("\"isotropic\""),
|
||||
],
|
||||
),
|
||||
variant(
|
||||
"table",
|
||||
"Table",
|
||||
&[rows(
|
||||
"points",
|
||||
"Hardening curve",
|
||||
&[positive("strain", "Plastic strain", D::None).req(), positive("stress", "Stress", D::Stress).req()],
|
||||
)
|
||||
.req()],
|
||||
),
|
||||
variant(
|
||||
"johnson_cook",
|
||||
"Johnson–Cook",
|
||||
&[
|
||||
positive("a", "A", D::Stress).req(),
|
||||
num("b", "B", D::Stress).req(),
|
||||
num("n", "n", D::None).req(),
|
||||
num("c", "C", D::None).def("0"),
|
||||
num("m", "m", D::None).def("1"),
|
||||
positive("reference_strain_rate", "Reference strain rate", D::None).def("1").hint("per time unit"),
|
||||
num("room_temperature", "Room temperature", D::Temperature).req(),
|
||||
num("melt_temperature", "Melt temperature", D::Temperature).req(),
|
||||
positive("specific_heat", "Specific heat", D::SpecificHeat).hint("isothermal when empty"),
|
||||
range("taylor_quinney", "Taylor–Quinney", D::None, 0.0, 1.0).def("0.9"),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
const DAMAGE: Field = variants(
|
||||
"damage",
|
||||
"Damage",
|
||||
&[variant(
|
||||
"johnson_cook",
|
||||
"Johnson–Cook",
|
||||
&[
|
||||
num("d1", "D1", D::None).req(),
|
||||
num("d2", "D2", D::None).req(),
|
||||
num("d3", "D3", D::None).req(),
|
||||
num("d4", "D4", D::None),
|
||||
num("d5", "D5", D::None),
|
||||
],
|
||||
)],
|
||||
);
|
||||
const EROSION: Field = group("erosion", "Erosion", &[positive("plastic_strain", "Plastic strain", D::None).req()]);
|
||||
|
||||
const HYPERELASTIC: Field = variants(
|
||||
"hyperelastic",
|
||||
"Hyperelasticity",
|
||||
&[
|
||||
variant("neo_hookean", "Neo-Hookean", &[]),
|
||||
variant("mooney_rivlin", "Mooney–Rivlin", &[num("c01", "C01", D::Stress).req()]),
|
||||
variant("yeoh", "Yeoh", &[num("c20", "C20", D::Stress).req(), num("c30", "C30", D::Stress).req()]),
|
||||
],
|
||||
)
|
||||
.hint("large strain in nonlinear steps, from the isotropic constants");
|
||||
|
||||
const THERMAL: Field = group(
|
||||
"thermal",
|
||||
"Thermal",
|
||||
&[
|
||||
json("conductivity", "Conductivity").hint("k or [k1, k2, k3]"),
|
||||
positive("specific_heat", "Specific heat", D::SpecificHeat),
|
||||
json("expansion", "Expansion").hint("α or [α1, α2, α3], 1/K"),
|
||||
num("reference_temperature", "Reference temperature", D::Temperature).def("0"),
|
||||
],
|
||||
);
|
||||
|
||||
pub const MATERIAL: &[Field] = &[
|
||||
NAME,
|
||||
ELASTIC,
|
||||
positive("density", "Density", D::Density),
|
||||
PLASTIC,
|
||||
HYPERELASTIC,
|
||||
DAMAGE,
|
||||
EROSION,
|
||||
THERMAL,
|
||||
variants("fluid", "Fluid", &[variant("newtonian", "Newtonian", &[positive("viscosity", "Viscosity", D::Viscosity).req()])])
|
||||
.hint("a fluid needs a density"),
|
||||
];
|
||||
|
||||
pub const MATERIAL_PLASTICITY: &[Field] = &[reference("name", "Material", C::Material).req(), PLASTIC.req().def(r#"{"type": "bilinear"}"#)];
|
||||
pub const MATERIAL_DAMAGE: &[Field] =
|
||||
&[reference("name", "Material", C::Material).req(), DAMAGE.def(r#"{"type": "johnson_cook"}"#).hint("give damage, erosion or both"), EROSION];
|
||||
|
||||
const PROFILE: Field = variants(
|
||||
"profile",
|
||||
"Profile",
|
||||
&[
|
||||
variant("rectangle", "Rectangle", &[positive("width", "Width", D::Length).req(), positive("height", "Height", D::Length).req()]),
|
||||
variant("circle", "Circle", &[positive("radius", "Radius", D::Length).req()]),
|
||||
variant("pipe", "Pipe", &[positive("radius", "Radius", D::Length).req(), positive("thickness", "Wall", D::Length).req()]),
|
||||
variant(
|
||||
"i",
|
||||
"I-beam",
|
||||
&[
|
||||
positive("height", "Height", D::Length).req(),
|
||||
positive("width", "Width", D::Length).req(),
|
||||
positive("web", "Web", D::Length).req(),
|
||||
positive("flange", "Flange", D::Length).req(),
|
||||
],
|
||||
),
|
||||
variant(
|
||||
"box",
|
||||
"Box",
|
||||
&[
|
||||
positive("width", "Width", D::Length).req(),
|
||||
positive("height", "Height", D::Length).req(),
|
||||
positive("thickness", "Wall", D::Length).req(),
|
||||
],
|
||||
),
|
||||
],
|
||||
)
|
||||
.req()
|
||||
.def(r#"{"type": "rectangle"}"#);
|
||||
|
||||
pub const SECTION: &[Field] = &[
|
||||
NAME,
|
||||
reference("set", "Region", C::Set).req(),
|
||||
reference("material", "Material", C::Material).req(),
|
||||
variants(
|
||||
"kind",
|
||||
"Kind",
|
||||
&[
|
||||
variant("solid", "Solid", &[]),
|
||||
variant(
|
||||
"shell",
|
||||
"Shell",
|
||||
&[
|
||||
positive("thickness", "Thickness", D::Length).req(),
|
||||
range("offset", "Offset", D::None, -0.5, 0.5).def("0").hint("fraction of the thickness"),
|
||||
int("points", "Integration points", 1, 15).def("5"),
|
||||
],
|
||||
),
|
||||
variant("beam", "Beam", &[PROFILE, xyz("orientation", "Orientation", D::None).req().def("[0, 0, 1]")]),
|
||||
variant("rod", "Rod", &[positive("area", "Area", D::Area).req()]),
|
||||
variant("plane_stress", "Plane stress", &[positive("thickness", "Thickness", D::Length).req().def("1")]),
|
||||
variant("plane_strain", "Plane strain", &[positive("thickness", "Thickness", D::Length).def("1")]),
|
||||
variant("axisymmetric", "Axisymmetric", &[]),
|
||||
],
|
||||
)
|
||||
.req()
|
||||
.def(r#"{"type": "solid"}"#),
|
||||
group(
|
||||
"formulation",
|
||||
"Formulation",
|
||||
&[
|
||||
choice("integration", "Integration", &[("full", "Full"), ("reduced", "Reduced")]).def("\"full\""),
|
||||
flag("incompatible_modes", "Incompatible modes").def("false"),
|
||||
flag("hybrid", "Hybrid").def("false"),
|
||||
],
|
||||
),
|
||||
];
|
||||
|
||||
pub const REFERENCE_POINT: &[Field] = &[
|
||||
NAME,
|
||||
xyz("xyz", "Position", D::Length).req().def("[0, 0, 0]"),
|
||||
int("label", "Node label", 0, u32::MAX as i64).hint("0: the highest free label"),
|
||||
];
|
||||
|
||||
const DOFS: Field = json("dofs", "Degrees of freedom").hint("[1, …, 6], default all");
|
||||
|
||||
pub const COUPLING: &[Field] = &[
|
||||
NAME,
|
||||
reference("reference_point", "Reference point", C::ReferencePoint).req(),
|
||||
reference("set", "Region", C::Set).req(),
|
||||
choice("kind", "Kind", &[("kinematic", "Kinematic"), ("distributing", "Distributing")]).req().def("\"kinematic\""),
|
||||
DOFS,
|
||||
];
|
||||
|
||||
pub const MASS: &[Field] = &[
|
||||
NAME,
|
||||
TARGET,
|
||||
positive("mass", "Mass", D::Mass).hint("per node; [mx, my, mz] in JSON"),
|
||||
vector("inertia", "Inertia", D::Inertia, &["I11", "I22", "I33", "I12", "I13", "I23"]).hint("about the node; needs a reference point"),
|
||||
];
|
||||
|
||||
const SPRING_FIRST: Field = target("first", "First end").req();
|
||||
const SPRING_SECOND: Field = target("second", "Second end").hint("ground when empty");
|
||||
const SPRING_DIRECTION: Field =
|
||||
either("direction", "Direction", &[int("dof", "DOF", 1, 6), xyz("vector", "Vector", D::None), unit("line", "Along the ends")])
|
||||
.req()
|
||||
.def(r#"{"dof": 1}"#);
|
||||
|
||||
pub const SPRING: &[Field] = &[
|
||||
NAME,
|
||||
variants(
|
||||
"",
|
||||
"Type",
|
||||
&[
|
||||
variant("spring", "Spring", &[SPRING_FIRST, SPRING_SECOND, SPRING_DIRECTION, positive("stiffness", "Stiffness", D::Stiffness).req()]),
|
||||
variant("dashpot", "Dashpot", &[SPRING_FIRST, SPRING_SECOND, SPRING_DIRECTION, positive("coefficient", "Coefficient", D::Damping).req()]),
|
||||
],
|
||||
)
|
||||
.req()
|
||||
.def("\"spring\""),
|
||||
];
|
||||
|
||||
/// The target of a boundary condition, force, moment or temperature.
|
||||
const TARGET: Field = target("target", "Target").req();
|
||||
|
||||
pub const BOUNDARY_CONDITION: &[Field] = &[
|
||||
NAME,
|
||||
variants(
|
||||
"",
|
||||
"Type",
|
||||
&[
|
||||
variant("fixed", "Fixed", &[TARGET]),
|
||||
variant(
|
||||
"displacement",
|
||||
"Displacement",
|
||||
&[
|
||||
TARGET,
|
||||
free_vector("values", "Values", D::Length, &["u1", "u2", "u3", "ur1", "ur2", "ur3"])
|
||||
.req()
|
||||
.def("[0, 0, 0, null, null, null]")
|
||||
.hint("empty: free"),
|
||||
],
|
||||
),
|
||||
variant("symmetry", "Symmetry", &[TARGET, choice("plane", "Plane normal", &[("x", "X"), ("y", "Y"), ("z", "Z")]).req().def("\"x\"")]),
|
||||
variant("temperature", "Temperature", &[TARGET, num("value", "Temperature", D::Temperature).req()]),
|
||||
],
|
||||
)
|
||||
.req()
|
||||
.def("\"fixed\""),
|
||||
];
|
||||
|
||||
const DISTRIBUTION: Field = choice("distribution", "Distribution", &[("total", "Total"), ("per_node", "Per node")]).def("\"total\"");
|
||||
const LOAD_SET: Field = reference("set", "Region", C::Set).req();
|
||||
|
||||
pub const LOAD: &[Field] = &[
|
||||
NAME,
|
||||
variants(
|
||||
"",
|
||||
"Type",
|
||||
&[
|
||||
variant("force", "Force", &[TARGET, xyz("vector", "Force", D::Force).req(), DISTRIBUTION]),
|
||||
variant("moment", "Moment", &[TARGET, xyz("vector", "Moment", D::Moment).req(), DISTRIBUTION]),
|
||||
variant("pressure", "Pressure", &[LOAD_SET, num("magnitude", "Pressure", D::Stress).req().hint("positive pushes in")]),
|
||||
variant("traction", "Traction", &[LOAD_SET, xyz("vector", "Traction", D::Stress).req()]),
|
||||
variant(
|
||||
"gravity",
|
||||
"Gravity",
|
||||
&[xyz("acceleration", "Acceleration", D::Acceleration).req(), reference("set", "Region", C::Set).hint("the whole model")],
|
||||
),
|
||||
variant("body_force", "Body force", &[LOAD_SET, xyz("vector", "Force per volume", D::ForcePerVolume).req()]),
|
||||
variant(
|
||||
"centrifugal",
|
||||
"Centrifugal",
|
||||
&[
|
||||
num("angular_velocity", "Angular velocity", D::AngularVelocity).req(),
|
||||
xyz("point", "Point on axis", D::Length).req().def("[0, 0, 0]"),
|
||||
xyz("axis", "Axis", D::None).req().def("[0, 0, 1]"),
|
||||
reference("set", "Region", C::Set).hint("the whole model"),
|
||||
],
|
||||
),
|
||||
variant("surface_flux", "Surface heat flux", &[LOAD_SET, num("flux", "Flux", D::HeatFlux).req()]),
|
||||
variant(
|
||||
"convection",
|
||||
"Convection",
|
||||
&[LOAD_SET, positive("film", "Film coefficient", D::FilmCoefficient).req(), num("sink", "Sink temperature", D::Temperature).req()],
|
||||
),
|
||||
variant("heat_source", "Heat source", &[LOAD_SET, num("power", "Power per volume", D::None).req()]),
|
||||
variant("temperature", "Temperature", &[TARGET, num("value", "Temperature", D::Temperature).req()]),
|
||||
],
|
||||
)
|
||||
.req()
|
||||
.def("\"force\""),
|
||||
];
|
||||
|
||||
const FACE_CONDITION: &[Variant] = &[
|
||||
variant("wall", "Wall", &[]),
|
||||
variant("moving_wall", "Moving wall", &[xyz("velocity", "Velocity", D::Velocity).req()]),
|
||||
variant("slip", "Slip", &[]),
|
||||
variant(
|
||||
"velocity",
|
||||
"Velocity inlet",
|
||||
&[
|
||||
xyz("velocity", "Velocity", D::Velocity).req(),
|
||||
choice("profile", "Profile", &[("uniform", "Uniform"), ("parabolic", "Parabolic")]).def("\"uniform\""),
|
||||
],
|
||||
),
|
||||
variant("pressure", "Pressure outlet", &[num("pressure", "Pressure", D::Stress).req().def("0")]),
|
||||
variant("periodic", "Periodic", &[]),
|
||||
];
|
||||
|
||||
const fn face(key: &'static str, label: &'static str) -> Field {
|
||||
variants(key, label, FACE_CONDITION).hint("wall")
|
||||
}
|
||||
|
||||
pub const FLUID_DOMAIN: &[Field] = &[
|
||||
NAME,
|
||||
reference("material", "Fluid", C::Material).req(),
|
||||
xyz("min", "Box min", D::Length).req(),
|
||||
xyz("max", "Box max", D::Length).req(),
|
||||
positive("spacing", "Cell size", D::Length).req(),
|
||||
group(
|
||||
"faces",
|
||||
"Box faces",
|
||||
&[
|
||||
face("x_min", "X min"),
|
||||
face("x_max", "X max"),
|
||||
face("y_min", "Y min"),
|
||||
face("y_max", "Y max"),
|
||||
face("z_min", "Z min"),
|
||||
face("z_max", "Z max"),
|
||||
],
|
||||
),
|
||||
references("obstacles", "Obstacles", C::Body),
|
||||
json("surfaces", "Obstacle faces").hint("[{\"face\", \"condition\"}]; walls by default"),
|
||||
xyz("initial_velocity", "Initial velocity", D::Velocity),
|
||||
xyz("acceleration", "Acceleration", D::Acceleration),
|
||||
positive("tolerance", "Obstacle tolerance", D::Length).hint("a tenth of the cell size"),
|
||||
];
|
||||
|
||||
pub const FLUID_BOUNDARY: &[Field] = &[
|
||||
reference("domain", "Domain", C::FluidDomain).req(),
|
||||
json("at", "Boundary").req().def("\"x_min\"").hint("\"x_min\" … \"z_max\", or {\"body\", \"face\"}"),
|
||||
variants("condition", "Condition", FACE_CONDITION).req().def(r#"{"type": "velocity"}"#),
|
||||
];
|
||||
|
||||
const PROCEDURE: Field = variants(
|
||||
"procedure",
|
||||
"Procedure",
|
||||
&[
|
||||
variant("static", "Static, linear", &[]),
|
||||
variant(
|
||||
"nonlinear_static",
|
||||
"Static, nonlinear",
|
||||
&[
|
||||
flag("nonlinear_geometry", "Nonlinear geometry").def("true"),
|
||||
range("initial_increment", "Initial increment", D::None, 0.0, 1.0).def("0.1"),
|
||||
range("min_increment", "Min increment", D::None, 0.0, 1.0).def("1e-5"),
|
||||
range("max_increment", "Max increment", D::None, 0.0, 1.0).def("1.0"),
|
||||
int("max_increments", "Max increments", 1, 1_000_000).def("100"),
|
||||
int("max_iterations", "Iterations per increment", 1, 1000).def("16"),
|
||||
group(
|
||||
"tolerances",
|
||||
"Tolerances",
|
||||
&[
|
||||
positive("force", "Force", D::None).def("1e-6"),
|
||||
positive("displacement", "Displacement", D::None).def("1e-5"),
|
||||
positive("energy", "Energy", D::None).def("1e-10"),
|
||||
],
|
||||
),
|
||||
flag("line_search", "Line search").def("false"),
|
||||
json("load_path", "Load path").hint("[[fraction, factor], …]; a ramp when empty"),
|
||||
group(
|
||||
"imperfection",
|
||||
"Imperfection",
|
||||
&[
|
||||
reference("step", "Buckling step", C::Step).req(),
|
||||
int("mode", "Mode", 1, 100_000).req().def("1"),
|
||||
num("scale", "Largest component", D::Length).req(),
|
||||
],
|
||||
),
|
||||
group(
|
||||
"arc_length",
|
||||
"Arc length",
|
||||
&[
|
||||
choice("constraint", "Constraint", &[("cylindrical", "Cylindrical"), ("spherical", "Spherical")]).def("\"cylindrical\""),
|
||||
positive("max_load_factor", "Max load factor", D::None).def("1"),
|
||||
json("displacement_limit", "Displacement limit").hint("{\"node\": 1, \"direction\": 3, \"displacement\": -10}"),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
variant("buckle", "Buckling", &[int("modes", "Modes", 1, 100_000).req().def("4"), num("shift", "Shift", D::None)]),
|
||||
variant(
|
||||
"frequency",
|
||||
"Frequency",
|
||||
&[
|
||||
int("modes", "Modes", 1, 10_000).req().def("10"),
|
||||
positive("min_hz", "Min frequency", D::Hertz),
|
||||
positive("max_hz", "Max frequency", D::Hertz),
|
||||
],
|
||||
),
|
||||
variant(
|
||||
"explicit_dynamic",
|
||||
"Dynamic, explicit",
|
||||
&[
|
||||
positive("end_time", "End time", D::Time).req(),
|
||||
range("dt_scale", "Time step scale", D::None, 0.0, 1.0).def("0.9"),
|
||||
int("max_increments", "Max increments", 1, 10_000_000_000).def("10000000"),
|
||||
positive("output_interval", "Field output every", D::Time),
|
||||
positive("history_interval", "History every", D::Time),
|
||||
reference("history_nodes", "History nodes", C::Set),
|
||||
rows(
|
||||
"initial_velocities",
|
||||
"Initial velocities",
|
||||
&[reference("set", "Set", C::Set).req(), xyz("velocity", "Velocity", D::Velocity).req()],
|
||||
),
|
||||
rows(
|
||||
"rigid_walls",
|
||||
"Rigid walls",
|
||||
&[
|
||||
reference("set", "Set", C::Set).req(),
|
||||
xyz("point", "Point", D::Length).req(),
|
||||
xyz("normal", "Normal", D::None).req(),
|
||||
FRICTION,
|
||||
],
|
||||
),
|
||||
group(
|
||||
"hourglass",
|
||||
"Hourglass control",
|
||||
&[
|
||||
choice("type", "Type", &[("viscous", "Viscous"), ("stiffness", "Stiffness")]).def("\"viscous\""),
|
||||
positive("coefficient", "Coefficient", D::None),
|
||||
],
|
||||
),
|
||||
group("bulk_viscosity", "Bulk viscosity", &[positive("linear", "Linear", D::None), positive("quadratic", "Quadratic", D::None)]),
|
||||
flag("nonlinear_geometry", "Nonlinear geometry").def("true"),
|
||||
choice("stress_rate", "Stress rate", &[("jaumann", "Jaumann"), ("green_naghdi", "Green–Naghdi")]),
|
||||
group(
|
||||
"mass_scaling",
|
||||
"Mass scaling",
|
||||
&[positive("target_increment", "Target increment", D::Time).req(), reference("set", "Set", C::Set)],
|
||||
),
|
||||
],
|
||||
),
|
||||
variant(
|
||||
"heat_transfer",
|
||||
"Heat transfer",
|
||||
&[group(
|
||||
"transient",
|
||||
"Transient",
|
||||
&[
|
||||
positive("end_time", "End time", D::Time).req(),
|
||||
positive("increment", "Increment", D::Time).req(),
|
||||
range("theta", "θ", D::None, 0.0, 1.0),
|
||||
num("initial_temperature", "Initial temperature", D::Temperature),
|
||||
],
|
||||
)
|
||||
.hint("steady state when off")],
|
||||
),
|
||||
variant("coupled_temperature_displacement", "Coupled temperature–displacement", &[]),
|
||||
variant(
|
||||
"fluid",
|
||||
"Fluid (lattice Boltzmann)",
|
||||
&[
|
||||
reference("domain", "Domain", C::FluidDomain).req(),
|
||||
positive("end_time", "End time", D::Time).hint("or Steps"),
|
||||
int("steps", "Steps", 1, 1_000_000_000_000),
|
||||
positive("time_step", "Time step", D::Time).hint("chosen for Mach 0.087"),
|
||||
int("frames", "Frames", 1, 100_000).def("10"),
|
||||
positive("magic", "TRT Λ", D::None).hint("0.1875"),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
const OUTPUT: Field = json("output", "Output").hint("[\"displacement\", \"stress\", …]; by procedure when empty");
|
||||
const STEP_BCS: Field = references("boundary_conditions", "Boundary conditions", C::BoundaryCondition);
|
||||
const STEP_LOADS: Field = references("loads", "Loads", C::Load);
|
||||
|
||||
pub const STEP_CREATE: &[Field] =
|
||||
&[NAME, PROCEDURE.req().def(r#"{"type": "static"}"#), OUTPUT, STEP_BCS, STEP_LOADS, reference("before", "Insert before", C::Step).hint("last")];
|
||||
|
||||
pub const STEP_EDIT: &[Field] = &[reference("name", "Step", C::Step).req(), PROCEDURE, OUTPUT, STEP_BCS, STEP_LOADS];
|
||||
|
||||
pub const STEP_ACTIVATE: &[Field] = &[
|
||||
reference("step", "Step", C::Step).req(),
|
||||
references("boundary_conditions", "Boundary conditions", C::BoundaryCondition),
|
||||
references("loads", "Loads", C::Load),
|
||||
flag("active", "Active").def("true"),
|
||||
];
|
||||
|
||||
pub const UNITS: &[Field] = &[choice(
|
||||
"system",
|
||||
"Unit system",
|
||||
&[
|
||||
("mm-t-s-N-MPa", "mm, t, s, N, MPa"),
|
||||
("m-kg-s-N-Pa", "m, kg, s, N, Pa"),
|
||||
("mm-kg-ms-kN-GPa", "mm, kg, ms, kN, GPa"),
|
||||
("mm-g-ms-N-MPa", "mm, g, ms, N, MPa"),
|
||||
("in-lbf-s-psi", "in, lbf·s²/in, s, lbf, psi"),
|
||||
("unspecified", "Unspecified"),
|
||||
],
|
||||
)
|
||||
.req()
|
||||
.def("\"mm-t-s-N-MPa\"")];
|
||||
|
||||
// ---- Contact ----
|
||||
|
||||
const FRICTION: Field = group(
|
||||
"friction",
|
||||
"Friction",
|
||||
&[
|
||||
positive("static", "Static μ", D::None).hint("0"),
|
||||
positive("kinetic", "Kinetic μ", D::None).hint("the static μ"),
|
||||
positive("decay", "Decay", D::None).hint("0; per slip rate"),
|
||||
],
|
||||
)
|
||||
.hint("frictionless");
|
||||
const PENALTY: Field = range("penalty_scale", "Penalty scale", D::None, 0.0, 1.0).def("1");
|
||||
const PENETRATION: Field =
|
||||
choice("initial_penetration", "Initial penetration", &[("adjust", "Adjust nodes"), ("refuse", "Refuse")]).def("\"adjust\"");
|
||||
|
||||
pub const CONTACT_PAIR: &[Field] = &[
|
||||
NAME,
|
||||
reference("main", "Main surface", C::Set).req(),
|
||||
reference("secondary", "Secondary surface", C::Set).req(),
|
||||
FRICTION,
|
||||
PENALTY,
|
||||
PENETRATION,
|
||||
];
|
||||
pub const CONTACT_GENERAL: &[Field] = &[NAME, reference("surface", "Surface", C::Set).hint("every exterior face"), FRICTION, PENALTY, PENETRATION];
|
||||
pub const CONTACT_EDIT: &[Field] = &[
|
||||
reference("name", "Contact", C::Contact).req(),
|
||||
variants(
|
||||
"surfaces",
|
||||
"Surfaces",
|
||||
&[
|
||||
variant("pair", "Pair", &[reference("main", "Main", C::Set).req(), reference("secondary", "Secondary", C::Set).req()]),
|
||||
variant("general", "General", &[reference("surface", "Surface", C::Set).hint("every exterior face")]),
|
||||
],
|
||||
)
|
||||
.req(),
|
||||
FRICTION,
|
||||
PENALTY,
|
||||
PENETRATION,
|
||||
];
|
||||
pub const CONTACT_FIND: &[Field] = &[
|
||||
positive("tolerance", "Tolerance", D::Length).hint("a tenth of the mean face size"),
|
||||
flag("create", "Create pairs").def("false"),
|
||||
FRICTION,
|
||||
PENALTY,
|
||||
PENETRATION,
|
||||
];
|
||||
|
||||
// ---- Meshing ----
|
||||
|
||||
const BODY: Field = reference("body", "Body", C::Body).hint("every body of the design");
|
||||
const SURFACE: Field = int("surface", "Imported surface", 0, 1_000_000).hint("instead of a body");
|
||||
const TOLERANCE: Field = positive("tolerance", "Chordal tolerance", D::Millimetre).hint("1e-3 of the diagonal");
|
||||
const WELD: Field = range("weld", "Weld", D::None, 0.0, 1e-3).hint("1e-9 of the diagonal");
|
||||
const WELD_DISTANCE: Field = positive("weld_distance", "Weld distance", D::Millimetre).hint("the surface's own");
|
||||
const FEATURE_ANGLE: Field = range("feature_angle", "Feature angle", D::Degree, 0.0, 180.0).hint("45");
|
||||
|
||||
pub const TET: &[Field] = &[
|
||||
BODY,
|
||||
SURFACE,
|
||||
positive("size", "Element size", D::Millimetre).hint("1/20 of the diagonal"),
|
||||
choice("order", "Order", &[("linear", "Linear (tet4)"), ("quadratic", "Quadratic (tet10)")]).def("\"linear\""),
|
||||
TOLERANCE,
|
||||
flag("quality", "Improve quality").def("true"),
|
||||
range("quality_target", "Quality target", D::Degree, 5.0, 60.0).hint("40"),
|
||||
range("curvature_angle", "Curvature angle", D::Degree, 0.0, 90.0).hint("22.5"),
|
||||
range("grading", "Grading", D::None, 0.05, 2.0).hint("0.3"),
|
||||
int("max_passes", "Improvement passes", 0, 200).hint("20"),
|
||||
int("max_points", "Max points", 1, 20_000_000).hint("1000000"),
|
||||
int("max_steiner", "Max Steiner points", 0, 10_000_000).hint("50000"),
|
||||
int("max_tets", "Max tetrahedra", 1, 50_000_000).hint("5000000"),
|
||||
WELD,
|
||||
WELD_DISTANCE,
|
||||
FEATURE_ANGLE,
|
||||
];
|
||||
|
||||
const HEX_SIZE: Field = positive("size", "Element size", D::Millimetre).hint("1/25 of the diagonal");
|
||||
const HEX_ORDER: Field = int("order", "Order", 1, 2).def("1").hint("1: hex8, 2: hex20");
|
||||
|
||||
pub const HEX_GENERATE: &[Field] = &[
|
||||
BODY,
|
||||
SURFACE,
|
||||
HEX_SIZE,
|
||||
HEX_ORDER,
|
||||
choice(
|
||||
"method",
|
||||
"Method",
|
||||
&[("auto", "Automatic"), ("swept", "Any sweep"), ("extrude", "Extrude"), ("sweep", "Sweep"), ("revolve", "Revolve"), ("mapped", "Mapped")],
|
||||
)
|
||||
.def("\"auto\""),
|
||||
TOLERANCE,
|
||||
WELD,
|
||||
WELD_DISTANCE,
|
||||
FEATURE_ANGLE,
|
||||
];
|
||||
|
||||
pub const HEX_SWEEP: &[Field] = &[
|
||||
BODY,
|
||||
SURFACE,
|
||||
HEX_SIZE,
|
||||
HEX_ORDER,
|
||||
choice("method", "Method", &[("swept", "Any sweep"), ("extrude", "Extrude"), ("sweep", "Sweep"), ("revolve", "Revolve")]).def("\"swept\""),
|
||||
TOLERANCE,
|
||||
WELD,
|
||||
WELD_DISTANCE,
|
||||
FEATURE_ANGLE,
|
||||
];
|
||||
|
||||
pub const HEX_MAPPED: &[Field] = &[BODY, SURFACE, HEX_SIZE, HEX_ORDER, TOLERANCE, WELD, WELD_DISTANCE, FEATURE_ANGLE];
|
||||
|
||||
pub const HEX_BLOCKS: &[Field] =
|
||||
&[references("bodies", "Cells", C::Body).hint("every body of the design"), HEX_SIZE, HEX_ORDER, TOLERANCE, WELD, WELD_DISTANCE, FEATURE_ANGLE];
|
||||
|
||||
pub const HEX_OCTREE: &[Field] = &[
|
||||
BODY,
|
||||
SURFACE,
|
||||
HEX_SIZE,
|
||||
TOLERANCE,
|
||||
int("max_depth", "Refinement levels", 0, 5).hint("3"),
|
||||
int("max_elements", "Max elements", 1, 10_000_000),
|
||||
int("attempts", "Attempts", 1, 8).hint("4"),
|
||||
int("max_sweeps", "Optimiser sweeps", 0, 10_000).hint("300"),
|
||||
WELD,
|
||||
WELD_DISTANCE,
|
||||
FEATURE_ANGLE,
|
||||
];
|
||||
|
||||
pub const BLOCK: &[Field] = &[
|
||||
text("body", "Body").req().def("\"Block\""),
|
||||
choice(
|
||||
"kind",
|
||||
"Element",
|
||||
&[
|
||||
("hex8", "hex8"),
|
||||
("hex20", "hex20"),
|
||||
("tet4", "tet4"),
|
||||
("tet10", "tet10"),
|
||||
("wedge6", "wedge6"),
|
||||
("quad4", "quad4 (2D)"),
|
||||
("quad8", "quad8 (2D)"),
|
||||
("tri3", "tri3 (2D)"),
|
||||
("tri6", "tri6 (2D)"),
|
||||
],
|
||||
)
|
||||
.req()
|
||||
.def("\"hex8\""),
|
||||
json("corners", "Corners").req().hint("[[x, y, z] × 8] (2D: × 4 at z = 0)"),
|
||||
json("divisions", "Divisions").req().hint("[n12, n14, n15] (2D: [n12, n14])"),
|
||||
json("bias", "Bias").hint("[1, 1, 1]"),
|
||||
json("edges", "Curved and named edges"),
|
||||
json("faces", "Face names").hint("{\"1\": \"bottom\"}"),
|
||||
json("vertices", "Corner names"),
|
||||
text("face", "2D face name").hint("area"),
|
||||
positive("merge", "Merge distance", D::Length).hint("1e-6 of the diagonal"),
|
||||
];
|
||||
|
||||
pub const PLANAR: &[Field] = &[
|
||||
positive("size", "Element size", D::Length).req(),
|
||||
choice("kind", "Element", &[("quad4", "quad4"), ("quad8", "quad8"), ("tri3", "tri3"), ("tri6", "tri6")]).def("\"quad4\""),
|
||||
BODY,
|
||||
text("face", "Face").hint("a planar face of the body"),
|
||||
TOLERANCE,
|
||||
json("polygon", "Polygon").hint("[[x, y], …] instead of a face"),
|
||||
json("holes", "Holes"),
|
||||
text("name", "Body name").hint("Plane"),
|
||||
int("max_elements", "Max elements", 1, 4_000_000),
|
||||
];
|
||||
|
||||
pub const QUALITY: &[Field] = &[json("elements", "Elements").hint("[labels]; all when empty"), int("bins", "Histogram bins", 1, 1000).def("10")];
|
||||
|
||||
pub const SURFACE_CHECK: &[Field] =
|
||||
&[reference("body", "Body", C::Body).req().hint("or an imported surface"), SURFACE, TOLERANCE, WELD, WELD_DISTANCE, FEATURE_ANGLE];
|
||||
|
||||
pub const NODE_ADD: &[Field] = &[int("label", "Label", 1, u32::MAX as i64).req(), xyz("xyz", "Position", D::Length).req().def("[0, 0, 0]")];
|
||||
pub const LABEL: &[Field] = &[int("label", "Label", 1, u32::MAX as i64).req()];
|
||||
pub const ELEMENT_ADD: &[Field] = &[
|
||||
int("label", "Label", 1, u32::MAX as i64).req(),
|
||||
choice(
|
||||
"kind",
|
||||
"Kind",
|
||||
&[
|
||||
("rod2", "rod2"),
|
||||
("beam2", "beam2"),
|
||||
("tri3", "tri3"),
|
||||
("tri6", "tri6"),
|
||||
("quad4", "quad4"),
|
||||
("quad8", "quad8"),
|
||||
("tet4", "tet4"),
|
||||
("tet10", "tet10"),
|
||||
("wedge6", "wedge6"),
|
||||
("hex8", "hex8"),
|
||||
("hex20", "hex20"),
|
||||
],
|
||||
)
|
||||
.req()
|
||||
.def("\"hex8\""),
|
||||
json("nodes", "Nodes").req().hint("[labels]"),
|
||||
];
|
||||
|
||||
pub const DELAUNAY_POINTS: &[Field] = &[json("points", "Points").req().hint("[[x, y, z], …]")];
|
||||
|
||||
pub const TAG: &[Field] = &[
|
||||
group("geometry", "Geometry", &[reference("body", "Body", C::Body).req(), text("face", "Face"), text("edge", "Edge"), text("vertex", "Vertex")])
|
||||
.req(),
|
||||
json("elements", "Elements"),
|
||||
json("faces", "Element faces"),
|
||||
json("edges", "Element edges"),
|
||||
json("nodes", "Nodes"),
|
||||
];
|
||||
|
||||
// ---- Geometry and files ----
|
||||
|
||||
pub const OPEN_DESIGN: &[Field] = &[path("path", "Design", false).req()];
|
||||
pub const TESSELLATE: &[Field] = &[reference("body", "Body", C::Body).req(), TOLERANCE];
|
||||
pub const IMPORT_MESH: &[Field] = &[path("path", "3MF file", false).req()];
|
||||
pub const FILE_OPEN: &[Field] = &[path("path", "Model", false).req()];
|
||||
pub const FILE_SAVE: &[Field] = &[path("path", "File", true).hint("the model's file")];
|
||||
pub const FILE_SAVE_AS: &[Field] = &[path("path", "File", true).req()];
|
||||
pub const RECOVERY_LIST: &[Field] = &[path("dir", "Folder", false).hint("the recovery folder")];
|
||||
pub const RECOVER: &[Field] = &[text("id", "Autosave").req(), path("dir", "Folder", false).hint("the recovery folder")];
|
||||
pub const RECOVERY_DISCARD: &[Field] = &[text("id", "Autosave"), flag("all", "All"), path("dir", "Folder", false).hint("the recovery folder")];
|
||||
pub const SAMPLE: &[Field] =
|
||||
&[choice("name", "Sample", &[("cantilever", "Cantilever"), ("impact", "Impact"), ("parts", "Parts")]).req().def("\"cantilever\"")];
|
||||
pub const COUNT: &[Field] = &[int("count", "Count", 1, 1_000_000).def("1")];
|
||||
|
||||
pub const DECK: &[Field] = &[
|
||||
choice("format", "Format", &[("abaqus", "Abaqus input (.inp)"), ("nastran", "Nastran bulk data (.bdf)"), ("lsdyna", "LS-DYNA keyword (.k)")])
|
||||
.req()
|
||||
.def("\"abaqus\""),
|
||||
path("path", "File", true).req(),
|
||||
references("steps", "Steps", C::Step).hint("all"),
|
||||
];
|
||||
|
||||
// ---- Solving ----
|
||||
|
||||
const STEP: Field = reference("step", "Step", C::Step).hint("the only one");
|
||||
const SOLVED: Field = reference("step", "Step", C::SolvedStep).hint("the step shown");
|
||||
const MAX_DOFS: Field = int("max_dofs", "Max DOFs", 1, 6_000_000).hint("6000000");
|
||||
const MAX_FACTOR: Field = int("max_factor_entries", "Max factor entries", 1, 400_000_000).hint("400000000");
|
||||
const THREADS: Field = int("threads", "Threads", 1, 256).hint("the session's");
|
||||
|
||||
pub const SOLVE_STATIC: &[Field] = &[STEP, MAX_DOFS, MAX_FACTOR, THREADS];
|
||||
pub const SOLVE_NONLINEAR: &[Field] =
|
||||
&[STEP, MAX_DOFS, MAX_FACTOR, int("max_newton_iterations", "Max Newton iterations", 1, 100_000).hint("100000"), THREADS];
|
||||
pub const SOLVE_FREQUENCY: &[Field] = &[
|
||||
STEP,
|
||||
choice("mass", "Mass matrix", &[("consistent", "Consistent"), ("lumped", "Lumped")]).def("\"consistent\""),
|
||||
num("shift", "Shift", D::None).hint("0"),
|
||||
MAX_DOFS,
|
||||
MAX_FACTOR,
|
||||
int("max_iterations", "Max Lanczos vectors", 1, 3000).hint("3000"),
|
||||
THREADS,
|
||||
];
|
||||
pub const SOLVE_BUCKLE: &[Field] = &[STEP, MAX_DOFS, MAX_FACTOR, int("max_iterations", "Max Lanczos vectors", 1, 3000).hint("3000"), THREADS];
|
||||
pub const SOLVE_EXPLICIT: &[Field] = &[
|
||||
STEP,
|
||||
MAX_DOFS,
|
||||
int("max_increments", "Max increments", 1, 1_000_000_000).hint("1000000000"),
|
||||
int("max_output_values", "Max output values", 1, 50_000_000).hint("50000000"),
|
||||
int("max_contact_faces", "Max contact faces", 1, 10_000_000).hint("10000000"),
|
||||
THREADS,
|
||||
];
|
||||
pub const SOLVE_HISTORY: &[Field] = &[SOLVED.req(), int("every", "Keep one in", 1, 1_000_000_000)];
|
||||
pub const SOLVE_FLUID: &[Field] = &[
|
||||
STEP,
|
||||
int("max_cells", "Max cells", 1, 16_000_000),
|
||||
int("max_steps", "Max steps", 1, 10_000_000),
|
||||
positive("max_cell_updates", "Max cell updates", D::None),
|
||||
positive("max_frame_bytes", "Max frame bytes", D::None),
|
||||
THREADS,
|
||||
];
|
||||
pub const SOLVE_PROBE: &[Field] = &[
|
||||
SOLVED.req(),
|
||||
json("nodes", "Nodes").hint("[labels]"),
|
||||
reference("set", "Set", C::Set),
|
||||
json("at", "Points").hint("[[x, y, z], …]: nearest nodes"),
|
||||
int("mode", "Mode", 1, 1_000_000),
|
||||
int("frame", "Frame", 0, 1_000_000_000),
|
||||
flag("elements", "Element results"),
|
||||
json("points", "Fluid points").hint("[[x, y, z], …]"),
|
||||
json("forces", "Fluid walls").hint("[\"x_min\", \"F2:top\"]"),
|
||||
];
|
||||
|
||||
// ---- Results ----
|
||||
|
||||
pub const DEFORMED: &[Field] = &[SOLVED, flag("show", "Show").def("true"), json("scale", "Scale").def("\"auto\"").hint("\"auto\" or a factor")];
|
||||
pub const CONTOUR: &[Field] = &[
|
||||
SOLVED,
|
||||
choice(
|
||||
"field",
|
||||
"Field",
|
||||
&[
|
||||
("von_mises", "Von Mises stress"),
|
||||
("displacement", "Displacement"),
|
||||
("displacement_x", "Displacement X"),
|
||||
("displacement_y", "Displacement Y"),
|
||||
("displacement_z", "Displacement Z"),
|
||||
("max_principal", "Max principal"),
|
||||
("mid_principal", "Mid principal"),
|
||||
("min_principal", "Min principal"),
|
||||
("stress_xx", "Stress XX"),
|
||||
("stress_yy", "Stress YY"),
|
||||
("stress_zz", "Stress ZZ"),
|
||||
("stress_xy", "Stress XY"),
|
||||
("stress_xz", "Stress XZ"),
|
||||
("stress_yz", "Stress YZ"),
|
||||
("none", "None"),
|
||||
],
|
||||
)
|
||||
.req()
|
||||
.def("\"von_mises\""),
|
||||
int("bands", "Bands", 2, 24).def("12"),
|
||||
];
|
||||
pub const MODES: &[Field] = &[SOLVED, int("mode", "Mode", 1, 1_000_000).def("1")];
|
||||
pub const ANIMATE: &[Field] = &[flag("on", "Animate").def("true")];
|
||||
pub const FRAME: &[Field] = &[SOLVED, int("frame", "Frame", 0, 1_000_000_000), positive("time", "Time", D::Time).hint("the last frame")];
|
||||
pub const REACTIONS: &[Field] = &[SOLVED, references("sets", "Sets", C::Set).hint("the step's BC sets"), xyz("about", "About point", D::Length)];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::*;
|
||||
use crate::{EngineError, Session};
|
||||
|
||||
/// The form's starting parameters (and those with the required names and references filled
|
||||
/// in from the model) are accepted, or refused only for a required field still empty; never
|
||||
/// for a value the form put there itself. Errors other than parameter errors (no design, no
|
||||
/// results) come after the parameters were read.
|
||||
#[test]
|
||||
fn form_defaults_are_accepted_or_need_only_required_fields() {
|
||||
let (mut checked, mut failures) = (0, Vec::new());
|
||||
for c in crate::commands() {
|
||||
let Some(form) = c.form else { continue };
|
||||
if c.id.starts_with("file.") && c.id != "file.save_as" || c.id == "edit.undo" || c.id == "edit.redo" {
|
||||
continue; // they replace or write the session's model; their forms are paths and counts
|
||||
}
|
||||
for fill_refs in [false, true] {
|
||||
let limits = crate::Limits { max_steiner: 10, max_tets: 100, max_hex_elements: 100, threads: 1 };
|
||||
let mut s = Session { limits, ..Session::default() };
|
||||
crate::cmd::define::tests::defined_bar(&mut s);
|
||||
s.execute("solve.run", &json!({})).unwrap();
|
||||
let mut p = prefill(form, &json!({}));
|
||||
if fill_refs {
|
||||
fill_required(&s, form, &mut p);
|
||||
}
|
||||
let missing: Vec<String> = problems(form, &p).into_iter().filter(|p| p.message == "required").map(|p| p.path).collect();
|
||||
match s.execute(c.id, &p) {
|
||||
// State, not parameters: the meshers' default is the open design's bodies, the
|
||||
// bar has no explicit step; activation and probes need one of several fields.
|
||||
Err(EngineError::Params(e)) if STATE.iter().any(|m| e.contains(m)) => {}
|
||||
Err(EngineError::Params(e)) if !missing.iter().any(|k| e.contains(k.rsplit('/').next().unwrap_or(k))) => {
|
||||
failures.push(format!("{}: {p} refused for `{e}`, but only {missing:?} were missing", c.id));
|
||||
}
|
||||
Err(EngineError::Params(_)) => {}
|
||||
_ => checked += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(failures.is_empty(), "{failures:#?}");
|
||||
assert!(checked > 20, "{checked}");
|
||||
}
|
||||
|
||||
/// The commands whose form is the JSON text alone (no schema yet). None: keep it that way.
|
||||
#[test]
|
||||
fn every_command_has_a_form() {
|
||||
let without: Vec<&str> = crate::commands().iter().filter(|c| c.form.is_none()).map(|c| c.id).collect();
|
||||
assert_eq!(without, Vec::<&str>::new());
|
||||
// A command that takes nothing has an empty form, and says so.
|
||||
for c in crate::commands() {
|
||||
assert_eq!(c.form.is_some_and(<[Field]>::is_empty), c.params.trim_start().starts_with("{}"), "{}", c.id);
|
||||
}
|
||||
}
|
||||
|
||||
const STATE: &[&str] = &["open a design first", "`boundary_conditions` or `loads`", "give one of", "is not an explicit", "has a result"];
|
||||
|
||||
/// Fill top-level required names (a fresh one) and references (the first existing item).
|
||||
fn fill_required(s: &Session, form: &[Field], p: &mut Value) {
|
||||
let Some(obj) = p.as_object_mut() else { return };
|
||||
for f in form {
|
||||
if !f.required || obj.contains_key(f.key) {
|
||||
continue;
|
||||
}
|
||||
match f.kind {
|
||||
Kind::Text => {
|
||||
obj.insert(f.key.into(), json!("Fresh"));
|
||||
}
|
||||
Kind::Ref(c) => {
|
||||
if let Some(n) = s.names(c).first() {
|
||||
obj.insert(f.key.into(), json!(n));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every default is JSON; every variant field's default names a variant.
|
||||
#[test]
|
||||
fn defaults_parse() {
|
||||
fn walk(fields: &[Field]) {
|
||||
for f in fields {
|
||||
if let Some(d) = f.default {
|
||||
assert!(serde_json::from_str::<serde_json::Value>(d).is_ok(), "{}: {d}", f.key);
|
||||
}
|
||||
match f.kind {
|
||||
Kind::Group(g) | Kind::Rows { fields: g, .. } | Kind::Either(g) => walk(g),
|
||||
Kind::Variants { variants, .. } => variants.iter().for_each(|v| walk(v.fields)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
for c in crate::commands() {
|
||||
if let Some(form) = c.form {
|
||||
walk(form);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ pub const OPEN: CommandSpec = CommandSpec {
|
||||
id: "geometry.open",
|
||||
label: "Open Design",
|
||||
params: r#"{"path": "part.solidcraft"} — rebuilds the SolidCraft design and makes its bodies the geometry; opening it again after an edit picks up the change"#,
|
||||
form: Some(super::forms::OPEN_DESIGN),
|
||||
kind: CommandKind::Model,
|
||||
run: open,
|
||||
};
|
||||
@@ -20,6 +21,7 @@ pub const BODIES: CommandSpec = CommandSpec {
|
||||
id: "geometry.bodies",
|
||||
label: "Bodies",
|
||||
params: "{} — the open design's bodies: measures and persistent face names (by face index)",
|
||||
form: Some(&[]),
|
||||
kind: CommandKind::Model,
|
||||
run: bodies,
|
||||
};
|
||||
@@ -28,6 +30,7 @@ pub const TESSELLATE: CommandSpec = CommandSpec {
|
||||
id: "geometry.tessellate",
|
||||
label: "Tessellate Body",
|
||||
params: r#"{"body": "Body1", "tolerance": 0.05} — triangulates the body's boundary within the chordal tolerance (mm); reports triangles per face"#,
|
||||
form: Some(super::forms::TESSELLATE),
|
||||
kind: CommandKind::Model,
|
||||
run: tessellate,
|
||||
};
|
||||
@@ -36,6 +39,7 @@ pub const IMPORT_MESH: CommandSpec = CommandSpec {
|
||||
id: "geometry.import.mesh",
|
||||
label: "Import Tagged Mesh",
|
||||
params: r#"{"path": "part.3mf"} — adds each build item of a 3MF package as a surface; triangles keep their B-rep face tags (docs/formats/tagged-mesh.md)"#,
|
||||
form: Some(super::forms::IMPORT_MESH),
|
||||
kind: CommandKind::Model,
|
||||
run: import_mesh,
|
||||
};
|
||||
|
||||
@@ -15,6 +15,7 @@ pub const HEX_GENERATE: CommandSpec = CommandSpec {
|
||||
id: "mesh.hex.generate",
|
||||
label: "Generate Hex Mesh",
|
||||
params: r#"{"body": "Body1" (default: every body of the open design) or "surface": 0 (an imported surface), "size": 2.0 (element size, mm; default 1/25 of the bounding-box diagonal), "order": 1 (hex8) or 2 (hex20, mid-edge nodes on the geometry), "method": "auto" (default) | "swept" (any sweep) | "extrude" | "sweep" | "revolve" | "mapped", "tolerance": 0.05 (chordal tolerance of the tessellation, mm; default 1e-3 of the diagonal)} — replaces the mesh with structured hexahedra: multi-level sweeps along a direction or around an axis, one-to-one sweeps through linking faces, or mapped blocks. Boundary element faces are tagged with their B-rep faces (named as in geometry.bodies; by index when a face has no name; `weld`, `weld_distance` and `feature_angle` as in mesh.tet.generate), so sets by geometry resolve. Reports per body the method, counts and quality; a body no structured method fits is an error that says why"#,
|
||||
form: Some(super::forms::HEX_GENERATE),
|
||||
kind: CommandKind::Model,
|
||||
run: hex_generate,
|
||||
};
|
||||
@@ -117,6 +118,7 @@ pub const HEX_SWEEP: CommandSpec = CommandSpec {
|
||||
id: "mesh.hex.sweep",
|
||||
label: "Sweep Hex Mesh",
|
||||
params: r#"the parameters of mesh.hex.generate, with "method": "swept" (default: extrude, sweep or revolve, whichever fits first) | "extrude" | "sweep" | "revolve" — mesh.hex.generate limited to the sweeping methods"#,
|
||||
form: Some(super::forms::HEX_SWEEP),
|
||||
kind: CommandKind::Model,
|
||||
run: hex_sweep,
|
||||
};
|
||||
@@ -125,6 +127,7 @@ pub const HEX_MAPPED: CommandSpec = CommandSpec {
|
||||
id: "mesh.hex.mapped",
|
||||
label: "Mapped Hex Mesh",
|
||||
params: r#"the parameters of mesh.hex.generate without "method" — mesh.hex.generate with the mapped method: a six-sided block (six faces of four edges, three edges at each of eight corners)"#,
|
||||
form: Some(super::forms::HEX_MAPPED),
|
||||
kind: CommandKind::Model,
|
||||
run: hex_mapped,
|
||||
};
|
||||
@@ -133,6 +136,7 @@ pub const HEX_BLOCKS: CommandSpec = CommandSpec {
|
||||
id: "mesh.hex.blocks",
|
||||
label: "Block Hex Mesh",
|
||||
params: r#"{"bodies": ["Cell1", "Cell2"] (default: every body of the open design), "size": 2.0 (element size, mm; default 1/25 of the bounding-box diagonal of all of them), "order": 1 (hex8) or 2 (hex20, mid-edge nodes on the geometry), "tolerance": 0.05 (chordal tolerance of the tessellation, mm; default 1e-3 of that diagonal)} — replaces the mesh with one conforming all-hex mesh of a part partitioned into cells (bodies that meet face to face, such as the pieces of solid.split_body in SolidCraft): every cell a mapped block (six four-sided faces; faces that meet smoothly, such as the two halves of a hole, count as one), division counts assigned over all cells together, each shared face meshed once and its nodes merged, radial lines graded off holes and fillets. Elements are tagged with their cell's body and boundary faces with its B-rep faces (`weld`, `weld_distance` and `feature_angle` as in mesh.tet.generate). Reports the cells, the shared faces, counts and quality; a cell that is not a block, or cells that touch without sharing whole faces, is an error that says which"#,
|
||||
form: Some(super::forms::HEX_BLOCKS),
|
||||
kind: CommandKind::Model,
|
||||
run: hex_blocks,
|
||||
};
|
||||
|
||||
@@ -19,6 +19,7 @@ pub const NODE_ADD: CommandSpec = CommandSpec {
|
||||
id: "mesh.node.add",
|
||||
label: "Add Node",
|
||||
params: r#"{"label": 1, "xyz": [x, y, z]} — adds the node, or moves it if the label exists"#,
|
||||
form: Some(super::forms::NODE_ADD),
|
||||
kind: CommandKind::Model,
|
||||
run: node_add,
|
||||
};
|
||||
@@ -27,6 +28,7 @@ pub const NODE_REMOVE: CommandSpec = CommandSpec {
|
||||
id: "mesh.node.remove",
|
||||
label: "Remove Node",
|
||||
params: r#"{"label": 1} — only a node no element uses"#,
|
||||
form: Some(super::forms::LABEL),
|
||||
kind: CommandKind::Model,
|
||||
run: node_remove,
|
||||
};
|
||||
@@ -35,17 +37,25 @@ pub const ELEMENT_ADD: CommandSpec = CommandSpec {
|
||||
id: "mesh.element.add",
|
||||
label: "Add Element",
|
||||
params: r#"{"label": 1, "kind": "rod2|beam2|tri3|tri6|quad4|quad8|tet4|tet10|wedge6|hex8|hex20", "nodes": [labels]} — adds or replaces"#,
|
||||
form: Some(super::forms::ELEMENT_ADD),
|
||||
kind: CommandKind::Model,
|
||||
run: element_add,
|
||||
};
|
||||
|
||||
pub const ELEMENT_REMOVE: CommandSpec =
|
||||
CommandSpec { id: "mesh.element.remove", label: "Remove Element", params: r#"{"label": 1}"#, kind: CommandKind::Model, run: element_remove };
|
||||
pub const ELEMENT_REMOVE: CommandSpec = CommandSpec {
|
||||
id: "mesh.element.remove",
|
||||
label: "Remove Element",
|
||||
params: r#"{"label": 1}"#,
|
||||
form: Some(super::forms::LABEL),
|
||||
kind: CommandKind::Model,
|
||||
run: element_remove,
|
||||
};
|
||||
|
||||
pub const QUALITY: CommandSpec = CommandSpec {
|
||||
id: "mesh.quality",
|
||||
label: "Mesh Quality",
|
||||
params: r#"{"elements": [labels] (optional, default all), "bins": 10 (1..=1000)} — certified validity (det J > 0 everywhere), volume, and min/max/mean/worst/histogram per metric (angles in degrees; histograms over each metric's fixed range, out-of-range values in the end bins)"#,
|
||||
form: Some(super::forms::QUALITY),
|
||||
kind: CommandKind::Model,
|
||||
run: quality_report,
|
||||
};
|
||||
@@ -54,6 +64,7 @@ pub const DELAUNAY_POINTS: CommandSpec = CommandSpec {
|
||||
id: "mesh.delaunay.points",
|
||||
label: "Delaunay of Points",
|
||||
params: r#"{"points": [[x, y, z], ...] (at most 20000)} — the exact Delaunay tetrahedralization (a debugging report; the model is not changed): {"dimension", "vertices", "duplicates": [[point, kept point], ...], "tets": [[i, j, k, l], ...]} with 0-based point indices in tet4 order; collinear or coplanar points give no tets"#,
|
||||
form: Some(super::forms::DELAUNAY_POINTS),
|
||||
kind: CommandKind::Model,
|
||||
run: delaunay_points,
|
||||
};
|
||||
@@ -79,6 +90,7 @@ pub const SURFACE_CHECK: CommandSpec = CommandSpec {
|
||||
id: "mesh.surface.check",
|
||||
label: "Check Boundary Surface",
|
||||
params: r#"{"body": "Body1", "tolerance": 0.05} or {"surface": 0}, optional "weld": 1e-9 (0 or 1e-15..=1e-3 of the bounding-box diagonal), "weld_distance": mm (default: the surface's own, twice SolidCraft's linear tolerance for a tessellated body, 0 for an imported mesh), "feature_angle": 45 (degrees, (0, 180]) — welds the tessellated body or imported surface and checks it can bound a volume mesh: closed, manifold, outward, no self-intersections; reports shells, genus, volume and feature edges, or the located defects"#,
|
||||
form: Some(super::forms::SURFACE_CHECK),
|
||||
kind: CommandKind::Model,
|
||||
run: surface_check,
|
||||
};
|
||||
@@ -87,6 +99,7 @@ pub const TET_GENERATE: CommandSpec = CommandSpec {
|
||||
id: "mesh.tet.generate",
|
||||
label: "Generate Tet Mesh",
|
||||
params: r#"{"body": "Body1" (default: every body of the open design) or "surface": 0 (an imported surface), "tolerance": 0.05 (chordal tolerance of the tessellation, mm; default 1e-3 of the body's bounding-box diagonal), the boundary options of mesh.surface.check ("weld", "weld_distance", "feature_angle"), optional "size": mm (target edge length; default a twentieth of the bounding-box diagonal), "order": "linear" | "quadratic" (tet4 or tet10; quadratic mid-edge nodes lie on the B-rep faces), "quality": true (false: the raw constrained Delaunay tetrahedralization), "quality_target": 40 (degrees: tetrahedra whose smallest dihedral-angle sine is at least sin of this are left alone by improvement, 5..=60), "curvature_angle": 22.5 (degrees per element along curved boundary, 0 for none, at most 90), "grading": 0.3 (largest size change per unit length, 0.05..=2), "max_passes": 20 (improvement passes, 0..=200), "max_points": 1000000 (1..=20000000), "max_steiner": 50000 (0..=10000000), "max_tets": 5000000 (1..=50000000) — the constrained Delaunay tetrahedralization of the welded boundary (every boundary triangle a union of tet faces), refined to the size field with its boundary vertices on the B-rep faces, smoothed and improved (Delaunay refinement, ODT smoothing, Klingner–Shewchuk improvement), with a quality report. Adds the elements and their nodes (labels after the largest existing ones), tags the elements with the body and each boundary element face with its geometry face, and fails, changing nothing, if a surface is invalid or a mesh does not pass the validity gate. Reports the totals and, under `bodies`, each body's counts, size and quality report"#,
|
||||
form: Some(super::forms::TET),
|
||||
kind: CommandKind::Model,
|
||||
run: tet_generate,
|
||||
};
|
||||
@@ -335,6 +348,7 @@ pub const PLANAR: CommandSpec = CommandSpec {
|
||||
id: "mesh.planar",
|
||||
label: "2D Mesh",
|
||||
params: r#"{"size": 1.0, "kind": "quad4|quad8|tri3|tri6" (default quad4), and either "polygon": [[x, y], ...] with optional "holes": [[[x, y], ...], ...] and "name": "Plane" (the body name its tags use), or "body": "Body1", "face": "F2:top", "tolerance": 0.05 (a planar face of an open design, parallel to XY); optional "max_elements": 1000000 (1..=4000000)} — meshes the planar region with 2D elements in the XY plane (a face at z = c is meshed at z = 0) for plane stress, plane strain or axisymmetric sections (x the radius, Y the axis): free quadrilaterals (or constrained Delaunay triangles) of about `size`, mid-side nodes on the boundary for quadratic kinds. Adds nodes and elements after the largest existing labels and tags them: the elements with the face (polygon: face `area` of body `name`), the boundary element edges with edges named after the neighbouring face of the body (polygon: `e1`, `e2`, … side by side, the outer loop then each hole, and vertices `v1`, … at the corners), so sets on those edges carry loads and boundary conditions"#,
|
||||
form: Some(super::forms::PLANAR),
|
||||
kind: CommandKind::Model,
|
||||
run: planar,
|
||||
};
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
//! The command registry. Each area has its own module; [`ALL`] lists every command.
|
||||
|
||||
mod block;
|
||||
mod contact;
|
||||
pub(crate) mod deck;
|
||||
pub(crate) mod define;
|
||||
mod edit;
|
||||
pub(crate) mod file;
|
||||
pub(crate) mod forms;
|
||||
mod geometry;
|
||||
mod hex;
|
||||
pub(crate) mod mesh;
|
||||
@@ -67,6 +69,11 @@ pub static ALL: &[CommandSpec] = &[
|
||||
define::COUPLING_CREATE,
|
||||
define::COUPLING_EDIT,
|
||||
define::COUPLING_DELETE,
|
||||
contact::PAIR,
|
||||
contact::GENERAL,
|
||||
contact::EDIT,
|
||||
contact::DELETE,
|
||||
contact::FIND,
|
||||
define::MASS_CREATE,
|
||||
define::MASS_EDIT,
|
||||
define::MASS_DELETE,
|
||||
@@ -102,6 +109,7 @@ pub static ALL: &[CommandSpec] = &[
|
||||
solve::STATIC,
|
||||
solve::NONLINEAR,
|
||||
solve::FREQUENCY,
|
||||
solve::BUCKLE,
|
||||
solve::HEAT,
|
||||
solve::EXPLICIT,
|
||||
solve::HISTORY,
|
||||
|
||||
@@ -4,22 +4,26 @@ use serde_json::{Value, json};
|
||||
use super::{listed, name};
|
||||
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
|
||||
|
||||
pub const INFO: CommandSpec = CommandSpec { id: "model.info", label: "Model Info", params: "{}", kind: CommandKind::Model, run: info };
|
||||
pub const INFO: CommandSpec =
|
||||
CommandSpec { id: "model.info", label: "Model Info", params: "{}", form: Some(&[]), kind: CommandKind::Model, run: info };
|
||||
|
||||
pub const UNITS: CommandSpec = CommandSpec {
|
||||
id: "model.units",
|
||||
label: "Unit System",
|
||||
params: r#"{"system": "m-kg-s-N-Pa|mm-t-s-N-MPa|mm-kg-ms-kN-GPa|mm-g-ms-N-MPa|in-lbf-s-psi|unspecified"} — labels the system the model's numbers are in; nothing is converted"#,
|
||||
form: Some(super::forms::UNITS),
|
||||
kind: CommandKind::Model,
|
||||
run: units,
|
||||
};
|
||||
|
||||
pub const CHECK: CommandSpec = CommandSpec { id: "model.check", label: "Check Model", params: "{}", kind: CommandKind::Model, run: check };
|
||||
pub const CHECK: CommandSpec =
|
||||
CommandSpec { id: "model.check", label: "Check Model", params: "{}", form: Some(&[]), kind: CommandKind::Model, run: check };
|
||||
|
||||
pub const SET_RESOLVE: CommandSpec = CommandSpec {
|
||||
id: "model.set.resolve",
|
||||
label: "Resolve Set",
|
||||
params: r#"{"name": "root"} — the set's nodes, elements and element faces on the current mesh (the first 100 of each); fails naming every member that is not on the mesh"#,
|
||||
form: Some(super::forms::SET_RESOLVE),
|
||||
kind: CommandKind::Model,
|
||||
run: set_resolve,
|
||||
};
|
||||
|
||||
@@ -15,6 +15,7 @@ pub const HEX_OCTREE: CommandSpec = CommandSpec {
|
||||
id: "mesh.hex.octree",
|
||||
label: "Octree Hex Mesh",
|
||||
params: r#"{"body": "Body1" (default: every body of the open design) or "surface": 0 (an imported surface), "size": 2.0 (element size in the interior, mm; default 1/25 of the bounding-box diagonal), "tolerance": 0.05 (chordal tolerance of the tessellation, mm; default 1e-3 of the diagonal), "max_depth": 3 (refinement levels below the size, each a third, 0..=5), "max_elements": 2000000 (1..=10000000; default the session limit), "attempts": 4 (builds, refining where one failed, 1..=8), "max_sweeps": 300 (optimiser sweeps, 0..=10000), and the boundary options of mesh.tet.generate ("weld", "weld_distance", "feature_angle")} — replaces the mesh with an unstructured all-hex8 mesh of any part: an adaptive 3-refinement grid with conforming transition templates, a core inside the part, two boundary layers that capture every B-rep face boundary and sharp edge, and untangling. Every element is proven valid; boundary element faces are tagged with their B-rep faces (named as in geometry.bodies; by index when a face has no name), so sets by geometry resolve. Reports per body the elements, quality, volume and grid statistics"#,
|
||||
form: Some(super::forms::HEX_OCTREE),
|
||||
kind: CommandKind::Model,
|
||||
run: hex_octree,
|
||||
};
|
||||
|
||||
@@ -12,6 +12,7 @@ pub const DEFORMED: CommandSpec = CommandSpec {
|
||||
id: "results.deformed",
|
||||
label: "Deformed Shape",
|
||||
params: r#"{"step": "Load", "show": true, "scale": "auto"} — shows a solved step's deformed shape (`show: false` the undeformed mesh); `scale` is a factor (0 draws the undeformed shape, so a sequence from 0 swings it out) or "auto" (the largest displacement drawn a tenth of the model's size); `step` defaults to the step shown or the first solved one"#,
|
||||
form: Some(super::forms::DEFORMED),
|
||||
kind: CommandKind::Session,
|
||||
run: deformed,
|
||||
};
|
||||
@@ -20,6 +21,7 @@ pub const CONTOUR: CommandSpec = CommandSpec {
|
||||
id: "results.contour",
|
||||
label: "Contours",
|
||||
params: r#"{"step": "Load", "field": "von_mises", "bands": 12} — contours of a nodal field: displacement, displacement_x/y/z, von_mises, max/mid/min_principal, stress_xx/yy/zz/xy/xz/yz (stresses for static steps); "none" turns them off; 2 to 24 bands"#,
|
||||
form: Some(super::forms::CONTOUR),
|
||||
kind: CommandKind::Session,
|
||||
run: contour,
|
||||
};
|
||||
@@ -28,6 +30,7 @@ pub const MODES: CommandSpec = CommandSpec {
|
||||
id: "results.modes",
|
||||
label: "Mode Shapes",
|
||||
params: r#"{"step": "Modes", "mode": 1} — shows a mode shape of a solved frequency step (from 1) and lists every mode's frequency"#,
|
||||
form: Some(super::forms::MODES),
|
||||
kind: CommandKind::Session,
|
||||
run: modes,
|
||||
};
|
||||
@@ -36,6 +39,7 @@ pub const ANIMATE: CommandSpec = CommandSpec {
|
||||
id: "results.animate",
|
||||
label: "Animate",
|
||||
params: r#"{"on": true} — animates the deformed shape: a mode swings through its positive and negative shape, a static step grows from undeformed to deformed"#,
|
||||
form: Some(super::forms::ANIMATE),
|
||||
kind: CommandKind::Session,
|
||||
run: animate,
|
||||
};
|
||||
@@ -44,6 +48,7 @@ pub const FRAME: CommandSpec = CommandSpec {
|
||||
id: "results.frame",
|
||||
label: "Field Frame",
|
||||
params: r#"{"step": "Impact", "frame": 3, "time": 0.002} — shows a field frame of a solved explicit step, by index from 0 or the frame nearest a time (neither: the last), or of a nonlinear static step (one per converged increment, `time` its load factor; the deformed shape follows it, its contours show the final state); the deformed shape and contours follow it"#,
|
||||
form: Some(super::forms::FRAME),
|
||||
kind: CommandKind::Session,
|
||||
run: frame,
|
||||
};
|
||||
@@ -52,6 +57,7 @@ pub const REACTIONS: CommandSpec = CommandSpec {
|
||||
id: "results.reactions",
|
||||
label: "Reaction Sums",
|
||||
params: r#"{"step": "Load", "sets": ["root"], "about": [0, 0, 0]} — reaction force and moment (about the point) summed over each node set, and over the whole model; `sets` defaults to the sets the step's boundary conditions hold"#,
|
||||
form: Some(super::forms::REACTIONS),
|
||||
kind: CommandKind::Session,
|
||||
run: reactions,
|
||||
};
|
||||
@@ -60,6 +66,7 @@ pub const CLEAR: CommandSpec = CommandSpec {
|
||||
id: "results.clear",
|
||||
label: "Hide Results",
|
||||
params: "{} — back to the model: hides the deformed shape, contours and modes",
|
||||
form: Some(&[]),
|
||||
kind: CommandKind::Session,
|
||||
run: clear,
|
||||
};
|
||||
|
||||
@@ -7,8 +7,8 @@ use fieldcraft_mesh::surface::{BoundarySurface, SurfaceOptions};
|
||||
use fieldcraft_model::FluidDomain;
|
||||
use fieldcraft_parallel as parallel;
|
||||
use fieldcraft_solver::{
|
||||
FrequencyOptions, Limits, Location, MassKind, StaticResult, StepResult as ImplicitResult, solve_frequency, solve_heat, solve_nonlinear,
|
||||
solve_static,
|
||||
FrequencyOptions, Limits, Location, MassKind, StaticResult, StepResult as ImplicitResult, solve_buckle, solve_frequency, solve_heat,
|
||||
solve_nonlinear, solve_static,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -19,6 +19,7 @@ pub const RUN: CommandSpec = CommandSpec {
|
||||
id: "solve.run",
|
||||
label: "Solve All Steps",
|
||||
params: r#"{} — solves every step in order with its procedure's solver (solve.static, solve.frequency, solve.explicit, solve.fluid with their default caps) and keeps the results; stops at the first step that fails, naming it"#,
|
||||
form: Some(&[]),
|
||||
kind: CommandKind::Model,
|
||||
run: run_all,
|
||||
};
|
||||
@@ -27,6 +28,7 @@ pub const STATIC: CommandSpec = CommandSpec {
|
||||
id: "solve.static",
|
||||
label: "Solve Static Step",
|
||||
params: r#"{"step": "Load", "max_dofs": 6000000, "max_factor_entries": 400000000, "threads": 8} — solves a linear static or coupled temperature–displacement step (the only one when `step` is left out) and keeps the result in the session; the caps may only be lowered; `threads` (1 to 256, by default the session's: `FIELDCRAFT_THREADS` or the cores) changes only the time, never the result"#,
|
||||
form: Some(super::forms::SOLVE_STATIC),
|
||||
kind: CommandKind::Model,
|
||||
run: run_static,
|
||||
};
|
||||
@@ -35,6 +37,7 @@ pub const NONLINEAR: CommandSpec = CommandSpec {
|
||||
id: "solve.nonlinear",
|
||||
label: "Solve Nonlinear Static Step",
|
||||
params: r#"{"step": "Inflate", "max_dofs": 6000000, "max_factor_entries": 400000000, "max_newton_iterations": 100000, "threads": 8} — solves a nonlinear static step (the only one when `step` is left out) in load increments with Newton–Raphson iterations and keeps the result in the session: the final displacements, reactions, Cauchy stresses and logarithmic strains (small strains without nonlinear geometry), the equivalent plastic strain of plastic materials (the largest in the summary), every increment's load factor, iterations and residuals (force, displacement and energy, relative to their tolerances' scales), and a displacement frame per converged increment; the caps may only be lowered (`max_newton_iterations` over the whole step); `threads` as for solve.static"#,
|
||||
form: Some(super::forms::SOLVE_NONLINEAR),
|
||||
kind: CommandKind::Model,
|
||||
run: run_nonlinear,
|
||||
};
|
||||
@@ -43,6 +46,7 @@ pub const HEAT: CommandSpec = CommandSpec {
|
||||
id: "solve.heat",
|
||||
label: "Solve Heat Transfer Step",
|
||||
params: r#"{"step": "Heat", "max_dofs": 6000000, "max_factor_entries": 400000000, "threads": 8} — steady or transient heat conduction of a heat transfer step (the only one when `step` is left out): temperatures, heat flux and the heat flow at prescribed temperatures, kept in the session; the caps may only be lowered; `threads` as for solve.static"#,
|
||||
form: Some(super::forms::SOLVE_STATIC),
|
||||
kind: CommandKind::Model,
|
||||
run: run_heat,
|
||||
};
|
||||
@@ -51,14 +55,25 @@ pub const FREQUENCY: CommandSpec = CommandSpec {
|
||||
id: "solve.frequency",
|
||||
label: "Solve Frequency Step",
|
||||
params: r#"{"step": "Modes", "mass": "consistent|lumped", "shift": 0.0, "max_dofs": 6000000, "max_factor_entries": 400000000, "max_iterations": 3000, "threads": 8} — natural frequencies and mode shapes of a frequency step (its modes and range); `max_iterations` caps the Lanczos vectors; the result stays in the session; `threads` as for solve.static"#,
|
||||
form: Some(super::forms::SOLVE_FREQUENCY),
|
||||
kind: CommandKind::Model,
|
||||
run: run_frequency,
|
||||
};
|
||||
|
||||
pub const BUCKLE: CommandSpec = CommandSpec {
|
||||
id: "solve.buckle",
|
||||
label: "Solve Buckling Step",
|
||||
params: r#"{"step": "Buckle", "max_dofs": 6000000, "max_factor_entries": 400000000, "max_iterations": 3000, "threads": 8} — linear buckling of a buckling step (the only one when `step` is left out): the step's loads as a linear preload, then the lowest load factors λ with (K + λ K_σ) φ = 0 and their mode shapes (largest component 1), or those above the step's shift (whose LDLᵀ factor counts the load factors below it); negative load factors found are reported; the result stays in the session and its modes display like frequency modes; `threads` as for solve.static"#,
|
||||
form: Some(super::forms::SOLVE_BUCKLE),
|
||||
kind: CommandKind::Model,
|
||||
run: run_buckle,
|
||||
};
|
||||
|
||||
pub const EXPLICIT: CommandSpec = CommandSpec {
|
||||
id: "solve.explicit",
|
||||
label: "Solve Explicit Dynamic Step",
|
||||
params: r#"{"step": "Impact", "max_dofs": 6000000, "max_increments": 1000000000, "max_output_values": 50000000, "threads": 8} — transient response of an explicit dynamic step (the only one when `step` is left out) by central differences; keeps its histories and field frames in the session; the caps may only be lowered (the step's own increment cap applies too); `threads` as for solve.static"#,
|
||||
params: r#"{"step": "Impact", "max_dofs": 6000000, "max_increments": 1000000000, "max_output_values": 50000000, "max_contact_faces": 10000000, "threads": 8} — transient response of an explicit dynamic step (the only one when `step` is left out) by central differences, with the model's contacts (interaction.contact.*) and the step's rigid walls; keeps its histories and field frames in the session and reports each contact's peak force, first and last contact, deepest penetration, friction dissipated and the nodes adjusted at the start; the caps may only be lowered (the step's own increment cap applies too); `threads` as for solve.static"#,
|
||||
form: Some(super::forms::SOLVE_EXPLICIT),
|
||||
kind: CommandKind::Model,
|
||||
run: run_explicit,
|
||||
};
|
||||
@@ -66,7 +81,8 @@ pub const EXPLICIT: CommandSpec = CommandSpec {
|
||||
pub const HISTORY: CommandSpec = CommandSpec {
|
||||
id: "solve.history",
|
||||
label: "Result Histories",
|
||||
params: r#"{"step": "Impact", "every": 1} — the time histories of a solved explicit step: time, increment, energies, momentum, constraint force and the history nodes' displacement and velocity; `every` keeps one sample in so many (by default enough to return at most 10000)"#,
|
||||
params: r#"{"step": "Impact", "every": 1} — the time histories of a solved explicit step: time, increment, energies, momentum, constraint force, the normal force across each contact (in `contacts` order) and the history nodes' displacement and velocity; `every` keeps one sample in so many (by default enough to return at most 10000)"#,
|
||||
form: Some(super::forms::SOLVE_HISTORY),
|
||||
kind: CommandKind::Model,
|
||||
run: history,
|
||||
};
|
||||
@@ -75,6 +91,7 @@ pub const FLUID: CommandSpec = CommandSpec {
|
||||
id: "solve.fluid",
|
||||
label: "Solve Fluid Step",
|
||||
params: r#"{"step": "Flow", "max_cells": 16000000, "max_steps": 10000000, "max_cell_updates": 1e12, "max_frame_bytes": 2e9, "threads": 8} — runs a fluid step with the lattice Boltzmann solver (the only fluid step when `step` is left out): obstacles are triangulated from the open design or taken from imported surfaces; returns the time step, relaxation time, Mach number, mass and the final force on every wall; the caps may only be lowered; `threads` as for solve.static"#,
|
||||
form: Some(super::forms::SOLVE_FLUID),
|
||||
kind: CommandKind::Model,
|
||||
run: run_fluid,
|
||||
};
|
||||
@@ -83,6 +100,7 @@ pub const PROBE: CommandSpec = CommandSpec {
|
||||
id: "solve.probe",
|
||||
label: "Probe Results",
|
||||
params: r#"{"step": "Load", "nodes": [1, 2] (or "set": "fillet", a set's nodes), "mode": 1, "frame": 0} — the stored result at nodes (with `max_von_mises`, the largest among them, for static steps): displacement, rotation, reaction, reaction moment, stress and von Mises (static, with `elements` each element's results: solid, 2D and truss nodal stresses (and, in a nonlinear step, the equivalent plastic strain at the integration points of a plastic element), shell section forces (N, M, Q per length in the element's axes) and bottom, middle and top stresses, beam end forces (N, V_y, V_z, T, M_y, M_z in its axes)), the shape of mode `mode` with its rotations (frequency, from 1), or displacement and velocity in field frame `frame` (explicit, from 0; the last by default) at `nodes` (or at the nodes nearest to points: "at": [[x, y, z], ...], lowest label on a tie, each entry then giving its `xyz` and `distance`) and, with `elements` (explicit), each element's stress, von Mises stress, strain, equivalent plastic strain, damage, temperature and whether it has eroded; a coupled reference point's label gives its six displacements (translations, rotations) and reactions (forces, moments). Fluid steps: {"step": "Flow", "points": [[x, y, z]], "frame": 10 (default the last)} gives velocity and pressure in the cells at the points; {"step": "Flow", "forces": ["x_min", "F2:top", "Body1/F2:top"]} gives those walls' force histories"#,
|
||||
form: Some(super::forms::SOLVE_PROBE),
|
||||
kind: CommandKind::Model,
|
||||
run: probe,
|
||||
};
|
||||
@@ -150,6 +168,7 @@ fn run_all(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Procedure::Static {} | Procedure::CoupledTemperatureDisplacement {} => run_static,
|
||||
Procedure::HeatTransfer { .. } => run_heat,
|
||||
Procedure::Frequency { .. } => run_frequency,
|
||||
Procedure::Buckle { .. } => run_buckle,
|
||||
Procedure::ExplicitDynamic(_) => run_explicit,
|
||||
Procedure::Fluid { .. } => run_fluid,
|
||||
Procedure::NonlinearStatic(_) => run_nonlinear,
|
||||
@@ -218,6 +237,8 @@ fn run_nonlinear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"increments": history.map(|h| &h.increments),
|
||||
"iterations": history.map(|h| h.iterations),
|
||||
"frames": history.map(|h| h.load_factors()),
|
||||
"load_factor": history.and_then(|h| h.frames.last()).map(|f| f.load_factor),
|
||||
"critical_points": history.map(|h| &h.critical_points),
|
||||
"max_displacement": largest(r.nodes.iter().zip(&r.displacement).map(|(l, u)| (*l, crate::results::magnitude(*u)))),
|
||||
"max_von_mises": largest(r.nodes.iter().zip(&r.von_mises).map(|(l, v)| (*l, *v))),
|
||||
"max_plastic_strain": largest(r.elements.iter().flat_map(|e| e.plastic_strain.iter().map(|v| (e.label, *v)))),
|
||||
@@ -283,12 +304,31 @@ fn run_frequency(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(summary)
|
||||
}
|
||||
|
||||
fn run_buckle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let limits = limits(p)?;
|
||||
let step = opt::<String>(p, "step")?;
|
||||
let model = &s.model;
|
||||
let r = parallel::with_threads(threads(s, p)?, || solve_buckle(model, step.as_deref(), &limits))?;
|
||||
let summary = json!({
|
||||
"step": r.step,
|
||||
"dofs": r.stats.dofs,
|
||||
"equations": r.stats.equations,
|
||||
"lanczos_vectors": r.stats.lanczos_vectors,
|
||||
"modes": r.modes.iter().enumerate().map(|(i, m)| json!({"mode": i + 1, "load_factor": m.eigenvalue})).collect::<Vec<_>>(),
|
||||
"buckling": r.buckling,
|
||||
"warnings": r.warnings,
|
||||
});
|
||||
s.store_result(StepResult::Implicit(ImplicitResult::Frequency(r)));
|
||||
Ok(summary)
|
||||
}
|
||||
|
||||
fn run_explicit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
use fieldcraft_explicit::Limits as ExplicitLimits;
|
||||
let limits = ExplicitLimits {
|
||||
max_dofs: cap(p, "max_dofs", ExplicitLimits::MAX_DOFS)?,
|
||||
max_increments: cap(p, "max_increments", ExplicitLimits::MAX_INCREMENTS)?,
|
||||
max_output_values: cap(p, "max_output_values", ExplicitLimits::MAX_OUTPUT_VALUES)?,
|
||||
max_contact_faces: cap(p, "max_contact_faces", ExplicitLimits::MAX_CONTACT_FACES)?,
|
||||
};
|
||||
let step = opt::<String>(p, "step")?;
|
||||
let model = &s.model;
|
||||
@@ -314,6 +354,8 @@ fn explicit_summary(r: &ExplicitResult) -> Value {
|
||||
"frames": r.frames.len(),
|
||||
"history_samples": r.history.time.len(),
|
||||
"eroded": r.eroded,
|
||||
"contacts": r.contacts,
|
||||
"mass_scaling": r.mass_scaling,
|
||||
"warnings": r.warnings,
|
||||
})
|
||||
}
|
||||
@@ -355,6 +397,8 @@ fn history(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"energies": pick(&|i| json!(h.energies.get(i))),
|
||||
"momentum": pick(&|i| json!(h.momentum.get(i))),
|
||||
"constraint_force": pick(&|i| json!(h.constraint_force.get(i))),
|
||||
"contact_force": pick(&|i| json!(h.contact_force.get(i))),
|
||||
"contacts": r.contacts.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(),
|
||||
"nodes": nodes,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -11,12 +11,13 @@ pub const TAG: CommandSpec = CommandSpec {
|
||||
id: "mesh.tag",
|
||||
label: "Tag Mesh with Geometry",
|
||||
params: r#"{"geometry": {"body": "Body1"} | {"body", "face"} | {"body", "edge"} | {"body", "vertex"}, "elements": [labels] (filling a body, face or edge), "faces": [{"element": 1, "face": 3}] (on a face), "edges": [{"element": 1, "edge": 2}] (on an edge), "nodes": [labels] (on a vertex)} — records where the mesh lies on the geometry, so sets named by geometry resolve"#,
|
||||
form: Some(super::forms::TAG),
|
||||
kind: CommandKind::Model,
|
||||
run: tag,
|
||||
};
|
||||
|
||||
pub const TAG_CLEAR: CommandSpec =
|
||||
CommandSpec { id: "mesh.tag.clear", label: "Clear Geometry Tags", params: "{}", kind: CommandKind::Model, run: tag_clear };
|
||||
CommandSpec { id: "mesh.tag.clear", label: "Clear Geometry Tags", params: "{}", form: Some(&[]), kind: CommandKind::Model, run: tag_clear };
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
|
||||
@@ -20,6 +20,7 @@ pub use cmd::analytic_surfaces;
|
||||
pub mod history;
|
||||
pub mod results;
|
||||
pub mod sample;
|
||||
pub mod schema;
|
||||
pub mod view;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
@@ -108,6 +109,9 @@ pub struct CommandSpec {
|
||||
pub label: &'static str,
|
||||
/// The JSON parameters, documented for scripts, `fieldcraft-cli commands` and agents.
|
||||
pub params: &'static str,
|
||||
/// The parameters field by field, for forms and JSON Schema; `None` when not described yet
|
||||
/// (the form is then the JSON text alone).
|
||||
pub form: Option<&'static [schema::Field]>,
|
||||
pub kind: CommandKind,
|
||||
pub run: fn(&mut Session, &Value) -> Result<Value>,
|
||||
}
|
||||
@@ -117,6 +121,19 @@ pub fn commands() -> &'static [CommandSpec] {
|
||||
cmd::ALL
|
||||
}
|
||||
|
||||
impl CommandSpec {
|
||||
/// The command as JSON for listings (`fieldcraft-cli commands --json`, the control channel's
|
||||
/// `engine.commands`, MCP `list_commands`): id, label, the parameter doc and, when described,
|
||||
/// the parameters as JSON Schema.
|
||||
pub fn listing(&self) -> Value {
|
||||
let mut v = serde_json::json!({"id": self.id, "label": self.label, "params": self.params});
|
||||
if let Some(form) = self.form {
|
||||
v["schema"] = schema::json_schema(form);
|
||||
}
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
pub fn find_command(id: &str) -> Option<&'static CommandSpec> {
|
||||
commands().iter().find(|c| c.id == id)
|
||||
}
|
||||
@@ -477,6 +494,18 @@ mod tests {
|
||||
json!({"name": "A", "procedure": {"type": "heat_transfer", "transient": {"end_time": -1, "increment": 0}}}),
|
||||
json!({"name": "A", "procedure": {"type": "coupled_temperature_displacement", "extra": 1}}),
|
||||
json!({"step": "Heat", "frame": u64::MAX, "nodes": [1]}),
|
||||
// Contact.
|
||||
json!({"name": "C", "main": 7, "secondary": null}),
|
||||
json!({"name": "C", "main": "end", "secondary": "root", "friction": {"static": 1e308, "kinetic": -1, "decay": -1e308}}),
|
||||
json!({"name": "C", "main": "end", "secondary": "end"}),
|
||||
json!({"name": "C", "main": "x".repeat(10_000), "secondary": "root", "penalty_scale": 1e308}),
|
||||
json!({"name": "C", "surface": "root", "penalty_scale": 0, "initial_penetration": "ignore"}),
|
||||
json!({"name": "C", "surface": 3}),
|
||||
json!({"name": "C", "surfaces": {"type": "pair", "main": "end"}}),
|
||||
json!({"name": "C", "surfaces": {"type": "general", "surface": "nope"}, "friction": "sticky"}),
|
||||
json!({"tolerance": 1e300, "create": true, "friction": {"static": 0.1}}),
|
||||
json!({"tolerance": -0.0, "create": true}),
|
||||
json!({"tolerance": 1e-300, "create": 1}),
|
||||
json!({"geometry": {"body": "Bar"}, "elements": [1, 99], "faces": [{"element": 1, "face": 200}]}),
|
||||
json!({"geometry": {"body": "Bar", "vertex": "v"}, "nodes": [1], "edges": [{"element": 1, "edge": 0}]}),
|
||||
];
|
||||
|
||||
@@ -0,0 +1,733 @@
|
||||
//! Typed parameter schemas: what a command's JSON parameters are, field by field.
|
||||
//!
|
||||
//! A command's [`CommandSpec::form`](crate::CommandSpec::form) lists its [`Field`]s: name, kind,
|
||||
//! default, whether it is required, its unit dimension, its choices, the model collection it
|
||||
//! names, nested groups and one-of variants. The schema describes the JSON the command already
|
||||
//! takes; it never changes it. The UI draws its command forms from it, `fieldcraft-cli commands
|
||||
//! --json` and the MCP `list_commands` tool give it as JSON Schema ([`json_schema`]).
|
||||
//!
|
||||
//! The schema is descriptive: the command's `run` stays the judge of its parameters. What the
|
||||
//! schema cannot express (a mass given per direction, a table of load-path points) stays reachable
|
||||
//! through the form's JSON view.
|
||||
|
||||
use fieldcraft_model::UnitSystem;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// Rows a list field holds at most in a form.
|
||||
pub const MAX_ROWS: usize = 1000;
|
||||
/// Names a reference list offers at most.
|
||||
pub const MAX_NAMES: usize = 10_000;
|
||||
|
||||
/// One parameter of a command.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Field {
|
||||
/// Its JSON key. Empty for [`Kind::Variants`] whose tag and fields sit in the parent object
|
||||
/// (an internally tagged definition such as a load: `{"name", "type": "force", "vector"}`).
|
||||
pub key: &'static str,
|
||||
pub label: &'static str,
|
||||
pub kind: Kind,
|
||||
pub required: bool,
|
||||
/// The value the form starts with, as JSON text; `None` leaves the field empty.
|
||||
pub default: Option<&'static str>,
|
||||
/// What an empty field means ("every body", "1/25 of the diagonal"), or a short note.
|
||||
pub hint: &'static str,
|
||||
}
|
||||
|
||||
/// What a field holds.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum Kind {
|
||||
/// A number in the model's unit system (or a fixed unit such as degrees).
|
||||
Number {
|
||||
dim: Dim,
|
||||
min: Option<f64>,
|
||||
max: Option<f64>,
|
||||
},
|
||||
/// A whole number in `min..=max`.
|
||||
Integer {
|
||||
min: i64,
|
||||
max: i64,
|
||||
},
|
||||
Text,
|
||||
/// A file path; `save` when the command writes it.
|
||||
Path {
|
||||
save: bool,
|
||||
},
|
||||
Bool,
|
||||
/// One of these strings: (value, label).
|
||||
Choice(&'static [(&'static str, &'static str)]),
|
||||
/// A fixed-length list of numbers, one per label (`["x", "y", "z"]`); `nullable` entries may
|
||||
/// be null (a free degree of freedom).
|
||||
Vector {
|
||||
dim: Dim,
|
||||
labels: &'static [&'static str],
|
||||
nullable: bool,
|
||||
},
|
||||
/// The name of an item of the model or the open design.
|
||||
Ref(Collection),
|
||||
/// A list of such names.
|
||||
RefList(Collection),
|
||||
/// A nested object.
|
||||
Group(&'static [Field]),
|
||||
/// A nested object (or, with an empty key, the parent object) tagged by `tag`: the tag's value
|
||||
/// picks the variant whose fields apply.
|
||||
Variants {
|
||||
tag: &'static str,
|
||||
variants: &'static [Variant],
|
||||
},
|
||||
/// An object with exactly one of these keys (`{"set": …}` or `{"reference_point": …}`), or a
|
||||
/// bare string for a [`Kind::Unit`] option.
|
||||
Either(&'static [Field]),
|
||||
/// An option of [`Kind::Either`] written as its key alone (`"line"`).
|
||||
Unit,
|
||||
/// A list of objects with these fields, at most `max` long.
|
||||
Rows {
|
||||
fields: &'static [Field],
|
||||
max: usize,
|
||||
},
|
||||
/// Any JSON: what the schema does not describe.
|
||||
Json,
|
||||
}
|
||||
|
||||
/// One variant of [`Kind::Variants`].
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Variant {
|
||||
pub tag: &'static str,
|
||||
pub label: &'static str,
|
||||
pub fields: &'static [Field],
|
||||
}
|
||||
|
||||
/// Where a reference field's names come from.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Collection {
|
||||
Set,
|
||||
Material,
|
||||
Section,
|
||||
ReferencePoint,
|
||||
Coupling,
|
||||
Contact,
|
||||
Mass,
|
||||
Spring,
|
||||
BoundaryCondition,
|
||||
Load,
|
||||
FluidDomain,
|
||||
Step,
|
||||
/// A solved step.
|
||||
SolvedStep,
|
||||
/// A body of the open design.
|
||||
Body,
|
||||
}
|
||||
|
||||
impl Collection {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Collection::Set => "set",
|
||||
Collection::Material => "material",
|
||||
Collection::Section => "section",
|
||||
Collection::ReferencePoint => "reference point",
|
||||
Collection::Coupling => "coupling",
|
||||
Collection::Contact => "contact",
|
||||
Collection::Mass => "point mass",
|
||||
Collection::Spring => "spring",
|
||||
Collection::BoundaryCondition => "boundary condition",
|
||||
Collection::Load => "load",
|
||||
Collection::FluidDomain => "fluid domain",
|
||||
Collection::Step => "step",
|
||||
Collection::SolvedStep => "solved step",
|
||||
Collection::Body => "body",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The names a reference field may take, in order (at most [`MAX_NAMES`]).
|
||||
pub fn names(&self, c: Collection) -> Vec<String> {
|
||||
let m = &self.model;
|
||||
let names: Box<dyn Iterator<Item = &str>> = match c {
|
||||
Collection::Set => Box::new(m.sets().keys().map(String::as_str)),
|
||||
Collection::Material => Box::new(m.materials().keys().map(String::as_str)),
|
||||
Collection::Section => Box::new(m.sections().keys().map(String::as_str)),
|
||||
Collection::ReferencePoint => Box::new(m.reference_points().keys().map(String::as_str)),
|
||||
Collection::Coupling => Box::new(m.couplings().keys().map(String::as_str)),
|
||||
Collection::Contact => Box::new(m.contacts().keys().map(String::as_str)),
|
||||
Collection::Mass => Box::new(m.masses().keys().map(String::as_str)),
|
||||
Collection::Spring => Box::new(m.springs().keys().map(String::as_str)),
|
||||
Collection::BoundaryCondition => Box::new(m.boundary_conditions().keys().map(String::as_str)),
|
||||
Collection::Load => Box::new(m.loads().keys().map(String::as_str)),
|
||||
Collection::FluidDomain => Box::new(m.fluid_domains().keys().map(String::as_str)),
|
||||
Collection::Step => Box::new(m.steps().iter().map(|s| s.name.as_str())),
|
||||
Collection::SolvedStep => Box::new(self.solved_steps()),
|
||||
Collection::Body => Box::new(self.design.iter().flat_map(|d| d.bodies.iter().map(|b| b.name.as_str()))),
|
||||
};
|
||||
names.take(MAX_NAMES).map(str::to_string).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A physical dimension: its unit follows the model's unit system.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Dim {
|
||||
/// No unit (a ratio, a count, a factor).
|
||||
None,
|
||||
Length,
|
||||
Area,
|
||||
Stress,
|
||||
Density,
|
||||
Force,
|
||||
Moment,
|
||||
Mass,
|
||||
Inertia,
|
||||
Time,
|
||||
Velocity,
|
||||
Acceleration,
|
||||
AngularVelocity,
|
||||
Stiffness,
|
||||
Damping,
|
||||
Viscosity,
|
||||
ForcePerVolume,
|
||||
Power,
|
||||
HeatFlux,
|
||||
FilmCoefficient,
|
||||
Conductivity,
|
||||
SpecificHeat,
|
||||
Expansion,
|
||||
Temperature,
|
||||
/// Always millimetres (geometry from SolidCraft).
|
||||
Millimetre,
|
||||
Degree,
|
||||
Hertz,
|
||||
}
|
||||
|
||||
impl Dim {
|
||||
/// Its unit in `system`, or `None` (no unit, or the system is unspecified).
|
||||
pub fn unit(self, system: UnitSystem) -> Option<String> {
|
||||
let fixed = match self {
|
||||
Dim::Millimetre => Some("mm"),
|
||||
Dim::Degree => Some("°"),
|
||||
Dim::Hertz => Some("Hz"),
|
||||
Dim::Expansion => Some("1/K"),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(f) = fixed {
|
||||
return Some(f.into());
|
||||
}
|
||||
let (l, m, t, f, s) = match system {
|
||||
UnitSystem::Unspecified => return None,
|
||||
UnitSystem::MKgS => ("m", "kg", "s", "N", "Pa"),
|
||||
UnitSystem::MmTonneS => ("mm", "t", "s", "N", "MPa"),
|
||||
UnitSystem::MmKgMs => ("mm", "kg", "ms", "kN", "GPa"),
|
||||
UnitSystem::MmGMs => ("mm", "g", "ms", "N", "MPa"),
|
||||
UnitSystem::InLbfS => ("in", "lbf·s²/in", "s", "lbf", "psi"),
|
||||
};
|
||||
let inch = system == UnitSystem::InLbfS;
|
||||
Some(match self {
|
||||
Dim::Length => l.into(),
|
||||
Dim::Area => format!("{l}²"),
|
||||
Dim::Stress => s.into(),
|
||||
Dim::Density if inch => "lbf·s²/in⁴".into(),
|
||||
Dim::Density => format!("{m}/{l}³"),
|
||||
Dim::Force => f.into(),
|
||||
Dim::Moment => format!("{f}·{l}"),
|
||||
Dim::Mass => m.into(),
|
||||
Dim::Inertia if inch => "lbf·s²·in".into(),
|
||||
Dim::Inertia => format!("{m}·{l}²"),
|
||||
Dim::Time => t.into(),
|
||||
Dim::Velocity => format!("{l}/{t}"),
|
||||
Dim::Acceleration => format!("{l}/{t}²"),
|
||||
Dim::AngularVelocity => format!("rad/{t}"),
|
||||
Dim::Stiffness => format!("{f}/{l}"),
|
||||
Dim::Damping => format!("{f}·{t}/{l}"),
|
||||
Dim::Viscosity => format!("{s}·{t}"),
|
||||
Dim::ForcePerVolume => format!("{f}/{l}³"),
|
||||
Dim::Power => format!("{f}·{l}/{t}"),
|
||||
Dim::HeatFlux => format!("{f}/({l}·{t})"),
|
||||
Dim::FilmCoefficient => format!("{f}/({l}·{t}·K)"),
|
||||
Dim::Conductivity => format!("{f}/({t}·K)"),
|
||||
Dim::SpecificHeat => format!("{l}²/({t}²·K)"),
|
||||
Dim::None | Dim::Temperature | Dim::Millimetre | Dim::Degree | Dim::Hertz | Dim::Expansion => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Building fields (const, so schemas are static tables) ----
|
||||
|
||||
const fn field(key: &'static str, label: &'static str, kind: Kind) -> Field {
|
||||
Field { key, label, kind, required: false, default: None, hint: "" }
|
||||
}
|
||||
|
||||
impl Field {
|
||||
/// Required.
|
||||
pub const fn req(self) -> Field {
|
||||
Field { required: true, ..self }
|
||||
}
|
||||
/// Starts with this JSON value.
|
||||
pub const fn def(self, json: &'static str) -> Field {
|
||||
Field { default: Some(json), ..self }
|
||||
}
|
||||
/// What an empty field means.
|
||||
pub const fn hint(self, hint: &'static str) -> Field {
|
||||
Field { hint, ..self }
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn num(key: &'static str, label: &'static str, dim: Dim) -> Field {
|
||||
field(key, label, Kind::Number { dim, min: None, max: None })
|
||||
}
|
||||
pub const fn range(key: &'static str, label: &'static str, dim: Dim, min: f64, max: f64) -> Field {
|
||||
field(key, label, Kind::Number { dim, min: Some(min), max: Some(max) })
|
||||
}
|
||||
pub const fn positive(key: &'static str, label: &'static str, dim: Dim) -> Field {
|
||||
field(key, label, Kind::Number { dim, min: Some(0.0), max: None })
|
||||
}
|
||||
pub const fn int(key: &'static str, label: &'static str, min: i64, max: i64) -> Field {
|
||||
field(key, label, Kind::Integer { min, max })
|
||||
}
|
||||
pub const fn text(key: &'static str, label: &'static str) -> Field {
|
||||
field(key, label, Kind::Text)
|
||||
}
|
||||
pub const fn path(key: &'static str, label: &'static str, save: bool) -> Field {
|
||||
field(key, label, Kind::Path { save })
|
||||
}
|
||||
pub const fn flag(key: &'static str, label: &'static str) -> Field {
|
||||
field(key, label, Kind::Bool)
|
||||
}
|
||||
pub const fn choice(key: &'static str, label: &'static str, options: &'static [(&'static str, &'static str)]) -> Field {
|
||||
field(key, label, Kind::Choice(options))
|
||||
}
|
||||
pub const fn xyz(key: &'static str, label: &'static str, dim: Dim) -> Field {
|
||||
field(key, label, Kind::Vector { dim, labels: &["x", "y", "z"], nullable: false })
|
||||
}
|
||||
/// A vector whose entries may be null (left free).
|
||||
pub const fn free_vector(key: &'static str, label: &'static str, dim: Dim, labels: &'static [&'static str]) -> Field {
|
||||
field(key, label, Kind::Vector { dim, labels, nullable: true })
|
||||
}
|
||||
pub const fn vector(key: &'static str, label: &'static str, dim: Dim, labels: &'static [&'static str]) -> Field {
|
||||
field(key, label, Kind::Vector { dim, labels, nullable: false })
|
||||
}
|
||||
pub const fn reference(key: &'static str, label: &'static str, c: Collection) -> Field {
|
||||
field(key, label, Kind::Ref(c))
|
||||
}
|
||||
pub const fn references(key: &'static str, label: &'static str, c: Collection) -> Field {
|
||||
field(key, label, Kind::RefList(c))
|
||||
}
|
||||
pub const fn group(key: &'static str, label: &'static str, fields: &'static [Field]) -> Field {
|
||||
field(key, label, Kind::Group(fields))
|
||||
}
|
||||
pub const fn variants(key: &'static str, label: &'static str, variants: &'static [Variant]) -> Field {
|
||||
field(key, label, Kind::Variants { tag: "type", variants })
|
||||
}
|
||||
pub const fn either(key: &'static str, label: &'static str, options: &'static [Field]) -> Field {
|
||||
field(key, label, Kind::Either(options))
|
||||
}
|
||||
pub const fn unit(key: &'static str, label: &'static str) -> Field {
|
||||
field(key, label, Kind::Unit)
|
||||
}
|
||||
pub const fn rows(key: &'static str, label: &'static str, fields: &'static [Field]) -> Field {
|
||||
field(key, label, Kind::Rows { fields, max: MAX_ROWS })
|
||||
}
|
||||
pub const fn json(key: &'static str, label: &'static str) -> Field {
|
||||
field(key, label, Kind::Json)
|
||||
}
|
||||
pub const fn variant(tag: &'static str, label: &'static str, fields: &'static [Field]) -> Variant {
|
||||
Variant { tag, label, fields }
|
||||
}
|
||||
|
||||
/// The `name` of a new or edited definition.
|
||||
pub const NAME: Field = text("name", "Name").req();
|
||||
|
||||
impl Kind {
|
||||
/// The variant of `tag`, for [`Kind::Variants`].
|
||||
pub fn variant(&self, tag: &str) -> Option<&'static Variant> {
|
||||
match self {
|
||||
Kind::Variants { variants, .. } => variants.iter().find(|v| v.tag == tag),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Prefilling, switching variants, checking ----
|
||||
|
||||
/// `params` with the defaults of the fields it leaves out filled in (required groups created,
|
||||
/// the active variant's defaults too). What it already has is kept.
|
||||
pub fn prefill(fields: &[Field], params: &Value) -> Value {
|
||||
let mut obj = params.as_object().cloned().unwrap_or_default();
|
||||
fill(fields, &mut obj, 0);
|
||||
Value::Object(obj)
|
||||
}
|
||||
|
||||
/// Nesting deeper than this is not followed (schemas are shallow; this bounds the recursion).
|
||||
pub const MAX_DEPTH: usize = 8;
|
||||
|
||||
fn fill(fields: &[Field], obj: &mut Map<String, Value>, depth: usize) {
|
||||
if depth > MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
for f in fields {
|
||||
match f.kind {
|
||||
Kind::Variants { tag, .. } if f.key.is_empty() => {
|
||||
if !obj.contains_key(tag)
|
||||
&& let Some(d) = parse_default(f)
|
||||
{
|
||||
obj.insert(tag.into(), d);
|
||||
}
|
||||
if let Some(v) = obj.get(tag).and_then(Value::as_str).and_then(|t| f.kind.variant(t)) {
|
||||
fill(v.fields, obj, depth + 1);
|
||||
}
|
||||
}
|
||||
Kind::Group(_) | Kind::Variants { .. } => {
|
||||
if !obj.contains_key(f.key) {
|
||||
match parse_default(f) {
|
||||
Some(d) => {
|
||||
obj.insert(f.key.into(), d);
|
||||
}
|
||||
None if f.required => {
|
||||
obj.insert(f.key.into(), Value::Object(Map::new()));
|
||||
}
|
||||
None => continue,
|
||||
}
|
||||
}
|
||||
if let Some(Value::Object(child)) = obj.get_mut(f.key) {
|
||||
fill_nested(f, child, depth + 1);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if !obj.contains_key(f.key)
|
||||
&& let Some(d) = parse_default(f)
|
||||
{
|
||||
obj.insert(f.key.into(), d);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fill a group's or a (keyed) variant field's own object.
|
||||
fn fill_nested(f: &Field, child: &mut Map<String, Value>, depth: usize) {
|
||||
match f.kind {
|
||||
Kind::Group(fields) => fill(fields, child, depth),
|
||||
Kind::Variants { tag, variants } => {
|
||||
if !child.contains_key(tag)
|
||||
&& let Some(first) = variants.first()
|
||||
{
|
||||
child.insert(tag.into(), json!(first.tag));
|
||||
}
|
||||
if let Some(v) = child.get(tag).and_then(Value::as_str).and_then(|t| f.kind.variant(t)) {
|
||||
fill(v.fields, child, depth);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_default(f: &Field) -> Option<Value> {
|
||||
f.default.and_then(|d| serde_json::from_str(d).ok())
|
||||
}
|
||||
|
||||
/// The object for variant `tag` of variants field `f`, from `old`: the tag, the values of `old`
|
||||
/// the new variant (or `common`, the fields beside the variants) also has, and the new variant's
|
||||
/// defaults.
|
||||
pub fn switch_variant(f: &Field, common: &[Field], old: &Map<String, Value>, tag: &str) -> Map<String, Value> {
|
||||
let Kind::Variants { tag: tag_key, .. } = f.kind else { return old.clone() };
|
||||
let Some(v) = f.kind.variant(tag) else { return old.clone() };
|
||||
let keep = |k: &str| v.fields.iter().chain(common).any(|g| g.key == k && g.key != tag_key);
|
||||
let mut out: Map<String, Value> = old.iter().filter(|(k, _)| keep(k)).map(|(k, v)| (k.clone(), v.clone())).collect();
|
||||
out.insert(tag_key.into(), json!(tag));
|
||||
fill(v.fields, &mut out, 0);
|
||||
out
|
||||
}
|
||||
|
||||
/// A problem with a field's value, for the form to show beside it.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Problem {
|
||||
/// The JSON path of the field (`elastic/young`).
|
||||
pub path: String,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// What is missing or out of range in `params`: required fields left out, numbers outside
|
||||
/// their range, values of the wrong kind. An empty list does not promise the command accepts
|
||||
/// them (it checks more); a problem means it would not.
|
||||
pub fn problems(fields: &[Field], params: &Value) -> Vec<Problem> {
|
||||
match params.as_object() {
|
||||
Some(obj) => object_problems(fields, obj),
|
||||
None => vec![Problem { path: String::new(), message: "the parameters must be a JSON object".into() }],
|
||||
}
|
||||
}
|
||||
|
||||
/// [`problems`] of an object's fields.
|
||||
pub fn object_problems(fields: &[Field], obj: &Map<String, Value>) -> Vec<Problem> {
|
||||
let mut out = Vec::new();
|
||||
check(fields, obj, "", &mut out, 0);
|
||||
out
|
||||
}
|
||||
|
||||
/// The path of field `key` inside `prefix` (`elastic/young`).
|
||||
pub fn join(prefix: &str, key: &str) -> String {
|
||||
if prefix.is_empty() {
|
||||
key.to_string()
|
||||
} else if key.is_empty() {
|
||||
prefix.to_string()
|
||||
} else {
|
||||
format!("{prefix}/{key}")
|
||||
}
|
||||
}
|
||||
|
||||
fn check(fields: &[Field], obj: &Map<String, Value>, prefix: &str, out: &mut Vec<Problem>, depth: usize) {
|
||||
if depth > MAX_DEPTH || out.len() > MAX_ROWS {
|
||||
return;
|
||||
}
|
||||
for f in fields {
|
||||
if let Kind::Variants { tag, .. } = f.kind
|
||||
&& f.key.is_empty()
|
||||
{
|
||||
match obj.get(tag).and_then(Value::as_str) {
|
||||
Some(t) => match f.kind.variant(t) {
|
||||
Some(v) => check(v.fields, obj, prefix, out, depth + 1),
|
||||
None => out.push(Problem { path: join(prefix, tag), message: format!("`{t}` is not a {}", f.label.to_lowercase()) }),
|
||||
},
|
||||
None if f.required => out.push(Problem { path: join(prefix, tag), message: "required".into() }),
|
||||
None => {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let path = join(prefix, f.key);
|
||||
match obj.get(f.key) {
|
||||
None | Some(Value::Null) if f.required => out.push(Problem { path, message: "required".into() }),
|
||||
None | Some(Value::Null) => {}
|
||||
Some(v) => {
|
||||
if let Some(message) = value_problem(f, v, &path, out, depth) {
|
||||
out.push(Problem { path, message });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What is wrong with `v` as the value of `f`; nested problems go to `out`.
|
||||
fn value_problem(f: &Field, v: &Value, path: &str, out: &mut Vec<Problem>, depth: usize) -> Option<String> {
|
||||
match f.kind {
|
||||
Kind::Number { min, max, .. } => match (v.as_f64().filter(|x| x.is_finite()), min, max) {
|
||||
(None, ..) => Some("a number".into()),
|
||||
(Some(x), Some(lo), _) if x < lo => Some(format!("at least {lo}")),
|
||||
(Some(x), _, Some(hi)) if x > hi => Some(format!("at most {hi}")),
|
||||
_ => None,
|
||||
},
|
||||
Kind::Integer { min, max } => match v.as_i64() {
|
||||
Some(x) if (min..=max).contains(&x) => None,
|
||||
_ => Some(format!("a whole number in {min}..={max}")),
|
||||
},
|
||||
Kind::Text | Kind::Path { .. } | Kind::Ref(_) => match v.as_str() {
|
||||
Some(s) if f.required && s.trim().is_empty() => Some("required".into()),
|
||||
Some(_) => None,
|
||||
None => Some("text".into()),
|
||||
},
|
||||
Kind::Bool => (!v.is_boolean()).then(|| "true or false".into()),
|
||||
Kind::Choice(options) => match v.as_str() {
|
||||
Some(s) if options.iter().any(|(o, _)| *o == s) => None,
|
||||
_ => Some(format!("one of {}", options.iter().map(|(o, _)| *o).collect::<Vec<_>>().join(", "))),
|
||||
},
|
||||
Kind::Vector { labels, nullable, .. } => match v.as_array() {
|
||||
Some(a) if a.len() == labels.len() && a.iter().all(|x| x.as_f64().is_some_and(f64::is_finite) || (nullable && x.is_null())) => None,
|
||||
_ => Some(format!("{} numbers", labels.len())),
|
||||
},
|
||||
Kind::RefList(_) => (!v.as_array().is_some_and(|a| a.iter().all(Value::is_string))).then(|| "a list of names".into()),
|
||||
Kind::Group(fields) => match v.as_object() {
|
||||
Some(o) => {
|
||||
check(fields, o, path, out, depth + 1);
|
||||
None
|
||||
}
|
||||
None => Some("an object".into()),
|
||||
},
|
||||
Kind::Variants { tag, .. } => match v.as_object() {
|
||||
Some(o) => match o.get(tag).and_then(Value::as_str).and_then(|t| f.kind.variant(t)) {
|
||||
Some(var) => {
|
||||
check(var.fields, o, path, out, depth + 1);
|
||||
None
|
||||
}
|
||||
None => Some(format!("needs a known `{tag}`")),
|
||||
},
|
||||
None => Some("an object".into()),
|
||||
},
|
||||
Kind::Either(options) => {
|
||||
let ok = match v {
|
||||
Value::String(s) => options.iter().any(|o| o.key == s && matches!(o.kind, Kind::Unit)),
|
||||
Value::Object(o) if o.len() == 1 => o.iter().all(|(k, inner)| {
|
||||
options.iter().find(|opt| opt.key == k).is_some_and(|opt| value_problem(opt, inner, path, out, depth + 1).is_none())
|
||||
}),
|
||||
_ => false,
|
||||
};
|
||||
(!ok).then(|| format!("one of {}", options.iter().map(|o| o.key).collect::<Vec<_>>().join(", ")))
|
||||
}
|
||||
Kind::Unit | Kind::Json => None,
|
||||
Kind::Rows { fields, max } => match v.as_array() {
|
||||
Some(a) if a.len() <= max => {
|
||||
for (i, row) in a.iter().enumerate() {
|
||||
match row.as_object() {
|
||||
Some(o) => check(fields, o, &format!("{path}/{i}"), out, depth + 1),
|
||||
None => out.push(Problem { path: format!("{path}/{i}"), message: "an object".into() }),
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
_ => Some(format!("a list of at most {max} rows")),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ---- JSON Schema ----
|
||||
|
||||
/// The fields as a JSON Schema (draft 2020-12) object schema, units and hints in descriptions.
|
||||
pub fn json_schema(fields: &[Field]) -> Value {
|
||||
object_schema(fields, 0)
|
||||
}
|
||||
|
||||
fn object_schema(fields: &[Field], depth: usize) -> Value {
|
||||
let mut properties = Map::new();
|
||||
let mut required = Vec::new();
|
||||
let mut one_of = None;
|
||||
for f in fields {
|
||||
if let Kind::Variants { tag, variants } = f.kind
|
||||
&& f.key.is_empty()
|
||||
{
|
||||
one_of = Some(variant_schemas(tag, variants, depth));
|
||||
if f.required {
|
||||
required.push(json!(tag));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
properties.insert(f.key.into(), field_schema(f, depth));
|
||||
if f.required {
|
||||
required.push(json!(f.key));
|
||||
}
|
||||
}
|
||||
let mut s = json!({"type": "object", "properties": properties});
|
||||
if !required.is_empty() {
|
||||
s["required"] = Value::Array(required);
|
||||
}
|
||||
if let Some(o) = one_of {
|
||||
s["oneOf"] = o;
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn variant_schemas(tag: &str, variants: &[Variant], depth: usize) -> Value {
|
||||
Value::Array(
|
||||
variants
|
||||
.iter()
|
||||
.map(|v| {
|
||||
let mut s = if depth > MAX_DEPTH { json!({"type": "object"}) } else { object_schema(v.fields, depth + 1) };
|
||||
s["properties"][tag] = json!({"const": v.tag, "title": v.label});
|
||||
let mut req = s.get("required").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
req.push(json!(tag));
|
||||
s["required"] = Value::Array(req);
|
||||
s
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn field_schema(f: &Field, depth: usize) -> Value {
|
||||
let mut s = match f.kind {
|
||||
Kind::Number { dim, min, max } => {
|
||||
let mut s = json!({"type": "number"});
|
||||
if let Some(lo) = min {
|
||||
s["minimum"] = json!(lo);
|
||||
}
|
||||
if let Some(hi) = max {
|
||||
s["maximum"] = json!(hi);
|
||||
}
|
||||
if dim != Dim::None {
|
||||
s["x-dimension"] = json!(format!("{dim:?}").to_lowercase());
|
||||
}
|
||||
s
|
||||
}
|
||||
Kind::Integer { min, max } => json!({"type": "integer", "minimum": min, "maximum": max}),
|
||||
Kind::Text | Kind::Path { .. } => json!({"type": "string"}),
|
||||
Kind::Bool => json!({"type": "boolean"}),
|
||||
Kind::Choice(options) => json!({"enum": options.iter().map(|(o, _)| *o).collect::<Vec<_>>()}),
|
||||
Kind::Vector { labels, nullable, .. } => {
|
||||
let item = if nullable { json!({"type": ["number", "null"]}) } else { json!({"type": "number"}) };
|
||||
json!({"type": "array", "items": item, "minItems": labels.len(), "maxItems": labels.len()})
|
||||
}
|
||||
Kind::Ref(c) => json!({"type": "string", "x-references": c.label()}),
|
||||
Kind::RefList(c) => json!({"type": "array", "items": {"type": "string", "x-references": c.label()}}),
|
||||
Kind::Group(fields) if depth <= MAX_DEPTH => object_schema(fields, depth + 1),
|
||||
Kind::Variants { tag, variants } if depth <= MAX_DEPTH => json!({"oneOf": variant_schemas(tag, variants, depth + 1)}),
|
||||
Kind::Either(options) if depth <= MAX_DEPTH => json!({"oneOf": options.iter().map(|o| match o.kind {
|
||||
Kind::Unit => json!({"const": o.key}),
|
||||
_ => json!({"type": "object", "properties": {o.key: field_schema(o, depth + 1)}, "required": [o.key], "additionalProperties": false}),
|
||||
}).collect::<Vec<_>>()}),
|
||||
Kind::Rows { fields, max } if depth <= MAX_DEPTH => json!({"type": "array", "items": object_schema(fields, depth + 1), "maxItems": max}),
|
||||
Kind::Unit => json!({"const": f.key}),
|
||||
_ => json!({}),
|
||||
};
|
||||
s["title"] = json!(f.label);
|
||||
if !f.hint.is_empty() {
|
||||
s["description"] = json!(f.hint);
|
||||
}
|
||||
if let Some(d) = parse_default(f) {
|
||||
s["default"] = d;
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn units_follow_the_system() {
|
||||
assert_eq!(Dim::Stress.unit(UnitSystem::MmTonneS).as_deref(), Some("MPa"));
|
||||
assert_eq!(Dim::Density.unit(UnitSystem::MmTonneS).as_deref(), Some("t/mm³"));
|
||||
assert_eq!(Dim::Moment.unit(UnitSystem::MKgS).as_deref(), Some("N·m"));
|
||||
assert_eq!(Dim::Density.unit(UnitSystem::InLbfS).as_deref(), Some("lbf·s²/in⁴"));
|
||||
assert_eq!(Dim::Stress.unit(UnitSystem::Unspecified), None);
|
||||
assert_eq!(Dim::Millimetre.unit(UnitSystem::Unspecified).as_deref(), Some("mm"));
|
||||
assert_eq!(Dim::None.unit(UnitSystem::MKgS), None);
|
||||
}
|
||||
|
||||
const LOADISH: &[Field] = &[
|
||||
NAME,
|
||||
variants(
|
||||
"",
|
||||
"Type",
|
||||
&[
|
||||
variant(
|
||||
"force",
|
||||
"Force",
|
||||
&[xyz("vector", "Vector", Dim::Force).req(), choice("distribution", "Spread", &[("total", "Total")]).def("\"total\"")],
|
||||
),
|
||||
variant("pressure", "Pressure", &[num("magnitude", "Magnitude", Dim::Stress).req(), reference("set", "Set", Collection::Set).req()]),
|
||||
],
|
||||
)
|
||||
.req()
|
||||
.def("\"force\""),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn prefill_switch_and_check() {
|
||||
let p = prefill(LOADISH, &json!({}));
|
||||
assert_eq!(p, json!({"type": "force", "distribution": "total"}));
|
||||
let problems = problems(LOADISH, &p);
|
||||
let paths: Vec<&str> = problems.iter().map(|p| p.path.as_str()).collect();
|
||||
assert_eq!(paths, ["name", "vector"]);
|
||||
let root = &LOADISH[1];
|
||||
let switched = switch_variant(
|
||||
root,
|
||||
LOADISH,
|
||||
&json!({"name": "a", "type": "force", "vector": [1, 2, 3]}).as_object().cloned().unwrap_or_default(),
|
||||
"pressure",
|
||||
);
|
||||
assert_eq!(Value::Object(switched), json!({"name": "a", "type": "pressure"}));
|
||||
assert!(super::problems(LOADISH, &json!({"name": "a", "type": "force", "vector": [1, "x", 3]})).iter().any(|p| p.path == "vector"));
|
||||
assert!(super::problems(LOADISH, &json!([1])).len() == 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_schema_has_variants_and_requirements() {
|
||||
let s = json_schema(LOADISH);
|
||||
assert_eq!(s["required"], json!(["name", "type"]));
|
||||
assert_eq!(s["oneOf"][1]["properties"]["type"]["const"], "pressure");
|
||||
assert_eq!(s["oneOf"][1]["required"], json!(["magnitude", "set", "type"]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,822 @@
|
||||
//! Penalty contact between element faces, with Coulomb friction.
|
||||
//!
|
||||
//! **Kinematics: segment to segment, both ways.** The normal contact pressure is integrated over
|
||||
//! the overlap of each pair of facing faces: a secondary face and a main face it faces are
|
||||
//! projected onto the secondary face's plane, each split into triangles, clipped against each
|
||||
//! other (Sutherland–Hodgman), and the overlap is integrated with a three-point rule per
|
||||
//! sub-triangle; at each point the gap g = (x_s − x_m) · n_m between the two faces (n_m the main
|
||||
//! face's outward normal) gives a penalty pressure p = ε (−g) where they overlap, which acts on
|
||||
//! the secondary face's nodes with weights N_i^s and on the main face's with −N_j^m. This is the
|
||||
//! segmentation and integration of mortar contact (M. A. Puso, T. A. Laursen, *A mortar
|
||||
//! segment-to-segment contact method for large deformation solid mechanics*, CMAME
|
||||
//! 193:601–629, 2004) with the penalty applied at the integration points (K. A. Fischer, P.
|
||||
//! Wriggers, *Frictionless 2D contact formulations for finite deformations based on the mortar
|
||||
//! method*, Comput. Mech. 36:226–244, 2005): for a uniform pressure across flat faces both sides
|
||||
//! receive exactly the consistent nodal forces ∫ p N dA, whatever the meshes, so the contact
|
||||
//! patch test is passed — node-to-segment contact fails it on non-matching meshes (R. L. Taylor,
|
||||
//! P. Papadopoulos, *On a patch test for contact problems in two dimensions*, 1991). Every
|
||||
//! contact runs both ways — a pair with each surface as the secondary in turn, single-surface
|
||||
//! (general and self) contact with every face against every other one that shares no node with
|
||||
//! it — at half the penalty each, so neither side is privileged and no corner of either surface
|
||||
//! sinks into the other. Two faces are in contact where they face each other (their normals more
|
||||
//! than [`FACING`] from parallel, which keeps the faces of one body that meet at an edge apart)
|
||||
//! and the gap is negative but no deeper than half the main face's element is thick (deeper, the
|
||||
//! surfaces have passed through each other). Faces of eroded elements leave the contact.
|
||||
//!
|
||||
//! **Search.** Every increment: each surface's faces go into a bucket grid with their boxes grown
|
||||
//! by their depth limit ([`fieldcraft_fem::contact::Grid`]: D. J. Benson, J. O. Hallquist, *A
|
||||
//! single surface contact algorithm for the post-buckling analysis of shell structures*, CMAME
|
||||
//! 78:141–163, 1990); each secondary face takes the main faces listed in the cells its box
|
||||
//! overlaps. The faces are integrated in parallel, each on its own, and their forces added face by
|
||||
//! face in a fixed order, so the result does not depend on how the faces are split among threads.
|
||||
//!
|
||||
//! **Penalty.** The penalty per area comes from the masses and the stable increment Δt:
|
||||
//! ε = s γ min_i (m_i / A_i) / Δt², with m_i the lumped mass of node i and A_i the area that
|
||||
//! bounds its contact stiffness, over the nodes of the contact. The stiffness entries of node i
|
||||
//! in direction d sum to at most 2 ε Σ_f a_f |n_f,d| Σ_d′ |n_f,d′| over its faces f (a_f its
|
||||
//! share of the face, a quarter of a quadrilateral or a third of a triangle, n_f the unit normal;
|
||||
//! its weights over a face sum to one on both sides), so A_i = κ_i max_d Σ_f a_f |n_f,d| with
|
||||
//! κ_i = max_f Σ_d |n_f,d| ∈ [1, √3]: the node's area on a flat surface in any orientation, and
|
||||
//! no more than the largest of its areas facing one way at an edge or a corner. By Gershgorin's
|
||||
//! theorem the contact then adds at most 2 s γ / Δt² to the square of any frequency (Weyl's
|
||||
//! inequality adds it to the elements'); with γ = [`GAMMA`] and the
|
||||
//! default increment scale (0.9 of the critical increment, ω Δt ≤ 1.8) the step stays under the
|
||||
//! stability limit ω Δt = 2 (1.8² + 2γ ≤ 4) and contact never shortens the increment. The penalty
|
||||
//! scale s ≤ 1 only softens it. The pressure stiffness this gives is about a fifth of the
|
||||
//! smallest element's M/h (M the constrained modulus): stiffer than the element-based penalty
|
||||
//! f K A²/V with its usual f = 0.1 (J. O. Hallquist, G. L. Goudreau, D. J. Benson, *Sliding
|
||||
//! interfaces with contact-impact in large-scale Lagrangian computations*, CMAME 51:107–137,
|
||||
//! 1985), and a uniform ε keeps a uniform pressure uniform.
|
||||
//!
|
||||
//! **Friction** at the secondary nodes by a regularised return map (P. Wriggers, *Computational
|
||||
//! Contact Mechanics*, 2nd ed., Springer 2006, §5.2 and §10.3; J. C. Simo, T. A. Laursen, *An
|
||||
//! augmented Lagrangian treatment of contact problems involving friction*, Comput. Struct.
|
||||
//! 42(1):97–116, 1992): a node's normal force f_n is its share of the pressure, its tangential
|
||||
//! force an elastic predictor, the previous force moved onto the current tangent plane less
|
||||
//! k_t times the tangential motion of the node relative to the closest point of the main face that
|
||||
//! pressed it most over the increment, t* = P t_n − k_t Δu_T with k_t the node's normal stiffness ε A_i / 2; if
|
||||
//! |t*| ≤ μ f_n the node sticks (t = t*), otherwise it slips and the force returns to the cone,
|
||||
//! t = μ f_n t*/|t*|, dissipating μ f_n (|t*| − μ f_n)/k_t. The reaction goes to the main face's
|
||||
//! nodes with −N_j. The coefficient μ = μ_k + (μ_s − μ_k) e^{−d γ̇} follows the slip rate
|
||||
//! γ̇ = |Δu_T|/Δt ([`fieldcraft_model::Friction`]). A node that leaves contact forgets its
|
||||
//! tangential force.
|
||||
//!
|
||||
//! **Energy.** The contact forces enter the equations of motion like external forces; their work
|
||||
//! (the penalty energy stored, plus what friction dissipates) is integrated with the trapezoidal
|
||||
//! rule like the internal forces' (see [`crate::integrate`]), and the friction dissipation is
|
||||
//! reported too.
|
||||
//!
|
||||
//! **Initial penetration.** Before the analysis each node of a secondary surface is projected
|
||||
//! onto the faces of the main surface ([`fieldcraft_fem::contact::closest_point`]); a node behind
|
||||
//! a face it lies over (within a fiftieth of the face's size), within the depth limit and with its
|
||||
//! own faces facing it, is moved onto it (strain-free: the reference coordinates change before the
|
||||
//! elements are built) or the analysis is refused with the node, the face and the depth, as the
|
||||
//! contact's `initial_penetration` says.
|
||||
//!
|
||||
//! **Erosion.** The faces of eroded elements leave the contact; the faces their removal exposes
|
||||
//! do not join it (eroding contact is later work).
|
||||
|
||||
use fieldcraft_fem::contact::{Aabb, Grid, Projection, bounds, closest_point};
|
||||
use fieldcraft_fem::frame::{cross, dot, norm, sub};
|
||||
use fieldcraft_model::{Contact, ContactSurfaces, ElementFace, ElementKind, Friction, InitialPenetration, Model, Resolved};
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::elements::{State, add_at};
|
||||
use crate::system::NODE_DOFS;
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// The penalty's share of the stability budget: ε = s γ min(m/A) / Δt² (see the module docs).
|
||||
pub const GAMMA: f64 = 0.3;
|
||||
|
||||
/// A node lies over a face when its lateral offset is at most this fraction of the face's size
|
||||
/// (the initial-penetration check).
|
||||
pub const EDGE_TOLERANCE: f64 = 0.02;
|
||||
|
||||
/// A point deeper than this fraction of the thickness of a face's element has passed through it.
|
||||
pub const DEPTH_FRACTION: f64 = 0.5;
|
||||
|
||||
/// Facing faces: the dot product of their unit normals is below minus this.
|
||||
pub const FACING: f64 = 0.1;
|
||||
|
||||
/// Faces per parallel task.
|
||||
const BLOCK: usize = 64;
|
||||
|
||||
/// The three-point rule on a triangle, exact for quadratics: barycentric points (of the second
|
||||
/// and third corners), weights summing to one.
|
||||
const TRIANGLE_RULE: [([f64; 2], f64); 3] =
|
||||
[([1.0 / 6.0, 1.0 / 6.0], 1.0 / 3.0), ([2.0 / 3.0, 1.0 / 6.0], 1.0 / 3.0), ([1.0 / 6.0, 2.0 / 3.0], 1.0 / 3.0)];
|
||||
|
||||
type Vec3 = [f64; 3];
|
||||
|
||||
/// A face of a contact surface.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Face {
|
||||
/// The corner nodes (system indices), in the face's order; the last unused on a triangle.
|
||||
pub nodes: [usize; 4],
|
||||
pub count: usize,
|
||||
/// The element's label, its position in [`crate::system::System::elements`] and the face
|
||||
/// number.
|
||||
pub element: u32,
|
||||
pub index: usize,
|
||||
pub face: u8,
|
||||
/// The nodes of the face's element (a node of it is never in contact with the face).
|
||||
pub owner: Vec<usize>,
|
||||
/// The penetration beyond which a point has passed through: [`DEPTH_FRACTION`] of the
|
||||
/// element's thickness under the face.
|
||||
pub depth: f64,
|
||||
}
|
||||
|
||||
impl Face {
|
||||
fn corners(&self) -> &[usize] {
|
||||
self.nodes.get(..self.count).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The faces and nodes of one surface.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Surface {
|
||||
pub faces: Vec<Face>,
|
||||
/// Its nodes, sorted (system indices).
|
||||
pub nodes: Vec<usize>,
|
||||
/// Per node (in `nodes` order), the faces that hold it.
|
||||
node_faces: Vec<Vec<usize>>,
|
||||
/// Per node, the area of the surface that bounds its contact stiffness (undeformed; see
|
||||
/// [`Interface::forces`]).
|
||||
area: Vec<f64>,
|
||||
}
|
||||
|
||||
/// A node's friction state in one pass.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
struct Slip {
|
||||
/// The tangential force on the node.
|
||||
force: Vec3,
|
||||
}
|
||||
|
||||
/// One pass: the faces of a surface (secondary) against the faces of a surface (main).
|
||||
#[derive(Debug, Clone)]
|
||||
struct Pass {
|
||||
secondary: usize,
|
||||
main: usize,
|
||||
/// Per node of the secondary surface.
|
||||
slip: Vec<Slip>,
|
||||
}
|
||||
|
||||
/// A contact as the solver runs it.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Interface {
|
||||
pub name: String,
|
||||
pub friction: Friction,
|
||||
pub scale: f64,
|
||||
pub surfaces: Vec<Surface>,
|
||||
passes: Vec<Pass>,
|
||||
/// Nodes moved onto the other surface before the analysis.
|
||||
pub adjusted: Vec<Adjustment>,
|
||||
/// min over the contact's nodes of mass / area, once the masses are known.
|
||||
mass_per_area: Option<f64>,
|
||||
}
|
||||
|
||||
/// A node moved onto a face before the analysis.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
|
||||
pub struct Adjustment {
|
||||
pub node: u32,
|
||||
pub element: u32,
|
||||
pub face: u8,
|
||||
/// How far it started inside.
|
||||
pub depth: f64,
|
||||
}
|
||||
|
||||
/// What one evaluation of the contact forces found, per contact.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct Evaluation {
|
||||
/// The normal force across the contact (the integrated pressure, both ways).
|
||||
pub normal_force: f64,
|
||||
/// The deepest penetration.
|
||||
pub penetration: f64,
|
||||
/// Integration points in contact.
|
||||
pub active: usize,
|
||||
/// Friction dissipated over the increment that led here.
|
||||
pub dissipation: f64,
|
||||
}
|
||||
|
||||
fn invalid(m: impl Into<String>) -> Error {
|
||||
Error::Invalid(m.into())
|
||||
}
|
||||
|
||||
/// The volume of a solid element of corners `x` (hex8 or tet4), for the thickness under a face.
|
||||
fn volume(kind: ElementKind, x: &[Vec3]) -> Option<f64> {
|
||||
match kind {
|
||||
ElementKind::Hex8 => <[Vec3; 8]>::try_from(x).ok().and_then(|a| fieldcraft_fem::uniform::Hex8::hex8(&a).ok()).map(|k| k.volume),
|
||||
ElementKind::Tet4 => <[Vec3; 4]>::try_from(x).ok().and_then(|a| fieldcraft_fem::uniform::Tet4::tet4(&a).ok()).map(|k| k.volume),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A face's area vector (its outward normal times its area, flat or bilinear).
|
||||
fn area_vector(x: &[Vec3]) -> Vec3 {
|
||||
match x {
|
||||
[a, b, c] => cross(sub(*b, *a), sub(*c, *a)).map(|v| 0.5 * v),
|
||||
[a, b, c, d] => cross(sub(*c, *a), sub(*d, *b)).map(|v| 0.5 * v),
|
||||
_ => [0.0; 3],
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest side of a face's bounding box.
|
||||
fn size(x: &[Vec3]) -> f64 {
|
||||
let b = bounds(x, 0.0);
|
||||
(0..3).map(|k| b[1][k] - b[0][k]).fold(0.0, f64::max)
|
||||
}
|
||||
|
||||
/// Where a node is: its rest position plus its displacement.
|
||||
fn position(xyz: &[Vec3], u: &[f64], node: usize) -> Vec3 {
|
||||
let x = xyz.get(node).copied().unwrap_or_default();
|
||||
[0, 1, 2].map(|k| x[k] + u.get(NODE_DOFS * node + k).copied().unwrap_or(0.0))
|
||||
}
|
||||
|
||||
/// A node's displacement increment.
|
||||
fn shift(du: &[f64], node: usize) -> Vec3 {
|
||||
[0, 1, 2].map(|k| du.get(NODE_DOFS * node + k).copied().unwrap_or(0.0))
|
||||
}
|
||||
|
||||
impl Surface {
|
||||
/// The surface of element faces `faces`, its nodes, their faces and areas. `node` and
|
||||
/// `element` give a label's index among the analysed nodes and elements.
|
||||
fn new(
|
||||
model: &Model,
|
||||
faces: &[ElementFace],
|
||||
xyz: &[Vec3],
|
||||
node: &impl Fn(u32) -> Option<usize>,
|
||||
element: &impl Fn(u32) -> Option<usize>,
|
||||
) -> Result<Surface> {
|
||||
let mut out = Surface::default();
|
||||
for f in faces {
|
||||
let at = |what: &str| invalid(format!("element {} face {}: {what}", f.element, f.face));
|
||||
let el = model.element(f.element).ok_or_else(|| at("the element is missing"))?;
|
||||
if !matches!(el.kind, ElementKind::Hex8 | ElementKind::Tet4) {
|
||||
return Err(Error::NotSupported(format!(
|
||||
"contact on the faces of {} elements (element {}); explicit contact acts on hex8 and tet4 faces",
|
||||
el.kind.name(),
|
||||
f.element
|
||||
)));
|
||||
}
|
||||
let labels = model.face_nodes(*f).ok_or_else(|| at("no such face"))?;
|
||||
let corners: Vec<usize> = labels.iter().map(|l| node(*l).ok_or_else(|| at("a node is not analysed"))).collect::<Result<_>>()?;
|
||||
let owner: Vec<usize> = el.nodes.iter().filter_map(|l| node(*l)).collect();
|
||||
let index = element(f.element).ok_or_else(|| at("the element is not analysed"))?;
|
||||
let x: Vec<Vec3> = corners.iter().map(|n| xyz.get(*n).copied().unwrap_or_default()).collect();
|
||||
let ex: Vec<Vec3> = owner.iter().map(|n| xyz.get(*n).copied().unwrap_or_default()).collect();
|
||||
let area = norm(area_vector(&x));
|
||||
// Thickness V/A; a face of no area or an element of no volume falls back on its size.
|
||||
let thickness = volume(el.kind, &ex).filter(|v| *v > 0.0 && area > 0.0).map_or(size(&x), |v| v / area);
|
||||
let mut nodes = [usize::MAX; 4];
|
||||
for (slot, n) in nodes.iter_mut().zip(&corners) {
|
||||
*slot = *n;
|
||||
}
|
||||
out.faces.push(Face { nodes, count: corners.len(), element: f.element, index, face: f.face, owner, depth: DEPTH_FRACTION * thickness });
|
||||
}
|
||||
out.nodes = out.faces.iter().flat_map(|f| f.corners().iter().copied()).collect();
|
||||
out.nodes.sort_unstable();
|
||||
out.nodes.dedup();
|
||||
out.node_faces = vec![Vec::new(); out.nodes.len()];
|
||||
// Per node and direction, Σ_f A_f |n_f,d| / count, and the largest Σ_d |n_d| of its faces.
|
||||
let mut directional = vec![[0.0; 3]; out.nodes.len()];
|
||||
let mut spread = vec![1.0f64; out.nodes.len()];
|
||||
for (i, f) in out.faces.iter().enumerate() {
|
||||
let x: Vec<Vec3> = f.corners().iter().map(|n| xyz.get(*n).copied().unwrap_or_default()).collect();
|
||||
let a = area_vector(&x);
|
||||
let l = norm(a);
|
||||
let share = a.map(|c| c.abs() / f.count as f64);
|
||||
let kappa = if l > 0.0 { a.iter().map(|c| c.abs()).sum::<f64>() / l } else { 1.0 };
|
||||
for n in f.corners() {
|
||||
if let Ok(k) = out.nodes.binary_search(n) {
|
||||
if let Some(list) = out.node_faces.get_mut(k) {
|
||||
list.push(i);
|
||||
}
|
||||
if let (Some(d), Some(s)) = (directional.get_mut(k), spread.get_mut(k)) {
|
||||
for c in 0..3 {
|
||||
d[c] += share[c];
|
||||
}
|
||||
*s = s.max(kappa);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out.area = directional.iter().zip(&spread).map(|(d, s)| s * d.iter().copied().fold(0.0, f64::max)).collect();
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The faces' corner positions at displacements `u`.
|
||||
fn positions(&self, xyz: &[Vec3], u: &[f64]) -> Vec<Vec<Vec3>> {
|
||||
self.faces.iter().map(|f| f.corners().iter().map(|n| position(xyz, u, *n)).collect()).collect()
|
||||
}
|
||||
|
||||
/// The nodes' outward normals (the sum of their faces' area vectors; not normalised).
|
||||
fn node_normals(&self, faces: &[Vec<Vec3>]) -> Vec<Vec3> {
|
||||
self.node_faces
|
||||
.iter()
|
||||
.map(|list| {
|
||||
let mut n = [0.0; 3];
|
||||
for a in list.iter().filter_map(|i| faces.get(*i)).map(|x| area_vector(x)) {
|
||||
for k in 0..3 {
|
||||
n[k] += a[k];
|
||||
}
|
||||
}
|
||||
n
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The faces' grid for the global search at positions `positions`.
|
||||
fn grid(surface: &Surface, positions: &[Vec<Vec3>]) -> Grid {
|
||||
let boxes: Vec<Aabb> = surface.faces.iter().zip(positions).map(|(f, x)| bounds(x, f.depth)).collect();
|
||||
Grid::new(&boxes, 4 * boxes.len() + 64)
|
||||
}
|
||||
|
||||
/// The face a node at `x` (index `node`, outward normal `normal`) starts inside, among the grid's
|
||||
/// candidates: over it, behind it within its depth limit, facing it; the nearest.
|
||||
fn inside(surface: &Surface, positions: &[Vec<Vec3>], grid: &Grid, node: usize, x: Vec3, normal: Vec3) -> Option<(usize, Projection)> {
|
||||
let mut best: Option<(usize, Projection)> = None;
|
||||
for &c in grid.candidates(x) {
|
||||
let c = c as usize;
|
||||
let (Some(face), Some(fx)) = (surface.faces.get(c), positions.get(c)) else { continue };
|
||||
if face.owner.contains(&node) {
|
||||
continue;
|
||||
}
|
||||
let Some(q) = closest_point(fx, x) else { continue };
|
||||
let over = q.lateral <= EDGE_TOLERANCE * size(fx);
|
||||
let n = norm(normal);
|
||||
let facing = n == 0.0 || dot(normal, q.normal) < -FACING * n;
|
||||
if q.gap < 0.0 && -q.gap <= face.depth && over && facing && best.is_none_or(|b| q.distance < b.1.distance) {
|
||||
best = Some((c, q));
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// A point of a plane in its own 2D coordinates.
|
||||
type Point = [f64; 2];
|
||||
|
||||
fn cross2(o: Point, a: Point, b: Point) -> f64 {
|
||||
(a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
|
||||
}
|
||||
|
||||
/// The signed area of a polygon (counter-clockwise positive).
|
||||
fn signed_area(p: &[Point]) -> f64 {
|
||||
let mut s = 0.0;
|
||||
for (i, a) in p.iter().enumerate() {
|
||||
let b = p.get((i + 1) % p.len()).copied().unwrap_or(*a);
|
||||
s += a[0] * b[1] - a[1] * b[0];
|
||||
}
|
||||
0.5 * s
|
||||
}
|
||||
|
||||
/// `subject` clipped by the convex counter-clockwise polygon `clip` (Sutherland–Hodgman).
|
||||
fn clip(subject: &[Point], clip: &[Point]) -> Vec<Point> {
|
||||
let mut out: Vec<Point> = subject.to_vec();
|
||||
for (i, a) in clip.iter().enumerate() {
|
||||
let Some(b) = clip.get((i + 1) % clip.len()).copied() else { break };
|
||||
let input = std::mem::take(&mut out);
|
||||
let side = |p: Point| cross2(*a, b, p);
|
||||
for (j, p) in input.iter().enumerate() {
|
||||
let Some(q) = input.get((j + 1) % input.len()).copied() else { break };
|
||||
let (sp, sq) = (side(*p), side(q));
|
||||
if sp >= 0.0 {
|
||||
out.push(*p);
|
||||
}
|
||||
if (sp >= 0.0) != (sq >= 0.0) {
|
||||
let t = sp / (sp - sq);
|
||||
out.push([p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1])]);
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The corners `t` of `points`, counter-clockwise.
|
||||
fn counter_clockwise(t: &[usize; 3], points: &[Point]) -> Vec<Point> {
|
||||
let mut out: Vec<Point> = t.iter().filter_map(|i| points.get(*i).copied()).collect();
|
||||
if signed_area(&out) < 0.0 {
|
||||
out.reverse();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The triangles a face splits into (corner positions in its order).
|
||||
fn triangles(count: usize) -> &'static [[usize; 3]] {
|
||||
if count == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] }
|
||||
}
|
||||
|
||||
/// What the integration needs of each main face, worked out once per increment.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct FaceInfo {
|
||||
/// Area vector and its length.
|
||||
area: Vec3,
|
||||
length: f64,
|
||||
/// The lateral offset beyond which a point is past the face's edge.
|
||||
edge: f64,
|
||||
alive: bool,
|
||||
}
|
||||
|
||||
fn face_info(surface: &Surface, positions: &[Vec<Vec3>], alive: &dyn Fn(&Face) -> bool) -> Vec<FaceInfo> {
|
||||
surface
|
||||
.faces
|
||||
.iter()
|
||||
.zip(positions)
|
||||
.map(|(f, x)| {
|
||||
let area = area_vector(x);
|
||||
FaceInfo { area, length: norm(area), edge: EDGE_TOLERANCE * size(x), alive: alive(f) }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// One secondary face against the main surface: its contributions to the nodal forces and to
|
||||
/// each secondary node's normal force.
|
||||
#[derive(Debug, Default)]
|
||||
struct FaceForces {
|
||||
/// (node, force) contributions, in order.
|
||||
forces: Vec<(usize, Vec3)>,
|
||||
/// (secondary node, normal force share, main face) of each integration point.
|
||||
normal: Vec<(usize, f64, usize)>,
|
||||
penetration: f64,
|
||||
points: usize,
|
||||
total: f64,
|
||||
}
|
||||
|
||||
/// The penalty pressure integrated over the overlaps of secondary face `f` (corners `fx`) with
|
||||
/// the main faces facing it, at penalty `eps` per area.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn integrate_face(
|
||||
f: &Face,
|
||||
fx: &[Vec3],
|
||||
alive: bool,
|
||||
main: &Surface,
|
||||
mx: &[Vec<Vec3>],
|
||||
info: &[FaceInfo],
|
||||
grid: &Grid,
|
||||
eps: f64,
|
||||
found: &mut Vec<u32>,
|
||||
) -> FaceForces {
|
||||
let mut out = FaceForces::default();
|
||||
if !alive {
|
||||
return out;
|
||||
}
|
||||
let area = area_vector(fx);
|
||||
let a = norm(area);
|
||||
if !(a > 0.0 && a.is_finite()) {
|
||||
return out;
|
||||
}
|
||||
let normal = area.map(|c| c / a);
|
||||
let n = fx.len() as f64;
|
||||
let center: Vec3 = [0, 1, 2].map(|k| fx.iter().map(|p| p[k]).sum::<f64>() / n);
|
||||
let Some(first) = fx.first().copied() else { return out };
|
||||
// A basis of the face's plane, (e1, e2, normal) right-handed.
|
||||
let r = sub(first, center);
|
||||
let r = sub(r, normal.map(|c| c * dot(r, normal)));
|
||||
let rl = norm(r);
|
||||
if !(rl > 0.0) {
|
||||
return out;
|
||||
}
|
||||
let e1 = r.map(|c| c / rl);
|
||||
let e2 = cross(normal, e1);
|
||||
let flat = |x: Vec3| -> Point {
|
||||
let d = sub(x, center);
|
||||
[dot(d, e1), dot(d, e2)]
|
||||
};
|
||||
let lift = |p: Point| -> Vec3 { [0, 1, 2].map(|k| center[k] + p[0] * e1[k] + p[1] * e2[k]) };
|
||||
let own: Vec<Point> = fx.iter().map(|x| flat(*x)).collect();
|
||||
let own_triangles: Vec<Vec<Point>> = triangles(f.count).iter().map(|t| counter_clockwise(t, &own)).collect();
|
||||
grid.candidates_in(&bounds(fx, 0.0), found);
|
||||
for &c in found.iter() {
|
||||
let c = c as usize;
|
||||
let (Some(m), Some(x), Some(mi)) = (main.faces.get(c), mx.get(c), info.get(c)) else { continue };
|
||||
if !mi.alive || m.corners().iter().any(|k| f.corners().contains(k)) {
|
||||
continue;
|
||||
}
|
||||
if !(mi.length > 0.0) || dot(mi.area, normal) >= -FACING * mi.length {
|
||||
continue;
|
||||
}
|
||||
let theirs: Vec<Point> = x.iter().map(|p| flat(*p)).collect();
|
||||
for s in &own_triangles {
|
||||
for tm in triangles(m.count) {
|
||||
let t = counter_clockwise(tm, &theirs);
|
||||
let overlap = clip(&t, s);
|
||||
if overlap.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
let Some(o) = overlap.first().copied() else { continue };
|
||||
for w in overlap.windows(2).skip(1) {
|
||||
let (p, q) = (w[0], w[1]);
|
||||
let tri_area = 0.5 * cross2(o, p, q);
|
||||
if !(tri_area > 0.0) {
|
||||
continue;
|
||||
}
|
||||
for (bary, weight) in TRIANGLE_RULE {
|
||||
let y = [0, 1].map(|k| o[k] + bary[0] * (p[k] - o[k]) + bary[1] * (q[k] - o[k]));
|
||||
let point = lift(y);
|
||||
let (Some(qs), Some(qm)) = (closest_point(fx, point), closest_point(x, point)) else { continue };
|
||||
let gap = dot(sub(qs.point, qm.point), qm.normal);
|
||||
// Over the main face (its foot not clamped to an edge), behind it, within
|
||||
// its depth.
|
||||
if !(gap < 0.0 && -gap <= m.depth && qm.lateral <= mi.edge) {
|
||||
continue;
|
||||
}
|
||||
let push = eps * (-gap) * weight * tri_area;
|
||||
if !push.is_finite() {
|
||||
continue;
|
||||
}
|
||||
let force = qm.normal.map(|k| push * k);
|
||||
for (node, w) in f.corners().iter().zip(qs.weights) {
|
||||
out.forces.push((*node, force.map(|k| w * k)));
|
||||
out.normal.push((*node, w * push, c));
|
||||
}
|
||||
for (node, w) in m.corners().iter().zip(qm.weights) {
|
||||
out.forces.push((*node, force.map(|k| -w * k)));
|
||||
}
|
||||
out.penetration = out.penetration.max(-gap);
|
||||
out.points += 1;
|
||||
out.total += push;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
impl Interface {
|
||||
/// The contact `name` of the model on the analysed nodes and elements: its surfaces, and the
|
||||
/// initial penetrations adjusted in `xyz` (or refused).
|
||||
pub fn new(
|
||||
model: &Model,
|
||||
resolved: &Resolved,
|
||||
name: &str,
|
||||
contact: &Contact,
|
||||
xyz: &mut [Vec3],
|
||||
labels: &[u32],
|
||||
elements: &[u32],
|
||||
) -> Result<Interface> {
|
||||
let context = |e: Error| match e {
|
||||
Error::Invalid(m) => invalid(format!("contact `{name}`: {m}")),
|
||||
other => other,
|
||||
};
|
||||
let node = |l: u32| labels.binary_search(&l).ok();
|
||||
let element = |l: u32| elements.binary_search(&l).ok();
|
||||
let faces_of = |set: &str| resolved.sets.get(set).map(|s| s.faces.clone()).unwrap_or_default();
|
||||
let (surfaces, passes) = match &contact.surfaces {
|
||||
ContactSurfaces::Pair { main, secondary } => {
|
||||
let main = Surface::new(model, &faces_of(main), xyz, &node, &element).map_err(context)?;
|
||||
let secondary = Surface::new(model, &faces_of(secondary), xyz, &node, &element).map_err(context)?;
|
||||
(vec![main, secondary], vec![(1, 0), (0, 1)])
|
||||
}
|
||||
ContactSurfaces::General { surface } => {
|
||||
let faces = match surface {
|
||||
Some(s) => faces_of(s),
|
||||
None => model.exterior_faces(),
|
||||
};
|
||||
(vec![Surface::new(model, &faces, xyz, &node, &element).map_err(context)?], vec![(0, 0)])
|
||||
}
|
||||
};
|
||||
let passes = passes
|
||||
.into_iter()
|
||||
.map(|(secondary, main)| Pass { secondary, main, slip: vec![Slip::default(); surfaces.get(secondary).map_or(0, |s| s.nodes.len())] })
|
||||
.collect();
|
||||
let mut interface = Interface {
|
||||
name: name.to_string(),
|
||||
friction: contact.friction,
|
||||
scale: contact.penalty_scale,
|
||||
surfaces,
|
||||
passes,
|
||||
adjusted: Vec::new(),
|
||||
mass_per_area: None,
|
||||
};
|
||||
interface.adjust(xyz, labels, contact.initial_penetration)?;
|
||||
Ok(interface)
|
||||
}
|
||||
|
||||
/// Move the nodes that start inside a face onto it, or refuse them.
|
||||
fn adjust(&mut self, xyz: &mut [Vec3], labels: &[u32], mode: InitialPenetration) -> Result<()> {
|
||||
let zero: Vec<f64> = Vec::new();
|
||||
for pass in &self.passes {
|
||||
let (Some(nodes), Some(faces)) = (self.surfaces.get(pass.secondary), self.surfaces.get(pass.main)) else { continue };
|
||||
let positions = faces.positions(xyz, &zero);
|
||||
let grid = grid(faces, &positions);
|
||||
let own = nodes.positions(xyz, &zero);
|
||||
let normals = nodes.node_normals(&own);
|
||||
// Each move is decided on the positions before any move of this pass.
|
||||
let mut moves: Vec<(usize, Vec3, Adjustment)> = Vec::new();
|
||||
for (i, &n) in nodes.nodes.iter().enumerate() {
|
||||
let x = xyz.get(n).copied().unwrap_or_default();
|
||||
let normal = normals.get(i).copied().unwrap_or_default();
|
||||
let Some((c, q)) = inside(faces, &positions, &grid, n, x, normal) else { continue };
|
||||
let Some(face) = faces.faces.get(c) else { continue };
|
||||
// Coordinates are exact to a few units in the last place: a node a hair behind a
|
||||
// face it was meshed on is touching, not inside.
|
||||
let scale = x.iter().fold(1.0f64, |m, c| m.max(c.abs()));
|
||||
if -q.gap <= 1e-9 * scale {
|
||||
continue;
|
||||
}
|
||||
let label = labels.get(n).copied().unwrap_or(0);
|
||||
let adjustment = Adjustment { node: label, element: face.element, face: face.face, depth: -q.gap };
|
||||
if mode == InitialPenetration::Refuse {
|
||||
return Err(invalid(format!(
|
||||
"contact `{}`: node {label} starts {:.4e} inside face {} of element {} (move it out, or let the contact adjust it: initial_penetration \"adjust\")",
|
||||
self.name, -q.gap, face.face, face.element
|
||||
)));
|
||||
}
|
||||
moves.push((n, q.point, adjustment));
|
||||
}
|
||||
for (n, point, a) in moves {
|
||||
if let Some(x) = xyz.get_mut(n) {
|
||||
*x = point;
|
||||
}
|
||||
self.adjusted.push(a);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The number of faces.
|
||||
pub fn faces(&self) -> usize {
|
||||
self.surfaces.iter().map(|s| s.faces.len()).sum()
|
||||
}
|
||||
|
||||
/// Add the contact forces at displacements `u` into `force` (per degree of freedom), with
|
||||
/// `du` the displacement increment that led to `u` over `dt_prev`, the stable increment
|
||||
/// `dt` and the lumped masses per degree of freedom `mass`; update the friction state.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn forces(
|
||||
&mut self,
|
||||
xyz: &[Vec3],
|
||||
u: &[f64],
|
||||
du: &[f64],
|
||||
dt_prev: f64,
|
||||
dt: f64,
|
||||
mass: &[f64],
|
||||
state: &State,
|
||||
force: &mut [f64],
|
||||
) -> Evaluation {
|
||||
let mut e = Evaluation::default();
|
||||
let node_mass = |n: usize| (0..3).map(|k| mass.get(NODE_DOFS * n + k).copied().unwrap_or(0.0)).fold(f64::INFINITY, f64::min);
|
||||
let mass_per_area = *self.mass_per_area.get_or_insert_with(|| {
|
||||
self.surfaces
|
||||
.iter()
|
||||
.flat_map(|s| s.nodes.iter().zip(&s.area))
|
||||
.filter(|(_, a)| **a > 0.0)
|
||||
.map(|(n, a)| node_mass(*n) / a)
|
||||
.fold(f64::INFINITY, f64::min)
|
||||
});
|
||||
// Every contact runs both ways, at half the penalty each.
|
||||
let eps = 0.5 * self.scale * GAMMA * mass_per_area / (dt * dt);
|
||||
if !(eps > 0.0 && eps.is_finite()) {
|
||||
for pass in &mut self.passes {
|
||||
pass.slip.fill(Slip::default());
|
||||
}
|
||||
return e;
|
||||
}
|
||||
let alive = |f: &Face| state.elements.get(f.index).is_none_or(|s| s.failed.is_none());
|
||||
let positions: Vec<Vec<Vec<Vec3>>> = self.surfaces.iter().map(|s| s.positions(xyz, u)).collect();
|
||||
let grids: Vec<Grid> = self.surfaces.iter().zip(&positions).map(|(s, p)| grid(s, p)).collect();
|
||||
let friction = self.friction;
|
||||
for pass in &mut self.passes {
|
||||
let (Some(secondary), Some(main), Some(sx), Some(mx), Some(grid)) = (
|
||||
self.surfaces.get(pass.secondary),
|
||||
self.surfaces.get(pass.main),
|
||||
positions.get(pass.secondary),
|
||||
positions.get(pass.main),
|
||||
grids.get(pass.main),
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
let info = face_info(main, mx, &alive);
|
||||
let blocks = fieldcraft_parallel::map_grained(secondary.faces.len().div_ceil(BLOCK), 1, |b| {
|
||||
let mut found = Vec::new();
|
||||
(b * BLOCK..((b + 1) * BLOCK).min(secondary.faces.len()))
|
||||
.map(|i| match (secondary.faces.get(i), sx.get(i)) {
|
||||
(Some(f), Some(fx)) => integrate_face(f, fx, alive(f), main, mx, &info, grid, eps, &mut found),
|
||||
_ => FaceForces::default(),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
// Per secondary node: its normal force, and the main face that gave it the most.
|
||||
let mut normal = vec![0.0; secondary.nodes.len()];
|
||||
let mut partner: Vec<Option<(usize, f64)>> = vec![None; secondary.nodes.len()];
|
||||
for face in blocks.iter().flatten() {
|
||||
for (node, f) in &face.forces {
|
||||
add_at(force, *node, f);
|
||||
}
|
||||
for (node, share, c) in &face.normal {
|
||||
if let Ok(k) = secondary.nodes.binary_search(node)
|
||||
&& let (Some(slot), Some(best)) = (normal.get_mut(k), partner.get_mut(k))
|
||||
{
|
||||
*slot += share;
|
||||
if best.is_none_or(|(_, s)| *share > s) {
|
||||
*best = Some((*c, *share));
|
||||
}
|
||||
}
|
||||
}
|
||||
e.normal_force += face.total;
|
||||
e.penetration = e.penetration.max(face.penetration);
|
||||
e.active += face.points;
|
||||
}
|
||||
if friction.is_frictionless() {
|
||||
continue;
|
||||
}
|
||||
// Friction at the secondary nodes, in node order, against the point under the node
|
||||
// of the main face that pressed it most.
|
||||
for (k, (&n, slip)) in secondary.nodes.iter().zip(pass.slip.iter_mut()).enumerate() {
|
||||
let fn_ = normal.get(k).copied().unwrap_or(0.0);
|
||||
let kt = eps * secondary.area.get(k).copied().unwrap_or(0.0);
|
||||
let hit = partner
|
||||
.get(k)
|
||||
.copied()
|
||||
.flatten()
|
||||
.filter(|_| fn_ > 0.0 && kt > 0.0)
|
||||
.and_then(|(c, _)| mx.get(c).and_then(|x| closest_point(x, position(xyz, u, n))).map(|q| (c, q)));
|
||||
let Some((c, q)) = hit else {
|
||||
*slip = Slip::default();
|
||||
continue;
|
||||
};
|
||||
let Some(face) = main.faces.get(c) else { continue };
|
||||
let mut rel = shift(du, n);
|
||||
for (m, w) in face.corners().iter().zip(q.weights) {
|
||||
let d = shift(du, *m);
|
||||
for c in 0..3 {
|
||||
rel[c] -= w * d[c];
|
||||
}
|
||||
}
|
||||
let normal = q.normal;
|
||||
let rn = dot(rel, normal);
|
||||
let slide = [0, 1, 2].map(|c| rel[c] - rn * normal[c]);
|
||||
let old = slip.force;
|
||||
let on = dot(old, normal);
|
||||
let trial: Vec3 = std::array::from_fn(|c| old[c] - on * normal[c] - kt * slide[c]);
|
||||
let size = norm(trial);
|
||||
let rate = if dt_prev > 0.0 { norm(slide) / dt_prev } else { 0.0 };
|
||||
let limit = friction.coefficient(rate) * fn_;
|
||||
let tangential = if size <= limit {
|
||||
trial
|
||||
} else {
|
||||
e.dissipation += limit * (size - limit) / kt;
|
||||
trial.map(|c| c * limit / size)
|
||||
};
|
||||
slip.force = tangential;
|
||||
add_at(force, n, &tangential);
|
||||
for (m, w) in face.corners().iter().zip(q.weights) {
|
||||
add_at(force, *m, &tangential.map(|c| -w * c));
|
||||
}
|
||||
}
|
||||
}
|
||||
e
|
||||
}
|
||||
}
|
||||
|
||||
/// Every contact of the model, built on the analysed nodes and elements (with the initial
|
||||
/// adjustments made in `xyz`), and no more than `max_faces` faces in all.
|
||||
pub fn interfaces(
|
||||
model: &Model,
|
||||
resolved: &Resolved,
|
||||
xyz: &mut [Vec3],
|
||||
labels: &[u32],
|
||||
elements: &[u32],
|
||||
max_faces: usize,
|
||||
) -> Result<Vec<Interface>> {
|
||||
let mut out = Vec::with_capacity(model.contacts().len());
|
||||
let mut faces = 0usize;
|
||||
for (name, c) in model.contacts() {
|
||||
let i = Interface::new(model, resolved, name, c, xyz, labels, elements)?;
|
||||
faces = faces.saturating_add(i.faces());
|
||||
if faces > max_faces {
|
||||
return Err(Error::Limit(format!(
|
||||
"the contacts hold more than {max_faces} faces (contact `{name}` passes the cap); name smaller surfaces"
|
||||
)));
|
||||
}
|
||||
out.push(i);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn clipping_two_triangles_gives_their_overlap() {
|
||||
let a = [[0.0, 0.0], [2.0, 0.0], [0.0, 2.0]];
|
||||
let b = [[1.0, -1.0], [1.0, 3.0], [-1.0, 1.0]];
|
||||
// b clockwise: reversed it is counter-clockwise.
|
||||
let mut b2 = b.to_vec();
|
||||
if signed_area(&b2) < 0.0 {
|
||||
b2.reverse();
|
||||
}
|
||||
let o = clip(&a, &b2);
|
||||
// The overlap: the part of a with x ≤ 1 and y ≤ x + 2… here the triangle's left half,
|
||||
// area 2 − ½ = 1.5.
|
||||
assert!((signed_area(&o) - 1.5).abs() < 1e-12, "{o:?} {}", signed_area(&o));
|
||||
assert!(clip(&a, &[[5.0, 5.0], [6.0, 5.0], [5.0, 6.0]]).is_empty());
|
||||
let same = clip(&a, &a);
|
||||
assert!((signed_area(&same) - 2.0).abs() < 1e-12);
|
||||
}
|
||||
}
|
||||
@@ -54,6 +54,7 @@
|
||||
//! reaches its material's erosion plastic strain is removed: it carries no stress from then on,
|
||||
//! its nodes keep their mass and momentum, and its internal energy at that moment is reported.
|
||||
|
||||
use fieldcraft_fem::constitutive::MaterialModel;
|
||||
use fieldcraft_fem::material::stress;
|
||||
use fieldcraft_fem::plasticity::{Increment, PointState};
|
||||
use fieldcraft_fem::rotation::{self, IDENTITY, Mat3, Polar};
|
||||
@@ -70,10 +71,16 @@ pub struct Workspace {
|
||||
pub stress_force: Vec<f64>,
|
||||
pub hourglass_force: Vec<f64>,
|
||||
pub viscous_force: Vec<f64>,
|
||||
/// Contact forces on the model per degree of freedom (empty without contact).
|
||||
pub contact_force: Vec<f64>,
|
||||
/// Per node: the volume-weighted volumetric strain increments of its tetrahedra, and their
|
||||
/// volume.
|
||||
theta: Vec<f64>,
|
||||
tet_volume: Vec<f64>,
|
||||
/// Per node, for hyperelastic tetrahedra: the current and the rest volume of its
|
||||
/// tetrahedra, then their ratio.
|
||||
tet_ratio: Vec<f64>,
|
||||
tet_rest: Vec<f64>,
|
||||
/// Per tetrahedron (in [`System::tets`] order): its increment between the two passes.
|
||||
tet_increment: Vec<Option<TetIncrement>>,
|
||||
}
|
||||
@@ -82,12 +89,16 @@ impl Workspace {
|
||||
pub fn new(sys: &System) -> Workspace {
|
||||
let n = sys.labels.len();
|
||||
let dofs = sys.dofs();
|
||||
let hyper_tets = sys.tets.iter().any(|t| sys.materials.get(t.material).is_some_and(|m| m.hyperelastic.is_some()));
|
||||
Workspace {
|
||||
stress_force: vec![0.0; dofs],
|
||||
hourglass_force: vec![0.0; dofs],
|
||||
viscous_force: vec![0.0; dofs],
|
||||
contact_force: if sys.contacts.is_empty() { Vec::new() } else { vec![0.0; dofs] },
|
||||
theta: vec![0.0; n],
|
||||
tet_volume: vec![0.0; n],
|
||||
tet_ratio: if hyper_tets { vec![1.0; n] } else { Vec::new() },
|
||||
tet_rest: if hyper_tets { vec![0.0; n] } else { Vec::new() },
|
||||
tet_increment: vec![None; sys.tets.len()],
|
||||
}
|
||||
}
|
||||
@@ -311,6 +322,52 @@ fn update(mat: &Material, es: &mut ElementState, q: &Mat3, d: &[f64; 6], vol: f6
|
||||
}
|
||||
}
|
||||
|
||||
/// The hyperelastic update of an element at deformation gradient `f` (the hexahedron's mean,
|
||||
/// or the tetrahedron's with its averaged volume ratio): the material point's Kirchhoff stress τ
|
||||
/// gives the stress of the nodal forces τ/`j` (`j` the element's own volume ratio, so the forces
|
||||
/// are ∫ τ ∇ₓN dV₀), the logarithmic strain is kept for output, and the stress work over the
|
||||
/// increment `d` (on the midpoint volume `volume`) is added to the element's energy. Returns the
|
||||
/// ratio of the tangent's largest normal stiffness (with the stress) to the material's
|
||||
/// small-strain one, at least 1, which scales the element's frequency bound.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn hyperelastic(
|
||||
model: &MaterialModel,
|
||||
mat: &Material,
|
||||
es: &mut ElementState,
|
||||
f: &Mat3,
|
||||
j: f64,
|
||||
pressure: Option<f64>,
|
||||
d: &[f64; 6],
|
||||
volume: f64,
|
||||
) -> Result<f64> {
|
||||
let unstable = |e: fieldcraft_fem::Error| Error::Unstable(e.to_string());
|
||||
if !(j > 0.0 && j.is_finite()) {
|
||||
return Err(Error::Unstable(format!("the material is inverted (volume ratio {j:.3e})")));
|
||||
}
|
||||
let r = model.response(f, None, &[], &mut []).map_err(unstable)?;
|
||||
let before = es.point.stress;
|
||||
es.point.stress = match pressure {
|
||||
// The isochoric part of the element's own F with the averaged pressure.
|
||||
Some(p) => {
|
||||
let iso = model.isochoric(f, None, &[], &mut []).map_err(unstable)?;
|
||||
let mut s = iso.stress.map(|t| t / j);
|
||||
for v in s.iter_mut().take(3) {
|
||||
*v += p;
|
||||
}
|
||||
s
|
||||
}
|
||||
None => r.stress.map(|t| t / j),
|
||||
};
|
||||
let work: f64 = (0..6).map(|k| 0.5 * (before[k] + es.point.stress[k]) * d[k]).sum();
|
||||
es.energy += work * volume;
|
||||
if let Some(e) = fieldcraft_fem::constitutive::logarithmic_strain(f) {
|
||||
es.strain = e;
|
||||
}
|
||||
let normal = (0..3).map(|k| r.tangent[k][k]).fold(0.0, f64::max) / j;
|
||||
let stress = es.point.stress.iter().fold(0.0f64, |m, s| m.max(s.abs()));
|
||||
Ok(((normal + stress) / mat.stiffest).max(1.0))
|
||||
}
|
||||
|
||||
/// The mechanical part of a strain increment: less the thermal strain increment `thermal` in
|
||||
/// every normal direction (isotropic expansion, the same in any frame).
|
||||
fn mechanical(mut d: [f64; 6], thermal: f64) -> [f64; 6] {
|
||||
@@ -490,7 +547,22 @@ fn hexahedron(sys: &System, h: &crate::system::Hex, m: &Motion, es: &mut Element
|
||||
let (d, _) = rotation::split(&g);
|
||||
let d = mechanical(d, h.thermal_rate * m.dt);
|
||||
let (rho, c) = current(mat, h.kinematics.volume, now.volume);
|
||||
update(mat, es, &q, &d, d[0] + d[1] + d[2], m.dt, rho, mid.volume);
|
||||
// Mass scaling raises the density the dynamics see (not the one adiabatic heating uses).
|
||||
let (rho_s, c_s) = (rho * h.mass_factor, c / h.mass_factor.sqrt());
|
||||
let stiffer = match &mat.hyperelastic {
|
||||
Some(model) => {
|
||||
let mut f = h.kinematics.gradient(&e.u);
|
||||
for k in 0..3 {
|
||||
f[k][k] += 1.0;
|
||||
}
|
||||
let j = fieldcraft_fem::dense::det3(&f);
|
||||
hyperelastic(model, mat, es, &f, j, None, &d, mid.volume).map_err(|_| inverted(h.label, m.time))?
|
||||
}
|
||||
None => {
|
||||
update(mat, es, &q, &d, d[0] + d[1] + d[2], m.dt, rho, mid.volume);
|
||||
1.0
|
||||
}
|
||||
};
|
||||
if let Some(failure) = es.failed {
|
||||
return Ok(Outcome::Eroded(failure));
|
||||
}
|
||||
@@ -498,7 +570,7 @@ fn hexahedron(sys: &System, h: &crate::system::Hex, m: &Motion, es: &mut Element
|
||||
// geometry).
|
||||
let (gamma, scales) = if sys.nonlinear {
|
||||
let gamma = now.hourglass_vectors(&x_now);
|
||||
let scales = hex_scales(&now, &gamma, &h.mass, mat, rho, hourglass);
|
||||
let scales = hex_scales(&now, &gamma, &h.mass, mat, rho_s, hourglass);
|
||||
(gamma, scales)
|
||||
} else {
|
||||
(h.gamma, h.rest)
|
||||
@@ -523,7 +595,7 @@ fn hexahedron(sys: &System, h: &crate::system::Hex, m: &Motion, es: &mut Element
|
||||
}
|
||||
}
|
||||
}
|
||||
let element = Element { now: &now, mid: &mid, density: rho, wave_speed: c, length: 2.0 * c / scales.omega2.sqrt() };
|
||||
let element = Element { now: &now, mid: &mid, density: rho_s, wave_speed: c_s, length: 2.0 * c_s / (stiffer * scales.omega2).sqrt() };
|
||||
let mut forces = element.finish(&es.point.stress, &e.v, m.bulk);
|
||||
forces.hourglass = Some(f);
|
||||
Ok(Outcome::Forces(forces))
|
||||
@@ -551,6 +623,7 @@ fn tetrahedron(
|
||||
t: &crate::system::Tet,
|
||||
inc: Option<TetIncrement>,
|
||||
theta: &[f64],
|
||||
ratio: &[f64],
|
||||
m: &Motion,
|
||||
es: &mut ElementState,
|
||||
) -> Result<Outcome<4>> {
|
||||
@@ -561,12 +634,36 @@ fn tetrahedron(
|
||||
let thermal = t.thermal_rate * m.dt;
|
||||
let d = mechanical(d, thermal);
|
||||
let (rho, c) = current(mat, t.kinematics.volume, inc.now.volume);
|
||||
update(mat, es, &q, &d, averaged - 3.0 * thermal, m.dt, rho, inc.mid.volume);
|
||||
let (rho_s, c_s) = (rho * t.mass_factor, c / t.mass_factor.sqrt());
|
||||
let stiffer = match &mat.hyperelastic {
|
||||
// The average nodal pressure of a decoupled material (Bonet & Burton 1998, at finite
|
||||
// strain): each node's pressure U′(J_a) from its tetrahedra's volume ratio, the element's
|
||||
// the mean of its nodes', with the isochoric stress of its own F.
|
||||
Some(model) => {
|
||||
let u = gather(m.u, &t.nodes);
|
||||
let mut f = t.kinematics.gradient(&u);
|
||||
for k in 0..3 {
|
||||
f[k][k] += 1.0;
|
||||
}
|
||||
let j = fieldcraft_fem::dense::det3(&f);
|
||||
let pressure = if model.is_decoupled() {
|
||||
let p: Option<f64> = t.nodes.iter().map(|n| model.volumetric(ratio.get(*n).copied().unwrap_or(1.0), false).map(|(p, _)| p)).sum();
|
||||
p.map(|p| p / 4.0)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
hyperelastic(model, mat, es, &f, j, pressure, &d, inc.mid.volume).map_err(|_| inverted(t.label, m.time))?
|
||||
}
|
||||
None => {
|
||||
update(mat, es, &q, &d, averaged - 3.0 * thermal, m.dt, rho, inc.mid.volume);
|
||||
1.0
|
||||
}
|
||||
};
|
||||
if let Some(failure) = es.failed {
|
||||
return Ok(Outcome::Eroded(failure));
|
||||
}
|
||||
let omega2 = if sys.nonlinear { frequency_bound(&inc.now, inc.now.gradient_norm(), mat.modulus, &t.mass) } else { t.omega2 };
|
||||
let element = Element { now: &inc.now, mid: &inc.mid, density: rho, wave_speed: c, length: 2.0 * c / omega2.sqrt() };
|
||||
let omega2 = stiffer * if sys.nonlinear { frequency_bound(&inc.now, inc.now.gradient_norm(), mat.modulus, &t.mass) } else { t.omega2 };
|
||||
let element = Element { now: &inc.now, mid: &inc.mid, density: rho_s, wave_speed: c_s, length: 2.0 * c_s / omega2.sqrt() };
|
||||
Ok(Outcome::Forces(element.finish(&es.point.stress, &inc.v, m.bulk)))
|
||||
}
|
||||
|
||||
@@ -629,16 +726,32 @@ pub fn internal_forces(sys: &System, m: &Motion, state: &mut State, ws: &mut Wor
|
||||
*x /= w;
|
||||
}
|
||||
}
|
||||
if !ws.tet_ratio.is_empty() {
|
||||
ws.tet_ratio.fill(0.0);
|
||||
ws.tet_rest.fill(0.0);
|
||||
for (t, inc) in tets.iter().zip(&ws.tet_increment) {
|
||||
let Some(inc) = inc else { continue };
|
||||
for node in t.nodes {
|
||||
if let (Some(x), Some(w)) = (ws.tet_ratio.get_mut(node), ws.tet_rest.get_mut(node)) {
|
||||
*x += inc.now.volume;
|
||||
*w += t.kinematics.volume;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (x, w) in ws.tet_ratio.iter_mut().zip(&ws.tet_rest) {
|
||||
*x = if *w > 0.0 { *x / w } else { 1.0 };
|
||||
}
|
||||
}
|
||||
// Pass 2: each tetrahedron's update.
|
||||
let State { elements, eroded } = state;
|
||||
let (theta, increments) = (&ws.theta, &ws.tet_increment);
|
||||
let (theta, ratio, increments) = (&ws.theta, &ws.tet_ratio, &ws.tet_increment);
|
||||
let mut forces: Vec<(usize, Forces<4>)> = Vec::new();
|
||||
run(
|
||||
elements,
|
||||
tets.len(),
|
||||
|k| tets.get(k).map_or(usize::MAX, |t| t.index),
|
||||
|k, es| match tets.get(k) {
|
||||
Some(t) => tetrahedron(sys, t, increments.get(k).copied().flatten(), theta, m, es),
|
||||
Some(t) => tetrahedron(sys, t, increments.get(k).copied().flatten(), theta, ratio, m, es),
|
||||
None => Ok(Outcome::Skipped),
|
||||
},
|
||||
|k, outcome| {
|
||||
|
||||
@@ -6,13 +6,16 @@
|
||||
//! 1. u^n = u^{n−1} + Δt^{n−½} v^{n−½}; t^n = t^{n−1} + Δt^{n−½};
|
||||
//! 2. internal forces f^n from u^n (stresses, hourglass stiffness) and v^{n−½} (hourglass and
|
||||
//! bulk viscosity), and the next increment Δt^{n+½} = scale · min_e Δt_e;
|
||||
//! 3. v^{n+½} = v^{n−½} + Δt^n M⁻¹(f_ext − f^n), then the constraints: rigid walls set the normal
|
||||
//! velocity of a node that would cross its wall so it lands on it (a frictionless kinematic
|
||||
//! contact condition: T. J. R. Hughes, R. L. Taylor, J. L. Sackman, A. Curnier, W.
|
||||
//! Kanoknukulchai, *A finite element method for a class of contact-impact problems*, CMAME
|
||||
//! 8(3):249–276, 1976), and prescribed degrees of freedom take their velocity. The change a
|
||||
//! constraint makes is the impulse of its reaction, r^n = M Δv / Δt^n;
|
||||
//! 4. energies: the works of the internal and external forces by the trapezoidal rule,
|
||||
//! 3. the contact forces c^n at u^n ([`crate::contact`], with the stable increment Δt^{n+½});
|
||||
//! v^{n+½} = v^{n−½} + Δt^n M⁻¹(f_ext + c^n − f^n), then the constraints: rigid walls set the
|
||||
//! normal velocity of a node that would cross its wall so it lands on it (a kinematic contact
|
||||
//! condition: T. J. R. Hughes, R. L. Taylor, J. L. Sackman, A. Curnier, W. Kanoknukulchai,
|
||||
//! *A finite element method for a class of contact-impact problems*, CMAME 8(3):249–276,
|
||||
//! 1976), with Coulomb friction as a tangential impulse at most μ times the normal one (the
|
||||
//! tangential velocity stops, or loses μ Δv_n when it slides), and prescribed degrees of
|
||||
//! freedom take their velocity. The change a constraint makes is the impulse of its reaction,
|
||||
//! r^n = M Δv / Δt^n;
|
||||
//! 4. energies: the works of the internal, contact and external forces by the trapezoidal rule,
|
||||
//! W += ½ Δu · (f^{n−1} + f^n) (exactly the strain energy for a linear elastic material),
|
||||
//! the constraints' work Δt^n r^n · ½(v^{n−½} + v^{n+½}) (exactly the kinetic energy their
|
||||
//! impulses add or remove), and the kinetic energy of v^n = v^{n−½} + ½Δt^{n−½} a^n.
|
||||
@@ -22,8 +25,9 @@
|
||||
|
||||
use fieldcraft_model::{ExplicitDynamic, Model, OutputVariable, Procedure, Step};
|
||||
|
||||
use crate::contact::{Evaluation, Interface};
|
||||
use crate::elements::{Motion, State, Workspace, internal_forces};
|
||||
use crate::result::{ControllingElement, Energies, ErodedElement, ExplicitResult, Frame, History};
|
||||
use crate::result::{ContactSummary, ControllingElement, Energies, ErodedElement, ExplicitResult, Frame, History};
|
||||
use crate::system::{NODE_DOFS, System};
|
||||
use crate::{Error, Limits, Result};
|
||||
|
||||
@@ -70,8 +74,10 @@ struct Output {
|
||||
}
|
||||
|
||||
/// Velocity constraints over an increment of length `dt` (rigid walls when dt > 0, then
|
||||
/// prescribed degrees of freedom).
|
||||
fn constrain(sys: &System, u: &[f64], v: &mut [f64], dt: f64) {
|
||||
/// prescribed degrees of freedom); returns the kinetic energy the walls' friction took (`mass`
|
||||
/// per degree of freedom).
|
||||
fn constrain(sys: &System, u: &[f64], v: &mut [f64], dt: f64, mass: &[f64]) -> f64 {
|
||||
let mut dissipated = 0.0;
|
||||
if dt > 0.0 {
|
||||
for w in &sys.walls {
|
||||
for &node in &w.nodes {
|
||||
@@ -86,6 +92,9 @@ fn constrain(sys: &System, u: &[f64], v: &mut [f64], dt: f64) {
|
||||
*c += change * w.normal[k];
|
||||
}
|
||||
}
|
||||
if !w.friction.is_frictionless() {
|
||||
dissipated += wall_friction(v, node, w, change, mass.get(at(0)).copied().unwrap_or(0.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -95,14 +104,75 @@ fn constrain(sys: &System, u: &[f64], v: &mut [f64], dt: f64) {
|
||||
*c = *p;
|
||||
}
|
||||
}
|
||||
dissipated
|
||||
}
|
||||
|
||||
/// v_out = v_in + dt M⁻¹ (f_ext − f_int).
|
||||
/// Coulomb friction of a node the wall `w` stopped with a normal velocity change `change`: its
|
||||
/// tangential velocity changes by at most μ · change (stick when that stops it); returns the
|
||||
/// kinetic energy taken, ½ m (|v_t|² − |v_t′|²).
|
||||
fn wall_friction(v: &mut [f64], node: usize, w: &crate::system::Wall, change: f64, mass: f64) -> f64 {
|
||||
let at = |k: usize| NODE_DOFS * node + k;
|
||||
let vel = [0, 1, 2].map(|k| v.get(at(k)).copied().unwrap_or(0.0));
|
||||
let vn: f64 = (0..3).map(|k| vel[k] * w.normal[k]).sum();
|
||||
let tangential = [0, 1, 2].map(|k| vel[k] - vn * w.normal[k]);
|
||||
let slide = tangential.iter().map(|c| c * c).sum::<f64>().sqrt();
|
||||
if slide == 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let cap = w.friction.coefficient(slide) * change;
|
||||
let keep = if slide <= cap { 0.0 } else { 1.0 - cap / slide };
|
||||
for k in 0..3 {
|
||||
if let Some(c) = v.get_mut(at(k)) {
|
||||
*c = vn * w.normal[k] + keep * tangential[k];
|
||||
}
|
||||
}
|
||||
0.5 * mass * slide * slide * (1.0 - keep * keep)
|
||||
}
|
||||
|
||||
/// v_out = v_in + dt M⁻¹ (f_ext + f_contact − f_int).
|
||||
fn accelerate(sys: &System, ws: &Workspace, mass: &[f64], v_in: &[f64], dt: f64, v_out: &mut [f64]) {
|
||||
let internal = ws.stress_force.iter().zip(&ws.hourglass_force).zip(&ws.viscous_force);
|
||||
for ((((out, v), m), e), ((s, h), q)) in v_out.iter_mut().zip(v_in).zip(mass).zip(&sys.external).zip(internal) {
|
||||
*out = v + dt * ((e - (s + h + q)) / m);
|
||||
}
|
||||
// Contact adds its forces (a separate pass, so a model without contact runs the same sums).
|
||||
if !ws.contact_force.is_empty() {
|
||||
for ((out, m), c) in v_out.iter_mut().zip(mass).zip(&ws.contact_force) {
|
||||
*out += dt * (c / m);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The contacts' forces at `u` (with the increment `du` over `dt_prev` that led there, and the
|
||||
/// stable increment `dt`) into `ws.contact_force`, and what each found.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn contact_forces(
|
||||
contacts: &mut [Interface],
|
||||
sys: &System,
|
||||
u: &[f64],
|
||||
du: &[f64],
|
||||
dt_prev: f64,
|
||||
dt: f64,
|
||||
mass: &[f64],
|
||||
state: &State,
|
||||
ws: &mut Workspace,
|
||||
) -> Vec<Evaluation> {
|
||||
ws.contact_force.fill(0.0);
|
||||
contacts.iter_mut().map(|c| c.forces(&sys.xyz, u, du, dt_prev, dt, mass, state, &mut ws.contact_force)).collect()
|
||||
}
|
||||
|
||||
/// A contact's record over the run.
|
||||
fn track(summary: &mut ContactSummary, e: &Evaluation, t: f64) {
|
||||
if e.active > 0 {
|
||||
summary.first_contact.get_or_insert(t);
|
||||
summary.last_contact = Some(t);
|
||||
}
|
||||
if e.normal_force > summary.peak_force {
|
||||
summary.peak_force = e.normal_force;
|
||||
summary.peak_time = t;
|
||||
}
|
||||
summary.max_penetration = summary.max_penetration.max(e.penetration);
|
||||
summary.friction += e.dissipation;
|
||||
}
|
||||
|
||||
/// The constraint reactions M (v_constrained − v_free) / Δt, into `r`.
|
||||
@@ -120,7 +190,7 @@ fn per_node(x: &[f64]) -> Vec<[f64; 3]> {
|
||||
pub fn solve_explicit(model: &Model, step: Option<&str>, limits: &Limits) -> Result<ExplicitResult> {
|
||||
let resolved = model.resolve()?;
|
||||
let (step, settings) = select_step(model, step)?;
|
||||
let sys = System::new(model, &resolved, step, settings, limits.max_dofs)?;
|
||||
let mut sys = System::new(model, &resolved, step, settings, limits)?;
|
||||
let end = settings.end_time;
|
||||
let scale = settings.dt_scale;
|
||||
let bulk = settings.bulk_viscosity;
|
||||
@@ -131,10 +201,14 @@ pub fn solve_explicit(model: &Model, step: Option<&str>, limits: &Limits) -> Res
|
||||
let mut critical: Vec<ControllingElement> = sys
|
||||
.hexes
|
||||
.iter()
|
||||
.map(|h| (h.label, h.length, h.material))
|
||||
.chain(sys.tets.iter().map(|t| (t.label, t.length, t.material)))
|
||||
.chain(sys.rods.iter().map(|r| (r.label, r.length, r.material)))
|
||||
.map(|(label, length, m)| ControllingElement { label, increment: length / sys.materials.get(m).map_or(f64::INFINITY, |m| m.wave_speed) })
|
||||
.map(|h| (h.label, h.length, h.material, h.mass_factor))
|
||||
.chain(sys.tets.iter().map(|t| (t.label, t.length, t.material, t.mass_factor)))
|
||||
.chain(sys.rods.iter().map(|r| (r.label, r.length, r.material, 1.0)))
|
||||
.map(|(label, length, m, f)| ControllingElement {
|
||||
label,
|
||||
// Mass scaling slows the element's waves by √f.
|
||||
increment: length * f.sqrt() / sys.materials.get(m).map_or(f64::INFINITY, |m| m.wave_speed),
|
||||
})
|
||||
.collect();
|
||||
critical.sort_by(|a, b| a.increment.total_cmp(&b.increment).then(a.label.cmp(&b.label)));
|
||||
critical.truncate(CONTROLLING);
|
||||
@@ -192,6 +266,9 @@ pub fn solve_explicit(model: &Model, step: Option<&str>, limits: &Limits) -> Res
|
||||
let total_mass: f64 = sys.mass.iter().sum::<f64>() + sys.discrete.mass.iter().sum::<f64>() / 3.0;
|
||||
let mut ws = Workspace::new(&sys);
|
||||
let mut previous = Workspace::new(&sys);
|
||||
let mut contacts = std::mem::take(&mut sys.contacts);
|
||||
let mut summaries: Vec<ContactSummary> =
|
||||
contacts.iter().map(|c| ContactSummary { name: c.name.clone(), adjusted: c.adjusted.clone(), ..ContactSummary::default() }).collect();
|
||||
let mut state = State::new(&sys);
|
||||
let mut eroded: Vec<ErodedElement> = Vec::new();
|
||||
let mut u = vec![0.0; n];
|
||||
@@ -205,10 +282,14 @@ pub fn solve_explicit(model: &Model, step: Option<&str>, limits: &Limits) -> Res
|
||||
let crit = internal_forces(&sys, &start, &mut state, &mut ws)?;
|
||||
let mut dt_half = (scale * crit).min(end);
|
||||
let initial_increment = dt_half;
|
||||
let mut found = contact_forces(&mut contacts, &sys, &u, &du, 0.0, scale * crit, &mass, &state, &mut ws);
|
||||
for (summary, e) in summaries.iter_mut().zip(&found) {
|
||||
track(summary, e, 0.0);
|
||||
}
|
||||
let mut v_half = vec![0.0; n];
|
||||
accelerate(&sys, &ws, &mass, &v0, 0.5 * dt_half, &mut v_half);
|
||||
let mut free = v_half.clone();
|
||||
constrain(&sys, &u, &mut v_half, dt_half);
|
||||
let wall_friction = constrain(&sys, &u, &mut v_half, dt_half, &mass);
|
||||
let mut reaction = vec![0.0; n];
|
||||
impulses(&mass, &free, &v_half, 0.5 * dt_half, &mut reaction);
|
||||
// The constraints' work is that of their impulses on the mean of the velocities before
|
||||
@@ -217,12 +298,18 @@ pub fn solve_explicit(model: &Model, step: Option<&str>, limits: &Limits) -> Res
|
||||
let impulse_work = |r: &[f64], before: &[f64], after: &[f64], dt: f64| -> f64 {
|
||||
dt * r.iter().zip(before.iter().zip(after)).map(|(r, (a, b))| r * 0.5 * (a + b)).sum::<f64>()
|
||||
};
|
||||
let mut energy = Energies { kinetic: initial_kinetic, constraint: impulse_work(&reaction, &v0, &v_half, 0.5 * dt_half), ..Energies::default() };
|
||||
let mut energy = Energies {
|
||||
kinetic: initial_kinetic,
|
||||
constraint: impulse_work(&reaction, &v0, &v_half, 0.5 * dt_half),
|
||||
friction: wall_friction,
|
||||
..Energies::default()
|
||||
};
|
||||
|
||||
let mut history = History { nodes: sys.history_nodes.iter().filter_map(|i| sys.labels.get(*i).copied()).collect(), ..History::default() };
|
||||
let mut out_frames = Vec::new();
|
||||
let sample = |history: &mut History, t: f64, dt: f64, e: Energies, u: &[f64], v: &[f64], r: &[f64]| {
|
||||
let sample = |history: &mut History, t: f64, dt: f64, e: Energies, u: &[f64], v: &[f64], r: &[f64], found: &[Evaluation]| {
|
||||
history.time.push(t);
|
||||
history.contact_force.push(found.iter().map(|e| e.normal_force).collect());
|
||||
history.increment.push(dt);
|
||||
history.energies.push(e);
|
||||
let sum = |x: &[f64], weight: &dyn Fn(usize, usize) -> f64| {
|
||||
@@ -260,7 +347,7 @@ pub fn solve_explicit(model: &Model, step: Option<&str>, limits: &Limits) -> Res
|
||||
let plastic = |state: &State| state.elements.iter().map(|e| e.plastic_work).sum::<f64>();
|
||||
let mut histories = Schedule { interval: settings.history_interval(), next: settings.history_interval() };
|
||||
let mut frames_due = Schedule { interval: settings.output_interval(), next: settings.output_interval() };
|
||||
sample(&mut history, 0.0, dt_half, energy, &u, &v0, &reaction);
|
||||
sample(&mut history, 0.0, dt_half, energy, &u, &v0, &reaction, &found);
|
||||
out_frames.push(frame(0.0, &u, &v0, &state));
|
||||
|
||||
let mut t = 0.0;
|
||||
@@ -294,9 +381,16 @@ pub fn solve_explicit(model: &Model, step: Option<&str>, limits: &Limits) -> Res
|
||||
let last = remaining <= 1e-12 * end;
|
||||
let dt_next = if last { 0.0 } else { (scale * crit).min(remaining) };
|
||||
let dt_n = 0.5 * (dt_half + dt_next);
|
||||
if !contacts.is_empty() {
|
||||
found = contact_forces(&mut contacts, &sys, &u, &du, dt_half, scale * crit, &mass, &state, &mut ws);
|
||||
for (summary, e) in summaries.iter_mut().zip(&found) {
|
||||
track(summary, e, t);
|
||||
energy.friction += e.dissipation;
|
||||
}
|
||||
}
|
||||
accelerate(&sys, &ws, &mass, &v_half, dt_n, &mut v_new);
|
||||
free.clone_from(&v_new);
|
||||
constrain(&sys, &u, &mut v_new, dt_next);
|
||||
energy.friction += constrain(&sys, &u, &mut v_new, dt_next, &mass);
|
||||
impulses(&mass, &free, &v_new, dt_n, &mut reaction);
|
||||
// One pass over the degrees of freedom: v^n = v^{n−½} + ½Δt^{n−½} a^n with the constrained
|
||||
// a^n = (v^{n+½} − v^{n−½}) / Δt^n, and the works (trapezoidal over the displacement for
|
||||
@@ -321,15 +415,26 @@ pub fn solve_explicit(model: &Model, step: Option<&str>, limits: &Limits) -> Res
|
||||
energy.external += external;
|
||||
energy.constraint += dt_n * constraint;
|
||||
energy.kinetic = 0.5 * kinetic;
|
||||
if !sys.added_mass.is_empty() {
|
||||
let per_node = v_now.as_chunks::<NODE_DOFS>().0.iter().zip(&sys.added_mass);
|
||||
energy.added_kinetic = 0.5 * per_node.map(|(v, m)| m * (v[0] * v[0] + v[1] * v[1] + v[2] * v[2])).sum::<f64>();
|
||||
}
|
||||
if !ws.contact_force.is_empty() {
|
||||
let work: f64 = du.iter().zip(ws.contact_force.iter().zip(&previous.contact_force)).map(|(d, (c, c0))| d * (c0 + c)).sum();
|
||||
energy.contact -= 0.5 * work;
|
||||
}
|
||||
peak_internal = peak_internal.max(energy.internal.abs());
|
||||
energy.balance = energy.kinetic + energy.internal + energy.hourglass + energy.viscous - energy.external - energy.constraint - initial_kinetic;
|
||||
energy.balance = energy.kinetic + energy.internal + energy.hourglass + energy.viscous + energy.contact
|
||||
- energy.external
|
||||
- energy.constraint
|
||||
- initial_kinetic;
|
||||
// Every element eroded leaves an infinite critical increment: the nodes fly freely.
|
||||
if !(energy.balance.is_finite() && !crit.is_nan()) {
|
||||
return Err(Error::Unstable(format!("the solution is not finite at time {t:.6e} (increment {increments})")));
|
||||
}
|
||||
if histories.due(t) || last {
|
||||
energy.plastic = plastic(&state);
|
||||
sample(&mut history, t, dt_half, energy, &u, &v_now, &reaction);
|
||||
sample(&mut history, t, dt_half, energy, &u, &v_now, &reaction, &found);
|
||||
}
|
||||
if frames_due.due(t) || last {
|
||||
out_frames.push(frame(t, &u, &v_now, &state));
|
||||
@@ -342,7 +447,7 @@ pub fn solve_explicit(model: &Model, step: Option<&str>, limits: &Limits) -> Res
|
||||
}
|
||||
if !completed {
|
||||
if history.time.last() != Some(&t) {
|
||||
sample(&mut history, t, dt_half, energy, &u, &v_now, &reaction);
|
||||
sample(&mut history, t, dt_half, energy, &u, &v_now, &reaction, &found);
|
||||
}
|
||||
if out_frames.last().map(|f| f.time) != Some(t) {
|
||||
out_frames.push(frame(t, &u, &v_now, &state));
|
||||
@@ -385,6 +490,8 @@ pub fn solve_explicit(model: &Model, step: Option<&str>, limits: &Limits) -> Res
|
||||
energy,
|
||||
initial_kinetic,
|
||||
eroded,
|
||||
contacts: summaries,
|
||||
mass_scaling: sys.mass_scaling.clone(),
|
||||
warnings,
|
||||
})
|
||||
}
|
||||
@@ -14,8 +14,12 @@
|
||||
//! hourglass control (viscous or stiffness), the Bonet–Burton average nodal pressure
|
||||
//! tetrahedron, von Neumann–Richtmyer/Wilkins bulk viscosity, and the element critical time
|
||||
//! increments.
|
||||
//! - **Integration** ([`integrate`]): the time loop, kinematic constraints, energy accounting
|
||||
//! with a balance check, history samples and field frames ([`result`]).
|
||||
//! - **Contact** ([`contact`]): penalty contact between element faces (pairs both ways, single
|
||||
//! surface and general contact) with Coulomb friction by a regularised return map, a bucket
|
||||
//! grid search, and the stiffness from the masses and the stable increment.
|
||||
//! - **Integration** ([`integrate`]): the time loop, kinematic constraints (rigid walls with
|
||||
//! friction), energy accounting with a balance check, history samples and field frames
|
||||
//! ([`result`]).
|
||||
//!
|
||||
//! With nonlinear geometry (the default) the elements are updated Lagrangian and the material
|
||||
//! state is integrated in rate form with an objective stress rate (Jaumann by Hughes–Winget,
|
||||
@@ -33,6 +37,7 @@
|
||||
// Small fixed-size vector kernels read as the textbook formulas with index loops.
|
||||
#![allow(clippy::needless_range_loop)]
|
||||
|
||||
pub mod contact;
|
||||
pub mod discrete;
|
||||
pub mod elements;
|
||||
pub mod integrate;
|
||||
@@ -41,7 +46,7 @@ pub mod system;
|
||||
|
||||
pub use elements::Failure;
|
||||
pub use integrate::solve_explicit;
|
||||
pub use result::{ControllingElement, Energies, ErodedElement, ExplicitResult, Frame, History};
|
||||
pub use result::{ContactSummary, ControllingElement, Energies, ErodedElement, ExplicitResult, Frame, History, MassScalingSummary};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
|
||||
pub enum Error {
|
||||
@@ -82,16 +87,24 @@ pub struct Limits {
|
||||
pub max_increments: u64,
|
||||
/// Numbers kept in field frames and histories together (8 bytes each).
|
||||
pub max_output_values: usize,
|
||||
/// Element faces of every contact surface together.
|
||||
pub max_contact_faces: usize,
|
||||
}
|
||||
|
||||
impl Limits {
|
||||
pub const MAX_DOFS: usize = 6_000_000;
|
||||
pub const MAX_INCREMENTS: u64 = fieldcraft_model::steps::MAX_INCREMENTS;
|
||||
pub const MAX_OUTPUT_VALUES: usize = 50_000_000;
|
||||
pub const MAX_CONTACT_FACES: usize = 10_000_000;
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> Limits {
|
||||
Limits { max_dofs: Limits::MAX_DOFS, max_increments: Limits::MAX_INCREMENTS, max_output_values: Limits::MAX_OUTPUT_VALUES }
|
||||
Limits {
|
||||
max_dofs: Limits::MAX_DOFS,
|
||||
max_increments: Limits::MAX_INCREMENTS,
|
||||
max_output_values: Limits::MAX_OUTPUT_VALUES,
|
||||
max_contact_faces: Limits::MAX_CONTACT_FACES,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,21 +22,36 @@ pub struct Energies {
|
||||
pub external: f64,
|
||||
/// Work of the boundary conditions and rigid walls on the model.
|
||||
pub constraint: f64,
|
||||
/// Energy taken by contact: the work the model does against the contact forces (the penalty
|
||||
/// energy stored in the contact springs, plus what friction dissipates there).
|
||||
pub contact: f64,
|
||||
/// The kinetic energy of the mass added by mass scaling (part of `kinetic`).
|
||||
pub added_kinetic: f64,
|
||||
/// Friction dissipation, in contact and on rigid walls (part of `contact` and of
|
||||
/// `constraint`).
|
||||
pub friction: f64,
|
||||
/// Plastic work: the part of `internal` dissipated by plastic flow.
|
||||
pub plastic: f64,
|
||||
/// Internal energy of the eroded elements when they eroded (part of `internal`).
|
||||
pub eroded: f64,
|
||||
/// kinetic + internal + hourglass + viscous − external − constraint − the initial kinetic
|
||||
/// energy: zero when energy is conserved.
|
||||
/// kinetic + internal + hourglass + viscous + contact − external − constraint − the initial
|
||||
/// kinetic energy: zero when energy is conserved.
|
||||
pub balance: f64,
|
||||
}
|
||||
|
||||
impl Energies {
|
||||
/// The balance relative to the largest energy in the account.
|
||||
pub fn relative_error(&self, initial_kinetic: f64) -> f64 {
|
||||
let scale = [initial_kinetic, self.kinetic, self.internal + self.hourglass + self.viscous, self.external.abs(), self.constraint.abs()]
|
||||
.into_iter()
|
||||
.fold(0.0, f64::max);
|
||||
let scale = [
|
||||
initial_kinetic,
|
||||
self.kinetic,
|
||||
self.internal + self.hourglass + self.viscous,
|
||||
self.external.abs(),
|
||||
self.constraint.abs(),
|
||||
self.contact.abs(),
|
||||
]
|
||||
.into_iter()
|
||||
.fold(0.0, f64::max);
|
||||
if scale > 0.0 { self.balance.abs() / scale } else { 0.0 }
|
||||
}
|
||||
}
|
||||
@@ -84,12 +99,46 @@ pub struct History {
|
||||
pub momentum: Vec<[f64; 3]>,
|
||||
/// Sum of the forces the boundary conditions and rigid walls exert on the model.
|
||||
pub constraint_force: Vec<[f64; 3]>,
|
||||
/// Per contact (in [`ExplicitResult::contacts`] order): the normal force across it (the sum
|
||||
/// of its constraints' normal forces).
|
||||
pub contact_force: Vec<Vec<f64>>,
|
||||
/// The nodes with histories, and per sample their displacement and velocity (in this order).
|
||||
pub nodes: Vec<u32>,
|
||||
pub displacement: Vec<Vec<[f64; 3]>>,
|
||||
pub velocity: Vec<Vec<[f64; 3]>>,
|
||||
}
|
||||
|
||||
/// What mass scaling added to a run.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
|
||||
pub struct MassScalingSummary {
|
||||
pub target_increment: f64,
|
||||
/// Elements whose density was raised.
|
||||
pub elements: usize,
|
||||
pub added_mass: f64,
|
||||
/// The added mass over the model's mass (with it).
|
||||
pub fraction: f64,
|
||||
/// The added mass per section, by name.
|
||||
pub sections: Vec<(String, f64)>,
|
||||
}
|
||||
|
||||
/// What a contact did over the run.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
|
||||
pub struct ContactSummary {
|
||||
pub name: String,
|
||||
/// Nodes moved onto the other surface before the analysis.
|
||||
pub adjusted: Vec<crate::contact::Adjustment>,
|
||||
/// The largest normal force across it, and when.
|
||||
pub peak_force: f64,
|
||||
pub peak_time: f64,
|
||||
/// The first and the last time it carried a force (none when it never did).
|
||||
pub first_contact: Option<f64>,
|
||||
pub last_contact: Option<f64>,
|
||||
/// The deepest penetration of a node into a face.
|
||||
pub max_penetration: f64,
|
||||
/// Friction dissipated in it.
|
||||
pub friction: f64,
|
||||
}
|
||||
|
||||
/// An element that limits the stable time increment.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
|
||||
pub struct ControllingElement {
|
||||
@@ -122,5 +171,9 @@ pub struct ExplicitResult {
|
||||
pub initial_kinetic: f64,
|
||||
/// Elements eroded during the run, in the order they eroded.
|
||||
pub eroded: Vec<ErodedElement>,
|
||||
/// Per contact of the model, in name order.
|
||||
pub contacts: Vec<ContactSummary>,
|
||||
/// What mass scaling added, when the step asks for it.
|
||||
pub mass_scaling: Option<MassScalingSummary>,
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
@@ -3,17 +3,19 @@
|
||||
//! ([`crate::discrete`]), prescribed velocities, rigid walls, initial velocities and the load
|
||||
//! vector of an explicit dynamic step.
|
||||
|
||||
use fieldcraft_fem::constitutive::MaterialModel;
|
||||
use fieldcraft_fem::material::Elasticity;
|
||||
use fieldcraft_fem::plasticity::J2;
|
||||
use fieldcraft_fem::uniform::{Hex8, Tet4, modulus_bound};
|
||||
use fieldcraft_fem::{DofKind, DofLayout, DofSet, face};
|
||||
use fieldcraft_model::{
|
||||
Elastic, ElementKind, ExplicitDynamic, HourglassKind, Integration, Load, Model, Resolved, SectionKind, Step, StressRate, Target,
|
||||
Elastic, ElementKind, ExplicitDynamic, Friction, HourglassKind, Integration, Load, Model, Resolved, SectionKind, Step, StressRate, Target,
|
||||
};
|
||||
|
||||
use crate::contact::Interface;
|
||||
use crate::discrete::{Discrete, Rod};
|
||||
use crate::elements::{HexScales, add_at, frequency_bound, hex_scales};
|
||||
use crate::{Error, Result};
|
||||
use crate::{Error, Limits, Result};
|
||||
|
||||
/// Degrees of freedom per node: the three translations, node-major (see [`System`]).
|
||||
pub const NODE_DOFS: usize = 3;
|
||||
@@ -37,6 +39,9 @@ pub struct Material {
|
||||
/// The hypoelastic(–plastic) update of an isotropic material; `None` for orthotropic
|
||||
/// elasticity, updated with [`Material::elasticity`].
|
||||
pub j2: Option<J2>,
|
||||
/// The finite-strain material point of a hyperelastic material (its stress from the
|
||||
/// deformation gradient; `None` for the rate-form materials).
|
||||
pub hyperelastic: Option<MaterialModel>,
|
||||
/// The equivalent plastic strain at which elements erode.
|
||||
pub erosion: Option<f64>,
|
||||
/// The (isotropic) expansion coefficient and reference temperature, when the material
|
||||
@@ -63,6 +68,8 @@ pub struct Hex {
|
||||
pub length: f64,
|
||||
/// The rate of its thermal strain, α ΔT / end time (every normal direction).
|
||||
pub thermal_rate: f64,
|
||||
/// Its density's factor from mass scaling (1 without).
|
||||
pub mass_factor: f64,
|
||||
}
|
||||
|
||||
/// A nodal-pressure tetrahedron.
|
||||
@@ -79,15 +86,18 @@ pub struct Tet {
|
||||
pub length: f64,
|
||||
/// The rate of its thermal strain, α ΔT / end time (every normal direction).
|
||||
pub thermal_rate: f64,
|
||||
/// Its density's factor from mass scaling (1 without).
|
||||
pub mass_factor: f64,
|
||||
}
|
||||
|
||||
/// A fixed, frictionless rigid plane.
|
||||
/// A fixed rigid plane.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Wall {
|
||||
pub point: [f64; 3],
|
||||
/// Unit normal, towards the side the nodes stay on.
|
||||
pub normal: [f64; 3],
|
||||
pub nodes: Vec<usize>,
|
||||
pub friction: Friction,
|
||||
}
|
||||
|
||||
/// The discrete system of an explicit dynamic step.
|
||||
@@ -114,9 +124,14 @@ pub struct System {
|
||||
/// The springs' and dashpots' stable increment on the lumped mass, and a link that sets it,
|
||||
/// when there are any.
|
||||
pub discrete_increment: Option<(f64, String)>,
|
||||
/// What mass scaling added: per node, and per section (in name order).
|
||||
pub added_mass: Vec<f64>,
|
||||
pub mass_scaling: Option<crate::result::MassScalingSummary>,
|
||||
/// Prescribed velocity per degree of freedom (`None` = free).
|
||||
pub prescribed: Vec<Option<f64>>,
|
||||
pub walls: Vec<Wall>,
|
||||
/// The model's contacts ([`crate::contact`]).
|
||||
pub contacts: Vec<Interface>,
|
||||
/// Velocity per degree of freedom at the start (prescribed velocities included).
|
||||
pub initial_velocity: Vec<f64>,
|
||||
/// Constant external force per degree of freedom.
|
||||
@@ -139,9 +154,6 @@ fn invalid(m: impl Into<String>) -> Error {
|
||||
fn material(model: &Model, name: &str) -> Result<Material> {
|
||||
let m = model.material(name).ok_or_else(|| invalid(format!("material `{name}` is missing")))?;
|
||||
let elastic = m.elastic.as_ref().ok_or_else(|| invalid(format!("material `{name}` has no elastic constants")))?;
|
||||
if let Some(h) = m.hyperelastic {
|
||||
return Err(Error::NotSupported(format!("{} hyperelastic material `{name}` in explicit dynamics", h.name())));
|
||||
}
|
||||
let density = m
|
||||
.density
|
||||
.filter(|d| *d > 0.0 && d.is_finite())
|
||||
@@ -170,6 +182,12 @@ fn material(model: &Model, name: &str) -> Result<Material> {
|
||||
stiffest,
|
||||
j2,
|
||||
erosion: m.erosion.map(|e| e.plastic_strain),
|
||||
hyperelastic: m
|
||||
.hyperelastic
|
||||
.as_ref()
|
||||
.map(|h| MaterialModel::from_model(elastic, Some(h)))
|
||||
.transpose()
|
||||
.map_err(|e| invalid(format!("material `{name}`: {e}")))?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -192,10 +210,12 @@ fn check_formulation(kind: ElementKind, section_name: &str, f: &fieldcraft_model
|
||||
}
|
||||
|
||||
impl System {
|
||||
pub fn new(model: &Model, resolved: &Resolved, step: &Step, settings: &ExplicitDynamic, max_dofs: usize) -> Result<System> {
|
||||
pub fn new(model: &Model, resolved: &Resolved, step: &Step, settings: &ExplicitDynamic, limits: &Limits) -> Result<System> {
|
||||
let max_dofs = limits.max_dofs;
|
||||
if let Some(name) = model.couplings().keys().next() {
|
||||
return Err(Error::NotSupported(format!("couplings (coupling `{name}`) in explicit dynamics")));
|
||||
}
|
||||
|
||||
// Elements by label, with their section's material.
|
||||
let mut materials: Vec<Material> = Vec::new();
|
||||
let mut chosen: Vec<(u32, ElementKind, Vec<u32>, usize, Option<f64>)> = Vec::new();
|
||||
@@ -264,10 +284,13 @@ impl System {
|
||||
tets: Vec::new(),
|
||||
rods: Vec::new(),
|
||||
mass: vec![0.0; n],
|
||||
added_mass: Vec::new(),
|
||||
mass_scaling: None,
|
||||
discrete: Discrete::default(),
|
||||
discrete_increment: None,
|
||||
prescribed: vec![None; dofs],
|
||||
walls: Vec::new(),
|
||||
contacts: Vec::new(),
|
||||
initial_velocity: vec![0.0; dofs],
|
||||
external: vec![0.0; dofs],
|
||||
history_nodes: Vec::new(),
|
||||
@@ -279,6 +302,20 @@ impl System {
|
||||
labels,
|
||||
xyz,
|
||||
};
|
||||
// Contact first: nodes that start inside a surface are moved before the elements are
|
||||
// built on the coordinates.
|
||||
sys.contacts = crate::contact::interfaces(model, resolved, &mut sys.xyz, &sys.labels, &sys.elements, limits.max_contact_faces)?;
|
||||
for c in &sys.contacts {
|
||||
if let Some(deepest) = c.adjusted.iter().max_by(|a, b| a.depth.total_cmp(&b.depth)) {
|
||||
sys.warnings.push(format!(
|
||||
"contact `{}`: {} nodes started inside the other surface and were moved onto it (the deepest, node {}, by {:.3e})",
|
||||
c.name,
|
||||
c.adjusted.len(),
|
||||
deepest.node,
|
||||
deepest.depth
|
||||
));
|
||||
}
|
||||
}
|
||||
for (index, (label, kind, nodes, mi, area)) in chosen.into_iter().enumerate() {
|
||||
let idx: Vec<usize> = nodes.iter().map(|l| sys.node(*l).ok_or_else(|| Error::Internal(format!("node {l}")))).collect::<Result<_>>()?;
|
||||
let mat = sys.materials.get(mi).ok_or_else(|| Error::Internal("material index".into()))?;
|
||||
@@ -294,7 +331,19 @@ impl System {
|
||||
let rest = hex_scales(&k, &gamma, &mass, mat, rho, settings.hourglass);
|
||||
sys.lump(&nodes, &mass);
|
||||
let length = 2.0 * c / rest.omega2.sqrt();
|
||||
sys.hexes.push(Hex { label, index, nodes, material: mi, kinematics: k, gamma, mass, rest, length, thermal_rate: 0.0 });
|
||||
sys.hexes.push(Hex {
|
||||
label,
|
||||
index,
|
||||
nodes,
|
||||
material: mi,
|
||||
kinematics: k,
|
||||
gamma,
|
||||
mass,
|
||||
rest,
|
||||
length,
|
||||
thermal_rate: 0.0,
|
||||
mass_factor: 1.0,
|
||||
});
|
||||
}
|
||||
ElementKind::Tet4 => {
|
||||
let nodes: [usize; 4] = idx.try_into().map_err(|_| invalid(format!("element {label} does not have 4 nodes")))?;
|
||||
@@ -313,6 +362,7 @@ impl System {
|
||||
omega2,
|
||||
length: 2.0 * c / omega2.sqrt(),
|
||||
thermal_rate: 0.0,
|
||||
mass_factor: 1.0,
|
||||
});
|
||||
}
|
||||
ElementKind::Rod2 | ElementKind::Rod3 => {
|
||||
@@ -341,15 +391,126 @@ impl System {
|
||||
other => return Err(Error::Internal(format!("{} element kind", other.name()))),
|
||||
}
|
||||
}
|
||||
if let Some(scaling) = &settings.mass_scaling {
|
||||
sys.scale_mass(model, resolved, scaling, settings)?;
|
||||
}
|
||||
sys.discrete = Discrete::new(resolved, sys.dofs(), &sys.xyz, |l| sys.node(l))?;
|
||||
sys.discrete_increment = sys.discrete.critical_increment(&sys.dof_mass(), sys.nonlinear);
|
||||
sys.prescribe(model, resolved, step, settings.end_time)?;
|
||||
sys.load(model, resolved, step)?;
|
||||
sys.temperatures(model, resolved, step, settings.end_time)?;
|
||||
sys.conditions(resolved, settings)?;
|
||||
sys.check_hyperelastic()?;
|
||||
Ok(sys)
|
||||
}
|
||||
|
||||
/// Mass scaling to a target increment (see [`fieldcraft_model::MassScaling`]): each solid
|
||||
/// element (of the set) whose stable increment times the step's scale is below the target
|
||||
/// gets its density times (target / increment)², its lumped masses and frequency bound with
|
||||
/// it; the added mass is kept per node and per section.
|
||||
fn scale_mass(&mut self, model: &Model, resolved: &Resolved, scaling: &fieldcraft_model::MassScaling, settings: &ExplicitDynamic) -> Result<()> {
|
||||
let chosen: Option<&[u32]> = match &scaling.set {
|
||||
Some(s) => Some(resolved.sets.get(s).map(|r| r.elements.as_slice()).ok_or_else(|| invalid(format!("set `{s}` is not resolved")))?),
|
||||
None => None,
|
||||
};
|
||||
let wanted = |label: u32| chosen.is_none_or(|l| l.binary_search(&label).is_ok());
|
||||
let factor = |length: f64, material: usize, materials: &[Material]| -> f64 {
|
||||
let c = materials.get(material).map_or(f64::INFINITY, |m| m.wave_speed);
|
||||
let dt = settings.dt_scale * length / c;
|
||||
if dt > 0.0 && dt < scaling.target_increment { (scaling.target_increment / dt).powi(2) } else { 1.0 }
|
||||
};
|
||||
let hourglass = fieldcraft_model::Hourglass { kind: settings.hourglass.kind, coefficient: settings.hourglass.coefficient };
|
||||
let mut added = vec![0.0; self.labels.len()];
|
||||
let mut by_element: Vec<(u32, f64)> = Vec::new();
|
||||
for h in self.hexes.iter_mut().filter(|h| wanted(h.label)) {
|
||||
let f = factor(h.length, h.material, &self.materials);
|
||||
if f == 1.0 {
|
||||
continue;
|
||||
}
|
||||
let extra = h.mass.map(|m| m * (f - 1.0));
|
||||
for (n, x) in h.nodes.iter().zip(extra) {
|
||||
if let Some(a) = added.get_mut(*n) {
|
||||
*a += x;
|
||||
}
|
||||
}
|
||||
h.mass = h.mass.map(|m| m * f);
|
||||
h.mass_factor = f;
|
||||
if let Some(mat) = self.materials.get(h.material) {
|
||||
h.rest = hex_scales(&h.kinematics, &h.gamma, &h.mass, mat, mat.density * f, hourglass);
|
||||
}
|
||||
by_element.push((h.label, extra.iter().sum()));
|
||||
}
|
||||
for t in self.tets.iter_mut().filter(|t| wanted(t.label)) {
|
||||
let f = factor(t.length, t.material, &self.materials);
|
||||
if f == 1.0 {
|
||||
continue;
|
||||
}
|
||||
let extra = t.mass.map(|m| m * (f - 1.0));
|
||||
for (n, x) in t.nodes.iter().zip(extra) {
|
||||
if let Some(a) = added.get_mut(*n) {
|
||||
*a += x;
|
||||
}
|
||||
}
|
||||
t.mass = t.mass.map(|m| m * f);
|
||||
t.omega2 /= f;
|
||||
t.mass_factor = f;
|
||||
by_element.push((t.label, extra.iter().sum()));
|
||||
}
|
||||
for (m, a) in self.mass.iter_mut().zip(&added) {
|
||||
*m += a;
|
||||
}
|
||||
let total_added: f64 = added.iter().sum();
|
||||
let total: f64 = self.mass.iter().sum();
|
||||
let mut sections: Vec<(String, f64)> = Vec::new();
|
||||
for (name, section) in model.sections() {
|
||||
let elements = resolved.sets.get(§ion.set).map(|r| r.elements.as_slice()).unwrap_or_default();
|
||||
let mass: f64 = by_element.iter().filter(|(l, _)| elements.binary_search(l).is_ok()).map(|(_, m)| m).sum();
|
||||
if mass > 0.0 {
|
||||
sections.push((name.clone(), mass));
|
||||
}
|
||||
}
|
||||
if total_added > 0.0 {
|
||||
self.warnings.push(format!(
|
||||
"mass scaling to an increment of {:.3e} added {total_added:.4e} of mass ({:.2}% of the model's) to {} elements",
|
||||
scaling.target_increment,
|
||||
100.0 * total_added / total.max(f64::MIN_POSITIVE),
|
||||
by_element.len()
|
||||
));
|
||||
}
|
||||
self.mass_scaling = Some(crate::result::MassScalingSummary {
|
||||
target_increment: scaling.target_increment,
|
||||
elements: by_element.len(),
|
||||
added_mass: total_added,
|
||||
fraction: total_added / total.max(f64::MIN_POSITIVE),
|
||||
sections,
|
||||
});
|
||||
self.added_mass = added;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Refuse what hyperelastic elements cannot take yet: small-displacement steps (the
|
||||
/// material is a finite-strain law) and thermal strain.
|
||||
fn check_hyperelastic(&self) -> Result<()> {
|
||||
let solids =
|
||||
self.hexes.iter().map(|h| (h.label, h.material, h.thermal_rate)).chain(self.tets.iter().map(|t| (t.label, t.material, t.thermal_rate)));
|
||||
for (label, material, thermal) in solids {
|
||||
let Some(m) = self.materials.get(material).filter(|m| m.hyperelastic.is_some()) else { continue };
|
||||
if !self.nonlinear {
|
||||
return Err(Error::NotSupported(format!(
|
||||
"hyperelastic material `{}` (element {label}) without nonlinear geometry; hyperelastic laws are finite-strain, set the step's nonlinear_geometry to true",
|
||||
m.name
|
||||
)));
|
||||
}
|
||||
if thermal != 0.0 {
|
||||
return Err(Error::NotSupported(format!(
|
||||
"thermal strain in hyperelastic material `{}` (element {label}) in explicit dynamics",
|
||||
m.name
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Add an element's row-sum lumped masses.
|
||||
fn lump(&mut self, nodes: &[usize], mass: &[f64]) {
|
||||
for (node, v) in nodes.iter().zip(mass) {
|
||||
@@ -584,7 +745,7 @@ impl System {
|
||||
return Err(invalid(format!("node {label} of set `{}` starts behind its rigid wall (gap {gap:e})", w.set)));
|
||||
}
|
||||
}
|
||||
self.walls.push(Wall { point: w.point, normal, nodes });
|
||||
self.walls.push(Wall { point: w.point, normal, nodes, friction: w.friction });
|
||||
}
|
||||
if let Some(set) = &settings.history_nodes {
|
||||
let nodes = self.nodes_of(resolved, set);
|
||||
|
||||
@@ -0,0 +1,707 @@
|
||||
//! Deformable contact and friction in explicit dynamics against closed-form solutions:
|
||||
//! - two identical elastic bars colliding exchange their velocities after a contact of 2L/c, with
|
||||
//! the interface force ρ c A v₀/2 (one-dimensional wave theory: K. F. Graff, *Wave Motion in
|
||||
//! Elastic Solids*, Dover 1991, §2.1–2.3; W. Johnson, *Impact Strength of Materials*, Arnold
|
||||
//! 1972, §1.6), and keep their energy (frictionless elastic impact);
|
||||
//! - a block sliding on a plane with Coulomb friction decelerates at μg and stops after
|
||||
//! v₀²/(2μg), on a rigid wall and on a deformable plate (any dynamics text, e.g. J. L. Meriam,
|
||||
//! L. G. Kraige, *Engineering Mechanics: Dynamics*, §3/5), and with the exponential decay law
|
||||
//! after the distance the decaying coefficient gives;
|
||||
//! - two elastic spheres colliding: Hertz's contact duration and peak force (H. Hertz, *Über die
|
||||
//! Berührung fester elastischer Körper*, J. reine angew. Math. 92:156–171, 1882; K. L. Johnson,
|
||||
//! *Contact Mechanics*, Cambridge 1985, §11.4);
|
||||
//! - a contact patch test: two blocks with non-matching meshes pressed together carry a uniform
|
||||
//! stress across the interface (R. L. Taylor, P. Papadopoulos, *On a patch test for contact
|
||||
//! problems in two dimensions*, in Nonlinear Computational Mechanics, Springer 1991, 690–702;
|
||||
//! T. Y. Crisfield-style uniform-pressure form for three dimensions);
|
||||
//! - and what a contact must never do: hold back a body in free flight, depend on the thread
|
||||
//! count, or crash on hostile input.
|
||||
|
||||
use fieldcraft_explicit::{ExplicitResult, Limits, solve_explicit};
|
||||
use fieldcraft_model::*;
|
||||
|
||||
/// A model built block by block, each block of hex8 with its own nodes.
|
||||
struct Mesh {
|
||||
model: Model,
|
||||
next_node: u32,
|
||||
next_element: u32,
|
||||
}
|
||||
|
||||
impl Mesh {
|
||||
fn new() -> Mesh {
|
||||
Mesh { model: Model::default(), next_node: 1, next_element: 1 }
|
||||
}
|
||||
|
||||
/// A box from `origin` of `size` with `n` hex8 along each axis, positions mapped by `map`;
|
||||
/// its elements.
|
||||
fn block_mapped(&mut self, origin: [f64; 3], size: [f64; 3], n: [usize; 3], map: impl Fn([f64; 3]) -> [f64; 3]) -> Vec<u32> {
|
||||
let base = self.next_node;
|
||||
let at = |i: usize, j: usize, k: usize| base + (i + (n[0] + 1) * (j + (n[1] + 1) * k)) as u32;
|
||||
for k in 0..=n[2] {
|
||||
for j in 0..=n[1] {
|
||||
for i in 0..=n[0] {
|
||||
let x = [0, 1, 2].map(|d| origin[d] + size[d] * [i, j, k][d] as f64 / n[d] as f64);
|
||||
self.model.set_node(at(i, j, k), map(x)).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
self.next_node = at(n[0], n[1], n[2]) + 1;
|
||||
let mut out = Vec::new();
|
||||
for k in 0..n[2] {
|
||||
for j in 0..n[1] {
|
||||
for i in 0..n[0] {
|
||||
let nodes = vec![
|
||||
at(i, j, k),
|
||||
at(i + 1, j, k),
|
||||
at(i + 1, j + 1, k),
|
||||
at(i, j + 1, k),
|
||||
at(i, j, k + 1),
|
||||
at(i + 1, j, k + 1),
|
||||
at(i + 1, j + 1, k + 1),
|
||||
at(i, j + 1, k + 1),
|
||||
];
|
||||
self.model.set_element(self.next_element, ElementKind::Hex8, nodes).unwrap();
|
||||
out.push(self.next_element);
|
||||
self.next_element += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn block(&mut self, origin: [f64; 3], size: [f64; 3], n: [usize; 3]) -> Vec<u32> {
|
||||
self.block_mapped(origin, size, n, |x| x)
|
||||
}
|
||||
|
||||
fn xyz(&self, node: u32) -> [f64; 3] {
|
||||
self.model.node(node).unwrap().xyz
|
||||
}
|
||||
|
||||
/// The faces of `elements` whose centre satisfies `f`.
|
||||
fn faces_where(&self, elements: &[u32], f: impl Fn([f64; 3]) -> bool) -> Vec<ElementFace> {
|
||||
let mut out = Vec::new();
|
||||
for &e in elements {
|
||||
let el = self.model.element(e).unwrap();
|
||||
for (i, local) in el.kind.faces().iter().enumerate() {
|
||||
let c = [0, 1, 2].map(|d| local.iter().map(|n| self.xyz(el.nodes[*n])[d]).sum::<f64>() / local.len() as f64);
|
||||
if f(c) {
|
||||
out.push(ElementFace { element: e, face: i as u8 + 1 });
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn nodes_where(&self, elements: &[u32], f: impl Fn([f64; 3]) -> bool) -> Vec<u32> {
|
||||
let mut out: Vec<u32> = elements.iter().flat_map(|e| self.model.element(*e).unwrap().nodes.clone()).filter(|n| f(self.xyz(*n))).collect();
|
||||
out.sort_unstable();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
|
||||
fn material(&mut self, name: &str, young: f64, poisson: f64, density: f64) {
|
||||
let m = Material { elastic: Some(Elastic::Isotropic { young, poisson }), density: Some(density), ..Material::default() };
|
||||
self.model.add_material(name, m).unwrap();
|
||||
}
|
||||
|
||||
/// A solid section of one-point hex8 of `material` on `elements`, under the set `name`.
|
||||
fn section(&mut self, name: &str, elements: &[u32], material: &str) {
|
||||
self.model.add_set(name, Set { elements: elements.to_vec(), ..Set::default() }).unwrap();
|
||||
let formulation = Formulation { integration: Integration::Reduced, ..Formulation::default() };
|
||||
self.model.add_section(name, Section { set: name.into(), material: material.into(), kind: SectionKind::Solid {}, formulation }).unwrap();
|
||||
}
|
||||
|
||||
fn face_set(&mut self, name: &str, faces: Vec<ElementFace>) {
|
||||
assert!(!faces.is_empty(), "{name}");
|
||||
self.model.add_set(name, Set { faces, ..Set::default() }).unwrap();
|
||||
}
|
||||
|
||||
fn node_set(&mut self, name: &str, nodes: Vec<u32>) {
|
||||
assert!(!nodes.is_empty(), "{name}");
|
||||
self.model.add_set(name, Set { nodes, ..Set::default() }).unwrap();
|
||||
}
|
||||
|
||||
fn pair(&mut self, name: &str, main: &str, secondary: &str, friction: Friction) {
|
||||
let c = Contact { friction, ..Contact::new(ContactSurfaces::Pair { main: main.into(), secondary: secondary.into() }) };
|
||||
self.model.add_contact(name, c).unwrap();
|
||||
}
|
||||
|
||||
fn step(&mut self, step: ExplicitDynamic, bcs: &[(&str, BoundaryCondition)], loads: &[(&str, Load)]) {
|
||||
let mut s = Step::new("Run", Procedure::ExplicitDynamic(step));
|
||||
for (name, bc) in bcs {
|
||||
self.model.add_boundary_condition(name, bc.clone()).unwrap();
|
||||
s.boundary_conditions.insert(name.to_string());
|
||||
}
|
||||
for (name, load) in loads {
|
||||
self.model.add_load(name, load.clone()).unwrap();
|
||||
s.loads.insert(name.to_string());
|
||||
}
|
||||
self.model.add_step(s, None).unwrap();
|
||||
}
|
||||
|
||||
fn solve(&self) -> ExplicitResult {
|
||||
let r = solve_explicit(&self.model, Some("Run"), &Limits::default()).unwrap();
|
||||
assert!(r.completed, "{:?}", r.warnings);
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
fn node_index(r: &ExplicitResult, label: u32) -> usize {
|
||||
r.nodes.binary_search(&label).unwrap()
|
||||
}
|
||||
|
||||
/// The mean velocity of some nodes in the last frame.
|
||||
fn mean_velocity(r: &ExplicitResult, nodes: &[u32]) -> [f64; 3] {
|
||||
let f = r.frames.last().unwrap();
|
||||
let mut v = [0.0; 3];
|
||||
for n in nodes {
|
||||
let x = f.velocity[node_index(r, *n)];
|
||||
for k in 0..3 {
|
||||
v[k] += x[k] / nodes.len() as f64;
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
const BAR_E: f64 = 1.0e4;
|
||||
const BAR_RHO: f64 = 1.0;
|
||||
const BAR_L: f64 = 10.0;
|
||||
const BAR_W: f64 = 0.1;
|
||||
|
||||
/// Two bars of `cells` hex8, the first moving at v₀ along x into the second at rest (touching
|
||||
/// end to end, separate nodes), with `contact` between their ends: (mesh, bar A, bar B).
|
||||
fn bars(cells: usize, v0: f64, end: f64, contact: impl FnOnce(&mut Mesh, Vec<ElementFace>, Vec<ElementFace>)) -> (Mesh, Vec<u32>, Vec<u32>) {
|
||||
let mut m = Mesh::new();
|
||||
let a = m.block([0.0; 3], [BAR_L, BAR_W, BAR_W], [cells, 1, 1]);
|
||||
let b = m.block([BAR_L, 0.0, 0.0], [BAR_L, BAR_W, BAR_W], [cells, 1, 1]);
|
||||
m.material("Mat", BAR_E, 0.0, BAR_RHO);
|
||||
m.section("A", &a, "Mat");
|
||||
m.section("B", &b, "Mat");
|
||||
let end_a = m.faces_where(&a, |c| (c[0] - BAR_L).abs() < 1e-9);
|
||||
let start_b = m.faces_where(&b, |c| (c[0] - BAR_L).abs() < 1e-9);
|
||||
contact(&mut m, end_a, start_b);
|
||||
let mut step = ExplicitDynamic::new(end);
|
||||
step.initial_velocities = vec![InitialVelocity { set: "A".into(), velocity: [v0, 0.0, 0.0] }];
|
||||
// The elastic solution: no linear bulk viscosity (it dissipates at the wave fronts).
|
||||
step.bulk_viscosity = BulkViscosity { linear: 0.0, quadratic: 1.5 };
|
||||
step.history_interval = Some(end / 4000.0);
|
||||
m.step(step, &[], &[]);
|
||||
(m, a, b)
|
||||
}
|
||||
|
||||
/// Velocity exchange, contact duration 2L/c, interface force ρ c A v₀ / 2 and the energy of a
|
||||
/// frictionless elastic impact, for a pair (both ways) and for general contact.
|
||||
#[test]
|
||||
fn colliding_bars_exchange_their_velocities() {
|
||||
let c = (BAR_E / BAR_RHO).sqrt();
|
||||
let v0 = 0.1;
|
||||
let duration = 2.0 * BAR_L / c;
|
||||
for kind in ["pair", "general"] {
|
||||
let (m, a, b) = bars(200, v0, 1.5 * duration, |m, end_a, start_b| match kind {
|
||||
"pair" => {
|
||||
m.face_set("end_a", end_a);
|
||||
m.face_set("start_b", start_b);
|
||||
m.pair("impact", "start_b", "end_a", Friction::NONE);
|
||||
}
|
||||
_ => m.model.add_contact("everything", Contact::new(ContactSurfaces::General { surface: None })).unwrap(),
|
||||
});
|
||||
let r = m.solve();
|
||||
let s = &r.contacts[0];
|
||||
let (first, last) = (s.first_contact.unwrap(), s.last_contact.unwrap());
|
||||
let plateau = BAR_RHO * c * BAR_W * BAR_W * v0 / 2.0;
|
||||
let va = mean_velocity(&r, &m.nodes_where(&a, |_| true))[0];
|
||||
let vb = mean_velocity(&r, &m.nodes_where(&b, |_| true))[0];
|
||||
let ke = r.energy.kinetic / r.initial_kinetic;
|
||||
// The force across the interface while the waves cross the bars.
|
||||
let mid: Vec<f64> = r
|
||||
.history
|
||||
.time
|
||||
.iter()
|
||||
.zip(&r.history.contact_force)
|
||||
.filter(|(t, _)| **t > 0.2 * duration && **t < 0.8 * duration)
|
||||
.map(|(_, f)| f[0])
|
||||
.collect();
|
||||
let mean_force = mid.iter().sum::<f64>() / mid.len() as f64;
|
||||
eprintln!(
|
||||
"{kind}: contact {first:.5}..{last:.5} ({:.5}) vs 2L/c = {duration:.5}; force {mean_force:.5e} (peak {:.5e}) vs ρcAv₀/2 = {plateau:.5e}; v_A {va:.5} v_B {vb:.5} vs 0, {v0}; KE/KE₀ {ke:.5}; contact energy {:.3e} of KE₀ {:.3e}; balance {:.2e}; max penetration {:.3e}; {} increments",
|
||||
last - first,
|
||||
s.peak_force,
|
||||
r.energy.contact,
|
||||
r.initial_kinetic,
|
||||
r.energy.relative_error(r.initial_kinetic),
|
||||
s.max_penetration,
|
||||
r.increments
|
||||
);
|
||||
assert!(first < 0.01 * duration, "{kind}: contact from the start, not {first}");
|
||||
assert!(((last - first) - duration).abs() < 0.015 * duration, "{kind}: contact for {} vs {duration}", last - first);
|
||||
assert!((mean_force - plateau).abs() < 0.02 * plateau, "{kind}: {mean_force} vs {plateau}");
|
||||
assert!(va.abs() < 0.02 * v0 && (vb - v0).abs() < 0.02 * v0, "{kind}: {va} {vb}");
|
||||
assert!(ke > 0.97 && ke <= 1.0 + 1e-6, "{kind}: KE ratio {ke}");
|
||||
// After the separation the contact springs are empty again: what they took they gave back.
|
||||
assert!(r.energy.contact.abs() < 0.005 * r.initial_kinetic, "{kind}: {:?}", r.energy);
|
||||
assert!(r.energy.relative_error(r.initial_kinetic) < 0.005, "{kind}: {:?}", r.energy);
|
||||
assert!(s.max_penetration < 0.01 * BAR_L / 200.0 * 10.0, "{kind}: penetration {}", s.max_penetration);
|
||||
assert_eq!(r.energy.friction, 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A body in free flight with general contact on all its faces feels no contact force (no node
|
||||
/// grabs a face of its own body), and its motion is that of the same run without contact.
|
||||
#[test]
|
||||
fn general_contact_leaves_a_free_body_alone() {
|
||||
let run = |contact: bool| {
|
||||
let mut m = Mesh::new();
|
||||
let e = m.block([0.0; 3], [1.0, 0.6, 0.4], [5, 3, 2]);
|
||||
m.material("Mat", 1e4, 0.3, 1.0);
|
||||
m.section("all", &e, "Mat");
|
||||
if contact {
|
||||
m.model.add_contact("all", Contact::new(ContactSurfaces::General { surface: None })).unwrap();
|
||||
}
|
||||
let mut step = ExplicitDynamic::new(0.05);
|
||||
step.initial_velocities = vec![InitialVelocity { set: "all".into(), velocity: [1.0, -0.5, 0.2] }];
|
||||
m.step(step, &[], &[]);
|
||||
m.solve()
|
||||
};
|
||||
let (with, without) = (run(true), run(false));
|
||||
assert!(with.history.contact_force.iter().all(|f| f[0] == 0.0));
|
||||
assert_eq!(with.contacts[0].first_contact, None);
|
||||
assert_eq!(with.frames.last().unwrap().displacement, without.frames.last().unwrap().displacement);
|
||||
assert_eq!(with.energy.contact, 0.0);
|
||||
}
|
||||
|
||||
/// What kind of plane a block slides on.
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
enum Plane {
|
||||
RigidWall,
|
||||
/// A plate fixed at its base, in contact with the block.
|
||||
Plate,
|
||||
}
|
||||
|
||||
/// A block (1 × 1 × 0.5, 4 × 4 × 2 hex8) launched along x at v₀ on a horizontal plane under
|
||||
/// gravity g with `friction`: the distance its centre of mass travels and the time it stops.
|
||||
fn slide(plane: Plane, friction: Friction, v0: f64, g: f64, end: f64) -> (f64, f64, ExplicitResult) {
|
||||
let mut m = Mesh::new();
|
||||
let block = m.block([0.0, 0.0, 0.0], [1.0, 1.0, 0.5], [4, 4, 2]);
|
||||
m.material("Mat", 1.0e5, 0.3, 1.0);
|
||||
m.section("block", &block, "Mat");
|
||||
let bottom = m.nodes_where(&block, |x| x[2].abs() < 1e-9);
|
||||
let mut step = ExplicitDynamic::new(end);
|
||||
step.initial_velocities = vec![InitialVelocity { set: "block".into(), velocity: [v0, 0.0, 0.0] }];
|
||||
step.history_interval = Some(end / 2000.0);
|
||||
let mut bcs = Vec::new();
|
||||
match plane {
|
||||
Plane::RigidWall => {
|
||||
m.node_set("bottom", bottom);
|
||||
step.rigid_walls = vec![RigidWall { set: "bottom".into(), point: [0.0; 3], normal: [0.0, 0.0, 1.0], friction }];
|
||||
}
|
||||
Plane::Plate => {
|
||||
let plate = m.block([-0.5, -0.5, -0.5], [4.5, 2.0, 0.5], [9, 4, 1]);
|
||||
m.section("plate", &plate, "Mat");
|
||||
let top = m.faces_where(&plate, |c| c[2].abs() < 1e-9);
|
||||
let under = m.faces_where(&block, |c| c[2].abs() < 1e-9);
|
||||
m.face_set("top", top);
|
||||
m.face_set("under", under);
|
||||
m.pair("slide", "top", "under", friction);
|
||||
m.node_set("base", m.nodes_where(&plate, |x| (x[2] + 0.5).abs() < 1e-9));
|
||||
bcs.push(("hold", BoundaryCondition::Fixed { target: Target::Set("base".into()) }));
|
||||
}
|
||||
}
|
||||
let gravity = Load::Gravity { acceleration: [0.0, 0.0, -g], set: Some("block".into()) };
|
||||
m.step(step, &bcs, &[("weight", gravity)]);
|
||||
let r = m.solve();
|
||||
let nodes = m.nodes_where(&block, |_| true);
|
||||
let f = r.frames.last().unwrap();
|
||||
let distance = nodes.iter().map(|n| f.displacement[node_index(&r, *n)][0]).sum::<f64>() / nodes.len() as f64;
|
||||
// The block's momentum per mass (the plate's is nothing along x when it is held).
|
||||
let mass = match plane {
|
||||
Plane::RigidWall => r.total_mass,
|
||||
Plane::Plate => 0.5,
|
||||
};
|
||||
let stop = r.history.time.iter().zip(&r.history.momentum).find(|(_, p)| p[0] / mass < 0.005 * v0).map_or(f64::NAN, |(t, _)| *t);
|
||||
(distance, stop, r)
|
||||
}
|
||||
|
||||
/// Coulomb friction μ: deceleration μg, stopping after v₀/(μg) at v₀²/(2μg); on a rigid wall
|
||||
/// (kinematic friction impulses) and on a deformable plate (penalty contact, return map).
|
||||
#[test]
|
||||
fn a_block_slides_to_a_stop_under_coulomb_friction() {
|
||||
let (v0, g, mu) = (3.0, 10.0, 0.3);
|
||||
let (t_stop, d_stop) = (v0 / (mu * g), v0 * v0 / (2.0 * mu * g));
|
||||
for plane in [Plane::RigidWall, Plane::Plate] {
|
||||
let (d, t, r) = slide(plane, Friction::coulomb(mu), v0, g, 1.3 * t_stop);
|
||||
eprintln!(
|
||||
"{plane:?}: stops at {t:.4} vs v₀/(μg) = {t_stop:.4}, after {d:.4} vs v₀²/(2μg) = {d_stop:.4}; friction dissipated {:.4} vs ½mv₀² = {:.4}; balance {:.2e}; {} increments",
|
||||
r.energy.friction,
|
||||
0.5 * 0.5 * v0 * v0,
|
||||
r.energy.relative_error(r.initial_kinetic),
|
||||
r.increments
|
||||
);
|
||||
assert!((t - t_stop).abs() < 0.02 * t_stop, "{plane:?}: {t} vs {t_stop}");
|
||||
assert!((d - d_stop).abs() < 0.02 * d_stop, "{plane:?}: {d} vs {d_stop}");
|
||||
// The kinetic energy went into friction (and a little into the bouncing on the plane).
|
||||
let ke0 = 0.5 * 0.5 * v0 * v0;
|
||||
assert!((r.energy.friction - ke0).abs() < 0.03 * ke0, "{plane:?}: {:?}", r.energy);
|
||||
assert!(r.energy.relative_error(r.initial_kinetic) < 0.01, "{plane:?}: {:?}", r.energy);
|
||||
}
|
||||
}
|
||||
|
||||
/// The exponential decay law μ(v) = μ_k + (μ_s − μ_k) e^{−d v}: the block decelerates at
|
||||
/// g μ(v), so it stops after t = ∫ dv / (g μ(v)) = [v₀ + ln((μ_k + Δμ e^{−d v₀}) / μ_s) / d] / (g μ_k)
|
||||
/// and travels ∫ v dv / (g μ(v)) (by quadrature).
|
||||
#[test]
|
||||
fn a_block_slides_with_a_decaying_friction_coefficient() {
|
||||
let (v0, g) = (3.0, 10.0);
|
||||
let f = Friction { static_coefficient: 0.5, kinetic: Some(0.2), decay: 1.5 };
|
||||
let (a, b, d): (f64, f64, f64) = (0.2, 0.3, 1.5);
|
||||
let t_stop = (v0 + ((a + b * (-d * v0).exp()) / (a + b)).ln() / d) / (g * a);
|
||||
let n = 20_000;
|
||||
let d_stop: f64 = (0..n)
|
||||
.map(|i| {
|
||||
let v = (i as f64 + 0.5) * v0 / n as f64;
|
||||
v / (g * f.coefficient(v)) * v0 / n as f64
|
||||
})
|
||||
.sum();
|
||||
for plane in [Plane::RigidWall, Plane::Plate] {
|
||||
let (dist, t, _) = slide(plane, f, v0, g, 1.3 * t_stop);
|
||||
eprintln!("{plane:?}, decaying μ: stops at {t:.4} vs {t_stop:.4}, after {dist:.4} vs {d_stop:.4}");
|
||||
assert!((t - t_stop).abs() < 0.03 * t_stop, "{plane:?}: {t} vs {t_stop}");
|
||||
assert!((dist - d_stop).abs() < 0.03 * d_stop, "{plane:?}: {dist} vs {d_stop}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Two blocks with non-matching meshes (3 × 3 below, 2 × 2 above) pressed together slowly
|
||||
/// between symmetry planes: the stress is uniform σ_zz on both sides of the interface and the
|
||||
/// force across it is σ_zz A (a contact patch test in uniaxial stress).
|
||||
#[test]
|
||||
fn a_contact_patch_test_carries_a_uniform_stress_across_non_matching_meshes() {
|
||||
let mut m = Mesh::new();
|
||||
let lower = m.block([0.0; 3], [1.0, 1.0, 1.0], [3, 3, 2]);
|
||||
let upper = m.block([0.0, 0.0, 1.0], [1.0, 1.0, 1.0], [2, 2, 2]);
|
||||
let (young, rho) = (1000.0, 1.0);
|
||||
m.material("Mat", young, 0.3, rho);
|
||||
m.section("lower", &lower, "Mat");
|
||||
m.section("upper", &upper, "Mat");
|
||||
let both: Vec<u32> = lower.iter().chain(&upper).copied().collect();
|
||||
m.face_set("lower_top", m.faces_where(&lower, |c| (c[2] - 1.0).abs() < 1e-9));
|
||||
m.face_set("upper_bottom", m.faces_where(&upper, |c| (c[2] - 1.0).abs() < 1e-9));
|
||||
m.pair("interface", "lower_top", "upper_bottom", Friction::NONE);
|
||||
m.node_set("x0", m.nodes_where(&both, |x| x[0].abs() < 1e-9));
|
||||
m.node_set("y0", m.nodes_where(&both, |x| x[1].abs() < 1e-9));
|
||||
m.node_set("z0", m.nodes_where(&both, |x| x[2].abs() < 1e-9));
|
||||
m.node_set("top", m.nodes_where(&both, |x| (x[2] - 2.0).abs() < 1e-9));
|
||||
let squeeze = 0.01;
|
||||
let held = |set: &str, k: usize| {
|
||||
let mut values = [None; 6];
|
||||
values[k] = Some(0.0);
|
||||
BoundaryCondition::Displacement { target: Target::Set(set.into()), values }
|
||||
};
|
||||
let mut push_values = [None; 6];
|
||||
push_values[2] = Some(-squeeze);
|
||||
let push = BoundaryCondition::Displacement { target: Target::Set("top".into()), values: push_values };
|
||||
// A hundred wave transits: quasi-static.
|
||||
let c = (young * 0.7 / (1.3 * 0.4) / rho).sqrt();
|
||||
let end = 100.0 * 2.0 / c;
|
||||
let mut step = ExplicitDynamic::new(end);
|
||||
step.output_interval = Some(end / 4.0);
|
||||
m.step(step, &[("x0", held("x0", 0)), ("y0", held("y0", 1)), ("z0", held("z0", 2)), ("push", push)], &[]);
|
||||
let r = m.solve();
|
||||
let f = r.frames.last().unwrap();
|
||||
let szz: Vec<f64> = f.stress.iter().map(|s| s[2]).collect();
|
||||
let mean = szz.iter().sum::<f64>() / szz.len() as f64;
|
||||
let spread = szz.iter().map(|s| (s - mean).abs()).fold(0.0, f64::max);
|
||||
let lateral = f.stress.iter().flat_map(|s| [s[0], s[1], s[3], s[4], s[5]]).map(f64::abs).fold(0.0, f64::max);
|
||||
let force = *r.history.contact_force.last().unwrap().first().unwrap();
|
||||
eprintln!(
|
||||
"patch: σ_zz mean {mean:.5} (E ε = {:.5}), spread {spread:.3e}, largest other component {lateral:.3e}; force across {force:.5} vs |σ_zz| A = {:.5}",
|
||||
-young * squeeze / 2.0,
|
||||
mean.abs()
|
||||
);
|
||||
assert!(spread < 0.02 * mean.abs(), "σ_zz {szz:?}");
|
||||
assert!(lateral < 0.02 * mean.abs(), "{lateral}");
|
||||
assert!((force - mean.abs()).abs() < 0.02 * mean.abs(), "{force} vs {mean}");
|
||||
// The interface's penalty takes some of the squeeze (uniformly): each block is strained by
|
||||
// what is left.
|
||||
let closure = r.contacts[0].max_penetration;
|
||||
let expected = young * (squeeze - closure) / 2.0;
|
||||
eprintln!("patch: interface closure {closure:.4e}, σ_zz vs E (squeeze − closure) / 2 = {expected:.5}");
|
||||
assert!((mean.abs() - expected).abs() < 0.01 * expected, "{mean} vs {expected}");
|
||||
}
|
||||
|
||||
/// The same contact run gives the same numbers, bit for bit, on one thread and on four.
|
||||
#[test]
|
||||
fn contact_results_do_not_depend_on_the_thread_count() {
|
||||
let c = (BAR_E / BAR_RHO).sqrt();
|
||||
let (m, _, _) = bars(60, 0.1, 2.0 * BAR_L / c, |m, _, _| {
|
||||
m.model.add_contact("all", Contact { friction: Friction::coulomb(0.2), ..Contact::new(ContactSurfaces::General { surface: None }) }).unwrap()
|
||||
});
|
||||
let one = fieldcraft_parallel::with_threads(1, || solve_explicit(&m.model, None, &Limits::default()).unwrap());
|
||||
let four = fieldcraft_parallel::with_threads(4, || solve_explicit(&m.model, None, &Limits::default()).unwrap());
|
||||
assert_eq!(one.frames, four.frames);
|
||||
assert_eq!(one.history, four.history);
|
||||
assert_eq!(one.energy, four.energy);
|
||||
assert_eq!(one.contacts, four.contacts);
|
||||
}
|
||||
|
||||
/// Nodes that start inside the other surface are moved onto it and reported, or refused with
|
||||
/// the node, the face and the depth; a cap on contact faces is honoured; contact on the faces
|
||||
/// of tetrahedra works too.
|
||||
#[test]
|
||||
fn initial_penetration_caps_and_tetrahedra() {
|
||||
let build = |mode: InitialPenetration, overlap: f64| {
|
||||
let mut m = Mesh::new();
|
||||
let a = m.block([0.0; 3], [1.0, 1.0, 1.0], [2, 2, 2]);
|
||||
let b = m.block([0.0, 0.0, 1.0 - overlap], [1.0, 1.0, 1.0], [3, 3, 2]);
|
||||
m.material("Mat", 1000.0, 0.3, 1.0);
|
||||
m.section("a", &a, "Mat");
|
||||
m.section("b", &b, "Mat");
|
||||
m.face_set("a_top", m.faces_where(&a, |c| (c[2] - 1.0).abs() < 1e-9));
|
||||
m.face_set("b_bottom", m.faces_where(&b, |c| (c[2] - 1.0 + overlap).abs() < 1e-9));
|
||||
let c = Contact { initial_penetration: mode, ..Contact::new(ContactSurfaces::Pair { main: "a_top".into(), secondary: "b_bottom".into() }) };
|
||||
m.model.add_contact("stack", c).unwrap();
|
||||
m.step(ExplicitDynamic::new(0.01), &[], &[]);
|
||||
m
|
||||
};
|
||||
let r = build(InitialPenetration::Adjust, 0.01).solve();
|
||||
let s = &r.contacts[0];
|
||||
// Both passes: b's 16 bottom nodes into a, and a's 9 top nodes into b (they are inside b
|
||||
// after b's nodes moved down? no: b's nodes are moved onto a's top first, then a's top nodes
|
||||
// are on b's bottom).
|
||||
assert!(!s.adjusted.is_empty(), "{s:?}");
|
||||
assert!(s.adjusted.iter().all(|a| (a.depth - 0.01).abs() < 1e-9), "{:?}", s.adjusted);
|
||||
assert!(r.warnings.iter().any(|w| w.contains("contact `stack`") && w.contains("moved onto it")), "{:?}", r.warnings);
|
||||
// After the adjustment nothing is pushed apart: no contact force worth the name.
|
||||
assert!(s.peak_force < 1e-6, "{s:?}");
|
||||
let e = solve_explicit(&build(InitialPenetration::Refuse, 0.01).model, None, &Limits::default()).unwrap_err().to_string();
|
||||
assert!(e.contains("contact `stack`") && e.contains("starts 1.0000e-2 inside face 2 of element"), "{e}");
|
||||
// Touching exactly is not a penetration.
|
||||
assert!(build(InitialPenetration::Refuse, 0.0).solve().contacts[0].adjusted.is_empty());
|
||||
let capped = Limits { max_contact_faces: 10, ..Limits::default() };
|
||||
let e = solve_explicit(&build(InitialPenetration::Adjust, 0.0).model, None, &capped).unwrap_err().to_string();
|
||||
assert!(e.contains("limit") && e.contains("contact `stack`"), "{e}");
|
||||
}
|
||||
|
||||
/// Interval ends on [0, 1] in `n` intervals growing from the first by `ratio`.
|
||||
fn graded(n: usize, ratio: f64) -> Vec<f64> {
|
||||
let widths: Vec<f64> = (0..n).map(|k| ratio.powi(k as i32)).collect();
|
||||
let total: f64 = widths.iter().sum();
|
||||
let mut out = vec![0.0];
|
||||
let mut at = 0.0;
|
||||
for w in widths {
|
||||
at += w / total;
|
||||
out.push(at);
|
||||
}
|
||||
if let Some(last) = out.last_mut() {
|
||||
*last = 1.0;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A quarter (x ≥ 0, y ≥ 0) of a ball of radius `radius` about `center`, meshed as a cubed sphere
|
||||
/// of hex8: an inner cube of half-size 0.4 R with `n` uniform elements per edge, and six blocks
|
||||
/// from its faces to the sphere with `n` × `n` elements across (equiangular, clustered towards
|
||||
/// each face's centre by `lateral`) and `layers` elements through (thinner towards the surface
|
||||
/// by `radial`). Its elements and the faces on the sphere within 30° of the pole below (−z) or
|
||||
/// above (+z) the centre (`towards`).
|
||||
fn quarter_ball(
|
||||
m: &mut Mesh,
|
||||
center: [f64; 3],
|
||||
radius: f64,
|
||||
n: usize,
|
||||
layers: usize,
|
||||
lateral: f64,
|
||||
radial: f64,
|
||||
towards: f64,
|
||||
) -> (Vec<u32>, Vec<ElementFace>) {
|
||||
use std::collections::BTreeMap;
|
||||
assert!(n.is_multiple_of(2));
|
||||
let inner = 0.4 * radius;
|
||||
// Clustered lateral parameter on [−1, 1]: symmetric, finest at 0.
|
||||
let half = graded(n / 2, lateral);
|
||||
let mut clustered: Vec<f64> = half.iter().rev().map(|s| -s).collect();
|
||||
clustered.extend(half.iter().skip(1));
|
||||
let uniform: Vec<f64> = (0..=n).map(|i| -1.0 + 2.0 * i as f64 / n as f64).collect();
|
||||
// Radial blend from the cube (0) to the sphere (1), finest at the sphere.
|
||||
let through: Vec<f64> = graded(layers, radial).iter().rev().map(|s| 1.0 - s).collect();
|
||||
let mut labels: BTreeMap<[i64; 3], u32> = BTreeMap::new();
|
||||
let quantum = 1e-9 * radius;
|
||||
let mut node = |m: &mut Mesh, x: [f64; 3]| -> u32 {
|
||||
let key = x.map(|c| (c / quantum).round() as i64);
|
||||
*labels.entry(key).or_insert_with(|| {
|
||||
let l = m.next_node;
|
||||
m.model.set_node(l, [center[0] + x[0], center[1] + x[1], center[2] + x[2]]).unwrap();
|
||||
m.next_node += 1;
|
||||
l
|
||||
})
|
||||
};
|
||||
let kept = |x: &[[f64; 3]]| {
|
||||
let c = [0, 1].map(|d| x.iter().map(|p| p[d]).sum::<f64>() / x.len() as f64);
|
||||
c[0] > 0.0 && c[1] > 0.0
|
||||
};
|
||||
let mut hexes: Vec<[[f64; 3]; 8]> = Vec::new();
|
||||
// The inner cube.
|
||||
let cube = |i: usize, j: usize, k: usize| [uniform[i], uniform[j], uniform[k]].map(|s| inner * s);
|
||||
for k in 0..n {
|
||||
for j in 0..n {
|
||||
for i in 0..n {
|
||||
hexes.push([
|
||||
cube(i, j, k),
|
||||
cube(i + 1, j, k),
|
||||
cube(i + 1, j + 1, k),
|
||||
cube(i, j + 1, k),
|
||||
cube(i, j, k + 1),
|
||||
cube(i + 1, j, k + 1),
|
||||
cube(i + 1, j + 1, k + 1),
|
||||
cube(i, j + 1, k + 1),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The six blocks: face axis a, sign σ; (u, v) along the other two axes.
|
||||
for axis in 0..3 {
|
||||
for sign in [-1.0, 1.0] {
|
||||
let place = |u: f64, v: f64, w: f64| -> [f64; 3] {
|
||||
let mut p = [0.0; 3];
|
||||
p[axis] = w;
|
||||
p[(axis + 1) % 3] = u;
|
||||
p[(axis + 2) % 3] = v;
|
||||
p
|
||||
};
|
||||
let point = |i: usize, j: usize, k: usize| -> [f64; 3] {
|
||||
let t = through[k];
|
||||
let p_in = place(uniform[i], uniform[j], sign).map(|c| inner * c);
|
||||
let angle = |s: f64| (s * std::f64::consts::FRAC_PI_4).tan();
|
||||
let d = place(angle(clustered[i]), angle(clustered[j]), sign);
|
||||
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
|
||||
let p_out = d.map(|c| radius * c / len);
|
||||
[0, 1, 2].map(|c| (1.0 - t) * p_in[c] + t * p_out[c])
|
||||
};
|
||||
for k in 0..layers {
|
||||
for j in 0..n {
|
||||
for i in 0..n {
|
||||
hexes.push([
|
||||
point(i, j, k),
|
||||
point(i + 1, j, k),
|
||||
point(i + 1, j + 1, k),
|
||||
point(i, j + 1, k),
|
||||
point(i, j, k + 1),
|
||||
point(i + 1, j, k + 1),
|
||||
point(i + 1, j + 1, k + 1),
|
||||
point(i, j + 1, k + 1),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut elements = Vec::new();
|
||||
for mut h in hexes.into_iter().filter(|h| kept(h)) {
|
||||
// Positive volume: the bottom face counter-clockwise seen from the top.
|
||||
let sub = |a: [f64; 3], b: [f64; 3]| [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
|
||||
let (a, b, c) = (sub(h[1], h[0]), sub(h[3], h[0]), sub(h[4], h[0]));
|
||||
let det = a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0]);
|
||||
if det < 0.0 {
|
||||
h = [h[4], h[5], h[6], h[7], h[0], h[1], h[2], h[3]];
|
||||
}
|
||||
let nodes: Vec<u32> = h.iter().map(|x| node(m, *x)).collect();
|
||||
m.model.set_element(m.next_element, ElementKind::Hex8, nodes).unwrap();
|
||||
elements.push(m.next_element);
|
||||
m.next_element += 1;
|
||||
}
|
||||
let pole = [0.0, 0.0, towards];
|
||||
let exterior = m.model.exterior_faces();
|
||||
let faces: Vec<ElementFace> = m
|
||||
.faces_where(&elements, |c| {
|
||||
let r = [c[0] - center[0], c[1] - center[1], c[2] - center[2]];
|
||||
let len = (r[0] * r[0] + r[1] * r[1] + r[2] * r[2]).sqrt();
|
||||
len > 0.9 * radius && (r[0] * pole[0] + r[1] * pole[1] + r[2] * pole[2]) / len > (std::f64::consts::PI / 6.0).cos()
|
||||
})
|
||||
.into_iter()
|
||||
.filter(|f| exterior.binary_search(f).is_ok())
|
||||
.collect();
|
||||
(elements, faces)
|
||||
}
|
||||
|
||||
/// Hertz's impact of two identical elastic spheres (radius R, mass m, E, ν) at relative speed v:
|
||||
/// with R* = R/2, m* = m/2, E* = E / (2(1 − ν²)), the approach reaches
|
||||
/// δ = (15 m* v² / (16 E* √R*))^{2/5}, the force F = (4/3) E* √R* δ^{3/2}, and the contact lasts
|
||||
/// 2.9432 δ / v (K. L. Johnson, *Contact Mechanics*, Cambridge 1985, §11.4).
|
||||
fn hertz(radius: f64, young: f64, poisson: f64, density: f64, v: f64) -> (f64, f64, f64) {
|
||||
let mass = 4.0 / 3.0 * std::f64::consts::PI * radius.powi(3) * density;
|
||||
let (r_eff, m_eff, e_eff) = (radius / 2.0, mass / 2.0, young / (2.0 * (1.0 - poisson * poisson)));
|
||||
let delta = (15.0 * m_eff * v * v / (16.0 * e_eff * r_eff.sqrt())).powf(0.4);
|
||||
(delta, 4.0 / 3.0 * e_eff * r_eff.sqrt() * delta.powf(1.5), 2.9432 * delta / v)
|
||||
}
|
||||
|
||||
/// Two spheres in a head-on collision (a quarter of each, between the symmetry planes x = 0 and
|
||||
/// y = 0), with a contact pair between their facing caps: the peak force and the contact
|
||||
/// duration against Hertz. `n` and `layers` set the mesh; `a_over_r` the contact radius the speed
|
||||
/// is chosen for.
|
||||
fn sphere_impact(n: usize, layers: usize, lateral: f64, radial: f64, a_over_r: f64) -> (f64, f64, f64, f64, ExplicitResult) {
|
||||
let (radius, young, poisson, density) = (1.0, 1.0, 0.3, 1.0);
|
||||
// The speed that gives a contact radius a = √(R* δ).
|
||||
let delta = a_over_r * a_over_r * radius * radius / (radius / 2.0);
|
||||
let mass = 4.0 / 3.0 * std::f64::consts::PI * density;
|
||||
let e_eff = young / (2.0 * (1.0 - poisson * poisson));
|
||||
let v = (delta.powf(2.5) * 16.0 * e_eff * (radius / 2.0f64).sqrt() / (15.0 * mass / 2.0)).sqrt();
|
||||
let (delta, force, duration) = hertz(radius, young, poisson, density, v);
|
||||
let mut m = Mesh::new();
|
||||
let (upper, upper_cap) = quarter_ball(&mut m, [0.0, 0.0, radius], radius, n, layers, lateral, radial, -1.0);
|
||||
let (lower, lower_cap) = quarter_ball(&mut m, [0.0, 0.0, -radius], radius, n, layers, lateral, radial, 1.0);
|
||||
m.material("Mat", young, poisson, density);
|
||||
m.section("upper", &upper, "Mat");
|
||||
m.section("lower", &lower, "Mat");
|
||||
m.face_set("upper_cap", upper_cap);
|
||||
m.face_set("lower_cap", lower_cap);
|
||||
m.pair("impact", "lower_cap", "upper_cap", Friction::NONE);
|
||||
let both: Vec<u32> = upper.iter().chain(&lower).copied().collect();
|
||||
m.node_set("x0", m.nodes_where(&both, |x| x[0].abs() < 1e-9));
|
||||
m.node_set("y0", m.nodes_where(&both, |x| x[1].abs() < 1e-9));
|
||||
let held = |set: &str, k: usize| {
|
||||
let mut values = [None; 6];
|
||||
values[k] = Some(0.0);
|
||||
BoundaryCondition::Displacement { target: Target::Set(set.into()), values }
|
||||
};
|
||||
let mut step = ExplicitDynamic::new(1.15 * duration);
|
||||
step.initial_velocities = vec![
|
||||
InitialVelocity { set: "upper".into(), velocity: [0.0, 0.0, -v / 2.0] },
|
||||
InitialVelocity { set: "lower".into(), velocity: [0.0, 0.0, v / 2.0] },
|
||||
];
|
||||
step.bulk_viscosity = BulkViscosity { linear: 0.0, quadratic: 1.5 };
|
||||
step.history_interval = Some(duration / 2000.0);
|
||||
step.output_interval = Some(1.15 * duration);
|
||||
m.step(step, &[("x0", held("x0", 0)), ("y0", held("y0", 1))], &[]);
|
||||
let r = m.solve();
|
||||
let s = &r.contacts[0];
|
||||
// A quarter of each sphere carries a quarter of the force.
|
||||
let peak = 4.0 * s.peak_force;
|
||||
let lasted = s.last_contact.unwrap_or(0.0) - s.first_contact.unwrap_or(0.0);
|
||||
eprintln!(
|
||||
"Hertz ({} elements, a/R = {a_over_r}): v = {v:.4e}, δ = {delta:.4e}; peak force {peak:.5e} vs {force:.5e} ({:+.2}%), duration {lasted:.4} vs {duration:.4} ({:+.2}%); max penetration {:.2e}; KE after/before {:.4}; balance {:.2e}; {} increments",
|
||||
both.len(),
|
||||
100.0 * (peak / force - 1.0),
|
||||
100.0 * (lasted / duration - 1.0),
|
||||
s.max_penetration,
|
||||
r.energy.kinetic / r.initial_kinetic,
|
||||
r.energy.relative_error(r.initial_kinetic),
|
||||
r.increments
|
||||
);
|
||||
(peak, force, lasted, duration, r)
|
||||
}
|
||||
|
||||
/// A coarse sphere impact in the main gate: Hertz's force and duration to a few percent.
|
||||
#[test]
|
||||
fn spheres_collide_as_hertz_says_coarse() {
|
||||
let (peak, force, lasted, duration, _) = sphere_impact(12, 6, 1.25, 1.25, 0.15);
|
||||
assert!((peak - force).abs() < 0.1 * force, "{peak} vs {force}");
|
||||
assert!((lasted - duration).abs() < 0.1 * duration, "{lasted} vs {duration}");
|
||||
}
|
||||
|
||||
/// The fine sphere impact: contact radius a tenth of the radius, about six elements across it.
|
||||
#[test]
|
||||
#[ignore = "heavy: cargo xtask test --heavy (CI heavy job)"]
|
||||
fn spheres_collide_as_hertz_says() {
|
||||
let (peak, force, lasted, duration, r) = sphere_impact(24, 12, 1.23, 1.185, 0.1);
|
||||
assert!((peak - force).abs() < 0.03 * force, "{peak} vs {force}");
|
||||
assert!((lasted - duration).abs() < 0.03 * duration, "{lasted} vs {duration}");
|
||||
assert!(r.energy.kinetic > 0.95 * r.initial_kinetic);
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
//! Hyperelastic materials in explicit dynamics: the stress of the shared finite-strain material
|
||||
//! point (neo-Hookean, Mooney–Rivlin, Yeoh) from the deformation gradient, on one-point hex8 and
|
||||
//! F-bar tet4, against the closed form of uniaxial strain reached quasi-statically, and the
|
||||
//! refusals.
|
||||
//!
|
||||
//! In uniaxial strain F = diag(λ, 1, 1): the hyperelastic Cauchy stress is the material point's
|
||||
//! Kirchhoff stress over J = λ (fieldcraft_fem::constitutive, whose laws are checked there
|
||||
//! against their strain energies), so the explicit elements must reproduce it once the motion has
|
||||
//! settled; the wave dynamics of a slow pull leave a fraction of a percent.
|
||||
|
||||
use fieldcraft_explicit::{ExplicitResult, Limits, solve_explicit};
|
||||
use fieldcraft_fem::constitutive::MaterialModel;
|
||||
use fieldcraft_model::*;
|
||||
|
||||
const N: usize = 2;
|
||||
|
||||
/// A unit cube of N³ hex8 (or six tet4 per cell), held on its faces x = 0, y = 0, y = 1, z = 0,
|
||||
/// z = 1 in their normal directions and pulled on x = 1 to a stretch λ over `end`.
|
||||
fn block(tet: bool, hyper: Hyperelastic, stretch: f64, end: f64, nonlinear: bool) -> Model {
|
||||
let mut m = Model::default();
|
||||
let h = 1.0 / N as f64;
|
||||
let label = |i: usize, j: usize, k: usize| (1 + i + (N + 1) * (j + (N + 1) * k)) as u32;
|
||||
for k in 0..=N {
|
||||
for j in 0..=N {
|
||||
for i in 0..=N {
|
||||
m.set_node(label(i, j, k), [i as f64 * h, j as f64 * h, k as f64 * h]).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
let corners = [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]];
|
||||
let mut next = 1;
|
||||
for k in 0..N {
|
||||
for j in 0..N {
|
||||
for i in 0..N {
|
||||
let at = |c: [usize; 3]| label(i + c[0], j + c[1], k + c[2]);
|
||||
if !tet {
|
||||
m.set_element(next, ElementKind::Hex8, corners.iter().map(|c| at(*c)).collect()).unwrap();
|
||||
next += 1;
|
||||
continue;
|
||||
}
|
||||
for perm in [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]] {
|
||||
let mut v = [[0usize; 3]; 4];
|
||||
for s in 0..3 {
|
||||
v[s + 1] = v[s];
|
||||
v[s + 1][perm[s]] = 1;
|
||||
}
|
||||
let e = |a: usize| [0, 1, 2].map(|d| v[a][d] as f64 - v[0][d] as f64);
|
||||
let (a, b, c) = (e(1), e(2), e(3));
|
||||
let vol = a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0]);
|
||||
if vol < 0.0 {
|
||||
v.swap(1, 2);
|
||||
}
|
||||
m.set_element(next, ElementKind::Tet4, v.iter().map(|c| at(*c)).collect()).unwrap();
|
||||
next += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let all: Vec<u32> = m.elements().keys().copied().collect();
|
||||
m.add_set("all", Set { elements: all, ..Set::default() }).unwrap();
|
||||
let nodes = |f: &dyn Fn([f64; 3]) -> bool| -> Vec<u32> { m.nodes().iter().filter(|(_, n)| f(n.xyz)).map(|(l, _)| *l).collect() };
|
||||
let sets = [
|
||||
("x0", nodes(&|x| x[0] == 0.0)),
|
||||
("x1", nodes(&|x| x[0] == 1.0)),
|
||||
("y", nodes(&|x| x[1] == 0.0 || x[1] == 1.0)),
|
||||
("z", nodes(&|x| x[2] == 0.0 || x[2] == 1.0)),
|
||||
];
|
||||
for (name, list) in sets {
|
||||
m.add_set(name, Set { nodes: list, ..Set::default() }).unwrap();
|
||||
}
|
||||
let elastic = Elastic::Isotropic { young: 1.0, poisson: 0.45 };
|
||||
m.add_material("Rubber", Material { elastic: Some(elastic), density: Some(1.0), hyperelastic: Some(hyper), ..Material::default() }).unwrap();
|
||||
let integration = if tet { Integration::Full } else { Integration::Reduced };
|
||||
let formulation = Formulation { integration, ..Formulation::default() };
|
||||
m.add_section("all", Section { set: "all".into(), material: "Rubber".into(), kind: SectionKind::Solid {}, formulation }).unwrap();
|
||||
let held = |set: &str, k: usize, v: f64| {
|
||||
let mut values = [None; 6];
|
||||
values[k] = Some(v);
|
||||
BoundaryCondition::Displacement { target: Target::Set(set.into()), values }
|
||||
};
|
||||
let mut step = ExplicitDynamic::new(end);
|
||||
step.nonlinear_geometry = nonlinear;
|
||||
step.output_interval = Some(end / 2.0);
|
||||
let mut s = Step::new("Pull", Procedure::ExplicitDynamic(step));
|
||||
for (name, bc) in [("x0", held("x0", 0, 0.0)), ("x1", held("x1", 0, stretch - 1.0)), ("y", held("y", 1, 0.0)), ("z", held("z", 2, 0.0))] {
|
||||
m.add_boundary_condition(name, bc).unwrap();
|
||||
s.boundary_conditions.insert(name.into());
|
||||
}
|
||||
m.add_step(s, None).unwrap();
|
||||
m
|
||||
}
|
||||
|
||||
/// σ of uniaxial strain λ from the material point.
|
||||
fn closed_form(hyper: Hyperelastic, stretch: f64) -> [f64; 6] {
|
||||
let model = MaterialModel::from_model(&Elastic::Isotropic { young: 1.0, poisson: 0.45 }, Some(&hyper)).unwrap();
|
||||
let f = [[stretch, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
|
||||
model.response(&f, None, &[], &mut []).unwrap().stress.map(|t| t / stretch)
|
||||
}
|
||||
|
||||
fn mean_stress(r: &ExplicitResult) -> [f64; 6] {
|
||||
let f = r.frames.last().unwrap();
|
||||
let mut s = [0.0; 6];
|
||||
for e in &f.stress {
|
||||
for k in 0..6 {
|
||||
s[k] += e[k] / f.stress.len() as f64;
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hyperelastic_uniaxial_strain_matches_the_material_point() {
|
||||
let stretch = 1.5;
|
||||
// Dilatational wave speed √((κ + 4μ/3)/ρ) ≈ 2.0: a pull over 400 transits of the cube.
|
||||
let end = 200.0;
|
||||
let materials = [Hyperelastic::NeoHookean {}, Hyperelastic::MooneyRivlin { c01: 0.08 }, Hyperelastic::Yeoh { c20: -0.01, c30: 0.002 }];
|
||||
for hyper in materials {
|
||||
let reference = closed_form(hyper, stretch);
|
||||
for tet in [false, true] {
|
||||
let r = solve_explicit(&block(tet, hyper, stretch, end, true), None, &Limits::default()).unwrap();
|
||||
assert!(r.completed);
|
||||
let s = mean_stress(&r);
|
||||
let spread = r.frames.last().unwrap().stress.iter().map(|e| (e[0] - s[0]).abs()).fold(0.0, f64::max);
|
||||
eprintln!(
|
||||
"{} {}: σ_xx {:.5} vs {:.5}, σ_yy {:.5} vs {:.5}; spread {spread:.2e}; balance {:.2e}; {} increments",
|
||||
hyper.name(),
|
||||
if tet { "tet4" } else { "hex8" },
|
||||
s[0],
|
||||
reference[0],
|
||||
s[1],
|
||||
reference[1],
|
||||
r.energy.relative_error(r.initial_kinetic),
|
||||
r.increments
|
||||
);
|
||||
for k in 0..3 {
|
||||
assert!((s[k] - reference[k]).abs() < 0.01 * reference[0].abs(), "{} tet {tet}: {s:?} vs {reference:?}", hyper.name());
|
||||
}
|
||||
assert!(spread < 0.01 * reference[0].abs(), "uniform state: {spread}");
|
||||
assert!(r.energy.relative_error(r.initial_kinetic) < 0.01, "{:?}", r.energy);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hyperelastic_materials_need_nonlinear_geometry() {
|
||||
let e = solve_explicit(&block(false, Hyperelastic::NeoHookean {}, 1.1, 1.0, false), None, &Limits::default()).unwrap_err().to_string();
|
||||
assert!(e.contains("nonlinear geometry") && e.contains("Rubber"), "{e}");
|
||||
}
|
||||
@@ -168,7 +168,7 @@ impl Driver {
|
||||
let resolved = model.resolve().unwrap();
|
||||
let step = model.step("Dynamic").unwrap();
|
||||
let Procedure::ExplicitDynamic(settings) = &step.procedure else { panic!() };
|
||||
let sys = System::new(model, &resolved, step, settings, 1000).unwrap();
|
||||
let sys = System::new(model, &resolved, step, settings, &Limits { max_dofs: 1000, ..Limits::default() }).unwrap();
|
||||
let (state, ws) = (State::new(&sys), Workspace::new(&sys));
|
||||
let u = vec![0.0; sys.dofs()];
|
||||
Driver { sys, state, ws, u, time: 0.0 }
|
||||
@@ -318,7 +318,7 @@ fn taylor_bar_recovers_its_yield_stress() {
|
||||
step.output_interval = Some(end / 4.0);
|
||||
step.history_interval = Some(end / 400.0);
|
||||
step.initial_velocities = vec![InitialVelocity { set: "nodes".into(), velocity: [0.0, 0.0, -speed] }];
|
||||
step.rigid_walls = vec![RigidWall { set: "nodes".into(), point: [0.0; 3], normal: [0.0, 0.0, 1.0] }];
|
||||
step.rigid_walls = vec![RigidWall { set: "nodes".into(), point: [0.0; 3], normal: [0.0, 0.0, 1.0], friction: Friction::NONE }];
|
||||
step.hourglass = Hourglass { kind: HourglassKind::Stiffness, coefficient: 0.1 };
|
||||
let mut m = block([4, 4, 30], [width, width, length], ElementKind::Hex8);
|
||||
node_set(&mut m, "nodes", |_| true);
|
||||
@@ -359,7 +359,7 @@ fn taylor_with(material: Material) -> (Model, ExplicitResult) {
|
||||
let mut step = ExplicitDynamic::new(end);
|
||||
step.output_interval = Some(end / 2.0);
|
||||
step.initial_velocities = vec![InitialVelocity { set: "nodes".into(), velocity: [0.0, 0.0, -300_000.0] }];
|
||||
step.rigid_walls = vec![RigidWall { set: "nodes".into(), point: [0.0; 3], normal: [0.0, 0.0, 1.0] }];
|
||||
step.rigid_walls = vec![RigidWall { set: "nodes".into(), point: [0.0; 3], normal: [0.0, 0.0, 1.0], friction: Friction::NONE }];
|
||||
step.hourglass = Hourglass { kind: HourglassKind::Stiffness, coefficient: 0.1 };
|
||||
let mut m = block([2, 2, 12], [7.6, 7.6, 25.4], ElementKind::Hex8);
|
||||
node_set(&mut m, "nodes", |_| true);
|
||||
|
||||
@@ -305,3 +305,55 @@ fn whirling_mass_on_a_corotational_rod() {
|
||||
// A quarter turn: the mass ends near (0, L).
|
||||
assert!((l + end[0]).abs() < 1e-2 && (end[1] - l).abs() < 1e-2, "{end:?}");
|
||||
}
|
||||
|
||||
/// Mass scaling to twice a uniform bar's stable increment quadruples its density: the added mass
|
||||
/// is three times the bar's, the stable increment doubles with the halved wave speed
|
||||
/// c = √(E/ρ), and the kinetic energy of the added mass is three quarters of the total.
|
||||
#[test]
|
||||
fn mass_scaling_slows_the_waves_as_the_added_density_says() {
|
||||
use fieldcraft_explicit::{Limits, solve_explicit};
|
||||
use fieldcraft_model::*;
|
||||
let build = |scaled: Option<f64>| {
|
||||
let mut m = Model::default();
|
||||
let n = 40;
|
||||
for i in 0..=n {
|
||||
for (j, (y, z)) in [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)].iter().enumerate() {
|
||||
m.set_node((4 * i + j + 1) as u32, [i as f64, *y, *z]).unwrap();
|
||||
}
|
||||
}
|
||||
for i in 0..n {
|
||||
let a = |j: usize| (4 * i + j + 1) as u32;
|
||||
let b = |j: usize| (4 * (i + 1) + j + 1) as u32;
|
||||
m.set_element(i as u32 + 1, ElementKind::Hex8, vec![a(0), b(0), b(1), a(1), a(3), b(3), b(2), a(2)]).unwrap();
|
||||
}
|
||||
m.add_set("all", Set { elements: (1..=n as u32).collect(), ..Set::default() }).unwrap();
|
||||
m.add_material("Mat", Material { elastic: Some(Elastic::Isotropic { young: 1.0, poisson: 0.0 }), density: Some(1.0), ..Material::default() })
|
||||
.unwrap();
|
||||
let formulation = Formulation { integration: Integration::Reduced, ..Formulation::default() };
|
||||
m.add_section("bar", Section { set: "all".into(), material: "Mat".into(), kind: SectionKind::Solid {}, formulation }).unwrap();
|
||||
let mut step = ExplicitDynamic::new(10.0);
|
||||
step.initial_velocities = vec![InitialVelocity { set: "all".into(), velocity: [0.01, 0.0, 0.0] }];
|
||||
step.mass_scaling = scaled.map(|t| MassScaling { target_increment: t, set: None });
|
||||
m.add_step(Step::new("Run", Procedure::ExplicitDynamic(step)), None).unwrap();
|
||||
solve_explicit(&m, None, &Limits::default()).unwrap()
|
||||
};
|
||||
let plain = build(None);
|
||||
let scaled = build(Some(2.0 * plain.initial_increment));
|
||||
let s = scaled.mass_scaling.as_ref().unwrap();
|
||||
eprintln!(
|
||||
"mass scaling: {s:?}; increments {} vs {}; Δt {:.4e} vs {:.4e}",
|
||||
scaled.increments, plain.increments, scaled.initial_increment, plain.initial_increment
|
||||
);
|
||||
assert_eq!(s.elements, 40);
|
||||
assert!((s.added_mass / plain.total_mass - 3.0).abs() < 1e-9 && (s.fraction - 0.75).abs() < 1e-9, "{s:?}");
|
||||
assert_eq!(s.sections.len(), 1);
|
||||
assert!((scaled.initial_increment / plain.initial_increment - 2.0).abs() < 1e-9);
|
||||
assert!((scaled.total_mass / plain.total_mass - 4.0).abs() < 1e-9);
|
||||
assert!((scaled.energy.added_kinetic / scaled.energy.kinetic - 0.75).abs() < 1e-9, "{:?}", scaled.energy);
|
||||
assert!(scaled.warnings.iter().any(|w| w.contains("mass scaling")));
|
||||
assert!(
|
||||
scaled.controlling.first().is_some_and(|c| (0.9 * c.increment / scaled.initial_increment - 1.0).abs() < 1e-6),
|
||||
"{:?}",
|
||||
scaled.controlling
|
||||
);
|
||||
}
|
||||
@@ -235,7 +235,7 @@ fn bar_rebounds_from_a_rigid_wall() {
|
||||
step.history_interval = Some(end / 3000.0);
|
||||
step.output_interval = Some(end);
|
||||
step.initial_velocities = vec![InitialVelocity { set: "all_nodes".into(), velocity: [-v0, 0.0, 0.0] }];
|
||||
step.rigid_walls = vec![RigidWall { set: "start".into(), point: [0.0; 3], normal: [1.0, 0.0, 0.0] }];
|
||||
step.rigid_walls = vec![RigidWall { set: "start".into(), point: [0.0; 3], normal: [1.0, 0.0, 0.0], friction: Friction::NONE }];
|
||||
step.bulk_viscosity.linear = linear;
|
||||
let mut bar = Bar::new(kind, 200, ExplicitDynamic::new(end));
|
||||
let nodes: Vec<u32> = bar.model.nodes().keys().copied().collect();
|
||||
@@ -347,7 +347,7 @@ fn caps_and_unsupported_models_are_errors() {
|
||||
assert!(solve_explicit(&light.model, None, &Limits::default()).is_err());
|
||||
// A node behind its wall at the start.
|
||||
let mut behind = ExplicitDynamic::new(end);
|
||||
behind.rigid_walls = vec![RigidWall { set: "end".into(), point: [LENGTH + 1.0, 0.0, 0.0], normal: [-1.0, 0.0, 0.0] }];
|
||||
behind.rigid_walls = vec![RigidWall { set: "end".into(), point: [LENGTH + 1.0, 0.0, 0.0], normal: [-1.0, 0.0, 0.0], friction: Friction::NONE }];
|
||||
let mut wall = Bar::new(ElementKind::Hex8, 4, ExplicitDynamic::new(end));
|
||||
wall.model.replace_step(Step::new("Dynamic", Procedure::ExplicitDynamic(behind.clone()))).unwrap();
|
||||
assert!(solve_explicit(&wall.model, None, &Limits::default()).is_ok(), "the wall is beyond the end node, which is on its allowed side");
|
||||
|
||||
@@ -0,0 +1,431 @@
|
||||
//! Contact geometry shared by the solvers: the closest point of an element face to a point (the
|
||||
//! local search) and a bucket grid of face boxes (the global search).
|
||||
//!
|
||||
//! **Closest point.** A face is a flat triangle or a bilinear quadrilateral given by its corner
|
||||
//! nodes, numbered so that their right-hand normal points out of the element. On a triangle the
|
||||
//! closest point is found exactly by the region tests of C. Ericson, *Real-Time Collision
|
||||
//! Detection*, Morgan Kaufmann 2005, §5.1.5. On a bilinear quadrilateral x(ξ, η) it is the
|
||||
//! minimum of ½|x(ξ, η) − p|² over [−1, 1]², found by Newton's method on the stationarity
|
||||
//! conditions x,ξ · (x − p) = x,η · (x − p) = 0 with the exact Hessian (the bilinear patch's
|
||||
//! only second derivative is x,ξη), projected onto the square after each step: the
|
||||
//! closest-point projection of node-to-segment contact (J. O. Hallquist, G. L. Goudreau, D. J.
|
||||
//! Benson, *Sliding interfaces with contact-impact in large-scale Lagrangian computations*,
|
||||
//! CMAME 51:107–137, 1985; P. Wriggers, *Computational Contact Mechanics*, 2nd ed., Springer
|
||||
//! 2006, §4.1). The signed gap is measured along the face's unit normal at the closest point; the
|
||||
//! lateral offset (how far the point lies beside the face rather than above or below it) tells a
|
||||
//! point over the face from one past its edge.
|
||||
//!
|
||||
//! **Global search.** Each face's bounding box, grown by a margin, goes into every cell of a
|
||||
//! uniform grid it overlaps (a bucket sort: D. J. Benson, J. O. Hallquist, *A single surface
|
||||
//! contact algorithm for the post-buckling analysis of shell structures*, CMAME 78:141–163,
|
||||
//! 1990); a point's candidates are the faces in its cell. The cell is twice the mean box size,
|
||||
//! grown until the grid and its entries fit their caps, so the search is linear in the number of
|
||||
//! faces and its memory bounded whatever the input. Entries are listed in face order, so the
|
||||
//! candidates (and everything decided from them) do not depend on how the work is split.
|
||||
|
||||
pub use crate::frame::Vec3;
|
||||
use crate::frame::{cross, dot, norm, sub};
|
||||
|
||||
/// Newton iterations of the bilinear closest-point search.
|
||||
const MAX_NEWTON: usize = 30;
|
||||
|
||||
/// The closest point of a face to a point.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Projection {
|
||||
/// Face coordinates of the closest point: (ξ, η) ∈ [−1, 1]² on a quadrilateral, the
|
||||
/// barycentric coordinates of the second and third nodes on a triangle.
|
||||
pub xi: [f64; 2],
|
||||
/// The face's shape functions at the closest point, per node (0 past the face's nodes).
|
||||
pub weights: [f64; 4],
|
||||
pub point: Vec3,
|
||||
/// The unit outward normal at the closest point.
|
||||
pub normal: Vec3,
|
||||
/// (p − point) · normal: negative when the point is behind the face.
|
||||
pub gap: f64,
|
||||
/// |p − point|.
|
||||
pub distance: f64,
|
||||
/// The part of p − point across the normal: 0 when the point is over or under the face, its
|
||||
/// distance from the face's edge when it is beside it.
|
||||
pub lateral: f64,
|
||||
}
|
||||
|
||||
/// The closest point of a face (three or four corner nodes, in its node order) to `p`; `None`
|
||||
/// for another number of nodes, non-finite coordinates or a face collapsed at that point.
|
||||
pub fn closest_point(face: &[Vec3], p: Vec3) -> Option<Projection> {
|
||||
if face.iter().chain(std::iter::once(&p)).flatten().any(|c| !c.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let (xi, weights, normal) = match face {
|
||||
[a, b, c] => triangle(*a, *b, *c, p)?,
|
||||
[a, b, c, d] => quadrilateral([*a, *b, *c, *d], p)?,
|
||||
_ => return None,
|
||||
};
|
||||
let mut point = [0.0; 3];
|
||||
for (x, w) in face.iter().zip(weights) {
|
||||
for k in 0..3 {
|
||||
point[k] += w * x[k];
|
||||
}
|
||||
}
|
||||
let d = sub(p, point);
|
||||
let gap = dot(d, normal);
|
||||
let distance = norm(d);
|
||||
let lateral = (distance * distance - gap * gap).max(0.0).sqrt();
|
||||
Some(Projection { xi, weights, point, normal, gap, distance, lateral })
|
||||
}
|
||||
|
||||
/// The unit vector along `v`, unless it is too short against `scale` (a squared length).
|
||||
fn unit(v: Vec3, scale: f64) -> Option<Vec3> {
|
||||
let n = norm(v);
|
||||
(n > 1e-12 * scale && n.is_finite()).then(|| v.map(|c| c / n))
|
||||
}
|
||||
|
||||
/// Ericson's closest point on triangle abc: (barycentric v, w), weights, unit normal.
|
||||
fn triangle(a: Vec3, b: Vec3, c: Vec3, p: Vec3) -> Option<([f64; 2], [f64; 4], Vec3)> {
|
||||
let (ab, ac, ap) = (sub(b, a), sub(c, a), sub(p, a));
|
||||
let normal = unit(cross(ab, ac), dot(ab, ab).max(dot(ac, ac)))?;
|
||||
let (d1, d2) = (dot(ab, ap), dot(ac, ap));
|
||||
let bp = sub(p, b);
|
||||
let (d3, d4) = (dot(ab, bp), dot(ac, bp));
|
||||
let cp = sub(p, c);
|
||||
let (d5, d6) = (dot(ab, cp), dot(ac, cp));
|
||||
let (va, vb, vc) = (d3 * d6 - d5 * d4, d5 * d2 - d1 * d6, d1 * d4 - d3 * d2);
|
||||
let (v, w) = if d1 <= 0.0 && d2 <= 0.0 {
|
||||
(0.0, 0.0)
|
||||
} else if d3 >= 0.0 && d4 <= d3 {
|
||||
(1.0, 0.0)
|
||||
} else if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 {
|
||||
(d1 / (d1 - d3), 0.0)
|
||||
} else if d6 >= 0.0 && d5 <= d6 {
|
||||
(0.0, 1.0)
|
||||
} else if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 {
|
||||
(0.0, d2 / (d2 - d6))
|
||||
} else if va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0 {
|
||||
let t = (d4 - d3) / ((d4 - d3) + (d5 - d6));
|
||||
(1.0 - t, t)
|
||||
} else {
|
||||
let s = va + vb + vc;
|
||||
(vb / s, vc / s)
|
||||
};
|
||||
if !(v.is_finite() && w.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
Some(([v, w], [1.0 - v - w, v, w, 0.0], normal))
|
||||
}
|
||||
|
||||
/// The bilinear shape functions and their derivatives at (ξ, η), nodes at (−1, −1), (1, −1),
|
||||
/// (1, 1), (−1, 1).
|
||||
fn bilinear(s: f64, t: f64) -> ([f64; 4], [f64; 4], [f64; 4]) {
|
||||
let n = [(1.0 - s) * (1.0 - t), (1.0 + s) * (1.0 - t), (1.0 + s) * (1.0 + t), (1.0 - s) * (1.0 + t)].map(|v| 0.25 * v);
|
||||
let ds = [-(1.0 - t), 1.0 - t, 1.0 + t, -(1.0 + t)].map(|v| 0.25 * v);
|
||||
let dt = [-(1.0 - s), -(1.0 + s), 1.0 + s, 1.0 - s].map(|v| 0.25 * v);
|
||||
(n, ds, dt)
|
||||
}
|
||||
|
||||
fn combine(x: &[Vec3; 4], w: &[f64; 4]) -> Vec3 {
|
||||
let mut out = [0.0; 3];
|
||||
for (xi, wi) in x.iter().zip(w) {
|
||||
for k in 0..3 {
|
||||
out[k] += wi * xi[k];
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The closest point of a bilinear quadrilateral by projected Newton iterations.
|
||||
fn quadrilateral(x: [Vec3; 4], p: Vec3) -> Option<([f64; 2], [f64; 4], Vec3)> {
|
||||
let size = dot(sub(x[2], x[0]), sub(x[2], x[0])).max(dot(sub(x[3], x[1]), sub(x[3], x[1])));
|
||||
if !(size > 0.0) {
|
||||
return None;
|
||||
}
|
||||
// x,ξη: constant over the patch.
|
||||
let twist = [0, 1, 2].map(|k| 0.25 * (x[0][k] - x[1][k] + x[2][k] - x[3][k]));
|
||||
let (mut s, mut t) = (0.0f64, 0.0f64);
|
||||
for _ in 0..MAX_NEWTON {
|
||||
let (n, ds, dt) = bilinear(s, t);
|
||||
let r = sub(combine(&x, &n), p);
|
||||
let (a, b) = (combine(&x, &ds), combine(&x, &dt));
|
||||
let g = [dot(a, r), dot(b, r)];
|
||||
let (haa, hbb) = (dot(a, a), dot(b, b));
|
||||
let mut hab = dot(a, b) + dot(r, twist);
|
||||
// Far from the patch the exact Hessian may be indefinite: Gauss–Newton then.
|
||||
if haa * hbb - hab * hab <= 1e-14 * haa * hbb {
|
||||
hab = dot(a, b);
|
||||
}
|
||||
let det = haa * hbb - hab * hab;
|
||||
if !(det > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let step = [-(hbb * g[0] - hab * g[1]) / det, -(haa * g[1] - hab * g[0]) / det];
|
||||
let (s1, t1) = ((s + step[0]).clamp(-1.0, 1.0), (t + step[1]).clamp(-1.0, 1.0));
|
||||
let moved = (s1 - s).abs().max((t1 - t).abs());
|
||||
(s, t) = (s1, t1);
|
||||
if !moved.is_finite() {
|
||||
return None;
|
||||
}
|
||||
if moved < 1e-13 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let (n, ds, dt) = bilinear(s, t);
|
||||
let normal = unit(cross(combine(&x, &ds), combine(&x, &dt)), size)?;
|
||||
Some(([s, t], n, normal))
|
||||
}
|
||||
|
||||
/// A box: its lowest and highest corners.
|
||||
pub type Aabb = [Vec3; 2];
|
||||
|
||||
/// The bounding box of a face's nodes, grown by `margin` on every side.
|
||||
pub fn bounds(face: &[Vec3], margin: f64) -> Aabb {
|
||||
let mut b = [[f64::INFINITY; 3], [f64::NEG_INFINITY; 3]];
|
||||
for x in face {
|
||||
for k in 0..3 {
|
||||
b[0][k] = b[0][k].min(x[k] - margin);
|
||||
b[1][k] = b[1][k].max(x[k] + margin);
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// A uniform grid of boxes (a bucket sort), for the global contact search.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Grid {
|
||||
lowest: Vec3,
|
||||
cell: f64,
|
||||
dims: [usize; 3],
|
||||
/// Per cell, the range of its entries in `items` (compressed rows).
|
||||
start: Vec<usize>,
|
||||
items: Vec<u32>,
|
||||
}
|
||||
|
||||
/// Most cells of a grid (whatever `max_cells` says).
|
||||
pub const MAX_GRID_CELLS: usize = 1 << 24;
|
||||
|
||||
/// Most entries of a grid (box × cell overlaps).
|
||||
pub const MAX_GRID_ITEMS: usize = 1 << 27;
|
||||
|
||||
impl Grid {
|
||||
/// The grid of `boxes` (their indices are the entries; boxes that are not finite are left
|
||||
/// out), with at most `max_cells` cells (and [`MAX_GRID_CELLS`]).
|
||||
pub fn new(boxes: &[Aabb], max_cells: usize) -> Grid {
|
||||
let finite = |b: &Aabb| b.iter().flatten().all(|c| c.is_finite()) && (0..3).all(|k| b[0][k] <= b[1][k]);
|
||||
let mut lowest = [f64::INFINITY; 3];
|
||||
let mut highest = [f64::NEG_INFINITY; 3];
|
||||
let (mut count, mut extent) = (0usize, 0.0);
|
||||
for b in boxes.iter().filter(|b| finite(b)) {
|
||||
for k in 0..3 {
|
||||
lowest[k] = lowest[k].min(b[0][k]);
|
||||
highest[k] = highest[k].max(b[1][k]);
|
||||
}
|
||||
extent += (0..3).map(|k| b[1][k] - b[0][k]).fold(0.0, f64::max);
|
||||
count += 1;
|
||||
}
|
||||
if count == 0 {
|
||||
return Grid::default();
|
||||
}
|
||||
let span = (0..3).map(|k| highest[k] - lowest[k]).fold(0.0, f64::max);
|
||||
let max_cells = max_cells.clamp(1, MAX_GRID_CELLS);
|
||||
// Twice the mean box size, but not below a millionth of the span (point-like boxes).
|
||||
let mut cell = (2.0 * extent / count as f64).max(1e-6 * span).max(f64::MIN_POSITIVE);
|
||||
for _ in 0..200 {
|
||||
let dims = [0, 1, 2].map(|k| ((highest[k] - lowest[k]) / cell).floor() + 1.0);
|
||||
let cells = dims[0] * dims[1] * dims[2];
|
||||
if !(cells <= max_cells as f64) {
|
||||
cell *= (cells / max_cells as f64).cbrt().max(1.01) * 1.01;
|
||||
continue;
|
||||
}
|
||||
let dims = dims.map(|d| d as usize);
|
||||
let mut grid = Grid { lowest, cell, dims, start: vec![0; dims[0] * dims[1] * dims[2] + 1], items: Vec::new() };
|
||||
// Count the entries per cell, then fill (compressed rows, boxes in order).
|
||||
let mut total = 0usize;
|
||||
for b in boxes.iter().filter(|b| finite(b)) {
|
||||
let (lo, hi) = (grid.coordinates(b[0]), grid.coordinates(b[1]));
|
||||
total = total.saturating_add((0..3).map(|k| hi[k] - lo[k] + 1).product::<usize>());
|
||||
}
|
||||
if total > MAX_GRID_ITEMS {
|
||||
cell *= 2.0;
|
||||
continue;
|
||||
}
|
||||
for b in boxes.iter().filter(|b| finite(b)) {
|
||||
grid.each_cell(b, |c, start| start[c + 1] += 1);
|
||||
}
|
||||
for c in 0..grid.start.len() - 1 {
|
||||
grid.start[c + 1] += grid.start[c];
|
||||
}
|
||||
let mut next = grid.start.clone();
|
||||
let mut items = vec![0u32; total];
|
||||
for (i, b) in boxes.iter().enumerate().filter(|(_, b)| finite(b)) {
|
||||
grid.each_cell(b, |c, _| {
|
||||
if let (Some(slot), Some(item)) = (next.get_mut(c), u32::try_from(i).ok()) {
|
||||
if let Some(e) = items.get_mut(*slot) {
|
||||
*e = item;
|
||||
}
|
||||
*slot += 1;
|
||||
}
|
||||
});
|
||||
}
|
||||
grid.items = items;
|
||||
return grid;
|
||||
}
|
||||
Grid::default()
|
||||
}
|
||||
|
||||
/// The cell coordinates of a point inside the grid's span (clamped to it).
|
||||
fn coordinates(&self, x: Vec3) -> [usize; 3] {
|
||||
[0, 1, 2].map(|k| {
|
||||
let c = ((x[k] - self.lowest[k]) / self.cell).floor();
|
||||
if c > 0.0 { (c as usize).min(self.dims[k].saturating_sub(1)) } else { 0 }
|
||||
})
|
||||
}
|
||||
|
||||
fn index(&self, c: [usize; 3]) -> usize {
|
||||
c[0] + self.dims[0] * (c[1] + self.dims[1] * c[2])
|
||||
}
|
||||
|
||||
/// Call `f(cell, start)` for every cell a box overlaps.
|
||||
fn each_cell(&mut self, b: &Aabb, mut f: impl FnMut(usize, &mut Vec<usize>)) {
|
||||
let (lo, hi) = (self.coordinates(b[0]), self.coordinates(b[1]));
|
||||
for k in lo[2]..=hi[2] {
|
||||
for j in lo[1]..=hi[1] {
|
||||
for i in lo[0]..=hi[0] {
|
||||
let c = self.index([i, j, k]);
|
||||
f(c, &mut self.start);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The boxes that may hold `p`: those listed in its cell, in box order (empty outside the
|
||||
/// grid).
|
||||
pub fn candidates(&self, p: Vec3) -> &[u32] {
|
||||
if self.items.is_empty() || p.iter().any(|c| !c.is_finite()) {
|
||||
return &[];
|
||||
}
|
||||
let outside = (0..3).any(|k| p[k] < self.lowest[k] || p[k] > self.lowest[k] + self.cell * self.dims[k] as f64);
|
||||
if outside {
|
||||
return &[];
|
||||
}
|
||||
let c = self.index(self.coordinates(p));
|
||||
match (self.start.get(c), self.start.get(c + 1)) {
|
||||
(Some(a), Some(b)) => self.items.get(*a..*b).unwrap_or_default(),
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// The boxes that may overlap box `b`: those listed in the cells it overlaps, in box order
|
||||
/// without repeats (into `out`, cleared first).
|
||||
pub fn candidates_in(&self, b: &Aabb, out: &mut Vec<u32>) {
|
||||
out.clear();
|
||||
if self.items.is_empty() || b.iter().flatten().any(|c| !c.is_finite()) {
|
||||
return;
|
||||
}
|
||||
let top = [0, 1, 2].map(|k| self.lowest[k] + self.cell * self.dims[k] as f64);
|
||||
if (0..3).any(|k| b[1][k] < self.lowest[k] || b[0][k] > top[k]) {
|
||||
return;
|
||||
}
|
||||
let (lo, hi) = (self.coordinates(b[0]), self.coordinates(b[1]));
|
||||
for k in lo[2]..=hi[2] {
|
||||
for j in lo[1]..=hi[1] {
|
||||
for i in lo[0]..=hi[0] {
|
||||
let c = self.index([i, j, k]);
|
||||
if let (Some(a), Some(e)) = (self.start.get(c), self.start.get(c + 1)) {
|
||||
out.extend_from_slice(self.items.get(*a..*e).unwrap_or_default());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort_unstable();
|
||||
out.dedup();
|
||||
}
|
||||
|
||||
/// The number of entries (box × cell overlaps).
|
||||
pub fn entries(&self) -> usize {
|
||||
self.items.len()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn close(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-12
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn triangle_projection_covers_the_face_its_edges_and_corners() {
|
||||
let t = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [0.0, 2.0, 0.0]];
|
||||
// Above the inside: the foot of the perpendicular, positive gap along +z.
|
||||
let p = closest_point(&t, [0.5, 0.25, 0.3]).unwrap();
|
||||
assert!(close(p.gap, 0.3) && close(p.lateral, 0.0) && close(p.point[0], 0.5) && close(p.point[1], 0.25));
|
||||
assert!(close(p.weights.iter().sum::<f64>(), 1.0) && p.normal == [0.0, 0.0, 1.0]);
|
||||
// Below: a negative gap.
|
||||
assert!(close(closest_point(&t, [0.5, 0.5, -0.1]).unwrap().gap, -0.1));
|
||||
// Past the hypotenuse: the closest point is on it, the offset lateral.
|
||||
let p = closest_point(&t, [2.0, 2.0, 0.0]).unwrap();
|
||||
assert!(close(p.point[0], 1.0) && close(p.point[1], 1.0) && close(p.lateral, 2f64.sqrt()) && close(p.gap, 0.0));
|
||||
// Past a corner.
|
||||
let p = closest_point(&t, [-1.0, -1.0, 1.0]).unwrap();
|
||||
assert_eq!(p.weights, [1.0, 0.0, 0.0, 0.0]);
|
||||
assert!(close(p.distance, 3f64.sqrt()));
|
||||
// Degenerate and hostile faces give nothing.
|
||||
assert!(closest_point(&[[0.0; 3], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0]], [0.0, 1.0, 0.0]).is_none());
|
||||
assert!(closest_point(&t, [f64::NAN, 0.0, 0.0]).is_none());
|
||||
assert!(closest_point(&t[..2], [0.0; 3]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quadrilateral_projection_finds_the_foot_on_a_warped_patch() {
|
||||
let flat = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [2.0, 1.0, 0.0], [0.0, 1.0, 0.0]];
|
||||
let p = closest_point(&flat, [1.5, 0.25, -0.2]).unwrap();
|
||||
assert!(close(p.xi[0], 0.5) && close(p.xi[1], -0.5) && close(p.gap, -0.2) && close(p.lateral, 0.0));
|
||||
assert!(close(p.weights.iter().sum::<f64>(), 1.0));
|
||||
// A warped (hyperbolic paraboloid) patch: the residual is normal to the surface.
|
||||
let warped = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.2], [1.0, 1.0, 0.0], [0.0, 1.0, 0.2]];
|
||||
let q = [0.3, 0.6, 0.5];
|
||||
let p = closest_point(&warped, q).unwrap();
|
||||
let (_, ds, dt) = bilinear(p.xi[0], p.xi[1]);
|
||||
let r = sub(q, p.point);
|
||||
assert!(dot(r, combine(&warped, &ds)).abs() < 1e-12 && dot(r, combine(&warped, &dt)).abs() < 1e-12, "{p:?}");
|
||||
assert!(p.lateral < 1e-9 && p.gap > 0.0);
|
||||
// Beyond an edge: clamped, with the offset lateral.
|
||||
let p = closest_point(&flat, [3.0, 0.5, 0.0]).unwrap();
|
||||
assert!(close(p.xi[0], 1.0) && close(p.lateral, 1.0));
|
||||
// A quadrilateral collapsed to a segment has no normal.
|
||||
assert!(closest_point(&[[0.0; 3], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0; 3]], [0.5, 0.5, 0.0]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_grid_finds_every_box_holding_a_point_and_stays_bounded() {
|
||||
let boxes: Vec<Aabb> = (0..50).map(|i| [[i as f64, 0.0, 0.0], [i as f64 + 1.5, 1.0, 1.0]]).collect();
|
||||
let grid = Grid::new(&boxes, 1000);
|
||||
for k in 0..500 {
|
||||
let p = [k as f64 * 0.1 + 0.01, 0.5, 0.5];
|
||||
let found = grid.candidates(p);
|
||||
for (i, b) in boxes.iter().enumerate() {
|
||||
let inside = (0..3).all(|d| p[d] >= b[0][d] && p[d] <= b[1][d]);
|
||||
assert!(!inside || found.contains(&(i as u32)), "point {p:?} misses box {i}");
|
||||
}
|
||||
assert!(found.windows(2).all(|w| w[0] < w[1]), "candidates in box order");
|
||||
}
|
||||
assert!(grid.candidates([-5.0, 0.0, 0.0]).is_empty() && grid.candidates([f64::NAN; 3]).is_empty());
|
||||
// One huge box among small ones, a cap of one cell, boxes that are not finite: still
|
||||
// bounded and correct.
|
||||
let mut mixed = boxes.clone();
|
||||
mixed.push([[-1e6, -1e6, -1e6], [1e6, 1e6, 1e6]]);
|
||||
mixed.push([[f64::NAN, 0.0, 0.0], [1.0, 1.0, 1.0]]);
|
||||
for cells in [1, 10, 1 << 30] {
|
||||
let g = Grid::new(&mixed, cells);
|
||||
assert!(g.candidates([10.2, 0.5, 0.5]).contains(&50) && g.candidates([10.2, 0.5, 0.5]).contains(&9));
|
||||
assert!(!g.candidates([10.2, 0.5, 0.5]).contains(&51));
|
||||
assert!(g.entries() <= MAX_GRID_ITEMS);
|
||||
}
|
||||
assert_eq!(Grid::new(&[], 10).candidates([0.0; 3]), &[] as &[u32]);
|
||||
// Box queries: every box that overlaps, once, in order.
|
||||
let mut found = Vec::new();
|
||||
grid.candidates_in(&[[10.2, 0.2, 0.2], [12.1, 0.4, 0.4]], &mut found);
|
||||
let expected: Vec<u32> = (0..50).filter(|i| boxes[*i as usize][0][0] <= 12.1 && boxes[*i as usize][1][0] >= 10.2).collect();
|
||||
assert!(expected.iter().all(|e| found.contains(e)) && found.windows(2).all(|w| w[0] < w[1]), "{found:?} {expected:?}");
|
||||
grid.candidates_in(&[[-9.0, 0.0, 0.0], [-8.0, 1.0, 1.0]], &mut found);
|
||||
assert!(found.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -194,7 +194,12 @@ fn add_point(force: &mut [f64], k: Option<&mut Matrix>, gradients: &[[f64; 3]],
|
||||
if !geometric {
|
||||
return;
|
||||
}
|
||||
let tau = crate::rotation::tensor(&r.stress);
|
||||
add_geometric(k, gradients, &r.stress, w);
|
||||
}
|
||||
|
||||
/// K_ab += w (∇N_a · τ ∇N_b) I, the geometric (initial-stress) term.
|
||||
fn add_geometric(k: &mut Matrix, gradients: &[[f64; 3]], stress: &[f64; 6], w: f64) {
|
||||
let tau = crate::rotation::tensor(stress);
|
||||
let n = k.n;
|
||||
for (a, ga) in gradients.iter().enumerate() {
|
||||
let tg: [f64; 3] = std::array::from_fn(|i| (0..3).map(|jj| tau[i][jj] * ga[jj]).sum());
|
||||
@@ -458,6 +463,58 @@ impl Solid<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
impl Solid<'_> {
|
||||
/// The initial-stress (geometric) stiffness of a stress state given at the stiffness
|
||||
/// integration points: K_σ,ab = ∫ (∇N_a · σ ∇N_b) I dV over the reference element, the
|
||||
/// geometric term of the tangent with the reference gradients (linear buckling: Bathe 2014,
|
||||
/// §6.8.2; the same term as [`Solid::nonlinear`]'s at u = 0 with τ = σ).
|
||||
pub fn geometric_stiffness(&self, stress: &[[f64; 6]]) -> Result<Matrix> {
|
||||
let points = self.rule().points();
|
||||
if stress.len() != points.len() {
|
||||
return Err(Error::Invalid(format!("{} stresses for {} integration points", stress.len(), points.len())));
|
||||
}
|
||||
let n = self.ty.nodes;
|
||||
let mut k = Matrix::zeros(3 * n);
|
||||
for (p, s) in points.iter().zip(stress) {
|
||||
if s.iter().any(|v| !v.is_finite()) {
|
||||
return Err(Error::Invalid("stresses must be finite".into()));
|
||||
}
|
||||
let g = self.gradients(p.xi)?;
|
||||
add_geometric(&mut k, g.dx.get(..n).unwrap_or_default(), s, g.det * p.weight);
|
||||
}
|
||||
Ok(k)
|
||||
}
|
||||
}
|
||||
|
||||
impl Plane<'_> {
|
||||
/// The initial-stress stiffness of a 2D element (u, v per node) for the stresses of
|
||||
/// [`Plane::stresses_with`] at its stiffness points: the in-plane term and, axisymmetric,
|
||||
/// the hoop stress's σ_θθ N_a N_b / r² on the radial motion.
|
||||
pub fn geometric_stiffness(&self, stress: &[[f64; 6]]) -> Result<Matrix> {
|
||||
let rule = self.rule().points();
|
||||
if stress.len() != rule.len() {
|
||||
return Err(Error::Invalid(format!("{} stresses for {} integration points", stress.len(), rule.len())));
|
||||
}
|
||||
let n = self.ty.nodes;
|
||||
let mut k = Matrix::zeros(2 * n);
|
||||
for (p, s) in rule.iter().zip(stress) {
|
||||
if s.iter().any(|v| !v.is_finite()) {
|
||||
return Err(Error::Invalid("stresses must be finite".into()));
|
||||
}
|
||||
let at = self.at(p)?;
|
||||
let cols = at.g.get(..n).unwrap_or_default();
|
||||
for (a, ga) in cols.iter().enumerate() {
|
||||
for (b, gb) in cols.iter().enumerate() {
|
||||
let v = ga[0] * gb[0] * s[0] + ga[1] * gb[1] * s[1] + (ga[0] * gb[1] + ga[1] * gb[0]) * s[3];
|
||||
k.add(2 * a, 2 * b, at.dv * (v + s[2] * ga[2] * gb[2]));
|
||||
k.add(2 * a + 1, 2 * b + 1, at.dv * v);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(k)
|
||||
}
|
||||
}
|
||||
|
||||
/// One integration point of a 2D element in a nonlinear step: the total deformation gradient,
|
||||
/// det F_m, the reference position and the response.
|
||||
struct PlanePoint {
|
||||
@@ -958,4 +1015,32 @@ mod tests {
|
||||
let stress = Plane::new(ElementKind::Quad4, &quad8[..4], Formulation::Full, Theory::PlaneStress { thickness: 1.0 }).unwrap();
|
||||
assert!(matches!(stress.finite_strain(&svk, &[[0.0; 2]; 4], &[], &mut [], true), Err(Error::NotSupported(_))));
|
||||
}
|
||||
|
||||
/// uᵀ K_σ u = ∫ σ_xx (∂u_y/∂x)² dV = σ_xx V for u_y = x under a uniform σ_xx, in a distorted
|
||||
/// hex20 and a plane strain quad8, and K_σ annihilates rigid translations.
|
||||
#[test]
|
||||
fn geometric_stiffness_of_a_uniform_stress() {
|
||||
let sigma = 2.5;
|
||||
let hex: Vec<[f64; 3]> = crate::basis::Basis::Hex20
|
||||
.nodes()
|
||||
.iter()
|
||||
.map(|p| [1.0 + 0.6 * p[0] + 0.05 * p[1] * p[2], 0.8 * p[1], 0.7 * p[2] + 0.03 * p[0]])
|
||||
.collect();
|
||||
let solid = Solid::new(ElementKind::Hex20, &hex, Formulation::Full).unwrap();
|
||||
let points = solid.rule().points().len();
|
||||
let k = solid.geometric_stiffness(&vec![[sigma, 0.0, 0.0, 0.0, 0.0, 0.0]; points]).unwrap();
|
||||
let u: Vec<f64> = hex.iter().flat_map(|x| [0.0, x[0], 0.0]).collect();
|
||||
let energy: f64 = (0..u.len()).map(|i| u[i] * (0..u.len()).map(|j| k.get(i, j) * u[j]).sum::<f64>()).sum();
|
||||
assert!((energy - sigma * solid.volume().unwrap()).abs() < 1e-12, "{energy}");
|
||||
let t: Vec<f64> = hex.iter().flat_map(|_| [0.3, -0.2, 1.0]).collect();
|
||||
assert!(k.mul_vec(&t).iter().all(|v| v.abs() < 1e-12));
|
||||
assert!(solid.geometric_stiffness(&[[sigma, 0.0, 0.0, 0.0, 0.0, 0.0]]).is_err());
|
||||
let quad: Vec<[f64; 3]> = crate::basis::Basis::Quad8.nodes().iter().map(|p| [1.0 + 0.5 * p[0] + 0.04 * p[1], 0.6 * p[1], 0.0]).collect();
|
||||
let plane =
|
||||
crate::plane::Plane::new(ElementKind::Quad8, &quad, Formulation::Full, crate::plane::Theory::PlaneStrain { thickness: 0.3 }).unwrap();
|
||||
let k = plane.geometric_stiffness(&vec![[sigma, 0.0, 0.0, 0.0, 0.0, 0.0]; plane.rule().points().len()]).unwrap();
|
||||
let u: Vec<f64> = quad.iter().flat_map(|x| [0.0, x[0]]).collect();
|
||||
let energy: f64 = (0..u.len()).map(|i| u[i] * (0..u.len()).map(|j| k.get(i, j) * u[j]).sum::<f64>()).sum();
|
||||
assert!((energy - sigma * plane.volume().unwrap()).abs() < 1e-12, "{energy}");
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,8 @@
|
||||
//! - [`beam`]: two-node Timoshenko beams with profile section properties;
|
||||
//! - [`frame`]: local axes of shells and beams and the rotation of their matrices;
|
||||
//! - [`face`]: consistent nodal forces of pressure on element faces;
|
||||
//! - [`contact`]: contact geometry: the closest point of an element face to a point and the
|
||||
//! bucket grid of the global search;
|
||||
//! - [`heat`]: heat conduction (conductivity, capacity, sources, surface flux and convection,
|
||||
//! heat flux); thermal strain loads and stresses are in [`element`];
|
||||
//! - [`uniform`]: uniform-strain (one-point) hexahedron and tetrahedron kinematics, hourglass
|
||||
@@ -54,6 +56,7 @@
|
||||
pub mod basis;
|
||||
pub mod beam;
|
||||
pub mod constitutive;
|
||||
pub mod contact;
|
||||
pub mod dense;
|
||||
pub mod dof;
|
||||
pub mod elastoplastic;
|
||||
|
||||
@@ -98,7 +98,7 @@ impl Backend for Headless {
|
||||
}
|
||||
|
||||
fn commands(&mut self) -> Result<Value, String> {
|
||||
Ok(fieldcraft_engine::commands().iter().map(|c| json!({"id": c.id, "label": c.label, "params": c.params})).collect())
|
||||
Ok(fieldcraft_engine::commands().iter().map(fieldcraft_engine::CommandSpec::listing).collect())
|
||||
}
|
||||
|
||||
fn picture(&mut self, r: &PictureRequest) -> Result<Picture, String> {
|
||||
|
||||
@@ -243,6 +243,9 @@ fn a_batch_stops_at_the_first_error() {
|
||||
assert_eq!(ok(&mut s, "inspect_model", json!({}))["model"]["nodes"], 0);
|
||||
let listed = ok(&mut s, "list_commands", json!({"filter": "SOLVE."}));
|
||||
assert!(listed.as_array().unwrap().iter().all(|c| c["id"].as_str().unwrap().starts_with("solve.")));
|
||||
// Each command's parameters as JSON Schema, for agents to build valid calls.
|
||||
let statics = listed.as_array().unwrap().iter().find(|c| c["id"] == "solve.static").unwrap();
|
||||
assert_eq!(statics["schema"]["properties"]["threads"]["maximum"], 256);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -322,6 +322,7 @@ impl Model {
|
||||
Procedure::ExplicitDynamic(_) => "is dynamic",
|
||||
Procedure::HeatTransfer { transient: Some(_) } => "is transient heat transfer",
|
||||
Procedure::Static {}
|
||||
| Procedure::Buckle { .. }
|
||||
| Procedure::NonlinearStatic(_)
|
||||
| Procedure::Fluid { .. }
|
||||
| Procedure::HeatTransfer { transient: None }
|
||||
@@ -387,6 +388,22 @@ impl Model {
|
||||
}
|
||||
}
|
||||
|
||||
// Contacts: their surfaces are element faces of solids.
|
||||
for (name, c) in &self.contacts {
|
||||
for set in c.surfaces.sets() {
|
||||
let faces = &set_of(set).faces;
|
||||
let solid = |f: &crate::ElementFace| self.elements.get(&f.element).is_some_and(|e| e.kind.dimension() == 3);
|
||||
if faces.is_empty() {
|
||||
d.error(format!("contact `{name}`"), format!("set `{set}` has no element faces (a contact surface is a set of faces)"));
|
||||
} else if !faces.iter().all(solid) {
|
||||
d.error(
|
||||
format!("contact `{name}`"),
|
||||
format!("set `{set}` has faces of elements that are not solids (contact acts on the faces of solid elements so far)"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Nodes with rotational degrees of freedom: those of shells and beams, and reference points
|
||||
// (worked out only when a boundary condition or load needs it).
|
||||
let rotational = std::cell::OnceCell::new();
|
||||
@@ -470,7 +487,7 @@ impl Model {
|
||||
}
|
||||
}
|
||||
match &s.procedure {
|
||||
Procedure::Static {} | Procedure::NonlinearStatic(_) => {
|
||||
Procedure::Static {} | Procedure::NonlinearStatic(_) | Procedure::Buckle { .. } => {
|
||||
if s.loads.is_empty() && !prescribes_motion {
|
||||
d.warning(&subject, "nothing loads the model in this step");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
//! Contact: which surfaces may touch, and the friction between them.
|
||||
//!
|
||||
//! A contact is a model definition, active in every step that can take it (explicit dynamics;
|
||||
//! the implicit solver refuses contact by name for now). Its surfaces are sets with element
|
||||
//! faces, so they survive remeshing like a pressure load does:
|
||||
//! - a **pair**: the faces of `main` against those of `secondary`, both ways (each surface's
|
||||
//! nodes are kept out of the other's faces, so neither surface is privileged);
|
||||
//! - **general** contact: every face against every other face of one surface (single-surface or
|
||||
//! self contact, for folding and buckling), or of every exterior face of the model's solid
|
||||
//! elements when no surface is named.
|
||||
//!
|
||||
//! **Friction** is Coulomb's law with a coefficient that falls from its static to its kinetic
|
||||
//! value with the slip rate γ̇: μ = μ_k + (μ_s − μ_k) e^{−d γ̇} (the exponential decay of
|
||||
//! E. Rabinowicz's observations, as LS-DYNA's and Abaqus's exponential decay friction write it).
|
||||
//! The same friction applies to the planar rigid walls of an explicit step
|
||||
//! ([`crate::RigidWall`]).
|
||||
//!
|
||||
//! **Penalty.** Explicit contact pushes penetrating nodes back with a penalty spring whose
|
||||
//! stiffness the solver chooses from the masses and the stable time increment, the stiffest
|
||||
//! that leaves the increment alone; `penalty_scale` (at most 1) softens it.
|
||||
//!
|
||||
//! **Initial penetration.** Nodes of a surface that start inside the other surface are either
|
||||
//! moved onto it before the analysis, strain-free (`adjust`, the default, each one reported), or
|
||||
//! the analysis is refused naming the first node, its depth and the face it is behind
|
||||
//! (`refuse`).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Error, Model, Result, context, insert_new, remove_existing, replace_existing, require};
|
||||
|
||||
/// Most contact definitions in a model.
|
||||
pub const MAX_CONTACTS: usize = 1000;
|
||||
|
||||
/// Largest friction coefficient (a coefficient of 10 already locks every practical interface).
|
||||
pub const MAX_FRICTION: f64 = 10.0;
|
||||
|
||||
/// Largest exponential decay coefficient (time per length: 1/d is the slip rate at which the
|
||||
/// coefficient has gone 63% of the way from static to kinetic).
|
||||
pub const MAX_DECAY: f64 = 1e15;
|
||||
|
||||
/// Penalty scale factors outside this range are refused (above 1 the contact springs would
|
||||
/// shorten the stable time increment; see the module docs).
|
||||
pub const PENALTY_SCALE_RANGE: (f64, f64) = (1e-6, 1.0);
|
||||
|
||||
/// Coulomb friction with an exponential decay from the static to the kinetic coefficient.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Friction {
|
||||
/// The static coefficient μ_s (0: frictionless).
|
||||
#[serde(rename = "static", default)]
|
||||
pub static_coefficient: f64,
|
||||
/// The kinetic coefficient μ_k (by default the static one: no decay).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub kinetic: Option<f64>,
|
||||
/// The decay coefficient d of μ = μ_k + (μ_s − μ_k) e^{−d γ̇}, per slip rate (time per length).
|
||||
#[serde(default, skip_serializing_if = "is_zero")]
|
||||
pub decay: f64,
|
||||
}
|
||||
|
||||
fn is_zero(v: &f64) -> bool {
|
||||
*v == 0.0
|
||||
}
|
||||
|
||||
impl Friction {
|
||||
/// No friction.
|
||||
pub const NONE: Friction = Friction { static_coefficient: 0.0, kinetic: None, decay: 0.0 };
|
||||
|
||||
/// A constant coefficient.
|
||||
pub fn coulomb(mu: f64) -> Friction {
|
||||
Friction { static_coefficient: mu, ..Friction::NONE }
|
||||
}
|
||||
|
||||
pub fn is_frictionless(&self) -> bool {
|
||||
self.static_coefficient == 0.0 && self.kinetic.is_none_or(|k| k == 0.0)
|
||||
}
|
||||
|
||||
/// The kinetic coefficient (the static one when none is given).
|
||||
pub fn kinetic_coefficient(&self) -> f64 {
|
||||
self.kinetic.unwrap_or(self.static_coefficient)
|
||||
}
|
||||
|
||||
/// The coefficient at slip rate `rate` (≥ 0).
|
||||
pub fn coefficient(&self, rate: f64) -> f64 {
|
||||
let (s, k) = (self.static_coefficient, self.kinetic_coefficient());
|
||||
if self.decay == 0.0 { s } else { k + (s - k) * (-self.decay * rate.abs()).exp() }
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
for (what, v) in [("static friction coefficient", self.static_coefficient), ("kinetic friction coefficient", self.kinetic_coefficient())] {
|
||||
if !(0.0..=MAX_FRICTION).contains(&v) {
|
||||
return Err(Error::Invalid(format!("the {what} is in 0..={MAX_FRICTION}, got {v}")));
|
||||
}
|
||||
}
|
||||
if !(0.0..=MAX_DECAY).contains(&self.decay) {
|
||||
return Err(Error::Invalid(format!("the friction decay coefficient is in 0..={MAX_DECAY:e}, got {}", self.decay)));
|
||||
}
|
||||
if self.decay == 0.0 && self.kinetic_coefficient() != self.static_coefficient {
|
||||
return Err(Error::Invalid("a kinetic friction coefficient other than the static one needs a decay coefficient".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Which faces a contact puts against which.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum ContactSurfaces {
|
||||
/// The faces of two sets, each surface's nodes against the other's faces.
|
||||
Pair { main: String, secondary: String },
|
||||
/// Every face against every other face of a set's faces (single-surface or self contact), or
|
||||
/// of every exterior face of the model's solid elements when no set is named.
|
||||
General {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
surface: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
impl ContactSurfaces {
|
||||
/// The sets it names.
|
||||
pub fn sets(&self) -> Vec<&str> {
|
||||
match self {
|
||||
ContactSurfaces::Pair { main, secondary } => vec![main.as_str(), secondary.as_str()],
|
||||
ContactSurfaces::General { surface } => surface.iter().map(String::as_str).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What happens to nodes that start inside the surface they are in contact with.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum InitialPenetration {
|
||||
/// Move them onto the surface before the analysis (strain-free), and report them.
|
||||
#[default]
|
||||
Adjust,
|
||||
/// Refuse the analysis, naming the first one.
|
||||
Refuse,
|
||||
}
|
||||
|
||||
/// A contact definition.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Contact {
|
||||
pub surfaces: ContactSurfaces,
|
||||
#[serde(default, skip_serializing_if = "Friction::is_frictionless")]
|
||||
pub friction: Friction,
|
||||
/// A factor on the solver's penalty stiffness.
|
||||
#[serde(default = "one")]
|
||||
pub penalty_scale: f64,
|
||||
#[serde(default)]
|
||||
pub initial_penetration: InitialPenetration,
|
||||
}
|
||||
|
||||
fn one() -> f64 {
|
||||
1.0
|
||||
}
|
||||
|
||||
impl Contact {
|
||||
/// A frictionless contact with the default penalty and initial adjustment.
|
||||
pub fn new(surfaces: ContactSurfaces) -> Contact {
|
||||
Contact { surfaces, friction: Friction::NONE, penalty_scale: 1.0, initial_penetration: InitialPenetration::Adjust }
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
if let ContactSurfaces::Pair { main, secondary } = &self.surfaces
|
||||
&& main == secondary
|
||||
{
|
||||
return Err(Error::Invalid(format!(
|
||||
"a contact pair needs two different surfaces, got `{main}` twice (self contact is general contact on that surface)"
|
||||
)));
|
||||
}
|
||||
self.friction.validate()?;
|
||||
let (lo, hi) = PENALTY_SCALE_RANGE;
|
||||
if !(lo..=hi).contains(&self.penalty_scale) {
|
||||
return Err(Error::Invalid(format!("the penalty scale is in {lo:e}..={hi}, got {}", self.penalty_scale)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Model {
|
||||
pub fn contacts(&self) -> &BTreeMap<String, Contact> {
|
||||
&self.contacts
|
||||
}
|
||||
|
||||
pub fn contact(&self, name: &str) -> Option<&Contact> {
|
||||
self.contacts.get(name)
|
||||
}
|
||||
|
||||
fn check_contact(&self, name: &str, c: &Contact) -> Result<()> {
|
||||
c.validate().map_err(|e| context("contact", name, e))?;
|
||||
for set in c.surfaces.sets() {
|
||||
require(&self.sets, "set", set).map_err(|e| context("contact", name, e))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn add_contact(&mut self, name: &str, contact: Contact) -> Result<()> {
|
||||
self.check_contact(name, &contact)?;
|
||||
if self.contacts.len() >= MAX_CONTACTS {
|
||||
return Err(Error::Limit(format!("a model holds at most {MAX_CONTACTS} contacts")));
|
||||
}
|
||||
insert_new(&mut self.contacts, "contact", name, contact)
|
||||
}
|
||||
|
||||
pub fn replace_contact(&mut self, name: &str, contact: Contact) -> Result<()> {
|
||||
self.check_contact(name, &contact)?;
|
||||
replace_existing(&mut self.contacts, "contact", name, contact)
|
||||
}
|
||||
|
||||
pub fn remove_contact(&mut self, name: &str) -> Result<()> {
|
||||
remove_existing(&mut self.contacts, "contact", name).map(|_| ())
|
||||
}
|
||||
|
||||
/// The exterior faces of the solid elements (the faces no other solid element shares), in
|
||||
/// element and face order: the surface of general contact without a named set.
|
||||
pub fn exterior_faces(&self) -> Vec<crate::ElementFace> {
|
||||
let mut keyed: Vec<([u32; 4], crate::ElementFace)> = Vec::new();
|
||||
for (label, e) in self.elements.iter().filter(|(_, e)| e.kind.dimension() == 3) {
|
||||
for (i, local) in e.kind.faces().iter().enumerate() {
|
||||
// A face is known by its sorted corner nodes (three or four).
|
||||
let corners = if local.len() == 6 || local.len() == 3 { 3 } else { 4 };
|
||||
let mut key = [u32::MAX; 4];
|
||||
for (k, n) in key.iter_mut().zip(local.iter().take(corners)) {
|
||||
*k = e.nodes.get(*n).copied().unwrap_or(u32::MAX);
|
||||
}
|
||||
key.sort_unstable();
|
||||
keyed.push((key, crate::ElementFace { element: *label, face: i as u8 + 1 }));
|
||||
}
|
||||
}
|
||||
keyed.sort_unstable();
|
||||
let mut out: Vec<crate::ElementFace> = keyed
|
||||
.chunk_by(|a, b| a.0 == b.0)
|
||||
.filter_map(|run| match run {
|
||||
[(_, face)] => Some(*face),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
out.sort_unstable();
|
||||
out
|
||||
}
|
||||
|
||||
/// The contacts that name a set, as ``contact `name` `` strings.
|
||||
pub(crate) fn contact_users<'a>(&'a self, set: &'a str) -> impl Iterator<Item = String> + 'a {
|
||||
self.contacts.iter().filter(move |(_, c)| c.surfaces.sets().contains(&set)).map(|(n, _)| format!("contact `{n}`"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Set;
|
||||
|
||||
fn model() -> Model {
|
||||
let mut m = Model::default();
|
||||
for s in ["top", "bottom"] {
|
||||
m.add_set(s, Set { nodes: vec![1], ..Set::default() }).unwrap();
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contacts_validate_refer_to_sets_and_round_trip() {
|
||||
let mut m = model();
|
||||
let json = serde_json::json!({
|
||||
"surfaces": {"type": "pair", "main": "top", "secondary": "bottom"},
|
||||
"friction": {"static": 0.3, "kinetic": 0.2, "decay": 5.0}, "penalty_scale": 0.5
|
||||
});
|
||||
let c: Contact = serde_json::from_value(json).unwrap();
|
||||
assert_eq!((c.friction.static_coefficient, c.friction.kinetic_coefficient(), c.initial_penetration), (0.3, 0.2, InitialPenetration::Adjust));
|
||||
assert_eq!(serde_json::from_value::<Contact>(serde_json::to_value(&c).unwrap()).unwrap(), c);
|
||||
m.add_contact("impact", c.clone()).unwrap();
|
||||
assert!(matches!(m.remove_set("top"), Err(Error::InUse(_))), "the contact refers to the set");
|
||||
assert!(m.add_contact("impact", c.clone()).is_err(), "names stay unique");
|
||||
let general: Contact = serde_json::from_value(serde_json::json!({"surfaces": {"type": "general"}})).unwrap();
|
||||
assert_eq!(general.surfaces, ContactSurfaces::General { surface: None });
|
||||
assert!(general.friction.is_frictionless() && general.penalty_scale == 1.0);
|
||||
m.add_contact("everything", general).unwrap();
|
||||
m.remove_contact("impact").unwrap();
|
||||
m.remove_set("top").unwrap();
|
||||
assert!(m.remove_contact("impact").is_err());
|
||||
assert!(serde_json::from_value::<Contact>(serde_json::json!({"surfaces": {"type": "general"}, "mu": 1})).is_err(), "typos are errors");
|
||||
|
||||
let base = Contact::new(ContactSurfaces::Pair { main: "bottom".into(), secondary: "top".into() });
|
||||
let bad = [
|
||||
Contact { friction: Friction::coulomb(-0.1), ..base.clone() },
|
||||
Contact { friction: Friction::coulomb(f64::NAN), ..base.clone() },
|
||||
Contact { friction: Friction { kinetic: Some(f64::INFINITY), ..Friction::coulomb(0.1) }, ..base.clone() },
|
||||
Contact { friction: Friction { decay: -1.0, ..Friction::coulomb(0.1) }, ..base.clone() },
|
||||
Contact { penalty_scale: 0.0, ..base.clone() },
|
||||
Contact { penalty_scale: f64::NAN, ..base.clone() },
|
||||
Contact { penalty_scale: 1.5, ..base.clone() },
|
||||
Contact::new(ContactSurfaces::Pair { main: "bottom".into(), secondary: "bottom".into() }),
|
||||
];
|
||||
for b in bad {
|
||||
assert!(b.validate().is_err(), "{b:?}");
|
||||
}
|
||||
let missing = Contact::new(ContactSurfaces::General { surface: Some("nope".into()) });
|
||||
assert!(matches!(m.add_contact("x", missing), Err(Error::NotFound(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn friction_decays_from_static_to_kinetic() {
|
||||
let f = Friction { static_coefficient: 0.5, kinetic: Some(0.2), decay: 2.0 };
|
||||
assert_eq!(f.coefficient(0.0), 0.5);
|
||||
assert!((f.coefficient(1.0) - (0.2 + 0.3 * (-2.0f64).exp())).abs() < 1e-15);
|
||||
assert!((f.coefficient(1e6) - 0.2).abs() < 1e-15);
|
||||
assert_eq!(Friction::coulomb(0.3).coefficient(10.0), 0.3);
|
||||
// A kinetic coefficient acts through the decay.
|
||||
assert!(Friction { kinetic: Some(0.1), ..Friction::coulomb(0.3) }.validate().is_err());
|
||||
assert!(Friction { kinetic: Some(0.3), ..Friction::coulomb(0.3) }.validate().is_ok());
|
||||
assert!(Friction::NONE.is_frictionless() && !Friction::coulomb(0.1).is_frictionless());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_check_wants_solid_faces_on_contact_surfaces() {
|
||||
let mut m = Model::default();
|
||||
let corners = [[0., 0., 0.], [1., 0., 0.], [1., 1., 0.], [0., 1., 0.], [0., 0., 1.], [1., 0., 1.], [1., 1., 1.], [0., 1., 1.]];
|
||||
for (i, x) in corners.iter().enumerate() {
|
||||
m.set_node(i as u32 + 1, *x).unwrap();
|
||||
}
|
||||
m.set_element(1, crate::ElementKind::Hex8, (1..=8).collect()).unwrap();
|
||||
m.add_set("nodes", Set { nodes: vec![1, 2], ..Set::default() }).unwrap();
|
||||
m.add_set("top", Set { faces: vec![crate::ElementFace { element: 1, face: 2 }], ..Set::default() }).unwrap();
|
||||
m.add_contact("c", Contact::new(ContactSurfaces::Pair { main: "top".into(), secondary: "nodes".into() })).unwrap();
|
||||
let errors: Vec<String> = m.check().iter().filter(|d| d.severity == crate::Severity::Error).map(ToString::to_string).collect();
|
||||
assert!(errors.iter().any(|e| e.contains("contact `c`") && e.contains("set `nodes` has no element faces")), "{errors:?}");
|
||||
assert!(!errors.iter().any(|e| e.contains("set `top`")), "{errors:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exterior_faces_are_those_of_one_solid() {
|
||||
// Two hexahedra sharing a face, and a tetrahedron on the top of the second.
|
||||
let mut m = Model::default();
|
||||
for k in 0..3 {
|
||||
for (i, xy) in [[0., 0.], [1., 0.], [1., 1.], [0., 1.]].iter().enumerate() {
|
||||
m.set_node(4 * k + i as u32 + 1, [xy[0], xy[1], k as f64]).unwrap();
|
||||
}
|
||||
}
|
||||
m.set_node(13, [0.5, 0.5, 3.0]).unwrap();
|
||||
m.set_element(1, crate::ElementKind::Hex8, (1..=8).collect()).unwrap();
|
||||
m.set_element(2, crate::ElementKind::Hex8, (5..=12).collect()).unwrap();
|
||||
m.set_element(3, crate::ElementKind::Tet4, vec![9, 10, 11, 13]).unwrap();
|
||||
let faces = m.exterior_faces();
|
||||
let of = |e: u32| faces.iter().filter(|f| f.element == e).map(|f| f.face).collect::<Vec<_>>();
|
||||
assert_eq!(of(1), [1, 3, 4, 5, 6], "all but the shared top");
|
||||
assert_eq!(of(2), [2, 3, 4, 5, 6], "all but the shared bottom (its top meets the tet over half its area)");
|
||||
assert_eq!(of(3), [1, 2, 3, 4], "a triangle never matches a quad");
|
||||
assert!(Model::default().exterior_faces().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_model_holds_a_bounded_number_of_contacts() {
|
||||
let mut m = model();
|
||||
for i in 0..MAX_CONTACTS {
|
||||
m.add_contact(&format!("c{i}"), Contact::new(ContactSurfaces::General { surface: None })).unwrap();
|
||||
}
|
||||
assert!(matches!(m.add_contact("one-more", Contact::new(ContactSurfaces::General { surface: None })), Err(Error::Limit(_))));
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,7 @@
|
||||
pub mod bcs;
|
||||
pub mod check;
|
||||
pub mod constraints;
|
||||
pub mod contact;
|
||||
pub mod discrete;
|
||||
pub mod fluids;
|
||||
pub mod geometry;
|
||||
@@ -53,6 +54,7 @@ use serde::{Deserialize, Serialize};
|
||||
pub use bcs::{BoundaryCondition, Dofs, Symmetry, TEMPERATURE_DOF, Target};
|
||||
pub use check::{Diagnostic, Resolved, ResolvedSet, Severity};
|
||||
pub use constraints::{Coupling, CouplingKind, ReferencePoint};
|
||||
pub use contact::{Contact, ContactSurfaces, Friction, InitialPenetration};
|
||||
pub use discrete::{Direction, Mass, PointMass, ResolvedDirection, ResolvedMass, ResolvedSpring, Spring};
|
||||
pub use fluids::{BoxFace, BoxFaces, FaceCondition, FluidBoundary, FluidDomain, Profile, SurfaceBoundary, SurfaceCondition};
|
||||
pub use geometry::{Classification, Entity, GeometryRef};
|
||||
@@ -65,8 +67,9 @@ pub use mesh::{
|
||||
pub use sections::{BeamProfile, Extent, Formulation, Integration, Section, SectionKind};
|
||||
pub use sets::Set;
|
||||
pub use steps::{
|
||||
BulkViscosity, ExplicitDynamic, Hourglass, HourglassKind, InitialVelocity, MAX_LOAD_PATH_POINTS, MAX_NONLINEAR_INCREMENTS,
|
||||
MAX_NONLINEAR_ITERATIONS, NonlinearStatic, OutputVariable, Procedure, RigidWall, Step, StressRate, Tolerances, Transient,
|
||||
ArcConstraint, ArcLength, BulkViscosity, DisplacementLimit, ExplicitDynamic, Hourglass, HourglassKind, Imperfection, InitialVelocity,
|
||||
MAX_LOAD_PATH_POINTS, MAX_NONLINEAR_INCREMENTS, MAX_NONLINEAR_ITERATIONS, MassScaling, NonlinearStatic, OutputVariable, Procedure, RigidWall,
|
||||
Step, StressRate, Tolerances, Transient,
|
||||
};
|
||||
pub use units::UnitSystem;
|
||||
|
||||
@@ -123,6 +126,8 @@ pub struct Model {
|
||||
reference_points: BTreeMap<String, ReferencePoint>,
|
||||
couplings: BTreeMap<String, Coupling>,
|
||||
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
|
||||
contacts: BTreeMap<String, Contact>,
|
||||
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
|
||||
masses: BTreeMap<String, PointMass>,
|
||||
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
|
||||
springs: BTreeMap<String, Spring>,
|
||||
@@ -157,6 +162,8 @@ struct ModelData {
|
||||
#[serde(default)]
|
||||
couplings: BTreeMap<String, Coupling>,
|
||||
#[serde(default)]
|
||||
contacts: BTreeMap<String, Contact>,
|
||||
#[serde(default)]
|
||||
masses: BTreeMap<String, PointMass>,
|
||||
#[serde(default)]
|
||||
springs: BTreeMap<String, Spring>,
|
||||
@@ -215,6 +222,9 @@ impl TryFrom<ModelData> for Model {
|
||||
for (n, v) in d.couplings {
|
||||
m.add_coupling(&n, v)?;
|
||||
}
|
||||
for (n, v) in d.contacts {
|
||||
m.add_contact(&n, v)?;
|
||||
}
|
||||
for (n, v) in d.masses {
|
||||
m.add_mass(&n, v)?;
|
||||
}
|
||||
@@ -330,6 +340,7 @@ impl Model {
|
||||
sections: self.sections.clone(),
|
||||
reference_points: self.reference_points.clone(),
|
||||
couplings: self.couplings.clone(),
|
||||
contacts: self.contacts.clone(),
|
||||
masses: self.masses.clone(),
|
||||
springs: self.springs.clone(),
|
||||
boundary_conditions: self.boundary_conditions.clone(),
|
||||
@@ -340,13 +351,14 @@ impl Model {
|
||||
}
|
||||
|
||||
/// Counts of each kind of definition, for summaries.
|
||||
pub fn definition_counts(&self) -> [(&'static str, usize); 11] {
|
||||
pub fn definition_counts(&self) -> [(&'static str, usize); 12] {
|
||||
[
|
||||
("sets", self.sets.len()),
|
||||
("materials", self.materials.len()),
|
||||
("sections", self.sections.len()),
|
||||
("reference_points", self.reference_points.len()),
|
||||
("couplings", self.couplings.len()),
|
||||
("contacts", self.contacts.len()),
|
||||
("masses", self.masses.len()),
|
||||
("springs", self.springs.len()),
|
||||
("boundary_conditions", self.boundary_conditions.len()),
|
||||
|
||||
@@ -122,6 +122,7 @@ impl Model {
|
||||
let mut users = Vec::new();
|
||||
users.extend(self.sections.iter().filter(|(_, s)| s.set == set).map(|(n, _)| format!("section `{n}`")));
|
||||
users.extend(self.couplings.iter().filter(|(_, c)| c.set == set).map(|(n, _)| format!("coupling `{n}`")));
|
||||
users.extend(self.contact_users(set));
|
||||
users.extend(self.discrete_users(|t| t.set() == Some(set)));
|
||||
users
|
||||
.extend(self.boundary_conditions.iter().filter(|(_, b)| b.target().set() == Some(set)).map(|(n, _)| format!("boundary condition `{n}`")));
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::collections::BTreeSet;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Error, Model, Result, check_name, context, finite, positive, require};
|
||||
use crate::{Error, Friction, Model, Result, check_name, context, finite, positive, require};
|
||||
|
||||
/// Most steps in a model.
|
||||
pub const MAX_STEPS: usize = 1000;
|
||||
@@ -55,6 +55,14 @@ pub enum Procedure {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
max_hz: Option<f64>,
|
||||
},
|
||||
/// Linear buckling: the load factors λ at which the step's loads (and prescribed motions),
|
||||
/// applied as a linear preload, make K + λ K_σ singular, and their mode shapes; the lowest
|
||||
/// `modes` positive ones, or those nearest above `shift` when one is given.
|
||||
Buckle {
|
||||
modes: u32,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
shift: Option<f64>,
|
||||
},
|
||||
/// Transient dynamics by explicit time integration up to `end_time`.
|
||||
ExplicitDynamic(ExplicitDynamic),
|
||||
/// Time-dependent incompressible flow in a fluid domain, from rest (or the domain's initial
|
||||
@@ -137,6 +145,65 @@ pub struct NonlinearStatic {
|
||||
/// them (cyclic loading). Increments end at every point of the path.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub load_path: Option<Vec<[f64; 2]>>,
|
||||
/// A geometric imperfection: the mode shape of a buckling step, scaled, added to the node
|
||||
/// coordinates before this step is solved (the step and its results are on that geometry).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub imperfection: Option<Imperfection>,
|
||||
/// Arc-length (Riks–Crisfield) control: the load factor becomes an unknown, so the step can
|
||||
/// follow its equilibrium path through limit points (snap-through, snap-back). The first
|
||||
/// increment's load factor change is `initial_increment`; the increment sizes become arc
|
||||
/// lengths in proportion. `None`: load control.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub arc_length: Option<ArcLength>,
|
||||
}
|
||||
|
||||
/// The constraint of an arc-length step.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ArcConstraint {
|
||||
/// ‖Δu‖ = Δl (Crisfield's cylindrical arc).
|
||||
#[default]
|
||||
Cylindrical,
|
||||
/// ‖Δu‖² + Δλ² ‖u_f‖² = Δl², u_f the first increment's tangent displacement of the unit
|
||||
/// load (the spherical arc, scaled to displacement units).
|
||||
Spherical,
|
||||
}
|
||||
|
||||
/// When an arc-length step ends: at `max_load_factor` (default 1), when the displacement of
|
||||
/// `node` along `direction` (1, 2, 3) reaches `displacement` in magnitude, or at the step's
|
||||
/// increment cap, whichever comes first.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct ArcLength {
|
||||
pub constraint: ArcConstraint,
|
||||
pub max_load_factor: f64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub displacement_limit: Option<DisplacementLimit>,
|
||||
}
|
||||
|
||||
impl Default for ArcLength {
|
||||
fn default() -> ArcLength {
|
||||
ArcLength { constraint: ArcConstraint::Cylindrical, max_load_factor: 1.0, displacement_limit: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// A displacement that ends an arc-length step.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct DisplacementLimit {
|
||||
pub node: u32,
|
||||
pub direction: u8,
|
||||
pub displacement: f64,
|
||||
}
|
||||
|
||||
/// Mode `mode` (from 1) of buckling step `step`, scaled so its largest component is `scale`
|
||||
/// (a length), as an initial imperfection.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Imperfection {
|
||||
pub step: String,
|
||||
pub mode: u32,
|
||||
pub scale: f64,
|
||||
}
|
||||
|
||||
/// Most points of a nonlinear step's load path.
|
||||
@@ -173,6 +240,8 @@ impl Default for NonlinearStatic {
|
||||
tolerances: Tolerances::default(),
|
||||
line_search: false,
|
||||
load_path: None,
|
||||
imperfection: None,
|
||||
arc_length: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -182,6 +251,28 @@ impl NonlinearStatic {
|
||||
let fraction = |what: &str, v: f64| {
|
||||
if v > 0.0 && v <= 1.0 { Ok(v) } else { Err(Error::Invalid(format!("the {what} is a fraction of the step in (0, 1], got {v}"))) }
|
||||
};
|
||||
if let Some(arc) = &self.arc_length {
|
||||
if !(arc.max_load_factor.is_finite() && arc.max_load_factor > 0.0) {
|
||||
return Err(Error::Invalid(format!("an arc-length step's maximum load factor is a positive number, got {}", arc.max_load_factor)));
|
||||
}
|
||||
if let Some(l) = &arc.displacement_limit {
|
||||
if !(1..=3).contains(&l.direction) {
|
||||
return Err(Error::Invalid(format!("a displacement limit's direction is 1, 2 or 3, got {}", l.direction)));
|
||||
}
|
||||
if !(l.displacement.is_finite() && l.displacement != 0.0) {
|
||||
return Err(Error::Invalid(format!("a displacement limit is a nonzero number, got {}", l.displacement)));
|
||||
}
|
||||
}
|
||||
if self.load_path.is_some() {
|
||||
return Err(Error::Invalid("an arc-length step finds its own load factor; it takes no load path".into()));
|
||||
}
|
||||
}
|
||||
if let Some(imp) = &self.imperfection {
|
||||
if !(1..=MAX_MODES).contains(&imp.mode) {
|
||||
return Err(Error::Invalid(format!("an imperfection takes mode 1 to {MAX_MODES}, got {}", imp.mode)));
|
||||
}
|
||||
finite("imperfection scale", imp.scale)?;
|
||||
}
|
||||
let initial = fraction("initial increment", self.initial_increment)?;
|
||||
let min = fraction("minimum increment", self.min_increment)?;
|
||||
let max = fraction("maximum increment", self.max_increment)?;
|
||||
@@ -317,7 +408,7 @@ pub struct ExplicitDynamic {
|
||||
/// the last one listed).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub initial_velocities: Vec<InitialVelocity>,
|
||||
/// Fixed, frictionless rigid planes the nodes of sets cannot pass through.
|
||||
/// Fixed rigid planes the nodes of sets cannot pass through, with Coulomb friction.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub rigid_walls: Vec<RigidWall>,
|
||||
/// Hourglass control of one-point hexahedra.
|
||||
@@ -334,6 +425,22 @@ pub struct ExplicitDynamic {
|
||||
/// The objective stress rate of large deformation.
|
||||
#[serde(default)]
|
||||
pub stress_rate: StressRate,
|
||||
/// Opt-in mass scaling: the elements whose stable increment is below a target get the
|
||||
/// density that brings them to it (the added mass is reported).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub mass_scaling: Option<MassScaling>,
|
||||
}
|
||||
|
||||
/// Mass scaling to a target time increment: every element (of `set`, or of the whole model) whose
|
||||
/// stable increment, times the step's scale, is below `target_increment` has its density raised
|
||||
/// by (target / increment)², which brings it to the target. It changes the dynamics: the added
|
||||
/// mass is reported, per section, with its share of the kinetic energy.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct MassScaling {
|
||||
pub target_increment: f64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub set: Option<String>,
|
||||
}
|
||||
|
||||
fn yes() -> bool {
|
||||
@@ -376,6 +483,7 @@ impl ExplicitDynamic {
|
||||
bulk_viscosity: BulkViscosity::default(),
|
||||
nonlinear_geometry: true,
|
||||
stress_rate: StressRate::default(),
|
||||
mass_scaling: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -396,6 +504,7 @@ impl ExplicitDynamic {
|
||||
.map(String::as_str)
|
||||
.chain(self.initial_velocities.iter().map(|v| v.set.as_str()))
|
||||
.chain(self.rigid_walls.iter().map(|w| w.set.as_str()))
|
||||
.chain(self.mass_scaling.iter().filter_map(|m| m.set.as_deref()))
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
@@ -431,6 +540,13 @@ impl ExplicitDynamic {
|
||||
if !(w.normal.iter().map(|c| c * c).sum::<f64>() > 0.0) {
|
||||
return Err(Error::Invalid("a rigid wall's normal must not be zero".into()));
|
||||
}
|
||||
w.friction.validate().map_err(|e| Error::Invalid(format!("rigid wall on set `{}`: {e}", w.set)))?;
|
||||
}
|
||||
if let Some(m) = &self.mass_scaling {
|
||||
positive("mass scaling target increment", m.target_increment)?;
|
||||
if m.target_increment > end {
|
||||
return Err(Error::Invalid(format!("the mass scaling target increment {} is longer than the step", m.target_increment)));
|
||||
}
|
||||
}
|
||||
self.hourglass.validate()?;
|
||||
self.bulk_viscosity.validate()
|
||||
@@ -445,14 +561,16 @@ pub struct InitialVelocity {
|
||||
pub velocity: [f64; 3],
|
||||
}
|
||||
|
||||
/// A fixed, frictionless rigid plane through `point`. Its `normal` points to the side the nodes
|
||||
/// of `set` stay on.
|
||||
/// A fixed rigid plane through `point`. Its `normal` points to the side the nodes of `set` stay
|
||||
/// on; nodes sliding on it feel `friction` (frictionless by default).
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct RigidWall {
|
||||
pub set: String,
|
||||
pub point: [f64; 3],
|
||||
pub normal: [f64; 3],
|
||||
#[serde(default, skip_serializing_if = "Friction::is_frictionless")]
|
||||
pub friction: Friction,
|
||||
}
|
||||
|
||||
/// How one-point hexahedra resist their hourglass (zero-energy) modes.
|
||||
@@ -543,6 +661,7 @@ impl Procedure {
|
||||
match self {
|
||||
Procedure::Static {} => "static",
|
||||
Procedure::Frequency { .. } => "frequency",
|
||||
Procedure::Buckle { .. } => "buckle",
|
||||
Procedure::ExplicitDynamic(_) => "explicit_dynamic",
|
||||
Procedure::HeatTransfer { .. } => "heat_transfer",
|
||||
Procedure::CoupledTemperatureDisplacement {} => "coupled_temperature_displacement",
|
||||
@@ -615,6 +734,14 @@ impl Procedure {
|
||||
if let Procedure::HeatTransfer { transient: Some(t) } = self {
|
||||
return t.validate();
|
||||
}
|
||||
if let Procedure::Buckle { modes, shift } = *self {
|
||||
if !(1..=MAX_MODES).contains(&modes) {
|
||||
return Err(Error::Invalid(format!("a buckling step extracts 1 to {MAX_MODES} modes, got {modes}")));
|
||||
}
|
||||
if let Some(s) = shift {
|
||||
finite("buckling shift", s)?;
|
||||
}
|
||||
}
|
||||
if let Procedure::Frequency { modes, min_hz, max_hz } = *self {
|
||||
if !(1..=MAX_MODES).contains(&modes) {
|
||||
return Err(Error::Invalid(format!("a frequency step extracts 1 to {MAX_MODES} modes, got {modes}")));
|
||||
@@ -637,7 +764,7 @@ impl Procedure {
|
||||
pub fn default_output(&self) -> BTreeSet<OutputVariable> {
|
||||
match self {
|
||||
Procedure::Static {} | Procedure::NonlinearStatic(_) => OutputVariable::ALL.into_iter().collect(),
|
||||
Procedure::Frequency { .. } => [OutputVariable::Displacement].into_iter().collect(),
|
||||
Procedure::Frequency { .. } | Procedure::Buckle { .. } => [OutputVariable::Displacement].into_iter().collect(),
|
||||
Procedure::ExplicitDynamic(_) => [OutputVariable::Displacement, OutputVariable::Stress].into_iter().collect(),
|
||||
// Velocity, pressure and wall forces, always.
|
||||
Procedure::Fluid { .. } => BTreeSet::new(),
|
||||
@@ -870,7 +997,7 @@ mod tests {
|
||||
let json = serde_json::json!({
|
||||
"type": "explicit_dynamic", "end_time": 1e-3, "history_nodes": "front",
|
||||
"initial_velocities": [{"set": "front", "velocity": [-10, 0, 0]}],
|
||||
"rigid_walls": [{"set": "front", "point": [0, 0, 0], "normal": [1, 0, 0]}],
|
||||
"rigid_walls": [{"set": "front", "point": [0, 0, 0], "normal": [1, 0, 0], "friction": {"static": 0.2}}],
|
||||
"hourglass": {"type": "stiffness"}
|
||||
});
|
||||
let p: Procedure = serde_json::from_value(json).unwrap();
|
||||
@@ -895,13 +1022,23 @@ mod tests {
|
||||
ExplicitDynamic { max_increments: 0, ..base.clone() },
|
||||
ExplicitDynamic { output_interval: Some(1e-9), ..base.clone() },
|
||||
ExplicitDynamic { history_interval: Some(-1.0), ..base.clone() },
|
||||
ExplicitDynamic { rigid_walls: vec![RigidWall { set: "front".into(), point: [0.0; 3], normal: [0.0; 3] }], ..base.clone() },
|
||||
ExplicitDynamic {
|
||||
rigid_walls: vec![RigidWall { set: "front".into(), point: [0.0; 3], normal: [0.0; 3], friction: Friction::NONE }],
|
||||
..base.clone()
|
||||
},
|
||||
ExplicitDynamic {
|
||||
rigid_walls: vec![RigidWall { set: "front".into(), point: [0.0; 3], normal: [1.0, 0.0, 0.0], friction: Friction::coulomb(f64::NAN) }],
|
||||
..base.clone()
|
||||
},
|
||||
ExplicitDynamic {
|
||||
initial_velocities: vec![InitialVelocity { set: "front".into(), velocity: [f64::INFINITY, 0.0, 0.0] }],
|
||||
..base.clone()
|
||||
},
|
||||
ExplicitDynamic { hourglass: Hourglass { kind: HourglassKind::Viscous, coefficient: 2.0 }, ..base.clone() },
|
||||
ExplicitDynamic { bulk_viscosity: BulkViscosity { linear: -1.0, quadratic: 1.0 }, ..base.clone() },
|
||||
ExplicitDynamic { mass_scaling: Some(MassScaling { target_increment: 0.0, set: None }), ..base.clone() },
|
||||
ExplicitDynamic { mass_scaling: Some(MassScaling { target_increment: f64::NAN, set: None }), ..base.clone() },
|
||||
ExplicitDynamic { mass_scaling: Some(MassScaling { target_increment: 2.0, set: None }), ..base.clone() },
|
||||
];
|
||||
for b in bad {
|
||||
assert!(Procedure::ExplicitDynamic(b.clone()).validate().is_err(), "{b:?}");
|
||||
|
||||
@@ -874,12 +874,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn rigid_walls_back_their_set_and_initial_velocities_leave_it() {
|
||||
use fieldcraft_model::{ExplicitDynamic, InitialVelocity, Procedure, RigidWall, Step};
|
||||
use fieldcraft_model::{ExplicitDynamic, Friction, InitialVelocity, Procedure, RigidWall, Step};
|
||||
let mut m = bar(4);
|
||||
m.add_set("all", Set { nodes: m.nodes().keys().copied().collect(), ..Set::default() }).unwrap();
|
||||
let e = ExplicitDynamic {
|
||||
initial_velocities: vec![InitialVelocity { set: "all".into(), velocity: [-10.0, 0.0, 0.0] }],
|
||||
rigid_walls: vec![RigidWall { set: "root".into(), point: [0.0, 0.0, 0.0], normal: [1.0, 0.0, 0.0] }],
|
||||
rigid_walls: vec![RigidWall { set: "root".into(), point: [0.0, 0.0, 0.0], normal: [1.0, 0.0, 0.0], friction: Friction::NONE }],
|
||||
..ExplicitDynamic::new(1.0)
|
||||
};
|
||||
m.add_step(Step::new("Impact", Procedure::ExplicitDynamic(e)), None).unwrap();
|
||||
|
||||
@@ -14,6 +14,7 @@ use fieldcraft_parallel as parallel;
|
||||
use crate::cholesky::{Factor, FactorError, UpperColumns};
|
||||
use crate::constraints::{Budget, Reduction, coupling_rows};
|
||||
use crate::eigen::{Operator, Wanted, lanczos};
|
||||
use crate::ldlt::{Kind, Symmetric};
|
||||
use crate::ordering::nested_dissection;
|
||||
use crate::sparse::{Csr, NodeGraph, add_block, add_diagonal, add_scalar};
|
||||
use crate::system::{
|
||||
@@ -146,6 +147,9 @@ pub struct FrequencyResult {
|
||||
pub total_mass: f64,
|
||||
pub stats: Stats,
|
||||
pub warnings: Vec<String>,
|
||||
/// For a buckling step: its modes' eigenvalues are load factors (`frequency`, participation
|
||||
/// and total mass are zero) and this says what else the eigenproblem found.
|
||||
pub buckling: Option<crate::buckle::Buckling>,
|
||||
}
|
||||
|
||||
/// Mass matrix choice for a frequency analysis.
|
||||
@@ -167,8 +171,8 @@ pub struct FrequencyOptions {
|
||||
}
|
||||
|
||||
/// The assembled matrices and the model's mass.
|
||||
struct Assembled {
|
||||
k: Csr,
|
||||
pub(crate) struct Assembled {
|
||||
pub(crate) k: Csr,
|
||||
m: Option<Csr>,
|
||||
}
|
||||
|
||||
@@ -179,7 +183,7 @@ pub(crate) const ROUND: usize = 4096;
|
||||
pub(crate) const GRAIN: usize = 16;
|
||||
|
||||
/// Assemble the stiffness (and the mass when `mass` is set) on the mesh's node graph.
|
||||
fn assemble(mesh: &Mesh, graph: &NodeGraph, mass: Option<MassKind>) -> Result<Assembled> {
|
||||
pub(crate) fn assemble(mesh: &Mesh, graph: &NodeGraph, mass: Option<MassKind>) -> Result<Assembled> {
|
||||
let layout = &mesh.layout;
|
||||
let mut k = graph.zero_matrix(layout);
|
||||
let mut m = mass.map(|_| graph.zero_matrix(layout));
|
||||
@@ -250,6 +254,12 @@ pub(crate) fn factor_raw(a: &Csr, limits: &Limits) -> std::result::Result<Factor
|
||||
Factor::new(&UpperColumns::from_symmetric(a), limits.max_factor_entries)
|
||||
}
|
||||
|
||||
/// Factor a free-dof matrix by Cholesky, LDLᵀ, or Cholesky with LDLᵀ when it is not positive
|
||||
/// definite ([`Kind`]).
|
||||
pub(crate) fn factor_symmetric(a: &Csr, limits: &Limits, kind: Kind) -> std::result::Result<Symmetric, FactorError> {
|
||||
Symmetric::new(&UpperColumns::from_symmetric(a), limits.max_factor_entries, kind)
|
||||
}
|
||||
|
||||
/// A factorization failure in the user's terms: the node (or reference point) and direction of
|
||||
/// a singular pivot.
|
||||
pub(crate) fn factor_error(e: FactorError, mesh: &Mesh, reduction: &Reduction) -> Error {
|
||||
@@ -265,6 +275,12 @@ pub(crate) fn factor_error(e: FactorError, mesh: &Mesh, reduction: &Reduction) -
|
||||
"the stiffness is singular at {at}: the model can move without straining (missing or insufficient boundary conditions, a part not connected to the rest, or a reference point direction nothing holds)"
|
||||
))
|
||||
}
|
||||
FactorError::Singular { column } => {
|
||||
let at = reduction.eq_dof.get(column).map_or_else(|| "an unknown degree of freedom".to_string(), |d| mesh.describe_dof(*d));
|
||||
Error::Singular(format!(
|
||||
"the matrix is singular at {at}: no pivot of its supernode is more than round-off (a mechanism, or a shift or load at an eigenvalue)"
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -527,10 +543,17 @@ impl Operator for ShiftInvert<'_> {
|
||||
}
|
||||
|
||||
/// Block size of the Lanczos iteration: enough for the six rigid-body modes of a free body.
|
||||
const BLOCK: usize = 6;
|
||||
pub(crate) const BLOCK: usize = 6;
|
||||
|
||||
/// Most Lanczos vectors for `neq` equations: the basis (vectors and their mass products) costs
|
||||
/// 2 n × vectors, capped with the factor's entry limit.
|
||||
pub(crate) fn lanczos_basis(limits: &Limits, neq: usize) -> usize {
|
||||
let by_memory = limits.max_factor_entries / (2 * neq).max(1);
|
||||
limits.max_lanczos_vectors.min(by_memory).max(BLOCK.min(neq))
|
||||
}
|
||||
|
||||
/// Relative residual of an accepted Ritz pair.
|
||||
const TOLERANCE: f64 = 1e-9;
|
||||
pub(crate) const TOLERANCE: f64 = 1e-9;
|
||||
|
||||
/// Solve a frequency step (the step named `step`, or the model's only frequency step): the
|
||||
/// lowest natural modes within the step's frequency range.
|
||||
@@ -600,10 +623,7 @@ pub fn solve_frequency(model: &Model, step: Option<&str>, options: &FrequencyOpt
|
||||
min: min_hz.map_or(f64::NEG_INFINITY, |f| (two_pi * f).powi(2)),
|
||||
max: max_hz.map_or(f64::INFINITY, |f| (two_pi * f).powi(2)),
|
||||
};
|
||||
// The basis (vectors and their mass products) costs 2 n × vectors; cap it with the factor's
|
||||
// entry limit.
|
||||
let by_memory = limits.max_factor_entries / (2 * neq).max(1);
|
||||
let max_basis = limits.max_lanczos_vectors.min(by_memory).max(BLOCK.min(neq));
|
||||
let max_basis = lanczos_basis(limits, neq);
|
||||
let op = ShiftInvert { m: &mff, factor: &chol };
|
||||
let pairs = lanczos(&op, shift, wanted, BLOCK, max_basis, TOLERANCE)?;
|
||||
// Participation: Γ_d = φᵀ M r_d with r_d the unit translation along d on the free equations
|
||||
@@ -642,6 +662,7 @@ pub fn solve_frequency(model: &Model, step: Option<&str>, options: &FrequencyOpt
|
||||
total_mass,
|
||||
stats: Stats { dofs: mesh.dofs(), equations: neq, factor_entries: chol.entries(), lanczos_vectors: pairs.basis },
|
||||
warnings,
|
||||
buckling: None,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
//! Linear buckling: the load factors λ at which a step's loads, applied as a linear preload,
|
||||
//! make the structure lose stiffness, (K + λ K_σ) φ = 0, and the mode shapes φ (K.-J. Bathe,
|
||||
//! *Finite Element Procedures*, 2nd ed., 2014, §6.8.2).
|
||||
//!
|
||||
//! **Preload.** The step is solved as a linear static step (its loads and prescribed motions);
|
||||
//! the stresses at every element's stiffness points give the initial-stress stiffness
|
||||
//! K_σ = ∫ (∇N_a · σ ∇N_b) I dV ([`fieldcraft_fem::finite`]). The eigenproblem holds every
|
||||
//! boundary condition of the step at zero (the buckling motion is a perturbation of the
|
||||
//! preloaded state). Pressures act as dead loads: the load stiffness of a follower pressure is
|
||||
//! not part of K_σ.
|
||||
//!
|
||||
//! **Eigenproblem** by the block Lanczos of [`crate::eigen`], in the K inner product (K is
|
||||
//! positive definite for a supported structure, while K_σ is indefinite), after R. G. Grimes,
|
||||
//! J. G. Lewis, H. D. Simon, *A shifted block Lanczos algorithm for solving sparse symmetric
|
||||
//! generalized eigenproblems*, SIAM J. Matrix Anal. Appl. 15(1):228–272, 1994, §3 (the buckling
|
||||
//! transformations):
|
||||
//! - **without a shift**, the operator K⁻¹(−K_σ) has eigenvalues θ = 1/λ: the lowest positive
|
||||
//! load factors are its largest positive θ, well separated, and K is factored by Cholesky.
|
||||
//! Converged negative θ are the load factors of the reversed load (reported, not returned as
|
||||
//! modes);
|
||||
//! - **with a shift σ ≠ 0**, the buckling spectral transformation (K + σ K_σ)⁻¹ K has
|
||||
//! θ = λ/(λ − σ), largest for the load factors nearest above σ; K + σ K_σ is indefinite once σ
|
||||
//! passes the first load factor and is factored by LDLᵀ ([`crate::ldlt`]), whose inertia counts
|
||||
//! the load factors between 0 and σ (Sylvester's law), reported so none is missed silently.
|
||||
//!
|
||||
//! Modes are scaled to a largest component of 1 (positive). Solids and 2D elements only:
|
||||
//! trusses, shells and beams have no initial-stress stiffness yet and are refused by name.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use fieldcraft_model::{Model, Procedure};
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::analysis::{
|
||||
BLOCK, FrequencyResult, Mode, Setup, Stats, TOLERANCE, assemble, budget, factor_error, factor_symmetric, lanczos_basis, pattern, reduction,
|
||||
solve_static, split,
|
||||
};
|
||||
use crate::eigen::{Operator, Wanted, lanczos};
|
||||
use crate::ldlt::{Kind, Symmetric};
|
||||
use crate::sparse::{Csr, add_block};
|
||||
use crate::system::Mesh;
|
||||
use crate::{Error, Limits, Result};
|
||||
|
||||
/// What a buckling eigenproblem found besides its modes.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
|
||||
pub struct Buckling {
|
||||
/// Converged negative load factors (the load reversed buckles at |λ|), nearest to zero
|
||||
/// first; found without a shift only.
|
||||
pub negative: Vec<f64>,
|
||||
/// The shift, and the number of load factors between 0 and it (the inertia of K + σ K_σ).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub shift: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub below_shift: Option<usize>,
|
||||
}
|
||||
|
||||
/// K⁻¹(−K_σ) in the K inner product: θ = 1/λ.
|
||||
struct Plain<'a> {
|
||||
k: &'a Csr,
|
||||
/// −K_σ.
|
||||
g: &'a Csr,
|
||||
factor: &'a Symmetric,
|
||||
}
|
||||
|
||||
impl Operator for Plain<'_> {
|
||||
fn n(&self) -> usize {
|
||||
self.k.n
|
||||
}
|
||||
fn mass(&self, x: &[f64], y: &mut [f64]) {
|
||||
self.k.mul(x, y);
|
||||
}
|
||||
fn solve(&self, x: &mut [f64]) -> Result<()> {
|
||||
self.factor.solve(x)
|
||||
}
|
||||
fn operand(&self, x: &[f64], _kx: &[f64]) -> Vec<f64> {
|
||||
let mut y = vec![0.0; self.g.n];
|
||||
self.g.mul(x, &mut y);
|
||||
y
|
||||
}
|
||||
fn eigenvalue(&self, _shift: f64, theta: f64) -> f64 {
|
||||
1.0 / theta
|
||||
}
|
||||
}
|
||||
|
||||
/// (K + σ K_σ)⁻¹ K in the K inner product: θ = λ/(λ − σ).
|
||||
struct Shifted<'a> {
|
||||
k: &'a Csr,
|
||||
/// K + σ K_σ and its factor, for iterative refinement.
|
||||
shifted: &'a Csr,
|
||||
factor: &'a Symmetric,
|
||||
}
|
||||
|
||||
impl Operator for Shifted<'_> {
|
||||
fn n(&self) -> usize {
|
||||
self.k.n
|
||||
}
|
||||
fn mass(&self, x: &[f64], y: &mut [f64]) {
|
||||
self.k.mul(x, y);
|
||||
}
|
||||
fn solve(&self, x: &mut [f64]) -> Result<()> {
|
||||
self.factor.solve_refined(self.shifted, x, 2)
|
||||
}
|
||||
fn eigenvalue(&self, shift: f64, theta: f64) -> f64 {
|
||||
shift * theta / (theta - 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Solve a buckling step (the step named `step`, or the model's only buckling step).
|
||||
pub fn solve_buckle(model: &Model, step: Option<&str>, limits: &Limits) -> Result<FrequencyResult> {
|
||||
let step = model.select_step(step, |p| matches!(p, Procedure::Buckle { .. }), "buckling")?;
|
||||
let Procedure::Buckle { modes, shift } = step.procedure else {
|
||||
return Err(Error::Internal("buckling step".into()));
|
||||
};
|
||||
step.procedure.validate()?;
|
||||
let resolved = model.resolve()?;
|
||||
let mesh = Mesh::new(model, &resolved, limits.max_dofs)?;
|
||||
if let Some(t) = mesh.trusses.first() {
|
||||
return Err(Error::NotSupported(format!(
|
||||
"trusses in buckling steps (element {}): their initial-stress stiffness is not implemented",
|
||||
t.label
|
||||
)));
|
||||
}
|
||||
if let Some(s) = mesh.structural.first() {
|
||||
return Err(Error::NotSupported(format!(
|
||||
"shells and beams in buckling steps (element {}): their initial-stress stiffness is not implemented",
|
||||
s.label
|
||||
)));
|
||||
}
|
||||
// The preload: the step solved as a linear static step.
|
||||
let mut preload_model = model.clone();
|
||||
let mut preload_step = step.clone();
|
||||
preload_step.procedure = Procedure::Static {};
|
||||
preload_model.replace_step(preload_step)?;
|
||||
let preload = solve_static(&preload_model, Some(&step.name), limits)?;
|
||||
let mut warnings: Vec<String> = preload.warnings.clone();
|
||||
let stresses: BTreeMap<u32, Vec<[f64; 6]>> = preload.elements.iter().map(|e| (e.label, e.points.iter().map(|p| p.stress).collect())).collect();
|
||||
|
||||
let (graph, order) = pattern(&mesh);
|
||||
let setup = Setup { model, resolved: &resolved, mesh: &mesh, step };
|
||||
let red = reduction(&setup, false, &order, budget(limits, &mesh, &graph, 2), &mut Vec::new())?;
|
||||
let neq = red.neq();
|
||||
if neq == 0 {
|
||||
return Err(Error::Invalid("every degree of freedom is held; there is nothing to buckle".into()));
|
||||
}
|
||||
let k = assemble(&mesh, &graph, None)?.k;
|
||||
let mut kg = graph.zero_matrix(&mesh.layout);
|
||||
let matrices = fieldcraft_parallel::map_grained(mesh.elements.len(), crate::analysis::GRAIN, |i| -> Result<_> {
|
||||
let e = mesh.elements.get(i).ok_or_else(|| Error::Internal("element index".into()))?;
|
||||
let kernel = e.kernel()?;
|
||||
let stress = stresses.get(&e.label).ok_or_else(|| Error::Internal(format!("element {} has no preload stress", e.label)))?;
|
||||
Ok((kernel.dofs().node, kernel.geometric_stiffness(stress).map_err(|err| Error::element(e.label, err))?.data))
|
||||
});
|
||||
for (e, m) in mesh.elements.iter().zip(matrices) {
|
||||
let (kinds, data) = m?;
|
||||
add_block(&mut kg, &mesh.layout, &e.nodes, kinds, &data)?;
|
||||
}
|
||||
let [kff, gff] = red.reduce([&k, &kg])?;
|
||||
drop((k, kg));
|
||||
if gff.val.iter().all(|v| *v == 0.0) {
|
||||
return Err(Error::Invalid(format!("step `{}` puts no stress into the model, so nothing can buckle (give it loads)", step.name)));
|
||||
}
|
||||
let max_basis = lanczos_basis(limits, neq);
|
||||
let count = usize::try_from(modes).unwrap_or(usize::MAX).min(neq);
|
||||
let sigma = shift.unwrap_or(0.0);
|
||||
let (pairs, entries, buckling) = if sigma == 0.0 {
|
||||
let factor = factor_symmetric(&kff, limits, Kind::Definite).map_err(|e| factor_error(e, &mesh, &red))?;
|
||||
let minus = Csr { val: gff.val.iter().map(|v| -v).collect(), ..gff.clone() };
|
||||
let op = Plain { k: &kff, g: &minus, factor: &factor };
|
||||
let pairs = lanczos(&op, 0.0, Wanted { count, min: 0.0, max: f64::INFINITY }, BLOCK, max_basis, TOLERANCE)?;
|
||||
let buckling = Buckling { negative: pairs.negative.clone(), shift: None, below_shift: None };
|
||||
(pairs, factor.entries(), buckling)
|
||||
} else {
|
||||
let shifted = kff.add_scaled(sigma, &gff)?;
|
||||
let factor = factor_symmetric(&shifted, limits, Kind::Indefinite).map_err(|e| match e {
|
||||
crate::cholesky::FactorError::Singular { .. } => {
|
||||
Error::Singular(format!("the shift {sigma} is a buckling load factor (K + σ K_σ is singular); move it a little"))
|
||||
}
|
||||
e => factor_error(e, &mesh, &red),
|
||||
})?;
|
||||
let below = factor.inertia().negative;
|
||||
if below > 0 {
|
||||
warnings.push(format!("{below} buckling load factor(s) lie between 0 and the shift {sigma}; the modes returned are those above it"));
|
||||
}
|
||||
let op = Shifted { k: &kff, shifted: &shifted, factor: &factor };
|
||||
let (min, max) = if sigma > 0.0 { (sigma, f64::INFINITY) } else { (f64::NEG_INFINITY, f64::INFINITY) };
|
||||
let pairs = lanczos(&op, sigma, Wanted { count, min, max }, BLOCK, max_basis, TOLERANCE)?;
|
||||
(pairs, factor.entries(), Buckling { negative: Vec::new(), shift: Some(sigma), below_shift: Some(below) })
|
||||
};
|
||||
if let Some(first) = buckling.negative.first() {
|
||||
warnings.push(format!("the reversed load buckles too: negative load factor {first:.6e} (and {} more found)", buckling.negative.len() - 1));
|
||||
}
|
||||
let mut out = Vec::with_capacity(pairs.values.len());
|
||||
for (lambda, phi) in pairs.values.iter().zip(&pairs.vectors) {
|
||||
// Scale to a largest component of 1 (Lanczos already made it positive).
|
||||
let big = phi.iter().fold(0.0f64, |m, v| m.max(v.abs()));
|
||||
let scaled: Vec<f64> = phi.iter().map(|v| if big > 0.0 { v / big } else { *v }).collect();
|
||||
let (shape, rotation, point_shape) = split(&red.expand(&scaled, false), &mesh);
|
||||
out.push(Mode { eigenvalue: *lambda, frequency: 0.0, shape, rotation, participation: [0.0; 3], effective_mass: [0.0; 3], point_shape });
|
||||
}
|
||||
if out.len() < count {
|
||||
warnings.push(format!("found {} of the {modes} buckling modes asked for", out.len()));
|
||||
}
|
||||
Ok(FrequencyResult {
|
||||
step: step.name.clone(),
|
||||
nodes: mesh.labels.clone(),
|
||||
reference_points: mesh.points.iter().map(|p| (p.name.clone(), p.label)).collect(),
|
||||
modes: out,
|
||||
total_mass: 0.0,
|
||||
stats: Stats { dofs: mesh.dofs(), equations: neq, factor_entries: entries, lanczos_vectors: pairs.basis },
|
||||
warnings,
|
||||
buckling: Some(buckling),
|
||||
})
|
||||
}
|
||||
@@ -211,6 +211,10 @@ fn postorder(parent: &[usize]) -> Vec<usize> {
|
||||
pub enum FactorError {
|
||||
/// The pivot of this column is not positive (relative to the diagonal).
|
||||
NotPositiveDefinite { column: usize },
|
||||
/// The symmetric indefinite factorization ([`crate::ldlt`]) found no pivot in this column's
|
||||
/// supernode that is not negligible next to the column's entries: the matrix is singular to
|
||||
/// working precision there.
|
||||
Singular { column: usize },
|
||||
/// The factor would hold more entries than allowed.
|
||||
TooLarge { entries: usize, limit: usize },
|
||||
/// The memory for the factor could not be had.
|
||||
@@ -219,6 +223,25 @@ pub enum FactorError {
|
||||
Internal(String),
|
||||
}
|
||||
|
||||
impl FactorError {
|
||||
/// The column a numeric failure names.
|
||||
fn column(&self) -> Option<usize> {
|
||||
match self {
|
||||
FactorError::NotPositiveDefinite { column } | FactorError::Singular { column } => Some(*column),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The same failure at another column.
|
||||
fn at(self, column: usize) -> FactorError {
|
||||
match self {
|
||||
FactorError::NotPositiveDefinite { .. } => FactorError::NotPositiveDefinite { column },
|
||||
FactorError::Singular { .. } => FactorError::Singular { column },
|
||||
e => e,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One supernode's update to a later one: supernode `k`'s rows from position `p1` on reach the
|
||||
/// later one, whose columns they meet at positions `p1..p2`.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
@@ -230,7 +253,7 @@ struct Update {
|
||||
|
||||
/// The supernodal structure (postorder numbering).
|
||||
#[derive(Debug, Clone)]
|
||||
struct Structure {
|
||||
pub(crate) struct Structure {
|
||||
/// First column of each supernode, and `n` at the end.
|
||||
first: Vec<usize>,
|
||||
/// Row structure of each supernode (its own columns first, then the rows below), sorted.
|
||||
@@ -239,64 +262,108 @@ struct Structure {
|
||||
}
|
||||
|
||||
impl Structure {
|
||||
fn cols(&self, s: usize) -> std::ops::Range<usize> {
|
||||
pub(crate) fn cols(&self, s: usize) -> std::ops::Range<usize> {
|
||||
self.first.get(s).copied().unwrap_or(0)..self.first.get(s + 1).copied().unwrap_or(0)
|
||||
}
|
||||
|
||||
fn rows(&self, s: usize) -> &[usize] {
|
||||
pub(crate) fn rows(&self, s: usize) -> &[usize] {
|
||||
let (a, b) = (self.rptr.get(s).copied().unwrap_or(0), self.rptr.get(s + 1).copied().unwrap_or(0));
|
||||
self.rows.get(a..b).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Entries of the supernode's lower trapezoid.
|
||||
fn size(&self, s: usize) -> usize {
|
||||
pub(crate) fn size(&self, s: usize) -> usize {
|
||||
trapezoid(self.rows(s).len(), self.cols(s).len())
|
||||
}
|
||||
}
|
||||
|
||||
/// Entries of an m-row, w-column lower trapezoid (column c holds rows c..m).
|
||||
fn trapezoid(m: usize, w: usize) -> usize {
|
||||
pub(crate) fn trapezoid(m: usize, w: usize) -> usize {
|
||||
(0..w).map(|c| m.saturating_sub(c)).sum()
|
||||
}
|
||||
|
||||
/// Where column c of an m-row trapezoid starts.
|
||||
fn offset(m: usize, c: usize) -> usize {
|
||||
pub(crate) fn offset(m: usize, c: usize) -> usize {
|
||||
c * m - c * c.saturating_sub(1) / 2
|
||||
}
|
||||
|
||||
/// A dense lower trapezoid of m rows: one supernode's values, column by column, column c
|
||||
/// holding rows c..m of the supernode's row structure.
|
||||
struct Panel<'a> {
|
||||
m: usize,
|
||||
data: &'a [f64],
|
||||
pub(crate) struct Panel<'a> {
|
||||
pub(crate) m: usize,
|
||||
pub(crate) data: &'a [f64],
|
||||
}
|
||||
|
||||
impl Panel<'_> {
|
||||
/// L(r, c) for r ≥ c.
|
||||
fn at(&self, r: usize, c: usize) -> f64 {
|
||||
pub(crate) fn at(&self, r: usize, c: usize) -> f64 {
|
||||
self.data.get(offset(self.m, c) + r - c).copied().unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// Rows r..r+len of column c (r ≥ c).
|
||||
fn column(&self, c: usize, r: usize, len: usize) -> &[f64] {
|
||||
pub(crate) fn column(&self, c: usize, r: usize, len: usize) -> &[f64] {
|
||||
let start = offset(self.m, c) + r - c;
|
||||
self.data.get(start..start + len).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
/// S(i, c) = Σ_k L(p + i, k) L(p + c, k) over the columns k < `kw` of a trapezoid, for rows i in
|
||||
/// 0..mu and columns c in 0..wu (meaningful for i ≥ c), each sum in column order from zero.
|
||||
/// Returned by row tiles: tile t holds rows t·TILE.. as `tile[c * TILE + i]`.
|
||||
fn products(l: &Panel, kw: usize, p: usize, mu: usize, wu: usize) -> Vec<Vec<f64>> {
|
||||
// Rows p..p+wu of the kw columns, transposed so that column c's coefficients are contiguous.
|
||||
/// The pivots of a symmetric indefinite factor's block diagonal D, per column of a supernode
|
||||
/// ([`crate::ldlt`]): a 1 × 1 pivot, or the first or second column of a 2 × 2 one. D's entries
|
||||
/// sit on the trapezoid's diagonal, and a 2 × 2 pivot's off-diagonal entry below its first
|
||||
/// column's diagonal (where L's unit block has a zero).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Pivot {
|
||||
One,
|
||||
First,
|
||||
Second,
|
||||
}
|
||||
|
||||
/// `row` (entries for the columns k0.. of a trapezoid) ← `row` D, with D the block diagonal the
|
||||
/// trapezoid holds for those columns and `pivots` its pivots from column k0.
|
||||
pub(crate) fn times_d(row: &mut [f64], l: &Panel, k0: usize, pivots: &[Pivot]) {
|
||||
let mut k = 0;
|
||||
while k < row.len() {
|
||||
let d = |r: usize, c: usize| l.at(k0 + r, k0 + c);
|
||||
if pivots.get(k) == Some(&Pivot::First) {
|
||||
let (a, b) = (row.get(k).copied().unwrap_or(0.0), row.get(k + 1).copied().unwrap_or(0.0));
|
||||
let (d11, d21, d22) = (d(k, k), d(k + 1, k), d(k + 1, k + 1));
|
||||
if let Some(x) = row.get_mut(k) {
|
||||
*x = a * d11 + b * d21;
|
||||
}
|
||||
if let Some(x) = row.get_mut(k + 1) {
|
||||
*x = a * d21 + b * d22;
|
||||
}
|
||||
k += 2;
|
||||
} else {
|
||||
if let Some(x) = row.get_mut(k) {
|
||||
*x *= d(k, k);
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// S(i, c) = Σ_k L(p + i, k) Y(p + c, k) over the columns k in `cols` of a trapezoid, for rows i
|
||||
/// in 0..mu and columns c in 0..wu (meaningful for i ≥ c), each sum in column order. Y is L
|
||||
/// (Cholesky), or L D with D the block diagonal the trapezoid holds when `pivots` (of the
|
||||
/// columns `cols`) are given. Returned by row tiles: tile t holds rows t·TILE.. as
|
||||
/// `tile[c * TILE + i]`.
|
||||
pub(crate) fn products(l: &Panel, cols: std::ops::Range<usize>, p: usize, mu: usize, wu: usize, pivots: Option<&[Pivot]>) -> Vec<Vec<f64>> {
|
||||
let (k0, kw) = (cols.start, cols.len());
|
||||
// Rows p..p+wu of the columns, transposed so that column c's coefficients are contiguous.
|
||||
let mut yt = vec![0.0; wu * kw];
|
||||
for k in 0..kw {
|
||||
for (c, y) in l.column(k, p, wu).iter().enumerate() {
|
||||
for (c, y) in l.column(k0 + k, p, wu).iter().enumerate() {
|
||||
if let Some(slot) = yt.get_mut(c * kw + k) {
|
||||
*slot = *y;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(pivots) = pivots {
|
||||
for row in yt.chunks_mut(kw.max(1)) {
|
||||
times_d(row, l, k0, pivots);
|
||||
}
|
||||
}
|
||||
let tiles = mu.div_ceil(TILE);
|
||||
let tile = |t: usize| -> Vec<f64> {
|
||||
let i0 = t * TILE;
|
||||
@@ -305,7 +372,7 @@ fn products(l: &Panel, kw: usize, p: usize, mu: usize, wu: usize) -> Vec<Vec<f64
|
||||
let mut x = vec![0.0; kw * TILE];
|
||||
for k in 0..kw {
|
||||
if let Some(dst) = x.get_mut(k * TILE..k * TILE + h) {
|
||||
dst.copy_from_slice(l.column(k, p + i0, h));
|
||||
dst.copy_from_slice(l.column(k0 + k, p + i0, h));
|
||||
}
|
||||
}
|
||||
let cols = wu.min(i0 + h);
|
||||
@@ -328,7 +395,7 @@ fn products(l: &Panel, kw: usize, p: usize, mu: usize, wu: usize) -> Vec<Vec<f64
|
||||
}
|
||||
|
||||
/// own(rel(i), rel(c)) −= S(i, c) for i ≥ c, with S in the tiles of [`products`].
|
||||
fn subtract(own: &mut [f64], m: usize, tiles: &[Vec<f64>], mu: usize, wu: usize, rel: impl Fn(usize) -> usize) {
|
||||
pub(crate) fn subtract(own: &mut [f64], m: usize, tiles: &[Vec<f64>], mu: usize, wu: usize, rel: impl Fn(usize) -> usize) {
|
||||
for (t, tile) in tiles.iter().enumerate() {
|
||||
let i0 = t * TILE;
|
||||
let h = TILE.min(mu - i0);
|
||||
@@ -379,11 +446,13 @@ fn solve_below(l: &Panel, c0: usize, c1: usize) -> Vec<Vec<f64>> {
|
||||
}
|
||||
|
||||
/// The matrix in postorder by lower columns: column j holds A(i, j) for i ≥ j, rows sorted.
|
||||
struct Lower {
|
||||
pub(crate) struct Lower {
|
||||
ptr: Vec<usize>,
|
||||
idx: Vec<usize>,
|
||||
val: Vec<f64>,
|
||||
diag: Vec<f64>,
|
||||
/// The largest magnitude in each row (= column) of the whole symmetric matrix.
|
||||
pub(crate) scale: Vec<f64>,
|
||||
}
|
||||
|
||||
impl Lower {
|
||||
@@ -407,6 +476,7 @@ impl Lower {
|
||||
let mut pairs = vec![(0usize, 0.0f64); ptr.last().copied().unwrap_or(0)];
|
||||
let mut next = ptr.clone();
|
||||
let mut diag = vec![0.0; n];
|
||||
let mut scale = vec![0.0f64; n];
|
||||
for k in 0..n {
|
||||
let (rows, vals) = a.column(k);
|
||||
for (&i, &v) in rows.iter().zip(vals) {
|
||||
@@ -416,6 +486,11 @@ impl Lower {
|
||||
{
|
||||
*d = v;
|
||||
}
|
||||
for x in [r, c] {
|
||||
if let Some(s) = scale.get_mut(x) {
|
||||
*s = s.max(v.abs());
|
||||
}
|
||||
}
|
||||
if let Some(slot) = next.get_mut(c) {
|
||||
if let Some(p) = pairs.get_mut(*slot) {
|
||||
*p = (r, v);
|
||||
@@ -431,7 +506,7 @@ impl Lower {
|
||||
}
|
||||
}
|
||||
let (idx, val) = pairs.into_iter().unzip();
|
||||
Lower { ptr, idx, val, diag }
|
||||
Lower { ptr, idx, val, diag, scale }
|
||||
}
|
||||
|
||||
fn column(&self, j: usize) -> (&[usize], &[f64]) {
|
||||
@@ -442,17 +517,38 @@ impl Lower {
|
||||
|
||||
/// What a supernode's factorization reads: the matrix, the structure and the updates each
|
||||
/// supernode receives.
|
||||
struct Context<'a> {
|
||||
a: &'a Lower,
|
||||
s: &'a Structure,
|
||||
pub(crate) struct Context<'a> {
|
||||
pub(crate) a: &'a Lower,
|
||||
pub(crate) s: &'a Structure,
|
||||
updates: &'a [Vec<Update>],
|
||||
}
|
||||
|
||||
/// What the numeric factorization of one kind keeps per supernode.
|
||||
pub(crate) trait Supernode: Send + Sync {
|
||||
/// The supernode's values: its lower trapezoid by columns.
|
||||
fn values(&self) -> &[f64];
|
||||
/// The pivots of D (symmetric indefinite factors), `None` for Cholesky.
|
||||
fn pivots(&self) -> Option<&[Pivot]>;
|
||||
}
|
||||
|
||||
impl Supernode for Vec<f64> {
|
||||
fn values(&self) -> &[f64] {
|
||||
self
|
||||
}
|
||||
fn pivots(&self) -> Option<&[Pivot]> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn internal(what: &str) -> FactorError {
|
||||
FactorError::Internal(format!("supernodal factorization: {what}"))
|
||||
}
|
||||
|
||||
impl Context<'_> {
|
||||
/// Factor supernode `j` into `own`; its descendants' values are `done[k - base]`. Fails with
|
||||
/// the first column (postorder) whose pivot is not positive.
|
||||
fn supernode(&self, j: usize, done: &[Vec<f64>], base: usize, own: &mut [f64]) -> std::result::Result<(), FactorError> {
|
||||
let internal = |what: &str| FactorError::Internal(format!("supernodal factorization: {what}"));
|
||||
/// Supernode `j` assembled into `own`: its columns of A minus the update L_K Y_Kᵀ of every
|
||||
/// descendant K that reaches it (Y = L, or L D), in supernode order; the descendants are
|
||||
/// `done[k - base]`.
|
||||
pub(crate) fn assemble<T: Supernode>(&self, j: usize, done: &[T], base: usize, own: &mut [f64]) -> std::result::Result<(), FactorError> {
|
||||
let rows = self.s.rows(j);
|
||||
let cols = self.s.cols(j);
|
||||
let (m, w, f) = (rows.len(), cols.len(), cols.start);
|
||||
@@ -476,7 +572,8 @@ impl Context<'_> {
|
||||
// The descendants' updates, in supernode order.
|
||||
let mut relative = Vec::new();
|
||||
for u in self.updates.get(j).map(Vec::as_slice).unwrap_or_default() {
|
||||
let lk = done.get(u.k.wrapping_sub(base)).ok_or_else(|| internal("an update from outside the subtree"))?;
|
||||
let done_k = done.get(u.k.wrapping_sub(base)).ok_or_else(|| internal("an update from outside the subtree"))?;
|
||||
let lk = done_k.values();
|
||||
let (kr, kw) = (self.s.rows(u.k), self.s.cols(u.k).len());
|
||||
let below = kr.get(u.p1..).unwrap_or_default();
|
||||
let (mu, wu) = (below.len(), u.p2 - u.p1);
|
||||
@@ -492,16 +589,26 @@ impl Context<'_> {
|
||||
}
|
||||
relative.push(at);
|
||||
}
|
||||
let tiles = products(&Panel { m: kr.len(), data: lk }, kw, u.p1, mu, wu);
|
||||
let tiles = products(&Panel { m: kr.len(), data: lk }, 0..kw, u.p1, mu, wu, done_k.pivots());
|
||||
subtract(own, m, &tiles, mu, wu, |i| relative.get(i).copied().unwrap_or(0));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Factor supernode `j` into `own`; its descendants' values are `done[k - base]`. Fails with
|
||||
/// the first column (postorder) whose pivot is not positive.
|
||||
fn supernode(&self, j: usize, done: &[Vec<f64>], base: usize, own: &mut [f64]) -> std::result::Result<(), FactorError> {
|
||||
self.assemble(j, done, base, own)?;
|
||||
let rows = self.s.rows(j);
|
||||
let cols = self.s.cols(j);
|
||||
let (m, w, f) = (rows.len(), cols.len(), cols.start);
|
||||
// Dense factorization by panels.
|
||||
for c0 in (0..w).step_by(PANEL) {
|
||||
let c1 = (c0 + PANEL).min(w);
|
||||
let pw = c1 - c0;
|
||||
if c0 > 0 {
|
||||
// The panel minus its products with the columns before it.
|
||||
let tiles = products(&Panel { m, data: own }, c0, c0, m - c0, pw);
|
||||
let tiles = products(&Panel { m, data: own }, 0..c0, c0, m - c0, pw, None);
|
||||
subtract(own, m, &tiles, m - c0, pw, |i| c0 + i);
|
||||
}
|
||||
// The diagonal block, column by column.
|
||||
@@ -549,20 +656,28 @@ impl Context<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A Cholesky factor: L in supernodes, for the matrix with its columns in postorder.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Factor {
|
||||
pub n: usize,
|
||||
/// The symbolic factorization shared by the Cholesky and the symmetric indefinite (LDLᵀ,
|
||||
/// [`crate::ldlt`]) factors: the postorder, the supernodes and their row structures, the updates
|
||||
/// each supernode receives, the matrix in that order, and the subtree tasks of the numeric
|
||||
/// phase.
|
||||
pub(crate) struct Symbolic {
|
||||
pub(crate) n: usize,
|
||||
/// `perm[k]`: the original column that is column k of the factor.
|
||||
perm: Vec<usize>,
|
||||
structure: Structure,
|
||||
/// The values of each supernode (a lower trapezoid by columns).
|
||||
values: Vec<Vec<f64>>,
|
||||
entries: usize,
|
||||
pub(crate) perm: Vec<usize>,
|
||||
pub(crate) structure: Structure,
|
||||
a: Lower,
|
||||
updates: Vec<Vec<Update>>,
|
||||
/// Subtrees factored as parallel tasks, and the supernodes above them, in order.
|
||||
tasks: Vec<std::ops::Range<usize>>,
|
||||
top: Vec<usize>,
|
||||
/// Entries of L.
|
||||
pub(crate) entries: usize,
|
||||
}
|
||||
|
||||
impl Factor {
|
||||
pub fn new(a: &UpperColumns, max_entries: usize) -> std::result::Result<Factor, FactorError> {
|
||||
impl Symbolic {
|
||||
/// The structure of the factor of `a`, refused before any numeric memory is taken when the
|
||||
/// factor would hold more than `max_entries` entries.
|
||||
pub(crate) fn new(a: &UpperColumns, max_entries: usize) -> std::result::Result<Symbolic, FactorError> {
|
||||
let n = a.n;
|
||||
let internal = |what: &str| FactorError::Internal(format!("supernodal structure: {what}"));
|
||||
let (parent0, counts0) = symbolic(a);
|
||||
@@ -682,16 +797,6 @@ impl Factor {
|
||||
}
|
||||
}
|
||||
|
||||
// Memory for the values, taken without aborting.
|
||||
let mut values: Vec<Vec<f64>> = Vec::new();
|
||||
values.try_reserve_exact(ns).map_err(|_| FactorError::OutOfMemory { entries: total })?;
|
||||
for s in 0..ns {
|
||||
let mut v = Vec::new();
|
||||
v.try_reserve_exact(structure.size(s)).map_err(|_| FactorError::OutOfMemory { entries: total })?;
|
||||
v.resize(structure.size(s), 0.0);
|
||||
values.push(v);
|
||||
}
|
||||
|
||||
// Tasks: subtrees (contiguous ranges of supernodes in postorder) of at most a share of the
|
||||
// work each; the supernodes above them are factored afterwards, in order.
|
||||
let mut subtree: Vec<usize> = (0..ns)
|
||||
@@ -737,12 +842,49 @@ impl Factor {
|
||||
}
|
||||
}
|
||||
|
||||
let context = Context { a: &a, s: &structure, updates: &updates };
|
||||
Ok(Symbolic { n, perm, structure, a, updates, tasks, top, entries: total })
|
||||
}
|
||||
|
||||
/// Supernodes.
|
||||
pub(crate) fn supernodes(&self) -> usize {
|
||||
self.structure.first.len().saturating_sub(1)
|
||||
}
|
||||
|
||||
/// The original column of factor column `column`.
|
||||
pub(crate) fn original(&self, column: usize) -> usize {
|
||||
self.perm.get(column).copied().unwrap_or(column)
|
||||
}
|
||||
|
||||
/// Zeroed memory for every supernode's trapezoid, taken without aborting.
|
||||
pub(crate) fn allocate(&self) -> std::result::Result<Vec<Vec<f64>>, FactorError> {
|
||||
let ns = self.supernodes();
|
||||
let mut values: Vec<Vec<f64>> = Vec::new();
|
||||
values.try_reserve_exact(ns).map_err(|_| FactorError::OutOfMemory { entries: self.entries })?;
|
||||
for s in 0..ns {
|
||||
let mut v = Vec::new();
|
||||
v.try_reserve_exact(self.structure.size(s)).map_err(|_| FactorError::OutOfMemory { entries: self.entries })?;
|
||||
v.resize(self.structure.size(s), 0.0);
|
||||
values.push(v);
|
||||
}
|
||||
Ok(values)
|
||||
}
|
||||
|
||||
/// Run `supernode(context, j, done, base, own)` over every supernode, children before
|
||||
/// parents: the subtree tasks in parallel, each through its supernodes in order, then the
|
||||
/// supernodes above them in order. A numeric failure is the first failing column in
|
||||
/// postorder (the one a pass in order would meet first, whichever thread meets it), named by
|
||||
/// its original column.
|
||||
pub(crate) fn factor<T: Supernode>(
|
||||
&self,
|
||||
values: &mut [T],
|
||||
supernode: impl Fn(&Context, usize, &[T], usize, &mut T) -> std::result::Result<(), FactorError> + Sync,
|
||||
) -> std::result::Result<(), FactorError> {
|
||||
let context = Context { a: &self.a, s: &self.structure, updates: &self.updates };
|
||||
// The tasks run in parallel, each through its supernodes in order.
|
||||
let mut pieces: Vec<(std::ops::Range<usize>, &mut [Vec<f64>], Option<usize>)> = Vec::with_capacity(tasks.len());
|
||||
let mut rest: &mut [Vec<f64>] = &mut values;
|
||||
let mut pieces: Vec<(std::ops::Range<usize>, &mut [T], Option<FactorError>)> = Vec::with_capacity(self.tasks.len());
|
||||
let mut rest: &mut [T] = values;
|
||||
let mut at = 0;
|
||||
for range in &tasks {
|
||||
for range in &self.tasks {
|
||||
let (_, tail) = std::mem::take(&mut rest).split_at_mut(range.start - at);
|
||||
let (piece, tail) = tail.split_at_mut(range.len());
|
||||
pieces.push((range.clone(), piece, None));
|
||||
@@ -750,14 +892,14 @@ impl Factor {
|
||||
at = range.end;
|
||||
}
|
||||
let broken = std::sync::Mutex::new(None::<FactorError>);
|
||||
parallel::for_each_mut(&mut pieces, |_, (range, piece, singular)| {
|
||||
parallel::for_each_mut(&mut pieces, |_, (range, piece, failed)| {
|
||||
for j in range.clone() {
|
||||
let (done, own) = piece.split_at_mut(j - range.start);
|
||||
let Some(own) = own.first_mut() else { break };
|
||||
match context.supernode(j, done, range.start, own) {
|
||||
match supernode(&context, j, done, range.start, own) {
|
||||
Ok(()) => {}
|
||||
Err(FactorError::NotPositiveDefinite { column }) => {
|
||||
*singular = Some(column);
|
||||
Err(e) if e.column().is_some() => {
|
||||
*failed = Some(e);
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -772,27 +914,50 @@ impl Factor {
|
||||
if let Some(e) = broken.into_inner().unwrap_or_else(std::sync::PoisonError::into_inner) {
|
||||
return Err(e);
|
||||
}
|
||||
// The first singular column in postorder is the one a pass in order would meet first:
|
||||
// The first failing column in postorder is the one a pass in order would meet first:
|
||||
// the supernodes above the tasks run up to it.
|
||||
let earliest = pieces.iter().filter_map(|p| p.2).min();
|
||||
let earliest = pieces.iter_mut().filter_map(|p| p.2.take()).min_by_key(|e| e.column());
|
||||
drop(pieces);
|
||||
let original = |column: usize| perm.get(column).copied().unwrap_or(column);
|
||||
for &j in &top {
|
||||
if earliest.is_some_and(|c| structure.cols(j).start > c) {
|
||||
let named = |e: FactorError| match e.column() {
|
||||
Some(c) => e.at(self.original(c)),
|
||||
None => e,
|
||||
};
|
||||
for &j in &self.top {
|
||||
if earliest.as_ref().and_then(FactorError::column).is_some_and(|c| self.structure.cols(j).start > c) {
|
||||
break;
|
||||
}
|
||||
let (done, own) = values.split_at_mut(j);
|
||||
let Some(own) = own.first_mut() else { break };
|
||||
match context.supernode(j, done, 0, own) {
|
||||
Ok(()) => {}
|
||||
Err(FactorError::NotPositiveDefinite { column }) => return Err(FactorError::NotPositiveDefinite { column: original(column) }),
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
supernode(&context, j, done, 0, own).map_err(named)?;
|
||||
}
|
||||
if let Some(column) = earliest {
|
||||
return Err(FactorError::NotPositiveDefinite { column: original(column) });
|
||||
match earliest {
|
||||
Some(e) => Err(named(e)),
|
||||
None => Ok(()),
|
||||
}
|
||||
Ok(Factor { n, perm, structure, values, entries: total })
|
||||
}
|
||||
}
|
||||
|
||||
/// A Cholesky factor: L in supernodes, for the matrix with its columns in postorder.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Factor {
|
||||
pub n: usize,
|
||||
/// `perm[k]`: the original column that is column k of the factor.
|
||||
perm: Vec<usize>,
|
||||
structure: Structure,
|
||||
/// The values of each supernode (a lower trapezoid by columns).
|
||||
values: Vec<Vec<f64>>,
|
||||
entries: usize,
|
||||
}
|
||||
|
||||
impl Factor {
|
||||
pub fn new(a: &UpperColumns, max_entries: usize) -> std::result::Result<Factor, FactorError> {
|
||||
Factor::from_symbolic(&Symbolic::new(a, max_entries)?)
|
||||
}
|
||||
|
||||
pub(crate) fn from_symbolic(symbolic: &Symbolic) -> std::result::Result<Factor, FactorError> {
|
||||
let mut values = symbolic.allocate()?;
|
||||
symbolic.factor(&mut values, |context, j, done, base, own| context.supernode(j, done, base, own))?;
|
||||
Ok(Factor { n: symbolic.n, perm: symbolic.perm.clone(), structure: symbolic.structure.clone(), values, entries: symbolic.entries })
|
||||
}
|
||||
|
||||
/// Entries in L.
|
||||
|
||||
@@ -190,6 +190,17 @@ pub trait Operator: Sync {
|
||||
fn mass(&self, x: &[f64], y: &mut [f64]);
|
||||
/// x ← (K − σM)⁻¹ x.
|
||||
fn solve(&self, x: &mut [f64]) -> Result<()>;
|
||||
/// The right-hand side the operator solves for, given a basis vector `x` and its M product
|
||||
/// `mx`: M x for the spectral transformation (the default); another matrix's product for
|
||||
/// other pencils (buckling, [`crate::buckle`]).
|
||||
fn operand(&self, _x: &[f64], mx: &[f64]) -> Vec<f64> {
|
||||
mx.to_vec()
|
||||
}
|
||||
/// The eigenvalue of a Ritz value θ of the operator: σ + 1/θ for the spectral
|
||||
/// transformation.
|
||||
fn eigenvalue(&self, shift: f64, theta: f64) -> f64 {
|
||||
shift + 1.0 / theta
|
||||
}
|
||||
}
|
||||
|
||||
/// Converged eigenpairs: λ ascending, vectors M-orthonormal.
|
||||
@@ -197,6 +208,9 @@ pub trait Operator: Sync {
|
||||
pub struct Eigenpairs {
|
||||
pub values: Vec<f64>,
|
||||
pub vectors: Vec<Vec<f64>>,
|
||||
/// Converged eigenvalues of negative Ritz values θ (outside what the transformation looks
|
||||
/// for: negative buckling load factors), largest |θ| first.
|
||||
pub negative: Vec<f64>,
|
||||
/// Lanczos vectors used.
|
||||
pub basis: usize,
|
||||
}
|
||||
@@ -287,7 +301,7 @@ pub fn lanczos(op: &impl Operator, shift: f64, wanted: Wanted, block: usize, max
|
||||
let mut w: Vec<Vec<f64>> = Vec::with_capacity(b);
|
||||
// The block's solves are independent: one task each.
|
||||
for y in fieldcraft_parallel::map(mcur.len(), |i| {
|
||||
let mut y = mcur.get(i).cloned().unwrap_or_default();
|
||||
let mut y = op.operand(cur.get(i).map(Vec::as_slice).unwrap_or_default(), mcur.get(i).map(Vec::as_slice).unwrap_or_default());
|
||||
op.solve(&mut y).map(|()| y)
|
||||
}) {
|
||||
w.push(y?);
|
||||
@@ -359,7 +373,7 @@ pub fn lanczos(op: &impl Operator, shift: f64, wanted: Wanted, block: usize, max
|
||||
if res2.sqrt() > tolerance * th {
|
||||
break;
|
||||
}
|
||||
let lambda = shift + 1.0 / th;
|
||||
let lambda = op.eigenvalue(shift, th);
|
||||
if lambda > wanted.max {
|
||||
done = true;
|
||||
break;
|
||||
@@ -384,10 +398,24 @@ pub fn lanczos(op: &impl Operator, shift: f64, wanted: Wanted, block: usize, max
|
||||
}
|
||||
}
|
||||
if done {
|
||||
// Negative Ritz values that have converged, largest magnitude first.
|
||||
let mut negative = Vec::new();
|
||||
for &i in idx.iter().rev() {
|
||||
let th = theta[i];
|
||||
if !(th < 0.0) {
|
||||
break;
|
||||
}
|
||||
let res2: f64 =
|
||||
if full { 0.0 } else { (0..b).map(|r| (0..b).map(|c| bnext[r][c] * s[(m - b + c) * m + i]).sum::<f64>().powi(2)).sum() };
|
||||
if res2.sqrt() > tolerance * th.abs() {
|
||||
break;
|
||||
}
|
||||
negative.push(op.eigenvalue(shift, th));
|
||||
}
|
||||
let mut values = Vec::new();
|
||||
let mut vectors = Vec::new();
|
||||
for &i in &accepted {
|
||||
values.push(shift + 1.0 / theta[i]);
|
||||
values.push(op.eigenvalue(shift, theta[i]));
|
||||
let mut x = vec![0.0; n];
|
||||
for (k, qk) in q.iter().enumerate() {
|
||||
let c = s[k * m + i];
|
||||
@@ -405,7 +433,7 @@ pub fn lanczos(op: &impl Operator, shift: f64, wanted: Wanted, block: usize, max
|
||||
}
|
||||
vectors.push(x);
|
||||
}
|
||||
return Ok(Eigenpairs { values, vectors, basis: m });
|
||||
return Ok(Eigenpairs { values, vectors, negative, basis: m });
|
||||
}
|
||||
}
|
||||
if full {
|
||||
|
||||
@@ -310,7 +310,7 @@ fn factor(a: &Csr, limits: &Limits, mesh: &HeatMesh, eqs: &Equations) -> Result<
|
||||
}
|
||||
FactorError::OutOfMemory { entries } => Error::Limit(format!("not enough memory for the factorization ({entries} entries)")),
|
||||
FactorError::Internal(what) => Error::Internal(what),
|
||||
FactorError::NotPositiveDefinite { column } => {
|
||||
FactorError::NotPositiveDefinite { column } | FactorError::Singular { column } => {
|
||||
let label = eqs.node.get(column).and_then(|n| mesh.labels.get(*n)).copied().unwrap_or(0);
|
||||
Error::Singular(format!(
|
||||
"the temperature is undetermined at node {label}: no temperature boundary condition or convection reaches its part of the model"
|
||||
|
||||
@@ -0,0 +1,886 @@
|
||||
//! Sparse symmetric indefinite factorization P A Pᵀ = L D Lᵀ: L unit lower triangular, D block
|
||||
//! diagonal with 1 × 1 and 2 × 2 pivots; supernodal, left-looking between supernodes,
|
||||
//! multithreaded, with a fixed operation order, on the symbolic factorization of the Cholesky
|
||||
//! factor ([`crate::cholesky`]).
|
||||
//!
|
||||
//! **Pivoting** (J. R. Bunch, L. Kaufman, *Some stable methods for calculating inertia and solving
|
||||
//! symmetric linear systems*, Math. Comp. 31(137):163–179, 1977), in its bounded form (C.
|
||||
//! Ashcraft, R. G. Grimes, J. G. Lewis, *Accurate symmetric indefinite linear equation solvers*,
|
||||
//! SIAM J. Matrix Anal. Appl. 20(2):513–561, 1998, the "bounded Bunch–Kaufman" or rook search):
|
||||
//! with α = (1 + √17)/8 and ω_i the largest off-diagonal magnitude of column i, column k is a
|
||||
//! 1 × 1 pivot when |a_kk| ≥ α ω_k; otherwise the search walks from column i to the row r of its
|
||||
//! largest entry: r is a 1 × 1 pivot when |a_rr| ≥ α ω_r, (i, r) a 2 × 2 pivot when ω_r = ω_i
|
||||
//! (the entry is the largest of both columns), else the search continues from r. Every entry of
|
||||
//! L is then bounded by 1/(1 − α) ≈ 2.78 for 1 × 1 pivots (and a like constant for 2 × 2 ones),
|
||||
//! which Bunch–Kaufman's single look does not guarantee; ω grows strictly, so the search ends.
|
||||
//! A 2 × 2 pivot has |a_ii a_rr| < α² a_ir², a negative determinant: one positive and one
|
||||
//! negative eigenvalue.
|
||||
//!
|
||||
//! **Where pivots come from: within supernodes** (the supernode Bunch–Kaufman of O. Schenk, K.
|
||||
//! Gärtner, *On fast factorization pivoting methods for sparse symmetric indefinite systems*,
|
||||
//! Electron. Trans. Numer. Anal. 23:158–179, 2006). The columns of a supernode are fully summed
|
||||
//! once its descendants' updates are in (left-looking, as the Cholesky factor), so any of them
|
||||
//! can be the next pivot: a symmetric interchange inside the supernode leaves the row structure
|
||||
//! of every supernode unchanged, so the static symbolic factorization, the ordering, the
|
||||
//! supernodal tasks and the fill are the Cholesky factor's exactly. The pivot search looks at
|
||||
//! the supernode's own rows; entries in the rows below (later supernodes) are not candidates.
|
||||
//! Multifrontal codes delay a column whose pivot fails into the parent (I. S. Duff, J. K. Reid,
|
||||
//! *The multifrontal solution of indefinite sparse symmetric linear equations*, ACM TOMS
|
||||
//! 9(3):302–325, 1983; J. W. H. Liu, *The multifrontal method for sparse matrix solution: theory
|
||||
//! and practice*, SIAM Review 34(1):82–109, 1992), which changes the structure as it goes; this
|
||||
//! factor keeps the static structure instead (deterministic, threads as Cholesky, the same
|
||||
//! memory bound checked up front), and:
|
||||
//! - a column with no acceptable pivot in its supernode — every remaining candidate negligible,
|
||||
//! at most `PIVOT_TOLERANCE` times the largest entry of the matrix's row — is reported as
|
||||
//! singular, naming the column; a nonsingular saddle point whose zero diagonal couples only to
|
||||
//! rows of a later supernode would also stop there (none of FieldCraft's systems has one: the
|
||||
//! hybrid elements' pressures are condensed per element);
|
||||
//! - L's entries in the rows below the supernode are not bounded by the search; the stiffness,
|
||||
//! shifted and mixed tangents solved here have sizeable diagonals, and
|
||||
//! [`Symmetric::solve_refined`] adds iterative refinement against A where accuracy matters.
|
||||
//!
|
||||
//! **Numeric.** A supernode starts as its columns of A minus L_K D_K L_Kᵀ of every descendant K
|
||||
//! that reaches it, in supernode order (the L D rows formed on the fly from L and D, so nothing
|
||||
//! more is stored than Cholesky's L plus the pivot order). It is then factored right-looking by
|
||||
//! panels of [`PANEL`] columns: inside a panel each column is brought up to date with the panel's
|
||||
//! columns before it when the search looks at it (the partial factorization of LAPACK's
|
||||
//! `dsytrf`, Anderson et al., *LAPACK Users' Guide*, SIAM 1999), and after the panel the rest of
|
||||
//! the supernode receives its update by the tiled, parallel kernel of the Cholesky factor. A
|
||||
//! 2 × 2 pivot may end a panel one column late.
|
||||
//!
|
||||
//! **Inertia** (Sylvester's law): the counts of positive and negative eigenvalues of A are those
|
||||
//! of D — a 1 × 1 pivot by its sign, a 2 × 2 one by its eigenvalues — so a factorization of
|
||||
//! K − σ M counts the eigenvalues below σ, and a tangent's negative pivots count its unstable
|
||||
//! directions. A pivot that would be zero stops the factorization (above), so the count of zero
|
||||
//! eigenvalues is never reported as anything but a located error.
|
||||
//!
|
||||
//! **Threads and determinism.** Every pivot decision and every entry is computed by one task in
|
||||
//! an order fixed by the matrix, ties in the search broken by the lowest index, so the factor,
|
||||
//! its pivots and its inertia are the same bit for bit on any number of threads.
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::cholesky::{
|
||||
Context, Factor, FactorError, PANEL, PIVOT_TOLERANCE, Panel, Pivot, Structure, Supernode, Symbolic, UpperColumns, offset, products, subtract,
|
||||
times_d,
|
||||
};
|
||||
use crate::sparse::Csr;
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// (1 + √17)/8: the growth bound of Bunch and Kaufman.
|
||||
const ALPHA: f64 = 0.640_388_203_202_207_6;
|
||||
|
||||
/// Most steps of one rook search (each strictly raises ω, so the cap only bounds a pathological
|
||||
/// sequence of near ties); at the cap the last two columns are the 2 × 2 pivot.
|
||||
const ROOK_STEPS: usize = 64;
|
||||
|
||||
/// The counts of positive and negative eigenvalues of a factored symmetric matrix.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
|
||||
pub struct Inertia {
|
||||
pub positive: usize,
|
||||
pub negative: usize,
|
||||
}
|
||||
|
||||
/// One supernode of an LDLᵀ factor.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct Block {
|
||||
/// L below the pivots and D on them, the lower trapezoid by columns in pivot order.
|
||||
values: Vec<f64>,
|
||||
pivots: Vec<Pivot>,
|
||||
/// `order[c]`: the supernode's own column (0..w, in the symbolic order) at pivot position c.
|
||||
order: Vec<usize>,
|
||||
inertia: Inertia,
|
||||
two_by_two: usize,
|
||||
}
|
||||
|
||||
impl Supernode for Block {
|
||||
fn values(&self) -> &[f64] {
|
||||
&self.values
|
||||
}
|
||||
fn pivots(&self) -> Option<&[Pivot]> {
|
||||
Some(&self.pivots)
|
||||
}
|
||||
}
|
||||
|
||||
/// The pivot a search chose, at supernode-local positions not yet moved to k.
|
||||
enum Choice {
|
||||
One(usize),
|
||||
Two(usize, usize),
|
||||
}
|
||||
|
||||
/// Symmetric interchange of local columns p < q (both among the supernode's own columns) in an
|
||||
/// m-row lower trapezoid: the rows of the columns before p, the diagonals, the strip between them
|
||||
/// and the rows below q.
|
||||
fn interchange(v: &mut [f64], m: usize, p: usize, q: usize) {
|
||||
let at = |r: usize, c: usize| offset(m, c) + r - c;
|
||||
for c in 0..p {
|
||||
v.swap(at(p, c), at(q, c));
|
||||
}
|
||||
v.swap(at(p, p), at(q, q));
|
||||
for c in p + 1..q {
|
||||
v.swap(at(c, p), at(q, c));
|
||||
}
|
||||
for r in q + 1..m {
|
||||
v.swap(at(r, p), at(r, q));
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest magnitude of `v[i]` over `range` except `skip`, with the lowest such index; NaN
|
||||
/// when an entry is not a number.
|
||||
fn largest(v: &[f64], range: std::ops::Range<usize>, skip: Option<usize>) -> (usize, f64) {
|
||||
let mut best = (range.start, 0.0f64);
|
||||
for i in range {
|
||||
if Some(i) == skip {
|
||||
continue;
|
||||
}
|
||||
let x = v.get(i).copied().unwrap_or(0.0).abs();
|
||||
if x.is_nan() {
|
||||
return (i, f64::NAN);
|
||||
}
|
||||
if x > best.1 {
|
||||
best = (i, x);
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// The work buffers of one supernode's panels.
|
||||
struct Scratch {
|
||||
/// The current values of the column being searched and of a candidate, by local row.
|
||||
a: Vec<f64>,
|
||||
b: Vec<f64>,
|
||||
/// A row of L D over the panel's factored columns.
|
||||
w: Vec<f64>,
|
||||
}
|
||||
|
||||
impl Block {
|
||||
/// Column `c` (local, ≥ k) of the part still to factor, rows k..m, into `out`: the trapezoid's
|
||||
/// entries less the products with the panel's factored columns c0..k.
|
||||
fn current(&self, m: usize, c0: usize, k: usize, c: usize, out: &mut [f64], w: &mut Vec<f64>) {
|
||||
let t = Panel { m, data: &self.values };
|
||||
for r in k..m {
|
||||
if let Some(o) = out.get_mut(r) {
|
||||
*o = if r >= c { t.at(r, c) } else { t.at(c, r) };
|
||||
}
|
||||
}
|
||||
w.clear();
|
||||
w.extend((c0..k).map(|q| t.at(c, q)));
|
||||
times_d(w, &t, c0, self.pivots.get(c0..k).unwrap_or_default());
|
||||
for (q, wq) in (c0..k).zip(w.iter()) {
|
||||
for (o, l) in out.get_mut(k..m).unwrap_or_default().iter_mut().zip(t.column(q, k, m - k)) {
|
||||
*o -= l * wq;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Swap local columns p and q (pivot positions ≥ k) in the trapezoid, the order and the
|
||||
/// current columns.
|
||||
fn swap(&mut self, m: usize, p: usize, q: usize, scratch: &mut Scratch) {
|
||||
if p == q {
|
||||
return;
|
||||
}
|
||||
let (p, q) = (p.min(q), p.max(q));
|
||||
interchange(&mut self.values, m, p, q);
|
||||
self.order.swap(p, q);
|
||||
scratch.a.swap(p, q);
|
||||
scratch.b.swap(p, q);
|
||||
}
|
||||
|
||||
/// Store a 1 × 1 pivot at k from the current column `col`.
|
||||
fn one(&mut self, m: usize, k: usize, col: &[f64]) {
|
||||
let d = col.get(k).copied().unwrap_or(0.0);
|
||||
let start = offset(m, k);
|
||||
if let Some(x) = self.values.get_mut(start) {
|
||||
*x = d;
|
||||
}
|
||||
for r in k + 1..m {
|
||||
if let Some(x) = self.values.get_mut(start + r - k) {
|
||||
*x = col.get(r).copied().unwrap_or(0.0) / d;
|
||||
}
|
||||
}
|
||||
if let Some(p) = self.pivots.get_mut(k) {
|
||||
*p = Pivot::One;
|
||||
}
|
||||
if d > 0.0 {
|
||||
self.inertia.positive += 1;
|
||||
} else {
|
||||
self.inertia.negative += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Store a 2 × 2 pivot at k, k + 1 from the current columns `a` (k) and `b` (k + 1).
|
||||
fn two(&mut self, m: usize, k: usize, a: &[f64], b: &[f64]) {
|
||||
let get = |v: &[f64], r: usize| v.get(r).copied().unwrap_or(0.0);
|
||||
let (d11, d21, d22) = (get(a, k), get(a, k + 1), get(b, k + 1));
|
||||
let det = d11 * d22 - d21 * d21;
|
||||
let (s0, s1) = (offset(m, k), offset(m, k + 1));
|
||||
for (at, v) in [(s0, d11), (s0 + 1, d21), (s1, d22)] {
|
||||
if let Some(x) = self.values.get_mut(at) {
|
||||
*x = v;
|
||||
}
|
||||
}
|
||||
for r in k + 2..m {
|
||||
let (x, y) = (get(a, r), get(b, r));
|
||||
if let Some(l) = self.values.get_mut(s0 + r - k) {
|
||||
*l = (x * d22 - y * d21) / det;
|
||||
}
|
||||
if let Some(l) = self.values.get_mut(s1 + r - k - 1) {
|
||||
*l = (y * d11 - x * d21) / det;
|
||||
}
|
||||
}
|
||||
if let Some(p) = self.pivots.get_mut(k) {
|
||||
*p = Pivot::First;
|
||||
}
|
||||
if let Some(p) = self.pivots.get_mut(k + 1) {
|
||||
*p = Pivot::Second;
|
||||
}
|
||||
// The eigenvalues' signs: one of each when det < 0, else both the sign of the trace.
|
||||
if det < 0.0 {
|
||||
self.inertia.positive += 1;
|
||||
self.inertia.negative += 1;
|
||||
} else if d11 + d22 > 0.0 {
|
||||
self.inertia.positive += 2;
|
||||
} else {
|
||||
self.inertia.negative += 2;
|
||||
}
|
||||
self.two_by_two += 1;
|
||||
}
|
||||
|
||||
/// Factor the panel from column c0 of a supernode with m rows and w columns: pivots chosen
|
||||
/// among the columns c0..w, each column brought up to date with the panel's columns before
|
||||
/// it. Returns where the panel ended. `scale(local)` is the largest entry of the matrix in
|
||||
/// that column; `column(local)` its postorder column.
|
||||
fn panel(
|
||||
&mut self,
|
||||
m: usize,
|
||||
w: usize,
|
||||
c0: usize,
|
||||
scale: &dyn Fn(usize) -> f64,
|
||||
column: &dyn Fn(usize) -> usize,
|
||||
scratch: &mut Scratch,
|
||||
) -> std::result::Result<usize, FactorError> {
|
||||
let end = (c0 + PANEL).min(w);
|
||||
let mut k = c0;
|
||||
while k < end {
|
||||
let singular = |b: &Block, at: usize| FactorError::Singular { column: column(b.order.get(at).copied().unwrap_or(at)) };
|
||||
let negligible = |b: &Block, at: usize, x: f64| !(x > PIVOT_TOLERANCE * scale(b.order.get(at).copied().unwrap_or(at)));
|
||||
let mut a = std::mem::take(&mut scratch.a);
|
||||
self.current(m, c0, k, k, &mut a, &mut scratch.w);
|
||||
scratch.a = a;
|
||||
let akk = scratch.a.get(k).copied().unwrap_or(0.0).abs();
|
||||
let (r0, omega_k) = largest(&scratch.a, k + 1..w, None);
|
||||
if !akk.is_finite() || !omega_k.is_finite() {
|
||||
return Err(singular(self, k));
|
||||
}
|
||||
let choice = if akk >= ALPHA * omega_k {
|
||||
Choice::One(k)
|
||||
} else {
|
||||
// The rook search: `a` holds column i, `b` the candidate r.
|
||||
let (mut i, mut omega_i, mut r) = (k, omega_k, r0);
|
||||
let mut step = 0;
|
||||
loop {
|
||||
let mut b = std::mem::take(&mut scratch.b);
|
||||
self.current(m, c0, k, r, &mut b, &mut scratch.w);
|
||||
scratch.b = b;
|
||||
let (s, omega_r) = largest(&scratch.b, k..w, Some(r));
|
||||
let arr = scratch.b.get(r).copied().unwrap_or(0.0).abs();
|
||||
if !arr.is_finite() || !omega_r.is_finite() {
|
||||
return Err(singular(self, k));
|
||||
}
|
||||
step += 1;
|
||||
if arr >= ALPHA * omega_r {
|
||||
std::mem::swap(&mut scratch.a, &mut scratch.b);
|
||||
break Choice::One(r);
|
||||
}
|
||||
if omega_r <= omega_i || step >= ROOK_STEPS {
|
||||
break Choice::Two(i, r);
|
||||
}
|
||||
std::mem::swap(&mut scratch.a, &mut scratch.b);
|
||||
(i, omega_i, r) = (r, omega_r, s);
|
||||
}
|
||||
};
|
||||
match choice {
|
||||
Choice::One(p) => {
|
||||
self.swap(m, k, p, scratch);
|
||||
if negligible(self, k, scratch.a.get(k).copied().unwrap_or(0.0).abs()) {
|
||||
return Err(singular(self, k));
|
||||
}
|
||||
let a = std::mem::take(&mut scratch.a);
|
||||
self.one(m, k, &a);
|
||||
scratch.a = a;
|
||||
k += 1;
|
||||
}
|
||||
Choice::Two(i, r) => {
|
||||
// i to k, then r to k + 1 (r was at k if i took its place).
|
||||
self.swap(m, k, i, scratch);
|
||||
let r = if r == k { i } else { r };
|
||||
self.swap(m, k + 1, r, scratch);
|
||||
let offdiagonal = scratch.a.get(k + 1).copied().unwrap_or(0.0).abs();
|
||||
let size = scale(self.order.get(k).copied().unwrap_or(k)).max(scale(self.order.get(k + 1).copied().unwrap_or(k + 1)));
|
||||
if !(offdiagonal > PIVOT_TOLERANCE * size) {
|
||||
return Err(singular(self, k));
|
||||
}
|
||||
let (a, b) = (std::mem::take(&mut scratch.a), std::mem::take(&mut scratch.b));
|
||||
self.two(m, k, &a, &b);
|
||||
(scratch.a, scratch.b) = (a, b);
|
||||
k += 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(k)
|
||||
}
|
||||
}
|
||||
|
||||
/// Factor supernode `j` into `own`; its descendants are `done[k - base]`.
|
||||
fn supernode(context: &Context, j: usize, done: &[Block], base: usize, own: &mut Block) -> std::result::Result<(), FactorError> {
|
||||
context.assemble(j, done, base, &mut own.values)?;
|
||||
let (m, cols) = (context.s.rows(j).len(), context.s.cols(j));
|
||||
let (w, f) = (cols.len(), cols.start);
|
||||
own.pivots = vec![Pivot::One; w];
|
||||
own.order = (0..w).collect();
|
||||
own.inertia = Inertia::default();
|
||||
own.two_by_two = 0;
|
||||
let scale = |local: usize| context.a.scale.get(f + local).copied().unwrap_or(0.0);
|
||||
let column = |local: usize| f + local;
|
||||
let mut scratch = Scratch { a: vec![0.0; m], b: vec![0.0; m], w: Vec::with_capacity(PANEL + 1) };
|
||||
let mut c0 = 0;
|
||||
while c0 < w {
|
||||
let c1 = own.panel(m, w, c0, &scale, &column, &mut scratch)?;
|
||||
if c1 < w {
|
||||
// The rest of the supernode minus the panel's L D Lᵀ.
|
||||
let tiles = products(&Panel { m, data: &own.values }, c0..c1, c1, m - c1, w - c1, own.pivots.get(c0..c1));
|
||||
subtract(&mut own.values, m, &tiles, m - c1, w - c1, |i| c1 + i);
|
||||
}
|
||||
c0 = c1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A symmetric indefinite factor P A Pᵀ = L D Lᵀ in supernodes.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LdltFactor {
|
||||
pub n: usize,
|
||||
perm: Vec<usize>,
|
||||
structure: Structure,
|
||||
blocks: Vec<Block>,
|
||||
entries: usize,
|
||||
inertia: Inertia,
|
||||
two_by_two: usize,
|
||||
}
|
||||
|
||||
impl LdltFactor {
|
||||
pub fn new(a: &UpperColumns, max_entries: usize) -> std::result::Result<LdltFactor, FactorError> {
|
||||
LdltFactor::from_symbolic(&Symbolic::new(a, max_entries)?)
|
||||
}
|
||||
|
||||
pub(crate) fn from_symbolic(symbolic: &Symbolic) -> std::result::Result<LdltFactor, FactorError> {
|
||||
let mut blocks = symbolic.allocate()?.into_iter().map(|values| Block { values, ..Block::default() }).collect::<Vec<_>>();
|
||||
symbolic.factor(&mut blocks, supernode)?;
|
||||
let mut inertia = Inertia::default();
|
||||
let mut two_by_two = 0;
|
||||
for b in &blocks {
|
||||
inertia.positive += b.inertia.positive;
|
||||
inertia.negative += b.inertia.negative;
|
||||
two_by_two += b.two_by_two;
|
||||
}
|
||||
Ok(LdltFactor {
|
||||
n: symbolic.n,
|
||||
perm: symbolic.perm.clone(),
|
||||
structure: symbolic.structure.clone(),
|
||||
blocks,
|
||||
entries: symbolic.entries,
|
||||
inertia,
|
||||
two_by_two,
|
||||
})
|
||||
}
|
||||
|
||||
/// Entries in L (as the Cholesky factor of the same pattern).
|
||||
pub fn entries(&self) -> usize {
|
||||
self.entries
|
||||
}
|
||||
|
||||
pub fn inertia(&self) -> Inertia {
|
||||
self.inertia
|
||||
}
|
||||
|
||||
/// The number of 2 × 2 pivots.
|
||||
pub fn two_by_two(&self) -> usize {
|
||||
self.two_by_two
|
||||
}
|
||||
|
||||
/// Solve A x = b in place.
|
||||
pub fn solve(&self, b: &mut [f64]) -> Result<()> {
|
||||
if b.len() != self.n {
|
||||
return Err(Error::Internal("right-hand side length".into()));
|
||||
}
|
||||
let mut x: Vec<f64> = self.perm.iter().map(|&j| b.get(j).copied().unwrap_or(0.0)).collect();
|
||||
let s = &self.structure;
|
||||
let get = |v: &[f64], i: usize| v.get(i).copied().unwrap_or(0.0);
|
||||
let mut y = Vec::new();
|
||||
// L z = P b, then D⁻¹, by supernodes; the supernode's own unknowns are left in pivot
|
||||
// order for the backward pass.
|
||||
for (k, blk) in self.blocks.iter().enumerate() {
|
||||
let rows = s.rows(k);
|
||||
let (m, f, w) = (rows.len(), s.cols(k).start, s.cols(k).len());
|
||||
let t = Panel { m, data: &blk.values };
|
||||
y.clear();
|
||||
y.extend(blk.order.iter().map(|c| get(&x, f + c)));
|
||||
let mut c = 0;
|
||||
while c < w {
|
||||
let width = if blk.pivots.get(c) == Some(&Pivot::First) { 2 } else { 1 };
|
||||
for q in c..c + width {
|
||||
let yq = get(&y, q);
|
||||
for (r, l) in (c + width..m).zip(t.column(q, c + width, m - c - width)) {
|
||||
let target = if r < w { y.get_mut(r) } else { rows.get(r).and_then(|g| x.get_mut(*g)) };
|
||||
if let Some(v) = target {
|
||||
*v -= l * yq;
|
||||
}
|
||||
}
|
||||
}
|
||||
c += width;
|
||||
}
|
||||
let mut c = 0;
|
||||
while c < w {
|
||||
if blk.pivots.get(c) == Some(&Pivot::First) {
|
||||
let (d11, d21, d22) = (t.at(c, c), t.at(c + 1, c), t.at(c + 1, c + 1));
|
||||
let det = d11 * d22 - d21 * d21;
|
||||
let (p, q) = (get(&y, c), get(&y, c + 1));
|
||||
if let Some(v) = y.get_mut(c) {
|
||||
*v = (d22 * p - d21 * q) / det;
|
||||
}
|
||||
if let Some(v) = y.get_mut(c + 1) {
|
||||
*v = (d11 * q - d21 * p) / det;
|
||||
}
|
||||
c += 2;
|
||||
} else {
|
||||
if let Some(v) = y.get_mut(c) {
|
||||
*v /= t.at(c, c);
|
||||
}
|
||||
c += 1;
|
||||
}
|
||||
}
|
||||
if let Some(dst) = x.get_mut(f..f + w) {
|
||||
dst.copy_from_slice(&y);
|
||||
}
|
||||
}
|
||||
// Lᵀ x = z, supernodes in reverse; each scatters its unknowns back from pivot order.
|
||||
for (k, blk) in self.blocks.iter().enumerate().rev() {
|
||||
let rows = s.rows(k);
|
||||
let (m, f, w) = (rows.len(), s.cols(k).start, s.cols(k).len());
|
||||
let t = Panel { m, data: &blk.values };
|
||||
y.clear();
|
||||
y.extend(x.get(f..f + w).unwrap_or_default());
|
||||
let mut c = w;
|
||||
while c > 0 {
|
||||
let width = if c >= 2 && blk.pivots.get(c - 1) == Some(&Pivot::Second) { 2 } else { 1 };
|
||||
let first = c - width;
|
||||
for q in first..c {
|
||||
let mut sum = get(&y, q);
|
||||
for (r, l) in (c..m).zip(t.column(q, c, m - c)) {
|
||||
let v = if r < w { get(&y, r) } else { rows.get(r).map_or(0.0, |g| get(&x, *g)) };
|
||||
sum -= l * v;
|
||||
}
|
||||
if let Some(v) = y.get_mut(q) {
|
||||
*v = sum;
|
||||
}
|
||||
}
|
||||
c = first;
|
||||
}
|
||||
for (pos, c) in blk.order.iter().enumerate() {
|
||||
if let Some(v) = x.get_mut(f + c) {
|
||||
*v = get(&y, pos);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (&j, v) in self.perm.iter().zip(&x) {
|
||||
if let Some(t) = b.get_mut(j) {
|
||||
*t = *v;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Which factorization a symmetric solve uses.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum Kind {
|
||||
/// Cholesky; a matrix that is not positive definite is refused.
|
||||
#[default]
|
||||
Definite,
|
||||
/// LDLᵀ with pivoting.
|
||||
Indefinite,
|
||||
/// Cholesky, and LDLᵀ when the matrix is not positive definite (one symbolic factorization
|
||||
/// serves both).
|
||||
Auto,
|
||||
}
|
||||
|
||||
/// A factored symmetric matrix: Cholesky or LDLᵀ.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Symmetric {
|
||||
Cholesky(Factor),
|
||||
Indefinite(LdltFactor),
|
||||
}
|
||||
|
||||
impl Symmetric {
|
||||
pub fn new(a: &UpperColumns, max_entries: usize, kind: Kind) -> std::result::Result<Symmetric, FactorError> {
|
||||
match kind {
|
||||
Kind::Definite => Factor::new(a, max_entries).map(Symmetric::Cholesky),
|
||||
Kind::Indefinite => LdltFactor::new(a, max_entries).map(Symmetric::Indefinite),
|
||||
Kind::Auto => {
|
||||
let symbolic = Symbolic::new(a, max_entries)?;
|
||||
match Factor::from_symbolic(&symbolic) {
|
||||
Ok(f) => Ok(Symmetric::Cholesky(f)),
|
||||
Err(FactorError::NotPositiveDefinite { .. }) => LdltFactor::from_symbolic(&symbolic).map(Symmetric::Indefinite),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn n(&self) -> usize {
|
||||
match self {
|
||||
Symmetric::Cholesky(f) => f.n,
|
||||
Symmetric::Indefinite(f) => f.n,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn entries(&self) -> usize {
|
||||
match self {
|
||||
Symmetric::Cholesky(f) => f.entries(),
|
||||
Symmetric::Indefinite(f) => f.entries(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The inertia: a Cholesky factor's matrix is positive definite.
|
||||
pub fn inertia(&self) -> Inertia {
|
||||
match self {
|
||||
Symmetric::Cholesky(f) => Inertia { positive: f.n, negative: 0 },
|
||||
Symmetric::Indefinite(f) => f.inertia(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn solve(&self, b: &mut [f64]) -> Result<()> {
|
||||
match self {
|
||||
Symmetric::Cholesky(f) => f.solve(b),
|
||||
Symmetric::Indefinite(f) => f.solve(b),
|
||||
}
|
||||
}
|
||||
|
||||
/// Solve A x = b in place, then refine with the residual against `a` (the matrix that was
|
||||
/// factored, both triangles) while it shrinks, at most `steps` times (iterative refinement
|
||||
/// in working precision: N. J. Higham, *Accuracy and Stability of Numerical Algorithms*, 2nd
|
||||
/// ed., SIAM 2002, §12.2). Cholesky solutions are returned as solved.
|
||||
pub fn solve_refined(&self, a: &Csr, b: &mut [f64], steps: usize) -> Result<()> {
|
||||
let rhs = b.to_vec();
|
||||
self.solve(b)?;
|
||||
if matches!(self, Symmetric::Cholesky(_)) {
|
||||
return Ok(());
|
||||
}
|
||||
let norm = |v: &[f64]| v.iter().fold(0.0f64, |m, x| m.max(x.abs()));
|
||||
let mut ax = vec![0.0; a.n];
|
||||
let residual = |x: &[f64], ax: &mut Vec<f64>| -> Vec<f64> {
|
||||
a.mul(x, ax);
|
||||
rhs.iter().zip(ax.iter()).map(|(p, q)| p - q).collect()
|
||||
};
|
||||
let mut r = residual(b, &mut ax);
|
||||
let mut size = norm(&r);
|
||||
for _ in 0..steps {
|
||||
if !(size > 0.0) {
|
||||
break;
|
||||
}
|
||||
let mut dx = r.clone();
|
||||
self.solve(&mut dx)?;
|
||||
let trial: Vec<f64> = b.iter().zip(&dx).map(|(x, d)| x + d).collect();
|
||||
let next = residual(&trial, &mut ax);
|
||||
let next_size = norm(&next);
|
||||
if !(next_size < size) {
|
||||
break;
|
||||
}
|
||||
b.copy_from_slice(&trial);
|
||||
(r, size) = (next, next_size);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use fieldcraft_parallel as parallel;
|
||||
|
||||
fn csr(rows: &[Vec<(usize, f64)>]) -> Csr {
|
||||
let mut ptr = vec![0];
|
||||
let mut idx = Vec::new();
|
||||
let mut val = Vec::new();
|
||||
for row in rows {
|
||||
let mut row = row.clone();
|
||||
row.sort_by_key(|e| e.0);
|
||||
for (c, v) in row {
|
||||
idx.push(c);
|
||||
val.push(v);
|
||||
}
|
||||
ptr.push(idx.len());
|
||||
}
|
||||
Csr { n: rows.len(), ptr, idx, val }
|
||||
}
|
||||
|
||||
fn residual(a: &Csr, f: &impl Fn(&mut [f64]), seed: f64) -> f64 {
|
||||
let n = a.n;
|
||||
let x: Vec<f64> = (0..n).map(|i| ((i as f64 + seed) * 0.37).sin()).collect();
|
||||
let mut b = vec![0.0; n];
|
||||
a.mul(&x, &mut b);
|
||||
f(&mut b);
|
||||
b.iter().zip(&x).map(|(p, q)| (p - q).abs()).fold(0.0, f64::max)
|
||||
}
|
||||
|
||||
/// A 3D grid Laplacian (3 coupled unknowns per point) shifted by σ: indefinite for σ inside
|
||||
/// its spectrum, with a known count of eigenvalues below σ.
|
||||
fn shifted_grid(n: [usize; 3], sigma: f64) -> (Csr, usize) {
|
||||
let [nx, ny, nz] = n;
|
||||
let point = |i: usize, j: usize, k: usize| i + nx * (j + ny * k);
|
||||
let size = 3 * nx * ny * nz;
|
||||
let mut rows: Vec<Vec<(usize, f64)>> = vec![Vec::new(); size];
|
||||
for k in 0..nz {
|
||||
for j in 0..ny {
|
||||
for i in 0..nx {
|
||||
let p = 3 * point(i, j, k);
|
||||
for a in 0..3 {
|
||||
rows[p + a].push((p + a, 6.0 - sigma));
|
||||
}
|
||||
let next = [
|
||||
(i + 1 < nx).then(|| point(i + 1, j, k)),
|
||||
(j + 1 < ny).then(|| point(i, j + 1, k)),
|
||||
(k + 1 < nz).then(|| point(i, j, k + 1)),
|
||||
];
|
||||
for q in next.into_iter().flatten() {
|
||||
for a in 0..3 {
|
||||
rows[p + a].push((3 * q + a, -1.0));
|
||||
rows[3 * q + a].push((p + a, -1.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Eigenvalues of the Dirichlet grid Laplacian: Σ 2 − 2 cos(π m/(n + 1)) over the axes.
|
||||
let axis = |n: usize| (1..=n).map(move |m| 2.0 - 2.0 * (std::f64::consts::PI * m as f64 / (n as f64 + 1.0)).cos());
|
||||
let mut below = 0;
|
||||
for a in axis(nx) {
|
||||
for b in axis(ny) {
|
||||
for c in axis(nz) {
|
||||
if a + b + c < sigma {
|
||||
below += 3;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(csr(&rows), below)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indefinite_systems_solve_with_their_inertia() {
|
||||
for sigma in [0.0, 0.9, 3.3, 7.1] {
|
||||
let (a, below) = shifted_grid([7, 6, 5], sigma);
|
||||
let upper = UpperColumns::from_symmetric(&a);
|
||||
let f = LdltFactor::new(&upper, usize::MAX).unwrap();
|
||||
assert_eq!(f.inertia(), Inertia { positive: a.n - below, negative: below }, "σ = {sigma}");
|
||||
let err = residual(&a, &|b: &mut [f64]| f.solve(b).unwrap(), sigma);
|
||||
assert!(err < 1e-10, "σ = {sigma}: {err}");
|
||||
}
|
||||
// A positive definite matrix: the same solution as Cholesky, no negative pivot.
|
||||
let (a, _) = shifted_grid([5, 5, 5], -0.5);
|
||||
let upper = UpperColumns::from_symmetric(&a);
|
||||
let f = LdltFactor::new(&upper, usize::MAX).unwrap();
|
||||
assert_eq!(f.inertia().negative, 0);
|
||||
assert_eq!(f.entries(), Factor::new(&upper, usize::MAX).unwrap().entries(), "the same fill");
|
||||
assert!(residual(&a, &|b: &mut [f64]| f.solve(b).unwrap(), 1.0) < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_by_two_pivots_for_zero_diagonals() {
|
||||
// A saddle point [[K, B], [Bᵀ, 0]] inside one dense supernode: zero diagonals need 2 × 2
|
||||
// pivots, and the inertia is (positive: K's size, negative: the constraints').
|
||||
let (nk, nb) = (8, 3);
|
||||
let n = nk + nb;
|
||||
let mut rows: Vec<Vec<(usize, f64)>> = vec![Vec::new(); n];
|
||||
for i in 0..nk {
|
||||
for j in 0..nk {
|
||||
// Small next to the constraints' entries, so the search pairs them.
|
||||
let v = if i == j { 0.5 } else { 0.05 / (1.0 + (i + j) as f64) };
|
||||
rows[i].push((j, v));
|
||||
}
|
||||
}
|
||||
for c in 0..nb {
|
||||
for i in 0..nk {
|
||||
let v = ((i * 7 + c * 3) % 5) as f64 - 2.0 + if i == c { 3.0 } else { 0.0 };
|
||||
rows[i].push((nk + c, v));
|
||||
rows[nk + c].push((i, v));
|
||||
}
|
||||
// Stored zeros: the constraints share one supernode with K (a zero diagonal whose
|
||||
// couplings all lie in later supernodes is the restriction the module documents).
|
||||
for d in 0..nb {
|
||||
rows[nk + c].push((nk + d, 0.0));
|
||||
}
|
||||
}
|
||||
// The zero-diagonal columns first, so the search must pivot past them.
|
||||
let order: Vec<usize> = (nk..n).chain(0..nk).collect();
|
||||
let mut permuted: Vec<Vec<(usize, f64)>> = vec![Vec::new(); n];
|
||||
let inverse: Vec<usize> = (0..n).map(|i| order.iter().position(|&o| o == i).unwrap()).collect();
|
||||
for (i, row) in rows.iter().enumerate() {
|
||||
permuted[inverse[i]] = row.iter().map(|(c, v)| (inverse[*c], *v)).collect();
|
||||
}
|
||||
let a = csr(&permuted);
|
||||
let f = LdltFactor::new(&UpperColumns::from_symmetric(&a), usize::MAX).unwrap();
|
||||
assert_eq!(f.inertia(), Inertia { positive: nk, negative: nb });
|
||||
assert!(f.two_by_two() > 0);
|
||||
assert!(residual(&a, &|b: &mut [f64]| f.solve(b).unwrap(), 0.5) < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn singular_and_hostile_matrices_are_located_errors() {
|
||||
// A Laplacian with the constant in its null space.
|
||||
let n = 12;
|
||||
let rows: Vec<Vec<(usize, f64)>> = (0..n)
|
||||
.map(|i: usize| {
|
||||
let mut r = vec![];
|
||||
let mut d = 0.0;
|
||||
for j in [i.wrapping_sub(1), i + 1] {
|
||||
if j < n {
|
||||
r.push((j, -1.0));
|
||||
d += 1.0;
|
||||
}
|
||||
}
|
||||
r.push((i, d));
|
||||
r
|
||||
})
|
||||
.collect();
|
||||
let e = LdltFactor::new(&UpperColumns::from_symmetric(&csr(&rows)), usize::MAX).unwrap_err();
|
||||
assert!(matches!(e, FactorError::Singular { column } if column < n), "{e:?}");
|
||||
// NaN.
|
||||
let mut bad = rows.clone();
|
||||
bad[5][0].1 = f64::NAN;
|
||||
bad[4].iter_mut().filter(|e| e.0 == 5).for_each(|e| e.1 = f64::NAN);
|
||||
assert!(matches!(LdltFactor::new(&UpperColumns::from_symmetric(&csr(&bad)), usize::MAX), Err(FactorError::Singular { .. })));
|
||||
// The cap is checked before the numeric factorization; empty and 1 × 1 matrices.
|
||||
let (a, _) = shifted_grid([3, 3, 3], 2.0);
|
||||
assert!(matches!(LdltFactor::new(&UpperColumns::from_symmetric(&a), 10), Err(FactorError::TooLarge { .. })));
|
||||
let empty = Csr { n: 0, ptr: vec![0], idx: vec![], val: vec![] };
|
||||
LdltFactor::new(&UpperColumns::from_symmetric(&empty), 10).unwrap().solve(&mut []).unwrap();
|
||||
let f = LdltFactor::new(&UpperColumns::from_symmetric(&csr(&[vec![(0, -4.0)]])), 10).unwrap();
|
||||
let mut b = [2.0];
|
||||
f.solve(&mut b).unwrap();
|
||||
assert_eq!((b, f.inertia()), ([-0.5], Inertia { positive: 0, negative: 1 }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_factor_on_any_number_of_threads() {
|
||||
// Large enough for parallel subtrees and tiles, with wide supernodes spanning panels.
|
||||
let (a, below) = shifted_grid([14, 12, 10], 2.7);
|
||||
let upper = UpperColumns::from_symmetric(&a);
|
||||
let one = parallel::with_threads(1, || LdltFactor::new(&upper, usize::MAX)).unwrap();
|
||||
assert_eq!(one.inertia().negative, below);
|
||||
let widest = one.blocks.iter().map(|b| b.order.len()).max().unwrap();
|
||||
assert!(widest > 2 * PANEL, "a supernode spans panels: {widest}");
|
||||
for threads in [2, 7] {
|
||||
let other = parallel::with_threads(threads, || LdltFactor::new(&upper, usize::MAX)).unwrap();
|
||||
for (x, y) in one.blocks.iter().zip(&other.blocks) {
|
||||
assert!(x.values.iter().zip(&y.values).all(|(p, q)| p.to_bits() == q.to_bits()) && x.order == y.order, "{threads} threads");
|
||||
}
|
||||
}
|
||||
let err = residual(&a, &|b: &mut [f64]| one.solve(b).unwrap(), 0.1);
|
||||
assert!(err < 1e-9, "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_selection_and_refinement() {
|
||||
let (spd, _) = shifted_grid([4, 4, 4], -1.0);
|
||||
let s = Symmetric::new(&UpperColumns::from_symmetric(&spd), usize::MAX, Kind::Auto).unwrap();
|
||||
assert!(matches!(s, Symmetric::Cholesky(_)));
|
||||
let (ind, below) = shifted_grid([4, 4, 4], 4.4);
|
||||
let s = Symmetric::new(&UpperColumns::from_symmetric(&ind), usize::MAX, Kind::Auto).unwrap();
|
||||
assert!(matches!(s, Symmetric::Indefinite(_)));
|
||||
assert_eq!(s.inertia().negative, below);
|
||||
let x: Vec<f64> = (0..ind.n).map(|i| (i as f64).cos()).collect();
|
||||
let mut b = vec![0.0; ind.n];
|
||||
ind.mul(&x, &mut b);
|
||||
s.solve_refined(&ind, &mut b, 3).unwrap();
|
||||
assert!(b.iter().zip(&x).all(|(p, q)| (p - q).abs() < 1e-12));
|
||||
assert!(matches!(
|
||||
Symmetric::new(&UpperColumns::from_symmetric(&ind), usize::MAX, Kind::Definite),
|
||||
Err(FactorError::NotPositiveDefinite { .. })
|
||||
));
|
||||
}
|
||||
|
||||
/// The stiffness pattern of a hex8 mesh (27 neighbours, 3 unknowns per node) on an n³ grid of
|
||||
/// nodes, ordered by nested dissection, diagonally dominant and shifted by σ.
|
||||
fn hex_pattern(n: usize, sigma: f64) -> Csr {
|
||||
let id = |i: usize, j: usize, k: usize| i + n * (j + n * k);
|
||||
let nodes = n * n * n;
|
||||
let xyz: Vec<[f64; 3]> = (0..nodes).map(|v| [(v % n) as f64, ((v / n) % n) as f64, (v / (n * n)) as f64]).collect();
|
||||
let mut adjacency = vec![Vec::new(); nodes];
|
||||
for k in 0..n {
|
||||
for j in 0..n {
|
||||
for i in 0..n {
|
||||
for (a, b, c) in (0..27).map(|t| (t % 3, (t / 3) % 3, t / 9)) {
|
||||
let (x, y, z) = (i + a, j + b, k + c);
|
||||
if (1..=n).contains(&x) && (1..=n).contains(&y) && (1..=n).contains(&z) {
|
||||
adjacency[id(i, j, k)].push(id(x - 1, y - 1, z - 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let order = crate::ordering::nested_dissection(&xyz, &adjacency);
|
||||
let mut place = vec![0; nodes];
|
||||
for (p, v) in order.iter().enumerate() {
|
||||
place[*v] = p;
|
||||
}
|
||||
let mut rows: Vec<Vec<(usize, f64)>> = vec![Vec::new(); 3 * nodes];
|
||||
for (v, adj) in adjacency.iter().enumerate() {
|
||||
for w in adj {
|
||||
for a in 0..3 {
|
||||
for b in 0..3 {
|
||||
let value = if v == *w {
|
||||
if a == b { 30.0 - sigma } else { 0.5 }
|
||||
} else if a == b {
|
||||
-1.0
|
||||
} else {
|
||||
0.01 * ((v + w) % 3) as f64
|
||||
};
|
||||
rows[3 * place[v] + a].push((3 * place[*w] + b, value));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
csr(&rows)
|
||||
}
|
||||
|
||||
/// Factor time and fill of Cholesky and LDLᵀ on a large stiffness pattern (`--nocapture`).
|
||||
#[test]
|
||||
#[ignore = "heavy: cargo xtask test --heavy (CI heavy job)"]
|
||||
fn speed_against_cholesky() {
|
||||
for n in [24, 36] {
|
||||
let a = hex_pattern(n, 0.0);
|
||||
let upper = UpperColumns::from_symmetric(&a);
|
||||
let t = std::time::Instant::now();
|
||||
let chol = Factor::new(&upper, usize::MAX).unwrap();
|
||||
let tc = t.elapsed().as_secs_f64();
|
||||
let t = std::time::Instant::now();
|
||||
let ldlt = LdltFactor::new(&upper, usize::MAX).unwrap();
|
||||
let tl = t.elapsed().as_secs_f64();
|
||||
assert_eq!((ldlt.entries(), ldlt.inertia().negative), (chol.entries(), 0));
|
||||
let shifted = hex_pattern(n, 22.0);
|
||||
let t = std::time::Instant::now();
|
||||
let indefinite = LdltFactor::new(&UpperColumns::from_symmetric(&shifted), usize::MAX).unwrap();
|
||||
let ti = t.elapsed().as_secs_f64();
|
||||
assert!(residual(&shifted, &|b: &mut [f64]| indefinite.solve(b).unwrap(), 0.3) < 1e-8);
|
||||
eprintln!(
|
||||
"{} equations, {} entries: Cholesky {tc:.2} s, LDLᵀ {tl:.2} s (×{:.2}); indefinite (σ = 22: {} negative, {} 2 × 2 pivots) {ti:.2} s",
|
||||
a.n,
|
||||
chol.entries(),
|
||||
tl / tc,
|
||||
indefinite.inertia().negative,
|
||||
indefinite.two_by_two()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,9 @@
|
||||
//! 4. **Solution** ([`cholesky`]): sparse Cholesky; reactions K u − f at the prescribed degrees
|
||||
//! of freedom; stresses at the integration points, extrapolated and averaged at the nodes, and
|
||||
//! von Mises. Frequency analysis ([`eigen`]) runs shift-invert block Lanczos on the same
|
||||
//! kind of factorization.
|
||||
//! kind of factorization. Indefinite matrices (tangents past a limit point, strained mixed
|
||||
//! elements, shifted operators) are factored by the symmetric indefinite LDLᵀ ([`ldlt`]) on
|
||||
//! the same symbolic factorization, which also counts their negative eigenvalues.
|
||||
//!
|
||||
//! Element matrices and stresses, the factorization's subtrees and dense tiles, the Lanczos
|
||||
//! block solves and matrix products run on threads ([`fieldcraft_parallel`]), but every number
|
||||
@@ -26,11 +28,13 @@
|
||||
#![allow(clippy::needless_range_loop)]
|
||||
|
||||
pub mod analysis;
|
||||
pub mod buckle;
|
||||
pub mod cholesky;
|
||||
pub mod constraints;
|
||||
pub mod discrete;
|
||||
pub mod eigen;
|
||||
pub mod heat;
|
||||
pub mod ldlt;
|
||||
pub mod nonlinear;
|
||||
pub mod ordering;
|
||||
pub mod sparse;
|
||||
@@ -40,6 +44,7 @@ pub use analysis::{
|
||||
ElementStress, FrequencyOptions, FrequencyResult, Location, MassKind, Mode, PointResult, StaticResult, Stats, StepResult, solve_frequency,
|
||||
solve_static,
|
||||
};
|
||||
pub use buckle::{Buckling, solve_buckle};
|
||||
pub use heat::{HeatResult, solve_heat};
|
||||
pub use nonlinear::solve_nonlinear;
|
||||
|
||||
|
||||
@@ -36,12 +36,21 @@
|
||||
//! increments in a row that converge in at most four iterations let the next grow by half (up
|
||||
//! to `max_increment`), one that needs more than eight shrinks it by a quarter. An increment is
|
||||
//! cut back to a quarter of its size when it fails: an element inverts, the residual is not
|
||||
//! finite, the residual grows in two successive iterations, the tangent is not positive definite
|
||||
//! (a limit point or an unstable material), or it does not converge in `max_iterations`. The
|
||||
//! finite, the residual grows in two successive iterations, the tangent is singular, or it does
|
||||
//! not converge in `max_iterations`. The
|
||||
//! step fails cleanly, naming the load factor and the last reason, when an increment falls below
|
||||
//! `min_increment`, when it has taken `max_increments` increments, or when the Newton iterations
|
||||
//! of the whole step reach [`crate::Limits::max_newton_iterations`].
|
||||
//!
|
||||
//! **Indefinite tangents.** A tangent that is not positive definite — a strained mixed element
|
||||
//! of a nearly incompressible material, an unstable material, a state past a limit or
|
||||
//! bifurcation point — is factored by the symmetric indefinite LDLᵀ ([`crate::ldlt`]) and Newton
|
||||
//! goes on: the residual decides convergence, and every iteration records the tangent's negative
|
||||
//! eigenvalues (its inertia), which the step summary reports when a converged state keeps some
|
||||
//! (an unstable equilibrium reached under load control). Only the first tangent of a model that
|
||||
//! can move without straining is an error (the undeformed model's Cholesky factor names where);
|
||||
//! a singular tangent later is a cutback.
|
||||
//!
|
||||
//! **Follower pressure** and the Cholesky factorization: the load stiffness of a pressure on the
|
||||
//! deformed surface is not symmetric (Schweizerhof & Ramm 1984); its skew part is left out of the
|
||||
//! tangent (the symmetric part is kept), so the factorization stays the supernodal Cholesky of the
|
||||
@@ -89,16 +98,20 @@ use fieldcraft_fem::finite::{Kinematics, Temperature};
|
||||
use fieldcraft_fem::plane::Theory;
|
||||
use fieldcraft_fem::quadrature::Rule;
|
||||
use fieldcraft_fem::{DofKind, DofSet, ElementType, PointStress, face, von_mises};
|
||||
use fieldcraft_model::{BoundaryCondition, Extent, Hardening, Load, Model, NonlinearStatic, Plastic, Procedure, SectionKind, Step};
|
||||
use fieldcraft_model::{
|
||||
ArcConstraint, ArcLength, BoundaryCondition, Extent, Hardening, Imperfection, Load, Model, NonlinearStatic, Plastic, Procedure, SectionKind, Step,
|
||||
};
|
||||
use fieldcraft_parallel as parallel;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::analysis::factor_symmetric;
|
||||
use crate::analysis::{
|
||||
ElementStress, GRAIN, PointResult, ROUND, Setup, StaticResult, Stats, budget, factor_error, factor_raw, ignored_dashpots, pattern, reduction,
|
||||
split,
|
||||
};
|
||||
use crate::cholesky::FactorError;
|
||||
use crate::constraints::Reduction;
|
||||
use crate::ldlt::{Kind, Symmetric};
|
||||
use crate::sparse::{Csr, add_block};
|
||||
use crate::system::{Mesh, add_element_thermal_loads, loads, temperature_loads, translations};
|
||||
use crate::{Error, Limits, Result};
|
||||
@@ -114,6 +127,14 @@ pub struct Iteration {
|
||||
pub energy: f64,
|
||||
/// The line search's step along the correction (1: the full Newton step).
|
||||
pub line_search: f64,
|
||||
/// Negative eigenvalues of the tangent the correction was solved with (an indefinite
|
||||
/// tangent is factored by LDLᵀ, [`crate::ldlt`]).
|
||||
#[serde(skip_serializing_if = "is_zero")]
|
||||
pub negative_pivots: usize,
|
||||
}
|
||||
|
||||
fn is_zero(n: &usize) -> bool {
|
||||
*n == 0
|
||||
}
|
||||
|
||||
/// One increment (converged, or cut back).
|
||||
@@ -130,6 +151,35 @@ pub struct Increment {
|
||||
/// Why it was cut back.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub cutback: Option<String>,
|
||||
/// Negative eigenvalues of the tangent at the converged state (arc-length steps, which
|
||||
/// factor it for the next predictor).
|
||||
#[serde(skip_serializing_if = "is_zero")]
|
||||
pub negative_pivots: usize,
|
||||
}
|
||||
|
||||
/// Where the tangent's inertia changes along an arc-length path.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CriticalKind {
|
||||
/// The load factor turns (snap-through).
|
||||
Limit,
|
||||
/// The load factor goes on: another branch crosses this one.
|
||||
Bifurcation,
|
||||
}
|
||||
|
||||
/// A critical point of an arc-length path: the tangent's count of negative eigenvalues changes
|
||||
/// between two converged states.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
|
||||
pub struct CriticalPoint {
|
||||
pub kind: CriticalKind,
|
||||
/// The increment whose converged state has the new count.
|
||||
pub increment: usize,
|
||||
/// For a limit point the extreme load factor of the converged states around it, for a
|
||||
/// bifurcation the last one before it.
|
||||
pub load_factor: f64,
|
||||
/// Negative eigenvalues before and after.
|
||||
pub negative_before: usize,
|
||||
pub negative_after: usize,
|
||||
}
|
||||
|
||||
/// The displacements at the end of a converged increment.
|
||||
@@ -149,6 +199,8 @@ pub struct History {
|
||||
pub frames: Vec<Frame>,
|
||||
/// Newton iterations over the step.
|
||||
pub iterations: usize,
|
||||
/// Arc-length steps: where the tangent's inertia changes along the path.
|
||||
pub critical_points: Vec<CriticalPoint>,
|
||||
}
|
||||
|
||||
impl History {
|
||||
@@ -252,6 +304,14 @@ fn half(k: &[f64], m: usize, sign: f64) -> Vec<f64> {
|
||||
(0..m * m).map(|i| 0.5 * (k.get(i).copied().unwrap_or(0.0) + sign * k.get((i % m) * m + i / m).copied().unwrap_or(0.0))).collect()
|
||||
}
|
||||
|
||||
/// T_fᵀ K T_p (s u_p): the free equations' forces of the prescribed motions scaled by `s`.
|
||||
fn prescribed_force(red: &Reduction, k: &Csr, s: f64) -> Vec<f64> {
|
||||
let jump = red.expand_scaled(&vec![0.0; red.neq()], s);
|
||||
let mut kj = vec![0.0; jump.len()];
|
||||
k.mul(&jump, &mut kj);
|
||||
red.restrict(&kj)
|
||||
}
|
||||
|
||||
/// The out-of-balance forces over the free equations, T_fᵀ (f_ext − f_int).
|
||||
fn free_residual(red: &Reduction, e: &Evaluation) -> Vec<f64> {
|
||||
let r: Vec<f64> = e.external.iter().zip(&e.internal).map(|(a, b)| a - b).collect();
|
||||
@@ -383,6 +443,21 @@ impl Problem<'_> {
|
||||
Ok(Evaluation { internal, external, tangent: k, history })
|
||||
}
|
||||
|
||||
/// The loads at load factor 1 at displacements `u` (dead loads and follower pressures on
|
||||
/// the current faces): ∂f_ext/∂λ.
|
||||
fn reference_load(&self, u: &[f64]) -> Result<Vec<f64>> {
|
||||
let mut external = self.dead.clone();
|
||||
for f in &self.followers {
|
||||
let (force, _) = self.follower(f, u, 1.0)?;
|
||||
for (d, v) in f.dofs.iter().zip(&force) {
|
||||
if let Some(x) = external.get_mut(*d) {
|
||||
*x += v;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(external)
|
||||
}
|
||||
|
||||
/// The size of the follower load stiffness's skew part relative to the whole, over the free
|
||||
/// degrees of freedom (Frobenius norms), at `u` and λ; `None` without followers.
|
||||
fn follower_asymmetry(&self, u: &[f64], lambda: f64) -> Result<Option<f64>> {
|
||||
@@ -435,8 +510,8 @@ struct Run<'a> {
|
||||
committed: Vec<Vec<f64>>,
|
||||
/// Whether a material keeps history (the tangent predictor and its convergence rules).
|
||||
path_dependent: bool,
|
||||
/// Whether the undeformed model's tangent factors, once asked.
|
||||
undeformed_stable: Option<bool>,
|
||||
/// How the undeformed model's tangent factors (Cholesky), once asked.
|
||||
undeformed: Option<std::result::Result<(), FactorError>>,
|
||||
}
|
||||
|
||||
/// The outcome of a converged increment.
|
||||
@@ -452,6 +527,15 @@ impl Run<'_> {
|
||||
free_residual(self.problem.red, e)
|
||||
}
|
||||
|
||||
/// The round-off floor of the force scale, from the first tangent's mean diagonal.
|
||||
fn seed_force_floor(&mut self, kff: &Csr) {
|
||||
if self.force_floor.is_none() {
|
||||
let diagonal = kff.diagonal();
|
||||
let mean = diagonal.iter().map(|d| d.abs()).sum::<f64>() / diagonal.len().max(1) as f64;
|
||||
self.force_floor = Some(1e-8 * mean * self.length);
|
||||
}
|
||||
}
|
||||
|
||||
fn scale(&self) -> f64 {
|
||||
self.force_scale.max(self.force_floor.unwrap_or(0.0)).max(f64::MIN_POSITIVE)
|
||||
}
|
||||
@@ -460,19 +544,50 @@ impl Run<'_> {
|
||||
Ok(self.problem.evaluate(&self.problem.red.expand_scaled(q, lambda), lambda, tangent, &self.committed)?)
|
||||
}
|
||||
|
||||
/// Whether the tangent of the undeformed, unloaded model is positive definite: a first
|
||||
/// tangent that is not, at a state the first increment has already strained, is then the
|
||||
/// material or the geometry (a cutback), not a model that can move freely (an error).
|
||||
fn undeformed_is_stable(&mut self) -> std::result::Result<bool, Failure> {
|
||||
if let Some(stable) = self.undeformed_stable {
|
||||
return Ok(stable);
|
||||
/// How the tangent of the undeformed, unloaded model factors (Cholesky): a first tangent
|
||||
/// that is not positive definite, at a state the first increment has already strained, is
|
||||
/// then the material or the geometry, not a model that can move freely (this error).
|
||||
fn undeformed(&mut self) -> std::result::Result<std::result::Result<(), FactorError>, Failure> {
|
||||
if let Some(u) = &self.undeformed {
|
||||
return Ok(u.clone());
|
||||
}
|
||||
let mut e = self.problem.evaluate(&vec![0.0; self.problem.mesh.dofs()], 0.0, true, &self.committed)?;
|
||||
let k = e.tangent.take().ok_or_else(|| Failure::Fatal(Error::Internal("tangent".into())))?;
|
||||
let [kff] = self.problem.red.reduce([&k])?;
|
||||
let stable = factor_raw(&kff, self.limits).is_ok();
|
||||
self.undeformed_stable = Some(stable);
|
||||
Ok(stable)
|
||||
let u = factor_raw(&kff, self.limits).map(|_| ());
|
||||
self.undeformed = Some(u.clone());
|
||||
Ok(u)
|
||||
}
|
||||
|
||||
/// Factor a tangent: Cholesky, or LDLᵀ when it is not positive definite (an indefinite
|
||||
/// tangent: a strained mixed element, an unstable material, a state past a limit or
|
||||
/// bifurcation point; Newton proceeds on it and the result counts its negative pivots). A
|
||||
/// model that can move freely is an error at its first tangent; a singular tangent later
|
||||
/// is a cutback.
|
||||
fn factor(&mut self, kff: &Csr, first: bool) -> std::result::Result<Symmetric, Failure> {
|
||||
let free_motion = |run: &mut Self| -> std::result::Result<Option<Error>, Failure> {
|
||||
if !first {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(match run.undeformed()? {
|
||||
Err(e @ (FactorError::NotPositiveDefinite { .. } | FactorError::Singular { .. })) => {
|
||||
Some(factor_error(e, run.problem.mesh, run.problem.red))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
match factor_symmetric(kff, self.limits, Kind::Auto) {
|
||||
Ok(f @ Symmetric::Cholesky(_)) => Ok(f),
|
||||
Ok(f) => match free_motion(self)? {
|
||||
Some(e) => Err(Failure::Fatal(e)),
|
||||
None => Ok(f),
|
||||
},
|
||||
Err(FactorError::NotPositiveDefinite { .. } | FactorError::Singular { .. }) => match free_motion(self)? {
|
||||
Some(e) => Err(Failure::Fatal(e)),
|
||||
None => Err(Failure::Cutback("the tangent stiffness is singular (a limit point or bifurcation, or an unstable material)".into())),
|
||||
},
|
||||
Err(e) => Err(Failure::Fatal(factor_error(e, self.problem.mesh, self.problem.red))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The tangent predictor of an increment from the converged `q0` at load factor `from` to
|
||||
@@ -487,10 +602,7 @@ impl Run<'_> {
|
||||
let red = self.problem.red;
|
||||
let mut e = self.problem.evaluate(&red.expand_scaled(q0, from), to, true, &self.committed)?;
|
||||
let k = e.tangent.take().ok_or_else(|| Failure::Fatal(Error::Internal("tangent".into())))?;
|
||||
let jump = red.expand_scaled(&vec![0.0; red.neq()], to - from);
|
||||
let mut kj = vec![0.0; jump.len()];
|
||||
k.mul(&jump, &mut kj);
|
||||
let rf: Vec<f64> = free_residual(red, &e).iter().zip(red.restrict(&kj)).map(|(a, b)| a - b).collect();
|
||||
let rf: Vec<f64> = free_residual(red, &e).iter().zip(prescribed_force(red, &k, to - from)).map(|(a, b)| a - b).collect();
|
||||
let mut dq = rf.clone();
|
||||
let [kff] = red.reduce([&k])?;
|
||||
drop(k);
|
||||
@@ -548,24 +660,14 @@ impl Run<'_> {
|
||||
// The first tangent of the step: a singular one is a modelling error, not a cutback.
|
||||
let first = self.force_floor.is_none();
|
||||
if first {
|
||||
let diagonal = kff.diagonal();
|
||||
let mean = diagonal.iter().map(|d| d.abs()).sum::<f64>() / diagonal.len().max(1) as f64;
|
||||
self.force_floor = Some(1e-8 * mean * self.length);
|
||||
self.seed_force_floor(&kff);
|
||||
}
|
||||
drop(k);
|
||||
let chol = match factor_raw(&kff, self.limits) {
|
||||
Ok(c) => c,
|
||||
Err(FactorError::NotPositiveDefinite { .. }) if !first || self.undeformed_is_stable()? => {
|
||||
return Err(Failure::Cutback(
|
||||
"the tangent stiffness is not positive definite (a limit point, a bifurcation or an unstable material)".into(),
|
||||
));
|
||||
}
|
||||
Err(e) => return Err(Failure::Fatal(factor_error(e, self.problem.mesh, red))),
|
||||
};
|
||||
self.factor_entries = chol.entries();
|
||||
let factor = self.factor(&kff, first)?;
|
||||
self.factor_entries = factor.entries();
|
||||
drop(kff);
|
||||
let mut dq = r.clone();
|
||||
chol.solve(&mut dq)?;
|
||||
factor.solve(&mut dq)?;
|
||||
if dq.iter().any(|v| !v.is_finite()) {
|
||||
return Err(Failure::Cutback("the Newton correction is not finite".into()));
|
||||
}
|
||||
@@ -585,6 +687,7 @@ impl Run<'_> {
|
||||
displacement: s * norm_inf(&dq) / reference,
|
||||
energy: if first > 0.0 { energy / first } else { 0.0 },
|
||||
line_search: s,
|
||||
negative_pivots: factor.inertia().negative,
|
||||
};
|
||||
iterations.push(it);
|
||||
if !it.force.is_finite() {
|
||||
@@ -794,14 +897,50 @@ fn followers(model: &Model, resolved: &fieldcraft_model::Resolved, mesh: &Mesh,
|
||||
/// Solve a nonlinear static step: the step named `step`, or the model's only nonlinear static
|
||||
/// step.
|
||||
pub fn solve_nonlinear(model: &Model, step: Option<&str>, limits: &Limits) -> Result<StaticResult> {
|
||||
let resolved = model.resolve()?;
|
||||
let step = model.select_step(step, |p| matches!(p, Procedure::NonlinearStatic(_)), "nonlinear static")?;
|
||||
let Procedure::NonlinearStatic(settings) = &step.procedure else {
|
||||
let chosen = model.select_step(step, |p| matches!(p, Procedure::NonlinearStatic(_)), "nonlinear static")?;
|
||||
let Procedure::NonlinearStatic(settings) = &chosen.procedure else {
|
||||
return Err(Error::Internal("nonlinear static step".into()));
|
||||
};
|
||||
settings.validate()?;
|
||||
let Some(imperfection) = &settings.imperfection else { return solve_on(model, chosen.name.as_str(), limits, Vec::new()) };
|
||||
let (perturbed, note) = imperfect(model, imperfection, limits)?;
|
||||
solve_on(&perturbed, chosen.name.as_str(), limits, vec![note])
|
||||
}
|
||||
|
||||
/// The model with a buckling mode, scaled to a largest component of `scale`, added to its node
|
||||
/// coordinates (the buckling step solved first), and a note saying so.
|
||||
fn imperfect(model: &Model, imperfection: &Imperfection, limits: &Limits) -> Result<(Model, String)> {
|
||||
let Imperfection { step, mode, scale } = imperfection;
|
||||
if !matches!(model.step(step).map(|s| &s.procedure), Some(Procedure::Buckle { .. })) {
|
||||
return Err(Error::Invalid(format!("the imperfection names step `{step}`, which is not a buckling step")));
|
||||
}
|
||||
let buckled = crate::buckle::solve_buckle(model, Some(step), limits)?;
|
||||
let shape =
|
||||
usize::try_from(*mode).ok().and_then(|m| m.checked_sub(1)).and_then(|m| buckled.modes.get(m)).ok_or_else(|| {
|
||||
Error::Invalid(format!("the imperfection takes mode {mode} of step `{step}`, which found {} modes", buckled.modes.len()))
|
||||
})?;
|
||||
let mut out = model.clone();
|
||||
for (label, u) in buckled.nodes.iter().zip(&shape.shape) {
|
||||
let node = model.node(*label).ok_or_else(|| Error::Internal(format!("node {label}")))?;
|
||||
let xyz: [f64; 3] = std::array::from_fn(|k| node.xyz[k] + scale * u[k]);
|
||||
out.set_node(*label, xyz)?;
|
||||
}
|
||||
let note = format!(
|
||||
"solved on an imperfect geometry: mode {mode} of buckling step `{step}` (load factor {:.6e}) scaled to {scale} added to the node coordinates",
|
||||
shape.eigenvalue
|
||||
);
|
||||
Ok((out, note))
|
||||
}
|
||||
|
||||
fn solve_on(model: &Model, step: &str, limits: &Limits, notes: Vec<String>) -> Result<StaticResult> {
|
||||
let resolved = model.resolve()?;
|
||||
let step = model.step(step).ok_or_else(|| Error::Internal("nonlinear static step".into()))?;
|
||||
let Procedure::NonlinearStatic(settings) = &step.procedure else {
|
||||
return Err(Error::Internal("nonlinear static step".into()));
|
||||
};
|
||||
let mesh = Mesh::new(model, &resolved, limits.max_dofs)?;
|
||||
let mut warnings: Vec<String> = resolved.warnings.iter().map(ToString::to_string).chain(mesh.warnings.iter().cloned()).collect();
|
||||
let mut warnings: Vec<String> =
|
||||
notes.into_iter().chain(resolved.warnings.iter().map(ToString::to_string)).chain(mesh.warnings.iter().cloned()).collect();
|
||||
check_supported(model, &mesh, step, settings, &mut warnings)?;
|
||||
let (graph, order) = pattern(&mesh);
|
||||
ignored_dashpots(&mesh, &mut warnings);
|
||||
@@ -882,7 +1021,7 @@ pub fn solve_nonlinear(model: &Model, step: Option<&str>, limits: &Limits) -> Re
|
||||
factor_entries: 0,
|
||||
committed,
|
||||
path_dependent,
|
||||
undeformed_stable: None,
|
||||
undeformed: None,
|
||||
};
|
||||
|
||||
let mut history = History::default();
|
||||
@@ -901,90 +1040,119 @@ pub fn solve_nonlinear(model: &Model, step: Option<&str>, limits: &Limits) -> Re
|
||||
history.frames.push(Frame { load_factor: lambda, displacement: split(u, &mesh).0 });
|
||||
};
|
||||
keep_frame(&mut history, 0.0, &vec![0.0; mesh.dofs()], &mut warnings);
|
||||
let mut q = vec![0.0; red.neq()];
|
||||
// The step fraction t and the load factor λ(t) of the step's load path (λ = t without one).
|
||||
let (mut t, mut lambda) = (0.0f64, 0.0f64);
|
||||
let mut size = settings.initial_increment;
|
||||
let mut fast = 0usize;
|
||||
let mut last: Option<Evaluation> = None;
|
||||
// The last converged increment's free motion and the change of the load factor over it.
|
||||
let mut previous: Option<(Vec<f64>, f64)> = None;
|
||||
let max_increments = usize::try_from(settings.max_increments).unwrap_or(usize::MAX);
|
||||
while t < 1.0 {
|
||||
if history.increments.len() >= max_increments {
|
||||
return Err(Error::Limit(format!(
|
||||
"step `{}`: {} increments reached the step's cap at load factor {lambda:.6} (raise max_increments)",
|
||||
step.name, settings.max_increments
|
||||
)));
|
||||
let (q, lambda, last) = if let Some(arc) = &settings.arc_length {
|
||||
if problem.field.is_some() {
|
||||
return Err(Error::NotSupported(format!("temperatures in arc-length steps (step `{}`)", step.name)));
|
||||
}
|
||||
// An increment ends at the next point of the load path at the latest.
|
||||
let turn = settings.next_turn(t);
|
||||
let remaining = turn - t;
|
||||
let (target, this) = if size >= remaining * (1.0 - 1e-9) { (turn, remaining) } else { (t + size, size) };
|
||||
let target_lambda = settings.load_factor(target);
|
||||
let change = if settings.load_path.is_some() { target_lambda - lambda } else { this };
|
||||
let mut iterations = Vec::new();
|
||||
let number = history.increments.len() + 1;
|
||||
// Linear extrapolation of the last converged increment's free motion, in proportion to
|
||||
// the change of the load factor (so it turns with the load path).
|
||||
let mut predictor: Option<Vec<f64>> = previous
|
||||
.as_ref()
|
||||
.filter(|(_, prev)| *prev != 0.0)
|
||||
.map(|(dq, prev): &(Vec<f64>, f64)| q.iter().zip(dq).map(|(a, d)| a + change / prev * d).collect());
|
||||
// Path-dependent materials start without one from the tangent predictor.
|
||||
let mut predicted_energy = None;
|
||||
if predictor.is_none() && path_dependent {
|
||||
match run.tangent_predictor(&q, lambda, target_lambda) {
|
||||
Ok(Some((p, energy))) => (predictor, predicted_energy) = (Some(p), Some(energy)),
|
||||
Ok(None) | Err(Failure::Cutback(_)) => {}
|
||||
arc_length(&mut run, arc, step, &mut history, &mut warnings, &mut keep_frame)?
|
||||
} else {
|
||||
let mut q = vec![0.0; red.neq()];
|
||||
// The step fraction t and the load factor λ(t) of the step's load path (λ = t without one).
|
||||
let (mut t, mut lambda) = (0.0f64, 0.0f64);
|
||||
let mut size = settings.initial_increment;
|
||||
let mut fast = 0usize;
|
||||
let mut last: Option<Evaluation> = None;
|
||||
// The last converged increment's free motion and the change of the load factor over it.
|
||||
let mut previous: Option<(Vec<f64>, f64)> = None;
|
||||
let max_increments = usize::try_from(settings.max_increments).unwrap_or(usize::MAX);
|
||||
while t < 1.0 {
|
||||
if history.increments.len() >= max_increments {
|
||||
return Err(Error::Limit(format!(
|
||||
"step `{}`: {} increments reached the step's cap at load factor {lambda:.6} (raise max_increments)",
|
||||
step.name, settings.max_increments
|
||||
)));
|
||||
}
|
||||
// An increment ends at the next point of the load path at the latest.
|
||||
let turn = settings.next_turn(t);
|
||||
let remaining = turn - t;
|
||||
let (target, this) = if size >= remaining * (1.0 - 1e-9) { (turn, remaining) } else { (t + size, size) };
|
||||
let target_lambda = settings.load_factor(target);
|
||||
let change = if settings.load_path.is_some() { target_lambda - lambda } else { this };
|
||||
let mut iterations = Vec::new();
|
||||
let number = history.increments.len() + 1;
|
||||
// Linear extrapolation of the last converged increment's free motion, in proportion to
|
||||
// the change of the load factor (so it turns with the load path).
|
||||
let mut predictor: Option<Vec<f64>> = previous
|
||||
.as_ref()
|
||||
.filter(|(_, prev)| *prev != 0.0)
|
||||
.map(|(dq, prev): &(Vec<f64>, f64)| q.iter().zip(dq).map(|(a, d)| a + change / prev * d).collect());
|
||||
// Path-dependent materials start without one from the tangent predictor.
|
||||
let mut predicted_energy = None;
|
||||
if predictor.is_none() && path_dependent {
|
||||
match run.tangent_predictor(&q, lambda, target_lambda) {
|
||||
Ok(Some((p, energy))) => (predictor, predicted_energy) = (Some(p), Some(energy)),
|
||||
Ok(None) | Err(Failure::Cutback(_)) => {}
|
||||
Err(Failure::Fatal(e)) => return Err(e),
|
||||
}
|
||||
}
|
||||
match run.increment(&q, predictor.as_deref(), predicted_energy, target_lambda, change.abs(), &mut iterations) {
|
||||
Ok(c) => {
|
||||
previous = Some((c.q.iter().zip(&q).map(|(a, b)| a - b).collect(), change));
|
||||
let count = iterations.len();
|
||||
history.increments.push(Increment {
|
||||
number,
|
||||
load_factor: target_lambda,
|
||||
size: this,
|
||||
iterations,
|
||||
converged: true,
|
||||
cutback: None,
|
||||
negative_pivots: 0,
|
||||
});
|
||||
(t, lambda) = (target, target_lambda);
|
||||
q = c.q;
|
||||
keep_frame(&mut history, lambda, &red.expand_scaled(&q, lambda), &mut warnings);
|
||||
run.committed.clone_from(&c.evaluation.history);
|
||||
last = Some(c.evaluation);
|
||||
fast = if count <= FAST_ITERATIONS { fast + 1 } else { 0 };
|
||||
if fast >= 2 {
|
||||
size *= GROWTH;
|
||||
} else if count > SLOW_ITERATIONS {
|
||||
size *= SHRINK;
|
||||
}
|
||||
size = size.clamp(settings.min_increment, settings.max_increment);
|
||||
}
|
||||
Err(Failure::Fatal(e)) => return Err(e),
|
||||
}
|
||||
}
|
||||
match run.increment(&q, predictor.as_deref(), predicted_energy, target_lambda, change.abs(), &mut iterations) {
|
||||
Ok(c) => {
|
||||
previous = Some((c.q.iter().zip(&q).map(|(a, b)| a - b).collect(), change));
|
||||
let count = iterations.len();
|
||||
history.increments.push(Increment { number, load_factor: target_lambda, size: this, iterations, converged: true, cutback: None });
|
||||
(t, lambda) = (target, target_lambda);
|
||||
q = c.q;
|
||||
keep_frame(&mut history, lambda, &red.expand_scaled(&q, lambda), &mut warnings);
|
||||
run.committed.clone_from(&c.evaluation.history);
|
||||
last = Some(c.evaluation);
|
||||
fast = if count <= FAST_ITERATIONS { fast + 1 } else { 0 };
|
||||
if fast >= 2 {
|
||||
size *= GROWTH;
|
||||
} else if count > SLOW_ITERATIONS {
|
||||
size *= SHRINK;
|
||||
}
|
||||
size = size.clamp(settings.min_increment, settings.max_increment);
|
||||
}
|
||||
Err(Failure::Fatal(e)) => return Err(e),
|
||||
Err(Failure::Cutback(reason)) => {
|
||||
history.increments.push(Increment {
|
||||
number,
|
||||
load_factor: target_lambda,
|
||||
size: this,
|
||||
iterations,
|
||||
converged: false,
|
||||
cutback: Some(reason.clone()),
|
||||
});
|
||||
fast = 0;
|
||||
size = this * CUTBACK;
|
||||
if size < settings.min_increment * (1.0 - 1e-9) {
|
||||
return Err(Error::NotConverged(format!(
|
||||
"step `{}` stopped at load factor {lambda:.6} (step fraction {t:.6}): the increment to {target_lambda:.6} failed ({reason}) and a smaller one would be below the minimum increment {}",
|
||||
step.name, settings.min_increment
|
||||
)));
|
||||
Err(Failure::Cutback(reason)) => {
|
||||
history.increments.push(Increment {
|
||||
number,
|
||||
load_factor: target_lambda,
|
||||
size: this,
|
||||
iterations,
|
||||
converged: false,
|
||||
cutback: Some(reason.clone()),
|
||||
negative_pivots: 0,
|
||||
});
|
||||
fast = 0;
|
||||
size = this * CUTBACK;
|
||||
if size < settings.min_increment * (1.0 - 1e-9) {
|
||||
return Err(Error::NotConverged(format!(
|
||||
"step `{}` stopped at load factor {lambda:.6} (step fraction {t:.6}): the increment to {target_lambda:.6} failed ({reason}) and a smaller one would be below the minimum increment {}",
|
||||
step.name, settings.min_increment
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(q, lambda, last)
|
||||
};
|
||||
history.iterations = run.iterations;
|
||||
let u = red.expand_scaled(&q, lambda);
|
||||
let evaluation = match last {
|
||||
Some(e) => e,
|
||||
None => problem.evaluate(&u, lambda, false, &run.committed)?,
|
||||
};
|
||||
if let Some((at, negative)) = history
|
||||
.increments
|
||||
.iter()
|
||||
.filter(|_| settings.arc_length.is_none())
|
||||
.filter(|i| i.converged)
|
||||
.filter_map(|i| i.iterations.last().map(|it| (i.load_factor, it.negative_pivots)))
|
||||
.find(|(_, n)| *n > 0)
|
||||
{
|
||||
warnings.push(format!(
|
||||
"the converged tangent had {negative} negative eigenvalue(s) from load factor {at:.6} on: an unstable equilibrium under load control (past a limit or bifurcation point, or an unstable material)"
|
||||
));
|
||||
}
|
||||
if let Some(a) = problem.follower_asymmetry(&u, lambda)?
|
||||
&& a > 1e-6
|
||||
{
|
||||
@@ -1107,3 +1275,285 @@ fn finish(
|
||||
nonlinear: Some(history),
|
||||
})
|
||||
}
|
||||
|
||||
/// What one arc-length increment starts from: the tangent at the converged state, factored, and
|
||||
/// the tangent displacement of the unit load.
|
||||
struct ArcStart {
|
||||
factor: Symmetric,
|
||||
load_displacement: Vec<f64>,
|
||||
}
|
||||
|
||||
impl Run<'_> {
|
||||
/// The tangent at (q, λ) factored (Cholesky, or LDLᵀ past a critical point), the unit load
|
||||
/// ∂r/∂λ at that state over the free equations (the loads at factor 1, less K T_p u_p for
|
||||
/// prescribed motions), and the evaluation's residual.
|
||||
fn arc_tangent(&mut self, e: &mut Evaluation, u: &[f64], first: bool) -> std::result::Result<(Symmetric, Vec<f64>), Failure> {
|
||||
let red = self.problem.red;
|
||||
let k = e.tangent.take().ok_or_else(|| Failure::Fatal(Error::Internal("tangent".into())))?;
|
||||
let mut g = red.restrict(&self.problem.reference_load(u)?);
|
||||
if red.largest_prescribed() > 0.0 {
|
||||
g.iter_mut().zip(prescribed_force(red, &k, 1.0)).for_each(|(a, b)| *a -= b);
|
||||
}
|
||||
let [kff] = red.reduce([&k])?;
|
||||
drop(k);
|
||||
if first {
|
||||
self.seed_force_floor(&kff);
|
||||
}
|
||||
let factor = self.factor(&kff, first)?;
|
||||
self.factor_entries = factor.entries();
|
||||
Ok((factor, g))
|
||||
}
|
||||
|
||||
/// The converged state's tangent (from its evaluation `e`, which keeps its forces) and the
|
||||
/// unit load's tangent displacement.
|
||||
fn arc_start(&mut self, e: &mut Evaluation, q: &[f64], lambda: f64, first: bool) -> std::result::Result<ArcStart, Failure> {
|
||||
let (factor, mut g) = self.arc_tangent(e, &self.problem.red.expand_scaled(q, lambda), first)?;
|
||||
factor.solve(&mut g)?;
|
||||
if g.iter().any(|v| !v.is_finite()) || norm_inf(&g) == 0.0 {
|
||||
return Err(Failure::Fatal(Error::Invalid("the step's loads do not move the model, so an arc length cannot be measured".into())));
|
||||
}
|
||||
Ok(ArcStart { factor, load_displacement: g })
|
||||
}
|
||||
|
||||
/// One arc-length increment from the converged (q0, λ0) (M. A. Crisfield, *A fast
|
||||
/// incremental/iterative solution procedure that handles "snap-through"*, Computers &
|
||||
/// Structures 13:55–62, 1981): the constraint Δqᵀ Δq + w Δλ² = Δl² (w = 0 cylindrical, w =
|
||||
/// ‖q_f‖² spherical) with the load factor an unknown. Predictor along the tangent, its sign
|
||||
/// by the angle with the last increment (M. Feng, D. Perić, D. R. J. Owen, *A new criterion for
|
||||
/// determination of initial loading parameter in arc-length methods*, Computers & Structures
|
||||
/// 58(3):479–485, 1996); each correction δq = δq_r + δλ δq_g solves the quadratic for δλ and
|
||||
/// takes the root whose increment is closest in direction to the previous iterate's (the
|
||||
/// angle criterion, Crisfield 1981).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn arc_increment(
|
||||
&mut self,
|
||||
q0: &[f64],
|
||||
lambda0: f64,
|
||||
start: &ArcStart,
|
||||
arc: f64,
|
||||
weight: f64,
|
||||
previous: Option<&(Vec<f64>, f64)>,
|
||||
iterations: &mut Vec<Iteration>,
|
||||
) -> std::result::Result<(Vec<f64>, f64, Evaluation), Failure> {
|
||||
let tol = self.settings.tolerances;
|
||||
let qg = &start.load_displacement;
|
||||
let sign = match previous {
|
||||
Some((dq, dl)) if dot(dq, qg) + weight * dl < 0.0 => -1.0,
|
||||
_ => 1.0,
|
||||
};
|
||||
let mut dlam = sign * arc / (dot(qg, qg) + weight).sqrt();
|
||||
let mut dq: Vec<f64> = qg.iter().map(|g| dlam * g).collect();
|
||||
let mut correction = f64::INFINITY;
|
||||
let mut first_energy: Option<f64> = None;
|
||||
let max_iterations = usize::try_from(self.settings.max_iterations).unwrap_or(usize::MAX);
|
||||
let at = |dq: &[f64]| -> Vec<f64> { q0.iter().zip(dq).map(|(a, b)| a + b).collect() };
|
||||
for it in 0..=max_iterations {
|
||||
let q = at(&dq);
|
||||
let mut e = self.state(&q, lambda0 + dlam, true)?;
|
||||
let r = self.residual(&e);
|
||||
let force = norm_inf(&r) / self.scale();
|
||||
if !force.is_finite() {
|
||||
return Err(Failure::Cutback("the residual is not finite".into()));
|
||||
}
|
||||
if it > 0 && ((force <= tol.force && correction <= tol.displacement) || force <= ROUND_OFF * tol.force) {
|
||||
return Ok((q, lambda0 + dlam, e));
|
||||
}
|
||||
if it == max_iterations {
|
||||
break;
|
||||
}
|
||||
if self.iterations >= self.limits.max_newton_iterations {
|
||||
return Err(Failure::Fatal(Error::Limit(format!(
|
||||
"the step took {} Newton iterations, the limit (raise max_newton_iterations or loosen the tolerances)",
|
||||
self.iterations
|
||||
))));
|
||||
}
|
||||
self.iterations += 1;
|
||||
let u = self.problem.red.expand_scaled(&q, lambda0 + dlam);
|
||||
let (factor, mut dqg) = self.arc_tangent(&mut e, &u, false)?;
|
||||
let mut dqr = r.clone();
|
||||
factor.solve(&mut dqr)?;
|
||||
factor.solve(&mut dqg)?;
|
||||
// (Δq + δq_r + δλ δq_g)² + w (Δλ + δλ)² = Δl².
|
||||
let base: Vec<f64> = dq.iter().zip(&dqr).map(|(a, b)| a + b).collect();
|
||||
let a = dot(&dqg, &dqg) + weight;
|
||||
let b = 2.0 * (dot(&dqg, &base) + weight * dlam);
|
||||
let c = dot(&base, &base) + weight * dlam * dlam - arc * arc;
|
||||
let disc = b * b - 4.0 * a * c;
|
||||
if !(disc >= 0.0) || !(a > 0.0) {
|
||||
return Err(Failure::Cutback("the arc-length constraint has no real root (the arc is too long here)".into()));
|
||||
}
|
||||
let root = disc.sqrt();
|
||||
// Stable roots of a x² + b x + c (no cancellation).
|
||||
let qr = -0.5 * (b + b.signum() * root);
|
||||
let roots = if qr == 0.0 { [0.0, 0.0] } else { [qr / a, c / qr] };
|
||||
let cosine = |dl: f64| dot(&dq, &base) + dl * dot(&dq, &dqg) + weight * dlam * (dlam + dl);
|
||||
let dl = if cosine(roots[0]) >= cosine(roots[1]) { roots[0] } else { roots[1] };
|
||||
let step: Vec<f64> = dqr.iter().zip(&dqg).map(|(r, g)| r + dl * g).collect();
|
||||
if step.iter().any(|v| !v.is_finite()) {
|
||||
return Err(Failure::Cutback("the arc-length correction is not finite".into()));
|
||||
}
|
||||
dq.iter_mut().zip(&step).for_each(|(a, s)| *a += s);
|
||||
dlam += dl;
|
||||
correction = norm_inf(&step) / norm_inf(&dq).max(1e-12 * self.length);
|
||||
let energy = dot(&step, &r).abs();
|
||||
let first = *first_energy.get_or_insert(energy);
|
||||
iterations.push(Iteration {
|
||||
force,
|
||||
displacement: correction,
|
||||
energy: if first > 0.0 { energy / first } else { 0.0 },
|
||||
line_search: 1.0,
|
||||
negative_pivots: factor.inertia().negative,
|
||||
});
|
||||
}
|
||||
Err(Failure::Cutback(format!("no convergence in {} iterations", self.settings.max_iterations)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Follow a step's equilibrium path by arc length (Riks 1979, Crisfield 1981): the load factor
|
||||
/// is an unknown, so the path goes through limit points. The first increment's load factor
|
||||
/// change is the step's initial increment, which sets the arc length; increments grow and
|
||||
/// shrink as under load control (the arc length in proportion, within the minimum and maximum
|
||||
/// increments' arcs). The tangent at every converged state is factored for the next predictor
|
||||
/// (Cholesky, LDLᵀ when indefinite); its negative eigenvalues are recorded per increment, and
|
||||
/// where their count changes a critical point is reported: a limit point when the load factor
|
||||
/// turns there, a bifurcation otherwise. The step ends at the maximum load factor, at the
|
||||
/// displacement limit, or at its increment cap (with a warning).
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn arc_length(
|
||||
run: &mut Run,
|
||||
arc: &ArcLength,
|
||||
step: &Step,
|
||||
history: &mut History,
|
||||
warnings: &mut Vec<String>,
|
||||
keep_frame: &mut dyn FnMut(&mut History, f64, &[f64], &mut Vec<String>),
|
||||
) -> Result<(Vec<f64>, f64, Option<Evaluation>)> {
|
||||
let settings = run.settings;
|
||||
let red = run.problem.red;
|
||||
let mesh = run.problem.mesh;
|
||||
let limit = match &arc.displacement_limit {
|
||||
Some(l) => {
|
||||
let slot =
|
||||
mesh.node(l.node).ok_or_else(|| Error::Invalid(format!("the displacement limit's node {} has no degrees of freedom", l.node)))?;
|
||||
let dofs = translations(mesh, slot)?;
|
||||
let dof = dofs
|
||||
.get(usize::from(l.direction).saturating_sub(1))
|
||||
.copied()
|
||||
.ok_or_else(|| Error::Invalid(format!("the displacement limit's node {} has no direction {}", l.node, l.direction)))?;
|
||||
Some((dof, l.displacement.abs()))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let fatal = |f: Failure| match f {
|
||||
Failure::Fatal(e) => e,
|
||||
Failure::Cutback(m) => Error::NotConverged(format!("step `{}`: {m}", step.name)),
|
||||
};
|
||||
let mut q = vec![0.0; red.neq()];
|
||||
let mut lambda = 0.0f64;
|
||||
let mut initial = run.state(&q, lambda, true).map_err(fatal)?;
|
||||
let mut start = run.arc_start(&mut initial, &q, lambda, true).map_err(fatal)?;
|
||||
// States: load factor and negative eigenvalues, from the undeformed one.
|
||||
let mut states: Vec<(usize, f64, usize)> = vec![(0, 0.0, start.factor.inertia().negative)];
|
||||
let scale = (dot(&start.load_displacement, &start.load_displacement)).sqrt();
|
||||
let weight = if arc.constraint == ArcConstraint::Spherical { scale * scale } else { 0.0 };
|
||||
let unit = (scale * scale + weight).sqrt();
|
||||
let mut size = settings.initial_increment * unit;
|
||||
let (smallest, largest) = (settings.min_increment * unit, settings.max_increment * unit);
|
||||
let mut previous: Option<(Vec<f64>, f64)> = None;
|
||||
let mut fast = 0usize;
|
||||
let mut last: Option<Evaluation> = None;
|
||||
let max_increments = usize::try_from(settings.max_increments).unwrap_or(usize::MAX);
|
||||
loop {
|
||||
if history.increments.len() >= max_increments {
|
||||
warnings.push(format!(
|
||||
"the arc-length step `{}` ended at its cap of {} increments, at load factor {lambda:.6}",
|
||||
step.name, settings.max_increments
|
||||
));
|
||||
break;
|
||||
}
|
||||
let number = history.increments.len() + 1;
|
||||
let mut iterations = Vec::new();
|
||||
match run.arc_increment(&q, lambda, &start, size, weight, previous.as_ref(), &mut iterations) {
|
||||
Ok((q1, lambda1, mut evaluation)) => {
|
||||
let change = lambda1 - lambda;
|
||||
previous = Some((q1.iter().zip(&q).map(|(a, b)| a - b).collect(), change));
|
||||
let count = iterations.len();
|
||||
(q, lambda) = (q1, lambda1);
|
||||
run.committed.clone_from(&evaluation.history);
|
||||
let u = red.expand_scaled(&q, lambda);
|
||||
keep_frame(history, lambda, &u, warnings);
|
||||
start = run.arc_start(&mut evaluation, &q, lambda, false).map_err(fatal)?;
|
||||
let negative = start.factor.inertia().negative;
|
||||
history.increments.push(Increment {
|
||||
number,
|
||||
load_factor: lambda,
|
||||
size: change,
|
||||
iterations,
|
||||
converged: true,
|
||||
cutback: None,
|
||||
negative_pivots: negative,
|
||||
});
|
||||
states.push((number, lambda, negative));
|
||||
last = Some(evaluation);
|
||||
fast = if count <= FAST_ITERATIONS { fast + 1 } else { 0 };
|
||||
if fast >= 2 {
|
||||
size *= GROWTH;
|
||||
} else if count > SLOW_ITERATIONS {
|
||||
size *= SHRINK;
|
||||
}
|
||||
size = size.clamp(smallest, largest);
|
||||
let reached = limit.is_some_and(|(dof, value)| u.get(dof).is_some_and(|x| x.abs() >= value));
|
||||
if lambda >= arc.max_load_factor || reached {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(Failure::Fatal(e)) => return Err(e),
|
||||
Err(Failure::Cutback(reason)) => {
|
||||
history.increments.push(Increment {
|
||||
number,
|
||||
load_factor: lambda,
|
||||
size: 0.0,
|
||||
iterations,
|
||||
converged: false,
|
||||
cutback: Some(reason.clone()),
|
||||
negative_pivots: 0,
|
||||
});
|
||||
fast = 0;
|
||||
size *= CUTBACK;
|
||||
if size < smallest * (1.0 - 1e-9) {
|
||||
return Err(Error::NotConverged(format!(
|
||||
"arc-length step `{}` stopped at load factor {lambda:.6}: an increment failed ({reason}) and a shorter arc would be below the minimum increment",
|
||||
step.name
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
history.critical_points = critical_points(&states);
|
||||
Ok((q, lambda, last))
|
||||
}
|
||||
|
||||
/// Critical points from the converged states' (increment, load factor, negative eigenvalues):
|
||||
/// where the count changes, a limit point if the load factor turns within a state of it, a
|
||||
/// bifurcation otherwise.
|
||||
fn critical_points(states: &[(usize, f64, usize)]) -> Vec<CriticalPoint> {
|
||||
let mut out = Vec::new();
|
||||
for k in 1..states.len() {
|
||||
let (Some(&(_, l0, n0)), Some(&(increment, _, n1))) = (states.get(k - 1), states.get(k)) else { continue };
|
||||
if n0 == n1 {
|
||||
continue;
|
||||
}
|
||||
let around: Vec<f64> = states.get(k.saturating_sub(2)..(k + 2).min(states.len())).unwrap_or_default().iter().map(|s| s.1).collect();
|
||||
let turns = around.windows(3).any(|w| (w[1] - w[0]) * (w[2] - w[1]) < 0.0);
|
||||
let (kind, load_factor) = if turns {
|
||||
// The extreme load factor next to the change.
|
||||
let rising = around.windows(2).next().is_some_and(|w| w[1] >= w[0]);
|
||||
let extreme =
|
||||
if rising { around.iter().copied().fold(f64::NEG_INFINITY, f64::max) } else { around.iter().copied().fold(f64::INFINITY, f64::min) };
|
||||
(CriticalKind::Limit, extreme)
|
||||
} else {
|
||||
(CriticalKind::Bifurcation, l0)
|
||||
};
|
||||
out.push(CriticalPoint { kind, increment, load_factor, negative_before: n0, negative_after: n1 });
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -155,6 +155,14 @@ impl Kernel<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The initial-stress stiffness of stresses at the stiffness points.
|
||||
pub fn geometric_stiffness(&self, stress: &[[f64; 6]]) -> fieldcraft_fem::Result<fieldcraft_fem::dense::Matrix> {
|
||||
match self {
|
||||
Kernel::Solid(s) => s.geometric_stiffness(stress),
|
||||
Kernel::Plane(p) => p.geometric_stiffness(stress),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn rule(&self) -> fieldcraft_fem::quadrature::Rule {
|
||||
match self {
|
||||
Kernel::Solid(s) => s.rule(),
|
||||
@@ -418,6 +426,11 @@ impl Mesh {
|
||||
|
||||
/// Build it from the model and its resolved view, refusing what the solver cannot represent.
|
||||
pub fn new(model: &Model, resolved: &Resolved, max_dofs: usize) -> Result<Mesh> {
|
||||
if let Some(name) = model.contacts().keys().next() {
|
||||
return Err(Error::NotSupported(format!(
|
||||
"contact (`{name}`) in implicit analyses (it comes with M7): a model's contacts apply to all its steps, so solve its explicit dynamic steps, or remove the contacts to solve the implicit ones"
|
||||
)));
|
||||
}
|
||||
let mut elements = Vec::new();
|
||||
let mut trusses = Vec::new();
|
||||
let mut structural = Vec::new();
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
//! Arc-length (Riks–Crisfield) control through limit points: the snap-through of a shallow
|
||||
//! sinusoidal arch of solids under a sinusoidal dead load, against the one-mode closed form of
|
||||
//! shallow arch theory (exact for this load and shape on the symmetric path), the limit points'
|
||||
//! load factors and the tangent's inertia along the path, and what arc-length steps refuse.
|
||||
//!
|
||||
//! Closed form: an arch y₀ = a sin(πx/L) on pins at a fixed span, bending stiffness EI, axial EA,
|
||||
//! r² = I/A, under q = q₀ sin(πx/L) deflects in the same shape, w = c sin(πx/L), with
|
||||
//! q₀ = EI k⁴ [c + (a − c)(2ac − c²)/(4r²)], k = π/L (the energy of bending and of the axial
|
||||
//! shortening ½∫(y₀′² − y′²)dx, S. P. Timoshenko, J. M. Gere, *Theory of Elastic Stability*, 2nd
|
||||
//! ed., 1961, §7.6, and Y. C. Fung, A. Kaplan, NACA TN 2840, 1952). Its limit points are at
|
||||
//! c = a ∓ r √((a²/r² − 4)/3); for a/r = 3.5 the antisymmetric mode never bifurcates first (the
|
||||
//! axial force stays below the second Euler load 4EIk², reached only at a/r = 4).
|
||||
|
||||
mod common;
|
||||
|
||||
use common::*;
|
||||
use fieldcraft_model::*;
|
||||
use fieldcraft_solver::nonlinear::CriticalKind;
|
||||
use fieldcraft_solver::{Limits, solve_nonlinear};
|
||||
|
||||
const E: f64 = 1.0e4;
|
||||
const SPAN: f64 = 100.0;
|
||||
const H: f64 = 1.0;
|
||||
|
||||
fn rise() -> f64 {
|
||||
3.5 * H / 12f64.sqrt()
|
||||
}
|
||||
|
||||
/// q₀ for a midspan deflection c (positive down).
|
||||
fn load(c: f64) -> f64 {
|
||||
let (a, r2, k) = (rise(), H * H / 12.0, std::f64::consts::PI / SPAN);
|
||||
E * H.powi(3) / 12.0 * k.powi(4) * (c + (a - c) * (2.0 * a * c - c * c) / (4.0 * r2))
|
||||
}
|
||||
|
||||
fn limit_points() -> (f64, f64) {
|
||||
let (a, r) = (rise(), H / 12f64.sqrt());
|
||||
let d = r * ((a * a / (r * r) - 4.0) / 3.0).sqrt();
|
||||
(a - d, a + d)
|
||||
}
|
||||
|
||||
/// The arch (40 × 2 × 1 hex20, unit width), its load scaled to the closed-form limit load, and
|
||||
/// the label of the midspan node at mid-height.
|
||||
fn arch(arc: Option<ArcLength>) -> (Grid, u32, f64) {
|
||||
let a = rise();
|
||||
let mut g = grid([40, 2, 1], ElementKind::Hex20, |p| {
|
||||
let x = SPAN * p[0];
|
||||
[x, a * (std::f64::consts::PI * x / SPAN).sin() + H * (p[1] - 0.5), p[2]]
|
||||
});
|
||||
let reference = load(limit_points().0);
|
||||
let settings = NonlinearStatic { arc_length: arc, initial_increment: 0.1, max_increments: 200, ..NonlinearStatic::default() };
|
||||
g.define(iso(E, 0.0), None, Formulation::default(), Procedure::NonlinearStatic(settings));
|
||||
g.node_set("pins", |p| (near(p[0], 0.0) || near(p[0], 1.0)) && near(p[1], 0.5));
|
||||
g.bc("pins", BoundaryCondition::Displacement { target: Target::Set("pins".into()), values: [Some(0.0), Some(0.0), None, None, None, None] });
|
||||
g.node_set("width", |_| true);
|
||||
g.bc("width", BoundaryCondition::Displacement { target: Target::Set("width".into()), values: [None, None, Some(0.0), None, None, None] });
|
||||
// q₀ sin(πx/L) per unit length, piecewise constant per element on the top face (dead).
|
||||
let top = g.faces_where(|p| near(p[1], 1.0));
|
||||
for f in top {
|
||||
let nodes = &g.model.element(f.element).unwrap().nodes;
|
||||
let xc = nodes.iter().take(8).map(|n| g.model.node(*n).unwrap().xyz[0]).sum::<f64>() / 8.0;
|
||||
let name = format!("q{}", f.element);
|
||||
g.model.add_set(&name, Set { faces: vec![f], ..Set::default() }).unwrap();
|
||||
let total = -reference * (std::f64::consts::PI * xc / SPAN).sin() * SPAN / 40.0;
|
||||
g.load(&name, Load::Force { target: Target::Set(name.clone()), vector: [0.0, total, 0.0], distribution: Distribution::Total });
|
||||
}
|
||||
let mid = g.nodes_where(|p| near(p[0], 0.5) && near(p[1], 0.5) && near(p[2], 0.0))[0];
|
||||
(g, mid, reference)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shallow_arch_snaps_through() {
|
||||
let a = rise();
|
||||
let (_, mid, _) = arch(None);
|
||||
let arc = ArcLength {
|
||||
displacement_limit: Some(DisplacementLimit { node: mid, direction: 2, displacement: -2.2 * a }),
|
||||
max_load_factor: 10.0,
|
||||
..ArcLength::default()
|
||||
};
|
||||
let (g, _, reference) = arch(Some(arc));
|
||||
let r = solve_nonlinear(&g.model, Some("Step"), &Limits::default()).unwrap();
|
||||
let h = r.nonlinear.as_ref().unwrap();
|
||||
let at = r.nodes.binary_search(&mid).unwrap();
|
||||
// Every converged state on the closed-form path.
|
||||
let mut worst = 0.0f64;
|
||||
for frame in &h.frames {
|
||||
let c = -frame.displacement[at][1];
|
||||
let err = (frame.load_factor * reference - load(c)).abs() / reference;
|
||||
worst = worst.max(err);
|
||||
}
|
||||
let (_, c_valley) = limit_points();
|
||||
eprintln!("{} increments; worst path error {:.3} % of the limit load", h.increments.len(), 100.0 * worst);
|
||||
for p in &h.critical_points {
|
||||
eprintln!(" {:?} at increment {}: λ = {:.5} ({} → {} negative)", p.kind, p.increment, p.load_factor, p.negative_before, p.negative_after);
|
||||
}
|
||||
assert!(worst < 0.02, "{worst}");
|
||||
assert!(-r.displacement[at][1] >= 2.2 * a, "ended at the displacement limit");
|
||||
// The limit points: the peak (λ = 1 by construction) and the valley, from the inertia.
|
||||
let [peak, valley] = h.critical_points.as_slice() else { panic!("{:?}", h.critical_points) };
|
||||
assert_eq!((peak.kind, peak.negative_before, peak.negative_after), (CriticalKind::Limit, 0, 1));
|
||||
assert_eq!((valley.kind, valley.negative_before, valley.negative_after), (CriticalKind::Limit, 1, 0));
|
||||
assert!((peak.load_factor - 1.0).abs() < 0.02, "{}", peak.load_factor);
|
||||
assert!((valley.load_factor - load(c_valley) / reference).abs() < 0.02, "{} vs {}", valley.load_factor, load(c_valley) / reference);
|
||||
// Negative pivots exactly between the limit points: every converged state's count follows
|
||||
// the sign of dλ along the path.
|
||||
let states: Vec<(f64, usize)> = h.increments.iter().filter(|i| i.converged).map(|i| (i.load_factor, i.negative_pivots)).collect();
|
||||
for w in states.windows(3) {
|
||||
let falling = w[2].0 < w[1].0 && w[1].0 < w[0].0;
|
||||
let rising = w[2].0 > w[1].0 && w[1].0 > w[0].0;
|
||||
if falling {
|
||||
assert_eq!(w[1].1, 1, "{states:?}");
|
||||
}
|
||||
if rising {
|
||||
assert_eq!(w[1].1, 0, "{states:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arc_length_steps_refuse_what_they_cannot_do() {
|
||||
let arc = ArcLength::default();
|
||||
let mut settings = NonlinearStatic { arc_length: Some(arc.clone()), load_path: Some(vec![[0.0, 0.0], [1.0, 1.0]]), ..NonlinearStatic::default() };
|
||||
assert!(settings.validate().is_err(), "a load path");
|
||||
settings.load_path = None;
|
||||
settings.arc_length = Some(ArcLength { max_load_factor: f64::NAN, ..arc.clone() });
|
||||
assert!(settings.validate().is_err());
|
||||
settings.arc_length = Some(ArcLength { displacement_limit: Some(DisplacementLimit { node: 1, direction: 7, displacement: 1.0 }), ..arc.clone() });
|
||||
assert!(settings.validate().is_err());
|
||||
// A node that does not exist; no load at all.
|
||||
let (mut g, _, _) =
|
||||
arch(Some(ArcLength { displacement_limit: Some(DisplacementLimit { node: 999_999, direction: 2, displacement: 1.0 }), ..arc }));
|
||||
assert!(solve_nonlinear(&g.model, Some("Step"), &Limits::default()).is_err());
|
||||
let loads: Vec<String> = g.model.step("Step").unwrap().loads.iter().cloned().collect();
|
||||
for l in loads {
|
||||
g.model.set_load_active("Step", &l, false).unwrap();
|
||||
}
|
||||
assert!(solve_nonlinear(&g.model, Some("Step"), &Limits::default()).is_err());
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
//! Linear buckling against closed forms: Euler columns of hex20 solids (pinned–pinned by a
|
||||
//! symmetry plane at midspan, and clamped–free), with Engesser's shear correction
|
||||
//! P = P_e / (1 + P_e/(κ G A)) (S. P. Timoshenko, J. M. Gere, *Theory of Elastic Stability*,
|
||||
//! 2nd ed., McGraw-Hill 1961, §2.1, §2.17), the shifted (LDLᵀ) form against the plain one, and
|
||||
//! what buckling steps refuse.
|
||||
|
||||
mod common;
|
||||
|
||||
use common::*;
|
||||
use fieldcraft_model::*;
|
||||
use fieldcraft_solver::{Limits, solve_buckle};
|
||||
|
||||
const E: f64 = 1000.0;
|
||||
const B: f64 = 1.0;
|
||||
const L: f64 = 20.0;
|
||||
|
||||
fn buckle(modes: u32, shift: Option<f64>) -> Procedure {
|
||||
Procedure::Buckle { modes, shift }
|
||||
}
|
||||
|
||||
/// Engesser's critical load of a square column of side B and effective length `le`, ν = 0.
|
||||
fn engesser(le: f64) -> f64 {
|
||||
let (a, i, g) = (B * B, B.powi(4) / 12.0, E / 2.0);
|
||||
let pe = std::f64::consts::PI.powi(2) * E * i / (le * le);
|
||||
pe / (1.0 + pe / (5.0 / 6.0 * g * a))
|
||||
}
|
||||
|
||||
/// A column of `length` along z, 2 × 2 × `cells` hex20, pressed by a unit pressure on its top.
|
||||
fn column(length: f64, cells: usize, shift: Option<f64>) -> Grid {
|
||||
let mut g = grid([2, 2, cells], ElementKind::Hex20, |x| [B * x[0], B * x[1], length * x[2]]);
|
||||
g.define(iso(E, 0.0), None, Formulation::default(), buckle(3, shift));
|
||||
g.face_set("top", |x| near(x[2], 1.0));
|
||||
g.load("press", Load::Pressure { set: "top".into(), magnitude: 1.0 });
|
||||
g
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn euler_columns() {
|
||||
// Pinned–pinned: half the column, the pinned end (z = 0 here is the loaded top) held
|
||||
// laterally over its face (which leaves its rotation free), midspan a symmetry plane.
|
||||
let mut g = grid([2, 2, 10], ElementKind::Hex20, |x| [B * x[0], B * x[1], L / 2.0 * x[2]]);
|
||||
g.define(iso(E, 0.0), None, Formulation::default(), buckle(2, None));
|
||||
g.face_set("end", |x| near(x[2], 0.0));
|
||||
g.load("press", Load::Pressure { set: "end".into(), magnitude: 1.0 });
|
||||
g.node_set("pin", |x| near(x[2], 0.0));
|
||||
g.bc("pin", BoundaryCondition::Displacement { target: Target::Set("pin".into()), values: [Some(0.0), Some(0.0), None, None, None, None] });
|
||||
g.symmetry("mid", Symmetry::Z, |x| near(x[2], 1.0));
|
||||
let r = solve_buckle(&g.model, Some("Step"), &Limits::default()).unwrap();
|
||||
let want = engesser(L) / (B * B);
|
||||
let got = r.modes[0].eigenvalue;
|
||||
eprintln!("pinned: λ = {got:.6} (Engesser {want:.6}, {:+.3} %), second {:.6}", 100.0 * (got / want - 1.0), r.modes[1].eigenvalue);
|
||||
assert!((got / want - 1.0).abs() < 5e-3);
|
||||
assert!((r.modes[1].eigenvalue / got - 1.0).abs() < 1e-6, "the square section's two planes");
|
||||
assert!(r.buckling.as_ref().unwrap().negative.is_empty() || r.buckling.as_ref().unwrap().negative[0] < -got);
|
||||
|
||||
// Clamped–free: the base held, the top free: le = 2L.
|
||||
let mut g = column(L / 2.0, 10, None);
|
||||
g.fixed("base", |x| near(x[2], 0.0));
|
||||
let r = solve_buckle(&g.model, Some("Step"), &Limits::default()).unwrap();
|
||||
let want = engesser(L) / (B * B);
|
||||
let got = r.modes[0].eigenvalue;
|
||||
eprintln!("clamped–free: λ = {got:.6} (Engesser {want:.6}, {:+.3} %)", 100.0 * (got / want - 1.0));
|
||||
assert!((got / want - 1.0).abs() < 5e-3);
|
||||
// Scaled to a largest component of 1, which is lateral at the free top.
|
||||
let big = r.modes[0].shape.iter().flatten().fold(0.0f64, |m, v| m.max(v.abs()));
|
||||
assert!((big - 1.0).abs() < 1e-12);
|
||||
|
||||
// Shifted between the first and the higher modes (LDLᵀ of K + σ K_σ): its inertia counts
|
||||
// the two load factors below the shift, and the modes above it come out.
|
||||
let mut s = column(L / 2.0, 10, Some(2.0 * got));
|
||||
s.fixed("base", |x| near(x[2], 0.0));
|
||||
let shifted = solve_buckle(&s.model, Some("Step"), &Limits::default()).unwrap();
|
||||
let info = shifted.buckling.as_ref().unwrap();
|
||||
assert_eq!(info.below_shift, Some(2));
|
||||
let third = r.modes[2].eigenvalue;
|
||||
assert!((shifted.modes[0].eigenvalue / third - 1.0).abs() < 1e-7, "{} vs {third}", shifted.modes[0].eigenvalue);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn buckling_steps_refuse_what_they_cannot_do() {
|
||||
// No load: nothing to buckle.
|
||||
let mut g = column(L, 4, None);
|
||||
g.model.set_load_active("Step", "press", false).unwrap();
|
||||
g.fixed("base", |x| near(x[2], 0.0));
|
||||
assert!(solve_buckle(&g.model, Some("Step"), &Limits::default()).is_err());
|
||||
// Unsupported: a located singular stiffness.
|
||||
let g = column(L, 4, None);
|
||||
let e = solve_buckle(&g.model, Some("Step"), &Limits::default()).unwrap_err();
|
||||
assert!(e.to_string().contains("singular"), "{e}");
|
||||
// A shift that is not finite, and a step of another kind.
|
||||
assert!(Procedure::Buckle { modes: 0, shift: None }.validate().is_err());
|
||||
assert!(Procedure::Buckle { modes: 1, shift: Some(f64::NAN) }.validate().is_err());
|
||||
}
|
||||
|
||||
/// A clamped–free column given its first buckling mode as an imperfection δ₀ at the top, under a
|
||||
/// dead end force of half its buckling load: the top's lateral deflection grows to
|
||||
/// δ₀ / (1 − P/P_cr) = 2 δ₀ (Timoshenko & Gere 1961, §1.12, for the mode-shaped imperfection).
|
||||
#[test]
|
||||
fn an_imperfection_from_the_buckling_mode() {
|
||||
let mut g = column(L / 2.0, 10, None);
|
||||
g.fixed("base", |x| near(x[2], 0.0));
|
||||
let critical = solve_buckle(&g.model, Some("Step"), &Limits::default()).unwrap().modes[0].eigenvalue * B * B;
|
||||
let delta0 = 0.01;
|
||||
g.node_set("tip", |x| near(x[2], 1.0));
|
||||
g.model
|
||||
.add_load("push", Load::Force { target: Target::Set("tip".into()), vector: [0.0, 0.0, -0.5 * critical], distribution: Distribution::Total })
|
||||
.unwrap();
|
||||
let settings = NonlinearStatic { imperfection: Some(Imperfection { step: "Step".into(), mode: 1, scale: delta0 }), ..NonlinearStatic::default() };
|
||||
let mut nl = Step::new("Push", Procedure::NonlinearStatic(settings));
|
||||
nl.boundary_conditions.insert("base".into());
|
||||
nl.loads.insert("push".into());
|
||||
g.model.add_step(nl, None).unwrap();
|
||||
let r = fieldcraft_solver::solve_nonlinear(&g.model, Some("Push"), &Limits::default()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("imperfect geometry")), "{:?}", r.warnings);
|
||||
let lateral = r.displacement.iter().map(|u| u[0].hypot(u[1])).fold(0.0, f64::max);
|
||||
// The deflection added to δ₀: δ₀ α/(1 − α) = δ₀ at α = ½.
|
||||
eprintln!("imperfection {delta0}: added top deflection {lateral:.6e}");
|
||||
assert!((lateral / delta0 - 1.0).abs() < 0.05, "{lateral}");
|
||||
// A mode the buckling step does not have, or a step that does not buckle.
|
||||
let mut bad = g.model.clone();
|
||||
let mut s = bad.step("Push").unwrap().clone();
|
||||
if let Procedure::NonlinearStatic(n) = &mut s.procedure {
|
||||
n.imperfection = Some(Imperfection { step: "Step".into(), mode: 9, scale: delta0 });
|
||||
}
|
||||
bad.replace_step(s).unwrap();
|
||||
assert!(fieldcraft_solver::solve_nonlinear(&bad, Some("Push"), &Limits::default()).is_err());
|
||||
}
|
||||
@@ -390,3 +390,14 @@ fn oversized_reductions_are_refused_before_allocating() {
|
||||
assert!(e.contains("reduced matrices need more than"), "{e}");
|
||||
assert!(solve_static(&g.model, Some("Step"), &Limits::default()).is_ok());
|
||||
}
|
||||
|
||||
/// Contact belongs to explicit dynamics so far: the implicit solves refuse it by name.
|
||||
#[test]
|
||||
fn implicit_solves_refuse_contact_by_name() {
|
||||
let mut g = grid([1, 1, 1], ElementKind::Hex8, |x| x);
|
||||
g.define(iso(1000.0, 0.3), Some(1.0), full(), Procedure::Static {});
|
||||
g.face_set("top", |x| near(x[2], 1.0));
|
||||
g.model.add_contact("touch", fieldcraft_model::Contact::new(fieldcraft_model::ContactSurfaces::General { surface: Some("top".into()) })).unwrap();
|
||||
let e = solve_static(&g.model, Some("Step"), &Limits::default()).unwrap_err().to_string();
|
||||
assert!(e.contains("contact (`touch`)") && e.contains("not supported"), "{e}");
|
||||
}
|
||||
@@ -514,3 +514,34 @@ fn mooney_rivlin_and_yeoh_in_the_homogeneous_modes() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Nearly incompressible hybrid blocks (ν = 0.4999) stretched to λ = 2 by a prescribed
|
||||
/// displacement: the first states of an increment strain the boundary elements alone, so their
|
||||
/// mixed tangents are indefinite; Newton goes on with the LDLᵀ factor and converges to the
|
||||
/// compressible neo-Hookean closed form.
|
||||
#[test]
|
||||
fn nearly_incompressible_hybrids_under_prescribed_displacement() {
|
||||
let (e, nu, lam) = (3.0, 0.4999, 2.0);
|
||||
let (mu, kappa) = (e / (2.0 * (1.0 + nu)), e / (3.0 * (1.0 - 2.0 * nu)));
|
||||
let (l, sigma) = neo_hookean_uniaxial(mu, kappa, lam);
|
||||
let mut indefinite = 0;
|
||||
for (kind, n) in [(ElementKind::Hex8, 3), (ElementKind::Hex20, 2), (ElementKind::Tet10, 2)] {
|
||||
let mut g = grid([n, n, n], kind, |x| x);
|
||||
g.define(iso(e, nu), None, Formulation { hybrid: true, ..Formulation::default() }, nonlinear());
|
||||
neo_hookean(&mut g, e, nu);
|
||||
g.symmetry("x0", Symmetry::X, |x| near(x[0], 0.0));
|
||||
g.symmetry("y0", Symmetry::Y, |x| near(x[1], 0.0));
|
||||
g.symmetry("z0", Symmetry::Z, |x| near(x[2], 0.0));
|
||||
g.node_set("x1", |x| near(x[0], 1.0));
|
||||
g.bc("pull", BoundaryCondition::Displacement { target: Target::Set("x1".into()), values: [Some(lam - 1.0), None, None, None, None, None] });
|
||||
let r = solve(&g);
|
||||
let corner = g.nodes_where(|x| near(x[0], 1.0) && near(x[1], 1.0) && near(x[2], 1.0))[0];
|
||||
assert!((r.displacement[at(&r, corner)][1] - (l - 1.0)).abs() < 1e-7, "{kind:?}: {:?}", r.displacement[at(&r, corner)]);
|
||||
for s in &r.stress {
|
||||
assert!((s[0] - sigma).abs() < 1e-5 * sigma, "{kind:?}: {s:?} vs {sigma}");
|
||||
}
|
||||
let h = r.nonlinear.as_ref().unwrap();
|
||||
indefinite += h.increments.iter().flat_map(|i| &i.iterations).filter(|i| i.negative_pivots > 0).count();
|
||||
}
|
||||
assert!(indefinite > 0, "the LDLᵀ path was exercised");
|
||||
}
|
||||
@@ -263,7 +263,8 @@ pub fn run_case(dir: &Path, expected: &Expected) -> Result<Vec<Result<f64, Strin
|
||||
}
|
||||
|
||||
/// Read one number: from a recipe step's output (`"from": id`) or a command run now
|
||||
/// (`"command"`, `"params"`), at a JSON pointer.
|
||||
/// (`"command"`, `"params"`), at a JSON pointer, times `scale`; with `"over"` (a measure of its
|
||||
/// own), divided by that measure's number.
|
||||
fn measure(session: &mut Session, outputs: &BTreeMap<String, Value>, m: &Value) -> Result<f64, String> {
|
||||
let pointer = m.get("pointer").and_then(Value::as_str).ok_or("no `pointer`")?;
|
||||
let fresh;
|
||||
@@ -278,7 +279,15 @@ fn measure(session: &mut Session, outputs: &BTreeMap<String, Value>, m: &Value)
|
||||
};
|
||||
let v = out.pointer(pointer).ok_or_else(|| format!("nothing at `{pointer}`"))?;
|
||||
let x = v.as_f64().ok_or_else(|| format!("`{pointer}` is {v}, not a number"))?;
|
||||
let x = x * m.get("scale").and_then(Value::as_f64).unwrap_or(1.0);
|
||||
let mut x = x * m.get("scale").and_then(Value::as_f64).unwrap_or(1.0);
|
||||
// A ratio: this value over another measure's (both from the same run).
|
||||
if let Some(over) = m.get("over") {
|
||||
let y = measure(session, outputs, over)?;
|
||||
if y == 0.0 {
|
||||
return Err(format!("`{pointer}` is measured over a zero"));
|
||||
}
|
||||
x /= y;
|
||||
}
|
||||
if x.is_finite() { Ok(x) } else { Err(format!("`{pointer}` is not finite")) }
|
||||
}
|
||||
|
||||
@@ -730,6 +739,18 @@ mod tests {
|
||||
assert_eq!(fixture_band(1e-16, 0.0, a, FIXTURE_RELATIVE), 1e-9, "a zero reference keeps its tolerance as the band");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn measures_read_pointers_scale_and_divide() {
|
||||
let mut session = Session::default();
|
||||
let outputs: BTreeMap<String, Value> = [("s".to_string(), json!({"a": 6.0, "b": -2.0, "z": 0.0}))].into_iter().collect();
|
||||
let m = |v: Value| measure(&mut Session::default(), &outputs, &v);
|
||||
assert_eq!(m(json!({"from": "s", "pointer": "/a", "scale": 0.5})), Ok(3.0));
|
||||
assert_eq!(m(json!({"from": "s", "pointer": "/a", "over": {"from": "s", "pointer": "/b", "scale": -1.0}})), Ok(3.0));
|
||||
assert!(m(json!({"from": "s", "pointer": "/a", "over": {"from": "s", "pointer": "/z"}})).is_err());
|
||||
assert!(m(json!({"from": "s", "pointer": "/a", "over": {"from": "s", "pointer": "/nope"}})).is_err());
|
||||
assert!(measure(&mut session, &outputs, &json!({"from": "t", "pointer": "/a"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expected_files_are_checked() {
|
||||
let good = json!({"title": "t", "kind": "theory", "source": "s", "quantities": [
|
||||
|
||||
@@ -33,6 +33,7 @@ pub enum Def {
|
||||
Load,
|
||||
ReferencePoint,
|
||||
Coupling,
|
||||
Contact,
|
||||
FluidDomain,
|
||||
}
|
||||
|
||||
@@ -48,6 +49,7 @@ impl Def {
|
||||
Def::Load => "load",
|
||||
Def::ReferencePoint => "reference_point",
|
||||
Def::Coupling => "coupling",
|
||||
Def::Contact => "contact",
|
||||
Def::FluidDomain => "fluid_domain",
|
||||
}
|
||||
}
|
||||
@@ -62,6 +64,7 @@ impl Def {
|
||||
Def::Load => "Load",
|
||||
Def::ReferencePoint => "Reference Point",
|
||||
Def::Coupling => "Coupling",
|
||||
Def::Contact => "Contact",
|
||||
Def::FluidDomain => "Fluid Domain",
|
||||
}
|
||||
}
|
||||
@@ -77,13 +80,19 @@ impl Def {
|
||||
Def::Load => "model.load.create",
|
||||
Def::ReferencePoint => "model.reference_point.create",
|
||||
Def::Coupling => "model.coupling.create",
|
||||
Def::Contact => "interaction.contact.pair",
|
||||
Def::FluidDomain => "model.fluid_domain.create",
|
||||
}
|
||||
}
|
||||
|
||||
/// The command of this kind with `verb` (`edit`, `delete`).
|
||||
/// The command of this kind with `verb` (`create`, `edit`, `delete`); contacts are
|
||||
/// interactions, created as pairs or general contact.
|
||||
pub fn command(self, verb: &str) -> String {
|
||||
format!("model.{}.{verb}", self.stem())
|
||||
match (self, verb) {
|
||||
(Def::Contact, "create") => "interaction.contact.pair".into(),
|
||||
(Def::Contact, _) => format!("interaction.contact.{verb}"),
|
||||
_ => format!("model.{}.{verb}", self.stem()),
|
||||
}
|
||||
}
|
||||
|
||||
/// How many definitions of this kind the model has.
|
||||
@@ -97,6 +106,7 @@ impl Def {
|
||||
Def::Load => m.loads().len(),
|
||||
Def::ReferencePoint => m.reference_points().len(),
|
||||
Def::Coupling => m.couplings().len(),
|
||||
Def::Contact => m.contacts().len(),
|
||||
Def::FluidDomain => m.fluid_domains().len(),
|
||||
}
|
||||
}
|
||||
@@ -112,6 +122,7 @@ impl Def {
|
||||
Def::Load => m.loads().contains_key(name),
|
||||
Def::ReferencePoint => m.reference_points().contains_key(name),
|
||||
Def::Coupling => m.couplings().contains_key(name),
|
||||
Def::Contact => m.contacts().contains_key(name),
|
||||
Def::FluidDomain => m.fluid_domain(name).is_some(),
|
||||
}
|
||||
}
|
||||
@@ -127,6 +138,7 @@ impl Def {
|
||||
Def::Load => m.loads().keys().cloned().collect(),
|
||||
Def::ReferencePoint => m.reference_points().keys().cloned().collect(),
|
||||
Def::Coupling => m.couplings().keys().cloned().collect(),
|
||||
Def::Contact => m.contacts().keys().cloned().collect(),
|
||||
Def::FluidDomain => m.fluid_domains().keys().cloned().collect(),
|
||||
}
|
||||
}
|
||||
@@ -143,6 +155,7 @@ pub fn definition(m: &Model, kind: Def, name: &str) -> Option<Value> {
|
||||
Def::Load => serde_json::to_value(m.loads().get(name)?),
|
||||
Def::ReferencePoint => serde_json::to_value(m.reference_points().get(name)?),
|
||||
Def::Coupling => serde_json::to_value(m.couplings().get(name)?),
|
||||
Def::Contact => serde_json::to_value(m.contacts().get(name)?),
|
||||
Def::FluidDomain => serde_json::to_value(m.fluid_domain(name)?),
|
||||
}
|
||||
.ok()?;
|
||||
@@ -442,7 +455,7 @@ fn rows(app: &mut ModelApp, ui: &mut egui::Ui, acts: &mut Vec<Act>) {
|
||||
("sections", "Sections", &[Def::Section]),
|
||||
("steps", "Steps", &[Def::Step]),
|
||||
("loads", "Loads & BCs", &[Def::BoundaryCondition, Def::Load]),
|
||||
("interactions", "Interactions", &[Def::ReferencePoint, Def::Coupling]),
|
||||
("interactions", "Interactions", &[Def::ReferencePoint, Def::Coupling, Def::Contact]),
|
||||
("fluids", "Fluid Domains", &[Def::FluidDomain]),
|
||||
];
|
||||
for (key, label, kinds) in groups {
|
||||
@@ -550,6 +563,7 @@ mod tests {
|
||||
Def::Load,
|
||||
Def::ReferencePoint,
|
||||
Def::Coupling,
|
||||
Def::Contact,
|
||||
Def::FluidDomain,
|
||||
] {
|
||||
for verb in ["create", "edit", "delete"] {
|
||||
|
||||
@@ -58,11 +58,17 @@ pub fn panel(app: &mut ModelApp, ui: &mut egui::Ui) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The open command's parameters as JSON, with the command's parameter documentation; OK runs it.
|
||||
/// JSON shorter than this is shown pretty-printed in the JSON view.
|
||||
const MAX_PRETTY: usize = 100_000;
|
||||
|
||||
/// The open command's form: typed fields drawn from its schema (or its JSON text, the Advanced
|
||||
/// view), with the command's parameter documentation; OK runs it.
|
||||
/// A command that applies to part of the model (a set, a boundary condition, a load, a section, a
|
||||
/// coupling) has a Target row that takes the viewport's selection.
|
||||
fn form(app: &mut ModelApp, ui: &mut egui::Ui, t: &Tokens) {
|
||||
let selected = (!app.pick.selection.is_empty()).then(|| app.pick.selection.summary());
|
||||
let units = app.session.model.units();
|
||||
let session = &app.session;
|
||||
let mut use_selection = false;
|
||||
let Some(d) = app.dialog.as_mut() else { return };
|
||||
let Some(spec) = fieldcraft_engine::find_command(d.command) else {
|
||||
@@ -90,15 +96,47 @@ fn form(app: &mut ModelApp, ui: &mut egui::Ui, t: &Tokens) {
|
||||
};
|
||||
use_selection = ui.add_enabled(selected.is_some(), egui::Button::new("Use selection")).on_hover_text(tip).clicked();
|
||||
match &selected {
|
||||
Some(text) => ui.label(RichText::new(text).color(t.pick_selected)),
|
||||
None => ui.label(RichText::new("Pick in the viewport, or type the names below").color(t.text_dim)),
|
||||
Some(text) => ui.add(egui::Label::new(RichText::new(text).color(t.pick_selected)).wrap()),
|
||||
None => ui.add(egui::Label::new(RichText::new("Pick in the viewport, or choose below").color(t.text_dim)).wrap()),
|
||||
};
|
||||
});
|
||||
}
|
||||
let mut advanced = d.advanced;
|
||||
heading(ui, t, Level::Section, |ui| {
|
||||
ui.label(RichText::new("Parameters").size(12.0));
|
||||
if spec.form.is_some() {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.toggle_value(&mut advanced, RichText::new("{ } JSON").small()).on_hover_text("Advanced: edit the parameters as JSON");
|
||||
});
|
||||
}
|
||||
});
|
||||
ui.add(egui::TextEdit::multiline(&mut d.text).code_editor().desired_rows(6).desired_width(f32::INFINITY));
|
||||
let mut invalid = 0;
|
||||
// The typed fields edit the JSON text's object; text that is not an object stays in the
|
||||
// JSON view until it is.
|
||||
let object = params.as_object().cloned();
|
||||
if advanced != d.advanced && !advanced && object.is_none() {
|
||||
d.error = Some("fix the JSON before going back to the fields".into());
|
||||
advanced = true;
|
||||
}
|
||||
// Pretty-printed once, when the JSON view opens.
|
||||
if advanced && !d.advanced && params.is_object() && d.text.len() < MAX_PRETTY {
|
||||
d.text = serde_json::to_string_pretty(¶ms).unwrap_or_else(|_| d.text.clone());
|
||||
}
|
||||
d.advanced = advanced;
|
||||
match (spec.form, object) {
|
||||
(Some(fields), Some(mut obj)) if !d.advanced => {
|
||||
let cx = crate::form::Context { units, names: &|c| session.names(c), salt: spec.id };
|
||||
let out = crate::form::show(ui, t, &cx, fields, &mut obj);
|
||||
invalid = out.invalid;
|
||||
if out.changed {
|
||||
d.text = Value::Object(obj).to_string();
|
||||
d.error = None;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
ui.add(egui::TextEdit::multiline(&mut d.text).code_editor().desired_rows(6).desired_width(f32::INFINITY));
|
||||
}
|
||||
}
|
||||
if let Some(e) = &d.error {
|
||||
ui.label(RichText::new(e).color(t.error));
|
||||
}
|
||||
@@ -109,7 +147,13 @@ fn form(app: &mut ModelApp, ui: &mut egui::Ui, t: &Tokens) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
cancel |= ui.button("Cancel").clicked();
|
||||
run = ui.add(egui::Button::new(RichText::new("OK").color(egui::Color32::WHITE)).fill(t.accent).min_size(vec2(64.0, 0.0))).clicked();
|
||||
run = ui
|
||||
.add_enabled(
|
||||
invalid == 0,
|
||||
egui::Button::new(RichText::new("OK").color(egui::Color32::WHITE)).fill(t.accent).min_size(vec2(64.0, 0.0)),
|
||||
)
|
||||
.on_disabled_hover_text("A field holds something that is not a value")
|
||||
.clicked();
|
||||
});
|
||||
});
|
||||
if ui.input(|i| i.key_pressed(egui::Key::Escape)) && app.ui.menu.is_none() && !app.ui.palette {
|
||||
|
||||
@@ -174,9 +174,7 @@ pub fn handle(app: &mut ModelApp, ctx: &egui::Context, req: &ControlRequest) ->
|
||||
let Some(steps) = p.get("commands") else { return err("missing `commands` (a list of {command, params})") };
|
||||
wrap(app.run_script(steps).map(|()| json!({"journal": app.session.journal.len()})))
|
||||
}
|
||||
"engine.commands" => {
|
||||
ok(Value::Array(fieldcraft_engine::commands().iter().map(|c| json!({"id": c.id, "label": c.label, "params": c.params})).collect()))
|
||||
}
|
||||
"engine.commands" => ok(Value::Array(fieldcraft_engine::commands().iter().map(fieldcraft_engine::CommandSpec::listing).collect())),
|
||||
"ui.inspect" => ok(json!({
|
||||
"ui": app.ui,
|
||||
"camera": app.cam,
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
//! Form field widgets: a labelled row, a number field that keeps what is being typed until it
|
||||
//! is a number, a drop-down, a text field. They know nothing of FieldCraft (colours and widths
|
||||
//! come in a [`Style`]), so they can move to the shared Craft UI crate.
|
||||
//!
|
||||
//! The row layout (a label column of fixed width, clamped for long labels, then the field) is
|
||||
//! adapted from SolidCraft's dialog rows (`crates/ui-egui/src/dialogs.rs`, MIT OR Apache-2.0).
|
||||
|
||||
use egui::{Color32, Id, RichText, Ui, vec2};
|
||||
|
||||
/// Widths and colours of a form.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Style {
|
||||
/// The label column.
|
||||
pub label_width: f32,
|
||||
/// A field (number, text, drop-down) without its unit.
|
||||
pub field_width: f32,
|
||||
pub dim: Color32,
|
||||
pub error: Color32,
|
||||
/// The mark of a required field.
|
||||
pub required: Color32,
|
||||
}
|
||||
|
||||
/// Row height.
|
||||
pub const ROW_H: f32 = 22.0;
|
||||
|
||||
/// A row: `label` (with a mark when `required`) in the label column, then `add`.
|
||||
pub fn row<R>(ui: &mut Ui, s: &Style, label: &str, required: bool, add: impl FnOnce(&mut Ui) -> R) -> R {
|
||||
ui.horizontal(|ui| {
|
||||
ui.allocate_ui_with_layout(vec2(s.label_width, ROW_H), egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
ui.set_width(s.label_width);
|
||||
ui.spacing_mut().item_spacing.x = 2.0;
|
||||
ui.add(egui::Label::new(RichText::new(label).color(s.dim)).truncate()).on_hover_text(label);
|
||||
if required {
|
||||
ui.label(RichText::new("*").color(s.required)).on_hover_text("Required");
|
||||
}
|
||||
});
|
||||
add(ui)
|
||||
})
|
||||
.inner
|
||||
}
|
||||
|
||||
/// A message under a field, aligned with the fields.
|
||||
pub fn note(ui: &mut Ui, s: &Style, text: &str, color: Color32) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(s.label_width + ui.spacing().item_spacing.x);
|
||||
ui.add(egui::Label::new(RichText::new(text).small().color(color)).wrap());
|
||||
});
|
||||
}
|
||||
|
||||
/// What a number field did this frame.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum NumberEdit {
|
||||
Unchanged,
|
||||
/// A new value; `None` when the field was emptied.
|
||||
Set(Option<f64>),
|
||||
/// What is typed is not a number (yet); the value is unchanged.
|
||||
Invalid,
|
||||
}
|
||||
|
||||
/// The typed text of a field and the value it was typed over: kept while the value stays the
|
||||
/// same, so a half-typed `1e-` survives frames and an outside change (undo, the JSON view)
|
||||
/// replaces it.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct Draft {
|
||||
text: String,
|
||||
over: Option<f64>,
|
||||
}
|
||||
|
||||
/// A number field: shows `value` (or the typed text), greys `hint` when empty, and reports a new
|
||||
/// value only when the text is a finite number (or empty). `integer` refuses fractions.
|
||||
pub fn number(ui: &mut Ui, s: &Style, id: Id, value: Option<f64>, hint: &str, integer: bool, width: f32) -> NumberEdit {
|
||||
let shown = |v: Option<f64>| v.map(format_number).unwrap_or_default();
|
||||
let mut draft = ui.data(|d| d.get_temp::<Draft>(id)).filter(|d| d.over == value).unwrap_or_else(|| Draft { text: shown(value), over: value });
|
||||
let parse = |t: &str| -> Option<Option<f64>> {
|
||||
let t = t.trim();
|
||||
if t.is_empty() {
|
||||
return Some(None);
|
||||
}
|
||||
let x = t.parse::<f64>().ok().filter(|x| x.is_finite())?;
|
||||
(!integer || x.fract() == 0.0).then_some(Some(x))
|
||||
};
|
||||
let bad = parse(&draft.text).is_none();
|
||||
let mut edit = egui::TextEdit::singleline(&mut draft.text).desired_width(width).hint_text(RichText::new(hint).italics().color(s.dim));
|
||||
if bad {
|
||||
edit = edit.text_color(s.error);
|
||||
}
|
||||
let r = ui.add(edit);
|
||||
let out = if r.changed() {
|
||||
match parse(&draft.text) {
|
||||
Some(v) => {
|
||||
draft.over = v;
|
||||
NumberEdit::Set(v)
|
||||
}
|
||||
None => NumberEdit::Invalid,
|
||||
}
|
||||
} else if bad {
|
||||
NumberEdit::Invalid
|
||||
} else {
|
||||
NumberEdit::Unchanged
|
||||
};
|
||||
ui.data_mut(|d| d.insert_temp(id, draft));
|
||||
out
|
||||
}
|
||||
|
||||
/// A number as typed: integers without a fraction, others in their shortest round-trip form.
|
||||
pub fn format_number(x: f64) -> String {
|
||||
if x.fract() == 0.0 && x.abs() < 1e15 {
|
||||
format!("{}", x as i64)
|
||||
} else {
|
||||
serde_json::Number::from_f64(x).map_or_else(|| x.to_string(), |n| n.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// A drop-down of `options` (labels); returns the index picked this frame.
|
||||
pub fn combo(ui: &mut Ui, id: Id, selected: &str, options: &[&str], width: f32) -> Option<usize> {
|
||||
let mut picked = None;
|
||||
egui::ComboBox::from_id_salt(id).selected_text(selected).width(width).truncate().show_ui(ui, |ui| {
|
||||
for (i, o) in options.iter().enumerate() {
|
||||
if ui.selectable_label(*o == selected, *o).clicked() {
|
||||
picked = Some(i);
|
||||
}
|
||||
}
|
||||
});
|
||||
picked
|
||||
}
|
||||
|
||||
/// A one-line text field with a greyed hint; true when it changed.
|
||||
pub fn text(ui: &mut Ui, s: &Style, value: &mut String, hint: &str, width: f32) -> bool {
|
||||
ui.add(egui::TextEdit::singleline(value).desired_width(width).hint_text(RichText::new(hint).italics().color(s.dim))).changed()
|
||||
}
|
||||
|
||||
/// A unit after a field.
|
||||
pub fn unit(ui: &mut Ui, s: &Style, unit: Option<&str>) {
|
||||
if let Some(u) = unit {
|
||||
ui.label(RichText::new(u).small().color(s.dim));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn numbers_print_as_typed() {
|
||||
assert_eq!(format_number(210000.0), "210000");
|
||||
assert_eq!(format_number(0.3), "0.3");
|
||||
assert_eq!(format_number(7.85e-9), "7.85e-9");
|
||||
assert_eq!(format_number(-2.0), "-2");
|
||||
}
|
||||
}
|
||||
@@ -1030,7 +1030,7 @@ mod tests {
|
||||
assert!(!app.display().bounds.is_empty());
|
||||
|
||||
app.start("mesh.tet.generate").unwrap();
|
||||
assert_eq!(app.dialog.as_ref().map(|d| (d.command, d.text.as_str())), Some(("mesh.tet.generate", "{}")));
|
||||
assert_eq!(app.dialog.as_ref().map(|d| (d.command, d.text.as_str())), Some(("mesh.tet.generate", r#"{"order":"linear","quality":true}"#)));
|
||||
app.submit_dialog();
|
||||
assert_eq!(app.busy(), Some("Generate Tet Mesh"), "meshing runs off the window thread");
|
||||
app.wait_loaded();
|
||||
|
||||
@@ -0,0 +1,454 @@
|
||||
//! A command's form drawn from its parameter schema ([`fieldcraft_engine::schema`]): typed fields
|
||||
//! with units, drop-downs of the model's items, groups and one-of variants. The form edits the
|
||||
//! command's JSON parameters in place; it never builds anything the command does not take.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use egui::{Id, RichText, Ui};
|
||||
use fieldcraft_engine::schema::{self, Collection, Field, Kind, MAX_DEPTH, MAX_ROWS, join};
|
||||
use fieldcraft_model::UnitSystem;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::fields::{self, NumberEdit, Style};
|
||||
use crate::theme::Tokens;
|
||||
|
||||
/// The label column.
|
||||
const LABEL_W: f32 = 112.0;
|
||||
/// A field without its unit.
|
||||
const FIELD_W: f32 = 120.0;
|
||||
/// Indentation of a group's fields.
|
||||
const INDENT: f32 = 10.0;
|
||||
|
||||
/// What the form reads beside the parameters.
|
||||
pub struct Context<'a> {
|
||||
pub units: UnitSystem,
|
||||
/// The names of a collection's items.
|
||||
pub names: &'a dyn Fn(Collection) -> Vec<String>,
|
||||
/// A salt for the widget ids (the command).
|
||||
pub salt: &'a str,
|
||||
}
|
||||
|
||||
/// What a frame of the form did.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Outcome {
|
||||
pub changed: bool,
|
||||
/// Fields whose typed text is not a value yet (OK waits for them).
|
||||
pub invalid: usize,
|
||||
}
|
||||
|
||||
struct Form<'a> {
|
||||
cx: &'a Context<'a>,
|
||||
style: Style,
|
||||
problems: BTreeMap<String, String>,
|
||||
names: BTreeMap<&'static str, Vec<String>>,
|
||||
out: Outcome,
|
||||
}
|
||||
|
||||
pub fn style(t: &Tokens) -> Style {
|
||||
Style { label_width: LABEL_W, field_width: FIELD_W, dim: t.text_dim, error: t.error, required: t.accent }
|
||||
}
|
||||
|
||||
/// Draw `fields` editing `params` (an object).
|
||||
pub fn show(ui: &mut Ui, t: &Tokens, cx: &Context, fields: &[Field], params: &mut Map<String, Value>) -> Outcome {
|
||||
let problems = schema::object_problems(fields, params).into_iter().filter(|p| p.message != "required").map(|p| (p.path, p.message)).collect();
|
||||
let mut f = Form { cx, style: style(t), problems, names: BTreeMap::new(), out: Outcome::default() };
|
||||
ui.spacing_mut().item_spacing.y = 3.0;
|
||||
f.fields(ui, fields, fields, params, "", 0);
|
||||
f.out
|
||||
}
|
||||
|
||||
impl Form<'_> {
|
||||
fn id(&self, path: &str) -> Id {
|
||||
Id::new(("fc_form", self.cx.salt, path))
|
||||
}
|
||||
|
||||
/// A value the fields cannot show: it stays as it is, editable in the JSON view.
|
||||
fn json_only(&self, ui: &mut Ui) {
|
||||
ui.label(RichText::new("set in JSON").small().color(self.style.dim)).on_hover_text("Edit it in the JSON view");
|
||||
}
|
||||
|
||||
fn names(&mut self, c: Collection) -> &[String] {
|
||||
self.names.entry(c.label()).or_insert_with(|| (self.cx.names)(c))
|
||||
}
|
||||
|
||||
fn unit(&self, dim: schema::Dim) -> Option<String> {
|
||||
dim.unit(self.cx.units)
|
||||
}
|
||||
|
||||
/// The fields of one object. `common` are the fields beside a flattened variant (kept when it
|
||||
/// switches).
|
||||
fn fields(&mut self, ui: &mut Ui, fields: &[Field], common: &[Field], obj: &mut Map<String, Value>, prefix: &str, depth: usize) {
|
||||
if depth > MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
for f in fields {
|
||||
if let Kind::Variants { tag, variants } = f.kind
|
||||
&& f.key.is_empty()
|
||||
{
|
||||
let current = obj.get(tag).and_then(Value::as_str).map(str::to_string);
|
||||
if let Some(t) = self.variant_choice(ui, f, variants, current.as_deref(), &join(prefix, tag)) {
|
||||
*obj = schema::switch_variant(f, common, obj, &t);
|
||||
self.out.changed = true;
|
||||
}
|
||||
if let Some(v) = obj.get(tag).and_then(Value::as_str).and_then(|t| f.kind.variant(t)) {
|
||||
self.fields(ui, v.fields, common, obj, prefix, depth + 1);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
self.field(ui, f, obj, prefix, depth);
|
||||
}
|
||||
}
|
||||
|
||||
/// A Type row: the variant's drop-down. Returns the tag picked.
|
||||
fn variant_choice(&mut self, ui: &mut Ui, f: &Field, variants: &[schema::Variant], current: Option<&str>, path: &str) -> Option<String> {
|
||||
let selected = variants.iter().find(|v| Some(v.tag) == current).map_or(current.unwrap_or("—"), |v| v.label);
|
||||
let labels: Vec<&str> = variants.iter().map(|v| v.label).collect();
|
||||
let id = self.id(path);
|
||||
let picked = fields::row(ui, &self.style, f.label, f.required, |ui| fields::combo(ui, id, selected, &labels, FIELD_W + 40.0));
|
||||
picked.and_then(|i| variants.get(i)).map(|v| v.tag.to_string()).filter(|t| Some(t.as_str()) != current)
|
||||
}
|
||||
|
||||
fn field(&mut self, ui: &mut Ui, f: &Field, obj: &mut Map<String, Value>, prefix: &str, depth: usize) {
|
||||
let path = join(prefix, f.key);
|
||||
match f.kind {
|
||||
Kind::Group(_) | Kind::Variants { .. } | Kind::Rows { .. } => self.section(ui, f, obj, &path, depth),
|
||||
_ => {
|
||||
let value = obj.get(f.key).cloned();
|
||||
let style = self.style;
|
||||
let new = fields::row(ui, &style, f.label, f.required, |ui| self.scalar(ui, f, value.as_ref(), &path));
|
||||
if let Some(new) = new {
|
||||
match new {
|
||||
Value::Null => obj.remove(f.key),
|
||||
v => obj.insert(f.key.into(), v),
|
||||
};
|
||||
self.out.changed = true;
|
||||
}
|
||||
if let Kind::Either(options) = f.kind {
|
||||
self.either_value(ui, f, options, obj, &path);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(message) = self.problems.get(&path).cloned() {
|
||||
fields::note(ui, &self.style, &message, self.style.error);
|
||||
}
|
||||
}
|
||||
|
||||
/// A one-row field; returns its new value (`Null` removes it).
|
||||
fn scalar(&mut self, ui: &mut Ui, f: &Field, value: Option<&Value>, path: &str) -> Option<Value> {
|
||||
let id = self.id(path);
|
||||
let s = self.style;
|
||||
match f.kind {
|
||||
Kind::Number { dim, .. } => {
|
||||
let unit = self.unit(dim);
|
||||
let out = self.number(ui, id, value, f.hint, false, FIELD_W);
|
||||
fields::unit(ui, &s, unit.as_deref());
|
||||
out
|
||||
}
|
||||
Kind::Integer { .. } => self.number(ui, id, value, f.hint, true, FIELD_W),
|
||||
Kind::Text | Kind::Path { .. } => {
|
||||
let mut text = value.and_then(Value::as_str).unwrap_or_default().to_string();
|
||||
fields::text(ui, &s, &mut text, f.hint, FIELD_W + 40.0)
|
||||
.then(|| if text.is_empty() && !f.required { Value::Null } else { json!(text) })
|
||||
}
|
||||
Kind::Bool => {
|
||||
let mut on = value.and_then(Value::as_bool).unwrap_or(false);
|
||||
let r = ui.checkbox(&mut on, "");
|
||||
if !f.hint.is_empty() {
|
||||
r.clone().on_hover_text(f.hint);
|
||||
}
|
||||
r.changed().then(|| json!(on))
|
||||
}
|
||||
Kind::Choice(options) => {
|
||||
let current = value.and_then(Value::as_str);
|
||||
let selected = options
|
||||
.iter()
|
||||
.find(|(v, _)| Some(*v) == current)
|
||||
.map_or(current.unwrap_or(if f.hint.is_empty() { "—" } else { f.hint }), |(_, l)| *l);
|
||||
let mut labels: Vec<&str> = options.iter().map(|(_, l)| *l).collect();
|
||||
let optional = !f.required;
|
||||
if optional {
|
||||
labels.push("(default)");
|
||||
}
|
||||
fields::combo(ui, id, selected, &labels, FIELD_W + 40.0).map(|i| options.get(i).map_or(Value::Null, |(v, _)| json!(v)))
|
||||
}
|
||||
Kind::Vector { dim, labels, nullable } => self.vector(ui, id, value, dim, labels, nullable),
|
||||
Kind::Ref(c) => self.reference(ui, id, value, c, f.hint, f.required),
|
||||
Kind::RefList(c) => self.reference_list(ui, value, c, f.hint),
|
||||
Kind::Either(options) => {
|
||||
let key = match value {
|
||||
Some(Value::String(s)) => Some(s.as_str()),
|
||||
Some(Value::Object(o)) => o.keys().next().map(String::as_str),
|
||||
_ => None,
|
||||
};
|
||||
let selected = options.iter().find(|o| Some(o.key) == key).map_or(if f.hint.is_empty() { "—" } else { f.hint }, |o| o.label);
|
||||
let mut labels: Vec<&str> = options.iter().map(|o| o.label).collect();
|
||||
if !f.required {
|
||||
labels.push("(none)");
|
||||
}
|
||||
fields::combo(ui, id, selected, &labels, FIELD_W + 40.0).and_then(|i| match options.get(i) {
|
||||
Some(o) if Some(o.key) == key => None,
|
||||
Some(o) if matches!(o.kind, Kind::Unit) => Some(json!(o.key)),
|
||||
Some(o) => Some(json!({o.key: schema::prefill(&[*o], &json!({})).get(o.key).cloned().unwrap_or(Value::Null)})),
|
||||
None => Some(Value::Null),
|
||||
})
|
||||
}
|
||||
Kind::Json => self.json(ui, id, value),
|
||||
Kind::Unit | Kind::Group(_) | Kind::Variants { .. } | Kind::Rows { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The chosen option's value of an [`Kind::Either`] field, on its own row.
|
||||
fn either_value(&mut self, ui: &mut Ui, f: &Field, options: &[Field], obj: &mut Map<String, Value>, path: &str) {
|
||||
let Some(Value::Object(inner)) = obj.get(f.key).cloned() else { return };
|
||||
let Some((key, value)) = inner.into_iter().next() else { return };
|
||||
let Some(option) = options.iter().find(|o| o.key == key) else { return };
|
||||
let sub = join(path, &key);
|
||||
let style = self.style;
|
||||
let new = fields::row(ui, &style, "", false, |ui| self.scalar(ui, option, Some(&value), &sub));
|
||||
if let Some(new) = new {
|
||||
obj.insert(f.key.into(), json!({key: new}));
|
||||
self.out.changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn number(&mut self, ui: &mut Ui, id: Id, value: Option<&Value>, hint: &str, integer: bool, width: f32) -> Option<Value> {
|
||||
let current = value.and_then(Value::as_f64);
|
||||
if value.is_some_and(|v| !v.is_null() && current.is_none()) {
|
||||
self.json_only(ui);
|
||||
return None;
|
||||
}
|
||||
match fields::number(ui, &self.style, id, current, hint, integer, width) {
|
||||
NumberEdit::Set(Some(x)) if integer => Some(json!(x as i64)),
|
||||
NumberEdit::Set(Some(x)) => Some(json!(x)),
|
||||
NumberEdit::Set(None) => Some(Value::Null),
|
||||
NumberEdit::Invalid => {
|
||||
self.out.invalid += 1;
|
||||
None
|
||||
}
|
||||
NumberEdit::Unchanged => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn vector(&mut self, ui: &mut Ui, id: Id, value: Option<&Value>, dim: schema::Dim, labels: &[&str], nullable: bool) -> Option<Value> {
|
||||
let current: Vec<Value> = match value {
|
||||
Some(Value::Array(a)) if a.len() == labels.len() => a.clone(),
|
||||
Some(v) if !v.is_null() => {
|
||||
self.json_only(ui);
|
||||
return None;
|
||||
}
|
||||
_ => vec![if nullable { Value::Null } else { json!(0.0) }; labels.len()],
|
||||
};
|
||||
let mut next = current.clone();
|
||||
let mut changed = false;
|
||||
let width = if labels.len() > 3 { 34.0 } else { 44.0 };
|
||||
let unit = self.unit(dim);
|
||||
ui.vertical(|ui| {
|
||||
for chunk in (0..labels.len()).collect::<Vec<_>>().chunks(3) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 3.0;
|
||||
for &i in chunk {
|
||||
let hint = labels.get(i).copied().unwrap_or("");
|
||||
let slot = current.get(i).cloned().unwrap_or(Value::Null);
|
||||
let shown = if nullable && slot.is_null() { None } else { Some(&slot) };
|
||||
if let Some(v) = self.number(ui, id.with(i), shown, hint, false, width) {
|
||||
if let Some(n) = next.get_mut(i) {
|
||||
*n = if v.is_null() && !nullable { json!(0.0) } else { v };
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if chunk.first() == Some(&0) {
|
||||
fields::unit(ui, &self.style, unit.as_deref());
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
// A vector left empty is not written until edited (a required one shows as missing).
|
||||
changed.then_some(Value::Array(next))
|
||||
}
|
||||
|
||||
fn reference(&mut self, ui: &mut Ui, id: Id, value: Option<&Value>, c: Collection, hint: &str, required: bool) -> Option<Value> {
|
||||
let current = value.and_then(Value::as_str).map(str::to_string);
|
||||
let names = self.names(c).to_vec();
|
||||
if names.is_empty() {
|
||||
let mut text = current.unwrap_or_default();
|
||||
let hint = format!("no {} yet", c.label());
|
||||
return fields::text(ui, &self.style, &mut text, &hint, FIELD_W + 40.0).then(|| if text.is_empty() { Value::Null } else { json!(text) });
|
||||
}
|
||||
let empty = if hint.is_empty() { "—" } else { hint };
|
||||
let selected = current.clone().unwrap_or_else(|| empty.to_string());
|
||||
let mut labels: Vec<&str> = names.iter().map(String::as_str).collect();
|
||||
if !required {
|
||||
labels.push("(default)");
|
||||
}
|
||||
fields::combo(ui, id, &selected, &labels, FIELD_W + 40.0).map(|i| names.get(i).map_or(Value::Null, |n| json!(n)))
|
||||
}
|
||||
|
||||
fn reference_list(&mut self, ui: &mut Ui, value: Option<&Value>, c: Collection, hint: &str) -> Option<Value> {
|
||||
let chosen: Vec<String> =
|
||||
value.and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default();
|
||||
let names = self.names(c).to_vec();
|
||||
let mut changed = None;
|
||||
ui.vertical(|ui| {
|
||||
if names.is_empty() {
|
||||
let text = if hint.is_empty() { format!("no {} yet", c.label()) } else { hint.to_string() };
|
||||
ui.label(RichText::new(text).color(self.style.dim));
|
||||
}
|
||||
for n in names.iter().take(MAX_ROWS) {
|
||||
let mut on = chosen.contains(n);
|
||||
if ui.checkbox(&mut on, n).changed() {
|
||||
let mut next: Vec<String> = names.iter().filter(|m| if *m == n { on } else { chosen.contains(m) }).cloned().collect();
|
||||
next.dedup();
|
||||
changed = Some(if next.is_empty() { Value::Null } else { json!(next) });
|
||||
}
|
||||
}
|
||||
});
|
||||
changed
|
||||
}
|
||||
|
||||
/// A JSON value typed as text: kept while it does not parse.
|
||||
fn json(&mut self, ui: &mut Ui, id: Id, value: Option<&Value>) -> Option<Value> {
|
||||
let shown = value.map(Value::to_string).unwrap_or_default();
|
||||
let mut text = ui.data(|d| d.get_temp::<(String, String)>(id)).filter(|(_, over)| *over == shown).map_or_else(|| shown.clone(), |(t, _)| t);
|
||||
let bad = !text.trim().is_empty() && serde_json::from_str::<Value>(&text).is_err();
|
||||
let mut edit = egui::TextEdit::singleline(&mut text).code_editor().desired_width(FIELD_W + 40.0);
|
||||
if bad {
|
||||
edit = edit.text_color(self.style.error);
|
||||
self.out.invalid += 1;
|
||||
}
|
||||
let r = ui.add(edit);
|
||||
let mut out = None;
|
||||
if r.changed() {
|
||||
if text.trim().is_empty() {
|
||||
out = Some(Value::Null);
|
||||
} else if let Ok(v) = serde_json::from_str::<Value>(&text) {
|
||||
out = Some(v);
|
||||
}
|
||||
}
|
||||
let over = out.as_ref().map_or(shown, |v| if v.is_null() { String::new() } else { v.to_string() });
|
||||
ui.data_mut(|d| d.insert_temp(id, (text, over)));
|
||||
out
|
||||
}
|
||||
|
||||
/// A group, a keyed variant or a list of rows: a sub-heading (with a checkbox when optional),
|
||||
/// then its fields, indented.
|
||||
fn section(&mut self, ui: &mut Ui, f: &Field, obj: &mut Map<String, Value>, path: &str, depth: usize) {
|
||||
let present = obj.get(f.key).is_some_and(|v| !v.is_null());
|
||||
let mut on = present;
|
||||
ui.add_space(2.0);
|
||||
if f.required {
|
||||
ui.label(RichText::new(f.label).strong());
|
||||
} else {
|
||||
ui.checkbox(&mut on, RichText::new(f.label).strong());
|
||||
}
|
||||
if !f.hint.is_empty() && !present {
|
||||
fields::note(ui, &Style { label_width: INDENT, ..self.style }, f.hint, self.style.dim);
|
||||
}
|
||||
if on != present {
|
||||
if on {
|
||||
let filled = schema::prefill(&[Field { required: true, ..*f }], &json!({}));
|
||||
let start = filled.get(f.key).cloned().unwrap_or_else(|| if matches!(f.kind, Kind::Rows { .. }) { json!([]) } else { json!({}) });
|
||||
obj.insert(f.key.into(), start);
|
||||
} else {
|
||||
obj.remove(f.key);
|
||||
}
|
||||
self.out.changed = true;
|
||||
}
|
||||
if !on {
|
||||
return;
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(INDENT);
|
||||
ui.vertical(|ui| match f.kind {
|
||||
Kind::Group(fields) => {
|
||||
if let Some(Value::Object(child)) = obj.get_mut(f.key) {
|
||||
self.fields(ui, fields, fields, child, path, depth + 1);
|
||||
}
|
||||
}
|
||||
Kind::Variants { tag, variants } => {
|
||||
let Some(Value::Object(child)) = obj.get_mut(f.key) else {
|
||||
self.json_only(ui);
|
||||
return;
|
||||
};
|
||||
let current = child.get(tag).and_then(Value::as_str).map(str::to_string);
|
||||
let row = Field { label: "Type", required: true, ..*f };
|
||||
if let Some(t) = self.variant_choice(ui, &row, variants, current.as_deref(), &join(path, tag)) {
|
||||
*child = schema::switch_variant(f, &[], child, &t);
|
||||
self.out.changed = true;
|
||||
}
|
||||
if let Some(v) = child.get(tag).and_then(Value::as_str).and_then(|t| f.kind.variant(t)) {
|
||||
self.fields(ui, v.fields, v.fields, child, path, depth + 1);
|
||||
}
|
||||
}
|
||||
Kind::Rows { fields, max } => self.rows(ui, fields, max, obj, f.key, path, depth),
|
||||
_ => {}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn rows(&mut self, ui: &mut Ui, fields: &[Field], max: usize, obj: &mut Map<String, Value>, key: &str, path: &str, depth: usize) {
|
||||
let Some(Value::Array(list)) = obj.get_mut(key) else {
|
||||
self.json_only(ui);
|
||||
return;
|
||||
};
|
||||
let mut remove = None;
|
||||
for (i, row) in list.iter_mut().enumerate().take(max) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(format!("{}", i + 1)).small().color(self.style.dim));
|
||||
if ui.small_button("×").on_hover_text("Remove").clicked() {
|
||||
remove = Some(i);
|
||||
}
|
||||
});
|
||||
if let Value::Object(child) = row {
|
||||
self.fields(ui, fields, fields, child, &format!("{path}/{i}"), depth + 1);
|
||||
}
|
||||
}
|
||||
if let Some(i) = remove {
|
||||
list.remove(i);
|
||||
self.out.changed = true;
|
||||
}
|
||||
if list.len() < max && ui.small_button("+ Add").clicked() {
|
||||
list.push(schema::prefill(fields, &json!({})));
|
||||
self.out.changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Every command's form draws, with its defaults and with hostile parameters, without
|
||||
/// panicking, and drawing alone changes nothing.
|
||||
#[test]
|
||||
fn every_form_draws() {
|
||||
let ctx = egui::Context::default();
|
||||
let names = |c: Collection| vec![format!("{}1", c.label())];
|
||||
let hostile =
|
||||
[json!({}), json!({"type": 7, "name": [], "elastic": "x", "target": {"set": 1, "reference_point": 2}, "values": [1], "geometry": {}})];
|
||||
for c in fieldcraft_engine::commands() {
|
||||
let Some(form) = c.form else { continue };
|
||||
for start in hostile.iter().chain([&schema::prefill(form, &json!({}))]) {
|
||||
let mut params = start.as_object().cloned().unwrap_or_default();
|
||||
let before = params.clone();
|
||||
let mut outcome = Outcome::default();
|
||||
let width = crate::context::WIDTH - 16.0;
|
||||
let mut used = 0.0;
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
|
||||
let cx = Context { units: UnitSystem::MmTonneS, names: &names, salt: c.id };
|
||||
ui.vertical(|ui| {
|
||||
ui.set_max_width(width);
|
||||
outcome = show(ui, &Tokens::get(false), &cx, form, &mut params);
|
||||
used = ui.min_rect().width();
|
||||
});
|
||||
});
|
||||
// Wider would push the context panel over the viewport.
|
||||
assert!(used <= width + 0.5, "{}: {used}", c.id);
|
||||
out.textures_delta.clear();
|
||||
assert!(!outcome.changed, "{}", c.id);
|
||||
assert_eq!(params, before, "{}", c.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,9 @@ pub mod browser;
|
||||
pub mod capture;
|
||||
pub mod context;
|
||||
pub mod control;
|
||||
pub mod fields;
|
||||
pub mod files;
|
||||
pub mod form;
|
||||
pub mod frame;
|
||||
pub mod gpu;
|
||||
pub mod icons;
|
||||
@@ -155,6 +157,8 @@ pub struct ParamsDialog {
|
||||
/// The parameters as JSON text.
|
||||
pub text: String,
|
||||
pub error: Option<String>,
|
||||
/// The JSON text is shown instead of the typed fields.
|
||||
pub advanced: bool,
|
||||
}
|
||||
|
||||
/// A status bar message.
|
||||
@@ -519,7 +523,9 @@ impl ModelApp {
|
||||
/// Open a command's parameter form with `params` filled in.
|
||||
pub fn open_form(&mut self, command: &str, params: Value) {
|
||||
if let Some(spec) = fieldcraft_engine::find_command(command) {
|
||||
self.dialog = Some(ParamsDialog { command: spec.id, text: params.to_string(), error: None });
|
||||
// The schema's defaults are filled in, so the form starts as the command would run.
|
||||
let params = spec.form.map_or(params.clone(), |form| fieldcraft_engine::schema::prefill(form, ¶ms));
|
||||
self.dialog = Some(ParamsDialog { command: spec.id, text: params.to_string(), error: None, advanced: spec.form.is_none() });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -64,11 +64,18 @@ pub struct Prepared {
|
||||
pub contour: Option<Arc<Contour>>,
|
||||
}
|
||||
|
||||
/// A mode's value as the results show it: its frequency, or a buckling mode's load factor.
|
||||
pub fn mode_value(buckling: bool, eigenvalue: f64, frequency: f64) -> String {
|
||||
if buckling { format!("λ = {}", number(eigenvalue)) } else { format!("{} Hz", number(frequency)) }
|
||||
}
|
||||
|
||||
impl Plot {
|
||||
/// A frequency step's mode shown, and its frequency.
|
||||
pub fn mode(&self) -> Option<(usize, f64)> {
|
||||
/// A frequency or buckling step's mode shown, and its frequency (Hz) or load factor.
|
||||
pub fn mode(&self) -> Option<(usize, String)> {
|
||||
match self.result.kind() {
|
||||
Kind::Frequency(f) => f.modes.get(self.pick.mode.checked_sub(1)?).map(|m| (self.pick.mode, m.frequency)),
|
||||
Kind::Frequency(f) => {
|
||||
f.modes.get(self.pick.mode.checked_sub(1)?).map(|m| (self.pick.mode, mode_value(f.buckling.is_some(), m.eigenvalue, m.frequency)))
|
||||
}
|
||||
Kind::Static(_) | Kind::Explicit(_) | Kind::Fluid(_) | Kind::Heat(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,8 +35,8 @@ fn legend(plot: &Plot, painter: &egui::Painter, rect: Rect, t: &Tokens) {
|
||||
(None, None) => "Deformed shape".into(),
|
||||
};
|
||||
let mut step = format!("Step {}", plot.view.step);
|
||||
if let Some((mode, hz)) = plot.mode() {
|
||||
step.push_str(&format!(", mode {mode}: {} Hz", number(hz)));
|
||||
if let Some((mode, value)) = plot.mode() {
|
||||
step.push_str(&format!(", mode {mode}: {value}"));
|
||||
}
|
||||
if let Some((k, time, n)) = plot.frame() {
|
||||
step.push_str(&format!(", frame {k} of {}: t = {}", n.saturating_sub(1), number(time)));
|
||||
@@ -179,7 +179,13 @@ pub fn controls(app: &mut ModelApp, plot: &Plot, ui: &mut egui::Ui, t: &Tokens)
|
||||
egui::ScrollArea::vertical().id_salt("fc_results_modes").max_height(150.0).show(ui, |ui| {
|
||||
for (i, m) in f.modes.iter().enumerate() {
|
||||
let mode = i + 1;
|
||||
if ui.selectable_label(plot.view.mode == mode, format!("{mode} {} Hz", number(m.frequency))).clicked() {
|
||||
if ui
|
||||
.selectable_label(
|
||||
plot.view.mode == mode,
|
||||
format!("{mode} {}", crate::results::mode_value(f.buckling.is_some(), m.eigenvalue, m.frequency)),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
run.push(("results.modes", json!({"mode": mode})));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -255,7 +255,7 @@ number their degrees of freedom with `fieldcraft_fem::DofLayout` (docs/fem.md).
|
||||
increment. Other element kinds and formulations, couplings, reference points, rotary inertia,
|
||||
rotational springs and moments return "not supported yet". Masses are row-sum lumped. A zero-valued boundary condition holds a degree of freedom; a
|
||||
displacement value is reached at constant velocity over the step. Loads act in full from the
|
||||
start. The step lists initial velocities and fixed frictionless rigid planes by set.
|
||||
start. The step lists initial velocities and fixed rigid planes (with friction) by set.
|
||||
2. **Time step.** Each element's highest frequency is bounded in closed form (exact for a cube);
|
||||
the increment is the step's scale (0.9 by default) times the smallest element increment with
|
||||
Wilkins' bulk-viscosity correction, recomputed every increment. The ten controlling elements
|
||||
@@ -280,6 +280,15 @@ number their degrees of freedom with `fieldcraft_fem::DofLayout` (docs/fem.md).
|
||||
`fem::plasticity`. Elements whose damage reaches 1 or whose plastic strain reaches the
|
||||
material's erosion strain are eroded (reported with their energy; their nodes keep mass and
|
||||
momentum). The energy account adds the plastic work and the eroded energy.
|
||||
7. **Contact (X3).** The model's contacts (`interaction.contact.*`) become interfaces before the
|
||||
elements are built (nodes that start inside a surface are moved onto it or refused):
|
||||
segment-to-segment penalty contact both ways (projection, polygon clipping and quadrature over
|
||||
each pair of facing faces), a bucket-grid search every increment in parallel by faces, a
|
||||
penalty per area from the masses and the stable increment that never shortens it, and Coulomb
|
||||
friction by a return map at the secondary nodes; rigid walls take Coulomb impulses. The contact
|
||||
forces join the equations of motion beside the external ones, their work and the friction
|
||||
dissipation join the energy account, and each contact's peak force, first and last contact,
|
||||
deepest penetration and friction are reported (docs/fem.md).
|
||||
|
||||
Verification (`crates/explicit/tests/verification.rs` and `large_deformation.rs`, analytic
|
||||
only): stress waves in hex8 and tet4 bars (front at c·t, σ = ρ c v, work input), a bar striking a
|
||||
@@ -288,7 +297,10 @@ bit-for-bit repeatability; Dienes' simple shear for both rates, a stressed eleme
|
||||
by 90°, the J2 uniaxial curve and unloading at large strain, damage failure at the fracture
|
||||
strain, and the Taylor bar against Taylor's 1948 estimate; `crates/explicit/tests/one_d.rs`:
|
||||
spring–mass period, damped decay rate and period, a dashpot alone, two masses on a line spring,
|
||||
waves in rod2 and rod3 bars; in the engine (`solve.rs`), a
|
||||
waves in rod2 and rod3 bars; `crates/explicit/tests/contact.rs`: colliding bars, sliding
|
||||
blocks under constant and decaying friction on a rigid wall and on a plate, the contact patch
|
||||
test, Hertz's sphere impact, a free body untouched by general contact, initial penetrations and
|
||||
thread-count independence; in the engine (`solve.rs`), a
|
||||
cantilever's free-vibration period against `solve.frequency`.
|
||||
|
||||
## Lattice Boltzmann solver
|
||||
|
||||
@@ -26,7 +26,7 @@ checked and clamped (drag steps, wheel lines, window size); `ui.render` refuses
|
||||
|---|---|---|
|
||||
| `engine.execute` | `command`: command id, `params`: JSON object | the command's result |
|
||||
| `engine.script` | `commands`: `[{command, params}, …]` | stops at the first error; `journal`: commands that changed the model so far |
|
||||
| `engine.commands` | — | every command: `id`, `label`, `params` (the parameter documentation) |
|
||||
| `engine.commands` | — | every command: `id`, `label`, `params` (the parameter documentation) and `schema` (its parameters as JSON Schema) |
|
||||
|
||||
Commands never open forms or file pickers when run this way. `fieldcraft-cli commands` prints the
|
||||
same registry. `file.sample {name}` opens a sample (`parts`, `cantilever`, `impact`) and
|
||||
|
||||
@@ -6,7 +6,7 @@ Every entry is a toolbar button. **Ready** entries run their command; **coming s
|
||||
shown greyed with the roadmap milestone that brings them (ROADMAP.md). Scripts, the command line,
|
||||
the control channel and AI agents over MCP (docs/mcp.md) run the same commands.
|
||||
|
||||
56 ready, 48 coming soon.
|
||||
59 ready, 45 coming soon.
|
||||
|
||||
## Geometry
|
||||
|
||||
@@ -103,9 +103,9 @@ the control channel and AI agents over MCP (docs/mcp.md) run the same commands.
|
||||
| Constraints | Reference Point — A reference point for couplings, loads and boundary conditions | ready | `model.reference_point.create`, `model.reference_point.edit`, `model.reference_point.delete` |
|
||||
| Constraints | Coupling — Kinematic or distributing coupling of a set to a reference point | ready | `model.coupling.create`, `model.coupling.edit`, `model.coupling.delete` |
|
||||
| Constraints | Tie — Tie non-matching meshes together | coming soon (M7) | |
|
||||
| Contact | General Contact — Contact between everything that touches, with friction | coming soon (M7) | |
|
||||
| Contact | Contact Pair — Contact between two surfaces | coming soon (M7) | |
|
||||
| Contact | Find Contacts — Detect contact pairs automatically | coming soon (M7) | |
|
||||
| Contact | General Contact — Contact between everything that may touch, or self contact of a surface, with friction (explicit dynamics) | ready | `interaction.contact.general`, `interaction.contact.edit`, `interaction.contact.delete` |
|
||||
| Contact | Contact Pair — Contact between two surfaces, with friction (explicit dynamics) | ready | `interaction.contact.pair`, `interaction.contact.edit`, `interaction.contact.delete` |
|
||||
| Contact | Find Contacts — Find the parts of the mesh that touch, and make contact pairs of them | ready | `interaction.contact.find` |
|
||||
| Contact | Rigid Wall — Rigid walls for explicit dynamics | coming soon (M10) | |
|
||||
| Connectors | Bolt Load — Bolt pretension | coming soon (M7) | |
|
||||
| Connectors | Spring — Spring or dashpot to the ground or between two points, along a direction or their line | ready | `model.spring.create`, `model.spring.edit`, `model.spring.delete` |
|
||||
@@ -123,7 +123,7 @@ the control channel and AI agents over MCP (docs/mcp.md) run the same commands.
|
||||
| Decks | Nastran Deck — Write Nastran bulk data (SOL 101, 103) | ready | `deck.write {"format":"nastran"}` |
|
||||
| Decks | LS-DYNA Deck — Write an LS-DYNA keyword file | ready | `deck.write {"format":"lsdyna"}` |
|
||||
| Decks | Read Deck — Read a deck, keeping keywords FieldCraft does not know | coming soon (M9) | |
|
||||
| Implicit | Static — Linear static (or coupled temperature–displacement) solve of a step with FieldCraft's own solver; nonlinear static and heat transfer in the drop-down | ready | `solve.static`, `solve.nonlinear`, `solve.heat` |
|
||||
| Implicit | Static — Linear static (or coupled temperature–displacement) solve of a step with FieldCraft's own solver; nonlinear static, buckling and heat transfer in the drop-down | ready | `solve.static`, `solve.nonlinear`, `solve.buckle`, `solve.heat` |
|
||||
| Implicit | Frequency — Natural frequencies and mode shapes of a frequency step | ready | `solve.frequency` |
|
||||
| Explicit | Explicit — Transient dynamics of an explicit step by central differences (contact and erosion coming in M10) | ready | `solve.explicit` |
|
||||
| Explicit | Blast & Impact — EOS-driven fluids with fluid–structure contact (ALE or SPH) | coming soon (M14) | |
|
||||
|
||||
@@ -150,6 +150,56 @@ when confined. A continuous
|
||||
nodal pressure (`DofKind::P`, Taylor–Hood) needs a symmetric indefinite factorization and is
|
||||
planned.
|
||||
|
||||
## Symmetric indefinite factorization (LDLᵀ)
|
||||
|
||||
`fieldcraft_solver::ldlt` factors P A Pᵀ = L D Lᵀ (L unit lower triangular, D with 1 × 1 and
|
||||
2 × 2 pivots) on the Cholesky factor's symbolic factorization: the same nested dissection
|
||||
ordering, elimination tree, supernodes, fill, factor-size cap and parallel subtree tasks, so it
|
||||
is deterministic on any number of threads. Pivots are chosen by the bounded Bunch–Kaufman (rook)
|
||||
search of Ashcraft, Grimes & Lewis (1998) among the columns of the supernode being factored
|
||||
(Schenk & Gärtner's supernode Bunch–Kaufman, 2006): an interchange inside a supernode changes no
|
||||
row structure, so nothing is delayed and the static structure holds. Its limits, stated in the
|
||||
module: L's entries below the supernode are not bounded by the search (`solve_refined` adds
|
||||
iterative refinement), and a column whose supernode offers no pivot above round-off is a located
|
||||
`Singular` error (a matrix singular at that column, or a zero diagonal coupled only to later
|
||||
supernodes, which no FieldCraft system has: hybrid pressures are condensed per element).
|
||||
|
||||
The factor reports its **inertia** (positive and negative eigenvalue counts, Sylvester's law):
|
||||
a 2 × 2 pivot of the search has a negative determinant (one of each). `Symmetric::new(a, cap,
|
||||
kind)` picks Cholesky (`Definite`, the default everywhere a matrix is positive definite, so
|
||||
linear results are bit for bit unchanged), LDLᵀ (`Indefinite`), or Cholesky with LDLᵀ when the
|
||||
matrix turns out not to be positive definite (`Auto`, one symbolic factorization for both).
|
||||
On a hex8 stiffness pattern of 140 000 equations (1.5 · 10⁸ entries) the LDLᵀ factor costs 1.1
|
||||
times the Cholesky factor, and 1.2 times on a shift with 10 600 negative eigenvalues and 7 700
|
||||
2 × 2 pivots (`ldlt::tests::speed_against_cholesky`).
|
||||
|
||||
## Linear buckling
|
||||
|
||||
A step `{"type": "buckle", "modes": 4}` (`Procedure::Buckle`, solved by `solve.buckle`,
|
||||
`fieldcraft_solver::buckle`) solves its loads and prescribed motions as a linear static preload,
|
||||
forms the initial-stress stiffness K_σ = ∫ (∇N_a · σ ∇N_b) I dV of every solid and 2D element
|
||||
from the preload's stresses at the stiffness points (`Solid::geometric_stiffness`,
|
||||
`Plane::geometric_stiffness`, with the axisymmetric hoop term), and finds the load factors λ
|
||||
with (K + λ K_σ) φ = 0 by block Lanczos in the K inner product (Grimes, Lewis & Simon 1994):
|
||||
without a shift on K⁻¹(−K_σ) (θ = 1/λ, Cholesky of K), the lowest positive λ; with `"shift": σ`
|
||||
on the buckling transformation (K + σ K_σ)⁻¹ K (θ = λ/(λ − σ), LDLᵀ), the λ above σ, and the
|
||||
LDLᵀ inertia counts the load factors between 0 and σ, reported. Negative load factors (the
|
||||
reversed load buckles) are reported, not returned. Modes are scaled to a largest component of 1
|
||||
and display and probe like frequency modes (their value is λ; `FrequencyResult::buckling`).
|
||||
Boundary conditions hold their directions at zero in the eigenproblem; pressures are dead loads
|
||||
(no load stiffness); trusses, shells and beams are refused (no K_σ yet). Decks: Abaqus
|
||||
`*BUCKLE, EIGENSOLVER=LANCZOS` (refused after a general step, whose loaded state Abaqus would
|
||||
buckle from, and with a shift); Nastran SOL 105 and LS-DYNA refuse it by name. Verified by Euler
|
||||
columns of hex20 (pinned and clamped–free, 0.18 % from Engesser's shear-corrected load) and the
|
||||
shifted form against the plain one.
|
||||
|
||||
**Imperfections.** A nonlinear static step's `"imperfection": {"step": "Buckle", "mode": 1,
|
||||
"scale": 0.01}` solves that buckling step first and adds its mode, scaled to a largest component
|
||||
of `scale`, to the node coordinates; the step is solved and reported on that geometry, with a
|
||||
warning naming the mode. Abaqus and LS-DYNA decks refuse it by name (their imperfection reads a
|
||||
results file). Verified: a clamped–free column with its first mode as imperfection under half its
|
||||
buckling load deflects by δ₀ α/(1 − α) (2.8 %).
|
||||
|
||||
## Nonlinear static analysis (finite strain)
|
||||
|
||||
A step `{"type": "nonlinear_static", …}` (`Procedure::NonlinearStatic`, solved by
|
||||
@@ -251,9 +301,38 @@ first iteration's) are all below their tolerances, or the residual is round-off.
|
||||
starts from the linear extrapolation of the last one. Automatic incrementation grows an
|
||||
increment by half after two fast ones (≤ 4 iterations), shrinks it after a slow one (> 8), and
|
||||
cuts it to a quarter when an element inverts, the residual is not finite or grows twice, the
|
||||
tangent is not positive definite, or the iterations run out; the step stops with the load factor
|
||||
tangent is singular, or the iterations run out; the step stops with the load factor
|
||||
and the reason at the minimum increment, the increment cap, or `Limits::max_newton_iterations`.
|
||||
|
||||
**Indefinite tangents.** A tangent that is not positive definite (a strained nearly
|
||||
incompressible mixed element, an unstable material, a state past a limit or bifurcation point)
|
||||
is factored by LDLᵀ and Newton goes on; each iteration records the tangent's negative
|
||||
eigenvalues, and the summary warns when a converged state keeps some (an unstable equilibrium
|
||||
under load control). This lifts the old limit on hybrid elements near ν = ½ under prescribed
|
||||
displacement (at ν = 0.4999 every increment used to be cut back to the cap). Only the first
|
||||
tangent of a model that can move freely is an error. The tangent predictor of path-dependent
|
||||
materials keeps Cholesky and is skipped when the tangent is indefinite.
|
||||
|
||||
**Arc length.** `"arc_length": {"constraint": "cylindrical"|"spherical", "max_load_factor": 1,
|
||||
"displacement_limit": {"node", "direction", "displacement"}}` makes the load factor an unknown
|
||||
(Riks 1979, Crisfield 1981): each increment keeps ‖Δq‖² + w Δλ² = Δl² (w = 0 cylindrical, w the
|
||||
first tangent displacement's ‖q_f‖² for the spherical arc), predicts along the tangent with the
|
||||
sign of its angle to the last increment (Feng, Perić & Owen 1996), and corrects with
|
||||
δq = δq_r + δλ δq_g, δλ the root of the constraint's quadratic whose increment turns least
|
||||
(Crisfield's angle criterion). The first increment's load factor change is `initial_increment`,
|
||||
which sets the arc; arcs grow, shrink and cut back as increments do, within the minimum and
|
||||
maximum increments' arcs. Prescribed motions scale with λ (∂r/∂λ includes −K T_p u_p) and
|
||||
follower pressures with their current faces. The tangent at every converged state is factored
|
||||
for the next predictor (LDLᵀ when indefinite); its negative eigenvalues are recorded per
|
||||
increment (`negative_pivots`), and where their count changes the step reports a **critical
|
||||
point**: a limit point where the load factor turns, a bifurcation otherwise
|
||||
(`History::critical_points`, in the `solve.nonlinear` summary). The step ends at the maximum load
|
||||
factor, at the displacement limit, or at its increment cap (a warning). Refused: a load path,
|
||||
temperatures. Decks: Abaqus `*STATIC, RIKS` (cylindrical only); LS-DYNA refuses arc-length steps
|
||||
by name. Verified by the snap-through of a shallow sinusoidal arch of hex20 solids
|
||||
(`crates/solver/tests/arc_length.rs`, `tests/oracle/arc-shallow-arch`): the path within 1.9 % of
|
||||
the one-mode closed form, both limit points, and the inertia 0 → 1 → 0 exactly between them.
|
||||
|
||||
**Results**: the final displacements and reactions, the **Cauchy stress** and the
|
||||
**logarithmic strain** (ln V, engineering shears; the small strain without nonlinear geometry) at
|
||||
the integration points and averaged at the nodes, the **equivalent plastic strain** at the
|
||||
@@ -315,3 +394,89 @@ form (exact), and a tube inflated by a follower pressure while stretched axially
|
||||
block at a thermal stretch of 1.2 (exact, full and hybrid), a bar held at its ends heated past
|
||||
yield (exact), the linear limit against the linear and coupled solvers, and tangents with a
|
||||
temperature field.
|
||||
|
||||
crushing stops at the minimum increment, naming it; the caps; what is refused).
|
||||
|
||||
## Contact and friction (explicit dynamics)
|
||||
|
||||
**Model** (`fieldcraft_model::contact`): a contact names its surfaces as sets of element faces —
|
||||
a **pair** (`main`, `secondary`) or **general** contact on one surface (self contact) or on every
|
||||
exterior face of the solids — with Coulomb **friction** μ = μ_k + (μ_s − μ_k) e^{−d γ̇} (static,
|
||||
kinetic, decay per slip rate), a **penalty scale** s ≤ 1 and what happens to nodes that start
|
||||
inside the other surface (**adjust**: moved onto it strain-free and reported; **refuse**: the
|
||||
analysis stops naming the node, the face and the depth). Planar rigid walls take the same friction.
|
||||
Commands `interaction.contact.pair|general|edit|delete|find`; Abaqus writes `*SURFACE
|
||||
INTERACTION` with `*FRICTION` (exponential decay), `*CONTACT PAIR` and general `*CONTACT`, LS-DYNA
|
||||
`*CONTACT_AUTOMATIC_SURFACE_TO_SURFACE` and `_SINGLE_SURFACE` (`fs`, `fd`, `dc`, `sfsa`,
|
||||
`sfsb`); Nastran and the implicit solver refuse contact by name (implicit contact is M7).
|
||||
|
||||
**Geometry** (`fieldcraft_fem::contact`, shared with the implicit solver to come): the closest
|
||||
point of a triangle (exact region tests) or of a bilinear quadrilateral (projected Newton with the
|
||||
exact Hessian) to a point, with the signed gap along the face's normal and the lateral offset;
|
||||
a bucket grid of face boxes whose cell is twice the mean box, grown until the grid and its entries
|
||||
fit their caps, queried by point or by box with the candidates in face order.
|
||||
|
||||
**Kinematics** (`fieldcraft_explicit::contact`): segment to segment. Each secondary face and
|
||||
each main face facing it (normals within 84° of opposite) are projected onto the secondary face's
|
||||
plane, split into triangles and clipped against each other; on each overlap triangle a
|
||||
three-point rule takes the gap g = (x_s − x_m)·n_m between the faces' closest points. Where
|
||||
g < 0 (no deeper than half the main face's element), a penalty pressure p = ε(−g) acts on the
|
||||
secondary face's nodes with weights N_i^s along n_m and on the main face's nodes with −N_j^m. For
|
||||
a uniform pressure across flat faces both meshes receive exactly the consistent nodal forces,
|
||||
so the contact patch test passes on non-matching meshes. Every contact runs both ways (a pair
|
||||
with each surface as the secondary, single-surface contact with every face against every other
|
||||
face that shares no node with it) at half the penalty each.
|
||||
|
||||
**Penalty**: ε = s γ min_i(m_i/A_i)/Δt² over the contact's nodes (m_i lumped mass, A_i the node's
|
||||
area facing one way, Δt the stable increment, γ = 0.3). By Gershgorin's and Weyl's inequalities
|
||||
the contact adds at most 2 s γ/Δt² to the square of any frequency, which the default increment
|
||||
scale 0.9 leaves room for: contact never shortens the increment.
|
||||
|
||||
**Friction**: at the secondary nodes, by a regularised return map against the main face that
|
||||
pressed each node most: the elastic predictor t* = P t_n − k_t Δu_T (k_t = ε A_i/2), stick when
|
||||
|t*| ≤ μ f_n, otherwise slip back to the cone, dissipating μ f_n (|t*| − μ f_n)/k_t. On rigid
|
||||
walls, a node's tangential velocity changes by at most μ times its normal velocity change.
|
||||
|
||||
**Energy**: the contact forces' work (penalty energy plus friction dissipated) is integrated with
|
||||
the trapezoidal rule and enters the balance; friction dissipation (contact and walls) is
|
||||
reported apart. **Search** every increment, in parallel by faces, forces added in face order: the
|
||||
results are the same on any number of threads.
|
||||
|
||||
**Verification** (`crates/explicit/tests/contact.rs`, `tests/oracle/explicit-*`): two bars
|
||||
colliding (contact for 2L/c, interface force ρcAv₀/2, velocities exchanged, kinetic energy kept to
|
||||
0.01%, the contact energy back to 10⁻⁴ of it), a block sliding to a stop under constant and
|
||||
decaying friction on a rigid wall and on a deformable plate (distance and time to 0.1–0.5%), the
|
||||
contact patch test on non-matching meshes (σ_zz uniform to 0.1%), two spheres colliding against
|
||||
Hertz (peak force +2.3%, duration −0.4% on a graded quarter-sphere mesh), a free body untouched
|
||||
by general contact on all its faces, initial penetrations adjusted or refused, the face cap, and
|
||||
bit-for-bit results on one and four threads.
|
||||
|
||||
## Hyperelastic materials in explicit dynamics
|
||||
|
||||
Hyperelastic materials (neo-Hookean, Mooney–Rivlin, Yeoh) use the shared finite-strain material
|
||||
point (`fieldcraft_fem::constitutive`) in explicit dynamics too, in total form, which is objective
|
||||
by construction (no stress rate): the one-point hexahedron takes F = I + ∂u/∂X, its mean over the
|
||||
undeformed element, and the Cauchy stress of the nodal forces τ/J; the tetrahedron takes the
|
||||
isochoric stress of its own F and the **average nodal pressure** of a decoupled material (each
|
||||
node's U′(J_a) from its tetrahedra's volume ratio, the element's the mean of its nodes': J. Bonet,
|
||||
A. J. Burton, Commun. Numer. Methods Eng. 14:437–449, 1998, at finite strain), which does not lock
|
||||
when the material is nearly incompressible. (Averaging J into an F-bar instead was unstable on
|
||||
the Kuhn mesh of the tests.) The stable increment follows the tangent: each element's frequency
|
||||
bound is scaled by the ratio of its tangent's largest normal stiffness, plus the stress, to the
|
||||
small-strain one. Logarithmic strain is the strain output. Hyperelastic elements need nonlinear
|
||||
geometry and take no thermal strain yet (both refused by name). Verified by uniaxial strain to
|
||||
λ = 1.5 of all three laws on hex8 and tet4 against the material point (`crates/explicit/tests/hyperelastic.rs`)
|
||||
and by `tests/oracle/explicit-neo-hookean-implicit`, a quasi-static explicit pull against the
|
||||
implicit nonlinear solver.
|
||||
|
||||
## Mass scaling (explicit dynamics)
|
||||
|
||||
Opt-in per explicit step (`mass_scaling: {target_increment, set}`): every solid element (of the
|
||||
set, or of the model) whose stable increment times the step's scale is below the target has its
|
||||
density raised by (target / increment)², which brings its increment to the target (its lumped
|
||||
masses, frequency bound and hourglass and bulk-viscosity scales follow; adiabatic heating keeps
|
||||
the physical density). The run reports the elements scaled, the added mass in all and per
|
||||
section, its fraction of the model's mass, a warning, and the kinetic energy of the added mass
|
||||
(`energy.added_kinetic`, part of the kinetic energy, so the balance holds). Verified on a uniform
|
||||
bar scaled to twice its increment: added mass three times the bar's, the increment doubled, the
|
||||
added mass's share of the kinetic energy three quarters (`crates/explicit/tests/one_d.rs`).
|
||||
@@ -12,7 +12,7 @@ unzip tool reads them: `unzip -p bracket.fieldcraft model.json`):
|
||||
|
||||
| Part | Content |
|
||||
|---|---|
|
||||
| `fieldcraft.json` | Manifest: `format` (`"fieldcraft/1"`), `generator` (`"FieldCraft 0.5.5"`), `geometry`, and `parts`: the byte size and SHA-256 of each other part. |
|
||||
| `fieldcraft.json` | Manifest: `format` (`"fieldcraft/1"`), `generator` (`"FieldCraft 0.5.7"`), `geometry`, and `parts`: the byte size and SHA-256 of each other part. |
|
||||
| `model.json` | The model definition: unit system, sets, materials, sections, reference points, couplings, boundary conditions, loads and steps. Pretty-printed JSON with a fixed key order (maps sorted by name), so a change shows as a line diff. Its form is the model's own JSON form, which commands take as parameters. |
|
||||
| `mesh.bin` | Nodes, elements and geometry tags, binary (below). |
|
||||
| `journal.json` | The commands that built the model, `[{"command": id, "params": {...}}, ...]`, one per line. It is a script `fieldcraft-cli run` replays. |
|
||||
|
||||
@@ -91,7 +91,7 @@ software on the computer.
|
||||
|
||||
| Tool | Arguments | What it does |
|
||||
|---|---|---|
|
||||
| `list_commands` | `filter?` | Every command with its label and parameter documentation; `filter` matches id and label. |
|
||||
| `list_commands` | `filter?` | Every command with its label, parameter documentation and `schema` (its parameters as JSON Schema: types, units as `x-dimension`, defaults, required fields, one-of variants); `filter` matches id and label. |
|
||||
| `execute` | `command`, `params?` | Run any command (`list_commands`). A failure leaves the model unchanged and names what to fix. |
|
||||
| `batch` | `commands: [{command, params}]` | Run steps in order, stop at the first error; the reply has every result and the failing step (`failed.index`, `failed.command`, `failed.error`). Steps before it stay applied (`undo` takes them back). |
|
||||
| `inspect_model` | — | `model.info` (counts, units, definitions), `model.activity` (the step table) and `geometry.bodies` (bodies with measures and persistent face names, which sets name as `{body, face}`). |
|
||||
|
||||
|
Before Width: | Height: | Size: 256 KiB After Width: | Height: | Size: 195 KiB |
|
Before Width: | Height: | Size: 74 KiB After Width: | Height: | Size: 64 KiB |
|
Before Width: | Height: | Size: 235 KiB After Width: | Height: | Size: 223 KiB |
|
After Width: | Height: | Size: 1.3 MiB |
|
After Width: | Height: | Size: 126 KiB |
@@ -0,0 +1,75 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- FieldCraft social preview (1280 x 640). Original artwork; the cube is the app icon's
|
||||
02-part layer (assets/app-icon/FieldCraft.icon/Assets/02-part.svg, cargo xtask app-icon).
|
||||
Text is set in Inter (crates/ui-egui/fonts, OFL). Render with that font visible to fontconfig:
|
||||
rsvg-convert -w 1280 -h 640 og.svg -o og.png -->
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="1280" height="640" viewBox="0 0 1280 640">
|
||||
<title>FieldCraft: Open-source CAE built in Rust</title>
|
||||
<defs>
|
||||
<pattern id="og-grid" width="32" height="32" patternUnits="userSpaceOnUse">
|
||||
<path d="M32 0 L0 0 L0 32" fill="none" stroke="#ffffff" stroke-opacity="0.045" stroke-width="1"/>
|
||||
</pattern>
|
||||
<radialGradient id="og-glow" cx="300" cy="320" r="320" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0" stop-color="#2f86e0" stop-opacity="0.16"/>
|
||||
<stop offset="1" stop-color="#2f86e0" stop-opacity="0"/>
|
||||
</radialGradient>
|
||||
</defs>
|
||||
<rect width="1280" height="640" fill="#161b22"/>
|
||||
<rect width="1280" height="640" fill="url(#og-grid)"/>
|
||||
<rect width="1280" height="640" fill="url(#og-glow)"/>
|
||||
<svg x="60" y="70" width="500" height="500" viewBox="200 160 624 680">
|
||||
<defs>
|
||||
<clipPath id="clip-path-1">
|
||||
<path d="M512 200 L764.81 345.96 L512 491.92 L259.19 345.96 Z"/>
|
||||
</clipPath>
|
||||
<clipPath id="clip-path-2">
|
||||
<path d="M252.19 358.08 L505 504.04 L505 795.96 L252.19 650 Z"/>
|
||||
</clipPath>
|
||||
<clipPath id="clip-path-3">
|
||||
<path d="M771.81 650 L519 795.96 L519 504.04 L771.81 358.08 Z"/>
|
||||
</clipPath>
|
||||
<clipPath id="clip-path-4">
|
||||
<path d="M512 200 L764.81 345.96 L512 491.92 L259.19 345.96 Z M252.19 358.08 L505 504.04 L505 795.96 L252.19 650 Z M771.81 650 L519 795.96 L519 504.04 L771.81 358.08 Z"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
<title>FieldCraft icon cube</title>
|
||||
<g id="Top_face" data-name="Top face" clip-path="url(#clip-path-1)">
|
||||
<path id="top" d="M512 200 L764.81 345.96 L512 491.92 L259.19 345.96 Z" fill="#2c4fbf"/>
|
||||
<path id="top_band_1" data-name="top band 1" d="M844.55 692 C660.89 798.04 363.11 798.04 179.45 692 C-4.22 585.96 -4.22 414.04 179.45 308 C363.11 201.96 660.89 201.96 844.55 308 C1028.22 414.04 1028.22 585.96 844.55 692 Z" fill="#2f86e0"/>
|
||||
<path id="top_band_2" data-name="top band 2" d="M789.99 660.5 C636.46 749.14 387.54 749.14 234.01 660.5 C80.47 571.86 80.47 428.14 234.01 339.5 C387.54 250.86 636.46 250.86 789.99 339.5 C943.53 428.14 943.53 571.86 789.99 660.5 Z" fill="#22bcd8"/>
|
||||
<path id="top_band_3" data-name="top band 3" d="M738.03 630.5 C613.2 702.57 410.8 702.57 285.97 630.5 C161.13 558.43 161.13 441.57 285.97 369.5 C410.8 297.43 613.2 297.43 738.03 369.5 C862.87 441.57 862.87 558.43 738.03 630.5 Z" fill="#3fc584"/>
|
||||
<path id="top_band_4" data-name="top band 4" d="M686.07 600.5 C589.93 656 434.07 656 337.93 600.5 C241.79 545 241.79 455 337.93 399.5 C434.07 344 589.93 344 686.07 399.5 C782.21 455 782.21 545 686.07 600.5 Z" fill="#f0d13a"/>
|
||||
<path id="top_band_5" data-name="top band 5" d="M634.11 570.5 C566.67 609.44 457.33 609.44 389.89 570.5 C322.45 531.56 322.45 468.44 389.89 429.5 C457.33 390.56 566.67 390.56 634.11 429.5 C701.55 468.44 701.55 531.56 634.11 570.5 Z" fill="#f28a2b"/>
|
||||
<path id="top_band_6" data-name="top band 6" d="M582.15 540.5 C543.41 562.87 480.59 562.87 441.85 540.5 C403.11 518.13 403.11 481.87 441.85 459.5 C480.59 437.13 543.41 437.13 582.15 459.5 C620.89 481.87 620.89 518.13 582.15 540.5 Z" fill="#de3b2f"/>
|
||||
<path id="top_shade" data-name="top shade" d="M512 200 L764.81 345.96 L512 491.92 L259.19 345.96 Z" fill="#ffffff" opacity="0.1"/>
|
||||
</g>
|
||||
<g id="Left_face" data-name="Left face" clip-path="url(#clip-path-2)">
|
||||
<path id="left" d="M252.19 358.08 L505 504.04 L505 795.96 L252.19 650 Z" fill="#2c4fbf"/>
|
||||
<path id="left_band_1" data-name="left band 1" d="M844.55 692 C844.55 479.92 695.66 222.04 512 116 C328.34 9.96 179.45 95.92 179.45 308 C179.45 520.08 328.34 777.96 512 884 C695.66 990.04 844.55 904.08 844.55 692 Z" fill="#2f86e0"/>
|
||||
<path id="left_band_2" data-name="left band 2" d="M789.99 660.5 C789.99 483.22 665.53 267.64 512 179 C358.47 90.36 234.01 162.22 234.01 339.5 C234.01 516.78 358.47 732.36 512 821 C665.53 909.64 789.99 837.78 789.99 660.5 Z" fill="#22bcd8"/>
|
||||
<path id="left_band_3" data-name="left band 3" d="M738.03 630.5 C738.03 486.35 636.83 311.07 512 239 C387.17 166.93 285.97 225.35 285.97 369.5 C285.97 513.65 387.17 688.93 512 761 C636.83 833.07 738.03 774.65 738.03 630.5 Z" fill="#3fc584"/>
|
||||
<path id="left_band_4" data-name="left band 4" d="M686.07 600.5 C686.07 489.49 608.14 354.5 512 299 C415.86 243.5 337.93 288.49 337.93 399.5 C337.93 510.51 415.86 645.5 512 701 C608.14 756.5 686.07 711.51 686.07 600.5 Z" fill="#f0d13a"/>
|
||||
<path id="left_band_5" data-name="left band 5" d="M634.11 570.5 C634.11 492.63 579.44 397.94 512 359 C444.56 320.06 389.89 351.63 389.89 429.5 C389.89 507.37 444.56 602.06 512 641 C579.44 679.94 634.11 648.37 634.11 570.5 Z" fill="#f28a2b"/>
|
||||
<path id="left_band_6" data-name="left band 6" d="M582.15 540.5 C582.15 495.76 550.74 441.37 512 419 C473.26 396.63 441.85 414.76 441.85 459.5 C441.85 504.24 473.26 558.63 512 581 C550.74 603.37 582.15 585.24 582.15 540.5 Z" fill="#de3b2f"/>
|
||||
<path id="left_shade" data-name="left shade" d="M252.19 358.08 L505 504.04 L505 795.96 L252.19 650 Z" fill="#000000" opacity="0.12"/>
|
||||
</g>
|
||||
<g id="Right_face" data-name="Right face" clip-path="url(#clip-path-3)">
|
||||
<path id="right" d="M771.81 650 L519 795.96 L519 504.04 L771.81 358.08 Z" fill="#2c4fbf"/>
|
||||
<path id="right_band_1" data-name="right band 1" d="M179.45 692 C179.45 479.92 328.34 222.04 512 116 C695.66 9.96 844.55 95.92 844.55 308 C844.55 520.08 695.66 777.96 512 884 C328.34 990.04 179.45 904.08 179.45 692 Z" fill="#2f86e0"/>
|
||||
<path id="right_band_2" data-name="right band 2" d="M234.01 660.5 C234.01 483.22 358.47 267.64 512 179 C665.53 90.36 789.99 162.22 789.99 339.5 C789.99 516.78 665.53 732.36 512 821 C358.47 909.64 234.01 837.78 234.01 660.5 Z" fill="#22bcd8"/>
|
||||
<path id="right_band_3" data-name="right band 3" d="M285.97 630.5 C285.97 486.35 387.17 311.07 512 239 C636.83 166.93 738.03 225.35 738.03 369.5 C738.03 513.65 636.83 688.93 512 761 C387.17 833.07 285.97 774.65 285.97 630.5 Z" fill="#3fc584"/>
|
||||
<path id="right_band_4" data-name="right band 4" d="M337.93 600.5 C337.93 489.49 415.86 354.5 512 299 C608.14 243.5 686.07 288.49 686.07 399.5 C686.07 510.51 608.14 645.5 512 701 C415.86 756.5 337.93 711.51 337.93 600.5 Z" fill="#f0d13a"/>
|
||||
<path id="right_band_5" data-name="right band 5" d="M389.89 570.5 C389.89 492.63 444.56 397.94 512 359 C579.44 320.06 634.11 351.63 634.11 429.5 C634.11 507.37 579.44 602.06 512 641 C444.56 679.94 389.89 648.37 389.89 570.5 Z" fill="#f28a2b"/>
|
||||
<path id="right_band_6" data-name="right band 6" d="M441.85 540.5 C441.85 495.76 473.26 441.37 512 419 C550.74 396.63 582.15 414.76 582.15 459.5 C582.15 504.24 550.74 558.63 512 581 C473.26 603.37 441.85 585.24 441.85 540.5 Z" fill="#de3b2f"/>
|
||||
<path id="right_shade" data-name="right shade" d="M771.81 650 L519 795.96 L519 504.04 L771.81 358.08 Z" fill="#000000" opacity="0.3"/>
|
||||
</g>
|
||||
<g id="Mesh" clip-path="url(#clip-path-4)">
|
||||
<path id="hexahedral_mesh" data-name="hexahedral mesh" d="M576.95 237.5 L317.14 387.5 M447.05 237.5 L706.86 387.5 M317.14 687.5 L317.14 387.5 M252.19 575 L512 725 M706.86 687.5 L706.86 387.5 M771.81 575 L512 725 M641.9 275 L382.1 425 M382.1 275 L641.9 425 M382.1 725 L382.1 425 M252.19 500 L512 650 M641.9 725 L641.9 425 M771.81 500 L512 650 M706.86 312.5 L447.05 462.5 M317.14 312.5 L576.95 462.5 M447.05 762.5 L447.05 462.5 M252.19 425 L512 575 M576.95 762.5 L576.95 462.5 M771.81 425 L512 575" fill="none" stroke="#0b2236" stroke-width="3.5" stroke-linejoin="round" opacity="0.45"/>
|
||||
</g>
|
||||
</svg>
|
||||
<g font-family="Inter" font-weight="600">
|
||||
<text x="600" y="300" font-size="104" fill="#ffffff" letter-spacing="-2">FieldCraft</text>
|
||||
<text x="604" y="372" font-size="40" fill="#79c0ff">Open-source CAE built in Rust</text>
|
||||
<text x="605" y="430" font-size="27" fill="#8b949e">Structures · Heat · Fluids · MCP for AI agents</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 8.3 KiB |
|
Before Width: | Height: | Size: 195 KiB After Width: | Height: | Size: 157 KiB |
@@ -2,18 +2,24 @@
|
||||
|
||||
Generated by `cargo xtask oracle` from [`tests/oracle/`](../tests/oracle/); the policy is [verification.md](verification.md). Every case is our own model, built with FieldCraft commands from the problem's published description, and compared with the reference value its `expected.json` cites, within the stated tolerance and for the stated reason. Accepted results are frozen in each case's `fixture.json`: a later change that moves one beyond its band (10⁻⁹ of its size) fails CI even while the reference still passes. No reference value was produced with a commercial product.
|
||||
|
||||
**174 of 180 quantities pass** (6 known failure(s)) in 52 active cases: 43 theory, 9 published benchmark, 0 experiment; 9 pending cases wait for capabilities still being built.
|
||||
**201 of 207 quantities pass** (6 known failure(s)) in 62 active cases: 53 theory, 9 published benchmark, 0 experiment; 10 pending cases wait for capabilities still being built.
|
||||
|
||||
## Theory: closed-form solutions, patch tests and mesh invariants
|
||||
|
||||
| Case | Quantity | Reference | FieldCraft | Error | Tolerance | Result | Fixture |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| [arc-shallow-arch](../tests/oracle/arc-shallow-arch/) | upper limit load factor (snap-through) | 1 | 0.99183 | -0.817% | 2% | pass | matches |
|
||||
| [arc-shallow-arch](../tests/oracle/arc-shallow-arch/) | lower limit load factor | 0.21104 | 0.21895 | 7.9e-3 | ± 0.02 | pass | matches |
|
||||
| [arc-shallow-arch](../tests/oracle/arc-shallow-arch/) | negative eigenvalues of the tangent past the upper limit point | 1 | 1 | ≈ 0 | exact | pass | matches |
|
||||
| [bar-pressure-wave](../tests/oracle/bar-pressure-wave/) | displacement of the loaded end at t = 0.06 | -6.0000e-4 | -5.9980e-4 | 0.034% | 1% | pass | matches |
|
||||
| [bar-pressure-wave](../tests/oracle/bar-pressure-wave/) | particle velocity at x = 5, 20 elements behind the front, at t = 0.06 | -0.01 | -0.0098552 | 1.45% | 2% | pass | matches |
|
||||
| [bar-pressure-wave](../tests/oracle/bar-pressure-wave/) | energy balance error | 0 | 0.001527 | 1.5e-3 | ± 0.01 | pass | matches |
|
||||
| [bar-rigid-wall-impact](../tests/oracle/bar-rigid-wall-impact/) | displacement of the struck end at t = 0.3 (in contact until 2L/c = 0.2, then leaving at v₀) | 0.01 | 0.0099541 | -0.459% | 3% | pass | matches |
|
||||
| [bar-rigid-wall-impact](../tests/oracle/bar-rigid-wall-impact/) | displacement of the far end at t = 0.3 (−v₀L/c, then +v₀ after the reflection) | 0.01 | 0.0099488 | -0.512% | 3% | pass | matches |
|
||||
| [bar-rigid-wall-impact](../tests/oracle/bar-rigid-wall-impact/) | kinetic energy after the rebound over the initial ½mv₀² | 1 | 0.99463 | -0.537% | 2% | pass | matches |
|
||||
| [buckle-euler-cantilever](../tests/oracle/buckle-euler-cantilever/) | first buckling stress (load factor of a unit end pressure) | 2.0461 | 2.0424 | -0.181% | 0.5% | pass | matches |
|
||||
| [buckle-euler-pinned](../tests/oracle/buckle-euler-pinned/) | first buckling stress (load factor of a unit end pressure) | 2.0461 | 2.0424 | -0.179% | 0.5% | pass | matches |
|
||||
| [buckle-plate-square](../tests/oracle/buckle-plate-square/) | buckling stress of a unit edge pressure | 0.36152 | 0.36013 | -0.386% | 1% | pass | matches |
|
||||
| [cantilever-frequencies](../tests/oracle/cantilever-frequencies/) | first bending frequency (modes 1 and 2 are the y and z pair) | 0.012771 | 0.012751 | -0.158% | 1% | pass | matches |
|
||||
| [cantilever-frequencies](../tests/oracle/cantilever-frequencies/) | the other first bending frequency | 0.012771 | 0.012751 | -0.158% | 1% | pass | matches |
|
||||
| [cantilever-frequencies](../tests/oracle/cantilever-frequencies/) | second bending frequency | 0.080034 | 0.079167 | -1.08% | 2% | pass | matches |
|
||||
@@ -28,6 +34,25 @@ Generated by `cargo xtask oracle` from [`tests/oracle/`](../tests/oracle/); the
|
||||
| [cdt-stepped-block](../tests/oracle/cdt-stepped-block/) | volume of the tetrahedra | 47000 | 47000 | < 1e-7% | 1e-12 rel. | pass | matches |
|
||||
| [cdt-stepped-block](../tests/oracle/cdt-stepped-block/) | elements that fail the certified Jacobian check | 0 | 0 | ≈ 0 | exact | pass | matches |
|
||||
| [cdt-stepped-block](../tests/oracle/cdt-stepped-block/) | elements the Jacobian check could not decide | 0 | 0 | ≈ 0 | exact | pass | matches |
|
||||
| [explicit-bars-collision](../tests/oracle/explicit-bars-collision/) | time of the last contact (the bars touch from t = 0) against 2L/c = 0.2 | 0.2 | 0.20242 | 1.21% | 2% | pass | matches |
|
||||
| [explicit-bars-collision](../tests/oracle/explicit-bars-collision/) | the largest force across the interface against ρcAv₀/2 = 0.05 | 0.05 | 0.05147 | 2.94% | 4% | pass | matches |
|
||||
| [explicit-bars-collision](../tests/oracle/explicit-bars-collision/) | velocity of the struck bar's far end after the impact (0: the striker stops) | 0 | -0.0033987 | -3.4e-3 | ± 0.005 | pass | matches |
|
||||
| [explicit-bars-collision](../tests/oracle/explicit-bars-collision/) | velocity of the struck bar's far end after the impact (v₀ = 0.1) | 0.1 | 0.1034 | 3.4% | 5% | pass | matches |
|
||||
| [explicit-bars-collision](../tests/oracle/explicit-bars-collision/) | kinetic energy after the impact over ½mv₀² (frictionless elastic impact) | 1 | 0.99995 | -0.00468% | 1% | pass | matches |
|
||||
| [explicit-bars-collision](../tests/oracle/explicit-bars-collision/) | energy left in the contact after the separation, over ½mv₀² (its drift) | 0 | -7.7435e-5 | -7.7e-5 | ± 0.001 | pass | matches |
|
||||
| [explicit-contact-patch](../tests/oracle/explicit-contact-patch/) | σ_zz of the lower block's corner element under the interface (element 10) over that of the upper block's corner element over it (element 19) | 1 | 1.0001 | 0.0118% | 0.5% | pass | matches |
|
||||
| [explicit-contact-patch](../tests/oracle/explicit-contact-patch/) | σ_zz of the lower block's centre element under the interface (element 14) over that of element 19 | 1 | 1.0003 | 0.0287% | 0.5% | pass | matches |
|
||||
| [explicit-contact-patch](../tests/oracle/explicit-contact-patch/) | σ_zz of the lower block's bottom corner element (element 1) over that of element 19 | 1 | 1.0001 | 0.0134% | 0.5% | pass | matches |
|
||||
| [explicit-contact-patch](../tests/oracle/explicit-contact-patch/) | σ_zz of the upper block's top far corner element (element 26) over that of element 19 | 1 | 0.99944 | -0.0564% | 0.5% | pass | matches |
|
||||
| [explicit-contact-patch](../tests/oracle/explicit-contact-patch/) | the force across the interface over −σ_zz A (A = 1) | 1 | 1.0026 | 0.259% | 1% | pass | matches |
|
||||
| [explicit-contact-patch](../tests/oracle/explicit-contact-patch/) | σ_xx of element 14 over its σ_zz (uniaxial stress: 0) | 0 | -3.6052e-4 | -3.6e-4 | ± 0.005 | pass | matches |
|
||||
| [explicit-neo-hookean-implicit](../tests/oracle/explicit-neo-hookean-implicit/) | lateral displacement of the corner (1, 1, 1) along y, explicit over implicit | 1 | 0.99908 | -0.0922% | 0.5% | pass | matches |
|
||||
| [explicit-neo-hookean-implicit](../tests/oracle/explicit-neo-hookean-implicit/) | σ_xx of element 1, explicit, over σ_xx at the node at (0, 0, 0), implicit | 1 | 1.0003 | 0.0255% | 0.5% | pass | matches |
|
||||
| [explicit-sliding-block-contact](../tests/oracle/explicit-sliding-block-contact/) | distance travelled (top centre node) against ∫ v dv / (g μ(v)) = 2.01524 | 2.0152 | 2.0118 | -0.172% | 1% | pass | matches |
|
||||
| [explicit-sliding-block-contact](../tests/oracle/explicit-sliding-block-contact/) | velocity of the top centre node after the stop | 0 | ≈ 0 | ≈ 0 | ± 0.03 | pass | matches |
|
||||
| [explicit-sliding-block-wall](../tests/oracle/explicit-sliding-block-wall/) | distance travelled (top centre node) against v₀²/(2μg) = 1.5 | 1.5 | 1.4999 | -0.0053% | 1% | pass | matches |
|
||||
| [explicit-sliding-block-wall](../tests/oracle/explicit-sliding-block-wall/) | velocity of the top centre node after the stop | 0 | ≈ 0 | ≈ 0 | ± 0.03 | pass | matches |
|
||||
| [explicit-sliding-block-wall](../tests/oracle/explicit-sliding-block-wall/) | friction dissipation over ½mv₀² = 2.25 | 1 | 1.0012 | 0.121% | 1% | pass | matches |
|
||||
| [filleted-bracket-fillet-stress](../tests/oracle/filleted-bracket-fillet-stress/) | largest nodal von Mises stress on the fillet face (MPa) | 213 | mesh-dependent | within 3% | 3% | pass | — |
|
||||
| [filleted-bracket-fillet-stress](../tests/oracle/filleted-bracket-fillet-stress/) | total reaction x (N) | -2000 | -2000 | < 1e-7% | 1e-9 rel. | pass | matches |
|
||||
| [filleted-bracket-fillet-stress-coarse](../tests/oracle/filleted-bracket-fillet-stress-coarse/) | largest nodal von Mises stress on the fillet face (MPa) | 213 | mesh-dependent | within 3% | 3% | pass | — |
|
||||
@@ -65,6 +90,8 @@ Generated by `cargo xtask oracle` from [`tests/oracle/`](../tests/oracle/); the
|
||||
| [nl-elastica-cantilever](../tests/oracle/nl-elastica-cantilever/) | tip shortening δ_h/L at P L²/(E I) = 5 | 0.38763 | 0.38955 | 0.495% | 2% | pass | matches |
|
||||
| [nl-elastica-cantilever](../tests/oracle/nl-elastica-cantilever/) | tip deflection δ_v/L at P L²/(E I) = 10 | 0.81061 | 0.81421 | 0.444% | 1% | pass | matches |
|
||||
| [nl-elastica-cantilever](../tests/oracle/nl-elastica-cantilever/) | tip shortening δ_h/L at P L²/(E I) = 10 | 0.555 | 0.558 | 0.541% | 2% | pass | matches |
|
||||
| [nl-hybrid-incompressible](../tests/oracle/nl-hybrid-incompressible/) | axial Cauchy stress, stretch λ = 2, ν = 0.4999 | 3.4988 | 3.4988 | 0.000000135% | 1e-6 rel. | pass | matches |
|
||||
| [nl-hybrid-incompressible](../tests/oracle/nl-hybrid-incompressible/) | lateral displacement at (1, 1, 1): l − 1 | -0.29281 | -0.29281 | < 1e-7% | 1e-6 rel. | pass | matches |
|
||||
| [nl-j2-uniaxial](../tests/oracle/nl-j2-uniaxial/) | axial Cauchy stress at a logarithmic strain of 0.2 | 642.74 | 642.74 | < 1e-7% | 1e-6 rel. | pass | matches |
|
||||
| [nl-j2-uniaxial](../tests/oracle/nl-j2-uniaxial/) | equivalent plastic strain | 0.19678 | 0.19678 | < 1e-7% | 1e-6 rel. | pass | matches |
|
||||
| [nl-mooney-rivlin-modes](../tests/oracle/nl-mooney-rivlin-modes/) | axial Cauchy stress, uniaxial stretch λ = 2 | 2.7366 | 2.7366 | < 1e-7% | 1e-6 rel. | pass | matches |
|
||||
@@ -196,14 +223,23 @@ Generated by `cargo xtask oracle` from [`tests/oracle/`](../tests/oracle/); the
|
||||
|
||||
## Sources and tolerances
|
||||
|
||||
- **[arc-shallow-arch](../tests/oracle/arc-shallow-arch/)** (theory): Snap-through of a shallow arch by arc length. Source: One-mode closed form of a shallow sinusoidal arch y₀ = a sin(πx/L) on pins at a fixed span under q₀ sin(πx/L): q₀ = EI k⁴ [c + (a − c)(2ac − c²)/(4r²)], k = π/L, limit points at c = a ∓ r √((a²/r² − 4)/3) (S. P. Timoshenko, J. M. Gere, Theory of Elastic Stability, 2nd ed., McGraw-Hill 1961, §7.6; Y. C. Fung, A. Kaplan, NACA TN 2840, 1952): L = 100, h = 1, unit width, E = 10⁴, ν = 0, a/r = 3.5; the load is scaled to the upper limit load, so the peak load factor is 1 and the valley 0.211035. Tolerances — peak: 40 × 2 × 1 hex20 against shallow Euler–Bernoulli arch theory, the load piecewise constant per element, and the limit load picked from converged states (second order in the arc); valley: as the peak; the valley is a fifth of the peak load and a small difference of the bending and axial terms, so its tolerance is stated as 2 % of the peak load; negative: the inertia of the LDLᵀ factor: exactly one unstable direction between the limit points
|
||||
- **[bar-pressure-wave](../tests/oracle/bar-pressure-wave/)** (theory): Elastic wave in a bar from a pressure step (explicit). Source: d'Alembert's solution of the one-dimensional wave equation: c = √(E/ρ), particle velocity v = p/(ρc); Graff, Wave Motion in Elastic Solids, Dover 1991, §2.1. Tolerances — u_end: the end moves at the particle velocity p/(ρc) from the start; the discrete wave's ringing behind the front changes the end's displacement by well under 1%; v_mid: central differences ring behind a step front (dispersion); bulk viscosity damps it within a few elements, leaving about 1% twenty elements behind; balance: external work = kinetic + internal + dissipated energy; the solver warns above 1%
|
||||
- **[bar-rigid-wall-impact](../tests/oracle/bar-rigid-wall-impact/)** (theory): Elastic bar striking a rigid wall (explicit). Source: One-dimensional elastic impact on a rigid wall: contact time 2L/c, rebound at the impact speed, contact stress ρcv₀; Graff, Wave Motion in Elastic Solids, Dover 1991, §2.3; Johnson, Impact Strength of Materials, Arnold 1972, §1.6. Tolerances — u_front: the contact ends at 2L/c in the elastic theory; the discrete release front is spread over a few elements, a few tenths of a percent of the time, and the rebound speed is v₀ to about 1%; u_back: as for the struck end; ke: an elastic impact keeps the kinetic energy; quadratic bulk viscosity in the compression front and the vibration left in the bar take about 1%
|
||||
- **[buckle-euler-cantilever](../tests/oracle/buckle-euler-cantilever/)** (theory): Euler buckling of a clamped–free column of solids. Source: Euler's column with Engesser's shear correction P = P_e/(1 + P_e/(κ G A)), κ = 5/6 (S. P. Timoshenko, J. M. Gere, Theory of Elastic Stability, 2nd ed., McGraw-Hill 1961, §2.1, §2.17): square section 1 × 1, E = 1000, ν = 0, length 10 clamped–free, effective length 20, P_e = π² E I/20², so σ_cr = P/A = 2.046071. Tolerances — lambda: hex20, 2 × 2 across and 10 along: the 3D solid's bending and shear against beam theory, and the preload concentrated at the held face
|
||||
- **[buckle-euler-pinned](../tests/oracle/buckle-euler-pinned/)** (theory): Euler buckling of a pinned column of solids. Source: Euler's column with Engesser's shear correction P = P_e/(1 + P_e/(κ G A)), κ = 5/6 (S. P. Timoshenko, J. M. Gere, Theory of Elastic Stability, 2nd ed., McGraw-Hill 1961, §2.1, §2.17): square section 1 × 1, E = 1000, ν = 0, effective length 20, P_e = π² E I/20², so σ_cr = P/A = 2.046071. Tolerances — lambda: hex20, 2 × 2 across and 10 along: the 3D solid's bending and shear against beam theory, and the preload concentrated at the held face
|
||||
- **[buckle-plate-square](../tests/oracle/buckle-plate-square/)** (theory): Buckling of a simply supported square plate in uniaxial compression. Source: Bryan's plate buckling stress σ_cr = k π² E/(12 (1 − ν²)) (t/b)² with k = 4 for a square plate simply supported on four edges (G. H. Bryan, Proc. London Math. Soc. 22:54–67, 1891; Timoshenko & Gere 1961, §9.2): b = 50, t = 0.5, E = 1000, ν = 0.3, σ_cr = 0.361524. Tolerances — lambda: a quarter plate of 10 × 10 × 2 hex20 (b/t = 100) supported on its bottom edge lines: the solid against thin-plate theory (−1.5 % at b/t = 50, falling with t/b) and the discretisation
|
||||
- **[cantilever-frequencies](../tests/oracle/cantilever-frequencies/)** (theory): Natural frequencies of a cantilever (Euler–Bernoulli). Source: Euler–Bernoulli beam: f_n = (β_n L)²/(2π L²)·√(EI/ρA), β₁L = 1.8751, β₂L = 4.6941; Timoshenko, Young and Weaver, Vibration Problems in Engineering, 4th ed., Wiley 1974, §5.3. Tolerances — f1: Euler–Bernoulli neglects shear and rotary inertia, which lower f1 by about 0.2% at L/h = 20; f1_pair: as f1: a square section bends alike in y and z; f2: shear and rotary inertia lower the second mode by about 1% at L/h = 20 (Timoshenko)
|
||||
- **[cantilever-hex20](../tests/oracle/cantilever-hex20/)** (theory): Cantilever under a tip load, Timoshenko deflection (hex20). Source: Timoshenko and Gere, Mechanics of Materials (beam with shear deformation: δ = PL³/3EI + PL/κGA, κ = 5/6 for a rectangle); Cowper, J. Appl. Mech. 33 (1966) 335–340 for the shear coefficient. Tolerances — tip_uz: beam theory vs 3D elasticity: the shear coefficient and the fully clamped end change the tip deflection by a few tenths of a percent at L/h = 10; reaction: equilibrium holds to rounding
|
||||
- **[cantilever-hex8-incompatible](../tests/oracle/cantilever-hex8-incompatible/)** (theory): Cantilever under a tip load, Timoshenko deflection (hex8-incompatible). Source: Timoshenko and Gere, Mechanics of Materials (beam with shear deformation: δ = PL³/3EI + PL/κGA, κ = 5/6 for a rectangle); Cowper, J. Appl. Mech. 33 (1966) 335–340 for the shear coefficient. Tolerances — tip_uz: beam theory vs 3D elasticity (a few tenths of a percent at L/h = 10); incompatible modes represent the bending exactly in the constant-moment part; reaction: equilibrium holds to rounding
|
||||
- **[cantilever-tet10](../tests/oracle/cantilever-tet10/)** (theory): Cantilever under a tip load, Timoshenko deflection (tet10). Source: Timoshenko and Gere, Mechanics of Materials (beam with shear deformation: δ = PL³/3EI + PL/κGA, κ = 5/6 for a rectangle); Cowper, J. Appl. Mech. 33 (1966) 335–340 for the shear coefficient. Tolerances — tip_uz: beam theory vs 3D elasticity (a few tenths of a percent at L/h = 10); quadratic tetrahedra are converged on this mesh; reaction: equilibrium holds to rounding
|
||||
- **[cdt-cylinder](../tests/oracle/cdt-cylinder/)** (theory): Constrained Delaunay mesh of a cylinder: volume within the chordal bound, valid elements. Source: mesh invariants: an inscribed polygon of sagitta s loses at most 2s/R of a circle's area (elementary geometry); constrained Delaunay tetrahedralization after Diazzi et al., ACM TOG 42(6) 2023. Tolerances — volume: the tessellation inscribes the cylinder within the chordal tolerance s = 0.05: the polygon section loses between 0 and 2s/R = 0.5% of the area; the reference is the middle of that band; invalid: every element of a valid mesh has positive volume
|
||||
- **[cdt-stepped-block](../tests/oracle/cdt-stepped-block/)** (theory): Constrained Delaunay mesh of a stepped block: exact volume, valid elements. Source: mesh invariants: a tetrahedralization of a polyhedron fills its volume exactly (Si, TetGen paper ACM TOMS 41(2) 2015 for the definition of a CDT; Diazzi et al., ACM TOG 42(6) 2023); the volume is 60·40·10 + 40·40·10 + 20·40·10 − 10·10·10. Tolerances — volume: a planar boundary is tessellated exactly and the constrained Delaunay mesh fills it exactly: only rounding; invalid: every element of a valid mesh has positive volume; undetermined: a linear tetrahedron's sign is exact
|
||||
- **[explicit-bars-collision](../tests/oracle/explicit-bars-collision/)** (theory): Two identical elastic bars colliding (explicit contact). Source: One-dimensional elastic impact of equal bars: contact for 2L/c, interface force ρcAv₀/2, exchange of velocities, no loss of energy; Graff, Wave Motion in Elastic Solids, Dover 1991, §2.1–2.3; Johnson, Impact Strength of Materials, Arnold 1972, §1.6. Tolerances — duration: the penalty springs at the interface delay the release by a few element transit times (about 1% of 2L/c with 200 elements per bar); force: the plateau is ρcAv₀/2 to 0.01%; the peak is the plateau plus the ringing behind the discrete wave front, a few percent; v_a: the striker stops on average (its kinetic energy is under 0.01% of the start's, see ke); its far end node keeps the ringing of the discrete release front, a few percent of v₀; v_b: the struck bar leaves at v₀ on average; its far end node keeps the ringing of the discrete wave fronts, a few percent; ke: an elastic impact keeps the kinetic energy; the quadratic bulk viscosity at the compression fronts and the vibration left in the bars take a fraction of a percent; contact_energy: the penalty springs give back what they took; the trapezoidal work of a spring that engages between increments drifts by far less than 0.1%
|
||||
- **[explicit-contact-patch](../tests/oracle/explicit-contact-patch/)** (theory): Contact patch test: two blocks with non-matching meshes in uniaxial compression (explicit contact). Source: The contact patch test: a contact discretisation must transmit a uniform pressure across a non-matching interface exactly; Taylor & Papadopoulos, On a patch test for contact problems in two dimensions, Nonlinear Computational Mechanics, Springer 1991, 690–702; Crisfield, Re-visiting the contact patch test, IJNME 48:435–449, 2000. Uniaxial stress between frictionless symmetry planes is uniform in both blocks. Tolerances — lower_corner: a uniform stress is an equilibrium of the discrete system (the integrated contact forces are the consistent nodal forces of a uniform pressure on both meshes); what is left is the ringing of the loading, a hundred wave transits slow; lower_centre: as for the corner element; lower_base: as for the corner element; upper_top: as for the corner element; force: the integrated contact pressure carries the whole load; the largest force of the run is the final one in a slow squeeze, up to the ringing; lateral: frictionless symmetry planes and a frictionless interface leave the blocks free to expand sideways; the non-matching interface must not hold them
|
||||
- **[explicit-neo-hookean-implicit](../tests/oracle/explicit-neo-hookean-implicit/)** (theory): Neo-Hookean cube stretched to λ = 1.5: explicit dynamics, loaded slowly, against the implicit nonlinear solver. Source: Uniaxial stress of a compressible neo-Hookean solid (Holzapfel, Nonlinear Solid Mechanics, Wiley 2000, §6.5): a homogeneous state that a quasi-static explicit run must share with the implicit Newton solution on the same material point; the implicit solver is itself checked against the closed form by nl-neo-hookean-uniaxial. Tolerances — lateral: the same material point and a homogeneous state; the explicit run is pulled over a few hundred wave transits, and what is left of its waves is a fraction of a percent; stress: as for the displacement
|
||||
- **[explicit-sliding-block-contact](../tests/oracle/explicit-sliding-block-contact/)** (theory): Block sliding to a stop on a deformable plate, friction decaying with the slip rate (explicit contact). Source: A rigid block launched at v₀ with friction μ(v) = μk + (μs − μk) e^(−d v) decelerates at g μ(v); it travels ∫₀^v₀ v dv / (g μ(v)) (Simpson's rule, 200 000 intervals) and stops after [v₀ + ln((μk + (μs − μk) e^(−d v₀))/μs)/d]/(g μk) = 1.2001; Meriam & Kraige, Engineering Mechanics: Dynamics, §3/5; the exponential decay law as in Oden & Martins, CMAME 52:527–634, 1985. Tolerances — distance: the block bounces on the penalty springs and the plate under it shears elastically, so the normal force and the slip rate it feels vary by a little around their rigid-body values; velocity: the block sticks; what is left is its elastic vibration, under 1% of v₀
|
||||
- **[explicit-sliding-block-wall](../tests/oracle/explicit-sliding-block-wall/)** (theory): Block sliding to a stop on a rigid wall with Coulomb friction (explicit). Source: A rigid block launched at v₀ on a horizontal plane with Coulomb friction μ decelerates at μg and stops after v₀/(μg) at v₀²/(2μg), its kinetic energy all dissipated by friction; Meriam & Kraige, Engineering Mechanics: Dynamics, §3/5 (work and energy). Tolerances — distance: the wall's friction impulses are exact Coulomb impulses; the block's elastic vibration from the sudden gravity and the friction moment move the node by a fraction of a percent; velocity: the block sticks; what is left is its elastic vibration, under 1% of v₀; dissipated: the kinetic energy goes into friction; the vibration and the work of gravity as the block settles add or take a fraction of a percent
|
||||
- **[filleted-bracket-fillet-stress](../tests/oracle/filleted-bracket-fillet-stress/)** (theory): Filleted L-bracket under a side load: the peak von Mises stress on the R6 fillet, fine tet10 mesh. Source: mesh convergence of the finite element solution (P. J. Roache, Verification and Validation in Computational Science and Engineering, Hermosa, 1998, ch. 5): the bracket has no closed-form stress; the reference is the mesh-independent peak of a four-level study of quadratic tetrahedral meshes refined by √2 in size and in curvature resolution (README.md); equilibrium. Tolerances — fillet_peak: the four-level study gives 213.3, 210.6, 214.3, 213.3 MPa (2k to 13.5k elements): the bending stress is converged across the fillet, and the peak nodal value moves only with which of the fillet's tessellation lines (fixed angles, through every level) carries the largest node, by under 2%; reaction: equilibrium holds to rounding
|
||||
- **[filleted-bracket-fillet-stress-coarse](../tests/oracle/filleted-bracket-fillet-stress-coarse/)** (theory): Filleted L-bracket under a side load: the peak von Mises stress on the R6 fillet, coarse tet10 mesh. Source: mesh convergence of the finite element solution (P. J. Roache, Verification and Validation in Computational Science and Engineering, Hermosa, 1998, ch. 5): the bracket has no closed-form stress; the reference is the mesh-independent peak of a four-level study of quadratic tetrahedral meshes refined by √2 in size and in curvature resolution (README.md); equilibrium. Tolerances — fillet_peak: the four-level study gives 213.3, 210.6, 214.3, 213.3 MPa (2k to 13.5k elements): the bending stress is converged across the fillet, and the peak nodal value moves only with which of the fillet's tessellation lines (fixed angles, through every level) carries the largest node, by under 2%; reaction: equilibrium holds to rounding
|
||||
- **[free-beam-frequencies](../tests/oracle/free-beam-frequencies/)** (theory): Natural frequencies of a free beam: rigid-body modes and the first bending mode. Source: Euler–Bernoulli free–free beam, β₁L = 4.7300; Timoshenko, Young and Weaver, Vibration Problems in Engineering, 4th ed., Wiley 1974, §5.3. Tolerances — rigid_6: a free body has six zero frequencies; numerical rigid-body frequencies below 10⁻³ of the first elastic one (eigenvalues below 10⁻⁶ of it) are rounding of the shifted solve; f7: Euler–Bernoulli neglects shear and rotary inertia, about 0.8% at L/h = 20 for the free–free mode; mass: the mass matrix integrates the density exactly
|
||||
@@ -225,6 +261,7 @@ Generated by `cargo xtask oracle` from [`tests/oracle/`](../tests/oracle/); the
|
||||
- **[nafems-le10](../tests/oracle/nafems-le10/)** (benchmark): NAFEMS LE10 thick plate under pressure (hex20). Source: NAFEMS, The Standard NAFEMS Benchmarks, TNSB Rev. 3, October 1990, test LE10 (target σ_yy = −5.38 MPa at D); as reproduced in the Abaqus 2017 Benchmarks Guide, 'LE10: Thick plate under pressure'. Tolerances — syy_D: the target is published to three figures; at D the stress is extrapolated to a corner where the hole edge meets the loaded face, and published converged solutions scatter by 1–2% (Abaqus Benchmarks Guide fine meshes: −5.51 to −5.89)
|
||||
- **[nl-cylinder-inflation](../tests/oracle/nl-cylinder-inflation/)** (theory): Inflation of a thick neo-Hookean cylinder by a follower pressure (plane strain). Source: Finite inflation of an incompressible neo-Hookean thick-walled tube in plane strain: r² = R² + a² − A², σ_θ − σ_r = μ (λ² − λ⁻²) with λ = r/R, integrated through the wall: p = (μ/2)[(ln λ_a² − λ_a⁻²) − (ln λ_b² − λ_b⁻²)] (R. S. Rivlin, Large elastic deformations of isotropic materials VI, Phil. Trans. R. Soc. A 242:173–195, 1949; R. W. Ogden, Non-Linear Elastic Deformations, Dover 1997, §5.3.2). Tolerances — ua: the closed form is incompressible and our material nearly so (κ/μ = 1000, a volume change of order p/κ ≈ 4·10⁻⁴); hybrid hex20, 6 × 16, follow the wall's strain gradient well inside; ub: as at the bore
|
||||
- **[nl-elastica-cantilever](../tests/oracle/nl-elastica-cantilever/)** (theory): Large-deflection cantilever under a dead tip load against the elastica (solids). Source: The elastica of a cantilever under a vertical end load: K. E. Bisshopp, D. C. Drucker, Large deflection of cantilever beams, Quarterly of Applied Mathematics 3(3):272–275, 1945 (elliptic-integral solution); values computed by integrating θ″ = −(P/EI) cos θ by shooting (our own RK4, 20000 steps), agreeing with the table of K. Mattiasson, Numerical results from large deflection beam and frame problems analysed by means of elliptic integrals, IJNME 17(1):145–153, 1981, to all six digits. Tolerances — v1: hex20, 40 × 2 through the depth, L/h = 20: shear deformation (0.6 (h/L)² ≈ 0.15 % of the deflection) and the clamp's local restraint, both absent from the elastica; u1: as δ_v; the shortening is the smaller, second-order quantity, so its relative error is about twice the deflection's; v2: hex20, 40 × 2 through the depth, L/h = 20: shear deformation (0.6 (h/L)² ≈ 0.15 % of the deflection) and the clamp's local restraint, both absent from the elastica; u2: as δ_v; the shortening is the smaller, second-order quantity, so its relative error is about twice the deflection's; v5: hex20, 40 × 2 through the depth, L/h = 20: shear deformation (0.6 (h/L)² ≈ 0.15 % of the deflection) and the clamp's local restraint, both absent from the elastica; u5: as δ_v; the shortening is the smaller, second-order quantity, so its relative error is about twice the deflection's; v10: hex20, 40 × 2 through the depth, L/h = 20: shear deformation (0.6 (h/L)² ≈ 0.15 % of the deflection) and the clamp's local restraint, both absent from the elastica; u10: as δ_v; the shortening is the smaller, second-order quantity, so its relative error is about twice the deflection's
|
||||
- **[nl-hybrid-incompressible](../tests/oracle/nl-hybrid-incompressible/)** (theory): Nearly incompressible hybrid block under prescribed stretch. Source: Uniaxial stress of the decoupled compressible neo-Hookean energy W = μ/2 (Ī₁ − 3) + κ/2 (J − 1)² (P. J. Flory, Trans. Faraday Soc. 57:829–838, 1961): σ = μ J^(−5/3) (λ² − I₁/3) + κ (J − 1) with the lateral stretch found so σ_yy = 0 (bisection; E = 3, ν = 0.4999: μ = 1.0000667, κ = 5000). Tolerances — sigma: a homogeneous deformation every hybrid hex8 represents exactly; the 27-element mesh makes the global mixed tangent indefinite in the first iterations (LDLᵀ): the tolerance admits the Newton tolerance and rounding; lateral: a homogeneous deformation every hybrid hex8 represents exactly; the 27-element mesh makes the global mixed tangent indefinite in the first iterations (LDLᵀ): the tolerance admits the Newton tolerance and rounding
|
||||
- **[nl-j2-uniaxial](../tests/oracle/nl-j2-uniaxial/)** (theory): Uniaxial tension of a J2 bilinear-hardening cube to large strain (implicit, finite strain). Source: J2 plasticity with linear isotropic hardening in uniaxial stress (Simo and Hughes, Computational Inelasticity, Springer 1998, §2.3) in the logarithmic strain, which Simo's exponential return map (CMAME 99:61–112, 1992) integrates exactly on a proportional path: Kirchhoff stress τ = σ_y + E_t (ε − σ_y/E), Cauchy stress σ = τ/J with ln J = τ/(3K) (Hencky's volume law). Tolerances — sigma: a homogeneous deformation the element represents exactly, reached on a proportional path: the tolerance only admits the Newton tolerance and rounding; plastic_strain: ε_p = (τ − σ_y)/H, as for the stress
|
||||
- **[nl-mooney-rivlin-modes](../tests/oracle/nl-mooney-rivlin-modes/)** (theory): Mooney–Rivlin block in uniaxial, equibiaxial and pure-shear tension. Source: Treloar's homogeneous modes of rubber testing (L. R. G. Treloar, The Physics of Rubber Elasticity, 3rd ed., Oxford 1975, ch. 10) for the decoupled compressible energy W = C₁₀ (Ī₁ − 3) + C₀₁ (Ī₂ − 3) + κ/2 (J − 1)²: principal Cauchy stresses σᵢ = (λᵢ/J) ∂W/∂λᵢ with the free stretch found so the free faces carry no stress (bisection; E = 3, ν = 0.49, C₀₁ = 0.2, C₁₀ = μ/2 − C₀₁). Tolerances — uniaxial: a homogeneous deformation the hybrid hex20 represents exactly: the tolerance admits the Newton tolerance and rounding; uniaxial_lateral: a homogeneous deformation the hybrid hex20 represents exactly: the tolerance admits the Newton tolerance and rounding; equibiaxial: a homogeneous deformation the hybrid hex20 represents exactly: the tolerance admits the Newton tolerance and rounding; shear_xx: a homogeneous deformation the hybrid hex20 represents exactly: the tolerance admits the Newton tolerance and rounding; shear_yy: a homogeneous deformation the hybrid hex20 represents exactly: the tolerance admits the Newton tolerance and rounding
|
||||
- **[nl-mooney-rivlin-tube](../tests/oracle/nl-mooney-rivlin-tube/)** (theory): Inflation of a stretched Mooney–Rivlin tube (follower pressure). Source: Finite inflation and extension of an incompressible Mooney–Rivlin tube (R. S. Rivlin, Large elastic deformations of isotropic materials VI, Phil. Trans. R. Soc. A 242:173–195, 1949; R. W. Ogden, Non-Linear Elastic Deformations, Dover 1997, §5.3): at axial stretch λ_z, r² = a² + (R² − A²)/λ_z, σ_θ − σ_r = 2 (λ_θ² − λ_r²)(C₁₀ + C₀₁ λ_z²) with λ_θ = r/R, λ_r = 1/(λ_θ λ_z), integrated through the wall: p = ∫ (σ_θ − σ_r) dr/r (Simpson, 2·10⁵ intervals). Tolerances — ua: 16 × 6 hybrid hex20 around the quarter; ν = 0.4995 stands in for incompressibility (a volume change of order p/κ ≈ 10⁻³ shifts the radii by about 0.1 %), and the tube is stretched axially by its ends, which a nearly incompressible solid takes with larger pressures than the plane-strain neo-Hookean tube; ub: 0.2 % of the outer radius b = 20.616: the same volume change of order 10⁻³ moves b by about 0.03, which is 4.5 % of b − B; the incompressible kinematics r² = a² + (R² − A²)/λ_z amplify it there
|
||||
@@ -256,6 +293,7 @@ Reference values already cited; each case gets its recipe when the capability it
|
||||
| Case | Kind | Problem | Needs | Reference values | Source |
|
||||
|---|---|---|---|---|---|
|
||||
| [cylinder-channel-2d1](../tests/oracle/cylinder-channel-2d1/) | benchmark | Flow around a cylinder, steady 2D-1 (Re = 20) | lattice Boltzmann CFD (M12) | drag coefficient (published interval 5.57–5.59) = 5.58; lift coefficient (interval 0.0104–0.0110) = 0.0107 | Schäfer and Turek, 'Benchmark computations of laminar flow around a cylinder', Notes on Numerical Fluid Mechanics 52 (1996) 547–566, Table 4 (reference intervals) |
|
||||
| [explicit-hertz-spheres](../tests/oracle/explicit-hertz-spheres/) | theory | Two elastic spheres in a head-on collision: Hertz's force and contact duration (explicit contact) | a graded sphere mesh from commands (a cubed-sphere hex mesher, or tet refinement towards a point); until then the explicit crate's tests `spheres_collide_as_hertz_says` (a graded cubed-sphere quarter of each sphere, 27 648 hex8: peak force +2.3%, duration −0.4%) and its coarse twin in the main gate check this case on a mesh generated in code | the largest contact force, two steel spheres R = 10 mm (E = 210 GPa, ν = 0.3, ρ = 7.85 t/m³) meeting at 1 m/s (N) = 1005.4; the contact duration (s) = 6.0163e-5 | Hertz's quasi-static impact: with R* = R/2, m* = m/2, E* = E/(2(1 − ν²)), the approach reaches δ = (15 m* v²/(16 E* √R*))^(2/5), the force (4/3) E* √R* δ^(3/2), and the contact lasts 2.9432 δ/v; Hertz, J. reine angew. Math. 92:156–171, 1882; K. L. Johnson, Contact Mechanics, Cambridge 1985, §11.4 |
|
||||
| [lid-driven-cavity-re100](../tests/oracle/lid-driven-cavity-re100/) | benchmark | Lid-driven cavity, Re = 100 | lattice Boltzmann CFD (M12) | u/U at y = 0.4531 on the vertical centreline = -0.2109 | Ghia, Ghia and Shin, Journal of Computational Physics 48 (1982) 387–411, Table I (u along the vertical centreline) |
|
||||
| [mh-twisted-beam](../tests/oracle/mh-twisted-beam/) | benchmark | MacNeal–Harder twisted beam | shell elements (M8) or mapped blocks with helical edges | tip displacement along the in-plane load = 0.005424; tip displacement along the out-of-plane load = 0.001754 | MacNeal and Harder, 'A proposed standard set of problems to test finite element accuracy', Finite Elements in Analysis and Design 1 (1985) 3–20, Fig. 6 (p. 8), Table 3 (p. 10) |
|
||||
| [nafems-le11](../tests/oracle/nafems-le11/) | benchmark | NAFEMS LE11 solid cylinder/taper/sphere under a temperature field | thermal loads (M8 heat transfer) | σ_zz at A = -105 | NAFEMS, The Standard NAFEMS Benchmarks, TNSB Rev. 3, October 1990, test LE11 (target σ_zz = −105 MPa at A) |
|
||||
|
||||
@@ -55,7 +55,7 @@ products are run, no documentation text is copied). Status: **done**, **started*
|
||||
| Model | Steps: linear static, frequency; output presets | M3 | | done |
|
||||
| Model | Steps: nonlinear static, explicit dynamics, heat transfer; amplitudes | M7–M8, M15 | | started (nonlinear static with or without nonlinear geometry, increments, tolerances and a load path (cyclic loading), written to Abaqus `*STEP, NLGEOM` and LS-DYNA implicit (the load path as LS-DYNA's curve; refused by Abaqus for now), refused by Nastran; explicit dynamics; heat transfer; amplitudes per load planned) |
|
||||
| Interaction | Tie between non-matching meshes | M7 | | planned |
|
||||
| Interaction | Contact (general and pairs), friction, automatic pair detection | M7 | | planned |
|
||||
| Interaction | Contact (general and pairs), friction, automatic pair detection | M7, M10 | | started (explicit: pairs, general and self contact, segment to segment with a penalty that keeps the time increment, Coulomb friction with exponential decay, friction on rigid walls, `interaction.contact.find`, Abaqus and LS-DYNA contact keywords; implicit contact in M7) |
|
||||
| Interaction | Springs and dashpots (ground or two-point; DOF, vector or line), point masses with rotary inertia | M4 | | done (implicit; explicit translational; all three decks with what each cannot take reported) |
|
||||
| Interaction | Bolt pretension, connectors | M7 | | planned |
|
||||
| Decks | Abaqus input writer (`deck.write`, flat deck; reports what Abaqus cannot express) | M3 | | done |
|
||||
@@ -63,8 +63,8 @@ products are run, no documentation text is copied). Status: **done**, **started*
|
||||
| Decks | LS-DYNA keyword writer (implicit; explicit in M8) | M3 | | done (implicit static and eigenvalue; beam sections planned) |
|
||||
| Decks | Readers keeping unknown keywords | M9 | | planned |
|
||||
| Solve | Own linear static and modal solver, verified against analytic solutions | M4 | yes | started (solid elements: tet4, tet10, wedge6, hex8, hex20; 2D plane stress, plane strain and axisymmetric tri3, tri6, quad4 (full, incompatible modes), quad8 (full, reduced); quad4/tri3 MITC shells and Timoshenko beams with profiles, mixed with solids; reference points, kinematic and distributing couplings, moments; centrifugal loads) |
|
||||
| Solve | Own nonlinear implicit solver: Newton–Raphson with line search and automatic increments, total Lagrangian solids and 2D elements, mixed u–p at finite strain, follower pressure | M15 | yes | started (solids, plane strain, axisymmetric; St Venant–Kirchhoff, neo-Hookean and J2 plasticity (Simo's exponential return map at finite strain, radial return at small strain, consistent tangents, the return shared with explicit dynamics); verified by the elastica, tube inflation, patch and objectivity tests, uniaxial tension to large strain, Hill's thick cylinder, a cantilever's collapse and the Bauschinger effect; Mooney–Rivlin and Yeoh; thermal strain at finite and small strain; shells, contact, arc-length next) |
|
||||
| Solve | Own explicit dynamics solver (central differences, one-point hex8 with hourglass control, nodal-pressure tet4, bulk viscosity, energy balance), verified against analytic wave and impact solutions | M10 | yes | started (X1 core and X2: large deformation, objective rates, J2 and Johnson–Cook plasticity, damage, erosion; contact planned) |
|
||||
| Solve | Own nonlinear implicit solver: Newton–Raphson with line search and automatic increments, total Lagrangian solids and 2D elements, mixed u–p at finite strain, follower pressure | M15 | yes | started (solids, plane strain, axisymmetric; St Venant–Kirchhoff, neo-Hookean and J2 plasticity (Simo's exponential return map at finite strain, radial return at small strain, consistent tangents, the return shared with explicit dynamics); verified by the elastica, tube inflation, patch and objectivity tests, uniaxial tension to large strain, Hill's thick cylinder, a cantilever's collapse and the Bauschinger effect; Mooney–Rivlin and Yeoh; thermal strain at finite and small strain; a symmetric indefinite LDLᵀ factorization with inertia, Newton through indefinite tangents (hybrid elements at ν = 0.4999 under prescribed displacement); linear buckling of solids (Euler columns, Bryan's plate) and imperfections from its modes; arc-length with critical points from the inertia (shallow-arch snap-through); shells, implicit contact next) |
|
||||
| Solve | Own explicit dynamics solver (central differences, one-point hex8 with hourglass control, nodal-pressure tet4, bulk viscosity, energy balance), verified against analytic wave and impact solutions | M10 | yes | started (X1 core and X2: large deformation, objective rates, J2 and Johnson–Cook plasticity, damage, erosion; X3: deformable contact and friction, verified by bar collision, sliding blocks, the contact patch test and Hertz; hyperelastic materials on the shared material point; opt-in mass scaling) |
|
||||
| Results | Deformed shape, contours, mode shapes, probes, reaction sums | M4 | | started (results in the session, `solve.probe`, reaction sums; display planned) |
|
||||
| Results | XY and path plots, cuts, display groups, free-body forces, animation | M9 | | planned |
|
||||
| Results | Readers for public result formats (Nastran OP2, LS-DYNA d3plot, Abaqus `.fil`) | M9 | | planned |
|
||||
|
||||
@@ -1228,3 +1228,74 @@ update are written from (cited again in the module docs):
|
||||
- Thermal strain by the multiplicative split F = F_m F_θ: V. A. Lubarda, *Constitutive
|
||||
theories based on the multiplicative decomposition of deformation gradient: thermoelasticity,
|
||||
elastoplasticity, and biomechanics*, Appl. Mech. Rev. 57(2):95–108, 2004.
|
||||
|
||||
## Part P: Symmetric indefinite factorization, linear buckling and arc-length, as implemented
|
||||
|
||||
- Symmetric indefinite pivoting: J. R. Bunch, L. Kaufman, *Some stable methods for calculating
|
||||
inertia and solving symmetric linear systems*, Math. Comp. 31(137):163–179, 1977; the bounded
|
||||
(rook) search, C. Ashcraft, R. G. Grimes, J. G. Lewis, *Accurate symmetric indefinite linear
|
||||
equation solvers*, SIAM J. Matrix Anal. Appl. 20(2):513–561, 1998; the panel's partial
|
||||
factorization of LAPACK's `dsytrf`, E. Anderson et al., *LAPACK Users' Guide*, 3rd ed., SIAM
|
||||
1999.
|
||||
- Pivoting within supernodes on a static structure: O. Schenk, K. Gärtner, *On fast
|
||||
factorization pivoting methods for sparse symmetric indefinite systems*, Electron. Trans.
|
||||
Numer. Anal. 23:158–179, 2006. Delayed pivots (the multifrontal alternative, not used: it
|
||||
changes the structure as it goes): I. S. Duff, J. K. Reid, *The multifrontal solution of
|
||||
indefinite sparse symmetric linear equations*, ACM TOMS 9(3):302–325, 1983; J. W. H. Liu, *The
|
||||
multifrontal method for sparse matrix solution: theory and practice*, SIAM Review
|
||||
34(1):82–109, 1992.
|
||||
- Arc-length: E. Riks, *An incremental approach to the solution of snapping and buckling
|
||||
problems*, Int. J. Solids Struct. 15(7):529–551, 1979; M. A. Crisfield, *A fast
|
||||
incremental/iterative solution procedure that handles "snap-through"*, Computers & Structures
|
||||
13:55–62, 1981; E. Ramm, *Strategies for tracing the nonlinear response near limit points*, in
|
||||
*Nonlinear Finite Element Analysis in Structural Mechanics*, Springer 1981, 63–89; the
|
||||
predictor's sign, M. Feng, D. Perić, D. R. J. Owen, Computers & Structures 58(3):479–485, 1996.
|
||||
Snap-through of a shallow sinusoidal arch: Y. C. Fung, A. Kaplan, NACA TN 2840, 1952;
|
||||
Timoshenko & Gere 1961, §7.6.
|
||||
- Iterative refinement: N. J. Higham, *Accuracy and Stability of Numerical Algorithms*, 2nd ed.,
|
||||
SIAM 2002, §12.2.
|
||||
- Linear buckling and the initial-stress stiffness: K.-J. Bathe, *Finite Element Procedures*,
|
||||
2nd ed., 2014, §6.8.2; the buckling spectral transformations in the K inner product: R. G.
|
||||
Grimes, J. G. Lewis, H. D. Simon, SIAM J. Matrix Anal. Appl. 15(1):228–272, 1994, §3; Euler's
|
||||
columns with Engesser's shear correction: S. P. Timoshenko, J. M. Gere, *Theory of Elastic
|
||||
Stability*, 2nd ed., McGraw-Hill 1961, §2.1, §2.17.
|
||||
|
||||
## Part Q: Contact and friction (explicit), as implemented
|
||||
|
||||
The papers and books `fieldcraft_fem::contact` and `fieldcraft_explicit::contact` are written
|
||||
from (cited again in the module docs); docs/fem.md describes the formulation.
|
||||
|
||||
- Closest point on a triangle by its Voronoi regions: C. Ericson, *Real-Time Collision
|
||||
Detection*, Morgan Kaufmann 2005, §5.1.5; on a bilinear quadrilateral by Newton's method on the
|
||||
stationarity conditions, projected on the parameter square: the local search of node-to-segment
|
||||
contact, J. O. Hallquist, G. L. Goudreau, D. J. Benson, CMAME 51:107–137, 1985 (A5.1), and P.
|
||||
Wriggers, *Computational Contact Mechanics*, 2nd ed., Springer 2006, §4.1.
|
||||
- Global search by bucket sorting into a uniform grid: D. J. Benson, J. O. Hallquist, CMAME
|
||||
78:141–163, 1990 (A5.2). We chose a grid over the BVH of A5.4: one pass per increment, memory
|
||||
bounded by caps whatever the mesh, candidates in face order (determinism); the cell grows when a
|
||||
few huge faces would blow the entry cap.
|
||||
- Segment-to-segment integration (projection on the secondary face's plane, clipping,
|
||||
sub-triangle quadrature): M. A. Puso, T. A. Laursen, *A mortar segment-to-segment contact
|
||||
method for large deformation solid mechanics*, CMAME 193:601–629, 2004; with the penalty applied
|
||||
at the integration points, K. A. Fischer, P. Wriggers, Comput. Mech. 36:226–244, 2005; polygon
|
||||
clipping, I. E. Sutherland, G. W. Hodgman, Commun. ACM 17(1):32–42, 1974. Chosen over
|
||||
node-to-segment because the latter fails the contact patch test on non-matching meshes (R. L.
|
||||
Taylor, P. Papadopoulos, in *Nonlinear Computational Mechanics*, Springer 1991, 690–702; M. A.
|
||||
Crisfield, IJNME 48:435–449, 2000), which our first node-to-segment version showed too (12%
|
||||
spread of σ_zz in the patch test, 0.1% now).
|
||||
- Penalty from the masses and the stable increment (the "soft constraint" idea: J. O. Hallquist,
|
||||
*LS-DYNA Theory Manual*, LSTC 2006, the contact chapter's soft-constraint option; the bound is ours: Gershgorin's row sums of the
|
||||
integrated contact stiffness with the node's directional area, added to the element
|
||||
frequencies by Weyl's inequality).
|
||||
- Friction by a regularised (penalty) return map: P. Wriggers, *Computational Contact
|
||||
Mechanics*, §5.2 and §10.3; J. C. Simo, T. A. Laursen, Comput. Struct. 42(1):97–116, 1992;
|
||||
rate-dependent coefficients reviewed by J. T. Oden, J. A. C. Martins, CMAME 52:527–634, 1985.
|
||||
The exponential decay μ = μ_k + (μ_s − μ_k) e^{−d γ̇} is the form the LS-DYNA and Abaqus
|
||||
manuals document, so the decks carry it unchanged.
|
||||
- Kinematic rigid walls with Coulomb impulses: T. J. R. Hughes et al., CMAME 8(3):249–276, 1976
|
||||
(A5.5), the tangential impulse capped at μ times the normal one.
|
||||
- Verification: the impact of equal bars, K. F. Graff, *Wave Motion in Elastic Solids*, Dover
|
||||
1991, §2.1–2.3, and W. Johnson, *Impact Strength of Materials*, Arnold 1972, §1.6; Hertz's
|
||||
impact of spheres, H. Hertz, J. reine angew. Math. 92:156–171, 1882, and K. L. Johnson,
|
||||
*Contact Mechanics*, Cambridge 1985, §11.4; the sliding block, any dynamics text (J. L. Meriam,
|
||||
L. G. Kraige, *Engineering Mechanics: Dynamics*, §3/5).
|
||||
@@ -59,7 +59,9 @@ cargo xtask oracle --quick # skip cases marked "slow"
|
||||
"known_failure": "optional: why FieldCraft misses the reference today"}]}
|
||||
```
|
||||
A measure reads a JSON pointer either from a recipe step's output (`"from": "<id>"`) or from a
|
||||
command run after the recipe (`"command"`, `"params"`); an optional `"scale"` multiplies it.
|
||||
command run after the recipe (`"command"`, `"params"`); an optional `"scale"` multiplies it, and
|
||||
an optional `"over"` (a measure of its own) divides it by another number of the same run, for
|
||||
ratios such as the stress in one element over the stress in another.
|
||||
A tolerance is `relative` (of the reference), `absolute`, both, or `"exact": true`. A pending
|
||||
case cites its reference values (or `null` until transcribed) and has no recipe yet.
|
||||
- `fixture.json` holds each passing quantity's accepted `value` and its `band`
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Snap-through of a shallow arch by arc length
|
||||
|
||||
A shallow sinusoidal arch y₀ = a sin(πx/L), L = 100, depth 1, unit width (40 × 2 × 1 hex20,
|
||||
E = 10⁴, ν = 0), pinned at mid-depth at both ends, under a sinusoidal dead load q₀ sin(πx/L)
|
||||
applied per element on its top face, in a nonlinear static step with arc-length control. With
|
||||
a/r = 3.5 the symmetric path has two limit points and the antisymmetric mode does not bifurcate
|
||||
before them. The load is scaled to the closed form's upper limit load, so the path peaks at load
|
||||
factor 1; the step snaps through, passes the lower limit point and stops at a midspan deflection
|
||||
of 2.2 a. Measured: both limit points' load factors (from the change of the tangent's inertia)
|
||||
and the one negative eigenvalue between them.
|
||||
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"title": "Snap-through of a shallow arch by arc length",
|
||||
"kind": "theory",
|
||||
"source": "One-mode closed form of a shallow sinusoidal arch y₀ = a sin(πx/L) on pins at a fixed span under q₀ sin(πx/L): q₀ = EI k⁴ [c + (a − c)(2ac − c²)/(4r²)], k = π/L, limit points at c = a ∓ r √((a²/r² − 4)/3) (S. P. Timoshenko, J. M. Gere, Theory of Elastic Stability, 2nd ed., McGraw-Hill 1961, §7.6; Y. C. Fung, A. Kaplan, NACA TN 2840, 1952): L = 100, h = 1, unit width, E = 10⁴, ν = 0, a/r = 3.5; the load is scaled to the upper limit load, so the peak load factor is 1 and the valley 0.211035",
|
||||
"quantities": [
|
||||
{
|
||||
"id": "peak",
|
||||
"quantity": "upper limit load factor (snap-through)",
|
||||
"measure": {
|
||||
"from": "solve",
|
||||
"pointer": "/critical_points/0/load_factor"
|
||||
},
|
||||
"value": 1.0,
|
||||
"tolerance": {
|
||||
"relative": 0.02
|
||||
},
|
||||
"reason": "40 × 2 × 1 hex20 against shallow Euler–Bernoulli arch theory, the load piecewise constant per element, and the limit load picked from converged states (second order in the arc)"
|
||||
},
|
||||
{
|
||||
"id": "valley",
|
||||
"quantity": "lower limit load factor",
|
||||
"measure": {
|
||||
"from": "solve",
|
||||
"pointer": "/critical_points/1/load_factor"
|
||||
},
|
||||
"value": 0.21103504613969407,
|
||||
"tolerance": {
|
||||
"absolute": 0.02
|
||||
},
|
||||
"reason": "as the peak; the valley is a fifth of the peak load and a small difference of the bending and axial terms, so its tolerance is stated as 2 % of the peak load"
|
||||
},
|
||||
{
|
||||
"id": "negative",
|
||||
"quantity": "negative eigenvalues of the tangent past the upper limit point",
|
||||
"measure": {
|
||||
"from": "solve",
|
||||
"pointer": "/critical_points/0/negative_after"
|
||||
},
|
||||
"value": 1,
|
||||
"tolerance": {
|
||||
"exact": true
|
||||
},
|
||||
"reason": "the inertia of the LDLᵀ factor: exactly one unstable direction between the limit points"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"note": "FieldCraft's accepted results for this case, written by `cargo xtask oracle --bless`. A result outside its band fails CI.",
|
||||
"values": {
|
||||
"negative": {
|
||||
"band": 1e-9,
|
||||
"value": 1.0
|
||||
},
|
||||
"peak": {
|
||||
"band": 1e-9,
|
||||
"value": 0.9918292211513776
|
||||
},
|
||||
"valley": {
|
||||
"band": 0.000020000218947968203,
|
||||
"value": 0.21894796820214898
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,944 @@
|
||||
[
|
||||
{"command": "mesh.node.add", "params": {"label": 1, "xyz": [0.0, -0.5, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 2, "xyz": [1.25, -0.460333335905542, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 3, "xyz": [2.5, -0.42072783493202, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 4, "xyz": [3.75, -0.381244565891271, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 5, "xyz": [5.0, -0.341944409122353, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 6, "xyz": [6.25, -0.302887962618471, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 7, "xyz": [7.5, -0.264135448589265, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 8, "xyz": [8.75, -0.225746620602531, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 9, "xyz": [10.0, -0.187780671448546, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 10, "xyz": [11.25, -0.15029614186908, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 11, "xyz": [12.5, -0.11335083029181, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 12, "xyz": [13.75, -0.077001703709339, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 13, "xyz": [15.0, -0.04130480984022, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 14, "xyz": [16.25, -0.006315190707437, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 15, "xyz": [17.5, 0.027913202232406, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 16, "xyz": [18.75, 0.061327591278318, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 17, "xyz": [20.0, 0.093876453864315, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 18, "xyz": [21.25, 0.125509602003477, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 19, "xyz": [22.5, 0.15617825967419, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 20, "xyz": [23.75, 0.185835138029234, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 21, "xyz": [25.0, 0.21443450831176, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 22, "xyz": [26.25, 0.241932272365715, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 23, "xyz": [27.5, 0.268286030632006, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 24, "xyz": [28.75, 0.293455147525545, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 25, "xyz": [30.0, 0.317400814092376, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 26, "xyz": [31.25, 0.340086107850269, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 27, "xyz": [32.5, 0.361476049720513, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 28, "xyz": [33.75, 0.381537657963118, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 29, "xyz": [35.0, 0.400239999032267, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 30, "xyz": [36.25, 0.417554235273605, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 31, "xyz": [37.5, 0.43345366938981, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 32, "xyz": [38.75, 0.447913785605886, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 33, "xyz": [40.0, 0.46091228747072, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 34, "xyz": [41.25, 0.472429132236587, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 35, "xyz": [42.5, 0.482446561763614, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 36, "xyz": [43.75, 0.490949129901548, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 37, "xyz": [45.0, 0.497923726306601, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 38, "xyz": [46.25, 0.503359596656643, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 39, "xyz": [47.5, 0.507248359233594, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 40, "xyz": [48.75, 0.509584017847425, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 41, "xyz": [50.0, 0.510362971081845, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 42, "xyz": [51.25, 0.509584017847425, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 43, "xyz": [52.5, 0.507248359233594, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 44, "xyz": [53.75, 0.503359596656643, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 45, "xyz": [55.0, 0.497923726306601, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 46, "xyz": [56.25, 0.490949129901548, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 47, "xyz": [57.5, 0.482446561763614, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 48, "xyz": [58.75, 0.472429132236587, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 49, "xyz": [60.0, 0.46091228747072, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 50, "xyz": [61.25, 0.447913785605886, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 51, "xyz": [62.5, 0.43345366938981, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 52, "xyz": [63.75, 0.417554235273605, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 53, "xyz": [65.0, 0.400239999032267, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 54, "xyz": [66.25, 0.381537657963118, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 55, "xyz": [67.5, 0.361476049720513, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 56, "xyz": [68.75, 0.340086107850269, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 57, "xyz": [70.0, 0.317400814092376, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 58, "xyz": [71.25, 0.293455147525545, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 59, "xyz": [72.5, 0.268286030632007, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 60, "xyz": [73.75, 0.241932272365715, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 61, "xyz": [75.0, 0.21443450831176, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 62, "xyz": [76.25, 0.185835138029234, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 63, "xyz": [77.5, 0.15617825967419, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 64, "xyz": [78.75, 0.125509602003477, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 65, "xyz": [80.0, 0.093876453864315, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 66, "xyz": [81.25, 0.061327591278319, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 67, "xyz": [82.5, 0.027913202232406, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 68, "xyz": [83.75, -0.006315190707437, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 69, "xyz": [85.0, -0.04130480984022, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 70, "xyz": [86.25, -0.077001703709339, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 71, "xyz": [87.5, -0.113350830291809, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 72, "xyz": [88.75, -0.150296141869079, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 73, "xyz": [90.0, -0.187780671448546, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 74, "xyz": [91.25, -0.225746620602531, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 75, "xyz": [92.5, -0.264135448589265, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 76, "xyz": [93.75, -0.30288796261847, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 77, "xyz": [95.0, -0.341944409122353, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 78, "xyz": [96.25, -0.381244565891272, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 79, "xyz": [97.5, -0.42072783493202, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 80, "xyz": [98.75, -0.460333335905541, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 81, "xyz": [100.0, -0.5, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 82, "xyz": [0.0, -0.25, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 84, "xyz": [2.5, -0.17072783493202, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 86, "xyz": [5.0, -0.091944409122353, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 88, "xyz": [7.5, -0.014135448589265, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 90, "xyz": [10.0, 0.062219328551454, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 92, "xyz": [12.5, 0.13664916970819, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 94, "xyz": [15.0, 0.20869519015978, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 96, "xyz": [17.5, 0.277913202232406, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 98, "xyz": [20.0, 0.343876453864315, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 100, "xyz": [22.5, 0.40617825967419, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 102, "xyz": [25.0, 0.46443450831176, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 104, "xyz": [27.5, 0.518286030632006, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 106, "xyz": [30.0, 0.567400814092376, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 108, "xyz": [32.5, 0.611476049720513, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 110, "xyz": [35.0, 0.650239999032267, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 112, "xyz": [37.5, 0.68345366938981, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 114, "xyz": [40.0, 0.71091228747072, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 116, "xyz": [42.5, 0.732446561763614, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 118, "xyz": [45.0, 0.747923726306601, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 120, "xyz": [47.5, 0.757248359233594, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 122, "xyz": [50.0, 0.760362971081845, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 124, "xyz": [52.5, 0.757248359233594, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 126, "xyz": [55.0, 0.747923726306601, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 128, "xyz": [57.5, 0.732446561763614, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 130, "xyz": [60.0, 0.71091228747072, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 132, "xyz": [62.5, 0.68345366938981, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 134, "xyz": [65.0, 0.650239999032267, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 136, "xyz": [67.5, 0.611476049720513, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 138, "xyz": [70.0, 0.567400814092376, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 140, "xyz": [72.5, 0.518286030632007, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 142, "xyz": [75.0, 0.46443450831176, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 144, "xyz": [77.5, 0.40617825967419, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 146, "xyz": [80.0, 0.343876453864315, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 148, "xyz": [82.5, 0.277913202232406, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 150, "xyz": [85.0, 0.20869519015978, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 152, "xyz": [87.5, 0.136649169708191, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 154, "xyz": [90.0, 0.062219328551454, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 156, "xyz": [92.5, -0.014135448589265, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 158, "xyz": [95.0, -0.091944409122353, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 160, "xyz": [97.5, -0.17072783493202, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 162, "xyz": [100.0, -0.25, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 163, "xyz": [0.0, 0.0, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 164, "xyz": [1.25, 0.039666664094458, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 165, "xyz": [2.5, 0.07927216506798, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 166, "xyz": [3.75, 0.118755434108729, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 167, "xyz": [5.0, 0.158055590877647, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 168, "xyz": [6.25, 0.197112037381529, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 169, "xyz": [7.5, 0.235864551410735, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 170, "xyz": [8.75, 0.274253379397469, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 171, "xyz": [10.0, 0.312219328551454, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 172, "xyz": [11.25, 0.34970385813092, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 173, "xyz": [12.5, 0.38664916970819, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 174, "xyz": [13.75, 0.422998296290661, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 175, "xyz": [15.0, 0.45869519015978, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 176, "xyz": [16.25, 0.493684809292563, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 177, "xyz": [17.5, 0.527913202232406, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 178, "xyz": [18.75, 0.561327591278318, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 179, "xyz": [20.0, 0.593876453864315, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 180, "xyz": [21.25, 0.625509602003477, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 181, "xyz": [22.5, 0.65617825967419, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 182, "xyz": [23.75, 0.685835138029234, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 183, "xyz": [25.0, 0.71443450831176, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 184, "xyz": [26.25, 0.741932272365715, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 185, "xyz": [27.5, 0.768286030632006, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 186, "xyz": [28.75, 0.793455147525545, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 187, "xyz": [30.0, 0.817400814092376, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 188, "xyz": [31.25, 0.840086107850269, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 189, "xyz": [32.5, 0.861476049720513, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 190, "xyz": [33.75, 0.881537657963118, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 191, "xyz": [35.0, 0.900239999032267, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 192, "xyz": [36.25, 0.917554235273605, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 193, "xyz": [37.5, 0.93345366938981, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 194, "xyz": [38.75, 0.947913785605886, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 195, "xyz": [40.0, 0.96091228747072, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 196, "xyz": [41.25, 0.972429132236587, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 197, "xyz": [42.5, 0.982446561763614, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 198, "xyz": [43.75, 0.990949129901548, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 199, "xyz": [45.0, 0.997923726306601, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 200, "xyz": [46.25, 1.003359596656643, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 201, "xyz": [47.5, 1.007248359233594, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 202, "xyz": [48.75, 1.009584017847425, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 203, "xyz": [50.0, 1.010362971081845, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 204, "xyz": [51.25, 1.009584017847425, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 205, "xyz": [52.5, 1.007248359233594, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 206, "xyz": [53.75, 1.003359596656643, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 207, "xyz": [55.0, 0.997923726306601, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 208, "xyz": [56.25, 0.990949129901548, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 209, "xyz": [57.5, 0.982446561763614, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 210, "xyz": [58.75, 0.972429132236587, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 211, "xyz": [60.0, 0.96091228747072, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 212, "xyz": [61.25, 0.947913785605886, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 213, "xyz": [62.5, 0.93345366938981, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 214, "xyz": [63.75, 0.917554235273605, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 215, "xyz": [65.0, 0.900239999032267, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 216, "xyz": [66.25, 0.881537657963118, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 217, "xyz": [67.5, 0.861476049720513, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 218, "xyz": [68.75, 0.840086107850269, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 219, "xyz": [70.0, 0.817400814092376, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 220, "xyz": [71.25, 0.793455147525545, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 221, "xyz": [72.5, 0.768286030632007, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 222, "xyz": [73.75, 0.741932272365715, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 223, "xyz": [75.0, 0.71443450831176, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 224, "xyz": [76.25, 0.685835138029234, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 225, "xyz": [77.5, 0.65617825967419, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 226, "xyz": [78.75, 0.625509602003477, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 227, "xyz": [80.0, 0.593876453864315, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 228, "xyz": [81.25, 0.561327591278319, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 229, "xyz": [82.5, 0.527913202232406, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 230, "xyz": [83.75, 0.493684809292563, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 231, "xyz": [85.0, 0.45869519015978, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 232, "xyz": [86.25, 0.422998296290661, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 233, "xyz": [87.5, 0.386649169708191, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 234, "xyz": [88.75, 0.349703858130921, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 235, "xyz": [90.0, 0.312219328551454, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 236, "xyz": [91.25, 0.274253379397469, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 237, "xyz": [92.5, 0.235864551410735, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 238, "xyz": [93.75, 0.19711203738153, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 239, "xyz": [95.0, 0.158055590877647, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 240, "xyz": [96.25, 0.118755434108728, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 241, "xyz": [97.5, 0.07927216506798, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 242, "xyz": [98.75, 0.039666664094459, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 243, "xyz": [100.0, 0.0, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 244, "xyz": [0.0, 0.25, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 246, "xyz": [2.5, 0.32927216506798, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 248, "xyz": [5.0, 0.408055590877647, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 250, "xyz": [7.5, 0.485864551410735, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 252, "xyz": [10.0, 0.562219328551454, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 254, "xyz": [12.5, 0.63664916970819, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 256, "xyz": [15.0, 0.70869519015978, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 258, "xyz": [17.5, 0.777913202232406, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 260, "xyz": [20.0, 0.843876453864315, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 262, "xyz": [22.5, 0.90617825967419, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 264, "xyz": [25.0, 0.96443450831176, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 266, "xyz": [27.5, 1.018286030632007, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 268, "xyz": [30.0, 1.067400814092376, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 270, "xyz": [32.5, 1.111476049720513, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 272, "xyz": [35.0, 1.150239999032267, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 274, "xyz": [37.5, 1.183453669389809, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 276, "xyz": [40.0, 1.21091228747072, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 278, "xyz": [42.5, 1.232446561763614, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 280, "xyz": [45.0, 1.247923726306601, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 282, "xyz": [47.5, 1.257248359233594, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 284, "xyz": [50.0, 1.260362971081845, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 286, "xyz": [52.5, 1.257248359233594, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 288, "xyz": [55.0, 1.247923726306601, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 290, "xyz": [57.5, 1.232446561763614, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 292, "xyz": [60.0, 1.210912287470721, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 294, "xyz": [62.5, 1.18345366938981, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 296, "xyz": [65.0, 1.150239999032267, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 298, "xyz": [67.5, 1.111476049720513, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 300, "xyz": [70.0, 1.067400814092376, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 302, "xyz": [72.5, 1.018286030632007, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 304, "xyz": [75.0, 0.96443450831176, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 306, "xyz": [77.5, 0.90617825967419, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 308, "xyz": [80.0, 0.843876453864315, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 310, "xyz": [82.5, 0.777913202232406, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 312, "xyz": [85.0, 0.70869519015978, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 314, "xyz": [87.5, 0.636649169708191, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 316, "xyz": [90.0, 0.562219328551454, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 318, "xyz": [92.5, 0.485864551410735, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 320, "xyz": [95.0, 0.408055590877647, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 322, "xyz": [97.5, 0.32927216506798, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 324, "xyz": [100.0, 0.25, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 325, "xyz": [0.0, 0.5, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 326, "xyz": [1.25, 0.539666664094458, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 327, "xyz": [2.5, 0.57927216506798, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 328, "xyz": [3.75, 0.618755434108728, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 329, "xyz": [5.0, 0.658055590877647, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 330, "xyz": [6.25, 0.697112037381529, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 331, "xyz": [7.5, 0.735864551410735, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 332, "xyz": [8.75, 0.774253379397469, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 333, "xyz": [10.0, 0.812219328551454, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 334, "xyz": [11.25, 0.84970385813092, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 335, "xyz": [12.5, 0.88664916970819, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 336, "xyz": [13.75, 0.922998296290661, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 337, "xyz": [15.0, 0.95869519015978, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 338, "xyz": [16.25, 0.993684809292563, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 339, "xyz": [17.5, 1.027913202232406, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 340, "xyz": [18.75, 1.061327591278318, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 341, "xyz": [20.0, 1.093876453864315, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 342, "xyz": [21.25, 1.125509602003477, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 343, "xyz": [22.5, 1.15617825967419, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 344, "xyz": [23.75, 1.185835138029234, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 345, "xyz": [25.0, 1.21443450831176, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 346, "xyz": [26.25, 1.241932272365715, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 347, "xyz": [27.5, 1.268286030632007, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 348, "xyz": [28.75, 1.293455147525545, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 349, "xyz": [30.0, 1.317400814092376, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 350, "xyz": [31.25, 1.340086107850269, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 351, "xyz": [32.5, 1.361476049720513, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 352, "xyz": [33.75, 1.381537657963118, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 353, "xyz": [35.0, 1.400239999032267, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 354, "xyz": [36.25, 1.417554235273605, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 355, "xyz": [37.5, 1.433453669389809, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 356, "xyz": [38.75, 1.447913785605886, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 357, "xyz": [40.0, 1.46091228747072, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 358, "xyz": [41.25, 1.472429132236587, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 359, "xyz": [42.5, 1.482446561763614, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 360, "xyz": [43.75, 1.490949129901548, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 361, "xyz": [45.0, 1.497923726306601, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 362, "xyz": [46.25, 1.503359596656643, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 363, "xyz": [47.5, 1.507248359233594, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 364, "xyz": [48.75, 1.509584017847425, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 365, "xyz": [50.0, 1.510362971081845, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 366, "xyz": [51.25, 1.509584017847425, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 367, "xyz": [52.5, 1.507248359233594, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 368, "xyz": [53.75, 1.503359596656643, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 369, "xyz": [55.0, 1.497923726306601, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 370, "xyz": [56.25, 1.490949129901548, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 371, "xyz": [57.5, 1.482446561763614, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 372, "xyz": [58.75, 1.472429132236587, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 373, "xyz": [60.0, 1.460912287470721, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 374, "xyz": [61.25, 1.447913785605886, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 375, "xyz": [62.5, 1.43345366938981, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 376, "xyz": [63.75, 1.417554235273605, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 377, "xyz": [65.0, 1.400239999032267, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 378, "xyz": [66.25, 1.381537657963118, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 379, "xyz": [67.5, 1.361476049720513, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 380, "xyz": [68.75, 1.340086107850269, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 381, "xyz": [70.0, 1.317400814092376, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 382, "xyz": [71.25, 1.293455147525545, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 383, "xyz": [72.5, 1.268286030632007, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 384, "xyz": [73.75, 1.241932272365715, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 385, "xyz": [75.0, 1.21443450831176, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 386, "xyz": [76.25, 1.185835138029234, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 387, "xyz": [77.5, 1.15617825967419, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 388, "xyz": [78.75, 1.125509602003477, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 389, "xyz": [80.0, 1.093876453864315, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 390, "xyz": [81.25, 1.061327591278319, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 391, "xyz": [82.5, 1.027913202232406, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 392, "xyz": [83.75, 0.993684809292563, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 393, "xyz": [85.0, 0.95869519015978, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 394, "xyz": [86.25, 0.922998296290661, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 395, "xyz": [87.5, 0.886649169708191, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 396, "xyz": [88.75, 0.849703858130921, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 397, "xyz": [90.0, 0.812219328551454, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 398, "xyz": [91.25, 0.774253379397469, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 399, "xyz": [92.5, 0.735864551410735, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 400, "xyz": [93.75, 0.69711203738153, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 401, "xyz": [95.0, 0.658055590877647, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 402, "xyz": [96.25, 0.618755434108728, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 403, "xyz": [97.5, 0.57927216506798, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 404, "xyz": [98.75, 0.539666664094459, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 405, "xyz": [100.0, 0.5, 0.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 406, "xyz": [0.0, -0.5, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 408, "xyz": [2.5, -0.42072783493202, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 410, "xyz": [5.0, -0.341944409122353, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 412, "xyz": [7.5, -0.264135448589265, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 414, "xyz": [10.0, -0.187780671448546, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 416, "xyz": [12.5, -0.11335083029181, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 418, "xyz": [15.0, -0.04130480984022, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 420, "xyz": [17.5, 0.027913202232406, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 422, "xyz": [20.0, 0.093876453864315, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 424, "xyz": [22.5, 0.15617825967419, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 426, "xyz": [25.0, 0.21443450831176, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 428, "xyz": [27.5, 0.268286030632006, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 430, "xyz": [30.0, 0.317400814092376, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 432, "xyz": [32.5, 0.361476049720513, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 434, "xyz": [35.0, 0.400239999032267, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 436, "xyz": [37.5, 0.43345366938981, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 438, "xyz": [40.0, 0.46091228747072, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 440, "xyz": [42.5, 0.482446561763614, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 442, "xyz": [45.0, 0.497923726306601, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 444, "xyz": [47.5, 0.507248359233594, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 446, "xyz": [50.0, 0.510362971081845, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 448, "xyz": [52.5, 0.507248359233594, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 450, "xyz": [55.0, 0.497923726306601, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 452, "xyz": [57.5, 0.482446561763614, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 454, "xyz": [60.0, 0.46091228747072, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 456, "xyz": [62.5, 0.43345366938981, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 458, "xyz": [65.0, 0.400239999032267, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 460, "xyz": [67.5, 0.361476049720513, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 462, "xyz": [70.0, 0.317400814092376, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 464, "xyz": [72.5, 0.268286030632007, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 466, "xyz": [75.0, 0.21443450831176, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 468, "xyz": [77.5, 0.15617825967419, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 470, "xyz": [80.0, 0.093876453864315, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 472, "xyz": [82.5, 0.027913202232406, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 474, "xyz": [85.0, -0.04130480984022, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 476, "xyz": [87.5, -0.113350830291809, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 478, "xyz": [90.0, -0.187780671448546, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 480, "xyz": [92.5, -0.264135448589265, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 482, "xyz": [95.0, -0.341944409122353, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 484, "xyz": [97.5, -0.42072783493202, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 486, "xyz": [100.0, -0.5, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 568, "xyz": [0.0, 0.0, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 570, "xyz": [2.5, 0.07927216506798, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 572, "xyz": [5.0, 0.158055590877647, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 574, "xyz": [7.5, 0.235864551410735, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 576, "xyz": [10.0, 0.312219328551454, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 578, "xyz": [12.5, 0.38664916970819, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 580, "xyz": [15.0, 0.45869519015978, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 582, "xyz": [17.5, 0.527913202232406, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 584, "xyz": [20.0, 0.593876453864315, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 586, "xyz": [22.5, 0.65617825967419, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 588, "xyz": [25.0, 0.71443450831176, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 590, "xyz": [27.5, 0.768286030632006, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 592, "xyz": [30.0, 0.817400814092376, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 594, "xyz": [32.5, 0.861476049720513, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 596, "xyz": [35.0, 0.900239999032267, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 598, "xyz": [37.5, 0.93345366938981, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 600, "xyz": [40.0, 0.96091228747072, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 602, "xyz": [42.5, 0.982446561763614, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 604, "xyz": [45.0, 0.997923726306601, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 606, "xyz": [47.5, 1.007248359233594, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 608, "xyz": [50.0, 1.010362971081845, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 610, "xyz": [52.5, 1.007248359233594, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 612, "xyz": [55.0, 0.997923726306601, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 614, "xyz": [57.5, 0.982446561763614, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 616, "xyz": [60.0, 0.96091228747072, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 618, "xyz": [62.5, 0.93345366938981, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 620, "xyz": [65.0, 0.900239999032267, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 622, "xyz": [67.5, 0.861476049720513, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 624, "xyz": [70.0, 0.817400814092376, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 626, "xyz": [72.5, 0.768286030632007, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 628, "xyz": [75.0, 0.71443450831176, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 630, "xyz": [77.5, 0.65617825967419, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 632, "xyz": [80.0, 0.593876453864315, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 634, "xyz": [82.5, 0.527913202232406, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 636, "xyz": [85.0, 0.45869519015978, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 638, "xyz": [87.5, 0.386649169708191, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 640, "xyz": [90.0, 0.312219328551454, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 642, "xyz": [92.5, 0.235864551410735, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 644, "xyz": [95.0, 0.158055590877647, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 646, "xyz": [97.5, 0.07927216506798, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 648, "xyz": [100.0, 0.0, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 730, "xyz": [0.0, 0.5, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 732, "xyz": [2.5, 0.57927216506798, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 734, "xyz": [5.0, 0.658055590877647, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 736, "xyz": [7.5, 0.735864551410735, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 738, "xyz": [10.0, 0.812219328551454, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 740, "xyz": [12.5, 0.88664916970819, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 742, "xyz": [15.0, 0.95869519015978, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 744, "xyz": [17.5, 1.027913202232406, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 746, "xyz": [20.0, 1.093876453864315, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 748, "xyz": [22.5, 1.15617825967419, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 750, "xyz": [25.0, 1.21443450831176, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 752, "xyz": [27.5, 1.268286030632007, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 754, "xyz": [30.0, 1.317400814092376, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 756, "xyz": [32.5, 1.361476049720513, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 758, "xyz": [35.0, 1.400239999032267, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 760, "xyz": [37.5, 1.433453669389809, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 762, "xyz": [40.0, 1.46091228747072, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 764, "xyz": [42.5, 1.482446561763614, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 766, "xyz": [45.0, 1.497923726306601, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 768, "xyz": [47.5, 1.507248359233594, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 770, "xyz": [50.0, 1.510362971081845, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 772, "xyz": [52.5, 1.507248359233594, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 774, "xyz": [55.0, 1.497923726306601, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 776, "xyz": [57.5, 1.482446561763614, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 778, "xyz": [60.0, 1.460912287470721, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 780, "xyz": [62.5, 1.43345366938981, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 782, "xyz": [65.0, 1.400239999032267, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 784, "xyz": [67.5, 1.361476049720513, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 786, "xyz": [70.0, 1.317400814092376, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 788, "xyz": [72.5, 1.268286030632007, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 790, "xyz": [75.0, 1.21443450831176, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 792, "xyz": [77.5, 1.15617825967419, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 794, "xyz": [80.0, 1.093876453864315, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 796, "xyz": [82.5, 1.027913202232406, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 798, "xyz": [85.0, 0.95869519015978, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 800, "xyz": [87.5, 0.886649169708191, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 802, "xyz": [90.0, 0.812219328551454, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 804, "xyz": [92.5, 0.735864551410735, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 806, "xyz": [95.0, 0.658055590877647, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 808, "xyz": [97.5, 0.57927216506798, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 810, "xyz": [100.0, 0.5, 0.5]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 811, "xyz": [0.0, -0.5, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 812, "xyz": [1.25, -0.460333335905542, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 813, "xyz": [2.5, -0.42072783493202, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 814, "xyz": [3.75, -0.381244565891271, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 815, "xyz": [5.0, -0.341944409122353, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 816, "xyz": [6.25, -0.302887962618471, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 817, "xyz": [7.5, -0.264135448589265, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 818, "xyz": [8.75, -0.225746620602531, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 819, "xyz": [10.0, -0.187780671448546, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 820, "xyz": [11.25, -0.15029614186908, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 821, "xyz": [12.5, -0.11335083029181, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 822, "xyz": [13.75, -0.077001703709339, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 823, "xyz": [15.0, -0.04130480984022, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 824, "xyz": [16.25, -0.006315190707437, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 825, "xyz": [17.5, 0.027913202232406, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 826, "xyz": [18.75, 0.061327591278318, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 827, "xyz": [20.0, 0.093876453864315, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 828, "xyz": [21.25, 0.125509602003477, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 829, "xyz": [22.5, 0.15617825967419, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 830, "xyz": [23.75, 0.185835138029234, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 831, "xyz": [25.0, 0.21443450831176, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 832, "xyz": [26.25, 0.241932272365715, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 833, "xyz": [27.5, 0.268286030632006, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 834, "xyz": [28.75, 0.293455147525545, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 835, "xyz": [30.0, 0.317400814092376, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 836, "xyz": [31.25, 0.340086107850269, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 837, "xyz": [32.5, 0.361476049720513, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 838, "xyz": [33.75, 0.381537657963118, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 839, "xyz": [35.0, 0.400239999032267, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 840, "xyz": [36.25, 0.417554235273605, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 841, "xyz": [37.5, 0.43345366938981, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 842, "xyz": [38.75, 0.447913785605886, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 843, "xyz": [40.0, 0.46091228747072, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 844, "xyz": [41.25, 0.472429132236587, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 845, "xyz": [42.5, 0.482446561763614, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 846, "xyz": [43.75, 0.490949129901548, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 847, "xyz": [45.0, 0.497923726306601, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 848, "xyz": [46.25, 0.503359596656643, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 849, "xyz": [47.5, 0.507248359233594, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 850, "xyz": [48.75, 0.509584017847425, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 851, "xyz": [50.0, 0.510362971081845, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 852, "xyz": [51.25, 0.509584017847425, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 853, "xyz": [52.5, 0.507248359233594, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 854, "xyz": [53.75, 0.503359596656643, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 855, "xyz": [55.0, 0.497923726306601, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 856, "xyz": [56.25, 0.490949129901548, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 857, "xyz": [57.5, 0.482446561763614, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 858, "xyz": [58.75, 0.472429132236587, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 859, "xyz": [60.0, 0.46091228747072, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 860, "xyz": [61.25, 0.447913785605886, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 861, "xyz": [62.5, 0.43345366938981, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 862, "xyz": [63.75, 0.417554235273605, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 863, "xyz": [65.0, 0.400239999032267, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 864, "xyz": [66.25, 0.381537657963118, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 865, "xyz": [67.5, 0.361476049720513, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 866, "xyz": [68.75, 0.340086107850269, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 867, "xyz": [70.0, 0.317400814092376, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 868, "xyz": [71.25, 0.293455147525545, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 869, "xyz": [72.5, 0.268286030632007, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 870, "xyz": [73.75, 0.241932272365715, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 871, "xyz": [75.0, 0.21443450831176, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 872, "xyz": [76.25, 0.185835138029234, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 873, "xyz": [77.5, 0.15617825967419, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 874, "xyz": [78.75, 0.125509602003477, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 875, "xyz": [80.0, 0.093876453864315, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 876, "xyz": [81.25, 0.061327591278319, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 877, "xyz": [82.5, 0.027913202232406, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 878, "xyz": [83.75, -0.006315190707437, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 879, "xyz": [85.0, -0.04130480984022, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 880, "xyz": [86.25, -0.077001703709339, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 881, "xyz": [87.5, -0.113350830291809, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 882, "xyz": [88.75, -0.150296141869079, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 883, "xyz": [90.0, -0.187780671448546, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 884, "xyz": [91.25, -0.225746620602531, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 885, "xyz": [92.5, -0.264135448589265, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 886, "xyz": [93.75, -0.30288796261847, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 887, "xyz": [95.0, -0.341944409122353, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 888, "xyz": [96.25, -0.381244565891272, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 889, "xyz": [97.5, -0.42072783493202, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 890, "xyz": [98.75, -0.460333335905541, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 891, "xyz": [100.0, -0.5, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 892, "xyz": [0.0, -0.25, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 894, "xyz": [2.5, -0.17072783493202, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 896, "xyz": [5.0, -0.091944409122353, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 898, "xyz": [7.5, -0.014135448589265, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 900, "xyz": [10.0, 0.062219328551454, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 902, "xyz": [12.5, 0.13664916970819, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 904, "xyz": [15.0, 0.20869519015978, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 906, "xyz": [17.5, 0.277913202232406, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 908, "xyz": [20.0, 0.343876453864315, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 910, "xyz": [22.5, 0.40617825967419, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 912, "xyz": [25.0, 0.46443450831176, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 914, "xyz": [27.5, 0.518286030632006, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 916, "xyz": [30.0, 0.567400814092376, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 918, "xyz": [32.5, 0.611476049720513, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 920, "xyz": [35.0, 0.650239999032267, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 922, "xyz": [37.5, 0.68345366938981, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 924, "xyz": [40.0, 0.71091228747072, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 926, "xyz": [42.5, 0.732446561763614, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 928, "xyz": [45.0, 0.747923726306601, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 930, "xyz": [47.5, 0.757248359233594, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 932, "xyz": [50.0, 0.760362971081845, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 934, "xyz": [52.5, 0.757248359233594, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 936, "xyz": [55.0, 0.747923726306601, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 938, "xyz": [57.5, 0.732446561763614, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 940, "xyz": [60.0, 0.71091228747072, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 942, "xyz": [62.5, 0.68345366938981, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 944, "xyz": [65.0, 0.650239999032267, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 946, "xyz": [67.5, 0.611476049720513, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 948, "xyz": [70.0, 0.567400814092376, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 950, "xyz": [72.5, 0.518286030632007, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 952, "xyz": [75.0, 0.46443450831176, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 954, "xyz": [77.5, 0.40617825967419, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 956, "xyz": [80.0, 0.343876453864315, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 958, "xyz": [82.5, 0.277913202232406, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 960, "xyz": [85.0, 0.20869519015978, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 962, "xyz": [87.5, 0.136649169708191, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 964, "xyz": [90.0, 0.062219328551454, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 966, "xyz": [92.5, -0.014135448589265, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 968, "xyz": [95.0, -0.091944409122353, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 970, "xyz": [97.5, -0.17072783493202, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 972, "xyz": [100.0, -0.25, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 973, "xyz": [0.0, 0.0, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 974, "xyz": [1.25, 0.039666664094458, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 975, "xyz": [2.5, 0.07927216506798, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 976, "xyz": [3.75, 0.118755434108729, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 977, "xyz": [5.0, 0.158055590877647, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 978, "xyz": [6.25, 0.197112037381529, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 979, "xyz": [7.5, 0.235864551410735, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 980, "xyz": [8.75, 0.274253379397469, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 981, "xyz": [10.0, 0.312219328551454, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 982, "xyz": [11.25, 0.34970385813092, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 983, "xyz": [12.5, 0.38664916970819, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 984, "xyz": [13.75, 0.422998296290661, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 985, "xyz": [15.0, 0.45869519015978, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 986, "xyz": [16.25, 0.493684809292563, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 987, "xyz": [17.5, 0.527913202232406, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 988, "xyz": [18.75, 0.561327591278318, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 989, "xyz": [20.0, 0.593876453864315, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 990, "xyz": [21.25, 0.625509602003477, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 991, "xyz": [22.5, 0.65617825967419, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 992, "xyz": [23.75, 0.685835138029234, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 993, "xyz": [25.0, 0.71443450831176, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 994, "xyz": [26.25, 0.741932272365715, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 995, "xyz": [27.5, 0.768286030632006, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 996, "xyz": [28.75, 0.793455147525545, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 997, "xyz": [30.0, 0.817400814092376, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 998, "xyz": [31.25, 0.840086107850269, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 999, "xyz": [32.5, 0.861476049720513, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1000, "xyz": [33.75, 0.881537657963118, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1001, "xyz": [35.0, 0.900239999032267, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1002, "xyz": [36.25, 0.917554235273605, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1003, "xyz": [37.5, 0.93345366938981, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1004, "xyz": [38.75, 0.947913785605886, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1005, "xyz": [40.0, 0.96091228747072, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1006, "xyz": [41.25, 0.972429132236587, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1007, "xyz": [42.5, 0.982446561763614, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1008, "xyz": [43.75, 0.990949129901548, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1009, "xyz": [45.0, 0.997923726306601, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1010, "xyz": [46.25, 1.003359596656643, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1011, "xyz": [47.5, 1.007248359233594, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1012, "xyz": [48.75, 1.009584017847425, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1013, "xyz": [50.0, 1.010362971081845, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1014, "xyz": [51.25, 1.009584017847425, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1015, "xyz": [52.5, 1.007248359233594, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1016, "xyz": [53.75, 1.003359596656643, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1017, "xyz": [55.0, 0.997923726306601, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1018, "xyz": [56.25, 0.990949129901548, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1019, "xyz": [57.5, 0.982446561763614, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1020, "xyz": [58.75, 0.972429132236587, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1021, "xyz": [60.0, 0.96091228747072, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1022, "xyz": [61.25, 0.947913785605886, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1023, "xyz": [62.5, 0.93345366938981, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1024, "xyz": [63.75, 0.917554235273605, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1025, "xyz": [65.0, 0.900239999032267, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1026, "xyz": [66.25, 0.881537657963118, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1027, "xyz": [67.5, 0.861476049720513, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1028, "xyz": [68.75, 0.840086107850269, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1029, "xyz": [70.0, 0.817400814092376, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1030, "xyz": [71.25, 0.793455147525545, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1031, "xyz": [72.5, 0.768286030632007, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1032, "xyz": [73.75, 0.741932272365715, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1033, "xyz": [75.0, 0.71443450831176, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1034, "xyz": [76.25, 0.685835138029234, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1035, "xyz": [77.5, 0.65617825967419, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1036, "xyz": [78.75, 0.625509602003477, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1037, "xyz": [80.0, 0.593876453864315, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1038, "xyz": [81.25, 0.561327591278319, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1039, "xyz": [82.5, 0.527913202232406, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1040, "xyz": [83.75, 0.493684809292563, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1041, "xyz": [85.0, 0.45869519015978, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1042, "xyz": [86.25, 0.422998296290661, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1043, "xyz": [87.5, 0.386649169708191, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1044, "xyz": [88.75, 0.349703858130921, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1045, "xyz": [90.0, 0.312219328551454, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1046, "xyz": [91.25, 0.274253379397469, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1047, "xyz": [92.5, 0.235864551410735, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1048, "xyz": [93.75, 0.19711203738153, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1049, "xyz": [95.0, 0.158055590877647, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1050, "xyz": [96.25, 0.118755434108728, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1051, "xyz": [97.5, 0.07927216506798, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1052, "xyz": [98.75, 0.039666664094459, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1053, "xyz": [100.0, 0.0, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1054, "xyz": [0.0, 0.25, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1056, "xyz": [2.5, 0.32927216506798, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1058, "xyz": [5.0, 0.408055590877647, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1060, "xyz": [7.5, 0.485864551410735, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1062, "xyz": [10.0, 0.562219328551454, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1064, "xyz": [12.5, 0.63664916970819, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1066, "xyz": [15.0, 0.70869519015978, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1068, "xyz": [17.5, 0.777913202232406, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1070, "xyz": [20.0, 0.843876453864315, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1072, "xyz": [22.5, 0.90617825967419, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1074, "xyz": [25.0, 0.96443450831176, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1076, "xyz": [27.5, 1.018286030632007, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1078, "xyz": [30.0, 1.067400814092376, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1080, "xyz": [32.5, 1.111476049720513, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1082, "xyz": [35.0, 1.150239999032267, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1084, "xyz": [37.5, 1.183453669389809, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1086, "xyz": [40.0, 1.21091228747072, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1088, "xyz": [42.5, 1.232446561763614, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1090, "xyz": [45.0, 1.247923726306601, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1092, "xyz": [47.5, 1.257248359233594, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1094, "xyz": [50.0, 1.260362971081845, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1096, "xyz": [52.5, 1.257248359233594, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1098, "xyz": [55.0, 1.247923726306601, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1100, "xyz": [57.5, 1.232446561763614, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1102, "xyz": [60.0, 1.210912287470721, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1104, "xyz": [62.5, 1.18345366938981, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1106, "xyz": [65.0, 1.150239999032267, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1108, "xyz": [67.5, 1.111476049720513, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1110, "xyz": [70.0, 1.067400814092376, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1112, "xyz": [72.5, 1.018286030632007, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1114, "xyz": [75.0, 0.96443450831176, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1116, "xyz": [77.5, 0.90617825967419, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1118, "xyz": [80.0, 0.843876453864315, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1120, "xyz": [82.5, 0.777913202232406, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1122, "xyz": [85.0, 0.70869519015978, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1124, "xyz": [87.5, 0.636649169708191, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1126, "xyz": [90.0, 0.562219328551454, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1128, "xyz": [92.5, 0.485864551410735, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1130, "xyz": [95.0, 0.408055590877647, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1132, "xyz": [97.5, 0.32927216506798, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1134, "xyz": [100.0, 0.25, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1135, "xyz": [0.0, 0.5, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1136, "xyz": [1.25, 0.539666664094458, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1137, "xyz": [2.5, 0.57927216506798, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1138, "xyz": [3.75, 0.618755434108728, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1139, "xyz": [5.0, 0.658055590877647, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1140, "xyz": [6.25, 0.697112037381529, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1141, "xyz": [7.5, 0.735864551410735, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1142, "xyz": [8.75, 0.774253379397469, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1143, "xyz": [10.0, 0.812219328551454, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1144, "xyz": [11.25, 0.84970385813092, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1145, "xyz": [12.5, 0.88664916970819, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1146, "xyz": [13.75, 0.922998296290661, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1147, "xyz": [15.0, 0.95869519015978, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1148, "xyz": [16.25, 0.993684809292563, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1149, "xyz": [17.5, 1.027913202232406, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1150, "xyz": [18.75, 1.061327591278318, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1151, "xyz": [20.0, 1.093876453864315, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1152, "xyz": [21.25, 1.125509602003477, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1153, "xyz": [22.5, 1.15617825967419, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1154, "xyz": [23.75, 1.185835138029234, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1155, "xyz": [25.0, 1.21443450831176, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1156, "xyz": [26.25, 1.241932272365715, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1157, "xyz": [27.5, 1.268286030632007, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1158, "xyz": [28.75, 1.293455147525545, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1159, "xyz": [30.0, 1.317400814092376, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1160, "xyz": [31.25, 1.340086107850269, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1161, "xyz": [32.5, 1.361476049720513, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1162, "xyz": [33.75, 1.381537657963118, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1163, "xyz": [35.0, 1.400239999032267, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1164, "xyz": [36.25, 1.417554235273605, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1165, "xyz": [37.5, 1.433453669389809, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1166, "xyz": [38.75, 1.447913785605886, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1167, "xyz": [40.0, 1.46091228747072, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1168, "xyz": [41.25, 1.472429132236587, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1169, "xyz": [42.5, 1.482446561763614, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1170, "xyz": [43.75, 1.490949129901548, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1171, "xyz": [45.0, 1.497923726306601, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1172, "xyz": [46.25, 1.503359596656643, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1173, "xyz": [47.5, 1.507248359233594, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1174, "xyz": [48.75, 1.509584017847425, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1175, "xyz": [50.0, 1.510362971081845, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1176, "xyz": [51.25, 1.509584017847425, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1177, "xyz": [52.5, 1.507248359233594, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1178, "xyz": [53.75, 1.503359596656643, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1179, "xyz": [55.0, 1.497923726306601, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1180, "xyz": [56.25, 1.490949129901548, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1181, "xyz": [57.5, 1.482446561763614, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1182, "xyz": [58.75, 1.472429132236587, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1183, "xyz": [60.0, 1.460912287470721, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1184, "xyz": [61.25, 1.447913785605886, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1185, "xyz": [62.5, 1.43345366938981, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1186, "xyz": [63.75, 1.417554235273605, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1187, "xyz": [65.0, 1.400239999032267, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1188, "xyz": [66.25, 1.381537657963118, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1189, "xyz": [67.5, 1.361476049720513, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1190, "xyz": [68.75, 1.340086107850269, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1191, "xyz": [70.0, 1.317400814092376, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1192, "xyz": [71.25, 1.293455147525545, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1193, "xyz": [72.5, 1.268286030632007, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1194, "xyz": [73.75, 1.241932272365715, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1195, "xyz": [75.0, 1.21443450831176, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1196, "xyz": [76.25, 1.185835138029234, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1197, "xyz": [77.5, 1.15617825967419, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1198, "xyz": [78.75, 1.125509602003477, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1199, "xyz": [80.0, 1.093876453864315, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1200, "xyz": [81.25, 1.061327591278319, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1201, "xyz": [82.5, 1.027913202232406, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1202, "xyz": [83.75, 0.993684809292563, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1203, "xyz": [85.0, 0.95869519015978, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1204, "xyz": [86.25, 0.922998296290661, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1205, "xyz": [87.5, 0.886649169708191, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1206, "xyz": [88.75, 0.849703858130921, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1207, "xyz": [90.0, 0.812219328551454, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1208, "xyz": [91.25, 0.774253379397469, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1209, "xyz": [92.5, 0.735864551410735, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1210, "xyz": [93.75, 0.69711203738153, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1211, "xyz": [95.0, 0.658055590877647, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1212, "xyz": [96.25, 0.618755434108728, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1213, "xyz": [97.5, 0.57927216506798, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1214, "xyz": [98.75, 0.539666664094459, 1.0]}},
|
||||
{"command": "mesh.node.add", "params": {"label": 1215, "xyz": [100.0, 0.5, 1.0]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 1, "kind": "hex20", "nodes": [1, 3, 165, 163, 811, 813, 975, 973, 2, 84, 164, 82, 812, 894, 974, 892, 406, 408, 570, 568]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 2, "kind": "hex20", "nodes": [3, 5, 167, 165, 813, 815, 977, 975, 4, 86, 166, 84, 814, 896, 976, 894, 408, 410, 572, 570]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 3, "kind": "hex20", "nodes": [5, 7, 169, 167, 815, 817, 979, 977, 6, 88, 168, 86, 816, 898, 978, 896, 410, 412, 574, 572]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 4, "kind": "hex20", "nodes": [7, 9, 171, 169, 817, 819, 981, 979, 8, 90, 170, 88, 818, 900, 980, 898, 412, 414, 576, 574]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 5, "kind": "hex20", "nodes": [9, 11, 173, 171, 819, 821, 983, 981, 10, 92, 172, 90, 820, 902, 982, 900, 414, 416, 578, 576]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 6, "kind": "hex20", "nodes": [11, 13, 175, 173, 821, 823, 985, 983, 12, 94, 174, 92, 822, 904, 984, 902, 416, 418, 580, 578]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 7, "kind": "hex20", "nodes": [13, 15, 177, 175, 823, 825, 987, 985, 14, 96, 176, 94, 824, 906, 986, 904, 418, 420, 582, 580]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 8, "kind": "hex20", "nodes": [15, 17, 179, 177, 825, 827, 989, 987, 16, 98, 178, 96, 826, 908, 988, 906, 420, 422, 584, 582]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 9, "kind": "hex20", "nodes": [17, 19, 181, 179, 827, 829, 991, 989, 18, 100, 180, 98, 828, 910, 990, 908, 422, 424, 586, 584]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 10, "kind": "hex20", "nodes": [19, 21, 183, 181, 829, 831, 993, 991, 20, 102, 182, 100, 830, 912, 992, 910, 424, 426, 588, 586]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 11, "kind": "hex20", "nodes": [21, 23, 185, 183, 831, 833, 995, 993, 22, 104, 184, 102, 832, 914, 994, 912, 426, 428, 590, 588]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 12, "kind": "hex20", "nodes": [23, 25, 187, 185, 833, 835, 997, 995, 24, 106, 186, 104, 834, 916, 996, 914, 428, 430, 592, 590]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 13, "kind": "hex20", "nodes": [25, 27, 189, 187, 835, 837, 999, 997, 26, 108, 188, 106, 836, 918, 998, 916, 430, 432, 594, 592]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 14, "kind": "hex20", "nodes": [27, 29, 191, 189, 837, 839, 1001, 999, 28, 110, 190, 108, 838, 920, 1000, 918, 432, 434, 596, 594]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 15, "kind": "hex20", "nodes": [29, 31, 193, 191, 839, 841, 1003, 1001, 30, 112, 192, 110, 840, 922, 1002, 920, 434, 436, 598, 596]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 16, "kind": "hex20", "nodes": [31, 33, 195, 193, 841, 843, 1005, 1003, 32, 114, 194, 112, 842, 924, 1004, 922, 436, 438, 600, 598]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 17, "kind": "hex20", "nodes": [33, 35, 197, 195, 843, 845, 1007, 1005, 34, 116, 196, 114, 844, 926, 1006, 924, 438, 440, 602, 600]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 18, "kind": "hex20", "nodes": [35, 37, 199, 197, 845, 847, 1009, 1007, 36, 118, 198, 116, 846, 928, 1008, 926, 440, 442, 604, 602]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 19, "kind": "hex20", "nodes": [37, 39, 201, 199, 847, 849, 1011, 1009, 38, 120, 200, 118, 848, 930, 1010, 928, 442, 444, 606, 604]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 20, "kind": "hex20", "nodes": [39, 41, 203, 201, 849, 851, 1013, 1011, 40, 122, 202, 120, 850, 932, 1012, 930, 444, 446, 608, 606]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 21, "kind": "hex20", "nodes": [41, 43, 205, 203, 851, 853, 1015, 1013, 42, 124, 204, 122, 852, 934, 1014, 932, 446, 448, 610, 608]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 22, "kind": "hex20", "nodes": [43, 45, 207, 205, 853, 855, 1017, 1015, 44, 126, 206, 124, 854, 936, 1016, 934, 448, 450, 612, 610]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 23, "kind": "hex20", "nodes": [45, 47, 209, 207, 855, 857, 1019, 1017, 46, 128, 208, 126, 856, 938, 1018, 936, 450, 452, 614, 612]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 24, "kind": "hex20", "nodes": [47, 49, 211, 209, 857, 859, 1021, 1019, 48, 130, 210, 128, 858, 940, 1020, 938, 452, 454, 616, 614]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 25, "kind": "hex20", "nodes": [49, 51, 213, 211, 859, 861, 1023, 1021, 50, 132, 212, 130, 860, 942, 1022, 940, 454, 456, 618, 616]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 26, "kind": "hex20", "nodes": [51, 53, 215, 213, 861, 863, 1025, 1023, 52, 134, 214, 132, 862, 944, 1024, 942, 456, 458, 620, 618]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 27, "kind": "hex20", "nodes": [53, 55, 217, 215, 863, 865, 1027, 1025, 54, 136, 216, 134, 864, 946, 1026, 944, 458, 460, 622, 620]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 28, "kind": "hex20", "nodes": [55, 57, 219, 217, 865, 867, 1029, 1027, 56, 138, 218, 136, 866, 948, 1028, 946, 460, 462, 624, 622]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 29, "kind": "hex20", "nodes": [57, 59, 221, 219, 867, 869, 1031, 1029, 58, 140, 220, 138, 868, 950, 1030, 948, 462, 464, 626, 624]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 30, "kind": "hex20", "nodes": [59, 61, 223, 221, 869, 871, 1033, 1031, 60, 142, 222, 140, 870, 952, 1032, 950, 464, 466, 628, 626]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 31, "kind": "hex20", "nodes": [61, 63, 225, 223, 871, 873, 1035, 1033, 62, 144, 224, 142, 872, 954, 1034, 952, 466, 468, 630, 628]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 32, "kind": "hex20", "nodes": [63, 65, 227, 225, 873, 875, 1037, 1035, 64, 146, 226, 144, 874, 956, 1036, 954, 468, 470, 632, 630]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 33, "kind": "hex20", "nodes": [65, 67, 229, 227, 875, 877, 1039, 1037, 66, 148, 228, 146, 876, 958, 1038, 956, 470, 472, 634, 632]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 34, "kind": "hex20", "nodes": [67, 69, 231, 229, 877, 879, 1041, 1039, 68, 150, 230, 148, 878, 960, 1040, 958, 472, 474, 636, 634]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 35, "kind": "hex20", "nodes": [69, 71, 233, 231, 879, 881, 1043, 1041, 70, 152, 232, 150, 880, 962, 1042, 960, 474, 476, 638, 636]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 36, "kind": "hex20", "nodes": [71, 73, 235, 233, 881, 883, 1045, 1043, 72, 154, 234, 152, 882, 964, 1044, 962, 476, 478, 640, 638]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 37, "kind": "hex20", "nodes": [73, 75, 237, 235, 883, 885, 1047, 1045, 74, 156, 236, 154, 884, 966, 1046, 964, 478, 480, 642, 640]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 38, "kind": "hex20", "nodes": [75, 77, 239, 237, 885, 887, 1049, 1047, 76, 158, 238, 156, 886, 968, 1048, 966, 480, 482, 644, 642]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 39, "kind": "hex20", "nodes": [77, 79, 241, 239, 887, 889, 1051, 1049, 78, 160, 240, 158, 888, 970, 1050, 968, 482, 484, 646, 644]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 40, "kind": "hex20", "nodes": [79, 81, 243, 241, 889, 891, 1053, 1051, 80, 162, 242, 160, 890, 972, 1052, 970, 484, 486, 648, 646]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 41, "kind": "hex20", "nodes": [163, 165, 327, 325, 973, 975, 1137, 1135, 164, 246, 326, 244, 974, 1056, 1136, 1054, 568, 570, 732, 730]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 42, "kind": "hex20", "nodes": [165, 167, 329, 327, 975, 977, 1139, 1137, 166, 248, 328, 246, 976, 1058, 1138, 1056, 570, 572, 734, 732]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 43, "kind": "hex20", "nodes": [167, 169, 331, 329, 977, 979, 1141, 1139, 168, 250, 330, 248, 978, 1060, 1140, 1058, 572, 574, 736, 734]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 44, "kind": "hex20", "nodes": [169, 171, 333, 331, 979, 981, 1143, 1141, 170, 252, 332, 250, 980, 1062, 1142, 1060, 574, 576, 738, 736]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 45, "kind": "hex20", "nodes": [171, 173, 335, 333, 981, 983, 1145, 1143, 172, 254, 334, 252, 982, 1064, 1144, 1062, 576, 578, 740, 738]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 46, "kind": "hex20", "nodes": [173, 175, 337, 335, 983, 985, 1147, 1145, 174, 256, 336, 254, 984, 1066, 1146, 1064, 578, 580, 742, 740]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 47, "kind": "hex20", "nodes": [175, 177, 339, 337, 985, 987, 1149, 1147, 176, 258, 338, 256, 986, 1068, 1148, 1066, 580, 582, 744, 742]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 48, "kind": "hex20", "nodes": [177, 179, 341, 339, 987, 989, 1151, 1149, 178, 260, 340, 258, 988, 1070, 1150, 1068, 582, 584, 746, 744]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 49, "kind": "hex20", "nodes": [179, 181, 343, 341, 989, 991, 1153, 1151, 180, 262, 342, 260, 990, 1072, 1152, 1070, 584, 586, 748, 746]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 50, "kind": "hex20", "nodes": [181, 183, 345, 343, 991, 993, 1155, 1153, 182, 264, 344, 262, 992, 1074, 1154, 1072, 586, 588, 750, 748]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 51, "kind": "hex20", "nodes": [183, 185, 347, 345, 993, 995, 1157, 1155, 184, 266, 346, 264, 994, 1076, 1156, 1074, 588, 590, 752, 750]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 52, "kind": "hex20", "nodes": [185, 187, 349, 347, 995, 997, 1159, 1157, 186, 268, 348, 266, 996, 1078, 1158, 1076, 590, 592, 754, 752]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 53, "kind": "hex20", "nodes": [187, 189, 351, 349, 997, 999, 1161, 1159, 188, 270, 350, 268, 998, 1080, 1160, 1078, 592, 594, 756, 754]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 54, "kind": "hex20", "nodes": [189, 191, 353, 351, 999, 1001, 1163, 1161, 190, 272, 352, 270, 1000, 1082, 1162, 1080, 594, 596, 758, 756]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 55, "kind": "hex20", "nodes": [191, 193, 355, 353, 1001, 1003, 1165, 1163, 192, 274, 354, 272, 1002, 1084, 1164, 1082, 596, 598, 760, 758]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 56, "kind": "hex20", "nodes": [193, 195, 357, 355, 1003, 1005, 1167, 1165, 194, 276, 356, 274, 1004, 1086, 1166, 1084, 598, 600, 762, 760]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 57, "kind": "hex20", "nodes": [195, 197, 359, 357, 1005, 1007, 1169, 1167, 196, 278, 358, 276, 1006, 1088, 1168, 1086, 600, 602, 764, 762]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 58, "kind": "hex20", "nodes": [197, 199, 361, 359, 1007, 1009, 1171, 1169, 198, 280, 360, 278, 1008, 1090, 1170, 1088, 602, 604, 766, 764]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 59, "kind": "hex20", "nodes": [199, 201, 363, 361, 1009, 1011, 1173, 1171, 200, 282, 362, 280, 1010, 1092, 1172, 1090, 604, 606, 768, 766]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 60, "kind": "hex20", "nodes": [201, 203, 365, 363, 1011, 1013, 1175, 1173, 202, 284, 364, 282, 1012, 1094, 1174, 1092, 606, 608, 770, 768]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 61, "kind": "hex20", "nodes": [203, 205, 367, 365, 1013, 1015, 1177, 1175, 204, 286, 366, 284, 1014, 1096, 1176, 1094, 608, 610, 772, 770]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 62, "kind": "hex20", "nodes": [205, 207, 369, 367, 1015, 1017, 1179, 1177, 206, 288, 368, 286, 1016, 1098, 1178, 1096, 610, 612, 774, 772]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 63, "kind": "hex20", "nodes": [207, 209, 371, 369, 1017, 1019, 1181, 1179, 208, 290, 370, 288, 1018, 1100, 1180, 1098, 612, 614, 776, 774]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 64, "kind": "hex20", "nodes": [209, 211, 373, 371, 1019, 1021, 1183, 1181, 210, 292, 372, 290, 1020, 1102, 1182, 1100, 614, 616, 778, 776]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 65, "kind": "hex20", "nodes": [211, 213, 375, 373, 1021, 1023, 1185, 1183, 212, 294, 374, 292, 1022, 1104, 1184, 1102, 616, 618, 780, 778]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 66, "kind": "hex20", "nodes": [213, 215, 377, 375, 1023, 1025, 1187, 1185, 214, 296, 376, 294, 1024, 1106, 1186, 1104, 618, 620, 782, 780]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 67, "kind": "hex20", "nodes": [215, 217, 379, 377, 1025, 1027, 1189, 1187, 216, 298, 378, 296, 1026, 1108, 1188, 1106, 620, 622, 784, 782]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 68, "kind": "hex20", "nodes": [217, 219, 381, 379, 1027, 1029, 1191, 1189, 218, 300, 380, 298, 1028, 1110, 1190, 1108, 622, 624, 786, 784]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 69, "kind": "hex20", "nodes": [219, 221, 383, 381, 1029, 1031, 1193, 1191, 220, 302, 382, 300, 1030, 1112, 1192, 1110, 624, 626, 788, 786]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 70, "kind": "hex20", "nodes": [221, 223, 385, 383, 1031, 1033, 1195, 1193, 222, 304, 384, 302, 1032, 1114, 1194, 1112, 626, 628, 790, 788]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 71, "kind": "hex20", "nodes": [223, 225, 387, 385, 1033, 1035, 1197, 1195, 224, 306, 386, 304, 1034, 1116, 1196, 1114, 628, 630, 792, 790]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 72, "kind": "hex20", "nodes": [225, 227, 389, 387, 1035, 1037, 1199, 1197, 226, 308, 388, 306, 1036, 1118, 1198, 1116, 630, 632, 794, 792]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 73, "kind": "hex20", "nodes": [227, 229, 391, 389, 1037, 1039, 1201, 1199, 228, 310, 390, 308, 1038, 1120, 1200, 1118, 632, 634, 796, 794]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 74, "kind": "hex20", "nodes": [229, 231, 393, 391, 1039, 1041, 1203, 1201, 230, 312, 392, 310, 1040, 1122, 1202, 1120, 634, 636, 798, 796]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 75, "kind": "hex20", "nodes": [231, 233, 395, 393, 1041, 1043, 1205, 1203, 232, 314, 394, 312, 1042, 1124, 1204, 1122, 636, 638, 800, 798]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 76, "kind": "hex20", "nodes": [233, 235, 397, 395, 1043, 1045, 1207, 1205, 234, 316, 396, 314, 1044, 1126, 1206, 1124, 638, 640, 802, 800]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 77, "kind": "hex20", "nodes": [235, 237, 399, 397, 1045, 1047, 1209, 1207, 236, 318, 398, 316, 1046, 1128, 1208, 1126, 640, 642, 804, 802]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 78, "kind": "hex20", "nodes": [237, 239, 401, 399, 1047, 1049, 1211, 1209, 238, 320, 400, 318, 1048, 1130, 1210, 1128, 642, 644, 806, 804]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 79, "kind": "hex20", "nodes": [239, 241, 403, 401, 1049, 1051, 1213, 1211, 240, 322, 402, 320, 1050, 1132, 1212, 1130, 644, 646, 808, 806]}},
|
||||
{"command": "mesh.element.add", "params": {"label": 80, "kind": "hex20", "nodes": [241, 243, 405, 403, 1051, 1053, 1215, 1213, 242, 324, 404, 322, 1052, 1134, 1214, 1132, 646, 648, 810, 808]}},
|
||||
{"command": "model.set.create", "params": {"name": "all", "elements": [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]}},
|
||||
{"command": "model.set.create", "params": {"name": "pins", "nodes": [163, 568, 973, 243, 648, 1053]}},
|
||||
{"command": "model.set.create", "params": {"name": "width", "nodes": [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, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160, 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, 246, 248, 250, 252, 254, 256, 258, 260, 262, 264, 266, 268, 270, 272, 274, 276, 278, 280, 282, 284, 286, 288, 290, 292, 294, 296, 298, 300, 302, 304, 306, 308, 310, 312, 314, 316, 318, 320, 322, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 408, 410, 412, 414, 416, 418, 420, 422, 424, 426, 428, 430, 432, 434, 436, 438, 440, 442, 444, 446, 448, 450, 452, 454, 456, 458, 460, 462, 464, 466, 468, 470, 472, 474, 476, 478, 480, 482, 484, 486, 568, 570, 572, 574, 576, 578, 580, 582, 584, 586, 588, 590, 592, 594, 596, 598, 600, 602, 604, 606, 608, 610, 612, 614, 616, 618, 620, 622, 624, 626, 628, 630, 632, 634, 636, 638, 640, 642, 644, 646, 648, 730, 732, 734, 736, 738, 740, 742, 744, 746, 748, 750, 752, 754, 756, 758, 760, 762, 764, 766, 768, 770, 772, 774, 776, 778, 780, 782, 784, 786, 788, 790, 792, 794, 796, 798, 800, 802, 804, 806, 808, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847, 848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 894, 896, 898, 900, 902, 904, 906, 908, 910, 912, 914, 916, 918, 920, 922, 924, 926, 928, 930, 932, 934, 936, 938, 940, 942, 944, 946, 948, 950, 952, 954, 956, 958, 960, 962, 964, 966, 968, 970, 972, 973, 974, 975, 976, 977, 978, 979, 980, 981, 982, 983, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 996, 997, 998, 999, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1056, 1058, 1060, 1062, 1064, 1066, 1068, 1070, 1072, 1074, 1076, 1078, 1080, 1082, 1084, 1086, 1088, 1090, 1092, 1094, 1096, 1098, 1100, 1102, 1104, 1106, 1108, 1110, 1112, 1114, 1116, 1118, 1120, 1122, 1124, 1126, 1128, 1130, 1132, 1134, 1135, 1136, 1137, 1138, 1139, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1147, 1148, 1149, 1150, 1151, 1152, 1153, 1154, 1155, 1156, 1157, 1158, 1159, 1160, 1161, 1162, 1163, 1164, 1165, 1166, 1167, 1168, 1169, 1170, 1171, 1172, 1173, 1174, 1175, 1176, 1177, 1178, 1179, 1180, 1181, 1182, 1183, 1184, 1185, 1186, 1187, 1188, 1189, 1190, 1191, 1192, 1193, 1194, 1195, 1196, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1204, 1205, 1206, 1207, 1208, 1209, 1210, 1211, 1212, 1213, 1214, 1215]}},
|
||||
{"command": "model.material.create", "params": {"name": "Mat", "elastic": {"type": "isotropic", "young": 10000.0, "poisson": 0.0}}},
|
||||
{"command": "model.section.create", "params": {"name": "arch", "set": "all", "material": "Mat", "kind": {"type": "solid"}}},
|
||||
{"command": "model.boundary_condition.create", "params": {"name": "pins", "type": "displacement", "target": {"set": "pins"}, "values": [0.0, 0.0, null, null, null, null]}},
|
||||
{"command": "model.boundary_condition.create", "params": {"name": "width", "type": "displacement", "target": {"set": "width"}, "values": [null, null, 0.0, null, null, null]}},
|
||||
{"command": "model.set.create", "params": {"name": "q41", "faces": [{"element": 41, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q41", "type": "force", "target": {"set": "q41"}, "vector": [0.0, -0.0001329404719441191, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q42", "faces": [{"element": 42, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q42", "type": "force", "target": {"set": "q42"}, "vector": [0.0, -0.0003980017936156289, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q43", "faces": [{"element": 43, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q43", "type": "force", "target": {"set": "q43"}, "vector": [0.0, -0.0006606093018804717, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q44", "faces": [{"element": 44, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q44", "type": "force", "target": {"set": "q44"}, "vector": [0.0, -0.0009191439341243371, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q45", "faces": [{"element": 45, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q45", "type": "force", "target": {"set": "q45"}, "vector": [0.0, -0.001172011738367952, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q46", "faces": [{"element": 46, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q46", "type": "force", "target": {"set": "q46"}, "vector": [0.0, -0.0014176537005110772, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q47", "faces": [{"element": 47, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q47", "type": "force", "target": {"set": "q47"}, "vector": [0.0, -0.0016545553561728588, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q48", "faces": [{"element": 48, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q48", "type": "force", "target": {"set": "q48"}, "vector": [0.0, -0.0018812561278683474, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q49", "faces": [{"element": 49, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q49", "type": "force", "target": {"set": "q49"}, "vector": [0.0, -0.0020963583299543837, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q50", "faces": [{"element": 50, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q50", "type": "force", "target": {"set": "q50"}, "vector": [0.0, -0.0022985357858263675, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q51", "faces": [{"element": 51, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q51", "type": "force", "target": {"set": "q51"}, "vector": [0.0, -0.00248654200423802, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q52", "faces": [{"element": 52, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q52", "type": "force", "target": {"set": "q52"}, "vector": [0.0, -0.0026592178643344245, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q53", "faces": [{"element": 53, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q53", "type": "force", "target": {"set": "q53"}, "vector": [0.0, -0.002815498762017533, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q54", "faces": [{"element": 54, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q54", "type": "force", "target": {"set": "q54"}, "vector": [0.0, -0.002954421173584459, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q55", "faces": [{"element": 55, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q55", "type": "force", "target": {"set": "q55"}, "vector": [0.0, -0.0030751285961715027, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q56", "faces": [{"element": 56, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q56", "type": "force", "target": {"set": "q56"}, "vector": [0.0, -0.0031768768283791235, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q57", "faces": [{"element": 57, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q57", "type": "force", "target": {"set": "q57"}, "vector": [0.0, -0.00325903855852104, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q58", "faces": [{"element": 58, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q58", "type": "force", "target": {"set": "q58"}, "vector": [0.0, -0.0033211072322093817, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q59", "faces": [{"element": 59, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q59", "type": "force", "target": {"set": "q59"}, "vector": [0.0, -0.003362700175430931, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q60", "faces": [{"element": 60, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q60", "type": "force", "target": {"set": "q60"}, "vector": [0.0, -0.0033835609538596678, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q61", "faces": [{"element": 61, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q61", "type": "force", "target": {"set": "q61"}, "vector": [0.0, -0.0033835609538596678, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q62", "faces": [{"element": 62, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q62", "type": "force", "target": {"set": "q62"}, "vector": [0.0, -0.003362700175430931, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q63", "faces": [{"element": 63, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q63", "type": "force", "target": {"set": "q63"}, "vector": [0.0, -0.0033211072322093817, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q64", "faces": [{"element": 64, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q64", "type": "force", "target": {"set": "q64"}, "vector": [0.0, -0.0032590385585210407, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q65", "faces": [{"element": 65, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q65", "type": "force", "target": {"set": "q65"}, "vector": [0.0, -0.0031768768283791235, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q66", "faces": [{"element": 66, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q66", "type": "force", "target": {"set": "q66"}, "vector": [0.0, -0.0030751285961715027, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q67", "faces": [{"element": 67, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q67", "type": "force", "target": {"set": "q67"}, "vector": [0.0, -0.002954421173584459, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q68", "faces": [{"element": 68, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q68", "type": "force", "target": {"set": "q68"}, "vector": [0.0, -0.002815498762017533, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q69", "faces": [{"element": 69, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q69", "type": "force", "target": {"set": "q69"}, "vector": [0.0, -0.0026592178643344237, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q70", "faces": [{"element": 70, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q70", "type": "force", "target": {"set": "q70"}, "vector": [0.0, -0.00248654200423802, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q71", "faces": [{"element": 71, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q71", "type": "force", "target": {"set": "q71"}, "vector": [0.0, -0.002298535785826367, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q72", "faces": [{"element": 72, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q72", "type": "force", "target": {"set": "q72"}, "vector": [0.0, -0.0020963583299543837, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q73", "faces": [{"element": 73, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q73", "type": "force", "target": {"set": "q73"}, "vector": [0.0, -0.0018812561278683485, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q74", "faces": [{"element": 74, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q74", "type": "force", "target": {"set": "q74"}, "vector": [0.0, -0.00165455535617286, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q75", "faces": [{"element": 75, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q75", "type": "force", "target": {"set": "q75"}, "vector": [0.0, -0.0014176537005110772, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q76", "faces": [{"element": 76, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q76", "type": "force", "target": {"set": "q76"}, "vector": [0.0, -0.001172011738367953, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q77", "faces": [{"element": 77, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q77", "type": "force", "target": {"set": "q77"}, "vector": [0.0, -0.0009191439341243368, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q78", "faces": [{"element": 78, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q78", "type": "force", "target": {"set": "q78"}, "vector": [0.0, -0.000660609301880473, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q79", "faces": [{"element": 79, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q79", "type": "force", "target": {"set": "q79"}, "vector": [0.0, -0.0003980017936156286, 0.0], "distribution": "total"}},
|
||||
{"command": "model.set.create", "params": {"name": "q80", "faces": [{"element": 80, "face": 5}]}},
|
||||
{"command": "model.load.create", "params": {"name": "q80", "type": "force", "target": {"set": "q80"}, "vector": [0.0, -0.00013294047194412024, 0.0], "distribution": "total"}},
|
||||
{"command": "model.step.create", "params": {"name": "Snap", "procedure": {"type": "nonlinear_static", "initial_increment": 0.1, "max_increments": 200, "arc_length": {"max_load_factor": 10.0, "displacement_limit": {"node": 203, "direction": 2, "displacement": -2.222798536380059}}}, "boundary_conditions": ["pins", "width"], "loads": ["q41", "q42", "q43", "q44", "q45", "q46", "q47", "q48", "q49", "q50", "q51", "q52", "q53", "q54", "q55", "q56", "q57", "q58", "q59", "q60", "q61", "q62", "q63", "q64", "q65", "q66", "q67", "q68", "q69", "q70", "q71", "q72", "q73", "q74", "q75", "q76", "q77", "q78", "q79", "q80"]}},
|
||||
{"command": "solve.nonlinear", "params": {"step": "Snap"}, "id": "solve"}
|
||||
]
|
||||
@@ -0,0 +1,5 @@
|
||||
# Euler buckling of a clamped–free column of solids
|
||||
|
||||
A square column, length 10, side 1, E = 1000, ν = 0 (2 × 2 × 10 hex20), clamped at its base and
|
||||
pressed by a unit dead pressure on its free top: effective length 20. Reference: Euler with
|
||||
Engesser's shear correction.
|
||||