Il y a donc un problème en ce sens qu'il n'accepte qu'un tableau 1D en tant que variable indépendante, une solution piratante serait de la passer en 1D et de remodeler dans la fonction.
import numpy as np
from scipy.optimize import fmin_slsqp
# some fake data
d = 3 # dimensionality of the problem
P0 = np.arange(d*d).reshape(d, d)
P0 /= P0.sum(1, keepdims=True) # so that each row sums to 1
q = np.random.rand(2, d) # assuming this is the structure of your q
q /= q.sum(1, keepdims=True)
# the function to minimize
def func(P, q):
n = q.shape[-1] # or n = np.sqrt(P.size)
P = P.reshape(n, n)
return np.linalg.norm(np.dot(q[0], P) - q[1])**2 # no changes here, just simplified syntax
def row_sum(P0, q):
""" row sums - 1 are zero """
n = np.sqrt(P0.size)
return P0.reshape(n,n).sum(1) - 1.
def non_neg(P0, q):
""" all elements >= 0 """
return P0
P_opt = fmin_slsqp(func, P0.ravel(), args=(q,), f_eqcons=row_sum, f_ieqcons=non_neg).reshape(d, d)
assert np.allclose(P_opt.sum(1), 1)
assert np.all(P_opt >= 0)