def process_data(matfile): data = D(matfile) t = data.abscissa("y1", valuesOnly=True) y1 = data.data("y1") y2 = data.data("y2") y3 = data.data("y3") df = pd.DataFrame(zip(t, y1, y2, y3), columns=["time", "y1", "y2", "y3"])[1:] delta_t = [] target_y1 = [] target_y2 = [] target_y3 = [] y1_init = [] y2_init = [] y3_init = [] for i in range(df.shape[0] - 1): delta_t.append(df.time.iloc[i + 1] - df.time.iloc[i]) target_y1.append(df.y1.iloc[i + 1]) target_y2.append(df.y2.iloc[i + 1]) target_y3.append(df.y3.iloc[i + 1]) y1_init.append(df.y1.iloc[i]) y2_init.append(df.y2.iloc[i]) y3_init.append(df.y3.iloc[i]) data = pd.DataFrame(zip(delta_t, y1_init, y2_init, y3_init, target_y1, target_y2, target_y3), columns=[ "delta_t", "y1", "y2", "y3", "target_y1", "target_y2", "target_y3" ]) der_y1 = (data.target_y1 - data.y1) / data.delta_t der_y2 = (data.target_y2 - data.y2) / data.delta_t der_y3 = (data.target_y3 - data.y3) / data.delta_t N = np.array([der_y1, der_y2, der_y3]).T print(N.shape) assert (N.shape[1] == 3) mm_der = MinMaxScaler().fit(N) state = np.array([data.y1, data.y2, data.y3]).T print(N.shape) assert (state.shape[1] == 3) mm_state = MinMaxScaler().fit(state) data = data.sample(frac=1).reset_index(drop=True) print(mm_state.data_max_) print(mm_state.data_min_) print(mm_der.data_max_) print(mm_der.data_min_) return data, mm_der, mm_state
def compare(f_r, f_s): data_r, data_s = D(f_r), D(f_s) abscissa_r = data_r.abscissa("E_stored", valuesOnly=True) / 3600 E_stored_r = data_r.data("E_stored") der_E_stored_r = data_r.data("der(E_stored)") m_flow_r = data_r.data("thermocline_Tank.Tank_A.m_flow") logic_A_r = data_r.data("logic_A") T_bot_r = data_r.data("T_bot_degC") T_top_r = data_r.data("T_top_degC") abscissa_s = data_s.abscissa("E_stored", valuesOnly=True) / 3600 E_stored_s = data_s.data("E_stored") der_E_stored_s = data_s.data("der(E_stored)") m_flow_s = data_s.data("thermocline_Tank.Tank_A.m_flow") logic_A_s = data_s.data("logic_A") T_bot_s = data_s.data("T_bot_degC") T_top_s = data_s.data("T_top_degC") fig, ax = plt.subplots(3, 1) ax[0].plot(abscissa_r, np.ones(len(abscissa_r)) * 550, label="$T_{rcv,max}$", ls="-.") ax[0].plot(abscissa_r, np.ones(len(abscissa_r)) * 680, label="$T_{PB,min}$", ls="-.") ax[0].plot(abscissa_r, T_bot_r, label="$T_{bot,real}$", c="red") ax[0].plot(abscissa_s, T_bot_s, label="$T_{bot,sur}$", c="red", ls="--") ax[0].legend() ax[2].plot(abscissa_s, m_flow_s, label="$\dot{m}_{fluid,s}$ ", ls="--") ax[2].plot(abscissa_r, m_flow_r, label="$\dot{m}_{fluid,r}$ ") ax[2].set_ylabel("$\dot{m}_{fluid}$ [kg/s]") ax[2].set_xlabel("Time [h]") ax[2].legend() for a in ax.flat: a.set_xlim(0, max(abscissa_r)) plt.show()
def checkParsing(self, N): self.matfile = "%s_res_0.mat" % (self.moname) self.data = D(self.matfile) a = self.data.data("T_max_sampling")[-1] b = self.data.data("T_min_sampling")[-1] c = self.data.data("X_offset")[-1] d = self.data.data("slope")[-1] e = self.data.data("delta_T")[-1] x = np.arange(1, 101, 1) y = sigmoid(x, a, b, c, d) y_filler = y - e T_f = [] T_p = [] for i in range(1, N + 1): T_f.append( self.data.data("thermocline_Tank.Tank_A.T_f[%s]" % (int(i)))[0]) T_p.append( self.data.data("thermocline_Tank.Tank_A.T_s[%s]" % (int(i)))[0]) ''' fig,ax = plt.subplots(1,figsize=(15,15)) ax.plot( x,T_f,label="fluid matfile",c = "black" ) ax.plot( x,y,label="fluid python", c="black",ls="--" ) ax.plot( x,T_p,label="filler surface matfile",c="red" ) ax.plot( x,y_filler,label="filler surface python",c="red",ls="--" ) ax.legend() ax.set_xlabel("X") ax.set_ylabel("Temperature in K") ax.set_title("Initial temperature in the tank.\n T_max:%s, T_min:%s, Offset:%s, Slope:%s, delta T:%s"%(a,b,c,d,e)) idx = 0 while os.path.exists("./fig/%s.png"%(idx)): idx +=1 plt.savefig("./fig/%s.png"%(idx)) ''' diff = sum(abs(y - T_f)) diff += sum(abs(y_filler - T_p)) assert (diff < 1e-2)
def generate_gif(f): data = D(f) T_s = [] for i in range(1, 101): name = "thermocline_Tank.Tank_A.T_s[%s]" % (i) val = data.data(name) T_s.append(val) T_s = np.array(T_s).T return T_s
def plot1(): data = D("11days_with_Regression.mat") der_a = data.data("der_a") der_b = data.data("der_b") der_c = data.data("der_c") der_d = data.data("der_d") a = data.data("params_a") b = data.data("params_b") c = data.data("params_c") d = data.data("params_d") time = data.abscissa("params_a", valuesOnly=True) plt.scatter(time, der_c, label="der_c", s=1) plt.scatter(time, c, label="a", s=1) plt.legend() plt.show()
def generate_data(self, f): data = D(f) self.Nf = int(data.data("N_f")[0]) #Get the value time = data.abscissa("thermocline_Tank.Tank_A.h_p[1]", valuesOnly=True) #Since no design params are perturbed, as such only state variables matter u_flow = data.data("thermocline_Tank.Tank_A.u_flow") #State variables vals = [] colnames = [] for i in range(1, self.Nf + 1): hf_ = "thermocline_Tank.Tank_A.h_f[%s]" % (i) hs_ = "thermocline_Tank.Tank_A.h_p[%s]" % (i) der_hf = "der(thermocline_Tank.Tank_A.h_f[%s])" % (i) der_hp = "der(thermocline_Tank.Tank_A.h_p[%s])" % (i) vals.append(data.data(hf_)) vals.append(data.data(hs_)) vals.append(data.data(der_hf)) vals.append(data.data(der_hp)) colnames.append("h_f_%s" % (i)) colnames.append("h_s_%s" % (i)) colnames.append("der_hf_%s" % (i)) colnames.append("der_hp_%s" % (i)) states = np.array(vals).T df = pd.DataFrame(states, columns=colnames) df["time"] = time df["u_flow"] = u_flow self.df = df[1:] return self.df
def get_data(self): self.fmat = "./%s_res_0.mat" % (self.moname) self.data = D(self.fmat) epsilon = self.data.data("epsilon_stg") mdot = self.data.data("thermocline_Tank.Tank_A.m_flow") lv = self.data.data("tank_level") h_in = self.data.data("thermocline_Tank.Tank_A.h_in") T_p_rep = self.data.data("T_p_rep") time = self.data.abscissa("epsilon_stg", valuesOnly=True) T_amb = self.data.data("thermocline_Tank.Tank_A.T_amb") h_in = self.data.data("thermocline_Tank.Tank_A.h_in") if len(T_amb) != len(time): T_amb = [T_amb[0]] * len(time) self.df = pd.DataFrame(zip(time, mdot, lv, h_in, T_p_rep, T_amb, h_in, epsilon), columns=[ "time", "mdot", "lv", "h_in", "T_p_rep", "T_amb", "h_in", "epsilon" ]) print(self.df) return self.df
def plot3(): data = D("test_data_half_annual_system_simulation.mat") T_top = data.data("Tank.T_top_measured") T_bot = data.data("Tank.T_bot_measured") SOC = data.data("tank_level") time = data.abscissa("tank_level", valuesOnly=True) mdot = data.data("Tank.Tank_A.m_flow") df = pd.DataFrame(zip(time, T_top, T_bot, SOC, mdot), columns=["time", "T_top", "T_bot", "SOC", "mdot"]) titlenames = [ "All days", "Day 2 - End", "Day 3 - End", "Day 4 - End", "Day 5 - End", "Day 6 - End" ] limit_time = [i * 24 * 3600 for i in range(6)] for j in range(2): fig, axes = plt.subplots(3, 2) fig.tight_layout(pad=2) for i, ax in enumerate(axes.flat): limit = limit_time[i] title = titlenames[i] df_ = df[(df.time >= limit) & (abs(df.mdot) >= 0)] df_charge = df_[df_.mdot < 0] df_discharge = df_[df_.mdot > 0] print(df_charge.SOC.max()) print(df_charge.SOC.min()) print(df_discharge.SOC.max()) print(df_discharge.SOC.min()) if j == 0: ax.scatter(df_charge.SOC, df_charge.T_top, c="black", s=5, label="charging") ax.scatter(df_discharge.SOC, df_discharge.T_top, c="green", s=5, label="discharging") ax.legend() ax.set_title(title) ax.set_xlabel("State of charge") ax.set_ylabel("T$_{top}$ [K]") ax.set_xlim(0, 1) elif j == 1: ax.scatter(df_charge.SOC, df_charge.T_bot, c="black", s=5, label="charging") ax.scatter(df_discharge.SOC, df_discharge.T_bot, c="green", s=5, label="discharging") ax.legend() ax.set_title(title) ax.set_xlabel("State of charge") ax.set_ylabel("T$_{bot}$ [K]") ax.set_xlim(0, 1) if j == 0: fig.suptitle("T$_{top}$ vs. SOC") elif j == 1: fig.suptitle("T$_{bot}$ vs. SOC") plt.show() fig.savefig("Fig_%s.png" % (j))
def generate_data(self): data = D(self.f) self.Nf = int(data.data("N_f")[0]) #Get the value time = data.abscissa("thermocline_Tank.Tank_A.h_p[1]",valuesOnly=True) #Since no design params are perturbed, as such only state variables matter u_flow = data.data("thermocline_Tank.Tank_A.u_flow") #State variables vals = [] colnames = [] for i in range(1,self.Nf+1): Tf_ = "thermocline_Tank.Tank_A.T_f[%s]"%(i) Ts_ = "thermocline_Tank.Tank_A.T_s[%s]"%(i) #der_hf = "der(thermocline_Tank.Tank_A.h_f[%s])"%(i) #der_hp = "der(thermocline_Tank.Tank_A.h_p[%s])"%(i) vals.append( data.data(Tf_) ) vals.append( data.data(Ts_) ) #vals.append( # data.data(der_hf) #) #vals.append( # data.data(der_hp) #) colnames.append("T_f_%s"%(i)) colnames.append("T_s_%s"%(i)) #colnames.append("der_hf_%s"%(i)) #colnames.append("der_hp_%s"%(i)) h_p_rep = data.data("h_p_rep") hf_in = data.data("thermocline_Tank.Tank_A.h_in") hf_out = data.data("thermocline_Tank.Tank_A.h_out") vals.append(h_p_rep) vals.append(hf_in) vals.append(hf_out) colnames.append("h_p_rep") colnames.append("h_f_in") colnames.append("h_f_out") states = np.array(vals).T df = pd.DataFrame( states, columns=colnames ) eta_storage = data.data("eta_storage") df["u_flow"] = u_flow df["eta_stg"] = eta_storage df["time"] = time self.df = df[ df.time > 86400 ] return self.df
from DyMat import DyMatFile as D fn_working = './xml_work_from_OMEdit/sCO2PBCalculator_res_0.mat' fn_finally_working = './xml_finally_working/sCO2PBCalculator_res_0.mat' fn_not_working = './xml_not_working/sCO2PBCalculator_res_0.mat' datawork = D(fn_working) datafinal = D(fn_finally_working) datanotwork = D(fn_not_working) h1 = datawork.data("powerBlock.state_HTF_in_des.h")[-1] h2 = datanotwork.data("powerBlock.state_HTF_in_des.h")[-1] hf = datafinal.data("powerBlock.state_HTF_in_des.h")[-1] t1 = datawork.data('powerBlock.T_HTF_in_des')[-1] t2 = datanotwork.data('powerBlock.T_HTF_in_des')[-1] tf = datafinal.data('powerBlock.T_HTF_in_des')[-1] p1 = datawork.data("powerBlock.state_HTF_in_des.p")[-1] p2 = datanotwork.data("powerBlock.state_HTF_in_des.p")[-1] pf = datafinal.data("powerBlock.state_HTF_in_des.p")[-1] print(p1, t1, h1) print(p2, t2, h2) print(pf, tf, hf)
def simulation_engine(LHS, fn, modelicavarname, mofile, P_net, T_in_ref_blk, p_high, PR, pinch_PHX, dTemp_HTF_PHX, sim): #Check whether the file exist or not def FileCheck(fn): try: open(fn, "r") return 1 except IOError: return 0 #Create a file to dump the modelica simulation result - write the heading if file doesn't exist existence = FileCheck(fn) if existence == 0: f = open(fn, 'a') write = 'P_net,' for name in modelicavarname: write += '%s,' % name write += '\n' f.write(write) f.close() #Get the variable names that will be overwrite par_n = [] for index in range(len(modelicavarname)): par_n.append(modelicavarname[index]) if index == 7: break for operation_param in LHS: par_v = [] #Appending base variables par_v.append(str(T_in_ref_blk)) par_v.append(str(p_high)) par_v.append(str(PR)) par_v.append(str(pinch_PHX)) par_v.append(str(dTemp_HTF_PHX)) for i in range(5, len(modelicavarname) - 2): par_v.append(str(round(operation_param[i - 5], 2))) #Updating parameters sim.load_init() sim.update_pars(par_n, par_v) #Start simulation sim.simulate(start="0", stop="1", step="1", tolerance="1e-06", integOrder="5", solver="dassl", nls="homotopy") #Read Data data = D('%s_res_0.mat' % mofile) #Check validity eta_gross_array = data.data('eta_gross') eta_Q_array = data.data('eta_Q') #Write P_net write = '%s,' % (P_net) if len(eta_gross_array) == 0: for name in modelicavarname: val = 0 write += '%s,' % (val) else: for name in modelicavarname: val = data.data(name)[-1] write += '%s,' % (val) write += '\n' f = open(fn, 'a') f.write(write) f.close() #Simulating full load par_v = [] #Appending base variables par_v.append(str(T_in_ref_blk)) par_v.append(str(p_high)) par_v.append(str(PR)) par_v.append(str(pinch_PHX)) par_v.append(str(dTemp_HTF_PHX)) #Appending operational variables at design point, load = 1, T_HTF_IN = T_in_ref_blk, T_amb_des = 312.15, par_v.append(str(1)) par_v.append(str(T_in_ref_blk)) par_v.append(str(312.15)) #Updating parameters and run the simulation sim.load_init() sim.update_pars(par_n, par_v) sim.simulate(start="0", stop="1", step="1", tolerance="1e-06", integOrder="5", solver="dassl", nls="homotopy") #Read Data data = D('%s_res_0.mat' % mofile) #Check validity eta_gross_array = data.data('eta_gross') eta_Q_array = data.data('eta_Q') #Write P_net write = '%s,' % (P_net) if len(eta_gross_array) == 0: for name in modelicavarname: val = 0 write += '%s,' % (val) else: for name in modelicavarname: val = data.data(name)[-1] write += '%s,' % (val) write += '\n' f = open(fn, 'a') f.write(write) f.close()
def explore(f): data = D(f) T_top = data.data("thermocline_Tank.T_top_measured") T_bot = data.data("thermocline_Tank.T_bot_measured") T_p_rep = data.data("T_p_rep") level = data.data("tank_level") mdot = data.data("thermocline_Tank.Tank_A.m_flow") delta_top = T_p_rep - T_top delta_bot = T_p_rep - T_bot df = pd.DataFrame(zip(mdot, level, T_p_rep, T_top, T_bot, delta_top, delta_bot), columns=[ "mdot", "level", "T_p_rep", "T_top", "T_bot", "delta_top", "delta_bot" ]) #Charging df_charging = df[df.mdot < 0] df_standby = df[abs(df.mdot) < 1e-3] df_disc = df[df.mdot > 0] fig, ax = plt.subplots(3, 2) fig.tight_layout(pad=2) ax[0, 0].scatter(df_charging.level, df_charging.T_top - 273.15, c="red", s=1) ax[0, 0].set_xlabel("SOC") ax[0, 0].set_ylabel("T_top [°C]") ax[0, 0].set_title("Charging") ax[0, 1].scatter(df_charging.level, df_charging.T_bot - 273.15, c="red", s=1) ax[0, 1].set_xlabel("SOC") ax[0, 1].set_ylabel("T_bot [°C]") ax[0, 1].set_title("Charging") ax[1, 0].scatter(df_disc.level, df_disc.T_top - 273.15, c="red", s=1) ax[1, 0].set_xlabel("SOC") ax[1, 0].set_ylabel("T_top [°C]") ax[1, 0].set_title("Discharging") ax[1, 1].scatter(df_disc.level, df_disc.T_bot - 273.15, c="red", s=1) ax[1, 1].set_xlabel("SOC") ax[1, 1].set_ylabel("T_bot [°C]") ax[1, 1].set_title("Disharging") ax[2, 0].scatter(df_standby.level, df_standby.T_top - 273.15, c="red", s=1) ax[2, 0].set_xlabel("SOC") ax[2, 0].set_ylabel("T_top [°C]") ax[2, 0].set_title("Stand-by") ax[2, 1].scatter(df_standby.level, df_standby.T_bot - 273.15, c="red", s=1) ax[2, 1].set_xlabel("SOC") ax[2, 1].set_ylabel("T_bot [°C]") ax[2, 1].set_title("Stand-by") plt.show() fig, ax = plt.subplots(1, 2) ax[0].scatter(df_charging.T_p_rep, df_charging.T_top) ax[1].scatter(df_disc.T_p_rep, df_disc.T_top) plt.show()
def __init__(self, f): self.f = f self.data = D(self.f)
def genRegressionData(self, N, numerical=False): self.matfile = "%s_res_0.mat" % (self.moname) self.data = D(self.matfile) self.N = N #Fluid temperatures data T_fs = [] Tf_preds = [] T_ss = [] for i in range(1, self.N + 1): key = "thermocline_Tank.Tank_A.T_f[%s]" % (i) vals = self.data.data(key) T_fs.append(vals) key = "thermocline_Tank.Tank_A.T_s[%s]" % (i) vals = self.data.data(key) T_ss.append(vals) key = "T_f_regression[%s]" % (i) vals = self.data.data(key) Tf_preds.append(vals) T_fs = np.transpose(np.array(T_fs)) Tf_preds = np.transpose(np.array(Tf_preds)) T_ss = np.transpose(np.array(T_ss)) #Derivative of a,b,c,d (regression coefficient) self.der_a = np.array(self.data.data("der_a")).reshape(-1, 1) self.der_b = np.array(self.data.data("der_b")).reshape(-1, 1) self.der_c = np.array(self.data.data("der_c")).reshape(-1, 1) self.der_d = np.array(self.data.data("der_d")).reshape(-1, 1) #a,b,c,d,e,f,g,h self.a = np.array(self.data.data("a")).reshape(-1, 1) self.b = np.array(self.data.data("b")).reshape(-1, 1) self.c = np.array(self.data.data("c")).reshape(-1, 1) self.d = np.array(self.data.data("d")).reshape(-1, 1) try: self.e = np.array(self.data.data("e")).reshape(-1, 1) self.f = np.array(self.data.data("f")).reshape(-1, 1) self.g = np.array(self.data.data("g")).reshape(-1, 1) self.h = np.array(self.data.data("h")).reshape(-1, 1) self.der_e = np.array(self.data.data("der_a")).reshape(-1, 1) self.der_f = np.array(self.data.data("der_b")).reshape(-1, 1) self.der_g = np.array(self.data.data("der_c")).reshape(-1, 1) self.der_h = np.array(self.data.data("der_d")).reshape(-1, 1) efgh = True except: efgh = False #Get operational params self.mdot = self.data.data("mdot") T_amb = np.array(self.data.data("thermocline_Tank.T_amb")).reshape( -1, 1) u_flow = np.array( self.data.data("thermocline_Tank.Tank_A.u_flow")).reshape(-1, 1) #Get time self.time_simul = self.data.abscissa("der_a", valuesOnly=True) self.time_simul = np.array(self.time_simul).reshape(-1, 1) #Get parameters par = [ "thermocline_Tank.Tank_A.rho_f_avg", "thermocline_Tank.Tank_A.dz", "thermocline_Tank.Tank_A.U_bot", "thermocline_Tank.Tank_A.D_tank", "thermocline_Tank.Tank_A.U_wall", "thermocline_Tank.Tank_A.eta" ] rows = T_fs.shape[0] parval = [] for p in par: v = self.data.data(p)[-1] v = v * np.ones(rows) parval.append(v) parval = np.transpose(np.array(parval)) T_recv_sampling = (self.data.data("T_recv_sampling")[0] * np.ones(rows)).reshape(-1, 1) T_PB_sampling = (self.data.data("T_PB_sampling")[0] * np.ones(rows)).reshape(-1, 1) if efgh == True: colnames = [ "time", "rho_f_avg", "dz", "U_bot", "D_tank", "U_wall", "eta", "u_flow", "T_rcv", "T_PB", "T_amb", "a", "b", "c", "d", "e", "f", "g", "h", "der_a", "der_b", "der_c", "der_d", "der_e", "der_f", "der_g", "der_h" ] else: colnames = [ "time", "rho_f_avg", "dz", "U_bot", "D_tank", "U_wall", "eta", "u_flow", "T_rcv", "T_PB", "T_amb", "a", "b", "c", "d", "der_a", "der_b", "der_c", "der_d" ] for i in range(1, self.N + 1): colnames.append("Tf_%s" % i) for i in range(1, self.N + 1): colnames.append("Tf_pred_%s" % i) for i in range(1, self.N + 1): colnames.append("Ts_%s" % i) if efgh == True: N = np.concatenate( (self.time_simul, parval, u_flow, T_recv_sampling, T_PB_sampling, T_amb, self.a, self.b, self.c, self.d, self.e, self.f, self.g, self.h, self.der_a, self.der_b, self.der_c, self.der_d, self.der_e, self.der_f, self.der_g, self.der_h, T_fs, Tf_preds, T_ss), axis=1) else: N = np.concatenate((self.time_simul, parval, u_flow, T_recv_sampling, T_PB_sampling, T_amb, self.a, self.b, self.c, self.d, self.der_a, self.der_b, self.der_c, self.der_d, T_fs, Tf_preds, T_ss), axis=1) self.df_raw = pd.DataFrame(N, columns=colnames) if numerical == True: self.der_a = [] self.der_b = [] self.der_c = [] self.der_d = [] self.der_e = [] self.der_f = [] self.der_g = [] self.der_h = [] #Manually calculated using forward differencing #https://en.wikipedia.org/wiki/Numerical_differentiation#Finite_differences #Leave out the last time step data (repetition of the N-1 data) for i in range(self.df_raw.shape[0] - 1): delta_time = abs(self.df_raw["time"].iloc[i + 1] - self.df_raw["time"].iloc[i]) if delta_time == 0: self.der_a.append(0) self.der_b.append(0) self.der_c.append(0) self.der_d.append(0) self.der_e.append(0) self.der_f.append(0) self.der_g.append(0) self.der_h.append(0) else: self.der_a.append((self.df_raw["a"].iloc[i + 1] - self.df_raw["a"].iloc[i]) / delta_time) self.der_b.append((self.df_raw["b"].iloc[i + 1] - self.df_raw["b"].iloc[i]) / delta_time) self.der_c.append((self.df_raw["c"].iloc[i + 1] - self.df_raw["c"].iloc[i]) / delta_time) self.der_d.append((self.df_raw["d"].iloc[i + 1] - self.df_raw["d"].iloc[i]) / delta_time) self.der_e.append((self.df_raw["e"].iloc[i + 1] - self.df_raw["e"].iloc[i]) / delta_time) self.der_f.append((self.df_raw["f"].iloc[i + 1] - self.df_raw["f"].iloc[i]) / delta_time) self.der_g.append((self.df_raw["g"].iloc[i + 1] - self.df_raw["g"].iloc[i]) / delta_time) self.der_h.append((self.df_raw["h"].iloc[i + 1] - self.df_raw["h"].iloc[i]) / delta_time) #Take the row in df that has derivative - data row 1 to N-1 self.df_raw = self.df_raw[0:self.df_raw.shape[0] - 1] #Replace the derivative of a,b,c,d self.df_raw.der_a = self.der_a self.df_raw.der_b = self.der_b self.df_raw.der_c = self.der_c self.df_raw.der_d = self.der_d self.df_raw.der_e = self.der_e self.df_raw.der_f = self.der_f self.df_raw.der_g = self.der_g self.df_raw.der_h = self.der_h #Take only from row 2 self.df_raw = self.df_raw[1:] #Save the df as csv idx = 0 while os.path.exists("./res/rawdata%s.csv" % (idx)): idx += 1 self.df_raw.to_csv("./res/rawdata%s.csv" % (idx), index=False)
def genRawData(self, N): self.matfile = "%s_res_0.mat" % (self.moname) self.data = D(self.matfile) self.N = N #--> Number of discretisations data = D(self.matfile) colnames = [ "time", "rho_f_avg", "dz", "U_bot", "D_tank", "U_wall", "eta", "m_p" ] for i in range(1, self.N + 1): colnames.append("Tf_%s" % i) for i in range(1, self.N + 1): colnames.append("hf_%s" % i) for i in range(1, self.N + 1): colnames.append("hp_%s" % i) for i in range(1, self.N + 1): colnames.append("der_hf_%s" % i) for i in range(1, self.N + 1): colnames.append("der_hp_%s" % i) for i in range(1, self.N + 1): colnames.append("Ts_%s" % i) T_fs = [] T_ss = [] h_fs = [] h_ps = [] der_h_fs = [] der_h_ps = [] k_effs = [] h_vs = [] time_simul = np.array( self.data.abscissa("der(thermocline_Tank.Tank_A.h_f[1])", valuesOnly=True)).reshape(-1, 1) for i in range(1, self.N + 1): key = "thermocline_Tank.Tank_A.T_f[%s]" % (i) vals = self.data.data(key) T_fs.append(vals) key = "thermocline_Tank.Tank_A.T_s[%s]" % (i) vals = self.data.data(key) T_ss.append(vals) key = "thermocline_Tank.Tank_A.h_f[%s]" % (i) vals = self.data.data(key) h_fs.append(vals) key = "thermocline_Tank.Tank_A.h_p[%s]" % (i) vals = self.data.data(key) h_ps.append(vals) key = "der(thermocline_Tank.Tank_A.h_f[%s])" % (i) vals = self.data.data(key) der_h_fs.append(vals) key = "der(thermocline_Tank.Tank_A.h_p[%s])" % (i) vals = self.data.data(key) der_h_ps.append(vals) T_fs = np.transpose(np.array(T_fs)) T_ss = np.transpose(np.array(T_ss)) h_fs = np.transpose(np.array(h_fs)) h_ps = np.transpose(np.array(h_ps)) der_h_fs = np.transpose(np.array(der_h_fs)) der_h_ps = np.transpose(np.array(der_h_ps)) par = [ "thermocline_Tank.Tank_A.rho_f_avg", "thermocline_Tank.Tank_A.dz", "thermocline_Tank.Tank_A.U_bot", "thermocline_Tank.Tank_A.D_tank", "thermocline_Tank.Tank_A.U_wall", "thermocline_Tank.Tank_A.eta", "thermocline_Tank.Tank_A.m_p[1]" ] rows = T_fs.shape[0] parval = [] for p in par: v = self.data.data(p)[-1] v = v * np.ones(rows) parval.append(v) parval = np.transpose(np.array(parval)) T_amb = np.array(self.data.data("thermocline_Tank.T_amb")).reshape( -1, 1) colnames.append("T_amb") u_flow = np.array( self.data.data("thermocline_Tank.Tank_A.u_flow")).reshape(-1, 1) colnames.append("u_flow") T_charge = np.transpose( np.array(self.data.data("T_recv_sampling")[0] * np.ones(rows))).reshape(-1, 1) colnames.append("T_charge") T_discharge = np.transpose( np.array(self.data.data("T_PB_sampling")[0] * np.ones(rows))).reshape(-1, 1) colnames.append("T_discharge") h_in = np.array( self.data.data("thermocline_Tank.Tank_A.h_in")).reshape(-1, 1) colnames.append("h_in") h_out = np.array( self.data.data("thermocline_Tank.Tank_A.h_out")).reshape(-1, 1) colnames.append("h_out") N = np.concatenate( (time_simul, parval, T_fs, h_fs, h_ps, der_h_fs, der_h_ps, T_ss, T_amb, u_flow, T_charge, T_discharge, h_in, h_out), axis=1) self.df_raw = pd.DataFrame(N, columns=colnames) #Append the new df with existing df idx = 0 while os.path.exists("./res/rawdata%s.csv" % (idx)): idx += 1 self.df_raw.to_csv("./res/rawdata%s.csv" % (idx), index=False)
while not_converging: print( "###################################### SIMULATION FOR THE %s th DATA ###################################################" % (i + 1)) cmd = 'st_simulate --step 0.002 --stop 1 --solver dassl --nls homotopy --tolerance 1e-06 --np 0 sCO2PBCalculator.mo ' for j in range(inputs.shape[1]): cmd += '%s=%s ' % (varnames[j], inputs[i, j]) cmd += 'delta=%s' % (guess_delta) print(cmd) #Run SolarTherm os.system(cmd) #Read result matfile data = D('sCO2PBCalculator_res_0.mat') #Check if value is updated assert (data.data('dTemp_HTF_PHX')[0] == inputs[i, 0]) np.testing.assert_almost_equal(data.data('delta')[0], guess_delta) assert (data.data('p_high')[0] == inputs[i, 1]) assert (data.data('PR')[0] == inputs[i, 2]) eta_gross_array = data.data('eta_gross') if len(eta_gross_array) > 0: T_CO2_in = data.data('powerBlock.exchanger.T_CO2_des[1]')[0] T_HTF_out = data.data('powerBlock.exchanger.T_HTF_des[1]')[0] delta_Temp = T_HTF_out - T_CO2_in if delta_Temp > 10: not_converging = False print(
from DyMat import DyMatFile as D import pandas as pd import numpy as np from matplotlib import pyplot as plt import seaborn as sns N = 100 matfile = "/home/philgun/Documents/PhD/Publication/ANNforDynamicModelling/data/2months _annual_simulation.mat" data = D(matfile) colnames = ["rho_f_avg", "dz", "U_bot", "D_tank", "U_wall", "eta"] for i in range(1, N + 1): colnames.append("Tf_%s" % i) for i in range(1, N + 1): colnames.append("hf_%s" % i) for i in range(1, N + 1): colnames.append("der_hf_%s" % i) for i in range(1, N + 1): colnames.append("k_eff_%s" % i) for i in range(1, N + 1): colnames.append("hv_%s" % i) #for i in range(1,N+1): # colnames.append("T_s_%s"%i)
T_s = generate_gif(f_lc) for i in range(T_s.shape[0]): fig, ax = plt.subplots() T = T_s[i, :] X = np.arange(1, 101, 1) ax.plot(X, [t - 273.15 for t in T]) ax.set_xlabel("Dimensionless position") ax.set_ylabel("Filler temperature [°C]") fig.savefig("./gif/figure%s.png" % (i)) if i == 4000: break data_lc = D(f_lc) data_s = D(f_s) #Plot Level Dynamics lc_abs = data_lc.abscissa("tank_level", valuesOnly=True) lc_LV = data_lc.data("tank_level") s_abs = data_s.abscissa("tank_level", valuesOnly=True) s_LV = data_s.data("tank_level") fig, ax = plt.subplots(1, 2) ax[0].plot(lc_abs / 3600, lc_LV, label="LC model") ax[0].plot(s_abs / 3600, s_LV, label="Surrogate") ax[0].set_title("State of charge (SOC) comparison") ax[0].set_ylabel("SOC")
def process_data_2(matfile): data = D(matfile) t = data.abscissa("y1", valuesOnly=True) y1 = data.data("y1") y2 = data.data("y2") y3 = data.data("y3") df = pd.DataFrame( zip(t, y1, y2, y3, data.data("der(y1)"), data.data("der(y2)"), data.data("der(y3)")), columns=["time", "y1", "y2", "y3", "der_y1", "der_y2", "der_y3"]) df.to_csv("ori.csv", index=False) df = df[1:] delta_t = [] target_y1 = [] target_y2 = [] target_y3 = [] y1_init = [] y2_init = [] y3_init = [] der_y1 = [] der_y2 = [] der_y3 = [] for i in range(df.shape[0] - 1): delta_t.append(df.time.iloc[i + 1] - df.time.iloc[i]) target_y1.append(df.y1.iloc[i + 1]) target_y2.append(df.y2.iloc[i + 1]) target_y3.append(df.y3.iloc[i + 1]) y1_init.append(df.y1.iloc[i]) y2_init.append(df.y2.iloc[i]) y3_init.append(df.y3.iloc[i]) data = pd.DataFrame(zip(delta_t, y1_init, y2_init, y3_init, target_y1, target_y2, target_y3), columns=[ "delta_t", "y1", "y2", "y3", "target_y1", "target_y2", "target_y3" ]) data.to_csv("dat.csv", index=False) der_y1 = (data.target_y1 - data.y1) / data.delta_t der_y2 = (data.target_y2 - data.y2) / data.delta_t der_y3 = (data.target_y3 - data.y3) / data.delta_t data["der_y1"] = der_y1 data["der_y2"] = der_y2 data["der_y3"] = der_y3 data.to_csv("modif.csv", index=False) data = data.sample(frac=1).reset_index(drop=True) return data
def __init__(self, matfile, N): self.matfile = matfile self.N = N self.data = D(matfile)