Ejemplo n.º 1
0
    def get_data(self):
        self.symbol = str(self.text())
        e = element(self.symbol)

        if e is None:
            # Special Cases only found on atomic number #
            n = {
                "Cn": 112,
                "Uut": 113,
                "Fl": 114,
                "Uup": 115,
                "Lv": 116,
                "Uus": 117,
                "Uuo": 118
            }

            if self.symbol in n:
                e = element(n[self.symbol])

            if e is None:
                print "Not Found: " + self.symbol
                return

        self.mass = e.mass
        self.name = e.name
        self.atomic_number = e.atomic
Ejemplo n.º 2
0
    def __init__(self, atomicNum, xPos, yPos, zPos):
        # Atomic number
        self.atomicNumber = atomicNum

        # Position
        self.xPos = xPos
        self.yPos = yPos
        self.zPos = zPos

        # Average mass
        self.mass = per.element(self.atomicNumber).mass
Ejemplo n.º 3
0
def test_incorrect_elements():
    tests = [
        '125',
        1232,
        'asdfas',
        'HDYROGEN',
    ]
    for test in tests:
        assert periodic.element(test) == None

    return True
Ejemplo n.º 4
0
    def __init__(self,atomicNum,xPos,yPos,zPos):
        # Atomic number
        self.atomicNumber = atomicNum

        # Position
        self.xPos = xPos
        self.yPos = yPos
        self.zPos = zPos

        # Average mass
        self.mass = per.element(self.atomicNumber).mass
Ejemplo n.º 5
0
def get_atm_weight(symb):

    """Gets the weight of a given element symbol

    :param symb: The element symbol, which is able to be suffixed by some
        numerals.

    """

    elem_symb = re.search(r'([a-zA-Z]+)\d*', symb).group(1)
    return periodic.element(elem_symb).mass
Ejemplo n.º 6
0
def test_incorrect_elements():
    tests = [
        '125',
        1232,
        'asdfas',
        'HDYROGEN',
    ]
    for test in tests:
        assert periodic.element(test) == None

    return True
Ejemplo n.º 7
0
def get_center_of_mass(atoms):
    mass = 0.0
    weighted_position = [0.0, 0.0, 0.0]
    for a in atoms:
        for i in range(1,4):
            a[i] = float(a[i])
        a_mass = periodic.element(a[0]).mass
        mass += a_mass
        weighted_position = [x + (a_mass * y) for x, y in \
            zip(weighted_position, a[1:4])]
    return [x/mass for x in weighted_position]
Ejemplo n.º 8
0
def get_atomic_numbers(atoms_list):
    """
	Returns the atomic number of a list of elements.
	"""
    import periodic

    dictionary = {}

    for i in atoms_list:
        element = periodic.element(i)
        atomic_number = element.atomic
        dictionary[i] = [atomic_number]

    return dictionary
Ejemplo n.º 9
0
def readin(coords_dat='coords.dat', eforces_dat='eforces.dat',
           gforces_dat='gforces.dat', modes_dat='modes.dat'):

    # read in the coordinates for your system
    with open(coords_dat, 'r') as file_coords:
        lines_coords = file_coords.readlines()
    num_atoms = len(lines_coords)
    coords = np.zeros((num_atoms, 3))
    atm_mass = np.zeros((num_atoms,3))

    for i, line in enumerate(lines_coords):
        c_info = line.split()
        atm_mass[i, :] = element(c_info[0]).mass*amu2kg
        coords[i, :] = map(float, c_info[1:4])
        coords[i, :] *= atm_mass[i, 0]

    # read in normal modes for your system
    num_modes = (3*num_atoms)
    red_mass = np.zeros(num_modes)
    modes = np.zeros((num_modes, num_modes))
    with open(modes_dat, 'r') as file_modes:
        for i in range(num_modes-6):
            nm_info = file_modes.readline().split()
            red_mass[i+6] = float(nm_info[5])
            if nm_info[1] == str(i+1):
                norm = 0.0
                for j in range(3*num_atoms):
                    mode_info = file_modes.readline().split()
                    modes[i+6, j] = float(mode_info[3])*math.sqrt(atm_mass[int(math.floor(j/3)), 0])
                    norm += modes[i+6, j]*modes[i+6, j]
                modes[i+6, :] /= math.sqrt(norm)
            else:
                print ("Unable to correctly read in the normal modes for your system.")

    # build the translational normal modes for your system
    for i in range(3):
        for j in range(3*num_atoms):
            modes[i, j] = math.sqrt(atm_mass[int(math.floor(j/3)), 0])

    # add a reduced mass of 1.0 for the first 6 normal modes which are rotational and translational modes
    red_mass[0:6] = 1.0

    # read in the excited state forces on your atoms
    eforces = read_forces(eforces_dat)

    # read in the ground state forces on your atoms
    gforces = read_forces(gforces_dat)

    return coords, eforces, gforces, atm_mass, modes
Ejemplo n.º 10
0
def test_correct_elements():
    hydrogen = periodic.session.query(periodic.Element).filter_by(name='Hydrogen').first()
    tests = [
        1,
        '1',
        1.00794,
        '1.00794',
        'H',
        'h',
        'Hydrogen',
        'hydrogen',
    ]

    for test in tests:
        assert hydrogen == periodic.element(test)

    return True
Ejemplo n.º 11
0
def test_correct_elements():
    hydrogen = periodic.session.query(
        periodic.Element).filter_by(name='Hydrogen').first()
    tests = [
        1,
        '1',
        1.00794,
        '1.00794',
        'H',
        'h',
        'Hydrogen',
        'hydrogen',
    ]

    for test in tests:
        assert hydrogen == periodic.element(test)

    return True
Ejemplo n.º 12
0
 def __init__(self, s, n=1):
     self.element = periodic.element(s)
     self.quantity = n
     self.metal = self.element.symbol in metals.metals
Ejemplo n.º 13
0
 def percent(self, s):
     e = periodic.element(s)
     return (e.mass * self.elements[e]) / self.mass()
Ejemplo n.º 14
0
 def __init__(self, ElementName):
     self._rep = Sorter(ElementName)
     self.ElementRep = periodic.element(self._rep[0])
     self.Amount = self._rep[1]
Ejemplo n.º 15
0
    def step(self, timeStamp=0.0):
        self.services.stage_plasma_state()
	print 'Hello from solps-data-iter worker'
	dict = {'task':self.TASK,'rmin':float(self.RMIN),
	        'rmax':float(self.RMAX), 'numr':int(self.NUMR), 
	        'zmin':float(self.ZMIN), 'zmax':float(self.ZMAX), 
		'numz':int(self.NUMZ), 
		'solps_geometry':self.SOLPS_GEOMETRY, 
		'solps_equilibrium':self.SOLPS_EQUILIBRIUM, 
		'solps_state':self.SOLPS_STATE, 
		'gitr_geometry':self.GITR_GEOMETRY, 
		'left_target':self.LEFT_TARGET, 'right_target':self.RIGHT_TARGET, 
		'result':self.RESULT, 'dakota_result':self.DAKOTA_RESULT
		}
	dict2 = {
		'rmin_sep':float(self.RMIN_SEP),'rmax_sep':float(self.RMAX_SEP),
		'zmin_sep':float(self.ZMIN_SEP),'zmax_sep':float(self.ZMAX_SEP)
		}
	arguments='-'+' -'.join("%s=%s" % (key,val) for (key,val) in dict.iteritems())
	print 'Regridding SOLPS Data from %s file using solps geometry %s' %(dict['solps_state'], dict['solps_geometry'])
	print 'Making use of data from %s equilibrium file and GITR geometry %s' %(dict['solps_equilibrium'], dict['gitr_geometry'])
	task_id = self.services.launch_task(self.NPROC,
		        self.services.get_working_dir(),
			self.EXE,arguments,task_ppn=1,logfile='task.log')
        #monitor task until complete
        if (self.services.wait_task(task_id)):
	    self.services.error('solps_iter_data_worker: step failed.')
	    return

	f = open(dict['solps_state'],'r')
	txt = f.readlines()[:200]
	f.close()
	
	znLine=0
	zn = ''
	for count,line in enumerate(txt):
	    if znLine:
	        if '*' in line:
		    break
		else:    
	            zn=''.join((zn,line)) 
	    if 'zn' in line:
	        znLine = count
	
	zaminLine=0
	zamin = ''
	for count,line in enumerate(txt):
	    if zaminLine:
	        if '*' in line:
		    break
		else:    
	            zamin=''.join((zamin,line)) 
	    if 'zamin' in line:
	        zaminLine = count
	
	amLine=0
	am = ''
	for count,line in enumerate(txt):
	    if amLine:
	        if '*' in line:
		    break
		else:    
	            am=''.join((am,line)) 
	    if 'am ' in line:
	        amLine = count

	zn = zn.split()
	zn = [float(i) for i in zn]

        zamin = zamin.split()
	zamin = [float(i) for i in zamin]
	
	am = am.split()
	am = [float(i) for i in am]
	#Section to manually add in Tritium
        zn.insert(2,1.0)
        zamin.insert(2,0.0)
        am.insert(2,3.0)
        zn.insert(3,1.0)
        zamin.insert(3,1.0)
        am.insert(3,3.0)
	nIonSpecies = len(zn)
	
	print 'nIonSpecies',nIonSpecies
	species_file = open("speciesList.txt", "w")
	species_file.write('SpeciesIndex   Z   Mass   Charge\n')
	print 'Existing species for current SOLPS run:\n'
	print 'SpeciesIndex   Z   Mass   Charge\n'
        for i in range(nIonSpecies):
	    print '%f       %f        %f      %f \n' %(i,zn[i],am[i],zamin[i])
            species_file.write('%f       %f        %f      %f \n' %(i,zn[i],am[i],zamin[i]))

	species_file.close()
	headers = 'RminusRsep R Z Ti'
	for i in range(len(zn)):
	    if(zn[i] == 1.0 and am[i]==2.0):
	        headers = headers + ' n_{D'+str(int(zamin[i]))+'+}'
	    elif(zn[i] == 1.0 and am[i]==3.0):
		headers = headers + ' n_{T'+str(int(zamin[i]))+'+}'
	    else:
	        headers = headers + ' n_{'+periodic.element(zn[i]).symbol+str(int(zamin[i]))+'+}'
	for i in range(len(zn)):
	    if(zn[i] == 1.0 and am[i]==2.0):
	        headers = headers + ' f_{D'+str(int(zamin[i]))+'+}'
	    elif(zn[i] == 1.0 and am[i]==3.0):
		headers = headers + ' f_{T'+str(int(zamin[i]))+'+}'
	    else:
	        headers = headers + ' f_{'+periodic.element(zn[i]).symbol+str(int(zamin[i]))+'+}'
	headers = headers + ' Te'+ ' ne'
	headers = headers + ' bAngle bMag'
        headers = headers.split()
        
	rt = np.loadtxt(dict['right_target']) 
	r=rt[:,0]
	z=rt[:,1]
        rSep,bAngle,bMag=solps.getBfield(r,z,filename=dict['solps_equilibrium'],geometryFile=dict['gitr_geometry'],rmin=dict2['rmin_sep'],rmax=dict2['rmax_sep'],zmin=dict2['zmin_sep'],zmax=dict2['zmax_sep'])
	print "Returned getBfield Successfully"
	#print 'rSep',rSep
	#Manually Add Tritium to target profiles
	print rt.shape
	print rt[1][0:2]

	ud = np.c_[rSep,rt[:,0:3]]
	ud = np.c_[ud,0.5*rt[:,3]]
	ud = np.c_[ud,0.5*rt[:,4]]
	ud = np.c_[ud,0.5*rt[:,3]]
	ud = np.c_[ud,0.5*rt[:,4]]
	ud = np.c_[ud,rt[:,5:24]]
	ud = np.c_[ud,0.5*rt[:,24]]
	ud = np.c_[ud,0.5*rt[:,25]]
	ud = np.c_[ud,0.5*rt[:,24]]
	ud = np.c_[ud,0.5*rt[:,25]]
	ud = np.c_[ud,rt[:,26:45]] #rest of flux species
	ud = np.c_[ud,rt[:,45:47]] #te,ne


	ud = np.c_[ud,bAngle]
	ud = np.c_[ud,bMag]
	#print ud
	np.savetxt('solpsTarg.txt',ud)
	for line in fileinput.input('solpsTarg.txt', inplace=True):
	    if fileinput.isfirstline():
	        print ' '.join(headers)
            print line
	plt.close()
	plt.plot(ud[:,0],ud[:,3])
	plt.plot(ud[:,0],ud[:,-4])
	plt.title('ITER Divertor Target Plasma Temperature')
	plt.ylabel('T[eV]')
	plt.xlabel('R-Rsep[m]')
	plt.legend(['Ti','Te'])
	plt.savefig('temp.png')
	plt.close()
	fig = plt.figure()
	ax = plt.subplot(111)
	for y_arr, label in zip(ud[:,4:-3-nIonSpecies].T,headers[4:-3-nIonSpecies]):
	    ax.plot(ud[:,0],y_arr.T,label=label)
	ax.plot(ud[:,0],ud[:,4+2*nIonSpecies],label='ne')
	plt.title('plot title')
	ax.legend()
	plt.title('ITER Divertor Target Plasma Density')
	plt.ylabel('n[m-3]')
	plt.xlabel('R-Rsep[m]')
	plt.yscale('log')
	plt.savefig('dens.png')
	plt.close()
	fig = plt.figure()
	ax = plt.subplot(111)
	#for y_arr, label in zip(ud[:,4+nIonSpecies:4+2*nIonSpecies-3].T,headers[4+nIonSpecies:4+2*nIonSpecies-3]):
	#    ax.plot(ud[:,0],y_arr.T,label=label)
	#    print y_arr
	for i in range(4+nIonSpecies,4+2*nIonSpecies):
	    ax.plot(ud[:,0],np.abs(ud[:,i]),label=headers[i])
        plt.axis([ud[:,0].min(), ud[:,0].max(), 1.0, 1.0e23])
	plt.title('ITER Divertor Target Plasma Flux')
	plt.ylabel('Flux[m-2s-1]')
	plt.xlabel('R-Rsep[m]')
	ax.legend()
	plt.yscale('log')
	plt.savefig('flux.png')
        dak = np.loadtxt('dakota')
	dak= np.reshape(dak,(dict['numr']*dict['numz'],-1))
	print 'dak shape', dak.shape
	rdak = np.unique(dak[:,0])
	print 'rdak',rdak
	rdak = np.unique(dak[:,0])
	zdak = np.unique(dak[:,1])
	te = np.reshape(dak[:,2],(dict['numz'],dict['numr']))
	te[te == -1]=0
	print('te shape', te.shape)
        print(te)
	print('rdak shape', rdak.shape)
        print(rdak[1]-rdak[0])
	print('zdak shape', zdak.shape)
        print(zdak[1]-zdak[0])
	[gradientsR, gradientsZ] = np.gradient(np.array(te),zdak[1]-zdak[0],rdak[1]-rdak[0])
	gradTeZ = gradientsZ
	gradTeR = gradientsR
        plt.close()
        plt.pcolor(rdak,zdak,np.reshape(te,(dict['numz'],dict['numr'])))
        plt.colorbar(orientation='vertical')
        plt.savefig('te.png')
        plt.close()
        plt.pcolor(rdak,zdak,gradTeZ)
        plt.colorbar(orientation='vertical')
        plt.savefig('tez.png')
	#plt.pcolor(rdak,zdak,field1)
	#plt.savefig('field1.png')
	ne = np.reshape(dak[:,3],(dict['numz'],dict['numr']))
	ne[ne == -1]=0
	ti = np.reshape(dak[:,4],(dict['numz'],dict['numr']))
	ti[ti == -1]=0
	[gradientsR,gradientsZ] = np.gradient(np.array(ti),zdak[1]-zdak[0],rdak[1]-rdak[0])
	gradTiZ = gradientsZ
	gradTiR = gradientsR
	ni = np.zeros((nIonSpecies,dict['numz'],dict['numr']))
	vr = np.zeros((nIonSpecies,dict['numz'],dict['numr']))
	vp = np.zeros((nIonSpecies,dict['numz'],dict['numr']))
	vz = np.zeros((nIonSpecies,dict['numz'],dict['numr']))
	niTotal = np.zeros((1,dict['numz'],dict['numr']))
	vrTotal = np.zeros((1,dict['numz'],dict['numr']))
	vpTotal = np.zeros((1,dict['numz'],dict['numr']))
	vzTotal = np.zeros((1,dict['numz'],dict['numr']))
	aveMass = np.zeros((1,dict['numz'],dict['numr']))
	aveCharge = np.zeros((1,dict['numz'],dict['numr']))
	offset=5
	nIonSpecies = 21
	print 'starting ionspec loop',nIonSpecies
	for i in range(nIonSpecies):
	    if i==0:
	        ni[0,:,:] = np.reshape(0.5*dak[:,offset+i],(dict['numz'],dict['numr']))
	        ni[2,:,:] = np.reshape(0.5*dak[:,offset+i],(dict['numz'],dict['numr']))
	        vr[0,:,:] = np.reshape(dak[:,offset+nIonSpecies+i],(dict['numz'],dict['numr']))
	        vr[2,:,:] = np.reshape(dak[:,offset+nIonSpecies+i],(dict['numz'],dict['numr']))
	        vp[0,:,:] = np.reshape(dak[:,offset+2*nIonSpecies+i],(dict['numz'],dict['numr']))
	        vp[2,:,:] = np.reshape(dak[:,offset+2*nIonSpecies+i],(dict['numz'],dict['numr']))
	        vz[0,:,:] = np.reshape(dak[:,offset+3*nIonSpecies+i],(dict['numz'],dict['numr']))
	        vz[2,:,:] = np.reshape(dak[:,offset+3*nIonSpecies+i],(dict['numz'],dict['numr']))
	    elif i==1:
	        ni[1,:,:] = np.reshape(0.5*dak[:,offset+i],(dict['numz'],dict['numr']))
	        ni[3,:,:] = np.reshape(0.5*dak[:,offset+i],(dict['numz'],dict['numr']))
	        vr[1,:,:] = np.reshape(dak[:,offset+nIonSpecies+i],(dict['numz'],dict['numr']))
	        vr[3,:,:] = np.reshape(dak[:,offset+nIonSpecies+i],(dict['numz'],dict['numr']))
	        vp[1,:,:] = np.reshape(dak[:,offset+2*nIonSpecies+i],(dict['numz'],dict['numr']))
	        vp[3,:,:] = np.reshape(dak[:,offset+2*nIonSpecies+i],(dict['numz'],dict['numr']))
	        vz[1,:,:] = np.reshape(dak[:,offset+3*nIonSpecies+i],(dict['numz'],dict['numr']))
	        vz[3,:,:] = np.reshape(dak[:,offset+3*nIonSpecies+i],(dict['numz'],dict['numr']))
	    else:
	        ni[i+2,:,:] = np.reshape(dak[:,offset+i],(dict['numz'],dict['numr']))
	        vr[i+2,:,:] = np.reshape(dak[:,offset+nIonSpecies+i],(dict['numz'],dict['numr']))
	        vp[i+2,:,:] = np.reshape(dak[:,offset+2*nIonSpecies+i],(dict['numz'],dict['numr']))
	        vz[i+2,:,:] = np.reshape(dak[:,offset+3*nIonSpecies+i],(dict['numz'],dict['numr']))
	print "finished ionspec loop"    
        #plt.close()
        #plt.figure(1,figsize=(10, 6), dpi=2000)
        #plotsize = math.ceil(nIonSpecies**(0.5))
        #for i in range(nIonSpecies):
        #    plt.subplot(plotsize,plotsize,i+1)
        ##plot2dGeom('../2d/input/iter2dRefinedOuterTarget.cfg')
        ##plt.title("ITER W Impurity Density")
        ##plt.xlabel("r [m]")
        ##plt.ylabel("z [m]")
        #    plt.pcolor(rdak,zdak,np.reshape(ni[i,:,:],(dict['numz'],dict['numr'])))
        #    plt.colorbar(orientation='vertical')
        #plt.savefig('image1.png')
        print('Starting total loop')
	for i in range(nIonSpecies):
	    if zamin[i] > 0.0:
	        #print niTotal.shape
		#print ni[i,:,:].shape
	        niTotal = niTotal + np.reshape(ni[i,:,:],(1,dict['numz'],dict['numr']))
	        aveMass = aveMass+np.reshape(am[i]*ni[i,:,:],(1,dict['numz'],dict['numr']))
	        aveCharge = aveCharge+np.reshape(zamin[i]*ni[i,:,:],(1,dict['numz'],dict['numr']))
	        vrTotal = vrTotal+np.reshape(np.multiply(vr[i,:,:],ni[i,:,:]),(1,dict['numz'],dict['numr']))
	        vpTotal = vpTotal+np.reshape(np.multiply(vp[i,:,:],ni[i,:,:]),(1,dict['numz'],dict['numr']))
	        vzTotal = vzTotal+np.reshape(np.multiply(vz[i,:,:],ni[i,:,:]),(1,dict['numz'],dict['numr']))
        
        print('Finished total loop')
	aveMass = np.divide(aveMass,niTotal)
	aveMass[np.reshape(ni[i,:,:],(1,dict['numz'],dict['numr'])) == -1]=0
	aveCharge= np.divide(aveCharge,niTotal)
	aveCharge[np.reshape(ni[i,:,:],(1,dict['numz'],dict['numr'])) == -1]=0
	niTotal[np.reshape(ni[i,:,:],(1,dict['numz'],dict['numr'])) == -1]=0
	vrTotal = np.divide(vrTotal,niTotal)
	vrTotal[np.reshape(ni[i,:,:],(1,dict['numz'],dict['numr'])) == -1]=0
	vpTotal = np.divide(vpTotal,niTotal)
	vpTotal[np.reshape(ni[i,:,:],(1,dict['numz'],dict['numr'])) == -1]=0
	vzTotal = np.divide(vzTotal,niTotal)
	vzTotal[np.reshape(ni[i,:,:],(1,dict['numz'],dict['numr'])) == -1]=0
        print('Finished divides')
	#print 'finished loop'	
	#print rdak
	#print zdak
	#print niTotal.shape
	#print niTotal
	plt.close()
	plt.pcolor(rdak,zdak,np.reshape(niTotal,(dict['numz'],dict['numr'])))
	plt.colorbar()
	plt.savefig('niTotal.png')
	plt.close()
	plt.pcolor(rdak,zdak,np.reshape(aveMass,(dict['numz'],dict['numr'])))
	plt.colorbar()
	plt.savefig('aveMass.png')
	plt.close()
	plt.pcolor(rdak,zdak,np.reshape(aveCharge,(dict['numz'],dict['numr'])))
	plt.colorbar()
	plt.savefig('aveCharge.png')
        
	    
        print('Finished plots, getting target bfields')
	br = np.reshape(dak[:,offset+4*nIonSpecies],(dict['numz'],dict['numr']))
	br[br == -1]=0
	bphi = np.reshape(dak[:,offset+4*nIonSpecies+1],(dict['numz'],dict['numr']))
	bphi[bphi == -1]=0
	bz = np.reshape(dak[:,offset+4*nIonSpecies+2],(dict['numz'],dict['numr']))
	bz[bz == -1]=0
	pot = np.reshape(dak[:,offset+4*nIonSpecies+3],(dict['numz'],dict['numr']))
	pot[pot == -1]=0
        [gradz,gradr] = np.gradient(np.array(pot),zdak[1]-zdak[0],rdak[1]-rdak[0])
	Ez = -gradz
        Er = -gradr
	rootgrp = netCDF4.Dataset("profiles.nc", "w", format="NETCDF4")
	nrr = rootgrp.createDimension("nR", len(rdak))
	nzz = rootgrp.createDimension("nZ", len(zdak))
	brr = rootgrp.createVariable("br","f8",("nZ","nR"))
	btt = rootgrp.createVariable("bt","f8",("nZ","nR"))
	bzz = rootgrp.createVariable("bz","f8",("nZ","nR"))
	rr = rootgrp.createVariable("r","f8",("nR"))
	zz = rootgrp.createVariable("z","f8",("nZ"))
	brr[:] = br
	btt[:] = bphi
	bzz[:] = bz
	rr[:] = rdak
	zz[:] = zdak
	tee = rootgrp.createVariable("te","f8",("nZ","nR"))
	nee = rootgrp.createVariable("ne","f8",("nZ","nR"))
	tii = rootgrp.createVariable("ti","f8",("nZ","nR"))
	nii = rootgrp.createVariable("ni","f8",("nZ","nR"))
	mass = rootgrp.createVariable("mass","f8",("nZ","nR"))
	charge = rootgrp.createVariable("charge","f8",("nZ","nR"))
	vrr = rootgrp.createVariable("vr","f8",("nZ","nR"))
	vzz = rootgrp.createVariable("vz","f8",("nZ","nR"))
	vpp = rootgrp.createVariable("vp","f8",("nZ","nR"))
	pott = rootgrp.createVariable("pot","f8",("nZ","nR"))
	Err = rootgrp.createVariable("Er","f8",("nZ","nR"))
	Ett = rootgrp.createVariable("Et","f8",("nZ","nR"))
	Ezz = rootgrp.createVariable("Ez","f8",("nZ","nR"))
	teer = rootgrp.createVariable("gradTeR","f8",("nZ","nR"))
	teez = rootgrp.createVariable("gradTeZ","f8",("nZ","nR"))
	teey = rootgrp.createVariable("gradTeY","f8",("nZ","nR"))
	tiir = rootgrp.createVariable("gradTiR","f8",("nZ","nR"))
	tiiz = rootgrp.createVariable("gradTiZ","f8",("nZ","nR"))
	tiiy = rootgrp.createVariable("gradTiY","f8",("nZ","nR"))
	tee[:] = te
	nee[:] = ne
	tii[:] = ti
	nii[:] = niTotal
	mass[:] = aveMass
	charge[:] = aveCharge
	vrr[:] = vrTotal
	vpp[:] = vpTotal
	vzz[:] = vzTotal
	pott[:] = pot
	Err[:] = Er
	Ett[:] = 0*Er
	Ezz[:] = Ez
	teer[:] = gradTeR
	teey[:] = 0*gradTeR
	teez[:] = gradTeZ
	tiir[:] = gradTiR
	tiiy[:] = 0*gradTiR
	tiiz[:] = gradTiZ
	rootgrp.close()
        self.services.update_plasma_state()        
        return
Ejemplo n.º 16
0
    def get_gamma(self, prvek):  #Toto je dost divné, už jsem to pochopil

        # print(prvek,neco)

        tercove_jadro0 = periodic.element(prvek)
        if tercove_jadro0 == None:
            return {}
        tercove_jadro0hmotnost = str(round(tercove_jadro0.mass))

        tercove_jadro = tercove_jadro0hmotnost + prvek
        pocet_nukleonu = int(re.findall('\d+', tercove_jadro)[0])
        terc_prvek = tercove_jadro.replace(
            re.findall('\d+', tercove_jadro)[0], '')
        # print(pocet_nukleonu,prvek)
        # zkoumane_reakce=['n>2n','n>3n','n>p','n>a']  #'n>4n','n>5n',
        zkoumane_reakce = ['n>5n', 'n>4n', 'n>3n', 'n>2n', 'n>p', 'n>a']
        m_castice = {'n': 1, 'p': 1, 'd': 2, 't': 3, '3He': 3, 'a': 4}
        z_castice = {'n': 0, 'p': 1, 'd': 1, 't': 1, '3He': 2, 'a': 2}
        Gamma = []

        switch_url = 0

        while len(zkoumane_reakce) > 0:

            reakce = zkoumane_reakce.pop()

            ##Změna nukleonového a atomového čísla

            if re.findall('\d+', reakce.split('>')[0]) == []:
                m_in = 1 * m_castice[reakce.split('>')[0]]
                z_in = 1 * z_castice[reakce.split('>')[0]]
            else:
                m_in = int(re.findall('\d+',
                                      reakce.split('>')[0])
                           [0]) * m_castice[reakce.split('>')[0].replace(
                               re.findall('\d+',
                                          reakce.split('>')[0])[0], '')]
                z_in = int(re.findall('\d+',
                                      reakce.split('>')[0])
                           [0]) * z_castice[reakce.split('>')[0].replace(
                               re.findall('\d+',
                                          reakce.split('>')[0])[0], '')]

            if re.findall('\d+', reakce.split('>')[1]) == []:
                m_out = 1 * m_castice[reakce.split('>')[1]]
                z_out = 1 * z_castice[reakce.split('>')[1]]
            else:
                m_out = int(re.findall('\d+',
                                       reakce.split('>')[1])
                            [0]) * m_castice[reakce.split('>')[1].replace(
                                re.findall('\d+',
                                           reakce.split('>')[1])[0], '')]
                z_out = int(re.findall('\d+',
                                       reakce.split('>')[1])
                            [0]) * z_castice[reakce.split('>')[1].replace(
                                re.findall('\d+',
                                           reakce.split('>')[1])[0], '')]

            m = -m_in + m_out
            z = -z_in + z_out

            prvek = periodic.element(periodic.element(terc_prvek).atomic -
                                     z).symbol
            isotop = '%i%s' % (pocet_nukleonu - m, prvek)

            try:
                del stranka
            except NameError:
                nic = 'nic'

            if switch_url == 0:
                self.textBrowser.append(
                    u'Připojuji se na server www.nndc.bnl.gov ')
                QtGui.QApplication.processEvents()
                switch_url = 1

            try:
                url_stranky = 'http://www.nndc.bnl.gov/nudat2/decaysearchdirect.jsp?nuc=%s' % (
                    isotop)
                stranka = requests.get(url_stranky)  #Stáhnutí stránky
                QtGui.QApplication.processEvents()
                # print(url_stranky)
            except requests.exceptions.ConnectionError:
                self.textBrowser.append(
                    u'Nepodařilo se získat data ze serveru www.nndc.bnl.gov ')
                Gamma = []
                return Gamma
            else:
                if switch_url == 1:
                    self.textBrowser.append(u'Hotovo! Načítám data...')
                    switch_url = 2

            text0 = stranka.text  #získání html kódu

            if 'No datasets were found since nucleus is stable' in text0:
                polozka = [
                    1, reakce, 'Q', isotop, 'stabilní', 'stabilní', 'stabilní',
                    'stabilní', 0, 'stabilní', 'stabilní', 'stabilní',
                    'stabilní'
                ]
                Gamma.append(polozka)
                print(polozka)

            elif 'No datasets were found within the specified search parameters' in text0:
                polozka = [
                    1, reakce, 'Q', isotop, 'neznámo', 'neznámo', 'neznámo',
                    'neznámo', 'neznámo', 'neznámo', 'neznámo', 'neznámo',
                    'neznámo'
                ]
                Gamma.append(polozka)
                print(polozka)

            else:
                text1 = BeautifulSoup(
                    text0, 'html.parser'
                )  #částečná extrakce textu z html ku do jednoho řetězce

                text2 = text1.get_text().split(
                    '\n')  #rozdělení tohoto řetězce podle znaku nového řádku

                for i in range(0, len(text2)):
                    # print(text2[i])

                    if 'NucleusDecayScheme' in text2[
                            i]:  #Hledání klíčového slova, po němž jsou ve vstupu uloženy příslušné informace

                        ### Poločas

                        try:
                            del korekceT_2
                        except NameError:
                            pass

                        if text2[i + 1].split(
                        )[4] == 'y':  # Zjištění, v jakých jednotkách (dny, hodiny, minuty, ...) je zdrojová hodnoty poločasu rozpadu
                            korekceT_2 = 1 * 365.25
                        elif text2[i + 1].split()[4] == 'd':
                            korekceT_2 = 1
                        elif text2[i + 1].split()[4] == 'h':
                            korekceT_2 = 1 / 24
                        elif text2[i + 1].split()[4] == 'm':
                            korekceT_2 = 1 / 24 / 60
                        elif text2[i + 1].split()[4] == 's':
                            korekceT_2 = 1 / 24 / 60 / 60
                        elif text2[i + 1].split()[4] == 'ms':
                            korekceT_2 = 1 / 24 / 60 / 60 / 1000
                        elif text2[i + 1].split()[4] == 'µS':
                            korekceT_2 = 1 / 24 / 60 / 60 / 1000 / 1000
                        elif text2[i + 1].split()[4] == 'nS':
                            korekceT_2 = 1 / 24 / 60 / 60 / 1000 / 1000 / 1000

                        T_2d0 = text2[i +
                                      1].split()[3]  # Načtení poločasu rozpadu
                        T_2d = float(T_2d0) * korekceT_2
                        T_2d_err0 = (text2[i + 1].split()[5]
                                     )  #Načtení chyby T1/2
                        if len(
                            (T_2d0).strip().split('.')
                        ) == 2:  #zjištění, zda je poločas uveden s nějakými desetinnými místy:
                            try:
                                T_2d_err = int(T_2d_err0) / (
                                    10**len(str(T_2d0).strip().split('.')[1])
                                ) * korekceT_2  #Určení, kolik desetinných míst má poločas a podle toho náležitá uprava mantisy? chyby poločasu
                            except ValueError:
                                T_2d_err0 = max(
                                    T_2d_err0.strip('+').strip('-').split('-'))
                                T_2d_err = int(T_2d_err0) / (10**len(
                                    str(T_2d0).strip().split('.')[1])
                                                             ) * korekceT_2
                        elif len((T_2d0).strip().split('.')) == 1:
                            T_2d_err = int(T_2d_err0) * korekceT_2

                    if 'Gamma and X' in text2[
                            i]:  #Hledání klíčového slova, po němž jsou ve vstupu uloženy příslušné informace
                        # print(i)
                        poradi = 1
                        b = i + 13
                        try:
                            while (not 'Gamma' in text2[b]) and (not 'Dataset'
                                                                 in text2[b]):
                                text3 = [
                                    text2[b].strip(), text2[b + 1].strip(),
                                    text2[b + 2].strip(), text2[b + 3].strip()
                                ]  #Jednotlivé řádky s požadovanými informacemi s chybami zapsanými u hodnot
                                # print(text3)

                                ## Vytvoření výstupu

                                polozka = [
                                    'poradi', 'reakce', 'Q', 'isotop',
                                    'T/2(d)', 'T/2(s)', 'T/2_err(d)',
                                    'T/2_err(s)', 'Lambda', 'energie', 'e_err',
                                    'intensita', 'i_err'
                                ]

                                ### Energie

                                if len(text3[1].split()
                                       ) == 2 and text3[0] == '':
                                    energie, e_err0 = text3[1].split()
                                    if e_err0 == '?':
                                        e_err = '?'
                                    elif e_err0 == 'S':
                                        e_err = 'S'
                                    else:
                                        e_err = int(e_err0) / (10**len(
                                            str(energie).strip().split('.')[1])
                                                               )
                                    # print(energie,chyba)
                                elif len(text3[1].split()) == 1:
                                    energie = text3[1]
                                    e_err = ''
                                    # print(energie)

                                ### Intenzita

                                intenzita0, intenzita_err0 = text3[2].split(
                                    '%')
                                intenzita = intenzita0.strip()
                                if len(intenzita.strip().split('.')) == 1:
                                    intenzita_err = intenzita_err0  #at už je to rovno '' nebo číslu

                                elif len(intenzita.strip().split('.')) == 2:

                                    if intenzita_err0 != '':
                                        intenzita_err = int(intenzita_err0) / (
                                            10**len(
                                                str(intenzita).strip().split(
                                                    '.')[1]))
                                    else:
                                        intenzita_err = intenzita_err0

                                polozka[0] = poradi
                                poradi += 1

                                polozka[1] = reakce

                                polozka[3] = isotop
                                polozka[4] = T_2d
                                polozka[5] = T_2d * 3600 * 24
                                polozka[6] = T_2d_err
                                polozka[7] = T_2d_err * 3600 * 24
                                polozka[8] = log(2) / polozka[5]
                                polozka[9] = energie
                                polozka[10] = e_err
                                polozka[11] = intenzita
                                polozka[12] = intenzita_err

                                b += 6
                                # print(polozka)
                                Gamma.append(polozka)
                        except IndexError:
                            nic = 'nic'
        return Gamma