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 __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 solve13(): # Optimization of Multiple Linked Phases # Initialize gekko model 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()
def param_from_mom(mom): if len(mom) != 3: raise ValueError("Moment dimension should be 3") mu, var, gamma = mom m = GEKKO() delta = m.Var(value=1.06) m.Equation([ gamma == 0.5 * (4 - PI) * ((delta * np.sqrt(2 / PI))**3) / ((1 - 2 * delta * delta / PI)**1.5) ]) m.solve(disp=False) # print("result of delta: {}".format(delta.value)) if len(delta) > 1: print("ERROR in delta") delta = delta.value[0] if np.abs(delta) > 1: print( "Warning: SkewNormal delta {:.5f} out of range!".format(delta)) delta = delta / (np.abs(delta) + 0.001) print("Changed delta to {:.5f}".format(delta)) # print("num delta: {:.3f}".format(delta)) alpha = delta / np.sqrt(1 - delta**2) omega = np.sqrt(var / (1 - (2 * delta * delta / PI))) zeta = mu - omega * delta * np.sqrt(2 / PI) return (zeta, omega, alpha)
def initGekko(alpha, beta, paddle, last_move): m = GEKKO() m.WEB = 0 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.1', \ # covergence tolerance 'minlp_gap_tol 0.01'] m.time = [0, 1, 2, 3] # control variable u = m.MV(lb=-1, ub=1, integer=True) u.DCOST = 0.1 # parameters alpha = m.Param(value=alpha) beta = m.Param(value=beta) # need need the last control vector ulast = m.Var() m.delay(u, ulast, 1) #variable y = m.CV(paddle) #equation m.Equation(y.dt() == (alpha * u) + (beta * ulast)) #options m.options.IMODE = 6 m.options.NODES = 2 m.options.CV_TYPE = 1 y.STATUS = 1 y.FSTATUS = 1 # to do get this from input y.SPHI = 25 y.SPLO = 25 y.TAU = 0 y.TR_INIT = 2 u.STATUS = 1 u.FSTATUS = 0 return m, y, u
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_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 init_solver_machine_scaling(v, machine_task_list, task_machine_dict, O_value=5): """ :param v: number of tasks dependent on each task :param machine_task_list: order :param task_machine_dict: task machine mapping :param O_value: optimal objective value :return: """ 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(machine_task_list) # rows # create array s = m.Array(m.Var, n) for i in range(n): s[i].value = 2.0 s[i].lower = 0 # Optimal value for ibjective O = m.Var(value=O_value, lb=0) # The objective basically m.Equation(sum([int(v[i]) / s[task_machine_dict[i]] + s[task_machine_dict[i]] for i in range(len(v))]) == O) return m, s, O
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 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 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 _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, 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 benchmark3(): m = GEKKO() nt = 101 m.time = np.linspace(0, 1, nt) x1 = m.Var(value=1) x2 = m.Var(value=0) u = m.Var(lb=0, ub=5) final = np.zeros(nt) final[-1] = 1 final = m.Param(value=final) m.Equation(x1.dt() == -(u + 0.5 * u**2) * x1) m.Equation(x2.dt() == u * x1) m.Obj(-final * x2) m.options.IMODE = 6 m.solve(disp=False) assert x1.value == [ 1.0, 0.9897626, 0.9795456, 0.9693489, 0.9591726, 0.9490164, 0.9388805, 0.9287647, 0.918669, 0.9085933, 0.8985376, 0.8885018, 0.8784858, 0.8684897, 0.8585132, 0.8485564, 0.8386191, 0.8287014, 0.818803, 0.8089239, 0.7990641, 0.7892234, 0.7794017, 0.7695989, 0.7598149, 0.7500497, 0.740303, 0.7305747, 0.7208648, 0.711173, 0.7014993, 0.6918435, 0.6822053, 0.6725848, 0.6629816, 0.6533956, 0.6438265, 0.6342743, 0.6247387, 0.6152194, 0.6057162, 0.5962288, 0.586757, 0.5773006, 0.5678592, 0.5584324, 0.54902, 0.5396217, 0.530237, 0.5208655, 0.5115069, 0.5021606, 0.4928263, 0.4835034, 0.4741914, 0.4648897, 0.4555977, 0.4463148, 0.4370403, 0.4277734, 0.4185133, 0.4092592, 0.4000102, 0.3907653, 0.3815233, 0.3722833, 0.3630438, 0.3538036, 0.3445612, 0.3353149, 0.3260631, 0.3168038, 0.3075349, 0.2982541, 0.2889588, 0.2796462, 0.2703132, 0.2609561, 0.2515712, 0.2421538, 0.232699, 0.223201, 0.2136533, 0.2040483, 0.1943772, 0.1846296, 0.1747934, 0.1648539, 0.1547935, 0.1445905, 0.1342179, 0.1236411, 0.1128152, 0.1016802, 0.09015248, 0.07811092, 0.06647803, 0.05657704, 0.04815068, 0.0409793, 0.034876 ] assert x2.value == [ 0.0, 0.007440616, 0.01485305, 0.02223722, 0.02959304, 0.03692043, 0.0442193, 0.05148956, 0.05873113, 0.06594391, 0.07312781, 0.08028274, 0.08740861, 0.09450531, 0.1015727, 0.1086108, 0.1156194, 0.1225984, 0.1295478, 0.1364673, 0.143357, 0.1502166, 0.1570461, 0.1638454, 0.1706143, 0.1773527, 0.1840605, 0.1907375, 0.1973837, 0.2039988, 0.2105828, 0.2171355, 0.2236568, 0.2301464, 0.2366044, 0.2430304, 0.2494244, 0.2557862, 0.2621156, 0.2684125, 0.2746766, 0.2809078, 0.2871059, 0.2932708, 0.2994021, 0.3054998, 0.3115635, 0.3175932, 0.3235885, 0.3295492, 0.3354752, 0.3413661, 0.3472217, 0.3530417, 0.3588259, 0.364574, 0.3702857, 0.3759607, 0.3815986, 0.3871993, 0.3927622, 0.3982871, 0.4037735, 0.4092212, 0.4146296, 0.4199984, 0.4253272, 0.4306153, 0.4358625, 0.441068, 0.4462315, 0.4513522, 0.4564297, 0.4614632, 0.4664519, 0.4713953, 0.4762924, 0.4811424, 0.4859444, 0.4906973, 0.4954001, 0.5000515, 0.5046501, 0.5091946, 0.5136832, 0.518114, 0.522485, 0.5267937, 0.5310373, 0.5352124, 0.539315, 0.5433401, 0.5472814, 0.5511306, 0.5548764, 0.5585023, 0.5618261, 0.5646549, 0.5670625, 0.5691114, 0.5708552 ]
def init_solver(v, O_value=5): 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 # Optimal value for ibjective O = m.Var(value=O_value, lb=0) # The objective basically m.Equation(sum([int(v[i]) / s[i] + s[i] for i in range(len(v))]) == O) return m, s, O
def try_gekko(): m = GEKKO() nt = 101 m.time = np.linspace(0, 1, nt) # Parameters u = m.MV(value=9, lb=-4, ub=10) u.STATUS = 1 u.DCOST = 0 # Variables t = m.Var(value=0) x1 = m.Var(value=0) x2 = m.Var(value=-1) x3 = m.Var(value=np.sqrt(5)) x4 = m.Var(value=0) p = np.zeros(nt) p[-1] = 1 final = m.Param(value=p) m.Equation(t.dt() == 1) m.Equation(x1.dt() == x2) m.Equation(x2.dt() == -x3 * u + 16 * t - 8) m.Equation(x3.dt == u) m.Equation(x4.dt() == x1**2 + x2**2 + .0005 * (x2 + 16 * t - 8 - 0.1 * x3 * u**2))**2 m.Obj(x4 * final)
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 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() # 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 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 __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 solve02(): # Solve NonLinear Equations m = GEKKO() # create GEKKO model x = m.Var(value=0) # define new variable, initial value=0 y = m.Var(value=1) # define new variable, initial value=1 m.Equations([x + 2 * y == 0, x**2 + y**2 == 1]) # equations m.solve(disp=False) # solve print([x.value[0], y.value[0]]) # print solution
def solve05(): # Solver Selection m = GEKKO() # create GEKKO model y = m.Var(value=2) # define new variable, initial value=2 m.Equation(y**2 == 1) # define new equation m.options.SOLVER = 1 # change solver (1=APOPT,3=IPOPT) m.solve(disp=False) # solve locally (remote=False) print('y: ' + str(y.value)) # print variable value
def solve01(): # Solve Linear Equations m = GEKKO() # create GEKKO model x = m.Var() # define new variable, default=0 y = m.Var() # define new variable, default=0 m.Equations([3 * x + 2 * y == 1, x + 2 * y == 0]) # equations m.solve(disp=False) # solve print(x.value, y.value) # print solution
def solve_elecar(inputs, t_interval=10): m = GEKKO() #Parameters v = m.Param(value=inputs['v']) # input voltage to the motor (volts) rm = m.Param(value=inputs['rm']) # motor resistance (ohm) lm = m.Param(value=inputs['lm']) # motor inductance (henrys) kb = m.Param(value=6.5e-4) # back emf constant (volt-sec/rad) kt = m.Param(value=0.1) # torque constant (N-m/a) jm = m.Param(value=inputs['jm']) # rotor inertia (kg m^2) bm = m.Param(value=inputs['bm'] ) # mechanical damping (linear model of friction: bm * dth) # automobile parameters jl = m.Param(value=inputs['jl']) # vehicle inertia (1000 times the rotor) bl = m.Param(value=inputs['bl']) # vehicle damping (friction) k = m.Param( value=inputs['k']) # spring constant for connection rotor/drive shaft b = m.Param( value=inputs['b']) # spring damping for connection rotor/drive shaft rl = m.Param( value=inputs['rl'] ) # gearing ratio between motor and tire (meters travelled per radian of motor rotation) tau = m.Param( value=2 ) # time constant of a lag between motor torque and car velocity. this lag is a simplified model of the power train. (sec) i = m.Var(value=0) # motor electrical current (amps) dth_m = m.Var( value=0) # rotor angular velocity sometimes called omega (radians/sec) th_m = m.Var(value=0) # rotor angle, theta (radians) dth_l = m.Var(value=0) # wheel angular velocity (rad/sec) th_l = m.Var(value=0) # wheel angle (radians) dth_v = m.Var(value=0) # vehicle velocity (m/sec) th_v = m.Var(value=0) # distance travelled (m) m.time = np.linspace(0, t_interval, 100) m.Equation(lm * i.dt() - v == -rm * i - kb * th_m.dt()) m.Equation(jm * dth_m.dt() == kt * i - (bm + b) * th_m.dt() - k * th_m + b * th_l.dt() + k * th_l) m.Equation(jl * dth_l.dt() == b * th_m.dt() + k * th_m - (b + bl) * th_l.dt() - k * th_l) m.Equation(tau * dth_v.dt() == rl * dth_l - dth_v) m.Equation(dth_m == th_m.dt()) m.Equation(dth_l == th_l.dt()) m.Equation(dth_v == th_v.dt()) m.options.IMODE = 4 m.solve(disp=False) res_dict = {} for var in valid_vars: res_dict[var] = eval(var).value[-1] res_dict["t"] = m.time return res_dict
def output_datarate_optimization_GEKKO(q, w, N, M, P, T_s, U_max=1000, Q_max=1, tol=1e-7): ''' inputs: q(k) and w(k) and P(k) set of base stations visible by sensors ''' if N == 0: return [] #initialize the model m = GEKKO(remote=False) q_k = m.Array(m.Param, N) for i in range(N): q_k[i].value = q[i] w_k = m.Array(m.Param, N) for i in range(N): w_k[i].value = w[i] u_k = m.Array(m.Var, (N, M), value=0, lb=0) P_k = m.Array(m.Param, (N, M)) for i in range(N): for j in range(M): P_k[i, j].value = P[i, j] for i in range(N): for j in range(M): m.Equation((1 - P_k[i, j]) * u_k[i, j] <= 0.0) for j in range(M): m.Equation(sum(u_k[:, j]) <= U_max) for i in range(N): m.Equation(q_k[i] + T_s * (w_k[i] - sum(u_k[i, :])) >= 0) m.Equation(q_k[i] + T_s * (w_k[i] - sum(u_k[i, :])) <= Q_max) #Load balancing m.Obj( sum([(sum(u_k[:, i]) - sum(u_k[:, j])) for i in range(M - 1) for j in range(i + 1, M)]) + 100 * sum([(q_k[i] + T_s * (w_k[i] - sum(u_k[i, :]))) for i in range(N)])) m.solve(disp=False) u_final = np.zeros((N, M)) for i in range(N): for j in range(M): u_final[i, j] = u_k[i, j].value[0] if u_final[i, j] < tol: u_final[i, j] = 0 return u_final
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)
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): 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 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): #################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()