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


Python pulp.value方法代码示例

本文整理汇总了Python中pulp.value方法的典型用法代码示例。如果您正苦于以下问题:Python pulp.value方法的具体用法?Python pulp.value怎么用?Python pulp.value使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pulp的用法示例。


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

示例1: _process_duals

# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import value [as 别名]
def _process_duals(self, dmu_code, categories, func):
        ''' Helper function that adds duals to solution using given method func.
            Helps to avoid code duplication.

            Args:
                dmu_code (str): DMU code under consideration.
                categories (list of str): list of either input or output
                    categories.
                func (function): a function that accepts DMU code, category and
                    dual variable value and adds it to solution.
        '''
        for category in categories:
            constraint_name = self._constraints[category]
            dual = self._concrete_model.process_dual_value(
                self.lp_model.constraints[constraint_name].pi)
            func(dmu_code, category, dual) 
开发者ID:araith,项目名称:pyDEA,代码行数:18,代码来源:envelopment_model_base.py

示例2: _get_efficiency_score

# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import value [as 别名]
def _get_efficiency_score(self, lambda_variable):
        ''' Returns efficiency score based on a given lambda variable.

            Args:
                lambda_variable (double): value of the lambda variable.

            Returns:
                double: efficiency spyDEA.core.
        '''
        eff_score = self._concrete_model.process_obj_var(pulp.value(
            self.lp_model.objective))
        # None is possible when objective function is zero
        if eff_score is None:
            eff_score = 0
        if is_efficient(eff_score, lambda_variable):
            eff_score = 1
        return eff_score 
开发者ID:araith,项目名称:pyDEA,代码行数:19,代码来源:multiplier_model_base.py

示例3: word_mover_distance

# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import value [as 别名]
def word_mover_distance(first_sent_tokens, second_sent_tokens, wvmodel, distancefunc=euclidean, lpFile=None):
    """ Compute the Word Mover's distance (WMD) between the two given lists of tokens.

    Using methods of linear programming, supported by PuLP, calculate the WMD between two lists of words. A word-embedding
    model has to be provided. WMD is returned.

    Reference: Matt J. Kusner, Yu Sun, Nicholas I. Kolkin, Kilian Q. Weinberger, "From Word Embeddings to Document Distances," *ICML* (2015).

    :param first_sent_tokens: first list of tokens.
    :param second_sent_tokens: second list of tokens.
    :param wvmodel: word-embedding models.
    :param distancefunc: distance function that takes two numpy ndarray.
    :param lpFile: log file to write out.
    :return: Word Mover's distance (WMD)
    :type first_sent_tokens: list
    :type second_sent_tokens: list
    :type wvmodel: gensim.models.keyedvectors.KeyedVectors
    :type distancefunc: function
    :type lpFile: str
    :rtype: float
    """
    prob = word_mover_distance_probspec(first_sent_tokens, second_sent_tokens, wvmodel,
                                        distancefunc=distancefunc, lpFile=lpFile)
    return pulp.value(prob.objective) 
开发者ID:stephenhky,项目名称:PyShortTextCategorization,代码行数:26,代码来源:wordmoverdist.py

示例4: __apply_initial_weights_override__

# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import value [as 别名]
def __apply_initial_weights_override__(self, weights_override={}, clear_before_override=None):
        """

        :param clear_before_override: bool: if True, all weights are set to a default value, no matter what.
        :param weights_override:
        """
        if (weights_override):
            if clear_before_override is not None:
                print("Clearing summarizer weights")
                for k, v in self.summarizer.weights.iteritems():
                    self.summarizer.weights[k] = float(clear_before_override)
            print("Overriding weights")
            for k, v in weights_override.iteritems():
                if self.summarizer.weights.has_key(k):
                    print("Overriding summarizer weight for '%s' with '%s' (was '%s')" % (
                    k, v, self.summarizer.weights[k]))
                    self.summarizer.weights[k] = v 
开发者ID:UKPLab,项目名称:acl2017-interactive_summarizer,代码行数:19,代码来源:simulated_feedback.py

示例5: solve

# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import value [as 别名]
def solve(self):
        super(_LP, self).solve()
        objective = pulp.value(self.objective)
        variables, values = [], []
        for v in self.variables():
            variables.append(v.name)
            values.append(v.varValue)
        status = pulp.LpStatus[self.status]
        self.assignVarsVals(dict.fromkeys(variables, None))
        return Result(status_code=self.status,
                      status=status,
                      objective=objective,
                      variables=variables,
                      values=values)


# =============================================================================
# CONCRETE CLASS
# ============================================================================= 
开发者ID:leliel12,项目名称:scikit-criteria,代码行数:21,代码来源:lp.py

示例6: solve_simple

# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import value [as 别名]
def solve_simple(scene):
    for cur in itertools.chain(scene.all_cells, scene.all_columns):
        if isinstance(cur, Cell) and cur.display is Cell.unknown:
            continue
        if cur.value is not None and any(x.display is Cell.unknown for x in cur.members):
            # Fill up remaining fulls
            if cur.value == sum(1 for x in cur.members if x.display is not Cell.empty):
                for x in cur.members:
                    if x.display is Cell.unknown:
                        yield x, Cell.full
            # Fill up remaining empties
            if len(cur.members)-cur.value == sum(1 for x in cur.members if x.display is not Cell.full):
                for x in cur.members:
                    if x.display is Cell.unknown:
                        yield x, Cell.empty 
开发者ID:oprypin,项目名称:sixcells,代码行数:17,代码来源:solver.py

示例7: _create_main_constraints

# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import value [as 别名]
def _create_main_constraints(self):
        # Depending on what you need, you may want to consider creating any of
        # the expressions (constraints or objective terms) as an attribute of
        # the OptimizationModel class (e.g. self.inv_balance_constraints).
        # That way if, for example, at the end of the optimization you need to check
        # the slack variables of certain constraints, you know they already exists in your model

        # ================== Inventory balance constraints ==================
        self.inv_balance_constraints = {
            period: add_constr(self.model, pulp.LpConstraint(
                e=self.inventory_variables[period - 1] + self.production_variables[period]
                  - self.inventory_variables[period],
                sense=pulp.LpConstraintEQ,
                name='inv_balance' + str(period),
                rhs=value.demand))
            for period, value in self.input_data.iloc[1:].iterrows()}

        # inv balance for first period
        self.first_period_inv_balance_constraints = add_constr(self.model, pulp.LpConstraint(
            e=self.production_variables[0] - self.inventory_variables[0],
            sense=pulp.LpConstraintEQ,
            name='inv_balance0',
            rhs=self.input_data.iloc[0].demand - self.input_params['initial_inventory']))

        # ================== Production capacity constraints ==================
        self.production_capacity_constraints = {
            index: add_constr(self.model, pulp.LpConstraint(
                e=value,
                sense=pulp.LpConstraintLE,
                name='prod_cap_month_' + str(index),
                rhs=self.input_data.iloc[index].production_capacity))
            for index, value in self.production_variables.items()}

    # ================== Costs and objective function ================== 
开发者ID:ekhoda,项目名称:optimization-tutorial,代码行数:36,代码来源:optimization_model_pulp.py

示例8: get_minima

# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import value [as 别名]
def get_minima(self, phases, bounds):
        """
        Given a set of Phases, get_minima will determine the minimum
        free energy elemental composition as a weighted sum of these
        compounds
        """

        prob = pulp.LpProblem('GibbsEnergyMin', pulp.LpMinimize)
        pvars = pulp.LpVariable.dicts('phase', phases, 0)
        bvars = pulp.LpVariable.dicts('bound', bounds, 0.0, 1.0)
        prob += pulp.lpSum( self.phase_energy(p)*pvars[p] for p in phases ) - \
                pulp.lpSum( self.phase_energy(bound)*bvars[bound] for bound in bounds ), \
                                "Free Energy"
        for elt in self.bound_space:
            prob += sum([ p.unit_comp.get(elt,0)*pvars[p] for p in phases ])\
                        == \
                sum([ b.unit_comp.get(elt, 0)*bvars[b] for b in bounds ]),\
                            'Contraint to the proper range of'+elt
        prob += sum([ bvars[b] for b in bounds ]) == 1, \
                'sum of bounds must be 1'

        if pulp.GUROBI().available():
            prob.solve(pulp.GUROBI(msg=False))
        elif pulp.COIN_CMD().available():
            prob.solve(pulp.COIN_CMD())
        elif pulp.COINMP_DLL().available():
            prob.solve(pulp.COINMP_DLL())
        else:
            prob.solve()

        E = pulp.value(prob.objective)
        xsoln = defaultdict(float,
            [(p, pvars[p].varValue) for p in phases if
                abs(pvars[p].varValue) > 1e-4])
        return xsoln, E 
开发者ID:wolverton-research-group,项目名称:qmpy,代码行数:37,代码来源:space.py

示例9: compute_stabilities

# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import value [as 别名]
def compute_stabilities(self, phases=None, save=False, reevaluate=True):
        """
        Calculate the stability for every Phase.

        Keyword Arguments:
            phases:
                List of Phases. If None, uses every Phase in PhaseSpace.phases

            save:
                If True, save the value for stability to the database. 

            new_only:
                If True, only compute the stability for Phases which did not
                import a stability from the OQMD. False by default.
        """
        from qmpy.analysis.vasp.calculation import Calculation
        if phases is None:
            phases = self.phases

        if reevaluate:
            for p in self.phases:
                p.stability = None

        for p in phases:
            if p.stability is None:
                if p in self.phase_dict.values():
                    self.compute_stability(p)
                else:
                    p2 = self.phase_dict[p.name]
                    if p2.stability is None:
                        self.compute_stability(p2)
                    base = max(0, p2.stability)
                    diff = p.energy - p2.energy
                    p.stability = base + diff

            if save:
                qs = qmpy.FormationEnergy.objects.filter(id=p.id)
                qs.update(stability=p.stability) 
开发者ID:wolverton-research-group,项目名称:qmpy,代码行数:40,代码来源:space.py

示例10: _fill_solution

# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import value [as 别名]
def _fill_solution(self, dmu_code, model_solution):
        ''' Fills given solution with data calculated for one DMU.

            Args:
                dmu_code (str): DMU code for which the LP was solved.
                model_solution (Solution): object where solution for one DMU
                    will be written.
        '''
        model_solution.orientation = self._concrete_model.get_orientation()
        model_solution.add_lp_status(dmu_code, self.lp_model.status)

        if self.lp_model.status == pulp.LpStatusOptimal:
            lambda_variables = dict()
            for dmu in self.input_data.DMU_codes:
                var = self._variables.get(dmu, None)
                if (var is not None and var.varValue is not None and
                        abs(var.varValue) > ZERO_TOLERANCE):
                    lambda_variables[dmu] = var.varValue

            if self._should_add_efficiency:
                model_solution.add_efficiency_score(
                    dmu_code, self._concrete_model.process_obj_var
                    (pulp.value(self.lp_model.objective)))
                
            model_solution.add_lambda_variables(dmu_code, lambda_variables)
            self._process_duals(dmu_code, self.input_data.input_categories,
                                model_solution.add_input_dual)
            self._process_duals(dmu_code, self.input_data.output_categories,
                                model_solution.add_output_dual) 
开发者ID:araith,项目名称:pyDEA,代码行数:31,代码来源:envelopment_model_base.py

示例11: solve

# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import value [as 别名]
def solve(g):
    el = g.get_edge_list()
    nl = g.get_node_list()
    p = LpProblem('min_cost', LpMinimize)
    capacity = {}
    cost = {}
    demand = {}
    x = {}
    for e in el:
        capacity[e] = g.get_edge_attr(e[0], e[1], 'capacity')
        cost[e] = g.get_edge_attr(e[0], e[1], 'cost')
    for i in nl:
        demand[i] = g.get_node_attr(i, 'demand')
    for e in el:
        x[e] = LpVariable("x"+str(e), 0, capacity[e])
    # add obj
    objective = lpSum (cost[e]*x[e] for e in el)
    p += objective
    # add constraints
    for i in nl:
        out_neig = g.get_out_neighbors(i)
        in_neig = g.get_in_neighbors(i)
        p += lpSum(x[(i,j)] for j in out_neig) -\
             lpSum(x[(j,i)] for j in in_neig)==demand[i]
    p.solve()
    return x, value(objective) 
开发者ID:coin-or,项目名称:GiMPy,代码行数:28,代码来源:simplex_test.py

示例12: get_allocations

# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import value [as 别名]
def get_allocations(x, product_names, out_shape):
    """Return allocations after solving of LP and reshape them."""
    allocations = [x[it].value() for it in product_names]
    return np.array(allocations).reshape(out_shape) 
开发者ID:flix-tech,项目名称:RevPy,代码行数:6,代码来源:lp_solve.py

示例13: solve_lp

# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import value [as 别名]
def solve_lp(prob):
    """Solve LP, return min/max."""
    optimization_result = prob.solve()
    assert optimization_result == pulp.LpStatusOptimal
    optimal_value = pulp.value(prob.objective)

    return optimal_value 
开发者ID:flix-tech,项目名称:RevPy,代码行数:9,代码来源:lp_solve.py

示例14: mass

# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import value [as 别名]
def mass(self, value):
        self.data['mass'] = value 
开发者ID:bjodah,项目名称:chempy,代码行数:4,代码来源:chemistry.py

示例15: composition_violation

# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import value [as 别名]
def composition_violation(self, substances, composition_keys=None):
        """ Net amount of constituent produced

        If composition keys correspond to conserved entities e.g. atoms
        in chemical reactions, this function should return a list of zeros.

        Parameters
        ----------
        substances : dict
        composition_keys : iterable of str, ``None`` or ``True``
            When ``None`` or True: composition keys are taken from substances.
            When ``True`` the keys are also return as an extra return value

        Returns
        -------
        - If ``composition_keys == True``: a tuple: (violations, composition_keys)
        - Otherwise: violations (list of coefficients)

        """
        keys, values = zip(*substances.items())
        ret_comp_keys = composition_keys is True
        if composition_keys in (None, True):
            composition_keys = Substance.composition_keys(values)
        net = [0]*len(composition_keys)
        for substance, coeff in zip(values, self.net_stoich(keys)):
            for idx, key in enumerate(composition_keys):
                net[idx] += substance.composition.get(key, 0) * coeff
        if ret_comp_keys:
            return net, composition_keys
        else:
            return net 
开发者ID:bjodah,项目名称:chempy,代码行数:33,代码来源:chemistry.py


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