Skip to content

Save

save(experiment)

Save the experiment to a file.

Args

experiment : Experiment The experiment to save.

Raises

ValueError If the experiment does not have a database attribute.

Examples

save minto.Experiment object to a file. This function is called as a method of minto.Experiment object.

import minto experiment = minto.Experiment() experiment.save()

Source code in minto/io/save.py
def save(experiment: Experiment) -> None:
    """Save the experiment to a file.

    Args
    ----------
    experiment : Experiment
        The experiment to save.

    Raises
    ----------
    ValueError
        If the experiment does not have a database attribute.

    Examples
    ----------
    save [minto.Experiment][minto.experiment.experiment.Experiment] object to a file.
    This function is called as a method of [minto.Experiment][minto.experiment.experiment.Experiment] object.
    >>> import minto
    >>> experiment = minto.Experiment()
    >>> experiment.save()
    """
    database: DatabaseSchema = getattr(experiment, "database")

    base_dir = experiment.savedir / experiment.name

    keys: list[Literal["index", "solver", "parameter", "result"]] = [
        "index",
        "solver",
        "parameter",
        "result",
    ]
    dtypes = {}
    for key in keys:
        dtypes[key] = {"info": {}, "content": {}}

    for key in keys:
        if key == "index":
            with open(base_dir / "index.json", "w") as f:
                df = database[key].dataframe()
                index = {
                    "experiment_name": experiment.name,
                    "run_id_range": [
                        int(df["run_id"].min()),
                        int(df["run_id"].max()) + 1,
                    ],
                }
                json.dump(index, f)
            dtypes[key] = database[key].pandas_dtypes
        else:
            data_dir = base_dir / key

            # get dtypes
            dtypes[key]["info"] = database[key]["info"].pandas_dtypes
            dtypes[key]["content"] = database[key]["content"].pandas_dtypes

            # save info
            with open(data_dir / "info.json", "w") as f:
                df = database[key]["info"].dataframe()
                if df.empty:
                    info = {
                        "experiment_name": experiment.name,
                        "runs": {},
                    }
                else:
                    info = {
                        "experiment_name": experiment.name,
                        "runs": df.groupby(f"{key}_name")[["run_id", f"{key}_id"]]
                        .apply(lambda x: x.to_dict(orient="list"))
                        .to_dict(),
                    }
                json.dump(info, f)

            # save content
            _save_content(database, key, base_dir)

    with open(base_dir / "dtypes.json", "w") as f:
        json.dump(dtypes, f)