{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n\n# Saving/Resuming Study with RDB Backend\n\nAn RDB backend enables persistent experiments (i.e., to save and resume a study) as well as access to history of studies.\nIn addition, we can run multi-node optimization tasks with this feature, which is described in `distributed`.\n\nIn this section, let's try simple examples running on a local environment with SQLite DB.\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>You can also utilize other RDB backends, e.g., PostgreSQL or MySQL, by setting the storage argument to the DB's URL.\n    Please refer to `SQLAlchemy's document <https://docs.sqlalchemy.org/en/latest/core/engines.html#database-urls>`_ for how to set up the URL.</p></div>\n\n\n## New Study\n\nWe can create a persistent study by calling :func:`~optuna.study.create_study` function as follows.\nAn SQLite file ``example.db`` is automatically initialized with a new study record.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import logging\nimport sys\n\nimport optuna\n\n# Add stream handler of stdout to show the messages\noptuna.logging.get_logger(\"optuna\").addHandler(logging.StreamHandler(sys.stdout))\nstudy_name = \"example-study\"  # Unique identifier of the study.\nstorage_name = \"sqlite:///{}.db\".format(study_name)\nstudy = optuna.create_study(study_name=study_name, storage=storage_name)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "To run a study, call :func:`~optuna.study.Study.optimize` method passing an objective function.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def objective(trial):\n    x = trial.suggest_uniform(\"x\", -10, 10)\n    return (x - 2) ** 2\n\n\nstudy.optimize(objective, n_trials=3)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Resume Study\n\nTo resume a study, instantiate a :class:`~optuna.study.Study` object\npassing the study name ``example-study`` and the DB URL ``sqlite:///example-study.db``.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "study = optuna.create_study(study_name=study_name, storage=storage_name, load_if_exists=True)\nstudy.optimize(objective, n_trials=3)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Experimental History\n\nWe can access histories of studies and trials via the :class:`~optuna.study.Study` class.\nFor example, we can get all trials of ``example-study`` as:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "study = optuna.create_study(study_name=study_name, storage=storage_name, load_if_exists=True)\ndf = study.trials_dataframe(attrs=(\"number\", \"value\", \"params\", \"state\"))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The method :func:`~optuna.study.Study.trials_dataframe` returns a pandas dataframe like:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "print(df)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "A :class:`~optuna.study.Study` object also provides properties\nsuch as :attr:`~optuna.study.Study.trials`, :attr:`~optuna.study.Study.best_value`,\n:attr:`~optuna.study.Study.best_params` (see also `first`).\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "print(\"Best params: \", study.best_params)\nprint(\"Best value: \", study.best_value)\nprint(\"Best Trial: \", study.best_trial)\nprint(\"Trials: \", study.trials)"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.8.6"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}