Optimal control of a system in a changing environment

Driver:

ActiveLearning

Download script:

changing_environment.py

The target of the study is show how to control a system that depends on environment parameters such as temperature or humidity. While the environment parameters can be measured, their influence on the system’s performance is often unknown.

As an example objective the 2d Rastrigin function

\[r(x_1, x_2) = 10\cdot 2 +x_1^2 + x_2^2 - 10\cos(2\pi x_1) - 10\cos(2\pi x_1)\]

is considered. The environment parameter \(\phi\) acts as an additional phase offset to the first cosine function in the objective function

\[r(x_1, x_2, \phi) = 10\cdot 2 +x_1^2 + x_2^2 - 10\cos(2\pi x_1 + \phi) - 10\cos(2\pi x_1)\]

The phase shall slowly vary over time as

\[\phi(t) = 2\pi\sin\left(\frac{t}{3{\rm min}}\right).\]

Please note, that this specific time dependent behaviour is not exploited and is assumed to be unknown.

Before being able to control the system in an optimal way depending on the environment, one has to learn for many environment values, where the global minimum is located. To this end, a standard Bayesian optimization is performed for 500 iterations that explores the parameter space. In a second phase, the target is to evaluate the system in an optimal way, i.e. an exploration of the parameter space is not desired. This behaviour is mainly enforced by choosing a small scaling value.

The control phase could have an arbitrary number of iterations and it would be problematic to add all new observations to the study. On the one hand, this slows down the computation time of a suggestion. Since the environment value changes during the computation, this can lead to less optimal evaluation points. On the other had, adding more and more data points close to each other leads to an ill conditioned Gaussian process surrogate. To avoid these drawbacks, data points are not added in the control phase if the study predicts a value with very small uncertainty, which means that the observation would not add significant information.

  1import sys,os
  2import numpy as np
  3import time
  4import matplotlib.pyplot as plt
  5
  6jcm_optimizer_path = r"<JCM_OPTIMIZER_PATH>"
  7sys.path.insert(0, os.path.join(jcm_optimizer_path, "interface", "python"))
  8from jcmoptimizer import Server, Client, Study, Observation
  9server = Server()
 10client = Client(server.host)
 11
 12#Rastrigin-like function depending on additional phase offset phi 
 13def rast(x1: float, x2:float, phi:float) -> float:
 14    return (10*2 + x1**2 + x2**2 
 15            - 10*np.cos(2*np.pi*x1 + phi)  
 16            - 10*np.cos(2*np.pi*x2)
 17           )
 18
 19#time-dependent slowly varying phi
 20def current_phi() -> float:
 21    return 2*np.pi*np.sin(time.time()/180)
 22
 23# Definition of the search domain
 24design_space = [
 25    {'name': 'x1', 'type': 'continuous', 'domain': (-1.5, 1.5)}, 
 26    {'name': 'x2', 'type': 'continuous', 'domain': (-1.5, 1.5)},
 27]
 28
 29# Definition of the environment variable "phi"
 30environment = [
 31    {'name': 'phi', 'type': 'variable', 'domain': (-2*np.pi, 2*np.pi)},
 32]
 33
 34# Creation of the study object with study_id 'changing_environment'
 35study = client.create_study(
 36    design_space=design_space,
 37    environment=environment,
 38    driver="ActiveLearning",
 39    name="Optimal control of a system in a changing environment",
 40    study_id="changing_environment"
 41)
 42
 43#In the initial training phase, the target is to explore the
 44#parameter space to find the global minimim.
 45study.configure(
 46    #train with 500 data points    
 47    max_iter=500,
 48    #Advanced sample computation is switched off since the environment
 49    #parameter phi can change significantly between computation
 50    #of the suggestion and evaluation of the objective function
 51    acquisition_optimizer={'compute_suggestion_in_advance': False}
 52)
 53
 54# Evaluation of the black-box function for specified design parameters
 55def evaluate(study: Study, x1: float, x2: float) -> Observation:
 56    time.sleep(2) # make objective expensive
 57    observation = study.new_observation()
 58    #get current phi
 59    phi = current_phi()
 60    observation.add(rast(x1, x2, phi), environment_value=[phi])
 61    return observation
 62
 63# Run the minimization
 64study.set_evaluator(evaluate)
 65study.run()
 66
 67#The target in the control phase is to evaluate the offet Rastrigin function only
 68#at well performing (x1,x2)-point depending on the current value of the environment.
 69MAX_ITER = 500 #evaluate for 500 additional iterations
 70study.configure(
 71    max_iter=500 + MAX_ITER,
 72    #The scaling is reduced to penalize parameters with large uncertainty    
 73    scaling=0.01,
 74    #The lower-confidence bound (LCB) strategy is chosen instead of the
 75    #default expected improvement (EI). LCB is easier to maximize at the
 76    #risk of less exploration of the parameter space, which is anyhow not
 77    #desired in the control phase.
 78    objectives =[
 79        {'type': 'Minimizer', 'name': 'objective', 'strategy': 'LCB'}
 80    ],
 81    acquisition_optimizer={'compute_suggestion_in_advance': False}
 82)
 83
 84
 85#keep track of suggested design points and phis at request time and evaluation time
 86design_points: list[list[float]] = []
 87phis_at_request: list[list[float]] = []
 88phis_at_eval: list[list[float]] = []
 89    
 90iter = 0    
 91while not study.is_done():
 92    iter += 1
 93    if iter > MAX_ITER: break
 94        
 95    phi = current_phi()    
 96    suggestion = study.get_suggestion(environment_value=[phi])
 97    phis_at_request.append(phi)    
 98    kwargs = suggestion.kwargs
 99    design_points.append((kwargs["x1"], kwargs["x2"]))
100    try:
101        obs = evaluate(study=study, **kwargs)
102        #update phi from observation
103        phi = obs.data[None][0]["env"][0]
104        phis_at_eval.append(phi)    
105        
106        predictions = study.driver.predict(
107            points=[(kwargs["x1"], kwargs["x2"], phi)]
108        )
109        std = np.sqrt(predictions["variance"][0][0])
110
111        print(f"Uncertainty of prediction {std}")
112        #add data only if prediction has significant uncertainty
113        if std > 0.01:
114            study.add_observation(obs, suggestion.id)
115        else:
116            study.clear_suggestion(
117                suggestion.id, f"Ignoring observation with uncertainty {std}"
118            )
119    except Exception as err:
120        study.clear_suggestion(
121            suggestion.id, f"Evaluator function failed with error: {err}"
122        )
123        raise
124
125
126fig = plt.figure(figsize=(10,5))
127
128#all observed training samples
129observed = study.driver.get_observed_values()
130plt.subplot(1, 2, 1)
131plt.plot(observed["means"],".")
132plt.axvline(x=500, ls='--', color = 'gray')
133plt.xlabel("training+control iteration")
134plt.ylabel("observed value of Rastrigin function")
135
136#observed values during control phase
137observed_vals = [
138    rast(p[0], p[1], phi) for p, phi in zip(design_points, phis_at_eval)
139]
140
141#values that would have been observed at request time,
142#i.e. if there would be no time delay between request and 
143#evaluation of suggestion
144observed_vals_at_request = [
145    rast(p[0], p[1], phi) for p, phi in zip(design_points, phis_at_request)
146]
147
148#best value of x1-parameter depending on environment
149def best_x1(phi: float) -> float:
150    return -phi/(2*np.pi) + (np.sign(phi) if np.abs(phi) > np.pi else 0.0)
151
152#best possible values 
153best_vals = [rast(best_x1(phi), 0, phi) for phi in phis_at_eval]
154
155plt.subplot(1, 2, 2)
156plt.plot(observed_vals,".", label="observed values")
157plt.plot(observed_vals_at_request,".", label="observed values if no time delay")
158plt.plot(best_vals, label="smallest possible values")
159plt.ylim(1e-4, 1e1)
160plt.yscale("log")
161plt.xlabel("control iteration")
162plt.legend()
163plt.savefig("training_and_control.svg", transparent=True) 
training and control

Left: During the initial training phase in the first 500 iterations, the parameter space is explored leading to small and large objective values. In the control phase, only small objective values are observed. Right: The observed values (blue dots) agree well with the lowest achievable values (green line). Most of the deviations are due to the time offset between the request of a new suggestion for a given environment value \(\phi\) and the actual evaluation of the Rastrigin function about a second later. To see this, the values that would have been observed at the time of request are shown as orange dots.