-
Notifications
You must be signed in to change notification settings - Fork 79
Enable Coefficients for DiscreteSumConstraint and from_simplex
#786
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
Scienfitz
wants to merge
17
commits into
main
Choose a base branch
from
feature/sum_constraint_coefficients
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
17 commits
Select commit
Hold shift + click to select a range
557c092
Add coefficients support to DiscreteSumConstraint
Scienfitz 6c403d4
Add simplex_coefficients to SubspaceDiscrete.from_simplex
Scienfitz fd46541
Add tests for DiscreteSumConstraint.coefficients and from_simplex sim…
Scienfitz e22196a
Switch DiscreteSumConstraint.get_invalid to column-by-column weighted…
Scienfitz 89deeab
Use any() for non-negativity check in from_simplex
Scienfitz f2f87d9
Use pure numpy in from_simplex incremental construction loop
Scienfitz a4af9af
Fix mypy error
Scienfitz 43b9c99
Improve validation in `from_simplex`
Scienfitz fa78764
Improve deserialization validation
Scienfitz 1c9d4a7
Forbid all-zero coefficients in linear/sum constraints
Scienfitz 583ba2b
Forbid individual zero coefficients in linear/sum constraints
Scienfitz d96d428
Add tests for non-zero coefficient validation
Scienfitz df93b36
Update CHANGELOG
Scienfitz 4f43355
Unify coefficient validation tests for both constraint types
Scienfitz 0163e3c
Merge simplex coefficient tests into three-way comparison
Scienfitz d2c7aa3
Consolidate polars sum constraint tests
Scienfitz 2ce4a29
Improve docstring
Scienfitz 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 | ||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -3,15 +3,16 @@ | |||||||||||||||
| from __future__ import annotations | ||||||||||||||||
|
|
||||||||||||||||
| import gc | ||||||||||||||||
| from collections.abc import Callable | ||||||||||||||||
| from collections.abc import Callable, Sequence | ||||||||||||||||
| from functools import reduce | ||||||||||||||||
| from typing import TYPE_CHECKING, Any, ClassVar, cast | ||||||||||||||||
|
|
||||||||||||||||
| import cattrs | ||||||||||||||||
| import numpy as np | ||||||||||||||||
| import numpy.typing as npt | ||||||||||||||||
| import pandas as pd | ||||||||||||||||
| from attrs import define, field | ||||||||||||||||
| from attrs.validators import in_, min_len | ||||||||||||||||
| from attrs.validators import deep_iterable, in_, min_len | ||||||||||||||||
| from typing_extensions import override | ||||||||||||||||
|
|
||||||||||||||||
| from baybe.constraints.base import CardinalityConstraint, DiscreteConstraint | ||||||||||||||||
|
|
@@ -26,6 +27,7 @@ | |||||||||||||||
| block_serialization_hook, | ||||||||||||||||
| converter, | ||||||||||||||||
| ) | ||||||||||||||||
| from baybe.utils.validation import finite_float | ||||||||||||||||
|
|
||||||||||||||||
| if TYPE_CHECKING: | ||||||||||||||||
| import polars as pl | ||||||||||||||||
|
|
@@ -77,7 +79,11 @@ def get_invalid_polars(self) -> pl.Expr: | |||||||||||||||
|
|
||||||||||||||||
| @define | ||||||||||||||||
| class DiscreteSumConstraint(DiscreteConstraint): | ||||||||||||||||
| """Class for modelling sum constraints.""" | ||||||||||||||||
| """Class for modelling sum constraints. | ||||||||||||||||
|
|
||||||||||||||||
| The constraint evaluates whether the (optionally weighted) sum of the specified | ||||||||||||||||
| parameters satisfies the given threshold condition. | ||||||||||||||||
| """ | ||||||||||||||||
|
|
||||||||||||||||
| # IMPROVE: refactor `SumConstraint` and `ProdConstraint` to avoid code copying | ||||||||||||||||
|
|
||||||||||||||||
|
|
@@ -94,9 +100,45 @@ class DiscreteSumConstraint(DiscreteConstraint): | |||||||||||||||
| condition: ThresholdCondition = field() | ||||||||||||||||
| """The condition modeled by this constraint.""" | ||||||||||||||||
|
|
||||||||||||||||
| coefficients: tuple[float, ...] = field( | ||||||||||||||||
| converter=lambda x: cattrs.structure(x, tuple[float, ...]), | ||||||||||||||||
| validator=deep_iterable(member_validator=finite_float), | ||||||||||||||||
| ) | ||||||||||||||||
| """The coefficients for the weighted sum, one per entry in ``parameters``. | ||||||||||||||||
|
|
||||||||||||||||
| Defaults to all-ones, i.e. an unweighted sum.""" | ||||||||||||||||
|
|
||||||||||||||||
| @coefficients.default | ||||||||||||||||
| def _default_coefficients(self) -> tuple[float, ...]: | ||||||||||||||||
| """Return equal weight coefficients as default.""" | ||||||||||||||||
| return (1.0,) * len(self.parameters) | ||||||||||||||||
|
|
||||||||||||||||
| @coefficients.validator | ||||||||||||||||
| def _validate_coefficients( # noqa: DOC101, DOC103 | ||||||||||||||||
| self, _: Any, coefficients: Sequence[float] | ||||||||||||||||
| ) -> None: | ||||||||||||||||
| """Validate the coefficients. | ||||||||||||||||
|
|
||||||||||||||||
| Raises: | ||||||||||||||||
| ValueError: If the number of coefficients does not match the number of | ||||||||||||||||
| parameters. | ||||||||||||||||
| """ | ||||||||||||||||
| if len(self.parameters) != len(coefficients): | ||||||||||||||||
| raise ValueError( | ||||||||||||||||
| "The given 'coefficients' list must have one floating point entry for " | ||||||||||||||||
| "each entry in 'parameters'." | ||||||||||||||||
| ) | ||||||||||||||||
| if any(c == 0.0 for c in coefficients): | ||||||||||||||||
| raise ValueError("All entries in 'coefficients' must be non-zero.") | ||||||||||||||||
|
|
||||||||||||||||
| @override | ||||||||||||||||
| def _get_invalid(self, df: pd.DataFrame, /) -> pd.Index: | ||||||||||||||||
| evaluate_df = df[self.parameters].sum(axis=1) | ||||||||||||||||
| evaluate_df = pd.Series( | ||||||||||||||||
| sum( | ||||||||||||||||
| df[p].to_numpy() * c for p, c in zip(self.parameters, self.coefficients) | ||||||||||||||||
| ), | ||||||||||||||||
| index=df.index, | ||||||||||||||||
| ) | ||||||||||||||||
|
Comment on lines
+136
to
+141
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||||||||||||||||
| mask_bad = ~self.condition.evaluate(evaluate_df) | ||||||||||||||||
|
|
||||||||||||||||
| return df.index[mask_bad] | ||||||||||||||||
|
|
@@ -105,7 +147,8 @@ def _get_invalid(self, df: pd.DataFrame, /) -> pd.Index: | |||||||||||||||
| def get_invalid_polars(self) -> pl.Expr: | ||||||||||||||||
| from baybe._optional.polars import polars as pl | ||||||||||||||||
|
|
||||||||||||||||
| return self.condition.to_polars(pl.sum_horizontal(self.parameters)).not_() | ||||||||||||||||
| weighted = [pl.col(p) * c for p, c in zip(self.parameters, self.coefficients)] | ||||||||||||||||
| return self.condition.to_polars(pl.sum_horizontal(weighted)).not_() | ||||||||||||||||
|
|
||||||||||||||||
|
|
||||||||||||||||
| @define | ||||||||||||||||
|
|
||||||||||||||||
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.

Uh oh!
There was an error while loading. Please reload this page.