sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def write_STELLA_model(self,name): """ Write an initial model in a format that may easily be read by the radiation hydrodynamics code STELLA. Parameters ---------- name : string an identifier for the model. There are two output files from this method, which will be <name>.hyd and <name>.abn, which contain the profiles for the hydro and abundance variables, respectively. """ # Hydro variables: zn = np.array(self.get('zone'),np.int64) Mr = self.get('mass')[::-1] dM = 10. ** self.get('logdq')[::-1] * self.header_attr['star_mass'] R = self.get('radius')[::-1] * ast.rsun_cm dR = np.insert( np.diff(R), 0, R[0] ) Rho = 10. ** self.get('logRho')[::-1] PRE = 10. ** self.get('logP')[::-1] T = 10. ** self.get('logT')[::-1] V = self.get('velocity')[::-1] # Abundances: def make_list(element,lowA,highA): l = [] for i in range(lowA,highA+1): l.append(element+str(i)) return l abun_avail = list(self.cols.keys()) def elemental_abund(ilist,abun_avail): X = np.zeros(len(self.get('mass'))) for a in ilist: if a in abun_avail: X += self.get(a)[::-1] return X iH = ['h1','h2','prot'] XH = elemental_abund(iH, abun_avail) XHe = elemental_abund(make_list('he',1,5), abun_avail) XC = elemental_abund(make_list('c',11,15), abun_avail) XN = elemental_abund(make_list('n',12,16), abun_avail) XO = elemental_abund(make_list('o',13,20), abun_avail) XNe = elemental_abund(make_list('ne',17,25), abun_avail) XNa = elemental_abund(make_list('na',20,25), abun_avail) XMg = elemental_abund(make_list('mg',21,28), abun_avail) XAl = elemental_abund(make_list('al',21,30), abun_avail) XSi = elemental_abund(make_list('si',25,34), abun_avail) XS = elemental_abund(make_list('s',28,38), abun_avail) XAr = elemental_abund(make_list('ar',32,46), abun_avail) XCa = elemental_abund(make_list('ca',36,53), abun_avail) XFe = elemental_abund(make_list('fe',50,65), abun_avail) XCo = elemental_abund(make_list('co',52,66), abun_avail) XNi = elemental_abund(make_list('ni',54,71), abun_avail) XNi56 = self.get('ni56') # Write the output files: file_hyd = name+'.hyd' file_abn = name+'.abn' f = open(file_hyd,'w') # write header: f.write(' 0.000E+00\n') f.write('# No.') f.write('Mr'.rjust(28)+ 'dM'.rjust(28)+ 'R'.rjust(28)+ 'dR'.rjust(28)+ 'Rho'.rjust(28)+ 'PRE'.rjust(28)+ 'T'.rjust(28)+ 'V'.rjust(28)+ '\n') # write data: for i in range(len(zn)): f.write( str(zn[i]).rjust(5) + '%.16E'.rjust(11) %Mr[i] + '%.16E'.rjust(11) %dM[i] + '%.16E'.rjust(11) %R[i] + '%.16E'.rjust(11) %dR[i] + '%.16E'.rjust(11) %Rho[i] + '%.16E'.rjust(11) %PRE[i] + '%.16E'.rjust(11) %T[i] + '%.16E'.rjust(11) %V[i] + '\n') f.close() f = open(file_abn,'w') # write header: f.write('# No.') f.write('Mr'.rjust(28)+ 'H'.rjust(28)+ 'He'.rjust(28)+ 'C'.rjust(28)+ 'N'.rjust(28)+ 'O'.rjust(28)+ 'Ne'.rjust(28)+ 'Na'.rjust(28)+ 'Mg'.rjust(28)+ 'Al'.rjust(28)+ 'Si'.rjust(28)+ 'S'.rjust(28)+ 'Ar'.rjust(28)+ 'Ca'.rjust(28)+ 'Fe'.rjust(28)+ 'Co'.rjust(28)+ 'Ni'.rjust(28)+ 'X(56Ni)'.rjust(28)+ '\n') # write data: for i in range(len(zn)): f.write( str(zn[i]).rjust(5) + '%.16E'.rjust(11) %Mr[i] + '%.16E'.rjust(11) %XH[i] + '%.16E'.rjust(11) %XHe[i] + '%.16E'.rjust(11) %XC[i] + '%.16E'.rjust(11) %XN[i] + '%.16E'.rjust(11) %XO[i] + '%.16E'.rjust(11) %XNe[i] + '%.16E'.rjust(11) %XNa[i] + '%.16E'.rjust(11) %XMg[i] + '%.16E'.rjust(11) %XAl[i] + '%.16E'.rjust(11) %XSi[i] + '%.16E'.rjust(11) %XS[i] + '%.16E'.rjust(11) %XAr[i] + '%.16E'.rjust(11) %XCa[i] + '%.16E'.rjust(11) %XFe[i] + '%.16E'.rjust(11) %XCo[i] + '%.16E'.rjust(11) %XNi[i] + '%.16E'.rjust(11) %XNi56[i] + '\n')
Write an initial model in a format that may easily be read by the radiation hydrodynamics code STELLA. Parameters ---------- name : string an identifier for the model. There are two output files from this method, which will be <name>.hyd and <name>.abn, which contain the profiles for the hydro and abundance variables, respectively.
entailment
def write_LEAFS_model(self,nzn=30000000,dr=5.e4, rhostrip=5.e-4): """ write an ascii file that will be read by Sam's version of inimod.F90 in order to make an initial model for LEAFS """ from scipy import interpolate ye = self.get('ye') newye=[] rho = 10.**self.get('logRho')[::-1] # centre to surface # get index to strip all but the core: idx = np.abs(rho - rhostrip).argmin() + 1 rho = rho[:idx] rhoc = rho[0] rad = 10.**self.get('logR') * ast.rsun_cm rad = rad[::-1][:idx] ye = ye[::-1][:idx] print('there will be about ',old_div(rad[-1], dr), 'mass cells...') # add r = 0 point to all arrays rad = np.insert(rad,0,0) ye = np.insert(ye,0,ye[0]) rho = np.insert(rho,0,rho[0]) print(rad) # interpolate fye = interpolate.interp1d(rad,ye) frho = interpolate.interp1d(rad,rho) newye = [] newrho = [] newrad = [] Tc = 10.**self.get('logT')[-1] for i in range(nzn): if i * dr > rad[-1]: break newye.append(fye( i * dr )) newrho.append(frho( i * dr )) newrad.append( i * dr ) f = open('M875.inimod','w') f.write(str(Tc)+' \n') f.write(str(rhoc)+' \n') for i in range(len(newye)): f.write(str(i+1)+' '+str(newrad[i])+' '+\ str(newrho[i])+' '+str(newye[i])+' \n') f.close()
write an ascii file that will be read by Sam's version of inimod.F90 in order to make an initial model for LEAFS
entailment
def energy_profile(self,ixaxis): """ Plot radial profile of key energy generations eps_nuc, eps_neu etc. Parameters ---------- ixaxis : 'mass' or 'radius' """ mass = self.get('mass') radius = self.get('radius') * ast.rsun_cm eps_nuc = self.get('eps_nuc') eps_neu = self.get('non_nuc_neu') if ixaxis == 'mass': xaxis = mass xlab = 'Mass / M$_\odot$' else: xaxis = old_div(radius, 1.e8) # Mm xlab = 'Radius (Mm)' pl.plot(xaxis, np.log10(eps_nuc), 'k-', label='$\epsilon_\mathrm{nuc}>0$') pl.plot(xaxis, np.log10(-eps_nuc), 'k--', label='$\epsilon_\mathrm{nuc}<0$') pl.plot(xaxis, np.log10(eps_neu), 'r-', label='$\epsilon_\\nu$') pl.xlabel(xlab) pl.ylabel('$\log(\epsilon_\mathrm{nuc},\epsilon_\\nu)$') pl.legend(loc='best').draw_frame(False)
Plot radial profile of key energy generations eps_nuc, eps_neu etc. Parameters ---------- ixaxis : 'mass' or 'radius'
entailment
def _read_starlog(self): """ read history.data or star.log file again""" sldir = self.sldir slname = self.slname slaname = slname+'sa' if not os.path.exists(sldir+'/'+slaname): print('No '+self.slname+'sa file found, create new one from '+self.slname) _cleanstarlog(sldir+'/'+slname) else: if self.clean_starlog: print('Requested new '+self.slname+'sa; create new from '+self.slname) _cleanstarlog(sldir+'/'+slname) else: print('Using old '+self.slname+'sa file ...') cmd=os.popen('wc '+sldir+'/'+slaname) cmd_out=cmd.readline() cnum_cycles=cmd_out.split()[0] num_cycles=int(cnum_cycles) - 6 filename=sldir+'/'+slaname header_attr,cols,data = _read_mesafile(filename,data_rows=num_cycles) self.cols = cols self.header_attr = header_attr self.data = data
read history.data or star.log file again
entailment
def CO_ratio(self,ifig,ixaxis): """ plot surface C/O ratio in Figure ifig with x-axis quantity ixaxis Parameters ---------- ifig : integer Figure number in which to plot ixaxis : string what quantity is to be on the x-axis, either 'time' or 'model' The default is 'model' """ def C_O(model): surface_c12=model.get('surface_c12') surface_o16=model.get('surface_o16') CORatio=old_div((surface_c12*4.),(surface_o16*3.)) return CORatio if ixaxis=='time': xax=self.get('star_age') elif ixaxis=='model': xax=self.get('model_number') else: raise IOError("ixaxis not recognised") pl.figure(ifig) pl.plot(xax,C_O(self))
plot surface C/O ratio in Figure ifig with x-axis quantity ixaxis Parameters ---------- ifig : integer Figure number in which to plot ixaxis : string what quantity is to be on the x-axis, either 'time' or 'model' The default is 'model'
entailment
def hrd(self,ifig=None,label=None,colour=None,s2ms=False, dashes=None,**kwargs): """ Plot an HR diagram Parameters ---------- ifig : integer or string Figure label, if None the current figure is used The default value is None. lims : list [x_lower, x_upper, y_lower, y_upper] label : string Label for the model The default value is None colour : string The colour of the line The default value is None s2ms : boolean, optional "Skip to Main Sequence"? The default is False. dashes : list, optional Custom dashing style. If None, ignore. The default is None. """ # fsize=18 # # params = {'axes.labelsize': fsize, # # 'font.family': 'serif', # 'font.family': 'Times New Roman', # 'figure.facecolor': 'white', # 'text.fontsize': fsize, # 'legend.fontsize': fsize, # 'xtick.labelsize': fsize*0.8, # 'ytick.labelsize': fsize*0.8, # 'text.usetex': False} # # try: # pl.rcParams.update(params) # except: # pass if ifig is not None: pl.figure(ifig) if s2ms: h1=self.get('center_h1') idx=np.where(h1[0]-h1>=3.e-3)[0][0] skip=idx else: skip=0 x = self.get('log_Teff')[skip:] y = self.get('log_L')[skip:] if label is not None: if colour is not None: line,=pl.plot(x,y,label=label,color=colour,**kwargs) else: line,=pl.plot(x,y,label=label,**kwargs) else: if colour is not None: line,=pl.plot(x,y,color=colour,**kwargs) else: line,=pl.plot(x,y,**kwargs) if dashes is not None: line.set_dashes(dashes) if label is not None: pl.legend(loc='best').draw_frame(False) # pyl.plot(self.data[:,self.cols['log_Teff']-1],\ # self.data[:,self.cols['log_L']-1],\ # label = "M="+str(self.header_attr['initial_mass'])+", Z="\ # +str(self.header_attr['initial_z'])) pyl.xlabel('$\log T_{\\rm eff}$') pyl.ylabel('$\log L$') x1,x2=pl.xlim() if x2 > x1: ax=pl.gca() ax.invert_xaxis()
Plot an HR diagram Parameters ---------- ifig : integer or string Figure label, if None the current figure is used The default value is None. lims : list [x_lower, x_upper, y_lower, y_upper] label : string Label for the model The default value is None colour : string The colour of the line The default value is None s2ms : boolean, optional "Skip to Main Sequence"? The default is False. dashes : list, optional Custom dashing style. If None, ignore. The default is None.
entailment
def hrd_key(self, key_str): """ plot an HR diagram Parameters ---------- key_str : string A label string """ pyl.plot(self.data[:,self.cols['log_Teff']-1],\ self.data[:,self.cols['log_L']-1],label = key_str) pyl.legend() pyl.xlabel('log Teff') pyl.ylabel('log L') x1,x2=pl.xlim() if x2 > x1: self._xlimrev()
plot an HR diagram Parameters ---------- key_str : string A label string
entailment
def hrd_new(self, input_label="", skip=0): """ plot an HR diagram with options to skip the first N lines and add a label string Parameters ---------- input_label : string, optional Diagram label. The default is "". skip : integer, optional Skip the first n lines. The default is 0. """ xl_old=pyl.gca().get_xlim() if input_label == "": my_label="M="+str(self.header_attr['initial_mass'])+", Z="+str(self.header_attr['initial_z']) else: my_label="M="+str(self.header_attr['initial_mass'])+", Z="+str(self.header_attr['initial_z'])+"; "+str(input_label) pyl.plot(self.data[skip:,self.cols['log_Teff']-1],self.data[skip:,self.cols['log_L']-1],label = my_label) pyl.legend(loc=0) xl_new=pyl.gca().get_xlim() pyl.xlabel('log Teff') pyl.ylabel('log L') if any(array(xl_old)==0): pyl.gca().set_xlim(max(xl_new),min(xl_new)) elif any(array(xl_new)==0): pyl.gca().set_xlim(max(xl_old),min(xl_old)) else: pyl.gca().set_xlim([max(xl_old+xl_new),min(xl_old+xl_new)])
plot an HR diagram with options to skip the first N lines and add a label string Parameters ---------- input_label : string, optional Diagram label. The default is "". skip : integer, optional Skip the first n lines. The default is 0.
entailment
def xche4_teff(self,ifig=None,lims=[1.,0.,3.4,4.7],label=None,colour=None, s2ms=True,dashes=None): """ Plot effective temperature against central helium abundance. Parameters ---------- ifig : integer or string Figure label, if None the current figure is used The default value is None. lims : list [x_lower, x_upper, y_lower, y_upper] label : string Label for the model The default value is None colour : string The colour of the line The default value is None s2ms : boolean, optional "Skip to Main Sequence" The default is True dashes : list, optional Custom dashing style. If None, ignore. The default is None. """ fsize=18 params = {'axes.labelsize': fsize, # 'font.family': 'serif', 'font.family': 'Times New Roman', 'figure.facecolor': 'white', 'text.fontsize': fsize, 'legend.fontsize': fsize, 'xtick.labelsize': fsize*0.8, 'ytick.labelsize': fsize*0.8, 'text.usetex': False} try: pl.rcParams.update(params) except: pass if s2ms: h1=self.get('center_h1') idx=np.where(h1[0]-h1>=1.e-3)[0][0] skip=idx else: skip=0 x = self.get('center_he4')[skip:] y = self.get('log_Teff')[skip:] if ifig is not None: pl.figure(ifig) if label is not None: if colour is not None: line,=pl.plot(x,y,label=label,color=colour) else: line,=pl.plot(x,y,label=label) pl.legend(loc='best').draw_frame(False) else: if colour is not None: line,=pl.plot(x,y,color=colour) else: line,=pl.plot(x,y) if dashes is not None: line.set_dashes(dashes) if label is not None: pl.legend(loc='best').draw_frame(False) pl.xlim(lims[:2]) pl.ylim(lims[2:]) pl.xlabel('$X_{\\rm c}(\,^4{\\rm He}\,)$') pl.ylabel('$\log\,T_{\\rm eff}$')
Plot effective temperature against central helium abundance. Parameters ---------- ifig : integer or string Figure label, if None the current figure is used The default value is None. lims : list [x_lower, x_upper, y_lower, y_upper] label : string Label for the model The default value is None colour : string The colour of the line The default value is None s2ms : boolean, optional "Skip to Main Sequence" The default is True dashes : list, optional Custom dashing style. If None, ignore. The default is None.
entailment
def tcrhoc(self,ifig=None,lims=[3.,10.,8.,10.],label=None,colour=None, dashes=None): """ Central temperature again central density plot Parameters ---------- ifig : integer or string Figure label, if None the current figure is used The default value is None. lims : list [x_lower, x_upper, y_lower, y_upper] label : string Label for the model The default value is None colour : string The colour of the line The default value is None dashes : list, optional Custom dashing style. If None, ignore. The default is None. """ # fsize=18 # # params = {'axes.labelsize': fsize, # # 'font.family': 'serif', # 'font.family': 'Times New Roman', # 'figure.facecolor': 'white', # 'text.fontsize': fsize, # 'legend.fontsize': fsize, # 'xtick.labelsize': fsize*0.8, # 'ytick.labelsize': fsize*0.8, # 'text.usetex': False} # # try: # pl.rcParams.update(params) # except: # pass if ifig is not None: pl.figure(ifig) if label is not None: if colour is not None: line,=pl.plot(self.get('log_center_Rho'),self.get('log_center_T'),label=label, color=colour) else: line,=pl.plot(self.get('log_center_Rho'),self.get('log_center_T'),label=label) else: if colour is not None: line,=pl.plot(self.get('log_center_Rho'),self.get('log_center_T'), color=colour) else: line,=pl.plot(self.get('log_center_Rho'),self.get('log_center_T')) if dashes is not None: line.set_dashes(dashes) if label is not None: pl.legend(loc='best').draw_frame(False) pl.xlim(lims[:2]) pl.ylim(lims[2:]) pl.xlabel('log $\\rho_{\\rm c}$') pl.ylabel('log $T_{\\rm c}$')
Central temperature again central density plot Parameters ---------- ifig : integer or string Figure label, if None the current figure is used The default value is None. lims : list [x_lower, x_upper, y_lower, y_upper] label : string Label for the model The default value is None colour : string The colour of the line The default value is None dashes : list, optional Custom dashing style. If None, ignore. The default is None.
entailment
def mdot_t(self,ifig=None,lims=[7.4,2.6,-8.5,-4.5],label=None,colour=None,s2ms=False, dashes=None): """ Plot mass loss history as a function of log-time-left Parameters ---------- ifig : integer or string Figure label, if None the current figure is used The default value is None. lims : list [x_lower, x_upper, y_lower, y_upper] label : string Label for the model The default value is None colour : string The colour of the line The default value is None s2ms : boolean, optional "skip to main sequence" dashes : list, optional Custom dashing style. If None, ignore. The default is None. """ fsize=18 params = {'axes.labelsize': fsize, # 'font.family': 'serif', 'font.family': 'Times New Roman', 'figure.facecolor': 'white', 'text.fontsize': fsize, 'legend.fontsize': fsize, 'xtick.labelsize': fsize*0.8, 'ytick.labelsize': fsize*0.8, 'text.usetex': False} try: pl.rcParams.update(params) except: pass if ifig is not None: pl.figure(ifig) if s2ms: h1=self.get('center_h1') idx=np.where(h1[0]-h1>=3.e-3)[0][0] skip=idx else: skip=0 gage= self.get('star_age') lage=np.zeros(len(gage)) agemin = max(old_div(abs(gage[-1]-gage[-2]),5.),1.e-10) for i in np.arange(len(gage)): if gage[-1]-gage[i]>agemin: lage[i]=np.log10(gage[-1]-gage[i]+agemin) else : lage[i]=np.log10(agemin) x = lage[skip:] y = self.get('log_abs_mdot')[skip:] if ifig is not None: pl.figure(ifig) if label is not None: if colour is not None: line,=pl.plot(x,y,label=label,color=colour) else: line,=pl.plot(x,y,label=label) else: if colour is not None: line,=pl.plot(x,y,color=colour) else: line,=pl.plot(x,y) if dashes is not None: line.set_dashes(dashes) if label is not None: pl.legend(loc='best').draw_frame(False) pl.xlim(lims[:2]) pl.ylim(lims[2:]) pl.ylabel('$\mathrm{log}_{10}(\|\dot{M}\|/M_\odot\,\mathrm{yr}^{-1})$') pl.xlabel('$\mathrm{log}_{10}(t^*/\mathrm{yr})$')
Plot mass loss history as a function of log-time-left Parameters ---------- ifig : integer or string Figure label, if None the current figure is used The default value is None. lims : list [x_lower, x_upper, y_lower, y_upper] label : string Label for the model The default value is None colour : string The colour of the line The default value is None s2ms : boolean, optional "skip to main sequence" dashes : list, optional Custom dashing style. If None, ignore. The default is None.
entailment
def mcc_t(self,ifig=None,lims=[0,15,0,25],label=None,colour=None, mask=False,s2ms=False,dashes=None): """ Plot mass of [oclark01@scandium 15M_led_f_print_nets]$ cp ../15M_led_f_ppcno/ective core as a function of time. Parameters ---------- ifig : integer or string Figure label, if None the current figure is used The default value is None. lims : list [x_lower, x_upper, y_lower, y_upper] label : string Label for the model The default value is None colour : string The colour of the line The default value is None mask : boolean, optional Do you want to try to hide numerical spikes in the plot? The default is False s2ms : boolean, optional skip to main squence? dashes : list, optional Custom dashing style. If None, ignore. The default is None. """ fsize=18 params = {'axes.labelsize': fsize, # 'font.family': 'serif', 'font.family': 'Times New Roman', 'figure.facecolor': 'white', 'text.fontsize': fsize, 'legend.fontsize': fsize, 'xtick.labelsize': fsize*0.8, 'ytick.labelsize': fsize*0.8, 'text.usetex': False} try: pl.rcParams.update(params) except: pass if ifig is not None: pl.figure(ifig) if s2ms: h1=self.get('center_h1') idx=np.where(h1[0]-h1>=3.e-3)[0][0] skip=idx else: skip=0 age= self.get('star_age') x1 = old_div(age, 1.e6) x2 = old_div(age, 1.e6) y1 = self.get('mix_qtop_1')*self.get('star_mass') y2 = self.get('mix_qtop_2')*self.get('star_mass') mt1 = self.get('mix_type_1') mt2 = self.get('mix_type_2') x1 = x1[skip:] x2 = x2[skip:] y1 = y1[skip:] y2 = y2[skip:] mt1 = mt1[skip:] mt2 = mt2[skip:] # Mask spikes... if mask: x1 = np.ma.masked_where(mt1 != 1, x1) x2 = np.ma.masked_where(mt2 != 1, x2) y1 = np.ma.masked_where(mt1 != 1, y1) y2 = np.ma.masked_where(mt2 != 1, y2) if ifig is not None: pl.figure(ifig) if label is not None: if colour is not None: line,=pl.plot(x1,y1,label=label,color=colour) line,=pl.plot(x2,y2,color=colour) else: line,=pl.plot(x1,y1,label=label) line,=pl.plot(x2,y2) else: if colour is not None: line,=pl.plot(x1,y1,color=colour) line,=pl.plot(x2,y2,color=colour) else: line,=pl.plot(x1,y1) line,=pl.plot(x2,y2) if dashes is not None: line.set_dashes(dashes) if label is not None: pl.legend(loc='best').draw_frame(False) pl.xlim(lims[:2]) pl.ylim(lims[2:]) pl.ylabel('$M/M_\odot}$') pl.xlabel('$t/{\\rm Myr}$')
Plot mass of [oclark01@scandium 15M_led_f_print_nets]$ cp ../15M_led_f_ppcno/ective core as a function of time. Parameters ---------- ifig : integer or string Figure label, if None the current figure is used The default value is None. lims : list [x_lower, x_upper, y_lower, y_upper] label : string Label for the model The default value is None colour : string The colour of the line The default value is None mask : boolean, optional Do you want to try to hide numerical spikes in the plot? The default is False s2ms : boolean, optional skip to main squence? dashes : list, optional Custom dashing style. If None, ignore. The default is None.
entailment
def kippenhahn_CO(self, num_frame, xax, t0_model=0, title='Kippenhahn diagram', tp_agb=0., ylim_CO=[0,0]): """ Kippenhahn plot as a function of time or model with CO ratio Parameters ---------- num_frame : integer Number of frame to plot this plot into. xax : string Either model or time to indicate what is to be used on the x-axis. t0_model : integer, optional Model for the zero point in time, for AGB plots this would be usually the model of the 1st TP, which can be found with the Kippenhahn plot. The default is 0. title : string, optional Figure title. The defalut is "Kippenhahn diagram". tp_agb : float, optional If >= 0 then, ylim=[h1_min*1.-tp_agb/100 : h1_max*1.+tp_agb/100] with h1_min, h1_max the min and max H-free core mass coordinate. The defalut is 0. ylim_CO : list if ylim_CO is [0,0], then it is automaticly set. The default is [0,0]. """ pyl.figure(num_frame) if xax == 'time': xaxisarray = self.get('star_age') elif xax == 'model': xaxisarray = self.get('model_number') else: print('kippenhahn_error: invalid string for x-axis selction.'+\ ' needs to be "time" or "model"') t0_mod=xaxisarray[t0_model] plot_bounds=True try: h1_boundary_mass = self.get('h1_boundary_mass') he4_boundary_mass = self.get('he4_boundary_mass') except: try: h1_boundary_mass = self.get('he_core_mass') he4_boundary_mass = self.get('c_core_mass') except: plot_bounds=False star_mass = self.get('star_mass') mx1_bot = self.get('mx1_bot')*star_mass mx1_top = self.get('mx1_top')*star_mass mx2_bot = self.get('mx2_bot')*star_mass mx2_top = self.get('mx2_top')*star_mass surface_c12 = self.get('surface_c12') surface_o16 = self.get('surface_o16') COratio=old_div((surface_c12*4.),(surface_o16*3.)) pyl.plot(xaxisarray[t0_model:]-t0_mod,COratio[t0_model:],'-k',label='CO ratio') pyl.ylabel('C/O ratio') pyl.legend(loc=4) if ylim_CO[0] is not 0 and ylim_CO[1] is not 0: pyl.ylim(ylim_CO) if xax == 'time': pyl.xlabel('t / yrs') elif xax == 'model': pyl.xlabel('model number') pyl.twinx() if plot_bounds: pyl.plot(xaxisarray[t0_model:]-t0_mod,h1_boundary_mass[t0_model:],label='h1_boundary_mass') pyl.plot(xaxisarray[t0_model:]-t0_mod,he4_boundary_mass[t0_model:],label='he4_boundary_mass') pyl.plot(xaxisarray[t0_model:]-t0_mod,mx1_bot[t0_model:],',r',label='conv bound') pyl.plot(xaxisarray[t0_model:]-t0_mod,mx1_top[t0_model:],',r') pyl.plot(xaxisarray[t0_model:]-t0_mod,mx2_bot[t0_model:],',r') pyl.plot(xaxisarray[t0_model:]-t0_mod,mx2_top[t0_model:],',r') pyl.plot(xaxisarray[t0_model:]-t0_mod,star_mass[t0_model:],label='star_mass') pyl.ylabel('mass coordinate') pyl.legend(loc=2) if tp_agb > 0.: h1_min = min(h1_boundary_mass[t0_model:]) h1_max = max(h1_boundary_mass[t0_model:]) h1_min = h1_min*(1.-old_div(tp_agb,100.)) h1_max = h1_max*(1.+old_div(tp_agb,100.)) print('setting ylim to zoom in on H-burning:',h1_min,h1_max) pyl.ylim(h1_min,h1_max)
Kippenhahn plot as a function of time or model with CO ratio Parameters ---------- num_frame : integer Number of frame to plot this plot into. xax : string Either model or time to indicate what is to be used on the x-axis. t0_model : integer, optional Model for the zero point in time, for AGB plots this would be usually the model of the 1st TP, which can be found with the Kippenhahn plot. The default is 0. title : string, optional Figure title. The defalut is "Kippenhahn diagram". tp_agb : float, optional If >= 0 then, ylim=[h1_min*1.-tp_agb/100 : h1_max*1.+tp_agb/100] with h1_min, h1_max the min and max H-free core mass coordinate. The defalut is 0. ylim_CO : list if ylim_CO is [0,0], then it is automaticly set. The default is [0,0].
entailment
def kippenhahn(self, num_frame, xax, t0_model=0, title='Kippenhahn diagram', tp_agb=0., t_eps=5.e2, plot_star_mass=True, symbol_size=8, c12_bm=False, print_legend=True): """Kippenhahn plot as a function of time or model. Parameters ---------- num_frame : integer Number of frame to plot this plot into, if <0 open no new figure. xax : string Either 'model', 'time' or 'logtimerev' to indicate what is to be used on the x-axis. t0_model : integer, optional If xax = 'time' then model for the zero point in time, for AGB plots this would be usually the model of the 1st TP, which can be found with the Kippenhahn plot. The default is 0. title : string, optional The figure title. The default is "Kippenhahn diagram". tp_agb : float, optional If > 0. then, ylim=[h1_min*1.-tp_agb/100 : h1_max*1.+tp_agb/100] with h1_min, h1_max the min and max H-free core mass coordinate. The default is 0. . t_eps : float, optional Final time for logtimerev. The default is '5.e2'. plot_star_mass : boolean, optional If True, then plot the stellar mass as a line as well. The default is True. symbol_size : integer, optional Size of convection boundary marker. The default is 8. c12_bm : boolean, optional If we plot c12_boundary_mass or not. The default is False. print_legend : boolean, optionla Show or do not show legend. The defalut is True. """ if num_frame >= 0: pyl.figure(num_frame) t0_mod=[] if xax == 'time': xaxisarray = self.get('star_age') if t0_model > 0: ind=self.get('model_number') t0_model=where(ind>t0_model)[0][0] t0_mod=xaxisarray[t0_model] else: t0_mod = 0. print('zero time is '+str(t0_mod)) elif xax == 'model': xaxisarray = self.get('model_number') #t0_mod=xaxisarray[t0_model] t0_mod = 0. elif xax == 'logtimerev': xaxi = self.get('star_age') xaxisarray = np.log10(np.max(xaxi)+t_eps-xaxi) t0_mod = 0. else: print('kippenhahn_error: invalid string for x-axis selction.'+\ ' needs to be "time" or "model"') plot_bounds=True try: h1_boundary_mass = self.get('h1_boundary_mass') he4_boundary_mass = self.get('he4_boundary_mass') if c12_bm: c12_boundary_mass = self.get('c12_boundary_mass') except: try: h1_boundary_mass = self.get('he_core_mass') he4_boundary_mass = self.get('c_core_mass') if c12_bm: c12_boundary_mass = self.get('o_core_mass') except: plot_bounds=False star_mass = self.get('star_mass') mx1_bot = self.get('mx1_bot')*star_mass mx1_top = self.get('mx1_top')*star_mass mx2_bot = self.get('mx2_bot')*star_mass mx2_top = self.get('mx2_top')*star_mass if xax == 'time': if t0_model>0: pyl.xlabel('$t - t_0$ $\mathrm{[yr]}$') else: pyl.xlabel('t / yrs') elif xax == 'model': pyl.xlabel('model number') elif xax == 'logtimerev': pyl.xlabel('$\log(t_{final} - t)$ $\mathrm{[yr]}$') pyl.plot(xaxisarray[t0_model:]-t0_mod,mx1_bot[t0_model:],linestyle='None',color='blue',alpha=0.3,marker='o',markersize=symbol_size,label='convection zones') pyl.plot(xaxisarray[t0_model:]-t0_mod,mx1_top[t0_model:],linestyle='None',color='blue',alpha=0.3,marker='o',markersize=symbol_size) pyl.plot(xaxisarray[t0_model:]-t0_mod,mx2_bot[t0_model:],linestyle='None',color='blue',alpha=0.3,marker='o',markersize=symbol_size) pyl.plot(xaxisarray[t0_model:]-t0_mod,mx2_top[t0_model:],linestyle='None',color='blue',alpha=0.3,marker='o',markersize=symbol_size) if plot_bounds: pyl.plot(xaxisarray[t0_model:]-t0_mod,h1_boundary_mass[t0_model:],color='red',linewidth=2,label='H-free core') pyl.plot(xaxisarray[t0_model:]-t0_mod,he4_boundary_mass[t0_model:],color='green',linewidth=2,linestyle='dashed',label='He-free core') if c12_bm: pyl.plot(xaxisarray[t0_model:]-t0_mod,c12_boundary_mass[t0_model:],color='purple',linewidth=2,linestyle='dotted',label='C-free core') if plot_star_mass is True: pyl.plot(xaxisarray[t0_model:]-t0_mod,star_mass[t0_model:],label='$M_\star$') pyl.ylabel('$m_\mathrm{r}/\mathrm{M}_\odot$') if print_legend: pyl.legend(loc=2) if tp_agb > 0.: h1_min = min(h1_boundary_mass[t0_model:]) h1_max = max(h1_boundary_mass[t0_model:]) h1_min = h1_min*(1.-old_div(tp_agb,100.)) h1_max = h1_max*(1.+old_div(tp_agb,100.)) print('setting ylim to zoom in on H-burning:',h1_min,h1_max) pyl.ylim(h1_min,h1_max)
Kippenhahn plot as a function of time or model. Parameters ---------- num_frame : integer Number of frame to plot this plot into, if <0 open no new figure. xax : string Either 'model', 'time' or 'logtimerev' to indicate what is to be used on the x-axis. t0_model : integer, optional If xax = 'time' then model for the zero point in time, for AGB plots this would be usually the model of the 1st TP, which can be found with the Kippenhahn plot. The default is 0. title : string, optional The figure title. The default is "Kippenhahn diagram". tp_agb : float, optional If > 0. then, ylim=[h1_min*1.-tp_agb/100 : h1_max*1.+tp_agb/100] with h1_min, h1_max the min and max H-free core mass coordinate. The default is 0. . t_eps : float, optional Final time for logtimerev. The default is '5.e2'. plot_star_mass : boolean, optional If True, then plot the stellar mass as a line as well. The default is True. symbol_size : integer, optional Size of convection boundary marker. The default is 8. c12_bm : boolean, optional If we plot c12_boundary_mass or not. The default is False. print_legend : boolean, optionla Show or do not show legend. The defalut is True.
entailment
def t_surfabu(self, num_frame, xax, t0_model=0, title='surface abundance', t_eps=1.e-3, plot_CO_ratio=False): """ t_surfabu plots surface abundance evolution as a function of time. Parameters ---------- num_frame : integer Number of frame to plot this plot into, if <0 don't open figure. xax : string Either model, time or logrevtime to indicate what is to be used on the x-axis. t0_model : integer, optional Model for the zero point in time, for AGB plots this would be usually the model of the 1st TP, which can be found with the Kippenhahn plot. The default is 0. title : string, optional Figure title. The default is "surface abundance". t_eps : float, optional Time eps at end for logrevtime. The default is 1.e-3. plot_CO_ratio : boolean, optional On second axis True/False. The default is False. """ if num_frame >= 0: pyl.figure(num_frame) if xax == 'time': xaxisarray = self.get('star_age')[t0_model:] elif xax == 'model': xaxisarray = self.get('model_number')[t0_model:] elif xax == 'logrevtime': xaxisarray = self.get('star_age') xaxisarray=np.log10(max(xaxisarray[t0_model:])+t_eps-xaxisarray[t0_model:]) else: print('t-surfabu error: invalid string for x-axis selction.'+ \ ' needs to be "time" or "model"') star_mass = self.get('star_mass') surface_c12 = self.get('surface_c12') surface_c13 = self.get('surface_c13') surface_n14 = self.get('surface_n14') surface_o16 = self.get('surface_o16') target_n14 = -3.5 COratio=old_div((surface_c12*4.),(surface_o16*3.)) t0_mod=xaxisarray[t0_model] log10_c12=np.log10(surface_c12[t0_model:]) symbs=['k:','-','--','-.','b:','-','--','k-.',':','-','--','-.'] pyl.plot(xaxisarray,log10_c12,\ symbs[0],label='$^{12}\mathrm{C}$') pyl.plot(xaxisarray,np.log10(surface_c13[t0_model:]),\ symbs[1],label='$^{13}\mathrm{C}$') pyl.plot(xaxisarray,np.log10(surface_n14[t0_model:]),\ symbs[2],label='$^{14}\mathrm{N}$') pyl.plot(xaxisarray,np.log10(surface_o16[t0_model:]),\ symbs[3],label='$^{16}\mathrm{O}$') # pyl.plot([min(xaxisarray[t0_model:]-t0_mod),max(xaxisarray[t0_model:]-t0_mod)],[target_n14,target_n14]) pyl.ylabel('mass fraction $\log X$') pyl.legend(loc=2) if xax == 'time': pyl.xlabel('t / yrs') elif xax == 'model': pyl.xlabel('model number') elif xax == 'logrevtime': pyl.xlabel('$\\log t-tfinal$') if plot_CO_ratio: pyl.twinx() pyl.plot(xaxisarray,COratio[t0_model:],'-k',label='CO ratio') pyl.ylabel('C/O ratio') pyl.legend(loc=4) pyl.title(title) if xax == 'logrevtime': self._xlimrev()
t_surfabu plots surface abundance evolution as a function of time. Parameters ---------- num_frame : integer Number of frame to plot this plot into, if <0 don't open figure. xax : string Either model, time or logrevtime to indicate what is to be used on the x-axis. t0_model : integer, optional Model for the zero point in time, for AGB plots this would be usually the model of the 1st TP, which can be found with the Kippenhahn plot. The default is 0. title : string, optional Figure title. The default is "surface abundance". t_eps : float, optional Time eps at end for logrevtime. The default is 1.e-3. plot_CO_ratio : boolean, optional On second axis True/False. The default is False.
entailment
def t_lumi(self,num_frame,xax): """ Luminosity evolution as a function of time or model. Parameters ---------- num_frame : integer Number of frame to plot this plot into. xax : string Either model or time to indicate what is to be used on the x-axis """ pyl.figure(num_frame) if xax == 'time': xaxisarray = self.get('star_age') elif xax == 'model': xaxisarray = self.get('model_number') else: print('kippenhahn_error: invalid string for x-axis selction. needs to be "time" or "model"') logLH = self.get('log_LH') logLHe = self.get('log_LHe') pyl.plot(xaxisarray,logLH,label='L_(H)') pyl.plot(xaxisarray,logLHe,label='L(He)') pyl.ylabel('log L') pyl.legend(loc=2) if xax == 'time': pyl.xlabel('t / yrs') elif xax == 'model': pyl.xlabel('model number')
Luminosity evolution as a function of time or model. Parameters ---------- num_frame : integer Number of frame to plot this plot into. xax : string Either model or time to indicate what is to be used on the x-axis
entailment
def t_surf_parameter(self, num_frame, xax): """ Surface parameter evolution as a function of time or model. Parameters ---------- num_frame : integer Number of frame to plot this plot into. xax : string Either model or time to indicate what is to be used on the x-axis """ pyl.figure(num_frame) if xax == 'time': xaxisarray = self.get('star_age') elif xax == 'model': xaxisarray = self.get('model_number') else: print('kippenhahn_error: invalid string for x-axis selction. needs to be "time" or "model"') logL = self.get('log_L') logTeff = self.get('log_Teff') pyl.plot(xaxisarray,logL,'-k',label='log L') pyl.plot(xaxisarray,logTeff,'-k',label='log Teff') pyl.ylabel('log L, log Teff') pyl.legend(loc=2) if xax == 'time': pyl.xlabel('t / yrs') elif xax == 'model': pyl.xlabel('model number')
Surface parameter evolution as a function of time or model. Parameters ---------- num_frame : integer Number of frame to plot this plot into. xax : string Either model or time to indicate what is to be used on the x-axis
entailment
def _kip_vline(self, modstart, modstop, sparse, outfile, xlims=[0.,0.], ylims=[0.,0.], ixaxis='log_time_left', mix_zones=5, burn_zones=50): """ *** DEPRECIATED and hence UNSUPPORTED *** This function creates a Kippenhahn plot with energy flux using vertical lines, better thermal pulse resolution. For a more comprehensive plot, your history.data or star.log file should contain columns called "mix_type_n", "mix_qtop_n", "burn_type_n" and "burn_qtop_n". The number of columns (i.e. the bbiggest value of n) is what goes in the arguments as mix_zones and burn_zones. DO NOT WORRY! if you do not have these columns, just leave the default values alone and the script should recognise that you do not have these columns and make the most detailed plot that is available to you. Parameters ---------- modstart : integer Model from which you want to plot (be careful if your history.data or star.log output is sparse...). modstop : integer Model to which you wish to plot. sparse : integer x-axis sparsity. outfile : string 'filename + extension' where you want to save the figure. xlims, ylims : list, optional plot limits, however these are somewhat obsolete now that we have modstart and modstop. Leaving them as 0. is probably no slower, and you can always zoom in afterwards in mpl. The default is [0., 0.,]. ixaxis : string, optional Either 'log_time_left', 'age', or 'model_number'. The default "log_time_left". mix_zones, burn_zones : integer As described above, if you have more detailed output about your convection and energy generation boundaries in columns mix_type_n, mix_qtop_n, burn_type_n and burn_qtop_n, you need to specify the total number of columns for mixing zones and burning zones that you have. Can't work this out from your history.data or star.log file? Check the history_columns.list that you used, it'll be the number after "mixing regions" and "burning regions". Can't see these columns? leave it and 2 conv zones and 2 burn zones will be drawn using other data that you certainly should have in your history.data or star.log file. The default for mix_zones is 5, the defalut for burn_zones is 50. """ xxyy=[self.get('star_age')[modstart:modstop],self.get('star_age')[modstart:modstop]] mup = max(float(self.get('star_mass')[0])*1.02,1.0) nmodels=len(self.get('model_number')[modstart:modstop]) Msol=1.98892E+33 engenstyle = 'full' dx = sparse x = np.arange(0, nmodels, dx) btypemax = 20 btypemin = -20 btypealpha=0. ######################################################################## #----------------------------------plot--------------------------------# fig = pl.figure() # fig.set_size_inches(16,9) fsize=15 ax=pl.axes() if ixaxis == 'log_time_left': # log of time left until core collapse gage= self.get('star_age') lage=np.zeros(len(gage)) agemin = max(old_div(abs(gage[-1]-gage[-2]),5.),1.e-10) for i in np.arange(len(gage)): if gage[-1]-gage[i]>agemin: lage[i]=np.log10(gage[-1]-gage[i]+agemin) else : lage[i]=np.log10(agemin) xxx = lage[modstart:modstop] print('plot versus time left') ax.set_xlabel('$\mathrm{log}_{10}(t^*) \, \mathrm{(yr)}$',fontsize=fsize) elif ixaxis =='model_number': xxx= self.get('model_number')[modstart:modstop] print('plot versus model number') ax.set_xlabel('Model number',fontsize=fsize) elif ixaxis =='age': xxx= old_div(self.get('star_age')[modstart:modstop],1.e6) print('plot versus age') ax.set_xlabel('Age [Myr]',fontsize=fsize) else: print('ixaxis must be one of: log_time_left, age or model_number') sys.exit() if xlims == [0.,0.]: xlims[0] = xxx[0] xlims[1] = xxx[-1] if ylims == [0.,0.]: ylims[0] = 0. ylims[1] = mup print('plotting patches') ax.plot(xxx[::dx],self.get('star_mass')[modstart:modstop][::dx],'k-') print('plotting abund boundaries') ax.plot(xxx,self.get('h1_boundary_mass')[modstart:modstop],label='H boundary') ax.plot(xxx,self.get('he4_boundary_mass')[modstart:modstop],label='He boundary') # ax.plot(xxx,self.get('c12_boundary_mass')[modstart:modstop],label='C boundary') ax.axis([xlims[0],xlims[1],ylims[0],ylims[1]]) ax.set_ylabel('Mass [M$_\odot$]') ######################################################################## try: self.get('burn_qtop_1') except: engenstyle = 'twozone' old_percent = 0 if engenstyle == 'full': for i in range(len(x)): # writing status percent = int(i*100/(len(x) - 1)) if percent >= old_percent + 5: sys.stdout.flush() sys.stdout.write("\r creating color map1 " + "...%d%%" % percent) old_percent = percent for j in range(1,burn_zones+1): ulimit=self.get('burn_qtop_'+str(j))[modstart:modstop][i*dx]*self.get('star_mass')[modstart:modstop][i*dx] if j==1: llimit=0.0 else: llimit=self.get('burn_qtop_'+str(j-1))[modstart:modstop][i*dx]*self.get('star_mass')[modstart:modstop][i*dx] btype=float(self.get('burn_type_'+str(j))[modstart:modstop][i*dx]) if llimit!=ulimit: if btype>0.: #btypealpha = btype/btypemax #ax.axvline(xxx[i*dx],ymin=(llimit-ylims[0])/(ylims[1]-ylims[0]),ymax=(ulimit-ylims[0])/(ylims[1]-ylims[0]),color='b',alpha=btypealpha) pass if btype<0.: #btypealpha = (btype/btypemin)/5 #ax.axvline(xxx[i*dx],ymin=(llimit-ylims[0])/(ylims[1]-ylims[0]),ymax=(ulimit-ylims[0])/(ylims[1]-ylims[0]),color='r',alpha=btypealpha) pass print(' \n') old_percent = 0 if engenstyle == 'twozone': for i in range(len(x)): # writing status percent = int(i*100/(len(x) - 1)) if percent >= old_percent + 5: sys.stdout.flush() sys.stdout.write("\r creating color map1 " + "...%d%%" % percent) old_percent = percent llimitl1=old_div(self.get('epsnuc_M_1')[modstart:modstop][i*dx],Msol) ulimitl1=old_div(self.get('epsnuc_M_4')[modstart:modstop][i*dx],Msol) llimitl2=old_div(self.get('epsnuc_M_5')[modstart:modstop][i*dx],Msol) ulimitl2=old_div(self.get('epsnuc_M_8')[modstart:modstop][i*dx],Msol) llimith1=old_div(self.get('epsnuc_M_2')[modstart:modstop][i*dx],Msol) ulimith1=old_div(self.get('epsnuc_M_3')[modstart:modstop][i*dx],Msol) llimith2=old_div(self.get('epsnuc_M_6')[modstart:modstop][i*dx],Msol) ulimith2=old_div(self.get('epsnuc_M_7')[modstart:modstop][i*dx],Msol) # lower thresh first, then upper thresh: #if llimitl1!=ulimitl1: #ax.axvline(xxx[i*dx],ymin=(llimitl1-ylims[0])/(ylims[1]-ylims[0]),ymax=(ulimitl1-ylims[0])/(ylims[1]-ylims[0]),color='b',alpha=1.) #if llimitl2!=ulimitl2: #ax.axvline(xxx[i*dx],ymin=(llimitl2-ylims[0])/(ylims[1]-ylims[0]),ymax=(ulimitl2-ylims[0])/(ylims[1]-ylims[0]),color='b',alpha=1.) #if llimith1!=ulimith1: #ax.axvline(xxx[i*dx],ymin=(llimith1-ylims[0])/(ylims[1]-ylims[0]),ymax=(ulimith1-ylims[0])/(ylims[1]-ylims[0]),color='b',alpha=4.) #if llimith2!=ulimith2: #ax.axvline(xxx[i*dx],ymin=(llimith2-ylims[0])/(ylims[1]-ylims[0]),ymax=(ulimith2-ylims[0])/(ylims[1]-ylims[0]),color='b',alpha=4.) print(' \n') mixstyle = 'full' try: self.get('mix_qtop_1') except: mixstyle = 'twozone' old_percent = 0 if mixstyle == 'full': for i in range(len(x)): # writing reading status percent = int(i*100/(len(x) - 1)) if percent >= old_percent + 5: sys.stdout.flush() sys.stdout.write("\r creating color map2 " + "...%d%%" % percent) old_percent = percent for j in range(1,mix_zones+1): ulimit=self.get('mix_qtop_'+str(j))[modstart:modstop][i*dx]*self.get('star_mass')[modstart:modstop][i*dx] if j==1: llimit=0.0 else: llimit=self.get('mix_qtop_'+str(j-1))[modstart:modstop][i*dx]*self.get('star_mass')[modstart:modstop][i*dx] mtype=self.get('mix_type_'+str(j))[modstart:modstop][i*dx] if llimit!=ulimit: if mtype == 1: ax.axvline(xxx[i*dx],ymin=old_div((llimit-ylims[0]),(ylims[1]-ylims[0])),ymax=old_div((ulimit-ylims[0]),(ylims[1]-ylims[0])),color='k',alpha=3., linewidth=.5) print(' \n') old_percent = 0 if mixstyle == 'twozone': for i in range(len(x)): # writing reading status percent = int(i*100/(len(x) - 1)) if percent >= old_percent + 5: sys.stdout.flush() sys.stdout.write("\r creating color map2 " + "...%d%%" % percent) old_percent = percent ulimit=self.get('conv_mx1_top')[modstart:modstop][i*dx]*self.get('star_mass')[modstart:modstop][i*dx] llimit=self.get('conv_mx1_bot')[modstart:modstop][i*dx]*self.get('star_mass')[modstart:modstop][i*dx] if llimit!=ulimit: ax.axvline(xxx[i*dx],ymin=old_div((llimit-ylims[0]),(ylims[1]-ylims[0])),ymax=old_div((ulimit-ylims[0]),(ylims[1]-ylims[0])),color='k',alpha=5.,linewidth=.5) ulimit=self.get('conv_mx2_top')[modstart:modstop][i*dx]*self.get('star_mass')[modstart:modstop][i*dx] llimit=self.get('conv_mx2_bot')[modstart:modstop][i*dx]*self.get('star_mass')[modstart:modstop][i*dx] if llimit!=ulimit: ax.axvline(xxx[i*dx],ymin=old_div((llimit-ylims[0]),(ylims[1]-ylims[0])),ymax=old_div((ulimit-ylims[0]),(ylims[1]-ylims[0])),color='k',alpha=3.,linewidth=.5) print(' \n') print('engenstyle was ', engenstyle) print('mixstyle was ', mixstyle) print('\n finished preparing color map') #fig.savefig(outfile) pl.show()
*** DEPRECIATED and hence UNSUPPORTED *** This function creates a Kippenhahn plot with energy flux using vertical lines, better thermal pulse resolution. For a more comprehensive plot, your history.data or star.log file should contain columns called "mix_type_n", "mix_qtop_n", "burn_type_n" and "burn_qtop_n". The number of columns (i.e. the bbiggest value of n) is what goes in the arguments as mix_zones and burn_zones. DO NOT WORRY! if you do not have these columns, just leave the default values alone and the script should recognise that you do not have these columns and make the most detailed plot that is available to you. Parameters ---------- modstart : integer Model from which you want to plot (be careful if your history.data or star.log output is sparse...). modstop : integer Model to which you wish to plot. sparse : integer x-axis sparsity. outfile : string 'filename + extension' where you want to save the figure. xlims, ylims : list, optional plot limits, however these are somewhat obsolete now that we have modstart and modstop. Leaving them as 0. is probably no slower, and you can always zoom in afterwards in mpl. The default is [0., 0.,]. ixaxis : string, optional Either 'log_time_left', 'age', or 'model_number'. The default "log_time_left". mix_zones, burn_zones : integer As described above, if you have more detailed output about your convection and energy generation boundaries in columns mix_type_n, mix_qtop_n, burn_type_n and burn_qtop_n, you need to specify the total number of columns for mixing zones and burning zones that you have. Can't work this out from your history.data or star.log file? Check the history_columns.list that you used, it'll be the number after "mixing regions" and "burning regions". Can't see these columns? leave it and 2 conv zones and 2 burn zones will be drawn using other data that you certainly should have in your history.data or star.log file. The default for mix_zones is 5, the defalut for burn_zones is 50.
entailment
def kip_cont(self, ifig=110, modstart=0, modstop=-1,t0_model=0, outfile='out.png', xlims=None, ylims=None, xres=1000, yres=1000, ixaxis='model_number', mix_zones=20, burn_zones=20, plot_radius=False, engenPlus=True, engenMinus=False, landscape_plot=False, rad_lines=False, profiles=[], showfig=True, outlines=True, boundaries=True, c12_boundary=False, rasterise=False, yscale='1.', engenlevels=None,CBM=False,fsize=14): """ This function creates a Kippenhahn plot with energy flux using contours. This plot uses mixing_regions and burning_regions written to your history.data or star.log. Set both variables in the log_columns.list file to 20 as a start. The output log file should then contain columns called "mix_type_n", "mix_qtop_n", "burn_type_n" and "burn_qtop_n". The number of columns (i.e. the biggest value of n) is what goes in the arguments as mix_zones and burn_zones. DO NOT WORRY! if you do not have these columns, just leave the default values alone and the script should recognise that you do not have these columns and make the most detailed plot that is available to you. Defaults are set to get some plot, that may not look great if you zoom in interactively. Play with xres and yres as well as setting the xlims to ylims to the region you are interested in. Parameters ---------- ifig : integer, optional Figure frame number. The default is 110. modstart : integer, optional Model from which you want to plot (be careful if your history.data or star.log output is sparse...). If it is 0 then it starts from the beginning, works even if log_cnt > 1. The default is 0. modstop : integer, optional Model to which you wish to plot, -1 corresponds to end [if log_cnt>1, devide modstart and modstop by log_cnt, this needs to be improved! SJ: this should be ficed now]. The defalut is -1. t0_model : integer, optional Model number from which to reset the time to 0. Typically, if modstart!=0, t0_model=modstart is a good choice, but we leave the choice to the user in case the time is wished to start from 0 at a different key point of the evolution. The default value is 0. outfile : sting, optional 'filename + extension' where you want to save the figure. The defalut is "out.png". xlims, ylims : list, optional Plot limits, however these are somewhat obsolete now that we have modstart and modstop. Leaving them as 0. is probably no slower, and you can always zoom in afterwards in mpl. ylims is important for well resolved thermal pulse etc plots; it's best to get the upper and lower limits of he-intershell using s.kippenhahn_CO(1,'model') first. The default is [0., 0.]. xres, yres : integer, optional plot resolution. Needless to say that increasing these values will yield a nicer plot with some slow-down in plotting time. You will most commonly change xres. For a prelim plot, try xres~200, then bump it up to anywhere from 1000-10000 for real nicely resolved, publication quality plots. The default is 1000. ixaxis : string, optional Either 'log_time_left', 'age', or 'model_number'. The default is "model_number". mix_zones, burn_zones : integer, optional As described above, if you have more detailed output about your convection and energy generation boundaries in columns mix_type_n, mix_qtop_n, burn_type_n and burn_qtop_n, you need to specify the total number of columns for mixing zones and burning zones that you have. Can't work this out from your history.data or star.log file? Check the history_columns.list that you used, it'll be the number after "mixing regions" and "burning regions". Can't see these columns? leave it and 2 conv zones and 2 burn zones will be drawn using other data that you certainly should have in your history.data or star.log file. The defalut for both is 20. plot_radius : boolean, optional Whether on a second y-axis you want to plot the radius of the surface and the he-free core. The default is False. engenPlus : boolean Plot energy generation contours for eps_nuc>0. The default is True. endgenMinus : boolean, optional Plot energy generation contours for eos_nuc<0. The default is True. landscape_plot : boolean, optionla The default is False. rad_lines : boolean, optional The deafault is False. profiles : list, optional The default is []. showfig : boolean, optional The default is True. outlines : boolean, optional Whether or not to plot outlines of conv zones in darker colour. boundaries : boolean, optional Whether or not to plot H-, He- and C-free boundaries. c12_boundary : boolean, optional The default is False. rasterise : boolean, optional Whether or not to rasterise the contour regions to make smaller vector graphics figures. The default is False. yscale : string, optional Re-scale the y-axis by this amount engenlevels : list Give cusstom levels to the engenPlus contour. If None, the levels are chosen automatically. The default is None. CBM : boolean, optional plot contours for where CBM is active? fsize : integer font size for labels Notes ----- The parameter xlims is depricated. """ if ylims is None: ylims=[0.,0.] if xlims is None: xlims=[0.,0.] # Find correct modstart and modstop: mod=np.array([int(i) for i in self.get('model_number')]) mod1=np.abs(mod-modstart).argmin() mod2=np.abs(mod-modstop).argmin() if modstart != 0 : modstart=mod1 if modstop != -1 : modstop=mod2 xxyy=[self.get('star_age')[modstart:modstop],self.get('star_age')[modstart:modstop]] mup = max(float(self.get('star_mass')[0])*1.02,1.0) nmodels=len(self.get('model_number')[modstart:modstop]) if ylims == [0.,0.]: mup = max(float(self.get('star_mass')[0])*1.02,1.0) mDOWN = 0. else: mup = ylims[1] mDOWN = ylims[0] # y-axis resolution ny=yres #dy=mup/float(ny) dy = old_div((mup-mDOWN),float(ny)) # x-axis resolution maxpoints=xres dx=int(max(1,old_div(nmodels,maxpoints))) #y = np.arange(0., mup, dy) y = np.arange(mDOWN, mup, dy) x = np.arange(0, nmodels, dx) Msol=1.98892E+33 engenstyle = 'full' B1=np.zeros([len(y),len(x)],float) B2=np.zeros([len(y),len(x)],float) try: self.get('burn_qtop_1') except: engenstyle = 'twozone' if engenstyle == 'full' and (engenPlus == True or engenMinus == True): ulimit_array = np.array([self.get('burn_qtop_'+str(j))[modstart:modstop:dx]*\ self.get('star_mass')[modstart:modstop:dx] for j in range(1,burn_zones+1)]) #ulimit_array = np.around(ulimit_array,decimals=len(str(dy))-2) llimit_array = np.delete(ulimit_array,-1,0) llimit_array = np.insert(ulimit_array,0,0.,0) #llimit_array = np.around(llimit_array,decimals=len(str(dy))-2) btype_array = np.array([self.get('burn_type_'+str(j))[modstart:modstop:dx] for j in range(1,burn_zones+1)]) old_percent = 0 for i in range(len(x)): # writing status percent = int(i*100/(len(x) - 1)) if percent >= old_percent + 5: sys.stdout.flush() sys.stdout.write("\r creating color map burn " + "...%d%%" % percent) old_percent = percent for j in range(burn_zones): if btype_array[j,i] > 0. and abs(btype_array[j,i]) < 99.: B1[(np.abs(y-llimit_array[j][i])).argmin():(np.abs(y-ulimit_array[j][i])).argmin()+1,i] = 10.0**(btype_array[j,i]) elif btype_array[j,i] < 0. and abs(btype_array[j,i]) < 99.: B2[(np.abs(y-llimit_array[j][i])).argmin():(np.abs(y-ulimit_array[j][i])).argmin()+1,i] = 10.0**(abs(btype_array[j,i])) print(' \n') if engenstyle == 'twozone' and (engenPlus == True or engenMinus == True): V=np.zeros([len(y),len(x)],float) old_percent = 0 for i in range(len(x)): # writing status percent = int(i*100/(len(x) - 1)) if percent >= old_percent + 5: sys.stdout.flush() sys.stdout.write("\r creating color map1 " + "...%d%%" % percent) old_percent = percent llimitl1=old_div(self.get('epsnuc_M_1')[modstart:modstop][i*dx],Msol) ulimitl1=old_div(self.get('epsnuc_M_4')[modstart:modstop][i*dx],Msol) llimitl2=old_div(self.get('epsnuc_M_5')[modstart:modstop][i*dx],Msol) ulimitl2=old_div(self.get('epsnuc_M_8')[modstart:modstop][i*dx],Msol) llimith1=old_div(self.get('epsnuc_M_2')[modstart:modstop][i*dx],Msol) ulimith1=old_div(self.get('epsnuc_M_3')[modstart:modstop][i*dx],Msol) llimith2=old_div(self.get('epsnuc_M_6')[modstart:modstop][i*dx],Msol) ulimith2=old_div(self.get('epsnuc_M_7')[modstart:modstop][i*dx],Msol) # lower thresh first, then upper thresh: if llimitl1!=ulimitl1: for k in range(ny): if llimitl1<=y[k] and ulimitl1>y[k]: V[k,i]=10. if llimitl2!=ulimitl2: for k in range(ny): if llimitl2<=y[k] and ulimitl2>y[k]: V[k,i]=10. if llimith1!=ulimith1: for k in range(ny): if llimith1<=y[k] and ulimith1>y[k]: V[k,i]=30. if llimith2!=ulimith2: for k in range(ny): if llimith2<=y[k] and ulimith2>y[k]: V[k,i]=30. print(' \n') mixstyle = 'full' try: self.get('mix_qtop_1') except: mixstyle = 'twozone' if mixstyle == 'full': old_percent = 0 Z=np.zeros([len(y),len(x)],float) if CBM: Zcbm=np.zeros([len(y),len(x)],float) ulimit_array = np.array([self.get('mix_qtop_'+str(j))[modstart:modstop:dx]*self.get('star_mass')[modstart:modstop:dx] for j in range(1,mix_zones+1)]) llimit_array = np.delete(ulimit_array,-1,0) llimit_array = np.insert(ulimit_array,0,0.,0) mtype_array = np.array([self.get('mix_type_'+str(j))[modstart:modstop:dx] for j in range(1,mix_zones+1)]) for i in range(len(x)): # writing status percent = int(i*100/(len(x) - 1)) if percent >= old_percent + 5: sys.stdout.flush() sys.stdout.write("\r creating color map mix " + "...%d%%" % percent) old_percent = percent for j in range(mix_zones): if mtype_array[j,i] == 1.: Z[(np.abs(y-llimit_array[j][i])).argmin():(np.abs(y-ulimit_array[j][i])).argmin()+1,i] = 1. if CBM: if mtype_array[j,i] == 2.: Zcbm[(np.abs(y-llimit_array[j][i])).argmin():(np.abs(y-ulimit_array[j][i])).argmin()+1,i] = 1. print(' \n') if mixstyle == 'twozone': Z=np.zeros([len(y),len(x)],float) old_percent = 0 for i in range(len(x)): # writing reading status # writing status percent = int(i*100/(len(x) - 1)) if percent >= old_percent + 5: sys.stdout.flush() sys.stdout.write("\r creating color map mix " + "...%d%%" % percent) old_percent = percent ulimit=self.get('conv_mx1_top')[modstart:modstop][i*dx]*self.get('star_mass')[modstart:modstop][i*dx] llimit=self.get('conv_mx1_bot')[modstart:modstop][i*dx]*self.get('star_mass')[modstart:modstop][i*dx] if llimit!=ulimit: for k in range(ny): if llimit<=y[k] and ulimit>y[k]: Z[k,i]=1. ulimit=self.get('conv_mx2_top')[modstart:modstop][i*dx]*self.get('star_mass')[modstart:modstop][i*dx] llimit=self.get('conv_mx2_bot')[modstart:modstop][i*dx]*self.get('star_mass')[modstart:modstop][i*dx] if llimit!=ulimit: for k in range(ny): if llimit<=y[k] and ulimit>y[k]: Z[k,i]=1. print(' \n') if rad_lines == True: masses = np.arange(0.1,1.5,0.1) rads=[[],[],[],[],[],[],[],[],[],[],[],[],[],[]] modno=[] for i in range(len(profiles)): p=mesa_profile('./LOGS',profiles[i]) modno.append(p.header_attr['model_number']) for j in range(len(masses)): idx=np.abs(p.get('mass')-masses[j]).argmin() rads[j].append(p.get('radius')[idx]) print('engenstyle was ', engenstyle) print('mixstyle was ', mixstyle) print('\n finished preparing color map') ######################################################################## #----------------------------------plot--------------------------------# fig = pyl.figure(ifig) #fsize=20 if landscape_plot == True: fig.set_size_inches(9,4) pl.gcf().subplots_adjust(bottom=0.2) pl.gcf().subplots_adjust(right=0.85) params = {'axes.labelsize': fsize, 'axes.labelsize': fsize, 'font.size': fsize, 'legend.fontsize': fsize, 'xtick.labelsize': fsize, 'ytick.labelsize': fsize, 'text.usetex': False} pyl.rcParams.update(params) #ax=pl.axes([0.1,0.1,0.9,0.8]) #fig=pl.figure() ax=pl.axes() if ixaxis == 'log_time_left': # log of time left until core collapse gage= self.get('star_age') lage=np.zeros(len(gage)) agemin = max(old_div(abs(gage[-1]-gage[-2]),5.),1.e-10) for i in np.arange(len(gage)): if gage[-1]-gage[i]>agemin: lage[i]=np.log10(gage[-1]-gage[i]+agemin) else : lage[i]=np.log10(agemin) xxx = lage[modstart:modstop] print('plot versus time left') ax.set_xlabel('$ \\log_{10}(t-t_\mathrm{end})\ /\ \mathrm{[yr]}$',fontsize=fsize) if xlims[1] == 0.: xlims = [xxx[0],xxx[-1]] elif ixaxis =='model_number': xxx= self.get('model_number')[modstart:modstop] print('plot versus model number') ax.set_xlabel('Model number',fontsize=fsize) if xlims[1] == 0.: xlims = [self.get('model_number')[modstart],self.get('model_number')[modstop]] elif ixaxis =='age': if t0_model != 0: t0_mod=np.abs(mod-t0_model).argmin() xxx= self.get('star_age')[modstart:modstop] - self.get('star_age')[t0_mod] print('plot versus age') ax.set_xlabel('t - %.5e / [yr]' %self.get('star_age')[modstart],fontsize=fsize) else: xxx= old_div(self.get('star_age')[modstart:modstop],1.e6) ax.set_xlabel('t [Myr]',fontsize=fsize) if xlims[1] == 0.: xlims = [xxx[0],xxx[-1]] ax.set_ylabel('$\mathrm{enclosed\ mass\ /\ [M_\odot]}$',fontsize=fsize) # some stuff for rasterizing only the contour part of the plot, for nice, but light, eps: class ListCollection(Collection): def __init__(self, collections, **kwargs): Collection.__init__(self, **kwargs) self.set_collections(collections) def set_collections(self, collections): self._collections = collections def get_collections(self): return self._collections @allow_rasterization def draw(self, renderer): for _c in self._collections: _c.draw(renderer) def insert_rasterized_contour_plot(c): collections = c.collections for _c in collections: _c.remove() cc = ListCollection(collections, rasterized=True) ax = pl.gca() ax.add_artist(cc) return cc cmapMIX = matplotlib.colors.ListedColormap(['w','#8B8386']) # rose grey if CBM: cmapCBM = matplotlib.colors.ListedColormap(['w','g']) # green cmapB1 = pyl.cm.get_cmap('Blues') cmapB2 = pl.cm.get_cmap('Reds') ylims1=[0.,0.] ylims1[0]=ylims[0] ylims1[1]=ylims[1] if ylims == [0.,0.]: ylims[0] = 0. ylims[1] = mup #print("Setting ylims[1] to mup="+str(mup)) if ylims[0] != 0.: ylab='$(\mathrm{Mass }$ - '+str(ylims[0]) if yscale!='1.': ylab+=') / '+yscale+' $M_\odot$' else: ylab+=') / $M_\odot$' ax.set_ylabel(ylab) y = y - ylims[0] y = y*float(yscale) # SJONES tweak ylims[0] = y[0] ylims[1] = y[-1] print('plotting contours') CMIX = ax.contourf(xxx[::dx],y,Z, cmap=cmapMIX,alpha=0.6,levels=[0.5,1.5]) #CMIX = ax.pcolor(xxx[::dx],y,Z, cmap=cmapMIX,alpha=0.6,vmin=0.5,vmax=1.5) if rasterise==True: insert_rasterized_contour_plot(CMIX) if outlines == True: CMIX_outlines = ax.contour(xxx[::dx],y,Z, cmap=cmapMIX) if rasterise==True: insert_rasterized_contour_plot(CMIX_outlines) if CBM: CCBM = ax.contourf(xxx[::dx],y,Zcbm, cmap=cmapCBM,alpha=0.6,levels=[0.5,1.5]) if rasterise==True: insert_rasterized_contour_plot(CCBM) if outlines == True: CCBM_outlines = ax.contour(xxx[::dx],y,Zcbm, cmap=cmapCBM) if rasterise==True: insert_rasterized_contour_plot(CCBM_outlines) if engenstyle == 'full' and engenPlus == True: if engenlevels!= None: CBURN1 = ax.contourf(xxx[::dx],y,B1, cmap=cmapB1, alpha=0.5,\ locator=matplotlib.ticker.LogLocator(),levels=engenlevels) if outlines: CB1_outlines = ax.contour(xxx[::dx],y,B1, cmap=cmapB1, alpha=0.7, \ locator=matplotlib.ticker.LogLocator(),levels=engenlevels) else: CBURN1 = ax.contourf(xxx[::dx],y,B1, cmap=cmapB1, alpha=0.5, \ locator=matplotlib.ticker.LogLocator()) if outlines: CB1_outlines = ax.contour(xxx[::dx],y,B1, cmap=cmapB1, alpha=0.7, \ locator=matplotlib.ticker.LogLocator()) CBARBURN1 = pyl.colorbar(CBURN1) CBARBURN1.set_label('$|\epsilon_\mathrm{nuc}-\epsilon_{\\nu}| \; (\mathrm{erg\,g}^{-1}\mathrm{\,s}^{-1})$',fontsize=fsize) if rasterise==True: insert_rasterized_contour_plot(CBURN1) if outlines: insert_rasterized_contour_plot(CB1_outlines) if engenstyle == 'full' and engenMinus == True: CBURN2 = ax.contourf(xxx[::dx],y,B2, cmap=cmapB2, alpha=0.5, locator=matplotlib.ticker.LogLocator()) if outlines: CBURN2_outlines = ax.contour(xxx[::dx],y,B2, cmap=cmapB2, alpha=0.7, locator=matplotlib.ticker.LogLocator()) CBARBURN2 = pl.colorbar(CBURN2) if engenPlus == False: CBARBURN2.set_label('$|\epsilon_\mathrm{nuc}-\epsilon_{\\nu}| \; (\mathrm{erg\,g}^{-1}\mathrm{\,s}^{-1})$',fontsize=fsize) if rasterise==True: insert_rasterized_contour_plot(CBURN2) if outlines: insert_rasterized_contour_plot(CB2_outlines) if engenstyle == 'twozone' and (engenPlus == True or engenMinus == True): ax.contourf(xxx[::dx],y,V, cmap=cmapB1, alpha=0.5) print('plotting patches') mtot=self.get('star_mass')[modstart:modstop][::dx] mtot1=(mtot-ylims1[0])*float(yscale) ax.plot(xxx[::dx],mtot1,'k-') if boundaries == True: print('plotting abund boundaries') try: bound=self.get('h1_boundary_mass')[modstart:modstop] bound1=(bound-ylims1[0])*float(yscale) ax.plot(xxx,bound1,label='H boundary',linestyle='-') bound=self.get('he4_boundary_mass')[modstart:modstop] bound1=(bound-ylims1[0])*float(yscale) ax.plot(xxx,bound1,label='He boundary',linestyle='--') bound=self.get('c12_boundary_mass')[modstart:modstop] bound1=(bound-ylims1[0])*float(yscale) ax.plot(xxx,bound1,label='C boundary',linestyle='-.') except: try: bound=self.get('he_core_mass')[modstart:modstop] bound1=(bound-ylims1[0])*float(yscale) ax.plot(xxx,bound1,label='H boundary',linestyle='-') bound=self.get('c_core_mass')[modstart:modstop]-ylims[0] bound1=(bound-ylims1[0])*float(yscale) ax.plot(xxx,bound1,label='He boundary',linestyle='--') bound=self.get('o_core_mass')[modstart:modstop]-ylims[0] bound1=(bound-ylims1[0])*float(yscale) ax.plot(xxx,bound1,label='C boundary',linestyle='-.') bound=self.get('si_core_mass')[modstart:modstop]-ylims[0] bound1=(bound-ylims1[0])*float(yscale) ax.plot(xxx,bound1,label='C boundary',linestyle='-.') bound=self.get('fe_core_mass')[modstart:modstop]-ylims[0] bound1=(bound-ylims1[0])*float(yscale) ax.plot(xxx,bound1,label='C boundary',linestyle='-.') except: # print 'problem to plot boundaries for this plot' pass ax.axis([xlims[0],xlims[1],ylims[0],ylims[1]]) if plot_radius == True: ax2=pyl.twinx() ax2.plot(xxx,np.log10(self.get('he4_boundary_radius')[modstart:modstop]),label='He boundary radius',color='k',linewidth=1.,linestyle='-.') ax2.plot(xxx,self.get('log_R')[modstart:modstop],label='radius',color='k',linewidth=1.,linestyle='-.') ax2.set_ylabel('log(radius)') if rad_lines == True: ax2=pyl.twinx() for i in range(len(masses)): ax2.plot(modno,np.log10(rads[i]),color='k') if outfile[-3:]=='png': fig.savefig(outfile,dpi=300) elif outfile[-3:]=='eps': fig.savefig(outfile,format='eps') elif outfile[-3:]=='pdf': fig.savefig(outfile,format='pdf') if showfig == True: pyl.show()
This function creates a Kippenhahn plot with energy flux using contours. This plot uses mixing_regions and burning_regions written to your history.data or star.log. Set both variables in the log_columns.list file to 20 as a start. The output log file should then contain columns called "mix_type_n", "mix_qtop_n", "burn_type_n" and "burn_qtop_n". The number of columns (i.e. the biggest value of n) is what goes in the arguments as mix_zones and burn_zones. DO NOT WORRY! if you do not have these columns, just leave the default values alone and the script should recognise that you do not have these columns and make the most detailed plot that is available to you. Defaults are set to get some plot, that may not look great if you zoom in interactively. Play with xres and yres as well as setting the xlims to ylims to the region you are interested in. Parameters ---------- ifig : integer, optional Figure frame number. The default is 110. modstart : integer, optional Model from which you want to plot (be careful if your history.data or star.log output is sparse...). If it is 0 then it starts from the beginning, works even if log_cnt > 1. The default is 0. modstop : integer, optional Model to which you wish to plot, -1 corresponds to end [if log_cnt>1, devide modstart and modstop by log_cnt, this needs to be improved! SJ: this should be ficed now]. The defalut is -1. t0_model : integer, optional Model number from which to reset the time to 0. Typically, if modstart!=0, t0_model=modstart is a good choice, but we leave the choice to the user in case the time is wished to start from 0 at a different key point of the evolution. The default value is 0. outfile : sting, optional 'filename + extension' where you want to save the figure. The defalut is "out.png". xlims, ylims : list, optional Plot limits, however these are somewhat obsolete now that we have modstart and modstop. Leaving them as 0. is probably no slower, and you can always zoom in afterwards in mpl. ylims is important for well resolved thermal pulse etc plots; it's best to get the upper and lower limits of he-intershell using s.kippenhahn_CO(1,'model') first. The default is [0., 0.]. xres, yres : integer, optional plot resolution. Needless to say that increasing these values will yield a nicer plot with some slow-down in plotting time. You will most commonly change xres. For a prelim plot, try xres~200, then bump it up to anywhere from 1000-10000 for real nicely resolved, publication quality plots. The default is 1000. ixaxis : string, optional Either 'log_time_left', 'age', or 'model_number'. The default is "model_number". mix_zones, burn_zones : integer, optional As described above, if you have more detailed output about your convection and energy generation boundaries in columns mix_type_n, mix_qtop_n, burn_type_n and burn_qtop_n, you need to specify the total number of columns for mixing zones and burning zones that you have. Can't work this out from your history.data or star.log file? Check the history_columns.list that you used, it'll be the number after "mixing regions" and "burning regions". Can't see these columns? leave it and 2 conv zones and 2 burn zones will be drawn using other data that you certainly should have in your history.data or star.log file. The defalut for both is 20. plot_radius : boolean, optional Whether on a second y-axis you want to plot the radius of the surface and the he-free core. The default is False. engenPlus : boolean Plot energy generation contours for eps_nuc>0. The default is True. endgenMinus : boolean, optional Plot energy generation contours for eos_nuc<0. The default is True. landscape_plot : boolean, optionla The default is False. rad_lines : boolean, optional The deafault is False. profiles : list, optional The default is []. showfig : boolean, optional The default is True. outlines : boolean, optional Whether or not to plot outlines of conv zones in darker colour. boundaries : boolean, optional Whether or not to plot H-, He- and C-free boundaries. c12_boundary : boolean, optional The default is False. rasterise : boolean, optional Whether or not to rasterise the contour regions to make smaller vector graphics figures. The default is False. yscale : string, optional Re-scale the y-axis by this amount engenlevels : list Give cusstom levels to the engenPlus contour. If None, the levels are chosen automatically. The default is None. CBM : boolean, optional plot contours for where CBM is active? fsize : integer font size for labels Notes ----- The parameter xlims is depricated.
entailment
def find_first_TP(self): """ Find first TP of the TPAGB phase and returns the model number at its LHe maximum. Parameters ---------- """ star_mass = self.get('star_mass') he_lumi = self.get('log_LHe') h_lumi = self.get('log_LH') mx2_bot = self.get('mx2_bot')*star_mass try: h1_boundary_mass = self.get('h1_boundary_mass') he4_boundary_mass = self.get('he4_boundary_mass') except: try: h1_boundary_mass = self.get('he_core_mass') he4_boundary_mass = self.get('c_core_mass') except: pass TP_bot=np.array(self.get('conv_mx2_bot'))*np.array(self.get('star_mass')) TP_top=np.array(self.get('conv_mx2_top'))*np.array(self.get('star_mass')) lum_array=[] activate=False models=[] pdcz_size=[] for i in range(len(h1_boundary_mass)): if (h1_boundary_mass[i]-he4_boundary_mass[i] <0.2) and (he4_boundary_mass[i]>0.2): if (mx2_bot[i]>he4_boundary_mass[i]) and (he_lumi[i]>h_lumi[i]): if TP_top[i]>he4_boundary_mass[i]: pdcz_size.append(TP_top[i]-TP_bot[i]) activate=True lum_array.append(he_lumi[i]) models.append(i) #print(TP_bot[i],TP_top[i]) if (activate == True) and (he_lumi[i]<h_lumi[i]): #if fake tp if max(pdcz_size)<1e-5: active=False lum_array=[] models=[] print('fake tp') else: break t0_model = models[np.argmax(lum_array)] return t0_model
Find first TP of the TPAGB phase and returns the model number at its LHe maximum. Parameters ----------
entailment
def find_TPs_and_DUPs(self, percent=5., makefig=False): """ Function which finds TPs and uses the calc_DUP_parameter function. To calculate DUP parameter evolution dependent of the star or core mass. Parameters ---------- fig : integer Figure number to plot. t0_model : integer First he-shell lum peak. percent : float dredge-up is defined as when the mass dredged up is a certain percent of the total mass dredged up during that event, which is set by the user in this variable. The default is 5. makefig : do you want a figure to be made? Returns ------- TPmods : array model numbers at the peak of each thermal pulse DUPmods : array model numbers at the dredge-up, where dredge-up is defined as when the mass dredged up is a certain percent of the total mass dredged up during that event, which is set by the user TPend : array model numbers at the end of the PDCZ for each TP lambda : array DUP efficiency for each pulse """ t0_model=self.find_first_TP() t0_idx=(t0_model-self.get("model_number")[0]) first_TP_he_lum=10**(self.get("log_LHe")[t0_idx]) he_lum=10**(self.get("log_LHe")[t0_idx:]) h_lum=10**(self.get("log_LH")[t0_idx:]) model=self.get("model_number")[t0_idx:] try: h1_bndry=self.get("h1_boundary_mass")[t0_idx:] except: try: h1_bndry=self.get('he_core_mass')[t0_idx:] except: pass # SJ find TPs by finding local maxima in He-burning luminosity and # checking that the he_lum is greater than the h_lum: maxima=[0] for i in range(2,len(model)-1): if he_lum[i] > he_lum[i-1] and he_lum[i] > he_lum[i+1]: if he_lum[i-1] > he_lum[i-2] and he_lum[i+1] > he_lum[i+2]: if he_lum[i] > h_lum[i]: maxima.append(i) # find DUPs when h-boundary first decreases by more than XX% of the total DUP # depth: DUPs=[] TPend=[] maxDUPs=[] for i in range(len(maxima)): idx1=maxima[i] try: idx2=maxima[i+1] except IndexError: idx2=-1 bound=h1_bndry[idx1:idx2] bound0=bound[0] if bound0==min(bound) or bound0 < min(bound): # then no DUP DUP=idx1 DUPs.append(DUP) maxDUPs.append(DUP) else: maxDUPs.append(idx1+bound.argmin()) # model number of deepest extend of 3DUP maxDUP=bound0-min(bound) # total mass dredged up in DUP db=bound - bound[0] db_maxDUP = old_div(db, maxDUP) DUP=np.where(db_maxDUP <= old_div(-float(percent),100.))[0][0] DUPs.append(DUP+idx1) # # Alternative definition, where envelope reaches mass coordinate # # where top of PDCZ had resided during the TP: # top=self.get('mx2_top')[idx1] # DUP=np.abs(bound-top).argmin() # DUPs.append(DUP+idx1) # find end of PDCZ by seeking from TP peak and checking mx2_bot: mx2b=self.get('mx2_bot')[t0_idx:][idx1:idx2] for i in range(len(mx2b)): if mx2b[i]==0.: endTP=i+idx1 TPend.append(endTP) break # 3DUP efficiency: lambd=[0.] for i in range(1,len(maxima)): dmenv = h1_bndry[maxima[i]] - h1_bndry[maxDUPs[i-1]] dmdredge = h1_bndry[maxima[i]] - h1_bndry[maxDUPs[i]] lambd.append(old_div(dmdredge,dmenv)) TPmods = maxima + t0_idx DUPmods = DUPs + t0_idx TPend = TPend + t0_idx return TPmods, DUPmods, TPend, lambd
Function which finds TPs and uses the calc_DUP_parameter function. To calculate DUP parameter evolution dependent of the star or core mass. Parameters ---------- fig : integer Figure number to plot. t0_model : integer First he-shell lum peak. percent : float dredge-up is defined as when the mass dredged up is a certain percent of the total mass dredged up during that event, which is set by the user in this variable. The default is 5. makefig : do you want a figure to be made? Returns ------- TPmods : array model numbers at the peak of each thermal pulse DUPmods : array model numbers at the dredge-up, where dredge-up is defined as when the mass dredged up is a certain percent of the total mass dredged up during that event, which is set by the user TPend : array model numbers at the end of the PDCZ for each TP lambda : array DUP efficiency for each pulse
entailment
def TPAGB_properties(self): """ Temporary, use for now same function in nugrid_set.py! Returns many TPAGB parameters which are TPstart,TPmods,TP_max_env,TPend,min_m_TP,max_m_TP,DUPmods,DUPm_min_h Same function in nugrid_set.py. Parameters ---------- """ peak_lum_model,h1_mass_min_DUP_model=self.find_TP_attributes( 3, t0_model=self.find_first_TP(), color='r', marker_type='o') print('first tp') print(self.find_first_TP()) print('peak lum mmmodel') print(peak_lum_model) print(h1_mass_min_DUP_model) TPmods=peak_lum_model DUPmods=h1_mass_min_DUP_model DUPmods1=[] for k in range(len(DUPmods)): DUPmods1.append(int(float(DUPmods[k]))+100) #to exclude HBB? effects DUPmods=DUPmods1 TPstart=[] #find beginning of TP, goes from TP peak backwards # find end of PDCZ by seeking from TP peak and checking mx2_bot: models=self.get('model_number') mx2b_array=self.get('conv_mx2_bot') mx2t_array=self.get('conv_mx2_top') massbot=mx2b_array#*self.header_attr['initial_mass'] masstop=mx2t_array#*self.header_attr['initial_mass'] massenv=np.array(self.get('conv_mx1_bot'))*np.array(self.get('star_mass')) #*self.header_attr['initial_mass'] #h1_bdy=self.get('h1_boundary_mass') for k in range(len(TPmods)): idx=list(models).index(TPmods[k]) mx2b=mx2b_array[:idx] for i in range(len(mx2b)-1,0,-1): if mx2b[i]==0.: startTP=models[i] TPstart.append(int(float(startTP))) break #Find end of TP, goes from TP forwards: TPend=[] max_m_TP=[] min_m_TP=[] DUP_m=[] TP_max_env=[] DUPm_min_h=[] flagdecline=False for k in range(len(TPmods)): idx=list(models).index(TPmods[k]) mx2b=mx2b_array[idx:] mx2t=mx2t_array[idx:] refsize=mx2t[0]-mx2b[0] for i in range(len(mx2b)): if i==0: continue if ((mx2t[i]-mx2b[i])<(0.5*refsize)) and (flagdecline==False): flagdecline=True refmasscoord=mx2t[i] print('flagdecline to true') continue if flagdecline==True: if (mx2t[i]-mx2b[i])<(0.1*refsize): #for the massive and HDUP AGB's where PDCZ conv zone becomes the Hdup CONV ZONE if refmasscoord<mx2t[i]: endTP=models[idx+i-1] TPend.append(int(float(endTP))) print('HDUp, TP end',endTP) break if (mx2t[i]-mx2b[i])<1e-5: endTP=models[idx+i-1] TPend.append(int(float(endTP))) print('normal TPend',endTP) break # if max(mx2t[0:(i-1)])>mx2t[i]: # (max(mx2t[0:(i-1)]) - min(mx2b[0:(i-1)])) # flag=True # continue # if flag==True: # endidx=idx+i # endTP=models[endidx] # TPend.append(int(float(endTP))) # if (mx2t[i]-mx2b[i])<1e-5: #mx2b[i])==0.: # endidx=idx+i # endTP=models[endidx] # TPend.append(int(float(endTP))) # break print('found TP boundaries',TPstart[-1],TPend[-1]) #find max and minimum mass coord of TP at max Lum mtot=self.get('star_mass') masstop_tot=np.array(masstop)*np.array(mtot) idx_tpext=list(masstop_tot).index(max(masstop_tot[TPstart[k]:(TPend[k]-10)])) print('TP',k+1,TPmods[k]) print(TPstart[k],TPend[k]) print('INDEX',idx_tpext,models[idx_tpext]) print(max(masstop_tot[TPstart[k]:(TPend[k]-10)])) mtot=self.get('star_mass')[idx_tpext] max_m_TP.append(masstop[idx_tpext]*mtot) min_m_TP.append(massbot[idx_tpext]*mtot) TP_max_env.append(massenv[idx_tpext])#*mtot) if k> (len(DUPmods)-1): continue idx=list(models).index(DUPmods[k]) mtot=self.get('star_mass')[idx] #DUP_m.append(h1_bdy[idx])#*mtot) #######identify if it is really a TDUP, Def. try: h1_bndry=self.get("h1_boundary_mass")[t0_idx:] except: try: h1_bndry=self.get('he_core_mass')[t0_idx:] except: pass if h1_bndry[idx]>=max_m_TP[-1]: print('Pulse',k+1,'model',TPmods[k],'skip') print(h1_bndry[idx],max_m_TP[-1]) DUPmods[k] = -1 DUPm_min_h.append( -1) continue DUPm_min_h.append(h1_bdy[idx]) for k in range(len(TPmods)): print('#############') print('TP ',k+1) print('Start: ',TPstart[k]) print('Peak' , TPmods[k],TP_max_env[k]) print('(conv) PDCZ size: ',min_m_TP[k],' till ',max_m_TP[k]) print('End',TPend[k]) if k <=(len(DUPmods)-1): print(len(DUPmods),k) print('DUP max',DUPmods[k]) print(DUPm_min_h[k]) else: print('no DUP') return TPstart,TPmods,TP_max_env,TPend,min_m_TP,max_m_TP,DUPmods,DUPm_min_h
Temporary, use for now same function in nugrid_set.py! Returns many TPAGB parameters which are TPstart,TPmods,TP_max_env,TPend,min_m_TP,max_m_TP,DUPmods,DUPm_min_h Same function in nugrid_set.py. Parameters ----------
entailment
def calc_DUP_parameter(self, modeln, label, fig=10, color='r', marker_type='*', h_core_mass=False): """ Method to calculate the DUP parameter evolution for different TPs specified specified by their model number. Parameters ---------- fig : integer Figure number to plot. modeln : list Array containing pairs of models each corresponding to a TP. First model where h boundary mass will be taken before DUP, second model where DUP reaches lowest mass. leg : string Plot label. color : string Color of the plot. marker_type : string marker type. h_core_mass : boolean, optional If True: plot dependence from h free core , else star mass. The default is False. """ number_DUP=(old_div(len(modeln),2) -1) #START WITH SECOND try: h1_bnd_m=self.get('h1_boundary_mass') except: try: h1_bnd_m=self.get('he_core_mass') except: pass star_mass=self.get('star_mass') age=self.get("star_age") firstTP=h1_bnd_m[modeln[0]] first_m_dredge=h1_bnd_m[modeln[1]] DUP_parameter=np.zeros(number_DUP) DUP_xaxis=np.zeros(number_DUP) j=0 for i in np.arange(2,len(modeln),2): TP=h1_bnd_m[modeln[i]] m_dredge=h1_bnd_m[modeln[i+1]] if i ==2: last_m_dredge=first_m_dredge #print "testest" #print modeln[i] if h_core_mass==True: DUP_xaxis[j]=h1_bnd_m[modeln[i]] #age[modeln[i]] - age[modeln[0]] else: DUP_xaxis[j]=star_mass[modeln[i]] #DUP_xaxis[j]=modeln[i] DUP_parameter[j]=old_div((TP-m_dredge),(TP-last_m_dredge)) last_m_dredge=m_dredge j+=1 pl.figure(fig) pl.rcParams.update({'font.size': 18}) pl.rc('xtick', labelsize=18) pl.rc('ytick', labelsize=18) pl.plot(DUP_xaxis,DUP_parameter,marker=marker_type,markersize=12,mfc=color,color='k',linestyle='-',label=label) if h_core_mass==True: pl.xlabel("$M_H$",fontsize=20) else: pl.xlabel("M/M$_{\odot}$",fontsize=24) pl.ylabel("$\lambda_{DUP}$",fontsize=24) pl.minorticks_on() pl.legend()
Method to calculate the DUP parameter evolution for different TPs specified specified by their model number. Parameters ---------- fig : integer Figure number to plot. modeln : list Array containing pairs of models each corresponding to a TP. First model where h boundary mass will be taken before DUP, second model where DUP reaches lowest mass. leg : string Plot label. color : string Color of the plot. marker_type : string marker type. h_core_mass : boolean, optional If True: plot dependence from h free core , else star mass. The default is False.
entailment
def _create_usm_user_obj(snmp_cred): """Creates the UsmUserData obj for the given credentials. This method creates an instance for the method hlapi.UsmUserData. The UsmUserData() allows the 'auth_protocol' and 'priv_protocol' to be undefined by user if their pass phrases are provided. :param snmp_cred: Dictionary of SNMP credentials. auth_user: SNMP user auth_protocol: Auth Protocol auth_prot_pp: Pass phrase value for AuthProtocol. priv_protocol:Privacy Protocol. auth_priv_pp: Pass phrase value for Privacy Protocol. :returns UsmUserData object as per given credentials. """ auth_protocol = snmp_cred.get('auth_protocol') priv_protocol = snmp_cred.get('priv_protocol') auth_user = snmp_cred.get('auth_user') auth_prot_pp = snmp_cred.get('auth_prot_pp') auth_priv_pp = snmp_cred.get('auth_priv_pp') if ((not auth_protocol) and priv_protocol): priv_protocol = ( MAPPED_SNMP_ATTRIBUTES['privProtocol'][priv_protocol]) usm_user_obj = hlapi.UsmUserData(auth_user, auth_prot_pp, auth_priv_pp, privProtocol=priv_protocol) elif ((not priv_protocol) and auth_protocol): auth_protocol = ( MAPPED_SNMP_ATTRIBUTES['authProtocol'][auth_protocol]) usm_user_obj = hlapi.UsmUserData(auth_user, auth_prot_pp, auth_priv_pp, authProtocol=auth_protocol) elif not all([priv_protocol and auth_protocol]): usm_user_obj = hlapi.UsmUserData(auth_user, auth_prot_pp, auth_priv_pp) else: auth_protocol = ( MAPPED_SNMP_ATTRIBUTES['authProtocol'][auth_protocol]) priv_protocol = ( MAPPED_SNMP_ATTRIBUTES['privProtocol'][priv_protocol]) usm_user_obj = hlapi.UsmUserData(auth_user, auth_prot_pp, auth_priv_pp, authProtocol=auth_protocol, privProtocol=priv_protocol) return usm_user_obj
Creates the UsmUserData obj for the given credentials. This method creates an instance for the method hlapi.UsmUserData. The UsmUserData() allows the 'auth_protocol' and 'priv_protocol' to be undefined by user if their pass phrases are provided. :param snmp_cred: Dictionary of SNMP credentials. auth_user: SNMP user auth_protocol: Auth Protocol auth_prot_pp: Pass phrase value for AuthProtocol. priv_protocol:Privacy Protocol. auth_priv_pp: Pass phrase value for Privacy Protocol. :returns UsmUserData object as per given credentials.
entailment
def _parse_mibs(iLOIP, snmp_credentials): """Parses the MIBs. :param iLOIP: IP address of the server on which SNMP discovery has to be executed. :param snmp_credentials: a Dictionary of SNMP credentials. auth_user: SNMP user auth_protocol: Auth Protocol auth_prot_pp: Pass phrase value for AuthProtocol. priv_protocol:Privacy Protocol. auth_priv_pp: Pass phrase value for Privacy Protocol. :returns the dictionary of parsed MIBs. :raises exception.InvalidInputError if pysnmp is unable to get SNMP data due to wrong inputs provided. :raises exception.IloError if pysnmp raises any exception. """ result = {} usm_user_obj = _create_usm_user_obj(snmp_credentials) try: for(errorIndication, errorStatus, errorIndex, varBinds) in hlapi.nextCmd( hlapi.SnmpEngine(), usm_user_obj, hlapi.UdpTransportTarget((iLOIP, 161), timeout=3, retries=3), hlapi.ContextData(), # cpqida cpqDaPhyDrvTable Drive Array Physical Drive Table hlapi.ObjectType( hlapi.ObjectIdentity('1.3.6.1.4.1.232.3.2.5.1')), # cpqscsi SCSI Physical Drive Table hlapi.ObjectType( hlapi.ObjectIdentity('1.3.6.1.4.1.232.5.2.4.1')), # cpqscsi SAS Physical Drive Table hlapi.ObjectType( hlapi.ObjectIdentity('1.3.6.1.4.1.232.5.5.2.1')), lexicographicMode=False, ignoreNonIncreasingOid=True): if errorIndication: LOG.error(errorIndication) msg = "SNMP failed to traverse MIBs %s", errorIndication raise exception.IloSNMPInvalidInputFailure(msg) else: if errorStatus: msg = ('Parsing MIBs failed. %s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBinds[-1][int(errorIndex)-1] or '?' ) ) LOG.error(msg) raise exception.IloSNMPInvalidInputFailure(msg) else: for varBindTableRow in varBinds: name, val = tuple(varBindTableRow) oid, label, suffix = ( mibViewController.getNodeName(name)) key = name.prettyPrint() # Don't traverse outside the tables we requested if not (key.find("SNMPv2-SMI::enterprises.232.3") >= 0 or (key.find( "SNMPv2-SMI::enterprises.232.5") >= 0)): break if key not in result: result[key] = {} result[key][label[-1]] = {} result[key][label[-1]][suffix] = val except Exception as e: msg = "SNMP library failed with error %s", e LOG.error(msg) raise exception.IloSNMPExceptionFailure(msg) return result
Parses the MIBs. :param iLOIP: IP address of the server on which SNMP discovery has to be executed. :param snmp_credentials: a Dictionary of SNMP credentials. auth_user: SNMP user auth_protocol: Auth Protocol auth_prot_pp: Pass phrase value for AuthProtocol. priv_protocol:Privacy Protocol. auth_priv_pp: Pass phrase value for Privacy Protocol. :returns the dictionary of parsed MIBs. :raises exception.InvalidInputError if pysnmp is unable to get SNMP data due to wrong inputs provided. :raises exception.IloError if pysnmp raises any exception.
entailment
def _get_disksize_MiB(iLOIP, cred): """Reads the dictionary of parsed MIBs and gets the disk size. :param iLOIP: IP address of the server on which SNMP discovery has to be executed. :param snmp_credentials in a dictionary having following mandatory keys. auth_user: SNMP user auth_protocol: Auth Protocol auth_prot_pp: Pass phrase value for AuthProtocol. priv_protocol:Privacy Protocol. auth_priv_pp: Pass phrase value for Privacy Protocol. :returns the dictionary of disk sizes of all physical drives. """ # '1.3.6.1.4.1.232.5.5.1.1', # cpqscsi SAS HBA Table # '1.3.6.1.4.1.232.3.2.3.1', # cpqida Drive Array Logical Drive Table result = _parse_mibs(iLOIP, cred) disksize = {} for uuid in sorted(result): for key in result[uuid]: # We only track the Physical Disk Size if key.find('PhyDrvSize') >= 0: disksize[uuid] = dict() for suffix in sorted(result[uuid][key]): size = result[uuid][key][suffix] disksize[uuid][key] = str(size) return disksize
Reads the dictionary of parsed MIBs and gets the disk size. :param iLOIP: IP address of the server on which SNMP discovery has to be executed. :param snmp_credentials in a dictionary having following mandatory keys. auth_user: SNMP user auth_protocol: Auth Protocol auth_prot_pp: Pass phrase value for AuthProtocol. priv_protocol:Privacy Protocol. auth_priv_pp: Pass phrase value for Privacy Protocol. :returns the dictionary of disk sizes of all physical drives.
entailment
def get_local_gb(iLOIP, snmp_credentials): """Gets the maximum disk size among all disks. :param iLOIP: IP address of the server on which SNMP discovery has to be executed. :param snmp_credentials in a dictionary having following mandatory keys. auth_user: SNMP user auth_protocol: Auth Protocol auth_prot_pp: Pass phrase value for AuthProtocol. priv_protocol:Privacy Protocol. auth_priv_pp: Pass phrase value for Privacy Protocol. """ disk_sizes = _get_disksize_MiB(iLOIP, snmp_credentials) max_size = 0 for uuid in disk_sizes: for key in disk_sizes[uuid]: if int(disk_sizes[uuid][key]) > max_size: max_size = int(disk_sizes[uuid][key]) max_size_gb = max_size/1024 return max_size_gb
Gets the maximum disk size among all disks. :param iLOIP: IP address of the server on which SNMP discovery has to be executed. :param snmp_credentials in a dictionary having following mandatory keys. auth_user: SNMP user auth_protocol: Auth Protocol auth_prot_pp: Pass phrase value for AuthProtocol. priv_protocol:Privacy Protocol. auth_priv_pp: Pass phrase value for Privacy Protocol.
entailment
def _http_error_handler(http_error): ''' Simple error handler for azure.''' message = str(http_error) if http_error.respbody is not None: message += '\n' + http_error.respbody.decode('utf-8-sig') raise AzureHttpError(message, http_error.status)
Simple error handler for azure.
entailment
def summary(self): """property to return the summary MAC addresses and state This filters the MACs whose health is OK, and in 'Enabled' State would be returned. The returned format will be {<port_id>: <mac_address>}. This is because RIBCL returns the data in format {'Port 1': 'aa:bb:cc:dd:ee:ff'} and ironic ilo drivers inspection consumes the data in this format. Note: 'Id' is referred to as "Port number". """ mac_dict = {} for eth in self.get_members(): if eth.mac_address is not None: if (eth.status is not None and eth.status.health == sys_cons.HEALTH_OK and eth.status.state == sys_cons.HEALTH_STATE_ENABLED): mac_dict.update( {'Port ' + eth.identity: eth.mac_address}) return mac_dict
property to return the summary MAC addresses and state This filters the MACs whose health is OK, and in 'Enabled' State would be returned. The returned format will be {<port_id>: <mac_address>}. This is because RIBCL returns the data in format {'Port 1': 'aa:bb:cc:dd:ee:ff'} and ironic ilo drivers inspection consumes the data in this format. Note: 'Id' is referred to as "Port number".
entailment
def _update_physical_disk_details(raid_config, server): """Adds the physical disk details to the RAID configuration passed.""" raid_config['physical_disks'] = [] physical_drives = server.get_physical_drives() for physical_drive in physical_drives: physical_drive_dict = physical_drive.get_physical_drive_dict() raid_config['physical_disks'].append(physical_drive_dict)
Adds the physical disk details to the RAID configuration passed.
entailment
def validate(raid_config): """Validates the RAID configuration provided. This method validates the RAID configuration provided against a JSON schema. :param raid_config: The RAID configuration to be validated. :raises: InvalidInputError, if validation of the input fails. """ raid_schema_fobj = open(RAID_CONFIG_SCHEMA, 'r') raid_config_schema = json.load(raid_schema_fobj) try: jsonschema.validate(raid_config, raid_config_schema) except json_schema_exc.ValidationError as e: raise exception.InvalidInputError(e.message) for logical_disk in raid_config['logical_disks']: # If user has provided 'number_of_physical_disks' or # 'physical_disks', validate that they have mentioned at least # minimum number of physical disks required for that RAID level. raid_level = logical_disk['raid_level'] min_disks_reqd = constants.RAID_LEVEL_MIN_DISKS[raid_level] no_of_disks_specified = None if 'number_of_physical_disks' in logical_disk: no_of_disks_specified = logical_disk['number_of_physical_disks'] elif 'physical_disks' in logical_disk: no_of_disks_specified = len(logical_disk['physical_disks']) if (no_of_disks_specified and no_of_disks_specified < min_disks_reqd): msg = ("RAID level %(raid_level)s requires at least %(number)s " "disks." % {'raid_level': raid_level, 'number': min_disks_reqd}) raise exception.InvalidInputError(msg)
Validates the RAID configuration provided. This method validates the RAID configuration provided against a JSON schema. :param raid_config: The RAID configuration to be validated. :raises: InvalidInputError, if validation of the input fails.
entailment
def _select_controllers_by(server, select_condition, msg): """Filters out the hpssa controllers based on the condition. This method updates the server with only the controller which satisfies the condition. The controllers which doesn't satisfies the selection condition will be removed from the list. :param server: The object containing all the supported hpssa controllers details. :param select_condition: A lambda function to select the controllers based on requirement. :param msg: A String which describes the controller selection. :raises exception.HPSSAOperationError, if all the controller are in HBA mode. """ all_controllers = server.controllers supported_controllers = [c for c in all_controllers if select_condition(c)] if not supported_controllers: reason = ("None of the available SSA controllers %(controllers)s " "have %(msg)s" % {'controllers': ', '.join([c.id for c in all_controllers]), 'msg': msg}) raise exception.HPSSAOperationError(reason=reason) server.controllers = supported_controllers
Filters out the hpssa controllers based on the condition. This method updates the server with only the controller which satisfies the condition. The controllers which doesn't satisfies the selection condition will be removed from the list. :param server: The object containing all the supported hpssa controllers details. :param select_condition: A lambda function to select the controllers based on requirement. :param msg: A String which describes the controller selection. :raises exception.HPSSAOperationError, if all the controller are in HBA mode.
entailment
def create_configuration(raid_config): """Create a RAID configuration on this server. This method creates the given RAID configuration on the server based on the input passed. :param raid_config: The dictionary containing the requested RAID configuration. This data structure should be as follows: raid_config = {'logical_disks': [{'raid_level': 1, 'size_gb': 100}, <info-for-logical-disk-2> ]} :returns: the current raid configuration. This is same as raid_config with some extra properties like root_device_hint, volume_name, controller, physical_disks, etc filled for each logical disk after its creation. :raises exception.InvalidInputError, if input is invalid. :raises exception.HPSSAOperationError, if all the controllers are in HBA mode. """ server = objects.Server() select_controllers = lambda x: not x.properties.get('HBA Mode Enabled', False) _select_controllers_by(server, select_controllers, 'RAID enabled') validate(raid_config) # Make sure we create the large disks first. This is avoid the # situation that we avoid giving large disks to smaller requests. # For example, consider this: # - two logical disks - LD1(50), LD(100) # - have 4 physical disks - PD1(50), PD2(50), PD3(100), PD4(100) # # In this case, for RAID1 configuration, if we were to consider # LD1 first and allocate PD3 and PD4 for it, then allocation would # fail. So follow a particular order for allocation. # # Also make sure we create the MAX logical_disks the last to make sure # we allot only the remaining space available. logical_disks_sorted = ( sorted((x for x in raid_config['logical_disks'] if x['size_gb'] != "MAX"), reverse=True, key=lambda x: x['size_gb']) + [x for x in raid_config['logical_disks'] if x['size_gb'] == "MAX"]) if any(logical_disk['share_physical_disks'] for logical_disk in logical_disks_sorted if 'share_physical_disks' in logical_disk): logical_disks_sorted = _sort_shared_logical_disks(logical_disks_sorted) # We figure out the new disk created by recording the wwns # before and after the create, and then figuring out the # newly found wwn from it. wwns_before_create = set([x.wwn for x in server.get_logical_drives()]) for logical_disk in logical_disks_sorted: if 'physical_disks' not in logical_disk: disk_allocator.allocate_disks(logical_disk, server, raid_config) controller_id = logical_disk['controller'] controller = server.get_controller_by_id(controller_id) if not controller: msg = ("Unable to find controller named '%(controller)s'." " The available controllers are '%(ctrl_list)s'." % {'controller': controller_id, 'ctrl_list': ', '.join( [c.id for c in server.controllers])}) raise exception.InvalidInputError(reason=msg) if 'physical_disks' in logical_disk: for physical_disk in logical_disk['physical_disks']: disk_obj = controller.get_physical_drive_by_id(physical_disk) if not disk_obj: msg = ("Unable to find physical disk '%(physical_disk)s' " "on '%(controller)s'" % {'physical_disk': physical_disk, 'controller': controller_id}) raise exception.InvalidInputError(msg) controller.create_logical_drive(logical_disk) # Now find the new logical drive created. server.refresh() wwns_after_create = set([x.wwn for x in server.get_logical_drives()]) new_wwn = wwns_after_create - wwns_before_create if not new_wwn: reason = ("Newly created logical disk with raid_level " "'%(raid_level)s' and size %(size_gb)s GB not " "found." % {'raid_level': logical_disk['raid_level'], 'size_gb': logical_disk['size_gb']}) raise exception.HPSSAOperationError(reason=reason) new_logical_disk = server.get_logical_drive_by_wwn(new_wwn.pop()) new_log_drive_properties = new_logical_disk.get_logical_drive_dict() logical_disk.update(new_log_drive_properties) wwns_before_create = wwns_after_create.copy() _update_physical_disk_details(raid_config, server) return raid_config
Create a RAID configuration on this server. This method creates the given RAID configuration on the server based on the input passed. :param raid_config: The dictionary containing the requested RAID configuration. This data structure should be as follows: raid_config = {'logical_disks': [{'raid_level': 1, 'size_gb': 100}, <info-for-logical-disk-2> ]} :returns: the current raid configuration. This is same as raid_config with some extra properties like root_device_hint, volume_name, controller, physical_disks, etc filled for each logical disk after its creation. :raises exception.InvalidInputError, if input is invalid. :raises exception.HPSSAOperationError, if all the controllers are in HBA mode.
entailment
def _sort_shared_logical_disks(logical_disks): """Sort the logical disks based on the following conditions. When the share_physical_disks is True make sure we create the volume which needs more disks first. This avoids the situation of insufficient disks for some logical volume request. For example, - two logical disk with number of disks - LD1(3), LD2(4) - have 4 physical disks In this case, if we consider LD1 first then LD2 will fail since not enough disks available to create LD2. So follow a order for allocation when share_physical_disks is True. Also RAID1 can share only when there is logical volume with only 2 disks. So make sure we create RAID 1 first when share_physical_disks is True. And RAID 1+0 can share only when the logical volume with even number of disks. :param logical_disks: 'logical_disks' to be sorted for shared logical disks. :returns: the logical disks sorted based the above conditions. """ is_shared = (lambda x: True if ('share_physical_disks' in x and x['share_physical_disks']) else False) num_of_disks = (lambda x: x['number_of_physical_disks'] if 'number_of_physical_disks' in x else constants.RAID_LEVEL_MIN_DISKS[x['raid_level']]) # Separate logical disks based on share_physical_disks value. # 'logical_disks_shared' when share_physical_disks is True and # 'logical_disks_nonshared' when share_physical_disks is False logical_disks_shared = [] logical_disks_nonshared = [] for x in logical_disks: target = (logical_disks_shared if is_shared(x) else logical_disks_nonshared) target.append(x) # Separete logical disks with raid 1 from the 'logical_disks_shared' into # 'logical_disks_shared_raid1' and remaining as # 'logical_disks_shared_excl_raid1'. logical_disks_shared_raid1 = [] logical_disks_shared_excl_raid1 = [] for x in logical_disks_shared: target = (logical_disks_shared_raid1 if x['raid_level'] == '1' else logical_disks_shared_excl_raid1) target.append(x) # Sort the 'logical_disks_shared' in reverse order based on # 'number_of_physical_disks' attribute, if provided, otherwise minimum # disks required to create the logical volume. logical_disks_shared = sorted(logical_disks_shared_excl_raid1, reverse=True, key=num_of_disks) # Move RAID 1+0 to first in 'logical_disks_shared' when number of physical # disks needed to create logical volume cannot be shared with odd number of # disks and disks higher than that of RAID 1+0. check = True for x in logical_disks_shared: if x['raid_level'] == "1+0": x_num = num_of_disks(x) for y in logical_disks_shared: if y['raid_level'] != "1+0": y_num = num_of_disks(y) if x_num < y_num: check = (True if y_num % 2 == 0 else False) if check: break if not check: logical_disks_shared.remove(x) logical_disks_shared.insert(0, x) check = True # Final 'logical_disks_sorted' list should have non shared logical disks # first, followed by shared logical disks with RAID 1, and finally by the # shared logical disks sorted based on number of disks and RAID 1+0 # condition. logical_disks_sorted = (logical_disks_nonshared + logical_disks_shared_raid1 + logical_disks_shared) return logical_disks_sorted
Sort the logical disks based on the following conditions. When the share_physical_disks is True make sure we create the volume which needs more disks first. This avoids the situation of insufficient disks for some logical volume request. For example, - two logical disk with number of disks - LD1(3), LD2(4) - have 4 physical disks In this case, if we consider LD1 first then LD2 will fail since not enough disks available to create LD2. So follow a order for allocation when share_physical_disks is True. Also RAID1 can share only when there is logical volume with only 2 disks. So make sure we create RAID 1 first when share_physical_disks is True. And RAID 1+0 can share only when the logical volume with even number of disks. :param logical_disks: 'logical_disks' to be sorted for shared logical disks. :returns: the logical disks sorted based the above conditions.
entailment
def delete_configuration(): """Delete a RAID configuration on this server. :returns: the current RAID configuration after deleting all the logical disks. """ server = objects.Server() select_controllers = lambda x: not x.properties.get('HBA Mode Enabled', False) _select_controllers_by(server, select_controllers, 'RAID enabled') for controller in server.controllers: # Trigger delete only if there is some RAID array, otherwise # hpssacli/ssacli will fail saying "no logical drives found.". if controller.raid_arrays: controller.delete_all_logical_drives() return get_configuration()
Delete a RAID configuration on this server. :returns: the current RAID configuration after deleting all the logical disks.
entailment
def get_configuration(): """Get the current RAID configuration. Get the RAID configuration from the server and return it as a dictionary. :returns: A dictionary of the below format. raid_config = { 'logical_disks': [{ 'size_gb': 100, 'raid_level': 1, 'physical_disks': [ '5I:0:1', '5I:0:2'], 'controller': 'Smart array controller' }, ] } """ server = objects.Server() logical_drives = server.get_logical_drives() raid_config = {} raid_config['logical_disks'] = [] for logical_drive in logical_drives: logical_drive_dict = logical_drive.get_logical_drive_dict() raid_config['logical_disks'].append(logical_drive_dict) _update_physical_disk_details(raid_config, server) return raid_config
Get the current RAID configuration. Get the RAID configuration from the server and return it as a dictionary. :returns: A dictionary of the below format. raid_config = { 'logical_disks': [{ 'size_gb': 100, 'raid_level': 1, 'physical_disks': [ '5I:0:1', '5I:0:2'], 'controller': 'Smart array controller' }, ] }
entailment
def erase_devices(): """Erase all the drives on this server. This method performs sanitize erase on all the supported physical drives in this server. This erase cannot be performed on logical drives. :returns: a dictionary of controllers with drives and the erase status. :raises exception.HPSSAException, if none of the drives support sanitize erase. """ server = objects.Server() for controller in server.controllers: drives = [x for x in controller.unassigned_physical_drives if (x.get_physical_drive_dict().get('erase_status', '') == 'OK')] if drives: controller.erase_devices(drives) while not has_erase_completed(): time.sleep(300) server.refresh() status = {} for controller in server.controllers: drive_status = {x.id: x.erase_status for x in controller.unassigned_physical_drives} sanitize_supported = controller.properties.get( 'Sanitize Erase Supported', 'False') if sanitize_supported == 'False': msg = ("Drives overwritten with zeros because sanitize erase " "is not supported on the controller.") else: msg = ("Sanitize Erase performed on the disks attached to " "the controller.") drive_status.update({'Summary': msg}) status[controller.id] = drive_status return status
Erase all the drives on this server. This method performs sanitize erase on all the supported physical drives in this server. This erase cannot be performed on logical drives. :returns: a dictionary of controllers with drives and the erase status. :raises exception.HPSSAException, if none of the drives support sanitize erase.
entailment
def _parse_metadata_and_message_count(response): ''' Extracts approximate messages count header. ''' metadata = _parse_metadata(response) headers = _parse_response_for_dict(response) metadata.approximate_message_count = _int_to_str(headers.get('x-ms-approximate-messages-count')) return metadata
Extracts approximate messages count header.
entailment
def _parse_queue_message_from_headers(response): ''' Extracts pop receipt and time next visible from headers. ''' headers = _parse_response_for_dict(response) message = QueueMessage() message.pop_receipt = headers.get('x-ms-popreceipt') message.time_next_visible = parser.parse(headers.get('x-ms-time-next-visible')) return message
Extracts pop receipt and time next visible from headers.
entailment
def _convert_xml_to_queue_messages(response, decode_function): ''' <?xml version="1.0" encoding="utf-8"?> <QueueMessagesList> <QueueMessage> <MessageId>string-message-id</MessageId> <InsertionTime>insertion-time</InsertionTime> <ExpirationTime>expiration-time</ExpirationTime> <PopReceipt>opaque-string-receipt-data</PopReceipt> <TimeNextVisible>time-next-visible</TimeNextVisible> <DequeueCount>integer</DequeueCount> <MessageText>message-body</MessageText> </QueueMessage> </QueueMessagesList> ''' if response is None or response.body is None: return response messages = list() list_element = ETree.fromstring(response.body) for message_element in list_element.findall('QueueMessage'): message = QueueMessage() message.id = message_element.findtext('MessageId') message.dequeue_count = message_element.findtext('DequeueCount') message.content = decode_function(message_element.findtext('MessageText')) message.insertion_time = parser.parse(message_element.findtext('InsertionTime')) message.expiration_time = parser.parse(message_element.findtext('ExpirationTime')) message.pop_receipt = message_element.findtext('PopReceipt') time_next_visible = message_element.find('TimeNextVisible') if time_next_visible is not None: message.time_next_visible = parser.parse(time_next_visible.text) # Add message to list messages.append(message) return messages
<?xml version="1.0" encoding="utf-8"?> <QueueMessagesList> <QueueMessage> <MessageId>string-message-id</MessageId> <InsertionTime>insertion-time</InsertionTime> <ExpirationTime>expiration-time</ExpirationTime> <PopReceipt>opaque-string-receipt-data</PopReceipt> <TimeNextVisible>time-next-visible</TimeNextVisible> <DequeueCount>integer</DequeueCount> <MessageText>message-body</MessageText> </QueueMessage> </QueueMessagesList>
entailment
def volumes(self): """This property prepares the list of volumes :return a list of volumes. """ return sys_volumes.VolumeCollection( self._conn, utils.get_subresource_path_by(self, 'Volumes'), redfish_version=self.redfish_version)
This property prepares the list of volumes :return a list of volumes.
entailment
def _drives_list(self): """Gets the list of drives :return a list of drives. """ drives_list = [] for member in self.drives: drives_list.append(sys_drives.Drive( self._conn, member.get('@odata.id'), self.redfish_version)) return drives_list
Gets the list of drives :return a list of drives.
entailment
def has_ssd(self): """Return true if any of the drive is ssd""" for member in self._drives_list(): if member.media_type == constants.MEDIA_TYPE_SSD: return True return False
Return true if any of the drive is ssd
entailment
def has_rotational(self): """Return true if any of the drive is HDD""" for member in self._drives_list(): if member.media_type == constants.MEDIA_TYPE_HDD: return True return False
Return true if any of the drive is HDD
entailment
def has_nvme_ssd(self): """Return True if the drive is SSD and protocol is NVMe""" for member in self._drives_list(): if (member.media_type == constants.MEDIA_TYPE_SSD and member.protocol == constants.PROTOCOL_NVMe): return True return False
Return True if the drive is SSD and protocol is NVMe
entailment
def drive_rotational_speed_rpm(self): """Gets set of rotational speed of the disks""" drv_rot_speed_rpm = set() for member in self._drives_list(): if member.rotation_speed_rpm is not None: drv_rot_speed_rpm.add(member.rotation_speed_rpm) return drv_rot_speed_rpm
Gets set of rotational speed of the disks
entailment
def volumes_maximum_size_bytes(self): """Gets the biggest logical drive :returns the size in MiB. """ return utils.max_safe([member.volumes.maximum_size_bytes for member in self.get_members()])
Gets the biggest logical drive :returns the size in MiB.
entailment
def drive_rotational_speed_rpm(self): """Gets set of rotational speed of the disks""" drv_rot_speed_rpm = set() for member in self.get_members(): drv_rot_speed_rpm.update(member.drive_rotational_speed_rpm) return drv_rot_speed_rpm
Gets set of rotational speed of the disks
entailment
def create_table_service(self): ''' Creates a TableService object with the settings specified in the CloudStorageAccount. :return: A service object. :rtype: :class:`~azure.storage.table.tableservice.TableService` ''' try: from ..table.tableservice import TableService return TableService(self.account_name, self.account_key, sas_token=self.sas_token, is_emulated=self.is_emulated) except ImportError: raise Exception('The package azure-storage-table is required. ' + 'Please install it using "pip install azure-storage-table"')
Creates a TableService object with the settings specified in the CloudStorageAccount. :return: A service object. :rtype: :class:`~azure.storage.table.tableservice.TableService`
entailment
def get_queue_service_properties(self, timeout=None): ''' Gets the properties of a storage account's Queue service, including logging, analytics and CORS rules. :param int timeout: The server timeout, expressed in seconds. :return: The queue service properties. :rtype: :class:`~azure.storage.models.ServiceProperties` ''' request = HTTPRequest() request.method = 'GET' request.host = self._get_host() request.path = _get_path() request.query = [ ('restype', 'service'), ('comp', 'properties'), ('timeout', _int_to_str(timeout)), ] response = self._perform_request(request) return _convert_xml_to_service_properties(response.body)
Gets the properties of a storage account's Queue service, including logging, analytics and CORS rules. :param int timeout: The server timeout, expressed in seconds. :return: The queue service properties. :rtype: :class:`~azure.storage.models.ServiceProperties`
entailment
def list_queues(self, prefix=None, num_results=None, include_metadata=False, marker=None, timeout=None): ''' Returns a generator to list the queues. The generator will lazily follow the continuation tokens returned by the service and stop when all queues have been returned or num_results is reached. If num_results is specified and the account has more than that number of queues, the generator will have a populated next_marker field once it finishes. This marker can be used to create a new generator if more results are desired. :param str prefix: Filters the results to return only queues with names that begin with the specified prefix. :param int num_results: The maximum number of queues to return. :param bool include_metadata: Specifies that container metadata be returned in the response. :param str marker: An opaque continuation token. This value can be retrieved from the next_marker field of a previous generator object if num_results was specified and that generator has finished enumerating results. If specified, this generator will begin returning results from the point where the previous generator stopped. :param int timeout: The server timeout, expressed in seconds. This function may make multiple calls to the service in which case the timeout value specified will be applied to each individual call. ''' include = 'metadata' if include_metadata else None kwargs = {'prefix': prefix, 'max_results': num_results, 'include': include, 'marker': marker, 'timeout': timeout} resp = self._list_queues(**kwargs) return ListGenerator(resp, self._list_queues, (), kwargs)
Returns a generator to list the queues. The generator will lazily follow the continuation tokens returned by the service and stop when all queues have been returned or num_results is reached. If num_results is specified and the account has more than that number of queues, the generator will have a populated next_marker field once it finishes. This marker can be used to create a new generator if more results are desired. :param str prefix: Filters the results to return only queues with names that begin with the specified prefix. :param int num_results: The maximum number of queues to return. :param bool include_metadata: Specifies that container metadata be returned in the response. :param str marker: An opaque continuation token. This value can be retrieved from the next_marker field of a previous generator object if num_results was specified and that generator has finished enumerating results. If specified, this generator will begin returning results from the point where the previous generator stopped. :param int timeout: The server timeout, expressed in seconds. This function may make multiple calls to the service in which case the timeout value specified will be applied to each individual call.
entailment
def _list_queues(self, prefix=None, marker=None, max_results=None, include=None, timeout=None): ''' Returns a list of queues under the specified account. Makes a single list request to the service. Used internally by the list_queues method. :param str prefix: Filters the results to return only queues with names that begin with the specified prefix. :param str marker: A token which identifies the portion of the query to be returned with the next query operation. The operation returns a next_marker element within the response body if the list returned was not complete. This value may then be used as a query parameter in a subsequent call to request the next portion of the list of queues. The marker value is opaque to the client. :param int max_results: The maximum number of queues to return. A single list request may return up to 1000 queues and potentially a continuation token which should be followed to get additional resutls. :param str include: Include this parameter to specify that the container's metadata be returned as part of the response body. :param int timeout: The server timeout, expressed in seconds. ''' request = HTTPRequest() request.method = 'GET' request.host = self._get_host() request.path = _get_path() request.query = [ ('comp', 'list'), ('prefix', _to_str(prefix)), ('marker', _to_str(marker)), ('maxresults', _int_to_str(max_results)), ('include', _to_str(include)), ('timeout', _int_to_str(timeout)) ] response = self._perform_request(request) return _convert_xml_to_queues(response)
Returns a list of queues under the specified account. Makes a single list request to the service. Used internally by the list_queues method. :param str prefix: Filters the results to return only queues with names that begin with the specified prefix. :param str marker: A token which identifies the portion of the query to be returned with the next query operation. The operation returns a next_marker element within the response body if the list returned was not complete. This value may then be used as a query parameter in a subsequent call to request the next portion of the list of queues. The marker value is opaque to the client. :param int max_results: The maximum number of queues to return. A single list request may return up to 1000 queues and potentially a continuation token which should be followed to get additional resutls. :param str include: Include this parameter to specify that the container's metadata be returned as part of the response body. :param int timeout: The server timeout, expressed in seconds.
entailment
def create_queue(self, queue_name, metadata=None, fail_on_exist=False, timeout=None): ''' Creates a queue under the given account. :param str queue_name: The name of the queue to create. A queue name must be from 3 through 63 characters long and may only contain lowercase letters, numbers, and the dash (-) character. The first and last letters in the queue must be alphanumeric. The dash (-) character cannot be the first or last character. Consecutive dash characters are not permitted in the queue name. :param metadata: A dict containing name-value pairs to associate with the queue as metadata. Note that metadata names preserve the case with which they were created, but are case-insensitive when set or read. :type metadata: a dict mapping str to str :param bool fail_on_exist: Specifies whether to throw an exception if the queue already exists. :param int timeout: The server timeout, expressed in seconds. :return: A boolean indicating whether the queue was created. If fail_on_exist was set to True, this will throw instead of returning false. :rtype: bool ''' _validate_not_none('queue_name', queue_name) request = HTTPRequest() request.method = 'PUT' request.host = self._get_host() request.path = _get_path(queue_name) request.query = [('timeout', _int_to_str(timeout))] request.headers = [('x-ms-meta-name-values', metadata)] if not fail_on_exist: try: response = self._perform_request(request) if response.status == _HTTP_RESPONSE_NO_CONTENT: return False return True except AzureHttpError as ex: _dont_fail_on_exist(ex) return False else: response = self._perform_request(request) if response.status == _HTTP_RESPONSE_NO_CONTENT: raise AzureConflictHttpError( _ERROR_CONFLICT.format(response.message), response.status) return True
Creates a queue under the given account. :param str queue_name: The name of the queue to create. A queue name must be from 3 through 63 characters long and may only contain lowercase letters, numbers, and the dash (-) character. The first and last letters in the queue must be alphanumeric. The dash (-) character cannot be the first or last character. Consecutive dash characters are not permitted in the queue name. :param metadata: A dict containing name-value pairs to associate with the queue as metadata. Note that metadata names preserve the case with which they were created, but are case-insensitive when set or read. :type metadata: a dict mapping str to str :param bool fail_on_exist: Specifies whether to throw an exception if the queue already exists. :param int timeout: The server timeout, expressed in seconds. :return: A boolean indicating whether the queue was created. If fail_on_exist was set to True, this will throw instead of returning false. :rtype: bool
entailment
def get_queue_metadata(self, queue_name, timeout=None): ''' Retrieves user-defined metadata and queue properties on the specified queue. Metadata is associated with the queue as name-value pairs. :param str queue_name: The name of an existing queue. :param int timeout: The server timeout, expressed in seconds. :return: A dictionary representing the queue metadata with an approximate_message_count int property on the dict estimating the number of messages in the queue. :rtype: a dict mapping str to str ''' _validate_not_none('queue_name', queue_name) request = HTTPRequest() request.method = 'GET' request.host = self._get_host() request.path = _get_path(queue_name) request.query = [ ('comp', 'metadata'), ('timeout', _int_to_str(timeout)), ] response = self._perform_request(request) return _parse_metadata_and_message_count(response)
Retrieves user-defined metadata and queue properties on the specified queue. Metadata is associated with the queue as name-value pairs. :param str queue_name: The name of an existing queue. :param int timeout: The server timeout, expressed in seconds. :return: A dictionary representing the queue metadata with an approximate_message_count int property on the dict estimating the number of messages in the queue. :rtype: a dict mapping str to str
entailment
def set_queue_metadata(self, queue_name, metadata=None, timeout=None): ''' Sets user-defined metadata on the specified queue. Metadata is associated with the queue as name-value pairs. :param str queue_name: The name of an existing queue. :param dict metadata: A dict containing name-value pairs to associate with the queue as metadata. :param int timeout: The server timeout, expressed in seconds. ''' _validate_not_none('queue_name', queue_name) request = HTTPRequest() request.method = 'PUT' request.host = self._get_host() request.path = _get_path(queue_name) request.query = [ ('comp', 'metadata'), ('timeout', _int_to_str(timeout)), ] request.headers = [('x-ms-meta-name-values', metadata)] self._perform_request(request)
Sets user-defined metadata on the specified queue. Metadata is associated with the queue as name-value pairs. :param str queue_name: The name of an existing queue. :param dict metadata: A dict containing name-value pairs to associate with the queue as metadata. :param int timeout: The server timeout, expressed in seconds.
entailment
def get_queue_acl(self, queue_name, timeout=None): ''' Returns details about any stored access policies specified on the queue that may be used with Shared Access Signatures. :param str queue_name: The name of an existing queue. :param int timeout: The server timeout, expressed in seconds. :return: A dictionary of access policies associated with the queue. :rtype: dict of str to :class:`~azure.storage.models.AccessPolicy` ''' _validate_not_none('queue_name', queue_name) request = HTTPRequest() request.method = 'GET' request.host = self._get_host() request.path = _get_path(queue_name) request.query = [ ('comp', 'acl'), ('timeout', _int_to_str(timeout)), ] response = self._perform_request(request) return _convert_xml_to_signed_identifiers(response.body)
Returns details about any stored access policies specified on the queue that may be used with Shared Access Signatures. :param str queue_name: The name of an existing queue. :param int timeout: The server timeout, expressed in seconds. :return: A dictionary of access policies associated with the queue. :rtype: dict of str to :class:`~azure.storage.models.AccessPolicy`
entailment
def set_queue_acl(self, queue_name, signed_identifiers=None, timeout=None): ''' Sets stored access policies for the queue that may be used with Shared Access Signatures. When you set permissions for a queue, the existing permissions are replaced. To update the queue’s permissions, call :func:`~get_queue_acl` to fetch all access policies associated with the queue, modify the access policy that you wish to change, and then call this function with the complete set of data to perform the update. When you establish a stored access policy on a queue, it may take up to 30 seconds to take effect. During this interval, a shared access signature that is associated with the stored access policy will throw an :class:`AzureHttpError` until the access policy becomes active. :param str queue_name: The name of an existing queue. :param signed_identifiers: A dictionary of access policies to associate with the queue. The dictionary may contain up to 5 elements. An empty dictionary will clear the access policies set on the service. :type signed_identifiers: dict of str to :class:`~azure.storage.models.AccessPolicy` :param int timeout: The server timeout, expressed in seconds. ''' _validate_not_none('queue_name', queue_name) request = HTTPRequest() request.method = 'PUT' request.host = self._get_host() request.path = _get_path(queue_name) request.query = [ ('comp', 'acl'), ('timeout', _int_to_str(timeout)), ] request.body = _get_request_body( _convert_signed_identifiers_to_xml(signed_identifiers)) self._perform_request(request)
Sets stored access policies for the queue that may be used with Shared Access Signatures. When you set permissions for a queue, the existing permissions are replaced. To update the queue’s permissions, call :func:`~get_queue_acl` to fetch all access policies associated with the queue, modify the access policy that you wish to change, and then call this function with the complete set of data to perform the update. When you establish a stored access policy on a queue, it may take up to 30 seconds to take effect. During this interval, a shared access signature that is associated with the stored access policy will throw an :class:`AzureHttpError` until the access policy becomes active. :param str queue_name: The name of an existing queue. :param signed_identifiers: A dictionary of access policies to associate with the queue. The dictionary may contain up to 5 elements. An empty dictionary will clear the access policies set on the service. :type signed_identifiers: dict of str to :class:`~azure.storage.models.AccessPolicy` :param int timeout: The server timeout, expressed in seconds.
entailment
def put_message(self, queue_name, content, visibility_timeout=None, time_to_live=None, timeout=None): ''' Adds a new message to the back of the message queue. The visibility timeout specifies the time that the message will be invisible. After the timeout expires, the message will become visible. If a visibility timeout is not specified, the default value of 0 is used. The message time-to-live specifies how long a message will remain in the queue. The message will be deleted from the queue when the time-to-live period expires. :param str queue_name: The name of the queue to put the message into. :param obj content: Message content. Allowed type is determined by the encode_function set on the service. Default is str. The encoded message can be up to 64KB in size. :param int visibility_timeout: If not specified, the default value is 0. Specifies the new visibility timeout value, in seconds, relative to server time. The value must be larger than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message cannot be set to a value later than the expiry time. visibility_timeout should be set to a value smaller than the time-to-live value. :param int time_to_live: Specifies the time-to-live interval for the message, in seconds. The maximum time-to-live allowed is 7 days. If this parameter is omitted, the default time-to-live is 7 days. :param int timeout: The server timeout, expressed in seconds. ''' _validate_not_none('queue_name', queue_name) _validate_not_none('content', content) request = HTTPRequest() request.method = 'POST' request.host = self._get_host() request.path = _get_path(queue_name, True) request.query = [ ('visibilitytimeout', _to_str(visibility_timeout)), ('messagettl', _to_str(time_to_live)), ('timeout', _int_to_str(timeout)) ] request.body = _get_request_body(_convert_queue_message_xml(content, self.encode_function)) self._perform_request(request)
Adds a new message to the back of the message queue. The visibility timeout specifies the time that the message will be invisible. After the timeout expires, the message will become visible. If a visibility timeout is not specified, the default value of 0 is used. The message time-to-live specifies how long a message will remain in the queue. The message will be deleted from the queue when the time-to-live period expires. :param str queue_name: The name of the queue to put the message into. :param obj content: Message content. Allowed type is determined by the encode_function set on the service. Default is str. The encoded message can be up to 64KB in size. :param int visibility_timeout: If not specified, the default value is 0. Specifies the new visibility timeout value, in seconds, relative to server time. The value must be larger than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message cannot be set to a value later than the expiry time. visibility_timeout should be set to a value smaller than the time-to-live value. :param int time_to_live: Specifies the time-to-live interval for the message, in seconds. The maximum time-to-live allowed is 7 days. If this parameter is omitted, the default time-to-live is 7 days. :param int timeout: The server timeout, expressed in seconds.
entailment
def get_messages(self, queue_name, num_messages=None, visibility_timeout=None, timeout=None): ''' Retrieves one or more messages from the front of the queue. When a message is retrieved from the queue, the response includes the message content and a pop_receipt value, which is required to delete the message. The message is not automatically deleted from the queue, but after it has been retrieved, it is not visible to other clients for the time interval specified by the visibility_timeout parameter. :param str queue_name: The name of the queue to get messages from. :param int num_messages: A nonzero integer value that specifies the number of messages to retrieve from the queue, up to a maximum of 32. If fewer are visible, the visible messages are returned. By default, a single message is retrieved from the queue with this operation. :param int visibility_timeout: Specifies the new visibility timeout value, in seconds, relative to server time. The new value must be larger than or equal to 1 second, and cannot be larger than 7 days. The visibility timeout of a message can be set to a value later than the expiry time. :param int timeout: The server timeout, expressed in seconds. :return: A list of :class:`~azure.storage.queue.models.QueueMessage` objects. :rtype: list of :class:`~azure.storage.queue.models.QueueMessage` ''' _validate_not_none('queue_name', queue_name) request = HTTPRequest() request.method = 'GET' request.host = self._get_host() request.path = _get_path(queue_name, True) request.query = [ ('numofmessages', _to_str(num_messages)), ('visibilitytimeout', _to_str(visibility_timeout)), ('timeout', _int_to_str(timeout)) ] response = self._perform_request(request) return _convert_xml_to_queue_messages(response, self.decode_function)
Retrieves one or more messages from the front of the queue. When a message is retrieved from the queue, the response includes the message content and a pop_receipt value, which is required to delete the message. The message is not automatically deleted from the queue, but after it has been retrieved, it is not visible to other clients for the time interval specified by the visibility_timeout parameter. :param str queue_name: The name of the queue to get messages from. :param int num_messages: A nonzero integer value that specifies the number of messages to retrieve from the queue, up to a maximum of 32. If fewer are visible, the visible messages are returned. By default, a single message is retrieved from the queue with this operation. :param int visibility_timeout: Specifies the new visibility timeout value, in seconds, relative to server time. The new value must be larger than or equal to 1 second, and cannot be larger than 7 days. The visibility timeout of a message can be set to a value later than the expiry time. :param int timeout: The server timeout, expressed in seconds. :return: A list of :class:`~azure.storage.queue.models.QueueMessage` objects. :rtype: list of :class:`~azure.storage.queue.models.QueueMessage`
entailment
def clear_messages(self, queue_name, timeout=None): ''' Deletes all messages from the specified queue. :param str queue_name: The name of the queue whose messages to clear. :param int timeout: The server timeout, expressed in seconds. ''' _validate_not_none('queue_name', queue_name) request = HTTPRequest() request.method = 'DELETE' request.host = self._get_host() request.path = _get_path(queue_name, True) request.query = [('timeout', _int_to_str(timeout))] self._perform_request(request)
Deletes all messages from the specified queue. :param str queue_name: The name of the queue whose messages to clear. :param int timeout: The server timeout, expressed in seconds.
entailment
def update_message(self, queue_name, message_id, pop_receipt, visibility_timeout, content=None, timeout=None): ''' Updates the visibility timeout of a message. You can also use this operation to update the contents of a message. This operation can be used to continually extend the invisibility of a queue message. This functionality can be useful if you want a worker role to “lease” a queue message. For example, if a worker role calls get_messages and recognizes that it needs more time to process a message, it can continually extend the message’s invisibility until it is processed. If the worker role were to fail during processing, eventually the message would become visible again and another worker role could process it. :param str queue_name: The name of the queue containing the message to update. :param str message_id: The message id identifying the message to update. :param str pop_receipt: A valid pop receipt value returned from an earlier call to the :func:`~get_messages` or :func:`~update_message` operation. :param int visibility_timeout: Specifies the new visibility timeout value, in seconds, relative to server time. The new value must be larger than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message cannot be set to a value later than the expiry time. A message can be updated until it has been deleted or has expired. :param obj content: Message content. Allowed type is determined by the encode_function set on the service. Default is str. :param int timeout: The server timeout, expressed in seconds. :return: A list of :class:`~azure.storage.queue.models.QueueMessage` objects. Note that only time_next_visible and pop_receipt will be populated. :rtype: list of :class:`~azure.storage.queue.models.QueueMessage` ''' _validate_not_none('queue_name', queue_name) _validate_not_none('message_id', message_id) _validate_not_none('pop_receipt', pop_receipt) _validate_not_none('visibility_timeout', visibility_timeout) request = HTTPRequest() request.method = 'PUT' request.host = self._get_host() request.path = _get_path(queue_name, True, message_id) request.query = [ ('popreceipt', _to_str(pop_receipt)), ('visibilitytimeout', _int_to_str(visibility_timeout)), ('timeout', _int_to_str(timeout)) ] if content is not None: request.body = _get_request_body(_convert_queue_message_xml(content, self.encode_function)) response = self._perform_request(request) return _parse_queue_message_from_headers(response)
Updates the visibility timeout of a message. You can also use this operation to update the contents of a message. This operation can be used to continually extend the invisibility of a queue message. This functionality can be useful if you want a worker role to “lease” a queue message. For example, if a worker role calls get_messages and recognizes that it needs more time to process a message, it can continually extend the message’s invisibility until it is processed. If the worker role were to fail during processing, eventually the message would become visible again and another worker role could process it. :param str queue_name: The name of the queue containing the message to update. :param str message_id: The message id identifying the message to update. :param str pop_receipt: A valid pop receipt value returned from an earlier call to the :func:`~get_messages` or :func:`~update_message` operation. :param int visibility_timeout: Specifies the new visibility timeout value, in seconds, relative to server time. The new value must be larger than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message cannot be set to a value later than the expiry time. A message can be updated until it has been deleted or has expired. :param obj content: Message content. Allowed type is determined by the encode_function set on the service. Default is str. :param int timeout: The server timeout, expressed in seconds. :return: A list of :class:`~azure.storage.queue.models.QueueMessage` objects. Note that only time_next_visible and pop_receipt will be populated. :rtype: list of :class:`~azure.storage.queue.models.QueueMessage`
entailment
def enable_secure_boot(self, secure_boot_enable): """Enable/Disable secure boot on the server. Caller needs to reset the server after issuing this command to bring this into effect. :param secure_boot_enable: True, if secure boot needs to be enabled for next boot, else False. :raises: InvalidInputError, if the validation of the input fails :raises: SushyError, on an error from iLO. """ if not isinstance(secure_boot_enable, bool): msg = ('The parameter "%(parameter)s" value "%(value)s" is ' 'invalid. Valid values are: True/False.' % {'parameter': 'secure_boot_enable', 'value': secure_boot_enable}) raise exception.InvalidInputError(msg) self._conn.patch(self.path, data={'SecureBootEnable': secure_boot_enable})
Enable/Disable secure boot on the server. Caller needs to reset the server after issuing this command to bring this into effect. :param secure_boot_enable: True, if secure boot needs to be enabled for next boot, else False. :raises: InvalidInputError, if the validation of the input fails :raises: SushyError, on an error from iLO.
entailment
def get_allowed_reset_keys_values(self): """Get the allowed values for resetting the system. :returns: A set with the allowed values. """ reset_keys_action = self._get_reset_keys_action_element() if not reset_keys_action.allowed_values: LOG.warning('Could not figure out the allowed values for the ' 'reset keys in secure boot %s', self.path) return set(mappings.SECUREBOOT_RESET_KEYS_MAP_REV) return set([mappings.SECUREBOOT_RESET_KEYS_MAP[v] for v in set(mappings.SECUREBOOT_RESET_KEYS_MAP). intersection(reset_keys_action.allowed_values)])
Get the allowed values for resetting the system. :returns: A set with the allowed values.
entailment
def reset_keys(self, target_value): """Resets the secure boot keys. :param target_value: The target value to be set. :raises: InvalidInputError, if the target value is not allowed. :raises: SushyError, on an error from iLO. """ valid_keys_resets = self.get_allowed_reset_keys_values() if target_value not in valid_keys_resets: msg = ('The parameter "%(parameter)s" value "%(target_value)s" is ' 'invalid. Valid values are: %(valid_keys_reset_values)s' % {'parameter': 'target_value', 'target_value': target_value, 'valid_keys_reset_values': valid_keys_resets}) raise exception.InvalidInputError(msg) value = mappings.SECUREBOOT_RESET_KEYS_MAP_REV[target_value] target_uri = ( self._get_reset_keys_action_element().target_uri) self._conn.post(target_uri, data={'ResetKeysType': value})
Resets the secure boot keys. :param target_value: The target value to be set. :raises: InvalidInputError, if the target value is not allowed. :raises: SushyError, on an error from iLO.
entailment
def _parse_properties(response, result_class): ''' Extracts out resource properties and metadata information. Ignores the standard http headers. ''' if response is None or response.headers is None: return None props = result_class() for key, value in response.headers: info = GET_PROPERTIES_ATTRIBUTE_MAP.get(key) if info: if info[0] is None: setattr(props, info[1], info[2](value)) else: attr = getattr(props, info[0]) setattr(attr, info[1], info[2](value)) return props
Extracts out resource properties and metadata information. Ignores the standard http headers.
entailment
def _parse_response_for_dict(response): ''' Extracts name-values from response header. Filter out the standard http headers.''' if response is None: return None http_headers = ['server', 'date', 'location', 'host', 'via', 'proxy-connection', 'connection'] return_dict = _HeaderDict() if response.headers: for name, value in response.headers: if not name.lower() in http_headers: return_dict[name] = value return return_dict
Extracts name-values from response header. Filter out the standard http headers.
entailment
def _convert_xml_to_service_properties(xml): ''' <?xml version="1.0" encoding="utf-8"?> <StorageServiceProperties> <Logging> <Version>version-number</Version> <Delete>true|false</Delete> <Read>true|false</Read> <Write>true|false</Write> <RetentionPolicy> <Enabled>true|false</Enabled> <Days>number-of-days</Days> </RetentionPolicy> </Logging> <HourMetrics> <Version>version-number</Version> <Enabled>true|false</Enabled> <IncludeAPIs>true|false</IncludeAPIs> <RetentionPolicy> <Enabled>true|false</Enabled> <Days>number-of-days</Days> </RetentionPolicy> </HourMetrics> <MinuteMetrics> <Version>version-number</Version> <Enabled>true|false</Enabled> <IncludeAPIs>true|false</IncludeAPIs> <RetentionPolicy> <Enabled>true|false</Enabled> <Days>number-of-days</Days> </RetentionPolicy> </MinuteMetrics> <Cors> <CorsRule> <AllowedOrigins>comma-separated-list-of-allowed-origins</AllowedOrigins> <AllowedMethods>comma-separated-list-of-HTTP-verb</AllowedMethods> <MaxAgeInSeconds>max-caching-age-in-seconds</MaxAgeInSeconds> <ExposedHeaders>comma-seperated-list-of-response-headers</ExposedHeaders> <AllowedHeaders>comma-seperated-list-of-request-headers</AllowedHeaders> </CorsRule> </Cors> </StorageServiceProperties> ''' service_properties_element = ETree.fromstring(xml) service_properties = ServiceProperties() # Logging logging = service_properties_element.find('Logging') if logging is not None: service_properties.logging = Logging() service_properties.logging.version = logging.find('Version').text service_properties.logging.delete = _bool(logging.find('Delete').text) service_properties.logging.read = _bool(logging.find('Read').text) service_properties.logging.write = _bool(logging.find('Write').text) _convert_xml_to_retention_policy(logging.find('RetentionPolicy'), service_properties.logging.retention_policy) # HourMetrics hour_metrics_element = service_properties_element.find('HourMetrics') if hour_metrics_element is not None: service_properties.hour_metrics = Metrics() _convert_xml_to_metrics(hour_metrics_element, service_properties.hour_metrics) # MinuteMetrics minute_metrics_element = service_properties_element.find('MinuteMetrics') if minute_metrics_element is not None: service_properties.minute_metrics = Metrics() _convert_xml_to_metrics(minute_metrics_element, service_properties.minute_metrics) # CORS cors = service_properties_element.find('Cors') if cors is not None: service_properties.cors = list() for rule in cors.findall('CorsRule'): allowed_origins = rule.find('AllowedOrigins').text.split(',') allowed_methods = rule.find('AllowedMethods').text.split(',') max_age_in_seconds = int(rule.find('MaxAgeInSeconds').text) cors_rule = CorsRule(allowed_origins, allowed_methods, max_age_in_seconds) exposed_headers = rule.find('ExposedHeaders').text if exposed_headers is not None: cors_rule.exposed_headers = exposed_headers.split(',') allowed_headers = rule.find('AllowedHeaders').text if allowed_headers is not None: cors_rule.allowed_headers = allowed_headers.split(',') service_properties.cors.append(cors_rule) # Target version target_version = service_properties_element.find('DefaultServiceVersion') if target_version is not None: service_properties.target_version = target_version.text return service_properties
<?xml version="1.0" encoding="utf-8"?> <StorageServiceProperties> <Logging> <Version>version-number</Version> <Delete>true|false</Delete> <Read>true|false</Read> <Write>true|false</Write> <RetentionPolicy> <Enabled>true|false</Enabled> <Days>number-of-days</Days> </RetentionPolicy> </Logging> <HourMetrics> <Version>version-number</Version> <Enabled>true|false</Enabled> <IncludeAPIs>true|false</IncludeAPIs> <RetentionPolicy> <Enabled>true|false</Enabled> <Days>number-of-days</Days> </RetentionPolicy> </HourMetrics> <MinuteMetrics> <Version>version-number</Version> <Enabled>true|false</Enabled> <IncludeAPIs>true|false</IncludeAPIs> <RetentionPolicy> <Enabled>true|false</Enabled> <Days>number-of-days</Days> </RetentionPolicy> </MinuteMetrics> <Cors> <CorsRule> <AllowedOrigins>comma-separated-list-of-allowed-origins</AllowedOrigins> <AllowedMethods>comma-separated-list-of-HTTP-verb</AllowedMethods> <MaxAgeInSeconds>max-caching-age-in-seconds</MaxAgeInSeconds> <ExposedHeaders>comma-seperated-list-of-response-headers</ExposedHeaders> <AllowedHeaders>comma-seperated-list-of-request-headers</AllowedHeaders> </CorsRule> </Cors> </StorageServiceProperties>
entailment
def insert_entity(self, entity): ''' Adds an insert entity operation to the batch. See :func:`~azure.storage.table.tableservice.TableService.insert_entity` for more information on inserts. The operation will not be executed until the batch is committed. :param entity: The entity to insert. Could be a dict or an entity object. Must contain a PartitionKey and a RowKey. :type entity: a dict or :class:`azure.storage.table.models.Entity` ''' request = _insert_entity(entity) self._add_to_batch(entity['PartitionKey'], entity['RowKey'], request)
Adds an insert entity operation to the batch. See :func:`~azure.storage.table.tableservice.TableService.insert_entity` for more information on inserts. The operation will not be executed until the batch is committed. :param entity: The entity to insert. Could be a dict or an entity object. Must contain a PartitionKey and a RowKey. :type entity: a dict or :class:`azure.storage.table.models.Entity`
entailment
def update_entity(self, entity, if_match='*'): ''' Adds an update entity operation to the batch. See :func:`~azure.storage.table.tableservice.TableService.update_entity` for more information on updates. The operation will not be executed until the batch is committed. :param entity: The entity to update. Could be a dict or an entity object. Must contain a PartitionKey and a RowKey. :type entity: a dict or :class:`azure.storage.table.models.Entity` :param str if_match: The client may specify the ETag for the entity on the request in order to compare to the ETag maintained by the service for the purpose of optimistic concurrency. The update operation will be performed only if the ETag sent by the client matches the value maintained by the server, indicating that the entity has not been modified since it was retrieved by the client. To force an unconditional update, set If-Match to the wildcard character (*). ''' request = _update_entity(entity, if_match) self._add_to_batch(entity['PartitionKey'], entity['RowKey'], request)
Adds an update entity operation to the batch. See :func:`~azure.storage.table.tableservice.TableService.update_entity` for more information on updates. The operation will not be executed until the batch is committed. :param entity: The entity to update. Could be a dict or an entity object. Must contain a PartitionKey and a RowKey. :type entity: a dict or :class:`azure.storage.table.models.Entity` :param str if_match: The client may specify the ETag for the entity on the request in order to compare to the ETag maintained by the service for the purpose of optimistic concurrency. The update operation will be performed only if the ETag sent by the client matches the value maintained by the server, indicating that the entity has not been modified since it was retrieved by the client. To force an unconditional update, set If-Match to the wildcard character (*).
entailment
def merge_entity(self, entity, if_match='*'): ''' Adds a merge entity operation to the batch. See :func:`~azure.storage.table.tableservice.TableService.merge_entity` for more information on merges. The operation will not be executed until the batch is committed. :param entity: The entity to merge. Could be a dict or an entity object. Must contain a PartitionKey and a RowKey. :type entity: a dict or :class:`azure.storage.table.models.Entity` :param str if_match: The client may specify the ETag for the entity on the request in order to compare to the ETag maintained by the service for the purpose of optimistic concurrency. The merge operation will be performed only if the ETag sent by the client matches the value maintained by the server, indicating that the entity has not been modified since it was retrieved by the client. To force an unconditional merge, set If-Match to the wildcard character (*). ''' request = _merge_entity(entity, if_match) self._add_to_batch(entity['PartitionKey'], entity['RowKey'], request)
Adds a merge entity operation to the batch. See :func:`~azure.storage.table.tableservice.TableService.merge_entity` for more information on merges. The operation will not be executed until the batch is committed. :param entity: The entity to merge. Could be a dict or an entity object. Must contain a PartitionKey and a RowKey. :type entity: a dict or :class:`azure.storage.table.models.Entity` :param str if_match: The client may specify the ETag for the entity on the request in order to compare to the ETag maintained by the service for the purpose of optimistic concurrency. The merge operation will be performed only if the ETag sent by the client matches the value maintained by the server, indicating that the entity has not been modified since it was retrieved by the client. To force an unconditional merge, set If-Match to the wildcard character (*).
entailment
def insert_or_replace_entity(self, entity): ''' Adds an insert or replace entity operation to the batch. See :func:`~azure.storage.table.tableservice.TableService.insert_or_replace_entity` for more information on insert or replace operations. The operation will not be executed until the batch is committed. :param entity: The entity to insert or replace. Could be a dict or an entity object. Must contain a PartitionKey and a RowKey. :type entity: a dict or :class:`azure.storage.table.models.Entity` ''' request = _insert_or_replace_entity(entity) self._add_to_batch(entity['PartitionKey'], entity['RowKey'], request)
Adds an insert or replace entity operation to the batch. See :func:`~azure.storage.table.tableservice.TableService.insert_or_replace_entity` for more information on insert or replace operations. The operation will not be executed until the batch is committed. :param entity: The entity to insert or replace. Could be a dict or an entity object. Must contain a PartitionKey and a RowKey. :type entity: a dict or :class:`azure.storage.table.models.Entity`
entailment
def insert_or_merge_entity(self, entity): ''' Adds an insert or merge entity operation to the batch. See :func:`~azure.storage.table.tableservice.TableService.insert_or_merge_entity` for more information on insert or merge operations. The operation will not be executed until the batch is committed. :param entity: The entity to insert or merge. Could be a dict or an entity object. Must contain a PartitionKey and a RowKey. :type entity: a dict or :class:`azure.storage.table.models.Entity` ''' request = _insert_or_merge_entity(entity) self._add_to_batch(entity['PartitionKey'], entity['RowKey'], request)
Adds an insert or merge entity operation to the batch. See :func:`~azure.storage.table.tableservice.TableService.insert_or_merge_entity` for more information on insert or merge operations. The operation will not be executed until the batch is committed. :param entity: The entity to insert or merge. Could be a dict or an entity object. Must contain a PartitionKey and a RowKey. :type entity: a dict or :class:`azure.storage.table.models.Entity`
entailment
def iscsi_settings(self): """Property to provide reference to iSCSI settings instance It is calculated once when the first time it is queried. On refresh, this property gets reset. """ return ISCSISettings( self._conn, utils.get_subresource_path_by( self, ["@Redfish.Settings", "SettingsObject"]), redfish_version=self.redfish_version)
Property to provide reference to iSCSI settings instance It is calculated once when the first time it is queried. On refresh, this property gets reset.
entailment
def update_iscsi_settings(self, iscsi_data): """Update iscsi data :param data: default iscsi config data """ self._conn.patch(self.path, data=iscsi_data)
Update iscsi data :param data: default iscsi config data
entailment
def array_controllers(self): """This property gets the list of instances for array controllers This property gets the list of instances for array controllers :returns: a list of instances of array controllers. """ return array_controller.HPEArrayControllerCollection( self._conn, utils.get_subresource_path_by( self, ['Links', 'ArrayControllers']), redfish_version=self.redfish_version)
This property gets the list of instances for array controllers This property gets the list of instances for array controllers :returns: a list of instances of array controllers.
entailment
def wait_for_operation_to_complete( has_operation_completed, retries=10, delay_bw_retries=5, delay_before_attempts=10, failover_exc=exception.IloError, failover_msg=("Operation did not complete even after multiple " "attempts."), is_silent_loop_exit=False): """Attempts the provided operation for a specified number of times. If it runs out of attempts, then it raises an exception. On success, it breaks out of the loop. :param has_operation_completed: the method to retry and it needs to return a boolean to indicate success or failure. :param retries: number of times the operation to be (re)tried, default 10 :param delay_bw_retries: delay in seconds before attempting after each failure, default 5. :param delay_before_attempts: delay in seconds before beginning any operation attempt, default 10. :param failover_exc: the exception which gets raised in case of failure upon exhausting all the attempts, default IloError. :param failover_msg: the msg with which the exception gets raised in case of failure upon exhausting all the attempts. :param is_silent_loop_exit: decides if exception has to be raised (in case of failure upon exhausting all the attempts) or not, default False (will be raised). :raises: failover_exc, if failure happens even after all the attempts, default IloError. """ retry_count = retries # Delay for ``delay_before_attempts`` secs, before beginning any attempt time.sleep(delay_before_attempts) while retry_count: try: LOG.debug("Calling '%s', retries left: %d", has_operation_completed.__name__, retry_count) if has_operation_completed(): break except exception.IloError: pass time.sleep(delay_bw_retries) retry_count -= 1 else: LOG.debug("Max retries exceeded with: '%s'", has_operation_completed.__name__) if not is_silent_loop_exit: raise failover_exc(failover_msg)
Attempts the provided operation for a specified number of times. If it runs out of attempts, then it raises an exception. On success, it breaks out of the loop. :param has_operation_completed: the method to retry and it needs to return a boolean to indicate success or failure. :param retries: number of times the operation to be (re)tried, default 10 :param delay_bw_retries: delay in seconds before attempting after each failure, default 5. :param delay_before_attempts: delay in seconds before beginning any operation attempt, default 10. :param failover_exc: the exception which gets raised in case of failure upon exhausting all the attempts, default IloError. :param failover_msg: the msg with which the exception gets raised in case of failure upon exhausting all the attempts. :param is_silent_loop_exit: decides if exception has to be raised (in case of failure upon exhausting all the attempts) or not, default False (will be raised). :raises: failover_exc, if failure happens even after all the attempts, default IloError.
entailment
def wait_for_ilo_after_reset(ilo_object): """Continuously polls for iLO to come up after reset.""" is_ilo_up_after_reset = lambda: ilo_object.get_product_name() is not None is_ilo_up_after_reset.__name__ = 'is_ilo_up_after_reset' wait_for_operation_to_complete( is_ilo_up_after_reset, failover_exc=exception.IloConnectionError, failover_msg='iLO is not up after reset.' )
Continuously polls for iLO to come up after reset.
entailment
def wait_for_ris_firmware_update_to_complete(ris_object): """Continuously polls for iLO firmware update to complete.""" p_state = ['IDLE'] c_state = ['IDLE'] def has_firmware_flash_completed(): """Checks for completion status of firmware update operation The below table shows the conditions for which the firmware update will be considered as DONE (be it success or error):: +---------------------+--------------------+ | Previous state | Current state | +=====================+====================+ | IDLE | ERROR | +---------------------+--------------------+ | IDLE | COMPLETED | +---------------------+--------------------+ | PROGRESSING | ERROR | +---------------------+--------------------+ | PROGRESSING | COMPLETED | +---------------------+--------------------+ | PROGRESSING | UNKNOWN | +---------------------+--------------------+ | PROGRESSING | IDLE | +---------------------+--------------------+ """ curr_state, curr_percent = ris_object.get_firmware_update_progress() p_state[0] = c_state[0] c_state[0] = curr_state if (((p_state[0] == 'PROGRESSING') and (c_state[0] in ['COMPLETED', 'ERROR', 'UNKNOWN', 'IDLE'])) or (p_state[0] == 'IDLE' and (c_state[0] in ['COMPLETED', 'ERROR']))): return True return False wait_for_operation_to_complete( has_firmware_flash_completed, delay_bw_retries=30, failover_msg='iLO firmware update has failed.' ) wait_for_ilo_after_reset(ris_object)
Continuously polls for iLO firmware update to complete.
entailment
def wait_for_ribcl_firmware_update_to_complete(ribcl_object): """Continuously checks for iLO firmware update to complete.""" def is_ilo_reset_initiated(): """Checks for initiation of iLO reset Invokes the ``get_product_name`` api and returns i) True, if exception gets raised as that marks the iLO reset initiation. ii) False, if the call gets through without any failure, marking that iLO is yet to be reset. """ try: LOG.debug(ribcl_object._('Checking for iLO reset...')) ribcl_object.get_product_name() return False except exception.IloError: LOG.debug(ribcl_object._('iLO is being reset...')) return True # Note(deray): wait for 5 secs, before checking if iLO reset got triggered # at every interval of 6 secs. This looping call happens for 10 times. # Once it comes out of the wait of iLO reset trigger, then it starts # waiting for iLO to be up again after reset. wait_for_operation_to_complete( is_ilo_reset_initiated, delay_bw_retries=6, delay_before_attempts=5, is_silent_loop_exit=True ) wait_for_ilo_after_reset(ribcl_object)
Continuously checks for iLO firmware update to complete.
entailment
def get_filename_and_extension_of(target_file): """Gets the base filename and extension of the target file. :param target_file: the complete path of the target file :returns: base filename and extension """ base_target_filename = os.path.basename(target_file) file_name, file_ext_with_dot = os.path.splitext(base_target_filename) return file_name, file_ext_with_dot
Gets the base filename and extension of the target file. :param target_file: the complete path of the target file :returns: base filename and extension
entailment
def add_exec_permission_to(target_file): """Add executable permissions to the file :param target_file: the target file whose permission to be changed """ mode = os.stat(target_file).st_mode os.chmod(target_file, mode | stat.S_IXUSR)
Add executable permissions to the file :param target_file: the target file whose permission to be changed
entailment
def get_major_minor(ilo_ver_str): """Extract the major and minor number from the passed string :param ilo_ver_str: the string that contains the version information :returns: String of the form "<major>.<minor>" or None """ if not ilo_ver_str: return None try: # Note(vmud213):This logic works for all strings # that contain the version info as <major>.<minor> # Formats of the strings: # Release version -> "2.50 Feb 18 2016" # Debug version -> "iLO 4 v2.50" # random version -> "XYZ ABC 2.30" pattern = re.search(ILO_VER_STR_PATTERN, ilo_ver_str) if pattern: matched = pattern.group(0) if matched: return matched return None except Exception: return None
Extract the major and minor number from the passed string :param ilo_ver_str: the string that contains the version information :returns: String of the form "<major>.<minor>" or None
entailment
def get_supported_boot_modes(supported_boot_mode_constant): """Retrieves the server supported boot modes It retrieves the server supported boot modes as a namedtuple containing 'boot_mode_bios' as 'true'/'false' (in string format) and 'boot_mode_uefi' again as true'/'false'. :param supported_boot_mode_constant: supported boot_mode constant :returns: A namedtuple containing ``boot_mode_bios`` and ``boot_mode_uefi`` with 'true'/'false' set accordingly for legacy BIOS and UEFI boot modes. """ boot_mode_bios = 'false' boot_mode_uefi = 'false' if (supported_boot_mode_constant == constants.SUPPORTED_BOOT_MODE_LEGACY_BIOS_ONLY): boot_mode_bios = 'true' elif (supported_boot_mode_constant == constants.SUPPORTED_BOOT_MODE_UEFI_ONLY): boot_mode_uefi = 'true' elif (supported_boot_mode_constant == constants.SUPPORTED_BOOT_MODE_LEGACY_BIOS_AND_UEFI): boot_mode_bios = 'true' boot_mode_uefi = 'true' return SupportedBootModes(boot_mode_bios=boot_mode_bios, boot_mode_uefi=boot_mode_uefi)
Retrieves the server supported boot modes It retrieves the server supported boot modes as a namedtuple containing 'boot_mode_bios' as 'true'/'false' (in string format) and 'boot_mode_uefi' again as true'/'false'. :param supported_boot_mode_constant: supported boot_mode constant :returns: A namedtuple containing ``boot_mode_bios`` and ``boot_mode_uefi`` with 'true'/'false' set accordingly for legacy BIOS and UEFI boot modes.
entailment
def _get_key_value(string): """Return the (key, value) as a tuple from a string.""" # Normally all properties look like this: # Unique Identifier: 600508B1001CE4ACF473EE9C826230FF # Disk Name: /dev/sda # Mount Points: None key = '' value = '' try: key, value = string.split(': ') except ValueError: # This handles the case when the property of a logical drive # returned is as follows. Here we cannot split by ':' because # the disk id has colon in it. So if this is about disk, # then strip it accordingly. # Mirror Group 0: physicaldrive 6I:1:5 string = string.lstrip(' ') if string.startswith('physicaldrive'): fields = string.split(' ') # Include fields[1] to key to avoid duplicate pairs # with the same 'physicaldrive' key key = fields[0] + " " + fields[1] value = fields[1] else: # TODO(rameshg87): Check if this ever occurs. return string.strip(' '), None return key.strip(' '), value.strip(' ')
Return the (key, value) as a tuple from a string.
entailment
def _get_dict(lines, start_index, indentation, deep): """Recursive function for parsing hpssacli/ssacli output.""" info = {} current_item = None i = start_index while i < len(lines): current_line = lines[i] current_line_indentation = _get_indentation(current_line) # Check for multi-level returns if current_line_indentation < indentation: return info, i-1 if current_line_indentation == indentation: current_item = current_line.lstrip(' ') info[current_item] = {} i = i + 1 continue if i < len(lines) - 1: next_line_indentation = _get_indentation(lines[i+1]) else: next_line_indentation = current_line_indentation if next_line_indentation > current_line_indentation: ret_dict, i = _get_dict(lines, i, current_line_indentation, deep+1) for key in ret_dict.keys(): if key in info[current_item]: info[current_item][key].update(ret_dict[key]) else: info[current_item][key] = ret_dict[key] else: key, value = _get_key_value(current_line) if key: info[current_item][key] = value # Do not return if it's the top level of recursion if next_line_indentation < current_line_indentation and deep > 0: return info, i i = i + 1 return info, i
Recursive function for parsing hpssacli/ssacli output.
entailment
def _convert_to_dict(stdout): """Wrapper function for parsing hpssacli/ssacli command. This function gets the output from hpssacli/ssacli command and calls the recursive function _get_dict to return the complete dictionary containing the RAID information. """ lines = stdout.split("\n") lines = list(filter(None, lines)) info_dict, j = _get_dict(lines, 0, 0, 0) return info_dict
Wrapper function for parsing hpssacli/ssacli command. This function gets the output from hpssacli/ssacli command and calls the recursive function _get_dict to return the complete dictionary containing the RAID information.
entailment
def _ssacli(*args, **kwargs): """Wrapper function for executing hpssacli/ssacli command. This function executes ssacli command if it exists, else it falls back to hpssacli. :param args: args to be provided to hpssacli/ssacli command :param kwargs: kwargs to be sent to processutils except the following: - dont_transform_to_hpssa_exception - Set to True if this method shouldn't transform other exceptions to hpssa exceptions only when hpssa controller is available. This is useful when the return code from hpssacli/ssacli is useful for analysis. :returns: a tuple containing the stdout and stderr after running the process. :raises: HPSSAOperationError, if some error was encountered and dont_dont_transform_to_hpssa_exception was set to False. :raises: OSError or processutils.ProcessExecutionError if execution failed and dont_transform_to_hpssa_exception was set to True. """ dont_transform_to_hpssa_exception = kwargs.get( 'dont_transform_to_hpssa_exception', False) kwargs.pop('dont_transform_to_hpssa_exception', None) try: if os.path.exists("/usr/sbin/ssacli"): stdout, stderr = processutils.execute("ssacli", *args, **kwargs) else: stdout, stderr = processutils.execute("hpssacli", *args, **kwargs) except (OSError, processutils.ProcessExecutionError) as e: if 'No controllers detected' in str(e): msg = ("SSA controller not found. Enable ssa controller" " to continue with the desired operation") raise exception.HPSSAOperationError(reason=msg) elif not dont_transform_to_hpssa_exception: raise exception.HPSSAOperationError(reason=e) else: raise return stdout, stderr
Wrapper function for executing hpssacli/ssacli command. This function executes ssacli command if it exists, else it falls back to hpssacli. :param args: args to be provided to hpssacli/ssacli command :param kwargs: kwargs to be sent to processutils except the following: - dont_transform_to_hpssa_exception - Set to True if this method shouldn't transform other exceptions to hpssa exceptions only when hpssa controller is available. This is useful when the return code from hpssacli/ssacli is useful for analysis. :returns: a tuple containing the stdout and stderr after running the process. :raises: HPSSAOperationError, if some error was encountered and dont_dont_transform_to_hpssa_exception was set to False. :raises: OSError or processutils.ProcessExecutionError if execution failed and dont_transform_to_hpssa_exception was set to True.
entailment
def refresh(self): """Refresh the server and it's child objects. This method removes all the cache information in the server and it's child objects, and fetches the information again from the server using hpssacli/ssacli command. :raises: HPSSAOperationError, if hpssacli/ssacli operation failed. """ config = self._get_all_details() raid_info = _convert_to_dict(config) self.controllers = [] for key, value in raid_info.items(): self.controllers.append(Controller(key, value, self)) self.last_updated = time.time()
Refresh the server and it's child objects. This method removes all the cache information in the server and it's child objects, and fetches the information again from the server using hpssacli/ssacli command. :raises: HPSSAOperationError, if hpssacli/ssacli operation failed.
entailment
def get_controller_by_id(self, id): """Get the controller object given the id. This method returns the controller object for given id. :param id: id of the controller, for example 'Smart Array P822 in Slot 2' :returns: Controller object which has the id or None if the controller is not found. """ for controller in self.controllers: if controller.id == id: return controller return None
Get the controller object given the id. This method returns the controller object for given id. :param id: id of the controller, for example 'Smart Array P822 in Slot 2' :returns: Controller object which has the id or None if the controller is not found.
entailment
def get_logical_drives(self): """Get all the RAID logical drives in the Server. This method returns all the RAID logical drives on the server by examining all the controllers. :returns: a list of LogicalDrive objects. """ logical_drives = [] for controller in self.controllers: for array in controller.raid_arrays: for logical_drive in array.logical_drives: logical_drives.append(logical_drive) return logical_drives
Get all the RAID logical drives in the Server. This method returns all the RAID logical drives on the server by examining all the controllers. :returns: a list of LogicalDrive objects.
entailment
def get_physical_drives(self): """Get all the RAID physical drives on the Server. This method returns all the physical drives on the server by examining all the controllers. :returns: a list of PhysicalDrive objects. """ physical_drives = [] for controller in self.controllers: # First add unassigned physical drives. for physical_drive in controller.unassigned_physical_drives: physical_drives.append(physical_drive) # Now add physical drives part of RAID arrays. for array in controller.raid_arrays: for physical_drive in array.physical_drives: physical_drives.append(physical_drive) return physical_drives
Get all the RAID physical drives on the Server. This method returns all the physical drives on the server by examining all the controllers. :returns: a list of PhysicalDrive objects.
entailment
def get_logical_drive_by_wwn(self, wwn): """Get the logical drive object given the wwn. This method returns the logical drive object with the given wwn. :param wwn: wwn of the logical drive :returns: LogicalDrive object which has the wwn or None if logical drive is not found. """ disk = [x for x in self.get_logical_drives() if x.wwn == wwn] if disk: return disk[0] return None
Get the logical drive object given the wwn. This method returns the logical drive object with the given wwn. :param wwn: wwn of the logical drive :returns: LogicalDrive object which has the wwn or None if logical drive is not found.
entailment
def get_physical_drive_by_id(self, id): """Get a PhysicalDrive object for given id. This method examines both assigned and unassigned physical drives of the controller and returns the physical drive. :param id: id of physical drive, for example '5I:1:1'. :returns: PhysicalDrive object having the id, or None if physical drive is not found. """ for phy_drive in self.unassigned_physical_drives: if phy_drive.id == id: return phy_drive for array in self.raid_arrays: for phy_drive in array.physical_drives: if phy_drive.id == id: return phy_drive return None
Get a PhysicalDrive object for given id. This method examines both assigned and unassigned physical drives of the controller and returns the physical drive. :param id: id of physical drive, for example '5I:1:1'. :returns: PhysicalDrive object having the id, or None if physical drive is not found.
entailment
def execute_cmd(self, *args, **kwargs): """Execute a given hpssacli/ssacli command on the controller. This method executes a given command on the controller. :params args: a tuple consisting of sub-commands to be appended after specifying the controller in hpssacli/ssacli command. :param kwargs: kwargs to be passed to execute() in processutils :raises: HPSSAOperationError, if hpssacli/ssacli operation failed. """ slot = self.properties['Slot'] base_cmd = ("controller", "slot=%s" % slot) cmd = base_cmd + args return _ssacli(*cmd, **kwargs)
Execute a given hpssacli/ssacli command on the controller. This method executes a given command on the controller. :params args: a tuple consisting of sub-commands to be appended after specifying the controller in hpssacli/ssacli command. :param kwargs: kwargs to be passed to execute() in processutils :raises: HPSSAOperationError, if hpssacli/ssacli operation failed.
entailment
def create_logical_drive(self, logical_drive_info): """Create a logical drive on the controller. This method creates a logical drive on the controller when the logical drive details and physical drive ids are passed to it. :param logical_drive_info: a dictionary containing the details of the logical drive as specified in raid config. :raises: HPSSAOperationError, if hpssacli/ssacli operation failed. """ cmd_args = [] if 'array' in logical_drive_info: cmd_args.extend(['array', logical_drive_info['array']]) cmd_args.extend(['create', "type=logicaldrive"]) if 'physical_disks' in logical_drive_info: phy_drive_ids = ','.join(logical_drive_info['physical_disks']) cmd_args.append("drives=%s" % phy_drive_ids) raid_level = logical_drive_info['raid_level'] # For RAID levels (like 5+0 and 6+0), HPSSA names them differently. # Check if we have mapping stored, otherwise use the same. raid_level = constants.RAID_LEVEL_INPUT_TO_HPSSA_MAPPING.get( raid_level, raid_level) cmd_args.append("raid=%s" % raid_level) # If size_gb is MAX, then don't pass size argument. HPSSA will # automatically allocate the maximum # disks size possible to the # logical disk. if logical_drive_info['size_gb'] != "MAX": size_mb = logical_drive_info['size_gb'] * 1024 cmd_args.append("size=%s" % size_mb) self.execute_cmd(*cmd_args, process_input='y')
Create a logical drive on the controller. This method creates a logical drive on the controller when the logical drive details and physical drive ids are passed to it. :param logical_drive_info: a dictionary containing the details of the logical drive as specified in raid config. :raises: HPSSAOperationError, if hpssacli/ssacli operation failed.
entailment
def _get_erase_command(self, drive, pattern): """Return the command arguments based on the pattern. Erase command examples: 1) Sanitize: "ssacli ctrl slot=0 pd 1I:1:1 modify erase erasepattern=overwrite unrestricted=off forced" 2) Zeros: "ssacli ctrl slot=0 pd 1I:1:1 modify erase erasepattern=zero forced" :param drive: A string with comma separated list of drives. :param pattern: A string which defines the type of erase. :returns: A list of ssacli command arguments. """ cmd_args = [] cmd_args.append("pd %s" % drive) cmd_args.extend(['modify', 'erase', pattern]) if pattern != 'erasepattern=zero': cmd_args.append('unrestricted=off') cmd_args.append('forced') return cmd_args
Return the command arguments based on the pattern. Erase command examples: 1) Sanitize: "ssacli ctrl slot=0 pd 1I:1:1 modify erase erasepattern=overwrite unrestricted=off forced" 2) Zeros: "ssacli ctrl slot=0 pd 1I:1:1 modify erase erasepattern=zero forced" :param drive: A string with comma separated list of drives. :param pattern: A string which defines the type of erase. :returns: A list of ssacli command arguments.
entailment
def erase_devices(self, drives): """Perform Erase on all the drives in the controller. This method erases all the hdd and ssd drives in the controller by overwriting the drives with patterns for hdd and erasing storage blocks for ssd drives. The drives would be unavailable until successful completion or failure of erase operation. If the sanitize erase is not supported on any disk it will try to populate zeros on disk drives. :param drives: A list of drive objects in the controller. :raises: HPSSAOperationError, if sanitize erase is not supported. """ for drive in drives: pattern = 'overwrite' if ( drive.disk_type == constants.DISK_TYPE_HDD) else 'block' cmd_args = self._get_erase_command( drive.id, 'erasepattern=%s' % pattern) stdout = self.execute_cmd(*cmd_args) LOG.debug("Sanitize disk erase invoked with erase pattern as " "'%(pattern)s' on disk type: %(disk_type)s." % {'pattern': pattern, 'disk_type': drive.disk_type}) if "not supported" in str(stdout): new_pattern = 'zero' cmd_args = self._get_erase_command(drive.id, 'erasepattern=zero') self.execute_cmd(*cmd_args) LOG.debug("Sanitize disk erase invoked with erase pattern as " "'%(pattern)s' is not supported on disk type: " "%(disk_type)s. Now its invoked with erase pattern " "as %(new_pattern)s." % {'pattern': pattern, 'disk_type': drive.disk_type, 'new_pattern': new_pattern})
Perform Erase on all the drives in the controller. This method erases all the hdd and ssd drives in the controller by overwriting the drives with patterns for hdd and erasing storage blocks for ssd drives. The drives would be unavailable until successful completion or failure of erase operation. If the sanitize erase is not supported on any disk it will try to populate zeros on disk drives. :param drives: A list of drive objects in the controller. :raises: HPSSAOperationError, if sanitize erase is not supported.
entailment
def can_accomodate(self, logical_disk): """Check if this RAID array can accomodate the logical disk. This method uses hpssacli/ssacli command's option to check if the logical disk with desired size and RAID level can be created on this RAID array. :param logical_disk: Dictionary of logical disk to be created. :returns: True, if logical disk can be created on the RAID array False, otherwise. """ raid_level = constants.RAID_LEVEL_INPUT_TO_HPSSA_MAPPING.get( logical_disk['raid_level'], logical_disk['raid_level']) args = ("array", self.id, "create", "type=logicaldrive", "raid=%s" % raid_level, "size=?") if logical_disk['size_gb'] != "MAX": desired_disk_size = logical_disk['size_gb'] else: desired_disk_size = constants.MINIMUM_DISK_SIZE try: stdout, stderr = self.parent.execute_cmd( *args, dont_transform_to_hpssa_exception=True) except processutils.ProcessExecutionError as ex: # hpssacli/ssacli returns error code 1 when RAID level of the # logical disk is not supported on the array. # If that's the case, just return saying the logical disk # cannot be accomodated in the array. # If exist_code is not 1, then it's some other error that we # don't expect to appear and hence raise it back. if ex.exit_code == 1: return False else: raise exception.HPSSAOperationError(reason=ex) except Exception as ex: raise exception.HPSSAOperationError(reason=ex) # TODO(rameshg87): This always returns in MB, but confirm with # HPSSA folks. match = re.search('Max: (\d+)', stdout) if not match: return False max_size_gb = int(match.group(1)) / 1024 return desired_disk_size <= max_size_gb
Check if this RAID array can accomodate the logical disk. This method uses hpssacli/ssacli command's option to check if the logical disk with desired size and RAID level can be created on this RAID array. :param logical_disk: Dictionary of logical disk to be created. :returns: True, if logical disk can be created on the RAID array False, otherwise.
entailment
def get_physical_drive_dict(self): """Returns a dictionary of with the details of the physical drive.""" if isinstance(self.parent, RaidArray): controller = self.parent.parent.id status = 'active' else: controller = self.parent.id status = 'ready' return {'size_gb': self.size_gb, 'controller': controller, 'id': self.id, 'disk_type': self.disk_type, 'interface_type': self.interface_type, 'model': self.model, 'firmware': self.firmware, 'status': status, 'erase_status': self.erase_status}
Returns a dictionary of with the details of the physical drive.
entailment
def logical_raid_levels(self): """Gets the raid level for each logical volume :returns the set of list of raid levels configured. """ lg_raid_lvls = set() for member in self.get_members(): lg_raid_lvls.add(mappings.RAID_LEVEL_MAP_REV.get(member.raid)) return lg_raid_lvls
Gets the raid level for each logical volume :returns the set of list of raid levels configured.
entailment