Datasets:
Languages:
English
Size:
100K<n<1M
Tags:
additive-manufacturing
laser-powder-bed-fusion
smoothed-particle-hydrodynamics
melt-pool
keyhole
physics-simulation
DOI:
License:
Delete apply_human_labels.py
Browse files- apply_human_labels.py +0 -302
apply_human_labels.py
DELETED
|
@@ -1,302 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""
|
| 3 |
-
apply_human_labels.py
|
| 4 |
-
|
| 5 |
-
Override auto-labels in the refactored dataset with human-verified labels
|
| 6 |
-
from a labeler's CSV.
|
| 7 |
-
|
| 8 |
-
CSV columns expected:
|
| 9 |
-
name, hash, P, VX, LS, ST, bug_free, correctly_finished,
|
| 10 |
-
timestep, label_1, label_2, label_final
|
| 11 |
-
|
| 12 |
-
- `name` = original raw folder name (e.g. P-...VX-...LS-..._H-...)
|
| 13 |
-
- `timestep` = simulation timestep (matches frames.csv `timestep`)
|
| 14 |
-
- `label_final` = consensus label to apply (overrides the auto-label)
|
| 15 |
-
- `bug_free`, `correctly_finished` = experiment-level QC flags, propagated
|
| 16 |
-
into labeling_provenance.json for downstream filtering.
|
| 17 |
-
|
| 18 |
-
MATCHING:
|
| 19 |
-
1. Build index { original_folder_name -> sim_NNNNN/ } by reading every
|
| 20 |
-
metadata.json under <dataset_root>.
|
| 21 |
-
2. Group CSV rows by `name`. Skip rows where `label_final` is blank
|
| 22 |
-
(those frames are not yet finalized).
|
| 23 |
-
3. For each grouped experiment that matches a sim folder:
|
| 24 |
-
- Override frames.csv `label` column where `timestep` matches a
|
| 25 |
-
CSV-supplied timestep.
|
| 26 |
-
- Mark labeling_provenance.json as "human-verified" (or "mixed" if
|
| 27 |
-
not all frames were covered) and record audit info.
|
| 28 |
-
|
| 29 |
-
Frames in frames.csv whose timestep is NOT in the CSV keep their auto-label.
|
| 30 |
-
CSV rows whose timestep is NOT in frames.csv are counted in audit info but
|
| 31 |
-
otherwise ignored.
|
| 32 |
-
|
| 33 |
-
USAGE:
|
| 34 |
-
python apply_human_labels.py <csv_path> <dataset_root>
|
| 35 |
-
"""
|
| 36 |
-
|
| 37 |
-
import argparse
|
| 38 |
-
import csv
|
| 39 |
-
import json
|
| 40 |
-
import sys
|
| 41 |
-
from collections import defaultdict
|
| 42 |
-
from datetime import datetime, timezone
|
| 43 |
-
from pathlib import Path
|
| 44 |
-
|
| 45 |
-
SCRIPT_VERSION = "human-label-override v0.1"
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
def build_sim_index(dataset_root):
|
| 49 |
-
"""Return { original_folder_name -> sim_dir } by reading metadata.json files."""
|
| 50 |
-
index = {}
|
| 51 |
-
for sim_dir in sorted(dataset_root.iterdir()):
|
| 52 |
-
if not sim_dir.is_dir() or not sim_dir.name.startswith("sim_"):
|
| 53 |
-
continue
|
| 54 |
-
meta_file = sim_dir / "metadata.json"
|
| 55 |
-
if not meta_file.is_file():
|
| 56 |
-
continue
|
| 57 |
-
try:
|
| 58 |
-
with open(meta_file) as f:
|
| 59 |
-
meta = json.load(f)
|
| 60 |
-
except (json.JSONDecodeError, OSError):
|
| 61 |
-
continue
|
| 62 |
-
name = meta.get("original_folder_name")
|
| 63 |
-
if name:
|
| 64 |
-
index[name] = sim_dir
|
| 65 |
-
return index
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
def parse_csv(csv_path):
|
| 69 |
-
"""
|
| 70 |
-
Group CSV rows by experiment name.
|
| 71 |
-
Returns: { name: {"bug_free": int|None, "correctly_finished": int|None,
|
| 72 |
-
"frames": {timestep: label_final}} }
|
| 73 |
-
Rows with empty `label_final` are dropped.
|
| 74 |
-
|
| 75 |
-
Label normalization: any "Convection" in the CSV is rewritten to
|
| 76 |
-
"Conduction" (terminology fix).
|
| 77 |
-
"""
|
| 78 |
-
groups = defaultdict(lambda: {"bug_free": None,
|
| 79 |
-
"correctly_finished": None,
|
| 80 |
-
"frames": {}})
|
| 81 |
-
|
| 82 |
-
with open(csv_path, newline="") as f:
|
| 83 |
-
reader = csv.DictReader(f)
|
| 84 |
-
for row in reader:
|
| 85 |
-
name = (row.get("name") or "").strip()
|
| 86 |
-
if not name:
|
| 87 |
-
continue
|
| 88 |
-
label = (row.get("label_final") or "").strip()
|
| 89 |
-
if not label:
|
| 90 |
-
continue
|
| 91 |
-
if label == "Convection":
|
| 92 |
-
label = "Conduction"
|
| 93 |
-
try:
|
| 94 |
-
ts = int(row["timestep"])
|
| 95 |
-
except (KeyError, ValueError, TypeError):
|
| 96 |
-
continue
|
| 97 |
-
|
| 98 |
-
groups[name]["frames"][ts] = label
|
| 99 |
-
|
| 100 |
-
# Pick up QC flags (same value across rows for one experiment;
|
| 101 |
-
# last-wins is fine).
|
| 102 |
-
for flag in ("bug_free", "correctly_finished"):
|
| 103 |
-
raw = (row.get(flag) or "").strip()
|
| 104 |
-
if raw == "":
|
| 105 |
-
continue
|
| 106 |
-
try:
|
| 107 |
-
groups[name][flag] = int(raw)
|
| 108 |
-
except ValueError:
|
| 109 |
-
pass
|
| 110 |
-
return groups
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
def apply_to_one(sim_dir, ts_to_label, bug_free, correctly_finished, csv_path):
|
| 114 |
-
"""Override frames.csv labels and update labeling_provenance.json."""
|
| 115 |
-
frames_csv = sim_dir / "frames.csv"
|
| 116 |
-
if not frames_csv.is_file():
|
| 117 |
-
return {"error": "no frames.csv"}
|
| 118 |
-
|
| 119 |
-
with open(frames_csv) as f:
|
| 120 |
-
reader = csv.reader(f)
|
| 121 |
-
header = next(reader)
|
| 122 |
-
rows = list(reader)
|
| 123 |
-
|
| 124 |
-
if "label" not in header or "timestep" not in header:
|
| 125 |
-
return {"error": "frames.csv missing 'label' or 'timestep' column"}
|
| 126 |
-
|
| 127 |
-
label_col = header.index("label")
|
| 128 |
-
ts_col = header.index("timestep")
|
| 129 |
-
|
| 130 |
-
n_in_csv = len(ts_to_label)
|
| 131 |
-
n_overridden = 0
|
| 132 |
-
n_unchanged = 0
|
| 133 |
-
matched_ts = set()
|
| 134 |
-
|
| 135 |
-
for row in rows:
|
| 136 |
-
try:
|
| 137 |
-
ts = int(row[ts_col])
|
| 138 |
-
except (ValueError, IndexError):
|
| 139 |
-
n_unchanged += 1
|
| 140 |
-
continue
|
| 141 |
-
if ts in ts_to_label:
|
| 142 |
-
row[label_col] = ts_to_label[ts]
|
| 143 |
-
matched_ts.add(ts)
|
| 144 |
-
n_overridden += 1
|
| 145 |
-
else:
|
| 146 |
-
n_unchanged += 1
|
| 147 |
-
|
| 148 |
-
n_csv_unmatched = n_in_csv - len(matched_ts)
|
| 149 |
-
|
| 150 |
-
# Atomic write
|
| 151 |
-
tmp = frames_csv.with_suffix(".csv.tmp")
|
| 152 |
-
with open(tmp, "w", newline="") as f:
|
| 153 |
-
writer = csv.writer(f)
|
| 154 |
-
writer.writerow(header)
|
| 155 |
-
writer.writerows(rows)
|
| 156 |
-
tmp.replace(frames_csv)
|
| 157 |
-
|
| 158 |
-
# Update labeling_provenance.json
|
| 159 |
-
prov_file = sim_dir / "labeling_provenance.json"
|
| 160 |
-
prov = {}
|
| 161 |
-
if prov_file.is_file():
|
| 162 |
-
try:
|
| 163 |
-
with open(prov_file) as f:
|
| 164 |
-
prov = json.load(f)
|
| 165 |
-
except json.JSONDecodeError:
|
| 166 |
-
prov = {}
|
| 167 |
-
|
| 168 |
-
now = datetime.now(timezone.utc).isoformat()
|
| 169 |
-
full_coverage = (n_unchanged == 0 and n_csv_unmatched == 0)
|
| 170 |
-
|
| 171 |
-
prov.update({
|
| 172 |
-
"method": "human-verified" if full_coverage else "mixed",
|
| 173 |
-
"n_frames_human_verified": n_overridden,
|
| 174 |
-
"labeled_at": now,
|
| 175 |
-
"tool_version": SCRIPT_VERSION,
|
| 176 |
-
"human_verification": {
|
| 177 |
-
"csv_path": str(csv_path.resolve()),
|
| 178 |
-
"applied_at": now,
|
| 179 |
-
"n_csv_rows_for_experiment": n_in_csv,
|
| 180 |
-
"n_csv_rows_overridden": n_overridden,
|
| 181 |
-
"n_csv_rows_unmatched": n_csv_unmatched,
|
| 182 |
-
"n_frames_unchanged": n_unchanged,
|
| 183 |
-
"bug_free": bug_free,
|
| 184 |
-
"correctly_finished": correctly_finished,
|
| 185 |
-
},
|
| 186 |
-
})
|
| 187 |
-
|
| 188 |
-
with open(prov_file, "w") as f:
|
| 189 |
-
json.dump(prov, f, indent=2)
|
| 190 |
-
|
| 191 |
-
return {
|
| 192 |
-
"n_overridden": n_overridden,
|
| 193 |
-
"n_unchanged": n_unchanged,
|
| 194 |
-
"n_csv_unmatched": n_csv_unmatched,
|
| 195 |
-
"bug_free": bug_free,
|
| 196 |
-
"correctly_finished": correctly_finished,
|
| 197 |
-
"full_coverage": full_coverage,
|
| 198 |
-
}
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
def main():
|
| 202 |
-
ap = argparse.ArgumentParser(description=__doc__,
|
| 203 |
-
formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 204 |
-
ap.add_argument("csv_path", type=Path,
|
| 205 |
-
help="Path to labeler's CSV (with label_final column)")
|
| 206 |
-
ap.add_argument("dataset_root", type=Path,
|
| 207 |
-
help="Dataset root containing sim_NNNNN/ folders")
|
| 208 |
-
args = ap.parse_args()
|
| 209 |
-
|
| 210 |
-
if not args.csv_path.is_file():
|
| 211 |
-
sys.exit(f"ERROR: CSV not found: {args.csv_path}")
|
| 212 |
-
if not args.dataset_root.is_dir():
|
| 213 |
-
sys.exit(f"ERROR: dataset root not found: {args.dataset_root}")
|
| 214 |
-
|
| 215 |
-
print(f"Indexing dataset: {args.dataset_root}")
|
| 216 |
-
index = build_sim_index(args.dataset_root)
|
| 217 |
-
print(f" {len(index)} sim folders found\n")
|
| 218 |
-
|
| 219 |
-
print(f"Parsing CSV: {args.csv_path}")
|
| 220 |
-
groups = parse_csv(args.csv_path)
|
| 221 |
-
print(f" {len(groups)} experiments with >= 1 finalized label\n")
|
| 222 |
-
|
| 223 |
-
print("Applying human labels...\n")
|
| 224 |
-
n_applied = 0
|
| 225 |
-
n_no_match = 0
|
| 226 |
-
n_error = 0
|
| 227 |
-
tot_csv = 0
|
| 228 |
-
tot_overridden = 0
|
| 229 |
-
n_full = 0
|
| 230 |
-
n_partial = 0
|
| 231 |
-
n_with_qc_issue = 0
|
| 232 |
-
|
| 233 |
-
for name in sorted(groups.keys()):
|
| 234 |
-
data = groups[name]
|
| 235 |
-
n_csv_rows = len(data["frames"])
|
| 236 |
-
tot_csv += n_csv_rows
|
| 237 |
-
|
| 238 |
-
sim_dir = index.get(name)
|
| 239 |
-
if sim_dir is None:
|
| 240 |
-
print(f" [NO MATCH] {name[:90]}... ({n_csv_rows} CSV rows)")
|
| 241 |
-
n_no_match += 1
|
| 242 |
-
continue
|
| 243 |
-
|
| 244 |
-
result = apply_to_one(sim_dir, data["frames"],
|
| 245 |
-
data["bug_free"], data["correctly_finished"],
|
| 246 |
-
args.csv_path)
|
| 247 |
-
if "error" in result:
|
| 248 |
-
print(f" [ERROR] {sim_dir.name}: {result['error']}")
|
| 249 |
-
n_error += 1
|
| 250 |
-
continue
|
| 251 |
-
|
| 252 |
-
flags = []
|
| 253 |
-
if result["bug_free"] == 0:
|
| 254 |
-
flags.append("BUG")
|
| 255 |
-
n_with_qc_issue += 1
|
| 256 |
-
if result["correctly_finished"] == 0:
|
| 257 |
-
flags.append("UNFINISHED")
|
| 258 |
-
n_with_qc_issue += 1 if result["bug_free"] != 0 else 0
|
| 259 |
-
if result["n_csv_unmatched"]:
|
| 260 |
-
flags.append(f"csv_unmatched={result['n_csv_unmatched']}")
|
| 261 |
-
if result["n_unchanged"]:
|
| 262 |
-
flags.append(f"unlabeled={result['n_unchanged']}")
|
| 263 |
-
flag_str = (" [" + ", ".join(flags) + "]") if flags else ""
|
| 264 |
-
|
| 265 |
-
coverage = "FULL" if result["full_coverage"] else "MIXED"
|
| 266 |
-
print(f" [OK] {sim_dir.name}: overrode {result['n_overridden']:4d} frames "
|
| 267 |
-
f"({coverage}){flag_str}")
|
| 268 |
-
|
| 269 |
-
if result["full_coverage"]:
|
| 270 |
-
n_full += 1
|
| 271 |
-
else:
|
| 272 |
-
n_partial += 1
|
| 273 |
-
n_applied += 1
|
| 274 |
-
tot_overridden += result["n_overridden"]
|
| 275 |
-
|
| 276 |
-
# Index entries not represented in the CSV at all (still auto-labeled)
|
| 277 |
-
n_no_csv = len(index) - n_applied - n_error
|
| 278 |
-
|
| 279 |
-
print()
|
| 280 |
-
print("=" * 72)
|
| 281 |
-
print("SUMMARY")
|
| 282 |
-
print("=" * 72)
|
| 283 |
-
print(f"CSV experiments with finalized labels: {len(groups)}")
|
| 284 |
-
print(f" applied to dataset (full coverage): {n_full}")
|
| 285 |
-
print(f" applied to dataset (mixed coverage): {n_partial}")
|
| 286 |
-
print(f" no matching sim folder: {n_no_match}")
|
| 287 |
-
if n_error:
|
| 288 |
-
print(f" errors: {n_error}")
|
| 289 |
-
if n_with_qc_issue:
|
| 290 |
-
print(f" flagged bug_free=0 or unfinished: {n_with_qc_issue}")
|
| 291 |
-
print()
|
| 292 |
-
print(f"Sim folders in dataset: {len(index)}")
|
| 293 |
-
print(f" human-labeled by this run: {n_applied}")
|
| 294 |
-
print(f" still on auto-labels: {n_no_csv}")
|
| 295 |
-
print()
|
| 296 |
-
print(f"CSV label rows: {tot_csv}")
|
| 297 |
-
print(f" successfully overridden: {tot_overridden}")
|
| 298 |
-
print(f" CSV rows without matching frame: {tot_csv - tot_overridden}")
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
if __name__ == "__main__":
|
| 302 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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