How to Free Variables Using Gekko

Viewed 155

I am trying to use GEKKO to do simple algebra.

Given the Equation 6 = X1 * X2, I first set X1 to 2 using the Gekko fix() function. After solving and printing that equation, I try freeing X1 using the Gekko free() function and fix X2 to 2 using the fix() function again. The free function doesn't seem to be properly freeing the X2 Variable.

from gekko import GEKKO

m = GEKKO()

# Variables
x1 = m.Var()
x2 = m.Var()

# Equation
FindX1 = 6 == x1*x2
m.Equation(FindX1)

# Fix x1 to 2
m.fix(x1, val=2)

# Solve X2
m.solve(disp=False)
print("X1: %s and X2: %s" % (x1.VALUE, x2.VALUE))

# Fix x2 to 2
m.fix(x2, val=2)

# Free x1
m.free(x1)

# Solve X1
m.solve(disp=False)
print("X1: %s and X2: %s" % (x1.VALUE, x2.VALUE))
1 Answers

The restart file is holding onto the specs. For IMODE=3 it is rto.t0 in the run directory m.path. You can remove that restart file with:

import os
os.remove(m.path+'\\rto.t0')

There is an option m.options.SPECS=0 that should also work to ignore the fixed / free specifications in the restart file but this isn't communicating to the solve engine. I created a new GitHub issue to address this bug.

import os
from gekko import GEKKO

m = GEKKO(remote=False)

# Variables
x1 = m.Var()
x2 = m.Var()

# Equation
FindX1 = 6 == x1*x2
m.Equation(FindX1)

# Fix x1 to 2
m.fix(x1, val=2)

# Solve X2
m.solve(disp=False)
print("X1: %s and X2: %s" % (x1.VALUE, x2.VALUE))

# Fix x2 to 2
m.fix(x2, val=2)

# Free x1
m.free(x1)

os.remove(m.path+'\\rto.t0')
#m.options.SPECS = 0

# Solve X1
m.solve(disp=False)
print("X1: %s and X2: %s" % (x1.VALUE, x2.VALUE))

m.open_folder()

This produces the correct response:

X1: [2.0] and X2: [3.0]
X1: [3.0] and X2: [2.0]
Related