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