def to_quadratic_program(self) -> QuadraticProgram:
        """Convert a portfolio diversification problem instance into a
        :class:`~qiskit_optimization.problems.QuadraticProgram`.

        Returns:
            The :class:`~qiskit_optimization.problems.QuadraticProgram` created
            from the portfolio diversification problem instance.
        """
        mdl = AdvModel(name='Portfolio diversification')
        x = {(i, j): mdl.binary_var(name='x_{0}_{1}'.format(i, j))
             for i in range(self._num_assets) for j in range(self._num_assets)}
        y = {
            i: mdl.binary_var(name='y_{0}'.format(i))
            for i in range(self._num_assets)
        }
        mdl.maximize(
            mdl.sum(self._similarity_matrix[i, j] * x[(i, j)]
                    for i in range(self._num_assets)
                    for j in range(self._num_assets)))
        mdl.add_constraint(
            mdl.sum(y[j]
                    for j in range(self._num_assets)) == self._num_clusters)
        for i in range(self._num_assets):
            mdl.add_constraint(
                mdl.sum(x[(i, j)] for j in range(self._num_assets)) == 1)
        for j in range(self._num_assets):
            mdl.add_constraint(x[(j, j)] == y[j])
        for i in range(self._num_assets):
            for j in range(self._num_assets):
                mdl.add_constraint(x[(i, j)] <= y[j])
        op = QuadraticProgram()
        op.from_docplex(mdl)
        return op
Ejemplo n.º 2
0
    def _transform_from_numpy(self, X, y, var_lbs, var_ubs,
                              **transform_params):
        # matrix is nrows x (ncols + 2)
        # last two columns are lbs, ubs in that order
        assert is_numpy_matrix(X)

        colnames = transform_params.get("colnames", None)
        mshape = X.shape
        xr, xc = mshape
        assert xc >= 2
        nb_vars = xc - 1
        X_cts = X[:, :-1]
        rhs = X[:, -1].A1
        with AdvModel(name='lp_transformer') as mdl:
            varlist = mdl.continuous_var_list(nb_vars,
                                              lb=var_lbs,
                                              ub=var_ubs,
                                              name=colnames)
            senses = transform_params.get('sense', 'le')
            mdl.add(mdl.matrix_constraints(X_cts, varlist, rhs, sense=senses))
            return self._solve_model(mdl,
                                     varlist,
                                     colnames,
                                     costs=y,
                                     **transform_params)
Ejemplo n.º 3
0
    def _transform_from_numpy(self, X, y, var_lbs, var_ubs,
                              **transform_params):
        # matrix is nrows x (ncols + 2)
        # last two columns are lbs, ubs in that order
        assert is_numpy_matrix(X)

        colnames = transform_params.pop("colnames", None)
        mshape = X.shape
        xr, xc = mshape
        assert xc >= 3
        nb_vars = xc - 2
        X_cts = X[:, :-2]
        row_mins = X[:, -2]
        row_maxs = X[:, -1]
        with AdvModel(name='lp_range_transformer') as mdl:
            varlist = mdl.continuous_var_list(nb_vars,
                                              lb=var_lbs,
                                              ub=var_ubs,
                                              name=colnames)
            mdl.add(mdl.matrix_ranges(X_cts, varlist, row_mins, row_maxs))
            return self._solve_model(mdl,
                                     varlist,
                                     colnames,
                                     costs=y,
                                     **transform_params)
Ejemplo n.º 4
0
    def _transform_from_scsparse(self, X, y, var_lbs, var_ubs,
                                 **transform_params):
        assert is_scipy_sparse(X)

        colnames = transform_params.get("colnames", None)
        mshape = X.shape
        nr, nc = mshape
        assert nc == nr + 1
        nb_vars = nc - 1
        with AdvModel(name='lp_transformer') as mdl:
            varlist = mdl.continuous_var_list(nb_vars, lb=var_lbs, ub=var_ubs)
            lfactory = mdl._lfactory
            r_rows = range(nr)
            exprs = [lfactory.linear_expr() for _ in r_rows]
            rhss = [0] * nr
            #  convert to coo before iterate()
            x_coo = X.tocoo()
            for coef, row, col in izip(x_coo.data, x_coo.row, x_coo.col):
                if col < nr:
                    exprs[row]._add_term(varlist[col], coef)
                else:
                    rhss[row] = coef
            senses = transform_params.get('sense', 'le')
            cts = [
                lfactory.new_binary_constraint(exprs[r],
                                               rhs=rhss[r],
                                               sense=senses) for r in r_rows
            ]
            lfactory._post_constraint_block(cts)
            return self._solve_model(mdl,
                                     varlist,
                                     colnames,
                                     costs=y,
                                     **transform_params)
Ejemplo n.º 5
0
 def build_matrix_range_model_and_solve(cls,
                                        var_count,
                                        var_lbs,
                                        var_ubs,
                                        var_types,
                                        var_names,
                                        cts_mat,
                                        range_mins,
                                        range_maxs,
                                        objsense,
                                        costs,
                                        cast_to_float,
                                        solution_maker=make_solution,
                                        **transform_params):
     with AdvModel(name='lpr_transformer') as mdl:
         varlist = mdl.continuous_var_list(var_count,
                                           lb=var_lbs,
                                           ub=var_ubs,
                                           name=var_names)
         mdl.add(mdl.matrix_ranges(cts_mat, varlist, range_mins,
                                   range_maxs))
         return cls._solve_model(mdl,
                                 varlist,
                                 var_names,
                                 objsense,
                                 costs=costs,
                                 solution_maker=solution_maker,
                                 **transform_params)
Ejemplo n.º 6
0
 def build_matrix_linear_model_and_solve(cls,
                                         var_count,
                                         var_lbs,
                                         var_ubs,
                                         var_types,
                                         var_names,
                                         cts_mat,
                                         rhs,
                                         objsense,
                                         costs,
                                         cast_to_float,
                                         solution_maker=make_solution,
                                         **transform_params):
     with AdvModel(name='lp_transformer') as mdl:
         varlist = mdl.continuous_var_list(var_count,
                                           lb=var_lbs,
                                           ub=var_ubs,
                                           name=var_names)
         sense = transform_params.get('sense', 'le')
         mdl.add(mdl.matrix_constraints(cts_mat, varlist, rhs, sense=sense))
         return cls._solve_model(mdl,
                                 varlist,
                                 var_names,
                                 objsense,
                                 costs=costs,
                                 solution_maker=solution_maker,
                                 **transform_params)
Ejemplo n.º 7
0
 def to_quadratic_program(self):
     num_assets = len(self._mu)
     mdl = AdvModel(name='portfolio')
     x = [mdl.binary_var(name='x_{0}'.format(i)) for i in range(num_assets)]
     quad = mdl.quad_matrix_sum(self._sigma, x)
     linear = np.dot(self._mu, x)
     mdl.minimize(quad + linear)
     mdl.add_constraint(mdl.sum(x[i] for i in range(num_assets)) == self._budget)
     qp = QuadraticProgram()
     qp.from_docplex(mdl)
     return qp
    def to_quadratic_program(self) -> QuadraticProgram:
        """Convert a portfolio optimization problem instance into a
        :class:`~qiskit_optimization.problems.QuadraticProgram`.

        Returns:
            The :class:`~qiskit_optimization.problems.QuadraticProgram` created
            from the portfolio optimization problem instance.
        """
        num_assets = len(self._expected_returns)
        mdl = AdvModel(name='Portfolio optimization')
        x = [mdl.binary_var(name='x_{0}'.format(i)) for i in range(num_assets)]
        quad = mdl.quad_matrix_sum(self._covariances, x)
        linear = np.dot(self._expected_returns, x)
        mdl.minimize(self._risk_factor * quad - linear)
        mdl.add_constraint(
            mdl.sum(x[i] for i in range(num_assets)) == self._budget)
        op = QuadraticProgram()
        op.from_docplex(mdl)
        return op
Ejemplo n.º 9
0
    def _transform_from_pandas(self, X, y, var_lbs, var_ubs,
                               **transform_params):
        assert is_pandas_dataframe(X)

        x_rows, x_cols = X.shape
        X_new = X.copy()
        # extract columns with name 'min' and 'max' as series then drop
        row_mins = X["min"].tolist()
        row_maxs = X["max"].tolist()
        X_new.drop(labels=["min", "max"], inplace=True, axis=1)

        with AdvModel(name='lp_range_trasnformer') as mdl:
            nb_vars = x_cols - 2
            varlist = mdl.continuous_var_list(nb_vars, lb=var_lbs, ub=var_ubs)
            mdl.add(mdl.matrix_ranges(X_new, varlist, row_mins, row_maxs))
            return self._solve_model(mdl,
                                     varlist,
                                     colnames=X_new.columns,
                                     costs=y,
                                     **transform_params)
Ejemplo n.º 10
0
    def _transform_from_pandas(self, X, y, var_lbs, var_ubs,
                               **transform_params):
        assert is_pandas_dataframe(X)

        X_new = X.copy()
        # save min, max per nutrients in lists, drop them
        rhs = X["rhs"].tolist()
        X_new.drop(labels=["rhs"], inplace=True, axis=1)

        with AdvModel(name='lp_transformer') as mdl:
            x_rows, x_cols = X.shape
            nb_vars = x_cols - 1

            varlist = mdl.continuous_var_list(nb_vars, lb=var_lbs, ub=var_ubs)
            senses = transform_params.get('sense', 'le')
            mdl.add(mdl.matrix_constraints(X_new, varlist, rhs, sense=senses))
            return self._solve_model(mdl,
                                     varlist,
                                     colnames=X_new.columns,
                                     costs=y,
                                     **transform_params)
Ejemplo n.º 11
0
 def build_sparse_linear_model_and_solve(cls,
                                         nb_vars,
                                         var_lbs,
                                         var_ubs,
                                         var_types,
                                         var_names,
                                         nb_rows,
                                         cts_sparse_coefs,
                                         objsense,
                                         costs,
                                         solution_maker=make_solution,
                                         **transform_params):
     with AdvModel(name='lp_transformer') as mdl:
         varlist = mdl.continuous_var_list(nb_vars, lb=var_lbs, ub=var_ubs)
         lfactory = mdl._lfactory
         r_rows = range(nb_rows)
         exprs = [lfactory.linear_expr() for _ in r_rows]
         rhss = [0] * nb_rows
         for coef, row, col in cts_sparse_coefs:
             if col < nb_vars:
                 exprs[row]._add_term(varlist[col], coef)
             else:
                 assert col == nb_vars
                 rhss[row] = coef
         sense = transform_params.get('sense', 'le')
         cts = [
             lfactory.new_binary_constraint(exprs[r],
                                            rhs=rhss[r],
                                            sense=sense) for r in r_rows
         ]
         lfactory._post_constraint_block(cts)
         return cls._solve_model(mdl,
                                 varlist,
                                 var_names,
                                 objsense=objsense,
                                 costs=costs,
                                 solution_maker=solution_maker,
                                 **transform_params)
Ejemplo n.º 12
0
    def to_quadratic_program(self) -> QuadraticProgram:
        """Convert a portfolio optimization problem instance into a
        :class:`~qiskit_optimization.problems.QuadraticProgram`.

        Returns:
            The :class:`~qiskit_optimization.problems.QuadraticProgram` created
            from the portfolio optimization problem instance.
        """
        self._check_compatibility(self._bounds)
        num_assets = len(self._expected_returns)
        mdl = AdvModel(name="Portfolio optimization")
        if self.bounds:
            x = [
                mdl.integer_var(lb=self.bounds[i][0], ub=self.bounds[i][1], name=f"x_{i}")
                for i in range(num_assets)
            ]
        else:
            x = [mdl.binary_var(name=f"x_{i}") for i in range(num_assets)]
        quad = mdl.quad_matrix_sum(self._covariances, x)
        linear = np.dot(self._expected_returns, x)
        mdl.minimize(self._risk_factor * quad - linear)
        mdl.add_constraint(mdl.sum(x[i] for i in range(num_assets)) == self._budget)
        op = from_docplex_mp(mdl)
        return op