def test_init(self): filepath = os.path.join(test_dir, 'CHGCAR.nospin') chg = Chgcar.from_file(filepath) self.assertAlmostEqual(chg.get_integrated_diff(0, 2)[0, 1], 0) filepath = os.path.join(test_dir, 'CHGCAR.spin') chg = Chgcar.from_file(filepath) self.assertAlmostEqual(chg.get_integrated_diff(0, 1)[0, 1], -0.0043896932237534022) #test sum chg += chg self.assertAlmostEqual(chg.get_integrated_diff(0, 1)[0, 1], -0.0043896932237534022 * 2) filepath = os.path.join(test_dir, 'CHGCAR.noncubic') chg = Chgcar.from_file(filepath) ans = [0.221423, 0.462059, 0.470549, 0.434775, 0.860738, 2.1717482] myans = chg.get_integrated_diff(0, 3, 6) self.assertTrue(np.allclose(myans[:, 1], ans))
def test_init(self): filepath = os.path.join(test_dir, 'CHGCAR.nospin') chg = Chgcar.from_file(filepath) self.assertAlmostEqual(chg.get_integrated_diff(0, 2)[0, 1], 0) filepath = os.path.join(test_dir, 'CHGCAR.spin') chg = Chgcar.from_file(filepath) self.assertAlmostEqual(chg.get_integrated_diff(0, 1)[0, 1], -0.0043896932237534022) #test sum chg += chg self.assertAlmostEqual(chg.get_integrated_diff(0, 1)[0, 1], -0.0043896932237534022 * 2) filepath = os.path.join(test_dir, 'CHGCAR.Fe3O4') chg = Chgcar.from_file(filepath) ans = [1.93313368, 3.91201473, 4.11858277, 4.1240093, 4.10634989, 3.38864822] myans = chg.get_integrated_diff(0, 3, 6) self.assertTrue(np.allclose(myans[:, 1], ans))
def __init__(self, chgcar_filename, potcar_filename=None): """ Args: chgcar_filename: The filename of the CHGCAR. potcar_filename: Optional: the filename of the corresponding POTCAR file. Used for calculating the charge transfer. If None, the get_charge_transfer method will raise a ValueError. """ temp_dir = tempfile.mkdtemp() self.chgcar = Chgcar.from_file(chgcar_filename) self.potcar = Potcar.from_file(potcar_filename) \ if potcar_filename is not None else None self.natoms = self.chgcar.poscar.natoms try: shutil.copy(chgcar_filename, os.path.join(temp_dir, "CHGCAR")) current_dir = os.getcwd() os.chdir(temp_dir) rs = subprocess.Popen(["bader", "CHGCAR"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, close_fds=True) rs.communicate() data = [] with open("ACF.dat") as f: raw = f.readlines() headers = [s.lower() for s in raw.pop(0).split()] raw.pop(0) while True: l = raw.pop(0).strip() if l.startswith("-"): break vals = map(float, l.split()[1:]) data.append(dict(zip(headers[1:], vals))) for l in raw: toks = l.strip().split(":") if toks[0] == "VACUUM CHARGE": self.vacuum_charge = float(toks[1]) elif toks[0] == "VACUUM VOLUME": self.vacuum_volume = float(toks[1]) elif toks[0] == "NUMBER OF ELECTRONS": self.nelectrons = float(toks[1]) self.data = data os.chdir(current_dir) except Exception as ex: print str(ex) finally: shutil.rmtree(temp_dir)
parser = argparse.ArgumentParser() parser.add_argument("-s1", type=str, default="", help="POSCAR for endpoint 1") parser.add_argument("-s2", type=str, default="", help="POSCAR for endpoint 2") parser.add_argument("-chg", type=str, default="", help="CHGCAR for interpolation (if not specified, use free volume metric)") parser.add_argument("-o", type=str, default="", help="Output POSCAR with images superimposed") args = parser.parse_args() s1 = Poscar.from_file(args.s1).structure s2 = Poscar.from_file(args.s2).structure # Find diffusing species site indices mg_sites = [] for site_i, site in enumerate(s1.sites): if site.specie == Element("Mg"): mg_sites.append(site_i) # Interpolate if args.chg != "": print("Using CHGCAR potential mode.") chg = Chgcar.from_file(args.chg) pf = NEBPathfinder(s1, s2, relax_sites=mg_sites, v=ChgcarPotential(chg).get_v(), n_images=10) else: print("Using free volume mode") print("WARNING: This mode is not optimized and a lot of numerical parameters are not good, so the output might be bad!") pf = NEBPathfinder(s1, s2, relax_sites=mg_sites, v=FreeVolumePotential(s1, (40,40,40)).get_v(), n_images=10, h=0.001) # Get images images = pf.images # Plot path pf.plot_images(args.o)
def main(): # Set default variables options = dict( spin_channel='total', center_cartesian=[0., 0., 0.], x_axis=[1., 0., 0.], y_axis=[0., 0., 1.], x_repeat=1, # approximate number of unit cells to interpolate y_repeat=1, # approximate number of unit cells to interpolate x_res=500, # points to interpolate y_res=500, # points to interpolate format='xyz', ) options.update(**vars(_build_parser().parse_args())) chg = Chgcar.from_file(options['filename']) structure = chg.structure rprim = chg.structure.lattice.matrix # Decide where to obtain center from # Cartesian option set center = options['center_direct'] if options['center_cartesian'] is not None: # Convert from cartesian to reduced coordinates center = numpy.linalg.solve(rprim, options['center_cartesian']).tolist() # Atomic option is set if options['center_atom'] is not None: # Convert from atom number to reduced coordinates center = structure[options['center_atom']].frac_coords.tolist() plane = numpy.array([options['x_axis'], options['y_axis']], dtype=float) repeat = [options['x_repeat'], options['y_repeat']] res = [options['x_res'], options['y_res']] data = 0 if options['spin_channel'] == 'total': data = chg.data['total'] if options['spin_channel'] == 'up': data = chg.spin_data[Spin.up] if options['spin_channel'] == 'down': data = chg.spin_data[Spin.down] if options['spin_channel'] == 'polarization': data = chg.spin_data[Spin.up] - chg.spin_data[Spin.down] data /= structure.volume cs = plane_to_cs(plane) posinplane = numpy.dot(cs, numpy.dot(structure.frac_coords - center, rprim).T).T print('Atom positions in plane:') for i, pos in enumerate(posinplane): print(' %s: %f %f (z = %f)' % (structure[i].specie, pos[0], pos[1], pos[2])) # Interpolate x, y, z = interpolate_plane(data, rprim, plane=plane, center=center, dim=repeat, res=res) print('Cell density:\n minimum: %f\n maximum: %f' % (data.min(), data.max())) print('In-plane density:\n minimum: %f\n maximum: %f' % (z.min(), z.max())) print('Note: PAW calculations may contain negative values for the pseudo-density in the core regions.') suffix = '.gz' if options['gzip'] else '' if options['format'] == 'xyz': out = numpy.array([x.flatten(), y.flatten(), z.flatten()]).T with open('chg_%s_in_plane.csv%s' % (options['spin_channel'], suffix), 'w+') as f: numpy.savetxt(f, out, delimiter=',', header=' X, Y, Z') if options['format'] == 'matrix': with open('chg_%s_in_plane.mat%s' % (options['spin_channel'], suffix), 'w+') as f: numpy.savetxt(f, z, delimiter=' ', header=' Z matrix') if options['format'] == 'image': import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt fig = plt.figure() plt.contour(x, y, z, options['contour'], colors='k') fig.savefig(options['out'])
default="", help="Output POSCAR with images superimposed") args = parser.parse_args() s1 = Poscar.from_file(args.s1).structure s2 = Poscar.from_file(args.s2).structure # Find diffusing species site indices mg_sites = [] for site_i, site in enumerate(s1.sites): if site.specie == Element("Mg"): mg_sites.append(site_i) # Interpolate if args.chg != "": print("Using CHGCAR potential mode.") chg = Chgcar.from_file(args.chg) pf = NEBPathfinder(s1, s2, relax_sites=mg_sites, v=ChgcarPotential(chg).get_v(), n_images=10) else: print("Using free volume mode") print( "WARNING: This mode is not optimized and a lot of numerical parameters are not good, so the output might be bad!" ) pf = NEBPathfinder(s1, s2, relax_sites=mg_sites, v=FreeVolumePotential(s1, (40, 40, 40)).get_v(), n_images=10,