File size: 15,260 Bytes
2abd452
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Package saved SCDDPM samples and build the dataset README figures.

Use GenISys_Env. This reads existing Ada experiment exports only: no model,
physics evaluation, or CAD generation is executed.
"""

import argparse
import csv
import hashlib
import json
from pathlib import Path
import shutil

import matplotlib
matplotlib.use("Agg")
from matplotlib import pyplot as plt
from matplotlib.ticker import FuncFormatter
import numpy as np
import pandas as pd


STUDY = Path("range_subsystem_redesign_experiment_results")
GENERATED = Path("generated/scddpm_rfr_fixed_range")
RANGES = (1000, 5000, 8000)
KEYS = ["Architecture", "Study", "Arm", "Range_nmi", "Batch", "Sample_In_Batch",
        "Feasibility_Alpha", "Performance_Alpha"]
RAW_FILES = (
    "Generated_Controls_133.csv.gz", "Submitted_Designs_189.csv.gz",
    "Exact_Results.csv.gz", "Postprocessing_Log.csv.gz",
    "exact_evaluation/compiled/Performance.csv.gz",
    "exact_evaluation/compiled/Constraint_Evaluations.csv.gz",
    "exact_evaluation/compiled/Evaluation_Failures.csv.gz",
    "exact_evaluation/compiled/Sample_Status.csv.gz",
    "exact_evaluation/compiled/Submitted_189_Parameter_Vectors.csv.gz",
)
COLORS = ("#357A84", "#4A6092", "#A55843")


def sha256(path):
    with path.open("rb") as stream:
        return hashlib.file_digest(stream, "sha256").hexdigest()


def write_csv(table, path):
    path.parent.mkdir(parents=True, exist_ok=True)
    compression = {"method": "gzip", "mtime": 0} if path.name.endswith(".gz") else None
    table.to_csv(path, index=False, compression=compression)


def package_samples(source_root, release):
    study_root = source_root / STUDY
    output = release / GENERATED
    output.mkdir(parents=True, exist_ok=True)
    manifest = json.loads((release / "file_manifest.json").read_text())
    manifest = [row for row in manifest if not row["path"].startswith(GENERATED.as_posix() + "/")]
    with (study_root / "ARCHIVE_MANIFEST.csv").open(newline="") as stream:
        archived = {row["Archive_Path"]: row["SHA256"] for row in csv.DictReader(stream)}
    source_records = []
    tables = []

    # Copy the original submissions, controls, outcomes, and compiled evidence
    # for every production attempt in the three approved guided SCDDPM arms.
    for voyage_range in RANGES:
        for batch in range(10):
            source_batch = (study_root / "production_samples_and_evaluations/fixed_range/scddpm"
                            / f"range_{voyage_range}/rfr_guided/batch_{batch:02d}")
            target_batch = output / f"raw/range_{voyage_range}/batch_{batch:02d}"
            for filename in RAW_FILES:
                source = source_batch / filename
                target = target_batch / filename
                target.parent.mkdir(parents=True, exist_ok=True)
                observed = sha256(source)
                expected = archived[source.relative_to(study_root).as_posix()]
                if observed != expected:
                    raise RuntimeError(f"Archived source hash differs: {source}")
                shutil.copy2(source, target)
                if sha256(target) != observed:
                    raise RuntimeError(f"Copied source hash differs: {target}")
                record = {"path": target.relative_to(release).as_posix(),
                          "bytes": target.stat().st_size, "sha256": observed,
                          "source": source.relative_to(source_root).as_posix(),
                          "archive_sha256_verified": True}
                manifest.append(record)
                source_records.append(record)

            # Match the original metadata keys, never the reused evaluator Index.
            submissions = pd.read_csv(source_batch / "Submitted_Designs_189.csv.gz",
                                      float_precision="round_trip")
            results = pd.read_csv(source_batch / "Exact_Results.csv.gz",
                                  float_precision="round_trip")
            joined = submissions.merge(results, on=KEYS, how="outer", validate="one_to_one", indicator=True)
            if len(joined) != 100 or not joined["_merge"].eq("both").all():
                raise RuntimeError(f"Unmatched submission/outcome records: {source_batch}")
            joined = joined.drop(columns="_merge")
            joined.insert(0, "Sample_ID", [f"scddpm_rfr_{voyage_range}_b{batch:02d}_s{int(i):03d}"
                                          for i in joined.Sample_In_Batch])
            joined.insert(1, "Population", "scddpm_rfr_generated")
            # This seed is reconstructed from the archived runner and config.
            joined.insert(2, "Sampling_Seed", 820000 + 2 * 10000 + voyage_range + batch)
            tables.append(joined)

    rows = pd.concat(tables, ignore_index=True)
    if len(rows) != 3000 or rows.Sample_ID.duplicated().any():
        raise RuntimeError("Generated release must retain 3,000 uniquely keyed attempts")
    if not rows.Voyage_Range.eq(rows.Range_nmi).all():
        raise RuntimeError("A submitted voyage range differs from its experiment assignment")
    write_csv(rows, output / "Generated_Designs.csv.gz")

    # Compute release summaries directly from the saved outcomes. Completion
    # and feasibility denominators include all attempts, including failures.
    summary = []
    for voyage_range, group in rows.groupby("Range_nmi", sort=True):
        feasible = group.Evaluator_Completed.eq(True) & group.Global_V1p1_Feasible.eq(True)
        rfr = group.loc[feasible, "Required_Freight_Rate_pounds_per_t"]
        summary.append({"Range_nmi": int(voyage_range), "Requested": len(group),
                        "Completed": int(group.Evaluator_Completed.eq(True).sum()),
                        "Fully_Feasible": int(feasible.sum()),
                        "Feasibility_Rate": float(feasible.mean()),
                        "Mean_Feasible_RFR_GBP_per_t": float(rfr.mean()),
                        "Median_Feasible_RFR_GBP_per_t": float(rfr.median())})
    summary = pd.DataFrame(summary)
    expected = pd.read_csv(study_root / "metrics/Fixed_Range_Arm_Summary.csv")
    expected = expected.loc[expected.Architecture.eq("scddpm") & expected.Arm.eq("rfr_guided")].sort_values("Range_nmi")
    for field in ("Requested", "Completed", "Fully_Feasible"):
        if not np.array_equal(summary[field].to_numpy(), expected[field].to_numpy()):
            raise RuntimeError(f"Generated counts differ from archived summary: {field}")
    if not np.allclose(summary.Mean_Feasible_RFR_GBP_per_t, expected.Mean_RFR_Feasible):
        raise RuntimeError("Generated RFR summary differs from the archived results")
    write_csv(summary, output / "Range_Summary.csv")

    # Preserve the exact study settings and checkpoint provenance as metadata.
    for name in ("range_subsystem_redesign_v1.json", "Checkpoint_Provenance.json"):
        source = study_root / "experiment" / name
        target = output / "provenance" / name
        target.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(source, target)
    receipt = {"source_study": STUDY.as_posix(), "architecture": "scddpm",
               "arm": "rfr_guided", "ranges_nmi": RANGES, "attempts": 3000,
               "source_files_copied": len(source_records), "all_archive_hashes_verified": True,
               "sample_key": "Sample_ID", "original_join_keys": KEYS,
               "sampling_seed_rule": "820000 + architecture_position(2)*10000 + Range_nmi + Batch",
               "sampling_seed_source_sha256": sha256(study_root / "experiment/code/range_subsystem_redesign_experiment.py"),
               "new_training_sampling_or_physics_evaluation": False,
               "copied_source_files": source_records}
    (output / "provenance/Release_Manifest.json").write_text(json.dumps(receipt, indent=2) + "\n")
    for target in (output / "Generated_Designs.csv.gz", output / "Range_Summary.csv",
                   *sorted((output / "provenance").iterdir())):
        manifest.append({"path": target.relative_to(release).as_posix(),
                         "bytes": target.stat().st_size, "sha256": sha256(target)})
    (release / "file_manifest.json").write_text(json.dumps(sorted(manifest, key=lambda row: row["path"]), indent=2) + "\n")
    print(summary.to_string(index=False), flush=True)
    return rows, summary


def save_figure(figure, release, name):
    directory = release / "figures"
    directory.mkdir(parents=True, exist_ok=True)
    for suffix in ("png", "svg"):
        figure.savefig(directory / f"{name}.{suffix}", dpi=220,
                       bbox_inches="tight", facecolor="white")
    plt.close(figure)


def build_figures(source_root, release):
    # Summarize the released rows; do not regenerate engineering outcomes.
    generated = pd.read_csv(release / GENERATED / "Generated_Designs.csv.gz", float_precision="round_trip")
    training = pd.read_csv(release / "Ship_Systems_Designs_v1p1/Unified_Training_Dataset/Training_Rows.csv.gz",
                           usecols=["Population", "Evaluation_Status", "Global_V1p1_Feasible"])
    plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 11,
                         "axes.spines.top": False, "axes.spines.right": False,
                         "axes.labelcolor": "#263746", "text.color": "#263746",
                         "svg.fonttype": "none"})
    states = []
    for label, group in (("Random", training.loc[training.Population.eq("random")]),
                         ("Repaired", training.loc[training.Population.eq("repaired")])):
        completed = group.Evaluation_Status.eq("completed")
        feasible = completed & group.Global_V1p1_Feasible.eq(True)
        states.append((label, int(feasible.sum()), int((completed & ~feasible).sum()), int((~completed).sum())))
    group = generated
    completed = group.Evaluator_Completed.eq(True)
    feasible = completed & group.Global_V1p1_Feasible.eq(True)
    states.append(("SCDDPM / RFR", int(feasible.sum()), int((completed & ~feasible).sum()), int((~completed).sum())))

    figure, axis = plt.subplots(figsize=(10.0, 3.5))
    values = np.asarray([row[1:] for row in states])
    fractions = values / values.sum(axis=1, keepdims=True)
    left = np.zeros(len(states))
    for position, (label, color) in enumerate(zip(
            ("Completed · feasible", "Completed · infeasible", "Evaluation not completed"),
            ("#357A84", "#B6C6D5", "#DAA081"))):
        axis.barh(np.arange(3), fractions[:, position], left=left, color=color, label=label, height=.52)
        for index in range(3):
            if fractions[index, position] >= .08:
                axis.text(left[index] + fractions[index, position] / 2, index,
                          f"{fractions[index,position]:.1%}", ha="center", va="center", fontsize=10,
                          color="white" if position == 0 else "#263746")
        left += fractions[:, position]
    axis.set_yticks(np.arange(3), [f"{row[0]}\nn = {sum(row[1:]):,}" for row in states])
    axis.invert_yaxis()
    axis.set_xlim(0, 1)
    axis.xaxis.set_major_formatter(FuncFormatter(lambda value, _: f"{value:.0%}"))
    axis.set_xlabel("Share of all released attempts in each population")
    axis.set_title("Dataset populations and saved evaluation status", loc="left", weight="bold", pad=18)
    axis.legend(loc="upper center", bbox_to_anchor=(.5, -.30), ncol=3, frameon=False, fontsize=9)
    figure.subplots_adjust(left=.17, bottom=.26)
    save_figure(figure, release, "dataset_populations")

    # Conditional RFR distributions are shown with their all-attempt success
    # counts, so a feasible-only performance plot does not hide failed designs.
    figure, axes = plt.subplots(1, 3, figsize=(11.5, 3.7))
    chart_rows = []
    for axis, voyage_range, color in zip(axes, RANGES, COLORS):
        group = generated.loc[generated.Range_nmi.eq(voyage_range)]
        feasible = group.Evaluator_Completed.eq(True) & group.Global_V1p1_Feasible.eq(True)
        values = group.loc[feasible, "Required_Freight_Rate_pounds_per_t"].dropna().to_numpy()
        median = float(np.median(values))
        axis.hist(values, bins=24, color=color, alpha=.88, edgecolor="white", linewidth=.4)
        axis.axvline(median, color="#263746", linestyle="--", linewidth=1.2)
        axis.set_title(f"{voyage_range:,} nmi", weight="bold")
        axis.text(.96, .96, f"{int(feasible.sum()):,} / {len(group):,} feasible\nMedian £{median:.2f}/t",
                  transform=axis.transAxes, ha="right", va="top", fontsize=9)
        axis.set_xlabel("Required freight rate (£/t)")
        axis.grid(axis="y", alpha=.15)
        axis.set_axisbelow(True)
        chart_rows.append({"Range_nmi": voyage_range, "Histogram_Rows": len(values), "Median_RFR": median})
    axes[0].set_ylabel("Feasible designs")
    figure.suptitle("SCDDPM with RFR guidance · saved feasible outcomes", x=.08, ha="left", weight="bold")
    figure.tight_layout(rect=(0, 0, 1, .92), w_pad=2)
    save_figure(figure, release, "scddpm_rfr_distributions")

    # Reuse the existing paper CAD plate without cropping or regenerating it.
    # It depicts a separate variable-mission validation cohort, not these runs.
    paper_source = source_root / "GenISys_Preprint/figures/fig_H1.png"
    paper_target = release / "figures/paper_generated_design_examples.png"
    shutil.copy2(paper_source, paper_target)
    figure_manifest = {"new_charts": ["dataset_populations", "scddpm_rfr_distributions"],
                       "population_counts": [{"Population": row[0], "Feasible": row[1],
                                              "Completed_Infeasible": row[2], "Not_Completed": row[3]} for row in states],
                       "rfr_chart_counts": chart_rows,
                       "paper_figure": {"source": str(paper_source.relative_to(source_root)),
                                        "sha256": sha256(paper_source), "copied_sha256": sha256(paper_target),
                                        "same_as_released_fixed_range_samples": False},
                       "new_geometry_generated": False}
    (release / "figures/figure_manifest.json").write_text(json.dumps(figure_manifest, indent=2) + "\n")
    manifest = json.loads((release / "file_manifest.json").read_text())
    manifest = [row for row in manifest if not row["path"].startswith("figures/")]
    for path in sorted((release / "figures").iterdir()):
        manifest.append({"path": path.relative_to(release).as_posix(),
                         "bytes": path.stat().st_size, "sha256": sha256(path)})
    (release / "file_manifest.json").write_text(json.dumps(sorted(manifest, key=lambda row: row["path"]), indent=2) + "\n")
    print("Created dataset and RFR charts; copied the existing paper CAD plate.", flush=True)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--source-root", type=Path, required=True)
    parser.add_argument("--stage", choices=("data", "figures", "all"), default="all")
    args = parser.parse_args()
    release = Path(__file__).resolve().parents[1]
    if args.stage in {"data", "all"}:
        package_samples(args.source_root, release)
    if args.stage in {"figures", "all"}:
        build_figures(args.source_root, release)