def __init__(self, m=[], remote=True): if m == []: self.m = GEKKO(remote=remote) else: self.m = m #True if thermo object is created self._thermo_obj = False
def __init__(self, id, x, y, nrj, ctrlHrz, ctrlRes): super().__init__(id, x, y, nrj) self.verbose = False self.errorFlag = False self.m = GEKKO(remote=False) # time points self.ctrlHrz = ctrlHrz # Control Horizon self.ctrlRes = ctrlRes # Control Resolution. Number of control steps within the control horizon self.m.time = np.linspace(0, self.ctrlHrz, self.ctrlRes) # constants self.Egen = 1 * 10**-5 #Counter for plots self.nrplots = 1 self.pltColors = ['r-', 'k-', 'b-', 'g-', 'y-', 'c-', 'm-'] self.labels = [ "Distance", "Velocity", "Energy Consumption", "Data Remaining", "Transmission Rate", "Battery" ] colorNr = rand.randrange(0, len(self.pltColors), 1) self.lineColor = self.pltColors[colorNr] #Threshold for when objective is seen as 0 self.limit = np.float64(1e-10) self.resetGEKKO()
def resetGEKKO(self): self.m = GEKKO(remote=False) self.m.time = np.linspace(0, self.ctrlHrz, self.ctrlRes) self.m.TIME_SHIFT = 1 self.xMove = self.m.MV(integer=True, lb=-self.v, ub=self.v) self.xMove.STATUS = 1 self.yMove = self.m.MV(integer=True, lb=-self.v, ub=self.v) self.yMove.STATUS = 1 self.xP = self.m.Var(value=self.xPos, lb=0, ub=100) self.yP = self.m.Var(value=self.yPos, lb=0, ub=100) self.xTar = self.m.Param() self.yTar = self.m.Param() self.xDist = self.m.CV() self.xDist.STATUS = 1 self.yDist = self.m.CV() self.yDist.STATUS = 1 self.m.options.CV_TYPE = 2 #Squared Error self.m.Equation(self.xDist == self.xP - self.xTar) self.m.Equation(self.yDist == self.yP - self.yTar) self.m.Equation(self.xDist.dt() == self.xMove) self.m.Equation(self.yDist.dt() == self.yMove) self.xErr = self.m.Intermediate((self.xTar - self.xP)) self.yErr = self.m.Intermediate((self.yTar - self.yP)) self.xDist.SP = 0 self.yDist.SP = 0 self.m.options.IMODE = 6
def resetGEKKO(self): self.m = GEKKO(remote=False) self.m.time = np.linspace( 0, self.ctrlHrz, self.ctrlRes) self.pr = self.m.MV(value=self.PA, integer = True,lb=1,ub=20) self.pr.STATUS = 1 self.pr.DCOST = 0
def __init__(self, capital, labour): self.Shock = {'K': capital, 'L': labour} self.use = pd.read_csv('Data\\production_structure.csv', index_col=0) self.xdem = pd.read_csv('Data\\consumption_structure.csv', index_col=0) self.enfac = pd.read_csv('Data\\endowment_of_the_household.csv', index_col=0) self.taxrev = pd.read_csv('Data\\tax_revenue.csv', index_col=0) self.trans = pd.read_csv('Data\\transfers.csv', index_col=0) self.factors = self.use.index self.sectors = self.use.columns self.households = self.xdem.loc[:, self.xdem.columns != 'GOVR'].columns self.beta = pd.DataFrame(index=self.factors, columns=self.sectors) self.alpha = pd.DataFrame(index=self.xdem.index, columns=self.xdem.columns) self.omega = pd.DataFrame(index=self.enfac.index, columns=self.enfac.columns) self.B = {} self.A = {} self.itax = {} self.tr_in = {} self.tr_out = {} self.p = {} self.S = {} self.taxK = {} self.taxL = {} self.PW = {} self.W = {} self.INC = {} self.m = GEKKO(remote=False)
def __init__(self, network: MModel.Network, task_dict: dict, free_utils: dict, commu_dict: dict): self._network = network self._task_dict = task_dict self._free_util = free_utils self._commu_pair = commu_dict self._solver = GEKKO(remote=False) self._vars = {}
def _genMeanVarianceModel(self, nvar, prepared_objective, prepared_constraints, prepared_option): Model = GEKKO(remote=prepared_option.get("remote", False)) x = Model.Array(Model.Var, (nvar, )) Obj = 0 if "f" in prepared_objective: Obj += np.dot(prepared_objective["f"].flatten(), x) if "X" in prepared_objective: Sigma = np.dot( np.dot(prepared_objective["X"], prepared_objective["F"]), prepared_objective["X"].T) + np.diag( prepared_objective["Delta"].flatten()) Sigma = (Sigma + Sigma.T) / 2 Obj += np.dot(np.dot(x, Sigma), x) elif "Sigma" in prepared_objective: Obj += np.dot(np.dot(x, prepared_objective["Sigma"]), x) if "Mu" in prepared_objective: Obj += np.dot(prepared_objective["Mu"].flatten(), x) if "lambda1" in prepared_objective: Obj += prepared_objective["lambda1"] * sum( abs(x - prepared_objective["c"].flatten())) if "lambda2" in prepared_objective: c_pos = prepared_objective["c_pos"].flatten() Obj += prepared_objective["lambda2"] / 2 * sum( abs(x - c_pos) + (x - c_pos)) if "lambda3" in prepared_objective: c_neg = prepared_objective["c_neg"].flatten() Obj += prepared_objective["lambda3"] / 2 * sum( abs(x - c_neg) + (x - c_neg)) Model.Obj(Obj) self._Model, self._x = self._genModelConstraints( Model, x, nvar, prepared_constraints, prepared_option) return 0
def __init__(self): #################GROUND DRIVING OPTIMIZER SETTTINGS############## self.d = GEKKO(remote=False) # Driving on ground optimizer # nt1 nt2 are how many the first half and second half of time will be split # t1 t2 are then concatenated to make the time vector which has variable deltaT # nt1 = 7 # nt2 = 5 # t1 = np.linspace(0,0.5, nt1) # t2 = np.linspace(0.55, 1.0, nt2) # self.d.time = np.concatenate((t1,t2), axis=0) ntd = 31 self.d.time = np.linspace(0, 1, ntd) # Time vector normalized 0-1 # options self.d.options.NODES = 3 self.d.options.SOLVER = 3 self.d.options.IMODE = 6 # MPC mode # m.options.IMODE = 9 #dynamic ode sequential self.d.options.MAX_ITER = 800 self.d.options.MV_TYPE = 0 self.d.options.DIAGLEVEL = 0 # final time for driving optimizer self.tf = self.d.FV(value=1.0, lb=0.1, ub=100.0) # allow gekko to change the tfd value self.tf.STATUS = 1 # Scaled time for Rocket league to get proper time # Acceleration variable self.a = self.d.MV(value=1, lb=0, ub=1) self.a.STATUS = 1 self.a.DCOST = 1e-1 # # Boost variable, its integer type since it can only be on or off # self.u_thrust_d = self.d.MV(value=0,lb=0,ub=1, integer=False) #Manipulated variable integer type # self.u_thrust_d.STATUS = 0 # self.u_thrust_d.DCOST = 1e-5 # # # Throttle value, this can vary smoothly between 0-1 # self.u_throttle_d = self.d.MV(value = 1, lb = 0.02, ub = 1) # self.u_throttle_d.STATUS = 1 # self.u_throttle_d.DCOST = 1e-5 # Turning input value also smooth self.u_turning_d = self.d.MV(lb=-1, ub=1) self.u_turning_d.STATUS = 1 self.u_turning_d.DCOST = 1e-5 # end time variables to multiply u2 by to get total value of integral # Time vector length is nt1 and nt2 self.p_d = np.zeros(ntd) self.p_d[-1] = 1.0 self.final = self.d.Param(value=self.p_d)
def resetGEKKO(self): self.errorFlag = False # Sets errorflag back to false self.m = GEKKO(remote=False) # Creates new GEKKO module self.m.time = np.linspace(0, self.ctrlHrz, self.ctrlRes) self.vp = np.zeros(self.ctrlRes) self.v = self.m.Param(value=self.vp) # define distance self.dist = self.m.Var() self.dtr = self.m.MV(value=0, integer=True, lb=0, ub=20) self.dtr.STATUS = 1 # define energy level self.nrj_stored = self.m.Var(value=self.energy, lb=0) self.data = self.m.Var(value=self.desData) self.DSround = 0 # Data sent this round self.e = self.m.Intermediate(( (Eelec + EDA) * self.conChildren + self.dtr * self.pSize * (Eelec + Eamp * self.dist**2)) - self.Egen) # equations # track the position self.m.Equation(self.dist.dt() == self.v) self.m.Equation(self.nrj_stored.dt() == -self.e) self.m.Equation(self.nrj_stored >= self.e) # as data is transmitted, remaining data stored decreases self.m.Equation(self.data.dt() == -self.dtr * self.pSize) self.deadline = self.m.Var(value=self.ctrlHrz) self.dlCost = self.m.Var() self.m.Equation(self.deadline.dt() == -1) # self.m.Equation(self.energy >= self.e) # objective #self.data.SP = 0 # soft (objective constraint) self.final = self.m.Param(value=np.zeros(self.ctrlRes)) self.final.value[-1] = 1 self.target = self.m.Intermediate((self.final * (0 - self.data)**2)) self.m.Obj(self.target) # transmit data by the end self.m.Obj(self.e) #self.m.Obj(self.final*self.data) # options # Solutions forced to terminate early by the MAX_TIME constraint do # not satisfy the Karush Kuhn Tucker conditions for optimality. self.m.options.MAX_TIME = 10 self.m.options.IMODE = 6 # optimal control self.m.options.NODES = 3 # collocation nodes #self.m.options.CTRLMODE = 3 self.m.options.SOLVER = 1 # solver (IPOPT), 1 is for when integers is used as MV self.m.options.TIME_SHIFT = 1 # Setting for saving values from last solve()
def __init__(self, id, x, y, nrj, ctrlHrz, ctrlRes): super().__init__(id, x, y, nrj) self.verbose = True self.ctrlHrz = ctrlHrz # Control Horizon # time points self.ctrlRes = ctrlRes # Control Resolution. Number of control steps within the control horizon # constants self.Egen = 1*10**-5 self.const = 0.6 self.packet = 1 self.E = 1 self.m = GEKKO(remote=False) self.m.time = np.linspace( 0, self.ctrlHrz, self.ctrlRes) #self.deltaDist = -1.5 self.deltaDist = self.m.FV(value = -1.5) #self.deltaDist.STATUS = 1 # packet rate self.pr = self.m.MV(value=self.PA, integer = True,lb=1,ub=20) self.pr.STATUS = 1 self.pr.DCOST = 0 # Energy Stored self.nrj = self.m.Var(value=0.05, lb=0) # Energy Amount self.d = self.m.Var(value=70, lb = 0) # Distance to receiver self.d2 = self.m.Intermediate(self.d**2) # energy/pr balance #self.m.Equation(self.d.dt() == -1.5) self.m.Equation(self.d.dt() == self.deltaDist) self.m.Equation(self.nrj >= self.Egen - ((Eelec+EDA)*self.packet + self.pr*self.pSize*(Eelec + Eamp * self.d2))) self.m.Equation(self.nrj.dt() == self.Egen - ((Eelec+EDA)*self.packet + self.pr*self.pSize*(Eelec + Eamp * self.d2))) # objective (profit) self.J = self.m.Var(value=0) # final objective self.Jf = self.m.FV() self.Jf.STATUS = 1 self.m.Connection(self.Jf,self.J,pos2='end') self.m.Equation(self.J.dt() == self.pr*self.pSize) # maximize profit self.m.Obj(-self.Jf) # options self.m.options.IMODE = 6 # optimal control self.m.options.NODES = 3 # collocation nodes self.m.options.SOLVER = 1 # solver (IPOPT)
class GekkoContext: def __init__(self, *args, **kwargs): self.solver = GEKKO(*args, **kwargs) def __enter__(self): return self.solver def __exit__(self, exec_type, exec_value, exec_traceback): self.solver.cleanup()
def resetGEKKO(self): self.m = GEKKO(remote=False) self.m.time = np.linspace(0, self.ctrlHrz, self.ctrlRes) self.vp = np.zeros(self.ctrlRes) self.v = self.m.Param(value=self.vp) # define distance self.dist = self.m.Var() self.dtr = self.m.MV(value=1, integer=True, lb=0, ub=20) self.dtr.STATUS = 1 # define energy level self.nrj_stored = self.m.Var(value=self.energy, lb=0) self.data = self.m.Var() # energy to transmit self.e = self.m.Intermediate(( (Eelec + EDA) * self.conChildren + self.dtr * self.pSize * (Eelec + Eamp * self.dist**2)) - self.Egen) # equations # track the position self.m.Equation(self.dist.dt() == self.v) self.m.Equation(self.nrj_stored.dt() == -self.e) # as data is transmitted, remaining data stored decreases self.m.Equation(self.data.dt() == -self.dtr * self.pSize) # self.m.Equation(self.energy >= self.e) # objective self.m.Obj(self.e) # minimize energy # soft (objective constraint) self.final = self.m.Param(value=np.zeros(self.ctrlRes)) self.final.value[int(np.floor(self.ctrlRes / 2)):-1] = 0.001 self.final.value[-1] = 1 #self.m.Equation(self.final*(self.data)<=0) #self.m.Obj(self.data*self.final) self.target = self.m.Intermediate( self.m.sqrt((self.data * self.final)**2)) self.m.Obj(self.target) # transmit data by the end # hard constraint # this form may cause infeasibility if it can't achieve # data=0 at the end #self.m.fix(self.data,self.ctrlRes-1,0) # options self.m.options.IMODE = 6 # optimal control self.m.options.NODES = 3 # collocation nodes self.m.options.SOLVER = 1 # solver (IPOPT), 1 is for when integers is used as MV self.m.options.TIME_SHIFT = 1 # Setting for saving values from last solve()
def __init__(self): self.gekko = GEKKO(remote=False) self.full_model_values = defaultdict() self.reserved_labels = [ 'abs', 'exp', 'log10', 'log', 'sqrt', 'sinh', 'cosh', 'tanh', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'erf', 'erfc' ]
def __init__(self): self.m = GEKKO(remote=False) nt = 11 self.m.time = np.linspace(0, 1, nt) # options # self.m.options.NODES = 3 self.m.options.SOLVER = 1 self.m.options.IMODE = 6 # MPC mode # m.options.IMODE = 9 #dynamic ode sequential self.m.options.MAX_ITER = 200 self.m.options.MV_TYPE = 0 self.m.options.DIAGLEVEL = 0 # final time self.tf = self.m.FV(value=1.0, lb=0.1, ub=100) # tf = m.FV(value=5.0) self.tf.STATUS = 1 # Scaled time for Rocket league to get proper time self.ts = np.multiply(self.m.time, self.tf) # some constants self.g = 650 # Gravity # v_end = 500 # force (thruster) self.u_thrust = self.m.FV(value=1, lb=0, ub=1) #Fixed variable, stays on entire time # self.u_thrust = self.m.MV(value=1, lb=0, ub=1) # Manipulated variable non integaer # self.u_thrust = self.m.MV(value=0,lb=0,ub=1, integer=True) #Manipulated variable integer type # self.u_thrust.STATUS = 1 # self.u_thrust.DCOST = 1e-5 # angular acceleration self.u_pitch = self.m.MV(value=0, lb=-1, ub=1) self.u_pitch.STATUS = 1 self.u_pitch.DCOST = 1e-5 self.Tp = 12.14599781908070 # torque coefficient for pitch self.Dp = -2.798194258050845 # drag coefficient fo rpitch # integral over time for u^2 self.u2 = self.m.Var(value=0) self.m.Equation(self.u2.dt() == 0.5 * self.u_thrust**2) # integral over time for u_pitch^2 # self.u2_pitch = self.m.Var(value=0) # self.m.Equation(self.u2.dt() == 0.5*self.u_pitch**2) # end time variables to multiply u2 by to get total value of integral self.p = np.zeros(nt) self.p[-1] = 1.0 self.final = self.m.Param(value=self.p)
def __init__(self): #################GROUND DRIVING OPTIMIZER SETTTINGS############## self.d = GEKKO(remote=False) # Driving on ground optimizer ntd = 7 self.d.time = np.linspace(0, 1, ntd) # Time vector normalized 0-1 # options # self.d.options.NODES = 3 self.d.options.SOLVER = 3 self.d.options.IMODE = 6 # MPC mode # m.options.IMODE = 9 #dynamic ode sequential self.d.options.MAX_ITER = 200 self.d.options.MV_TYPE = 0 self.d.options.DIAGLEVEL = 0 # final time for driving optimizer self.tf = self.d.FV(value=1.0, lb=0.1, ub=100.0) # allow gekko to change the tfd value self.tf.STATUS = 1 # Scaled time for Rocket league to get proper time # Acceleration variable self.a = self.d.MV(value=1.0, lb=0.0, ub=1.0, integer=True) self.a.STATUS = 1 self.a.DCOST = 1e-10 # # Boost variable, its integer type since it can only be on or off # self.u_thrust_d = self.d.MV(value=0,lb=0,ub=1, integer=False) #Manipulated variable integer type # self.u_thrust_d.STATUS = 0 # self.u_thrust_d.DCOST = 1e-5 # # # Throttle value, this can vary smoothly between 0-1 # self.u_throttle_d = self.d.MV(value = 1, lb = 0.02, ub = 1) # self.u_throttle_d.STATUS = 1 # self.u_throttle_d.DCOST = 1e-5 # Turning input value also smooth # self.u_turning_d = self.d.MV(lb = -1, ub = 1) # self.u_turning_d.STATUS = 1 # self.u_turning_d.DCOST = 1e-5 # end time variables to multiply u2 by to get total value of integral self.p_d = np.zeros(ntd) self.p_d[-1] = 1.0 self.final = self.d.Param(value=self.p_d) # integral over time for u_pitch^2 # self.u2_pitch = self.d.Var(value=0) # self.d.Equation(self.u2.dt() == 0.5*self.u_pitch**2) # Data for generating a trajectory self.initial_car_state = Car() self.final_car_state = Car()
def __init__(self, name=None, remote=True, solver=1): # Problem name self.name = name # Initialize Gekko Model self.model = GEKKO(remote=remote, name=name) # (optional) server='http://xps.apmonitor.com' # Initialize Solver (1=ADOPT, 2=BPOPT, len(slices)=IPOPT) self.model.options.SOLVER = solver
def __init__(self): self.solver = GEKKO(remote=False) ntd = 100 self.solver.time = np.linspace(0, 3, ntd) self.solver.options.NODES = 2 self.solver.options.SOLVER = 3 #Solver Type IPOPT self.solver.options.IMODE = 6 #MPC solution mode, will manipulate MV's to minimize Objective functions
def solve08(): # Nonlinear Regression # 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 # regression equation m.Equation(y == 0.1 * m.exp(a * x)) # regression mode m.options.IMODE = 2 # optimize m.solve(disp=False) # print parameters print('Optimized, a = ' + str(a.value[0])) plt.plot(xm, ym, 'bo') plt.plot(xm, y.value, 'r-') plt.show()
def threePlayersEUtility(): eq = GEKKO(remote=False) p, q, r = eq.Var(), eq.Var(), eq.Var() ## U1(A) == U1(B) eq.Equation(q*p*Fraction(self.utility_tableau[0][0][0][0])+p*(1-q)*self.utility_tableau[0][1][0][0]+(1-p)*q*self.utility_tableau[0][0][1][0]+(1-p)*(1-q)*self.utility_tableau[0][1][1][0]==q*p*self.utility_tableau[1][0][0][0]+p*(1-q)*self.utility_tableau[1][1][0][0]+(1-p)*q*self.utility_tableau[1][0][1][0]+(1-p)*(1-q)*self.utility_tableau[1][1][1][0]) ## U2(A) == U2(B) eq.Equation(r*p*self.utility_tableau[0][0][0][1]+(1-r)*p*self.utility_tableau[1][0][0][1]+r*(1-p)*self.utility_tableau[0][0][1][1]+(1-r)*(1-p)*self.utility_tableau[1][0][1][1]==r*p*self.utility_tableau[0][1][0][1]+(1-r)*p*self.utility_tableau[1][1][0][1]+r*(1-p)*self.utility_tableau[0][1][1][1]+(1-r)*(1-p)*self.utility_tableau[1][1][1][1]) ## U3(A) == U3(B) eq.Equation(r*q*self.utility_tableau[0][0][0][2]+(1-q)*r*self.utility_tableau[0][1][0][2]+(1-r)*q*self.utility_tableau[1][0][0][2]+(1-r)*(1-q)*self.utility_tableau[1][1][0][2]==r*q*self.utility_tableau[0][0][1][2]+(1-q)*r*self.utility_tableau[0][1][1][2]+(1-r)*q*self.utility_tableau[1][0][1][2]+(1-r)*(1-q)*self.utility_tableau[1][1][1][2]) eq.solve(disp=False) return q.value[0],r.value[0],p.value[0]
def inciso2(remote=False): #se intento con esta libreria que se usa para resolver ecuaciones de este tipo a = GEKKO() x = a.Var(value=1) y = a.Var(value=1) w = a.Var(value=1) z = a.Var(value=1) a.Equation(x**2 + 3 * y**2 - z**3 + w**2 - 5 == 0) a.Equation(x**3 - 2 * y**2 - 10 * z + w == 0) a.Equation(x**2 + y**3 + z**2 - w + 20 == 0) a.Equation(x - y**3 + z + w**3 - 10 == 0) a.solve(disp=False) print(x.value, y.value, w.value, z.value)
def init_solver_original(v, machine_task_list): m = GEKKO() # Use IPOPT solver (default) m.options.SOLVER = 3 # Change to parallel linear solver m.solver_options = ['linear_solver ma97'] # variable array dimension n = len(v) # rows # create array s = m.Array(m.Var, n) for i in range(n): s[i].value = 2.0 s[i].lower = 0 P = m.Var(value=5, lb=0) m.Equation(sum([s[i] for i in range(len(v))]) == P) M1 = m.Var(value=5, lb=0) M2 = m.Var(value=5, lb=0) m.Equation(sum([1 / s[i] for i in machine_task_list[0]]) == M1) m.Equation(sum([1 / s[i] for i in machine_task_list[1]]) == M2) return m, s, P, M1, M2
def iniConditions(self, *args): m = GEKKO(remote=False) q = float(self.q_copy.get()) V = float(self.V_copy.get()) Cp = float(self.Cp_copy.get()) EoverR = float(self.EoverR_copy.get()) k0 = float(self.k0_copy.get()) UA = float(self.UA_copy.get()) mdelH = float(self.mdelH_copy.get()) rho = float(self.rho_copy.get()) Tf = float(self.Tf_copy.get()) Tc = float(self.u_ss_copy.get()) Caf = float(self.Caf_copy.get()) T_1 = m.Var(value=300.0) Ca_1 = m.Var(value=1.0) m.Equation(q / (V * 100) * (Tf - T_1) + mdelH / (rho * Cp) * (k0 * 2.7184**(-(EoverR / T_1)) * Ca_1) + UA / (V * 100) / rho / Cp * (Tc - T_1) == 0) m.Equation(q / (V * 100) * (Caf - Ca_1) - (k0 * 2.7184**(-(EoverR / T_1)) * Ca_1) == 0) m.solve() #disp=False self.Ca_ss_copy.set('%7.4f' % Ca_1.value[0]) self.T_ss_copy.set('%7.4f' % T_1.value[0]) pass
def solve_beta_for_single_time_exponential(next_I, curr_I, sigma, N, prev_beta, k, cap_for_searching_exact_sol): #clear_output(wait=True) #print("curr", curr_I, "next", next_I) # if next_I != 0 and curr_I != 0 and next_I != curr_I: # m = GEKKO() # create GEKKO model # beta = m.Var(value=1.0) # define new variable, initial value=0 # m.Equations([((1/(beta-sigma))*m.log(next_I/((beta-sigma)-beta*next_I/N))) - ((1/(beta-sigma))*m.log(curr_I/((beta-sigma)-beta*curr_I/N))) == 1.0]) # equations # m.solve(disp=False) # solve # output = beta.value[0] # else: # output = solve_beta_for_single_time_polynomial(next_I,curr_I,sigma,N,prev_beta) ################################## # data = (next_I,curr_I,sigma,N) # beta_guess = .2 # output = fsolve(function_for_solver, beta_guess, args=data) ################################# #cap_for_searching_exact_sol = 10 output = max( 0, solve_beta_for_single_time_polynomial(next_I, curr_I, sigma, N, prev_beta, k)) if output > cap_for_searching_exact_sol and next_I != 0 and curr_I != 0 and next_I != curr_I: m = GEKKO(remote=False) # create GEKKO model beta = m.Var(value=1.0) # define new variable, initial value=0 m.Equations([((1 / (beta - sigma)) * m.log(k * next_I / ( (beta - sigma) - beta * k * next_I / N))) - ((1 / (beta - sigma)) * m.log(k * curr_I / ( (beta - sigma) - beta * k * curr_I / N))) == 1.0 ]) # equations m.solve(disp=False) # solve output = beta.value[0] return output
def __init__(self, remote=True, bfgs=True, explicit=True): self.m = GEKKO(remote=remote) #generic model options self.m.options.MAX_ITER = 4000 self.m.options.OTOL = 1e-4 self.m.options.RTOL = 1e-4 if bfgs: self.m._solver_options = ['hessian_approximation limited-memory'] self._explicit = explicit self._input_size = None self._output_size = None self._layers = [] self._weights = [] self.input = [] self.output = []
def __init__( self, recipes: Dict[str, 'Recipe'], percentages: Dict[str, float], rates: Dict[str, float], scale_clock: bool = False, shard_mode: ShardMode = ShardMode.NONE, ): self.solved: List[SolvedRecipe] = [] self.recipes, self.rates, self.shard_mode = recipes, rates, shard_mode recipe_clocks = [ (recipes[recipe], clock) for recipe, clock in percentages.items() ] # No network; discontinuous problem; respect integer constraints self.m = m = GEKKO(remote=False, name='satisfactory_power') if scale_clock: logger.warning('Scaling enabled; inexact solution likely') self.clock_scale = m.Var( name='clock_scale', value=1, ) m.Equation(self.clock_scale > 0) else: self.clock_scale = m.Const(1, 'scale') self.buildings, self.building_total = self.define_buildings(recipe_clocks) self.powers, self.power_total = self.define_power(recipe_clocks) self.clocks_each, self.clock_totals = self.define_clocks(recipe_clocks) if shard_mode != ShardMode.NONE: self.shards_each, self.shard_totals, self.shard_total = self.define_shards()
def solve12(): # Model Predictive Control 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') plt.show()
def solve04(): # HS 71 Benchmark # Initialize Model m = GEKKO(remote=True) #help(m) #define parameter eq = m.Param(value=40) #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 == eq) #Objective m.Obj(x1 * x4 * (x1 + x2 + x3) + x3) #Set global options m.options.IMODE = 3 #steady state optimization #Solve simulation m.solve() # solve on public server #Results print('') print('Results') print('x1: ' + str(x1.value)) print('x2: ' + str(x2.value)) print('x3: ' + str(x3.value)) print('x4: ' + str(x4.value))
def solve03(): # Variable and Equation Arrays m = GEKKO() p = m.Param(1.2) x = m.Array(m.Var, 3) eq0 = x[1] == x[0] + p eq1 = x[2] - 1 == x[1] + x[0] m.Equation(x[2] == x[1]**2) m.Equations([eq0, eq1]) m.solve() for i in range(3): print('x[' + str(i) + ']=' + str(x[i].value))
def hs71(): # Initialize Model m = GEKKO() #help(m) #define parameter eq = m.Param(value=40) #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==eq) #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 assert x1.value == [1.0] assert x2.value == [4.743] assert x3.value == [3.82115] assert x4.value == [1.379408]
def solve10(): # Mixed Integer Nonlinear Programming m = GEKKO() # Initialize gekko m.options.SOLVER = 1 # APOPT is an MINLP solver # 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 1', \ # maximum deviation from whole number 'minlp_integer_tol 0.05', \ # covergence tolerance 'minlp_gap_tol 0.01'] # Initialize variables x1 = m.Var(value=1, lb=1, ub=5) x2 = m.Var(value=5, lb=1, ub=5) # Integer constraints for x3 and x4 x3 = m.Var(value=5, lb=1, ub=5, integer=True) x4 = m.Var(value=1, lb=1, ub=5, integer=True) # Equations m.Equation(x1 * x2 * x3 * x4 >= 25) m.Equation(x1**2 + x2**2 + x3**2 + x4**2 == 40) m.Obj(x1 * x4 * (x1 + x2 + x3) + x3) # Objective m.solve(disp=False) # Solve print('Results') print('x1: ' + str(x1.value)) print('x2: ' + str(x2.value)) print('x3: ' + str(x3.value)) print('x4: ' + str(x4.value)) print('Objective: ' + str(m.options.objfcnval))