[SOLVED] Creating multiple functions using a for loop

Issue

I am trying to create multiple constraint functions to feed scipy.minimize.

The minimize function is:

res1 = minimize(f, x0, args, method='SLSQP', bounds=bnds, constraints=cons, options={'disp': True})

I have set cons to:

cons = [con1, con2, con3, con4]
con1 = {'type': 'eq', 'fun': constraint1}
con2 = {'type': 'eq', 'fun': constraint2}
con3 = {'type': 'eq', 'fun': constraint3}
con4 = {'type': 'eq', 'fun': constraint4}

def constraint1(x):
    return x[0] + x[1] + x[2] + x[3] + x[4] + x[5] + x[6] + x[7] + x[8] - 4321
def constraint2(x):
    return x[9] + x[10] + x[11] + x[12] + x[13] + x[14] + x[15] + x[16] + x[17] - 123
def constraint3(x):
    return x[18] + x[19] + x[20] + x[21] + x[22] + x[23] + x[24] + x[25] + x[26] - 1234
def constraint4(x):
    return x[27] + x[28] + x[29] + x[30] + x[31] + x[32] + x[33] + x[34] + x[35] - 432

How can I automate this process by using a for loop? The problem is to create function with parametric name

Solution

You needn’t give the functions names at all:

def make_constraint(i,j,c):
  def constraint(x):
    return sum(x[i:j])+c

cons=[dict(type='eq',fun=make_constraint(i*9,(i+1)*9,c))
      for i,c in enumerate([-4321,-123,-1234,-432])]

This sort of approach will not in general run quite as fast as the hand-written functions, since values like i and j must be retrieved on every call; if that matters, it is possible to use the ast module to actually create new Python functions without exec (and its associated lack of structure and security).

Answered By – Davis Herring

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.