Skip to content

Commit b8df435

Browse files
committed
source code for paper added
1 parent ecf5c60 commit b8df435

33 files changed

+3135
-76
lines changed

.gitignore

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# Python
2+
*.pyc
3+
*__pycache__
4+

README.md

+14-76
Original file line numberDiff line numberDiff line change
@@ -1,93 +1,31 @@
1-
# 2025-code-An-Analysis-of-Safety-Guarantees-in-Multi-Task-Bayesian-Optimization
1+
# An Analysis of Safety Guarantees in Multi-Task Bayesian Optimization
22

3+
## General
34

5+
This repository contains supplementary material and the code to reproduce the tables and figures presented in
46

5-
## Getting started
7+
> J. O. Lübsen, A. Eichler, "An Anlysis of Safety Guarantees in Multi-Task Bayesian Optimization"
68
7-
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
89

9-
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
10+
http://arxiv.org/abs/2312.07281
1011

11-
## Add your files
12+
To run the proposed SaMSBO alogrithm the use may use the 'run_SaMSBO.py' file. To run the safe UCB algorithm for comparison, the user may use the 'run_SafeUCB.py' file.
13+
In addition, there is a jupyter notebook 'visualized_example.ipynb' which shows the optimization of a one-dimensional example. This may be run to visually follow the optimization procedure.
1214

13-
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
14-
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
15+
The data used for plots to generate the figures in the manuscript are in the data folder. The use may use the 'generate_plots.ipynb' notebook to recreate the figures in the 'plot_scripts' folder.
1516

16-
```
17-
cd existing_repo
18-
git remote add origin https://collaborating.tuhh.de/ICS/ics-private/phd-students/papers/2025-code-an-analysis-of-safety-guarantees-in-multi-task-bayesian-optimization.git
19-
git branch -M main
20-
git push -uf origin main
21-
```
17+
## Prerequisites
2218

23-
## Integrate with your tools
19+
To run the code install python3.12.8 and the dependencies specified in `requirements.txt`.
2420

25-
- [ ] [Set up project integrations](https://collaborating.tuhh.de/ICS/ics-private/phd-students/papers/2025-code-an-analysis-of-safety-guarantees-in-multi-task-bayesian-optimization/-/settings/integrations)
21+
> pip install -r requirements.txt
2622
27-
## Collaborate with your team
23+
The code in this repository was tested in the following environment:
2824

29-
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
30-
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
31-
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
32-
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
33-
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
25+
* *Ubuntu 24.04.2 LTS
26+
* *Python 3.12.8
3427

35-
## Test and Deploy
3628

37-
Use the built-in continuous integration in GitLab.
3829

39-
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
40-
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
41-
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
42-
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
43-
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
4430

45-
***
4631

47-
# Editing this README
48-
49-
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
50-
51-
## Suggestions for a good README
52-
53-
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
54-
55-
## Name
56-
Choose a self-explaining name for your project.
57-
58-
## Description
59-
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
60-
61-
## Badges
62-
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
63-
64-
## Visuals
65-
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
66-
67-
## Installation
68-
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
69-
70-
## Usage
71-
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
72-
73-
## Support
74-
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
75-
76-
## Roadmap
77-
If you have ideas for releases in the future, it is a good idea to list them in the README.
78-
79-
## Contributing
80-
State if you are open to contributions and what your requirements are for accepting them.
81-
82-
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
83-
84-
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
85-
86-
## Authors and acknowledgment
87-
Show your appreciation to those who have contributed to the project.
88-
89-
## License
90-
For open source projects, say how it is licensed.
91-
92-
## Project status
93-
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.

bo/__init__.py

Whitespace-only changes.

bo/bo_loop.py

+250
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,250 @@
1+
#!/usr/bin/env python3
2+
"""
3+
BayesianOptimization class for performing safe multi-task Bayesian optimization.
4+
5+
Attributes:
6+
obj: The objective function to be optimized.
7+
tasks: List of tasks for multi-task optimization.
8+
bounds: Tensor specifying the bounds for the optimization variables.
9+
threshold: The safety threshold for the optimization.
10+
targets_mean_std: Tuple containing the mean and standard deviation of the targets.
11+
num_acq_samps: List specifying the number of acquisition samples for each task.
12+
boundary_T: Boundary threshold for the optimization.
13+
run: Counter for the number of optimization steps.
14+
best_y: List of best observed values.
15+
best_x: List of best observed inputs.
16+
dim: Dimensionality of the optimization problem.
17+
gp: Gaussian process model used for optimization.
18+
19+
Methods:
20+
__init__(self, obj, tasks, bounds, threshold, targets_mean_std, num_acq_samps=[1, 1], boundary_T=-15.0):
21+
Initializes the BayesianOptimization class with the given parameters.
22+
23+
step(self):
24+
Performs one step of the Bayesian optimization loop.
25+
26+
inequality_consts(self, input: Tensor):
27+
Computes the inequality constraints for the given input.
28+
29+
update_gp(self, gp, sqrtbeta):
30+
Updates the Gaussian process model and related attributes.
31+
32+
_line_search(self, initial_condition, maxiter=20, step_size=2.0):
33+
Performs a line search to find a feasible initial condition.
34+
35+
_get_max_observed(self):
36+
Returns the maximum observed values for each task.
37+
38+
_get_min_observed(self):
39+
Returns the minimum observed values for each task.
40+
41+
_get_best_input(self):
42+
Returns the best input values for each task.
43+
44+
_get_initial_cond(self):
45+
Returns the initial conditions for the optimization.
46+
47+
get_next_point(self, task, posterior_transform):
48+
Returns the next point to evaluate for the given task.
49+
"""
50+
51+
52+
import torch
53+
from torch import Tensor
54+
from botorch.optim.optimize import optimize_acqf
55+
from botorch.acquisition import qUpperConfidenceBound
56+
from utils.utils import concat_data, unstandardize, standardize
57+
from botorch.acquisition.objective import ScalarizedPosteriorTransform
58+
59+
N_TOL = -1e-6
60+
61+
62+
class BayesianOptimization:
63+
def __init__(
64+
self,
65+
obj,
66+
tasks,
67+
bounds,
68+
threshold,
69+
targets_mean_std,
70+
num_acq_samps: list = [1, 1],
71+
boundary_T=-15.0,
72+
):
73+
self.obj = obj
74+
self.bounds = bounds
75+
self.threshold = threshold
76+
self.boundary_T = boundary_T
77+
self.mu, self.std = targets_mean_std
78+
self.num_acq_samps = num_acq_samps
79+
self.tasks = tasks
80+
if len(self.num_acq_samps) != len(self.tasks):
81+
raise ValueError("Number of tasks and number of samples must match")
82+
self.run = 0
83+
self.best_y = []
84+
self.best_x = []
85+
self.dim = bounds.size(-1)
86+
self.gp = None
87+
88+
def step(self):
89+
self.run += 1
90+
print("Run : ", self.run)
91+
print(f"Best value found: {self.observed_max[0]: .3f}")
92+
print(f"Worst value: {self._get_min_observed()[0]}")
93+
W = torch.eye(len(self.tasks))
94+
for i in self.tasks:
95+
posterior_transform = ScalarizedPosteriorTransform(W[:, i].squeeze())
96+
new_point = self.get_next_point(i, posterior_transform)
97+
if i == 0:
98+
print(f"New Point: {new_point}")
99+
new_point_task0 = new_point
100+
if i != 0:
101+
new_point = torch.vstack((new_point, new_point_task0))
102+
new_result = self.obj.f(new_point, i)
103+
self.train_inputs, self.train_tasks, self.unstd_train_targets = concat_data(
104+
(new_point, i * torch.ones(new_point.shape[0], 1), new_result),
105+
(self.train_inputs, self.train_tasks, self.unstd_train_targets),
106+
)
107+
threshold = unstandardize(self.threshold, self.mu, self.std)
108+
self.train_targets, self.mu, self.std = standardize(
109+
self.unstd_train_targets, train_task=self.train_tasks
110+
)
111+
self.threshold, _, _ = standardize(threshold, self.mu, self.std)
112+
self.observed_max = self._get_max_observed()
113+
self.best_y.append(self.observed_max[0])
114+
self.best_x.append(self._get_best_input()[0])
115+
return self.train_inputs, self.train_tasks, self.train_targets
116+
117+
def inequality_consts(self, input: Tensor):
118+
self.gp.eval()
119+
inputx = input.view(int(input.numel() / self.dim), self.dim)
120+
output = self.gp(torch.hstack((inputx, torch.zeros(inputx.size(0), 1))))
121+
val = (
122+
output.mean
123+
- output.covariance_matrix.diag().sqrt() * self.sqrtbeta
124+
- self.threshold
125+
)
126+
return val.view(inputx.shape[0], 1)
127+
128+
def update_gp(self, gp, sqrtbeta):
129+
with torch.no_grad():
130+
self.train_inputs = gp.train_inputs[0][..., :-1]
131+
self.train_tasks = gp.train_inputs[0][..., -1:].to(dtype=torch.int32)
132+
self.train_targets = gp.train_targets.unsqueeze(-1)
133+
self.unstd_train_targets = unstandardize(
134+
self.train_targets, self.mu, self.std, self.train_tasks
135+
)
136+
self.sqrtbeta = sqrtbeta.detach()
137+
if self.gp is None:
138+
self.observed_max = self._get_max_observed()
139+
self.best_y.append(self.observed_max[0])
140+
self.best_x.append(self._get_best_input()[0])
141+
self.gp = gp
142+
pass
143+
144+
def _line_search(self, initial_condition, maxiter=20, step_size=2.0):
145+
k = 1000
146+
direction = torch.randn(initial_condition.size())
147+
direction /= (
148+
torch.linalg.norm(direction, dim=-1, ord=2)
149+
.unsqueeze(-1)
150+
.repeat(1, 1, self.dim)
151+
)
152+
steps = torch.linspace(0, step_size, k).view(1, k, 1) - step_size / 2
153+
line_search = initial_condition + steps * direction
154+
inds = (
155+
(self.inequality_consts(line_search) >= 0).view(
156+
initial_condition.size(0), -1
157+
)
158+
& torch.all(line_search <= self.bounds[1, :].view(1, 1, self.dim), dim=-1)
159+
& torch.all(line_search >= self.bounds[0, :].view(1, 1, self.dim), dim=-1)
160+
)
161+
for id in range(inds.size(0)):
162+
possible_steps = steps[:, inds[id, :].squeeze(), :].squeeze()
163+
if possible_steps.numel() <= 1:
164+
return initial_condition
165+
max_step_ind = possible_steps.abs().argmax()
166+
initial_condition[id] = (
167+
initial_condition[id] + possible_steps[max_step_ind] * direction[id]
168+
)
169+
return initial_condition
170+
171+
def _get_max_observed(self):
172+
return [
173+
torch.max(self.unstd_train_targets[self.train_tasks == i]).item()
174+
for i in self.tasks
175+
]
176+
177+
def _get_min_observed(self):
178+
return [
179+
torch.min(self.unstd_train_targets[self.train_tasks == i]).item()
180+
for i in self.tasks
181+
]
182+
183+
def _get_best_input(self):
184+
return [
185+
self.train_inputs[self.train_tasks.squeeze() == i, ...][
186+
torch.argmax(self.train_targets[self.train_tasks == i])
187+
]
188+
for i in self.tasks
189+
]
190+
191+
def _get_initial_cond(self):
192+
_, ind = self.train_targets.sort(dim=0, descending=True)
193+
sorted_train_inp = self.train_inputs[ind.squeeze(), ...]
194+
eqfull = self.inequality_consts(sorted_train_inp).squeeze()
195+
pot_cond = sorted_train_inp.view(self.train_inputs.size())[eqfull >= 0, ...][
196+
:5, ...
197+
]
198+
return pot_cond.view(pot_cond.size(0), 1, self.dim)
199+
200+
def get_next_point(self, task, posterior_transform):
201+
if task == 0:
202+
init_cond = self._get_initial_cond()
203+
if init_cond.numel() == 0:
204+
print(
205+
"No feasible initial condition found. Randomly sampling a new one."
206+
)
207+
x_new = self.train_inputs[
208+
self.train_targets[self.train_tasks == 0].argmax(), :
209+
].view(1, self.dim)
210+
offset = torch.randn(1, self.dim) * 0.005
211+
ind = (x_new + offset <= self.bounds[1, :].view(1, self.dim)) & (
212+
x_new + offset >= self.bounds[0, :].view(1, self.dim)
213+
)
214+
x_new[ind] = x_new[ind] + offset[ind]
215+
x_new[~ind] = x_new[~ind] - offset[~ind]
216+
return x_new
217+
else:
218+
init_cond = self._line_search(init_cond)
219+
acq = qUpperConfidenceBound(
220+
self.gp,
221+
self.sqrtbeta,
222+
posterior_transform=posterior_transform,
223+
)
224+
# if different acquisitions should be used
225+
else:
226+
acq = qUpperConfidenceBound(
227+
self.gp,
228+
beta=self.sqrtbeta,
229+
posterior_transform=posterior_transform,
230+
)
231+
candidate, tt = optimize_acqf(
232+
acq_function=acq,
233+
bounds=(
234+
self.bounds
235+
if task == 0
236+
else self.bounds
237+
+ torch.tensor(
238+
[[self.obj.max_disturbance], [-self.obj.max_disturbance]] # max_disturbance is zero for LbSync (only shifts)
239+
)
240+
),
241+
q=self.num_acq_samps[task],
242+
num_restarts=init_cond.size(0) if task == 0 else 1,
243+
raw_samples=512 if task != 0 else None,
244+
nonlinear_inequality_constraints=(
245+
[self.inequality_consts] if task == 0 else None
246+
),
247+
batch_initial_conditions=init_cond if task == 0 else None,
248+
options={"maxiter": 200},
249+
)
250+
return candidate

cov/__init__.py

Whitespace-only changes.

0 commit comments

Comments
 (0)