Python fmin(find minimum) for a vector function

595 views Asked by At

I would like to find the minimum of 3dvar function defined as:

J(x)=(x-x_b)B^{-1}(x-x_b)^T + (y-H(x)) R^{-1} (y-H(x))^T (latex code)

with B,H,R,x_b,y given. I would like to find the argmin(J(x)). However it seems fmin in python does not work. (the function J works correctly)

Here is my code:

import numpy as np

from scipy.optimize import fmin

import math


def dvar_3(x):

    B=np.eye(5)
    H=np.ones((3,5))
    R=np.eye(3)
    xb=np.ones(5)
    Y=np.ones(3)

    Y.shape=(Y.size,1)

    xb.shape=(xb.size,1)


    value=np.dot(np.dot(np.transpose(x-xb),(np.linalg.inv(B))),(x-xb)) +np.dot(np.dot(np.transpose(Y-np.dot(H,x)),(np.linalg.inv(R))),(Y-np.dot(H,x)))    

    return value[0][0]


ini=np.ones(5) #
ini.shape=(ini.size,1) #change initial to vertical vector

fmin(dvar_3,ini) #start at initial vector

I receive this error:

ValueError: operands could not be broadcast together with shapes (5,5) (3,3) 

How can I solve this problem? Thank you in advance.

1

There are 1 answers

0
HYRY On

reshape argument x in the function dvar_3, the init argument of fmin() needs a one-dim array.

import numpy as np   
from scipy.optimize import fmin   
import math

def dvar_3(x):
    x = x[:, None]
    B=np.eye(5)
    H=np.ones((3,5))
    R=np.eye(3)
    xb=np.ones(5)
    Y=np.ones(3)

    Y.shape=(Y.size,1)

    xb.shape=(xb.size,1)


    value=np.dot(np.dot(np.transpose(x-xb),(np.linalg.inv(B))),(x-xb)) +np.dot(np.dot(np.transpose(Y-np.dot(H,x)),(np.linalg.inv(R))),(Y-np.dot(H,x)))    

    return value[0][0]


ini=np.ones(5) #
fmin(dvar_3,ini) #start at initial vector