Skip to content

Commit

Permalink
Merge pull request #361 from CUQI-DTU/disable_conditioning_on_mutable…
Browse files Browse the repository at this point in the history
…_if_not_conditional

Distributions: Disable conditioning on mutable variables if not conditioning variable
  • Loading branch information
nabriis authored Feb 19, 2024
2 parents f274c4a + bfdbfe3 commit c7499ad
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
6 changes: 6 additions & 0 deletions cuqi/distribution/_distribution.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,12 @@ def _condition(self, *args, **kwargs):
new_dist = self._make_copy() #New cuqi distribution conditioned on the kwargs
processed_kwargs = set() # Keep track of processed (unique) elements in kwargs

# Check if kwargs contain any mutable variables that are not conditioning variables
# If so we raise an error since these are not allowed to be specified.
for kw_key in kwargs.keys():
if kw_key in mutable_vars and kw_key not in cond_vars:
raise ValueError(f"The mutable variable \"{kw_key}\" is not a conditioning variable of this distribution.")

# Go through every mutable variable and assign value from kwargs if present
for var_key in mutable_vars:

Expand Down
14 changes: 7 additions & 7 deletions tests/test_abstract_distribution_density.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ def test_conditioning_on_main_parameter():
def test_conditioning_kwarg_as_mutable_var():
""" This checks if we allow kwargs for a distribution that has no conditioning variables. """
x = cuqi.distribution.Gaussian(mean=1, cov=1)
x = x(cov=2) #This should be ok and not throw an error
assert x.cov == 2
with pytest.raises(ValueError):
x = x(cov=2) #This should raise error since no cond vars

def test_conditioning_both_args_kwargs():
""" This tests that we throw error if we accidentally provide arg and kwarg for same variable. """
Expand Down Expand Up @@ -172,7 +172,7 @@ def test_cond_positional_and_kwargs():
""" Test conditioning for both positional and kwargs """
x = cuqi.distribution.Gaussian(cov=lambda s:s, geometry=1)

logd = x(mean=3, cov=7).logd(13)
logd = x(mean=3, s=7).logd(13)

# Conditioning full positional
assert x(3, 7, 13).value == logd
Expand All @@ -181,10 +181,10 @@ def test_cond_positional_and_kwargs():
assert x(3)(7)(13).value == logd

# Conditioning full kwargs
assert x(mean=3, cov=7, x=13).value == logd
assert x(mean=3, cov=7)(x=13).value == logd
assert x(mean=3)(cov=7, x=13).value == logd
assert x(mean=3)(cov=7)(x=13).value == logd
assert x(mean=3, s=7, x=13).value == logd
assert x(mean=3, s=7)(x=13).value == logd
assert x(mean=3)(s=7, x=13).value == logd
assert x(mean=3)(s=7)(x=13).value == logd

# Conditioning partial positional
assert x(3, s=7, x=13).value == logd
Expand Down

0 comments on commit c7499ad

Please sign in to comment.