File size: 35,575 Bytes
4452800
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
"""Generate the 1,000-trajectory DENIM capability extension v4.

The extension targets four gaps left by the frozen 2,660-trajectory release:
long-cycle state drift, full six-component loading, finite-element-derived local
paths, and paired time-discretization/observation robustness.  Existing data
and splits are never overwritten.  One sample remains one complete history.

The structure-derived cohort is deliberately explicit about its fidelity: an
AgentFEM linear-elastic solve supplies three local unit-load strain bases for
four perforated/notched plates.  Time-dependent load coefficients are then
superposed and replayed through the same nonlinear hidden reference material
used by the DENIM closure study.  This produces genuine FE-derived local path
shapes without claiming fully coupled elastoplastic redistribution.
"""

from __future__ import annotations

import argparse
import csv
import hashlib
import json
import math
import os
import subprocess
import time
from collections import Counter
from pathlib import Path
from typing import Iterable

import h5py
import numpy as np

from src.generate_t2_denim_boundary_v1 import quality as boundary_quality
from src.generate_t2_graybox_closure import MATERIAL, material
from src.t2_multiaxial_ood_v2 import PATH_FAMILIES, strain_history, tensor_to_voigt


ROOT = Path(__file__).resolve().parents[1]
CONFIG_PATH = ROOT / "configs" / "t2_denim_capability_v4.json"
DATA_DIR = ROOT / "data" / "t2_denim_capability_v4"
DATA_PATH = DATA_DIR / "cohort.h5"
INDEX_PATH = DATA_DIR / "index.jsonl"
INDEX_CSV_PATH = DATA_DIR / "index.csv"
MANIFEST_PATH = DATA_DIR / "manifest.json"
STRUCTURE_BASIS_PATH = DATA_DIR / "structure_bases.npz"
ARTIFACT_DIR = ROOT / "artifacts" / "t2_denim_capability_v4"
AGENTFEM_ROOT = Path("/Users/luo/Desktop/开发环境/fenicsx-code/agentfem")

FULL_3D_FAMILIES = (
    "triaxial_phase_lissajous",
    "principal_axis_rotation_3d",
    "three_shear_rotation",
    "hydro_deviatoric_sequence",
    "six_component_random_blocks",
    "biaxial_torsion_reversal",
)
RESOLUTIONS = (61, 121, 241, 481)
STRUCTURE_SPECS = (
    ("central_hole_r018", "central_hole", 0.18),
    ("central_hole_r026", "central_hole", 0.26),
    ("double_notch_r016", "double_edge_notch", 0.16),
    ("double_notch_r024", "double_edge_notch", 0.24),
)


def load_config() -> dict[str, object]:
    return json.loads(CONFIG_PATH.read_text(encoding="utf-8"))


def _sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for block in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def _write_json(path: Path, value: object) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_suffix(path.suffix + ".tmp")
    temporary.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8")
    os.replace(temporary, path)


def _polyline(anchors: np.ndarray, count: int) -> np.ndarray:
    anchors = np.asarray(anchors, dtype=float)
    distances = np.linalg.norm(np.diff(anchors, axis=0), axis=1)
    cumulative = np.concatenate(([0.0], np.cumsum(distances)))
    if cumulative[-1] <= 0.0:
        return np.repeat(anchors[:1], count, axis=0)
    target = np.linspace(0.0, cumulative[-1], count)
    return np.column_stack(
        [np.interp(target, cumulative, anchors[:, column]) for column in range(anchors.shape[1])]
    )


def _symmetric_from_voigt(values: np.ndarray) -> np.ndarray:
    selected = np.asarray(values, dtype=float)
    tensor = np.zeros((*selected.shape[:-1], 3, 3), dtype=float)
    tensor[..., 0, 0] = selected[..., 0]
    tensor[..., 1, 1] = selected[..., 1]
    tensor[..., 2, 2] = selected[..., 2]
    tensor[..., 0, 1] = tensor[..., 1, 0] = selected[..., 3]
    tensor[..., 1, 2] = tensor[..., 2, 1] = selected[..., 4]
    tensor[..., 0, 2] = tensor[..., 2, 0] = selected[..., 5]
    return tensor


def _equivalent_strain(strains: np.ndarray) -> np.ndarray:
    selected = np.asarray(strains, dtype=float)
    trace = np.trace(selected, axis1=-2, axis2=-1)[..., None, None]
    dev = selected - trace / 3.0 * np.eye(3)
    return np.sqrt(np.maximum(2.0 / 3.0 * np.sum(dev * dev, axis=(-2, -1)), 0.0))


def _scale_history(strains: np.ndarray, amplitude: float) -> np.ndarray:
    selected = np.asarray(strains, dtype=float)
    selected = 0.5 * (selected + np.swapaxes(selected, -1, -2))
    scale = float(np.max(_equivalent_strain(selected)))
    if scale <= np.finfo(float).eps:
        raise ValueError("History has zero equivalent-strain amplitude.")
    return selected * (float(amplitude) / scale)


def _base_parameters(
    *, index: int, family: str, amplitude: float, seed: int, points: int
) -> dict[str, object]:
    rng = np.random.default_rng(seed)
    return {
        **MATERIAL,
        "case_id": f"denim-capability-v4-{index:05d}",
        "material_model": "hidden_three_memory_tabulated_hardening",
        "path_family": family,
        "path_seed": int(seed),
        "path_shape_a": float(rng.random()),
        "path_shape_b": float(rng.random()),
        "path_shape_c": float(rng.random()),
        "yield_design_coordinate": float(rng.random()),
        "maximum_equivalent_strain": float(amplitude),
        "points": int(points),
    }


def design(seed: int = 20260925) -> list[dict[str, object]]:
    """Create exactly 1,000 deterministic records with frozen cohort roles."""

    rng = np.random.default_rng(seed)
    rows: list[dict[str, object]] = []

    # 300 long-cycle histories. Training sees 10/25 cycles, validation 50,
    # and the frozen test remains a true 100-cycle horizon extrapolation.
    long_roles = (
        (180, "train_long_cycle", (10, 25)),
        (40, "validation_long_cycle", (50,)),
        (80, "test_long_cycle_ood", (100,)),
    )
    for count, split, cycle_options in long_roles:
        for local in range(count):
            cycles = int(cycle_options[local % len(cycle_options)])
            points = cycles * 20 + 1
            family = PATH_FAMILIES[(len(rows) + local) % len(PATH_FAMILIES)]
            row = _base_parameters(
                index=len(rows),
                family=family,
                amplitude=float(rng.uniform(0.003, 0.010)),
                seed=int(seed + len(rows) * 104729),
                points=points,
            )
            row.update(
                cohort="long_cycle",
                split=split,
                group_id=row["case_id"],
                cycle_count=cycles,
                increments_per_cycle=20,
                observation_protocol="clean",
            )
            rows.append(row)

    # 300 full six-component histories. Four families are available to train,
    # principal-axis rotation validates, and random six-component blocks are
    # held out as a shape-OOD family.
    for family in FULL_3D_FAMILIES:
        for local in range(50):
            if family in FULL_3D_FAMILIES[:4]:
                split = "train_full_3d" if local < 36 else "validation_full_3d"
            elif family == "principal_axis_rotation_3d":
                split = "validation_full_3d"
            else:
                split = "test_full_3d_ood"
            row = _base_parameters(
                index=len(rows),
                family=family,
                amplitude=float(rng.uniform(0.003, 0.014)),
                seed=int(seed + len(rows) * 130363),
                points=241,
            )
            row.update(
                cohort="full_3d_nonproportional",
                split=split,
                group_id=row["case_id"],
                cycle_count=1,
                observation_protocol="clean",
            )
            rows.append(row)

    # 200 structure-derived probe histories, 50 from each FE source group.
    for structure_name, structure_kind, radius in STRUCTURE_SPECS:
        for probe_index in range(50):
            family = (
                "fe_tension_shear_lissajous",
                "fe_tension_bending_sequence",
                "fe_reversed_mixed_cycle",
                "fe_random_load_blocks",
                "fe_rotating_load_vector",
            )[probe_index % 5]
            row = _base_parameters(
                index=len(rows),
                family=family,
                amplitude=float(rng.uniform(0.003, 0.012)),
                seed=int(seed + len(rows) * 15485863),
                points=241,
            )
            row.update(
                cohort="structure_derived",
                split="test_structure_derived",
                group_id=structure_name,
                structure_name=structure_name,
                structure_kind=structure_kind,
                structure_radius=float(radius),
                probe_index=int(probe_index),
                cycle_count=1,
                observation_protocol="clean",
            )
            rows.append(row)

    # 50 unique continuous paths at four matched resolutions = 200 records.
    # Noise and sparse observation masks are fields, not extra fake samples.
    for matched_index in range(50):
        family = PATH_FAMILIES[matched_index % len(PATH_FAMILIES)]
        shared_seed = int(seed + 900_000 + matched_index * 32452843)
        shared_rng = np.random.default_rng(shared_seed)
        amplitude = float(shared_rng.uniform(0.003, 0.012))
        shared_shapes = shared_rng.random(3)
        for points in RESOLUTIONS:
            row = _base_parameters(
                index=len(rows),
                family=family,
                amplitude=amplitude,
                seed=shared_seed,
                points=points,
            )
            row["path_shape_a"], row["path_shape_b"], row["path_shape_c"] = (
                float(value) for value in shared_shapes
            )
            row.update(
                cohort="discretization_and_observation",
                split="test_discretization_observation",
                group_id=f"matched-resolution-{matched_index:03d}",
                matched_path_id=f"matched-resolution-{matched_index:03d}",
                cycle_count=1,
                observation_protocol="noisy_sparse_paired",
                strain_noise_fraction=float(shared_rng.uniform(0.0005, 0.0030)),
                stress_noise_fraction=float(shared_rng.uniform(0.0005, 0.0050)),
                observation_keep_fraction=float(shared_rng.uniform(0.20, 0.65)),
            )
            rows.append(row)

    if len(rows) != 1000:
        raise RuntimeError(f"Capability extension must contain 1,000 rows, got {len(rows)}.")
    if len({str(row["case_id"]) for row in rows}) != len(rows):
        raise RuntimeError("Case IDs are not unique.")
    return rows


def _long_cycle_history(row: dict[str, object]) -> np.ndarray:
    cycles = int(row["cycle_count"])
    per_cycle = int(row["increments_per_cycle"]) + 1
    _, one_cycle = strain_history(row, points=per_cycle)
    pieces = [one_cycle]
    pieces.extend(one_cycle[1:] for _ in range(cycles - 1))
    history = np.concatenate(pieces, axis=0)
    if len(history) != int(row["points"]):
        raise RuntimeError("Long-cycle path length does not match the design.")
    return history


def _rotation(axis: np.ndarray, angle: np.ndarray) -> np.ndarray:
    axis = np.asarray(axis, dtype=float)
    axis /= np.linalg.norm(axis)
    cross = np.asarray(
        ((0.0, -axis[2], axis[1]), (axis[2], 0.0, -axis[0]), (-axis[1], axis[0], 0.0))
    )
    outer = np.outer(axis, axis)
    rotations = []
    for value in np.asarray(angle, dtype=float):
        rotations.append(
            np.cos(value) * np.eye(3)
            + (1.0 - np.cos(value)) * outer
            + np.sin(value) * cross
        )
    return np.asarray(rotations)


def _full_3d_history(row: dict[str, object]) -> np.ndarray:
    count = int(row["points"])
    time_coordinate = np.linspace(0.0, 1.0, count)
    phase = 2.0 * np.pi * time_coordinate
    family = str(row["path_family"])
    a = float(row["path_shape_a"])
    b = float(row["path_shape_b"])
    c = float(row["path_shape_c"])
    rng = np.random.default_rng(int(row["path_seed"]))

    if family == "triaxial_phase_lissajous":
        values = np.column_stack(
            (
                np.sin(phase),
                0.75 * np.sin(2.0 * phase + 0.3 + a),
                0.55 * np.sin(3.0 * phase + 0.7 + b),
                0.45 * np.sin(phase + np.pi / 3.0),
                0.35 * np.sin(2.0 * phase + np.pi / 5.0),
                0.30 * np.sin(3.0 * phase + np.pi / 7.0),
            )
        )
        return _scale_history(_symmetric_from_voigt(values), float(row["maximum_equivalent_strain"]))

    if family == "principal_axis_rotation_3d":
        principal = np.column_stack(
            (
                np.sin(phase),
                -0.55 * np.sin(phase),
                -0.45 * np.sin(phase),
            )
        )
        rotations = _rotation(np.asarray((1.0, 1.0 + a, 0.5 + b)), 2.0 * phase)
        diagonal = np.asarray([np.diag(value) for value in principal])
        tensors = np.einsum("nij,njk,nlk->nil", rotations, diagonal, rotations)
        return _scale_history(tensors, float(row["maximum_equivalent_strain"]))

    if family == "three_shear_rotation":
        values = np.column_stack(
            (
                np.zeros(count),
                np.zeros(count),
                np.zeros(count),
                np.sin(phase),
                np.sin(phase + 2.0 * np.pi / 3.0),
                np.sin(phase + 4.0 * np.pi / 3.0),
            )
        )
        return _scale_history(_symmetric_from_voigt(values), float(row["maximum_equivalent_strain"]))

    if family == "hydro_deviatoric_sequence":
        amplitude = 0.6 + 0.4 * a
        anchors = np.asarray(
            (
                (0, 0, 0, 0, 0, 0),
                (1, 1, 1, 0, 0, 0),
                (1 + amplitude, 1 - amplitude, 1, 0, 0, 0),
                (-0.7, -0.7, -0.7, 0.6, 0, 0),
                (0.8, -0.4, -0.4, 0, 0.55, 0.35),
                (0, 0, 0, 0, 0, 0),
            ),
            dtype=float,
        )
        return _scale_history(_symmetric_from_voigt(_polyline(anchors, count)), float(row["maximum_equivalent_strain"]))

    if family == "six_component_random_blocks":
        directions = rng.normal(size=(9, 6))
        directions /= np.linalg.norm(directions, axis=1, keepdims=True)
        directions[1::2] *= -1.0
        directions[:, :3] += 0.15 * rng.normal(size=(9, 1))
        anchors = np.vstack((np.zeros(6), directions, np.zeros(6)))
        return _scale_history(_symmetric_from_voigt(_polyline(anchors, count)), float(row["maximum_equivalent_strain"]))

    if family == "biaxial_torsion_reversal":
        ratio = 0.4 + 0.4 * c
        anchors = np.asarray(
            (
                (0, 0, 0, 0, 0, 0),
                (1, -0.4, 0, ratio, 0, 0),
                (-0.8, 0.5, 0, ratio, 0.5, 0),
                (0.6, 0.2, -0.5, -ratio, 0, 0.45),
                (-0.5, -0.3, 0.4, 0, -0.55, -0.25),
                (0, 0, 0, 0, 0, 0),
            ),
            dtype=float,
        )
        return _scale_history(_symmetric_from_voigt(_polyline(anchors, count)), float(row["maximum_equivalent_strain"]))

    raise ValueError(f"Unknown full-3D family: {family}")


def _load_coefficients(row: dict[str, object]) -> np.ndarray:
    count = int(row["points"])
    t = np.linspace(0.0, 1.0, count)
    phase = 2.0 * np.pi * t
    family = str(row["path_family"])
    rng = np.random.default_rng(int(row["path_seed"]))
    if family == "fe_tension_shear_lissajous":
        return np.column_stack((np.sin(phase), 0.75 * np.sin(2.0 * phase + 0.4), 0.35 * np.sin(phase + 1.1)))
    if family == "fe_tension_bending_sequence":
        return _polyline(np.asarray(((0, 0, 0), (1, 0, 0), (0.6, 0, 0.8), (-0.5, 0.7, 0.6), (0, 0, 0))), count)
    if family == "fe_reversed_mixed_cycle":
        return _polyline(np.asarray(((0, 0, 0), (1, 0.4, 0), (-0.8, 0.4, 0.5), (0.7, -0.6, -0.4), (-0.4, 0.3, 0.7), (0, 0, 0))), count)
    if family == "fe_random_load_blocks":
        anchors = rng.normal(size=(8, 3))
        anchors /= np.maximum(np.linalg.norm(anchors, axis=1, keepdims=True), 1.0e-15)
        anchors[1::2] *= -1.0
        return _polyline(np.vstack((np.zeros(3), anchors, np.zeros(3))), count)
    if family == "fe_rotating_load_vector":
        return np.column_stack((np.sin(phase), np.cos(phase) - 1.0, 0.6 * np.sin(2.0 * phase)))
    raise ValueError(f"Unknown FE load-coefficient family: {family}")


def _make_gmsh_domain(kind: str, radius: float):
    import gmsh

    from agentfem import mesh

    if not gmsh.isInitialized():
        gmsh.initialize()
    gmsh.clear()
    gmsh.option.setNumber("General.Terminal", 0)
    gmsh.model.add(f"denim_v4_{kind}_{radius:.3f}")
    length, height = 2.0, 1.0
    plate = gmsh.model.occ.addRectangle(0.0, 0.0, 0.0, length, height)
    if kind == "central_hole":
        tool = gmsh.model.occ.addDisk(1.0, 0.5, 0.0, radius, radius)
        surfaces, _ = gmsh.model.occ.cut([(2, plate)], [(2, tool)])
    elif kind == "double_edge_notch":
        lower = gmsh.model.occ.addDisk(1.0, 0.0, 0.0, radius, radius)
        upper = gmsh.model.occ.addDisk(1.0, 1.0, 0.0, radius, radius)
        surfaces, _ = gmsh.model.occ.cut([(2, plate)], [(2, lower), (2, upper)])
    else:
        raise ValueError(f"Unknown structure kind: {kind}")
    gmsh.model.occ.synchronize()
    gmsh.model.addPhysicalGroup(2, [tag for _, tag in surfaces], 1)
    gmsh.option.setNumber("Mesh.MeshSizeMin", 0.045)
    gmsh.option.setNumber("Mesh.MeshSizeMax", 0.10)
    gmsh.model.mesh.generate(2)
    return mesh.import_gmsh_model(gmsh.model, gdim=2).domain


def _solve_unit_strain(domain, *, traction: tuple[float, float], side: str) -> tuple[np.ndarray, np.ndarray]:
    from agentfem import constitutive, fields, mesh, models, studies
    from agentfem.solvers import LinearSolverOptions

    model = models.create(
        study=studies.static_solid(dimension=2, assumption="plane_stress"),
        mesh=domain,
    )
    displacement = model.field(fields.displacement(domain, degree=1))
    model.material(constitutive.isotropic_elastic(young=190.0e9, poisson=0.30, density=7800.0))
    left = mesh.boundary(domain, lambda x: np.isclose(x[0], 0.0), tag=101)
    model.fix(displacement, on=left, value=0.0)
    if side == "right":
        boundary = mesh.boundary(domain, lambda x: np.isclose(x[0], 2.0), tag=102)
    elif side == "top":
        boundary = mesh.boundary(domain, lambda x: np.isclose(x[1], 1.0), tag=103)
    else:
        raise ValueError(f"Unknown loaded side: {side}")
    model.traction(traction, on=boundary)
    result = model.step(
        target=displacement,
        solver_options=LinearSolverOptions(ksp_type="preonly", pc_type="lu"),
    ).solve_result(field_variables=("E",))
    result.verify("engineering").require()
    field = result.fields["E"].field
    coordinates = field.function_space.tabulate_dof_coordinates()
    raw = np.asarray(field.x.array, dtype=float).reshape((-1, 4))
    tensor = np.zeros((len(raw), 3, 3), dtype=float)
    tensor[:, 0, 0] = raw[:, 0]
    tensor[:, 0, 1] = tensor[:, 1, 0] = 0.5 * (raw[:, 1] + raw[:, 2])
    tensor[:, 1, 1] = raw[:, 3]
    return np.asarray(coordinates, dtype=float), tensor


def build_structure_bases(*, force: bool = False) -> dict[str, dict[str, np.ndarray]]:
    """Solve 12 AgentFEM unit-load cases and retain 50 probe bases per structure."""

    if STRUCTURE_BASIS_PATH.exists() and not force:
        loaded = np.load(STRUCTURE_BASIS_PATH, allow_pickle=False)
        result: dict[str, dict[str, np.ndarray]] = {}
        for name, _, _ in STRUCTURE_SPECS:
            result[name] = {
                "coordinates": loaded[f"{name}__coordinates"],
                "basis": loaded[f"{name}__basis"],
                "cell_indices": loaded[f"{name}__cell_indices"],
            }
        return result

    collected: dict[str, np.ndarray] = {}
    result = {}
    for name, kind, radius in STRUCTURE_SPECS:
        domain = _make_gmsh_domain(kind, radius)
        mode_outputs = (
            _solve_unit_strain(domain, traction=(1.0e6, 0.0), side="right"),
            _solve_unit_strain(domain, traction=(0.0, 1.0e6), side="right"),
            _solve_unit_strain(domain, traction=(0.0, 1.0e6), side="top"),
        )
        coordinates = mode_outputs[0][0]
        if any(not np.allclose(coordinates, item[0]) for item in mode_outputs[1:]):
            raise RuntimeError("DG0 strain-field coordinates changed between unit-load modes.")
        bases = np.stack([item[1] for item in mode_outputs], axis=1)
        score = np.linalg.norm(bases.reshape((len(bases), -1)), axis=1)
        valid = np.flatnonzero(score > np.quantile(score, 0.20))
        order = valid[np.argsort(score[valid])]
        positions = np.linspace(0, len(order) - 1, 50).round().astype(int)
        selected = order[positions]
        selected_coordinates = coordinates[selected]
        selected_bases = bases[selected]
        result[name] = {
            "coordinates": selected_coordinates,
            "basis": selected_bases,
            "cell_indices": selected.astype(np.int64),
        }
        collected[f"{name}__coordinates"] = selected_coordinates
        collected[f"{name}__basis"] = selected_bases
        collected[f"{name}__cell_indices"] = selected.astype(np.int64)
    DATA_DIR.mkdir(parents=True, exist_ok=True)
    np.savez_compressed(STRUCTURE_BASIS_PATH, **collected)
    return result


def _structure_history(row: dict[str, object], bases: dict[str, dict[str, np.ndarray]]) -> tuple[np.ndarray, dict[str, np.ndarray]]:
    source = bases[str(row["structure_name"])]
    probe = int(row["probe_index"])
    basis = source["basis"][probe]
    coefficients = _load_coefficients(row)
    strains = np.einsum("nm,mij->nij", coefficients, basis)
    strains = _scale_history(strains, float(row["maximum_equivalent_strain"]))
    metadata = {
        "source_strain_basis": tensor_to_voigt(basis),
        "load_mode_coefficients": coefficients,
        "source_coordinate": source["coordinates"][probe],
        "source_cell_index": np.asarray([source["cell_indices"][probe]], dtype=np.int64),
    }
    return strains, metadata


def _standard_history(row: dict[str, object]) -> np.ndarray:
    _, strains = strain_history(row, points=int(row["points"]))
    return strains


def _integrate_reference(strains: np.ndarray) -> dict[str, np.ndarray]:
    law = material()
    count = len(strains)
    stress = np.empty_like(strains)
    plastic = np.empty_like(strains)
    peeq = np.empty(count)
    increment = np.empty(count)
    truth_memories = np.empty((count, 3, 3, 3))
    latent_memories = np.empty((count, 2, 3, 3))
    radius = np.empty(count)
    state = None
    for point, strain in enumerate(strains):
        update = law.update(strain, state, linearization="none")
        state = update.state
        stress[point] = update.stress
        plastic[point] = state.plastic_strain
        peeq[point] = state.equivalent_plastic_strain
        increment[point] = update.plastic_multiplier_increment
        truth_memories[point] = state.backstresses
        latent_memories[point, 0] = state.backstresses[0]
        latent_memories[point, 1] = state.backstresses[1] + state.backstresses[2]
        radius[point] = law.current_yield_stress(peeq[point]) - law.yield_stress
    return {
        "strain": tensor_to_voigt(strains),
        "stress_pa": tensor_to_voigt(stress),
        "plastic_strain": tensor_to_voigt(plastic),
        "peeq": peeq,
        "plastic_increment": increment,
        "memories_pa": tensor_to_voigt(latent_memories),
        "truth_memories_pa": tensor_to_voigt(truth_memories),
        "isotropic_radius_pa": radius,
        "time_coordinate": np.linspace(0.0, 1.0, count),
    }


def _add_observations(row: dict[str, object], arrays: dict[str, np.ndarray]) -> None:
    if row["cohort"] != "discretization_and_observation":
        return
    rng = np.random.default_rng(int(row["path_seed"]) + int(row["points"]) * 1009)
    strain = arrays["strain"]
    stress = arrays["stress_pa"]
    strain_scale = max(float(np.max(np.abs(strain))), 1.0e-12)
    stress_scale = max(float(np.max(np.abs(stress))), 1.0)
    observed_strain = strain + rng.normal(
        scale=float(row["strain_noise_fraction"]) * strain_scale,
        size=strain.shape,
    )
    observed_stress = stress + rng.normal(
        scale=float(row["stress_noise_fraction"]) * stress_scale,
        size=stress.shape,
    )
    keep = float(row["observation_keep_fraction"])
    mask = rng.random(len(strain)) < keep
    mask[0] = True
    mask[-1] = True
    arrays["observed_strain"] = observed_strain
    arrays["observed_stress_pa"] = observed_stress
    arrays["observation_mask"] = mask.astype(np.uint8)


def solve_row(row: dict[str, object], bases: dict[str, dict[str, np.ndarray]]) -> tuple[dict[str, np.ndarray], dict[str, float | bool]]:
    cohort = str(row["cohort"])
    extras: dict[str, np.ndarray] = {}
    if cohort == "long_cycle":
        strains = _long_cycle_history(row)
    elif cohort == "full_3d_nonproportional":
        strains = _full_3d_history(row)
    elif cohort == "structure_derived":
        strains, extras = _structure_history(row, bases)
    elif cohort == "discretization_and_observation":
        strains = _standard_history(row)
    else:
        raise ValueError(f"Unknown cohort: {cohort}")
    arrays = _integrate_reference(strains)
    arrays.update(extras)
    _add_observations(row, arrays)
    metrics = boundary_quality(arrays)
    metrics["maximum_equivalent_total_strain"] = float(np.max(_equivalent_strain(strains)))
    metrics["trajectory_point_count"] = int(len(strains))
    metrics["plastic_step_count"] = int(np.count_nonzero(arrays["plastic_increment"] > 1.0e-12))
    return arrays, metrics


def _agentfem_commit() -> str:
    return subprocess.run(
        ("git", "rev-parse", "HEAD"),
        cwd=AGENTFEM_ROOT,
        check=True,
        capture_output=True,
        text=True,
    ).stdout.strip()


def _record(row: dict[str, object], metrics: dict[str, float | bool]) -> dict[str, object]:
    return {
        "sample_id": str(row["case_id"]),
        "cohort": str(row["cohort"]),
        "split": str(row["split"]),
        "group_id": str(row["group_id"]),
        "path_family": str(row["path_family"]),
        "points": int(row["points"]),
        "cycle_count": int(row["cycle_count"]),
        "maximum_equivalent_strain": float(row["maximum_equivalent_strain"]),
        "all_finite": bool(metrics["all_finite"]),
        "plastic_step_count": int(metrics["plastic_step_count"]),
        "maximum_absolute_stress_pa": float(metrics["maximum_absolute_stress_pa"]),
        "maximum_peeq": float(metrics["maximum_peeq"]),
        "maximum_yield_surface_relative_residual": float(metrics["maximum_yield_surface_relative_residual"]),
        "minimum_peeq_increment": float(metrics["minimum_peeq_increment"]),
        "maximum_plastic_strain_trace": float(metrics["maximum_plastic_strain_trace"]),
        "observation_protocol": str(row["observation_protocol"]),
    }


def generate(*, force: bool = False, limit: int | None = None) -> dict[str, object]:
    rows = design()
    if limit is not None:
        rows = rows[: int(limit)]
    DATA_DIR.mkdir(parents=True, exist_ok=True)
    ARTIFACT_DIR.mkdir(parents=True, exist_ok=True)
    if DATA_PATH.exists() and not force:
        raise FileExistsError(f"{DATA_PATH} exists; pass --force to replace it.")
    need_structures = any(row["cohort"] == "structure_derived" for row in rows)
    bases = build_structure_bases(force=force) if need_structures else {}
    temporary = DATA_PATH.with_suffix(".h5.tmp")
    records: list[dict[str, object]] = []
    started = time.perf_counter()
    with h5py.File(temporary, "w") as h5:
        h5.attrs["schema"] = "agentfem.physics-data.denim-capability-extension"
        h5.attrs["schema_version"] = "4.0.0"
        h5.attrs["material_json"] = json.dumps(MATERIAL, sort_keys=True)
        h5.attrs["scope"] = str(load_config()["scope"])
        for index, row in enumerate(rows):
            arrays, metrics = solve_row(row, bases)
            if not bool(metrics["all_finite"]):
                raise RuntimeError(f"Non-finite trajectory at index {index}.")
            if float(metrics["minimum_peeq_increment"]) < -1.0e-12:
                raise RuntimeError(f"PEEQ decreased at index {index}.")
            if float(metrics["maximum_yield_surface_relative_residual"]) > 1.0e-8:
                raise RuntimeError(f"Yield residual failed at index {index}.")
            group = h5.create_group(f"{index:05d}")
            for key in (
                "case_id",
                "cohort",
                "split",
                "group_id",
                "path_family",
                "observation_protocol",
            ):
                group.attrs[key] = str(row[key])
            group.attrs["points"] = int(row["points"])
            group.attrs["cycle_count"] = int(row["cycle_count"])
            group.attrs["parameters_json"] = json.dumps(row, sort_keys=True)
            group.attrs["quality_json"] = json.dumps(metrics, sort_keys=True)
            for name, value in arrays.items():
                group.create_dataset(name, data=value, compression="gzip", shuffle=True)
            records.append(_record(row, metrics))
            if (index + 1) % 50 == 0 or index + 1 == len(rows):
                print(f"generated {index + 1}/{len(rows)}", flush=True)
    os.replace(temporary, DATA_PATH)
    INDEX_PATH.write_text(
        "".join(json.dumps(record, sort_keys=True) + "\n" for record in records),
        encoding="utf-8",
    )
    with INDEX_CSV_PATH.open("w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=list(records[0]))
        writer.writeheader()
        writer.writerows(records)
    manifest: dict[str, object] = {
        "schema": "agentfem.physics-data.denim-capability-extension",
        "schema_version": "4.0.0",
        "sample_count": len(records),
        "complete_release": len(records) == 1000,
        "cohort_counts": dict(sorted(Counter(record["cohort"] for record in records).items())),
        "split_counts": dict(sorted(Counter(record["split"] for record in records).items())),
        "path_family_counts": dict(sorted(Counter(record["path_family"] for record in records).items())),
        "point_count_distribution": dict(sorted(Counter(str(record["points"]) for record in records).items())),
        "group_count": len({record["group_id"] for record in records}),
        "data_sha256": _sha256(DATA_PATH),
        "index_jsonl_sha256": _sha256(INDEX_PATH),
        "index_csv_sha256": _sha256(INDEX_CSV_PATH),
        "structure_bases_sha256": _sha256(STRUCTURE_BASIS_PATH) if STRUCTURE_BASIS_PATH.exists() else None,
        "data_bytes": DATA_PATH.stat().st_size,
        "generation_seconds": time.perf_counter() - started,
        "agentfem_commit": _agentfem_commit(),
        "reference_material": "hidden three-memory Chaboche with tabulated isotropic hardening",
        "quality": {
            "all_finite_failures": sum(not bool(record["all_finite"]) for record in records),
            "maximum_yield_surface_relative_residual": max(float(record["maximum_yield_surface_relative_residual"]) for record in records),
            "minimum_peeq_increment": min(float(record["minimum_peeq_increment"]) for record in records),
            "maximum_plastic_strain_trace": max(float(record["maximum_plastic_strain_trace"]) for record in records),
            "minimum_plastic_step_count": min(int(record["plastic_step_count"]) for record in records),
        },
        "structure_fidelity": "AgentFEM linear-elastic unit-load strain bases with one-way nonlinear material replay; no coupled elastoplastic redistribution claim",
        "counting_rule": "One sample is one complete trajectory. Observation noise/masks are fields, not extra samples. Matched resolutions are explicitly grouped.",
    }
    _write_json(MANIFEST_PATH, manifest)
    _write_json(ARTIFACT_DIR / "quality.json", manifest)
    return manifest


def audit() -> dict[str, object]:
    manifest = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
    rows = [json.loads(line) for line in INDEX_PATH.read_text(encoding="utf-8").splitlines() if line]
    with h5py.File(DATA_PATH, "r") as h5:
        groups = list(h5.keys())
        finite_failures = 0
        missing = []
        for group_name in groups:
            group = h5[group_name]
            required = (
                "strain",
                "stress_pa",
                "plastic_strain",
                "peeq",
                "plastic_increment",
                "memories_pa",
                "truth_memories_pa",
                "isotropic_radius_pa",
                "time_coordinate",
            )
            for name in required:
                if name not in group:
                    missing.append(f"{group_name}:{name}")
                elif not np.isfinite(group[name][...]).all():
                    finite_failures += 1
            if group.attrs["cohort"] == "discretization_and_observation":
                for name in ("observed_strain", "observed_stress_pa", "observation_mask"):
                    if name not in group:
                        missing.append(f"{group_name}:{name}")
            if group.attrs["cohort"] == "structure_derived":
                for name in ("source_strain_basis", "load_mode_coefficients", "source_coordinate"):
                    if name not in group:
                        missing.append(f"{group_name}:{name}")
    audit_result = {
        "sample_count": len(rows),
        "hdf5_group_count": len(groups),
        "case_id_unique": len({row["sample_id"] for row in rows}) == len(rows),
        "missing_required_fields": missing,
        "nonfinite_required_field_count": finite_failures,
        "data_sha256_matches_manifest": _sha256(DATA_PATH) == manifest["data_sha256"],
        "grouped_resolution_protocol": all(
            len([row for row in rows if row["group_id"] == group_id]) == 4
            for group_id in {row["group_id"] for row in rows if row["cohort"] == "discretization_and_observation"}
        ),
        "structure_group_count": len({row["group_id"] for row in rows if row["cohort"] == "structure_derived"}),
    }
    audit_result["passed"] = bool(
        audit_result["sample_count"] == 1000
        and audit_result["hdf5_group_count"] == 1000
        and audit_result["case_id_unique"]
        and not audit_result["missing_required_fields"]
        and audit_result["nonfinite_required_field_count"] == 0
        and audit_result["data_sha256_matches_manifest"]
        and audit_result["grouped_resolution_protocol"]
        and audit_result["structure_group_count"] == 4
    )
    _write_json(ARTIFACT_DIR / "audit.json", audit_result)
    return audit_result


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--force", action="store_true")
    parser.add_argument("--limit", type=int)
    parser.add_argument("--audit-only", action="store_true")
    args = parser.parse_args()
    if args.audit_only:
        report = audit()
    else:
        report = generate(force=args.force, limit=args.limit)
        if args.limit is None:
            report = {"generation": report, "audit": audit()}
    print(json.dumps(report, indent=2, sort_keys=True))


if __name__ == "__main__":
    main()