コード例 #1
0
 def test_solver_not_found(self):
     """
     Check that SolverNotFound is raised when the solver does not exist.
     """
     c, G, h = self.get_small_problem()
     with self.assertRaises(SolverNotFound):
         solve_lp(c, G, h, solver="ideal")
コード例 #2
0
 def test(self):
     c, G, h = self.get_small_problem()
     x = solve_lp(c, G, h, solver=solver)
     x_sp = solve_lp(c, G, h, solver=solver)
     self.assertIsNotNone(x)
     self.assertIsNotNone(x_sp)
     known_solution = np.array([2.2, -0.8, -3.4])
     sol_tolerance = 1e-8
     ineq_tolerance = 1e-10
     self.assertLess(np.linalg.norm(x - known_solution), sol_tolerance)
     self.assertLess(np.linalg.norm(x_sp - known_solution),
                     sol_tolerance)
     self.assertLess(max(np.dot(G, x) - h), ineq_tolerance)
コード例 #3
0
 def lp_train(self):
     """
     Function which calculates linear solution to problem described as:
     Px
     s.t; Gx < h
     :return: None
     """
     filterwarnings('ignore')
     max_lr = self.lr
     epochs = 0
     self.save_parameters()
     for epoch in range(self.max_iterations):
         loss = self.loss_function()
         self.loss_history.append(loss)
         print(loss)
         d, n = len(self.weights), len(
             self.training_bags)  # basic dimensions
         c = np.r_[np.zeros(d + 2 * self.k + 1, dtype=np.float16),
                   np.ones(n + d, dtype=np.float16)]
         A = self.a_matrix()  # creates G matrix
         b = np.r_[-np.ones(n), np.zeros(n + 2 * d)]  # creates h matrix
         A = A.astype('float64')
         c = c.astype('float64')
         b = b.astype('float64')
         try:
             sol = solve_lp(c, A, b)
             if loss <= min(self.loss_history):
                 self.save_parameters()
             self.get_solution(sol)  # applies solution for new weights
         except ValueError:
             print('Infeasable solution')
             break
         if loss < 1:
             break
     self.load_parameters()
コード例 #4
0
    def ExactOmega(midA, radA, b, Q):
        S = np.eye(m) * np.insert(np.sign(Q.a), _nu, np.sign(V[_nu].a))
        midAS = midA @ S

        p[:m] = np.insert(-Q.a, _nu, 1e15)
        p[m:] = np.insert(Q.b, _nu, 1e15)

        c = np.zeros(m, dtype='float64')
        c[_nu] = S[_nu, _nu]

        A_ub[:n] = midAS - radA
        A_ub[n:2 * n] = -midAS - radA
        A_ub[2 * n:2 * n + m] = -S
        A_ub[2 * n + m:2 * (n + m)] = S

        b_ub[:n] = b.b
        b_ub[n:2 * n] = -b.a
        b_ub[2 * n:2 * (n + m)] = p

        try:
            result = solve_lp(c, A_ub, b_ub)
            return result @ c
        except:
            pass

        S[_nu, _nu] = np.sign(V[_nu].b)
        midAS = midA @ S

        c[_nu] = S[_nu, _nu]
        A_ub[:n] = midAS - radA
        A_ub[n:2 * n] = -midAS - radA
        A_ub[2 * n:2 * n + m] = -S
        A_ub[2 * n + m:2 * (n + m)] = S

        try:
            result = solve_lp(c, A_ub, b_ub)
            return result @ c
        except:
            return 10**15
コード例 #5
0
    def _update_LP_sol(self):
        """
        Update the solution `d_S` of the linear program for the SOC policy. The solution is then
        cached in attribute `lp_d_S` along with the corresponding indices `lp_d_S_idx` of
        susceptible individuals.

        Note: To speed up convergence of the linear program optimization, we use the Epigraph
        trick and transform the equality contraint into an inequality.
        """

        # find subarrays
        x_S = np.where(self.is_sus)[0]  # Indices of susceptible individuals
        x_I = np.where(
            self.is_inf)[0]  # Indices of infected/recovered individuals
        len_S = x_S.shape[0]
        len_I = x_I.shape[0]
        A_IS = self.A[np.ix_(x_I, x_S)]

        K3 = self.eta * (self.gamma * (self.delta + self.eta) + self.beta *
                         (self.delta + self.rho))
        K4 = self.beta * (self.delta + self.rho) * self.q_x

        # objective: c^T x
        c = np.hstack((np.ones(len_I), np.zeros(len_S)))

        # inequality: Ax <= b
        A_ineq = sp.sparse.hstack(
            [sp.sparse.csr_matrix((len_I, len_I)), -A_IS])

        # equality: Ax = b
        A_eq = sp.sparse.hstack([-sp.sparse.eye(len_I), A_IS])

        A = sp.sparse.vstack([A_ineq, A_eq])

        b = np.hstack([
            K4 / K3 * np.ones(len_I) - 1e-8,  # b_ineq
            -K4 / K3 * np.ones(len_I) + 1e-8  # b_eq
        ])

        bounds = tuple([(0.0, None)] * len_I + [(None, None)] * len_S)

        if self.lpsolver == 'scipy':

            result = scipy.optimize.linprog(c,
                                            A_ub=A,
                                            b_ub=b,
                                            bounds=bounds,
                                            method="interior-point",
                                            options={'tol': 1e-8})

            if result['success']:
                d_S = result['x'][len_I:]
            else:
                raise Exception("LP couldn't be solved.")

        elif self.lpsolver == 'cvxopt':

            A_dense = A.toarray()
            res = solve_lp(c, A_dense, b, None, None)
            d_S = res[len_I:]

        else:
            raise KeyError('Invalid LP Solver.')

        # store LP solution
        self.lp_d_S = d_S
        self.lp_d_S_idx = x_S
コード例 #6
0
ファイル: eq_problems.py プロジェクト: robodreamer/lpsolvers
# lpsolvers is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# lpsolvers is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with lpsolvers. If not, see <http://www.gnu.org/licenses/>.

from lpsolvers import available_solvers, solve_lp
from numpy import array

problems = []

c = array([1., 2., 3.])
G = array([[1., 2., -1.], [2., 0., 1.], [1., 2., 1.], [-1., -1., -1.]])
h = array([4., 1., 3., 2.])
A = array([[2., 0., 0.], [0., 0., 1.]])
b = array([1., 0.])
problems.append((c, G, h, A, b))

if __name__ == "__main__":
    for i, (c, G, h, A, b) in enumerate(problems):
        for solver in available_solvers:
            x = solve_lp(c, G, h, A, b, solver=solver)
            print "LP %d for %6s:" % (i, solver), x
コード例 #7
0
# later version.
#
# lpsolvers is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with lpsolvers. If not, see <http://www.gnu.org/licenses/>.

from lpsolvers import available_solvers, solve_lp
from numpy import array, ones, eye, zeros

problems = []

c = -ones(10)
G = eye(10)
h = zeros(10)
problems.append((c, G, h))

c = array([1., 2., 3.])
G = array([[1., 2., -1.], [2., 0., 1.], [1., 2., 1.], [-1., -1., -1.]])
h = array([4., 1., 3., 2.])
problems.append((c, G, h))

if __name__ == "__main__":
    for i, (c, G, h) in enumerate(problems):
        for solver in available_solvers:
            x = solve_lp(c, G, h, solver=solver)
            print("LP %d for %6s:" % (i, solver), x)
コード例 #8
0
 def test(self):
     c, G, h = self.get_small_problem()
     G[1] *= -1.0  # makes problem unfeasible
     with self.assertRaises(ValueError):
         solve_lp(c, G, h, solver=solver)
コード例 #9
0
 def test(self):
     c, G, h = self.get_small_problem()
     G, h = G[1], h[1].reshape((1, ))
     with self.assertRaises(ValueError):
         solve_lp(c, G, h, solver=solver)