Quickstart¶
Start a Python project. In your manifest file, add a dependency on the COI. Make sure to pick a COI version that is supported by the application that will optimize your problem:
1[build-system]
2requires = ['setuptools']
3build-backend = 'setuptools.build_meta'
4
5[project]
6name = 'my-project'
7version = '1.0'
8dependencies = [
9 'cernml-coi >= 0.9.0',
10]
1[metadata]
2name = my-project
3version = 1.0
4
5[options]
6install_requires =
7 cernml-coi >= 0.9.0
1from setuptools import setup
2
3setup(
4 name='my-project',
5 version='1.0',
6 install_requires=[
7 'cernml-coi >= 0.9.0',
8 ],
9)
Now consider the following optimization problem: It is defined by an objective function and an initial point:
1import numpy as np
2
3def objective_function(x):
4 goal = np.array([0.123, -0.456])
5 return np.linalg.norm(x - goal)
6
7x0 = np.zeros(2)
Now, write a class that implements multiple of the optimization interfaces, specifically interfaces for single-objective numerical optimization and reinforcement learning.
8import gymnasium as gym
9import numpy as np
10from cernml import coi
11
12class Parabola(coi.SingleOptimizable, gym.Env):
13 metadata = {
14 "render_modes": [],
15 "cern.machine": coi.Machine.NO_MACHINE,
16 }
17
18 # Obervations for RL are 2D vectors in the box from -2 to +2.
19 observation_space = gym.spaces.Box(-2.0, 2.0, shape=(2,))
20
21 # RL agents may make steps that are 2D vectors from -1 to +1.
22 action_space = gym.spaces.Box(-1.0, 1.0, shape=(2,))
23
24 # Numerical optimization searches within a 2D box from -2 to +2.
25 optimization_space = gym.spaces.Box(-2.0, 2.0, shape=(2,))
26
27 def __init__(self, render_mode=None):
28 super().__init__(render_mode)
29 self.pos = x0.copy()
30
31 # Single-objective optimization methods:
32
33 def get_initial_params(self, *, seed=None, options=None):
34 super().reset(seed=seed, options=options)
35 self.pos = x0.copy()
36 return self.pos.copy()
37
38 def compute_single_objective(self, params):
39 # Force parameters into observable space.
40 space = self.optimization_space
41 self.pos = np.clip(params, space.low, space.high)
42 return objective_function(self.pos)
43
44 # Reinforcement learning methods:
45
46 def reset(self, *, seed=None, options=None):
47 super().reset(seed=seed, options=options)
48 self.pos = x0.copy()
49 obs = self.pos.copy()
50 info = {}
51 return obs, info
52
53 def step(self, action):
54 space = self.observation_space
55 self.pos = np.clip(self.pos + action, space.low, space.high)
56 obs = self.pos.copy()
57 reward = -objective_function(self.pos)
58 terminated = (reward > -0.05)
59 truncated = next_pos not in ob_space
60 info = {}
61 return obs, reward, terminated, truncated, info
62
63coi.register("Parabola-v0", entry_point=Parabola, max_episode_steps=10)
Do take note of that last statement, which registers your class whenever your package is imported.
We still need to declare how to find our class. We put the entry point
cernml.envs
into our manifest file for this:
10[project.entry-points.'cernml.envs']
11my-project = 'my_project'
8[entry_points]
9cernml.envs =
10 my-project = my_project
1from setuptools import setup
2
3setup(
4 name='my-project',
5 version='1.0',
6 install_requires=[
7 'cernml-coi >= 0.9.0',
8 ],
9 entry_points={
10 'cernml.envs': [
11 'my-project = my_project',
12 ],
13 }
14)
Any host application (e.g. Geoff) may now instantiate your optimization problem by passing both the namespace of your entry point and the environment ID of the register call. If you don’t have a proper application available, the package :doc:` cernml-coi-optimizers <optimizers:index>` provides a simple optimization loop:
1from cernml import coi, optimizers
2
3# Imports happens automatically behind the scene!
4env = coi.make("my-project/Parabola-v0")
5opt = optimizers.make("BOBYQA")
6
7# Uses the BOBYQA algorithm to solve our quadratic problem.
8optimizers.solve(opt, env)
See also
- Example of Using Both Optimization and RL
A more fully featured version of the above code.
- The Core API
The rest of the user guide.
- Packaging Crash Course
A tutorial on how to package your Python code so it can be installed and reused.
- Implementing SingleOptimizable
A thorough and step-by-step tour of one optimization interface and all the customization points that it provides.
Install Extras¶
This package defines the following optional dependencies. You can include them by adding the names of all extras in a comma-separated list in brackets behind the name of this package, e.g.:
# pyproject.toml
[project]
dependencies = [
'cernml-coi[matplotlib, optimizers] >= 0.8.0',
]
- matplotlib
Adds a dependency on matplotlib. This is used by a few Problem Checkers.
- optimizers
Adds a dependency on cernml-coi-optimizers. This is only used for the type annotations of
CustomOptimizerProvider
.
- robotics
Adds a dependency on gymnasium-robotics. We extend the Multi-Goal Environments that it defines. But if this package isn’t installed, we poly-fill
GoalEnv
with our own implementation.
- all
Adds all optional dependencies except the one on gymnasium-robotics. This exists mostly for convenience.
For easier maintenance, this package also defines the following extras:
- doc
Adds all dependencies necessary to build the documentation for this package.
- examples
Adds all dependencies necessary to run the Code Examples provided by this package.
- test
Adds all dependencies to run the unit tests defined for this package.