File size: 7,501 Bytes
d22f9ea
 
 
bbb6cc7
d22f9ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbb6cc7
 
 
 
 
d22f9ea
 
bbb6cc7
d22f9ea
bbb6cc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d22f9ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbb6cc7
 
 
d22f9ea
 
bbb6cc7
d22f9ea
bbb6cc7
 
 
d22f9ea
 
 
bbb6cc7
 
 
d22f9ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Show two zero-strain states with different stresses in published train data.

Install: pip install numpy matplotlib huggingface_hub
Run: python show_material_memory.py
Offline: python show_material_memory.py --shard /path/to/part-00002.h5
Code: Apache-2.0; source data: CC BY 4.0, Haoming Luo / AgentFEM.
This reads a synthetic material-point history, not a DENIM prediction.
"""
import argparse
import hashlib
import json
from pathlib import Path

import numpy as np

REPO = "HaomingLuo/AgentFEM-Material-Loading-Memory"
REVISION = "cc9644aa5b51ac4f0ff5cccc9a42452de0d220a3"
FILE = "data/t2_material_loading_memory_v1/shards/part-00002.h5"
SHA256 = "952b90eed1ce3ac288487cf31180384fc12f79aa03d95e4885bfd73b85c9a46d"
SAMPLE = "00252"  # First training trajectory in the symmetric-cyclic J2 cohort.
EXCERPT_REVISION = "62cedc709b159c9faa652e0aff34ff48771b3f07"
EXCERPT_FILE = "example/training-history-00252.npz"
EXCERPT_SHA256 = "c16bd5da346dd6926d32c730ad9ad040c5bd9a51dccba92b1f8c4ae1dce8717f"
ARRAY_NAMES = ("total_strain", "signed_equivalent_strain",
               "signed_equivalent_stress_pa", "equivalent_plastic_strain")


def read_sample(path, excerpt=False):
    digest = hashlib.sha256(Path(path).read_bytes()).hexdigest()
    if digest != (EXCERPT_SHA256 if excerpt else SHA256):
        raise ValueError("Input checksum mismatch; use the pinned published file.")
    if excerpt:
        with np.load(path, allow_pickle=False) as packed:
            if (str(packed["split"]) != "train" or str(packed["sample_id"]) != SAMPLE
                    or str(packed["source_sha256"]) != SHA256):
                raise ValueError("Unexpected excerpt provenance.")
            arrays = {name: packed[name] for name in ARRAY_NAMES}
            case_id = str(packed["case_id"])
    else:
        import h5py  # Only needed when inspecting the complete source shard.
        with h5py.File(path, "r") as f:
            g = f[SAMPLE]
            if str(g.attrs["split"]) != "train":
                raise ValueError("Illustration must use training data only.")
            arrays = {name: g[name][:] for name in ARRAY_NAMES}
            case_id = str(g.attrs["case_id"])
    if not all(np.isfinite(a).all() for a in arrays.values()):
        raise ValueError("Non-finite trajectory.")
    # First two returns to zero after the virgin state, not maximum-gap selection.
    zero = np.flatnonzero(np.max(np.abs(arrays["total_strain"]), axis=(1, 2)) < 1e-12)
    zero = zero[zero > 0]
    if len(zero) < 2:
        raise ValueError("No two noninitial zero-strain states.")
    a, b = map(int, zero[:2])
    if not np.allclose(arrays["total_strain"][a], arrays["total_strain"][b], atol=1e-12, rtol=0):
        raise ValueError("The complete strain tensors differ.")
    return arrays, a, b, case_id


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    inputs = parser.add_mutually_exclusive_group()
    inputs.add_argument("--shard", type=Path, help="Original HDF5 shard (requires h5py)")
    inputs.add_argument("--sample", type=Path, help="Local 4.5 KB NPZ training excerpt")
    parser.add_argument("--out", type=Path, default=Path("memory-example"))
    args = parser.parse_args()
    if args.shard is None and args.sample is None:
        from huggingface_hub import hf_hub_download
        args.sample = Path(hf_hub_download(REPO, EXCERPT_FILE, repo_type="dataset", revision=EXCERPT_REVISION))
    using_excerpt = args.sample is not None
    d, a, b, case_id = read_sample(args.sample if using_excerpt else args.shard, excerpt=using_excerpt)
    strain = d["signed_equivalent_strain"] * 100
    stress = d["signed_equivalent_stress_pa"] / 1e6
    report = {"repository": REPO, "revision": REVISION, "shard_sha256": SHA256,
              "input_kind": "lossless_training_excerpt" if using_excerpt else "original_shard",
              "input_sha256": EXCERPT_SHA256 if using_excerpt else SHA256,
              "excerpt_revision": EXCERPT_REVISION if using_excerpt else None,
              "sample_id": SAMPLE, "case_id": case_id, "split": "train",
              "selection": "First two noninitial returns to zero strain; no interpolation",
              "states": [{"index": i, "signed_equivalent_strain": float(strain[i]/100),
                          "signed_equivalent_stress_MPa": float(stress[i]),
                          "equivalent_plastic_strain": float(d["equivalent_plastic_strain"][i])}
                         for i in (a, b)],
              "stress_difference_MPa": float(abs(stress[b]-stress[a])),
              "scope": "Synthetic proportional deviatoric J2 material-point history; not experiment or model accuracy."}
    args.out.mkdir(parents=True, exist_ok=True)
    (args.out / "memory-evidence.json").write_text(json.dumps(report, indent=2)+"\n")
    np.savetxt(args.out / "memory-history.csv", np.column_stack((np.arange(len(strain)), strain/100, stress,
               d["equivalent_plastic_strain"])), delimiter=",", comments="",
               header="state,signed_equivalent_strain,signed_equivalent_stress_MPa,equivalent_plastic_strain")
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 11})
    bg, panel, fg, muted = "#081418", "#102127", "#edf3f1", "#97afb2"
    colors = ["#85d6cb", "#e9b16d"]
    fig, axes = plt.subplots(1, 2, figsize=(12, 5.7), facecolor=bg)
    fig.subplots_adjust(left=.085, right=.97, bottom=.23, top=.76, wspace=.3)
    for ax in axes:
        ax.set_facecolor(panel)
        ax.tick_params(colors=muted)
        ax.xaxis.label.set_color(fg); ax.yaxis.label.set_color(fg)
        for spine in ax.spines.values(): spine.set_color("#344a50")
        ax.grid(alpha=.12, color=muted)
    steps = np.arange(b+1)
    axes[0].plot(steps, strain[:b+1], color=fg, lw=2)
    axes[0].axhline(0, color=muted, lw=.8, ls="--")
    axes[0].set(xlabel="Loading state (not physical time)", ylabel="Signed equivalent strain / %")
    axes[1].plot(strain[:a+1], stress[:a+1], color=colors[0], lw=2)
    axes[1].plot(strain[a:b+1], stress[a:b+1], color=colors[1], lw=2)
    axes[1].axvline(0, color=muted, lw=.8, ls="--")
    axes[1].set(xlabel="Signed equivalent strain / %", ylabel="Signed equivalent stress / MPa")
    for label, i, color in zip(["A", "B"], (a, b), colors):
        axes[0].scatter(i, strain[i], color=color, s=65, zorder=5)
        axes[0].annotate(label, (i, strain[i]), xytext=(0, 12), textcoords="offset points", ha="center", color=color)
        axes[1].scatter(strain[i], stress[i], color=color, s=65, zorder=5)
        axes[1].annotate(f"{label}  {stress[i]:+.1f} MPa", (strain[i], stress[i]),
                         xytext=(12, 5), textcoords="offset points", color=color, fontsize=10,
                         bbox={"facecolor": panel, "edgecolor": "none", "pad": 2})
    fig.text(.085, .92, "Same strain. Different stress.", color=fg, size=25, weight="bold")
    fig.text(.085, .85, "The loading path leaves a material memory.", color=muted, size=14)
    fig.text(.085, .105, "A and B: zero total strain, different plastic states. No interpolation or neural prediction.", color=fg, size=10)
    fig.text(.085, .055, "AgentFEM  |  Synthetic J2 training history 00252  |  Data: CC BY 4.0", color=muted, size=9)
    fig.savefig(args.out / "material-memory.png", dpi=160, facecolor=bg)
    plt.close(fig)
    print(json.dumps(report, indent=2))


if __name__ == "__main__":
    main()