def write_cube(self, index, fname, repeat=None, real=True): """Dump specified Wannier function to a cube file""" from ase.io.cube import write_cube # Default size of plotting cell is the one corresponding to k-points. if repeat is None: repeat = self.kptgrid atoms = self.calc.get_atoms() * repeat func = self.get_function(index, repeat) # Handle separation of complex wave into real parts if real: if self.Nk == 1: func *= np.exp(-1.j * np.angle(func.max())) if 0: assert max(abs(func.imag).flat) < 1e-4 func = func.real else: func = abs(func) else: phase_fname = fname.split('.') phase_fname.insert(1, 'phase') phase_fname = '.'.join(phase_fname) write_cube(phase_fname, atoms, data=np.angle(func)) func = abs(func) write_cube(fname, atoms, data=func)
def main(inList, outFile, subtract=False): #if output exists mv to .bak if os.path.isfile(outFile): print('ATTENTION: {:} exists, moving to *.bak'.format(outFile)) os.rename(outFile, outFile + '.bak') cubeData = [] for inFile in inList: if not os.path.isfile(inFile): raise ValueError('File {:} does not exist'.format(inFile)) print(inFile) with open(inFile) as f: dct = read_cube(f) cubeData.append(dct['data'].copy()) atoms = dct['atoms'] origin = dct['origin'] if subtract: sumData = cubeData[0] for i in range(1, len(cubeData)): sumData = np.subtract(sumData, cubeData[i]) else: sumData = np.sum(cubeData, axis=0) with open(outFile, 'w') as f: write_cube(f, atoms, data=sumData, origin=origin) return
def get_rho_atom(CDFTSolver, origin): """ Generate charge density for each atom Attributes: CDFTSolver (CDFTSolver) origin (tuple): (x,y,z) coord; same as rhor.cube file; origin of volumetric data give in Angstroms; gets converted to Bohr in program """ atoms_iter = CDFTSolver.sample.atoms # calculating requires pycdft-modified Atom type atoms_write = CDFTSolver.sample.ase_cell # writing requires ASE Atom type n = CDFTSolver.sample.n omega = CDFTSolver.sample.omega index = 1 for atom in atoms_iter: rhoatom_g = CDFTSolver.sample.compute_rhoatom_g(atom) rhoatom_r = (n / omega) * ifftn(rhoatom_g).real # FT G -> R #rhoatom_r = (n / omega) * ifftn(rhoatom_g).real # FT G -> R # write to cube file rhoatom_r = parse(rhoatom_r, -1) filname = "rhoatom_r_" + str(index) + ".cube" fileobj = open(filname, "w") write_cube(fileobj, atoms_write, rhoatom_r, origin=origin) fileobj.close() print(f"Generated rhoatom_r cube file for Atom {index}") index += 1 print("Completed get_rho_atom")
def get_hirsh(CDFTSolver, origin): """ Extract Hirschfeld weights for Charge constraint Attributes: CDFTSolver (CDFTSolver) origin (tuple): (x,y,z) coord; same as rhor.cube file; origin of volumetric data; give in Angstroms; gets converted to Bohr in program """ constraints = CDFTSolver.sample.constraints index = 1 for c in constraints: atoms_iter = CDFTSolver.sample.atoms # calculating requires pycdft-modified Atom type atoms_write = CDFTSolver.sample.ase_cell # writing requires ASE Atom type # write to cube file for visualizing weights_dat = parse(c.w[0], -1) filname = "hirshr" + str(index) + ".cube" fileobj = open(filname, "w") write_cube(fileobj, atoms_write, weights_dat, origin=origin) fileobj.close() print(f"Generated cube file for Constraint {index}.") print("Completed Hirshfeld weight extraction!")
def write_cube(self, index, fname, repeat=None, real=True): """Dump specified Wannier function to a cube file""" from ase.io.cube import write_cube # Default size of plotting cell is the one corresponding to k-points. if repeat is None: repeat = self.kptgrid atoms = self.calc.get_atoms() * repeat func = self.get_function(index, repeat) # Handle separation of complex wave into real parts if real: if self.Nk == 1: func *= np.exp(-1.0j * np.angle(func.max())) if 0: assert max(abs(func.imag).flat) < 1e-4 func = func.real else: func = abs(func) else: phase_fname = fname.split(".") phase_fname.insert(1, "phase") phase_fname = ".".join(phase_fname) write_cube(phase_fname, atoms, data=np.angle(func)) func = abs(func) write_cube(fname, atoms, data=func)
def get_grad(CDFTSolver, origin): r""" Extract gradient of Hirschfeld weights and charge density; both are calculated in calculation of :math:`\nabla w(\bf{r})` Attributes: CDFTSolver (CDFTSolver) origin (tuple): (x,y,z) coord; same as rhor.cube file; origin of volumetric data; give in Angstroms; gets converted to Bohr in program """ constraints = CDFTSolver.sample.constraints ic = 1 for c in constraints: atoms_iter = CDFTSolver.sample.atoms # calculating requires pycdft-modified Atom type atoms_write = CDFTSolver.sample.ase_cell # writing requires ASE Atom type ia = 1 for atom in atoms_iter: #w_grad, rho_grad_r,w_grad_part,rhopro_r = c.debug_w_grad_r(atom) w_grad, rho_grad_r = c.debug_w_grad_r(atom) # write to cube file for visualizing # separate file for each cartesian direction for icart in range(3): w_grad_tmp = parse(w_grad[icart][0], -1) rho_grad_r_tmp = parse(rho_grad_r[icart], -1) fil1 = "w_grad_atom" + str(ia) + "_c" + str(ic) + "_i" + str( icart) + ".cube" fil2 = "rhoatom_grad_atom" + str(ia) + "_c" + str( ic) + "_i" + str(icart) + ".cube" fileobj = open(fil1, "w") write_cube(fileobj, atoms_write, w_grad_tmp, origin=origin) fileobj.close() print( f"Generated Hirshfeld wts cube file for Atom {ia}, constraint {ic}, dir {icart}" ) fileobj = open(fil2, "w") write_cube(fileobj, atoms_write, rho_grad_r_tmp, origin=origin) fileobj.close() ia += 1 ic += 1 print( f"Generated charge density cube file for Atom {ia}, constraint {ic}, dir {icart}" ) print("Completed extraction of grad quantities!")
def write_densities(self, outfilename): """Write electron and hole densities to cube files outfilename Output file name""" self.calculate() name = outfilename+'_rho_e.cube' write_cube(open(name, 'w'), self.calc.get_atoms(), data=self.rho_e) name = outfilename+'_rho_h.cube' write_cube(open(name, 'w'), self.calc.get_atoms(), data=self.rho_h)
def main(): """Command line executable""" if not argv[1].endswith('.cube'): raise ValueError(argv[1]) rho_e, atoms = read_cube_data(open(argv[1], 'r')) if not argv[2].endswith('.cube'): raise ValueError(argv[2]) rho_h, atoms = read_cube_data(open(argv[2], 'r')) drho = rho_h + rho_e name = argv[1].split('.cube')[0]+'drho.cube' write_cube(open(name, 'w'), atoms, data=drho)
def write_3D(self, bias, file, filetype=None): """Write the density as a 3D file. Units: [e/A^3]""" self.calculate_ldos(bias) self.calc.wfs.kd.comm.sum(self.ldos) ldos = self.gd.collect(self.ldos) # print "write: integrated =", self.gd.integrate(self.ldos) if mpi.rank != MASTER: return if filetype is None: # estimate file type from name ending filetype = file.split('.')[-1] filetype.lower() if filetype == 'cube': write_cube(file, self.calc.get_atoms(), ldos / Bohr**3) elif filetype == 'plt': write_plt(file, self.calc.get_atoms(), ldos / Bohr**3) else: raise NotImplementedError('unknown file type "' + filetype + '"')
def write_3D(self, bias, file, filetype=None): """Write the density as a 3D file. Units: [e/A^3]""" self.calculate_ldos(bias) self.calc.wfs.kpt_comm.sum(self.ldos) ldos = self.gd.collect(self.ldos) ## print "write: integrated =", self.gd.integrate(self.ldos) if mpi.rank != MASTER: return if filetype is None: # estimate file type from name ending filetype = file.split('.')[-1] filetype.lower() if filetype == 'cube': write_cube(file, self.calc.get_atoms(), ldos / Bohr**3) elif filetype == 'plt': write_plt(file, self.calc.get_atoms(), ldos / Bohr**3) else: raise NotImplementedError('unknown file type "' + filetype + '"')
def get_hirsh_ct(CDFTSolver, origin): """ Extract Hirschfeld weights for Charge_Transfer constraint Attributes: CDFTSolver (CDFTSolver) origin (tuple): (x,y,z) coord; same as rhor.cube file; origin of volumetric data; give in Angstroms; gets converted to Bohr in program """ constraints = CDFTSolver.sample.constraints index = 1 for c in constraints: atoms = CDFTSolver.sample.ase_cell # write to cube file for visualizing weights_dat = parse(c.w[0], -1) filname = "hirshr" + str(index) + ".cube" fileobj = open(filname, "w") write_cube(fileobj, atoms, weights_dat, origin=origin) fileobj.close() print(f"Generated for Constraint {index}.") print("Completed! Have fun plotting")
#!/usr/bin/env python3 from ase.io.xsf import read_xsf from ase.io.cube import write_cube from ase.io import read import glob ''' convert xsf with grid data to cube for Bader analysis need xsf grid data from rho2xsf script, rename it *_data.XSF and xsf structure from xv2xsf script then run "bader *_data.cube" for Bader analysis ''' grid = glob.glob('*_data.XSF') all_xsf = glob.glob('*.XSF') stru = list(set(all_xsf) - set(grid)) xsf = read_xsf(open(grid[0], 'r'), read_data=True) write_cube(open(str(grid[0])[:-4] + ".cube", 'w'), atoms=read(stru[0]), data=xsf[0])
field *= x if (options.plus != None): plus = options.plus field += plus print plus, min(field), max(field) # for i,x in enumerate(field): # for j,y in enumerate(x): # for k,z in enumerate(y): # field[i][j][k] += plus # print field.shape # field = field + ####### WRITEING THE FILE ############# if (oformat == "xsf"): # write_xsf(sys.stdout,field[1],field[0]) write_xsf(sys.stdout, atoms, field) elif (oformat == "cube"): # print "Warrning: Third line should contain number of atoms together with position of the origin of the volumetric data." # print "Warrning: Make sure it contain corrrect data." write_cube(sys.stdout, atoms, field) elif (oformat == "locpot"): locpot_out = VaspChargeDensity(filename=None) locpot_out.atoms = [ atoms, ] locpot_out.chg = [ field, ] locpot_out.write(filename=sys.argv[num - 1] + ".out", format="chgcar")