Ejemplo n.º 1
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
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.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.º 3
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.º 4
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.º 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)
    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.º 8
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
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)
    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.º 13
0
}

dfv = pd.DataFrame(var, index=securities, columns=securities)
dfv


def is_nam(s):
    return 1 if s == 'N-Am.' else 0


df_secs['is_na'] = df_secs['area'].apply(is_nam)
df_secs

from docplex.mp.advmodel import AdvModel as Model

mdl = Model(name='portfolio_miqp')

# create variables
df_secs['frac'] = mdl.continuous_var_list(securities, name='frac', ub=1)

# max fraction
frac_max = 0.3
for row in df_secs.itertuples():
    mdl.add_constraint(row.frac <= 0.3)

# sum of fractions equal 100%
mdl.add_constraint(mdl.sum(df_secs.frac) == 1)

# north america constraint:
#    - add a 1-0 column equal to 1
# compute the scalar product of frac variables and the 1-0 'is_na' column and set a minimum
Ejemplo n.º 14
0
def get_model(u, C, f, c, l):
    """
    Get a CPLEX model set to optimise fitness in a communication game
    involving communication efficiency and production cost constraints,
    as defined by input parameters.
    
    Input:
        u: numpy array of size n, utility of each referent
        C: numpy array of size m x m, confusion matrix between signals
        f: numpy array of size n, frequency of production of each referent
        c: numpy array of size m, production cost of each signal
        l: positive float, controls production cost/communication efficiency
                            trade-off. 0 means no influence of production costs,
                            very high means no influence of communication
                            efficiency

    Output:
        mdl: CPLEX model set to optimise fitness as defined by input parameters
        P: production matrix CPLEX variables
        Q: reception matrix CPLEX variables
    """
    m, n = len(c), len(u)
    mdl = Model(name='evophono')
    # create variables (with positivity constraint)
    # is an explicit upper bound for p and q helpful? Seems slightly faster...
    P = mdl.continuous_var_matrix(range(n), range(m), lb=0, ub=1, name='p')
    Q = mdl.continuous_var_matrix(range(m), range(n), lb=0, ub=1, name='q')
    # add summing to one constraints
    for i in range(n):
        mdl.add_constraint(mdl.sum(P[i,j] for j in range(m)) == 1)
    for j in range(m):
        mdl.add_constraint(mdl.sum(Q[j,i] for i in range(n)) == 1)
    # defining objective
    communication_accuracy = mdl.sum(u[i]*P[i,j]*C[j,k]*Q[k,i] 
                                        for i in range(n)
                                            for j in range(m)
                                                for k in range(m))
    production_cost = mdl.sum(f[i]*P[i,j]*c[j]
                                for i in range(n)
                                   for j in range(m))   
    fitness = communication_accuracy - l*production_cost
    # setting objective
    mdl.maximize(fitness)
    return mdl, P, Q