def __strikes_and_weights(self, opt, swaption, strike, period): if isinstance(swaption, BlackLognormalModel): # lognormal model strike_at_maxvega = swaption.forward * np.exp( swaption.stdev**2 / 2) # at which max vega occurs lower_bound = 1e-10 # rate must be positive else: # normal model strike_at_maxvega = swaption.forward # at which max vega occurs lower_bound = -1e2 # rate can be negative cutoff_vega = swaption.vega( strike_at_maxvega ) / 100.0 # cutoff at vega that is 100 times smaller find_strike = lambda k: swaption.vega(k) - cutoff_vega if opt == self.Option.Cap: cutoff_rate = solver(find_strike, strike_at_maxvega, 1e2) # to high end else: # == self.Option.Floor cutoff_rate = solver(find_strike, lower_bound, strike_at_maxvega) # to low end def curves(t, h): # bumped by h, new curve with (t, T, h) def bump(curve): def newcurve(T): # T can be float or Numpy.Array return curve(T) * np.exp( -h * self.__b(t, T)) # curve(t) = 1.0 return DiscountCurve.from_fn(t, newcurve) return bump(self.proj), bump(self.disc) def rate_to_h(swaprate): def find_h(h): newproj, newdisc = curves(period.fixdate.t, h) return swaption.underlier.pleg_parrate(newproj, newdisc) - swaprate try: # clamped to avoid double precision overflow return solver(find_h, -self.__shift_clamp, self.__shift_clamp) except ValueError: return self.__shift_clamp # only positive h causes trouble h_stt = rate_to_h(strike) h_end = rate_to_h(cutoff_rate) # clamped if too large n = self.nswpns H = np.linspace(h_stt, h_end, n + 1) K = np.zeros_like(H) G = np.zeros_like(H) for i, h in enumerate(H): newproj, newdisc = curves(period.fixdate.t, h) K[i] = swaption.underlier.pleg_parrate(newproj, newdisc) G[i] = period.accr_cov * newdisc( period.paydate.t) / swaption.underlier.pleg.get_annuity( newdisc) GK = G * (K - K[0]) # [g * (k - K[0]) for g, k in zip(G, K)] W = np.zeros(n) for i in range(1, n): W[i - 1] = (GK[i] - W[:i].dot(K[i] - K[:i])) / (K[i] - K[i - 1]) return K[:-1], W # swaption at K[n] is not used
def __strikes_and_weights(self, opt, swaption, strike, period): if isinstance(swaption, BlackLognormalModel): # lognormal model strike_at_maxvega = swaption.forward * np.exp(swaption.stdev ** 2 / 2) # at which max vega occurs lower_bound = 1e-10 # rate must be positive else: # normal model strike_at_maxvega = swaption.forward # at which max vega occurs lower_bound = -1e2 # rate can be negative cutoff_vega = swaption.vega(strike_at_maxvega) / 100.0 # cutoff at vega that is 100 times smaller find_strike = lambda k: swaption.vega(k) - cutoff_vega if opt == self.Option.Cap: cutoff_rate = solver(find_strike, strike_at_maxvega, 1e2) # to high end else: # == self.Option.Floor cutoff_rate = solver(find_strike, lower_bound, strike_at_maxvega) # to low end def curves(t, h): # bumped by h, new curve with (t, T, h) def bump(curve): def newcurve(T): # T can be float or Numpy.Array return curve(T) * np.exp(-h * self.__b(t, T)) # curve(t) = 1.0 return DiscountCurve.from_fn(t, newcurve) return bump(self.proj), bump(self.disc) def rate_to_h(swaprate): def find_h(h): newproj, newdisc = curves(period.fixdate.t, h) return swaption.underlier.pleg_parrate(newproj, newdisc) - swaprate try: # clamped to avoid double precision overflow return solver(find_h, -self.__shift_clamp, self.__shift_clamp) except ValueError: return self.__shift_clamp # only positive h causes trouble h_stt = rate_to_h(strike) h_end = rate_to_h(cutoff_rate) # clamped if too large n = self.nswpns H = np.linspace(h_stt, h_end, n + 1) K = np.zeros_like(H) G = np.zeros_like(H) for i, h in enumerate(H): newproj, newdisc = curves(period.fixdate.t, h) K[i] = swaption.underlier.pleg_parrate(newproj, newdisc) G[i] = period.accr_cov * newdisc(period.paydate.t) / swaption.underlier.pleg.get_annuity(newdisc) GK = G * (K - K[0]) # [g * (k - K[0]) for g, k in zip(G, K)] W = np.zeros(n) for i in range(1, n): W[i - 1] = (GK[i] - W[:i].dot(K[i] - K[:i])) / (K[i] - K[i - 1]) return K[:-1], W # swaption at K[n] is not used
def __payer_swpn_value(self, swap, strike): def eta(x): #constant multiplicative spread between proj and disc curve return self.disc(x.matdate.t) / self.disc(x.effdate.t) * self.proj(x.effdate.t) / self.proj(x.matdate.t) # floating leg cashflows dateflows = [(swap.rleg.effdate, 1.), (swap.rleg.matdate, -1.)] # P(T,te ) - P(T,tm ) dateflows += [(p.index.effdate, eta(p.index) - 1.) for p in swap.rleg.cp] # fixed leg cashflows dateflows += [(p.paydate, -strike * p.accr_cov) for p in swap.pleg.cp] t = swap.effdate.t # option expiry (should have been swap.fixdate, but has been offset to swap.effdate) def disc_tf(T, z): # bond price under t-forward measure, a martingale # bond price: P(t,T)/P(s,t,T) = exp(-xi2(s,t,t,T)/2 - xi(s,t,t,T)*z), z ~ N(0,1) xi2 = self.vol.xi2(None,t,t,T) return self.disc(T) / self.disc(t) * np.exp(-xi2 / 2 - xi2 ** 0.5 * z) def find_zstar(z): return sum(cf * disc_tf(d.t,z) for d, cf in dateflows) # sum of cashflows = 0 bound = 5.0 while True: try: zstar = solver(find_zstar, -bound, bound) # z can be regarded as a standard normal break except ValueError: print("bound exception: z=%s" % bound) bound *= 2 return sum(cf * self.disc(d.t) * norm.cdf(-zstar - self.vol.xi2(None,t,t,d.t) ** 0.5) for d, cf in dateflows)
def callvalue_to_vol(self, value, strike=None): if strike is None: strike = self.forward def find_vol(vol): self.stdev = vol * self.sqr_term return self.value(strike=strike) - value return solver(find_vol, 1e-10, 1e2)
def TofX(X, ho, n, omega, phi): ''' numerically solve T = X + ho/(omega*(1-n))*sin(omega*(T-nX)+phi) for T ''' return solver(lambda T: X + ho/(omega*(1-n))*(np.sin(omega*(T-n*X)+phi)-np.sin(phi)) - T, X)
def rate_to_h(swaprate): def find_h(h): newproj, newdisc = curves(period.fixdate.t, h) return swaption.underlier.pleg_parrate(newproj, newdisc) - swaprate try: # clamped to avoid double precision overflow return solver(find_h, -self.__shift_clamp, self.__shift_clamp) except ValueError: return self.__shift_clamp # only positive h causes trouble
def process(self, data): text_lines = data['lines'] rects = text_lines.rects centers = np.stack(((rects[:, 0] + rects[:, 2]) / 2, (rects[:, 1] + rects[:, 3]) / 2), axis=1) # Nx2 min_height = 1 ratios = [] for rect in rects: width = (rect[2] - rect[0]) height = (rect[3] - rect[1]) ratio = width / height ratios.append(ratio) if ratio < 1: min_height = 1 / ratio ratios = np.array(ratios) heights = np.empty([rects.shape[0]]) heights.fill(min_height) widths = ratios * heights shapes = np.stack((widths, heights), axis=1) / 2 min_rects = np.zeros_like(rects) min_rects[:, :2] = centers - shapes min_rects[:, 2:] = centers + shapes for rect in rects: data['image'] = Visualize.visualize_rect(data['image'], rect, color=(0, 255, 0)) for rect in min_rects: data['image'] = Visualize.visualize_rect(data['image'], rect) best_ratio = 100 area = data['image'].shape[0] * data['image'].shape[1] def F(r): new_rects = self.expand(min_rects, r) return self.loss(new_rects, area) best_ratio = solver(F, best_ratio, f_tol=1e-2, maxiter=1000) print(best_ratio) best_rects = self.expand(min_rects, best_ratio) for rect in best_rects: data['image'] = Visualize.visualize_rect(data['image'], rect, color=(255, 0, 0)) data['min_rects'] = min_rects data['rects'] = rects return data
def calcWeightShares(self, day): """Solve system of equations and get number of shares for each intrument so that if every instrument is purchased at current price, its weight in portfolio is equal to the definition""" """w_i = (no0_i+no_i)*price_i/sum((no0_j+no_j)*price_j) inv = sum(no_j*price_j*(1+relfee_j) + absfee_j)""" # If no shares were purchased yet, equations do not converge # In that case determine noShares same way like during initial investment if all([True if noShares<=0 else False for noShares in self.sharesArray]): pointerIter = self.portIter() for _ in range(len(self.portfolio)): pointer = next(pointerIter) availVol = (self.invAvailable*self.portfolio[pointer][1] - self.portfolio[pointer][2])/(1+self.portfolio[pointer][3]) self.weightSharesArray[pointer] = int(availVol/self.portfolio[pointer][0]['data'][day]) return # Solve SOE def fun(*args): nonlocal day vol = 0.0 for i in range(len(self.portfolio)): vol += (self.sharesArray[i]+args[0][i])*self.portfolio[i][0]['data'][day] out = list() for i in range(len(self.portfolio)): out.append(((self.sharesArray[i]+args[0][i])*self.portfolio[i][0]['data'][day]/vol) - self.portfolio[i][1]) fourth = 0.0 for i in range(len(self.portfolio)): fourth += args[0][i]*self.portfolio[i][0]['data'][day]*(1+self.portfolio[i][3]) + self.portfolio[i][2] fourth -= (self.invAvailable + self.remainInvAfterPurchase) out.append(fourth) return tuple(out) solution = solver(fun, tuple(0 for _ in range(len(self.portfolio))), method='lm') # Print warning in case solver did not find solution if any(np.isnan(solution['x'])): print('%s: Solver could not determine noShares to preserve weights!' % day.strftime('%d. %m. %Y')) pointerIter = self.portIter() for _ in range(len(self.portfolio)): pointer = next(pointerIter) self.weightSharesArray[pointer] = 0 self.weightSharesArray = solution['x']
def SimulateCobelliDay(modelData): # modelData = np.zeros((22,1)) eatingTime = 30 # [min ] # Data is unpacked bHour = modelData[1] bMin = modelData[2] bCHO = 1000*modelData[3]*18.018 # converted to mg bInsulin = 6.945*modelData[4]/1000 # converted from IU/L to pmol/L lHour = modelData[5] lMin = modelData[6] lCHO = 1000*modelData[7]*18.018 # converted to mg lInsulin = 6.945*modelData[8]/1000 # converted to pmol/L dHour = modelData[9] dMin = modelData[10] dCHO = 1000*modelData[11]*18.018 # converted to mg dInsulin = 6.945*modelData[12]/1000 # converted to pmol/L insulinTime = modelData[13] # Initialize the time vector t = np.zeros((11,1)) # Relevant moments are calculated t[0] = 0 t[1] = bHour*60 + bMin - insulinTime t[2] = bHour*60 + bMin t[3] = bHour*60 + bMin + eatingTime t[4] = lHour*60 + lMin - insulinTime t[5] = lHour*60 + lMin t[6] = lHour*60 + lMin + eatingTime t[7] = dHour*60 + dMin - insulinTime t[8] = dHour*60 + dMin t[9] = dHour*60 + dMin + eatingTime t[10] = 24*60 V_G = 1.88 #1.49 # [dL/kg] k_1 = 0.065 #0.042 # [min ^-1] k_2 = 0.079 #0.071 # [min ^-1] V_I = 0.05 #0.04 # [L/kg] m_1 = 0.190 #0.379 # [min ^-1] m_2 = 0.484 #0.673 # [min ^-1] m_4 = 0.194 #0.269 # [min ^-1] m_5 = 0.0304 #0.0526 # [min *kg/pmol ] m_6 = 0.6471 #0.8118 # [-] HE_b = 0.6 # [-] k_max = 0.0558 #0.0465 # [min ^-1] k_min = 0.0080 #0.0076 # [min ^-1] k_abs = 0.057 #0.023 # [min ^-1] k_gri = 0.0558 #0.0465 # [min ^-1] f = 0.90 # [-] a = 0.00013 #0.00006 # [mg ^-1] b = 0.82 #0.68 # [-] c = 0.00236 #0.00023 # [mg ^-1] d = 0.010 # 0.09 # [-] k_p1 = 2.70 #3.09 # [mg/kg/min ] k_p2 = 0.0021 #0.0007 # [min ^-1] k_p3 = 0.009 #0.005 # [mg/kg/min per pmol/L] k_p4 = 0.0618 #0.0786 # [mg/kg/min per pmol/kg] k_i = 0.0079 #0.0066 # [min ^-1] F_cns = 1 # [mg/kg/min ] V_m0 = 2.50 #4.65 # [mg/kg/min ] V_mx = 0.047 #0.034 # [mg/kg/min per pmol/L] K_m0 = 225.59 #466.21 # [mg/kg] p_2U = .0331 #0.084 # [min ^-1] K = 2.30 #0.99 # [pmol/kg per mg/dL] alpha = 0.050 #0.013 # [min ^-1] beta = 0.11 #0.05 # [pmol/kg/min per mg/dL] gamma = 0.5 # [min ^-1] k_e1 = 0.0005 #0.0007 # [min ^-1] k_e2 = 339 #269 # [mg/kg] p = [V_G ,k_1 ,k_2 , V_I ,m_1 ,m_2 ,m_4 ,m_5 ,m_6 ,HE_b, k_max , k_min , k_abs , k_gri,f,a,b,c,d, k_p1,k_p2, k_p3, k_p4,k_i , F_cns , V_m0,V_mx ,K_m0, p_2U,K, alpha,beta, gamma , k_e1, k_e2] u = 0 #0.0954119*BW, #7.15 X = [] # Calculate the steady state values xStart = [90,90,54.18,54.18,0,0,0,4.4,4.4,0,0,0] #zeros(16,1) , # (xStart,u,0,p,modelData) xInitial0 = solver(CobelliWrap,xStart,args=(u,0,p,modelData)) # Midnight to first insulinshot r = ode(Cobelli).set_integrator('vode', method='bdf', order=15).set_initial_value(xInitial0, t[0]).set_f_params(u ,0,p,modelData) while r.successful() and r.t < t[1]: r.integrate(r.t+1) X.append(r.y[0]) # Insulinshot before breakfast xInitial1 = r.y.T xInitial1[2] = xInitial1[2] + bInsulin r1 = ode(Cobelli).set_integrator('vode', method='bdf', order=15).set_initial_value(xInitial1, t[1]).set_f_params(u ,0,p,modelData) while r1.successful() and r1.t < t[2]: r1.integrate(r1.t+1) X.append(r1.y[0]) # Breakfast start xInitial2 = r1.y.T r2 = ode(Cobelli).set_integrator('vode', method='bdf', order=15).set_initial_value(xInitial2, t[2]).set_f_params(u ,bCHO/(eatingTime),p,modelData) while r2.successful() and r2.t < t[3]: r2.integrate(r2.t+1) X.append(r2.y[0]) # Breakfast stop xInitial3 = r2.y.T r3 = ode(Cobelli).set_integrator('vode', method='bdf', order=15).set_initial_value(xInitial3, t[3]).set_f_params(u ,0,p,modelData) while r3.successful() and r3.t < t[4]: r3.integrate(r3.t+1) X.append(r3.y[0]) # Insulinshot before lunch xInitial4 = r3.y.T xInitial4[2] = xInitial4[2] + lInsulin r4 = ode(Cobelli).set_integrator('vode', method='bdf', order=15).set_initial_value(xInitial4, t[4]).set_f_params(u ,0,p,modelData) while r4.successful() and r4.t < t[5]: r4.integrate(r4.t+1) X.append(r4.y[0]) # Lunch start xInitial5 = r4.y.T r5 = ode(Cobelli).set_integrator('vode', method='bdf', order=15).set_initial_value(xInitial5, t[5]).set_f_params(u ,lCHO/(eatingTime),p,modelData) while r5.successful() and r5.t < t[6]: r5.integrate(r5.t+1) X.append(r5.y[0]) # Lunch stop xInitial6 = r5.y.T r6 = ode(Cobelli).set_integrator('vode', method='bdf', order=15).set_initial_value(xInitial6, t[6]).set_f_params(u ,0,p,modelData) while r6.successful() and r6.t < t[7]: r6.integrate(r6.t+1) X.append(r6.y[0]) # Insulinshot before dinner xInitial7 = r6.y.T xInitial7[2] = xInitial7[2] + dInsulin r7 = ode(Cobelli).set_integrator('vode', method='bdf', order=15).set_initial_value(xInitial7, t[7]).set_f_params(u ,0,p,modelData) while r7.successful() and r7.t < t[8]: r7.integrate(r7.t+1) X.append(r7.y[0]) # Dinner start xInitial8 = r7.y.T r8 = ode(Cobelli).set_integrator('vode', method='bdf', order=15).set_initial_value(xInitial8, t[8]).set_f_params(u ,dCHO/(eatingTime),p,modelData) while r8.successful() and r8.t < t[9]: r8.integrate(r8.t+1) X.append(r8.y[0]) # Dinner stop xInitial9 = r8.y.T r9 = ode(Cobelli).set_integrator('vode', method='bdf', order=15).set_initial_value(xInitial9, t[9]).set_f_params(u ,0,p,modelData) while r9.successful() and r9.t < t[10]: r9.integrate(r9.t+1) X.append(r9.y[0]) #sys.exit(0) # Collects all the simulated intervals G = [x / V_G for x in X] T = r.t return (T,G,t)
def get_spread(self, proj, disc, pv): def find_spread(spread): return self.value(proj, disc, spread=spread) - pv return solver(find_spread, -1e2, 1e2)
def RunSimulation(self, t, x, u, p, modelType, modelData, malady): from scipy.optimize import fsolve as solver from scipy.integrate import ode self.t = t self.x = x self.u = u self.modelType = modelType self.p = p self.model_data = modelData self.malady = malady breakfast_carbpermin = self.model_data[8] lunch_carbpermin = self.model_data[9] dinner_carbpermin = self.model_data[10] insulin = self.u G_p = [] G_t = [] I_l = [] I_p = [] Q_sto1 = [] Q_sto2 = [] Q_gut = [] I_1 = [] I_d = [] X = [] Y = [] I_po = [] if malady == "type1": G_s = [] G_M = [] I_sc1 = [] I_sc2 = [] # State vector for training Neural Network if malady == "type1": stateVector = [G_p, G_t, I_l, I_p, Q_sto1, Q_sto2, Q_gut, I_1, I_d, X, Y, I_po, G_s, G_M, I_sc1, I_sc2] else: stateVector = [G_p, G_t, I_l, I_p, Q_sto1, Q_sto2, Q_gut, I_1, I_d, X, Y, I_po] # (xStart,u,0,p,modelData) xInitial0 = solver(self.CobelliWrap,x, args=(u,0,p,modelData,malady)) #Initialize empty meal vector mealVector = [] mealVectorAppend = mealVector.append stateVector_0_Append = stateVector[0].append stateVector_1_Append = stateVector[1].append stateVector_2_Append = stateVector[2].append stateVector_3_Append = stateVector[3].append stateVector_4_Append = stateVector[4].append stateVector_5_Append = stateVector[5].append stateVector_6_Append = stateVector[6].append stateVector_7_Append = stateVector[7].append stateVector_8_Append = stateVector[8].append stateVector_9_Append = stateVector[9].append stateVector_10_Append = stateVector[10].append stateVector_11_Append = stateVector[11].append # Midnight to first insulin shot r = ode(modelType).set_integrator('vode', method='bdf', order=15).set_initial_value(xInitial0, t[0]).set_f_params(self.u , 0, self.p, self.model_data) while r.successful() and r.t < t[1]: r.integrate(r.t+1) mealVectorAppend(r.f_params[1]) stateVector_0_Append(r.y[0]) stateVector_1_Append(r.y[1]) stateVector_2_Append(r.y[2]) stateVector_3_Append(r.y[3]) stateVector_4_Append(r.y[4]) stateVector_5_Append(r.y[5]) stateVector_6_Append(r.y[6]) stateVector_7_Append(r.y[7]) stateVector_8_Append(r.y[8]) stateVector_9_Append(r.y[9]) stateVector_10_Append(r.y[10]) stateVector_11_Append(r.y[11]) if malady == "type1": stateVector[12].append(r.y[12]) stateVector[13].append(r.y[13]) stateVector[14].append(r.y[14]) stateVector[15].append(r.y[15]) # Insulin shot before breakfast xInitial1 = r.y.T xInitial1[1] = xInitial1[1] + insulin r1 = ode(modelType).set_integrator('vode', method='bdf', order=15).set_initial_value(xInitial1, t[1]).set_f_params(self.u , 0, self.p, self.model_data) while r1.successful() and r1.t < t[2]: r1.integrate(r1.t+1) mealVectorAppend(r1.f_params[1]) stateVector_0_Append(r1.y[0]) stateVector_1_Append(r1.y[1]) stateVector_2_Append(r1.y[2]) stateVector_3_Append(r1.y[3]) stateVector_4_Append(r1.y[4]) stateVector_5_Append(r1.y[5]) stateVector_6_Append(r1.y[6]) stateVector_7_Append(r1.y[7]) stateVector_8_Append(r1.y[8]) stateVector_9_Append(r1.y[9]) stateVector_10_Append(r1.y[10]) stateVector_11_Append(r1.y[11]) if malady == "type1": stateVector[12].append(r1.y[12]) stateVector[13].append(r1.y[13]) stateVector[14].append(r1.y[14]) stateVector[15].append(r1.y[15]) # Breakfast start xInitial2 = r1.y.T r2 = ode(modelType).set_integrator('vode', method='bdf', order=15).set_initial_value(xInitial2, t[2]).set_f_params(u, breakfast_carbpermin, p, modelData) while r2.successful() and r2.t < t[3]: r2.integrate(r2.t+1) mealVectorAppend(r2.f_params[1]) stateVector_0_Append(r2.y[0]) stateVector_1_Append(r2.y[1]) stateVector_2_Append(r2.y[2]) stateVector_3_Append(r2.y[3]) stateVector_4_Append(r2.y[4]) stateVector_5_Append(r2.y[5]) stateVector_6_Append(r2.y[6]) stateVector_7_Append(r2.y[7]) stateVector_8_Append(r2.y[8]) stateVector_9_Append(r2.y[9]) stateVector_10_Append(r2.y[10]) stateVector_11_Append(r2.y[11]) if malady == "type1": stateVector[12].append(r2.y[12]) stateVector[13].append(r2.y[13]) stateVector[14].append(r2.y[14]) stateVector[15].append(r2.y[15]) # Breakfast stop xInitial3 = r2.y.T r3 = ode(self.modelType).set_integrator('vode', method='bdf', order=15).set_initial_value(xInitial3, t[3]).set_f_params(self.u, 0, self.p, self.model_data) while r3.successful() and r3.t < t[4]: r3.integrate(r3.t+1) mealVectorAppend(r3.f_params[1]) stateVector_0_Append(r3.y[0]) stateVector_1_Append(r3.y[1]) stateVector_2_Append(r3.y[2]) stateVector_3_Append(r3.y[3]) stateVector_4_Append(r3.y[4]) stateVector_5_Append(r3.y[5]) stateVector_6_Append(r3.y[6]) stateVector_7_Append(r3.y[7]) stateVector_8_Append(r3.y[8]) stateVector_9_Append(r3.y[9]) stateVector_10_Append(r3.y[10]) stateVector_11_Append(r3.y[11]) if malady == "type1": stateVector[12].append(r3.y[12]) stateVector[13].append(r3.y[13]) stateVector[14].append(r3.y[14]) stateVector[15].append(r3.y[15]) # Insulin shot before lunch xInitial4 = r3.y.T r4 = ode(self.modelType).set_integrator('vode', method='bdf', order=15).set_initial_value(xInitial4, t[4]).set_f_params(self.u, 0, self.p, self.model_data) while r4.successful() and r4.t < t[5]: r4.integrate(r4.t+1) mealVectorAppend(r4.f_params[1]) stateVector_0_Append(r4.y[0]) stateVector_1_Append(r4.y[1]) stateVector_2_Append(r4.y[2]) stateVector_3_Append(r4.y[3]) stateVector_4_Append(r4.y[4]) stateVector_5_Append(r4.y[5]) stateVector_6_Append(r4.y[6]) stateVector_7_Append(r4.y[7]) stateVector_8_Append(r4.y[8]) stateVector_9_Append(r4.y[9]) stateVector_10_Append(r4.y[10]) stateVector_11_Append(r4.y[11]) if malady == "type1": stateVector[12].append(r4.y[12]) stateVector[13].append(r4.y[13]) stateVector[14].append(r4.y[14]) stateVector[15].append(r4.y[15]) # Lunch start xInitial5 = r4.y.T r5 = ode(modelType).set_integrator('vode', method='bdf', order=15).set_initial_value(xInitial5, t[5]).set_f_params(u,lunch_carbpermin,p,modelData) while r5.successful() and r5.t < t[6]: r5.integrate(r5.t+1) mealVectorAppend(r5.f_params[1]) stateVector_0_Append(r5.y[0]) stateVector_1_Append(r5.y[1]) stateVector_2_Append(r5.y[2]) stateVector_3_Append(r5.y[3]) stateVector_4_Append(r5.y[4]) stateVector_5_Append(r5.y[5]) stateVector_6_Append(r5.y[6]) stateVector_7_Append(r5.y[7]) stateVector_8_Append(r5.y[8]) stateVector_9_Append(r5.y[9]) stateVector_10_Append(r5.y[10]) stateVector_11_Append(r5.y[11]) if malady == "type1": stateVector[12].append(r5.y[12]) stateVector[13].append(r5.y[13]) stateVector[14].append(r5.y[14]) stateVector[15].append(r5.y[15]) # Lunch stop xInitial6 = r5.y.T r6 = ode(self.modelType).set_integrator('vode', method='bdf', order=15).set_initial_value(xInitial6, t[6]).set_f_params(self.u, 0, self.p, self.model_data) while r6.successful() and r6.t < t[7]: r6.integrate(r6.t+1) mealVectorAppend(r6.f_params[1]) stateVector_0_Append(r6.y[0]) stateVector_1_Append(r6.y[1]) stateVector_2_Append(r6.y[2]) stateVector_3_Append(r6.y[3]) stateVector_4_Append(r6.y[4]) stateVector_5_Append(r6.y[5]) stateVector_6_Append(r6.y[6]) stateVector_7_Append(r6.y[7]) stateVector_8_Append(r6.y[8]) stateVector_9_Append(r6.y[9]) stateVector_10_Append(r6.y[10]) stateVector_11_Append(r6.y[11]) if malady == "type1": stateVector[12].append(r6.y[12]) stateVector[13].append(r6.y[13]) stateVector[14].append(r6.y[14]) stateVector[15].append(r6.y[15]) # Insulin shot before dinner xInitial7 = r6.y.T r7 = ode(self.modelType).set_integrator('vode', method='bdf', order=15).set_initial_value(xInitial7, t[7]).set_f_params(self.u, 0, self.p, self.model_data) while r7.successful() and r7.t < t[8]: r7.integrate(r7.t+1) mealVectorAppend(r7.f_params[1]) stateVector_0_Append(r7.y[0]) stateVector_1_Append(r7.y[1]) stateVector_2_Append(r7.y[2]) stateVector_3_Append(r7.y[3]) stateVector_4_Append(r7.y[4]) stateVector_5_Append(r7.y[5]) stateVector_6_Append(r7.y[6]) stateVector_7_Append(r7.y[7]) stateVector_8_Append(r7.y[8]) stateVector_9_Append(r7.y[9]) stateVector_10_Append(r7.y[10]) stateVector_11_Append(r7.y[11]) if malady == "type1": stateVector[12].append(r7.y[12]) stateVector[13].append(r7.y[13]) stateVector[14].append(r7.y[14]) stateVector[15].append(r7.y[15]) # Dinner start xInitial8 = r7.y.T r8 = ode(modelType).set_integrator('vode', method='bdf', order=15).set_initial_value(xInitial8, t[8]).set_f_params(u,dinner_carbpermin,p,modelData) while r8.successful() and r8.t < t[9]: r8.integrate(r8.t+1) mealVectorAppend(r8.f_params[1]) stateVector_0_Append(r8.y[0]) stateVector_1_Append(r8.y[1]) stateVector_2_Append(r8.y[2]) stateVector_3_Append(r8.y[3]) stateVector_4_Append(r8.y[4]) stateVector_5_Append(r8.y[5]) stateVector_6_Append(r8.y[6]) stateVector_7_Append(r8.y[7]) stateVector_8_Append(r8.y[8]) stateVector_9_Append(r8.y[9]) stateVector_10_Append(r8.y[10]) stateVector_11_Append(r8.y[11]) if malady == "type1": stateVector[12].append(r8.y[12]) stateVector[13].append(r8.y[13]) stateVector[14].append(r8.y[14]) stateVector[15].append(r8.y[15]) # Dinner stop xInitial9 = r8.y.T r9 = ode(self.modelType).set_integrator('vode', method='bdf', order=15).set_initial_value(xInitial9, t[9]).set_f_params(self.u, 0, self.p, self.model_data) while r9.successful() and r9.t < t[10]: r9.integrate(r9.t+1) mealVectorAppend(r9.f_params[1]) stateVector_0_Append(r9.y[0]) stateVector_1_Append(r9.y[1]) stateVector_2_Append(r9.y[2]) stateVector_3_Append(r9.y[3]) stateVector_4_Append(r9.y[4]) stateVector_5_Append(r9.y[5]) stateVector_6_Append(r9.y[6]) stateVector_7_Append(r9.y[7]) stateVector_8_Append(r9.y[8]) stateVector_9_Append(r9.y[9]) stateVector_10_Append(r9.y[10]) stateVector_11_Append(r9.y[11]) if malady == "type1": stateVector[12].append(r9.y[12]) stateVector[13].append(r9.y[13]) stateVector[14].append(r9.y[14]) stateVector[15].append(r9.y[15]) #Convert stateVector into a NumPy Array outputArray = np.array(stateVector) # Collects all the simulated intervals outputArray[0] = [x / self.p[0] for x in outputArray[0]] return {'outputArray': outputArray,'mealVector': mealVector}
def simple_bootstrap_cycle(mach, m, e_recirc, H_cab_ft, Tcab, n_pax, Qrequired, alpha, print_results=False): """ :param mach: :param m: :param H_cab_ft: :param Tcab: :return: """ # Flight Conditions H_ft = 38000 H_m = H_ft * ft_2_m H_cab_m = H_cab_ft * ft_2_m H_m = H_ft * ft_2_m deltaT = 0 Tcab = 24 + 273 rho, Pcab, T = atmosferaISA(H_cab_m, deltaT) Pcab = Pcab / 1000 n_pack = 2 min_ventilation = n_pax * 0.55 * lbmin_2_kgs / n_pack if m < min_ventilation: print('Insuficient mass') m = min_ventilation gamma = 1.4 eta_d = 0.84 eta_c = 0.82 hx_eff = 0.8 eta_t = 0.77 rho, P1, T1 = atmosferaISA(H_m, deltaT) T1 = -57 + 273 P1 = 20 # Kpa T2, P2, w_r = ram_compression(m, T1, P1, mach, gamma, eta_d) P3 = 250 T3a, P3a, w_pc = compressor(m, T2, P2, P3 / P2, gamma, eta_c) T3b = 200 + 247 # Fixed P3b = P3a # No loss in preecooler P4a = 200 # Pressure after PRSOV T4a = T3b # Same temperature after PRSOV P4b = P4a # No pressure drop in hx T4b, Qphx = heat_exchanger(m, T4a, T2, hx_eff) P7 = Pcab P50 = np.array([100]) resfunc = lambda P5: get_residual(m, T2, P4b, T4b, P5, P7, gamma, hx_eff, eta_c, eta_t, alpha) sol = solver(resfunc, np.array([P50])) P5 = sol.x[0] P6 = P5 P7 = Pcab T5, T6, T7, Qshx, w_t, w_sc = loop(m, T2, P4b, T4b, P5, P7, gamma, hx_eff, eta_c, eta_t) m_recirc = e_recirc * m m_mixer = m_recirc + m T8 = (m_recirc * Cp * Tcab * 1.1 + m * Cp * T7) / (m_mixer * Cp) P8 = P7 Qcooling = m_mixer * Cp * (Tcab - T8) # Pressurization work _, _, w_press = compressor(m, T2, P2, P7 / P2, gamma, eta_c) w_press = w_press + w_r COPP = Qcooling / (w_r + w_pc) COP = Qcooling / (w_r + w_pc - w_press) T = np.array([T1, T2, T3a, T3b, T4a, T4b, T5, T6, T7, T8, Tcab]) P = np.array([P1, P2, P3a, P3b, P4a, P4b, P5, P6, P7, P8, Pcab]) W = np.array([w_r, w_pc, w_sc, w_t, w_press]) s = np.zeros_like(T) for idx, _ in enumerate(T): s[idx] = PropsSI('S', 'T', T[idx], 'P', P[idx] * 1000, 'air') / 1000 label = ('1', '2', '3a', '3b', '4a', '4b', '5', '6', '7', '8', 'cab') if print_results: for idx in range(0, len(P)): print('T%s: %.2f P%s: %.2f' % (label[idx], T[idx], label[idx], P[idx])) print('\nTurbine Work: %.2f kW\nCompressor Work: %.2f kW' % (w_t, w_sc)) print('Cooling effect: %.2f kW\t %.2f BTU/hr' % (Qcooling, Qcooling * kW2btumin)) print('COP %.2f \tCOPP %.2f' % (COP, COPP)) return W, T, P, s, Qcooling, COP, COPP
def SimulateCobelliDay(modelData): # modelData = np.zeros((22,1)) eatingTime = 30 # [min ] # Data is unpacked bHour = modelData[1] bMin = modelData[2] bCHO = 1000 * modelData[3] * 18.018 # converted to mg bInsulin = 6.945 * modelData[4] / 1000 # converted from IU/L to pmol/L lHour = modelData[5] lMin = modelData[6] lCHO = 1000 * modelData[7] * 18.018 # converted to mg lInsulin = 6.945 * modelData[8] / 1000 # converted to pmol/L dHour = modelData[9] dMin = modelData[10] dCHO = 1000 * modelData[11] * 18.018 # converted to mg dInsulin = 6.945 * modelData[12] / 1000 # converted to pmol/L insulinTime = modelData[13] # Initialize the time vector t = np.zeros((11, 1)) # Relevant moments are calculated t[0] = 0 t[1] = bHour * 60 + bMin - insulinTime t[2] = bHour * 60 + bMin t[3] = bHour * 60 + bMin + eatingTime t[4] = lHour * 60 + lMin - insulinTime t[5] = lHour * 60 + lMin t[6] = lHour * 60 + lMin + eatingTime t[7] = dHour * 60 + dMin - insulinTime t[8] = dHour * 60 + dMin t[9] = dHour * 60 + dMin + eatingTime t[10] = 24 * 60 V_G = 1.88 #1.49 # [dL/kg] k_1 = 0.065 #0.042 # [min ^-1] k_2 = 0.079 #0.071 # [min ^-1] V_I = 0.05 #0.04 # [L/kg] m_1 = 0.190 #0.379 # [min ^-1] m_2 = 0.484 #0.673 # [min ^-1] m_4 = 0.194 #0.269 # [min ^-1] m_5 = 0.0304 #0.0526 # [min *kg/pmol ] m_6 = 0.6471 #0.8118 # [-] HE_b = 0.6 # [-] k_max = 0.0558 #0.0465 # [min ^-1] k_min = 0.0080 #0.0076 # [min ^-1] k_abs = 0.057 #0.023 # [min ^-1] k_gri = 0.0558 #0.0465 # [min ^-1] f = 0.90 # [-] a = 0.00013 #0.00006 # [mg ^-1] b = 0.82 #0.68 # [-] c = 0.00236 #0.00023 # [mg ^-1] d = 0.010 # 0.09 # [-] k_p1 = 2.70 #3.09 # [mg/kg/min ] k_p2 = 0.0021 #0.0007 # [min ^-1] k_p3 = 0.009 #0.005 # [mg/kg/min per pmol/L] k_p4 = 0.0618 #0.0786 # [mg/kg/min per pmol/kg] k_i = 0.0079 #0.0066 # [min ^-1] F_cns = 1 # [mg/kg/min ] V_m0 = 2.50 #4.65 # [mg/kg/min ] V_mx = 0.047 #0.034 # [mg/kg/min per pmol/L] K_m0 = 225.59 #466.21 # [mg/kg] p_2U = .0331 #0.084 # [min ^-1] K = 2.30 #0.99 # [pmol/kg per mg/dL] alpha = 0.050 #0.013 # [min ^-1] beta = 0.11 #0.05 # [pmol/kg/min per mg/dL] gamma = 0.5 # [min ^-1] k_e1 = 0.0005 #0.0007 # [min ^-1] k_e2 = 339 #269 # [mg/kg] p = [ V_G, k_1, k_2, V_I, m_1, m_2, m_4, m_5, m_6, HE_b, k_max, k_min, k_abs, k_gri, f, a, b, c, d, k_p1, k_p2, k_p3, k_p4, k_i, F_cns, V_m0, V_mx, K_m0, p_2U, K, alpha, beta, gamma, k_e1, k_e2 ] u = 0 #0.0954119*BW, #7.15 X = [] # Calculate the steady state values xStart = [90, 90, 54.18, 54.18, 0, 0, 0, 4.4, 4.4, 0, 0, 0] #zeros(16,1) , # (xStart,u,0,p,modelData) xInitial0 = solver(CobelliWrap, xStart, args=(u, 0, p, modelData)) # Midnight to first insulinshot r = ode(Cobelli).set_integrator('vode', method='bdf', order=15).set_initial_value( xInitial0, t[0]).set_f_params(u, 0, p, modelData) while r.successful() and r.t < t[1]: r.integrate(r.t + 1) X.append(r.y[0]) # Insulinshot before breakfast xInitial1 = r.y.T xInitial1[2] = xInitial1[2] + bInsulin r1 = ode(Cobelli).set_integrator( 'vode', method='bdf', order=15).set_initial_value(xInitial1, t[1]).set_f_params(u, 0, p, modelData) while r1.successful() and r1.t < t[2]: r1.integrate(r1.t + 1) X.append(r1.y[0]) # Breakfast start xInitial2 = r1.y.T r2 = ode(Cobelli).set_integrator( 'vode', method='bdf', order=15).set_initial_value(xInitial2, t[2]).set_f_params(u, bCHO / (eatingTime), p, modelData) while r2.successful() and r2.t < t[3]: r2.integrate(r2.t + 1) X.append(r2.y[0]) # Breakfast stop xInitial3 = r2.y.T r3 = ode(Cobelli).set_integrator( 'vode', method='bdf', order=15).set_initial_value(xInitial3, t[3]).set_f_params(u, 0, p, modelData) while r3.successful() and r3.t < t[4]: r3.integrate(r3.t + 1) X.append(r3.y[0]) # Insulinshot before lunch xInitial4 = r3.y.T xInitial4[2] = xInitial4[2] + lInsulin r4 = ode(Cobelli).set_integrator( 'vode', method='bdf', order=15).set_initial_value(xInitial4, t[4]).set_f_params(u, 0, p, modelData) while r4.successful() and r4.t < t[5]: r4.integrate(r4.t + 1) X.append(r4.y[0]) # Lunch start xInitial5 = r4.y.T r5 = ode(Cobelli).set_integrator( 'vode', method='bdf', order=15).set_initial_value(xInitial5, t[5]).set_f_params(u, lCHO / (eatingTime), p, modelData) while r5.successful() and r5.t < t[6]: r5.integrate(r5.t + 1) X.append(r5.y[0]) # Lunch stop xInitial6 = r5.y.T r6 = ode(Cobelli).set_integrator( 'vode', method='bdf', order=15).set_initial_value(xInitial6, t[6]).set_f_params(u, 0, p, modelData) while r6.successful() and r6.t < t[7]: r6.integrate(r6.t + 1) X.append(r6.y[0]) # Insulinshot before dinner xInitial7 = r6.y.T xInitial7[2] = xInitial7[2] + dInsulin r7 = ode(Cobelli).set_integrator( 'vode', method='bdf', order=15).set_initial_value(xInitial7, t[7]).set_f_params(u, 0, p, modelData) while r7.successful() and r7.t < t[8]: r7.integrate(r7.t + 1) X.append(r7.y[0]) # Dinner start xInitial8 = r7.y.T r8 = ode(Cobelli).set_integrator( 'vode', method='bdf', order=15).set_initial_value(xInitial8, t[8]).set_f_params(u, dCHO / (eatingTime), p, modelData) while r8.successful() and r8.t < t[9]: r8.integrate(r8.t + 1) X.append(r8.y[0]) # Dinner stop xInitial9 = r8.y.T r9 = ode(Cobelli).set_integrator( 'vode', method='bdf', order=15).set_initial_value(xInitial9, t[9]).set_f_params(u, 0, p, modelData) while r9.successful() and r9.t < t[10]: r9.integrate(r9.t + 1) X.append(r9.y[0]) #sys.exit(0) # Collects all the simulated intervals G = [x / V_G for x in X] T = r.t return (T, G, t)