|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from dataclasses import dataclass |
| 4 | +from pathlib import Path |
| 5 | +from time import time |
| 6 | +from uuid import uuid4 |
| 7 | + |
| 8 | +import numpy as np |
| 9 | + |
| 10 | +from poli.core.black_box_information import BlackBoxInformation |
| 11 | +from poli.core.exceptions import ObserverNotInitializedError |
| 12 | +from poli.core.util.abstract_observer import AbstractObserver |
| 13 | + |
| 14 | + |
| 15 | +@dataclass |
| 16 | +class CSVObserverInitInfo: |
| 17 | + """Initialization information for the CSVObserver.""" |
| 18 | + |
| 19 | + experiment_id: str |
| 20 | + experiment_path: str | Path = "./poli_results" |
| 21 | + |
| 22 | + |
| 23 | +class CSVObserver(AbstractObserver): |
| 24 | + """ |
| 25 | + A simple observer that logs to a CSV file, appending rows on each query. |
| 26 | + """ |
| 27 | + |
| 28 | + def __init__(self): |
| 29 | + self.has_been_initialized = False |
| 30 | + super().__init__() |
| 31 | + |
| 32 | + def initialize_observer( |
| 33 | + self, |
| 34 | + problem_setup_info: BlackBoxInformation, |
| 35 | + caller_info: CSVObserverInitInfo | dict, |
| 36 | + seed: int, |
| 37 | + ) -> object: |
| 38 | + """ |
| 39 | + Initializes the observer with the given information. |
| 40 | +
|
| 41 | + Parameters |
| 42 | + ---------- |
| 43 | + black_box_info : BlackBoxInformation |
| 44 | + The information about the black box. |
| 45 | + caller_info : dict | CSVObserverInitInfo |
| 46 | + Information used for logging. If a dictionary, it should contain the |
| 47 | + keys `experiment_id` and `experiment_path`. |
| 48 | + seed : int |
| 49 | + The seed used for the experiment. This is only logged, not used. |
| 50 | + """ |
| 51 | + self.info = problem_setup_info |
| 52 | + self.seed = seed |
| 53 | + self.unique_id = f"{uuid4()}"[:8] |
| 54 | + |
| 55 | + if isinstance(caller_info, CSVObserverInitInfo): |
| 56 | + caller_info = caller_info.__dict__ |
| 57 | + |
| 58 | + self.all_results_path = Path( |
| 59 | + caller_info.get("experiment_path", "./poli_results") |
| 60 | + ) |
| 61 | + self.experiment_path = self.all_results_path / problem_setup_info.name |
| 62 | + self.experiment_path.mkdir(exist_ok=True, parents=True) |
| 63 | + self._write_gitignore() |
| 64 | + |
| 65 | + self.experiment_id = caller_info.get( |
| 66 | + "experiment_id", |
| 67 | + f"{int(time())}_experiment_{problem_setup_info.name}_{seed}_{self.unique_id}", |
| 68 | + ) |
| 69 | + |
| 70 | + self.csv_file_path = self.experiment_path / f"{self.experiment_id}.csv" |
| 71 | + self.save_header() |
| 72 | + self.has_been_initialized = True |
| 73 | + |
| 74 | + def _write_gitignore(self): |
| 75 | + if not (self.all_results_path / ".gitignore").exists(): |
| 76 | + with open(self.all_results_path / ".gitignore", "w") as f: |
| 77 | + f.write("*\n") |
| 78 | + |
| 79 | + def _make_folder_for_experiment(self): |
| 80 | + self.experiment_path.mkdir(exist_ok=True, parents=True) |
| 81 | + |
| 82 | + def _validate_input(self, x: np.ndarray, y: np.ndarray) -> None: |
| 83 | + if x.ndim != 2: |
| 84 | + raise ValueError(f"x should be 2D, got {x.ndim}D instead.") |
| 85 | + if y.ndim != 2: |
| 86 | + raise ValueError(f"y should be 2D, got {y.ndim}D instead.") |
| 87 | + if x.shape[0] != y.shape[0]: |
| 88 | + raise ValueError( |
| 89 | + f"x and y should have the same number of samples, got {x.shape[0]} and {y.shape[0]} respectively." |
| 90 | + ) |
| 91 | + |
| 92 | + def _ensure_proper_shape(self, x: np.ndarray) -> np.ndarray: |
| 93 | + if x.ndim == 1: |
| 94 | + return x.reshape(-1, 1) |
| 95 | + return x |
| 96 | + |
| 97 | + def observe(self, x: np.ndarray, y: np.ndarray, context=None) -> None: |
| 98 | + if not self.has_been_initialized: |
| 99 | + raise ObserverNotInitializedError( |
| 100 | + "The observer has not been initialized. Please call `initialize_observer` first." |
| 101 | + ) |
| 102 | + x = self._ensure_proper_shape(x) |
| 103 | + self._validate_input(x, y) |
| 104 | + self.append_results(["".join(x_i) for x_i in x], [y_i for y_i in y.flatten()]) |
| 105 | + |
| 106 | + def save_header(self): |
| 107 | + self._make_folder_for_experiment() |
| 108 | + with open(self.csv_file_path, "w") as f: |
| 109 | + f.write("x,y\n") |
| 110 | + |
| 111 | + def append_results(self, x: list[str], y: list[float]): |
| 112 | + with open(self.csv_file_path, "a") as f: |
| 113 | + for x_i, y_i in zip(x, y): |
| 114 | + f.write(f"{x_i},{y_i}\n") |
0 commit comments