示例#1
0
 def test_sdp(self):
     """Test a problem with semidefinite cones.
     """
     a = sp.rand(100, 100, .1, random_state=1)
     a = a.todense()
     X = Variable(100, 100)
     obj = at.norm(X, "nuc") + at.norm(X - a, 'fro')
     p = Problem(Minimize(obj))
     p.solve(solver="SCS")
示例#2
0
 def test_sdp(self):
     """Test a problem with semidefinite cones.
     """
     a = sp.rand(100,100,.1, random_state=1)
     a = a.todense()
     X = Variable(100,100)
     obj = at.norm(X, "nuc") + at.norm(X-a,'fro')
     p = Problem(Minimize(obj))
     p.solve(solver="SCS")
示例#3
0
 def test_sdp(self) -> None:
     """Test a problem with semidefinite cones.
     """
     self.skipTest("Too slow.")
     a = sp.rand(100, 100, .1, random_state=1)
     a = a.todense()
     X = Variable((100, 100))
     obj = at.norm(X, "nuc") + at.norm(X - a, 'fro')
     p = Problem(cp.Minimize(obj))
     p.solve(solver="SCS")
示例#4
0
    def test_sum_squares(self):
        X = Variable(5, 4)
        P = np.asmatrix(np.random.randn(3, 5))
        Q = np.asmatrix(np.random.randn(4, 7))
        M = np.asmatrix(np.random.randn(3, 7))

        y = P*X*Q + M
        self.assertFalse(y.is_constant())
        self.assertTrue(y.is_affine())
        self.assertTrue(y.is_quadratic())
        self.assertTrue(y.is_dcp())

        s = sum_squares(y)
        self.assertFalse(s.is_constant())
        self.assertFalse(s.is_affine())
        self.assertTrue(s.is_quadratic())
        self.assertTrue(s.is_dcp())

        # Frobenius norm squared is indeed quadratic
        # but can't show quadraticity using recursive rules
        t = norm(y, 'fro')**2
        self.assertFalse(t.is_constant())
        self.assertFalse(t.is_affine())
        self.assertFalse(t.is_quadratic())
        self.assertTrue(t.is_dcp())
示例#5
0
    def test_sum_squares(self):
        X = Variable(5, 4)
        P = np.asmatrix(np.random.randn(3, 5))
        Q = np.asmatrix(np.random.randn(4, 7))
        M = np.asmatrix(np.random.randn(3, 7))

        y = P*X*Q + M
        self.assertFalse(y.is_constant())
        self.assertTrue(y.is_affine())
        self.assertTrue(y.is_quadratic())
        self.assertTrue(y.is_dcp())

        s = sum_squares(y)
        self.assertFalse(s.is_constant())
        self.assertFalse(s.is_affine())
        self.assertTrue(s.is_quadratic())
        self.assertTrue(s.is_dcp())

        # Frobenius norm squared is indeed quadratic
        # but can't show quadraticity using recursive rules
        t = norm(y, 'fro')**2
        self.assertFalse(t.is_constant())
        self.assertFalse(t.is_affine())
        self.assertFalse(t.is_quadratic())
        self.assertTrue(t.is_dcp())
示例#6
0
    def test_gurobi_environment(self) -> None:
        """Tests that Gurobi environments can be passed to Model.
        Gurobi environments can include licensing and model parameter data.
        """
        from cvxpy import GUROBI
        if GUROBI in INSTALLED_SOLVERS:
            import gurobipy

            # Set a few parameters to random values close to their defaults
            params = {
                'MIPGap': np.random.random(),  # range {0, INFINITY}
                'AggFill': np.random.randint(10),  # range {-1, MAXINT}
                'PerturbValue': np.random.random(),  # range: {0, INFINITY}
            }

            # Create a custom environment and set some parameters
            custom_env = gurobipy.Env()
            for k, v in params.items():
                custom_env.setParam(k, v)

            # Testing QP Solver Interface
            sth = StandardTestLPs.test_lp_0(solver='GUROBI', env=custom_env)
            model = sth.prob.solver_stats.extra_stats
            for k, v in params.items():
                # https://www.gurobi.com/documentation/9.1/refman/py_model_getparaminfo.html
                name, p_type, p_val, p_min, p_max, p_def = model.getParamInfo(
                    k)
                self.assertEqual(v, p_val)

        else:
            with self.assertRaises(Exception) as cm:
                prob = Problem(Minimize(norm(self.x, 1)), [self.x == 0])
                prob.solve(solver=GUROBI, TimeLimit=0)
            self.assertEqual(str(cm.exception),
                             "The solver %s is not installed." % GUROBI)
示例#7
0
 def mat_norm_2(self, solver):
     A = np.random.randn(5, 3)
     B = np.random.randn(5, 2)
     p = Problem(Minimize(norm(A @ self.C - B, 2)))
     s = self.solve_QP(p, solver)
     for var in p.variables():
         self.assertItemsAlmostEqual(lstsq(A, B)[0],
                                     s.primal_vars[var.id], places=1)
示例#8
0
 def norm_2(self, solver):
     A = np.random.randn(10, 5)
     b = np.random.randn(10)
     p = Problem(Minimize(norm(A @ self.w - b, 2)))
     self.solve_QP(p, solver)
     for var in p.variables():
         self.assertItemsAlmostEqual(lstsq(A, b)[0].flatten(), var.value,
                                     places=1)
示例#9
0
 def norm_2(self, solver):
     A = numpy.random.randn(10, 5)
     b = numpy.random.randn(10, 1)
     p = Problem(Minimize(norm(A * self.w - b, 2)))
     s = self.solve_QP(p, solver)
     for var in p.variables():
         self.assertItemsAlmostEqual(lstsq(A, b)[0].flatten(),
                                     s.primal_vars[var.id],
                                     places=1)
示例#10
0
    def test_gurobi_time_limit_no_solution(self) -> None:
        """Make sure that if Gurobi terminates due to a time limit before finding a solution:
            1) no error is raised,
            2) solver stats are returned.
            The test is skipped if something changes on Gurobi's side so that:
            - a solution is found despite a time limit of zero,
            - a different termination criteria is hit first.
        """
        from cvxpy import GUROBI
        if GUROBI in INSTALLED_SOLVERS:
            import gurobipy
            objective = Minimize(self.x[0])
            constraints = [self.x[0] >= 1]
            prob = Problem(objective, constraints)
            try:
                prob.solve(solver=GUROBI, TimeLimit=0.0)
            except Exception as e:
                self.fail(
                    "An exception %s is raised instead of returning a result."
                    % e)

            extra_stats = None
            solver_stats = getattr(prob, "solver_stats", None)
            if solver_stats:
                extra_stats = getattr(solver_stats, "extra_stats", None)
            self.assertTrue(extra_stats,
                            "Solver stats have not been returned.")

            nb_solutions = getattr(extra_stats, "SolCount", None)
            if nb_solutions:
                self.skipTest(
                    "Gurobi has found a solution, the test is not relevant anymore."
                )

            solver_status = getattr(extra_stats, "Status", None)
            if solver_status != gurobipy.StatusConstClass.TIME_LIMIT:
                self.skipTest(
                    "Gurobi terminated for a different reason than reaching time limit, "
                    "the test is not relevant anymore.")

        else:
            with self.assertRaises(Exception) as cm:
                prob = Problem(Minimize(norm(self.x, 1)), [self.x == 0])
                prob.solve(solver=GUROBI, TimeLimit=0)
            self.assertEqual(str(cm.exception),
                             "The solver %s is not installed." % GUROBI)
示例#11
0
    def optimize(self):

        self._pre_optimizer.optimize()
        self._pre_optimizer.update()

        points = self.graph.free_points
        landmarks = self.graph.landmarks

        num_points = len(points)
        point_dim = self.graph.point_dim
        num_landmarks = len(landmarks)
        landmark_dim = self.graph.landmark_dim

        transforms = [
            equivalence.SumMass(self.graph.correspondence_map.set_map()),
            equivalence.ExpDistance(self._sigma),
            equivalence.Facing()
        ]
        E, W = equivalence.equivalence_matrix(landmarks, transforms=transforms)
        if E.shape[0] == 0:
            self.M = self._pre_optimizer.M
            self.P = self._pre_optimizer.P
            self.res_d = self._pre_optimizer.res_d
            self.res_t = self._pre_optimizer.res_t
            self.equivalence_pairs = []
            return

        Am, Ap, d, sigma_d = self.graph.observation_system()
        Bp, t, sigma_t = self.graph.odometry_system()

        S_d, S_t = sp.sparse.diags(
            1 / _sanitized_noise_array(sigma_d)), sp.sparse.diags(
                1 / _sanitized_noise_array(sigma_t))

        M = cp.Variable((landmark_dim, num_landmarks))
        P = cp.Variable((point_dim, num_points))

        M.value = self._pre_optimizer.M
        P.value = self._pre_optimizer.P

        objective = cp.Minimize(mixed_norm(W * E * M.T))
        constraints = [
            norm((Am * vec(M)) +
                 (Ap * vec(P)) - d) <= 2 * np.linalg.norm(sigma_d + 1e-6),
            norm((Bp * vec(P)) - t) <= 2 * np.linalg.norm(sigma_t + 1e-6)
        ]
        problem = cp.Problem(objective, constraints)
        problem.solve(verbose=self._verbosity,
                      solver=self._solver,
                      warm_start=True)

        if problem.solution.status == 'infeasible':
            self.M = self._pre_optimizer.M
            self.P = self._pre_optimizer.P
            self.res_d = self._pre_optimizer.res_d
            self.res_t = self._pre_optimizer.res_t
            self.equivalence_pairs = []
            return

        E_ = E[np.abs(np.linalg.norm(E * M.value.T, axis=1)) < 0.001, :]
        objective = cp.Minimize(
            sum_squares(S_d * ((Am * vec(M)) + (Ap * vec(P)) - d)) +
            sum_squares(S_t * ((Bp * vec(P)) - t)))
        constraints = [E_ * M.T == 0] if E_.shape[0] > 0 else []
        problem = cp.Problem(objective, constraints)
        problem.solve(verbose=self._verbosity,
                      solver=self._solver,
                      warm_start=True)

        self.M = M.value
        self.P = P.value

        m = self.M.ravel(order='F')
        p = self.P.ravel(order='F')

        self.res_d = Am.dot(m) + Ap.dot(p) - d
        self.res_t = Bp.dot(p) - t

        self.equivalence_pairs = [(landmarks[i], landmarks[j])
                                  for (i, j) in E_.tolil().rows]