origami-engine 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- origami_engine/__init__.py +70 -0
- origami_engine/backend.py +24 -0
- origami_engine/constants.py +69 -0
- origami_engine/dynamics.py +92 -0
- origami_engine/evaluation.py +178 -0
- origami_engine/example.py +29 -0
- origami_engine/geometry.py +120 -0
- origami_engine/model.py +209 -0
- origami_engine/patterns.py +86 -0
- origami_engine/plotting.py +122 -0
- origami_engine/render_individual.py +159 -0
- origami_engine/schemas/crease_pattern.schema.json +51 -0
- origami_engine/serialization.py +124 -0
- origami_engine/simulation.py +90 -0
- origami_engine/types.py +52 -0
- origami_engine-0.1.0.dist-info/METADATA +375 -0
- origami_engine-0.1.0.dist-info/RECORD +21 -0
- origami_engine-0.1.0.dist-info/WHEEL +5 -0
- origami_engine-0.1.0.dist-info/entry_points.txt +2 -0
- origami_engine-0.1.0.dist-info/licenses/LICENSE +201 -0
- origami_engine-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Origami simulation package.
|
|
2
|
+
|
|
3
|
+
Public entry points are grouped into:
|
|
4
|
+
|
|
5
|
+
- simulation domain/model construction in `geometry`, `model`, `dynamics`
|
|
6
|
+
- fitness/evaluation interfaces in `evaluation`
|
|
7
|
+
- reusable reference inputs in `patterns`
|
|
8
|
+
- crease input normalization in `serialization`
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from .constants import (
|
|
12
|
+
MAX_FOLD,
|
|
13
|
+
PAPER_MASS,
|
|
14
|
+
THICK,
|
|
15
|
+
VIB_AMP_X,
|
|
16
|
+
VIB_AMP_Z,
|
|
17
|
+
VIB_FREQ,
|
|
18
|
+
Z0,
|
|
19
|
+
M,
|
|
20
|
+
S,
|
|
21
|
+
V,
|
|
22
|
+
)
|
|
23
|
+
from .dynamics import drive_table, paper_centroid, run_simulation
|
|
24
|
+
from .evaluation import compute_forward_displacement, evaluate_individual, evaluate_population
|
|
25
|
+
from .geometry import build_pattern
|
|
26
|
+
from .model import generate_xml
|
|
27
|
+
from .patterns import (
|
|
28
|
+
DEFAULT_PATTERN_JSON,
|
|
29
|
+
load_default_creases,
|
|
30
|
+
reference_miura_legacy_creases,
|
|
31
|
+
reference_miura_render_creases,
|
|
32
|
+
)
|
|
33
|
+
from .plotting import plot_pattern
|
|
34
|
+
from .serialization import CREASE_SCHEMA, load_creases_from_json, normalize_creases, save_creases_to_json
|
|
35
|
+
from .types import Crease, Pattern, SimulationResult
|
|
36
|
+
|
|
37
|
+
__version__ = "0.1.0"
|
|
38
|
+
|
|
39
|
+
__all__ = [
|
|
40
|
+
"CREASE_SCHEMA",
|
|
41
|
+
"DEFAULT_PATTERN_JSON",
|
|
42
|
+
"MAX_FOLD",
|
|
43
|
+
"PAPER_MASS",
|
|
44
|
+
"THICK",
|
|
45
|
+
"VIB_AMP_X",
|
|
46
|
+
"VIB_AMP_Z",
|
|
47
|
+
"VIB_FREQ",
|
|
48
|
+
"Z0",
|
|
49
|
+
"Crease",
|
|
50
|
+
"M",
|
|
51
|
+
"Pattern",
|
|
52
|
+
"S",
|
|
53
|
+
"SimulationResult",
|
|
54
|
+
"V",
|
|
55
|
+
"build_pattern",
|
|
56
|
+
"compute_forward_displacement",
|
|
57
|
+
"drive_table",
|
|
58
|
+
"evaluate_individual",
|
|
59
|
+
"evaluate_population",
|
|
60
|
+
"generate_xml",
|
|
61
|
+
"load_creases_from_json",
|
|
62
|
+
"load_default_creases",
|
|
63
|
+
"normalize_creases",
|
|
64
|
+
"paper_centroid",
|
|
65
|
+
"plot_pattern",
|
|
66
|
+
"reference_miura_legacy_creases",
|
|
67
|
+
"reference_miura_render_creases",
|
|
68
|
+
"run_simulation",
|
|
69
|
+
"save_creases_to_json",
|
|
70
|
+
]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
"""MuJoCo import guard.
|
|
4
|
+
|
|
5
|
+
Keeping the optional import in one place lets geometry and I/O modules be
|
|
6
|
+
imported (and unit-tested) without MuJoCo installed.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
MUJOCO_IMPORT_ERROR: BaseException | None = None
|
|
10
|
+
try:
|
|
11
|
+
import mujoco
|
|
12
|
+
except Exception as exc: # noqa: BLE001 - broad catch intentional for import guard
|
|
13
|
+
mujoco = None
|
|
14
|
+
MUJOCO_IMPORT_ERROR = exc
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def require_mujoco(message: str = "MuJoCo is required for this operation."):
|
|
18
|
+
"""Return the imported ``mujoco`` module or raise a helpful RuntimeError."""
|
|
19
|
+
if mujoco is None:
|
|
20
|
+
raise RuntimeError(message) from MUJOCO_IMPORT_ERROR
|
|
21
|
+
return mujoco
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
__all__ = ["MUJOCO_IMPORT_ERROR", "mujoco", "require_mujoco"]
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
"""Physical and solver constants shared across the engine."""
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
# Sheet geometry and mass
|
|
8
|
+
S = 1.0
|
|
9
|
+
THICK = 0.0001
|
|
10
|
+
PAPER_MASS = 0.2
|
|
11
|
+
Z0 = THICK + 0.001
|
|
12
|
+
|
|
13
|
+
# Pattern validation
|
|
14
|
+
MIN_FACE_AREA = 1e-4 * S * S
|
|
15
|
+
MAX_FOLD = np.pi * 0.98
|
|
16
|
+
|
|
17
|
+
# Hinge actuation and panels
|
|
18
|
+
KP, KV, DAMPING, FORCE_MAX = 2.0, 0.15, 0.003, 2.0
|
|
19
|
+
MU_PAPER = 0.3
|
|
20
|
+
MU_TABLE = 0.5
|
|
21
|
+
|
|
22
|
+
# Table vibration
|
|
23
|
+
VIB_FREQ = 75.0
|
|
24
|
+
VIB_AMP_X = 0.0
|
|
25
|
+
VIB_AMP_Z = 0.0013
|
|
26
|
+
|
|
27
|
+
# Constraint solver tuning
|
|
28
|
+
EQ_SOLREF = "0.005 1"
|
|
29
|
+
EQ_SOLIMP = "0.95 0.99 0.001"
|
|
30
|
+
STRETCH_K = 5.0e4
|
|
31
|
+
STRETCH_DAMP = 50.0
|
|
32
|
+
STRETCH_MAX = 1.0e-4
|
|
33
|
+
K_PANEL = 1e5
|
|
34
|
+
D_PANEL = 50.0
|
|
35
|
+
MAX_STRAIN = 0.005
|
|
36
|
+
COLL_THICK = THICK * 0.1
|
|
37
|
+
|
|
38
|
+
# Canonical mountain/valley angles
|
|
39
|
+
V = np.deg2rad(-45)
|
|
40
|
+
M = np.deg2rad(45)
|
|
41
|
+
|
|
42
|
+
__all__ = [
|
|
43
|
+
"COLL_THICK",
|
|
44
|
+
"DAMPING",
|
|
45
|
+
"D_PANEL",
|
|
46
|
+
"EQ_SOLIMP",
|
|
47
|
+
"EQ_SOLREF",
|
|
48
|
+
"FORCE_MAX",
|
|
49
|
+
"KP",
|
|
50
|
+
"KV",
|
|
51
|
+
"K_PANEL",
|
|
52
|
+
"MAX_FOLD",
|
|
53
|
+
"MAX_STRAIN",
|
|
54
|
+
"MIN_FACE_AREA",
|
|
55
|
+
"MU_PAPER",
|
|
56
|
+
"MU_TABLE",
|
|
57
|
+
"PAPER_MASS",
|
|
58
|
+
"STRETCH_DAMP",
|
|
59
|
+
"STRETCH_K",
|
|
60
|
+
"STRETCH_MAX",
|
|
61
|
+
"THICK",
|
|
62
|
+
"VIB_AMP_X",
|
|
63
|
+
"VIB_AMP_Z",
|
|
64
|
+
"VIB_FREQ",
|
|
65
|
+
"Z0",
|
|
66
|
+
"M",
|
|
67
|
+
"S",
|
|
68
|
+
"V",
|
|
69
|
+
]
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
"""Simulation execution: build the model, step MuJoCo, track the paper."""
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
from .backend import require_mujoco
|
|
8
|
+
from .constants import VIB_AMP_X, VIB_AMP_Z, VIB_FREQ
|
|
9
|
+
from .geometry import build_pattern
|
|
10
|
+
from .model import generate_xml
|
|
11
|
+
from .serialization import normalize_creases
|
|
12
|
+
from .types import SimulationResult
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def drive_table(model, data, t, amp_x=VIB_AMP_X, amp_z=VIB_AMP_Z, freq_hz=VIB_FREQ):
|
|
16
|
+
"""Kinemetically drive the support table with a sinusoidal vibration."""
|
|
17
|
+
w = 2 * np.pi * freq_hz
|
|
18
|
+
jx, jz = model.joint("table_x"), model.joint("table_z")
|
|
19
|
+
data.qpos[jx.qposadr[0]] = amp_x * np.sin(w * t)
|
|
20
|
+
data.qvel[jx.dofadr[0]] = amp_x * w * np.cos(w * t)
|
|
21
|
+
data.qpos[jz.qposadr[0]] = amp_z * np.sin(w * t)
|
|
22
|
+
data.qvel[jz.dofadr[0]] = amp_z * w * np.cos(w * t)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def paper_centroid(model, data):
|
|
26
|
+
"""Mean XY position of all non-table geoms (the paper sheet)."""
|
|
27
|
+
table_id = model.body("table").id
|
|
28
|
+
ids = [g for g in range(model.ngeom) if model.geom_bodyid[g] != table_id]
|
|
29
|
+
if not ids:
|
|
30
|
+
raise ValueError("No paper geoms were found in the MuJoCo model.")
|
|
31
|
+
points = np.asarray(data.geom_xpos[ids, :3], dtype=float)
|
|
32
|
+
if points.size == 0:
|
|
33
|
+
raise ValueError("Simulation geometry is empty.")
|
|
34
|
+
return points[:, :2].mean(axis=0)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# Backward-compatible private alias.
|
|
38
|
+
_paper_centroid = paper_centroid
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def run_simulation(
|
|
42
|
+
creases,
|
|
43
|
+
duration=8.0,
|
|
44
|
+
fold_duration=3.0,
|
|
45
|
+
vibrate=True,
|
|
46
|
+
amp_x=VIB_AMP_X,
|
|
47
|
+
amp_z=VIB_AMP_Z,
|
|
48
|
+
freq_hz=VIB_FREQ,
|
|
49
|
+
):
|
|
50
|
+
"""Run the fold simulation and return final MuJoCo state plus centroid data."""
|
|
51
|
+
mujoco = require_mujoco("MuJoCo is required to run the simulation.")
|
|
52
|
+
if duration <= 0:
|
|
53
|
+
raise ValueError("duration must be positive.")
|
|
54
|
+
|
|
55
|
+
normalized = normalize_creases(creases)
|
|
56
|
+
pat = build_pattern(normalized)
|
|
57
|
+
if not pat.valid:
|
|
58
|
+
raise ValueError(f"invalid crease pattern: {pat.reason}")
|
|
59
|
+
|
|
60
|
+
xml, info = generate_xml(pat, normalized)
|
|
61
|
+
model = mujoco.MjModel.from_xml_string(xml)
|
|
62
|
+
data = mujoco.MjData(model)
|
|
63
|
+
|
|
64
|
+
initial_centroid = paper_centroid(model, data)
|
|
65
|
+
target_angles = np.asarray(info["targets"], dtype=float)
|
|
66
|
+
hinge_adr = np.array([model.joint(h["name"]).qposadr[0] for h in info["hinges"]], dtype=int)
|
|
67
|
+
if len(hinge_adr):
|
|
68
|
+
data.qpos[hinge_adr] = 0.0
|
|
69
|
+
|
|
70
|
+
while data.time < duration:
|
|
71
|
+
t = min(data.time / fold_duration, 1.0)
|
|
72
|
+
s = t * t * (3 - 2 * t)
|
|
73
|
+
data.ctrl[:] = s * target_angles
|
|
74
|
+
if vibrate:
|
|
75
|
+
drive_table(model, data, data.time, amp_x=amp_x, amp_z=amp_z, freq_hz=freq_hz)
|
|
76
|
+
mujoco.mj_step(model, data)
|
|
77
|
+
|
|
78
|
+
if not np.isfinite(data.qpos).all():
|
|
79
|
+
raise FloatingPointError("unstable simulation: non-finite joint coordinates produced.")
|
|
80
|
+
|
|
81
|
+
final_centroid = paper_centroid(model, data)
|
|
82
|
+
return SimulationResult(
|
|
83
|
+
model=model,
|
|
84
|
+
data=data,
|
|
85
|
+
pattern=pat,
|
|
86
|
+
info=info,
|
|
87
|
+
initial_centroid=initial_centroid,
|
|
88
|
+
final_centroid=final_centroid,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
__all__ = ["drive_table", "paper_centroid", "run_simulation"]
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
"""Evaluation interfaces for single-individual and batch fitness runs."""
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from concurrent.futures import ProcessPoolExecutor
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
from .constants import VIB_AMP_X, VIB_AMP_Z, VIB_FREQ
|
|
11
|
+
from .dynamics import run_simulation
|
|
12
|
+
from .serialization import normalize_creases
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _as_trajectory_vector(trajectory):
|
|
16
|
+
if trajectory is None:
|
|
17
|
+
return np.asarray([1.0, 0.0, 0.0], dtype=float)
|
|
18
|
+
|
|
19
|
+
arr = np.asarray(trajectory, dtype=float)
|
|
20
|
+
if arr.ndim == 0:
|
|
21
|
+
raise ValueError("trajectory must be a direction vector or a sequence of points.")
|
|
22
|
+
if arr.ndim == 1:
|
|
23
|
+
if arr.size not in (2, 3):
|
|
24
|
+
raise ValueError("direction vectors must have length 2 or 3.")
|
|
25
|
+
direction = arr.astype(float)
|
|
26
|
+
elif arr.ndim == 2:
|
|
27
|
+
if arr.shape[0] < 2:
|
|
28
|
+
raise ValueError("trajectory waypoint arrays require at least two points.")
|
|
29
|
+
direction = arr[-1] - arr[0]
|
|
30
|
+
else:
|
|
31
|
+
raise ValueError("trajectory must be a vector or 2D waypoint array.")
|
|
32
|
+
|
|
33
|
+
norm = np.linalg.norm(direction)
|
|
34
|
+
if not math.isfinite(norm) or norm <= 0.0:
|
|
35
|
+
raise ValueError("trajectory direction must be non-zero and finite.")
|
|
36
|
+
return direction / norm
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def compute_forward_displacement(sim_result, trajectory=(1.0, 0.0, 0.0)):
|
|
40
|
+
direction = _as_trajectory_vector(trajectory)
|
|
41
|
+
initial = np.asarray(sim_result.initial_centroid, dtype=float)
|
|
42
|
+
final = np.asarray(sim_result.final_centroid, dtype=float)
|
|
43
|
+
delta = final - initial
|
|
44
|
+
|
|
45
|
+
if direction.size == 2:
|
|
46
|
+
delta_2d = np.asarray([delta[0], delta[1]], dtype=float)
|
|
47
|
+
return float(np.dot(delta_2d, direction))
|
|
48
|
+
|
|
49
|
+
delta_3d = np.zeros(3, dtype=float)
|
|
50
|
+
delta_3d[:2] = delta
|
|
51
|
+
return float(np.dot(delta_3d, direction))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def evaluate_individual(
|
|
55
|
+
creases,
|
|
56
|
+
duration=8.0,
|
|
57
|
+
trajectory=(1.0, 0.0, 0.0),
|
|
58
|
+
fold_duration=3.0,
|
|
59
|
+
vibrate=True,
|
|
60
|
+
amp_x=VIB_AMP_X,
|
|
61
|
+
amp_z=VIB_AMP_Z,
|
|
62
|
+
freq_hz=VIB_FREQ,
|
|
63
|
+
return_details=False,
|
|
64
|
+
):
|
|
65
|
+
"""Evaluate one crease configuration and return net forward displacement."""
|
|
66
|
+
if duration <= 0:
|
|
67
|
+
raise ValueError("duration must be positive.")
|
|
68
|
+
|
|
69
|
+
normalized = normalize_creases(creases)
|
|
70
|
+
sim_result = run_simulation(
|
|
71
|
+
normalized,
|
|
72
|
+
duration=duration,
|
|
73
|
+
fold_duration=fold_duration,
|
|
74
|
+
vibrate=vibrate,
|
|
75
|
+
amp_x=amp_x,
|
|
76
|
+
amp_z=amp_z,
|
|
77
|
+
freq_hz=freq_hz,
|
|
78
|
+
)
|
|
79
|
+
displacement = compute_forward_displacement(sim_result, trajectory=trajectory)
|
|
80
|
+
|
|
81
|
+
if return_details:
|
|
82
|
+
return {
|
|
83
|
+
"displacement": float(displacement),
|
|
84
|
+
"initial_centroid": np.asarray(sim_result.initial_centroid, dtype=float),
|
|
85
|
+
"final_centroid": np.asarray(sim_result.final_centroid, dtype=float),
|
|
86
|
+
"duration": float(duration),
|
|
87
|
+
"trajectory": np.asarray(_as_trajectory_vector(trajectory), dtype=float),
|
|
88
|
+
"n_faces": int(sim_result.pattern.n_faces),
|
|
89
|
+
"n_loops": len(sim_result.pattern.loop_edges or []),
|
|
90
|
+
}
|
|
91
|
+
return float(displacement)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _evaluate_worker(item, duration, trajectory, fold_duration, vibrate, amp_x, amp_z, freq_hz):
|
|
95
|
+
return evaluate_individual(
|
|
96
|
+
item,
|
|
97
|
+
duration=duration,
|
|
98
|
+
trajectory=trajectory,
|
|
99
|
+
fold_duration=fold_duration,
|
|
100
|
+
vibrate=vibrate,
|
|
101
|
+
amp_x=amp_x,
|
|
102
|
+
amp_z=amp_z,
|
|
103
|
+
freq_hz=freq_hz,
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def evaluate_population(
|
|
108
|
+
individuals,
|
|
109
|
+
duration=8.0,
|
|
110
|
+
trajectory=(1.0, 0.0, 0.0),
|
|
111
|
+
fold_duration=3.0,
|
|
112
|
+
vibrate=True,
|
|
113
|
+
amp_x=VIB_AMP_X,
|
|
114
|
+
amp_z=VIB_AMP_Z,
|
|
115
|
+
freq_hz=VIB_FREQ,
|
|
116
|
+
workers=1,
|
|
117
|
+
error_policy="raise",
|
|
118
|
+
):
|
|
119
|
+
"""Evaluate a list of GA individuals in sequence or parallel."""
|
|
120
|
+
if workers is None or workers <= 1:
|
|
121
|
+
results = []
|
|
122
|
+
for i, item in enumerate(individuals):
|
|
123
|
+
try:
|
|
124
|
+
results.append(
|
|
125
|
+
evaluate_individual(
|
|
126
|
+
item,
|
|
127
|
+
duration=duration,
|
|
128
|
+
trajectory=trajectory,
|
|
129
|
+
fold_duration=fold_duration,
|
|
130
|
+
vibrate=vibrate,
|
|
131
|
+
amp_x=amp_x,
|
|
132
|
+
amp_z=amp_z,
|
|
133
|
+
freq_hz=freq_hz,
|
|
134
|
+
)
|
|
135
|
+
)
|
|
136
|
+
except Exception as exc: # pragma: no cover - exercised by tests via explicit raise
|
|
137
|
+
if error_policy == "raise":
|
|
138
|
+
raise RuntimeError(f"individual {i} failed during evaluation: {exc}") from exc
|
|
139
|
+
results.append(float("nan"))
|
|
140
|
+
return results
|
|
141
|
+
|
|
142
|
+
max_workers = max(1, min(workers, len(individuals) if individuals else 1))
|
|
143
|
+
with ProcessPoolExecutor(max_workers=max_workers) as pool:
|
|
144
|
+
futures = []
|
|
145
|
+
for i, item in enumerate(individuals):
|
|
146
|
+
futures.append(
|
|
147
|
+
(
|
|
148
|
+
i,
|
|
149
|
+
pool.submit(
|
|
150
|
+
_evaluate_worker,
|
|
151
|
+
item,
|
|
152
|
+
duration,
|
|
153
|
+
trajectory,
|
|
154
|
+
fold_duration,
|
|
155
|
+
vibrate,
|
|
156
|
+
amp_x,
|
|
157
|
+
amp_z,
|
|
158
|
+
freq_hz,
|
|
159
|
+
),
|
|
160
|
+
)
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
results = [float("nan")] * len(individuals)
|
|
164
|
+
for i, future in futures:
|
|
165
|
+
try:
|
|
166
|
+
results[i] = future.result()
|
|
167
|
+
except Exception as exc:
|
|
168
|
+
if error_policy == "raise":
|
|
169
|
+
raise RuntimeError(f"individual {i} failed during evaluation: {exc}") from exc
|
|
170
|
+
return results
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
__all__ = [
|
|
174
|
+
"_as_trajectory_vector",
|
|
175
|
+
"compute_forward_displacement",
|
|
176
|
+
"evaluate_individual",
|
|
177
|
+
"evaluate_population",
|
|
178
|
+
]
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
# Allow running this file directly (`python origami_engine/example.py`) as well as
|
|
7
|
+
# via `python -m origami_engine.example` from the project root.
|
|
8
|
+
PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
|
9
|
+
if str(PROJECT_ROOT) not in sys.path:
|
|
10
|
+
sys.path.insert(0, str(PROJECT_ROOT))
|
|
11
|
+
|
|
12
|
+
from origami_engine.evaluation import evaluate_individual, evaluate_population
|
|
13
|
+
from origami_engine.patterns import DEFAULT_PATTERN_JSON, reference_miura_legacy_creases
|
|
14
|
+
from origami_engine.simulation import load_creases_from_json
|
|
15
|
+
|
|
16
|
+
DEFAULT_CREASE_JSON = DEFAULT_PATTERN_JSON
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
if __name__ == "__main__":
|
|
20
|
+
if DEFAULT_CREASE_JSON.exists():
|
|
21
|
+
creases = load_creases_from_json(DEFAULT_CREASE_JSON)
|
|
22
|
+
print(f"loaded crease pattern from {DEFAULT_CREASE_JSON}")
|
|
23
|
+
else:
|
|
24
|
+
creases = reference_miura_legacy_creases()
|
|
25
|
+
print("loaded embedded legacy reference crease pattern")
|
|
26
|
+
|
|
27
|
+
displacement = evaluate_individual(creases, duration=0.5, trajectory=(1.0, 0.0, 0.0))
|
|
28
|
+
print(f"single-individual displacement: {displacement:.6f}")
|
|
29
|
+
print(evaluate_population([creases, creases], duration=0.5, trajectory=(1.0, 0.0, 0.0), workers=1))
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
"""Geometry reconstruction: turn crease segments into a validated face graph."""
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from shapely.geometry import LineString, Point, box
|
|
7
|
+
from shapely.ops import linemerge, polygonize, unary_union
|
|
8
|
+
|
|
9
|
+
from .constants import MIN_FACE_AREA, S
|
|
10
|
+
from .types import Pattern
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _parts(g):
|
|
14
|
+
return list(g.geoms) if hasattr(g, "geoms") else [g]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _straight_pieces(g):
|
|
18
|
+
lines = [x for x in _parts(g) if x.geom_type == "LineString"]
|
|
19
|
+
if not lines:
|
|
20
|
+
return []
|
|
21
|
+
out = []
|
|
22
|
+
for part in _parts(linemerge(lines)):
|
|
23
|
+
c = list(part.simplify(1e-9).coords)
|
|
24
|
+
out += [
|
|
25
|
+
(c[i], c[i + 1]) for i in range(len(c) - 1) if np.hypot(c[i + 1][0] - c[i][0], c[i + 1][1] - c[i][1]) > 1e-6
|
|
26
|
+
]
|
|
27
|
+
return out
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def build_pattern(creases):
|
|
31
|
+
"""Reconstruct polygonal faces and the spanning-tree hinge graph.
|
|
32
|
+
|
|
33
|
+
Returns a :class:`~origami_engine.types.Pattern` whose ``valid`` flag
|
|
34
|
+
reports whether the creases tile the square sheet without sliver faces or
|
|
35
|
+
disconnected panels.
|
|
36
|
+
"""
|
|
37
|
+
lines = [LineString([c.p1, c.p2]) for c in creases]
|
|
38
|
+
noded = unary_union([box(0, 0, S, S).exterior] + lines)
|
|
39
|
+
faces = list(polygonize(_parts(noded)))
|
|
40
|
+
if not faces:
|
|
41
|
+
return Pattern(False, "no faces")
|
|
42
|
+
|
|
43
|
+
areas = np.array([f.area for f in faces])
|
|
44
|
+
if areas.min() < MIN_FACE_AREA:
|
|
45
|
+
return Pattern(False, f"sliver face (area {areas.min():.2e})")
|
|
46
|
+
if abs(areas.sum() - S * S) > 1e-6:
|
|
47
|
+
return Pattern(False, "faces do not tile the sheet")
|
|
48
|
+
|
|
49
|
+
bnd = [f.boundary for f in faces]
|
|
50
|
+
edges = []
|
|
51
|
+
for i in range(len(faces)):
|
|
52
|
+
for j in range(i + 1, len(faces)):
|
|
53
|
+
if not faces[i].intersects(faces[j]):
|
|
54
|
+
continue
|
|
55
|
+
for p, q in _straight_pieces(bnd[i].intersection(bnd[j])):
|
|
56
|
+
mid = Point((p[0] + q[0]) / 2, (p[1] + q[1]) / 2)
|
|
57
|
+
dist = [ln.distance(mid) for ln in lines]
|
|
58
|
+
k = int(np.argmin(dist)) if dist else -1
|
|
59
|
+
if k >= 0 and dist[k] > 1e-6:
|
|
60
|
+
k = -1
|
|
61
|
+
edges.append({"i": i, "j": j, "p": p, "q": q, "crease": k})
|
|
62
|
+
|
|
63
|
+
adj = {i: [] for i in range(len(faces))}
|
|
64
|
+
for k, e in enumerate(edges):
|
|
65
|
+
adj[e["i"]].append((e["j"], k))
|
|
66
|
+
adj[e["j"]].append((e["i"], k))
|
|
67
|
+
|
|
68
|
+
root = int(np.argmax(areas))
|
|
69
|
+
parent, depth, tree_edge = {root: None}, {root: 0}, {}
|
|
70
|
+
queue = [root]
|
|
71
|
+
while queue:
|
|
72
|
+
u = queue.pop(0)
|
|
73
|
+
for v, k in adj[u]:
|
|
74
|
+
if v not in parent:
|
|
75
|
+
parent[v], depth[v], tree_edge[v] = u, depth[u] + 1, k
|
|
76
|
+
queue.append(v)
|
|
77
|
+
|
|
78
|
+
if len(parent) < len(faces):
|
|
79
|
+
return Pattern(False, "disconnected faces")
|
|
80
|
+
|
|
81
|
+
used = set(tree_edge.values())
|
|
82
|
+
loop_edges = [k for k in range(len(edges)) if k not in used]
|
|
83
|
+
return Pattern(
|
|
84
|
+
True,
|
|
85
|
+
"",
|
|
86
|
+
faces,
|
|
87
|
+
edges,
|
|
88
|
+
root,
|
|
89
|
+
parent,
|
|
90
|
+
depth,
|
|
91
|
+
tree_edge,
|
|
92
|
+
loop_edges,
|
|
93
|
+
n_faces=len(faces),
|
|
94
|
+
n_loops=len(loop_edges),
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _tri_area(t):
|
|
99
|
+
return 0.5 * abs((t[1][0] - t[0][0]) * (t[2][1] - t[0][1]) - (t[2][0] - t[0][0]) * (t[1][1] - t[0][1]))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _triangles(poly):
|
|
103
|
+
if poly.convex_hull.area - poly.area < 1e-12 and not list(poly.interiors):
|
|
104
|
+
c = np.array(poly.exterior.coords)[:-1]
|
|
105
|
+
tris = [(c[0], c[k], c[k + 1]) for k in range(1, len(c) - 1)]
|
|
106
|
+
else:
|
|
107
|
+
try:
|
|
108
|
+
import shapely
|
|
109
|
+
|
|
110
|
+
tris = [np.array(t.exterior.coords)[:3] for t in shapely.constrained_delaunay_triangles(poly).geoms]
|
|
111
|
+
except Exception: # noqa: BLE001 - broad catch intentional for Delaunay fallback
|
|
112
|
+
from shapely.ops import triangulate
|
|
113
|
+
|
|
114
|
+
tris = [
|
|
115
|
+
np.array(t.exterior.coords)[:3] for t in triangulate(poly) if poly.contains(t.representative_point())
|
|
116
|
+
]
|
|
117
|
+
return [np.asarray(t) for t in tris if _tri_area(t) > 1e-7]
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
__all__ = ["build_pattern"]
|