# Composite outcomes

Sometimes, the objective is a known function of several outcomes that we observe. Then we model the outcomes and let the acquisition function compute the objective from joint samples of them. As in BoTorch’s tutorial on composite Bayesian optimization, the outcomes are Hartmann6 at three contexts, and the objective mixes all three.

``` python
import torch
from botorch.acquisition import GenericMCObjective, qLogExpectedImprovement
from botorch.models.transforms.outcome import Standardize
from botorch.optim import optimize_acqf
from botorch.sampling import SobolQMCNormalSampler
from botorch.test_functions import Hartmann
from torch import nn

from laplacekit_bayesopt import LaplaceBoTorchSurrogate

torch.set_default_dtype(torch.float64)
torch.manual_seed(10)

hartmann = Hartmann(dim=6, negate=True)
contexts = torch.linspace(0, 1, 3)
bounds = torch.stack([torch.zeros(5), torch.ones(5)])
weights = torch.randn(3)


def outcomes(X):
    """Hartmann6 at the 5 inputs plus each context, `[..., 3]`."""

    X = X.unsqueeze(-2).expand(*X.shape[:-1], 3, 5)
    c = contexts[:, None].expand(*X.shape[:-2], 3, 1)
    return hartmann(torch.cat([X, c], -1)) + 0.001 * torch.randn(c.shape[:-1])


def composite(samples, X=None):
    return -torch.cos(samples**2 + samples * weights).sum(-1)


objective = GenericMCObjective(composite)
train_X = torch.rand(5, 5)
train_Y = outcomes(train_X)


def make_net():
    return nn.Sequential(
        nn.Linear(5, 20),
        nn.Tanh(),
        nn.Linear(20, 20),
        nn.Tanh(),
        nn.Linear(20, 3),  # one output per outcome
    )
```

The surrogate’s posterior is joint over the three outputs, so the Monte Carlo samples of the outcomes are correlated, as they should be.

``` python
best = []

for _ in range(10):
    model = LaplaceBoTorchSurrogate(
        make_net(),
        train_X,
        train_Y,
        outcome_transform=Standardize(m=3),
    )
    acq = qLogExpectedImprovement(
        model,
        best_f=objective(train_Y).max(),
        sampler=SobolQMCNormalSampler(sample_shape=torch.Size([64])),
        objective=objective,
    )
    x, _ = optimize_acqf(
        acq, bounds=bounds, q=4, num_restarts=10, raw_samples=64
    )
    train_X = torch.cat([train_X, x])
    train_Y = torch.cat([train_Y, outcomes(x)])
    best.append(objective(train_Y).max().item())

for i, b in enumerate(best):
    print(f"round {i + 1:2d}: best objective = {b:.3f}")
```

    round  1: best objective = -2.980
    round  2: best objective = -2.979
    round  3: best objective = -2.979
    round  4: best objective = -2.979
    round  5: best objective = -2.531
    round  6: best objective = -2.531
    round  7: best objective = -2.531
    round  8: best objective = -2.531
    round  9: best objective = -2.531
    round 10: best objective = -2.531

We only do 10 rounds here so that the page runs quickly. In practice, BO runs for hundreds or thousands of rounds.
