Search code examples
pythonnonlinear-optimizationgekko

How to conduct mathematical operation on numpy array in the presence of GEKKO unknown variables


I tried to solve the following integer program through Gekko python package, but stuck in objective function part. Your help is highly appreciated.

from gekko import GEKKO
import numpy
import pandas as pd

d=numpy.zeros((3,2))
d[:,0]=numpy.array([10,30,50])

w1=numpy.array([0,1.2,2])
w2=numpy.array([0,2,0])
w3=numpy.array([0.1,0,0.2])


def obj_fun(x1, x2, x3):
  d[:,1]=d[:,0]-w1[:,0]*x1-w1[:,0]*x2-w1[:,0]*x3
  obf=d.min(axis=1).sum()
  return(obf)

m = GEKKO(remote=False)
m.options.SOLVER=1

# Initialize variables
x1 = m.Var(value=1,lb=1,ub=3,integer=True)
x2 = m.Var(value=1,lb=1,ub=4,integer=True)
x3 = m.Var(value=1,lb=1,ub=5,integer=True)
obf= m.Var()

m.Obj(obj_fun(x1, x2, x3))
m.solve(disp=False) # Solve
print('Results')
print('x1: ' + str(x1.value))
print('x2: ' + str(x2.value))
print('x3: ' + str(x3.value))
print('Objective: ' + str(m.options.objfcnval))

Solution

  • Try using either a list comprehension:

      c = [d[i]-w1[0]*x1-w2[0]*x2-w3[0]*x3 for i in range(n)]
      minc = [m.min3(c[i],d[i]) for i in range(n)]
    

    or a loop to define the objective function:

    n = 3; c = [None]*n; minc = [None]*n
    def obj_fun(x1, x2, x3):
      for i in range(n):
        c[i] = d[i]-w1[0]*x1-w2[0]*x2-w3[0]*x3
        minc[i] = m.min3(c[i],d[i])
      obf=m.sum(minc)
      return(obf)
    

    Here is the complete script with a list comprehension:

    from gekko import GEKKO
    import numpy
    import pandas as pd
    
    d=numpy.array([10,30,50])
    w1=numpy.array([0,1.2,2])
    w2=numpy.array([0,2,0])
    w3=numpy.array([0.1,0,0.2])
    
    n = 3
    def obj_fun(x1, x2, x3):
      c = [d[i]-w1[0]*x1-w2[0]*x2-w3[0]*x3 for i in range(n)]
      minc = [m.min3(c[i],d[i]) for i in range(n)]
      obf=m.sum(minc)
      return(obf)
    
    m = GEKKO(remote=False)
    m.options.SOLVER=1
    
    # Initialize variables
    x1 = m.Var(value=1,lb=1,ub=3,integer=True)
    x2 = m.Var(value=1,lb=1,ub=4,integer=True)
    x3 = m.Var(value=1,lb=1,ub=5,integer=True)
    obf= m.Var()
    
    m.Obj(obj_fun(x1, x2, x3))
    m.solve(disp=True) # Solve
    print('Results')
    print('x1: ' + str(x1.value))
    print('x2: ' + str(x2.value))
    print('x3: ' + str(x3.value))
    print('Objective: ' + str(m.options.objfcnval))
    

    It produces the solution:

    Results
    x1: [1.0]
    x2: [1.0]
    x3: [5.0]
    Objective: 88.5