예제 #1
0
def get_result(A_helio_total, A_rcv, fb, R1, ab_particle, t_storage, pinch):
    os.system(
        'st_simulate --stop 1y --maxStep 300s --step 3600s --np=0 PhysicalParticleCO21D_2ndApproach.mo n_row_oelt=9 n_col_oelt=25 A_helio_total=%f A_rcv=%f fb=%f R1=%f ab_particle=%f t_storage=%f pinch=%f'
        % (A_helio_total, A_rcv, fb, R1, ab_particle, t_storage, pinch))
    resmat = "PhysicalParticleCO21D_2ndApproach_res_0.mat"
    data = DyMat.DyMatFile(resmat)
    UA_HX = data.data("powerBlock.exchanger.UA_HX")[-1] / 1000
    C_heliostat = data.data("C_field")[-1]
    C_rcv = data.data("C_receiver")[-1]
    C_HX = data.data("powerBlock.C_exchanger")[-1]
    C_cycle = data.data("C_block")[-1] - C_HX
    C_storage = data.data("C_storage")[-1]
    C_equipment = data.data("C_cap_total")[-1]
    C_total = data.data("C_cap")[-1]
    EPY = data.data("E_elec")[-1] / 1000  #in kJ
    resultclass = postproc.SimResultElec
    res_object = resultclass(
        resmat
    )  #passing the resmatfile into resultclass (postproc.SimResultElec)
    result = res_object.calc_perf()
    LCOE = float('%.2f' % (result[1])) / 1000
    return [
        fb, R1, UA_HX, C_heliostat, C_rcv, C_HX, C_cycle, C_storage,
        C_equipment, C_total, EPY, LCOE
    ]
예제 #2
0
    def loadMatFile(filename, prefix=None):
        tic = time.time()
        d = DyMat.DyMatFile(filename)
        toc = time.time()
        print("Opening %s in %.3f ms" % (filename, (toc - tic) * 1000))

        extractVars(d, var_set, prefix=prefix)
 def setUp(self):
     fn = '../examples/Reference_2.mo'
     res_fn = './Reference_2_res_0.mat'
     xml_fn = './Reference_2_init_0.xml'
     #xml_fn2='./Reference_2_init.xml'
     self.sm = 2.8
     self.t_storage = 9
     os.system('st_simulate %s SM=%s t_storage=%s' %
               (fn, self.sm, self.t_storage))
     self.mat = DyMat.DyMatFile(res_fn)
     self.pxml = ProcesXML(xml_fn)
예제 #4
0
	def setUp(self):

		fn = '../examples/Reference_2.mo'
		res_fn='./Reference_2_res.mat'
		xml_fn='./Reference_2_init.xml'
		self.sm=2.8
		self.t_storage=9

		sim = simulation.Simulator(fn)
		sim.compile_model()
		self.pxml=ProcesXML(xml_fn)
		self.pxml.write_par(par_n=['SM', 't_storage'], par_v=[self.sm, self.t_storage],one=False)
		sim.compile_sim(args=['-s'])
		sim.simulate(start=0, stop=10, step=0.1)		
		self.mat=DyMat.DyMatFile(res_fn)
예제 #5
0
def extractVars(filename, tic=time.time()):
    # use just a subset or use all
    # vrs_names = ['Systemic1.posterior_tibial_T4_R236.u_C', 'Systemic1.aortic_arch_C2.port_a.pressure']
    # vrs_names = d.names(block = 2)
    d = DyMat.DyMatFile(filename)
    vrs_names = d.names()
    timevar = d.abscissa(2)[0]

    var_set = {}
    var_set['time'] = timevar
    for vn in vrs_names:
        var_set[vn] = d.data(vn)

    print("Opening result ", filename, " in ", time.time() - tic, " s")
    return var_set
예제 #6
0
def test_modelica():
    """
	Run the modelica test of STMotab.
	"""
    fn = './TestSTMotab.mo'
    sim = simulation.Simulator(fn)
    sim.compile_model()
    sim.compile_sim(args=['-s'])
    sim.simulate(start=0, stop='1y', step='5m', solver='dassl', nls='homotopy')

    res = DyMat.DyMatFile('TestSTMotab_res.mat')
    assert res.data("t1")[0] == 31500000.
    assert res.data("dnival")[0] == 976.
    assert res.data("dnicol")[0] == 2.

    cleantest.clean('TestSTMotab')
예제 #7
0
    def get_state_values(self):
        """
        Extracts the values of model outputs at the end of modeling time interval from simulation result

        :return: Values of model outputs as tuple in order specified in `model_outputs` attribute
        """

        self.data = DyMat.DyMatFile('temp_dir/dsres.mat')
        for name in self.debug_data:
            self.debug_data[name] += self.data[name].tolist()

        for name in self.add_names + self.model_input_names + self.rbc_action_names:
            if not name in self.debug_data:
                self.debug_data.update({name: []})
                self.debug_data[name] += self.data[name].tolist()

        return
예제 #8
0
    def loadResult(self):
        res__ = DyMat.DyMatFile(self.resultName)
        res_ = {}
        # get result for dymola mat file
        for i, req in enumerate(self.requestName):
            res_[i] = res__.data(req)

        # make time for interpolation
        time = numpy.zeros(int(self.simTime / self.deltaTime))
        for i in range(1, int(self.simTime / self.deltaTime)):
            time[i] = time[i - 1] + self.deltaTime

        # interpolation for equibalant time step
        res = numpy.zeros((len(time), len(res_)))
        for i in range(1, len(res_)):
            res[:, i] = numpy.interp(time, res_[0], res_[i])

        return res
예제 #9
0
    def setUp(self):
        fn = '../examples/Reference_2.mo'
        res_fn = './Reference_2_res_0.mat'
        xml_fn = './Reference_2_init_0.xml'
        #xml_fn2='./Reference_2_init.xml'
        self.sm = 2.8
        self.t_storage = 9

        cmd = ST() + [
            'simulate', fn,
            'SM=%s' % (self.sm, ),
            't_storage=%s' % (self.t_storage, )
        ]
        print("CMD =", cmd)
        shell = False
        if platform.system() == "Windows":
            shell = True
        subprocess.run(cmd, shell=shell, check=True)

        self.mat = DyMat.DyMatFile(res_fn)
        self.pxml = ProcessXML(xml_fn)
예제 #10
0
파일: OAT.py 프로젝트: philgun/coolstuff
            modelicavarname = [             
                'P_net',
                'T_in_ref_blk',
                'p_high',
                'PR',
                'pinch_PHX',
                'dTemp_HTF_PHX',
                'load',
                'T_HTF_in',
                'T_amb_input',
                'eta_gross',
                'eta_Q'
            ]

            data = DyMat.DyMatFile('%s_res_0.mat'%(mofile))

            #check convergence of the simulation
            eta_array = data.data('eta_gross')
            written = ''

            if len(eta_array)>0:
                for name in modelicavarname:
                    val = data.data(name)[-1]
                    written+='%s,'%(val)
            else:
                for name in modelicavarname:
                    written+='%s,'%(0)

            written+='\n'
예제 #11
0
        print(
            '################################################### ITERATION %s #########################################################'
            % (i + 1))

        print(cmd)
        with open('cmd.txt', 'w') as a:
            a.write(cmd)
            a.close()
        a = open('cmd.txt', 'a')
        a.write('\n%s P_net=%s' % (i + 1, P_net))
        a.close()
        #Run solartherm
        os.system(cmd)

        matfile = '%s_res_0.mat' % (mofile)
        data = DyMat.DyMatFile(matfile)

        #Get the data
        eta_gross_array = data.data('eta_gross')
        eta_Q_array = data.data('eta_Q')

        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 data exists:
        if len(eta_gross_array) > 0:
            if delta_Temp > 0:
                print(
                    "MODEL CONVERGE, NO TEMPERATURE CROSSING IN PHX, ALL GOOD! CROSSING: %s"
                    % (delta_Temp))
예제 #12
0
par_fr = 0.1
eta_rec_assumption = 0.88
T_amb_design = 283.15
P_gross_design = P_net / (1 - par_fr)
T_out_design = 800 + 273.15
T_in_design = 550 + 273.15

os.chdir(
    "/home/philgun/solartherm-particle/SolarTherm/Models/CSP/CRS/Receivers")
os.system(
    "st_simulate ParticleReceiver1DCalculator.mo SolarMultiple=%s dni_des=%s eta_rec_assumption=%s T_amb_design=%s P_gross_design=%s T_out_design=%s T_in_design=%s"
    % (sm, dni_des, eta_rec_assumption, T_amb_design, P_gross_design,
       T_out_design, T_in_design))
os.system("rm -rf *.c *.o *.h *.json *.xml *.makefile *.cmake *.bakmo")
resmat = "ParticleReceiver1DCalculator_res_0.mat"
data = DyMat.DyMatFile(resmat)
H_drop = data.data("particleReceiver1D.H_drop")[-1]
print(H_drop)
os.system("rm -rf *.mat")
os.chdir("/home/philgun/solartherm-particle/examples/")

#Generating the efficiency data
n_row = 15  #25 points of Q_in
n_col = 15  #25 points of T_amb

qsolar_val = np.linspace(100e6, 750e6, num=n_row, endpoint=True)
tamb_val = np.linspace(263.15, 323.15, num=n_col, endpoint=True)

meta = []
heading1 = "#1"
heading2 = "#METADATA Efficiency of the receiver Q_in_rcv [W] vs T_amb [K]"
예제 #13
0
def dy_mat_func(file):
    
    #for n in f.names():
    #    print(n)
    
    f = dm.DyMatFile(file + ".mat")

    time = f.abscissa('HC_B9.T', valuesOnly=True)
    B9_T = f.data('HC_B9.T')-273.15
    A7_T = f.data('HC_A7.T')-273.15
    A2_T = f.data('HC_A2.T')-273.15
    A11_T = f.data('HC_A11.T')-273.15
    B3_T = f.data('HC_B3.T')-273.15
    
    #speed
    v = f.data('Speed.y[1]')
    
    #Perscribed heat flow (conversion from W to kW)
    Q = f.data('timeTable.y[1]')/1000
    
    #Inlet and outlet temperature of HE or Radiator
    fi = f.data('fluid_inlet.y')
    fo = f.data('fluid_outlet.y')
    
    #Conversion of arrays to lists
    list1 = time.tolist()
    list2 = B9_T.tolist()
    list3 = A7_T.tolist()
    list4 = A2_T.tolist()
    list5 = A11_T.tolist()
    list6 = B3_T.tolist()

    list7 = fi.tolist()
    list8 = fo.tolist()
    
    list9 = v.tolist()
    list10 = Q.tolist()
    
    #Plots
    f, axarr = plt.subplots(2, 2, figsize=(14, 10))
    
    axarr[0, 0].plot(list1, list2, label='T$_{B9}$')
    axarr[0, 0].plot(list1, list3, label='T$_{A7}$')
    axarr[0, 0].plot(list1, list4, label='T$_{A2}$')
    axarr[0, 0].plot(list1, list5, label='T$_{A11}$')
    axarr[0, 0].plot(list1, list6, label='T$_{B3}$')
    axarr[0, 0].set_xlabel("Time [s]", fontsize=10)
    axarr[0, 0].set_ylabel("Temperature $[^{\circ}C]$", fontsize=10)
    axarr[0, 0].autoscale(tight=True)
    axarr[0, 0].grid(True)
    axarr[0, 0].legend()
    #axarr[0, 0].set_title(file)
    
    axarr[0, 1].plot(list1, list7, label='T$_{fluid\; inlet}$')
    axarr[0, 1].plot(list1, list8, label='T$_{fluid\; outlet}$')
    axarr[0, 1].set_xlabel("Time [s]", fontsize=10)
    axarr[0, 1].set_ylabel("Temperature $[^{\circ}C]$", fontsize=10)
    axarr[0, 1].autoscale(tight=True)
    axarr[0, 1].grid(True)
    axarr[0, 1].legend()
    #axarr[0, 1].set_title(file)
    
    axarr[1, 0].plot(list1, list9)
    axarr[1, 0].set_xlabel("Time [s]", fontsize=10)
    axarr[1, 0].set_ylabel("Velocity [km/h]", fontsize=10)
    axarr[1, 0].autoscale(tight=True)
    axarr[1, 0].grid(True)
    #axarr[1, 0].set_title(file)
    
    axarr[1, 1].plot(list1, list10)  
    axarr[1, 1].set_xlabel("Time [s]", fontsize=10)
    axarr[1, 1].set_ylabel("Q [kW]", fontsize=10)
    axarr[1, 1].autoscale(tight=True)
    axarr[1, 1].grid(True)
   # axarr[1, 1].set_title(file)
    
    plt.subplots_adjust(wspace=0.25, hspace=0.25)
    plt.suptitle(file)
    plt.savefig(file + "_COMPLETE.pdf", format='pdf')
    plt.show()
예제 #14
0
def dy_mat_func_inverter(file):

    #for n in f.names():
    #    print(n)

    f = dm.DyMatFile(file + ".mat")

    #Stores values from .mat file to numpy array
    time = f.abscissa('Chip1.T', valuesOnly=True)
    T1 = f.data('Chip1.T') - 273.15
    T2 = f.data('DC.T') - 273.15
    T3 = f.data('Housing_1.T') - 273.15
    T4 = f.data('Housing_pins.T') - 273.15
    T5 = f.data('Vapor_chamber.T') - 273.15
    T6 = f.data('Insulation.T') - 273.15

    #Rejected heat flow [W]
    Q = f.data('volume.q.Q_flow')

    #Conversion of arrays to lists
    list1 = time.tolist()
    list2 = T1.tolist()
    list3 = T2.tolist()
    list4 = T3.tolist()
    list5 = T4.tolist()
    list6 = T5.tolist()
    list7 = T6.tolist()

    list8 = Q.tolist()

    #Dataframes for plotting
    data1 = pd.DataFrame({
        'time': list1,
        'T$_{chip}$': list2,
        'T$_{AC/DC\; copper}$': list3,
        'T$_{housing}$': list4,
        'T$_{pins}$': list5,
        'T$_{vapor\; chamber}$': list6,
        'T$_{insulation}$': list7
    })

    data2 = pd.DataFrame({'time': list1, 'Q [W]': list8})

    xmin = 0
    xmax = max(list1)
    ymin1 = min(list2)
    ymax1 = max(list2)
    ymin2 = min(list8)
    ymax2 = max(list8)

    print("Max temperature for case " + file + ": " + str(round(ymax1, 2)) +
          " degC.")

    with open("Results.txt", "a") as f:
        f.write("Max temperature for case " + file + ": " +
                str(round(ymax1, 2)) + " degC.\n")


#    data1.plot(x='time')
#    plt.xlabel("Time [s]")
#    plt.ylabel("Temperature $[^{\circ}C]$")
#    plt.xlim(xmin, xmax)
#    plt.ylim(ymin1, ymax1+5)
##    plt.autoscale(tight=True)
#    plt.grid(True)
#    plt.title(file)
#    plt.savefig(file + "_Inverter_T.png")
#    plt.show()
#
#    data2.plot(x='time')
#    plt.xlabel("Time [s]")
#    plt.ylabel("Q [W]")
#    plt.xlim(xmin, xmax)
#    plt.ylim(ymin2, ymax2+5)
##    plt.autoscale(tight=True)
#    plt.grid(True)
#    plt.title(file)
#    plt.legend().remove()
#    plt.savefig(file + "_Q.png")
#    plt.show()

#    #All plots
    f, axarr = plt.subplots(2, sharex=True, figsize=(15, 10))

    axarr[0].plot(list1, list2, label='T$_{chip}$')
    axarr[0].plot(list1, list3, label='T$_{AC/DC\; copper}$')
    axarr[0].plot(list1, list4, label='T$_{housing}$')
    axarr[0].plot(list1, list5, label='T$_{pins}$')
    axarr[0].plot(list1, list6, label='T$_{vapor\; chamber}$')
    axarr[0].plot(list1, list7, label='T$_{insulation}$')
    axarr[0].set_xlabel("Time [s]", fontsize=10)
    axarr[0].set_ylabel("Temperature $[^{\circ}C]$", fontsize=10)
    axarr[0].set_xlim(xmin, xmax)
    axarr[0].set_ylim(ymin1, ymax1 + 5)
    #    axarr[0].autoscale(tight=True)
    axarr[0].grid(True)
    axarr[0].legend()
    #    plt.xlim((0,694))
    #    axarr[0].set_title(file)

    axarr[1].plot(list1, list8)
    axarr[1].set_xlabel("Time [s]", fontsize=10)
    axarr[1].set_ylabel("Q [W]", fontsize=10)
    axarr[1].set_xlim(xmin, xmax)
    axarr[1].set_ylim(ymin2, ymax2 + 5)
    #    axarr[1].autoscale(tight=True)
    axarr[1].grid(True)
    #    axarr[1, 0].set_title(file)

    plt.subplots_adjust(wspace=0.25, hspace=0.25)
    plt.suptitle(file)
    plt.savefig(file + "_complete.png", format='png')
    plt.show()
예제 #15
0
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


import DyMat, DyMat.Export, random

files = ('DoublePendulum_Dymola-7.4.mat', 
         'DoublePendulum_OpenModelica-1.8.mat',
         'DoublePendulum_Dymola-2012.mat',
         'DoublePendulum_Dymola-2012-SaveAs.mat',
         'DoublePendulum_Dymola-2012-SaveAsPlotted.mat' )

formats = DyMat.Export.formats.keys()


for fi in files:
    # open file
    df = DyMat.DyMatFile(fi)
    
    # pick a maximum of 30 random variable names
    n = df.names()
    x = min(len(n), 30)
    va = random.sample(df.names(), x)
    
    # do export
    for fo in formats:
        print('Exporting %s to %s' % (fi, fo))
        DyMat.Export.export(fo, df, va)
예제 #16
0
def dy_mat_func(file):

    #for n in f.names():
    #    print(n)

    f = dm.DyMatFile(file + ".mat")

    #Stores values from .mat file to numpy array
    time = f.abscissa('MotorLeft.T', valuesOnly=True)
    MotorL = f.data('MotorLeft.T') - 273.15
    MotorR = f.data('MotorRight.T') - 273.15

    #speed
    v = f.data('Speed.y[1]')

    #Perscribed heat flow (conversion from W to kW)
    Q_L = f.data('timeTable1.y[1]') / 1000
    Q_R = f.data('timeTable2.y[1]') / 1000

    #Inlet and outlet temperature of HE or Radiator
    fi = f.data('HE_inlet1.y')
    fo = f.data('HE_outlet1.y')

    #Conversion of arrays to lists
    list1 = time.tolist()
    list2 = MotorL.tolist()
    list3 = MotorR.tolist()

    list4 = fi.tolist()
    list5 = fo.tolist()

    list6 = v.tolist()
    list7 = Q_L.tolist()
    list8 = Q_R.tolist()

    #Average heat flow
    list9 = averageQ(list7)
    list10 = averageQ(list8)

    #Dataframes for plotting
    data1 = pd.DataFrame({
        'time': list1,
        'T$_{left\; motor}$': list2,
        'T$_{right\; motor}$': list3
    })

    data2 = pd.DataFrame({
        'time': list1,
        'T$_{fluid\; inlet}$': list4,
        'T$_{fluid\; outlet}$': list5
    })

    data3 = pd.DataFrame({'time': list1, 'Velocity [km/h]': list6})

    data4 = pd.DataFrame({
        'time': list1,
        'Q$_{left\; motor}$ [kW]': list7,
        'Q$_{right\; motor}$ [kW]': list8,
        'Q$_{average\; left}$ [kW]': list9,
        'Q$_{average\; right}$ [kW]': list10
    })

    #fig, ax = plt.subplots()

    data1.plot(x='time')
    plt.xlabel("Time [s]")
    plt.ylabel("Temperature $[^{\circ}C]$")
    #plt.xlim((0,694))
    #plt.ylim((25,120))
    plt.autoscale(tight=True)
    plt.grid(True)
    plt.title(file)
    plt.savefig(file + "_Motor_T.png")
    plt.show()

    data2.plot(x='time')
    plt.xlabel("Time [s]")
    plt.ylabel("Temperature $[^{\circ}C]$")
    plt.autoscale(tight=True)
    #plt.xlim((0,694))
    #plt.ylim((20,100))
    plt.grid(True)
    plt.title(file)
    plt.savefig(file + "_HE_T.png")
    plt.show()

    data3.plot(x='time')
    plt.xlabel("Time [s]")
    plt.ylabel("Velocity [km/h]")
    plt.autoscale(tight=True)
    #plt.xlim((0,694))
    #plt.ylim((0,100))
    plt.grid(True)
    plt.title(file)
    plt.legend().remove()
    plt.savefig(file + "_velocity.png")
    plt.show()

    data4.plot(x='time')
    plt.xlabel("Time [s]")
    plt.ylabel("Q [kW]")
    #plt.xlim((0,694))
    #plt.ylim((0,25))
    plt.autoscale(tight=True)
    plt.grid(True)
    plt.title(file)
    #plt.legend().remove()
    plt.savefig(file + "_Q.png")
    plt.show()

    #All plots
    f, axarr = plt.subplots(2, 2, figsize=(14, 10))

    axarr[0, 0].plot(list1, list2, label='T$_{left\; motor}$')
    axarr[0, 0].plot(list1, list3, label='T$_{right\; motor}$')
    axarr[0, 0].set_xlabel("Time [s]", fontsize=10)
    axarr[0, 0].set_ylabel("Temperature $[^{\circ}C]$", fontsize=10)
    axarr[0, 0].autoscale(tight=True)
    axarr[0, 0].grid(True)
    axarr[0, 0].legend()
    #axarr[0, 0].set_title(file)

    axarr[0, 1].plot(list1, list4, label='T$_{fluid\; inlet}$')
    axarr[0, 1].plot(list1, list5, label='T$_{fluid\; outlet}$')
    axarr[0, 1].set_xlabel("Time [s]", fontsize=10)
    axarr[0, 1].set_ylabel("Temperature $[^{\circ}C]$", fontsize=10)
    axarr[0, 1].autoscale(tight=True)
    axarr[0, 1].grid(True)
    axarr[0, 1].legend()
    #axarr[0, 1].set_title(file)

    axarr[1, 0].plot(list1, list6)
    axarr[1, 0].set_xlabel("Time [s]", fontsize=10)
    axarr[1, 0].set_ylabel("Velocity [km/h]", fontsize=10)
    axarr[1, 0].autoscale(tight=True)
    axarr[1, 0].grid(True)
    #axarr[1, 0].set_title(file)

    axarr[1, 1].plot(list1, list7, label='Q$_{left\; motor}$ [kW]')
    axarr[1, 1].plot(list1, list8, label='Q$_{right\; motor}$ [kW]')
    axarr[1, 1].plot(list1, list9, label='Q$_{average\; left}$ [kW]')
    axarr[1, 1].plot(list1, list10, label='Q$_{average\; right}$ [kW]')
    axarr[1, 1].set_xlabel("Time [s]", fontsize=10)
    axarr[1, 1].set_ylabel("Q [kW]", fontsize=10)
    axarr[1, 1].autoscale(tight=True)
    axarr[1, 1].grid(True)
    axarr[1, 1].legend()
    #axarr[1, 1].set_title(file)

    plt.subplots_adjust(wspace=0.25, hspace=0.25)
    plt.suptitle(file)
    plt.savefig(file + "_COMPLETE.png", format='png')
    plt.show()
예제 #17
0
# Build modelica Object Tree
mc_tree = mc.ModelicaClass.BuildObjectTree(lines, root=base_model)

if resetVPV:
    mc_tree.buildChildTree([['settings.V_PV_init', 'param']])
    vpvn = mc_tree.findNode('settings.V_PV_init')
    vpvn.start_val = 0

if mat_file_path is None:
    mat_file_path = relative_folder + base_model + '.mat'

mat_date = str(datetime.datetime.fromtimestamp(
    os.path.getmtime(mat_file_path)))

# open file with values
d = DyMat.DyMatFile(mat_file_path)
time = d.abscissa(2)[0]

nmsList = d.names(block=2)
#nmsStr = "\r".join(nmsList)
steadyStateInd = TerminalDS.findLowestIndex(steadyStateAt,
                                            time,
                                            returnLast=True)

# pick value
for name in nmsList:
    # look for its existence in the states set
    n = mc_tree.findNode(name)
    if n is None:
        continue
    # if 'radial_vein_T3_R120' in name:
예제 #18
0
# -*- coding: utf-8 -*-
#xmodmap -e "keycode 72 = dead_greek dead_greek dead_greek dead_greek"
import DyMat 
import numpy as np
from tabulate import tabulate
from solartherm import postproc

fn_1 = '925'
resmat_1 = '/home/philgun/solartherm-particle/examples/%s.mat' %(fn_1)
data_1 = DyMat.DyMatFile(resmat_1)
print(data_1.data('C_hx')[-1])

fn_2 = '2125'
if fn_2 is None :
	data_2 = data_1
else:
	resmat_2 = '/home/philgun/solartherm-particle/examples/%s.mat' %(fn_2)
	data_2 = DyMat.DyMatFile(resmat_2)

if fn_2 is None:
	data_set = 1
else:
	data_set = 2

num_var = 20
num_parameter = 11



#item_1 = "Turbine / PB Design Efficiency " #powerBlock.turbine.eta_design or eff_blk
item_1 = "Total heliostat area" #SM
예제 #19
0
    def __init__(self, CSV_path, **kwargs):

        # Default:
        #   It WILL NOT interpolate the data according to another "step"
        #   It WILL replace the . with _ in the variables names

        try:  # if the kwarg exist, create a variable called x_func
            kwargs['interp']
            x_func = kwargs['interp']
            self.time = kwargs['interp']
        except KeyError:  # if it doesn't exist:
            kwargs['interp'] = 0

        try:
            kwargs['replaceDot']
        except KeyError:
            kwargs['replaceDot'] = True

        if ".csv" in CSV_path:  # User enters with an CSV file
            df = pd.read_csv(
                CSV_path
            )  # Read the .OUT file and storage it in a pandas data frame

            header = df.columns  # Header that will be modified to create object variables
            header_orig = df.columns  # Original header, just like it is in modelica
            n_var = len(df.columns)  # Number of variables

            aa = ""  # Add "nothing" to the variables' names and
            header = [aa + s for s in header]  # Now it is a list of strings

            count = [0] * n_var  # Storage the number of . in a variable's name

            for ii in range(0, n_var):
                if kwargs['replaceDot'] == True:  # replaces . with _
                    for jj in header[ii]:
                        if jj == ".":
                            header[ii] = header[ii].replace(".", "_")
                        elif jj == ")":
                            header[ii] = header[ii].replace(")", "_")
                        elif jj == "(":
                            header[ii] = header[ii].replace("(", "_")
                else:
                    for jj in header[ii]:
                        if jj == ".":
                            count[ii] = count[ii] + 1
                        elif jj == ")":
                            header[ii] = header[ii].replace(")", "_")
                        elif jj == "(":
                            header[ii] = header[ii].replace("(", "_")
                    for kk in range(0, count[ii]):
                        header[ii] = re.sub(
                            r'^.*?\.', "", header[ii]
                        )  # Takes everything before the . and replace with nothing

            h_str = "self."  # Add "nothing" to the variables names and
            header = [h_str + s for s in header]  # now it is a list of strings

            ############################################################################
            # Interpolate OMEDit Variables with the PSCAD Time variable, if its the case
            # and then storage it in a variable with its name
            ############################################################################

            if type(kwargs['interp']
                    ) is not int:  # Means the kwarg is a vector
                df1 = pd.DataFrame(
                )  # A X sized DataFrame can't receive a Y sized df, so a new one is created

                for ii in range(0, n_var):
                    if ii == 0:
                        df1[header_orig[ii]] = x_func
                    else:
                        f_lin = interp1d(df[header_orig[0]],
                                         df[header_orig[ii]]
                                         )  # x = OMEdit time, y = the variable
                        df1[header_orig[ii]] = f_lin(x_func)

                    exec('%s = np.array(%s)' %
                         (header[ii], 'df1[header_orig[ii]]'))
            else:
                for ii in range(0, n_var):
                    exec('%s = np.array(%s)' %
                         (header[ii], 'df[header_orig[ii]]'))

        else:  # If user enters with a .MAT file

            d = DyMat.DyMatFile(CSV_path)

            n_var = len(d.names())
            header = [0] * n_var

            vec = []

            header_lst = list(d.names())

            for a in range(0, n_var):
                header[a] = "self." + header_lst[a].replace(".", "_")
                header[a] = header[a].replace("(", "_")
                header[a] = header[a].replace(")", "_")

                if type(kwargs['interp']
                        ) is not int:  # Means it is an interpolation vector

                    f_lin = interp1d(
                        d.abscissa(header_lst[a])[0], d.data(header_lst[a]))
                    vec = f_lin(self.time)
                    exec('%s = np.array(%s)' % (header[a], 'vec'))

                else:
                    exec('%s = np.array(%s)' %
                         (header[a], 'd.data(header_lst[a])'))
예제 #20
0
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd

import DyMat
import postproc

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

# TODO: use argparse or somethng else to get filename
modelica_result_path = "kiss_1_res.mat"
modelica_result = DyMat.DyMatFile(modelica_result_path)

# parameters for visualisation
tmax = 1000
every = 5

# -----------------------------------------
# Cell temperatures vs. time, as facet plot
# -----------------------------------------
k = 0  # plot fwd cells only
df_tcell = postproc.read_tcell(modelica_result,
                               every=every).query(f'k=={k} & t<{tmax}')
df_tcell["Tcell"] -= 273.15
fig_tcell = px.line(df_tcell,
                    x="t",
                    y="Tcell",
예제 #21
0
    def test1(self):
        global VERBOSE, RUNSIM, PLOTME
        file_name = 'PhysicalParticleCO21D'
        #file_name = 'PhysicalParticleSystem1D'
        fn = ('%s.mo' % (file_name, ))
        print "Modelica File Name = " + fn
        sim = simulation.Simulator(fn)
        resfn = sim.model + '_res.mat'
        print "Modelica File Result Name = " + resfn

        if VERBOSE: print "RUNNING SETUP"

        if RUNSIM == 1:
            if VERBOSE: print "COMPILING MODEL"
            sim.compile_model(args=['-d=bltdump'])
            if VERBOSE: print "COMPILING SIM"
            sim.compile_sim(args=['-s'])
            if VERBOSE: print "SOLVING MODEL"
            reporting_interval = 1800
            step_string = '%fs' % (reporting_interval)
            stop_time = 365 * 24 * 3600
            stop_string = '%fs' % (stop_time)
            sim.simulate(start=0,
                         stop=stop_string,
                         step=step_string,
                         maxStep='300s',
                         solver='dassl',
                         nls=None
                         #,lv='LOG_DEBUG,LOG_NLS,LOG_SOLVER'#,LOG_NLS_V'
                         )

        self.res = postproc.SimResult(resfn)

        resmatfile = '/home/philgun/solartherm/examples/%s' % (
            resfn)  #getting the res_mat file
        data = DyMat.DyMatFile(
            resmatfile)  #getting the value inside the resmat file
        data2 = DyMat.DyMatFile('/home/philgun/solartherm/examples/%s' %
                                ('PhysicalParticleCO21D_res.mat'))

        if file_name == 'PhysicalParticleSystem0D':
            rcv = 'receiver.'
        elif file_name == 'PhysicalParticleCO21D_v11':
            rcv = 'particleReceiver1D_v11.'
        else:
            rcv = 'particleReceiver1D.'
        pb = 'powerBlock.'

        if file_name == 'PhysicalParticleSystem1D' or file_name == 'PhysicalParticleCO21D':
            N = data.data(rcv +
                          'N')[1]  #getval(rcv + 'N') # getval('%s.N' %(rcv,))
            print 'Particle Receiver Discretization = %f cells' % (N)

        if VERBOSE:
            print("SYSTEM'S RESULTS %s" % (file_name))
            print ""

            name_var = 'A_field'
            var = data.data(name_var)
            print 'Heliostat Field Area (m.sq) = %f' % (var[1])

            name_var = 'E_elec'
            var = data.data(
                name_var)  #getval (name_var)   #('%s.%s' %(sys,name_var))
            print 'Energy Per Year (MWh/year) = %f' % (var[-1] * 2.778e-10)

            name_var = 'E_total_loses_optical'
            var = data.data('heliostatsField.E_total_loses_optical')[
                -1]  #getval (name_var)   #('%s.%s' %(sys,name_var))
            print 'Energy losses due to optical (MWh/year) = %f' % (var *
                                                                    2.778e-10)

            name_var = 'H_tower'
            var = data.data(name_var)
            print 'Tower height (m) = %f' % (var[1])

            print ""

            print "Receiver's Geometry"

            name_var = 'A_rcv'
            var = data.data(name_var)
            print 'Total receiver area (m.sq) = %f' % (var[1])

            name_var = 'H_rcv'
            var = data.data(name_var)
            print 'Receiver height (m) = %f' % (var[1])

            name_var = 'A_rcv'
            var = data.data(name_var)
            print 'Receiver aperture area (m.sq) = %f' % (var[1])
            print ""

            print "PLANT'S ANALYTICS"  #two type curtailments 1 shutdown the heliostat 2 defocusing
            print ""
            print "Energy Analytics"
            name_var = 'E_resource'
            var = data.data(name_var)
            print "Annual Sun's Energy coming to the heliostat field before cosine loses and curtailment  (MWh/year) = %f" % (
                var[-1] * 2.778e-10)

            name_var = 'E_helio_incident'
            var = data.data(name_var)[-1]
            print "Annual energy incident of the heliostat field after curtailment due to low DNI / high windspeed  (MWh/year) = %f" % (
                var * 2.778e-10)

            name_var = 'E_helio_raw'
            var = data.data(name_var)[-1]
            print "Annual energy delivered by the heliostat field before defocusing curtailment (MWh/year) = %f" % (
                var * 2.778e-10)

            name_var = 'E_helio_net'
            var = data.data(name_var)[-1]
            print "Annual energy delivered by the heliostat to the receiver after every curtailments (MWh/year) = %f" % (
                var * 2.778e-10)

            name_var = 'E_recv_incident'
            var = data.data(name_var)[-1]
            print "Annual energy delivered to the receiver by heliostat (MWh/year) = %f" % (
                var * 2.778e-10)

            name_var = 'E_recv_net'
            var = data.data(name_var)[-1]
            print "Annual energy absorbed by the working fluid in the receiver (MWh/year) = %f" % (
                var * 2.778e-10)

            name_var = 'E_pb_input'
            var = data.data(name_var)[-1]
            print "Annual energy delivered to the power block  (MWh/year) = %f" % (
                var * 2.778e-10)

            name_var = 'E_pb_gross'
            var = data.data(name_var)[-1]
            print "Annual energy produced by the turbine's shaft  (MWh/year) = %f" % (
                var * 2.778e-10)

            name_var = 'E_pb_net'
            var = data.data(name_var)[-1]
            print "Annual net energy produced by the system (MWh/year) = %f" % (
                var * 2.778e-10)
            print '#################################################################################################################'
            print ""
            print "Efficiency Analytics"

            name_var = 'eta_curtail_off'
            var = data.data(name_var)[-1]
            print "Annual Efficiency of the heliostat due to low DNI/high windspeed curtailment = %f" % (
                var)

            name_var = 'eta_optical'
            var = data.data(name_var)[-1]
            print "Annual Efficiency of the heliostat due to field efficiency = %f" % (
                var)

            name_var = 'he_av_design'
            var = data.data(name_var)[1]
            print "Annual Efficiency of the heliostat due availability = %f" % (
                var)

            name_var = 'eta_curtail_defocus'
            var = data.data(name_var)[-1]
            print "Annual Efficiency of the heliostat due to defocus curtailment = %f" % (
                var)

            if resfn == 'PhysicalParticleCO21D_res.mat' or resfn == 'PhysicalParticleSystem1D._res.mat':
                print "Annual Efficiency of the receiver due to absorption = %s" % (
                    'N/A')
            else:
                name_var = 'eta_recv_abs'
                var = data.data(name_var)[-1]
                print "Annual Efficiency of the receiver due to absorption = %s" % (
                    'N/A')

            name_var = 'eta_recv_thermal'
            var = data.data(name_var)[-1]
            print "Annual Efficiency of the receiver due to heat losses and physics phenomena in the receiver = %f" % (
                var)

            name_var = 'eta_storage'
            var = data.data(name_var)[-1]
            print "Annual Efficiency of the storage due to losses in the storage system = %f" % (
                var)

            name_var = 'eta_pb_gross'
            var = data.data(name_var)[-1]
            print "Annual Efficiency of the power block (ratio between power gross power block / heat input to the heat exchanger) = %f" % (
                var)

            name_var = 'eta_pb_net'
            var = data.data(name_var)[-1]
            print "Annual Efficiency of the power block (ratio between net power produced by power block sub system / power produced by turbine shaft)  = %f" % (
                var)

            name_var = 'eta_solartoelec'
            var = data.data(name_var)[-1]
            print "Annual Efficiency of system (solar energy / generated electrical energy) = %f" % (
                var)

            print '#################################################################################################################'
            print "TOTAL PLANT'S COST (million AUD) = %f " % (
                data.data('C_cap')[1] / 1e6)
            print "TOTAL EQUIPMENTS COST (million AUD) = %f " % (
                data.data('C_cap_total')[1] / 1e6)
            print "Contingency, indirect and construction cost constants = %f" % (
                (data.data('r_contg')[1] + 1) *
                (data.data('r_indirect')[1] + 1) *
                (data.data('r_cons')[1] + 1))
            print ""
            print "Annual OnM (million AUD) = %f " % (data.data('C_year')[1] /
                                                      1e6)

            print '#################################################################################################################'
            print ""

            print "Site's, land and heliostat field's cost (million AUD) = %f" % (
                (data.data('C_field')[1] + data.data('C_site')[1] +
                 data.data('C_land')[1]) / 1e6)

            name_var = 'C_field'
            var = data.data(name_var)[1]
            print 'Capital cost of the solar field (million AUD) = %f' % (
                (var) / 1e6)

            name_var = 'C_site'
            var = data.data(name_var)[1]
            print 'Capital cost of site improvement work (million AUD) = %f' % (
                (var) / 1e6)

            name_var = 'C_land'
            var = data.data(name_var)[1]
            print 'Capital cost of land (million AUD) = %f' % ((var) / 1e6)

            print '#################################################################################################################'
            print ""

            print "Falling particle receiver sub-system cost (million AUD)= %f" % (
                (data.data('C_receiver')[1]) / 1e6)

            name_var = 'C_tower'
            var = data.data(name_var)[1]
            print 'Capital cost of the tower (million AUD) = %f' % (
                (var) / 1e6)

            name_var = 'C_fpr'
            var = data.data(name_var)[1]
            print 'Capital cost of the falling particle receiver (million AUD) = %f' % (
                (var) / 1e6)

            name_var = 'C_lift_rec'
            var = data.data(name_var)[1]
            print 'Capital cost of the receiver lift (million AUD) = %f' % (
                (var) / 1e6)

            print '#################################################################################################################'
            print ""

            print 'Storage Tank / Bin costs (million AUD)= %f' % (
                (data.data('C_storage')[1]) / 1e6)

            name_var = 'C_bins'
            var = data.data(name_var)[1]
            print 'Total capital cost hot and cold storage bins (million AUD) = %f' % (
                (var) / 1e6)

            name_var = 'C_particles'
            var = data.data(name_var)[1]
            print 'Total capital cost of the particles (million AUD) = %f' % (
                (var) / 1e6)

            name_var = 'C_lift_hx'
            var = data.data(name_var)[1]
            print 'Capital cost of the heat exchanger lift (power block) (million AUD) = %f' % (
                (var) / 1e6)

            name_var = 'C_lift_cold'
            var = data.data(name_var)[1]
            print 'Capital cost of the cold storage lift (million AUD) = %f' % (
                (var) / 1e6)

            print '#################################################################################################################'

            if fn == 'PhysicalParticleSystem1D.mo' or fn == 'PhysicalParticleSystem0D.mo':

                print 'Power Block sub-system cost (million AUD)= %f' % (
                    (data.data('C_pb')[1]) / 1e6)

            else:

                print 'Power Block sub-system cost (million AUD)= %f' % (
                    (data.data('C_block')[1]) / 1e6)

                name_var = 'C_LTR'
                var = data.data(pb + name_var)[1]
                print 'Capital cost of the low temperature recuperator (million AUD) = %f' % (
                    (var) / 1e6)

                name_var = 'C_HTR'
                var = data.data(pb + name_var)[1]
                print 'Capital cost of the high temperature recuperator (million AUD) = %f' % (
                    (var) / 1e6)

                name_var = 'C_cooler'
                var = data.data(pb + name_var)[1]
                print 'Capital cost of the air-cooler CO2 (million AUD) = %f' % (
                    var / 1e6)

                name_var = 'C_exchanger'
                var = data.data(pb + name_var)[1]
                print 'Capital cost of the main heat exchager (between CO2 and Particle) (million AUD) = %f' % (
                    (var) / 1e6)

                name_var = 'C_generator'
                var = data.data(pb + name_var)[1]
                print 'Capital cost of the generator (million AUD) = %f' % (
                    (var) / 1e6)

                name_var = 'C_mainCompressor'
                var = data.data(pb + name_var)[1]
                print 'Capital cost of the main compressor (million AUD) = %f' % (
                    (var) / 1e6)

                name_var = 'C_reCompressor'
                var = data.data(pb + name_var)[1]
                print 'Capital cost of the recompressor (million AUD) = %f' % (
                    (var) / 1e6)

                name_var = 'C_turbine'
                var = data.data(pb + name_var)[1]
                print 'Capital cost of the turbine (million AUD) = %f' % (
                    (var) / 1e6)
            print '#################################################################################################################'
            print ""
        resultclass = postproc.SimResultElec  #calling the class of SimResultElec in postproc.py
        res = resultclass(
            resfn
        )  #passing the resmatfile into resultclass (postproc.SimResultElec)
        result = res.calc_perf(
        )  #calculating result by calling calc_perf function inside the resultclass class

        print '#################################################################################################################'
        print "Energy Per Year(MWh/year) = %f, LCOE(USD/MWh) = %f, Capacity Factor(%%)= %f, Spot Market Revenue(million USD/year) = %f" % (
            result[0], result[1], result[2], result[3] / 1e6
        )  #printing the postproc result

        #vl = ['N','T_s[1]','T_s[%d]'%(N+1,), 'mdot', 'q_solar','A_ap'
        #	,'eta_rec','eps_c[%d]'%(N,)
        #	,'H_drop','W_rcv','t_c_in']
        #for v in vl:
        #	print '%s = %f' %(v,getval('revOneDPGv2LookUpTable.%s'%(v,)))
        #for v in ['Qdot_rec','Qdot_inc']:
        #	print '%s = %f MW' %(v,getval('revOneDPGv2LookUpTable.%s'%(v,))/1e6)
        #for T in ['T_in','T_out']:
        #	#print '%s = %f°C'%(T,getval('revOneDPGv2LookUpTable.%s'%(T,))-273.15)
        #print 'T_in = %f°C'%(getval('revOneDPGv2LookUpTable.T_s[1]')-273.15)
        #print 'T_out= %f°C'%(getval('revOneDPGv2LookUpTable.T_s[%d]'%(N+1,))-273.15)

        if PLOTME:
            import matplotlib
            matplotlib.use('GTKCairo')
            import matplotlib.pyplot as pl
            #nr = 1; nc = 1; sp=0 #nr = number of row , nc = nuber of column, sp = space between plot
            time = data.abscissa(rcv + 'eta_rec', valuesOnly=True)
            eta_rec_v11 = data.data(rcv + 'eta_rec')
            eta_rec_v9 = data2.data('particleReceiver1D.' + 'eta_rec')
            Qdot_rec_v11 = data.data(rcv + 'Qdot_rec') * 100
            Qdot_rec_v9 = data2.data('particleReceiver1D.' + 'Qdot_rec') * 100
            #print type(y)
            #print np.shape(y)
            #print type(time)
            #print np.shape(time)
            #print '**********************************'
            #print ''

            fig = pl.figure()
            #sp+=1; ax1 = pl.subplot(nr,nc,sp)
            pl.xlim(170 * 24 * 3600, 173 * 24 * 3600)
            pl.plot(time, eta_rec_v11, label='v_11')
            pl.plot(time, eta_rec_v9, label='v_09')
            pl.legend(fontsize=20)
            pl.ylabel('Efficiency of the receiver', fontsize=40)
            pl.xlabel('Time', fontsize=40)
            pl.title('Receiver efficiency at day 170 to 172', fontsize=40)
            pl.show()

            pl.xlim(170 * 24 * 3600, 173 * 24 * 3600)
            pl.plot(time, Qdot_rec_v11, label='v_11')
            pl.plot(time, Qdot_rec_v9, label='v_09')
            pl.legend(fontsize=20)
            pl.ylabel('Energy (MW)', fontsize=40)
            pl.xlabel('Time', fontsize=40)
            pl.title('Energy absorbed by particle at day 170 to 172',
                     fontsize=40)
            pl.show()
예제 #22
0
	def load_res(self):
		self.mat = DyMat.DyMatFile(self.fn)
		self.load_units()
예제 #23
0
def dy_mat_func_motor(file):

    #for n in f.names():
    #    print(n)

    f = dm.DyMatFile(file + ".mat")

    #Stores values from .mat file to numpy array
    time = f.abscissa('Shaft.T', valuesOnly=True)
    T1 = f.data('Shaft.T') - 273.15
    T2 = f.data('Magnet.T') - 273.15
    T3 = f.data('Tooth_outerInner.T') - 273.15
    T4 = f.data('StatorYoke.T') - 273.15
    T5 = f.data('Winding.T') - 273.15
    T6 = f.data('Housing_pin.T') - 273.15
    T7 = f.data('Housing_casing.T') - 273.15
    T8 = f.data('Gearbox.T') - 273.15

    #Rejected heat flow [W]
    Q = f.data('volume.q.Q_flow')

    #Conversion of arrays to lists
    list1 = time.tolist()
    list2 = T1.tolist()
    list3 = T2.tolist()
    list4 = T3.tolist()
    list5 = T4.tolist()
    list6 = T5.tolist()
    list7 = T6.tolist()
    list8 = T7.tolist()
    list9 = T8.tolist()

    list10 = Q.tolist()

    #Dataframes for plotting
    data1 = pd.DataFrame({
        'time': list1,
        'T$_{shaft}$': list2,
        'T$_{magnet}$': list3,
        'T$_{stator\; tooth}$': list4,
        'T$_{stator\; yoke}$': list5,
        'T$_{winding}$': list6,
        'T$_{pins}$': list7,
        'T$_{casing}$': list8,
        'T$_{gearbox}$': list9
    })

    data2 = pd.DataFrame({'time': list1, 'Q [W]': list10})

    xmin = 0
    xmax = max(list1)
    ymin1 = min(list6)
    ymax1 = max(list6)
    ymin2 = min(list10)
    ymax2 = max(list10)

    print("Max temperature for case " + file + ": " + str(round(ymax1, 2)) +
          " degC.")

    with open("Results.txt", "a") as f:
        f.write("Max temperature for case " + file + ": " +
                str(round(ymax1, 2)) + " degC.\n")


#    data1.plot(x='time')
#    plt.xlabel("Time [s]")
#    plt.ylabel("Temperature $[^{\circ}C]$")
#    plt.xlim(xmin, xmax)
#    plt.ylim(ymin1, ymax1+5)
##    plt.autoscale(tight=True)
#    plt.grid(True)
#    plt.title(file)
#    plt.savefig(file + "_Inverter_T.png")
#    plt.show()
#
#    data2.plot(x='time')
#    plt.xlabel("Time [s]")
#    plt.ylabel("Q [W]")
#    plt.xlim(xmin, xmax)
#    plt.ylim(ymin2, ymax2+5)
##    plt.autoscale(tight=True)
#    plt.grid(True)
#    plt.title(file)
#    plt.legend().remove()
#    plt.savefig(file + "_Q.png")
#    plt.show()

#    #All plots
    f, axarr = plt.subplots(2, sharex=True, figsize=(15, 10))

    axarr[0].plot(list1, list2, label='T$_{shaft}$')
    axarr[0].plot(list1, list3, label='T$_{magnet}$')
    axarr[0].plot(list1, list4, label='T$_{stator\; tooth}$')
    axarr[0].plot(list1, list5, label='T$_{stator\; yoke}$')
    axarr[0].plot(list1, list6, label='T$_{winding}$')
    axarr[0].plot(list1, list7, label='T$_{pins}$')
    axarr[0].plot(list1, list8, label='T$_{casing}$')
    axarr[0].plot(list1, list9, label='T$_{gearbox}$')
    axarr[0].set_xlabel("Time [s]", fontsize=10)
    axarr[0].set_ylabel("Temperature $[^{\circ}C]$", fontsize=10)
    axarr[0].set_xlim(xmin, xmax)
    axarr[0].set_ylim(ymin1, ymax1 + 15)
    #    axarr[0].autoscale(tight=True)
    axarr[0].grid(True)
    axarr[0].legend()
    #    plt.xlim((0,694))
    #    axarr[0].set_title(file)

    axarr[1].plot(list1, list10)
    axarr[1].set_xlabel("Time [s]", fontsize=10)
    axarr[1].set_ylabel("Q [W]", fontsize=10)
    axarr[1].set_xlim(xmin, xmax)
    axarr[1].set_ylim(ymin2, ymax2 + 5)
    #    axarr[1].autoscale(tight=True)
    axarr[1].grid(True)
    #    axarr[1, 0].set_title(file)

    plt.subplots_adjust(wspace=0.25, hspace=0.25)
    plt.suptitle(file)
    plt.savefig(file + "_complete.png", format='png')
    plt.show()
예제 #24
0
arg.add_argument('-o',
                 '--outfile',
                 nargs=1,
                 help='write exported data to this file')
arg.add_argument('-f', '--format', nargs=1, help='export data in this format')
arg.add_argument('-p',
                 '--options',
                 nargs=1,
                 help='export options specific to export format')

arg.add_argument('matfile', nargs=1, help='MAT-file')

pargs = arg.parse_args()

dm = DyMat.DyMatFile(pargs.matfile[0])

if pargs.info:
    blocks = dm.blocks()
    blocks.sort()
    for b in blocks:
        print('Block %02d:' % b)
        s = dm.mat['data_%d' % (b)].shape
        v = len(dm.names(b))
        print('  %d variables point to %d columns with %d timesteps' %
              (v, s[0] - 1, s[1]))

elif pargs.list:
    for n in dm.names():
        print(n)
예제 #25
0
                 BPM='maxBP',
                 Qlymph='Qlymph [L/day]',
                 Vint_r='Relative change to interstitial volume',
                 Vint_excess='Excess interstitial volume [L]',
                 ESP='ESP',
                 EDP='EDP',
                 comp='compensated'))

    for i in exp_range:
        filename = filePattern % (experiment_type, i)
        # filename = R"c:\home\UMICH\Valsalva\Results2\CardiovascularSystem.mat"

        try:
            print("Loading file %s..." % filename, end='')
            tic = timer.time()
            datafile = DyMat.DyMatFile(filename)
            print("Ok [%ds]. Processing..." % (timer.time() - tic), end='')
        except FileNotFoundError:
            print(" File %0d  not found !" % i)
            continue
        except:
            print(" File %0d  failed, show must go on" % i)

            # os.system("c:\\Program Files\\Dymola 2021\\bin\\dsres2dsf %s %s" % (filename, filename.replace('.mat', '.sdf'))

            continue

        time = datafile.abscissa(2)[0]
        i_dt = int(
            6 / (time[100] / 100)
        )  # index of mean interval of 6s , measured over range of 100 samples
예제 #26
0
## Reads parameters of venous terminals for reparametrization

import scipy.io as skipy
import DyMat
from matplotlib import pyplot as plt
import re
import TerminalDS

# filename = 'CardiovascularSystem_ADANExport'

steadyStateAt = 30
filename = '../CardiovascularSystem'
# mat = skipy.loadmat(filename)
d = DyMat.DyMatFile(filename)
time = d.abscissa(2)[0]

nmsList = d.names(block=2)
nmsStr = "\r".join(nmsList)
steadyStateInd = TerminalDS.findLowestIndex(steadyStateAt, time)

# lines = open('terminators_venousRed.txt', 'r').read().splitlines()
lines = open('terminators_venousRedPlus.txt', 'r').read().splitlines()
terminators_venous = TerminalDS.createTerminatorsDS(lines)

name_patt = ["Systemic1.", '']

for t in terminators_venous:
    t.C = d.data("".join([name_patt[0], t.name, '.', 'C']))[-1]
    t.RA = d.data("".join([name_patt[0], t.name, '.', 'Ra']))[-1]
    t.RV = 3.0 * d.data("".join([name_patt[0], t.name, '.', 'Rv']))[-1]
    t.I = d.data("".join([name_patt[0], t.name, '.', 'I']))[-1]
예제 #27
0
def dy_mat_func(file):

    #for n in f.names():
    #    print(n)

    f = dm.DyMatFile(file + ".mat")

    #Stores values from .mat file to numpy array
    time = f.abscissa('HC_B9.T', valuesOnly=True)
    B9_T = f.data('HC_B9.T') - 273.15
    A7_T = f.data('HC_A7.T') - 273.15
    A2_T = f.data('HC_A2.T') - 273.15
    A11_T = f.data('HC_A11.T') - 273.15
    B3_T = f.data('HC_B3.T') - 273.15

    #speed
    v = f.data('Speed.y[1]')

    #Perscribed heat flow (conversion from W to kW)
    Q = f.data('timeTable.y[1]') / 1000

    #Inlet and outlet temperature of HE or Radiator
    fi = f.data('fluid_inlet.y')
    fo = f.data('fluid_outlet.y')

    #Conversion of arrays to lists
    list1 = time.tolist()
    list2 = B9_T.tolist()
    list3 = A7_T.tolist()
    list4 = A2_T.tolist()
    list5 = A11_T.tolist()
    list6 = B3_T.tolist()

    list7 = fi.tolist()
    list8 = fo.tolist()

    list9 = v.tolist()
    list10 = Q.tolist()

    #Dataframes for plotting
    data1 = pd.DataFrame({
        'time': list1,
        'T$_{B9}$': list2,
        'T$_{A7}$': list3,
        'T$_{A2}$': list4,
        'T$_{A11}$': list5,
        'T$_{B3}$': list6
    })

    data2 = pd.DataFrame({
        'time': list1,
        'T$_{fluid\; inlet}$': list7,
        'T$_{fluid\; outlet}$': list8
    })

    data3 = pd.DataFrame({'time': list1, 'Velocity [km/h]': list9})

    data4 = pd.DataFrame({'time': list1, 'Q [kW]': list10})

    #fig, ax = plt.subplots()

    data1.plot(x='time')
    plt.xlabel("Time [s]")
    plt.ylabel("Temperature $[^{\circ}C]$")
    #plt.xlim((0,694))
    #plt.ylim((25,120))
    plt.autoscale(tight=True)
    plt.grid(True)
    plt.title(file)
    plt.savefig(file + "_Module_T.png")
    plt.show()

    data2.plot(x='time')
    plt.xlabel("Time [s]")
    plt.ylabel("Temperature $[^{\circ}C]$")
    plt.autoscale(tight=True)
    #plt.xlim((0,694))
    #plt.ylim((20,100))
    plt.grid(True)
    plt.title(file)
    plt.savefig(file + "_HE_T.png")
    plt.show()

    data3.plot(x='time')
    plt.xlabel("Time [s]")
    plt.ylabel("Velocity [km/h]")
    plt.autoscale(tight=True)
    #plt.xlim((0,694))
    #plt.ylim((0,100))
    plt.grid(True)
    plt.title(file)
    plt.legend().remove()
    plt.savefig(file + "_velocity.png")
    plt.show()

    data4.plot(x='time')
    plt.xlabel("Time [s]")
    plt.ylabel("Q [kW]")
    #plt.xlim((0,694))
    #plt.ylim((0,25))
    plt.autoscale(tight=True)
    plt.grid(True)
    plt.title(file)
    plt.legend().remove()
    plt.savefig(file + "_Q.png")
    plt.show()

    #All plots
    f, axarr = plt.subplots(2, 2, figsize=(14, 10))

    axarr[0, 0].plot(list1, list2, label='T$_{B9}$')
    axarr[0, 0].plot(list1, list3, label='T$_{A7}$')
    axarr[0, 0].plot(list1, list4, label='T$_{A2}$')
    axarr[0, 0].plot(list1, list5, label='T$_{A11}$')
    axarr[0, 0].plot(list1, list6, label='T$_{B3}$')
    axarr[0, 0].set_xlabel("Time [s]", fontsize=10)
    axarr[0, 0].set_ylabel("Temperature $[^{\circ}C]$", fontsize=10)
    axarr[0, 0].autoscale(tight=True)
    axarr[0, 0].grid(True)
    axarr[0, 0].legend()
    #axarr[0, 0].set_title(file)

    axarr[0, 1].plot(list1, list7, label='T$_{fluid\; inlet}$')
    axarr[0, 1].plot(list1, list8, label='T$_{fluid\; outlet}$')
    axarr[0, 1].set_xlabel("Time [s]", fontsize=10)
    axarr[0, 1].set_ylabel("Temperature $[^{\circ}C]$", fontsize=10)
    axarr[0, 1].autoscale(tight=True)
    axarr[0, 1].grid(True)
    axarr[0, 1].legend()
    #axarr[0, 1].set_title(file)

    axarr[1, 0].plot(list1, list9)
    axarr[1, 0].set_xlabel("Time [s]", fontsize=10)
    axarr[1, 0].set_ylabel("Velocity [km/h]", fontsize=10)
    axarr[1, 0].autoscale(tight=True)
    axarr[1, 0].grid(True)
    #axarr[1, 0].set_title(file)

    axarr[1, 1].plot(list1, list10)
    axarr[1, 1].set_xlabel("Time [s]", fontsize=10)
    axarr[1, 1].set_ylabel("Q [kW]", fontsize=10)
    axarr[1, 1].autoscale(tight=True)
    axarr[1, 1].grid(True)
    #axarr[1, 1].set_title(file)

    plt.subplots_adjust(wspace=0.25, hspace=0.25)
    plt.suptitle(file)
    plt.savefig(file + "_COMPLETE.pdf", format='pdf')
    plt.show()