the_dankest
the_dankest

Reputation: 205

Scipy Objective function

I am trying to convert my gurobi code into scipy but I am having trouble defining the objective function. When testing to see if I defined the function correctly I get the error:

TypeError: 'float' object is not iterable

The code is here:

import pandas as pd
import numpy as np
import scipy as sp
from scipy.optimize import minimize
import matplotlib.pyplot as plt
%matplotlib inline
step=80
f1load=[44,48,53,28,32,36,41,48,38,32,38,34,44,36,41,48,38,32,44,48,53,28,32,36,41,48,38,32,38,34,44,36,41,48,38,32,44,48,53,28,32,36,41,48,38,32,38,34,44,36,41,48,38,32,44,48,53,28,32,36,41,48,38,32,38,34,44,36,41,48,38,32,44,48,53,28,32,36,41,48,38,32,38,34,44,36,41,48]
fload=f1load[0:step+1]
i1load=[40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40]
iload=i1load[0:step+1]
#Following command converts fload&iload to arrays and subtracts them from each other 
load1=np.array(iload)-np.array(fload)
load1
#This command converts array to list so we can use it as a list in the rest of the code
load2=load1.tolist()
load=load2
x = np.zeros(80)
x = x.tolist()
def objective(x,load):
# this line is from my gurobi code    obj1=sum(((load[i+1]-(6*x[i]))*(load[i+1]-(6*x[i])) for i in range (n)))
    for i in range(step):
        obj1 = sum((load[i+1]-(6*x[i]))*(load[i+1]-(6*x[i])))
        obj2 = obj2 + obj1
    return obj2

objective(x,load)

Full stack trace of error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-26-cef8470baf0d> in <module>
----> 1 objective(x,load)

<ipython-input-25-a9de3ab9ff2b> in objective(x, load)
      2 #     obj1=sum(((load[i+1]-(6*x[i]))*(load[i+1]-(6*x[i])) for i in range (n)))
      3     for i in range(step):
----> 4         obj1 = sum((load[i+1]-(6*x[i]))*(load[i+1]-(6*x[i])))
      5         obj2 = obj2 + obj1
      6     return obj2

TypeError: 'float' object is not iterable

Upvotes: 2

Views: 58

Answers (1)

Jerfov2
Jerfov2

Reputation: 5504

On this line:

obj1 = sum((load[i+1]-(6*x[i]))*(load[i+1]-(6*x[i])))

The expression inside the parantheses, (load[i+1]-(6*x[i]))*(load[i+1]-(6*x[i])), evaluates to a float, and calling sum on that expression gives you the error because the sum function expects an iterable argument.

Upvotes: 1

Related Questions