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


Python optimize.linprog函数代码示例

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


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

示例1: test_issue_6139

    def test_issue_6139(self):
        # Linprog(method='simplex') fails to find a basic feasible solution
        # if phase 1 pseudo-objective function is outside the provided tol.
        # https://github.com/scipy/scipy/issues/6139

        # Note: This is not strictly a bug as the default tolerance determines
        # if a result is "close enough" to zero and should not be expected
        # to work for all cases.

        c = np.array([1, 1, 1])
        A_eq = np.array([[1., 0., 0.], [-1000., 0., - 1000.]])
        b_eq = np.array([5.00000000e+00, -1.00000000e+04])
        A_ub = -np.array([[0., 1000000., 1010000.]])
        b_ub = -np.array([10000000.])
        bounds = (None, None)

        low_tol = 1e-20
        res = linprog(
            c, A_ub, b_ub, A_eq, b_eq, method=self.method,
            bounds=bounds, options={'tol': low_tol}
            )
        _assert_unable_to_find_basic_feasible_sol(res)

        high_tol = 1e-9
        res2 = linprog(
            c, A_ub, b_ub, A_eq, b_eq, method=self.method,
            bounds=bounds, options={'tol': high_tol}
            )

        # The result should be valid given a higher tolerance.
        _assert_success(
            res2, desired_fun=14.95, desired_x=np.array([5, 4.95, 5])
        )
开发者ID:BranYang,项目名称:scipy,代码行数:33,代码来源:test_linprog.py

示例2: test_simple_bounds

 def test_simple_bounds(self):
     res = linprog([1, 2], bounds=(1, 2),
                   method=self.method, options=self.options)
     _assert_success(res, desired_x=[1, 1])
     res = linprog([1, 2], bounds=[(1, 2), (1, 2)],
                   method=self.method, options=self.options)
     _assert_success(res, desired_x=[1, 1])
开发者ID:aerval,项目名称:scipy,代码行数:7,代码来源:test_linprog.py

示例3: GenerateWeights

 def GenerateWeights(self):
     restrictions_right_side = [[0 for _ in range(self.n)] for __ in range(self.n * (self.n - 1))]
     restrictions_left_side = [0 for _ in range(self.n * (self.n - 1))]
     equality_constraint_left = [[1 for _ in range(self.n)]]
     equality_constraint_right = [1.]
     variable_boundaries = tuple([(0, 1) for _ in range(self.n)])
     counter = 0
     for i in range(self.n - 1):
         for j in range(i + 1, self.n):
             restrictions_right_side[counter][i] = -1
             restrictions_right_side[counter][j] = self.matrix[i][j].low
             restrictions_right_side[counter + self.n * (self.n - 1) / 2][i] = 1
             restrictions_right_side[counter + self.n * (self.n - 1) / 2][j] = -self.matrix[i][j].high
             counter += 1
     weights = []
     for i in range(self.n):
         coefficients = [0 for _ in range(self.n)]
         coefficients[i] = 1
         lower_bound = linprog(c=coefficients, A_ub=restrictions_right_side, b_ub=restrictions_left_side,
                               A_eq=equality_constraint_left, b_eq=equality_constraint_right,
                               bounds=variable_boundaries)
         lower_bound = lower_bound.x[i] / sum(lower_bound.x)
         coefficients[i] = -1
         upper_bound = linprog(c=coefficients, A_ub=restrictions_right_side, b_ub=restrictions_left_side,
                               A_eq=equality_constraint_left, b_eq=equality_constraint_right,
                               bounds=variable_boundaries)
         upper_bound = upper_bound.x[i] / sum(upper_bound.x)
         weights.append(IntervalNumber(lower_bound, upper_bound))
     return FuzzyWeights(self.n, weights)
开发者ID:Lolmarty,项目名称:PRISLab2,代码行数:29,代码来源:main.py

示例4: test_bug_8662

    def test_bug_8662(self):
        # scipy.linprog returns incorrect optimal result for constraints using
        # default bounds, but, correct if boundary condition as constraint.
        # https://github.com/scipy/scipy/issues/8662
        c = [-10, 10, 6, 3]
        A = [
            [8, -8, -4, 6],
            [-8, 8, 4, -6],
            [-4, 4, 8, -4],
            [3, -3, -3, -10]
        ]
        b = [9, -9, -9, -4]
        bounds = [(0, None), (0, None), (0, None), (0, None)]
        desired_fun = 36.0000000000

        res1 = linprog(c, A, b, bounds=bounds,
                       method=self.method, options=self.options)

        # Set boundary condition as a constraint
        A.append([0, 0, -1, 0])
        b.append(0)
        bounds[2] = (None, None)

        res2 = linprog(c, A, b, bounds=bounds, method=self.method,
                       options=self.options)
        rtol = 1e-5
        _assert_success(res1, desired_fun=desired_fun, rtol=rtol)
        _assert_success(res2, desired_fun=desired_fun, rtol=rtol)
开发者ID:BranYang,项目名称:scipy,代码行数:28,代码来源:test_linprog.py

示例5: test_network_flow_limited_capacity

    def test_network_flow_limited_capacity(self):
        # A network flow problem with supply and demand at nodes
        # and with costs and capacities along directed edges.
        # http://blog.sommer-forst.de/2013/04/10/
        cost = [2, 2, 1, 3, 1]
        bounds = [
            [0, 4],
            [0, 2],
            [0, 2],
            [0, 3],
            [0, 5]]
        n, p = -1, 1
        A_eq = [
            [n, n, 0, 0, 0],
            [p, 0, n, n, 0],
            [0, p, p, 0, n],
            [0, 0, 0, p, p]]
        b_eq = [-4, 0, 0, 4]

        if self.method == "simplex":
            # Including the callback here ensures the solution can be
            # calculated correctly, even when phase 1 terminated
            # with some of the artificial variables as pivots
            # (i.e. basis[:m] contains elements corresponding to
            # the artificial variables)
            res = linprog(c=cost, A_eq=A_eq, b_eq=b_eq, bounds=bounds,
                          method=self.method, options=self.options,
                          callback=lambda x, **kwargs: None)
        else:
            with suppress_warnings() as sup:
                sup.filter(RuntimeWarning, "scipy.linalg.solve\nIll...")
                sup.filter(OptimizeWarning, "A_eq does not appear...")
                res = linprog(c=cost, A_eq=A_eq, b_eq=b_eq, bounds=bounds,
                              method=self.method, options=self.options)
        _assert_success(res, desired_fun=14)
开发者ID:aerval,项目名称:scipy,代码行数:35,代码来源:test_linprog.py

示例6: main

def main():
	cons = []
	rhs = []
	
	makeTitle()
	print("ALWAYS PUT X -> Y")
	print("Enter Objective Function Coefficient (Seperated By Spaces): ")
	obj = [float(x) for x in input().split()]
	
	dir = input("Maximize[1] or Minimize[2]\n")
	if dir == "1":
		for i in range(len(obj)):
			obj[i] = obj[i]*-1
	
	nCons = int(input("Enter the number of upper-bound constraints: \n"))
	
	for i in range(nCons):
		print("Enter Constraint Coefficients[%d]:" %(i + 1))
		cons.append([float(y) for y in input().split()])
		print("Enter RHS [%d]:" %(i + 1))
		rhs += [float(x) for x in input().split()]
		
	if input("Lower Bounds: Y/N\n") == "Y":
		xmin = float(input("Enter lower bound value: \n"))
		res = linprog(obj, A_ub=cons, b_ub=rhs, bounds=((xmin, None), (None, None)))
	else:	
		res = linprog(obj, A_ub=cons, b_ub=rhs)
		
	print(res)
开发者ID:Babesalad,项目名称:Python-Stuff,代码行数:29,代码来源:LPSimplex.py

示例7: q1

def q1():
    c = [3,2,5]
    b = [-5, -2, -3]
    A = [[-1,0,1],
         [2,-1,1],
         [-2,-1,-2],
         ]
    print linprog(c, A_ub=A, b_ub=b)
开发者ID:wlnirvana,项目名称:mooc,代码行数:8,代码来源:quiz1.py

示例8: q1

def q1():
    c = [-10,-2,-4,-8]
    b = [10,5,4]
    A = [[1,1,-5,6],
         [1,0,1,-1],
         [1,-1,-2,1],
         ]
    print linprog(c, A_ub=A, b_ub=b)
开发者ID:wlnirvana,项目名称:mooc,代码行数:8,代码来源:quiz3.py

示例9: test_linprog_cyclic_bland

def test_linprog_cyclic_bland():
    # Test the effect of Bland's rule on a cycling problem
    c = np.array([-10, 57, 9, 24.])
    A_ub = np.array([[0.5, -5.5, -2.5, 9],
                     [0.5, -1.5, -0.5, 1],
                     [1, 0, 0, 0]])
    b_ub = [0, 0, 1]
    res = linprog(c, A_ub=A_ub, b_ub=b_ub, options=dict(maxiter=100))
    assert_(not res.success)
    res = linprog(c, A_ub=A_ub, b_ub=b_ub,
                  options=dict(maxiter=100, bland=True,))
    _assert_success(res, desired_x=[1, 0, 1, 0])
开发者ID:ChadFulton,项目名称:scipy,代码行数:12,代码来源:test_linprog.py

示例10: global_weights

def global_weights(w, wc):
    w_glob = [0] * len(w[0])
    for i in range(0, len(w[0])):
        w_glob[i] = [0] * 2
        cl = [w[k][i][0] for k in range(0, len(wc))]
        cu = [-w[k][i][1] for k in range(0, len(wc))]
        wcl = [wc[k][0] for k in range(0, len(wc))]
        wcu = [wc[k][1] for k in range(0, len(wc))]
        x = linprog(c=cl, A_eq=[[1] * len(wc)], b_eq=[1], bounds=tuple([(wcl[i], wcu[i]) for i in range(0, len(wc))]))
        y = linprog(c=cu, A_eq=[[1] * len(wc)], b_eq=[1], bounds=tuple([(wcl[i], wcu[i]) for i in range(0, len(wc))]))
        w_glob[i][0] = x.fun
        w_glob[i][1] = -y.fun
    return w_glob
开发者ID:Alexander-Zipa,项目名称:Hierarchial-Systems,代码行数:13,代码来源:glob.py

示例11: test_enzo_example_c_with_infeasibility

 def test_enzo_example_c_with_infeasibility(self):
     # rescued from https://github.com/scipy/scipy/pull/218
     m = 50
     c = -np.ones(m)
     tmp = 2 * np.pi * np.arange(m) / (m + 1)
     A_eq = np.vstack((np.cos(tmp) - 1, np.sin(tmp)))
     b_eq = [1, 1]
     if self.method == "simplex":
         res = linprog(c=c, A_eq=A_eq, b_eq=b_eq,
                       method=self.method, options=self.options)
     else:
         res = linprog(c=c, A_eq=A_eq, b_eq=b_eq, method=self.method,
                       options={"presolve": False})
     _assert_infeasible(res)
开发者ID:aerval,项目名称:scipy,代码行数:14,代码来源:test_linprog.py

示例12: q3

def q3():
    """ max     5y_1 + 2y_2 + 3y_3
        s.t.    y1 - 2y_2 + 2y_3 <= 3
                y2 + y3 <= 2
                -y1 - y2 + 2y_3 <= 5
    """
    b = [3,2,5]
    c = [-5, -2, -3]
    A = [[-1,0,1],
         [2,-1,1],
         [-2,-1,-2],
         ]
    A = np.array(A)
    A = (-A).T
    print linprog(c, A_ub=A, b_ub=b)
开发者ID:wlnirvana,项目名称:mooc,代码行数:15,代码来源:quiz1.py

示例13: test_bounds_second_form_unbounded_above

def test_bounds_second_form_unbounded_above():
    c = np.array([1.0])
    A_eq = np.array([[1.0]])
    b_eq = np.array([3.0])
    bounds = (1.0, None)
    res = linprog(c, A_eq=A_eq, b_eq=b_eq, bounds=bounds)
    _assert_success(res, desired_fun=3, desired_x=[3])
开发者ID:1641731459,项目名称:scipy,代码行数:7,代码来源:test_linprog.py

示例14: test_negative_variable

    def test_negative_variable(self):
        # Test linprog with a problem with one unbounded variable and
        # another with a negative lower bound.
        c = np.array([-1,4])*-1  # maximize

        A_ub = [[-3,1],
                [1,2]]

        b_ub = [6,4]

        x0_bounds = (-np.inf,np.inf)
        x1_bounds = (-3,np.inf)

        res = linprog(c,A_ub=A_ub,b_ub=b_ub,bounds=(x0_bounds,x1_bounds))

        assert_(res.status == 0,
                "Test of linprog with negative variable failed.  "
                "Expected status = 0, got %d." % res.status)

        assert_allclose(-res.fun,80/7,err_msg="Test of linprog with negative "
                                              "variable converged but yielded "
                                              "unexpected result.")

        assert_array_almost_equal(res.x,[-8/7,18/7],
                                  err_msg="Test of linprog with negative "
                                          "variable converged but yielded "
                                          "unexpected result")
开发者ID:jabooth,项目名称:scipy,代码行数:27,代码来源:test_linprog.py

示例15: optimize

    def optimize(self, method="simplex", verbosity=False, **kwargs):
        """Run the linprog function on the problem. Returns None."""
        c = np.array([self.objective.get(name, 0) for name in self._variables])
        if self.direction == "max":
            c *= -1

        bounds = list(six.itervalues(self.bounds))
        solution = linprog(
            c,
            self.A,
            self.upper_bounds,
            bounds=bounds,
            method=method,
            options={"maxiter": 10000, "disp": verbosity},
            **kwargs
        )
        self._solution = solution
        self._status = solution.status
        if SCIPY_STATUS[self._status] == interface.OPTIMAL:
            self._var_primals = solution.x
            self._slacks = solution.slack
        else:
            self._var_primals = None
            self._slacks = None

        self._f = solution.fun
开发者ID:KristianJensen,项目名称:optlang,代码行数:26,代码来源:scipy_interface.py


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