Skip to content

Commit c873f96

Browse files
committed
Changed saving and loading function so the logs can be saved as valid JSON objects
1 parent 626aafe commit c873f96

File tree

2 files changed

+26
-18
lines changed

2 files changed

+26
-18
lines changed

bayes_opt/logger.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,15 @@ def update(self, event: str, instance: BayesianOptimization) -> None:
298298
if "constraint" in data and isinstance(data["constraint"], np.ndarray):
299299
data["constraint"] = data["constraint"].tolist()
300300

301-
with self._path.open("a") as f:
302-
f.write(json.dumps(data) + "\n")
301+
# Read current data
302+
with self._path.open("r") as f:
303+
fileData = json.load(f)
304+
305+
# Append next data point
306+
fileData.append(data)
307+
308+
# Writes content back to a file
309+
with self._path.open("w") as f:
310+
json.dumps(fileData)
303311

304312
self._update_tracker(event, instance)

bayes_opt/util.py

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -39,22 +39,22 @@ def load_logs(
3939
logs = [logs]
4040

4141
for log in logs:
42-
with Path(log).open("r") as j:
43-
while True:
44-
try:
45-
iteration = next(j)
46-
except StopIteration:
47-
break
48-
49-
iteration = json.loads(iteration)
50-
try:
51-
optimizer.register(
52-
params=iteration["params"],
53-
target=iteration["target"],
54-
constraint_value=(iteration["constraint"] if optimizer.is_constrained else None),
55-
)
56-
except NotUniqueError:
57-
continue
42+
try:
43+
with Path(log).open("r") as fil:
44+
fileData = json.load(fil)
45+
except json.JSONDecodeError:
46+
print(f"ERROR: JSON decode error when decoding '{log}'")
47+
continue
48+
49+
for iteration in fileData:
50+
try:
51+
optimizer.register(
52+
params=iteration["params"],
53+
target=iteration["target"],
54+
constraint_value=(iteration["constraint"] if optimizer.is_constrained else None),
55+
)
56+
except NotUniqueError:
57+
continue
5858

5959
return optimizer
6060

0 commit comments

Comments
 (0)