5

I'm trying to fit a cubic spline to the data points below, I'm a bit confused when I would use a Param like the example m.x = m.Param(value=np.linspace(-1, 6)) or when I would use a constant Const.

import numpy as np
from gekko import GEKKO
xm = np.array([0, 1, 2, 3, 4, 5])
ym = np.array([0.1, 0.2, 0.3, 0.5, 1.0, 0.9])

m = GEKKO()
m.x = m.Param(value=np.linspace(-1, 6))
m.y = m.Var()
m.options.IMODE = 2
m.cspline(m.x, m.y, xm, ym)
m.solve(disp=False)

p = GEKKO()
p.x = p.Var(value=1, lb=0, ub=5)
p.y = p.Var()
p.cspline(p.x, p.y, xm, ym)
p.Obj(-p.y)
p.solve(disp=False)
John Hedengren
  • 12,068
  • 1
  • 21
  • 25
J Edward Hammond
  • 509
  • 1
  • 3
  • 12
  • 1
    FYI: there is a new `Maximize` function in gekko so that your objective function can be more readable with `p.Maximize(p.y)` instead of `p.Obj(-p.y)`. – John Hedengren Nov 22 '19 at 11:56

1 Answers1

1

A constant Const is a single scalar value that is not expected to change. A parameter Param has an initial value but it can be changed by the user with data. A fixed value FV or manipulated variable MV are two special types of parameters that have extra options for becoming a solver decision variable. The difference between an FV and MV is that an FV has one value while an MV can have different values across the data (IMODE=2) or time (IMODE=4-9) dimension.

You have a nice example of fitting a cubic spline to data and then solving for the maximum across the range 0 < x < 5.

Cubic spline maximization

import numpy as np
from gekko import GEKKO
xm = np.array([0, 1, 2, 3, 4, 5])
ym = np.array([0.1, 0.2, 0.3, 0.5, 1.0, 0.9])

m = GEKKO()
m.x = m.Param(value=np.linspace(-1, 6))
m.y = m.Var()
m.options.IMODE = 2
m.cspline(m.x, m.y, xm, ym)
m.solve(disp=False)

p = GEKKO()
p.x = p.Var(value=1, lb=0, ub=5)
p.y = p.Var()
p.cspline(p.x, p.y, xm, ym)
p.Maximize(p.y)
p.solve(disp=False)

import matplotlib.pyplot as plt
plt.plot(xm,ym,'rs',label='Data')
plt.plot(m.x,m.y,'r.-',label='Cubic Spline')
plt.plot(p.x,p.y,'bo',label='Maximize')
plt.xlabel('x'), plt.ylabel('y')
plt.legend()
plt.show()

In your case, a Param (or MV with STATUS=0) is the appropriate gekko object. A Const gives an error: ValueError: Constant value must be scalar.

John Hedengren
  • 12,068
  • 1
  • 21
  • 25