def main(argv): OUTCARname='OUTCAR' Nsteps = 1 InitialStep = 0 CurrentTime = 0.0 TimeStep = 0.0 string = '' umd.headerumd() try: opts, arg = getopt.getopt(argv,"hf:i:",["fOUTCARfile","iInitialStep"]) except getopt.GetoptError: print ('VaspParser.py -f <OUTCAR_filename> -i <InitialStep>') sys.exit(2) for opt, arg in opts: if opt == '-h': print ('VaspParser.py program to translate VASP outcar files into UMD ascii format file') print ('VaspParser.py -f <OUTCAR_filename> -i <InitialStep>') print (' default values: -f OUTCAR -i 0') sys.exit() elif opt in ("-f", "--fOUTCARfile"): OUTCARname = str(arg) elif opt in ("-i", "--iInitialStep"): InitialStep = int(arg) if (os.path.isfile(OUTCARname)): (CurrentTime,TimeStep) = read_outcar(OUTCARname,InitialStep) string = 'Total simulation time ' + str(CurrentTime) + ' fs, done in ' + str(int(CurrentTime/TimeStep)) + ' steps of ' + str(TimeStep) + ' fs each.' print(string) else: print ('Error. The outcar files ',OUTCARname,' does not exist') sys.exit()
def main(argv): umd.headerumd() umdfile='OUTCAR.umd.dat' Nsteps = 1 discrete = 0.01 #delta_r = width of bins in histogram InitialStep = 0 #in case we want to skip additional timesteps try: opts, arg = getopt.getopt(argv,"hf:s:d:i:",["fumdfile","sNsteps","ddiscrete","iInitialStep"]) except getopt.GetoptError: print ('gofrs_umd.py -f <UMD_filename> -s <No.steps> -d <discretization.interval> -i <InitialStep>') sys.exit(2) for opt, arg in opts: if opt == '-h': print ('gofrs_umd.py program to compute pair-distribution fuctions g(r) and print all the results in one file') print ('gofrs_umd.py -f <UMD_filename> -s <Nsteps> -d <discretization.interval> -i <InitialStep>') print ('Defaults: Nsteps = 1; discretization.interval=0.01 Angstroms; InitialStep = 0') sys.exit() elif opt in ("-f", "--fumdfile"): umdfile = str(arg) #print('umdfile = ',umdfile) elif opt in ("-s", "--sNsteps"): Nsteps = int(arg) #print('we compute the gofrs every ',Nsteps,' steps') elif opt in ("-d", "--ddiscrete"): discrete = float(arg) #print('the distance delta_r we use to compute the number of atoms around the central one is ',discrete, 'Angstroms') elif opt in ("-i", "--iInitialStep"): InitialStep = int(arg) #print('I will skip ',initial,' timesteps. ') if (os.path.isfile(umdfile)): read_umd(umdfile,Nsteps,discrete,InitialStep) else: print ('the umd file ',umdfile,' does not exist') sys.exit()
def main(argv): umd.headerumd() umdfile = 'output.umd.dat' Nsteps = 1 discrete = 0.01 #delta_r = width of bins in histogram InitialStep = 0 #in case we want to skip additional timesteps try: opts, arg = getopt.getopt( argv, "hf:s:d:i:", ["fumdfile", "Sampling_Frequency", "ddiscrete", "iInitialStep"]) except getopt.GetoptError: print( 'gofrs_umd.py -f <umdfile> -s <No.steps> -d <discretization.interval> -i <InitialStep>' ) sys.exit(2) for opt, arg in opts: if opt == '-h': print( 'gofrs_umd.py program to compute pair-distribution fuctions g(r) and print all the results in one file. Usage:' ) print( 'gofrs_umd.py -f <umdfile> -s <Sampling_Frequency> -d <discretization.interval> -i <InitialStep>' ) print('umdfile = name of the umd file. Default = output.umd.dat') print( 'Sampling_Frequency = frequency of sampling the trajectory. Default = 1' ) print( 'discretization.interval = for plotting the g(r). Default = 0.01 Angstroms' ) print( 'InitialStep = number of initial steps of the trajectory to be removed. Default = 0' ) sys.exit() elif opt in ("-f", "--fumdfile"): umdfile = str(arg) #print('umdfile = ',umdfile) elif opt in ("-s", "--sNsteps"): Nsteps = int(arg) elif opt in ("-d", "--ddiscrete"): discrete = float(arg) #print('the distance delta_r we use to compute the number of atoms around the central one is ',discrete, 'Angstroms') elif opt in ("-i", "--iInitialStep"): InitialStep = int(arg) #print('I will skip ',initial,' timesteps. ') if (os.path.isfile(umdfile)): read_umd(umdfile, Nsteps, discrete, InitialStep) else: print('the umd file ', umdfile, ' does not exist') sys.exit()
def main(argv): XYZfile='file.xyz' hh = 1 vv = 1 ww = 1 natom = 0 typat =[] Elements = [] ballistic = 0 TimeStep = 1 umd.headerumd() try: opts, arg = getopt.getopt(argv,"hf:z:v:b:",["fumdfile","zHorizontalJump","vVerticalJump","bBallistic"]) except getopt.GetoptError: print ('msd_umd.py -f <XYZ_filename> -z <HorizontalJump> -v <VerticalJump> -b <Ballistic>') sys.exit(2) for opt, arg in opts: if opt == '-h': print ('Program to compute the Mean Square Displacement. Usage: ') print ('msd_umd.py -f <UMD_filename> -z <HorizontalJump> -v <VerticalJump> -b <Ballistic>') print ('UMD_filename = input file with the trajectory, in UMD format.') print (' As the MSD is measured with a sliding window of various size up to half the trajectory\'s length, ') print (' we can accelerate the calculation using a selected reduced sampling ') print ('HorizontalJump = discretization for the start of the sampling window.') print ('VerticalJump = discretization for the length of the sampling window.') print ('Ballistic = estimation of the ballistic part of the trajectory. Default is 0. Typical values of 100 are sufficient.') sys.exit() elif opt in ("-f", "--fumdfile"): umdfile = str(arg) print ('I will use the ',umdfile,' for input') elif opt in ("-z", "--zHorizontalJump"): hh = int(arg) elif opt in ("-v", "--vVerticalJump"): vv = int(arg) elif opt in ("-b", "--bBallistic"): ballistic = int(arg) if (os.path.isfile(umdfile)): # initstruct(XYZfile) MyCrystal = cr.Lattice() AllSnapshots = [cr.Lattice] (MyCrystal,AllSnapshots,TimeStep)=umd.read_absxcart(umdfile) # (MyCrystal,AllSnapshots,TimeStep)=up.readumd(umdfile) # print 'Elements are ',elem print ('Number of atoms of each type is ',MyCrystal.types) # print 'Atomic types are ',znucl msd(MyCrystal,AllSnapshots,TimeStep,hh,vv,ballistic,umdfile) else: print ('umd file ',umdfile,'does not exist') sys.exit()
def main(argv): iterstep = 1 firststep = 0 laststep = 10000000 UMDname = 'output.umd.dat' up.headerumd() try: opts, arg = getopt.getopt(argv, "hf:i:l:s:") except getopt.GetoptError: print( 'umd2poscar.py -f <umdfile> -i <InitialStep> l <LastStep> -s <Sampling_Frequency>' ) sys.exit(2) for opt, arg in opts: if opt == '-h': print( 'umd2poscar.py program to extract POSCAR snapshots from the umd file' ) print( 'umd2poscar.py -f <umdfile> -i <InitialStep> l <LastStep> -s <Sampling_Frequency>' ) print(' default values: -f output.umd.dat -i 0 -l 10000000 -s 1') sys.exit() elif opt in ("-f"): UMDname = str(arg) elif opt in ("-i"): firststep = int(arg) elif opt in ("-l"): laststep = int(arg) elif opt in ("-s"): iterstep = int(arg) if (os.path.isfile(UMDname)): print('The first ', firststep, 'timesteps will be discarded') print('The POSCAR file contains every ', iterstep, ' timesteps') MyCrystal = cr.Lattice() AllSnapshots = [cr.Lattice] (MyCrystal, AllSnapshots, TimeStep) = up.readumd(UMDname) if laststep > len(AllSnapshots): laststep = len(AllSnapshots) print_poscar(MyCrystal, AllSnapshots, UMDname, firststep, laststep, iterstep) else: print('the umdfile ', umdfile, ' does not exist') sys.exit()
def main(argv): FileName = '' SkipSteps = 0 up.headerumd() try: opts, arg = getopt.getopt(argv, "hf:i:", ["fFileName,iInitialStep"]) except getopt.GetoptError: print('averages.py -f <FileName> -i <InitialStep>') sys.exit() for opt, arg in opts: if opt == '-h': print('averages.py -f <FileName> -i <InitialStep>') print( 'averages.py program to extract the average and the spread of the numerical values of Pressure, Temperature, and InternalEnergy' ) sys.exit() elif opt in ("-f", "--fFileName"): FileName = str(arg) elif opt in ("-i", "--sSkipSteps"): SkipSteps = int(arg) #print(FileName) if (os.path.isfile(FileName)): #****Calculations and creation of arrays Pressure, Average_P, stdev_P = grep_pattern(FileName, "Pressure", SkipSteps) Temperature, Average_T, stdev_T = grep_pattern(FileName, "Temperature", SkipSteps) Energy, Average_E, stdev_E = grep_pattern(FileName, "InternalEnergy", SkipSteps) arraytowrite = FileName + '\t#PstdTstdEstd\t' + str( len(Pressure)) + '\t' + str(Average_P) + '\t' + str( stdev_P) + '\t' + str(Average_T) + '\t' + str( stdev_T) + '\t' + str(Average_E) + '\t' + str(stdev_E) #print('Averages over no.steps, P, stdev_P, T, stdev_T, E, stdev_E',len(Pressure),Average_P,stdev_P,Average_T,stdev_T,Average_E,stdev_E) print(arraytowrite) else: print('No input file or file "', FileName, '" does not exist') sys.exit()
def main(argv): iterstep = 1 firststep = 0 UMDname = 'output.umd.dat' UMDname = '' up.headerumd() try: opts, arg = getopt.getopt(argv, "hf:i:n:") except getopt.GetoptError: print( 'umd2xyz.py -f <umdfile> -i <InitialStep> -s <Sampling_Frequency>') sys.exit(2) for opt, arg in opts: if opt == '-h': print( 'umd2xyz.py program to write an xyz file with the atomic trajectories from the umd file' ) print( 'umd2xyz.py -f <umdfile> -i <InitialStep> -s <Sampling_Frequency>' ) print(' default values: -f output.umd.dat -i 0 -s 1') sys.exit() elif opt in ("-f"): UMDname = str(arg) elif opt in ("-i"): firststep = int(arg) elif opt in ("-n"): iterstep = int(arg) if (os.path.isfile(UMDname)): print('The first ', firststep, 'timesteps will be discarded') print('The XYZ file contains every ', iterstep, ' timesteps') MyCrystal = cr.Lattice() AllSnapshots = [cr.Lattice] (MyCrystal, AllSnapshots, TimeStep) = up.readumd(UMDname) print_xyz(MyCrystal, AllSnapshots, UMDname, firststep, iterstep) else: print('the umdfile ', umdfile, ' does not exist') sys.exit()
def read_umd(umdfile, radius, Nsteps, InitialStep, level): """Read umd file and store data into classes """ umd.headerumd() niter = 0 istep = 0 MyCrystal = cr.Lattice() with open( umdfile, 'r' ) as ff: #read the head and half of the 1st iter in order to get acell while True: line = ff.readline() if not line: break #print(line,len(line)) if len(line) > 1: line = line.strip() entry = line.split() if entry[0] == 'natom': MyCrystal.natom = int(entry[1]) #print('natom=',MyCrystal.natom) MyCrystal.typat = [0 for _ in range(MyCrystal.natom)] if entry[0] == 'ntypat': MyCrystal.ntypat = int(entry[1]) MyCrystal.types = [0 for _ in range(MyCrystal.ntypat)] MyCrystal.elements = ['X' for _ in range(MyCrystal.ntypat)] if entry[0] == 'types': for ii in range(MyCrystal.ntypat): MyCrystal.types[ii] = int(entry[ii + 1]) if entry[0] == 'elements': for ii in range(MyCrystal.ntypat): MyCrystal.elements[ii] = entry[ii + 1] if entry[0] == 'typat': for ii in range(MyCrystal.natom): MyCrystal.typat[ii] = int(entry[ii + 1]) if entry[0] == 'acell': for i in range(3): MyCrystal.acell[i] = float(entry[i + 1]) newfile = print_header(umdfile, MyCrystal, radius) #create the new file with open(umdfile, 'r') as ff: #read the entire file to get the atomic positions while True: line = ff.readline() if not line: break #print(line,len(line)) if len(line) > 1: line = line.strip() entry = line.split() if entry[0] == 'atoms:': istep += 1 #print('current iteration no.',istep) MySnapshot = cr.Lattice() MySnapshot.atoms = [ cr.Atom() for _ in range(MyCrystal.natom) ] for iatom in range(MyCrystal.natom): line = ff.readline() line = line.strip() entry = line.split() for jj in range(3): MySnapshot.atoms[iatom].xcart[jj] = float( entry[jj + 3]) #print(MySnapshot.atoms[iatom].xcart[0]) if istep > InitialStep: if niter % Nsteps == 0: #if the remainder of niter/Nsteps is 0, then I compute the dmin #print (' at step ',istep,' I am calling dmin ') dmin = computealldmin(MyCrystal, MySnapshot) overlap = computeoverlap(dmin, radius, MyCrystal) print_overlap(newfile, overlap, dmin, istep, MyCrystal, radius, level) niter += 1
def main(argv): up.headerumd() UMDname = 'output.umd.dat' Nsteps = 1 InitialStep = 0 ClusterAtoms = [] Cations = [] Anions = [] maxlength = 3.0 InputFile = '' minlife = 5 rings = 1 header = '' try: opts, arg = getopt.getopt(argv, "hf:s:l:c:a:m:i:r:", [ "fUMDfile", "sSampling_Frequency", "lMaxLength", "cCations", "aAnions", "mMinlife", "iInputFile", "rRings" ]) except getopt.GetoptError: print( 'speciation.py -f <UMD_filename> -s <Sampling_Frequency> -l <MaxLength> -c <Cations> -a <Anions> -m <MinLife> -i <InputFile> -r <Rings>' ) sys.exit(2) for opt, arg in opts: if opt == '-h': print( 'speciation.py program to compute bonding maps and identify speciation' ) print( 'speciation.py -f <UMD_filename> -s <Sampling_Frequency> -l <MaxLength> -c <Cations> -a <Anions> -m <MinLife> -i <InputFile> -r <Rings>' ) print(' default values: -f output.umd.dat -s 1 -l 3.0 -m 0 -r 1') print( ' the input file contains the bond lengths for the different atom pairs. \n the values overwrite the option -l' ) print( ' rings = 1 default, polymerization, all anions and cations bond to each other; rings = 0 only individual cation-anion groups' ) sys.exit() elif opt in ("-f", "--fUMDfile"): UMDname = str(arg) header = header + 'FILE: -f=' + UMDname elif opt in ("-s", "--sNsteps"): Nsteps = int(arg) header = header + ' -s=' + arg print('Will sample the MD trajectory every ', Nsteps, ' steps') elif opt in ("-l", "--lMaxLength"): maxlength = float(arg) print('Maximum bonding length is', maxlength) header = header + ' -l=' + str(maxlength) elif opt in ("-m", "--mMinlife"): minlife = float(arg) elif opt in ("-c", "--Cations"): header = header + arg Cations = arg.split(",") #print ('Cation list is: ',Cations) elif opt in ("-a", "--Anions"): header = header + arg Anions = arg.split(",") #print ('Anion list is: ',Anions) elif opt in ("-i", "--iInputFile"): InputFile = str(arg) header = header + ' -i=' + InputFile print('Bonding cutoffs to be read from file ', InputFile) elif opt in ("-r", "--rRings"): rings = int(arg) header = header + ' -r=' + arg if rings == 0: print('Calculation of non-polymerized coordination polyhedra') elif rings == 1: print('Calculation of polymerized coordination') else: print('Undefined calculation') if not (os.path.isfile(UMDname)): print('the UMD files ', UMDname, ' does not exist') sys.exit() for ii in range(len(Cations)): ClusterAtoms.append(Cations[ii]) for ii in range(len(Anions)): ClusterAtoms.append(Anions[ii]) if rings == 0: print('searching for cations', Cations) print('surrounded by anions ', Anions) else: print('all atoms bonding:', ClusterAtoms) #writes the header of the files containing eventually the clusters header = header + '\n' FileAll = UMDname + '.r' + str(rings) + '.popul.dat' print('Population will be written in ', FileAll, ' file') fa = open(FileAll, 'w') fa.write(header) fa.close() FileStat = UMDname + '.r' + str(rings) + '.stat.dat' print('Statistics will be written in ', FileStat, ' file') fa = open(FileStat, 'w') fa.write(header) fa.close() #reading the xc art coordinates of the atoms from the UMD file. it uses the read_xcart (i.e. only xcart) function from the umd_process library MyCrystal = cr.Lattice() AllSnapshots = [cr.Lattice] (MyCrystal, AllSnapshots, TimeStep) = up.read_xcart(UMDname) #print('checks after reading the umd file') #print('no of atoms = ',MyCrystal.natom) #reading the cutoff radii for the bonds BondTable = [[maxlength * maxlength for _ in range(MyCrystal.ntypat)] for _ in range(MyCrystal.ntypat)] if len(InputFile) > 0: BondTable = read_inputfile(InputFile, MyCrystal, ClusterAtoms) #print ('unique bondlength, with square',maxlength) #defining the ligands, the coordinated and the coordinating atoms centralatoms = [] outeratoms = [] ligands = [] for iatom in range(MyCrystal.natom): for jatom in range(len(ClusterAtoms)): if MyCrystal.elements[ MyCrystal.typat[iatom]] == ClusterAtoms[jatom]: ligands.append( iatom ) #contains the list with the index of the ligand atoms from the 0 ... natom for iatom in range(MyCrystal.natom): for jatom in range(len(Cations)): if MyCrystal.elements[MyCrystal.typat[iatom]] == Cations[jatom]: centralatoms.append( iatom ) #contains the list with the index of the central atoms from the 0 ... natom for jatom in range(len(Anions)): if MyCrystal.elements[MyCrystal.typat[iatom]] == Anions[jatom]: outeratoms.append( iatom ) #contains the list with the index of the coordinating atoms from the 0 ... natom print('All ligands are: ', ligands) print('Central atoms are :', centralatoms) print('Coordinating atoms are :', outeratoms) #span the entire trajectory and analyze only the Nsteps snapshots clusters = [] for istep in range(0, len(AllSnapshots), Nsteps): #print('analyzing new simulation snapshot, step no. ',istep) #first build the bonding maps BondMap = [[0.0 for _ in range(MyCrystal.natom)] for _ in range(MyCrystal.natom)] BooleanMap = [[0 for _ in range(MyCrystal.natom)] for _ in range(MyCrystal.natom)] (BondMap, BooleanMap) = ComputeBondMapInput(MyCrystal, AllSnapshots[istep], ligands, BondTable) if rings == 1: clusters.append(clustering(BooleanMap, ligands)) elif rings == 0: clusters.append( clusteringnorings(BooleanMap, centralatoms, outeratoms)) #print('number of identified clusters ',len(clusters)) #print(' clusters at this point:\n',clusters) else: print( 'value of rings = ', rings, ' is not allowed. Only 0 (polymers) or 1 (coordinating polyhedra) are allowed', ) sys.exit() analysis_clusters(clusters, MyCrystal, ligands, minlife, Nsteps, UMDname, rings)
def main(argv): umd.headerumd() iterstep = 1 firststep = 0 UMDname = '' originshift = 1 length = 4000 temperature = 1000 try: opts, arg = getopt.getopt(argv, "hf:t:i:s:o:l:") except getopt.GetoptError: print( 'viscosity_umd.py -f <umdfile> -i <Initial TimeStep> -s <Sampling_Frequency> -o <frequency of origin shift> -l <correlation timelength>' ) sys.exit(2) for opt, arg in opts: if opt == '-h': print( 'viscosity_umd.py to compute the viscosity of the fluid from a fit on the self-correlation of stresses' ) print( ' viscosity_umd.py -f <umdfile> -i <InitialStep> -s <Sampling_Frequency> -o <frequency_of_origin_shift> -l <max_correlation_timelength>' ) print('umdfile = input file with the trajectory, in UMD format.') print('Initial TimeStep from umd file. Default = 0') print( 'Sampling_Frequency = frequency of sampling the trajectory. Default = 1' ) print('Frequency_of_origin_shift. Default = 1') print( '-l = maximum timelength for the correlation. Default = 4000>') sys.exit() elif opt in ("-f"): UMDname = str(arg) elif opt in ("-t"): temperature = int(arg) elif opt in ("-i"): firststep = int(arg) elif opt in ("-n"): iterstep = int(arg) elif opt in ("-s"): originshift = int(arg) elif opt in ("-l"): length = int(arg) if (os.path.isfile(UMDname)): print('The first ', firststep, 'timesteps will be discarded') print('The umd.dat file is read every ', iterstep, ' timesteps') # AllSnapshots = [cr.Lattice] AllSnapshots = [] (AllSnapshots, TimeStep) = umd.read_stresses_4visc(UMDname) print('Len(allsnapshots),timestep : ', len(AllSnapshots), TimeStep) volume = AllSnapshots[0].cellvolume temperature = 0.0 for ii in range(firststep, len(AllSnapshots)): temperature = temperature + AllSnapshots[ii].temperature # print('current temperature at step ',ii,' is:', AllSnapshots[ii].temperature) temperature = temperature / (len(AllSnapshots) - firststep) print('Average temperature from the umd file = ', temperature) if (length > len(AllSnapshots)): print('The length requested (', length, ') is too long for the whole duration of the trajectory(', len(AllSnapshots), ')') print('Will impose the length of the trajectory') length = len(AllSnapshots) ViscosityAnalysis(AllSnapshots, TimeStep, firststep, originshift, length, temperature) else: print('the umdfile ', umdfile, ' does not exist') sys.exit()
def main(argv): umd.headerumd() umdfile = 'output.umd.dat' temperature = 5000 # start_time = time.time() #--------------------------------------------- # Warning #maxtau == max correlation time, should be # less than 1/2*total_simulation_steps #--------------------------------------------- try: opts, arg = getopt.getopt(argv,"hf:t:",["help","fumdfile="]) except getopt.GetoptError: print ('Usage: vel_correlation_umd.py -f <UMDfilename> -t <temperature>') sys.exit(2) for opt, arg in opts: if opt in ('-h', "--help"): print ('vel_correlation_umd.py program to compute the atomic velocity self-correlation') print (' and extract rlevant properties: vibrational spectrum and diffusion coefficient') print ('vel_correlation_umd.py -f <umdfilename> -t <temperature>') print (' the program needs an UMD file prepared and the temperature') print (' defaults are: output.umd.dat and 5000K') sys.exit() elif opt in ("-f", "--fumdfile"): umdfile = arg print ('I will use the ',umdfile,' for input') elif opt in ("-t"): temperature = float(arg) print('the temperature is',temperature) if not (os.path.isfile(umdfile)): print ('umd file ',umdfile,'does not exist') sys.exit() Boltzmann=8.6173303*10**(-5) #eV Avogadro=6.022140857*(10**(23)) # mol-1 au_angstrom_squre = 1.0 / Avogadro * (10**(-3)) * (10**10) / (1.602176634 * 10**-19) # unit is eV kB_T = temperature * Boltzmann # read umdfile (MyCrystal,AllSnapshots,TimeStep)=umd.readumd(umdfile,0) # make TimeMatrix file TimeMatrix = np.empty((len(AllSnapshots),3*MyCrystal.natom)) for ii in range(len(AllSnapshots)): icounter = -1 for jj in range(MyCrystal.natom): for zz in range(3): icounter = icounter + 1 TimeMatrix[ii][icounter]=AllSnapshots[ii].atoms[jj].vels[zz] # correlation for different atom, direction autocorrelation,fft_correlation,freq = correlation(TimeMatrix,TimeStep,temperature) # average over species, and mass weighted average_correlation = np.zeros((len(autocorrelation),MyCrystal.ntypat)) total_average_correlation = np.zeros(len(autocorrelation)) for ii in range(len(autocorrelation)): icounter = -1 for jj in range(MyCrystal.natom): for zz in range(3): icounter = icounter + 1 average_correlation[ii][MyCrystal.typat[jj]] = average_correlation[ii][MyCrystal.typat[jj]] + autocorrelation[ii][icounter] * MyCrystal.masses[MyCrystal.typat[jj]] total_average_correlation = np.sum(average_correlation,axis=1) temp = total_average_correlation[0] total_average_correlation[:] = total_average_correlation[:] / temp temp = np.copy(average_correlation[0]) #normalization for ii in range(MyCrystal.ntypat): average_correlation[:,ii] = average_correlation[:,ii] / temp[ii] # average over species, and mass weighted diffusion_coefficient = np.zeros(MyCrystal.ntypat) average_fft_correlation = np.zeros((len(autocorrelation),MyCrystal.ntypat)) total_fft_correlation = np.zeros(len(autocorrelation)) for ii in range(len(fft_correlation)): icounter = -1 for jj in range(MyCrystal.natom): for zz in range(3): icounter = icounter + 1 average_fft_correlation[ii][MyCrystal.typat[jj]] = average_fft_correlation[ii][MyCrystal.typat[jj]] + fft_correlation[ii][icounter] * MyCrystal.masses[MyCrystal.typat[jj]] for ii in range(MyCrystal.ntypat): average_fft_correlation[:,ii] = average_fft_correlation[:,ii] * 2 * au_angstrom_squre / kB_T #normalize to 3N -3 diffusion_coefficient[ii] = average_fft_correlation[0][ii] / 12.0 / MyCrystal.types[ii] * kB_T *(1.602176634 * 10**-19) /(1.0 / Avogadro * (10**(-3)) * MyCrystal.masses[ii]) * 10**(-15) total_fft_correlation = np.sum(average_fft_correlation,axis=1) print('sum of average_fft_correlation:','theory gives a value (3N-3 =',3*MyCrystal.natom-3,') ,numerical calcualtion gives',np.trapz(np.sum(average_fft_correlation,axis=1),freq)) print ('\n Diffusion:') print('For elements:',MyCrystal.elements) print('The diffusion coefficients are',diffusion_coefficient, 'in m^2/s') with open(umdfile[:-8] + '.diff.dat','w') as df: df.write("\t".join(str(x) for x in diffusion_coefficient)+ "\n") #--------------------------------------------- vaffilename = umdfile[:-8] + '.vels.scf.dat' nf = open(vaffilename,'w') headerstring = 'Vel_AutoCorr_Fct(fs)\t' for itype in range(MyCrystal.ntypat): headerstring = headerstring + MyCrystal.elements[itype] + '\t' headerstring = headerstring + '\n' nf.write(headerstring) # nf.write('velocity autocorrelation function(correlation_time(fs) species1 species2 ... total)\n') for ii in range(len(average_correlation)): string=str(ii*TimeStep) for jj in range(MyCrystal.ntypat): string=string + ' '+ str(average_correlation[ii][jj]) string = string + ' ' + str(total_average_correlation[ii]) + '\n' nf.write(string) nf.close() specfilename = umdfile[:-8] + '.vibr.dat' nf = open(specfilename,'w') headerstring = 'Frequency(cm^-1)\t' for itype in range(MyCrystal.ntypat): headerstring = headerstring + 'VDos_' + MyCrystal.elements[itype] + '\t' headerstring = headerstring + 'Total_DOS\n' nf.write(headerstring) for ii in range(len(fft_correlation)): string=str(freq[ii]*33356.41) for jj in range(MyCrystal.ntypat): string=string+' '+str(average_fft_correlation[ii][jj]) string = string + '\t' + str(total_fft_correlation[ii]) + '\n' nf.write(string) nf.close()
def main(argv): """ ********* Main program ********* """ SkipSteps = 0 units = 0 #parameters Na = 6.022e23 #Avogadro constant eVtoJ = 1.6e-19 #1eV = 1.6e-19 J KtoeV = 0.000086173324 #1K = 8.62E-5 eV kb = 1.38064852e-23 #boltzmann constant umd.headerumd() try: options, arg = getopt.getopt(argv, "hs:u:", ["sSkipSteps", "units"]) except getopt.GetoptError: print( 'fullaverages.py -s <SkipSteps> -u <units version: 0 = minimal (default), 1 = full units>' ) sys.exit() for opt, arg in options: if opt == '-h': print( 'fullaverages.py -s <SkipSteps> -u <units version: 0 = minimal (default), 1 = full units>' ) print( 'Program to extract and average thermodynamic data from all the umd files in the current folder' ) print( 'As ouptut it produces a fullthermo.dat file. On each line there are specified in order: ' ) print(' - the umd filename, the number of snapshots') print(' - 3 columns per variable (rho,P,T,E)') print(' - average') print(' - stdev of data to the mean') print(' - statistical error on the mean') print( ' - 2 columns for the Cv(Nkb) with the calculated value and statistical error' ) print( 'WARNING: please note that the Cv formulation is valdid *only* for NVT simulations' ) print(' ') sys.exit() elif opt in ("-s", "--sSkipSteps"): SkipSteps = int(arg) elif opt in ("-u", "--units"): units = int(arg) #Initialization files = sorted( glob.glob('*.umd.dat')) #list every umd files in alphabetic order f, natom = headerfile(files[0], units) #I create the first newfile for averages #Calculation for each file and writing of the newfile for file in files: results = [ ] #initialization of the final result array, used to print each line of result in the new file is_E = 0 #initialization of the indicator of energy (in order to compute the Cv) is_KE = 0 print('Averaging in file', file) results.append(file) #********** Extraction of the Data for the Density, Pressure, Temperature and Energy # In each case we try to: # 1) extract the data from the umd, create the array and compute the average and stendard deviation # 2) compute the sequence of values obtained from (c0/(n-1))**(1/2) (see blocking method in Flyvbjerg1989) # 3) select the values to write in the file # #**** Density try: nsteps_rho, Density, Average_rho, Variance_rho, stdev_rho = grep_pattern( file, "Density", SkipSteps) list_sigma_rho, list_err_rho = blocking_method( Density, Variance_rho) final_sigma_rho, final_err_rho = selection_value( list_sigma_rho, list_err_rho) except subprocess.CalledProcessError: print(' WARNING !!! Density is not defined in the UMD file') nsteps_rho, Density, Average_rho, Variance_rho, stdev_rho = (0.0, 0.0, 0.0, 0.0, 0.0) list_sigma_rho, list_err_rho = (np.zeros(3), np.zeros(3)) final_sigma_rho, final_err_rho = ('0.0', '0.0') #**** Pressure try: nsteps_P, Pressure, Average_P, Variance_P, stdev_P = grep_pattern( file, "Pressure", SkipSteps) list_sigma_P, list_err_P = blocking_method(Pressure, Variance_P) final_sigma_P, final_err_P = selection_value( list_sigma_P, list_err_P) except subprocess.CalledProcessError: print(' WARNING !!! Pressure is not defined in the UMD file') nsteps_P, Pressure, Average_P, Variance_P, stdev_P = (0.0, 0.0, 0.0, 0.0, 0.0) list_sigma_P, list_err_P = (np.zeros(3), np.zeros(3)) final_sigma_P, final_err_P = ('0.0', '0.0') #**** Temperature try: nsteps_T, Temperature, Average_T, Variance_T, stdev_T = grep_pattern( file, "Temperature", SkipSteps) list_sigma_T, list_err_T = blocking_method(Temperature, Variance_T) final_sigma_T, final_err_T = selection_value( list_sigma_T, list_err_T) except subprocess.CalledProcessError: print(' WARNING !!! Temperature is not defined in the UMD file') nsteps_T, Temperature, Average_T, Variance_T, stdev_T = (0.0, 0.0, 0.0, 0.0, 0.0) list_sigma_T, list_err_T = (np.zeros(3), np.zeros(3)) final_sigma_T, final_err_T = ('0.0', '0.0') #**** Energies try: #this energy does not include the kinetic energy of ions, it is the energy without entropy of VASP nsteps_EWE, EnergyWithoutEntropy, Average_EWE, Variance_EWE, stdev_EWE = grep_pattern( file, "InternalEnergy", SkipSteps) list_sigma_EWE, list_err_EWE = blocking_method( EnergyWithoutEntropy, Variance_EWE) final_sigma_EWE, final_err_EWE = selection_value( list_sigma_EWE, list_err_EWE) is_E = 1 except subprocess.CalledProcessError: print( ' WARNING !!! InternalEnergy is not defined in the UMD file' ) nsteps_EWE, EnergyWithoutEntropy, Average_EWE, Variance_EWE, stdev_EWE = ( 0.0, 0.0, 0.0, 0.0, 0.0) list_sigma_EWE, list_err_EWE = (np.zeros(3), np.zeros(3)) final_sigma_EWE, final_err_EWE = ('0.0', '0.0') try: nsteps_K, KineticEnergy, Average_K, Variance_K, stdev_K = grep_pattern( file, "KineticEnergyIons", SkipSteps) is_KE = 1 except subprocess.CalledProcessError: print( ' WARNING !!! KineticEnergy is not defined in the UMD file') nsteps_K, KineticEnergy, Average_K, Variance_K, stdev_K = (0.0, 0.0, 0.0, 0.0, 0.0) #the internal energy as used in the Hugoniot calculation is the internal energy which includes the kinetic energy of ions if is_E == 1 and is_KE == 1: Energy = [ KineticEnergy[ii] + EnergyWithoutEntropy[ii] for ii in range(len(KineticEnergy)) ] nsteps_E = len(Energy) Average_E = sum(Energy) / nsteps_E Variance_E = 0 for ii in range(nsteps_E): Variance_E = Variance_E + (Energy[ii] - Average_E)**2 Variance_E = Variance_E / nsteps_E stdev_E = np.sqrt(Variance_E) list_sigma_E, list_err_E = blocking_method(Energy, Variance_E) final_sigma_E, final_err_E = selection_value( list_sigma_E, list_err_E) else: print( ' WARNING !!! InternalEnergy does not include the kinetic energy of ions!!' ) nsteps_E, Energy, Average_E, Variance_E, stdev_E = nsteps_EWE, EnergyWithoutEntropy, Average_EWE, Variance_EWE, stdev_EWE list_sigma_E, list_err_E = list_sigma_EWE, list_err_EWE final_sigma_E, final_err_E = final_sigma_EWE, final_err_EWE #**** For the calculation of Cv and conversions we need the mass of the cell and natoms #--> we read the header of the umd file using umd_process store the elements information in the class MyCrystal (MyCrystal, TimeStep) = umd.read_bigheader_umd(file) natom = MyCrystal.natom #***** Calculation of Cv and statistical error using the bootstrap method #*** The calculation of Cv depends on the data we have (E, KE) # If we have E but not KE, then we take the ideal gas kinetic part to compute the Cv if is_E == 1 and is_KE == 0: print( ' For information: Cv is computed using the ideal gas kinetic part' ) Cv_bootstrap = [] for n in range(1000): #print('*****Bootstrap N°',n) Energy_rand = np.random.choice(Energy, nsteps_E, replace=True) variance_Erand = 0 variance_Erand = np.mean(Energy_rand** 2) - np.mean(Energy_rand)**2 Cv = variance_Erand * (eVtoJ)**2 / ( kb * Average_T**2) + 3 / 2 * natom * kb #in J/unitcell/K Cv_bootstrap.append(Cv) Cv_bootstrap = np.asarray(Cv_bootstrap) Cv = np.mean( Cv_bootstrap) #an estimator of the mean of Cv, in J/unitcell/K Cv_stdev = np.sqrt( np.mean(Cv_bootstrap**2) - np.mean(Cv_bootstrap)** 2) #the error on the previous mean, in J/unitcell/K # If we have E and KE, then we take both variances to compute the Cv elif is_E == 1 and is_KE == 1: print( ' For information: Cv is computed using both internal and kinetic energy variances' ) Cv_bootstrap = [] for n in range(1000): #print('*****Bootstrap N°',n) Energy_rand = np.random.choice(Energy, nsteps_E, replace=True) variance_Erand = 0 variance_Erand = np.mean(Energy_rand** 2) - np.mean(Energy_rand)**2 Cv = variance_Erand * (eVtoJ)**2 / (kb * Average_T**2 ) #in J/unitcell/K Cv_bootstrap.append(Cv) Cv_bootstrap = np.asarray(Cv_bootstrap) Cv = np.mean( Cv_bootstrap) #an estimator of the mean of Cv, in J/unitcell/K Cv_stdev = np.sqrt( np.mean(Cv_bootstrap**2) - np.mean(Cv_bootstrap)** 2) #the error on the previous mean, in J/unitcell/K #if we do not have the energy, then we do not compute the Cv else: print(' WARNING !!! Cv is not computed') Cv, Cv_stdev = (0, 0) Cvm = Cv * Na / natom #in J/K/mol Cvm_stdev = Cv_stdev * Na / natom #in J/K/mol Cvm_Nkb = Cv / (kb * natom) #in Nakb Cvm_Nkb_stdev = Cv_stdev / (kb * natom) #in Nakb #****** Write result line #**** For the conversions we need the mass of the cell #--> we read the header of the umd file using umd_process store the elements information in the class MyCrystal (MyCrystal, TimeStep) = umd.read_bigheader_umd(file) mass = 0 for itypat in range(MyCrystal.ntypat): (atomicname, atomicsymbol, atomicnumber, MyCrystal.masses[itypat]) = cr.Elements2rest( MyCrystal.elements[itypat]) mass = mass + MyCrystal.masses[itypat] * MyCrystal.types[itypat] mass = mass / Na #convert eV/unitcell to eV/atom or to J/g if final_sigma_E[0] == '>': final_sigma_E_conv = '>' + '{:1.1e}'.format( float(final_sigma_E[1:]) / natom) final_sigma_E_mass = '>' + '{:1.1e}'.format( float(final_sigma_E[1:]) * eVtoJ / mass) else: final_sigma_E_conv = '{:1.1e}'.format( float(final_sigma_E[:]) / natom) final_sigma_E_mass = '{:1.1e}'.format( float(final_sigma_E[:]) * eVtoJ / mass) if units == 0: results.extend([ str(nsteps_P), '{:1.2f}'.format(Average_rho), '{:1.1e}'.format(stdev_rho), str(final_sigma_rho), '{:1.2e}'.format(Average_P), '{:1.1e}'.format(stdev_P), str(final_sigma_P), '{:1.0f}'.format(Average_T), '{:1.0f}'.format(stdev_T), str(final_sigma_T), '{:1.2e}'.format(Average_E / natom), '{:1.1e}'.format(stdev_E / natom), str(final_sigma_E_conv), '{:1.2f}'.format(Cvm_Nkb), '{:1.1e}'.format(Cvm_Nkb_stdev) ]) else: #additional conversion of units #conversion of eV/unitcell to J/g Average_E_mass = Average_E * eVtoJ / mass stdev_E_mass = stdev_E * eVtoJ / mass #conversion of J/K to J/K/g Cvm_mass = Cv / mass Cvm_mass_stdev = Cv_stdev / mass #conversion K to eV if final_sigma_T[0] == '>': final_sigma_T_conv = '>' + '{:1.1e}'.format( float(final_sigma_T[1:]) * KtoeV) else: final_sigma_T_conv = '{:1.1e}'.format( float(final_sigma_T[:]) * KtoeV) results.extend([ str(nsteps_P), '{:1.2f}'.format(Average_rho), '{:1.1e}'.format(stdev_rho), str(final_sigma_rho), '{:1.2e}'.format(Average_P), '{:1.1e}'.format(stdev_P), str(final_sigma_P), '{:1.0f}'.format(Average_T), '{:1.0f}'.format(stdev_T), str(final_sigma_T), '{:1.2e}'.format(Average_T * KtoeV), '{:1.1e}'.format(stdev_T * KtoeV), str(final_sigma_T_conv), '{:1.2e}'.format(Average_E / natom), '{:1.1e}'.format(stdev_E / natom), str(final_sigma_E_conv), '{:1.3e}'.format(Average_E), '{:1.1e}'.format(stdev_E), str(final_sigma_E), '{:1.3e}'.format(Average_E_mass), '{:1.1e}'.format(stdev_E_mass), str(final_sigma_E_mass), '{:1.2f}'.format(Cvm_Nkb), '{:1.1e}'.format(Cvm_Nkb_stdev), '{:1.2e}'.format(Cvm), '{:1.1e}'.format(Cvm_stdev), '{:1.2e}'.format(Cvm_mass), '{:1.1e}'.format(Cvm_mass_stdev), '{:1.2e}'.format(Cv), '{:1.1e}'.format(Cv_stdev) ]) f.write("\t".join(x for x in results) + "\n") f.close()
def main(argv): UMDname = '' POPname = '' RADname = '' Nsteps = 5 cubesize = 0.025 ClusterMaxSize = 5 AtomicRadius = 1.0 Ballistic = 10.0 umd.headerumd() try: opts, arg = getopt.getopt( argv, "hf:p:s:b:c:", ["fUMDfile", "pPOPfile", "sSTEP", "bBallistic", "cClusterMaxSize"]) except getopt.GetoptError: print( 'msd_cluster -f <UMD_filename> -p <POPuL_filename> -s <Nsteps> -b <Ballistic> -c <ClusterMaxSize>' ) sys.exit(2) for opt, arg in opts: if opt == '-h': print( 'Program to compute the mean square displacements for all the atomic species found by speciation.py. Usage:' ) print( 'msd_cluster -f <UMD_filename> -p <POPuL_filename> -s <Nsteps> -b <Ballistic> -c <ClusterMaxSize>' ) print( 'UMD_filename = input file with the trajectory, in UMD format.' ) print( 'POPuL_filename = input file with all the individual atomic clusters and their lifetimes in popul format.' ) print( 'Nsteps = frequency of sampling of the trajectory. Default = 1 (all steps are considered)' ) print( 'Ballistic = estimation of the ballistic part of the trajectory. Default is 0. Typical values of 100 are sufficient.' ) print( 'ClusterMaxSize = arbitrary upper size limit for defining checmnial species. Default = 5. You can safely assume values up to 10-12.' ) sys.exit() elif opt in ("-f", "--fUMD_filename"): UMDname = str(arg) print('UMDname = ', UMDname) elif opt in ("-p", "--pPOP_filename"): POPname = str(arg) print('POPname = ', POPname) elif opt in ("-s", "--sNsteps"): Nsteps = int(arg) print('Density of sampling: every ', Nsteps, ' steps') elif opt in ("-s", "--bBallistic"): Ballistic = int(arg) print('Ballistic threshold: ', Ballistic, ' steps') elif opt in ("-c", "--cClusterMaxSize"): ClusterMaxSize = int(arg) print('Clusters smaller than ', ClusterMaxSize, ' atoms are considered gas') #checking the existence of the files before doing any other operation if os.path.isfile(UMDname): print('using ', UMDname, ' umd file') else: print('the UMD file ', UMDname, ' does not exist') sys.exit() if os.path.isfile(POPname): print('using ', POPname, ' population file') else: print('the UMD file ', POPname, ' does not exist') sys.exit() #read the umd file and allocate structure MyCrystal = cr.Lattice() AllSnapshots = [cr.Lattice] (MyCrystal, AllSnapshots, TimeStep) = umd.read_absxcart(UMDname) ana_popul(MyCrystal, AllSnapshots, POPname, Ballistic, ClusterMaxSize, Nsteps)