1

I am working on writing a repeatable script that uses the scipy optimize package. As part of this, you need to create functions of constraints. I am wanting to create a repeatable script that allows me to create the right number of constraint functions, based on a variable number of inputs.

For example:

def constraintx1(x):
    return (x2c2*(x[1]**2))+(x1c2*x[1]) + maxresponsec2
def constraintx2(x):
    return (x2c3*(x[2]**2))+(x1c3*x[2]) + maxresponsec3
def constraintx3(x):
    return (x2c4*(x[3]**2))+(x1c4*x[3]) + maxresponsec4

constraints = [{'type':'ineq', 'fun':constraintx1},
               {'type':'ineq', 'fun':constraintx2},
               {'type':'ineq', 'fun':constraintx3}]

all the x2c2, x1c2 and maxresponsec2 are coming from an input table defined earlier as curvestable.

These are some of my constraint functions, for 3 input variables. However, with another project, I might need to repeat this for 12 variables and I am hoping to create a loop that will generate the right number of constraint functions, based on a counter. I have been looking around but havent been able to find anything yet. I am hoping that there is something along the lines of:

numberofvariables = len(someinput)
constraints = []
for g in range(0,numberofvariables):
    def constraintg (x):
        return curvestable.iloc[g,1]*(x[0]**2))+(curvestable.iloc[g,2]*x[0]) + curvestable.iloc[g,4]
    constraints = constraints.append([{'type':'ineq', 'fun':constraintg}])
    next

I also need to point out I am an extreme amateur in coding so not sure if this is possible or not.

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96

2 Answers2

1

You should check out python closure functions.

def constraint_func_maker(x2c2, x1c2, maxresp):
    def constraint_func(x):
        return (x2c2 * (x[1] ** 2)) + (x1c2 * x[1]) + maxresp
    return constraint_func
nicholishen
  • 2,602
  • 2
  • 9
  • 13
0
n = len(someinput)
ct = curvetable
constraints = [lambda x: ct.iloc[g,1]*(x[0]**2))+(ct.iloc[g,2]*x[0])+ ct.iloc[g,4] for g in range(n)]

This involves using two key python elements:

  1. lambda expression, this addresses the core of your question - create functions using functions
  2. list comprehension, this just makes code cleaner than for-loop plus append

Additionally, since your curvetable(renamed to ct to make code shorter) is a DataFrame, you can use the apply function, but I don't want to jam too much tricks to distract from the main point - lambda expression

Indominus
  • 1,228
  • 15
  • 31