Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Differential evolution breaks with LinearConstraints with sparse matrixes #11586

Closed
santiher opened this issue Feb 25, 2020 · 1 comment
Closed

Comments

@santiher
Copy link
Contributor

Differential evolution breaks if a LinearConstraint built with a sparse matrix is given as argument.

LinearConstraint's A parameter can be a sparse matrix:

class LinearConstraint(object):

    Parameters
    ----------
    A : {array_like, sparse matrix}, shape (m, n)
        Matrix defining the constraint.

Yet when differential evolution does:

elif isinstance(constraint, LinearConstraint):
    def fun(x):
        A = np.atleast_2d(constraint.A)
        return A.dot(x)

If constraint.A is a sparse matrix, A will be a 2d array of (1, 1) with the sparse matrix in A[0][0], breaking the A.dot(x) due to shape mismatch. Example:

> import numpy as np
> from scipy.sparse import dok_matrix
> A = dok_matrix((2, 3))
> A[0, 0] = A[0, 1] = A[1, 1] = A[1, 2] = 1
> print(np.atleast_2d(A))
[[<2x3 sparse matrix of type '<class 'numpy.float64'>'
 with 4 stored elements in Dictionary Of Keys format>]]

If constraint.A is a Sparse matrix, it is guaranteed to have ndims == 2 and should not be np.atleast_2ded.

Minimum working example of the problem:

import numpy as np

from scipy.optimize import differential_evolution, LinearConstraint
from scipy.sparse import dok_matrix


A = dok_matrix((2, 3))
A[0, 0] = A[0, 1] = A[1, 1] = A[1, 2] = 1
constraint = LinearConstraint(
    A,  # Currently it would work if A were a numpy array: `A = A.toarray()`
    np.array([0, 0]),
    np.array([2, 3]),
    keep_feasible=True,
)
solution = differential_evolution(
    lambda x: 0.5 * x[0] + 1 * x[1] - 1 * x[2],
    bounds=[(0, 4), (0, 4), (0, 4)],
    constraints=constraint,
    seed=14,
)
@andyfaff
Copy link
Contributor

closed by #11587

@tylerjereddy tylerjereddy added this to the 1.5.0 milestone Feb 28, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants