2

My goal is to calculate the value of both a matrix (df_a) and a list (l), with the main idea being to calculate, for each position i, the value of the following: enter image description here - and aiming to minimize the error, i.e., S - RHS of the equation shown However, I can't seem to calculate it via the scipy package`

The code is the following:


def objective(x, S, d, num_cols):
    l = x[:num_cols]
    df_a = x[num_cols:].reshape(num_cols, num_cols)
    aux = np.dot(df_a, l)
    d = d.astype(int)
    aux = aux * (1 - d)
    soma = []
    obj = []
    for i in range(num_cols):
        soma.append(aux[:i].sum() + aux[i+1:].sum())
        obj.append((S[i] - soma[i])**2)
    return sum(obj)

Define the constraints that take a combined variable as input

def cons(x, num_cols):
    l = x[:num_cols]
    df_a = x[num_cols:].reshape(num_cols, num_cols)
    # compute the constraints using l and df_a
    con1 = {'type': 'ineq', 'fun': lambda l: l.sum() - 1}
    con2 = {'type': 'ineq', 'fun': lambda df_a: df_a.sum(axis=0) - 1}
    return [con1, con2]

Concatenate the l and df_a arrays into a single array

l = np.zeros(num_cols)
df_a = np.zeros((num_cols, num_cols))
x0 = np.concatenate([l, df_a.flatten()])

Define other parameters and call the optimization function

S = df_demand_rate['demand_rate'] / 52
d = df_stockout['prob_stockout'].astype(int)
res = minimize(objective, x0, args=(S, d, num_cols), method='SLSQP', constraints=cons)

And I get the following error message: Traceback (most recent call last):

File "<stdin>", line 1, in <module>   File "C:\Users\ricardo.cabral\Miniconda3\envs\analytics_foundation\lib\site-packages\scipy\optimize\_minimize.py", 
line 595, in minimize             
constraints = standardize_constraints(constraints, x0, meth)   
File "C:\Users\ricardo.cabral\Miniconda3\envs\analytics_foundation\lib\site-packages\scipy\optimize\_minimize.py", 
line 815, in standardize_constraints     
constraints = list(constraints)  # ensure it's a mutable sequence TypeError: 'function' object is not iterable

Thank you in advance!!!

I am trying to solve a non-linear programming problem by aiming to calculate both df_a and l, by inputing the values of S (vector with size n_cols) and d (vector size n_cols) I tried even to use ChatGPT to help me but with no use.`

1 Answers1

2

Replace:

res = minimize(objective, x0, args=(S, d, num_cols), method='SLSQP', 
               constraints=cons)

By:

res = minimize(objective, x0, args=(S, d, num_cols), method='SLSQP',
               constraints=cons())  # <- You have to call your function
Corralien
  • 109,409
  • 8
  • 28
  • 52