From c873f96d3982412c2cb76b2f1f39bb0ec1b7444c Mon Sep 17 00:00:00 2001 From: Fernando Date: Wed, 26 Mar 2025 08:36:41 -0300 Subject: [PATCH] Changed saving and loading function so the logs can be saved as valid JSON objects --- bayes_opt/logger.py | 12 ++++++++++-- bayes_opt/util.py | 32 ++++++++++++++++---------------- 2 files changed, 26 insertions(+), 18 deletions(-) diff --git a/bayes_opt/logger.py b/bayes_opt/logger.py index 0f5cd41c2..d6b58a3fc 100644 --- a/bayes_opt/logger.py +++ b/bayes_opt/logger.py @@ -298,7 +298,15 @@ def update(self, event: str, instance: BayesianOptimization) -> None: if "constraint" in data and isinstance(data["constraint"], np.ndarray): data["constraint"] = data["constraint"].tolist() - with self._path.open("a") as f: - f.write(json.dumps(data) + "\n") + # Read current data + with self._path.open("r") as f: + fileData = json.load(f) + + # Append next data point + fileData.append(data) + + # Writes content back to a file + with self._path.open("w") as f: + json.dumps(fileData) self._update_tracker(event, instance) diff --git a/bayes_opt/util.py b/bayes_opt/util.py index 2795ca07a..3a6cf293e 100644 --- a/bayes_opt/util.py +++ b/bayes_opt/util.py @@ -39,22 +39,22 @@ def load_logs( logs = [logs] for log in logs: - with Path(log).open("r") as j: - while True: - try: - iteration = next(j) - except StopIteration: - break - - iteration = json.loads(iteration) - try: - optimizer.register( - params=iteration["params"], - target=iteration["target"], - constraint_value=(iteration["constraint"] if optimizer.is_constrained else None), - ) - except NotUniqueError: - continue + try: + with Path(log).open("r") as fil: + fileData = json.load(fil) + except json.JSONDecodeError: + print(f"ERROR: JSON decode error when decoding '{log}'") + continue + + for iteration in fileData: + try: + optimizer.register( + params=iteration["params"], + target=iteration["target"], + constraint_value=(iteration["constraint"] if optimizer.is_constrained else None), + ) + except NotUniqueError: + continue return optimizer