-
Notifications
You must be signed in to change notification settings - Fork 77
Add outcome constraints #792
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Waschenbacher
wants to merge
6
commits into
main
Choose a base branch
from
feature/outcome-constraint
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
0019a8f
Add OutcomeConstraint model with target reference and operators
Waschenbacher 0d7714c
Allow NumericalTarget.minimize=None for constraint-only targets
Waschenbacher 8a12ff8
Integrate outcome constraints into Objective classes
Waschenbacher cc05d25
Wire outcome constraints into BotorchRecommender acquisition function…
Waschenbacher d7f29cb
Add compatibility checks for outcome constraints in recommenders
Waschenbacher 9550bb0
Add tests for outcome constraints (integration and validation)
Waschenbacher File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| """Functionality for outcome constraints.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from collections.abc import Callable | ||
| from typing import Literal | ||
|
|
||
| import pandas as pd | ||
| import torch | ||
| from attrs import define, field | ||
| from attrs.validators import in_, instance_of | ||
|
|
||
| from baybe.serialization.mixin import SerialMixin | ||
| from baybe.targets.base import Target | ||
|
|
||
|
|
||
| @define(frozen=True, slots=False) | ||
| class OutcomeConstraint(SerialMixin): | ||
| """A constraint applied to target outcomes in the output space. | ||
|
|
||
| Outcome constraints restrict the feasible region based on target predictions, | ||
| different from parameter constraints which restrict the input space. | ||
| """ | ||
|
|
||
| target: Target = field(validator=instance_of(Target)) | ||
| """The target to be constrained.""" | ||
|
|
||
| operator: Literal["<=", ">=", "=="] = field(validator=in_(["<=", ">=", "=="])) | ||
| """The constraint operator.""" | ||
|
|
||
| threshold: float = field(validator=instance_of((int, float)), converter=float) | ||
| """The constraint threshold value in experimental units.""" | ||
|
|
||
|
Comment on lines
+25
to
+33
|
||
| def __str__(self) -> str: | ||
| """Return string representation.""" | ||
| return f"{self.target.name} {self.operator} {self.threshold}" | ||
|
|
||
| def get_computational_threshold(self) -> float: | ||
| """Convert experimental threshold to computational units. | ||
|
|
||
| Returns: | ||
| The threshold value in computational units. | ||
| """ | ||
| # Create dummy series with threshold value in experimental units | ||
| experimental_series = pd.Series([self.threshold], name=self.target.name) | ||
|
|
||
| # Apply the same transformations as the target | ||
| computational_series = self.target.transform(experimental_series) | ||
|
|
||
| return computational_series.iloc[0] | ||
|
|
||
| def to_botorch_constraint_func( | ||
| self, target_idx: int | ||
| ) -> Callable[[torch.Tensor], torch.Tensor]: | ||
| """Create a botorch-compatible constraint function. | ||
|
|
||
| Args: | ||
| target_idx: Index of the target in model output. | ||
|
|
||
| Returns: | ||
| A constraint function that returns <= 0 for feasible region. | ||
| """ | ||
| computational_threshold = self.get_computational_threshold() | ||
|
|
||
| def constraint_func(samples: torch.Tensor) -> torch.Tensor: | ||
| """Constraint function operating on computational level. | ||
|
|
||
| Args: | ||
| samples: Model output samples in computational units. | ||
|
|
||
| Returns: | ||
| Constraint values where <= 0 indicates feasible region. | ||
|
|
||
| Raises: | ||
| ValueError: If the constraint operator is not supported. | ||
| """ | ||
| if self.operator == "<=": | ||
| return samples[..., target_idx] - computational_threshold | ||
| elif self.operator == ">=": | ||
| return computational_threshold - samples[..., target_idx] | ||
| elif self.operator == "==": | ||
| # Equality constraint with small tolerance | ||
| return ( | ||
| torch.abs(samples[..., target_idx] - computational_threshold) - 1e-6 | ||
| ) | ||
| else: | ||
| raise ValueError(f"Unsupported constraint operator: {self.operator}") | ||
|
|
||
| return constraint_func | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I suggest to do the following:
I don't know when you branched this branch off of main, but we only recently added the
AGENTS.mdfiles (#769) which auto-inject instructions to achieve consistent code using agentic development. So if you haven't done that yet, please rebase this PR on main immediately and ask the agent to "replay" the commits with the new rules fromAGENTS.mdfiles in mind, the force push