update optuna example
"import covasim as cv\n",
"import optuna as op\n",
"\n",
+ "# Create a (mutable) dictionary for global settings\n",
+ "g = sc.objdict()\n",
+ "g.name = 'my-example-calibration'\n",
+ "g.db_name = f'{g.name}.db'\n",
+ "g.storage = f'sqlite:///{g.db_name}'\n",
+ "g.n_workers = 4 # Define how many workers to run in parallel\n",
+ "g.n_trials = 25 # Define the number of trials, i.e. sim runs, per worker\n",
+ "\n",
"\n",
"def run_sim(pars, label=None, return_sim=False):\n",
" ''' Create and run a simulation '''\n",
"\n",
"def worker():\n",
" ''' Run a single worker '''\n",
- " study = op.load_study(storage=storage, study_name=name)\n",
- " output = study.optimize(run_trial, n_trials=n_trials)\n",
+ " study = op.load_study(storage=g.storage, study_name=g.name)\n",
+ " output = study.optimize(run_trial, n_trials=g.n_trials)\n",
" return output\n",
"\n",
"\n",
"def run_workers():\n",
" ''' Run multiple workers in parallel '''\n",
- " output = sc.parallelize(worker, n_workers)\n",
+ " output = sc.parallelize(worker, g.n_workers)\n",
" return output\n",
"\n",
"\n",
"def make_study():\n",
" ''' Make a study, deleting one if it already exists '''\n",
- " if os.path.exists(db_name):\n",
- " os.remove(db_name)\n",
- " print(f'Removed existing calibration {db_name}')\n",
- " output = op.create_study(storage=storage, study_name=name)\n",
+ " if os.path.exists(g.db_name):\n",
+ " os.remove(g.db_name)\n",
+ " print(f'Removed existing calibration {g.db_name}')\n",
+ " output = op.create_study(storage=g.storage, study_name=g.name)\n",
" return output\n",
"\n",
"\n",
"if __name__ == '__main__':\n",
"\n",
- " # Settings\n",
- " n_workers = 2 # Define how many workers to run in parallel\n",
- " n_trials = 25 # Define the number of trials, i.e. sim runs, per worker\n",
- " name = 'my-example-calibration'\n",
- " db_name = f'{name}.db'\n",
- " storage = f'sqlite:///{db_name}'\n",
- "\n",
" # Run the optimization\n",
" t0 = sc.tic()\n",
" make_study()\n",
" run_workers()\n",
- " study = op.load_study(storage=storage, study_name=name)\n",
+ " study = op.load_study(storage=g.storage, study_name=g.name)\n",
" best_pars = study.best_params\n",
" T = sc.toc(t0, output=True)\n",
" print(f'\\n\\nOutput: {best_pars}, time: {T:0.1f} s')"
],
"metadata": {
"kernelspec": {
- "display_name": "Python 3",
- "language": "python",
+ "display_name": "Python 3 (Spyder)",
+ "language": "python3",
"name": "python3"
},
"language_info": {
