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 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 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 solve(var): # initialize model reaction_model = GEKKO() # set model time as time gathered data reaction_model.time = time # Constants R = reaction_model.Const(8.3145) # Gas constant J / mol K # Parameters T = reaction_model.Param(temperature) # Fixed Variables to change # bounds E_a_1 = reaction_model.FV(E_a_1_initial_guess) E_a_2 = reaction_model.FV(E_a_2_initial_guess) A_1 = reaction_model.FV(A_1_initial_guess) A_2 = reaction_model.FV(A_2_initial_guess) alpha = reaction_model.FV(alpha_initial_guess) beta = reaction_model.FV(beta_initial_guess) # NO bounds # state Variables Ph_3_minus = reaction_model.SV(Ph_3_minus_initial) # variable we will use to regress other Parameters Ph_2_minus = reaction_model.SV(Ph_2_minus_initial) # intermediates k1 = reaction_model.Intermediate(A_1 * reaction_model.exp(-E_a_1 / (R * T))) k2 = reaction_model.Intermediate(A_2 * reaction_model.exp(-E_a_2 / (R * T))) r1 = reaction_model.Intermediate(k1 * Ph_2_minus**alpha) r2 = reaction_model.Intermediate(k2 * Ph_3_minus**beta) # equations reaction_model.Equations( [Ph_2_minus.dt() == r2 - r1, Ph_3_minus.dt() == r1 - r2]) # parameter options # controlled variable options # model options and other to solve reaction_model.options.IMODE = 4 # set up dynamic simulation reaction_model.options.NODES = 2 # number of nodes for collocation equations reaction_model.options.SOLVER = 1 # use APOPT active set non-linear solverreaction_model.options.EV_TYPE = 2 # use l-1 norm rather than 2 norm reaction_model.solve(disp=True) return Ph_2_minus.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 solve11(): # error # Moving Horizon Estimation # Estimator Model m = GEKKO() m.time = p.time # Parameters m.u = m.MV(value=u_meas) #input m.K = m.FV(value=1, lb=1, ub=3) # gain m.tau = m.FV(value=5, lb=1, ub=10) # time constant # Variables m.x = m.SV() #state variable m.y = m.CV(value=y_meas) #measurement # Equations m.Equations([m.tau * m.x.dt() == -m.x + m.u, m.y == m.K * m.x]) # Options m.options.IMODE = 5 #MHE m.options.EV_TYPE = 1 # STATUS = 0, optimizer doesn't adjust value # STATUS = 1, optimizer can adjust m.u.STATUS = 0 m.K.STATUS = 1 m.tau.STATUS = 1 m.y.STATUS = 1 # FSTATUS = 0, no measurement # FSTATUS = 1, measurement used to update model m.u.FSTATUS = 1 m.K.FSTATUS = 0 m.tau.FSTATUS = 0 m.y.FSTATUS = 1 # DMAX = maximum movement each cycle m.K.DMAX = 2.0 m.tau.DMAX = 4.0 # MEAS_GAP = dead-band for measurement / model mismatch m.y.MEAS_GAP = 0.25 # solve m.solve(disp=False) # Plot results plt.subplot(2, 1, 1) plt.plot(m.time, u_meas, 'b:', label='Input (u) meas') plt.legend() plt.subplot(2, 1, 2) plt.plot(m.time, y_meas, 'gx', label='Output (y) meas') plt.plot(p.time, p.y.value, 'k-', label='Output (y) actual') plt.plot(m.time, m.y.value, 'r--', label='Output (y) estimated') plt.legend() plt.show()
def calculating_risk_for_single_community(vec_I,population,sigma,ave_k): """ This function computes the daily risk score for a single community given the number of daily infected cases, population of the community, inverse of average recovery dates, and number of times actual infected cases is higher than reported ones.""" # Inputs: # - vec_I : Represents the vector of number of daily infected cases reported for the community # - population : Indicates the population of the community # - sigma : Is equal to 1/D where D represents the average recovery days (usually D is around 7.5) # - ave_k : Average value for the ration of actual active daily infected cases to reported ones (should be >=1) # Outputs: # - risk : Vector of the risk score of the community over time c = len(vec_I) matrix_I = vec_I[np.newaxis,:] beta_SIR,R,risk = np.zeros((c-1,)),np.zeros((c-1,)),np.zeros((c-1,)) for time in range(c-1): #clear_output(wait=True) next_I,curr_I,N = ave_k*vec_I[time+1],ave_k*vec_I[time],population #print("curr", curr_I, "next", next_I) if next_I>curr_I: if next_I != 0 and curr_I != 0 and next_I != curr_I: m = GEKKO(remote=False) # create GEKKO model beta = m.Var(value=.2) # 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: if curr_I != 0: output = (next_I - curr_I+sigma*curr_I)/(curr_I-(1/N)*curr_I**2) else: output = 0 else: if curr_I != 0: output = (next_I - curr_I+sigma*curr_I)/(curr_I-(1/N)*curr_I**2) else: output = 0 beta_SIR[time] = max(0,output) #beta_SIR[time] = max(0,solve_beta_for_single_time_exponential(matrix_I[0,time+1],matrix_I[0,time],sigma,population,0) ) R[time] = beta_SIR[time] / sigma risk[time] = (10000)*R[time]*vec_I[time]*ave_k/(1.0*population) #clear_output(wait=True) return risk
def optimize_gekko(gammas, K_vals, pressure, XHtot, XStot, fO2): m = GEKKO() # create GEKKO model fH2 = m.Var(value=0) # define new variable, initial value=0 fS2 = m.Var(value=0) # define new variable, initial value=0 fH2.lower = 0 # set lower bound to 0 fS2.lower = 0 # set lower bound to 0 m.Equations([ ((fH2 / (gammas['H2'] * pressure)) + ((sympy.Rational(2.0) * K_vals['H2O'] * fH2 * m.sqrt(fO2)) / (sympy.Rational(3.0) * gammas['H2O'] * pressure)) + ((sympy.Rational(2.0) * K_vals['H2S'] * fH2 * m.sqrt(fS2)) / (sympy.Rational(3.0) * gammas['H2S'] * pressure)) - XHtot == 0), ((fS2 / (gammas['S2'] * pressure)) + ((K_vals['H2S'] * fH2 * m.sqrt(fS2)) / (sympy.Rational(3.0) * gammas['H2S'] * pressure)) + ((K_vals['SO2'] * fO2 * m.sqrt(fS2)) / (sympy.Rational(3.0) * gammas['SO2'] * pressure)) - XStot == 0) ]) m.solve(disp=False) return fH2.value[0], fS2.value[0]
def solve_equation(PT, faps): m = GEKKO(remote=False) x = m.Var() y = m.Var() z = m.Var() for fap in faps: x_term = (x - fap.x)**2 y_term = (y - fap.y)**2 z_term = (z - fap.z)**2 radius_term = calculate_radius(PT, fap.snr)**2 # z > 5 to ensure that the UAV is at a reasonable height m.Equations([x_term + y_term + z_term <= radius_term, z > 5.0]) try: m.solve(disp=False) solution = (x.value[0], y.value[0], z.value[0]) except: solution = None return solution
class Brain(): 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._biases = [] self.input = [] self.output = [] def input_layer(self, size): #store input size self._input_size = size #build FV with Feedback to accept inputs self.input = [self.m.Param() for _ in range(size)] # #set FV options # for n in self.input: # n.FSTATUS = 1 # n.STATUS = 0 #add input layer to list of layers self._layers.append(self.input) def layer(self, linear=0, relu=0, tanh=0, gaussian=0, bent=0, leaky=0, ltype='dense'): """ Layer types: dense convolution pool (mean) Activation options: none softmax relu tanh sigmoid linear """ size = relu + tanh + linear + gaussian + bent + leaky if size < 1: raise Exception("Need at least one node") if ltype == 'dense': ## weights between neurons n_p = len(self._layers[-1]) #number of neuron in previous layer n_c = n_p * size # number of axion connections # build n_c FVs as axion weights, initialize randomly in [-1,1] self._weights.append([ self.m.FV(value=[np.random.rand() * 2 - 1]) for _ in range(n_c) ]) for w in self._weights[-1]: w.STATUS = 1 w.FSTATUS = 0 #input times weights, add bias and activate self._biases.append([self.m.FV(value=0) for _ in range(size)]) for b in self._biases[-1]: b.STATUS = 1 b.FSTATUS = 0 count = 0 if self._explicit: # build new neuron weighted inputs neuron_inputs = [ self.m.Intermediate(self._biases[-1][i] + sum( (self._weights[-1][(i * n_p) + j] * self._layers[-1][j]) for j in range(n_p))) for i in range(size) ] #i counts nodes in this layer, j counts nodes of previous layer ##neuron activation self._layers.append([]) if linear > 0: self._layers[-1] += [ self.m.Intermediate(neuron_inputs[i]) for i in range(count, count + linear) ] count += linear if tanh > 0: self._layers[-1] += [ self.m.Intermediate(self.m.tanh(neuron_inputs[i])) for i in range(count, count + tanh) ] count += tanh if relu > 0: self._layers[-1] += [ self.m.Intermediate( self.m.log(1 + self.m.exp(neuron_inputs[i]))) for i in range(count, count + relu) ] count += relu if gaussian > 0: self._layers[-1] += [ self.m.Intermediate(self.m.exp(-neuron_inputs[i]**2)) for i in range(count, count + gaussian) ] count += gaussian if bent > 0: self._layers[-1] += [ self.m.Intermediate( (self.m.sqrt(neuron_inputs[i]**2 + 1) - 1) / 2 + neuron_inputs[i]) for i in range(count, count + bent) ] count += bent if leaky > 0: s = [self.m.Var(lb=0) for _ in range(leaky * 2)] self.m.Equations([ (1.5 * neuron_inputs[i + count]) - (0.5 * neuron_inputs[i + count]) == s[2 * i] - s[2 * i + 1] for i in range(leaky) ]) self._layers[-1] += [ self.m.Intermediate(neuron_inputs[count + i] + s[2 * i]) for i in range(leaky) ] [self.m.Obj(s[2 * i] * s[2 * i + 1]) for i in range(leaky)] self.m.Equations( [s[2 * i] * s[2 * i + 1] == 0 for i in range(leaky)]) count += leaky else: #type=implicit # build new neuron weighted inputs neuron_inputs = [self.m.Var() for i in range(size)] self.m.Equations( [ neuron_inputs[i] == self._biases[-1][i] + sum( (self._weights[-1][(i * n_p) + j] * self._layers[-1][j]) for j in range(n_p)) for i in range(size) ] ) #i counts nodes in this layer, j counts nodes of previous layer ##neuron activation neurons = [self.m.Var() for i in range(size)] self._layers.append(neurons) ##neuron activation if linear > 0: self.m.Equations([ neurons[i] == neuron_inputs[i] for i in range(count, count + linear) ]) count += linear if tanh > 0: self.m.Equations([ neurons[i] == self.m.tanh(neuron_inputs[i]) for i in range(count, count + tanh) ]) for n in neurons[count:count + tanh]: n.LOWER = -5 n.UPPER = 5 count += tanh if relu > 0: self.m.Equations([ neurons[i] == self.m.log(1 + self.m.exp(neuron_inputs[i])) for i in range(count, count + relu) ]) for n in neurons[count:count + relu]: n.LOWER = -10 count += relu if gaussian > 0: self.m.Equations([ neurons[i] == self.m.exp(-neuron_inputs[i]**2) for i in range(count, count + gaussian) ]) for n in neurons[count:count + gaussian]: n.LOWER = -3.5 n.UPPER = 3.5 count += gaussian if bent > 0: self.m.Equations([ neurons[i] == ( (self.m.sqrt(neuron_inputs[i]**2 + 1) - 1) / 2 + neuron_inputs[i]) for i in range(count, count + bent) ]) count += bent if leaky > 0: s = [self.m.Var(lb=0) for _ in range(leaky * 2)] self.m.Equations([ (1.5 * neuron_inputs[count + i]) - (0.5 * neuron_inputs[count + i]) == s[2 * i] - s[2 * i + 1] for i in range(leaky) ]) self.m.Equations([ neurons[count + i] == neuron_inputs[count + i] + s[2 * i] for i in range(leaky) ]) [ self.m.Obj(10000 * s[2 * i] * s[2 * i + 1]) for i in range(leaky) ] #self.m.Equations([s[2*i]*s[2*i+1] == 0 for i in range(leaky)]) count += leaky else: raise Exception('layer type not implemented yet') def output_layer(self, size, ltype='dense', activation='linear'): """ Layer types: dense convolution pool (mean) Activation options: none softmax relu tanh sigmoid linear """ # build a layer to ensure that the number of nodes matches the output self.layer(size, 0, 0, 0, 0, 0, ltype) self.output = [self.m.CV() for _ in range(size)] for o in self.output: o.FSTATUS = 1 o.STATUS = 1 #link output CVs to last layer for i in range(size): self.m.Equation(self.output[i] == self._layers[-1][i]) def think(self, inputs): #convert inputs to numpy ndarray inputs = np.atleast_2d(inputs) ##confirm input/output dimensions in_dims = inputs.shape ni = len(self.input) #consistent layer size if in_dims[0] != ni: raise Exception('Inconsistent number of inputs') #set input values for i in range(ni): self.input[i].value = inputs[i, :] #solve in SS simulation self.m.options.IMODE = 2 #disable all weights for wl in self._weights: for w in wl: w.STATUS = 0 for bl in self._biases: for b in bl: b.STATUS = 0 self.m.solve(disp=False) ##return result res = [] #concatentate result from each CV in one list for i in range(len(self.output)): res.append(self.output[i].value) return res def learn(self, inputs, outputs, obj=2, gap=0, disp=True): """ Make the brain learn. Give inputs as (n)xm Where n = input layer dimensions m = number of datasets Give outputs as (n)xm Where n = output layer dimensions m = number of datasets Objective can be 1 (L1 norm) or 2 (L2 norm) If obj=1, gap provides a deadband around output matching. """ #convert inputs to numpy ndarray inputs = np.atleast_2d(inputs) outputs = np.atleast_2d(outputs) ##confirm input/output dimensions in_dims = inputs.shape out_dims = outputs.shape ni = len(self.input) no = len(self.output) #consistent dataset size if in_dims[1] != out_dims[1]: raise Exception('Inconsistent number of datasets') #consistent layer size if in_dims[0] != ni: raise Exception('Inconsistent number of inputs') if out_dims[0] != no: raise Exception('Inconsistent number of outputs') #set input values for i in range(ni): self.input[i].value = inputs[i, :] #set output values for i in range(no): o = self.output[i] o.value = outputs[i, :] if obj == 1: #set meas_gap while cycling through CVs o.MEAS_GAP = gap #solve in MPU mode self.m.options.IMODE = 2 self.m.options.EV_TYPE = obj self.m.options.REDUCE = 3 #enable all weights for wl in self._weights: for w in wl: w.STATUS = 1 for bl in self._biases: for b in bl: b.STATUS = 1 self.m.solve(disp=disp) def shake(self, percent): """ Neural networks are non-convex. Some stochastic shaking can sometimes help bump the problem to a new region. This function perturbs all weights by +/-percent their values.""" for l in self._weights: for f in l: f.value = f.value[-1] * ( 1 + (1 - 2 * np.random.rand()) * percent / 100)
def pitch(mission, rocket, stage, trajectory, general, optimization, Data): alpha_v = 20 g0 = 9.810665 Re = 6371000 T = stage[0].thrust Mass = rocket.mass ISP = stage[0].Isp Area = stage[0].diameter**2 / 4 * np.pi #The pitch is also considered only in the first stage m = GEKKO(remote=False) m.time = np.linspace(0, trajectory.pitch_time, 101) final = np.zeros(len(m.time)) final[-1] = 1 final = m.Param(value=final) tf = m.FV(value=1, lb=0.1, ub=100) tf.STATUS = 0 alpha = m.MV(value=0, lb=-0.2, ub=0.1) alpha.STATUS = 1 alpha.DMAX = alpha_v * np.pi / 180 * trajectory.pitch_time / 101 x = m.Var(value=Data[1][-1], lb=0) y = m.Var(value=Data[2][-1], lb=0) v = m.Var(value=Data[3][-1], lb=0) phi = m.Var(value=Data[4][-1], ub=np.pi / 2, lb=0) mass = m.Var(value=Data[5][-1]) vG = m.Var(value=Data[7][-1]) vD = m.Var(value=Data[8][-1]) rho = m.Intermediate(rho_func(y)) cD = m.Intermediate(Drag_Coeff(v / (m.sqrt(1.4 * 287.053 * Temp_func(y))))) D = m.Intermediate(1 / 2 * rho * Area * cD * v**2) #D=m.Intermediate(Drag_force(rho_func(y),Temp_func(y),Area,v,1,n)) m.Equations([ x.dt() / tf == v * m.cos(phi), y.dt() / tf == v * m.sin(phi), v.dt() / tf == T / mass * m.cos(alpha) - D / mass - g0 * m.sin(phi) * (Re / (Re + y))**2, ISP * g0 * mass.dt() / tf == -T, v * phi.dt() / tf == (v**2 / (Re + y) - g0 * (Re / (Re + y))**2) * m.cos(phi) + T * m.sin(alpha) / mass, vG.dt() / tf == g0 * m.sin(phi) * (Re / (Re + y))**2, vD.dt() / tf == D / mass ]) #m.fix(alpha,100,0) m.Obj(final * (phi - trajectory.pitch)**2) m.Obj(1e-4 * alpha**2) m.options.IMODE = 6 m.options.SOLVER = 3 m.options.MAX_ITER = 500 m.solve(disp=False) ###Save Data tm = np.linspace(Data[0][-1], m.time[-1] + Data[0][-1], 101) Data[0].extend(tm[1:]) Data[1].extend(x.value[1:]) Data[2].extend(y.value[1:]) Data[3].extend(v.value[1:]) Data[4].extend(phi.value[1:]) Data[5].extend(mass.value[1:]) Data[6].extend(alpha.value[1:]) Data[7].extend(vG.value[1:]) Data[8].extend(vD.value[1:]) print(Data[4][-1]) return Data
n = 1 #process model order #Parameters p.u = p.MV() p.K = p.Param(value=1) #gain p.tau = p.Param(value=5) #time constant #Intermediate p.x = [p.Intermediate(p.u)] #Variables p.x.extend([p.Var() for _ in range(n)]) #state variables p.y = p.SV() #measurement #Equations p.Equations( [p.tau / n * p.x[i + 1].dt() == -p.x[i + 1] + p.x[i] for i in range(n)]) p.Equation(p.y == p.K * p.x[n]) #options p.options.IMODE = 4 #p.u.FSTATUS = 1 #p.u.STATUS = 0 #%% Model m = GEKKO() m.time = np.linspace(0, 20, 41) #0-20 by 0.5 -- discretization must match simulation #Parameters
#%% Model m = GEKKO() #time m.time = np.linspace(0, 15, 61) #parameters to estimate lg10_kr = [m.FV(value=lkr[i]) for i in range(6)] #variables kr = [m.Var() for i in range(6)] H = m.Var(value=1e6) I = m.Var(value=0) V = m.Var(value=1e2) #Variable to match with data LV = m.CV(value=2) #equations m.Equations([10**lg10_kr[i] == kr[i] for i in range(6)]) m.Equations([ H.dt() == kr[0] - kr[1] * H - kr[2] * H * V, I.dt() == kr[2] * H * V - kr[3] * I, V.dt() == -kr[2] * H * V - kr[4] * V + kr[5] * I, LV == m.log10(V) ]) #%% Estimation ## Global options m.options.IMODE = 5 #switch to estimation m.options.TIME_SHIFT = 0 #don't timeshift on new solve m.options.EV_TYPE = 2 #l2 norm m.options.COLDSTART = 2 m.options.SOLVER = 1 m.options.MAX_ITER = 1000
import numpy as np import matplotlib.pyplot as plt from gekko import GEKKO """ Solving 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 """ Mixed-integer nonlinear example """ 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", \
Q.value = random.uniform(low=100, high=10000) #define dThn dTc dTh = m.Array(m.FV, (Nh, Nhe)) dTc = m.Array(m.FV, (Nc, Nhe)) #calculate change in temperature print(Qm) for i in range(Nh): for mf in range(Nhe): dTh[i][mf] = whot[i][mf] * Qm[mf] / Cph[i] for j in range(Nc): for mf in range(Nhe): dTc[j][mf] = wcold[j][mf] * Qm[mf] / Cpc[j] ''' m.Equations(dTh[i][m]==[[whot.T[i][m]*Qm/Cph[i] for i in range(Nh)] for m in range(Nhe)]) m.Equations(dTc[j][m]==[[wcold.T[j][m]*Qm/Cpc[j] for j in range(Nc)] for m in range(Nhe)]) ''' #Calculate outlet temperature Thout = m.Array(m.FV, (Nhe, Nh)) Tcout = m.Array(m.FV, (Nhe, Nc)) for mf in range(Nhe): for i in range(Nh): m.Equations(Thout[mf][i] == Thin[mf][i] - dTh.T[mf][i]) for j in range(Nc): m.Equations(Tcout[mf][j] == Tcin[mf][j] - dTc.T[mf][j]) ''''
from gekko import GEKKO import numpy as np m = GEKKO(remote=False) ni = 3; nj = 2; nk = 4 # solve AX=B A = m.Array(m.Var,(ni,nj),lb=0) X = m.Array(m.Var,(nj,nk),lb=0) AX = np.dot(A,X) B = m.Array(m.Var,(ni,nk),lb=0) # equality constraints m.Equations([AX[i,j]==B[i,j] for i in range(ni) \ for j in range(nk)]) m.Equation(5==m.sum([m.sum([A[i][j] for i in range(ni)]) \ for j in range(nj)])) m.Equation(2==m.sum([m.sum([X[i][j] for i in range(nj)]) \ for j in range(nk)])) # objective function m.Minimize(m.sum([m.sum([B[i][j] for i in range(ni)]) \ for j in range(nk)])) m.solve() print(A) print(X) print(B)
e_initial = 1 / N i_initial = 0.00 r_initial = 0.00 s_initial = 1 - e_initial - i_initial - r_initial alpha = 1 / t_incubation gamma = 1 / t_infective beta = R0 * gamma s, e, i, r = m.Array(m.Var, 4) s.value = s_initial e.value = e_initial i.value = i_initial s.value = s_initial m.Equations([s.dt()==-(1-u)*beta * s * i,\ e.dt()== (1-u)*beta * s * i - alpha * e,\ i.dt()==alpha * e - gamma * i,\ r.dt()==gamma*i]) t = np.linspace(0, 200, 101) t = np.insert(t,1,[0.001,0.002,0.004,0.008,0.02,0.04,0.08,\ 0.2,0.4,0.8]) m.time = t m.options.IMODE = 7 m.options.NODES = 3 m.solve(disp=False) # plot the data plt.figure(figsize=(8, 5)) plt.subplot(2, 1, 1) plt.title('Social Distancing = ' + str(u.value[0] * 100) + '%') plt.plot(m.time, s.value, color='blue', lw=3, label='Susceptible')
A = [m.Param(value=i) for i in areas] #python list comprehension Vin[0] = m.Param(value=vin) #Variables V = [m.Var(value=i) for i in V0] h = [m.Var(value=i) for i in h0] Vout = [m.Var(value=i) for i in Vout0] #Intermediates Vin[1:4] = [m.Intermediate(Vout[i]) for i in range(3)] Vevap = [m.Intermediate(evap_c[i] * A[i]) for i in range(4)] #Equations m.Equations( [V[i].dt() == Vin[i] - Vout[i] - Vevap[i] - Vuse[i] for i in range(4)]) m.Equations([1000 * V[i] == h[i] * A[i] for i in range(4)]) m.Equations([Vout[i]**2 == c[i]**2 * h[i] for i in range(4)]) #Set to simulation mode m.options.imode = 4 #Solve m.solve() #%% Plot results time = [x * 12 for x in m.time] # plot results plt.figure(1) plt.subplot(311)
# Parameters steps = np.zeros(n) p.u = p.MV(value=u_meas) p.u.FSTATUS=1 p.K = p.Param(value=1) #gain p.tau = p.Param(value=5) #time constant # Intermediate p.x = [p.Intermediate(p.u)] # Variables p.x.extend([p.Var() for _ in range(n)]) #state variables p.y = p.SV() #measurement # Equations p.Equations([p.tau/n * p.x[i+1].dt() == -p.x[i+1] + p.x[i] for i in range(n)]) p.Equation(p.y == p.K * p.x[n]) # Simulate. p.options.IMODE = 4 p.solve(disp=False) # Add measurement noise. y_meas = (np.random.rand(nt)-0.5)*0.2 for i in range(nt): y_meas[i] += p.y.value[i] # Plot our simulated input and output data. plt.plot(p.time, u_meas, "b:", label="Input (u) measurement") plt.plot(p.time, y_meas, "ro", label="Output (y) measurement")
final = m.Param(value=final) #Manipulated variable u = m.Var(value=0) #Variables theta = m.Var(value=0) q = m.Var(value=0) #Controlled Variable y = m.Var(value=-1) v = m.Var(value=0) #Equations m.Equations([ y.dt() == v, v.dt() == mass2 / (mass1 + mass2) * theta + u, theta.dt() == q, q.dt() == -theta - u ]) #Objective m.Obj(final * (y**2 + v**2 + theta**2 + q**2)) m.Obj(0.001 * u**2) #%% Tuning #global m.options.IMODE = 6 #control #%% Solve m.solve() #%% Plot solution
print("") print("- Setting Contraints") print(" 1. Initial State and Time") # initial time # Starting Point and Goal Point (R^3) StartPoint = cls.StartPoint #np.array([[3],[3],[3]]) EndPoint = cls.EndPoint #np.array([[18],[18],[8]]) x0 = np.zeros((12)) x0[state['x']] = StartPoint[0,0] x0[state['y']] = StartPoint[1,0] x0[state['z']] = StartPoint[2,0] epsilon = 0.03 m.Equation(t_list[0] == 0) # m.Equations([min(max(epsilon*Set_num_roots[i-1], 0.5),0.5) <= t_list[i] - t_list[i-1] for i in range(1, num_corr + 1)]) m.Equations([t_list[-1]/(num_corr*2.0) <= t_list[i] - t_list[i-1] for i in range(1, num_corr + 1)]) m.Equations([X_list[0][0, i] == x0[i] for i in range(dim_state)]) print(" 2. Corridor's Start States and End States") for j in range(dim_state): m.Equations([ X_list[i][-1, j] == X_list[i+1][0, j] for i in range(num_corr - 1)]) #### 20210528 revision #### ####### differentiable condition ###### for i in range(num_corr - 1): Di_N = Set_DiffMat[i][-1,:] Dip1_bar = Set_Dbar[i+1] DX_iN = np.matmul(Di_N, X_list[i]) DX_ip10 = np.matmul(Dip1_bar, X_list[i+1]) m.Equations([ DX_iN[j] == DX_ip10[j] for j in range(dim_state)])
def reservoirs(): #Initial conditions c = np.array([0.03, 0.015, 0.06, 0]) areas = np.array([13.4, 12, 384.5, 4400]) V0 = np.array([0.26, 0.18, 0.68, 22]) h0 = 1000 * V0 / areas Vout0 = c * np.sqrt(h0) vin = [ 0.13, 0.13, 0.13, 0.21, 0.21, 0.21, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13 ] Vin = [0, 0, 0, 0] #Initialize model m = GEKKO() #time array m.time = np.linspace(0, 1, 13) #define constants #ThunderSnow Constants exist c = m.Array(m.Const, 4, value=0) c[0].value = 0.03 c[1].value = c[0] / 2 c[2].value = c[0] * 2 c[3].value = 0 #python constants are equivilant to ThunderSnow constants Vuse = [0.03, 0.05, 0.02, 0.00] #Paramters evap_c = m.Array(m.Param, 4, value=1e-5) evap_c[-1].value = 0.5e-5 A = [m.Param(value=i) for i in areas] #python list comprehension Vin[0] = m.Param(value=vin) #Variables V = [m.Var(value=i) for i in V0] h = [m.Var(value=i) for i in h0] Vout = [m.Var(value=i) for i in Vout0] #Intermediates Vin[1:4] = [m.Intermediate(Vout[i]) for i in range(3)] Vevap = [m.Intermediate(evap_c[i] * A[i]) for i in range(4)] #Equations m.Equations( [V[i].dt() == Vin[i] - Vout[i] - Vevap[i] - Vuse[i] for i in range(4)]) m.Equations([1000 * V[i] == h[i] * A[i] for i in range(4)]) m.Equations([Vout[i]**2 == c[i]**2 * h[i] for i in range(4)]) #Set to simulation mode m.options.imode = 4 #Solve m.solve(disp=False) hvals = [h[i].value for i in range(4)] assert (test.like( hvals, [[ 19.40299, 19.20641, 19.01394, 19.31262, 19.60511, 19.89159, 19.6849, 19.48247, 19.28424, 19.09014, 18.90011, 18.71408, 18.53199 ], [ 15.0, 15.15939, 15.31216, 15.46995, 15.63249, 15.79955, 15.95968, 16.11305, 16.25983, 16.40018, 16.53428, 16.66226, 16.7843 ], [ 1.768531, 1.758775, 1.74913, 1.739597, 1.730178, 1.720873, 1.71168, 1.702594, 1.693612, 1.684731, 1.675947, 1.667259, 1.658662 ], [ 5.0, 5.001073, 5.002143, 5.003208, 5.004269, 5.005326, 5.00638, 5.007429, 5.008475, 5.009516, 5.010554, 5.011589, 5.012619 ]]))
Ph_3_minus = reaction_model.SV(Ph_3_minus_initial) # variable we will use to regress other Parameters Ph_2_minus = reaction_model.CV(ph_abs) # intermediates k1 = reaction_model.Intermediate(A_1 * reaction_model.exp(-E_a_1 / (R * T))) k2 = reaction_model.Intermediate(A_2 * reaction_model.exp(-E_a_2 / (R * T))) # forward reaction r1 = reaction_model.Intermediate(k1 * Ph_2_minus**alpha) # backwards reaction r2 = reaction_model.Intermediate(k2 * Ph_3_minus**beta) # equations reaction_model.Equations( [Ph_2_minus.dt() == r2 - r1, Ph_3_minus.dt() == r1 - r2]) # parameter options E_a_1.STATUS = 1 E_a_2.STATUS = 1 A_1.STATUS = 0 A_2.STATUS = 0 alpha.STATUS = 0 beta.STATUS = 0 # controlled variable options Ph_2_minus.MEAS_GAP = 1e-3 Ph_2_minus.STATUS = 1 # regress to this value Ph_2_minus.FSTATUS = 1 # take in data measurements
def dynamic(rs, a, c): m = GEKKO(remote=True, server='http://xps.apmonitor.com') m.options.IMODE = 5 m.options.REDUCE = 1 m.options.MAX_ITER = 100 m.time = time # VARIABLES -------------------------------------------------------- # # list of catalytic rates v for all enzymes v = pd.Series([m.Var(value=1, lb=0, ub=100, name='v_' + i) for i in enz], index=enz) # list of alpha = fraction of ribosomes engaged in synthesis of protein a = pd.Series([m.Param(value=a[i].value, name='a_' + i) for i in pro], index=pro) # list of concentration of all components (enzymes and metabolites) c = pd.Series( [m.Var(value=c[i][1], lb=0, ub=500, name='c_' + i) for i in pro + met], index=pro + met) # optional protein utilization, µ dependent: u = c - reserve rs u = pd.Series([m.Var(value=1, lb=0, ub=1, name='u_' + i) for i in enz], index=enz) # hv is the time-dependent light intensity hv = m.Param(value=light, name='hv') # growth rate, here simply equals rate of the ribosome mu = m.Var(value=1, name='mu') # biomass accumulated over time with initial value bm = m.Var(value=1, name='bm') # EQUATIONS -------------------------------------------------------- # # time-dependent differential equation for change in protein_conc # with the 'error' being a logistic term approximating -1 and 1 # for big differences between a and c, and 0 for small differences m.Equations( [c[i].dt() == v['RIB'] * (a[i] - c[i]) / (a[i] + c[i]) for i in pro]) # metabolite mass balance m.Equations([sum(stoich.loc[i] * v) - mu * c[i] == 0 for i in met]) # growth rate mu equals rate of the ribosome v_RIB when a_pro = c_pro = 1, m.Equation(mu == v['RIB']) # utilized enzyme fraction = total enzyme - reserve m.Equations([u[i] == c[i] - rs[i] * (1 - mu / mumax) for i in enz]) # biomass accumulation over time m.Equation(bm.dt() == mu * bm) # Michaelis-Menthen type enzyme kinetics m.Equation(v['LHC'] == kcat['LHC'] * u['LHC'] * hv**hc['LHC'] / (Km['LHC']**hc['LHC'] + hv**hc['LHC'] + (hv**(2 * hc['LHC'])) / Ki)) m.Equation(v['PSET'] == kcat['PSET'] * u['PSET'] * c['hvi']**hc['PSET'] / (c['hvi']**hc['PSET'] + Km['PSET']**hc['PSET'])) m.Equation(v['CBM'] == kcat['CBM'] * u['CBM'] * c['nadph'] * sub**hc['CBM'] * c['atp'] / (c['nadph'] * sub**hc['CBM'] * c['atp'] + KmNADPH * c['atp'] + KmATP * c['nadph'] + KmATP * sub**hc['CBM'] + Km['CBM']**hc['CBM'] * c['nadph'])) m.Equation(v['LPB'] == kcat['LPB'] * u['LPB'] * c['pre']**hc['LPB'] / (Km['LPB']**hc['LPB'] + c['pre']**hc['LPB'])) m.Equation(v['RIB'] == kcat['RIB'] * u['RIB'] * c['pre']**hc['RIB'] / (Km['RIB']**hc['RIB'] + c['pre']**hc['RIB'])) # SOLVING ---------------------------------------------------------- # # solving maximizing specific growth rate; # objective is always minimized, so that we have # to state -1*obj to maximize it m.Obj(-mu) m.solve() # collect results and return (result("dynamic", m, v, a, c, u))
def free_flight(vA, mission, rocket, stage, trajectory, general, optimization, Data): aux_vA = vA g0 = 9.810665 Re = 6371000 tb = trajectory.coast_time for i in range(0, rocket.num_stages): T = stage[i].thrust ISP = stage[i].Isp tb = tb + (stage[i].propellant_mass) / (T) * g0 * ISP tb = Data[0][-1] + (stage[-1].propellant_mass) / ( stage[-1].thrust) * g0 * stage[-1].Isp ##############Ccntrol law for no coast ARC######################## #### Only for last stage Obj = 1000 #Boundary Defined, for better convergence in Free flight t_lb = -(tb - Data[0][-1]) * 0.5 t_ub = 0 aux3 = 0 m = GEKKO(remote=False) m.time = np.linspace(0, 1, 100) final = np.zeros(len(m.time)) final[-1] = 1 final = m.Param(value=final) #Lagrange multipliers with l1=0 l2 = m.FV(-0.01, lb=trajectory.l2_lb, ub=trajectory.l2_ub) l2.STATUS = 1 l3 = m.FV(-1, lb=trajectory.l3_lb, ub=trajectory.l3_ub) l3.Status = 1 l4 = m.Var(value=0) rate = m.Const(value=T / ISP / g0) #value=(tb-Data[0][-1]+(t_ub+t_lb)/2) tf = m.FV(value=(tb - Data[0][-1] + t_lb), ub=tb - Data[0][-1] + t_ub, lb=tb - Data[0][-1] + t_lb) tf.STATUS = 1 aux = m.FV(0, lb=-5, ub=5) aux.STATUS = 1 vD = m.FV(value=Data[8][-1]) #Initial Conditions x = m.Var(value=Data[1][-1]) y = m.Var(value=Data[2][-1]) vx = m.Var(value=Data[3][-1] * cos(Data[4][-1])) vy = m.Var(value=Data[3][-1] * sin(Data[4][-1]), lb=0) vG = m.Var(value=Data[7][-1]) vA = m.Var(value=0) gamma = m.Var() alpha = m.Var() t = m.Var(value=0) m.Equations([l4.dt() / tf == -l2]) m.Equation(t.dt() / tf == 1) mrt = m.Intermediate(Data[5][-1] - rate * t) srt = m.Intermediate(m.sqrt(l3**2 + (l4 - aux)**2)) m.Equations([ x.dt() / tf == vx, y.dt() / tf == vy, vx.dt() / tf == (T / mrt * (-l3) / srt - (vx**2 + vy**2) / (Re + y) * m.sin(gamma)), vy.dt() / tf == (T / mrt * (-(l4 - aux) / srt) + (vx**2 + vy**2) / (Re + y) * m.cos(gamma) - g0 * (Re / (Re + y))**2), vG.dt() / tf == g0 * (Re / (Re + y))**2 * m.sin(m.atan(vy / vx)) ]) m.Equation(gamma == m.atan(vy / vx)) m.Equation(alpha == m.atan((l4 - aux) / l3)) m.Equation(vA.dt() / tf == T / mrt - T / mrt * m.cos((alpha - gamma))) #m.Obj(final*vA) # Soft constraints m.Obj(final * (y - mission.final_altitude)**2) m.Obj(final * 100 * (vx - mission.final_velocity * cos(mission.final_flight_angle))**2) m.Obj(final * 100 * (vy - mission.final_velocity * sin(mission.final_flight_angle))**2) #m.Obj(100*tf) m.Obj(final * (l2 * vy + l3 * (T / (Data[5][-1] - rate * t) * (-l3 / (m.sqrt(l3**2 + (l4 - aux)**2))) - (vx**2 + vy**2) / (Re + y) * m.sin(gamma)) + (l4 - aux) * (T / (Data[5][-1] - rate * t) * (-(l4 - aux) / (m.sqrt(l3**2 + (l4 - aux)**2))) + (vx**2 + vy**2) / (Re + y) * m.cos(gamma) - g0 * (Re / (Re + y))**2) + 1)**2) #Options m.options.IMODE = 6 m.options.SOLVER = 1 m.options.NODES = 3 m.options.MAX_MEMORY = 10 m.options.MAX_ITER = 500 m.options.COLDSTART = 0 m.options.REDUCE = 0 m.solve(disp=False) print("vA", vA.value[-1] + aux_vA) print() """ #print("Obj= ",Obj) print("altitude: ", y.value[-1], vx.value[-1], vy.value[-1]) print("Final mass=",Data[5][-1]-rate.value*t.value[-1]) print("Gravity= ",vG.value[-1], " Drag= ",vD.value[-1], " alpha= ", vA.value[-1]," Velocity= ", sqrt(vx.value[-1]**2+vy.value[-1]**2) ) print("Flight angle=",gamma.value[-1]) print("") print("l2:",l2.value[-1],"l3:", l3.value[-1], "aux:", aux.value[-1]) print("tf:", tf.value[-1], "tb:",tb-Data[0][-1]) print("Obj:", Obj) # if t_lb==-10.0 or t_ub==10.0: # break """ tm = np.linspace(Data[0][-1], tf.value[-1] + Data[0][-1], 100) mass = Data[5][-1] Data[0].extend(tm[1:]) Data[1].extend(x.value[1:]) Data[2].extend(y.value[1:]) for i in range(1, 100): Data[3].extend([sqrt(vx.value[i]**2 + vy.value[i]**2)]) Data[4].extend([atan(vy.value[i] / vx.value[i])]) Data[5].extend([mass - rate.value * t.value[i]]) Data[6].extend([atan((l4.value[i] - aux.value[i]) / l3.value[i])]) Data[7].extend(vG.value[1:]) Data[8].extend(vD.value[1:]) DV_required = mission.final_velocity + Data[7][-1] + Data[8][ -1] + aux_vA + vA.value[-1] Obj = m.options.objfcnval + DV_required return Data, DV_required, Obj
k3 = reaction_model.Intermediate(A_1 * reaction_model.exp(-E_a_1 / (R * T_2))) k4 = reaction_model.Intermediate(A_2 * reaction_model.exp(-E_a_2 / (R * T_2))) # forward reaction r1 = reaction_model.Intermediate(k1 * Ph_2_minus**alpha) # backwards reaction r2 = reaction_model.Intermediate(k2 * Ph_3_minus**beta) # forward reaction r3 = reaction_model.Intermediate(k3 * Ph_2_minus_2**alpha) # backwards reaction r4 = reaction_model.Intermediate(k4 * Ph_3_minus_2**beta) # equations reaction_model.Equations([ Ph_2_minus.dt() == r2 - r1, Ph_3_minus.dt() == r1 - r2, Ph_2_minus_2.dt() == r4 - r3, Ph_3_minus_2.dt() == r3 - r4 ]) # parameter options E_a_1.STATUS = 1 E_a_2.STATUS = 1 A_1.STATUS = 1 A_2.STATUS = 1 alpha.STATUS = 0 beta.STATUS = 0 # controlled variable options Ph_2_minus.MEAS_GAP = 1e-3 Ph_2_minus.STATUS = 1 # regress to this value Ph_2_minus.FSTATUS = 1 # take in data measurements
# backwards reaction r2 = reaction_model.Intermediate(k2 * Ph_3_minus**beta) # forward reaction r3 = reaction_model.Intermediate(k3 * Ph_2_minus_2**alpha) # backwards reaction r4 = reaction_model.Intermediate(k4 * Ph_3_minus_2**beta) # forward reaction r5 = reaction_model.Intermediate(k5 * Ph_2_minus_3**alpha) # backwards reaction r6 = reaction_model.Intermediate(k6 * Ph_3_minus_3**beta) # equations reaction_model.Equations([ Ph_2_minus.dt() == r2 - r1, Ph_3_minus.dt() == r1 - r2, Ph_2_minus_2.dt() == r4 - r3, Ph_3_minus_2.dt() == r3 - r4, Ph_2_minus_3.dt() == r6 - r5, Ph_3_minus_3.dt() == r5 - r6 ]) # parameter options E_a_1.STATUS = 1 E_a_2.STATUS = 1 A_1.STATUS = 1 A_2.STATUS = 1 alpha.STATUS = 0 beta.STATUS = 0 # controlled variable options Ph_2_minus.MEAS_GAP = 1e-3 Ph_2_minus.STATUS = 1 # regress to this value
m = GEKKO() kappa = m.Param(value=5.0) v = m.Param(value=1) sigma = m.Param(value=0.8) eta_l = m.Param(value=5.5) eta_h = m.Param(value=0.5) z = m.Param(value=1) theta = m.Param(value=0.6) kmax = m.Param(value=2) lambd = m.Param(value=0.95) phi = m.Param(value=0.2) k = m.Param(value=1) c_l, c_h, h_l, h_h, w, r = [m.Var(1) for i in range(6)] m.Equations ([-r+(1-theta)*z*(h_l*eta_l+h_h*eta_h)**(theta)*kmax**(-theta)==0,\ -w+(theta)*z*kmax**(1-theta)*(h_l*eta_l+h_h*eta_h)**(theta-1)==0,\ -kappa*h_l**(1/v)+c_l**(-sigma)*w*eta_l*lambd*(1-phi)*(w*h_l)**(-phi)==0,\ -kappa*h_h**(1/v)+c_h**(-sigma)*w*eta_h*lambd*(1-phi)*(w*h_h)**(-phi)==0,\ -c_l+lambd*(w*h_l*eta_l)**(1-phi)+r*k**(eta_l)==0,\ -c_h+lambd*(w*h_h*eta_h)**(1-phi)+r*k**(eta_h)==0]) m.solve(disp=False) print(c_l.value, c_h.value, h_l.value, h_h.value, w.value, r.value) # Country B m = GEKKO() kappa = m.Param(value=5.0) v = m.Param(value=1) sigma = m.Param(value=0.8) eta_l = m.Param(value=3.5) eta_h = m.Param(value=2.5) z = m.Param(value=1) theta = m.Param(value=0.6)
from gekko import GEKKO m = GEKKO() # create GEKKO model m._path = r'C:\test' # save modell to files # Constants and Variables a = m.Var(value=0.5) x = m.Var(value=0) # define new variable, initial value=0 y = m.Var(value=1) # define new variable, initial value=1 # Equations m.Equations([ x + 2 * y == 0, # equations x**2 + y**2 == 1, a + x == 1 ]) # solve m.solve(disp=False) print([x.value[0], y.value[0], a.value[0]]) # print solution
def BeamOpt2(variables, bw_lim): # ---------------------- BeamOpt2 ---------------------- # # Recebe os parâmetros do projeto "variables" # Realiza a Otimização e retorna a Largura da Viga(bw) e # o valor da Linha Neutra encontrado. # ----------------------------------------------------- # m = GEKKO() # Coletando as informações das variáveis fck = variables['fck'] fcd = variables['fck'] * 1000 / 1.4 # MPa -> KPa fyk = variables['fyk'] fyd = variables['fyk'] * 1000 / 1.15 # MPa -> KPa md = variables['mk'] * 1.4 # KNm vsd = variables['vsk'] * 1.4 # KN h = variables['h'] / 100 # cm -> m L = variables['L'] # m d_ = 4 / 100 d = variables['h'] / 100 - d_ # Cálculo da massa específica média das barras de ferro def calc_peso_aco(): D = [6.3, 8.0, 10.0, 12.5, 16.0, 20.0, 25.0, 32.0, 40.0] P = [0.248, 0.393, 0.624, 0.988, 1.570, 2.480, 3.930, 6.240, 9.880] def area(d): return math.pi * (d**2) * (10**-6) / 4 pesos = [] for (d, p) in zip(D, P): pesos.append(p / area(d)) return np.mean(pesos) p = calc_peso_aco() # Massa específica média # Preço dos materiais R$/kg e R$/m3 preco_CA5060 = 8.86 preco_concreto = 295.46 # Armadura Longitudinal bw = m.Var(lb=bw_lim, ub=1.00) # m kx34 = 0.45 x34 = kx34 * d m34 = (0.68 * x34 * d - 0.272 * x34**2) * bw * fcd # Armadura inferior kz34 = 1 - kx34 As34 = m34 / (kz34 * d * fyd) # m2 # Armadura superior m2 = md - m34 As2 = m2 / ((d - d_) * fyd) # m2 Asl = As34 + As2 # Armadura Transversal alpha = 1 - fck / 250 vrd2 = 0.27 * alpha * fck / 1.4 * bw * d * (10**3) fctm = 0.3 * (fck**(2 / 3)) fctd = 0.7 * 0.3 * (fck**(2 / 3)) / 1.4 vc = 0.6 * (fctd * 1000) * bw * d vsw = vsd - vc Ast = (vsw / (0.9 * d * fyd)) * L # Volume Concreto Volume_Concreto = bw * h * L # Formulação dos preços dos componentes Preco_acolong = preco_CA5060 * p * (L + 0.4) * Asl Preco_acotrans = preco_CA5060 * p * (2 * (bw + h)) * Ast Preco_concreto = preco_concreto * Volume_Concreto # Função objetivo e equações de restrição m.Obj(Preco_acolong + Preco_acotrans + Preco_concreto) m.Equations([ vsd <= vrd2, vsw > 0, md > m34, (vsw / (0.9 * d * fyd)) / bw >= 0.2 * (fctm / fyk), Asl + As2 <= 0.04 * bw * h ]) m.solve(display=True) print('''Otimização Concluída! \n Largura encontrada (m): {}'''.format(bw.value[0])) return [bw.value[0]]