• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python base.value函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: update_bounds_lists

        def update_bounds_lists(var_name):

            var_lb = None
            var_ub = None

            if var_data.fixed and self._output_fixed_variable_bounds:
                var_lb = var_ub = var_data.value
            elif var_data.fixed:
                # if we've been directed to not deal with fixed
                # variables, then skip - they should have been
                # compiled out of any description of the constraints
                return
            else:
                if var_data.lb is None:
                    var_lb = -cplex.infinity
                else:
                    var_lb = value(var_data.lb)

                if var_data.ub is None:
                    var_ub = cplex.infinity
                else:
                    var_ub= value(var_data.ub)

            var_cplex_id = self._cplex_variable_ids[var_name]

            new_lower_bounds.append((var_cplex_id, var_lb))
            new_upper_bounds.append((var_cplex_id, var_ub))
开发者ID:Juanlu001,项目名称:pyomo,代码行数:27,代码来源:CPLEXPersistent.py


示例2: _collect_linear_pow

def _collect_linear_pow(exp, idMap, multiplier, coef, varmap, compute_values):

    if exp.is_fixed():
        if compute_values:
            coef[None] += multiplier * value(exp)
        else:
            coef[None] += multiplier * exp
    elif value(exp._args[1]) == 1:
        arg = exp._args[0]
        _linear_collectors[arg.__class__](arg, idMap, multiplier, coef, varmap, compute_values)
    else:
        raise TypeError( "Unsupported power expression: "+str(exp._args) )
开发者ID:SemanticBeeng,项目名称:pyomo,代码行数:12,代码来源:canonical_repn.py


示例3: instance2dat

def instance2dat(instance, output_filename):

    output_file = open(output_filename,"w")

    for set_name, set_object in iteritems(instance.component_map(Set, active=True)):
        if (set_object.initialize is not None) and (type(set_object.initialize) is types.FunctionType):
            continue

        if (set_name.find("_index") == -1) and (set_name.find("_domain") == -1):
            if set_object.dim() == 0:
                if len(set_object) == 0:
                    continue
                print >>output_file, "set "+set_name+" := "
                for element in set_object:
                    print >>output_file, element
                print >>output_file, ";"
            elif set_object.dim() == 1:
                for index in set_object:
                    print >>output_file, "set "+set_name+"[\""+str(index)+"\"]"+" := ",
                    for element in set_object[index]:
                        print >>output_file, element,
                    print >>output_file, ";"
            else:
                print >>output_file, "***MULTIPLY INDEXED SETS NOT IMPLEMENTED!!!"
                pass

            print >>output_file, ""

    for param_name, param_object in iteritems(instance.component_map(Param, active=True)):
        if (param_object._initialize is not None) and (type(param_object._initialize) is types.FunctionType):
            continue
        elif len(param_object) == 0:
            continue

        if None in param_object:
            print >>output_file, "param "+param_name+" := "+str(value(param_object[None]))+" ;"
            print >>output_file, ""
        else:
            print >>output_file, "param "+param_name+" := "
            if param_object.dim() == 1:
                for index in param_object:
                    print >>output_file, index, str(value(param_object[index]))
            else:
                for index in param_object:
                    for i in index:
                        print >>output_file, i,
                    print >>output_file, str(value(param_object[index]))
            print >>output_file, ";"
            print >>output_file, ""

    output_file.close()
开发者ID:Juanlu001,项目名称:pyomo,代码行数:51,代码来源:instance2dat.py


示例4: __imul__

    def __imul__(self, other):
        _type = other.__class__
        if _type in native_numeric_types:
            pass
        elif _type is CompiledLinearCanonicalRepn:
            if other.variables:
                self, other = other, self
            assert(not other.variables)
            CompiledLinearCanonicalRepn_Pool.append(other)
            other = other.constant
        elif other.is_fixed():
            other = value(other)
        else:
            assert isinstance(other, _VarData)
            assert not self.variables
            self.variables.append(other)
            self.linear[id(other)] = self.constant
            self.constant = 0.
            return self

        if other:
            for _id in self.linear:
                self.linear[_id] *= other
        else:
            self.linear = {}
            self.variables = []
        self.constant *= other
        return self
开发者ID:SemanticBeeng,项目名称:pyomo,代码行数:28,代码来源:canonical_repn.py


示例5: __iadd__

 def __iadd__(self, other):
     _type = other.__class__
     if _type in native_numeric_types:
         self.constant += other
     elif _type is CompiledLinearCanonicalRepn:
         self.constant += other.constant
         for v in other.variables:
             _id = id(v)
             if _id in self.linear:
                 self.linear[_id] += other.linear[_id]
             else:
                 self.variables.append(v)
                 self.linear[_id] = other.linear[_id]
         CompiledLinearCanonicalRepn_Pool.append(other)
     elif other.is_fixed():
         self.constant += value(other)
     else:
         assert isinstance(other, _VarData)
         _id = id(other)
         if _id in self.linear:
             self.linear[_id] += 1.
         else:
             self.variables.append(other)
             self.linear[_id] = 1.
     return self
开发者ID:SemanticBeeng,项目名称:pyomo,代码行数:25,代码来源:canonical_repn.py


示例6: _collect_linear_intrinsic

def _collect_linear_intrinsic(exp, idMap, multiplier, coef, varmap, compute_values):

    if exp.is_fixed():
        if compute_values:
            coef[None] += multiplier * value(exp)
        else:
            coef[None] += multiplier * exp
    else:
        raise TypeError( "Unsupported intrinsic expression: %s: %s" % (exp, str(exp._args)) )
开发者ID:SemanticBeeng,项目名称:pyomo,代码行数:9,代码来源:canonical_repn.py


示例7: _collect_identity

def _collect_identity(exp, idMap, multiplier, coef, varmap, compute_values):
    exp = exp.expr
    if exp.is_fixed():
        if compute_values:
            coef[None] += multiplier * value(exp)
        else:
            coef[None] += multiplier * exp
    else:
        _linear_collectors[exp.__class__](exp, idMap, multiplier, coef, varmap, compute_values)
开发者ID:SemanticBeeng,项目名称:pyomo,代码行数:9,代码来源:canonical_repn.py


示例8: propagate_solution

    def propagate_solution(self, scaled_model, original_model):
        """
        This method takes the solution in scaled_model and maps it back to the original model.

        It will also transform duals and reduced costs if the suffixes 'dual' and/or 'rc' are present.
        The :code:`scaled_model` argument must be a model that was already scaled using this transformation
        as it expects data from the transformation to perform the back mapping.

        Parameters
        ----------
        scaled_model : Pyomo Model
           The model that was previously scaled with this transformation
        original_model : Pyomo Model
           The original unscaled source model

        """
        if not hasattr(scaled_model, 'component_scaling_factor_map'):
            raise AttributeError('ScaleModel:propagate_solution called with scaled_model that does not '
                                 'have a component_scaling_factor_map. It is possible this method was called '
                                 'using a model that was not scaled with the ScaleModel transformation')
        if not hasattr(scaled_model, 'scaled_component_to_original_name_map'):
            raise AttributeError('ScaleModel:propagate_solution called with scaled_model that does not '
                                 'have a scaled_component_to_original_name_map. It is possible this method was called '
                                 'using a model that was not scaled with the ScaleModel transformation')

        component_scaling_factor_map = scaled_model.component_scaling_factor_map
        scaled_component_to_original_name_map = scaled_model.scaled_component_to_original_name_map

        # get the objective scaling factor
        scaled_objectives = list(scaled_model.component_data_objects(ctype=Objective, active=True, descend_into=True))
        if len(scaled_objectives) != 1:
            raise NotImplementedError(
                'ScaleModel.propagate_solution requires a single active objective function, but %d objectives found.' % (
                    len(objectives)))
        objective_scaling_factor = component_scaling_factor_map[scaled_objectives[0]]

        # transfer the variable values and reduced costs
        check_reduced_costs = type(scaled_model.component('rc')) is Suffix
        for scaled_v in scaled_model.component_objects(ctype=Var, descend_into=True):
            # get the unscaled_v from the original model
            original_v_path = scaled_component_to_original_name_map[scaled_v]
            original_v = original_model.find_component(original_v_path)

            for k in scaled_v:
                original_v[k].value = value(scaled_v[k]) / component_scaling_factor_map[scaled_v[k]]
                if check_reduced_costs and scaled_v[k] in scaled_model.rc:
                    original_model.rc[original_v[k]] = scaled_model.rc[scaled_v[k]] * component_scaling_factor_map[
                        scaled_v[k]] / objective_scaling_factor

        # transfer the duals
        if type(scaled_model.component('dual')) is Suffix and type(original_model.component('dual')) is Suffix:
            for scaled_c in scaled_model.component_objects(ctype=Constraint, descend_into=True):
                original_c = original_model.find_component(scaled_component_to_original_name_map[scaled_c])

                for k in scaled_c:
                    original_model.dual[original_c[k]] = scaled_model.dual[scaled_c[k]] * component_scaling_factor_map[
                        scaled_c[k]] / objective_scaling_factor
开发者ID:Pyomo,项目名称:pyomo,代码行数:57,代码来源:scaling.py


示例9: visiting_potential_leaf

        def visiting_potential_leaf(self, node):
            """ 
            Visiting a potential leaf.

            Return True if the node is not expanded.
            """
            if node.__class__ in native_numeric_types:
                return True, node

            if node.__class__ is casadi.SX:
                return True, node

            if node.is_variable_type():
                return True, value(node)

            if not node.is_expression_type():
                return True, value(node)

            return False, None
开发者ID:Pyomo,项目名称:pyomo,代码行数:19,代码来源:simulator.py


示例10: _collect_linear_prod

def _collect_linear_prod(exp, idMap, multiplier, coef, varmap, compute_values):

    multiplier *= exp._coef
    _coef = { None : 0 }
    _varmap = {}

    for subexp in exp._denominator:
        if compute_values:
            x = value(subexp) # only have constants/fixed terms in the denominator.
            if x == 0:
                buf = StringIO()
                subexp.pprint(buf)
                logger.error("Divide-by-zero: offending sub-expression:\n   " + buf)
                raise ZeroDivisionError
            multiplier /= x
        else:
            multiplier /= subexp

    for subexp in exp._numerator:
        if _varmap:
            if compute_values:
                multiplier *= value(subexp)
            else:
                multiplier *= subexp
        else:
            _linear_collectors[subexp.__class__](subexp, idMap, 1, _coef, _varmap, compute_values)
            if not _varmap:
                multiplier *= _coef[None]
                _coef[None] = 0

    if _varmap:
        for key, val in iteritems(_coef):
            if key in coef:
                coef[key] += multiplier * val
            else:
                coef[key] = multiplier * val
        varmap.update(_varmap)
    else:
        # constant expression; i.e. 1/x
        coef[None] += multiplier
开发者ID:SemanticBeeng,项目名称:pyomo,代码行数:40,代码来源:canonical_repn.py


示例11: get_table

 def get_table(self):
     tmp = []
     if not self.options.columns is None:
         tmp.append(self.options.columns)
     if not self.options.set is None:
         # Create column names
         if self.options.columns is None:
             cols = []
             for i in xrange(self.options.set.dimen):
                 cols.append(self.options.set.local_name+str(i))
             tmp.append(cols)
         # Get rows
         if not self.options.sort is None:
             for data in sorted(self.options.set):
                 if self.options.set.dimen > 1:
                     tmp.append(list(data))
                 else:
                     tmp.append([data])
         else:
             for data in self.options.set:
                 if self.options.set.dimen > 1:
                     tmp.append(list(data))
                 else:
                     tmp.append([data])
     elif not self.options.param is None:
         if type(self.options.param) in (list,tuple):
             _param = self.options.param
         else:
             _param = [self.options.param]
         tmp = []
         # Collect data
         for index in _param[0]:
             if index is None:
                 row = []
             elif type(index) in (list,tuple):
                 row = list(index)
             else:
                 row = [index]
             for param in _param:
                 row.append(value(param[index]))
             tmp.append(row)
         # Create column names
         if self.options.columns is None:
             cols = []
             for i in xrange(len(tmp[0])-len(_param)):
                 cols.append('I'+str(i))
             for param in _param:
                 cols.append(param)
             tmp = [cols] + tmp
     return tmp
开发者ID:qtothec,项目名称:pyomo,代码行数:50,代码来源:TableData.py


示例12: subproblem_solve

    def subproblem_solve(gdp, solver, config):
        subproblem = gdp.clone()
        TransformationFactory('gdp.fix_disjuncts').apply_to(subproblem)

        result = solver.solve(subproblem, **config.solver_args)
        main_obj = next(subproblem.component_data_objects(Objective, active=True))
        obj_sign = 1 if main_obj.sense == minimize else -1
        if (result.solver.status is SolverStatus.ok and
                result.solver.termination_condition is tc.optimal):
            return value(main_obj.expr), result, subproblem.GDPbb_utils.variable_list
        elif result.solver.termination_condition is tc.unbounded:
            return obj_sign * float('-inf'), result, subproblem.GDPbb_utils.variable_list
        else:
            return obj_sign * float('inf'), result, subproblem.GDPbb_utils.variable_list
开发者ID:Pyomo,项目名称:pyomo,代码行数:14,代码来源:GDPbb.py


示例13: coopr3_generate_canonical_repn

def coopr3_generate_canonical_repn(exp, idMap=None, compute_values=True):
    if exp is None:
        return CompiledLinearCanonicalRepn()
    degree = exp.polynomial_degree()

    if idMap is None:
        idMap = {}
    idMap.setdefault(None, {})

    if degree == 0:
        ans = CompiledLinearCanonicalRepn()
        ans.constant = value(exp)
        return ans

    elif degree == 1:
        # varmap is a map from the variable id() to a _VarData.
        # coef is a map from the variable id() to its coefficient.
        coef, varmap = collect_linear_canonical_repn(exp, idMap, compute_values)
        ans = CompiledLinearCanonicalRepn()
        if None in coef:
            val = coef.pop(None)
            if type(val) not in [int,float] or val != 0.0:
                ans.constant = val

        # the six module is inefficient in terms of wrapping iterkeys
        # and itervalues, in the context of Python 2.7. use the native
        # dictionary methods where possible.
        if using_py3:
            ans.linear = tuple( itervalues(coef) )
            ans.variables = tuple(varmap[var_hash] for var_hash in iterkeys(coef) )
        else:
            ans.linear = tuple( coef.itervalues() )
            ans.variables = tuple(varmap[var_hash] for var_hash in coef.iterkeys() )
        return ans

    # **Py3k: degree > 1 comparision will error if degree is None
    elif degree and degree > 1:
        ans = collect_general_canonical_repn(exp, idMap, compute_values)
        if 1 in ans:
            linear_terms = {}
            for key, coef in iteritems(ans[1]):
                linear_terms[list(key.keys())[0]] = coef
            ans[1] = linear_terms
        return GeneralCanonicalRepn(ans)
    else:
        return GeneralCanonicalRepn(
            { None: exp, -1 : collect_variables(exp, idMap) } )
开发者ID:Pyomo,项目名称:pyomo,代码行数:47,代码来源:canonical_repn.py


示例14: _collect_linear_var

def _collect_linear_var(exp, idMap, multiplier, coef, varmap, compute_values):

    if exp.is_fixed():
        if compute_values:
            coef[None] += multiplier * value(exp)
        else:
            coef[None] += multiplier * exp
    else:
        id_ = id(exp)
        if id_ in idMap[None]:
            key = idMap[None][id_]
        else:
            key = len(idMap) - 1
            idMap[None][id_] = key
            idMap[key] = exp
        #
        if key in coef:
            coef[key] += multiplier
        else:
            coef[key] = multiplier
        varmap[key] = exp
开发者ID:SemanticBeeng,项目名称:pyomo,代码行数:21,代码来源:canonical_repn.py


示例15: pyomo4_generate_canonical_repn

def pyomo4_generate_canonical_repn(exp, idMap=None, compute_values=True):
    if exp is None:
        return CompiledLinearCanonicalRepn()
    if exp.__class__ in native_numeric_types:
        ans = CompiledLinearCanonicalRepn()
        ans.constant = value(exp)
        return ans
    if not exp.is_expression():
        if exp.is_fixed():
            ans = CompiledLinearCanonicalRepn()
            ans.constant = value(exp)
            return ans
        elif isinstance(exp, _VarData):
            ans = CompiledLinearCanonicalRepn()
            ans.constant = 0
            ans.linear = (1.,)
            ans.variables = (exp,)
            return ans
        else:
            raise RuntimeError(
                "Unrecognized expression node: %s" % (type(exp),) )

    degree = exp.polynomial_degree()

    if degree == 1:
        _stack = []
        _args = exp._args
        _idx = 0
        _len = len(_args)
        _result = None
        while 1:
            # Linear expressions just need to be filteres and copied
            if exp.__class__ is expr_pyomo4._LinearExpression:
                _result = expr_pyomo4._LinearExpression(None, 0)
                _result._args = []
                _result._coef.clear()
                _result._const = value(exp._const)
                for v in _args:
                    _id = id(v)
                    if v.is_fixed():
                        _result._const += v.value * value(exp._coef[_id])
                    else:
                        _result._args.append(v)
                        _result._coef[_id] = value(exp._coef[_id])
                _idx = _len

            # Other expressions get their arguments parsed one at a time
            if _idx < _len:
                _stack.append((exp, _args, _idx+1, _len, _result))
                exp = _args[_idx]
                if exp.__class__ in native_numeric_types:
                    _len = _idx = 0
                    _result = exp
                elif exp.is_expression():
                    _args = exp._args
                    _idx = 0
                    _len = len(_args)
                    _result = None
                    continue
                elif isinstance(exp, _VarData):
                    _len = _idx = 0
                    if exp.is_fixed():
                        _result = exp.value
                    else:
                        _result = expr_pyomo4._LinearExpression(exp, 1.)
                else:
                    raise RuntimeError(
                        "Unrecognized expression node: %s" % (type(exp),) )

            #
            # End of _args... time to move up the stack
            #

            # Top of the stack.  _result had better be a _LinearExpression
            if not _stack:
                ans = CompiledLinearCanonicalRepn()
                # old format
                ans.constant = _result._const
                ans.linear = []
                for v in _result._args:
                    # Note: this also filters out the bogus NONE we added above
                    _coef = _result._coef[id(v)]
                    if _coef:
                        ans.variables.append(v)
                        ans.linear.append(_coef)

                if idMap:
                    if None not in idMap:
                        idMap[None] = {}
                    _test = idMap[None]
                    _key = len(idMap) - 1
                    for v in ans.variables:
                        if id(v) not in _test:
                            _test[id(v)] = _key
                            idMap[_key] = v
                            _key += 1
                return ans

            # Ok ... process the new argument to the node.  Note that
            # _idx is 1-based now...
#.........这里部分代码省略.........
开发者ID:Pyomo,项目名称:pyomo,代码行数:101,代码来源:canonical_repn.py


示例16: simulate

    def simulate(self, numpoints=None, tstep=None, integrator=None,
                 varying_inputs=None, initcon=None, integrator_options=None):
        """
        Simulate the model. Integrator-specific options may be specified as
        keyword arguments and will be passed on to the integrator.

        Parameters
        ----------
        numpoints : int
            The number of points for the profiles returned by the simulator.
            Default is 100

        tstep : int or float
            The time step to use in the profiles returned by the simulator.
            This is not the time step used internally by the integrators.
            This is an optional parameter that may be specified in place of
            'numpoints'.

        integrator : string
            The string name of the integrator to use for simulation. The
            default is 'lsoda' when using Scipy and 'idas' when using CasADi

        varying_inputs : ``pyomo.environ.Suffix``
            A :py:class:`Suffix<pyomo.environ.Suffix>` object containing the
            piecewise constant profiles to be used for certain time-varying
            algebraic variables.

        initcon : list of floats
            The initial conditions for the the differential variables. This
            is an optional argument. If not specified then the simulator
            will use the current value of the differential variables at the
            lower bound of the ContinuousSet for the initial condition.

        integrator_options : dict
            Dictionary containing options that should be passed to the
            integrator. See the documentation for a specific integrator for a
            list of valid options.

        Returns
        -------
        numpy array, numpy array
            The first return value is a 1D array of time points corresponding
            to the second return value which is a 2D array of the profiles for
            the simulated differential and algebraic variables.
        """

        if not numpy_available:
            raise ValueError("The numpy module is not available. "
                              "Cannot simulate the model.")

        if integrator_options is None:
            integrator_options = {}

        if self._intpackage == 'scipy':
            # Specify the scipy integrator to use for simulation
            valid_integrators = ['vode', 'zvode', 'lsoda', 'dopri5', 'dop853']
            if integrator is None:
                integrator = 'lsoda'
            elif integrator is 'odeint':
                integrator = 'lsoda'
        else:
            # Specify the casadi integrator to use for simulation.
            # Only a subset of these integrators may be used for 
            # DAE simulation. We defer this check to CasADi.
            valid_integrators = ['cvodes', 'idas', 'collocation', 'rk']
            if integrator is None:
                integrator = 'idas'

        if integrator not in valid_integrators:
            raise DAE_Error("Unrecognized %s integrator \'%s\'. Please select"
                            " an integrator from %s" % (self._intpackage,
                                                        integrator,
                                                        valid_integrators))

        # Set the time step or the number of points for the lists
        # returned by the integrator
        if tstep is not None and \
           tstep > (self._contset.last() - self._contset.first()):
            raise ValueError(
                "The step size %6.2f is larger than the span of the "
                "ContinuousSet %s" % (tstep, self._contset.name()))
        
        if tstep is not None and numpoints is not None:
            raise ValueError(
                "Cannot specify both the step size and the number of "
                "points for the simulator")
        if tstep is None and numpoints is None:
            # Use 100 points by default
            numpoints = 100

        if tstep is None:
            tsim = np.linspace(
                self._contset.first(), self._contset.last(), num=numpoints)

            # Consider adding an option for log spaced time points. Can be
            # important for simulating stiff systems.
            # tsim = np.logspace(-4,6, num=100)
            # np.log10(self._contset.first()),np.log10(
            # self._contset.last()),num=1000, endpoint=True)

#.........这里部分代码省略.........
开发者ID:Pyomo,项目名称:pyomo,代码行数:101,代码来源:simulator.py


示例17: _apply_to

    def _apply_to(self, model, **kwds):
        # create a map of component to scaling factor
        component_scaling_factor_map = ComponentMap()

        # if the scaling_method is 'user', get the scaling parameters from the suffixes
        if self._scaling_method == 'user':
            # perform some checks to make sure we have the necessary suffixes
            if type(model.component('scaling_factor')) is not Suffix:
                raise ValueError("ScaleModel transformation called with scaling_method='user'"
                                 ", but cannot find the suffix 'scaling_factor' on the model")

            # get the scaling factors
            for c in model.component_data_objects(ctype=(Var, Constraint, Objective), descend_into=True):
                component_scaling_factor_map[c] = self._get_float_scaling_factor(model, c)
        else:
            raise ValueError("ScaleModel transformation: unknown scaling_method found"
                             "-- supported values: 'user' ")

        # rename all the Vars, Constraints, and Objectives from foo to scaled_foo
        scaled_component_to_original_name_map = \
            rename_components(model=model,
                              component_list=list(model.component_objects(ctype=[Var, Constraint, Objective])),
                              prefix='scaled_')

        # scale the variable bounds and values and build the variable substitution map
        # for scaling vars in constraints
        variable_substitution_map = ComponentMap()
        for variable in [var for var in model.component_objects(ctype=Var, descend_into=True)]:
            # set the bounds/value for the scaled variable
            for k in variable:
                v = variable[k]
                scaling_factor = component_scaling_factor_map[v]
                variable_substitution_map[v] = v / scaling_factor

                if v.lb is not None:
                    v.setlb(v.lb * scaling_factor)
                if v.ub is not None:
                    v.setub(v.ub * scaling_factor)
                if scaling_factor < 0:
                    temp = v.lb
                    v.setlb(v.ub)
                    v.setub(temp)

                if v.value is not None:
                    v.value = value(v) * scaling_factor

        # scale the objectives/constraints and perform the scaled variable substitution
        scale_constraint_dual = False
        if type(model.component('dual')) is Suffix:
            scale_constraint_dual = True

        # translate the variable_substitution_map (ComponentMap)
        # to variable_substition_dict (key: id() of component)
        # ToDo: We should change replace_expressions to accept a ComponentMap as well
        variable_substitution_dict = dict()
        for k in variable_substitution_map:
            variable_substitution_dict[id(k)] = variable_substitution_map[k]

        for component in model.component_objects(ctype=(Constraint, Objective), descend_into=True):
            for k in component:
                c = component[k]
                # perform the constraint/objective scaling and variable sub
                scaling_factor = component_scaling_factor_map[c]
                if isinstance(c, _ConstraintData):
                    body = scaling_factor * \
                           replace_expressions(expr=c.body,
                                               substitution_map=variable_substitution_dict,
                                               descend_into_named_expressions=True,
                                               remove_named_expressions=True)

                    # scale the rhs
                    if c._lower is not None:
                        c._lower = c._lower * scaling_factor
                    if c._upper is not None:
                        c._upper = c._upper * scaling_factor

                    if scaling_factor < 0:
                        c._lower, c._upper = c._upper, c._lower

                    if scale_constraint_dual and c in model.dual:
                        dual_value = model.dual[c]
                        if dual_value is not None:
                            model.dual[c] = dual_value / scaling_factor

                    c.set_value((c._lower, body, c._upper))

                elif isinstance(c, _ObjectiveData):
                    c.expr = scaling_factor * \
                             replace_expressions(expr=c.expr,
                                                 substitution_map=variable_substitution_dict,
                                                 descend_into_named_expressions=True,
                                                 remove_named_expressions=True)
                else:
                    raise NotImplementedError(
                        'Unknown object type found when applying scaling factors in ScaleModel transformation - Internal Error')

        model.component_scaling_factor_map = component_scaling_factor_map
        model.scaled_component_to_original_name_map = scaled_component_to_original_name_map

        return model
开发者ID:Pyomo,项目名称:pyomo,代码行数:100,代码来源:scaling.py


示例18: pyomo4_generate_canonical_repn

def pyomo4_generate_canonical_repn(exp, idMap=None, compute_values=True):
    # A **very** special case
    if TreeWalkerHelper.typeList.get(exp.__class__,0) == 4: # _LinearExpression:
        ans = CompiledLinearCanonicalRepn()

        # old format
        ans.constant = exp._const
        ans.variables = list( exp._args )
        _l = exp._coef
        ans.linear = [_l[id(v)] for v in exp._args]

        if idMap:
            if None not in idMap:
                idMap[None] = {}
            _test = idMap[None]
            _key = len(idMap) - 1
            for v in exp._args:
                if id(v) not in _test:
                    _test[id(v)] = _key
                    idMap[_key] = v
                    _key += 1
        return ans
    else:
        degree = exp.polynomial_degree()

    if degree == 1:
        _typeList = TreeWalkerHelper.typeList
        _stackMax = len(_stack)
        _stackIdx = 0
        _stackPtr = _stack[0]

        _stackPtr[0] = exp
        try:
            _stackPtr[1] = exp._args
        except AttributeError:
            ans = CompiledLinearCanonicalRepn()
            ans.variables.append(exp)
            # until we can redefine CompiledLinearCanonicalRepn, restore
            # old format
            #ans.linear[id(exp)] = 1.
            ans.linear = [1.]
            return ans
        try:
            _stackPtr[2] = _type = _typeList[exp.__class__]
            if _stackPtr[2] == 2:
                _stackPtr[5].constant = 1.
        except KeyError:
            _stackPtr[2] = _type = 0
        _stackPtr[3] = len(_stackPtr[1])
        _stackPtr[4] = 0
        #_stackPtr[5] = CompiledLinearCanonicalRepn()

        if _type == 4: # _LinearExpression
            _stackPtr[4] = _stackPtr[3]
            _stackPtr[5].constant = exp._const
            _stackPtr[5].linear = dict(exp._coef)
            _stackPtr[5].variables = list(exp._args)

        while 1: # Note: 1 is faster than True for Python 2.x
            if _stackPtr[4] < _stackPtr[3]:
                _sub = _stackPtr[1][_stackPtr[4]]
                _stackPtr[4] += 1
                _test = _sub.__class__ in native_numeric_types
                if _test or not _sub.is_expression():
                    if not _test and _sub.is_fixed():
                        _sub = value(_sub)
                        _test = 1 # True
                    if _test:
                        if _type == 2:
                            _stackPtr[5].constant *= _sub
                            _l = _stackPtr[5].linear
                            if _l:
                                for _id in _l:
                                    _l[_id] *= _sub
                        elif _type == 1:
                            _stackPtr[5].constant += _sub
                        elif _type == 3:
                            _stackPtr[5].constant = -1. * _sub
                        else:
                            raise RuntimeError("HELP")
                    else:
                        _id = id(_sub)
                        if _type == 2:
                            _lcr = _stackPtr[5]
                            _lcr.variables.append(_sub)
                            _lcr.linear[_id] = _lcr.constant
                            _lcr.constant = 0
                        elif _type == 1:
                            if _id in _stackPtr[5].linear:
                                _stackPtr[5].linear[_id] += 1.
                            else:
                                _stackPtr[5].variables.append(_sub)
                                _stackPtr[5].linear[_id] = 1.
                        elif _type == 3:
                            _lcr = _stackPtr[5]
                            _lcr.variables.append(_sub)
                            _lcr.linear[_id] = -1.
                        else:
                            raise RuntimeError("HELP")
                else:
#.........这里部分代码省略.........
开发者ID:SemanticBeeng,项目名称:pyomo,代码行数:101,代码来源:canonical_repn.py


示例19: _print_model_LP


#.........这里部分代码省略.........

        output_file.write("bounds\n")

        # Scan all variables even if we're only writing a subset of them.
        # required because we don't store maps by variable type currently.

        # FIXME: This is a hack to get nested blocks working...
        lb_string_template = "%"+self._precision_string+" <= "
        ub_string_template = " <= %"+self._precision_string+"\n"
        # Track the number of integer and binary variables, so you can
        # output their status later.
        integer_vars = []
        binary_vars = []
        for vardata in variable_list:

            # TODO: We could just loop over the set of items in
            #       self._referenced_variable_ids, except this is
            #       a dictionary that is hashed by id(vardata)
            #       which would make the bounds section
            #       nondeterministic (bad for unit testing)
            if (not include_all_variable_bounds) and \
               (id(vardata) not in self._referenced_variable_ids):
                continue

            if vardata.fixed:
                if not output_fixed_variable_bounds:
                    raise ValueError(
                        "Encountered a fixed variable (%s) inside an active "
                        "objective or constraint expression on model %s, which is "
                        "usually indicative of a preprocessing error. Use the "
                        "IO-option 'output_fixed_variable_bounds=True' to suppress "
                        "this error and fix the variable by overwriting its bounds "
                        "in the LP file." % (vardata.name, model.name))
                if vardata.value is None:
                    raise ValueError("Variable cannot be fixed to a value of None.")
                vardata_lb = value(vardata.value)
                vardata_ub = value(vardata.value)
            else:
                vardata_lb = self._get_bound(vardata.lb)
                vardata_ub = self._get_bound(vardata.ub)

            name_to_output = variable_symbol_dictionary[id(vardata)]

            # track the number of integer and binary variables, so we know whether
            # to output the general / binary sections below.
            if vardata.is_integer():
                integer_vars.append(name_to_output)
            elif vardata.is_binary():
                binary_vars.append(name_to_output)
            elif not vardata.is_continuous():
                raise TypeError("Invalid domain type for variable with name '%s'. "
                                "Variable is not continuous, integer, or binary."
                                % (vardata.name))

            # in the CPLEX LP file format, the default variable
            # bounds are 0 and +inf.  These bounds are in
            # conflict with Pyomo, which assumes -inf and +inf
            # (which we would argue is more rational).
            output_file.write("   ")
            if (vardata_lb is not None) and (vardata_lb != -infinity):
                output_file.write(lb_string_template
                                  % (_no_negative_zero(vardata_lb)))
            else:
                output_file.write(" -inf <= ")
            if name_to_output == "e":
                raise ValueError(
开发者ID:qtothec,项目名称:pyomo,代码行数:67,代码来源:cpxlp.py



鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python environ.value函数代码示例发布时间:2022-05-27
下一篇:
Python core.ConcreteModel类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap