Skip to content

leastsq needlessly appends extra dimension for scalar problems #8532

@nschloe

Description

@nschloe

When treating a scalar problem, leastsq needlessly appends an extra dimension to the argument of the function to be minimized as well as the result. MCVE:

from scipy.optimize import leastsq

def f(x):
    print(x.shape)
    return x


out = leastsq(f, 0.0)
print(out)
print()
leastsq(f, [0.0])
print(out)

Output:

(1,)
(1,)
(1,)
(1,)
(array([0.]), 4)

(1,)
(1,)
(1,)
(1,)
(array([0.]), 4)

Expected output:

()
()
()
()
(array(0.), 4)

(1,)
(1,)
(1,)
(1,)
(array([0.]), 4)

As a consequence of this, many codes have to select the "first" element in a scalar problem

out, _ = leastsq(f, 0.0)
theta = out[0]  # this should be unnecessary

I personally ran into this when trying to clean up my f(x) which involves dots and such, and wondered why things like

array = something()

def f(theta):
    sc = numpy.array([numpy.sin(theta), numpy.cos(theta)])
    return numpy.dot(sc, array)

wouldn't work. (It was the superfluous dimension in theta that had the dot product fail.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    defectA clear bug or issue that prevents SciPy from being installed or used as expectedscipy.optimize

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions