Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
fixed = Gekko parameter (True) or variable (False) if []
'''
nc = len(self.m._compounds)
if x==[]:
x = [None]*nc
for i in range(nc):
if fixed:
x[i] = self.m.Param(val)
else:
x[i] = self.m.Var(val)
else:
if len(x)!=nc:
raise Exception('Error: array length must match number of declared compounds: '\
+str(nc))
for i in range(nc):
if not isinstance(x[i],(GKVariable,GKParameter)):
# create input variable if it is an expression
xi = self.m.Var(val)
self.m.Equation(xi==x[i])
x[i] = xi
if cn!='':
for i in range(nc):
self.m._connections.append(x[i].name+'='+cn+'['+str(i+1)+']')
return x
options = {}
try:
var_dict = {
'name': var,
'data': [self.results[main_dict[var].name][0]],
'x': [self.results['time'][0]],
'options': options
}
except Exception:
var_dict = {
'name': var,
'data': [],
'x': [],
'options': options
}
if isinstance(main_dict[var], GKVariable):
self.gekko_data['vars']['variables'].append(var_dict)
if main_dict[var].name + '.tr_hi' in self.results:
d = var_dict.copy()
d['name'] = var + '(Tr_hi)'
self.gekko_data['vars']['variables'].append(d)
if main_dict[var].name + '.tr_lo' in self.results:
d = var_dict.copy()
d['name'] = var + '(Tr_lo)'
self.gekko_data['vars']['variables'].append(d)
if main_dict[var].name + '.tr' in self.results:
d = var_dict.copy()
d['name'] = var + '(Tr)'
self.gekko_data['vars']['variables'].append(d)
if main_dict[var].name + '.bcv' in self.results:
d1 = var_dict.copy()
d1['name'] = var + '_hist(bias)'
def make_vars_map(self):
"""Maps python script names to APMonitor names"""
vars_map = {}
main_dict = vars(main)
for var in main_dict:
if isinstance(main_dict[var], (GKVariable,GKParameter,GK_Intermediate)):
vars_map[main_dict[var].name] = var
if isinstance(main_dict[var], list):
list_var = main_dict[var]
for i in range(len(list_var)):
if isinstance(list_var[i], (GKVariable,GKParameter,GK_Intermediate)):
vars_map[list_var[i].name] = var+'['+str(i)+']'
self.vars_map = vars_map
def Var(self, value=None, lb=None, ub=None, integer=False, fixed_initial=True, name=None):
"""Calculated by solver to meet constraints (Equations). The number of
variables (including CVs and SVs) must equal the number of equations."""
if name is not None:
name = re.sub(r'\W+', '_', name).lower()
else:
name = 'v' + str(len(self._variables) + 1)
if integer == True:
name = 'int_'+name
variable = GKVariable(name, value, lb, ub)
self._variables.append(variable)
if fixed_initial is False:
self.Connection(variable,'calculated',pos1=1,node1=1)
return variable
self.__dict__['_initialized'] = False
if not hasattr(self,'type'): #don't overwrite CV
self.type = 'SV'
self.model_name = gk_model
self.path = model_path #use the same path as the model
# SV specific options
self.FSTATUS = None
self.LOWER = None
self.MEAS = None
self.MODEL = None
self.PRED = None
self.UPPER = None
GKVariable.__init__(self, name, value, lb, ub, integer)
def __init__(self, name='', value=None, lb=None, ub=None, integer=False):
if name == '':
name = 'v' + GKVariable.counter
GKVariable.counter += 1
if integer == True:
name = 'int_'+name
# prevents the __setattr__ function from sending options to the server
# until the __init__ function has completed since they should only be
# sent if changed from their defaults
self.__dict__['_initialized'] = False
GK_Operators.__init__(self, name, value=value)
#self.VALUE = value #initialized value is done in GK_Operators
if not hasattr(self,'type'): #don't overwrite SV and CV
self.type = None
if lb is not None:
except TypeError:
raise AttributeError(str(name)+" is an output property")
#no other properties allowed
else:
raise AttributeError(str(name)+" is not a property of this variable")
#for initializing model
else:
self.__dict__[name] = value
class GK_SV(GKVariable):
"""State Variable. Inherits GKVariable."""
def __init__(self, name='', value=0, lb=None, ub=None, gk_model=None, model_path=None, integer=False):
# prevents the __setattr__ function from sending options to the server
# until the __init__ function has completed since they should only be
# sent if changed from their defaults
self.__dict__['_initialized'] = False
if not hasattr(self,'type'): #don't overwrite CV
self.type = 'SV'
self.model_name = gk_model
self.path = model_path #use the same path as the model
# SV specific options
self.FSTATUS = None
y = StreamObj()
y.name = self.add_obj('Feed')
if self.sl>=1:
# pressure
y.P = self.cxn(y.P,101325.0,y.name+'.P',fixed)
# temperature
y.T = self.cxn(y.T,300.0,y.name+'.T',fixed)
# stream phase
y.phase = self.set_phase(y,phase=y.phase)
# molar flow
y.ndot = self.cxn(y.ndot,1.0,y.name+'.ndot',fixed)
# mole fractions
y.x = self.cxnl(y.x,self.dfrac(),fixed=fixed)
# additional equation for last mole fraction
if isinstance(y.x[-1],GKVariable):
self.m.Equation(y.x[-1]==1-sum(y.x[0:-1]))
# don't connect last mole fraction to stream object (explicit calc)
for i in range(len(self.m._compounds)-1):
self.m._connections.append(y.x[i].name+'='+y.name+'.x['+str(i+1)+']')
return y
def abs2(self,x):
""" Generates the absolute value with continuous first and
second derivatives. The traditional method for absolute value (abs) has
a point that is not continuously differentiable at an argument value
of zero and can cause a gradient-based optimizer to fail to converge.
Usage: y = m.abs2(x)
Input: GEKKO variable, parameter, or expression
Output: GEKKO variable
"""
# verify that x is a valid GEKKO variable or parameter
if isinstance(x,(GKVariable,GKParameter)):
xin = x
else:
# create input variable if it is an expression
xin = self.Var()
self.Equation(xin==x)
# build abs object with unique object name
abs_name = 'abs2_' + str(len(self._objects) + 1)
self._objects.append(abs_name + ' = abs')
# add connections between x and abs object attribute x
self._connections.append(xin.name + ' = ' + abs_name+'.x')
# add connections between y and abs object attribute y
y = self.Var()
self._connections.append(y.name + ' = ' + abs_name+'.y')
return y