byu-prism / gekko Goto Github PK
View Code? Open in Web Editor NEWGEKKO Python for Machine Learning and Dynamic Optimization
Home Page: https://machinelearning.byu.edu
License: Other
GEKKO Python for Machine Learning and Dynamic Optimization
Home Page: https://machinelearning.byu.edu
License: Other
It would be useful to be able to access solver specific options through GEKKO.
See: https://apmonitor.com/wiki/index.php/Main/OptionApmSolver
Hi, this is a question or a potential enhancement.
The "Gekko Optimization Suite" (2018) paper states that "GEKKO operands are required so that first and second derivatives are calculated with automatic differentiation." What about operands or functions not defined in GEKKO? Is there a way to use them, perhaps with numerical differentiation?
I'm mainly interested in functions from numpy.linalg, particularly the matrix determinant (det) and inverse (inv).
Many thanks!
It would be helpful to have consistent ordering across variables and intermediates in their name declarations.
The HS71 example returns the error "CSV_READ was not written correctly" in steady state optimization mode.
It would be nice to be able to set values for parameters and variables using columns from a pandas dataframe. This can be achieved presently using m.x.value = df['x'].values
, so a type check from GEKKO should be able to resolve the issue.
When using the syntax m.x = m.Var(), it would be nice to be able to list the variables that are currently stored in the model, something like print(m.Vars())
perhaps. It would also be nice to be able to iterate over the variables:
for var in m:
var.value = 0
Dividing a Gekko variable by a negative number in an intermediate definition causes a "Multiple operators" error. It looks like it needs another set of parenthesis.
from gekko import GEKKO
m = GEKKO()
a = m.Var()
b = -1
c = m.Intermediate(a/b)
m.solve()
*** Error in syntax of function string: Multiple operators
The Linux (apm) and ARM (apm_arm) version of the local executable no longer requires libraries and the folder os.path.realpath(file))+'/bin/lib'. When the apm binary is missing, I get the following error when I run on Linux:
Local Solve: k2 n0
Traceback (most recent call last):
File "rosenbrock.py", line 60, in
m.solve(disp=False)
File "/home/hedengren/.local/lib/python3.5/site-packages/gekko/gekko.py", line 661, in solve
app = subprocess.Popen([apm_exe, self._model_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE,cwd = self._path, env = {"PATH" : self._path, "LD_LIBRARY_PATH" : os.path.dirname(os.path.realpath(file))+'/bin/lib' }, universal_newlines=True)
File "/usr/lib/python3.5/subprocess.py", line 947, in init
restore_signals, start_new_session)
File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: '/home/hedengren/.local/lib/python3.5/site-packages/gekko/bin/apm'
I tried to resolve the issue by retrieving the apm executable and creating an empty lib directory as:
cd /home/hedengren/.local/lib/python3.5/site-packages/gekko/bin
mkdir lib
wget https://github.com/BYU-PRISM/GEKKO/tree/master/gekko/bin/apm
sudo chmod 775 apm
This resolved the issue but it would be nice to have this modified in the PyPi pip distribution.
We also need a check in the Python code to determine the architecture (Windows, Linux, ARM) and use the appropriate local executable (apm.exe, apm (linux), apm_arm (ARM)).
Setting the upper bound of a variable equal to a Constant raises an error:
from gekko import GEKKO
m = GEKKO()
myConst = m.Const(1)
myVar = m.Var(ub=myConst)
m.build_model()
produces:
>
> File "C:/Users/oacom/Documents/Python Scripts/testGEKKO/testBug.py", line 11, in <module>
> m.build_model()
>
> File "C:\Users\oacom\Anaconda3\lib\site-packages\gekko\gekko.py", line 515, in build_model
> if parameter.UB != None:
>
> File "C:\Users\oacom\Anaconda3\lib\site-packages\gekko\gk_operators.py", line 25, in __len__
> return len(self.value)
>
> File "C:\Users\oacom\Anaconda3\lib\site-packages\gekko\gk_operators.py", line 122, in __len__
> return len(self.value)
>
> TypeError: object of type 'int' has no len()
Add IPOPT to Linux and ARM versions of local executables. IPOPT still works with the default option (remote=True). However, the IPOPT solver is not available when remote=False for a local solve.
Setting the option DIAGLEVEL to any value other than zero results in an error. On remote solve, the solve stops after model building but before the solver is called. On a local solve, this error is displayed:
Error: Exception: Access Violation
At line 7184 of file files.f90 (Unit 10 "apm_lbt.txt")
I ran this example from the documentation and got the same output:
---------------------------------------------------
Solver : APOPT (v1.0)
Solution time : 1.639999999315478E-002 sec
Objective : 17.5322673012512
Successful solution
---------------------------------------------------
Results
x1: [1.358909]
x2: [4.599279]
x3: [4.0]
x4: [1.0]
Objective: 17.5322673
I then checked how the solution would look like when all xi
would be integers, so I changed the definitions for x1
and x2
to
# Initialize variables
x1 = m.Var(value=1, lb=1, ub=5, integer=True)
x2 = m.Var(value=5, lb=1, ub=5, integer=True)
which then gives
Successful solution
---------------------------------------------------
Solver : APOPT (v1.0)
Solution time : 0.103800000011688 sec
Objective : 82.0000000000000
Successful solution
---------------------------------------------------
Results
x1: [4.0]
x2: [4.0]
x3: [2.0]
x4: [2.0]
Objective: 82.0
As one can see, the constraints are fulfilled, however, the objective value is now almost 5 times higher than before when x1
and x2
were not restricted to be integers.
Why is this solution not picked up when x1
and x2
are not constrained to be integers? Which optimization parameters would I have to fine-tune to avoid this local optimum?
A linear time invariant (LTI) system identification function (ARX, State Space, etc) is not currently available in GEKKO. There are functions in APM MATLAB (ARX, Continuous State Space, and Discrete State Space) and APM Python (ARX only). I'd like to request a function similar to apm_id (APM MATLAB) or sysid (APM Python) to facilitate creation of LTI models. I'd be glad to a assist if someone wants to take the lead.
APM MATLAB
The apm_id function in APM MATLAB does this for you. Please see the source at:
https://github.com/APMonitor/apm_matlab/blob/master/apm/apm_id.m
In particular, lines 216-241 converts the ARX model (for identification) into a continuous (sysc) and discrete (sysd) state space form. There are examples on the github site such as:
https://github.com/APMonitor/apm_matlab/blob/master/example_id/myTest.m
https://github.com/APMonitor/apm_matlab/blob/master/example_lti_regression/lti_regression.m
APM Python
You can install APMonitor (previously used before GEKKO) with pip install APMonitor. The apm_id function in APM MATLAB is more capable than the sysid function available in APM Python. The APM Python sysid function is here:
https://github.com/APMonitor/apm_python/blob/master/apm.py (See starting at line 705)
Unlike the APM MATLAB function, the APM Python function does not do the final step of converting to state space. Here is an example:
https://github.com/APMonitor/apm_python/tree/master/example_lti_regression
After many successful solutions of a model predictive controller over succeeding horizons, there is an error accessing the results of a successful solution. The readout is reproduced below. The solve was done remotely, from a computer with a wireless internet connection.
@loganbeal raised the possibility that this problem could be caused by the IP address of the computer changing during the optimization process. This is the second time I have seen an error like this. @APMonitor, does this seem like the most likely cause?
I have connected my computer to the internet with an ethernet cable, with the hope that this will reduce the frequency of this error. I am pre-pending my model name with a string generated from the time and date, which should prevent over-writing other models. Would it be possible to add a feature that could disable the use of the computer's IP address in the model tracking from the APM side?
EXIT: Optimal Solution Found.
The solution was found.
The final value of the objective function is -3238.64169605372
---------------------------------------------------
Solver : IPOPT (v3.9)
Solution time : 13.2771999999968 sec
Objective : -3238.64165515089
Successful solution
---------------------------------------------------
Could not retrieve results.json from server
I noticed that the gekko package does not have a version attribute as most standard packages do.
>>> import numpy
>>> numpy.__version__
'1.16.2'
>>> import gekko
>>> gekko.__version__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'gekko' has no attribute '__version__'
Add support for new APMonitor cubic splines.
My python script is reporting that my derivatives are causing attribute errors as in quotations
"
File "C:\Users\corya\Anaconda3\lib\site-packages\gekko\gk_operators.py", line 36, in getattr
raise AttributeError(name)
AttributeError: dt
"
I did not have this issue prior to updating GEKKO, so I think it may be related. Thanks!
It would be helpful to be able to include underscores in variable names, as an alternative to camel case which is not possible.
This is an enhancement not a bug. There is a python module "copy" that contains a function "deepcopy" which recursively creates a deep copy of a custom made object. For the value attribute of the currently defined GEKKO object (which can be a scalar or an array) the deepcopy function attempts to iterate regardless of whether the value is a scalar (which is not iterable) or an array. The following fix to gk_operators.py allows compatibility with deepcopy (not extensively tested, worked for simple model):
line 160 of gk_operators.py:
def iter(self):
try:
for v in self.value:
yield v
except:
return self.value
feel free to email me at [email protected]
-Will
I'd like to request support for higher-dimensional splines. I've found the 1-D splines to be very useful, and haven't noticed significant slow-downs compared with fitting a function to the data. The advantage in accuracy over a function fit is very beneficial. 2-D splines would be very useful for a suite of optimization scenarios, including my current research. 3-D would also be quite useful, although it may begin to cause some slowdowns depending on the implementation.
With the current 1-D spline capability, it should be possible to implement 2-D splines by building a series of 1-D splines in one dimension and using those to build splines in another dimension. Since this would also include smooth, continuous 1st and 2nd derivatives, it may be easier to implement than bicubic interpolation.
If variable bounds are set/changed after the initial solve, they new bound is not registered. Here's an example with the HS71 problem where the lower bound on x1 is changed from 0.1 to 1:
from gekko import GEKKO
# Initialize Model
m = GEKKO(remote=False)
#initialize variables
x1,x2,x3,x4 = [m.Var() for i in range(4)]
#initial values
x1.value = 1
x2.value = 5
x3.value = 5
x4.value = 1
#lower bounds
x1.lower = .1
x2.lower = 1
x3.lower = 1
x4.lower = 1
#upper bounds
x1.upper = 5
x2.upper = 5
x3.upper = 5
x4.upper = 5
#Equations
m.Equation(x1*x2*x3*x4>=25)
m.Equation(x1**2+x2**2+x3**2+x4**2==40)
#Objective
m.Obj(x1*x4*(x1+x2+x3)+x3)
#Set global options
m.options.IMODE = 3 #steady state optimization
#Solve simulation
m.solve(disp=False) # solve on public server
print(m._variables)
#%% adjust problem and resolve
x1.LOWER = 1
m.solve(disp=False)
print(m._variables)
The output shows that the lower bound of 1 on x1 is not used:
[[0.7545087], [4.639369], [3.788569], [1.885132]]
[[0.7545087], [4.639369], [3.788569], [1.885132]]
The bound_x=True option has an error. I tried the following script:
import numpy as np
import matplotlib.pyplot as plt
xm = np.array([0,1,2,3,4,5])
ym = np.array([0.1,0.2,0.3,0.5,1.0,0.9])
from gekko import GEKKO
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)
#help(m.cspline)
p = GEKKO()
p.x = p.Var(value=1,lb=0,ub=5)
p.y = p.Var()
p.cspline(p.x,p.y,xm,ym,bound_x=True)
p.Obj(-p.y)
p.solve(disp=False)
plt.plot(xm,ym,'bo')
plt.plot(m.x.value,m.y.value,'r--')
plt.plot(p.x.value,p.y.value,'ko')
plt.show()
I can add bounds manually but I'd like to add them automatically to avoid extrapolation error.
** Current **
There is no example on MPC on https://gekko.readthedocs.io/en/latest/examples.html
** Desired **
An example on MPC, as this is a likely differentiating capability of GEKKO w.r.t. other optimization toolkits.
Say I have the following, where I want to reuse a model in multiple places. Other than using the gekko model's built-in _variables
attribute, is there a "right" way to access the variable x
?
def getModel():
m = GEKKO()
m.Var(value=5, name='x')
return m
m = getModel()
# How to access variable x?
Putting x
in the global scope is not what I intend.
Attempting to initialize a variable using a constant i.e. x = m.Var(value=myConst.value) results in no value being assigned to the variable.
GEKKO is writting MV properties LB and UB that are not needed. The APM executable ignores them so this isn't a critical issue.
APM.CYCLECOUNT = 0
APM.PRED_HOR = 1.0
APM.PRED_TIME = 60.0
p1.LB = 1e-05
p1.UB = 1
p1.FSTATUS = 0
p1.LOWER = 1e-05
p1.STATUS = 1
p1.UPPER = 1
p1.DCOST = 0.01
You can find this in overrides.dbs. The above is just the relevant section that includes the MV properties.
Custom named variables with capital letters are not read correctly from the results file. This is probably because APMonitor takes everything to lowercase.
I've seen two different errors that seem to be related to this:
E_Batt not found in results file
or
File "", line 1, in
m.solve()
File "C:\Users\UAV-PRISM\Anaconda3\lib\site-packages\gekko\gekko.py", line 365, in solve
self.load_JSON()
File "C:\Users\UAV-PRISM\Anaconda3\lib\site-packages\gekko\gekko.py", line 703, in load_JSON
vp.dict[o] = data[vp.name][o]
KeyError: 'P_bat'
It seems like final value constraints come up enough in dynamic problems that it would be worth adding them directly to the interface. Something like x.final = 0 perhaps?
Gekko translates a negative exponent such as x**(-1) to x^-1 when it writes the model file. This causes the error *** Error in syntax of function string: Multiple operators in APMonitor when attempting a solve.
What is the current behavior of the csv_read option in GEKKO?
GEKKO needs to clear the application on the first cycle when remote=True else certain files become very large such as overrides.dbs and 127.0.0.1_gk_model0.info. Options also persist from prior applications. I tested this with m.server='http://127.0.0.1' and repeatedly solved a problem such as would happen with mhe or mpc. The INFO file has 3354 lines (all from 1 MV and 1 CV declared) and the overrides.dbs file is over 600 KB. Adding to the file each solve will make it large and will slow down the execution as all the lines are parsed.
I recommend two possible things:
I'd like to run GEKKO for a couple weeks, months, or years with scheduled cycles and want to make sure that the application doesn't slow down when running either on a remote server or else on a localhost server.
I could also do something on the APM side to manage the overrides.dbs and info file size like is done with measurements.dbs where the file contents are deleted when a measurement is read. Only the last measurement in the list is implemented so it is okay to have a separate process sending a stream of measurements to the file - it will always use the most updated measurement. The overrides.dbs and info files would be different in that I'd only keep the latest definitions. The one thing that this can't manage is information from a prior application such as MV, FV, or CV declarations.
Running Python 3 in a Windows 10 environment. When calling m.GUI(), a server is created, but when navigating to the page specified by the port, a 404 (page not found) error is returned.
When the default server is down a gekko object can't be created, even if only using the local solve option.
Ex:
from gekko import*
m = GEKKO()
m.solve(remote = False)
Doesn't work when the default server is down.
But when I add the name of a working server:
from gekko import*
m = GEKKO(server='server_name')
m.solve(remote = False)
Then it works.
Would like to suggest improved readability of names by replacing special characters and spaces with an underscore.
For example the name, 'pseudo effective Heat Transfer Coefficient (W/m2-K)' instead of current value of 'pseudoeffectiveheattransfercoefficeintwm2k' can become 'pseudo_effective_heat_transfer_coefficient_w_m2_k_'
with name = re.sub('[^0-9a-zA-Z]+', '_',t).lower()
Looks like APM doesn't like upper case and the fix was accomplished with
def MV(self, value=None, lb=None, ub=None, integer=False, fixed_initial=True, name=None):
"""Change these variables optimally to meet objectives"""
if name is not None:
name = re.sub(r'\W+', '', name).lower()
else:
name = 'p' + str(len(self.parameters) + 1)
if integer == True:
name = 'int'+name
GEKKO's solution for parsing expressions in m.Equation
, m.Intermediate
, and m.Obj
is really slick. I understand that it simply uses operator overloading to construct a string version of the expression that is later parsed by APMonitor. Entering expressions into GEKKO this way is fast and intuitive.
However, there is currently no way to use a custom function:
def myComplicatedFunction(x):
# ...Do work
return result
m = GEKKO()
x = m.Var()
m.Obj( myComplicatedFunction(x) )
I understand that it would take a major architectural change to support this, as models are transmitted to APMonitor in string format. There appear to be some python libraries that can serialize functions, such as dill, but that might be a headache in itself, since if I'm not mistaken, APMonitor is not even written in python, so it would take some work to get the server to evaluate a custom function in this way. And having the server communicate over the wire to ask the client to evaluate an objective function probably wouldn't be fast enough unless the server was running locally.
Are there any plans to expose the powerful solvers of APMonitor in such a way that custom functions can be passed to them? I know it's possible to use the free solvers on their own, but then you lose all of the convenience that APMonitor provides. Here is another question I don't know the answer to: Does APMonitor examine the form of expressions symbolically to determine how to set up the problem, and which solver to use? Clearly, using the string expressions would be advantageous if this were the case.
I am trying to compare differences and debug between two versions of a model I have written in gekko. When solving dynamically in simultaneous mode, I am able to investigate the results closely by comparing the values of the intermediates which are written to the results file. The values of the intermediates are written to the results file alongside the variables.
However, when solving in sequential mode, only the values of the variables are written to the results file. I need to see the values of the intermediates in addition to the values of the variables for the purpose of debugging and comparing the two models--a feature which apparently is not currently available.
Thank you!
I am trying to solve a simple ODE system:
du/dt = v
dv/dt = - u
with initial conditions u[0] = 1
and v[0] = 0
The anaytical solution is u[t] = cos(t)
and v[t] = sin(t)
I am using the following GEKKO code:
LL = GEKKO()
LL.time = np.linspace(0,24*np.pi,1000)
S = [LL.Var(value=1), LL.Var(value=0)]
t = LL.Param(value=LL.time)
LL.Equations([S[0].dt() == -S[1], S[1].dt() == S[0]])
LL.options.IMODE = 4
LL.solve(disp=False)
For some reason, the solution has an exponential decay....
Wolfram Mathematica solves the same equations just fine.
It would be useful to have variables be named automatically to whatever they are set equal to, instead of requiring separate names designated inside of quotes.
It looks like when there are multiple models in one script, the GUI doesn't verify that the variables it's loading pertain to the associated model. For example, the GEKKO/tests/mpc_example.py fails on the rocket problem with KeyError: 'p1'
, but there isn't a p1
on the rocket problem. I think p1
comes from the CSTR problem solved earlier.
When I try to assign a gekko Param to a Var:
import numpy as np
from gekko import GEKKO
m = GEKKO()
m.options.IMODE = 4
m.time = np.linspace(0, 10, 11)
T0 = m.Param(298.15)
T = m.Var(T0.value) # Assign T0 to T
m.Equation(T.dt() == 1)
m.solve()
I get this:
Traceback (most recent call last):
File "/home/eric/Documents/Dynamic Optimization/Temp control Lab A/debug.py", line 13, in <module>
m.solve()
File "/home/eric/.local/lib/python2.7/site-packages/gekko/gekko.py", line 661, in solve
self._write_csv()
File "/home/eric/.local/lib/python2.7/site-packages/gekko/gk_write_files.py", line 166, in _write_csv
elif len(vp.VALUE) == 1:
File "/home/eric/.local/lib/python2.7/site-packages/gekko/gk_operators.py", line 134, in __len__
return len(self.value)
File "/home/eric/.local/lib/python2.7/site-packages/gekko/gk_operators.py", line 134, in __len__
return len(self.value)
TypeError: object of type 'float' has no len()
If I just assign a number to it, it works:
T0 = m.Param(298.15)
T = m.Var(298.15) # This works
Being able to assign one Param to another, or at the very least a better error message, would be helpful.
Let's say I want to maximize
cos(x1) + cos(x2) + cos(x3)
where
x1 + x2 + x3 = n
with 1 <= xi <= n
and xi
should be an integer.
Then I can do:
from gekko import GEKKO
m = GEKKO()
m.options.SOLVER = 1
# optional solver settings with APOPT
m.solver_options = ['minlp_maximum_iterations 500', \
# minlp iterations with integer solution
'minlp_max_iter_with_int_sol 10', \
# treat minlp as nlp
'minlp_as_nlp 0', \
# nlp sub-problem max iterations
'nlp_maximum_iterations 50', \
# 1 = depth first, 2 = breadth first
'minlp_branch_method 2', \
# maximum deviation from whole number
'minlp_integer_tol 0.05', \
# covergence tolerance
'minlp_gap_tol 0.01']
n = 50
# Initialize variables
x1 = m.Var(value=1, lb=1, ub=n, integer=True)
x2 = m.Var(value=1, lb=1, ub=n, integer=True)
x3 = m.Var(value=1, lb=1, ub=n, integer=True)
# the constraint
m.Equation(x1 + x2 + x3 == n)
# the objective function; we multiply by -1 as we want to maximize
m.Obj(-1*(m.cos(x1) + m.cos(x2) + m.cos(x3)))
m.solve(disp=True)
print('Results')
print('x1: ' + str(x1.value))
print('x2: ' + str(x2.value))
print('x3: ' + str(x3.value))
print('Objective: ' + str(m.options.objfcnval))
This will print:
--Integer Solution: -1.96E+00 Lowest Leaf: -1.96E+00 Gap: 0.00E+00
Iter: 6 I: 0 Tm: 0.00 NLPi: 2 Dpth: 2 Lvs: 1 Obj: -1.96E+00 Gap: 0.00E+00
Successful solution
---------------------------------------------------
Solver : APOPT (v1.0)
Solution time : 1.420000000507571E-002 sec
Objective : -1.95568412506861
Successful solution
---------------------------------------------------
Results
x1: [1.0]
x2: [24.0]
x3: [25.0]
Objective: -1.95568413
That seems odd as I would expect a value close to 3.
When I then try
x1 = m.Var(value=2, lb=1, ub=n, integer=True)
x2 = m.Var(value=3, lb=1, ub=n, integer=True)
x3 = m.Var(value=4, lb=1, ub=n, integer=True)
I get
----------------------------------------------
Steady State Optimization with APOPT Solver
----------------------------------------------
Iter: 1 I: 0 Tm: 0.00 NLPi: 3 Dpth: 0 Lvs: 0 Obj: -4.40E-01 Gap: 0.00E+00
Successful solution
---------------------------------------------------
Solver : APOPT (v1.0)
Solution time : 1.350000000093132E-002 sec
Objective : -0.440460272267080
Successful solution
---------------------------------------------------
Results
x1: [1.0]
x2: [48.0]
x3: [1.0]
Objective: -0.440460272
And finally, when using
x1 = m.Var(value=3, lb=1, ub=n, integer=True)
x2 = m.Var(value=4, lb=1, ub=n, integer=True)
x3 = m.Var(value=5, lb=1, ub=n, integer=True)
I get
Iter: 7 I: 0 Tm: 0.00 NLPi: 2 Dpth: 2 Lvs: 1 Obj: -2.94E+00 Gap: 0.00E+00
Successful solution
---------------------------------------------------
Solver : APOPT (v1.0)
Solution time : 1.550000000861473E-002 sec
Objective : -2.94007771670051
Successful solution
---------------------------------------------------
Results
x1: [6.0]
x2: [19.0]
x3: [25.0]
Objective: -2.94007772
So, for three different initial guesses I receive three different objective values (which is, of course, not unusual for numeric optimization).
How do you usually deal with this? Is there a multi-start option or something like this? Thanks!
I am new to GEKKO, it seems an amazing tool but there are some things that are nit entirely clear to me so some help would be greatly appreciated.
I run the code below and get an exception about badly encoded rtesults.json. It is true, the json file contains HTML codeof some 404 server not found page. It is not clear to me:
(a) why this simulator needs to use a json file, why it strangely,
(b) when something seems incorrect (though starting from time 1 is not really incorrect) the json file is ill written and
(c) what is a good method (if any available) to test if the provided ODE is well or ill defined.
long_term_inflation_rate = 0.0173
m = GEKKO(remote=None)
print(m.path+'/results.json')
m.options.IMODE = 4
m.time = np.linspace(1,10,100) # fails to run if not set from zero
t = m.Param(value=m.time)
i = long_term_inflation_rate
x = m.Var(value=10)
#y = m.Var(value=20)
m.Equation(x.dt() == i*x)
m.solve(disp=False)
plt.xlabel('time')
plt.ylabel('x')
plt.plot(m.time,x.value)
When I try to run the ODE solver for a simple equation, and the time is not set from zero then i get this exception. The content of the results.json file is actually HTML content provided after the exception.
ValueError Traceback (most recent call last)
in ()
16 m.Equation(x.dt() == i*x)
17
---> 18 m.solve(disp=False)
19
20 plt.xlabel('time')/usr/local/lib/python2.7/dist-packages/gekko/gekko.pyc in solve(self, disp, debug, GUI, **kwargs)
734 if timing == True:
735 t = time.time()
--> 736 self.load_results()
737 if timing == True:
738 print('load results', time.time() - t)/usr/local/lib/python2.7/dist-packages/gekko/gk_post_solve.pyc in load_results(self)
76 if (os.path.isfile(os.path.join(self._path, 'results.json'))):
77 f = open(os.path.join(self._path,'results.json'))
---> 78 data = json.load(f)
79 f.close()
80/usr/lib/python2.7/json/init.pyc in load(fp, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
289 parse_float=parse_float, parse_int=parse_int,
290 parse_constant=parse_constant, object_pairs_hook=object_pairs_hook,
--> 291 **kw)
292
293/usr/lib/python2.7/json/init.pyc in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
337 parse_int is None and parse_float is None and
338 parse_constant is None and object_pairs_hook is None and not kw):
--> 339 return _default_decoder.decode(s)
340 if cls is None:
341 cls = JSONDecoder/usr/lib/python2.7/json/decoder.pyc in decode(self, s, _w)
362
363 """
--> 364 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
365 end = _w(s, end).end()
366 if end != len(s):/usr/lib/python2.7/json/decoder.pyc in raw_decode(self, s, idx)
380 obj, end = self.scan_once(s, idx)
381 except StopIteration:
--> 382 raise ValueError("No JSON object could be decoded")
383 return obj, endValueError: No JSON object could be decoded
The contents of results.json:
<title>404 Not Found</title>Not Found
The requested URL /online/195.218.17.172_gk_model22/results.json was not found on this server.
Rumor has it that the GUI does not work on Python2. Bug fix the code so it works on both Python2 and Python3.
When attempting to use the MA57 solver on the byu server, the following error is returned:
Exception of type: OPTION_INVALID in file "IpAlgBuilder.cpp" at line 295:
Exception message: Selected linear solver MA57 not available.
Tried to obtain MA57 from shared library "libhsl.so", but the following error occured:
libhsl.so: cannot open shared object file: No such file or directory
Is this related to the recent server upgrade?
The GUI can't be run twice from the same console on Windows 10. I ran it once successfully, stopped the process with Ctrl+C in the console, ran the script again and got this error:
File "C:/Users/beall/Downloads/control3_fishing.py", line 34, in <module>
m.GUI()
File "C:\Anaconda2\lib\site-packages\gekko\gekko.py", line 581, in GUI
gui.display()
File "C:\Anaconda2\lib\site-packages\gekko\gk_gui.py", line 103, in display
self.set_endpoints()
File "C:\Anaconda2\lib\site-packages\gekko\gk_gui.py", line 72, in set_endpoints
@app.route('/get_data')
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1080, in decorator
self.add_url_rule(rule, endpoint, f, **options)
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 64, in wrapper_func
return f(self, *args, **kwargs)
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1051, in add_url_rule
'existing endpoint function: %s' % endpoint)
AssertionError: View function mapping is overwriting an existing endpoint function: get_data
It worked again in a new console.
I get this error trying to launch the GUI from spyder in windows:
Starting Flask Thread on port 8050
Exception in thread Thread-7:
Traceback (most recent call last):
File "C:\Users\SCD\Anaconda3\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Users\SCD\Anaconda3\lib\site-packages\gekko\gk_gui.py", line 395, in run
app.run(debug=False, port=self.port, threaded=True)
File "C:\Users\SCD\Anaconda3\lib\site-packages\flask\app.py", line 938, in run
cli.show_server_banner(self.env, self.debug, self.name, False)
File "C:\Users\SCD\Anaconda3\lib\site-packages\flask\cli.py", line 629, in show_server_banner
click.echo(message)
File "C:\Users\SCD\Anaconda3\lib\site-packages\click\utils.py", line 259, in echo
file.write(message)
io.UnsupportedOperation: not writable
The same script works from the console and in Linux.
Optimizing in IMODE 3 gives a CSV_READ error when variables are initialized without values.
This nasty-looking error has come up when running m.GUI()
to launch the gui on some machines.
As far as I can tell this is not actually an issue with the Gekko project itself, but is actually an error being thrown from chromium in this case. It is also a problem for our friends on the jupyter project as is evidenced in their issue 2836
I'd like to request object support for state space models, especially discrete state space. These are supported in APM MATLAB and APM Python.
https://github.com/APMonitor/apm_python/blob/master/example_lti_regression/
https://github.com/APMonitor/apm_matlab/tree/master/example_lti
Here is an example model: http://apmonitor.com/wiki/index.php/Apps/LinearStateSpace
The discrete state space model should be able to link with other models. If a discrete state space model is used, a uniform time discretization should be enforced or a warning issued if there are non-uniform time intervals.
There is also the apm_id function in APM MATLAB and APM Python that identifies Linear Time-Invariant (LTI) models from data and writes the APM model. Identification can be a separate / future effort. This request is to add support for state space models.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.