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)
python类append()的实例源码
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]
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]
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
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
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+'}$')
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]
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)
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()
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
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)
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)
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()
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)
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
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()
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)
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)
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)
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)
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")
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}$')
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
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
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])
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
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))
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])
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
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