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