Python time.append() Examples

The following are code examples for showing how to use time.append(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 6 votes vote down vote up
def initial_finall_mass_relation(self,marker='o',linestyle='--'):
		'''
			INtiial to final mass relation
		'''

		final_m=[]
                ini_m=[]
                for i in range(len(self.runs_H5_surf)):
			sefiles=se(self.runs_H5_out[i])
                        ini_m.append(sefiles.get("mini")) 
			h1=sefiles.get(int(sefiles.se.cycles[-2]),'H-1')
			mass=sefiles.get(int(sefiles.se.cycles[-2]),'mass')
			idx=-1
			for k in range(len(h1)):
				if h1[k]>0.1:
					idx=k
					break
			final_m.append(mass[idx])
		label='Z='+str(sefiles.get('zini'))
		plt.plot(ini_m,final_m,label=label,marker=marker,linestyle=linestyle)
		plt.xlabel('$M_{Initial} [M_{\odot}]$',size=23)
		plt.ylabel('$M_{Final} [M_{\odot}]$',size=23) 
Example 2
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 6 votes vote down vote up
def final_bottom_envelope_set1(self):
		'''
			For paper1 marco routine:
			 Numbers of remnant mass shell masses, exists also in mesa_set!
		'''
		inim=[]
		remnm=[]
		for i in range(len(self.runs_H5_surf)):
			m1p65_last=se(self.runs_H5_out[i])	
			mass_dummy=m1p65_last.se.get(m1p65_last.se.cycles[len(m1p65_last.se.cycles)-1],'mass')
			top_of_envelope=mass_dummy[len(mass_dummy)-1]
			h_dummy=m1p65_last.se.get(m1p65_last.se.cycles[len(m1p65_last.se.cycles)-1],'iso_massf','H-1')

			for j in range(len(mass_dummy)):
        			if h_dummy[j] > 0.05:
                			bottom_of_envelope = mass_dummy[j]
                			break
			inim.append(m1p65_last.get("mini"))
			remnm.append(bottom_of_envelope)
		print "M_initial | M_remn/bottom of envelope"
		for i in range(len(inim)):
			print inim[i],"|",remnm[i] 
Example 3
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 6 votes vote down vote up
def set_burnstages_upgrade_massive(self):
		'''
			Outputs burnign stages as done in burningstages_upgrade (nugridse)
		'''
		burn_info=[]
		burn_mini=[]
                for i in range(len(self.runs_H5_surf)):
                        sefiles=se(self.runs_H5_out[i])
			burn_info.append(sefiles.burnstage_upgrade())
                        mini=sefiles.get('mini')
                        #zini=sefiles.get('zini')
			burn_mini.append(mini)
		for i in range(len(self.runs_H5_surf)):
			print 'Following returned for each initial mass'
			print '[burn_cycles,burn_ages, burn_abun, burn_type,burn_lifetime]'
			print '----Mini: ',burn_mini[i],'------'
			print burn_info[i] 
Example 4
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 6 votes vote down vote up
def read_yield_sn1a_tables(self,sn1a_table,isotopes):
		f1=open(sn1a_table)
		lines=f1.readlines()
		f1.close()
		iso_1a=[]
		yield_1a=[]
		for line in lines:
			#for header
			if '#' in line:
				continue
			iso_1a.append(line.split()[0])
			yield_1a.append(float(line.split()[1]))				


		yields=[]
		#fill up the missing isotope yields with zero
		for iso in isotopes:
			if iso in iso_1a:
				idx=iso_1a.index(iso)
				yields.append(yield_1a[idx])
			else:
				yields.append(0.)		
		return yields 
Example 5
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 6 votes vote down vote up
def read_yield_tables(self,table,Z):
	
		'''
			Reads out yield tables in table format
		'''
	
		print 'reading yield tables'
		import read_yield_tables as y
		y1=y.yields(table)
		masses=[]
		for header in y1.table_header:
			if str(Z) in header:
				mass=header.split(',')[0].split('=')[1]
				masses.append(float(mass))
		#print y1.get(1.65,0.01,'age')	
		#print 'Available masses: ',masses	

		return y1,masses 
Example 6
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 6 votes vote down vote up
def plot_surf_isotope(self,isotope='C-12'):
               
                '''
                        Plots surface evolution of certain isotope

                '''

                for i in range(len(self.runs_H5_surf)):
                        sefiles=se(self.runs_H5_surf[i])
                        y=[]
                        mass=sefiles.get("mini")
                        z=sefiles.get("zini")
                        legend=str(mass)+"M$_{\odot}$ Z= "+str(z)
                        for j in arange(0,len(sefiles.se.cycles)-1000,500):
                                y.append(sefiles.get(j,"iso_massf",isotope))
                        plt.plot(arange(0,len(sefiles.se.cycles)-1000,500),y,label=legend)
                        plt.xlabel('Cycles')
                        plt.ylabel('X$_{'+isotope+'}$') 
Example 7
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 6 votes vote down vote up
def find_most_abundant(self,coords=[],cycle=[]):
		
		minis=[]
		isotopes=[]
		abus=[]
                for i in range(len(self.runs_H5_out)):
                        sefiles=se(self.runs_H5_out[i])
                        mass_ini=sefiles.get("mini")
                        z=sefiles.get("zini")
			if cycle[i]==-1:
				cyc=sefiles.se.cycles[-1]
			else:
				cyc=cycle[i]
			coord=coords[i]
			mass=sefiles.get(cyc,'mass')
			mass_idx=min(range(len(mass)), key=lambda i: abs(mass[i]-coord))
			abu=sefiles.get(cyc,'iso_massf')[mass_idx]
			idx=list(abu).index(max(abu))
			print 'at mass coord',coord,': ',sefiles.se.isotopes[idx],'with ',max(abu)
			minis.append(mass_ini)
			isotopes.append(sefiles.se.isotopes[idx])
			abus.append(max(abu))

		for k in range(len(minis)):
			print 'M=',minis[k],'Z=',z,'at mass coord',coords[k],': ',isotopes[k],'with ',abus[k] 
Example 8
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 6 votes vote down vote up
def lifetime(self,label=""):
		'''
			Calculate stellar lifetime till first TP 
			dependent of initial mass
		'''
                plt.rcParams.update({'font.size': 20})
                plt.rc('xtick', labelsize=20)
                plt.rc('ytick', labelsize=20)
                t0_model=self.set_find_first_TP()
                m=self.run_historydata
                i=0
		age=[]
		mass=[]
                for case in m:
			##lifetime till first TP
			age.append(np.log10(case.get("star_age")[t0_model[i]]))
			mass.append(case.get("star_mass")[0])
			i+=1
		plt.plot(mass,age,"*",markersize=10,linestyle="-",label=label)
		plt.xlabel('star mass $[M_{\odot}]$',fontsize=20)
		plt.ylabel('Logarithmic stellar lifetime',fontsize=20) 
Example 9
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 6 votes vote down vote up
def TPAGB_core_growth(self,fig, label="",color='k',marker_type='<',linestyle='-'):
		'''
			Creates diagram of the core growth during AGB phase.
			Uses function mult_DUP to identify first TP cycle
			and subtract from last cycle of simulation.
			(Tested with 2 cases)
		'''
                m=self.run_historydata
                i=0
                t0_model=self.set_find_first_TP()
               	core_growth=[]
		ini_m=[]
		plt.figure(fig)
		for case in m:
			mH_first_TP=case.get('h1_boundary_mass')[t0_model[i]]
			mH_last_TP=case.get('h1_boundary_mass')[-1]                
			core_growth.append(mH_last_TP-mH_first_TP)
			ini_m.append(case.header_attr["initial_mass"])
			i += 1
                plt.plot(ini_m,core_growth,marker=marker_type,color=color,markersize=10,mfc=color,linewidth=2,linestyle=linestyle,label=label)
		xlabel('Initial star  mass $[M_{\odot}]$',fontsize=18)
                ylabel('Core growth $[M_{\odot}]$',fontsize=18)
                legend() 
Example 10
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 6 votes vote down vote up
def get_stable(specie_list,get_elements=True):

	'''
		Input isotope list or element list, get stable list back
		if get_elements=True return elements of all stables in isotope_list

	'''

	stable_list=[]
	for specie in specie_list:
		if is_stable(specie) == 't':
			if get_elements==True and  len(specie.split("-"))==2:
				if specie.split("-")[0] not in stable_list:
					stable_list.append(specie.split("-")[0])	
			else:
				stable_list.append(specie)
	
	return stable_list 
Example 11
Project: picasso   Author: jungmannlab   File: simulate.py    (license) View Source Project 6 votes vote down vote up
def exportTable(self):

        table = dict()
        tablecontent = []
        print(self.table.rowCount())
        tablecontent.append(['FileName', 'Imager concentration[nM]', 'Integration time [ms]', 'Laserpower', 'Mean [Photons]', 'Std [Photons]'])
        for row in range(self.table.rowCount()):
            rowdata = []
            for column in range(self.table.columnCount()):
                item = self.table.item(row, column)
                if item is not None:
                    rowdata.append(item.text())
                else:
                    rowdata.append('')
            tablecontent.append(rowdata)

        table[0] = tablecontent
        print(tablecontent)
        print(table)
        path = QtGui.QFileDialog.getSaveFileName(self,  'Export calibration table to.',  filter='*.csv')
        if path:
            self.savePlate(path, table) 
Example 12
Project: picasso   Author: jungmannlab   File: simulate.py    (license) View Source Project 6 votes vote down vote up
def evalTable(self):
        conc = []
        time = []
        las = []
        bg = []
        bgstd = []
        for i in range(0, self.tifCounter):
            conc.append(float(self.table.item(i, 1).text()))
            time.append(float(self.table.item(i, 2).text()))
            las.append(float(self.table.item(i, 3).text()))
            bg.append(float(self.table.item(i, 4).text()))
            bgstd.append(float(self.table.item(i, 5).text()))

        # self.exportTable()
        return bg, bgstd, las, time, conc

    # static method to create the dialog and return (date, time, accepted) 
Example 13
Project: HaD-to-Py   Author: latomkovic   File: storeDSSdata.py    (license) View Source Project 6 votes vote down vote up
def createTSrecord(dss_filename, pathname, start_time, values, comp_step, data_units ):
	
	
	start = HecTime()
	tsc = TimeSeriesContainer()
	tsc.fullName = pathname
	tsc.interval = comp_step
	start.set(start_time)
	times =  []
	for value in values:
		times.append(start.value())
		start.add(tsc.interval)
	tsc.values = values
	tsc.times = times
	tsc.startTime = times[0]
	tsc.endTime = times[-1]
	tsc.numberValues = len(values)
	tsc.units = data_units	
	tsc.type = "INST-VAL"
	dss_file = HecDss.open(dss_filename)
	dss_file.put(tsc) 
	dss_file.done() 
Example 14
Project: fscan   Author: danielmoraes   File: misc.py    (license) View Source Project 5 votes vote down vote up
def format_time(s):
    ftime = str(datetime.timedelta(seconds=s)).split(':')
    if len(ftime[0].split('day')) > 1:
        ftime[0] = int(ftime[0].split(' day')[0]) * 24 +\
            int(ftime[0].split(', ')[1])
    d = [float(i) for i in ftime]
    time = []
    if d[0] > 0:
        time.append('%dh' % (d[0]))
    if d[1] > 0:
        time.append('%dm' % (d[1]))
    if d[2] > 0:
        time.append('%0.3fs' % (d[2]))
    return ' '.join(time) 
Example 15
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 5 votes vote down vote up
def set_get_abu_distr_decay(self,cycles=20*[-1],mass_range=20*[[0,0]],ylim=20*[[0,0]],isotopes=['all']):
                import nugridse as mp
                import utils as u
                print self.runs_H5_restart
                massfrac_all=[]
                iso_all=[]
                for i in range(len(self.runs_H5_restart)):		
                        sefiles=mp.se(self.runs_H5_restart[i])
                        cycle=cycles[i]
                        if cycle==-1:
                                cycle=int(sefiles.se.cycles[-1])
                        if mass_range[i][0] ==0 and mass_range[i][1]==0:
                                mass_range[i][1]=sefiles.get(cycle,'mass')[-1]
			print 'use cycle',cycle
			sefiles.average_iso_abund_marco(mass_range=mass_range[i],cycle=cycle,stable=True,i_decay=2)			
			massfrac1=mp.average_mass_frac_decay
			other_name_scheme=u.back_ind.keys()
			isos=[]
			massfrac=[]
			print len(massfrac),len(other_name_scheme)
			for kk in range(len(other_name_scheme)):
				list1=re.split('(\d+)',other_name_scheme[kk])
				newname=list1[0].capitalize().strip()+'-'+list1[1].strip()
				#print other_name_scheme[kk],newname,massfrac[kk]
				isos.append(newname)
				massfrac.append(massfrac1[u.back_ind[other_name_scheme[kk]]])
			massfrac_all.append(massfrac)
			iso_all.append(isos)
		return iso_all,massfrac_all 
Example 16
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 5 votes vote down vote up
def set_cores_massive(self,filename='core_masses_massive.txt'):

		'''
			Uesse function cores in nugridse.py
		'''
		
		core_info=[]
		minis=[]
                for i in range(len(self.runs_H5_surf)):
                        sefiles=se(self.runs_H5_out[i])
			mini=sefiles.get('mini')
			minis.append(mini)
			incycle=int(sefiles.se.cycles[-1])
			core_info.append(sefiles.cores(incycle=incycle))
		print_info=''
                for i in range(len(self.runs_H5_surf)):
			if i ==0:
				print 'Following returned for each initial mass'
				print core_info[i][1]
                        #print '----Mini: ',minis[i],'------'
			print_info+=(str(minis[i])+' & ')
			info=core_info[i][0]
			for k in range(len(info)):
				print_info+=('{:.3E}'.format(float(core_info[i][0][k]))+' & ')
			print_info=(print_info+'\n')
			#print core_info[i][2]
		f1=open(filename,'a')
		f1.write(print_info)
		f1.close() 
Example 17
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 5 votes vote down vote up
def set_plot_CC_T_rho_max(self,linestyle=[],burn_limit=0.997,color=['r'],marker=['o'],markevery=500): 
		'''
			Plots 
			end_model - array, control how far in models a run is plottet, if -1 till end
			symbs_1  - set symbols of runs
		'''
		if len(linestyle)==0:
			linestyle=200*['-']
		plt.figure('CC evol')
                for i in range(len(self.runs_H5_surf)):
                        sefiles=se(self.runs_H5_out[i])
			t1_model=-1
			sefiles.get('temperature')
			sefiles.get('density')
                        mini=sefiles.get('mini')
			zini=sefiles.get('zini')
                        model=sefiles.se.cycles
                        model_list=[]
                        for k in range(0,len(model),1):
                                model_list.append(model[k])
                        rho1=sefiles.get(model_list,'rho')   #[:(t1_model-t0_model)]
                        T1=sefiles.get(model_list,'temperature')#[:(t1_model-t0_model)]
                        rho=[]
                        T=[]
			T_unit=sefiles.get('temperature_unit')
			labeldone=False
                        for k in range(len(model_list)):
				t9=np.array(T1[k])*T_unit/1e9
				T.append(max(t9))
				rho.append(max(rho1[k]))
			label=str(mini)+'$M_{\odot}$, Z='+str(zini)
			plt.plot(T,rho,label=label,color=color[i],marker=marker[i],markevery=markevery)					
		plt.xlabel('$T_{9,max} (GK)$')
		plt.ylabel(r'$\rho [cm^{-3}]$')
		plt.yscale('log')
		plt.xscale('log')
		plt.legend(loc=2) 
Example 18
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 5 votes vote down vote up
def chem_plot(self,xaxis,yaxis):

		'''
			Plotting tool for the chem chemical evolution function
		'''	
	
		#Assume isotope input
		if '-' in xaxis:
			yields=self.gce_yields_t
			iso_idx=self.gce_isotopes.index(xaxis)
			x=[]
			for k in range(len(yields)):
				x.append(yields[k][iso_idx])
		if '-' in yaxis:
                        yields=self.gce_yields_t
                        iso_idx=self.gce_isotopes.index(yaxis)
                        y=[]
                        for k in range(len(yields)):
                                y.append(yields[k][iso_idx])
			
		if 'time' in xaxis:
			times=self.gce_t_contri
			x=times
		plt.plot(x,y)
		plt.xlabel(xaxis)
		plt.ylabel(yaxis) 
Example 19
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 5 votes vote down vote up
def write_latex_table_set1(self,isotopes_for_table,data,headers=['this is a test','to write strings in the first col'],file_name_table_species_wind = 'isotopic_table_set1.2_prodfac.txt',case_label_and_first_column = ['specie','1.65 Msun','2 Msun','3 Msun','5 Msun','15 Msun','20 Msun','25 Msun',]):

		'''
			Table write method from Paper1 scripts (from Marco)

			isotopes_for_table - isotopes for table (first column), preferable stable
			data - 2d array e.g. [tab_w_1p65,tab_w_2,tab_w_3,tab_w_5,tab_w_15,tab_w_20,tab_w_25]


		'''


		# headers and format
		form_str='%7.3E'
		sep_string=' & '

		all_data=[]
		all_data.append(isotopes_for_table)
		for i in range(len(data)):
        		datal=list(form_str%data[i][j] for j in range(len(data[i])))
        		all_data.append(datal)


		### attempt to add the trailing '\\' to a latex table
		final_col=len(isotopes_for_table)*[r'\\ ']
		case_label_and_first_column.append(r'\\ ')
		all_data.append(final_col)
		att.write(file_name_table_species_wind,headers,case_label_and_first_column,all_data,sep=sep_string) 
Example 20
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 5 votes vote down vote up
def plot_final_surf_abu(self,yaxis='[Ba/Eu]',color='r',marker='o',linestyle='-',iniabupath='/astro/critter/critter/PPN/forum.astro.keele.ac.uk/frames/mppnp/USEEPP/iniab2.0E-02GN93.ppn'):


		elem1=yaxis.split('/')[0].split('[')[1]
		elem2=yaxis.split('/')[1].split(']')[0]

		elem1_ini=get_ini_elem_abu(element=elem1,iniabupath=iniabupath)
		elem2_ini=get_ini_elem_abu(element=elem2,iniabupath=iniabupath)

		spec_values=[]
		masses=[]
		for i in range(len(self.runs_H5_surf)):
			
			sefiles=se(self.runs_H5_surf[i])
			abu=[]
			abu1=self.get_elem_abu(cycles=-1,element=elem1,sefiles=sefiles)[0]	
			abu2=self.get_elem_abu(cycles=-1,element=elem2,sefiles=sefiles)[0]
			spec_values.append(np.log10(abu1/elem1_ini * elem2_ini/abu2))
                        print abu1,abu2
                        print elem1_ini,elem2_ini

			mass=sefiles.get("mini")
                        z=sefiles.get("zini")
			masses.append(mass)
                        legend=str(mass)+"M$_{\odot}$ Z= "+str(z)
		print spec_values
		print 'for ',elem1,elem2
		plt.figure(elem1+'_'+elem2)#+', Z='+str(z))
		plt.plot(masses,spec_values,marker=marker,color=color,linestyle=linestyle,label='Z='+str(z))
		plt.ylabel(yaxis)
		plt.xlabel('M/M$_{\odot}$')
		plt.legend(loc=1) 
Example 21
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 5 votes vote down vote up
def pocket_composition(self,mp,sefiles,cycle,massbot,masstop,isotopes,label,legend,color,title):  ###hdf5out
        	'''

		mass_range    - required to plot data in a certain mass range. Needed for read_iso_abund_marco
        	cycle         - which cycle from the h5 file?. Needed for read_iso_abund_marco
        	stable        - logic if want to plot only stable or not.  
        	i_decay       - if = 1 I plot not decayed, if = 2 I plot decayed. Make sense only if stable is true.


		'''


		mass_range=[massbot,masstop]
		sefiles.average_iso_abund_marco(mass_range,cycle,stable=False,i_decay=1)
		mass=[]
		plotiso=[]
		startyields=[]
		plotiso_massfrac=[]
		for i in range(len(isotopes)):
			startyields.append(sefiles.get(sefiles.se.cycles[0],isotopes[i])[0])
		for j in range(len(sefiles.se.isotopes)):
			if sefiles.se.isotopes[j] in isotopes:
				plotiso.append(mp.average_mass_frac[j])
				mass.append(sefiles.se.A[j])
		for i in range(len(isotopes)):
			plotiso_massfrac.append(plotiso[i]/startyields[i])
		plt.plot(mass,plotiso_massfrac,marker='*',markersize=8,mfc=color,linestyle='None',label=legend)
		#plt.plot(mass,plotiso_massfrac,marker='*')
		if label ==True:
			for j in range(len(isotopes)):
				plt.annotate(isotopes[j], xytext = (0, 10),textcoords = 'offset points' ,xy=(mass[j], plotiso_massfrac[j]))
		mass=np.array(mass)
		plt.xlim(mass.min()-4,mass.max()+4)
		plt.legend()
		plt.title(title)
		plt.xlabel("mass number")
		plt.ylabel("Isotopic production factors") 
Example 22
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 5 votes vote down vote up
def set_plot_core_lum_relation(self,symb='o',linestyle='--',sparsity=500,label=''):

		'''
			Plots the core luminosity relation. Mean core mass
			from first TP till last TP in model steps of sparsity
			Mean lum derived first TP to last TP in model steps of sparsity
			time-weighted averages
		'''


                m=self.run_historydata
		core_mean=[]
		lum=[]
                for case in m:
	        	peak_lum_model,h1_mass_min_DUP_model=case.find_TP_attributes(t0_model=case.find_first_TP(),fig=3, color='r', marker_type='o')
			modelrange=range(int(peak_lum_model[0]),int(peak_lum_model[-1]+sparsity),int(sparsity))
			core_mean1=[]
			lum1=[]
			#weight for mean value
			ages=case.get('star_age')
			weight_sum=0.
			for h in range(len(modelrange)):
				mod=modelrange[h]
				if h==0:
					weight=(ages[modelrange[h+1]] - ages[mod])/2.
				elif h == len(modelrange)-1:
					weight=(ages[mod]-ages[modelrange[h-1]])/2.
				else:
					weight=(ages[modelrange[h+1]] - ages[mod])/2. + (ages[mod]-ages[modelrange[h-1]])/2.
				weight_sum+=weight

				core_mean1.append(case.get('h1_boundary_mass')[mod]*weight)
				lum1.append(case.get('log_L')[mod]*weight)
			
			core_mean.append(sum(core_mean1)/weight_sum)
			lum.append(sum(lum1)/weight_sum)
			
		plt.plot(core_mean,lum,marker=symb,linestyle=linestyle,label=label)
		print core_mean,lum
		plt.xlabel("M/M$_{\odot}$")
		plt.ylabel('log L/L$_{\odot}$') 
Example 23
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 5 votes vote down vote up
def set_find_first_TP_age(self,dirs=[]):

		'''
			Time at first TP
		'''
	        m=self.run_historydata
		firstTPs=[]
		ages=[]
		for case in m:
			firstTPs.append(case.find_first_TP())
			age=case.get('star_age')[int(case.find_first_TP())]
			ages.append(age)
		return ages 
Example 24
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 5 votes vote down vote up
def set_find_first_TP(self,dirs=[]):

		'''
			Find first TP of all runs and return array
		'''


                historydata=[]
                if (len(dirs)) == 0:
                        dirs=self.run_LOGS
                        historydata=self.run_historydata
                else:
                        for i in range(len(dirs)):
                                historydata.append(history_data(dirs[i]+"/LOGS"))
		t0_models=[]
		for j in range(len(dirs)):
			h1_boundary_mass  = historydata[j].get('h1_boundary_mass')
                	he4_boundary_mass = historydata[j].get('he4_boundary_mass')
                	star_mass         = historydata[j].get('star_mass')
                	#mx1_bot           = historyda.get('mx1_bot')*star_mass
                	#mx1_top           = historydata.get('mx1_top')*star_mass
                	mx2_bot           = historydata[j].get('mx2_bot')*star_mass
                	#mx2_top           = historydata.get('mx2_top')*star_mass
			he_lumi		  = historydata[j].get('log_LHe')
			h_lumi 		  = historydata[j].get('log_LH')
			#model_number            = historydata[j].get('model_number')
			lum_array=[]
			activate=False
			models=[]
			for i in range(len(h1_boundary_mass)):
				if (h1_boundary_mass[i]-he4_boundary_mass[i] <0.1) and (he4_boundary_mass[i]>0.2):
					if (mx2_bot[i]>he4_boundary_mass[i]) and (he_lumi[i]>h_lumi[i]):
						activate=True
						lum_array.append(he_lumi[i])
						models.append(i)
					if (activate == True) and (he_lumi[i]<h_lumi[i]):
						break	
			t0_models.append(models[np.argmax(lum_array)]  )
		return t0_models 
Example 25
Project: leetcode   Author: thomasyimgit   File: execution.py    (license) View Source Project 5 votes vote down vote up
def _format_time(timespan, precision=3):
    """Formats the timespan in a human readable form"""

    if timespan >= 60.0:
        # we have more than a minute, format that in a human readable form
        # Idea from http://snipplr.com/view/5713/
        parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
        time = []
        leftover = timespan
        for suffix, length in parts:
            value = int(leftover / length)
            if value > 0:
                leftover = leftover % length
                time.append(u'%s%s' % (str(value), suffix))
            if leftover < 1:
                break
        return " ".join(time)

    
    # Unfortunately the unicode 'micro' symbol can cause problems in
    # certain terminals.  
    # See bug: https://bugs.launchpad.net/ipython/+bug/348466
    # Try to prevent crashes by being more secure than it needs to
    # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
    units = [u"s", u"ms",u'us',"ns"] # the save value   
    if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
        try:
            u'\xb5'.encode(sys.stdout.encoding)
            units = [u"s", u"ms",u'\xb5s',"ns"]
        except:
            pass
    scaling = [1, 1e3, 1e6, 1e9]
        
    if timespan > 0.0:
        order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
    else:
        order = 3
    return u"%.*g %s" % (precision, timespan * scaling[order], units[order]) 
Example 26
Project: picasso   Author: jungmannlab   File: simulate.py    (license) View Source Project 5 votes vote down vote up
def readStructure(self):
        structurexxtxt = _np.asarray((self.structurexxEdit.text()).split(","))
        structureyytxt = _np.asarray((self.structureyyEdit.text()).split(","))
        structureextxt = _np.asarray((self.structureexEdit.text()).split(","))
        structure3dtxt = _np.asarray((self.structure3DEdit.text()).split(","))

        structurexx = []
        structureyy = []
        structureex = []
        structure3d = []

        for element in structurexxtxt:
            try:
                structurexx.append(float(element))
            except ValueError:
                pass
        for element in structureyytxt:
            try:
                structureyy.append(float(element))
            except ValueError:
                pass
        for element in structureextxt:
            try:
                structureex.append(int(element))
            except ValueError:
                pass

        for element in structure3dtxt:
            try:
                structure3d.append(float(element))
            except ValueError:
                pass

        minlen = min(len(structureex), len(structurexx), len(structureyy), len(structure3d))

        structurexx = structurexx[0:minlen]
        structureyy = structureyy[0:minlen]
        structureex = structureex[0:minlen]
        structure3d = structure3d[0:minlen]

        return structurexx, structureyy, structureex, structure3d 
Example 27
Project: picasso   Author: jungmannlab   File: simulate.py    (license) View Source Project 5 votes vote down vote up
def plotStructure(self):

        structurexx, structureyy, structureex, structure3d = self.readStructure()
        noexchangecolors = len(set(structureex))
        exchangecolors = list(set(structureex))
        #self.figure2.suptitle('Structure [nm]')
        ax1 = self.figure2.add_subplot(111)
        ax1.cla()
        ax1.hold(True)
        ax1.axis('equal')

        for i in range(0, noexchangecolors):
            plotxx = []
            plotyy = []
            for j in range(0, len(structureex)):
                if structureex[j] == exchangecolors[i]:
                    plotxx.append(structurexx[j])
                    plotyy.append(structureyy[j])
            ax1.plot(plotxx, plotyy, 'o')

        distx = round(1 / 10 * (max(structurexx) - min(structurexx)))
        disty = round(1 / 10 * (max(structureyy) - min(structureyy)))

        ax1.axes.set_xlim((min(structurexx) - distx, max(structurexx) + distx))
        ax1.axes.set_ylim((min(structureyy) - disty, max(structureyy) + disty))
        self.canvas2.draw()

        exchangecolorsList = ','.join(map(str, exchangecolors))
        # UPDATE THE EXCHANGE COLORS IN BUTTON TO BE simulated
        self.exchangeroundsEdit.setText(str(exchangecolorsList)) 
Example 28
Project: Repobot   Author: Desgard   File: execution.py    (license) View Source Project 5 votes vote down vote up
def _format_time(timespan, precision=3):
    """Formats the timespan in a human readable form"""
    import math
    
    if timespan >= 60.0:
        # we have more than a minute, format that in a human readable form
        # Idea from http://snipplr.com/view/5713/
        parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
        time = []
        leftover = timespan
        for suffix, length in parts:
            value = int(leftover / length)
            if value > 0:
                leftover = leftover % length
                time.append(u'%s%s' % (str(value), suffix))
            if leftover < 1:
                break
        return " ".join(time)

    
    # Unfortunately the unicode 'micro' symbol can cause problems in
    # certain terminals.  
    # See bug: https://bugs.launchpad.net/ipython/+bug/348466
    # Try to prevent crashes by being more secure than it needs to
    # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
    units = [u"s", u"ms",u'us',"ns"] # the save value   
    if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
        try:
            u'\xb5'.encode(sys.stdout.encoding)
            units = [u"s", u"ms",u'\xb5s',"ns"]
        except:
            pass
    scaling = [1, 1e3, 1e6, 1e9]
        
    if timespan > 0.0:
        order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
    else:
        order = 3
    return u"%.*g %s" % (precision, timespan * scaling[order], units[order]) 
Example 29
Project: HaD-to-Py   Author: latomkovic   File: getDSSdata.py    (license) View Source Project 5 votes vote down vote up
def get_dss_filename(i):
	dss_ext = False
	filename_list = []
	if arg_list[i][-3:].lower() == 'dss':
		filename = arg_list[i]
		filename = ''.join(filename)
		dss_ext = True
		i+=1
	while dss_ext == False:
		filename_list.append(arg_list[i])
		filename = ' '.join(filename_list)
		if arg_list[i][-3:].lower() == 'dss':
			dss_ext = True
		i+=1
	return filename, i 
Example 30
Project: HaD-to-Py   Author: latomkovic   File: getDSSdata.py    (license) View Source Project 5 votes vote down vote up
def get_txt_filename(i):
	txt_ext = False
	filename_list = []
	if arg_list[i][-3:].lower() == 'txt':
		filename = arg_list[i]
		filename = ''.join(filename)
		txt_ext = True
		i+=1
	while txt_ext == False:
		filename_list.append(arg_list[i])
		filename = ' '.join(filename_list)
		if arg_list[i][-3:].lower() == 'txt':
			txt_ext = True
		i+=1
	return filename, i 
Example 31
Project: HaD-to-Py   Author: latomkovic   File: getDSSdata.py    (license) View Source Project 5 votes vote down vote up
def get_path_from_sys(i):
	slash = 0
	path_list = []
	while (slash < 7):
		path_list.append(arg_list[i])
		path = ''.join(path_list)
		if path[-1:] != '/':
			path_list.append(' ')
		slash = path.count("/")
		i+=1
	return path, i 
Example 32
Project: HaD-to-Py   Author: latomkovic   File: getDSSdata.py    (license) View Source Project 5 votes vote down vote up
def get_datetime_from_sys(i):
	time = []
	time.append(arg_list[i])
	time.append(' ')
	time.append(arg_list[i+1])
	datetime = ''.join(time)
	i +=2
	return datetime,i

# Initialize argument list from system command input 
Example 33
Project: HaD-to-Py   Author: latomkovic   File: storeDSSdata.py    (license) View Source Project 5 votes vote down vote up
def get_dss_filename(i):
	dss_ext = False
	filename_list = []
	if arg_list[i][-3:].lower() == 'dss':
		filename = arg_list[i]
		filename = ''.join(filename)
		dss_ext = True
		i+=1
	while dss_ext == False:
		filename_list.append(arg_list[i])
		filename = ' '.join(filename_list)
		if arg_list[i][-3:].lower() == 'dss':
			dss_ext = True
		i+=1
	return filename, i 
Example 34
Project: HaD-to-Py   Author: latomkovic   File: storeDSSdata.py    (license) View Source Project 5 votes vote down vote up
def get_path_from_sys(i):
	slash = 0
	path_list = []
	while (slash < 7):
		path_list.append(arg_list[i])
		path = ''.join(path_list)
		if path[-1:] != '/':
			path_list.append(' ')
		slash = path.count("/")
		i+=1
	return path, i 
Example 35
Project: HaD-to-Py   Author: latomkovic   File: storeDSSdata.py    (license) View Source Project 5 votes vote down vote up
def get_datetime_from_sys(i):
	time = []
	time.append(arg_list[i])
	time.append(' ')
	time.append(arg_list[i+1])
	datetime = ''.join(time)
	i +=2
	return datetime,i 
Example 36
Project: HaD-to-Py   Author: latomkovic   File: storeDSSdata.py    (license) View Source Project 5 votes vote down vote up
def get_data_list(i):
	data_count = int(arg_list[i])
	i+=1
	count = 0
	data_list = []
	while count < data_count:
		data_list.append(float(arg_list[i]))
		count+=1
		i+=1
	return data_list
	
# Initialize argument list from system command input 
Example 37
Project: gitsome   Author: donnemartin   File: timings.py    (license) View Source Project 5 votes vote down vote up
def format_time(timespan, precision=3):
    """Formats the timespan in a human readable form"""
    if timespan >= 60.0:
        # we have more than a minute, format that in a human readable form
        parts = [("d", 60 * 60 * 24), ("h", 60 * 60), ("min", 60), ("s", 1)]
        time = []
        leftover = timespan
        for suffix, length in parts:
            value = int(leftover / length)
            if value > 0:
                leftover = leftover % length
                time.append('{0}{1}'.format(str(value), suffix))
            if leftover < 1:
                break
        return " ".join(time)
    # Unfortunately the unicode 'micro' symbol can cause problems in
    # certain terminals.
    # See bug: https://bugs.launchpad.net/ipython/+bug/348466
    # Try to prevent crashes by being more secure than it needs to
    # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
    units = ["s", "ms", 'us', "ns"]  # the save value
    if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
        try:
            '\xb5'.encode(sys.stdout.encoding)
            units = ["s", "ms", '\xb5s', "ns"]
        except Exception:
            pass
    scaling = [1, 1e3, 1e6, 1e9]

    if timespan > 0.0:
        order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
    else:
        order = 3
    return "{1:.{0}g} {2}".format(precision, timespan * scaling[order],
                                  units[order]) 
Example 38
Project: blender   Author: gastrodia   File: execution.py    (license) View Source Project 5 votes vote down vote up
def _format_time(timespan, precision=3):
    """Formats the timespan in a human readable form"""
    import math
    
    if timespan >= 60.0:
        # we have more than a minute, format that in a human readable form
        # Idea from http://snipplr.com/view/5713/
        parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
        time = []
        leftover = timespan
        for suffix, length in parts:
            value = int(leftover / length)
            if value > 0:
                leftover = leftover % length
                time.append(u'%s%s' % (str(value), suffix))
            if leftover < 1:
                break
        return " ".join(time)

    
    # Unfortunately the unicode 'micro' symbol can cause problems in
    # certain terminals.  
    # See bug: https://bugs.launchpad.net/ipython/+bug/348466
    # Try to prevent crashes by being more secure than it needs to
    # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
    units = [u"s", u"ms",u'us',"ns"] # the save value   
    if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
        try:
            u'\xb5'.encode(sys.stdout.encoding)
            units = [u"s", u"ms",u'\xb5s',"ns"]
        except:
            pass
    scaling = [1, 1e3, 1e6, 1e9]
        
    if timespan > 0.0:
        order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
    else:
        order = 3
    return u"%.*g %s" % (precision, timespan * scaling[order], units[order]) 
Example 39
Project: yatta_reader   Author: sound88   File: execution.py    (license) View Source Project 5 votes vote down vote up
def _format_time(timespan, precision=3):
    """Formats the timespan in a human readable form"""

    if timespan >= 60.0:
        # we have more than a minute, format that in a human readable form
        # Idea from http://snipplr.com/view/5713/
        parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
        time = []
        leftover = timespan
        for suffix, length in parts:
            value = int(leftover / length)
            if value > 0:
                leftover = leftover % length
                time.append(u'%s%s' % (str(value), suffix))
            if leftover < 1:
                break
        return " ".join(time)

    
    # Unfortunately the unicode 'micro' symbol can cause problems in
    # certain terminals.  
    # See bug: https://bugs.launchpad.net/ipython/+bug/348466
    # Try to prevent crashes by being more secure than it needs to
    # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
    units = [u"s", u"ms",u'us',"ns"] # the save value   
    if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
        try:
            u'\xb5'.encode(sys.stdout.encoding)
            units = [u"s", u"ms",u'\xb5s',"ns"]
        except:
            pass
    scaling = [1, 1e3, 1e6, 1e9]
        
    if timespan > 0.0:
        order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
    else:
        order = 3
    return u"%.*g %s" % (precision, timespan * scaling[order], units[order]) 
Example 40
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 4 votes vote down vote up
def remnant_lifetime_agb(self):
                '''
                        For paper1 extension:
			bottom_envelope
                         Numbers of remnant mass shell masses, exists also in mesa_set + star age!
                '''
                inim=[]
                remnm=[]
		time11=[]
		tottime=[]
		c_core=[]
		o_core=[]
		small_co_core=[]
		c_core_center=[]	
                for i in range(len(self.runs_H5_surf)):
                        m1p65_last=se(self.runs_H5_out[i])
                        mass_dummy=m1p65_last.se.get(m1p65_last.se.cycles[len(m1p65_last.se.cycles)-2],'mass')
                        top_of_envelope=mass_dummy[len(mass_dummy)-1]
                        h_dummy=m1p65_last.se.get(m1p65_last.se.cycles[len(m1p65_last.se.cycles)-2],'iso_massf','H-1')
			c_dummy=m1p65_last.se.get(m1p65_last.se.cycles[len(m1p65_last.se.cycles)-2],'iso_massf','C-12')
                        o_dummy=m1p65_last.se.get(m1p65_last.se.cycles[len(m1p65_last.se.cycles)-2],'iso_massf','O-16')
			for j in range(len(mass_dummy)):
                                if h_dummy[j] > 1e-1:
                                        bottom_of_envelope = mass_dummy[j]
                                        break
                        inim.append(m1p65_last.get("mini"))
                        remnm.append(bottom_of_envelope)

			###Calculate the lifetime (MS)
                        sefiles=m1p65_last
                        cycs=[]
                        for k in range(5,len(sefiles.se.cycles),5):
                                cycs.append(int(sefiles.se.cycles[k]))
                        w=0
                        for cyc in cycs:
                                c12_center=sefiles.get(cyc,'C-12')[0]
                                #c12_center=c12[w][0]
                                w+=1
                                if c12_center>1e-1:
                                        time1=(sefiles.get(cyc,'age')*sefiles.get('age_unit'))/31557600.
                                        time11.append(time1)
                                        break
			tottime.append(sefiles.get(int(sefiles.se.cycles[-1]),'age')/31557600.)



                print "M_initial | M_remn/bottom of envelope | total lifetime"
                for i in range(len(inim)):
                        print inim[i],"|",'{:.3E}'.format(remnm[i]),"|",'{:.3E}'.format(tottime[i]) 
Example 41
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 4 votes vote down vote up
def set_plot_profile_decay(self,cycles=20*[-1],mass_range=20*[[0,0]],ylim=20*[[0,0]],isotopes=[],linestyle=[],save_dir=''): 
		'''
			Plots HRDs


			end_model - array, control how far in models a run is plottet, if -1 till end
			symbs_1  - set symbols of runs
		'''
		if len(linestyle)==0:
			linestyle=200*['-']
		import nugridse as mp
		import utils as u
		#print self.runs_H5_restart
                for i in range(len(self.runs_H5_restart)):
        		sefiles=mp.se(self.runs_H5_restart[i])
			cycle=cycles[i]
                        if cycle==-1:
                                cycle=int(sefiles.se.cycles[-1])			
			if mass_range[i][0] ==0 and mass_range[i][1]==0:
				mass_range[i][1]=sefiles.get(cycle,'mass')[-1]				
			sefiles.read_iso_abund_marco(mass_range[i],cycle)
		    	u.stable_specie()
		    	sefiles.decay(sefiles.mass_frac)
			idx_species=[]
			for k in range(len(isotopes)):
				other_name_scheme=isotopes[k].split("-")[0].upper()+(5-len(isotopes[k])+1)*" "+isotopes[k].split("-")[1]
				#other_name_scheme=other_name_scheme.capitalize()

				idx_specie=u.back_ind[other_name_scheme]
				idx_species.append(idx_specie)
			mass_abu_array=[]
			for idx_specie in idx_species:
				mass_abu_array.append([])
				for idx_mass in range(len(mp.decayed_multi_d)):
					mass_abu_array[-1].append(mp.decayed_multi_d[idx_mass][idx_specie])
					
			#plotting
			plt.figure(self.run_dirs_name[i])
			#print len(mp.used_masses),len(mass_abu_array[0])
			#print mass_abu_array[0]
			for k in range(len(isotopes)):
				plt.plot(mp.used_masses,mass_abu_array[k],linestyle=linestyle[k],label=isotopes[k])
			plt.legend()
			plt.yscale('log')
			#print sefiles.get(cycle,'mass')[-1]
			plt.xlabel('M/Msun')
			plt.ylabel('$X_i$')
			plt.xlim(mass_range[i][0],mass_range[i][1])
			if (ylim[i][0]>0 or ylim[i][1]>0) or (ylim[i][0]>0 and ylim[i][1]>0):
				plt.ylim(ylim[i][0],ylim[i][1])
			if len(save_dir)>0:
				star_mass=sefiles.get("mini")
				star_z=sefiles.get("zini")
				plt.savefig(save_dir+'/'+self.run_dirs_name[i]+'_decay_profiles.png') 
Example 42
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 4 votes vote down vote up
def set_pocket(self,runs=[],cycle=[45532,47566],mass_cell=[0.641981,0.641981],isotopes=[],x_charge=False,mass_number_range=[],decayed=False,iso_label=False,title="PDCZ",colors=["red","blue","green","black"],yax_log=True,filename_norm="iniab2.0E-02GN93.ppn",elem_norm=''):

		'''
			plots isotopic composition for different runs, each with specific cycle number cycle[i] and specific mass cell mass_cell[i].
			Initial abundace file for normalization can be chosen as filename_norm, but MUST be in run directory

			decayed - plot only decayed isotopes
			mass_number_range - array of min mass number and max mass number, isotopes inbetween will be plottet, if set, isotope array will be ignored
			iso_label - set labels of isotopes True or False
			title - 
			colors -
			filename_norm - not yet included, normalization with initial abundance file
			....
			e.g.
			
			setse.set_pocket(cycle=[32840,29390],mass_cell=[0.6300,0.6076],isotopes=["He-4","C-12","O-16","Ne-22"],mass_number_range=[80,140],decayed=True)
			

	
		'''
	
		import nugridse as mp	
                sefiles=[]
                legend=[]
                HDF5_out=[]
                extra_label=[]

		if len(runs) ==0:
			HDF5_out=self.runs_H5_out
			runs=self.run_dirs_name
			extra_label=self.extra_label
		else:
			for i in range(len(self.run_dirs_name)):
				if self.run_dirs_name[i] in runs:
					HDF5_out.append(self.runs_H5_out[i])
                                        extra_label.append(self.extra_label[i])
		for i in range(len(HDF5_out)):
			reload(mp)
			file_norm=HDF5_out[i][:-6]+filename_norm
			sefiles=se(HDF5_out[i])
                        mass=sefiles.get("mini")
                        z=sefiles.get("zini")
                        legend=str(mass)+"M$_{\odot}$ Z= "+str(z)+", "+extra_label[i]
			if len(isotopes)==0:
                                self.plot_abu_atmasscoord(mp,sefiles,cycle[i],mass_cell[i],["He-4","C-12","O-16","Ne-22"],x_charge,mass_number_range,decayed,file_norm,elem_norm,yax_log,label=iso_label,legend=legend,color=colors[i],title=title)

				#plt.figure(111);self.pocket_composition(mp,sefiles=sefiles,cycle=cycle[i], massbot=massrange[i][0],masstop=massrange[i][1],isotopes=["He-4","C-12","O-16","Ne-22"],label=True,legend=legend,color=colors[i],title=title)
				#plt.figure(222);self.pocket_composition(mp,sefiles=sefiles,cycle=cycle[i], massbot=massrange[i][0],masstop=massrange[i][1],isotopes=['Fe-56','Co-60','Ni-61','Cu-65','Zn-67','Ga-71','Ge-73','As-75','Se-77','Br-82','Kr-84','Rb-87','Sr-88','Y-89','Zr-92','Nb-94','Zr-96','Mo-96','Ba-137','Ba-138','La-139','Ce-140','Nd-142','Sm-144','Pb-206'],label=True,legend=legend,color=colors[i],title=title)
			else:
				#plt.figure(111);self.pocket_composition(mp,sefiles=sefiles,cycle=cycle[i], massbot=massrange[i][0],masstop=massrange[i][1],isotopes=isotopes,label=True,legend=legend,color=colors[i],title=title)
				self.plot_abu_atmasscoord(mp,sefiles,cycle[i],mass_cell[i],isotopes,x_charge,mass_number_range,decayed,file_norm,elem_norm,yax_log,label=iso_label,legend=legend,color=colors[i],title=title) 
Example 43
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 4 votes vote down vote up
def set_surface_abundances(self,runs=[],cycle=[-1,-1],isotopes=[],x_charge=True,mass_number_range=[],decayed=False,iso_label=False,title="",colors=["red","blue","green","black"],yax_log=True,filename_norm="iniab2.0E-02GN93.ppn",elem_norm=''):

                '''
                        plots isotopic composition for different runs, each with specific cycle number cycle[i] and specific mass cell mass_cell[i].
                        Initial abundace file for normalization can be chosen as filename_norm, but MUST be in run directory

                        decayed - plot only decayed isotopes
                        mass_number_range - array of min mass number and max mass number, isotopes inbetween will be plottet, if set, isotope array will be ignored
                        iso_label - set labels of isotopes True or False
                        title - 
                        colors -
                        filename_norm - not yet included, normalization with initial abundance file
                        ....
                        e.g.
                        
                        setse.set_pocket(cycle=[32840,29390],mass_cell=[0.6300,0.6076],isotopes=["He-4","C-12","O-16","Ne-22"],mass_number_range=[80,140],decayed=True)
                        

        
                '''


                import nugridse as mp
                sefiles=[]
                legend=[]
                HDF5_out=[]
                extra_label=[]


                if len(runs) ==0:
                        HDF5_out=self.runs_H5_out
                        runs=self.run_dirs_name
                        extra_label=self.extra_label
                else:
                        for i in range(len(self.run_dirs_name)):
                                if self.run_dirs_name[i] in runs:
                                        HDF5_out.append(self.runs_H5_out[i])
                                        extra_label.append(self.extra_label[i])
                for i in range(len(HDF5_out)):
                        reload(mp)
                        file_norm=HDF5_out[i][:-6]+filename_norm
                        sefiles=se(HDF5_out[i])
			if cycle[i] ==-1:
				cycle_1=sefiles.se.cycles[-1]
			else:
				cycle_1=cycle[i]
			masscell=sefiles.get(cycle_1,"mass")[0]
                        mass=sefiles.get("mini")
                        z=sefiles.get("zini")
                        legend=str(mass)+"M$_{\odot}$ Z= "+str(z)+", "+extra_label[i]
                        if len(isotopes)==0:
                                self.plot_abu_atmasscoord(mp,sefiles,cycle_1,masscell,isotopes,x_charge,mass_number_range,decayed,file_norm,elem_norm,yax_log,label=iso_label,legend=legend,color=colors[i],title=title)

                                #plt.figure(111);self.pocket_composition(mp,sefiles=sefiles,cycle=cycle[i], massbot=massrange[i][0],masstop=massrange[i][1],isotopes=["He-4","C-12","O-16","Ne-22"],label=True,legend=legend,color=colors[i],title=title)
                                #plt.figure(222);self.pocket_composition(mp,sefiles=sefiles,cycle=cycle[i], massbot=massrange[i][0],masstop=massrange[i][1],isotopes=['Fe-56','Co-60','Ni-61','Cu-65','Zn-67','Ga-71','Ge-73','As-75','Se-77','Br-82','Kr-84','Rb-87','Sr-88','Y-89','Zr-92','Nb-94','Zr-96','Mo-96','Ba-137','Ba-138','La-139','Ce-140','Nd-142','Sm-144','Pb-206'],label=True,legend=legend,color=colors[i],title=title)
                        else:
                                #plt.figure(111);self.pocket_composition(mp,sefiles=sefiles,cycle=cycle[i], massbot=massrange[i][0],masstop=massrange[i][1],isotopes=isotopes,label=True,legend=legend,color=colors[i],title=title)
                                self.plot_abu_atmasscoord(mp,sefiles,cycle_1,masscell,isotopes,x_charge,mass_number_range,decayed,file_norm,elem_norm,yax_log,label=iso_label,legend=legend,color=colors[i],title=title) 
Example 44
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 4 votes vote down vote up
def write_gce_input_wind_ejection_rate(self,file_name="isotopic_table.txt",final_models=[]):

		'''
			Calculates total mass ejection rate from stellar wind phase.
		'''

		e_kin_array=[]
		mz=[]
		m_final=[]
		mz=[]
		ini_m=[]
		p=-1
		for i in range(len(self.runs_H5_out)):
			p+=1
			sefiles=se(self.runs_H5_out[i])
			sefiles_restart=se(self.runs_H5_restart[i])
			mass=sefiles.get("mini")
			metallicity=sefiles.get("zini")	
			mz1='(M='+str(round(mass,2))+',Z='+str(metallicity)+')'
			endcycle=int(sefiles.se.cycles[-1])
			if len(final_models)>0:
				cycs=self.get_last_cycle([0,final_models[p]+500,500],sefiles,sefiles_restart)
			else:
				cycs=self.get_last_cycle([0,-1,500],sefiles,sefiles_restart)
			endcycle=cycs[-1]
			h_mass_frac=sefiles.get(endcycle,'H-1')
			mass_array=sefiles.get(endcycle,'mass')
			#earlier: 1.e-1 but now as in set1 scripts 0.05
			h_free_core=mass_array[np.where(h_mass_frac<5.e-2)[0][-1]]
			m_final.append(h_free_core)		
			mz.append(mz1)
			ini_m.append(mass)

                f1=open(file_name,'r')
                lines=f1.readlines()
                f1.close()
                i=-1
                line1=''
                while (True):
                        i+=1
                        if i>len(lines)-1:
                                break
                        line=lines[i]
                        line1+=lines[i]
                        for k in range(len(mz)):
                                if mz[k] in lines[i]:
					## check ahead for H Mfinal:
					#for h in range(i,i+10):
					#	if 'H Lifetime:' in lines[h]:
					#		lifetime=float(lines[h].split(':')[1])
					#		break
					#	if h==i+9:
					#		print 'ERROR: no lifetime in table found!!'
					#		return
					ejection=(ini_m[k]-m_final[k]) #/lifetime
                                        line1+=('H Wind ejection: '+'{:.3E}'.format(ejection)+'\n')
                                        break

                f1=open(file_name,'w')
                f1.write(line1)
                f1.close() 
Example 45
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 4 votes vote down vote up
def write_gce_input_lifetimes(self,file_name="isotopic_table.txt",final_cycles=[]):

		'''
			Calculates and writes lifetime in file_name
			X_carbon_center >  0.4
			
		'''

		###Get lifetimes###

		print '##############GETTING THE LIFETIMES##############'
		time=[]
		model=[]
		mz=[]
		for i in range(len(self.runs_H5_surf)):
			sefiles=se(self.runs_H5_surf[i])
			mass=sefiles.get("mini")
			metallicity=sefiles.get("zini")
			mz1='(M='+str(round(mass,2))+',Z='+str(metallicity)+')'
			cycs=[]
			if final_cycles[i]>-1:
				final_cycle=final_cycles[i]
			else:
				final_cycle=int(sefiles.se.cycles[-1])
			time1=(sefiles.get(final_cycle,'age')*sefiles.get('age_unit'))/31557600.
			time.append(time1)
			mz.append(mz1)

		f1=open(file_name,'r')
		lines=f1.readlines()
		f1.close()
		i=-1
		line1=''
		print 'Adding for ',mz,'lifetime : ',time
		while (True):
			i+=1
			if i>len(lines)-1:
				break
			line=lines[i]	
			line1+=lines[i]
			for k in range(len(mz)):
				if mz[k] in lines[i]:
					line1+=('H Lifetime: '+'{:.3E}'.format(time[k])+'\n')
					break			
			
		f1=open(file_name,'w')
                f1.write(line1)
                f1.close() 
Example 46
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 4 votes vote down vote up
def get_last_cycle(self,cycles,sefiles,sefiles_restart):

		'''
			Because there are a lot of issues with cycles we need this routine :(
		'''

		if cycles[1]==-1:
			#if star_mass>9:
			endcycle=int(sefiles_restart.se.cycles[-2])
			#else:
			#       endcycle=int(sefiles[k].se.cycles[-2])
		else:
			endcycle=cycles[1]
		cycs=range(cycles[0],endcycle,cycles[2])
		if endcycle not in cycs:
			cycs=cycs+[endcycle]
		print 'first, last cycle: ',cycles[0],endcycle
		star_mass11=sefiles.get(cycs,'mass')				
		#do a check for missing cycles
		if not len(star_mass11)==len(cycs):
			cycs1=[int(cycs[0])]
			for cyc in cycs[1:]:
				if  cyc <= max(cycs1):
					continue
				a=sefiles.get(cyc,'mass')
				cyctest=int(cyc)
				#if cycle 0 or a non-existing cycle, or cycle was alrady added, 
				#go one cycle further   
				while ((type(a)==list) or (a==0)):
					if   cyctest<int(cycs[-1]):
						print int(cycs[-1])
						print 'found bad cycle',cyctest
						cyctest+=1
						a=sefiles.get(cyctest,'mass')
					elif cyctest==int(cycs[-1]):
						cyctest=int(sefiles_restart.se.cycles[-3])
						a=sefiles.get(cyctest,'mass')	
						h=-4
						while ((type(a)==list) or (a==0)):
							cyctest=int(sefiles_restart.se.cycles[h])
							a=sefiles.get(cyctest,'mass')
							h-=1
						for kk in cycs1:
							if kk>=cyctest:
								cycs1=cycs1[:kk]
						break
					else:
						break
				print 'Use cycle ',cyctest
				if cyctest>max(cycs1):
					cycs1.append(cyctest)
			print len(cycs),len(cycs1)
			cycs=cycs1

		return cycs 
Example 47
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 4 votes vote down vote up
def weighted_yields_pre_explosion(self,mp,sefiles,sefiles_hout,endcycle,mass_cut,isotopes):
		
		'''
			Marcos routine adapted, calc pre SN yields
			explosion cycle is endcycle, at which pre SN yield is taken from
		'''


		import utils as u
		

		cycle=endcycle
		first_cycle=sefiles.se.cycles[0]	
		#mass_cut=1.60
                mass_last_cycle=sefiles_hout.get(cycle,"mass")
                idx_mcut=int(np.where(mass_last_cycle>mass_cut)[0][0])
                

		# I take the max mass coord
		mass_limit=mass_last_cycle[-1]
		# I calculate average_mass_frac_decay
		sefiles_hout.average_iso_abund_marco([mass_cut,mass_limit],cycle,True,2)

		E_i_pre_15=array(mp.average_mass_frac_decay)*(mass_limit-mass_cut)

		#follwoing needed for isotope identification,must be stable
		# define back_ind presn
		back_ind_pre=u.back_ind

		yields=[]
		iniabus=[]
		prod_facs=[]
		for i in range(len(isotopes)):
			other_name_scheme=isotopes[i].split("-")[0].upper()+(5-len(isotopes[i])+1)*" "+isotopes[i].split("-")[1] 
			if other_name_scheme not in u.stable:
				print "error: Chosen isotope is not stable:",other_name_scheme
				return 1
			idx_iso=back_ind_pre[other_name_scheme]
			yield_decayed=E_i_pre_15[idx_iso]
			yields.append(yield_decayed)
			iniabu_1=sefiles.get(0,isotopes[i])	
                        print "iniabu for exp",iniabu_1
                        iniabus.append(iniabu_1)
                        total_yield= yield_decayed
                        total_prod_factor=  total_yield/     ((mass_limit-mass_cut)*iniabu_1)
                        prod_facs.append(total_prod_factor)
                        print total_yield, total_prod_factor
                
		ini_star_mass=sefiles.get("mini")
		iniabus=np.array(iniabus)*(ini_star_mass)#-end_star_mass)
                
		return np.array(prod_facs),isotopes,yields,iniabus 
Example 48
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 4 votes vote down vote up
def prodfac_explosion(self,mp,sefiles,sefiles_hout,isotopes,ini_abu=""):
		'''
			Marcos routine adapted, calc SN yields
		'''

		import utils as u

                initial_abu=iniabu(ini_abu)                     #,iniabufile='../../frames/mppnp/USEEPP/"

		cycle=sefiles_hout.se.cycles[-1]
		first_cycle=sefiles_hout.se.cycles[0]	
		#mass_cut=1.60
                ###identify mcut at mass cell where rho >1 at first cycle,from core to surface
                rho_first_cycle=sefiles_hout.get(first_cycle,"rho")
                mass_first_cycle=sefiles_hout.get(first_cycle,"mass")
		print rho_first_cycle
		
		print cycle
		print sefiles_hout.get("mini")
		print sefiles_hout.get("zini")
                idx_mcut=int(np.where(rho_first_cycle!=1)[0][0])
                mass_cut=mass_first_cycle[idx_mcut]

		# I take the max mass coord
		mass_limit=mass_first_cycle[-1]
		# I calculate average_mass_frac_decay
		sefiles_hout.average_iso_abund_marco([mass_cut,mass_limit],cycle,True,2)

		E_i_pre_15=array(mp.average_mass_frac_decay)*(mass_limit-mass_cut)

		#follwoing needed for isotope identification,must be stable
		# define back_ind presn
		back_ind_pre=u.back_ind

		yields=[]
		iniabus=[]
		prod_facs=[]
		for i in range(len(isotopes)):
			other_name_scheme=isotopes[i].split("-")[0].upper()+(5-len(isotopes[i])+1)*" "+isotopes[i].split("-")[1] 
			if other_name_scheme not in u.stable:
				print "error: Chosen isotope is not stable: ",other_name_scheme
				return 1
			idx_iso=back_ind_pre[other_name_scheme]
			yield_decayed=E_i_pre_15[idx_iso]
			yields.append(yield_decayed)	
			iniabu_1=initial_abu.abu[ initial_abu.names.index(isotopes[i].split("-")[0].lower()+(5-len(isotopes[i])+1)*" "+isotopes[i].split("-")[1])]	
                        print "iniabu for exp",iniabu_1
                        iniabus.append(iniabu_1)
                        total_yield= yield_decayed
                        total_prod_factor=  total_yield/     ((mass_limit-mass_cut)*iniabu_1)
                        prod_facs.append(total_prod_factor)
                        print total_yield, total_prod_factor
                
		ini_star_mass=sefiles.get("mini")
		iniabus=np.array(iniabus)*(ini_star_mass)#-end_star_mass)
                
		return np.array(prod_facs),isotopes,yields,iniabus,mass_cut,first_cycle 
Example 49
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 4 votes vote down vote up
def multi_DUP(self,t0_model=[],h_core_mass=False,plot_fig=True,linestyle=[],marker=[],color=[]):
		'''
			Plot (!) DUP parameter lambda versus mass.
			There is a algorithm finding the first TP (and set t0_model) for reach run dir 
			which worked fine for set1. But there could be a problem with SAGB stars
			so use with caution! You can use a manual input (the array t0_model) to
			skip this step.

			It also returns peak lum and corresponding
			model number of each TP.


			h_core_mass - If True: plot dependence from h free core , else star mass 
			t0_model -  Array of first TPs of models.			
		
			examples of set1:
			t0_model paramter:		
			z1e-2:1.65-5: [13690,3120,3163,5306]
			z2e-2:1.65-5: [16033,6214,3388,5368]

			dirs=["M1.65Z2.0e-02/LOGS","M2.00Z2.0e-02/LOGS","M3.00Z2.0e-02/LOGS","M5.00Z2.0e-02/LOGS"]
			dirs=["M1.65Z1.0e-02/LOGS","M2.00Z1.0e-02/LOGS","M3.00Z1.0e-02/LOGS","M5.00Z1.0e-02/LOGS"]
			note: M3_1e-2 shows decrease in core mass in the end
			set.multi_DUP(t0_model=[13690,3120,3163,5306])
			set.multi_DUP(t0_model=[16033,6214,3388,5368])
		
		'''
		if len(t0_model)==0:
			t0_model=self.set_find_first_TP()
		dirs=self.run_LOGS
		historydata=self.run_historydata
	
		marker_type=marker
		#line_style=['--','-','-.',':']
		peak_lum_model_array=[]
		h1_mass_min_DUP_model_array=[]
		for i in range(len(dirs)):
			#color,marker_type)
			peak_lum_model,h1_mass_min_DUP_model = historydata[i].find_TP_attributes(0,t0_model[i],color[i],marker_type[i],h_core_mass,no_fig=plot_fig)			
			peak_lum_model_array.append(peak_lum_model)
			h1_mass_min_DUP_model.append(h1_mass_min_DUP_model)

		return peak_lum_model_array,h1_mass_min_DUP_model_array

				
	###the following methods allow are parts of Falks vis3.py file, thanks Falk 
Example 50
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    (license) View Source Project 4 votes vote down vote up
def plot_TPDCZ(self,fig=13,marker=[]):

		'''Plots TPDCZ vs TP'''
		
		minis=[]
		for hh in range(len(self.run_historydata)):
				historydata=self.run_historydata[hh]
				sefiles_out=se(self.runs_H5_out[hh])
				sefiles=sefiles_out
				mini=float(sefiles_out.se.get('mini'))
				zini=float(sefiles_out.se.get('zini'))
				label=str(mini)+'$M_{\odot}$, Z='+str(zini)
				minis.append(mini)
				TPstart,TPmods,TP_max_env,TPend,min_m_TP,max_m_TP,DUPmods,DUPm_min_h,c13_pocket_min,c13_pocket_max=self.TPAGB_properties(historydata,sefiles_out)

				###Temperature

				pulse_peak_T=[]
				pulse_number=[]
				plt.figure(fig)
				for k in range(len(TPmods)):
					model=int(float(TPmods[k]))
					T_profile=sefiles_out.get(model,'temperature')*sefiles_out.get('temperature_unit')
					mass=sefiles_out.get(model,'mass')
					#plt.figure(2)
					print 'testse'
					print TPmods[k]
					#plt.plot(mass,T_profile,label='cycle '+str(TPmods[k]),marker=marker[k],markevery=100)
					#plt.figure(11)
					#models=sefiles_out.se.cycles
					#models=map(int,models)
					#print 'model taken: ',models[min(range(len(models)), key=lambda i: abs(models[i]-model))]
					idx_mass=min(range(len(mass)), key=lambda i: abs(mass[i]-min_m_TP[k]))	
					pulse_peak_T.append(max(T_profile[idx_mass:]))
					print k+1
					print '{:.3E}'.format(T_profile[idx_mass])
					pulse_number.append(k+1)

				plt.plot(pulse_number,pulse_peak_T,marker=marker[hh],linestyle='--',label=label)

				plt.legend()
				plt.ylabel('$T_{max,PDCZ}$')
				plt.xlabel('TP number')