当前位置: 首页>>代码示例>>Python>>正文


Python expreval.ExprEvaluator类代码示例

本文整理汇总了Python中openmdao.main.expreval.ExprEvaluator的典型用法代码示例。如果您正苦于以下问题:Python ExprEvaluator类的具体用法?Python ExprEvaluator怎么用?Python ExprEvaluator使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了ExprEvaluator类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _create

    def _create(self, target, low, high, scaler, adder, start, fd_step,
                key, scope):
        """ Create one Parameter or ArrayParameter. """
        try:
            expreval = ExprEvaluator(target, scope)
        except Exception as err:
            raise err.__class__("Can't add parameter: %s" % err)
        if not expreval.is_valid_assignee():
            raise ValueError("Can't add parameter: '%s' is not a"
                             " valid parameter expression"
                             % expreval.text)
        try:
            val = expreval.evaluate()
        except Exception as err:
            val = None  # Let Parameter code sort out why.

        name = key[0] if isinstance(key, tuple) else key

        if isinstance(val, ndarray):
            return ArrayParameter(target, low=low, high=high,
                                  scaler=scaler, adder=adder,
                                  start=start, fd_step=fd_step,
                                  name=name, scope=scope,
                                  _expreval=expreval, _val=val,
                                  _allowed_types=self._allowed_types)
        else:
            return Parameter(target, low=low, high=high,
                             scaler=scaler, adder=adder,
                             start=start, fd_step=fd_step,
                             name=name, scope=scope,
                             _expreval=expreval, _val=val,
                             _allowed_types=self._allowed_types)
开发者ID:theoryno3,项目名称:OpenMDAO-Framework,代码行数:32,代码来源:hasparameters.py

示例2: _split_expr

def _split_expr(text):
    """Take an expression string and return varpath, expr"""
    if text.startswith('@') or is_legal_name(text):
        return text, text
    
    expr = ExprEvaluator(text)
    return expr.get_referenced_varpaths().pop(), text
开发者ID:Kenneth-T-Moore,项目名称:OpenMDAO-Framework,代码行数:7,代码来源:depgraph.py

示例3: test_bogus

 def test_bogus(self):
     # now try some bogus expressions
     try:
         ex = ExprEvaluator('abcd.efg', self.top)
         ex.evaluate()
     except AttributeError, err:
         self.assertEqual(str(err), "can't evaluate expression 'abcd.efg': : object has no attribute 'abcd.efg'")
开发者ID:drousis,项目名称:OpenMDAO-Framework,代码行数:7,代码来源:test_evalexpr.py

示例4: _translate_up

    def _translate_up(self, text, node):
        if is_legal_name(text):
            return '.'.join([node, text])

        expr = ExprEvaluator(text)
        varpath = expr.get_referenced_varpaths().pop()
        return transform_expression(text, { varpath: '.'.join([node, varpath]) })
开发者ID:fzahle,项目名称:OpenMDAO-Framework,代码行数:7,代码来源:depgraph.py

示例5: __init__

    def __init__(self, lhs, comparator, rhs, scope, jacs=None):
        self.lhs = ExprEvaluator(lhs, scope=scope)
        self._pseudo = None
        self.pcomp_name = None
        unresolved_vars = self.lhs.get_unresolved()

        if unresolved_vars:
            msg = "Left hand side of constraint '{0}' has invalid variables {1}"
            expression = ' '.join((lhs, comparator, rhs))

            raise ExprEvaluator._invalid_expression_error(unresolved_vars,
                                                          expr=expression,
                                                          msg=msg)
        self.rhs = ExprEvaluator(rhs, scope=scope)
        unresolved_vars = self.rhs.get_unresolved()

        if unresolved_vars:
            msg = "Right hand side of constraint '{0}' has invalid variables {1}"
            expression = ' '.join((lhs, comparator, rhs))

            raise ExprEvaluator._invalid_expression_error(unresolved_vars,
                                                          expr=expression,
                                                          msg=msg)
        self.comparator = comparator
        self._size = None

        # Linear flag: constraints are nonlinear by default
        self.linear = False

        # User-defined jacobian function
        self.jacs = jacs

        self._create_pseudo()
开发者ID:ChanChiChoi,项目名称:OpenMDAO-Framework,代码行数:33,代码来源:hasconstraints.py

示例6: test_multi_object

 def test_multi_object(self):
     # verify that expressions with multiple objects raise a reasonable error message
     # when a set is attempted.
     try:
         ex = ExprEvaluator('comp.x+comp.x', self.top)
         ex.set(1)
     except ValueError, err:
         self.assertEqual(str(err),
             "expression 'comp.x+comp.x' can't be set to a value")
开发者ID:TwanvdBorgh,项目名称:OpenMDAO-Framework,代码行数:9,代码来源:test_evalexpr.py

示例7: test_no_scope

 def test_no_scope(self):
     ex = ExprEvaluator('abs(-3)+int(2.3)+math.floor(5.4)')
     self.assertEqual(ex.evaluate(), 10.0)
     
     ex.text = 'comp.x'
     try:
         ex.evaluate()
     except Exception, err:
         self.assertEqual(str(err), "can't evaluate expression 'comp.x': expression has no scope")
开发者ID:drousis,项目名称:OpenMDAO-Framework,代码行数:9,代码来源:test_evalexpr.py

示例8: test_scope_transform

    def test_scope_transform(self):
        exp = ExprEvaluator('myvar+abs(comp.x)*a.a1d[2]', self.top)
        self.assertEqual(new_text(exp), "scope.get('myvar')+abs(scope.get('comp.x'))*scope.get('a.a1d',[(0,2)])")
        xformed = exp.scope_transform(self.top, self.top.comp)
        self.assertEqual(xformed, 'parent.myvar+abs(x)*parent.a.a1d[2]')

        exp = ExprEvaluator('parent.var+abs(x)*parent.a.a1d[2]', self.top.comp)
        xformed = exp.scope_transform(self.top.comp, self.top)
        self.assertEqual(xformed, 'var+abs(comp.x)*a.a1d[2]')
开发者ID:TwanvdBorgh,项目名称:OpenMDAO-Framework,代码行数:9,代码来源:test_evalexpr.py

示例9: test_bogus

    def test_bogus(self):
        # now try some bogus expressions
        try:
            ex = ExprEvaluator('abcd.efg', self.top)
            ex.evaluate()
        except AttributeError, err:

            self.assertEqual(str(err), "can't evaluate expression 'abcd.efg':"
                             " : name 'abcd' is not defined")
开发者ID:ChanChiChoi,项目名称:OpenMDAO-Framework,代码行数:9,代码来源:test_evalexpr.py

示例10: test_eval_gradient_array

    def test_eval_gradient_array(self):
        top = set_as_top(Assembly())
        top.add('comp1', A())
        top.run()

        # Uncomment these when arrays work
        exp = ExprEvaluator('4.0*comp1.b2d[0][1]*comp1.b2d[1][1]', top.driver)
        grad = exp.evaluate_gradient(scope=top)
        assert_rel_error(self, grad['comp1.b2d[0][1]'], 12.0, 0.00001)
        assert_rel_error(self, grad['comp1.b2d[1][1]'], 4.0, 0.00001)
开发者ID:TwanvdBorgh,项目名称:OpenMDAO-Framework,代码行数:10,代码来源:test_evalexpr.py

示例11: test_eval_gradient_lots_of_vars

    def test_eval_gradient_lots_of_vars(self):
        top = set_as_top(Assembly())
        top.add('comp1', B())
        #build expr
        expr = "2*comp1.in1 + 3*comp1.in11"

        exp = ExprEvaluator(expr, top.driver)
        grad = exp.evaluate_gradient(scope=top)
        assert_rel_error(self, grad['comp1.in1'], 2.0, 0.00001)
        assert_rel_error(self, grad['comp1.in11'], 3.0, 0.00001)
开发者ID:TwanvdBorgh,项目名称:OpenMDAO-Framework,代码行数:10,代码来源:test_evalexpr.py

示例12: test_no_scope

    def test_no_scope(self):
        ex = ExprEvaluator('abs(-3)+int(2.3)+math.floor(5.4)')
        self.assertEqual(ex.evaluate(), 10.0)

        ex.text = 'comp.x'
        try:
            ex.evaluate()
        except Exception, err:
            self.assertEqual(str(err), "can't evaluate expression 'comp.x':"
                             " 'NoneType' object has no attribute 'get'")
开发者ID:TwanvdBorgh,项目名称:OpenMDAO-Framework,代码行数:10,代码来源:test_evalexpr.py

示例13: __init__

 def __init__(self, exprs=(), derivatives=(), sleep=0, dsleep=0):
     super(ExecCompWithDerivatives, self).__init__()
     
     ins = set()
     outs = set()
     allvars = set()
     self.exprs = exprs
     self.codes = [compile(expr,'<string>','exec') for expr in exprs]
     self.sleep = sleep
     self.dsleep = dsleep
     
     for expr in exprs:
         lhs,rhs = expr.split('=')
         lhs = lhs.strip()
         lhs = lhs.split(',')
         outs.update(lhs)
         expreval = ExprEvaluator(expr, scope=self)
         allvars.update(expreval.get_referenced_varpaths(copy=False))
     ins = allvars - outs
     
     for var in allvars:
         if '.' not in var:  # if a varname has dots, it's outside of our scope,
                             # so don't add a trait for it
             if var in outs:
                 iotype = 'out'
             else:
                 iotype = 'in'
             self.add(var, Float(0.0, iotype=iotype))
 
     self.deriv_exprs = derivatives
     self.derivative_codes = \
         [compile(expr,'<string>','exec') for expr in derivatives]
     
     self.derivative_names = []
     regex = re.compile('d(.*)_d(.*)')
     for expr in derivatives:
         expreval = ExprEvaluator(expr, scope=self)
         exvars = expreval.get_referenced_varpaths(copy=False)
         
         lhs, _ = expr.split('=')
         lhs = lhs.strip()
         allvars.add(lhs)
         
         # Check for undefined vars the cool way with sets
         if len(exvars-allvars) > 0:
             self.raise_exception('derivative references a variable '
                                  'that is not defined in exprs',
                                  ValueError)
                 
         names = regex.findall(lhs)
         num = names[0][0]
         wrt = names[0][1]
         self.derivatives.declare_first_derivative(num, wrt)
         
         self.derivative_names.append( (lhs, num, wrt) )
开发者ID:Kenneth-T-Moore,项目名称:OpenMDAO-Framework,代码行数:55,代码来源:execcomp.py

示例14: __init__

    def __init__(self, target, high=None, low=None,
                 scaler=None, adder=None, start=None,
                 fd_step=None, scope=None, name=None,
                 _expreval=None):
        """If scaler and/or adder are not None, then high, low, and start, if
        not None, are assumed to be expressed in unscaled form. If high and low
        are not supplied, then their values will be pulled from the target
        variable (along with a start value), and are assumed to be in scaled
        form, so their values will be unscaled prior to being stored in the
        Parameter.
        """

        if scaler is None:
            scaler = 1.0
        if adder is None:
            adder = 0.0
        self._scaling_required = scaler != 1. or adder != 0.

        self.low = low
        self.high = high
        self.scaler = scaler
        self.adder = adder
        self.start = start
        self.fd_step = fd_step

        self.name = name or target

        if _expreval is None:
            try:
                _expreval = ExprEvaluator(target, scope)
            except Exception as err:
                raise err.__class__("Can't add parameter: %s" % str(err))
            if not _expreval.is_valid_assignee():
                raise ValueError("Can't add parameter: '%s' is not a valid"
                                 " parameter expression" % _expreval.text)
        self._expreval = _expreval

        try:
            self._metadata = self._expreval.get_metadata()
        except AttributeError:
            raise AttributeError("Can't add parameter '%s' because it doesn't"
                                 " exist." % target)

        # 'raw' metadata is in the form [(varname, metadata)],
        # so use [0][1] to get the actual metadata dict
        metadata = self._metadata[0][1]

        if 'iotype' in metadata and metadata['iotype'] == 'out':
            raise RuntimeError("Can't add parameter '%s' because '%s' is an"
                               " output." % (target, target))
        try:
            # So, our traits might not have a vartypename?
            self.vartypename = metadata['vartypename']
        except KeyError:
            self.vartypename = None
开发者ID:theoryno3,项目名称:OpenMDAO-Framework,代码行数:55,代码来源:hasparameters.py

示例15: test_slice

 def test_slice(self):
     ex = ExprEvaluator('a1d[1::2]', self.top.a)
     self.assertTrue(all(numpy.array([2.,4.,6.]) == ex.evaluate()))
     ex.text = 'a1d[2:4]'
     self.assertTrue(all(numpy.array([3.,4.]) == ex.evaluate()))
     ex.text = 'a1d[2:]'
     self.assertTrue(all(numpy.array([3.,4.,5.,6.]) == ex.evaluate()))
     ex.text = 'a1d[::-1]'
     self.assertTrue(all(numpy.array([6.,5.,4.,3.,2.,1.]) == ex.evaluate()))
     ex.text = 'a1d[:2]'
     self.assertTrue(all(numpy.array([1.,2.]) == ex.evaluate()))
开发者ID:drousis,项目名称:OpenMDAO-Framework,代码行数:11,代码来源:test_evalexpr.py


注:本文中的openmdao.main.expreval.ExprEvaluator类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。