Skip to content

Commit

Permalink
Use _evaluate for constraint evaluation
Browse files Browse the repository at this point in the history
  • Loading branch information
dhadka committed Sep 10, 2024
1 parent 15eb960 commit 1b3ae1f
Showing 1 changed file with 3 additions and 21 deletions.
24 changes: 3 additions & 21 deletions rhodium/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
from abc import ABCMeta, abstractmethod
from enum import Enum
from platypus import Real, Integer, Permutation, Subset
from .expr import _evaluate_all
from .expr import _evaluate, _evaluate_all

class RhodiumError(Exception):
pass
Expand Down Expand Up @@ -103,14 +103,6 @@ def __getattr__(self, name):
else:
raise AttributeError()

# Set up the evaluation environment with all math function.
_eval_env = {}
_module = __import__("math", fromlist=[''])

for name in dir(_module):
if not name.startswith("_"):
_eval_env[name] = getattr(_module, name)

class Constraint:
"""Defines model constraints.
Expand Down Expand Up @@ -156,25 +148,15 @@ def _convert(self):

def is_feasible(self, env):
"""Returns True if the constraint is feasible / satisfied, otherwise False."""
tmp_env = {}
tmp_env.update(_eval_env)
tmp_env.update(env)

if isinstance(self.expr, str):
return eval(self.expr, {}, tmp_env)
else:
return self.expr(tmp_env)
return _evaluate(self.expr, env, update_env=False)

def distance(self, env):
"""Returns the distance to the feasibility threshold."""
if self.is_feasible(env):
return 0.0
elif hasattr(self, "_distance"):
try:
tmp_env = {}
tmp_env.update(_eval_env)
tmp_env.update(env)
return abs(eval(self._distance, {}, tmp_env)) + 0.001
return math.nextafter(abs(_evaluate(self._distance, env, update_env=False)), math.inf)
except Exception:
return 1.0
else:
Expand Down

0 comments on commit 1b3ae1f

Please sign in to comment.