BYU-PRISM / GEKKO

GEKKO Python for Machine Learning and Dynamic Optimization
https://machinelearning.byu.edu
Other
594 stars 104 forks source link

Exception: @error: Equation Definition, solve nonlinear equations #122

Closed leavor closed 3 years ago

leavor commented 3 years ago

Problem

Use GEKKO to solve nonlinear equations, the equations are as follows, image alpha, beta, p1, p2 are known, find the unknowns n and c, where n and c are non-negative integers, n≥2, 1≤c≤n, The goal is to minimize the sum of squared errors of the equation A detailed introduction to the system of equations

thanks very much for your help!

Traceback

Traceback (most recent call last):

  File "E:\work\Amos\equation.py", line 51, in <module>
    m.solve(disp=False,debug=1) # Solve

  File "C:\Users\Admin\Anaconda3\envs\python3.7.9\lib\site-packages\gekko\gekko.py", line 2185, in solve
    raise Exception(response)

Exception:  @error: Equation Definition
 Equation without an equality (=) or inequality (>,<)
 false
 STOPPING...

Code

import numpy as np
from gekko import GEKKO
fac = np.math.factorial
p1 = 0.015# AQL
p2 = 0.1# RQL 
alpha = 0.05
beta = 0.1
def func(n,c,p):
    nv = int(str(n.value))
    cv = int(str(c.value))
    p_ac = 0
    for i in range (0,cv+1):
        p_ac = p_ac+binomial(nv,p,i)
    return p_ac

def binomial(n,p,r):
    return fac(n)/(fac(r)*fac(n-r))*p**r*(1-p)**(n-r)

m = GEKKO() # Initialize gekko
n = m.Var(value=2,integer=True)
c = m.Var(value=1,integer=True)

m.Equations([func(n,c,p1)==1-alpha,func(n,c,p2)==beta]) # equations
m.solve(disp=False,debug=1) # Solve
print('Results')
print('n: ' + str(n.value))
print('c: ' + str(c.value))
print(n.value[0],c.value[0]) # print solution
APMonitor commented 3 years ago

Gekko supports many Numpy functions but doesn't support others such as fact. I recommend either rewriting with Gekko functions or else use a solver such as scipy.optimize.minimize(). Here are a couple tutorials that may help: https://apmonitor.com/che263/index.php/Main/PythonOptimization