當前位置: 首頁>>代碼示例>>Python>>正文


Python pulp.LpMinimize方法代碼示例

本文整理匯總了Python中pulp.LpMinimize方法的典型用法代碼示例。如果您正苦於以下問題:Python pulp.LpMinimize方法的具體用法?Python pulp.LpMinimize怎麽用?Python pulp.LpMinimize使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在pulp的用法示例。


在下文中一共展示了pulp.LpMinimize方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: label_prop

# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import LpMinimize [as 別名]
def label_prop(C, nt, Dct, lp="linear"):
    
#Inputs:
#  C      :    Number of share classes between src and tar
#  nt     :    Number of target domain samples
#  Dct    :    All d_ct in matrix form, nt * C
#  lp     :    Type of linear programming: linear (default) | binary
#Outputs:
#  Mcj    :    all M_ct in matrix form, m * C
    
    Dct = abs(Dct)
    model = pulp.LpProblem("Cost minimising problem", pulp.LpMinimize)
    Mcj = pulp.LpVariable.dicts("Probability",
                                ((i, j) for i in range(C) for j in range(nt)),
                                lowBound=0,
                                upBound=1,
                                cat='Continuous')
    
    # Objective Function
    model += (
    pulp.lpSum([Dct[j, i]*Mcj[(i, j)] for i in range(C) for j in range(nt)])
    )
    
    # Constraints
    for j in range(nt):
        model += pulp.lpSum([Mcj[(i, j)] for i in range(C)]) == 1
    for i in range(C):
        model += pulp.lpSum([Mcj[(i, j)] for j in range(nt)]) >= 1
    
    # Solve our problem
    model.solve()
    pulp.LpStatus[model.status]
    Output = [[Mcj[i, j].varValue for i in range(C)] for j in range(nt)]
    
    return np.array(Output) 
開發者ID:jindongwang,項目名稱:transferlearning,代碼行數:37,代碼來源:label_prop_v2.py

示例2: __init__

# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import LpMinimize [as 別名]
def __init__(self, input_data, input_params):
        self.input_data = input_data
        self.input_params = input_params
        self.model = pulp.LpProblem(name='prod_planning', sense=pulp.LpMinimize)
        self._create_decision_variables()
        self._create_main_constraints()
        self._set_objective_function()

    # ================== Decision variables ================== 
開發者ID:ekhoda,項目名稱:optimization-tutorial,代碼行數:11,代碼來源:optimization_model_pulp.py

示例3: create_model

# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import LpMinimize [as 別名]
def create_model(self):
        def distances(assignment):
            return l2_distance(self.data[assignment[0]], self.centroids[assignment[1]])

        clusters = list(range(self.k))
        assignments = [(i, j)for i in range(self.n) for j in range(self.k)]

        # outflow variables for data nodes
        self.y = pulp.LpVariable.dicts('data-to-cluster assignments',
                                  assignments,
                                  lowBound=0,
                                  upBound=1,
                                  cat=pulp.LpInteger)

        # outflow variables for cluster nodes
        self.b = pulp.LpVariable.dicts('cluster outflows',
                                  clusters,
                                  lowBound=0,
                                  upBound=self.n-self.min_size,
                                  cat=pulp.LpContinuous)

        # create the model
        self.model = pulp.LpProblem("Model for assignment subproblem", pulp.LpMinimize)

        # objective function
        self.model += pulp.lpSum(distances(assignment) * self.y[assignment] for assignment in assignments)

        # flow balance constraints for data nodes
        for i in range(self.n):
            self.model += pulp.lpSum(self.y[(i, j)] for j in range(self.k)) == 1

        # flow balance constraints for cluster nodes
        for j in range(self.k):
            self.model += pulp.lpSum(self.y[(i, j)] for i in range(self.n)) - self.min_size == self.b[j]

        # flow balance constraint for the sink node
        self.model += pulp.lpSum(self.b[j] for j in range(self.k)) == self.n - (self.k * self.min_size) 
開發者ID:Behrouz-Babaki,項目名稱:MinSizeKmeans,代碼行數:39,代碼來源:run_mskmeans.py

示例4: create_model

# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import LpMinimize [as 別名]
def create_model(self):
        def distances(assignment):
            return l2_distance(self.data[assignment[0]], self.centroids[assignment[1]])

        clusters = list(range(self.k))
        assignments = [(i, j)for i in range(self.n) for j in range(self.k)]

        # outflow variables for data nodes
        self.y = pulp.LpVariable.dicts('data-to-cluster assignments',
                                  assignments,
                                  lowBound=0,
                                  upBound=1,
                                  cat=pulp.LpInteger)

        # outflow variables for cluster nodes
        self.b = pulp.LpVariable.dicts('cluster outflows',
                                  clusters,
                                  lowBound=0,
                                  upBound=self.n-self.min_size,
                                  cat=pulp.LpContinuous)

        # create the model
        self.model = pulp.LpProblem("Model for assignment subproblem", pulp.LpMinimize)

        # objective function
        self.model += pulp.lpSum([distances(assignment) * self.y[assignment] for assignment in assignments])

        # flow balance constraints for data nodes
        for i in range(self.n):
            self.model += pulp.lpSum(self.y[(i, j)] for j in range(self.k)) == 1

        # flow balance constraints for cluster nodes
        for j in range(self.k):
            self.model += pulp.lpSum(self.y[(i, j)] for i in range(self.n)) - self.min_size == self.b[j]
            
        # capacity constraint on outflow of cluster nodes
        for j in range(self.k):
            self.model += self.b[j] <= self.max_size - self.min_size 

        # flow balance constraint for the sink node
        self.model += pulp.lpSum(self.b[j] for j in range(self.k)) == self.n - (self.k * self.min_size) 
開發者ID:Behrouz-Babaki,項目名稱:MinSizeKmeans,代碼行數:43,代碼來源:minmax_kmeans.py

示例5: create_model

# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import LpMinimize [as 別名]
def create_model(self):
        def distances(assignment):
            return l2_distance(self.data[assignment[0]], self.centroids[assignment[1]])

        assignments = [(i, j) for i in range(self.n) for j in range(self.k)]

        # assignment variables
        self.y = pulp.LpVariable.dicts('data-to-cluster assignments',
                                  assignments,
                                  lowBound=0,
                                  upBound=1,
                                  cat=pulp.LpInteger)

        # create the model
        self.model = pulp.LpProblem("Model for assignment subproblem", pulp.LpMinimize)

        # objective function
        self.model += pulp.lpSum([distances(assignment) * self.weights[assignment[0]] * self.y[assignment] for assignment in assignments]), 'Objective Function - sum weighted squared distances to assigned centroid'
        # this is also weighted, otherwise the weighted centroid computation don't make sense.

        # constraints on the total weights of clusters
        for j in range(self.k):
            self.model += pulp.lpSum([self.weights[i] * self.y[(i, j)] for i in range(self.n)]) >= self.min_weight, "minimum weight for cluster {}".format(j)
            self.model += pulp.lpSum([self.weights[i] * self.y[(i, j)] for i in range(self.n)]) <= self.max_weight, "maximum weight for cluster {}".format(j)

        # make sure each point is assigned at least once, and only once
        for i in range(self.n):
            self.model += pulp.lpSum([self.y[(i, j)] for j in range(self.k)]) == 1, "must assign point {}".format(i) 
開發者ID:Behrouz-Babaki,項目名稱:MinSizeKmeans,代碼行數:30,代碼來源:weighted_mm_kmeans.py

示例6: _gclp

# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import LpMinimize [as 別名]
def _gclp(self, composition={}, mus={}, phases=[]):
        if not qmpy.FOUND_PULP:
            raise Exception('Cannot do GCLP without installing PuLP and an LP',
                    'solver')
        prob = pulp.LpProblem('GibbsEnergyMin', pulp.LpMinimize)
        phase_vars = pulp.LpVariable.dicts('lib', phases, 0.0)
        prob += pulp.lpSum([ (p.energy -
            sum([ p.unit_comp.get(elt,0)*mu
                for elt, mu in mus.items() ])) * phase_vars[p]
            for p in phases]),\
                    "Free Energy"
        for elt, constraint in composition.items():
            prob += pulp.lpSum([
                p.unit_comp.get(elt,0)*phase_vars[p]
                for p in phases ]) == float(constraint),\
                        'Conservation of '+elt
        ##[vh]
        ##print prob
        if pulp.GUROBI().available():
            prob.solve(pulp.GUROBI(msg=False))
        elif pulp.COIN_CMD().available():
            prob.solve(pulp.COIN_CMD())
        else:
            prob.solve()

        phase_comp = dict([ (p, phase_vars[p].varValue)
            for p in phases if phase_vars[p].varValue > 1e-5])
        
        energy = sum( p.energy*amt for p, amt in phase_comp.items() )
        energy -= sum([ a*composition.get(e, 0) for e,a in mus.items()])
        return energy, phase_comp 
開發者ID:wolverton-research-group,項目名稱:qmpy,代碼行數:33,代碼來源:space.py

示例7: get_minima

# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import LpMinimize [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

示例8: get_objective_type

# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import LpMinimize [as 別名]
def get_objective_type(self):
        ''' Returns pulp.LpMinimize - we minimize objective function in case
            of output-oriented multiplier model.

            Returns:
                pulp.LpMinimize.
        '''
        return pulp.LpMinimize 
開發者ID:araith,項目名稱:pyDEA,代碼行數:10,代碼來源:multiplier_model.py

示例9: get_objective_type

# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import LpMinimize [as 別名]
def get_objective_type(self):
        ''' Returns pulp.LpMinimize - we minimize objective function in case
            of input-oriented envelopment model.

            Returns:
                pulp.LpMaximize: type of objective function.
        '''
        return pulp.LpMinimize 
開發者ID:araith,項目名稱:pyDEA,代碼行數:10,代碼來源:envelopment_model.py

示例10: solve

# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import LpMinimize [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

示例11: _solve_balancing_ilp_pulp

# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import LpMinimize [as 別名]
def _solve_balancing_ilp_pulp(A):
    import pulp
    x = [pulp.LpVariable('x%d' % i, lowBound=1, cat='Integer') for i in range(A.shape[1])]
    prob = pulp.LpProblem("chempy balancing problem", pulp.LpMinimize)
    prob += reduce(add, x)
    for expr in [pulp.lpSum([x[i]*e for i, e in enumerate(row)]) for row in A.tolist()]:
        prob += expr == 0
    prob.solve()
    return [pulp.value(_) for _ in x] 
開發者ID:bjodah,項目名稱:chempy,代碼行數:11,代碼來源:chemistry.py

示例12: __min_one_norm

# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import LpMinimize [as 別名]
def __min_one_norm(B, initial_seed, seed):
    weight_initial = 1 / float(len(initial_seed))
    weight_later_added = weight_initial / float(0.5)
    difference = len(seed) - len(initial_seed)
    [r, c] = B.shape
    prob = pulp.LpProblem("Minimum one norm", pulp.LpMinimize)
    indices_y = range(0, r)
    y = pulp.LpVariable.dicts("y_s", indices_y, 0)
    indices_x = range(0, c)
    x = pulp.LpVariable.dicts("x_s", indices_x)

    f = dict(zip(indices_y, [1.0] * r))

    prob += pulp.lpSum(f[i] * y[i] for i in indices_y)  # objective function

    prob += pulp.lpSum(y[s] for s in initial_seed) >= 1

    prob += pulp.lpSum(y[r] for r in seed) >= 1 + weight_later_added * difference

    for j in range(r):
        temp = dict(zip(indices_x, list(B[j, :])))
        prob += pulp.lpSum(y[j] + (temp[k] * x[k] for k in indices_x)) == 0

    prob.solve()

    result = []
    for var in indices_y:
        result.append(y[var].value())

    return result 
開發者ID:GiulioRossetti,項目名稱:cdlib,代碼行數:32,代碼來源:LEMON.py

示例13: make_into_lp_problem

# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import LpMinimize [as 別名]
def make_into_lp_problem(good_for, N, add_noise=False):
    """
    Helper function for solve_with_lp_and_reduce()

    N --- number of isoform sequences
    good_for --- dict of <isoform_index> --> list of matched paths index
    """
    prob = LpProblem("The Whiskas Problem",LpMinimize)

    # each good_for is (isoform_index, [list of matched paths index])
    # ex: (0, [1,2,4])
    # ex: (3, [2,5])
    used_paths = []
    for t_i, p_i_s in good_for:
        used_paths += p_i_s
    used_paths = list(set(used_paths))

    variables = [LpVariable(str(i),0,1,LpInteger) for i in used_paths]
    #variables = [LpVariable(str(i),0,1,LpInteger) for i in xrange(N)]

    # objective is to minimize sum_{Xi}
    prob += sum(v for v in variables)

    already_seen = set()
    # constraints are for each isoform, expressed as c_i * x_i >= 1
    # where c_i = 1 if x_i is matched for the isoform
    # ex: (0, [1,2,4]) becomes t_0 = x_1 + x_2 + x_4 >= 1
    for t_i, p_i_s in good_for:
        #c_i_s = [1 if i in p_i_s else 0 for i in xrange(N)]
        #prob += sum(variables[i]*(1 if i in p_i_s else 0) for i in xrange(N)) >= 1
        p_i_s.sort()
        pattern = ",".join(map(str,p_i_s))
        #print >> sys.stderr, t_i, p_i_s, pattern
        if pattern not in already_seen:
            if add_noise:
                prob += sum(variables[i]*(1+random.random() if p in p_i_s else 0) for i,p in enumerate(used_paths)) >= 1
            else:
                prob += sum(variables[i]*(1 if p in p_i_s else 0) for i,p in enumerate(used_paths)) >= 1
        already_seen.add(pattern)
    prob.writeLP('cogent.lp')
    return prob 
開發者ID:Magdoll,項目名稱:Cogent,代碼行數:43,代碼來源:process_path.py

示例14: word_mover_distance_probspec

# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import LpMinimize [as 別名]
def word_mover_distance_probspec(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, and return the LP problem class.

    Using methods of linear programming, supported by PuLP, calculate the WMD between two lists of words. A word-embedding
    model has to be provided. The problem class is returned, containing all the information about the LP.

    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: a linear programming problem contains the solution
    :type first_sent_tokens: list
    :type second_sent_tokens: list
    :type wvmodel: gensim.models.keyedvectors.KeyedVectors
    :type distancefunc: function
    :type lpFile: str
    :rtype: pulp.LpProblem
    """
    all_tokens = list(set(first_sent_tokens+second_sent_tokens))
    wordvecs = {token: wvmodel[token] for token in all_tokens}

    first_sent_buckets = tokens_to_fracdict(first_sent_tokens)
    second_sent_buckets = tokens_to_fracdict(second_sent_tokens)

    T = pulp.LpVariable.dicts('T_matrix', list(product(all_tokens, all_tokens)), lowBound=0)

    prob = pulp.LpProblem('WMD', sense=pulp.LpMinimize)
    prob += pulp.lpSum([T[token1, token2]*distancefunc(wordvecs[token1], wordvecs[token2])
                        for token1, token2 in product(all_tokens, all_tokens)])
    for token2 in second_sent_buckets:
        prob += pulp.lpSum([T[token1, token2] for token1 in first_sent_buckets])==second_sent_buckets[token2]
    for token1 in first_sent_buckets:
        prob += pulp.lpSum([T[token1, token2] for token2 in second_sent_buckets])==first_sent_buckets[token1]

    if lpFile!=None:
        prob.writeLP(lpFile)

    prob.solve()

    return prob 
開發者ID:stephenhky,項目名稱:PyShortTextCategorization,代碼行數:45,代碼來源:wordmoverdist.py

示例15: create_lscp_model

# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import LpMinimize [as 別名]
def create_lscp_model(coverage_dict, model_file=None, delineator="$", ):
    """
    Creates a LSCP (Location set covering problem) using the provided coverage and
    parameters. Writes a .lp file which can be solved with Gurobi

    Church, R., & Murray, A. (2009). Coverage Business Site Selection, Location
    Analysis, and GIS (pp. 209-233). Hoboken, New Jersey: Wiley.

    :param coverage_dict: (dictionary) The coverage to use to generate the model
    :param model_file: (string) The model file to output
    :param delineator: (string) The character(s) to use to delineate the layer from the ids
    :return: (Pulp problem) The generated problem to solve
    """
    validate_coverage(coverage_dict, ["coverage"], ["binary"])
    if not isinstance(coverage_dict, dict):
        raise TypeError("coverage_dict is not a dictionary")
    if model_file and not (isinstance(model_file, str)):
        raise TypeError("model_file is not a string")
    if not isinstance(delineator, str):
        raise TypeError("delineator is not a string")
        # create the variables
    demand_vars = {}
    for demand_id in coverage_dict["demand"]:
        demand_vars[demand_id] = pulp.LpVariable("Y{}{}".format(delineator, demand_id), 0, 1, pulp.LpInteger)
    facility_vars = {}
    for facility_type in coverage_dict["facilities"]:
        facility_vars[facility_type] = {}
        for facility_id in coverage_dict["facilities"][facility_type]:
            facility_vars[facility_type][facility_id] = pulp.LpVariable(
                "{}{}{}".format(facility_type, delineator, facility_id), 0, 1, pulp.LpInteger)
    # create the problem
    prob = pulp.LpProblem("LSCP", pulp.LpMinimize)
    # Create objective, minimize number of facilities
    to_sum = []
    for facility_type in coverage_dict["facilities"]:
        for facility_id in coverage_dict["facilities"][facility_type]:
            to_sum.append(facility_vars[facility_type][facility_id])
    prob += pulp.lpSum(to_sum)
    # add coverage constraints
    for demand_id in coverage_dict["demand"]:
        to_sum = []
        for facility_type in coverage_dict["demand"][demand_id]["coverage"]:
            for facility_id in coverage_dict["demand"][demand_id]["coverage"][facility_type]:
                to_sum.append(facility_vars[facility_type][facility_id])
        # Hack to get model to "solve" when infeasible with GLPK.
        # Pulp will automatically add dummy variables when the sum is empty, since these are all the same name,
        # it seems that GLPK doesn't read the lp problem properly and fails
        if not to_sum:
            to_sum = [pulp.LpVariable("__dummy{}{}".format(delineator, demand_id), 0, 0, pulp.LpInteger)]
        prob += pulp.lpSum(to_sum) >= 1, "D{}".format(demand_id)
    if model_file:
        prob.writeLP(model_file)
    return prob 
開發者ID:apulverizer,項目名稱:pyspatialopt,代碼行數:55,代碼來源:covering.py


注:本文中的pulp.LpMinimize方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。