本文整理汇总了Python中openmdao.main.expreval.ExprEvaluator.check_resolve方法的典型用法代码示例。如果您正苦于以下问题:Python ExprEvaluator.check_resolve方法的具体用法?Python ExprEvaluator.check_resolve怎么用?Python ExprEvaluator.check_resolve使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类openmdao.main.expreval.ExprEvaluator
的用法示例。
在下文中一共展示了ExprEvaluator.check_resolve方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_resolve
# 需要导入模块: from openmdao.main.expreval import ExprEvaluator [as 别名]
# 或者: from openmdao.main.expreval.ExprEvaluator import check_resolve [as 别名]
def test_resolve(self):
ex = ExprEvaluator('comp.x[0] = 10*(3.2+ a.a1d[3]* 1.1*a.a1d[2 ])', self.top)
self.assertEqual(ex.check_resolve(), True)
ex.text = 'comp.contlist[1].a2d[2][1]'
self.assertEqual(ex.check_resolve(), True)
ex.scope = self.top.comp
ex.text = 'contlist[1]'
self.assertEqual(ex.check_resolve(), True)
ex.text = 'contlist[1]-foo.flambe'
self.assertEqual(ex.check_resolve(), False)
示例2: Constraint
# 需要导入模块: from openmdao.main.expreval import ExprEvaluator [as 别名]
# 或者: from openmdao.main.expreval.ExprEvaluator import check_resolve [as 别名]
class Constraint(object):
""" Object that stores info for a single constraint. """
def __init__(self, lhs, comparator, rhs, scaler, adder, scope=None):
self.lhs = ExprEvaluator(lhs, scope=scope)
if not self.lhs.check_resolve():
raise ValueError("Constraint '%s' has an invalid left-hand-side." \
% ' '.join([lhs, comparator, rhs]))
self.comparator = comparator
self.rhs = ExprEvaluator(rhs, scope=scope)
if not self.rhs.check_resolve():
raise ValueError("Constraint '%s' has an invalid right-hand-side." \
% ' '.join([lhs, comparator, rhs]))
if not isinstance(scaler, float):
raise ValueError("Scaler parameter should be a float")
self.scaler = scaler
if scaler <= 0.0:
raise ValueError("Scaler parameter should be a float > 0")
if not isinstance(adder, float):
raise ValueError("Adder parameter should be a float")
self.adder = adder
def evaluate(self, scope):
"""Returns a tuple of the form (lhs, rhs, comparator, is_violated)."""
lhs = (self.lhs.evaluate(scope) + self.adder)*self.scaler
rhs = (self.rhs.evaluate(scope) + self.adder)*self.scaler
return (lhs, rhs, self.comparator, not _ops[self.comparator](lhs, rhs))
def evaluate_gradient(self, scope, stepsize=1.0e-6, wrt=None):
"""Returns the gradient of the constraint eq/inep as a tuple of the
form (lhs, rhs, comparator, is_violated)."""
lhs = self.lhs.evaluate_gradient(scope=scope, stepsize=stepsize, wrt=wrt)
for key, value in lhs.iteritems():
lhs[key] = (value + self.adder)*self.scaler
rhs = self.rhs.evaluate_gradient(scope=scope, stepsize=stepsize, wrt=wrt)
for key, value in rhs.iteritems():
rhs[key] = (value + self.adder)*self.scaler
return (lhs, rhs, self.comparator, not _ops[self.comparator](lhs, rhs))
def get_referenced_compnames(self):
return self.lhs.get_referenced_compnames().union(self.rhs.get_referenced_compnames())
def __str__(self):
return ' '.join([self.lhs.text, self.comparator, self.rhs.text])
示例3: add_objective
# 需要导入模块: from openmdao.main.expreval import ExprEvaluator [as 别名]
# 或者: from openmdao.main.expreval.ExprEvaluator import check_resolve [as 别名]
def add_objective(self, expr, name=None, scope=None):
"""Adds an objective to the driver.
expr: string
String containing the objective expression.
name: string (optional)
Name to be used to refer to the objective in place of the expression
string.
scope: object (optional)
The object to be used as the scope when evaluating the expression.
"""
if self._max_objectives > 0 and len(self._objectives) >= self._max_objectives:
self._parent.raise_exception("Can't add objective '%s'. Only %d objectives are allowed" % (expr,self._max_objectives),
RuntimeError)
expr = _remove_spaces(expr)
if expr in self._objectives:
self._parent.raise_exception("Trying to add objective "
"'%s' to driver, but it's already there" % expr,
AttributeError)
if name is not None and name in self._objectives:
self._parent.raise_exception("Trying to add objective "
"'%s' to driver using name '%s', but name is already used" % (expr,name),
AttributeError)
expreval = ExprEvaluator(expr, self._get_scope(scope))
if not expreval.check_resolve():
self._parent.raise_exception("Can't add objective because I can't evaluate '%s'." % expr,
ValueError)
if name is None:
self._objectives[expr] = expreval
else:
self._objectives[name] = expreval
self._parent._invalidate()
示例4: Constraint
# 需要导入模块: from openmdao.main.expreval import ExprEvaluator [as 别名]
# 或者: from openmdao.main.expreval.ExprEvaluator import check_resolve [as 别名]
#.........这里部分代码省略.........
else:
first = self.lhs.text
second = self.rhs.text
first_zero = False
try:
f = float(first)
except Exception:
pass
else:
if f == 0:
first_zero = True
second_zero = False
try:
f = float(second)
except Exception:
pass
else:
if f == 0:
second_zero = True
if first_zero:
newexpr = "-(%s)" % second
elif second_zero:
newexpr = first
else:
newexpr = '%s-(%s)' % (first, second)
return ExprEvaluator(newexpr, scope)
def copy(self):
""" Returns a copy of our self. """
return Constraint(str(self.lhs), self.comparator, str(self.rhs),
scope=self.lhs.scope, jacs=self.jacs)
def evaluate(self, scope):
"""Returns the value of the constraint as a sequence."""
vname = self.pcomp_name + '.out0'
try:
system = getattr(scope,self.pcomp_name)._system
info = system.vec['u']._info[scope.name2collapsed[vname]]
# if a pseudocomp output is marked as hidden, that means that
# it's really a residual, but it's mapped in the vector to
# the corresponding state, so don't pull that value because
# we want the actual residual value
if info.hide: # it's a residual so pull from f vector
return -system.vec['f'][scope.name2collapsed[vname]]
else:
return info.view
except (KeyError, AttributeError):
pass
val = getattr(scope, self.pcomp_name).out0
if isinstance(val, ndarray):
return val.flatten()
else:
return [val]
def get_referenced_compnames(self):
"""Returns a set of names of each component referenced by this
constraint.
"""
if isinstance(self.rhs, float):
return self.lhs.get_referenced_compnames()
else:
return self.lhs.get_referenced_compnames().union(
self.rhs.get_referenced_compnames())
def get_referenced_varpaths(self, copy=True, refs=False):
"""Returns a set of names of each component referenced by this
constraint.
"""
if isinstance(self.rhs, float):
return self.lhs.get_referenced_varpaths(copy=copy, refs=refs)
else:
return self.lhs.get_referenced_varpaths(copy=copy, refs=refs).union(
self.rhs.get_referenced_varpaths(copy=copy, refs=refs))
def check_resolve(self):
"""Returns True if this constraint has no unresolved references."""
return self.lhs.check_resolve() and self.rhs.check_resolve()
def get_unresolved(self):
return list(set(self.lhs.get_unresolved()).union(self.rhs.get_unresolved()))
def name_changed(self, old, new):
"""Update expressions if necessary when an object is renamed."""
self.rhs.name_changed(old, new)
self.lhs.name_changed(old, new)
def __str__(self):
return ' '.join((str(self.lhs), self.comparator, str(self.rhs)))
def __eq__(self, other):
if not isinstance(other, Constraint):
return False
return (self.lhs, self.comparator, self.rhs) == \
(other.lhs, other.comparator, other.rhs)
示例5: Constraint
# 需要导入模块: from openmdao.main.expreval import ExprEvaluator [as 别名]
# 或者: from openmdao.main.expreval.ExprEvaluator import check_resolve [as 别名]
class Constraint(object):
""" Object that stores info for a single constraint. """
def __init__(self, lhs, comparator, rhs, scope):
self.lhs = ExprEvaluator(lhs, scope=scope)
if not self.lhs.check_resolve():
raise ValueError("Constraint '%s' has an invalid left-hand-side."
% ' '.join([lhs, comparator, rhs]))
self.comparator = comparator
self.rhs = ExprEvaluator(rhs, scope=scope)
if not self.rhs.check_resolve():
raise ValueError("Constraint '%s' has an invalid right-hand-side."
% ' '.join([lhs, comparator, rhs]))
self.pcomp_name = None
self._size = None
@property
def size(self):
"""Total scalar items in this constraint."""
if self._size is None:
self._size = len(self.evaluate(self.lhs.scope))
return self._size
def activate(self):
"""Make this constraint active by creating the appropriate
connections in the dependency graph.
"""
if self.pcomp_name is None:
pseudo = PseudoComponent(self.lhs.scope, self._combined_expr(),
pseudo_type='constraint')
self.pcomp_name = pseudo.name
self.lhs.scope.add(pseudo.name, pseudo)
getattr(self.lhs.scope, pseudo.name).make_connections(self.lhs.scope)
def deactivate(self):
"""Remove this constraint from the dependency graph and remove
its pseudocomp from the scoping object.
"""
if self.pcomp_name:
scope = self.lhs.scope
try:
pcomp = getattr(scope, self.pcomp_name)
except AttributeError:
pass
else:
# pcomp.remove_connections(scope)
# if hasattr(scope, pcomp.name):
scope.remove(pcomp.name)
finally:
self.pcomp_name = None
def _combined_expr(self):
"""Given a constraint object, take the lhs, operator, and
rhs and combine them into a single expression by moving rhs
terms over to the lhs. For example,
for the constraint 'C1.x < C2.y + 7', return the expression
'C1.x - C2.y - 7'. Depending on the direction of the operator,
the sign of the expression may be flipped. The final form of
the constraint, when evaluated, will be considered to be satisfied
if it evaluates to a value <= 0.
"""
scope = self.lhs.scope
if self.comparator.startswith('>'):
first = self.rhs.text
second = self.lhs.text
else:
first = self.lhs.text
second = self.rhs.text
first_zero = False
try:
f = float(first)
except Exception:
pass
else:
if f == 0:
first_zero = True
second_zero = False
try:
f = float(second)
except Exception:
pass
else:
if f == 0:
second_zero = True
if first_zero:
newexpr = "-(%s)" % second
elif second_zero:
newexpr = "%s" % first
else:
newexpr = '%s-(%s)' % (first, second)
return ExprEvaluator(newexpr, scope)
#.........这里部分代码省略.........