oinolan commited on
Commit
085fdaa
·
1 Parent(s): de12ca3

add optimization history from json plot

Browse files
Files changed (1) hide show
  1. plots.py +101 -0
plots.py CHANGED
@@ -1,5 +1,10 @@
 
 
 
 
1
  import matplotlib.pyplot as plt
2
  import numpy as np
 
3
  from keras import ops
4
  from matplotlib.patches import PathPatch
5
  from matplotlib.path import Path as pltPath
@@ -252,3 +257,99 @@ def plot_metrics(metrics, limits, out_path):
252
  bbox_to_anchor=(0.5, 1.02),
253
  )
254
  return fig
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+ from typing import Any, Dict, List
4
+
5
  import matplotlib.pyplot as plt
6
  import numpy as np
7
+ import tyro
8
  from keras import ops
9
  from matplotlib.patches import PathPatch
10
  from matplotlib.path import Path as pltPath
 
257
  bbox_to_anchor=(0.5, 1.02),
258
  )
259
  return fig
260
+
261
+
262
+ def plot_optimization_history_from_json(
263
+ trials_data: List[Dict[str, Any]], output_path: Path, method: str
264
+ ):
265
+ """Plot optimization history directly from JSON data."""
266
+
267
+ # Extract completed trials with values
268
+ completed_trials = [
269
+ t for t in trials_data if t["state"] == "COMPLETE" and t["value"] is not None
270
+ ]
271
+
272
+ if not completed_trials:
273
+ print("No completed trials found!")
274
+ return
275
+
276
+ # Sort by trial number
277
+ completed_trials.sort(key=lambda x: x["number"])
278
+
279
+ trial_numbers = [t["number"] for t in completed_trials]
280
+ values = [t["value"] for t in completed_trials]
281
+
282
+ # Apply seaborn styling
283
+ plt.style.use("seaborn-v0_8-darkgrid")
284
+
285
+ # Create the plot
286
+ fig, ax = plt.subplots(figsize=(5, 3), dpi=600)
287
+
288
+ # Plot all trial values with styling similar to plots.py
289
+ ax.scatter(
290
+ trial_numbers,
291
+ values,
292
+ c="#0057b7",
293
+ alpha=0.6,
294
+ s=30,
295
+ edgecolor="black",
296
+ linewidth=0.5,
297
+ )
298
+
299
+ # Plot best value so far
300
+ best_values = []
301
+ current_best = values[0]
302
+ for val in values:
303
+ if val > current_best: # Assuming maximization
304
+ current_best = val
305
+ best_values.append(current_best)
306
+
307
+ ax.plot(
308
+ trial_numbers,
309
+ best_values,
310
+ color="#d62d20",
311
+ linewidth=2.5,
312
+ label="Best Value",
313
+ marker="o",
314
+ markersize=4,
315
+ markevery=max(1, len(trial_numbers) // 20),
316
+ )
317
+
318
+ ax.set_xlabel("Trial", fontsize=11)
319
+ ax.set_ylabel("Objective Value", fontsize=11)
320
+ # ax.set_title("Optimization History", fontsize=12)
321
+ ax.legend(fontsize=10, frameon=False)
322
+
323
+ # Remove top and right spines like in plots.py
324
+ ax.spines["top"].set_visible(False)
325
+ ax.spines["right"].set_visible(False)
326
+ ax.tick_params(axis="both", which="major", labelsize=9)
327
+
328
+ # Save plot
329
+ fig.savefig(
330
+ output_path / f"optimization_history_{method}.png", dpi=600, bbox_inches="tight"
331
+ )
332
+ plt.close(fig)
333
+
334
+
335
+ def main(json_file: str, output_dir: str = "plots", method: str = "semantic_dps"):
336
+ json_path = Path(json_file)
337
+ if not json_path.exists():
338
+ raise FileNotFoundError(f"JSON file not found: {json_file}")
339
+
340
+ # Load trial data
341
+ with open(json_path, "r") as f:
342
+ trials_data = json.load(f)
343
+
344
+ print(f"Loaded {len(trials_data)} trials from {json_file}")
345
+
346
+ # Create output directory
347
+ output_path = Path(output_dir)
348
+ output_path.mkdir(parents=True, exist_ok=True)
349
+
350
+ print("Generating optimization history plot...")
351
+ plot_optimization_history_from_json(trials_data, output_path, method)
352
+
353
+
354
+ if __name__ == "__main__":
355
+ tyro.cli(main)