### Pyomo Example with GEKKO Source: https://github.com/byu-prism/gekko/blob/master/docs/solver_extension.md Example demonstrating the use of the solver extension module with the Pyomo converter in GEKKO. ```APIDOC ## Pyomo Example with GEKKO ### Description Example use of the solver extension module with the Pyomo converter is shown below: ### Method Python Script ### Endpoint N/A ### Request Example ```python from gekko import GEKKO m = GEKKO(remote=False) # remote=True not supported x = m.Var() y = m.Var() m.Equations([3*x+2*y==1, x+2*y==0]) # enable solver extension and use Pyomo converter m.options.SOLVER_EXTENSION = "PYOMO" m.options.SOLVER = "cbc" # use CBC solver m.solve() # solve print(x.value,y.value) ``` ### Response #### Success Response (200) Prints the solved values of x and y. #### Response Example ``` 0.5 -0.5 ``` ``` -------------------------------- ### Install AMPLPY Library Source: https://github.com/byu-prism/gekko/blob/master/docs/solver_extension.md Install the AMPLPY library to enable GEKKO to interface with AMPL solvers. ```bash $ pip install amplpy ``` -------------------------------- ### Steady-State NLP Example in MATLAB Source: https://github.com/byu-prism/gekko/blob/master/gekko-matlab/README.md A quick start example demonstrating a steady-state non-linear programming problem. It includes setting up variables, equations, an objective, and solving the problem remotely. ```matlab addpath('../src') m = Gekko(); m.remote = true; x1 = m.Var(1,1,5); x2 = m.Var(5,1,5); x3 = m.Var(5,1,5); x4 = m.Var(1,1,5); m.Equation(x1^2 + x2^2 + x3^2 + x4^2 == 40); m.Equation(x1*x2*x3*x4 >= 25); m.Minimize(x1*x4*(x1+x2+x3) + x3); m.solve(); fprintf('x1 = %.4f\n', x1.value); fprintf('x2 = %.4f\n', x2.value); fprintf('x3 = %.4f\n', x3.value); fprintf('x4 = %.4f\n', x4.value); ``` -------------------------------- ### Install and Import GEKKO Source: https://github.com/byu-prism/gekko/blob/master/docs/gekko_examples.ipynb This snippet shows how to install GEKKO if it's not already present and then import it. It also includes commands to display package information and upgrade GEKKO. ```python try: # import gekko if installed from gekko import GEKKO except: # install gekko if error on try !pip install gekko from gekko import GEKKO # package information !pip show gekko # upgrade GEKKO to latest version # !pip install --upgrade gekko ``` -------------------------------- ### Install Pyomo Library Source: https://github.com/byu-prism/gekko/blob/master/docs/solver_extension.md Install the Pyomo library, which is required for using the Pyomo solver extension in GEKKO. ```bash $ pip install Pyomo ``` -------------------------------- ### State-Space Helper Example in MATLAB Source: https://github.com/byu-prism/gekko/blob/master/gekko-matlab/README.md Shows how to implement a state-space model using the `state_space` helper. This example defines system matrices and uses the helper to generate state, output, and input variables. ```matlab addpath('../src') m = Gekko(); m.time = linspace(0,5,51); m.options.imode = 4; A = -1; B = 1; C = 1; [x,y,u] = m.state_space(A,B,C,[],[],false,true); m.fix(u,1); m.solve(); plot(m.time, x.value) ``` -------------------------------- ### AMPLPY Solver Extension Example Source: https://github.com/byu-prism/gekko/blob/master/docs/solver_extension.md Example demonstrating the use of the solver extension with the AMPLPY converter and the BONMIN solver. Ensure remote=False is used as remote solving is not supported with this extension. ```python from gekko import GEKKO m = GEKKO(remote=False) # remote=True not supported x = m.Var() y = m.Var() m.Equations([3*x+2*y==1, x+2*y==0]) # enable solver extension and use AMPLPY converter m.options.SOLVER_EXTENSION = "AMPLPY" m.options.SOLVER = "bonmin" # use BONMIN solver m.solve() # solve print(x.value,y.value) ``` -------------------------------- ### Gekko Quadratic Programming Setup Source: https://github.com/byu-prism/gekko/blob/master/examples/Optimization_Introduction.ipynb Initializes a Gekko model and defines variables, objective function, and constraints for quadratic programming. This setup is for solving the problem using Gekko's optimization engine. ```python m = GEKKO(remote=False) x = m.Array(m.Var,2,lb=0,ub=10) m.Minimize(0.5 * x@Q@x + p@x) gx = G@x m.Equations([gx[i]>=h[i] for i in range(len(h))]) m.solve(disp=False) ``` -------------------------------- ### Start Model Training Source: https://github.com/byu-prism/gekko/blob/master/docs/llm/README.md Initiates the fine-tuning process for the LLM using the configured `Trainer` object. This command starts the training loop. ```python # Start training trainer.train() ``` -------------------------------- ### Install Python Libraries Source: https://github.com/byu-prism/gekko/blob/master/docs/llm/README.md Installs necessary Python libraries including PyTorch, Transformers, Datasets, Matplotlib, and Requests. ```bash pip install torch transformers datasets matplotlib requests ``` -------------------------------- ### System Identification Helper Example in MATLAB Source: https://github.com/byu-prism/gekko/blob/master/gekko-matlab/README.md Provides an example of system identification using the `sysid` helper. It includes generating sample data and then using `sysid` to estimate model parameters. ```matlab addpath('../src') t = (0:20)' ; u = double(t >= 5); y = zeros(size(t)); for k = 3:numel(t) y(k) = 0.6*y(k-1) - 0.1*y(k-2) + 0.25*u(k-1) + 0.1*u(k-2) + 0.05; end m = Gekko(); [ypred,p,K] = m.sysid(t,u,y,2,2,0,'calc',true,0,'meas'); ``` -------------------------------- ### Install AMPL Solver via AMPLPY Source: https://github.com/byu-prism/gekko/blob/master/docs/solver_extension.md Install a specific solver through the amplpy.modules interface. Replace '' with the desired solver name. ```bash $ python -m amplpy.modules install ``` -------------------------------- ### Dynamic Model Example in MATLAB Source: https://github.com/byu-prism/gekko/blob/master/gekko-matlab/README.md Illustrates how to set up and solve a dynamic optimization problem. This example defines time points, an option for dynamic mode, a parameter, a variable, and an equation involving a time derivative. ```matlab addpath('../src') m = Gekko(); m.time = linspace(0,5,41); m.options.imode = 4; k = m.Param(2); x = m.Var(0); m.Equation(x.dt() == -k*x + 1); m.solve(); plot(m.time, x.value) xlabel('time') ylabel('x') ``` -------------------------------- ### GEKKO Initialization and Variable Setup Source: https://github.com/byu-prism/gekko/blob/master/docs/gekko_examples.ipynb Initializes a GEKKO model, sets up time points, and defines variables including a control input with bounds. ```python from gekko import GEKKO import numpy as np import matplotlib.pyplot as plt %matplotlib inline m = GEKKO() # initialize gekko nt = 101 m.time = np.linspace(0,2,nt) # Variables x1 = m.Var(value=1) x2 = m.Var(value=0) u = m.Var(value=0,lb=-1,ub=1) p = np.zeros(nt) # mark final time point p[-1] = 1.0 final = m.Param(value=p) ``` -------------------------------- ### Install GEKKO with pip Source: https://github.com/byu-prism/gekko/blob/master/docs/index.md Install the GEKKO package using pip. Use the --user option if permission errors occur. ```default pip install gekko ``` -------------------------------- ### Solve Nonlinear Equations with GEKKO Source: https://github.com/byu-prism/gekko/blob/master/docs/examples.md This example demonstrates solving nonlinear equations. Initialize GEKKO, define variables with initial values, and set up the equations. ```python from gekko import GEKKO m = GEKKO() x = m.Var(value=0) y = m.Var(value=1) m.Equations([x + 2*y==0, x**2+y**2==1]) m.solve(disp=False) print([x.value[0],y.value[0]]) ``` -------------------------------- ### Nonlinear Regression with GEKKO Source: https://github.com/byu-prism/gekko/blob/master/docs/examples.md Sets up a GEKKO model for nonlinear regression. This example initializes measurements, parameters, and variables for fitting a nonlinear model. ```python from gekko import GEKKO import numpy as np import matplotlib.pyplot as plt # measurements xm = np.array([0,1,2,3,4,5]) ym = np.array([0.1,0.2,0.3,0.5,0.8,2.0]) # GEKKO model m = GEKKO() # parameters x = m.Param(value=xm) a = m.FV() a.STATUS=1 # variables y = m.CV(value=ym) y.FSTATUS=1 ``` -------------------------------- ### Model Predictive Control (MPC) Setup Source: https://github.com/byu-prism/gekko/blob/master/docs/imode.md Initializes a GEKKO model for Model Predictive Control (IMODE=6) with a specified time horizon. Requires GEKKO, NumPy, and Matplotlib. ```python from gekko import GEKKO import numpy as np import matplotlib.pyplot as plt m = GEKKO() m.time = np.linspace(0,20,41) ``` -------------------------------- ### Gekko QP Solver Example Source: https://github.com/byu-prism/gekko/blob/master/examples/Optimization_Introduction.ipynb Solves a quadratic programming problem using Gekko, defining variables with bounds, constraints, and an objective function to maximize. It then prints the optimal solution and objective value. ```python m = GEKKO(remote=False) x,y = m.Array(m.Var,2,lb=0) m.Equations([6*x+4*y<=24,x+2*y<=6,-x+y<=1,y<=2]) m.Maximize(0.5*(x**2+y**2)-2*x+2*y) m.solve(disp=False) xopt = x.value[0]; yopt = y.value[0] print('x:', xopt,'y:', yopt,'obj:',-m.options.objfcnval) ``` -------------------------------- ### Configure GEKKO Run Directory Source: https://github.com/byu-prism/gekko/blob/master/docs/quick_start.md This example shows how to create and change the run directory for GEKKO optimizations, allowing for local solving and specifying the output path for model files and diagnostics. ```python from gekko import GEKKO import numpy as np import os # create and change run directory rd=r'.\RunDir' if not os.path.isdir(os.path.abspath(rd)): os.mkdir(os.path.abspath(rd)) m = GEKKO(remote=False) # solve locally m.path = os.path.abspath(rd) # change run directory x = m.Array(m.Var,4,value=1,lb=1,ub=5) x1,x2,x3,x4 = x # rename variables x2.value = 5; x3.value = 5 # change guess m.Equation(np.prod(x)>=25) # prod>=25 m.Equation(m.sum([xi**2 for xi in x])==40) # sum=40 m.Minimize(x1*x4*(x1+x2+x3)+x3) # objective m.solve(disp=False) print(x) ``` -------------------------------- ### Model Predictive Control (MPC) Example in GEKKO Source: https://context7.com/byu-prism/gekko/llms.txt Implements a Model Predictive Control strategy for a thermal system to track a setpoint while respecting constraints. This example requires the GEKKO and NumPy libraries and sets up manipulated variables, controlled variables, and disturbance parameters. ```python from gekko import GEKKO import numpy as np m = GEKKO(remote=False) # Time horizon m.time = np.linspace(0, 60, 61) # Model parameters tau = m.Const(10) # Time constant K = m.Const(2) # Gain T_amb = m.Const(25) # Ambient temperature # Manipulated variable (heater power) Q = m.MV(value=0, lb=0, ub=100, name='heater') Q.STATUS = 1 # Optimizer can adjust Q.DCOST = 0.5 # Penalize movement Q.DMAX = 10 # Max change per step # Controlled variable (temperature) T = m.CV(value=25, name='temperature') T.STATUS = 1 # Include in objective T.SP = 50 # Setpoint T.TR_INIT = 1 # Experiment trajectory T.TAU = 10 # Trajectory time constant m.options.CV_TYPE = 2 # Squared error # Disturbance (measured but not controlled) D = m.Param(value=0, name='disturbance') # First-order energy balance m.Equation(tau * T.dt() == -(T - T_amb) + K*Q + D) # Solve MPC m.options.IMODE = 6 m.options.SOLVER = 3 m.options.NODES = 3 m.solve(disp=False) print(f"MPC Solution:") print(f" Temperature: {T.value[0]:.1f} -> {T.value[-1]:.1f} (SP={T.SP})") print(f" Heater: {Q.value[0]:.1f} -> {Q.value[-1]:.1f}") print(f" Objective: {m.options.OBJFCNVAL:.4f}") ``` -------------------------------- ### Scipy Quadratic Programming Setup Source: https://github.com/byu-prism/gekko/blob/master/examples/Optimization_Introduction.ipynb Defines the objective function, constraints, and bounds for a quadratic programming problem to be solved using Scipy's minimize function. It specifies the optimization method and options. ```python from scipy.optimize import minimize def objective_function(x): return 0.5 * x @ Q @ x + p @ x def constraint(x): return G @ x - h con = {'type': 'ineq', 'fun': constraint} b = (0,10); bnds = (b,b) opt = {'maxiter':1000} res = minimize(objective_function, x0, constraints=con,bounds=bnds, method='SLSQP',options=opt) ``` -------------------------------- ### Solve HS71 Problem with GEKKO Source: https://github.com/byu-prism/gekko/blob/master/docs/quick_start.md This example demonstrates how to set up and solve the HS71 optimization problem using GEKKO, including defining parameters, variables, equations, and the objective function. ```python from gekko import GEKKO #Initialize Model m = GEKKO() #define parameter eq = m.Param(value=40) #initialize variables x1,x2,x3,x4 = [m.Var(lb=1, ub=5) for i in range(4)] #initial values x1.value = 1 x2.value = 5 x3.value = 5 x4.value = 1 #Equations m.Equation(x1*x2*x3*x4>=25) m.Equation(x1**2+x2**2+x3**2+x4**2==eq) #Objective m.Minimize(x1*x4*(x1+x2+x3)+x3) #Set global options m.options.IMODE = 3 #steady state optimization #Solve simulation m.solve() #Results print('') print('Results') print('x1: ' + str(x1.value)) print('x2: ' + str(x2.value)) print('x3: ' + str(x3.value)) print('x4: ' + str(x4.value)) ``` -------------------------------- ### HS71 Benchmark Problem with GEKKO Source: https://github.com/byu-prism/gekko/blob/master/docs/examples.md Solves the HS71 benchmark optimization problem. This example shows how to set up constraints, bounds, and an objective function for a complex problem. ```python from gekko import GEKKO m = GEKKO(remote=True) eq = m.Param(value=40) x1,x2,x3,x4 = [m.Var() for i in range(4)] x1.value = 1 x2.value = 5 x3.value = 5 x4.value = 1 x1.lower = 1 x2.lower = 1 x3.lower = 1 x4.lower = 1 x1.upper = 5 x2.upper = 5 x3.upper = 5 x4.upper = 5 m.Equation(x1*x2*x3*x4>=25) m.Equation(x1**2+x2**2+x3**2+x4**2==eq) m.Obj(x1*x4*(x1+x2+x3)+x3) m.options.IMODE = 3 m.solve() print('') print('Results') print('x1: ' + str(x1.value)) print('x2: ' + str(x2.value)) print('x3: ' + str(x3.value)) print('x4: ' + str(x4.value)) ``` -------------------------------- ### Create and Initialize Array of Variables Source: https://github.com/byu-prism/gekko/blob/master/docs/model_methods.md Create a multi-dimensional array of GEKKO variables with specified dimensions, initial values, and bounds. This example demonstrates a 3x2 array. ```python from gekko import GEKKO m = GEKKO() # variable array dimension n = 3 # rows p = 2 # columns # create array x = m.Array(m.Var,(n,p)) for i in range(n): for j in range(p): x[i,j].value = 2.0 x[i,j].lower = -10.0 x[i,j].upper = 10.0 # create parameter y = m.Param(value = 1.0) # sum columns z = [None]*p for j in range(p): z[j] = m.Intermediate(sum([x[i,j] for i in range(n)])) # objective m.Obj(sum([ (z[j]-1)**2 + y for j in range(p)])) # minimize objective m.solve() print('x:', x) print('z:', z) ``` -------------------------------- ### ARX Helper Example in MATLAB Source: https://github.com/byu-prism/gekko/blob/master/gekko-matlab/README.md Demonstrates the use of the ARX (AutoRegressive with eXogenous inputs) helper for system identification. It defines ARX parameters and applies an input signal to predict the output. ```matlab addpath('../src') m = Gekko(); m.remote = true; m.time = linspace(0,10,51); m.options.imode = 4; p = struct(); p.a = 0.7; p.b = zeros(1,2,1); p.b(1,1,1) = 0.2; p.b(1,2,1) = 0.1; p.c = 0.0; [y,u] = m.arx(p); u.value = double(m.time(:) >= 2.0); m.solve(); plot(m.time, y.value) ``` -------------------------------- ### Simulate Process with Input Steps Source: https://github.com/byu-prism/gekko/blob/master/docs/gekko_examples.ipynb Simulates a dynamic process with defined input steps and adds measurement noise to the output. This is used to generate data for subsequent estimation and control examples. ```python nt = 51 # input steps u_meas = np.zeros(nt) u_meas[3:10] = 1.0 u_meas[10:20] = 2.0 u_meas[20:40] = 0.5 u_meas[40:] = 3.0 # simulation model p = GEKKO() p.time = np.linspace(0,10,nt) n = 1 #process model order # Parameters steps = np.zeros(n) p.u = p.MV(value=u_meas) p.u.FSTATUS=1 p.K = p.Param(value=1) #gain p.tau = p.Param(value=5) #time constant # Intermediate p.x = [p.Intermediate(p.u)] # Variables p.x.extend([p.Var() for _ in range(n)]) #state variables p.y = p.SV() #measurement # Equations p.Equations([p.tau/n * p.x[i+1].dt() == -p.x[i+1] + p.x[i] for i in range(n)]) p.Equation(p.y == p.K * p.x[n]) # Simulate p.options.IMODE = 4 p.solve(disp=False) # add measurement noise y_meas = (np.random.rand(nt)-0.5)*0.2 for i in range(nt): y_meas[i] += p.y.value[i] plt.plot(p.time,u_meas,'b:',label='Input (u) meas') plt.plot(p.time,y_meas,'ro',label='Output (y) meas') plt.plot(p.time,p.y.value,'k-',label='Output (y) actual') plt.legend() ``` -------------------------------- ### Summarize GEKKO Results and Suggest Tuning Source: https://github.com/byu-prism/gekko/blob/master/docs/mcp.md Retrieve model options and summarize solve results using the ModelMCP helper. Use suggest_tuning_changes to get rule-based recommendations for improving solver performance or model behavior. ```python from gekko import gk_mcp helper = gk_mcp.ModelMCP(m) options = helper.get_options() results = helper.summarize_results() tuning = helper.suggest_tuning_changes(goal="faster solve with smoother MV movement") ``` -------------------------------- ### Simulate Process with Measurement Noise Source: https://github.com/byu-prism/gekko/blob/master/examples/gekko_18examples.ipynb This example simulates a first-order process and adds measurement noise to the output. It's useful for testing system identification or control algorithms that need to handle noisy data. ```python from gekko import GEKKO import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Generate "data" with process simulation nt = 51 # input steps u_meas = np.zeros(nt) u_meas[3:10] = 1.0 u_meas[10:20] = 2.0 u_meas[20:40] = 0.5 u_meas[40:] = 3.0 # simulation model p = GEKKO() p.time = np.linspace(0,10,nt) n = 1 #process model order # Parameters steps = np.zeros(n) p.u = p.MV(value=u_meas) p.u.FSTATUS=1 p.K = p.Param(value=1) #gain p.tau = p.Param(value=5) #time constant # Intermediate p.x = [p.Intermediate(p.u)] # Variables p.x.extend([p.Var() for _ in range(n)]) #state variables p.y = p.SV() #measurement # Equations p.Equations([p.tau/n * p.x[i+1].dt() == -p.x[i+1] + p.x[i] for i in range(n)]) p.Equation(p.y == p.K * p.x[n]) # Simulate p.options.IMODE = 4 p.solve(disp=False) # add measurement noise y_meas = (np.random.rand(nt)-0.5)*0.2 for i in range(nt): y_meas[i] += p.y.value[i] plt.plot(p.time,u_meas,'b:',label='Input (u) meas') plt.plot(p.time,y_meas,'ro',label='Output (y) meas') plt.plot(p.time,p.y.value,'k-',label='Output (y) actual') plt.legend() ``` -------------------------------- ### Define Multi-Phase Dynamic Optimization Problem in GEKKO Source: https://github.com/byu-prism/gekko/blob/master/docs/examples.md This snippet sets up a multi-phase dynamic optimization problem. It defines parameters, variables, equations for each phase, connections between phases, and the objective function. Ensure GEKKO is installed and imported. ```python import numpy as np from gekko import GEKKO import matplotlib.pyplot as plt # Initialize GEKKO m = GEKKO() # Number of collocation nodes nodes = 3 # Number of phases n = 5 # Time horizon (for all phases) m.time = np.linspace(0,1,100) # Input (constant in IMODE 4) u = [m.Var(1,lb=-2,ub=2,fixed_initial=False) for i in range(n)] # Example of same parameter for each phase tau = 5 # Example of different parameters for each phase K = [2,3,5,1,4] # Scale time of each phase tf = [1,2,4,8,16] # Variables (one version of x for each phase) x = [m.Var(0) for i in range(5)] # Equations (different for each phase) for i in range(n): m.Equation(tau*x[i].dt()/tf[i]==-x[i]+K[i]*u[i]) # Connect phases together at endpoints for i in range(n-1): m.Connection(x[i+1],x[i],1,len(m.time)-1,1,nodes) m.Connection(x[i+1],'CALCULATED',pos1=1,node1=1) # Objective # Maximize final x while keeping third phase = -1 m.Obj(-x[n-1]+(x[2]+1)**2*100) # Solver options m.options.IMODE = 6 m.options.NODES = nodes # Solve m.solve() # Calculate the start time of each phase ts = [0] for i in range(n-1): ts.append(ts[i] + tf[i]) # Plot plt.figure() tm = np.empty(len(m.time)) for i in range(n): tm = m.time * tf[i] + ts[i] plt.plot(tm,x[i]) plt.show() ``` -------------------------------- ### Install GEKKO in Jupyter Notebook Source: https://github.com/byu-prism/gekko/blob/master/docs/index.md Install GEKKO within a Jupyter notebook environment using pip. This method is not preferred. ```python try: from pip import main as pipmain except: from pip._internal import main as pipmain pipmain(['install','gekko']) ``` -------------------------------- ### Example GEKKO Equation Source: https://github.com/byu-prism/gekko/blob/master/docs/quick_start.md An example of defining an equation with variables x, y, and z using Python syntax within GEKKO. ```python m.Equation(3*x == (y**2)/z) ``` -------------------------------- ### Add Gekko-MATLAB to MATLAB Path Source: https://github.com/byu-prism/gekko/blob/master/gekko-matlab/README.md Installs the Gekko-MATLAB library by adding its source folder to the MATLAB path. Ensure the path is correct for your installation. ```matlab addpath('path/to/gekko-matlab/src'); ``` -------------------------------- ### Example Usage of if2 Conditional Source: https://github.com/byu-prism/gekko/blob/master/docs/model_methods.md Demonstrates the practical application of the `if2` function by plotting its output over time. This example uses constants and a time-dependent condition to switch between two values. ```default import numpy as np from gekko import gekko m = gekko() x1 = m.Const(5) x2 = m.Const(6) t = m.Var(0) m.Equation(t.dt()==1) m.time = np.linspace(0,10) y = m.if2(t-5,x1,x2) m.options.IMODE = 6 m.solve() import matplotlib.pyplot as plt plt.plot(m.time,y) plt.show() ``` -------------------------------- ### GEKKO Steady-State Optimization (IMODE 3) Source: https://context7.com/byu-prism/gekko/llms.txt Demonstrates steady-state optimization using IMODE 3. Requires defining variables, equations, and an objective function. ```python m3 = GEKKO(remote=False) x3 = m3.Var(value=1, lb=0, ub=10) y3 = m3.Var(value=1, lb=0, ub=10) m3.Equation(x3 + y3 == 5) m3.Maximize(x3 * y3) m3.options.IMODE = 3 m3.solve(disp=False) print(f"IMODE 3 (SS Opt): x={x3.value[0]:.2f}, y={y3.value[0]:.2f}") ``` -------------------------------- ### Moving Horizon Estimation (MHE) Example in GEKKO Source: https://context7.com/byu-prism/gekko/llms.txt Performs Moving Horizon Estimation to identify a decay constant and initial state from noisy measurements. This example uses GEKKO in estimation mode (IMODE=5) and requires NumPy for data generation. ```python from gekko import GEKKO import numpy as np m = GEKKO(remote=False) # Measurement data (with noise) t_meas = np.linspace(0, 5, 21) y_meas = 10 * np.exp(-0.5 * t_meas) + 0.5 * np.random.randn(21) m.time = t_meas # Parameter to estimate k = m.FV(value=0.3, lb=0.01, ub=2) k.STATUS = 1 # Allow optimizer to adjust # State with measurements y = m.CV(value=y_meas) y.FSTATUS = 1 # Use measurements y.MEAS_GAP = 0.5 # Dead-band around measurement # Model m.Equation(y.dt() == -k * y) # Estimation mode m.options.IMODE = 5 m.options.EV_TYPE = 2 # Squared error m.options.NODES = 4 m.solve(disp=False) print(f"Estimated decay constant k = {k.value[0]:.4f}") print(f"True value: k = 0.5") print(f"Initial state: y(0) = {y.value[0]:.2f}") ``` -------------------------------- ### Get Thermodynamic Property Source: https://github.com/byu-prism/gekko/blob/master/docs/chemical.md Retrieves thermodynamic properties for defined compounds. ```APIDOC ## Get Thermodynamic Property ### Description Retrieves thermodynamic properties for the compounds defined in the `chemical.Properties` object. Properties can be temperature-independent constants or temperature-dependent quantities. ### Method `c.thermo(name, [T])` ### Parameters #### Path Parameters - **name** (string) - Required - The name of the thermodynamic property to retrieve (e.g., 'mw', 'lvp'). - **T** (GEKKO Parameter or Variable) - Optional - The temperature in Kelvin for temperature-dependent properties. ### Request Example ```python from gekko import GEKKO, chemical m = GEKKO() c = chemical.Properties(m) c.compound('water') c.compound('hexane') # Molecular weight (temperature independent) mw = c.thermo('mw') # Liquid vapor pressure (temperature dependent) T = m.Param(value=310) vp = c.thermo('lvp',T) m.solve(disp=False) print(mw) print(vp) ``` ### Response - **property_value** (float or GEKKO Array) - The value(s) of the requested thermodynamic property. ``` -------------------------------- ### Solver Selection in GEKKO Source: https://github.com/byu-prism/gekko/blob/master/docs/examples.md Demonstrates how to select a specific solver (e.g., APOPT or IPOPT) for solving equations. Ensure the solver is available and configured. ```python from gekko import GEKKO m = GEKKO() y = m.Var(value=2) m.Equation(y**2==1) m.options.SOLVER=1 m.solve(disp=False) print('y: ' + str(y.value)) ``` -------------------------------- ### Upgrade GEKKO with pip Source: https://github.com/byu-prism/gekko/blob/master/docs/index.md Upgrade an existing GEKKO installation to the latest version using pip. ```default pip install --upgrade gekko ``` -------------------------------- ### Free Variable at Initial Condition Source: https://github.com/byu-prism/gekko/blob/master/docs/model_methods.md Frees a variable specifically at the initial time step, enabling the solver to modify its starting value. ```default free_initial(var) ``` -------------------------------- ### Initialize GEKKO Model and Time Source: https://github.com/byu-prism/gekko/blob/master/examples/benchmark_Bryson_Denham.ipynb Initialize a GEKKO model and define the time points for simulation. ```python m = GEKKO(remote=False) nt = 101; m.time = np.linspace(0,1,nt) ``` -------------------------------- ### Initialize Support Agent Source: https://github.com/byu-prism/gekko/blob/master/examples/test_support.ipynb Initializes the support agent with a specified context size to manage the number of past Q+A pairs remembered. Adjust context_size to balance response speed and server timeout avoidance. ```python from gekko import support a = support.agent(context_size=3) ``` -------------------------------- ### GEKKO PID Controller Tuning Source: https://github.com/byu-prism/gekko/blob/master/docs/gekko_examples.ipynb Implement and tune a PID controller within the GEKKO optimization framework. This example models both the controller and the process. ```python from gekko import GEKKO import numpy as np import matplotlib.pyplot as plt %matplotlib inline m = GEKKO() tf = 40 m.time = np.linspace(0,tf,2*tf+1) step = np.zeros(2*tf+1) step[3:40] = 2.0 step[40:] = 5.0 # Controller model Kc = 15.0 # controller gain tauI = 2.0 # controller reset time tauD = 1.0 # derivative constant OP_0 = m.Const(value=0.0) # OP bias OP = m.Var(value=0.0) # controller output PV = m.Var(value=0.0) # process variable SP = m.Param(value=step) # set point Intgl = m.Var(value=0.0) # integral of the error err = m.Intermediate(SP-PV) # set point error m.Equation(Intgl.dt()==err) # integral of the error m.Equation(OP == OP_0 + Kc*err + (Kc/tauI)*Intgl - PV.dt()) # Process model Kp = 0.5 # process gain tauP = 10.0 # process time constant m.Equation(tauP*PV.dt() + PV == Kp*OP) m.options.IMODE=4 m.solve(disp=False) plt.figure() plt.subplot(2,1,1) plt.plot(m.time,OP.value,'b:',label='OP') plt.ylabel('Output') plt.legend() plt.subplot(2,1,2) plt.plot(m.time,SP.value,'k-',label='SP') plt.plot(m.time,PV.value,'r--',label='PV') plt.xlabel('Time (sec)') plt.ylabel('Process') plt.legend() ``` -------------------------------- ### Initialize Trainer Source: https://github.com/byu-prism/gekko/blob/master/docs/llm/README.md Sets up the `transformers.Trainer` with specified training configurations, including hyperparameters like learning rate and batch size. The `...` indicates omitted configuration details. ```python import transformers from datetime import datetime # Training configurations trainer = transformers.Trainer( ... ) ``` -------------------------------- ### Create and Use GEKKO Support Agent Source: https://github.com/byu-prism/gekko/blob/master/docs/support.md Instantiate a support agent to ask questions. Prior interactions are stored as context for follow-up questions. User questions are not stored for LLM training. ```python from gekko import support a = support.agent() a.ask("Can you optimize the Rosenbrock function?") ``` -------------------------------- ### Set IMODE Option in Gekko Source: https://github.com/byu-prism/gekko/blob/master/docs/global.md Demonstrates how to set the IMODE option for a GEKKO model. This is a common starting point for configuring model behavior. ```python from gekko import GEKKO m = GEKKO() m.options.IMODE = 3 ``` -------------------------------- ### Initialize GEKKO Model with MCP Helper Source: https://github.com/byu-prism/gekko/blob/master/docs/mcp.md Instantiate a GEKKO model and wrap it with the ModelMCP helper for direct Python interaction. Use this to access helper functions for model analysis and manipulation. ```python from gekko import GEKKO from gekko import gk_mcp m = GEKKO(remote=False) helper = gk_mcp.ModelMCP(m) dof = helper.get_degrees_of_freedom() options = helper.get_options() tuning = helper.suggest_tuning_changes(goal="faster solve") ``` -------------------------------- ### Import Gekko and ML Modules Source: https://github.com/byu-prism/gekko/blob/master/examples/Gekko_GPR_Optimization.ipynb Imports necessary libraries for Gekko, machine learning, and data manipulation. Includes a fallback to install Gekko if not found. ```python import numpy as np import matplotlib.pyplot as plt import pandas as pd import sklearn.gaussian_process as gp from sklearn.metrics import r2_score from sklearn.model_selection import train_test_split try: from gekko.ML import Gekko_GPR from gekko import GEKKO except: !pip install gekko from gekko.ML import Gekko_GPR from gekko import GEKKO ``` -------------------------------- ### Optimize Final Time with GEKKO Source: https://github.com/byu-prism/gekko/blob/master/examples/gekko_18examples.ipynb This example demonstrates optimizing the final time of a dynamic system. It sets up differential equations for three state variables and uses GEKKO's optimal control mode to minimize the final time while satisfying constraints. ```python from gekko import GEKKO import numpy as np import matplotlib.pyplot as plt %matplotlib inline m = GEKKO() # initialize GEKKO nt = 501 m.time = np.linspace(0,1,nt) # Variables x1 = m.Var(value=np.pi/2.0) x2 = m.Var(value=4.0) x3 = m.Var(value=0.0) p = np.zeros(nt) # final time = 1 p[-1] = 1.0 final = m.Param(value=p) # optimize final time tf = m.FV(value=1.0,lb=0.1,ub=100.0) tf.STATUS = 1 # control changes every time period u = m.MV(value=0,lb=-2,ub=2) u.STATUS = 1 m.Equation(x1.dt()==u*tf) m.Equation(x2.dt()==m.cos(x1)*tf) m.Equation(x3.dt()==m.sin(x1)*tf) m.Equation(x2*final<=0) m.Equation(x3*final<=0) m.Obj(tf) m.options.IMODE = 6 m.solve(disp=False) print('Final Time: ' + str(tf.value[0])) tm = np.linspace(0,tf.value[0],nt) plt.figure(1) plt.plot(tm,x1.value,'k-',label=r'$x_1$') plt.plot(tm,x2.value,'b-',label=r'$x_2$') plt.plot(tm,x3.value,'g--',label=r'$x_3$') plt.plot(tm,u.value,'r--',label=r'$u$') plt.legend(loc='best') plt.xlabel('Time') ``` -------------------------------- ### Optimization of Multiple Linked Phases Source: https://github.com/byu-prism/gekko/blob/master/docs/examples.md Initializes a GEKKO model for optimizing multiple linked phases. This is a starting point for more complex multi-stage optimization problems. ```python import numpy as np from gekko import GEKKO import matplotlib.pyplot as plt # Initialize gekko model m = GEKKO() ``` -------------------------------- ### Gekko LP with Multiple Constraints and Visualization Source: https://github.com/byu-prism/gekko/blob/master/examples/Optimization_Introduction.ipynb Solve a linear programming problem with multiple constraints using Gekko and visualize the solution space with constraints and objective contours. The 'remote=False' option runs the solver locally. ```python # solve LP m = GEKKO(remote=False) x,y = m.Array(m.Var,2,lb=0) m.Equations([6*x+4*y<=24,x+2*y<=6,-x+y<=1,y<=2]) m.Maximize(x+y) m.solve(disp=False) xopt = x.value[0]; yopt = y.value[0] print('x:', xopt,'y:', yopt,'obj:',-m.options.objfcnval) ``` ```python import numpy as np import matplotlib.pyplot as plt # visualize solution g = np.linspace(0,5,200) x,y = np.meshgrid(g,g) obj = x+y plt.imshow(((6*x+4*y<=24)&(x+2*y<=6)&(-x+y<=1)&(y<=2)).astype(int), extent=(x.min(),x.max(),y.min(),y.max()),origin='lower',cmap='Greys',alpha=0.3); # plot constraints x0 = np.linspace(0, 5, 2000) y0 = 6-1.5*x0 # 6*x+4*y<=24 y1 = 3-0.5*x0 # x+2*y<=6 y2 = 1+x0 # -x+y<=1 y3 = (x0*0) + 2 # y <= 2 y4 = x0*0 # x >= 0 plt.plot(x0, y0, label=r'$6x+4y 6*x+4*y<=24$') plt.plot(x0, y1, label=r'$x+2y <=6$') plt.plot(x0, y2, label=r'$-x+y <=1$') plt.plot(x0, 2*np.ones_like(x0), label=r'$y <=2$') plt.plot(x0, y4, label=r'$x >=0$') plt.plot([0,0],[0,3], label=r'$y >=0$') xv = [0,0,1,2,3,4,0]; yv = [0,1,2,2,1.5,0,0] plt.plot(xv,yv,'ko--',markersize=7,linewidth=2) for i in range(len(xv)): plt.text(xv[i]+0.1,yv[i]+0.1,f'({xv[i]},{yv[i]})') # objective contours CS = plt.contour(x,y,obj,np.arange(1,7)) plt.clabel(CS, inline=1, fontsize=10) # optimal point plt.plot([xopt],[yopt],marker='o',color='orange',markersize=10) plt.xlim(0,5); plt.ylim(0,3); plt.grid(); plt.tight_layout() plt.legend(loc=1); plt.xlabel('x'); plt.ylabel('y') plt.show() ``` -------------------------------- ### Configure Solver Options Source: https://github.com/byu-prism/gekko/blob/master/docs/model_methods.md Sets solver options by providing a list of strings, where each string specifies an option and its value. For example, to set maximum iterations and CPU time. ```default m = GEKKO() m.solver_options = ['max_iter 100','max_cpu_time 100'] ``` -------------------------------- ### Model Predictive Control (MPC) with GEKKO Source: https://github.com/byu-prism/gekko/blob/master/examples/gekko_18examples.ipynb This example demonstrates Model Predictive Control (MPC) using GEKKO. It defines a simple dynamic system and configures the optimizer to control a variable to a setpoint. Adjust DCOST and DMAX to influence the manipulated variable's movement. ```python from gekko import GEKKO import numpy as np from random import random import matplotlib.pyplot as plt %matplotlib inline m = GEKKO() m.time = np.linspace(0,20,41) # Parameters mass = 500 b = m.Param(value=50) K = m.Param(value=0.8) # Manipulated variable p = m.MV(value=0, lb=0, ub=100) p.STATUS = 1 # allow optimizer to change p.DCOST = 0.1 # smooth out gas pedal movement p.DMAX = 20 # slow down change of gas pedal # Controlled Variable v = m.CV(value=0) v.STATUS = 1 # add the SP to the objective m.options.CV_TYPE = 2 # squared error v.SP = 40 # set point v.TR_INIT = 1 # set point trajectory v.TAU = 5 # time constant of trajectory # Process model m.Equation(mass*v.dt() == -v*b + K*b*p) m.options.IMODE = 6 # control m.solve(disp=False) # get additional solution information import json with open(m.path+'//results.json') as f: results = json.load(f) plt.figure() plt.subplot(2,1,1) plt.plot(m.time,p.value,'b-',label='MV Optimized') plt.legend() plt.ylabel('Input') plt.subplot(2,1,2) plt.plot(m.time,results['v1.tr'],'k-',label='Reference Trajectory') plt.plot(m.time,v.value,'r--',label='CV Response') plt.ylabel('Output') plt.xlabel('Time') plt.legend(loc='best') ``` -------------------------------- ### Import GEKKO and Supporting Libraries Source: https://github.com/byu-prism/gekko/blob/master/docs/gekko_examples_blank.ipynb Installs and imports the GEKKO package along with common data science libraries like NumPy and Matplotlib for use in a Python notebook environment. ```python # install and import GEKKO # other packages needed in this notebook import numpy as np import matplotlib.pyplot as plt %matplotlib inline ``` -------------------------------- ### Basic Model Definition and Solution in MATLAB Source: https://github.com/byu-prism/gekko/blob/master/gekko-matlab/README.md Demonstrates how to define variables, equations, and an objective function, then solve an optimization problem using Gekko-MATLAB. This is the primary modeling path. ```matlab m = Gekko(); x = m.Var(1,0,10); y = m.Var(2,0,10); m.Equation(x + y == 3); m.Minimize((x-1)^2 + (y-2)^2); m.solve(); ```