Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to Solve Optimization in scpy.optimize.minimize Problem?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 400
    Answer it

    I have a problem with optimizing of a function that contains loops. I start with paricular lista=[0.002,0.006,0.003,0.02,0.008,0.006,0.05] of floats and the intervals `(0,k*0.0025),(0.005,k*0.005),(0.005,k*0.0125), where upper border depends. So, depending on which of the interval the float of list belong to, I assign to the function one of values k*0.005,k*0.01,k*0.025 and k*0.05 that also depend on k.

     

    I want to minimize k such that the sum (new scalar function) of values of assign(k) or sum(assign(k)) is equal to 0.32.

     

    I used scipy.optimize procedure to do that. My constraint is constraint=sum(assign(k))-0.2 and objective function iz fun(k)=k. So, I minimized k to satisfy the constraint.

     

    import scipy
    from scipy.optimize import minimize
    
    
    lista=[0.002,0.006,0.003,0.02,0.008,0.006,0.05]
    
    def assign(k):
        return list(map(lambda x:(k*0.005 if x in np.arange(0,k*0.0025,0.001) 
        else k*0.01 if x in np.arange(0.0025,k*0.005,0.001) else k*0.025 if x in 
        np.arange(0.005,k*0.0125,0.001) else k*0.05), lista))
    
    def constraint(k):
        return sum(assign(k))-0.32
    
    def fun(k):
        return k
    
    k0=0
    bnds=[(0,10)]
    cons={'type':'eq','fun':constraint}
    res=minimize(fun,k0,bounds=bnds,method='SLSQP',constraints=cons,options= 

     

    {'maxiter':2000}) print(res)

     

    I got k=1.1999 wich is a strange result, it does not satisfy the constraint. It should be 2 since sum(assign(2))=0.52. I also got a error message:

     

      message: 'Iteration limit exceeded'

 0 Answer(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: