Question

I have a list (actually I'd like to make it a 1D numpy array) whose first and last element will remain constant but whose other elements are objects of an optimisation, i.e will change often and need to be in a separate variable (because scipy.optimize.leastsq() needs it that way). So I've got this code to put the constant "outer" elements together with the changing ones:

b_0 = 1      # this will stay constant
b_n = 10     # this as well

def _b(b_0, b_n, b_in):
    import numpy as np            
    b = np.zeros((b_inner.shape[0]+2))
    b[0] = b_0
    b[-1] = b_n
    b[1:-1] = b_in
    return(b)

>>> b_in = range(2,10)
>>> _b(b_0, b_n, b_in)   #returns array([1,2,3,4,5,6,7,8,9,10])

This looks very unelegant to me, and I'm convinced there must be a way to do this in just one line that defines

b = np.array([b_0, somefunction(b_in), b_n])

For background, I need this because I have an error function for leastsq that takes a 1D array of which only the inner elements are optimized. I am feeding the result of the above to a lambda function, together with other parameters to the error function, so that I can pass only the stuff that changes to leastsq:

err_func = lambda b_in: error_function(_b(b_0,b_n,b_in), other_parameters)

b_in_0 = range(2,10)   # starting guess
target = scipy.optimize.leastsq(err_func, b_in_0)

because I am using the same error function for different types of optimisation (there are different aspects and different types of constraints that the function can be fitted to), I do not want to re-write the error function for a specific purpose.

Was it helpful?

Solution

I think np.r_ might be what you're looking for. You could use np.r_[b_0, somefunction(b_in), b_n], for example:

np.r_[12, np.arange(5), 13]
# array([12,  0,  1,  2,  3,  4,  5, 13])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top