Exemple #1
0
    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)
Exemple #2
0
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)
Exemple #3
0
    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)
Exemple #4
0
 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])
Exemple #5
0
    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])
        )
Exemple #6
0
 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)
Exemple #7
0
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)
Exemple #8
0
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)
Exemple #9
0
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])
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
Exemple #11
0
 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)
Exemple #12
0
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)
Exemple #13
0
    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")
Exemple #14
0
    def test_nontrivial_problem(self):
        # Test linprog for a problem involving all constraint types,
        # negative resource limits, and rounding issues.
        c = [-1,8,4,-6]

        A_ub = [[-7,-7,6,9],
                [1,-1,-3,0],
                [10,-10,-7,7],
                [6,-1,3,4]]
        b_ub = [-3,6,-6,6]

        A_eq = [[-10,1,1,-8]]
        b_eq = [-4]

        res = linprog(c,A_ub=A_ub,b_ub=b_ub,A_eq=A_eq,b_eq=b_eq)

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

        assert_almost_equal(res.fun,7083/1391,9,
                "Test of linprog with nontrivial problem converged but yielded "
                "unexpected result (%f)" % res.fun)

        assert_array_almost_equal(res.x,[101/1391,1462/1391,0,752/1391],
                                  err_msg="Test of linprog with nontrivial "
                                          "problem converged but yielded "
                                          "unexpected result.")
    def solve(self):
        """Solves linear program.

        :return: solution vector
        """
        lp_solution = linprog(
            self.linear_program.objective_function_coefficients,
            A_eq=self.linear_program.equality_constraint_matrix or None,
            b_eq=self.linear_program.equality_constraint_vector or None,
            A_ub=self._make_upper_constraint_matrix() or None,
            b_ub=self._make_upper_constraint_vector() or None,
            bounds=self.linear_program.bounds,
            options={"disp": False})

        self._check_errors(lp_solution)

        # Naive implementation of getting integer result
        # from a linear programming algorithm, MIP
        # (mixed integer programming) should be considered
        # instead, but it may have a lot of problems (solution
        # of such equations is NP-hard in some cases),
        # for our practical purposes it's enough to round
        # the number down, in this case we may get `n` megabytes
        # unallocated, where n is len(spaces) * len(disks)
        solution_vector = utils.round_vector_down(lp_solution.x)

        return solution_vector
Exemple #16
0
def convex(B0, c0, B, c, alpha, x):
    J0 = [index for index in xrange(len(x)) if x[index] == 0.0]
    g = array([function_g_x(x, B_i, c_i, alpha_i) for B_i, c_i, alpha_i in zip(B, c, alpha)])
    print list(x), "- начальный план" if (g <= 0).all() else exit()  # проверим исходный план
    print "Значение целевой функции по начальному плану f(x) =", function_g_x(x, B0, c0, 0.0)
    print "Проверка оптимальности начального плана..."
    I0 = array([index for index in xrange(len(g)) if g[index] == 0.0])
    df = function_df_dx(x, B0, c0)
    dg_I0 = array([function_df_dx(x, B[i], c[i]) for i in I0])
    # границы
    d_m = zeros(len(x))  # dm
    d_m[delete(arange(len(x)), J0)] = -1
    l = opt.linprog(df, A_ub=dg_I0, b_ub=zeros(len(dg_I0)), bounds=zip(d_m, ones(len(x))))
    f = l.fun
    l = l.x  # l0
    print "План не оптимален. Значение dg/dx", f if f < 0 else exit()
    a = 1  # подберём число А для неравенства
    delta_x = zeros(len(x)) - x
    k = df.dot(delta_x)
    a0 = -f / k
    if k < 0 < a0:
        a = a0 / 2
    if k > 0 and a0 > 0:
        a = a0 + 1
    t = 2.0  # подберём число t для неравенства
    while True:
        x_t = x + t * (l + a * delta_x)  # новый план
        if (array([function_g_x(x_t, B_i, c_i, alpha_i) for B_i, c_i, alpha_i in zip(B, c, alpha)]) <= 0.0).all() and (x_t >= 0.0).all():
            break
        t /= 2.0
    print "Новый план  x_t =", list(x_t)
    print "Новое значение целевой функции f(x_t) =", function_g_x(x_t, B0, c0, 0.0)  # less then f(x*)
    print "Улучшение плана: ", round(100 - function_g_x(x_t, B0, c0, 0.0) / function_g_x(x, B0, c0, 0.0) * 100, 2), "%"
def vc_lp_relax(G):
    n = max(G.nodes())
    m = len(G.edges())

    # For the objective function, add a variable with
    #   coefficient 1 in the objective function for
    #   each node and create a slack variable with
    #   coefficient 0 in the objective function for
    #   each constraint (one for each edge)
    cvar = [1 for i in range(n)]
    cslack = [0 for i in range(m)]
    c = cvar + cslack

    # Add the constraints. In this case, xj+xi>=1 for
    #   each edge (i,j) in E
    b = [1 for i in range(m)]

    # Construct the matrix of constrains. Slack variables
    #   with coefficient -1 are added to make the constraints
    #   xj + xi >= 1
    A = []
    j = 0
    for edge in G.edges():
        const = [0 for i in range(n+m)]
        idx1 = edge[0] - 1
        idx2 = edge[1] - 1
        const[idx1] = 1
        const[idx2] = 1
        const[n+j] = -1
        A.append(const)
        j+=1
    # Run the linear program to find the lp relaxation solution,
    #   this is the lower bound for the ILP
    res = opt.linprog(c,A_eq=A,b_eq=b,bounds=(0,1))
    return res.fun
Exemple #18
0
def price_lp():
    L = pow(up, T)*S0-K # Upper bound for J
    # Look at PDF for definition of A, B, U and c
    A = get_A() 
    B = get_B() 
    U = get_U() 
    c = np.ones_like(U)
    
    res = linprog(c, 
              A_ub=np.vstack(A-np.eye(T*T)), 
              b_ub=np.zeros_like(U),
              A_eq=B,
              b_eq=L*np.ones(B.shape[0]),
              bounds = list(zip(U, np.ones_like(U)*L)),
              options={"disp": True})

    if res.status != 0: 
        print("Optimization failed, try a lower value for T")
        exit()

    J = res.x
    U.shape = J.shape = (T, T)
    control = (J - U < 1e-8)
    for i, slate in generate_slates(T):
        St = map(lambda k: pow(down,k)*pow(up,i-k), slate)
        St = np.array(list(St))*S0
        yield np.array([i*np.ones_like(St), St, J[i, :i+1], control[i, :i+1]])
Exemple #19
0
 def test_empty_constraint_1(self):
     # detected in presolve?
     res = linprog([-1, 1, -1, 1],
                   bounds=[(0, np.inf), (-np.inf, 0), (-1, 1), (-1, 1)],
                   method=self.method, options=self.options)
     _assert_unbounded(res)
     assert_equal(res.nit, 0)
Exemple #20
0
def test_network_flow_limited_capacity():
    # 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]
    # 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,
                  callback=lambda x, **kwargs: None)
    _assert_success(res, desired_fun=14)
    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
Exemple #22
0
    def test_bug_6690(self):
        # https://github.com/scipy/scipy/issues/6690
        A_eq = np.array([[0., 0., 0., 0.93, 0., 0.65, 0., 0., 0.83, 0.]])
        b_eq = np.array([0.9626])
        A_ub = np.array([[0., 0., 0., 1.18, 0., 0., 0., -0.2, 0.,
                          -0.22],
                         [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
                         [0., 0., 0., 0.43, 0., 0., 0., 0., 0., 0.],
                         [0., -1.22, -0.25, 0., 0., 0., -2.06, 0., 0.,
                          1.37],
                         [0., 0., 0., 0., 0., 0., 0., -0.25, 0., 0.]])
        b_ub = np.array([0.615, 0., 0.172, -0.869, -0.022])
        bounds = np.array(
            [[-0.84, -0.97, 0.34, 0.4, -0.33, -0.74, 0.47, 0.09, -1.45, -0.73],
             [0.37, 0.02, 2.86, 0.86, 1.18, 0.5, 1.76, 0.17, 0.32, -0.15]]).T
        c = np.array([-1.64, 0.7, 1.8, -1.06, -1.16,
                      0.26, 2.13, 1.53, 0.66, 0.28])

        with suppress_warnings() as sup:
            sup.filter(RuntimeWarning, "scipy.linalg.solve\nIll...")
            sup.filter(OptimizeWarning, "Solving system with option...")
            sol = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq,
                          bounds=bounds, method=self.method,
                          options=self.options)
        _assert_success(sol, desired_fun=-1.191)
Exemple #23
0
    def test_bug_5400(self):
        # https://github.com/scipy/scipy/issues/5400
        bounds = [
            (0, None),
            (0, 100), (0, 100), (0, 100), (0, 100), (0, 100), (0, 100),
            (0, 900), (0, 900), (0, 900), (0, 900), (0, 900), (0, 900),
            (0, None), (0, None), (0, None), (0, None), (0, None), (0, None)]

        f = 1 / 9
        g = -1e4
        h = -3.1
        A_ub = np.array([
            [1, -2.99, 0, 0, -3, 0, 0, 0, -1, -1, 0, -1, -1, 1, 1, 0, 0, 0, 0],
            [1, 0, -2.9, h, 0, -3, 0, -1, 0, 0, -1, 0, -1, 0, 0, 1, 1, 0, 0],
            [1, 0, 0, h, 0, 0, -3, -1, -1, 0, -1, -1, 0, 0, 0, 0, 0, 1, 1],
            [0, 1.99, -1, -1, 0, 0, 0, -1, f, f, 0, 0, 0, g, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 2, -1, -1, 0, 0, 0, -1, f, f, 0, g, 0, 0, 0, 0],
            [0, -1, 1.9, 2.1, 0, 0, 0, f, -1, -1, 0, 0, 0, 0, 0, g, 0, 0, 0],
            [0, 0, 0, 0, -1, 2, -1, 0, 0, 0, f, -1, f, 0, 0, 0, g, 0, 0],
            [0, -1, -1, 2.1, 0, 0, 0, f, f, -1, 0, 0, 0, 0, 0, 0, 0, g, 0],
            [0, 0, 0, 0, -1, -1, 2, 0, 0, 0, f, f, -1, 0, 0, 0, 0, 0, g]])

        b_ub = np.array([0.0, 0, 0, 0, 0, 0, 0, 0, 0])
        c = np.array([-1.0, 1, 1, 1, 1, 1, 1, 1, 1,
                      1, 1, 1, 1, 0, 0, 0, 0, 0, 0])

        res = linprog(c, A_ub, b_ub, bounds=bounds,
                      method=self.method, options=self.options)
        _assert_success(res, desired_fun=-106.63507541835018)
Exemple #24
0
 def test_singleton_row_eq_2(self):
     c = [1, 1, 1, 2]
     A_eq = [[1, 0, 0, 0], [0, 2, 0, 0], [1, 0, 0, 0], [1, 1, 1, 1]]
     b_eq = [1, 2, 1, 4]
     res = linprog(c, A_eq=A_eq, b_eq=b_eq,
                   method=self.method, options=self.options)
     _assert_success(res, desired_fun=4)
Exemple #25
0
 def test_linprog_cyclic_bland(self):
     # 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]
     # "interior-point" will succeed, "simplex" will fail
     res = linprog(c, A_ub=A_ub, b_ub=b_ub, options=dict(maxiter=100),
                   method=self.method)
     if self.method == "simplex":
         assert_(not res.success)
         res = linprog(c, A_ub=A_ub, b_ub=b_ub,
                       options=dict(maxiter=100, bland=True,),
                       method=self.method)
     _assert_success(res, desired_x=[1, 0, 1, 0])
Exemple #26
0
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])
Exemple #27
0
 def test_large_problem(self):
     # Test linprog simplex with a rather large problem (400 variables,
     # 40 constraints) generated by https://gist.github.com/denis-bz/8647461
     A, b, c = lpgen_2d(20, 20)
     res = linprog(c, A_ub=A, b_ub=b,
                   method=self.method, options=self.options)
     _assert_success(res, desired_fun=-64.049494229)
def earth_movers_distance_pmf(x, y, distances=None):
    """
    Compute the Earth Mover's Distance between `p` and `q`.

    Parameters
    ----------
    p : np.ndarray
        The first pmf.
    q : np.ndarray
        The second pmf.
    distances : np.ndarray, None
        The cost of moving probability from p[i] to q[j]. If None,
        the cost is assumed to be i != j.

    Returns
    -------
    emd : float
        The Earth Mover's Distance.
    """
    n = len(x)

    if distances is None:
        # assume categorical distribution
        distances = categorical_distances(n)

    eye = np.eye(n)
    A = np.vstack([np.dstack([eye]*n).reshape(n, n**2), np.tile(eye, n)])

    b = np.concatenate([x, y], axis=0)

    c = distances.flatten()

    res = linprog(c, A_eq=A, b_eq=b, bounds=[0, None])

    return res.fun
Exemple #29
0
 def test_zero_row_4(self):
     A_ub = [[0, 0, 0], [1, 1, 1], [0, 0, 0]]
     b_ub = [0, 3, 0]
     c = [1, 2, 3]
     res = linprog(c=c, A_ub=A_ub, b_ub=b_ub,
                   method=self.method, options=self.options)
     _assert_success(res, desired_fun=0)
Exemple #30
0
 def test_unbounded_below_and_above(self):
     A = np.eye(3)
     b = np.array([1, 2, 3])
     c = np.ones(3)
     res = linprog(c, A_eq=A, b_eq=b, bounds=(-np.inf, np.inf),
                   method=self.method, options=self.options)
     _assert_success(res, desired_x=b, desired_fun=np.sum(b))
    a_pow = BEST_FIT_COEF_1
    b_pow = BEST_FIT_COEF_2  # b_pow is not used because the system is linear.
    n_bulbs = min(8, len(actuators.lights))
    c = [a_pow] * n_bulbs

    # Target for each sensor
    # Offsetting target by environmental contribution (Again, to get the form required by scipy.optimize.linprog)
    target_no_env = [target_illum[i] - E[i] for i in range(len(E))]
    target_no_env = np.negative(target_no_env)

    # Solve optimization program
    bounds = [(0.0, 1.0) for _ in range(n_bulbs)]

    res = linprog(c,
                  A_ub=A,
                  b_ub=target_no_env,
                  bounds=bounds,
                  method='interior-point',
                  options={"disp": False})

    # Note: if we use Simplex, tolerance  ("tol") is required.
    # res = linprog(c, A_ub=A, b_ub=target_no_env, bounds=bounds, method='simplex',
    #               options={"disp": False, "tol": 1e-11})

    print "{:<35} {:<25}".format("Optimization finished.",
                                 dt.now().strftime("%H:%M:%S.%f"))

    if res.success:
        d_opt = res.x
        d_opt = d_opt.tolist()
        actuators.set_dimming(d_opt, wait_time)
        bulbs_on = 0
Exemple #32
0
# Ограничение 7: сумма объемов внутреннего сбыта нефтепродуктов не превышают спрос
tmp = np.zeros((1, 2 * M + 2 * N))
for n in range(N):
    tmp[0, 2 * M + N + n] = 1
A = np.vstack([A, tmp])
b = np.hstack((b, q_petr_dom))

# Ограничение 8: объемы сбыта нефтепродуктов на экспорт не превышают спрос
tmp = np.zeros((1, 2 * M + 2 * N))
for n in range(N):
    tmp[0, 2 * M + n] = 1
A = np.vstack([A, tmp])
b = np.hstack((b, q_petr_exp))

#  Заполняем столбец p
for m in range(M):
    p[m] = (p_oil_exp - ndpi -
            exp_oil_tax) * r - cost_oil_prod[m] - cost_oil_tran
for m in range(M):
    p[M + m] = 0
for n in range(N):
    p[2 * M +
      n] = (p_petr_exp - exp_petr_tax) * r - cost_oil_ref - cost_petr_tran
for n in range(N):
    p[2 * M + N +
      n] = p_petr_dom * r - excise_petr - cost_oil_ref - cost_petr_tran

#res = linprog(-p, A_ub=A, b_ub=b, A_eq=Ae, b_eq=be)
res = linprog(-p, A_ub=A, b_ub=b)
print(res)
Exemple #33
0
def Num_Stab_Approx(X, Y, RM, penalty, normalize):
    '''
    This function implements the approximation methods mentioned in Judd et al. (2011)
    --------
    Arguments:
        X(2D numpy array): Matrix of dependent variables in a regression.
        Y(2D numpy array):Matrix of independent variables.
        RM(int): Regression (approximation) method, from 1 to 6. RLAD-DP & LAD-DP are not included, see notebook for reasoning.
        penalty(int): Regularisation parameter for a regularisation methods.
        normalize(int): Optional parameter to normalise the data or not. 1 or 0.

    ---------
    Outputs:
        B(2D numpy array): Matrix of the regression coefficients.

    '''
    
    # Step 1: Compute the dimensionality of the data
    ################################################

    T, n = X.shape
    N  = Y.shape[1]
    
    # Step 2: Normalize the data(or not)
    ####################################

    if ((normalize==1) or (RM>=5)):
        X1 = (X[:,1:n]-np.ones((T,1))@X[:,1:n].mean(axis=0)[np.newaxis,])/(np.ones((T,1))@np.std(X[:,1:n], axis=0, ddof=1)[np.newaxis,])
        Y1 = (Y - np.ones((T,1))@Y.mean(axis=0)[np.newaxis,])/(np.ones((T,1))@np.std(Y, axis=0, ddof= 1)[np.newaxis,])
        n1 = n-1
    
    else:#leave the values unchange if not normalised
        X1 = X
        Y1 = Y
        n1 = n

    # Step 3: Regression methods
    ############################

    #OLS
    if RM == 1:
        B = linalg.inv(X1.conj().T@X1)@X1.conj().T@Y1

    #LS-SVD
    elif RM == 2:
        U, S, Vh = linalg.svd(X1 ,full_matrices=False)
        V = Vh.T
        S_inv = np.diag(1/S)
        B = V@[email protected]().T@Y1

    #LAD-PP
    elif RM == 3:
        BND = [(-100, 100)]*n1 + [(0, None)]*2*T
        f = np.vstack((np.zeros((n1,1)), np.ones((2*T,1))))
        Aeq = np.concatenate((X1, np.eye(T), -np.eye(T)), axis=1)
        B =[]
        #solve the equation
        for i in range(N):
            beq = Y1[:,i]
            result = linprog(f, A_eq = Aeq, b_eq = beq, bounds= BND, method="highs-ipm")
            B.append(list(result.x[0:n1]))
        B = np.asarray(B).T

    # RLS-Tikhonov
    elif RM == 4:
        B = linalg.inv(X1.conj().T@X1+T/n1*np.eye(n1)*10**penalty)@X1.conj().T@Y1

    # RLS-TSVD
    elif RM == 5:
        U, S, Vh = linalg.svd(X1, full_matrices=False)
        V = Vh.T
        r = np.count_nonzero(np.divide(np.diag(S).max(), np.diag(S))<= 10**(penalty))
        Sr_inv = np.zeros((n1,n1))
        Sr_inv[0:r, 0:r]= np.diag(np.divide(1., S[:r]))
        B = V@[email protected]().T@Y1

    # RLAD-PP
    elif RM == 6:
        #we can just use the default setting from scipy as the lower and upper will be the same
        f= np.vstack((10**penalty*np.ones((n1*2,1))*T/n1, np.ones((2*T,1))))
        Aeq= np.c_[X1,-X1, np.eye(T), -np.eye(T)]
        B = []
        #solve the equation
        for i in range(N):
            beq = Y1[:,i]
            result = linprog(f, A_eq = Aeq, b_eq = beq, method="highs-ipm")
            B.append(list(result.x[0:n1]-result.x[n1:2*n1]))
        B = np.asarray(B).T
    
    #Step 4: Infer the regression coefficients in the original regression with unnormalised data
    ############################################################################################

    if ((normalize==1) or (RM>=5)):
        B2 = (1/np.std(X[:,1:n], axis=0).conj().T).reshape((n1,1))@np.std(Y, axis=0)[np.newaxis,]*B
        B1 = Y.mean(axis=0)[np.newaxis,] - X[:, 1:n].mean(axis=0)[np.newaxis,]@B2
        B = np.vstack((B1,B2))
    
    return B
Exemple #34
0
# https://stackoverflow.com/questions/45873783/python-linprog-minimization-simplex-method
"""
Ejemplo 1
Maximixe        z = x1*0.12 + x2*0.16 + x3*0.16 
                    + x4*0.14
Subject to:     x1 + x2 + x3 + x4 <= 1
				x1 >= 0.55 * (x1+x2)
                x1 >= 0.25 * (x1+x2+x3+x4)
                x2 >= 0.30 * (x1+x2+x3+x4)
                z  <= 0.14 * (x1+x2+x3+x4)

                0<=xi<=1 i=1 ... 4

with              x1 >= 0, x2 >= 0
"""
A = np.array([[1, 2], [2, 2], [-1, 0], [0, -1]])
b = np.array([6, 8, 0, 0])
c = np.array([3, 4])

# max
c *= -1  # negate the objective coefficients

res = linprog(c, A_ub=A, b_ub=b, bounds=(0, None))

# print('Optimal value:', res.fun, '\nX:', res.x)

# max
print("Objective = {} \n X: {}".format(
    res.get('fun') * -1,
    res.x))  # don't forget to retransform your objective back!
def PT(t_now, M1, M2, constraints):
    global Cnt
    if t_now > t:
        # dupilicate one
        constraints_now = list(constraints)
        for OPT_M1 in OPT_Assignments:
            constraints = list(constraints_now)
            # Get the jobs on M2, i.e., all jobs not on M1
            OPT_M2 = Jobs - OPT_M1
            # tot processing time of jobs on M1 <= C^*
            # tot processing time of jobs on M2 <= C^*
            # p_{t+2} is C^*
            constraints.append((OPT_M1, {t + 2}))
            constraints.append((OPT_M2, {t + 2}))
            # p_{t+1} is C^{PT}
            # C^{PT} <= tot p.t. of machine that p_t is on
            # 9 <= tot p.t. of machine that p_t is on
            # tot p.t. of machines before p_t is assigned <= 7
            if t in M1:
                constraints.append(({t + 1}, M1))
                constraints.append(({'9'}, M1))
                constraints.append((M1 - {t}, {'7'}))
                constraints.append((M2, {'7'}))
            else:
                constraints.append(({t + 1}, M2))
                constraints.append(({'9'}, M2))
                constraints.append((M1, {'7'}))
                constraints.append((M2 - {t}, {'7'}))

            # minimize -(C^{PT}-9/8C^*) i.e. maximize C^{PT}-9/8C^*
            c = [0 for i in range(1, t + 1)] + [-1, +9 / 8]
            A_ub = []
            b_ub = []
            #print(constraints)
            for a_cons in constraints:
                a_row = [0 for i in range(1, t + 1)] + [0, 0]
                a_b = [0]
                # variables in LHS
                for var in a_cons[0]:
                    # if it is some p_i
                    if type(var) == int:
                        a_row[var - 1] = 1
                    # if it is a number, represented using string
                    else:
                        a_b = [-int(var)]
                # variables in RHS
                for var in a_cons[1]:
                    # if it is some p_i
                    if type(var) == int:
                        a_row[var - 1] = -1
                    # if it is a number, represented using string
                    else:
                        a_b = [int(var)]
                A_ub.append(a_row)
                b_ub += a_b
            res = linprog(c, A_ub, b_ub, A_eq, b_eq)
            if res.success:
                Cnt += 1
                #if M1=={1,4,5} and OPT_M1=={1,2}:
                #for cs in constraints:
                #    print(cs)

                print(M1)
                print(M2)
                print(OPT_M1)
                print(OPT_M2)
                #for l in range(len(A_ub)):
                #    print(A_ub[l])
                #for l in range(len(A_ub)):
                #    print(b_ub[l])
                print(res)
                fout.write('PT Assignment:\n')
                fout.write('\\begin{equation}')
                fout.write('M_1 = \\{' + str(N2S(M1)) + '\\},')
                fout.write('M_2 = \\{' + str(N2S(M2)) + '\\}\n')
                fout.write('\\end{equation}\n')
                fout.write('OPT Assignment:\n')
                fout.write('\\begin{equation*}\n')
                fout.write('M_1 = \\{' + str(N2S(OPT_M1)) + '\\},')
                fout.write('M_2 = \\{' + str(N2S(OPT_M2)) + '\\}\n')
                fout.write('\\end{equation*}\n')
                fout.write('\\begin{eqnarray*}\n')
                for i in range(len(A_ub)):
                    first = True
                    for j in range(len(A_ub[i])):
                        #    if A_ub[i][j] == 1:
                        #        print('+'+names[j],end='')
                        #    elif A_ub[i][j] == -1:
                        #        print('-'+names[j],end='')
                        #print("<=", end='')
                        #print(b_ub[i], end=',\n')
                        if A_ub[i][j] == 1:
                            if first:
                                fout.write(names[j])
                                first = False
                            else:
                                fout.write('+' + names[j])
                        elif A_ub[i][j] == -1:
                            fout.write('-' + names[j])
                            first = False
                    fout.write('\\leq')
                    fout.write(str(b_ub[i]))
                    fout.write('\\\\\n')
                fout.write('\\end{eqnarray*}\n')
                fout.write('$f^\\ast=' + str(-res.fun) + '$\n\n')

            #if res.success:
            #    print(res.fun)

        return
    # M1 < M2
    new_cons = (M1, M2)
    # Either jobs on M2 with p_i <7 or >9,
    # otherwise primal assign rule will apply
    constraints1 = constraints + [new_cons] + [(M2 | {t_now}, {'7'})]
    constraints2 = constraints + [new_cons] + [({'9'}, M2 | {t_now})]
    # assign p_i to M1
    PT(t_now + 1, M1 | {t_now}, M2, constraints1)
    PT(t_now + 1, M1 | {t_now}, M2, constraints2)
    # M2 < M1
    new_cons = (M2, M1)
    # Either jobs on M1 with p_i <7 or >9,
    # otherwise primal assign rule will apply
    constraints1 = constraints + [new_cons] + [(M1 | {t_now}, {'7'})]
    constraints2 = constraints + [new_cons] + [({'9'}, M1 | {t_now})]
    # assign p_i to M2
    PT(t_now + 1, M1, M2 | {t_now}, constraints1)
    PT(t_now + 1, M1, M2 | {t_now}, constraints2)
		[1, -2, 1, 0], 

		[2, 1, 0, 1]
		
	]
)

b_eq = np.array(
	[5/2, 3/2]
)

# Multiplicators of objective function
c = np.array(
	[3, 2, 0, 0]
)


res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=(None, None))#, options={"tol":1e-3})

# print('Optimal value:', res.fun, '\nX:', res.x)

# case of maximize
print("Objective = {} \n X: {}".format(round(res.get('fun'), 20), res.x,5)) # don't forget to retransform your objective back!

print(res.get('fun'))

for varName, i in zip(["x_"+str(x) for x in range(1, len(res.x)+1)], res.x):
	print(varName, i)

# for i in res.keys():
#	print(i, "->", res.get(i))
Exemple #37
0
	[
		
		[0, 0, 0, 1], 

	]
)

b_eq = np.array(
	[1]
)

# Multiplicators of objective function
c = np.array(
	[-1, 1, 4, -12]
)

# Case of maximize
c *= -1 # negate the objective coefficients

res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=(None, None))

# print('Optimal value:', res.fun, '\nX:', res.x)

# case of maximize
print("Objective = {} \n X: {}".format(res.get('fun') * -1, res.x)) # don't forget to retransform your objective back!

for i in res.keys():
	print(i, "->", res.get(i))

for varName, i in zip(["x_"+str(x) for x in range(1, len(res.x)+1)], res.x):
	print(varName, i)
Exemple #38
0
alternatives_Bel = [
    Bel(alter_comb, alter_mass[key]) for key in range(num_of_cri)
]
alternatives_Pl = [
    Pl(alter_comb, alter_mass[key]) for key in range(num_of_cri)
]

left_side, right_side = getCriteriaConditional(cri_comb, criterias,
                                               criteria_Pl, criteria_Bel)

c_bel = [
    np.array([alternatives_Bel[cri][alter] for cri in range(num_of_cri)])
    for alter in range(len(alter_comb))
]
BEL = np.array(
    [np.dot((linprog(c, left_side, right_side).x), c) for c in c_bel])

c_pl = [
    np.array([alternatives_Pl[cri][alter] for cri in range(num_of_cri)])
    for alter in range(len(alter_comb))
]
PL = np.array(
    [np.dot((linprog(-c, left_side, right_side).x), c) for c in c_pl])

alpha = 0.4
final_result = alpha * BEL + (1 - alpha) * PL

print("BEL:\n", BEL)
print("PL:\n", PL)
print("Final result:\n", final_result)
Exemple #39
0
 def test_empty_constraint_2(self):
     res = linprog([1, -1, 1, -1],
                   bounds=[(0, np.inf), (-np.inf, 0), (-1, 1), (-1, 1)],
                   method=self.method,
                   options=self.options)
     _assert_success(res, desired_x=[0, 0, -1, 1], desired_fun=-2)
Exemple #40
0
 def test_no_constraints(self):
     res = linprog([-1, -2], method=self.method, options=self.options)
     if self.method == "simplex":
         # Why should x be 0,0? inf,inf is more correct, IMO
         assert_equal(res.x, [0, 0])
     _assert_unbounded(res)
Exemple #41
0
c = [-1, 4]  # minimize function
A = [[-3, 1], [1, 2]]  # subject to 1, 2
b = [6, 4]  # subject to 1, 2 (free term)

x0_bounds = (None, None)
x1_bounds = (-3, None)

# In[7]:

from scipy.optimize import linprog

result = linprog(
    c,  # coeffs of the linear objective function to be minimized
    A_ub=A,  # inequality constraint matrix: coeffs of a linear inequality
    b_ub=b,  # inequality constraint vector: upper bound A_ub @ x
    bounds=(x0_bounds,
            x1_bounds),  # sequence of (min, max) pairs for each element in x
    options={'disp': True})

display(result)

# In[14]:

# Example 2

# A trading company is looking for a way to maximize profit per transportation of their goods.
# The company has a train available with 3 wagons.
# When stocking the wagons they can choose between 4 types of cargo, each with its own specifications.
# How much of each cargo type should be loaded on which wagon in order to maximize profit?
                ],
                [
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
                    0, 0, 0, 0, 0
                ],
                [
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    1, 1, 1, 1, 1
                ]]
x_ver = [30, 55, 40, 24, 59]
A_vertical = [[
    1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0
], [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0],
              [
                  0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0,
                  0, 0, 1, 0, 0
              ],
              [
                  0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0,
                  0, 0, 0, 1, 0
              ],
              [
                  0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1,
                  0, 0, 0, 0, 1
              ]]

print(linprog(c, A_horizontal, x_hor, A_vertical, x_ver))

finish = time.time()
print("Время : ", finish - start)
    def steiner_forest(self):
        vars_ = {}  # Dictionary of variables.
        E = self.__graph.get_edges()
        # Allocate x_ij variables.
        for i, e in enumerate(E):
            vars_[e] = i
        # Allocate f_k_ij variables (both directions).
        i = len(vars_)
        for e in E:
            for ts in self.__terminals:
                for t in ts:
                    vars_[(e[0], e[1], t)] = i
                    i += 1
                    vars_[(e[1], e[0], t)] = i
                    i += 1
        # Sort dictionary of variables by index.
        sorted_vars = sorted(vars_.iteritems(), key=operator.itemgetter(1))
        # Create the c vector.
        c = []
        for var, _ in sorted_vars:
            try:
                c.append(E[var])
            except KeyError:
                c.append(0)
        # Create the conservation of flow constraints.
        A_eq_d = {}
        b_eq_d = {}
        for v, val in self.__graph.iteritems():
            for w, _ in val.iteritems():
                for ts in self.__terminals:
                    for t in ts:
                        try:
                            A_eq_d[(v, t)][(v, w, t)] = 1
                        except KeyError:
                            A_eq_d[(v, t)] = {(v, w, t): 1}
                        try:
                            A_eq_d[(v, t)][(w, v, t)] = -1
                        except KeyError:
                            A_eq_d[(v, t)] = {(w, v, t): -1}
            for k, ts in enumerate(self.__terminals):
                for t in ts:
                    if v == self.__roots[k]:
                        b_eq_d[(v, t)] = 1
                    elif v == t:
                        b_eq_d[(v, t)] = -1
                    else:
                        b_eq_d[(v, t)] = 0
        A_eq = []
        b_eq = []
        for v in self.__graph:
            for ts in self.__terminals:
                for t in ts:
                    a = []
                    for var, _ in sorted_vars:
                        if var in A_eq_d[(v, t)]:
                            a.append(A_eq_d[(v, t)][var])
                        else:
                            a.append(0)
                    A_eq.append(a)
                    b_eq.append(b_eq_d[(v, t)])
        # Create the edge orientation constraints.
        A_ub_d = {}
        for e, _ in E.iteritems():
            for ts in self.__terminals:
                ts_ = set(ts)
                for v in ts:
                    ws = ts_.difference([v])
                    for w in ws:
                        # First inequality.
                        try:
                            A_ub_d[(e, v, w, 0)][(e[0], e[1], v)] = -1
                        except KeyError:
                            A_ub_d[(e, v, w, 0)] = {(e[0], e[1], v): -1}
                        A_ub_d[(e, v, w, 0)][(e[1], e[0], w)] = -1
                        # Second inequality.
                        try:
                            A_ub_d[(e, v, w, 1)][e] = -1
                        except KeyError:
                            A_ub_d[(e, v, w, 1)] = {e: -1}
                        A_ub_d[(e, v, w, 1)][(e[0], e[1], v)] = 1
                        A_ub_d[(e, v, w, 1)][(e[1], e[0], w)] = 1
        A_ub = []
        b_ub = []
        for e in E:
            for ts in self.__terminals:
                ts_ = set(ts)
                for v in ts:
                    ws = ts_.difference([v])
                    for w in ws:
                        a0 = []
                        a1 = []
                        for var, _ in sorted_vars:
                            if var in A_ub_d[(e, v, w, 0)]:
                                a0.append(A_ub_d[(e, v, w, 0)][var])
                            else:
                                a0.append(0)
                            if var in A_ub_d[(e, v, w, 1)]:
                                a1.append(A_ub_d[(e, v, w, 1)][var])
                            else:
                                a1.append(0)
                        A_ub.append(a0)
                        A_ub.append(a1)
                        b_ub.append(0)
                        b_ub.append(0)
        # print A_ub
        # Solve the linear program.
        res = linprog(c=c,
                      A_eq=A_eq,
                      b_eq=b_eq,
                      A_ub=A_ub,
                      b_ub=b_ub,
                      options={"maxiter": 1000000})
        print res
        # Build the Steiner forest.
        steiner_forest = Graph()
        for i in range(len(res['x'])):
            if res['x'][i] > .4:
                if len(sorted_vars[i][0]) == 2:
                    steiner_forest.append_edge_1(sorted_vars[i][0],
                                                 self.__graph)

        return steiner_forest
Exemple #44
0
    print("Итерация", k)
    print("xk", vector_x0)
    print("fx_k", fx_x)
    print("vector_fx_k", vector_fx)
    print("Норма vector_fx_k", vector_fx_norma)

    if vector_fx_norma > eps_y_all:

        print("Так как Норма vector_fx_k=", vector_fx_norma, ">", eps_y_all,
              ", то продолжаем вычисления")
        print(
            "Для этого вычислим значение альфы, найдем новое приближение х и проверим условия останова итерационного процесса eps_x и eps_y"
        )
        #использую симплекс метод для решения системы
        res = linprog(solution, A_ub=AB_x_all, b_ub=AB_b_all, bounds=(0, None))
        reshenie = res.x
        reshenie = np.array(reshenie)

        vector_f_lambda = vector_x0 + lambdaAK * (reshenie - vector_x0)

        #создаю еще один dictionary чтобы вставить в уравнение с лямбдой
        dict3 = {}
        dict3 = dict(zip(keys, vector_f_lambda))
        solution_fx = simplify(f_x.subs(dict3))

        #Вычисление lambda (в нашем случае Альфы)
        proizv_lambda = sp.Derivative(solution_fx, lambdaAK).doit()
        proizv_lambda_solve = solve(proizv_lambda)

        #границы решения [0:1]
Exemple #45
0
def test(maxAdjustRatio=None):
    print('=====' + str(maxAdjustRatio) + '=====')
    old_ratio = np.array([
        3.20, 3.20, 3.20, 3.20, 10.80, 10.80, 2.20, 27.60, 28.80, 1.60
    ]) * 0.01

    # 定义目标函数系数
    # 股票资产占比
    C = np.array([0.365, 0.235, 0.176, 0.298, 0.17, 0.255, 0.001, 0, 0, 0])
    n = len(C)

    T = 184000  # 规模
    R = 0.1  # 股票比例
    T2 = 500  # 冻结
    CASH_RATIO = 0.054  # 现金比例

    # 实际剩余基金大小
    CT = (T - T2) * (1 - CASH_RATIO)

    if np.sum(old_ratio * C) > R:
        print("bad old ratio")
        return False

    # 定义约束条件系数
    AUB = [
        C.copy(),
    ]
    BUB = [
        T * R,
    ]

    AEQ = [
        np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]),
        np.array([1, -1, 0, 0, 0, 0, 0, 0, 0, 0]),
        np.array([1, 0, -1, 0, 0, 0, 0, 0, 0, 0]),
        np.array([1, 0, 0, -1, 0, 0, 0, 0, 0, 0]),
        np.array([1, 0, 0, 0, 0, -1, 0, 0, 0, 0]),
    ]

    BEQ = [CT, 0, 0, 0, 0]

    BOUNDS = [(0, None)] * n
    if maxAdjustRatio is not None:

        C = np.append(C, np.zeros(n))
        for i in range(len(AUB)):
            AUB[i] = np.append(AUB[i], np.zeros(n))
        for i in range(len(AEQ)):
            AEQ[i] = np.append(AEQ[i], np.zeros(n))
        BOUNDS.extend([(0, None)] * n)

        # introduce other variables.
        norm = old_ratio / np.sum(old_ratio)
        n2 = 2 * n
        for i in range(n):
            old = norm[i] * CT

            # abs(c-old)
            # absx >= c-old
            # -absx + c <= old
            a = [0] * n2
            a[i] = 1
            a[i + n] = -1
            b = old
            AUB.append(a)
            BUB.append(b)

            # absx >= -(c-old)
            # -absx <= (c-old)
            # -absx -c <= -old
            a = [0] * n2
            a[i] = -1
            a[i + n] = -1
            b = -old
            AUB.append(a)
            BUB.append(b)

        a = [0] * n2
        for i in range(n):
            a[i + n] = 1
        b = maxAdjustRatio * CT
        AUB.append(a)
        BUB.append(b)

    # 求解
    res = op.linprog(-C,
                     A_ub=np.array(AUB),
                     b_ub=np.array(BUB),
                     A_eq=np.array(AEQ),
                     b_eq=np.array(BEQ),
                     bounds=BOUNDS)
    if not res.success:
        return False

    print(res)
    x = res.x

    if maxAdjustRatio is not None:
        x = x[:n]

    ratio = np.round(x / np.sum(x), 3)
    print('max adjust = {}'.format(maxAdjustRatio))
    print('old ratio = {}'.format(old_ratio))
    print('new ratio = {}'.format(ratio))
    print('abs adjust = {}'.format(np.sum(np.abs(ratio - old_ratio))))
    return True
])

shift_value = abs(np.min(game_matrix))

#player A
#f(x) min (1/v)
#constraints -> iloczyn każdy z każdym kolumny >=1 -> do postaci <= -1
game_matrixA = -(game_matrix + shift_value).T

constraints_values_A = [-1, -1, -1, -1]

goal_function_coeff = [1, 1, 1, 1]

#wylicza x_i
gameA_result = linprog(goal_function_coeff,
                       A_ub=game_matrixA,
                       b_ub=constraints_values_A,
                       options={"disp": True})

v_A = 1 / sum(gameA_result.x)

#zamiana na p_i
probabilities_A = gameA_result.x * v_A
gameA_value = v_A - shift_value

print("Player A")
print("Probabilities A", probabilities_A)
print("Game value A %.2f" % gameA_value)

#player B
#f(x) max (1/v) -> min -f(x)
#constraints -> iloczyn każdy z każdym kolumny <=1
Exemple #47
0
#    currentDT = datetime.datetime.now()
#    print (str(currentDT))
#    print(file)
#    c, A_ub, b_ub, A_eq, b_eq, bounds, obj = load(file)
#    res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, method="interior-point", options={"sparse":True})
#    print(res.status)
#    if not res.status == 2:
#        print("INCORRECT:" + file)

#problems = ['bgdbg1', 'bgprtr', 'box1', 'chemcom', 'cplex2',
#            'ex72a', 'ex73a', 'forest6', 'galenet', 'itest2',
#            'itest6', 'klein1', 'refinery', 'woodinfe']
#for prob in problems:
#    c, A_ub, b_ub, A_eq, b_eq, bounds, obj = load(prob+".npz")
#    t0 = time.perf_counter()
#    res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, method="revised simplex")
#    t1 = time.perf_counter()
#    print(prob, res.nit, res.status)

# method="revised simplex"
prob_name = "neos-4960896-besbre"
#filename = prob_name + ".mps"
#p = problem(filename)
#p.obj = np.array([0])
#c, A_ub, b_ub, A_eq, b_eq, bounds = p.get()
filename = prob_name + ".npz"
#p.save(filename)
c, A_ub, b_ub, A_eq, b_eq, bounds, obj = load(filename)
res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, options={"Sparse":True})
print(res)
from scipy import optimize as op
import numpy as np
c = np.array([130, 230])
A_ub = np.array([[5, 15], [4, 4], [35, 20], [1.5, 2.5]])
B_ub = np.array([480, 160, 1190, 84])
# A_eq=np.array([[1,1,1]])
# B_eq=np.array([7])
x1 = (0, None)
x2 = (0, None)
res = op.linprog(-c, A_ub, B_ub, bounds=(x1, x2))
print(res)
# print(68*200+150*52)
Exemple #49
0
def scheduler():
    class_size = len(Class.objects.all())
    classroom_size =  len(Classroom.objects.all())
    class_period = 10 # There are 2 * 5 periods for a class day
    # x(i,j,k): class i, classroom j, periods k for a class
    x = np.zeros((class_size, classroom_size, class_period), dtype = np.int)
    #class_period for every class
    a = np.array(np.concatenate(np.array(list(Class.objects.values_list('period')))))
    #c(i,j): the capacity of classroom j divided by the number of students enrolled in course i.  
    ccc = np.zeros((class_size, classroom_size, class_period), dtype = np.float)

    count = 0
    for i in range(class_size):
        for j in range(classroom_size):
            class_people = Class.objects.filter(identity = i).values('capacity')[0]['capacity']
            class_room_people = Classroom.objects.filter(identity = j).values('capacity')[0]['capacity']
            if class_people > class_room_people:
                count += 1
            temp = class_people / class_room_people
            for k in range(class_period):
                ccc[i,j,k] = temp

    T_size = count
    #print(x)
    #print(a)
    #print(c)
    c = np.concatenate(ccc) 
    #print(c)
    A_eq = np.zeros((class_size, classroom_size, class_period, class_size ), dtype = np.int)
    A_ub = np.zeros((class_size, classroom_size, class_period, classroom_size * class_period), dtype = np.int)

    b_eq = np.array(a)
    temp = np.zeros((T_size))
    b_eq = np.append(b_eq, temp)

    temp = np.ones((classroom_size, class_period))
    b_ub = np.array(temp)

    # calculate A_eq
    count = 0 
    temp = np.zeros((class_size, classroom_size, class_period, T_size))
    for i in range(class_size):
        A_eq[i,:,:,i] = np.ones((classroom_size, class_period))
    for i in range(class_size):
        for j in range(classroom_size):
            class_people = Class.objects.filter(identity = i).values('capacity')[0]['capacity']
            #class_people = Class.objects.filter(identity = 1)[0].capacity
            class_room_people = Classroom.objects.filter(identity = j).values('capacity')[0]['capacity']
            if(class_people > class_room_people):
                temp[i, j, :, count] = np.ones((class_period))
                count += 1
    A_eq = np.append(A_eq, temp, axis = 3)

    # calculate A_ub
    count = 0
    for j in range(classroom_size):
        for k in range(class_period):
            A_ub[:, j, k, count] = np.ones((class_size))
            count += 1

    c = c.reshape(-1)
    A_eq = np.concatenate(A_eq).reshape(-1, class_size + T_size ).T
    A_ub = np.concatenate(A_ub).reshape(-1, classroom_size * class_period).T      
    #b_eq = np.concatenate(b_eq)
    b_ub = np.concatenate(b_ub)

    '''
    print(c.shape)
    print(A_eq.shape)
    print(A_ub.shape)
    print(b_eq.shape)
    print(b_ub.shape)
    '''

    r = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds=tuple([(0,1)]* (class_size * classroom_size * class_period)))

    #print(r)

    #print(r.x)
    if(r.success):
        reshape_x = r.x.reshape(class_size, classroom_size, class_period)
        #print(reshape_x)
        count = 0
        for i in range(class_size):
            is_class = 0
            class_table_obj = Classtable(identity = count)
            for j in range(classroom_size):
                for k in range(class_period):
                    if reshape_x[i,j,k] == 1:
                        if is_class == 0:
                            class_table_obj.identity = count
                            class_table_obj.course_identity = Class.objects.filter(identity = i)[0].identity
                            class_table_obj.course_name = Class.objects.filter(identity = i)[0].name
                            class_table_obj.teacher_name = Class.objects.filter(identity = i)[0].teacher_name
                            class_table_obj.course_capacity = Class.objects.filter(identity = i)[0].capacity
                            class_table_obj.course_period = Class.objects.filter(identity = i)[0].period
                            class_table_obj.course_time_1 = k
                            class_table_obj.classroom_identity_1 = Classroom.objects.filter(identity = j)[0].identity
                            class_table_obj.classroom_name_1 = Classroom.objects.filter(identity = j)[0].name
                            class_table_obj.classroom_capacity_1 = Classroom.objects.filter(identity = j)[0].capacity
                            is_class = 1
                            count += 1
                        else :
                            class_table_obj.course_time_2 = k
                            class_table_obj.classroom_identity_2 = Classroom.objects.filter(identity = j)[0].identity
                            class_table_obj.classroom_name_2 = Classroom.objects.filter(identity = j)[0].name
                            class_table_obj.classroom_capacity_2 = Classroom.objects.filter(identity = j)[0].capacity
            class_table_obj.save()
        
        print(Classtable.objects.all().values())
Exemple #50
0
    dictlist = list(inv_val.apply(tuple, axis=0))
        # dictlist=dictlist[:-1]

    listofzeroes = [0] * len(feat)
    Price_Per_Unit_index = feat.index('Price_Per_Unit')
    listofzeroes[Price_Per_Unit_index] = 1
    Discount_index = feat.index('Discount')
    listofzeroes[Discount_index] = -1

    A = listofzeroes
    A = [-x for x in A]
    A = [A]
    b = 0.85

    res = linprog(c, A_ub=A, b_ub=b, bounds=dictlist)

    output = res.x
    res_list = [output[i] * c[i] for i in range(len(output))]
    st.write(res_list)
    sales = sum(res_list)

    if name == "standard":
        scaler = preprocessing.StandardScaler()
    else:
        scaler = preprocessing.MinMaxScaler()
    scaler = scaler.fit(target_col)
    inv_tar = scaler.transform(target_col)
    sales_transformed = scaler.inverse_transform(sales.reshape(-1, 1))
    sales_transformed = sales_transformed[0]
    sales_transformed = sales_transformed[0]
        ],
        [
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0,
            0, 0, 0
        ],
        [
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1,
            1, 1, 1
        ]]
b_eq = [20, 70, 43, 25, 40]
A_eq = [[
    1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0
], [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0],
        [
            0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0,
            1, 0, 0
        ],
        [
            0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0,
            0, 1, 0
        ],
        [
            0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0,
            0, 0, 1
        ]]
b_ub = [30, 50, 45, 70, 65]
print(linprog(d, A_ub, b_ub, A_eq, b_eq))
stop = time.time()
print("Время :")
print(stop - start)
    def _clc(self, branch_bound1, branch_bound2):
        res1 = optimize.linprog(self.c,
                                self.A,
                                self.b,
                                self.Aeq,
                                self.beq,
                                bounds=branch_bound1)
        res2 = optimize.linprog(self.c,
                                self.A,
                                self.b,
                                self.Aeq,
                                self.beq,
                                bounds=branch_bound2)
        if not res1.success or gt(res1.fun, self.solution_min):
            # 无线性规划解或者当前最优解比最小值小,剪枝
            pass
        else:
            if validate(res1.x):
                # 是局部最优解
                self.solution_min = res1.fun
                self.global_best = res1
            else:
                # 分支
                x_index = get_first_non_int(res1.x)
                x_lt = floor(res1.x[x_index])
                x_gt = x_lt + 1
                temp = list(branch_bound1)
                left_edge = temp[x_index][0]
                right_edge = temp[x_index][1]

                if (left_edge > x_lt):
                    pass
                else:
                    temp[x_index] = (left_edge, x_lt)
                    temp2 = temp.copy()
                    if (right_edge is not None and x_gt > right_edge):
                        pass
                    else:
                        temp2[x_index] = (x_gt, right_edge)
                        self._clc(temp, temp2)

        if not res2.success or gt(res2.fun, self.solution_min):
            pass
        else:
            if validate(res2.x):
                self.solution_min = res2.fun
                self.global_best = res2
            else:
                x_index = get_first_non_int(res2.x)
                x_lt = floor(res2.x[x_index])
                x_gt = x_lt + 1
                temp = list(branch_bound2)
                left_edge = temp[x_index][0]
                right_edge = temp[x_index][1]
                if (left_edge > x_lt):
                    pass
                else:
                    temp[x_index] = (left_edge, x_lt)
                    temp2 = temp.copy()
                    if (right_edge is not None and x_gt > right_edge):
                        pass
                    else:
                        temp2[x_index] = (x_gt, right_edge)
                        self._clc(temp, temp2)
Exemple #53
0
def BaBSimplex(c,
               A_ub,
               b_ub,
               A_eq,
               b_eq,
               intVars=["x1"],
               is_maximize=False,
               decimals=10):
    # number of variables from model
    numberVars = len(c)
    """
	Create a list with a properly variables names (x1, x2, ... xn) n is 
	the value of numberVars
	"""
    varNames = ["x" + str(x) for x in range(1, numberVars + 1)]

    # Create a dict base for check integer vars
    intVarsBase = {i: False for i in intVars}
    # set intVars in All int
    intVars = intVarsBase.copy()

    colorFailed = "red"
    colorWorst = "orange"
    colorPossibleSolution = "yellow"
    colorUnsolved = "blue"
    colorSolvedDecimal = "gray"
    colorOptimalSolution = "green"

    # List of bounds of all variables
    bounds = [(None, None)] * len(c)

    # Configure values for maximize or minize
    if (is_maximize):
        factor = -1  # Factor for result for maximize with minimize process
        c *= -1  # negate the objective coefficients
    else:
        factor = 1

    # Create graph instance
    G = nx.Graph()

    # Get answers for root node
    res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=bounds)

    # var control
    iteration = 0

    if (not res.get("success")):
        print("can't found optimal answer from root state with message: {}".
              format(res.get("message")))
        printStep("{} phase root".format(iteration), varNames, res, decimals)

        G.add_nodes_from([[
            iteration, {
                "color": colorFailed,
                "objective": res.get("fun") * factor
            }
        ]])
        return G

    G.add_nodes_from([[
        iteration, {
            "color": colorUnsolved,
            "parent": None,
            "objective": res.get("fun") * factor
        }
    ]])
    printStep("{} phase root".format(iteration), varNames, res, decimals)
    draw_graph_states(G, iteration)
    iteration += 1

    while colorUnsolved in nx.get_node_attributes(G, 'color').values():

        # Control for iterations, because graph change for each iteration (only add nodes)
        IterationsNodes = list(G.nodes())
        for nodeI in IterationsNodes:
            if (G.nodes[nodeI]["color"] == colorUnsolved):

                # Get actions for bound restrictions #### continuie here
                actions = get_actions(G, nodeI, intVars.keys())

                # Update bounds
                for varName in actions:
                    if (actions.get(varName) is not None):
                        # Separate xn from <= ### (xn|###)
                        action = actions.get(varName)
                        if (action[:2] == ">="):
                            # Bound index is var number -1
                            bounds[int(varName[1:]) - 1] = (int(action[2:]),
                                                            None)
                        elif (action[:2] == "<="):
                            bounds[int(varName[1:]) - 1] = (None,
                                                            int(action[2:]))
                    else:
                        #if control is none
                        bounds[int(varName[1:]) - 1] = (None, None)

                # Get solution with simplex
                res = linprog(c,
                              A_ub=A_ub,
                              b_ub=b_ub,
                              A_eq=A_eq,
                              b_eq=b_eq,
                              bounds=bounds)

                # Update extra actions in label node
                varInts = [
                    i + ":" + str(res.x[int(i[1:]) - 1]) for i in actions
                ]
                G.nodes[nodeI]["label"] = (
                    str(nodeI) + "\n" + str(varInts)[1:-1] + "\n" +
                    "Objective" +
                    str(round(res.get("fun") * factor, decimals))).replace(
                        "None", "").replace(",", "\n")

                if (not res.get("success")):
                    printStep(nodeI, varNames, res, decimals)
                    print("Optimal failed")

                    G.nodes[nodeI]["color"] = colorFailed
                    G.nodes[nodeI]["objective"] = round(
                        res.get("fun") * factor, decimals)
                    draw_graph_states(G, nodeI)
                    continue

                # set intVars in All int
                intVars = intVarsBase.copy()

                # Check decimal vars in integer vars
                for varName, varResult in zip(varNames, res.x):
                    if (varName in intVars):
                        if (round(varResult, decimals).is_integer()):
                            intVars[varName] = True

                # All vars are integers
                if (False in intVars.values()):
                    #print("found optimal with integer values")
                    #print("Objective = {}".format(res.get('fun')))
                    printStep(nodeI, varNames, res, decimals)
                    G.nodes[nodeI]["color"] = colorSolvedDecimal
                    G.nodes[nodeI]["objective"] = res.get("fun") * factor

                    #G.add_nodes_from([[iteration, {"color":colorUnsolved, "parent":nodeToSolve}]])
                    #iteration+=1

                    # Check if objetive worsts
                    if (is_worst_objective(G, nodeI, is_maximize)):
                        print("Worst objective")
                        G.nodes[nodeI]["color"] = colorWorst
                        G.nodes[nodeI]["objective"] = round(
                            res.get("fun") * factor, decimals)
                        draw_graph_states(G, nodeI)
                        continue

                    for varName in intVars:
                        # Is not integer answer
                        if (intVars.get(varName) is False):

                            # Left part
                            G.add_nodes_from([[
                                iteration, {
                                    "color": colorUnsolved,
                                    "parent": nodeI
                                }
                            ]])
                            G.add_edges_from([[
                                nodeI, iteration, {
                                    "action":
                                    varName + "|<=" +
                                    str(int(res.x[int(varName[1:]) - 1]))
                                }
                            ]])
                            iteration += 1

                            # Rigth Part
                            G.add_nodes_from([[
                                iteration, {
                                    "color": colorUnsolved,
                                    "parent": nodeI
                                }
                            ]])
                            G.add_edges_from([[
                                nodeI, iteration, {
                                    "action":
                                    varName + "|>=" +
                                    str(int(res.x[int(varName[1:]) - 1]) + 1)
                                }
                            ]])
                            iteration += 1
                            draw_graph_states(G, nodeI)
                            break
                else:
                    printStep(nodeI, varNames, res, decimals)
                    print("found with integer values")
                    G.nodes[nodeI]["color"] = colorPossibleSolution
                    G.nodes[nodeI]["objective"] = round(
                        res.get("fun") * factor, decimals)
                    draw_graph_states(G, nodeI)

    optimalValue = None
    for nodeI in G.nodes():
        if (G.nodes[nodeI]["color"] == colorPossibleSolution):
            if (optimalValue is None):
                optimalValue = G.nodes[nodeI]["objective"]
            else:
                if (is_maximize):
                    if (G.nodes[nodeI]["objective"] > optimalValue):
                        optimalValue = G.nodes[nodeI]["objective"]
                elif (not is_maximize):
                    if (G.nodes[nodeI]["objective"] < optimalValue):
                        optimalValue = G.nodes[nodeI]["objective"]

    for nodeI in G.nodes():
        if (G.nodes[nodeI]["color"] == colorPossibleSolution):
            if (G.nodes[nodeI]["objective"] == optimalValue):
                G.nodes[nodeI]["color"] = colorOptimalSolution
                break

    return G
Exemple #54
0
#let's use linear programming to solve for optimal policy of the MDP
#we actually need r to be over states and actions, I think
r_sa = np.array([+1., -1., +1., -1.])  #s1-left, s2-left, s1-right, s2-right
P_left = np.array([[1., 0.], [1., 0.]])
P_right = np.array([[0., 1.], [0., 1.]])
I_s = np.eye(num_states)
#use same p0 as before
from scipy.optimize import linprog

A_eq = np.concatenate(
    (I_s - gamma * P_left.transpose(), I_s - gamma * P_right.transpose()),
    axis=1)
b_eq = p0
c = -1.0 * r_sa  #we want to maximize r_sa^T c so make it negative since scipy minimizes by default

sol = linprog(c, A_eq=A_eq, b_eq=b_eq)
#minimize:
#c @ x
#such that:
#A_ub @ x <= b_ub
#A_eq @ x == b_eq
#all variables are non-negative by default
print(sol)

print("expeced value LP",
      -sol['fun'])  #need to negate the value to get the maximum
print("state_action occupancies", sol['x'])
u_sa = sol['x']

print("expected value dot product", np.dot(u_sa, r_sa))
#calculate the optimal policy
Exemple #55
0
def generate_bqm(graph,
                 table,
                 decision_variables,
                 linear_energy_ranges=None,
                 quadratic_energy_ranges=None,
                 min_classical_gap=2):
    """
    Args:
        graph: A networkx.Graph
        table: An iterable of valid spin configurations. Each configuration is a tuple of
            variable assignments ordered by `decision`.
        decision_variables: An ordered iterable of the variables in the binary quadratic model.
        linear_energy_ranges: Dictionary of the form {v: (min, max), ...} where min and
            max are the range of values allowed to v. The default range is [-2, 2].
        quadratic_energy_ranges: Dict of the form {(u, v): (min, max), ...} where min and max are
            the range of values allowed to (u, v). The default range is [-1, 1].
        min_classical_gap: A float. The minimum energy gap between the highest feasible state and
            the lowest infeasible state.
    """
    # Check for auxiliary variables in the graph
    if len(graph) != len(decision_variables):
        raise ValueError(
            'Penaltymodel-lp does not handle problems with auxiliary variables'
        )

    if not linear_energy_ranges:
        linear_energy_ranges = {}

    if not quadratic_energy_ranges:
        quadratic_energy_ranges = {}

    # Simplify graph naming
    # Note: nodes' and edges' order determine the column order of the LP
    nodes = decision_variables
    edges = graph.edges

    # Set variable names for lengths
    m_linear = len(nodes)  # Number of linear biases
    m_quadratic = len(edges)  # Number of quadratic biases
    n_noted = len(table)  # Number of spin combinations specified in the table
    n_unnoted = 2**m_linear - n_noted  # Number of spin combinations that were not specified

    # Linear programming matrix for spin states specified by 'table'
    noted_states = table.keys() if isinstance(table, dict) else table
    noted_states = list(noted_states)
    noted_matrix = _get_lp_matrix(np.asarray(noted_states), nodes, edges, 1, 0)

    # Linear programming matrix for spins states that were not specified by 'table'
    spin_states = product([-1, 1],
                          repeat=m_linear) if m_linear > 1 else [-1, 1]
    unnoted_states = [
        state for state in spin_states if state not in noted_states
    ]
    unnoted_matrix = _get_lp_matrix(np.asarray(unnoted_states), nodes, edges,
                                    1, -1)
    if unnoted_matrix is not None:
        unnoted_matrix *= -1  # Taking negative in order to flip the inequality

    # Constraints
    if isinstance(table, dict):
        noted_bound = np.asarray([table[state] for state in noted_states])
        unnoted_bound = np.full(
            (n_unnoted, 1),
            -1 * max(table.values()))  # -1 for flipped inequality
    else:
        noted_bound = np.zeros((n_noted, 1))
        unnoted_bound = np.zeros((n_unnoted, 1))

    # Bounds
    linear_range = (MIN_LINEAR_BIAS, MAX_LINEAR_BIAS)
    quadratic_range = (MIN_QUADRATIC_BIAS, MAX_QUADRATIC_BIAS)

    bounds = [linear_energy_ranges.get(node, linear_range) for node in nodes]
    bounds += [
        get_item(quadratic_energy_ranges, edge, quadratic_range)
        for edge in edges
    ]

    # Note: Since ising has {-1, 1}, the largest possible gap is [-largest_bias, largest_bias],
    #   hence that 2 * sum(largest_biases)
    max_gap = 2 * sum(
        max(abs(lbound), abs(ubound)) for lbound, ubound in bounds)
    bounds.append((None, None))  # Bound for offset
    bounds.append((min_classical_gap, max_gap))  # Bound for gap.

    # Cost function
    cost_weights = np.zeros((1, m_linear + m_quadratic + 2))
    cost_weights[0, -1] = -1  # Only interested in maximizing the gap

    # Returns a Scipy OptimizeResult
    result = linprog(cost_weights.flatten(),
                     A_eq=noted_matrix,
                     b_eq=noted_bound,
                     A_ub=unnoted_matrix,
                     b_ub=unnoted_bound,
                     bounds=bounds)

    #TODO: propagate scipy.optimize.linprog's error message?
    if not result.success:
        raise ValueError('Penaltymodel-lp is unable to find a solution.')

    # Split result
    x = result.x
    h = x[:m_linear]
    j = x[m_linear:-2]
    offset = x[-2]
    gap = x[-1]

    if gap <= 0:
        raise ValueError('Penaltymodel-lp is unable to find a solution.')

    # Create BQM
    bqm = dimod.BinaryQuadraticModel.empty(dimod.SPIN)
    bqm.add_variables_from((v, bias) for v, bias in zip(nodes, h))
    bqm.add_interactions_from((u, v, bias) for (u, v), bias in zip(edges, j))
    bqm.add_offset(offset)

    return bqm, gap
Exemple #56
0
	outstr=''
	for i_x in range(len(A_ub[1])):
		if A_ub[i][i_x]>0:
			if A_ub[i][i_x]>1:
				outstr+='+'+str(A_ub[i][i_x])+'*x'+str(i_x)
			else:
				outstr+='+x'+str(i_x)
	outstr+='<='+str(b_ub[i])
	print(outstr)
	outstr=''


# Преобразование в каноническую форму
# Формирование симплексной таблицы
# Вычисление симплекс методом
res = linprog(c, A_ub, b_ub)


# Вывод результатов
result=res['x']
value_f=0
for i,e in enumerate(result):
	result[i]=round(e,2)
	# if i==7 or i==8:
	# 	result[7]=201
	# 	result[8]=49
	value_f+=result[i]*c[i]
print('\nОптимальное решение:\nx={0}'.format(result))
print ('\nЗначение целевой функции:\nf(x)={0}'.format(-value_f))
input()
Exemple #57
0
from scipy.optimize import linprog
import numpy

A = [[2, 1, -9000], [1, 1, -5500], [1, 2.5, -10000], [-1, 0, 100],
     [0, -1, 100], [36.8, 65.7, 1], [-36.8, -65.7, -1]]
b = [0, 0, 0, 0, 0, 1, -1]
c = [150, 130, 0]

c = numpy.negative(c)

res = linprog(c, A, b, options={"disp": True}).x
print(res)

x1 = res[0] / res[2]
print("A:", x1)

x2 = res[1] / res[2]
print("B:", x2)
import numpy as np
import scipy
from scipy.optimize import linprog
from pytest import approx

from simplex_networks_profile import create_matrix, pivots_col, pivots_row, find_negative_col, find_negative_row, find_pivot_col, find_pivot_row, pivot
from problem_definition_profile import add_cons, constrain, add_obj, obj, maxz, minz

if __name__ == "__main__":
    # Definimos y resolvemos problema con scipy
    c_min_obj = [-1, -3]
    A_min_obj = [[1, 1], [-1, 2]]
    b_min_obj = [6, 8]
    min_obj = linprog(c_min_obj, A_ub=A_min_obj, b_ub=b_min_obj).fun
    coeff_obj = linprog(c_min_obj, A_ub=A_min_obj, b_ub=b_min_obj).x

    # Definimos y resolvemos problema con nuestro paquete
    n_var_approx = 2
    n_cons_approx = 2
    matrix_min_approx = create_matrix(n_var_approx, n_cons_approx)
    constrain(matrix_min_approx, '1,1,L,6')
    constrain(matrix_min_approx, '-1,2,L,8')
    obj(matrix_min_approx, '-1,-3,0')
    problem_approx = minz(matrix_min_approx)
    min_approx = problem_approx['min']
    problem_approx.pop('min')
    coeff_approx = np.array(list(problem_approx.values()))
    assert min_approx == approx(min_obj)
    assert coeff_obj == approx(coeff_approx)
def getMaxOverPartitions(A, b, x_bounds, perSubsetSensitivities):
    #print(perSubsetSensitivities)
    c = [-x for x in perSubsetSensitivities]
    res = linprog(c, A_ub=A, b_ub=b, bounds=x_bounds)
    # find the highly sensitive partition
    return -res.fun, res.x
Exemple #60
0
    #restricciones.append(ecuacion(1, 1, '>=', 800, x_vals))
    #restricciones.append(ecuacion(0.21, -0.3, '<=', 0, x_vals))
    #restricciones.append(ecuacion(0.03, -0.01, '>=', 0, x_vals))

    for r in restricciones:
        print(r.type_ec)
        if r.type_ec == 'ub':
            A_ub.append(r.X)
            b_ub.append(r.result)
        else:
            A_eq.append(r.X)
            b_eq.append(r.result)

    if (len(A_eq) != 0) and (len(A_ub) != 0):
        print("Hay equidades y mayor/menor")
        res = linprog(c.X, A_ub, b_ub, A_eq, b_eq, bounds=(0, None))
        print(c.X, A_ub, b_ub, A_eq, b_eq)
        print(res)
        print("Valor óptimo: ", np.absolute(res.fun), "\nX: ", res.x)
    elif (len(A_ub) != 0):
        print("No hay equidades")
        res = linprog(c.X, A_ub, b_ub, bounds=(0, None))
        print(c.X, A_ub, b_ub)
        print(res)
        print("Valor óptimo: ", np.absolute(res.fun), "\nX: ", res.x)
    elif (len(A_eq) != 0):
        print("No hay equidades")
        res = linprog(c.X, A_eq=A_eq, b_eq=b_eq, bounds=(0, None))
        print(c.X, A_eq, b_eq)
        print(res)
        print("Valor óptimo: ", np.absolute(res.fun), "\nX: ", res.x)