Ejemplo n.º 1
0
 def test_mul_funcs(self):
     """Test functions to multiply by A, A.T
     """
     n = 10
     x = Variable(n)
     obj = Minimize(norm(x, 1))
     constraints = [x >= 2]
     prob = Problem(obj, constraints)
     data, dims = prob.get_problem_data(solver=SCS)
     A = data["A"]
     objective, constraints = prob.canonicalize()
     sym_data = SymData(objective, constraints, SOLVERS[SCS])
     sym_data.constraints = prune_constants(sym_data.constraints)
     Amul, ATmul = iterative.get_mul_funcs(sym_data)
     vec = np.array(range(sym_data.x_length))
     # A*vec
     result = np.zeros(A.shape[0])
     Amul(vec, result)
     self.assertItemsAlmostEqual(A * vec, result)
     Amul(vec, result)
     self.assertItemsAlmostEqual(2 * A * vec, result)
     # A.T*vec
     vec = np.array(range(A.shape[0]))
     result = np.zeros(A.shape[1])
     ATmul(vec, result)
     self.assertItemsAlmostEqual(A.T * vec, result)
     ATmul(vec, result)
     self.assertItemsAlmostEqual(2 * A.T * vec, result)
Ejemplo n.º 2
0
 def test_mul_funcs(self):
     """Test functions to multiply by A, A.T
     """
     n = 10
     x = Variable(n)
     obj = Minimize(norm(x, 1))
     constraints = [x >= 2]
     prob = Problem(obj, constraints)
     data = prob.get_problem_data(solver=SCS)
     A = data["A"]
     objective, constraints = prob.canonicalize()
     sym_data = SymData(objective, constraints, SOLVERS[SCS])
     sym_data.constraints = prune_constants(sym_data.constraints)
     Amul, ATmul = iterative.get_mul_funcs(sym_data)
     vec = np.array(range(sym_data.x_length))
     # A*vec
     result = np.zeros(A.shape[0])
     Amul(vec, result)
     self.assertItemsAlmostEqual(A * vec, result)
     Amul(vec, result)
     self.assertItemsAlmostEqual(2 * A * vec, result)
     # A.T*vec
     vec = np.array(range(A.shape[0]))
     result = np.zeros(A.shape[1])
     ATmul(vec, result)
     self.assertItemsAlmostEqual(A.T * vec, result)
     ATmul(vec, result)
     self.assertItemsAlmostEqual(2 * A.T * vec, result)
Ejemplo n.º 3
0
    def choose_solver(constraints):
        """Determines the appropriate solver.

        Parameters
        ----------
        constraints: list
            The list of canonicalized constraints.

        Returns
        -------
        str
            The solver that will be used.
        """
        constr_map = SymData.filter_constraints(constraints)
        # If no constraints, use ECOS.
        if len(constraints) == 0:
            return s.ECOS
        # If mixed integer constraints, use ECOS_BB.
        elif constr_map[s.BOOL] or constr_map[s.INT]:
            return s.ECOS_BB
        # If SDP, defaults to CVXOPT.
        elif constr_map[s.SDP]:
            return s.CVXOPT
        # Otherwise use ECOS.
        else:
            return s.ECOS
Ejemplo n.º 4
0
    def choose_solver(constraints):
        """Determines the appropriate solver.

        Parameters
        ----------
        constraints: list
            The list of canonicalized constraints.

        Returns
        -------
        str
            The solver that will be used.
        """
        constr_map = SymData.filter_constraints(constraints)
        # If no constraints, use ECOS.
        if len(constraints) == 0:
            return s.ECOS
        # If mixed integer constraints, use ECOS_BB.
        elif constr_map[s.BOOL] or constr_map[s.INT]:
            return s.ECOS_BB
        # If SDP or EXP, defaults to CVXOPT.
        elif constr_map[s.SDP] or constr_map[s.EXP]:
            return s.CVXOPT
        # Otherwise use ECOS.
        else:
            return s.ECOS
Ejemplo n.º 5
0
    def __init__(self, cvx_problem):
        objective, constraints = cvx_problem.canonicalize()
        self.sym_data = SymData(objective, constraints, SOLVERS[s.SCS])

        # sort variables by offset
        self.var_ids = [
            var_id for var_id, var_offset in sorted(
                self.sym_data.var_offsets.items(),
                key=lambda var_id, var_offset: var_offset)
        ]
        self.constraints = (self.sym_data.constr_map[s.EQ] +
                            self.sym_data.constr_map[s.LEQ])

        self.A_exprs, self.b = get_constraint_tensors(self.constraints)
        self.c = get_objective_tensor(self.var_ids, self.sym_data)
Ejemplo n.º 6
0
    def validate_solver(self, constraints):
        """Raises an exception if the solver cannot solve the problem.

        Parameters
        ----------
        constraints: list
            The list of canonicalized constraints.
        """
        constr_map = SymData.filter_constraints(constraints)
        if (constr_map[s.SDP] and not self.sdp_capable()) or \
           (constr_map[s.EXP] and not self.exp_capable()) or \
           (len(constraints) == 0 and self.name() == s.SCS):
            raise SolverError(
                "The solver %s cannot solve the problem." % self.name()
            )
Ejemplo n.º 7
0
    def __init__(self, objective, constraints, vars, params, solver=None):
        if vars == []:
            raise TypeError("Problem has no variables.")

        if solver == None:
            solver = 'ecos'
        elif not (solver in SOLVER_INTFS.keys):
            raise TypeError("Unknown solver %s." % str(solver))
        self.solver = SOLVER_INTFS[solver]()

        self.objective = objective
        self.constraints = constraints
        self.sym_data = SymData(self.objective, self.constraints, self.solver.CVXPY_SOLVER)
        self.named_vars = self.get_named_vars(vars)
        self.params = self.get_named_params(params)

        # TODO rm params, so all params hanlded by the param_handler:
        self.template_vars = {'named_vars' : self.named_vars,
                              'params' : self.params,
                              'cprint_var' : cprint_var}
Ejemplo n.º 8
0
    def get_sym_data(self, objective, constraints, cached_data):
        """Returns the symbolic data for the problem.

        Parameters
        ----------
        objective : LinOp
            The canonicalized objective.
        constraints : list
            The list of canonicalized constraints.
        cached_data : dict
            A map of solver name to cached problem data.

        Returns
        -------
        SymData
            The symbolic data for the problem.
        """
        prob_data = cached_data[self.name()]
        if prob_data.sym_data is None:
            prob_data.sym_data = SymData(objective, constraints, self)
        return prob_data.sym_data
Ejemplo n.º 9
0
    def validate_solver(self, constraints):
        """Raises an exception if the solver cannot solve the problem.

        Parameters
        ----------
        constraints: list
            The list of canonicalized constraints.
        """
        # Check the solver is installed.
        if not self.is_installed():
            raise SolverError("The solver %s is not installed." % self.name())
        # Check the solver can solve the problem.
        constr_map = SymData.filter_constraints(constraints)
        if ((constr_map[s.BOOL] or constr_map[s.INT]) \
            and not self.MIP_CAPABLE) or \
           (constr_map[s.SDP] and not self.SDP_CAPABLE) or \
           (constr_map[s.EXP] and not self.EXP_CAPABLE) or \
           (constr_map[s.SOC] and not self.SOCP_CAPABLE) or \
           (len(constraints) == 0 and self.name() in [s.SCS,
                                                      s.GLPK]):
            raise SolverError("The solver %s cannot solve the problem." %
                              self.name())
Ejemplo n.º 10
0
    def test_consistency(self):
        """Test that variables and constraints keep a consistent order.
        """
        import itertools
        num_solves = 4
        vars_lists = []
        ineqs_lists = []
        var_ids_order_created = []
        for k in range(num_solves):
            sum = 0
            constraints = []
            var_ids = []
            for i in range(100):
                var = Variable(name=str(i))
                var_ids.append(var.id)
                sum += var
                constraints.append(var >= i)
            var_ids_order_created.append(var_ids)
            obj = Minimize(sum)
            p = Problem(obj, constraints)
            objective, constraints = p.canonicalize()
            sym_data = SymData(objective, constraints, SOLVERS[s.ECOS])
            # Sort by offset.
            vars_ = sorted(sym_data.var_offsets.items(),
                key=lambda key_val: key_val[1])
            vars_ = [var_id for (var_id, offset) in vars_]
            vars_lists.append(vars_)
            ineqs_lists.append(sym_data.constr_map[s.LEQ])

        # Verify order of variables is consistent.
        for i in range(num_solves):
            self.assertEqual(var_ids_order_created[i],
                vars_lists[i])
        for i in range(num_solves):
            for idx, constr in enumerate(ineqs_lists[i]):
                var_id, _ = lu.get_expr_vars(constr.expr)[0]
                self.assertEqual(var_ids_order_created[i][idx],
                    var_id)
Ejemplo n.º 11
0
    def validate_solver(self, constraints):
        """Raises an exception if the solver cannot solve the problem.

        Parameters
        ----------
        constraints: list
            The list of canonicalized constraints.
        """
        # Check the solver is installed.
        if not self.is_installed():
            raise SolverError("The solver %s is not installed." % self.name())
        # Check the solver can solve the problem.
        constr_map = SymData.filter_constraints(constraints)
        if ((constr_map[s.BOOL] or constr_map[s.INT]) \
            and not self.MIP_CAPABLE) or \
           (constr_map[s.SDP] and not self.SDP_CAPABLE) or \
           (constr_map[s.EXP] and not self.EXP_CAPABLE) or \
           (constr_map[s.SOC] and not self.SOCP_CAPABLE) or \
           (len(constraints) == 0 and self.name() in [s.SCS,
                                                      s.GLPK]):
            raise SolverError(
                "The solver %s cannot solve the problem." % self.name()
            )
Ejemplo n.º 12
0
    def validate_solver(self, constraints):
        """Raises an exception if the solver cannot solve the problem.

        Parameters
        ----------
        constraints: list
            The list of canonicalized constraints.
        """
        # Check the solver is installed.
        if not self.is_installed():
            raise SolverError("The solver %s is not installed." % self.name())
        # Check the solver can solve the problem.
        constr_map = SymData.filter_constraints(constraints)

        if (constr_map[s.BOOL] or constr_map[s.INT]) and not self.MIP_CAPABLE:
            self._reject_problem("it cannot solve mixed-integer problems")
        elif constr_map[s.SDP] and not self.SDP_CAPABLE:
            self._reject_problem("it cannot solve semidefinite problems")
        elif constr_map[s.EXP] and not self.EXP_CAPABLE:
            self._reject_problem("it cannot solve exponential cone problems")
        elif constr_map[s.SOC] and not self.SOCP_CAPABLE:
            self._reject_problem("it cannot solve second-order cone problems")
        elif len(constraints) == 0 and self.name() in (s.SCS, s.GLPK):
            self._reject_problem("it cannot solve unconstrained problems")
Ejemplo n.º 13
0
    def validate_solver(self, constraints):
        """Raises an exception if the solver cannot solve the problem.

        Parameters
        ----------
        constraints: list
            The list of canonicalized constraints.
        """
        # Check the solver is installed.
        if not self.is_installed():
            raise SolverError("The solver %s is not installed." % self.name())
        # Check the solver can solve the problem.
        constr_map = SymData.filter_constraints(constraints)

        if (constr_map[s.BOOL] or constr_map[s.INT]) and not self.MIP_CAPABLE:
            self._reject_problem("it cannot solve mixed-integer problems")
        elif constr_map[s.SDP] and not self.SDP_CAPABLE:
            self._reject_problem("it cannot solve semidefinite problems")
        elif constr_map[s.EXP] and not self.EXP_CAPABLE:
            self._reject_problem("it cannot solve exponential cone problems")
        elif constr_map[s.SOC] and not self.SOCP_CAPABLE:
            self._reject_problem("it cannot solve second-order cone problems")
        elif len(constraints) == 0 and self.name() in (s.SCS, s.GLPK):
            self._reject_problem("it cannot solve unconstrained problems")
Ejemplo n.º 14
0
 def test(self):
     objective, constraints = self.canonicalize()
     sym_data = SymData(objective, constraints, SOLVERS[s.ECOS])
     return (len(sym_data.constr_map[s.EQ]),
             len(sym_data.constr_map[s.LEQ]))