Ejemplo n.º 1
0
def get_volumetric_data(self, filename='CHG', **kwargs):
    '''Read filename to read the volumetric data in it.

    Supported filenames are CHG, CHGCAR, and LOCPOT.
    '''
    atoms = self.get_atoms()
    vd = VaspChargeDensity(filename)

    data = np.array(vd.chg)
    n0, n1, n2 = data[0].shape

    s0 = 1.0 / n0
    s1 = 1.0 / n1
    s2 = 1.0 / n2

    X, Y, Z = np.mgrid[0.0:1.0:s0, 0.0:1.0:s1, 0.0:1.0:s2]

    C = np.column_stack([X.ravel(), Y.ravel(), Z.ravel()])

    uc = atoms.get_cell()
    real = np.dot(C, uc)

    # now convert arrays back to unitcell shape
    x = np.reshape(real[:, 0], (n0, n1, n2))
    y = np.reshape(real[:, 1], (n0, n1, n2))
    z = np.reshape(real[:, 2], (n0, n1, n2))

    return x, y, z, data
Ejemplo n.º 2
0
def chg_at_point(
    chgfile,
    xred1,
):
    """
    Return the the value of charge density at coordinate xred1; Actually it provides charge density for the closest grid point
    Most probably the units are (el/A^3)

    chgfile - full path to the file with charge density
    xred1 - reduced coordinate;

    RETURN: 
    Charge density at given point
    """
    vasp_charge = VaspChargeDensity(chgfile)
    density = vasp_charge.chg[-1]
    atoms = vasp_charge.atoms[-1]
    del vasp_charge
    # print density[0][0][0]

    ngridpts = numpy.array(density.shape)  # size of grid
    print('Size of grid', ngridpts)
    # rprimd = atoms.get_cell()
    # print rprimd

    # xred1 = [0.5, 0.5, 0.5]
    # rprimd_lengths=numpy.sqrt(numpy.dot(rprimd,rprimd.transpose()).diagonal()) #length of cell vectors
    i, j, k = [int(round(x * (n - 1))) for x, n in zip(xred1, ngridpts)
               ]  # corresponding to xred1 point
    print(i, j, k)
    print('Density at xred', xred1, 'is', density[i][j][k])
    return density[i][j][k]
Ejemplo n.º 3
0
Archivo: CHG.py Proyecto: saisai/jasp
def get_charge_density(self, spin=0):
    """Returns x, y, and z coordinate and charge density arrays.

    :param int spin:
    :returns: x, y, z, charge density arrays
    :rtype: 3-d numpy arrays

    Relies on :func:`ase.calculators.vasp.VaspChargeDensity`.
    """

    atoms = self.get_atoms()
    vcd = VaspChargeDensity()

    cd = np.array(vcd.chg[spin])
    n0, n1, n2 = cd.shape

    s0 = 1.0 / n0
    s1 = 1.0 / n1
    s2 = 1.0 / n2

    X, Y, Z = np.mgrid[0.0:1.0:s0, 0.0:1.0:s1, 0.0:1.0:s2]

    C = np.column_stack([X.ravel(), Y.ravel(), Z.ravel()])

    uc = atoms.get_cell()
    real = np.dot(C, uc)

    # now convert arrays back to unitcell shape
    x = np.reshape(real[:, 0], (n0, n1, n2))
    y = np.reshape(real[:, 1], (n0, n1, n2))
    z = np.reshape(real[:, 2], (n0, n1, n2))

    return x, y, z, cd
Ejemplo n.º 4
0
def get_volumetric_data(self, filename='CHG', **kwargs):
    """Read filename to read the volumetric data in it.

    Supported filenames are CHG, CHGCAR, and LOCPOT.

    """
    atoms = self.get_atoms()
    vd = VaspChargeDensity(filename)

    data = np.array(vd.chg)
    n0, n1, n2 = data[0].shape

    s0 = np.linspace(0, 1, num=n0, endpoint=False)
    s1 = np.linspace(0, 1, num=n1, endpoint=False)
    s2 = np.linspace(0, 1, num=n2, endpoint=False)

    X, Y, Z = np.meshgrid(s0, s1, s2)

    C = np.column_stack([X.ravel(), Y.ravel(), Z.ravel()])

    uc = atoms.get_cell()
    real = np.dot(C, uc)

    # now convert arrays back to unitcell shape
    x = np.reshape(real[:, 0], (n0, n1, n2))
    y = np.reshape(real[:, 1], (n0, n1, n2))
    z = np.reshape(real[:, 2], (n0, n1, n2))

    return x, y, z, data
Ejemplo n.º 5
0
def load(loc, axis="Z"):

    global average, latticelength, ngridpts, idir, direction

    LOCPOTfile = loc + '/LOCPOT'
    direction = axis

    vasp_charge = VaspChargeDensity(filename=LOCPOTfile)
    atoms = vasp_charge.atoms[-1]
    cell = atoms.cell
    potl = vasp_charge.chg[-1] * atoms.get_volume()
    latticelength = np.dot(cell, cell.T).diagonal()**0.5
    ngridpts = np.array(potl.shape)

    if direction == "X":
        idir = 0
    elif direction == "Y":
        idir = 1
    else:
        idir = 2

    average = np.zeros(ngridpts[idir], np.float)

    for ipt in range(ngridpts[idir]):
        if direction == "X":
            average[ipt] = potl[ipt, :, :].sum()
        elif direction == "Y":
            average[ipt] = potl[:, ipt, :].sum()
        else:
            average[ipt] = potl[:, :, ipt].sum()

    average /= ngridpts[(idir + 1) % 3] * ngridpts[(idir + 2) % 3]
Ejemplo n.º 6
0
 def from_file(file_path):
     data = VaspChargeDensity(file_path)
     density = data.chg[-1]
     atoms = data.atoms[-1]
     ngridpts = np.array(density.shape)
     totalgridpts = ngridpts.prod()
     unitcell = atoms.get_cell()
     return VaspDens(density, atoms, ngridpts, unitcell)
Ejemplo n.º 7
0
def read_vasp_density(density_file):
    data = VaspChargeDensity(density_file)
    density = data.chg[-1]
    atoms = data.atoms[-1]
    ngridpts = np.array(density.shape)
    totalgridpts = ngridpts.prod()
    unitcell = atoms.get_cell()
    return data, density, atoms, ngridpts, totalgridpts, unitcell
Ejemplo n.º 8
0
def chg_at_z_direct(cl, k_p=20, plot=None, filetype='CHGCAR'):
    """
    Return the the value of charge density or electrostatic potential along z direction of slab; 

    chgfile - full path to the file with charge density
    cl - Calculation() with slab structure; 
    it is needed for the definition of the correct coordinates of points in a structure  in which  will be calculated of el/stat pot 

    RETURN: 
    List of z-coordinates and respective average value of electrostatic pot in the z slice.
    """
    from siman.picture_functions import fit_and_plot

    if filetype == 'CHGCAR':
        chgfile = cl.get_chg_file()
    else:
        chgfile = cl.get_file(filetype=filetype)

    st = cl.end
    vasp_charge = VaspChargeDensity(chgfile)
    density = vasp_charge.chg[-1]
    atoms = vasp_charge.atoms[-1]
    del vasp_charge

    ngridpts = np.array(density.shape)  # size of grid
    # print ('Size of grid', ngridpts)

    z = int(cl.vlength[2] * 10)

    elst = []
    z_coord = []
    xred1 = [0, 0, 0]
    for n3 in range(0, z):
        dens = 0
        # for more accurate calculation of electrostatic pot, it is needed to split the z-sliced plane into a grid of points k_p (20 x 20)
        # and find the average value for the slice
        for n1 in range(0, k_p):
            for n2 in range(0, k_p):
                xred1[0] = n1 / k_p
                xred1[1] = n2 / k_p
                xred1[2] = n3 / z
                i, j, k = [
                    int(round(x * (n - 1))) for x, n in zip(xred1, ngridpts)
                ]  # corresponding to xred1 point
                dens += density[i][j][k] * st.vol

        elst.append(dens / k_p**2 * st.vol)
        z_coord.append(n3 / 10)

    if plot:
        # print(z_coord, elst)
        fit_and_plot(a=(z_coord, elst, '-b'),
                     xlabel='Z coordinate, $\AA$',
                     ylabel='Potential, eV',
                     filename='figs/' + st.id[0] + '_pot')

    return z_coord, elst
Ejemplo n.º 9
0
def locpot_mean(fname="LOCPOT",
                axis='z',
                savefile='locpot.dat',
                outcar="OUTCAR"):
    '''
    Reads the LOCPOT file and calculate the average potential along `axis`.
     @in: See function argument.
    @out:
          - xvals: grid data along selected axis;
          - mean: averaged potential corresponding to `xvals`.
    '''
    def get_efermi(outcar="OUTCAR"):
        if not os.path.isfile(outcar):
            logger.warning("OUTCAR file not found. E-fermi set to 0.0eV")
            return None
        txt = open(outcar).read()
        efermi = re.search(
            r'E-fermi :\s*([-+]?[0-9]+[.]?[0-9]*([eE][-+]?[0-9]+)?)',
            txt).groups()[0]
        logger.info("Found E-fermi = {}".format(efermi))
        return float(efermi)

    logger.info("Loading LOCPOT file {}".format(fname))
    locd = VaspChargeDensity(fname)
    cell = locd.atoms[0].cell
    latlens = np.linalg.norm(cell, axis=1)
    vol = np.linalg.det(cell)

    iaxis = ['x', 'y', 'z'].index(axis.lower())
    axes = [0, 1, 2]
    axes.remove(iaxis)
    axes = tuple(axes)

    locpot = locd.chg[0]
    # must multiply with cell volume, similar to CHGCAR
    logger.info("Calculating workfunction along {} axis".format(axis))
    mean = np.mean(locpot, axes) * vol

    xvals = np.linspace(0, latlens[iaxis], locpot.shape[iaxis])

    # save to 'locpot.dat'
    efermi = get_efermi(outcar)
    logger.info("Saving raw data to {}".format(savefile))
    if efermi is None:
        np.savetxt(savefile,
                   np.c_[xvals, mean],
                   fmt='%13.5f',
                   header='Distance(A) Potential(eV) # E-fermi not corrected')
    else:
        mean -= efermi
        np.savetxt(
            savefile,
            np.c_[xvals, mean],
            fmt='%13.5f',
            header='Distance(A) Potential(eV) # E-fermi shifted to 0.0eV')
    return (xvals, mean)
Ejemplo n.º 10
0
def read_chgcar(INDATA, CONTCAR='CONTCAR'):

    print('Input data: ', INDATA)

    print('Read ', INDATA)
    print(datetime.datetime.now())

    rho = VaspChargeDensity(INDATA)

    print(datetime.datetime.now())

    return rho
Ejemplo n.º 11
0
def _read_vasp(filecontent):
    # Write to tmp file and read using ASE
    tmpfd, tmppath = tempfile.mkstemp(prefix="tmpdeepdft")
    tmpfile = os.fdopen(tmpfd, "wb")
    tmpfile.write(filecontent)
    tmpfile.close()
    vasp_charge = VaspChargeDensity(filename=tmppath)
    os.remove(tmppath)
    density = vasp_charge.chg[-1]  # separate density
    atoms = vasp_charge.atoms[-1]  # separate atom positions

    return density, atoms, np.zeros(3)  # TODO: Can we always assume origin at 0,0,0?
Ejemplo n.º 12
0
def get_s(chgcar='CHGCAR'):
    chg = VaspChargeDensity(chgcar)
    abc = np.shape(chg.chg[-1])
    dx = abc[0] / np.shape(chg.chg[0])[0]
    dy = abc[1] / np.shape(chg.chg[0])[1]
    dz = abc[2] / np.shape(chg.chg[0])[2]
    v_chg_gr = np.gradient(chg.chg[0], dx, dy, dz)
    chg_grad = np.sqrt(
        np.square(v_chg_gr[0]) + np.square(v_chg_gr[1]) +
        np.square(v_chg_gr[2]))
    s = chg_grad / (2 * (3. * pi**2 * chg.chg[0])**1. / 3 * chg.chg[0])
    return s
Ejemplo n.º 13
0
def plan_avg_ase(filename='LOCPOT'):
    import numpy as np
    from ase.calculators.vasp import VaspChargeDensity
    locpot = VaspChargeDensity(filename)
    # For LOCPOT files we multiply by the volume to get back to eV
    if 'LOCPOT' in filename:
        avg_c = [
            np.average(locpot.chg[0][:, :, i] * locpot.atoms[0].get_volume())
            for i in range(0,
                           np.shape(locpot.chg)[3])
        ]
    else:
        avg_c = [
            np.average(locpot.chg[0][:, :, i])
            for i in range(0,
                           np.shape(locpot.chg)[3])
        ]
    return avg_c
Ejemplo n.º 14
0
    def write_chg_file(self):
        """Write the charge input file for the vdW calculation."""

        fd = open('%s.chargeden' % self.name, 'w')
        fd.write('lattice\n')
        cell = self.atoms.get_cell()
        for n in range(3):
            fd.write(' %14.7f %14.7f %14.7f\n' %
                     (cell[n, 0], cell[n, 1], cell[n, 2]))
        fd.write('Mesh\n')
        if self.calc_name == 'vasp':
            from ase.calculators.vasp import VaspChargeDensity
            charge = VaspChargeDensity('CHGCAR')
        elif self.calc_name == 'aims':
            from ase.io.cube import read_cube
            charge = read_cube('total_density.cube', read_data=True)
        a, b, c = charge.chg[0].shape
        charge = charge.chg[0].T.ravel()
        charge *= self.atoms.get_volume()
        fd.write(' %5d %5d %5d\n' % (a, b, c))
        fd.write('Density\n')
        for c in charge:
            fd.write('%17.15E\n' % c)
        fd.close()
Ejemplo n.º 15
0
    print("\n** ERROR: Must specify the name of file on command line.")
    print("eg. chgdiff.py CHGCAR")
    print("Only one file name are allowed")
    sys.exit(0)

if not os.path.isfile(prm.CHGCAR[0]):
    print("\n** ERROR: Input file %s was not found." % prm.CHGCAR[0])
    sys.exit(0)

# Read information from command line
# First specify location of CHGCAR
CHGCARfile = prm.CHGCAR[0].lstrip()

# Open geometry and density class objects
#-----------------------------------------
vasp_charge = VaspChargeDensity(filename=CHGCARfile)
if len(vasp_charge.chgdiff) == 3:
    spin = 3
    print("\nReading spin orbital potential data from file %s ... " %
          CHGCARfile,
          end='')
    sys.stdout.flush()
    atoms = vasp_charge.atoms[-1]
    potl_total = vasp_charge.chg[-1]
    potl_x = vasp_charge.chgdiff[0]
    potl_y = vasp_charge.chgdiff[1]
    potl_z = vasp_charge.chgdiff[2]
    if not potl_total.shape == potl_x.shape == potl_y.shape == potl_z.shape:
        print("\n**ERROR: Two sets of data are not on the same grid.")
        print("Data from data block 1 on %dx%dx%d grid." %
              (potl_total.shape[0], potl_total.shape[1], potl_total.shape[2]))
Ejemplo n.º 16
0
# for step in range(1,20):
for step in [14,]:
    # distance = 4.5+step/10.
    # distance = 4.7+step/4.   
    distance = 4+step/4.   
    #First option is to read data from a CHGCAR file and then interpolate density onto
    #an arbitrary plane
    if option=="1":
        # Ask which file to plot
        # inputstr=raw_input("Enter filename of CHGCAR format file containing data:\n")

        print "Reading charge/potential data from file...",
        sys.stdout.flush()

        # Read density and atoms
        vasp_charge = VaspChargeDensity(filename = inputstr)
        density = vasp_charge.chg[-1]
        atoms = vasp_charge.atoms[-1]
        del vasp_charge
        print "Done.\n"

        # Read size of grid 
        ngridpts = numpy.array(density.shape)

        # Read total number of grid points
        totgridpts = ngridpts.prod()

        # Read scaling factor and unit cell
        unit_cell=atoms.get_cell()

        # Take Fourier transform of density
Ejemplo n.º 17
0
from ChargeDensity.image_file_process import charge_file_crop_2d
from CrystalToolkit.geometry_properties import symmetry_order_2d, rectangle_transform_2d
from CrystalToolkit.vasp_chgcar import chgcar_file_slice_2d, charge_file_2d_reformat

file_chgcar = sys.argv[1]
stru = Chgcar.from_file(file_chgcar).poscar.structure
'''
# find the symmetry order of the 2D structure
with open('data.json') as json_file:
    symmetry_data = json.load(json_file)
point_group_list = symmetry_data['point_group_list']
symmetry_order_2d(structure=stru, point_group_list=point_group_list)
'''
# slice the vasp chgcar file into 2D
vasp_charge = VaspChargeDensity(filename=file_chgcar)
density = vasp_charge.chg[-1]
atoms = vasp_charge.atoms[-1]
*_, chgden_2d = chgcar_file_slice_2d(density=density, atoms=atoms)
# change to RGB values, type must be unit 8 otherwise PIL will complain
chgden_2d = (255.0 / chgden_2d.max() * (chgden_2d - chgden_2d.min())).astype(
    np.uint8)
file_png = file_chgcar.replace('chgcar', 'png')
Image.fromarray(chgden_2d).save(file_png)
#cv2.imwrite(file_png, chgden_2d)

#charge_file_2d_reformat(filein=file_chgcar.replace('chgcar', 'chgtile'))

if_transform, alat, blat = rectangle_transform_2d(structure=stru)
if if_transform:
    im = cv2.imread(file_png, 0)
Ejemplo n.º 18
0
#======================================
atom1 = 2  # atom in the center
atom2 = 1  # atom from the plane
atom3 = 0  # second atom in the plain

npx = 90  # number of point to sample the plane in x
npy = 90  # number of point to sample the plane in y

angle = radians(-144)  # rotate the final plot around the central atom
#angle= radians(0)

start = time.time()
sys.stdout.write("Reading CHGCAR... ")
sys.stdout.flush()
CHGCAR = VaspChargeDensity("CHGCAR")
end = time.time()
print "finished. {0}".format(end - start)

cell = CHGCAR.atoms[0].cell
nx, ny, nz = np.shape(CHGCAR.chg[0])
ncell = cell / np.array([nx, ny, nz])

# define plane =================================
p1 = CHGCAR.atoms[0].get_scaled_positions()[atom1]
p2 = CHGCAR.atoms[0].get_scaled_positions()[atom2]
p3 = CHGCAR.atoms[0].get_scaled_positions()[atom3]

# get normal to the plane
v1 = p2 - p1
v2 = p3 - p1
Ejemplo n.º 19
0
# Check that files exist
for name in sys.argv[1:]:
    if not os.path.isfile(name):
        print "\n** ERROR: Input file %s was not found." % name
        sys.exit(0)

# Read information from command line
# First specify location of CHGCAR file with reference density
CHGCARfile1 = sys.argv[1].lstrip()

# Open geometry and density class objects
#-----------------------------------------
print "Reading density data from file %s ..." % CHGCARfile1,
sys.stdout.flush()
vasp_charge1 = VaspChargeDensity(filename=CHGCARfile1)
chg1 = vasp_charge1.chg[-1]
atoms1 = vasp_charge1.atoms[-1]
del vasp_charge1
print "done."

chgadd = chg1
for CHGCARfile2 in sys.argv[2:]:
    CHGCARfile2 = CHGCARfile2.strip()
    print "Reading density data from file %s ..." % CHGCARfile2,
    sys.stdout.flush()
    vasp_charge2 = VaspChargeDensity(filename=CHGCARfile2)
    chg2 = vasp_charge2.chg[-1]
    del vasp_charge2
    print "done."
Ejemplo n.º 20
0
       print "\n**ERROR: Two sets of data are not on the same grid."
       print "Data from file %s on %dx%dx%d grid." % (CHGCARfile1,chg1.shape[0],chg1.shape[1],chg1.shape[2])
       print "Data from file %s on %dx%dx%d grid.\n" % (CHGCARfile2,chg2.shape[0],chg2.shape[1],chg2.shape[2])
       sys.exit(0)
    else:
       print "Adding data from file %s ..." % CHGCARfile2,
       sys.stdout.flush()

    # Add charge density
    #-----------------
    chgadd += chg2
    print "done." 

zero = raw_input("Set negative values of the added charge density to zero (Yes/No): ")

vasp_charge_add = VaspChargeDensity(filename=None)
vasp_charge_add.atoms=[atoms1,]
vasp_charge_add.chg=[chgadd,] 

# Print out charge density
#--------------------------
# Check whether CHGADD exists
if os.path.isfile("./CHGADD"):
   print "\n**WARNING: A file called CHGADD already exists in this directory."
   yesno=raw_input("Type y to continue and overwrite it, any other key to stop\n")
   if yesno!="y":
      sys.exit(0)


print "Writing added density data to file CHGADD ...", 
sys.stdout.flush()
Ejemplo n.º 21
0
    sys.exit(0)

if not os.path.isfile(prm.OUTCAR):
    print("\n** ERROR: Input file %s was not found." % prm.CHGCAR)
    sys.exit(0)


# Read information from command line
# First specify location of CHGCAR
CHGCARfile = prm.CHGCAR.lstrip()
OUTCARfile = prm.OUTCAR.lstrip()


# Open geometry and density class objects
#-----------------------------------------
vasp_charge = VaspChargeDensity(filename = CHGCARfile)
potl = vasp_charge.chg[-1]
atoms = vasp_charge.atoms[-1]
del vasp_charge

# Open outcar to find zval and ions_per_type
#-----------------------------------------
with open(OUTCARfile) as search:
    for line in search:
        line = line.rstrip()  # remove '\n' at end of line
        if "ZVAL" in line:
            ZVAL = line.split()[2:]
        elif "ions per type" in line:
            ions_per_type = line.split()[4:]

Ejemplo n.º 22
0
# Check that files exist
for name in sys.argv[1:]:
    if not os.path.isfile(name):
        print "\n** ERROR: Input file %s was not found." % name
        sys.exit(0)

# Read information from command line
# First specify location of CHGCAR file with reference density
CHGCARfile1 = sys.argv[1].lstrip()

# Open geometry and density class objects
#-----------------------------------------
print "Reading potential data from file %s ..." % CHGCARfile1,
sys.stdout.flush()
vasp_charge1 = VaspChargeDensity(filename=CHGCARfile1)
chg1 = vasp_charge1.chg[-1]
atoms1 = vasp_charge1.atoms[-1]
del vasp_charge1
print "done."

chgdiff = chg1
for CHGCARfile2 in sys.argv[2:]:
    CHGCARfile2 = CHGCARfile2.strip()
    print "Reading potential data from file %s ..." % CHGCARfile2,
    sys.stdout.flush()
    vasp_charge2 = VaspChargeDensity(filename=CHGCARfile2)
    chg2 = vasp_charge2.chg[-1]
    del vasp_charge2
    print "done."
Ejemplo n.º 23
0
spin_cut_off = 0.4
density_cut_off = 0.15

rotation = '24x, 34y, 14z'
#rotation = '0x, 0y, 0z'

run_povray = True

pov_name = 'NiO_marching_cubes.pov'
ini_name = 'NiO_marching_cubes.ini'

#########################

from ase.calculators.vasp import VaspChargeDensity
vchg = VaspChargeDensity('CHGCAR')
atoms = vchg.atoms[0]

kwargs = {  # For povray files only
    'pause': False,  # Pause when done rendering (only if display)
    'transparent': False,  # Transparent background
    'canvas_width': None,  # Width of canvas in pixels
    'canvas_height': 1024,  # Height of canvas in pixels
    'show_unit_cell': 1,
    'camera_dist': 25.0,  # Distance from camera to front atom
    'camera_type': 'orthographic angle 35',  # 'perspective angle 20'
    'radii': atoms.positions.shape[0] * [0.3],
    'textures': len(atoms) * ['ase3']
}

# some more options:
#'image_plane'  : None,  # Distance from front atom to image plane
Ejemplo n.º 24
0
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from ase.calculators.vasp import VaspChargeDensity

print("-" * 86)
starttime = time.perf_counter()
print("Starting the program at")
print(time.strftime("%Y-%m-%d %H:%M:%S"))
print("-" * 86)

# Check if the PARCHG exists and import charge density data from it.
# If not, enter the filename of CHGCAR/PARCHG format file containing charge density data.
if os.path.exists("PARCHG"):
    print("PARCHG file already exists, reading data now...\n")
    vasp_charge = VaspChargeDensity('PARCHG')
    density = vasp_charge.chg[-1]
    atoms = vasp_charge.atoms[-1]
    del vasp_charge
    print("Done!\n")

else:
    active = True
    while active:
        inputstr1 = input(
            "Enter the filename of CHGCAR/PARCHG format file containing data:")
        if os.path.exists(inputstr1):
            print("\nReading charge density data from %s...\n" % inputstr1)
            vasp_charge = VaspChargeDensity(filename=inputstr1)
            density = vasp_charge.chg[-1]
            atoms = vasp_charge.atoms[-1]
Ejemplo n.º 25
0
                  dest='outfile',
                  help='Output to file \
named by this argument. If omitted, defaults to a file chgfile0_op_chgfile1')
parser.add_option('-w',
                  '--which-cell',
                  dest='wcell',
                  help='Take the \
embedded supercell information from which charge density file. Must be \
either 0 or 1.')
(options, args) = parser.parse_args()

chgf1 = args[0]
chgf2 = args[2]
op = args[1]

chg1 = VaspChargeDensity(chgf1)
chg2 = VaspChargeDensity(chgf2)

if options.wcell:
    wcell = int(options.wcell)
    if wcell == 0:
        chga = chg1
    elif wcell == 1:
        chga = chg2
    else:
        print 'Error, invalid argument to -w option'
        sys.exit(1)
else:
    chga = chg1

if len(chg1.chg) != len(chg2.chg):
Ejemplo n.º 26
0
    opt_diff = options.diff
    opt_grad = options.gradient

    two_files_involved = (opt_diff)

    ####### READING THE FILE #############
    if (iformat == "cube"):
        if (two_files_involved):
            field, atoms = read_cube(sys.argv[num - 2], read_data=True)
            field2, atoms2 = read_cube(sys.argv[num - 1], read_data=True)
            if (atoms == atoms2):
                print "WARRNING: geometries of the system are not the same"
        else:
            field, atoms = read_cube(sys.argv[num - 1], read_data=True)
    elif (iformat == "locpot"):
        locpot = VaspChargeDensity(filename=sys.argv[num - 1])
        field = locpot.chg[-1]
        atoms = locpot.atoms[-1]
        del locpot

####### MANIPULATE #############
    get = options.get

    # Calculate Gradient of the fild
    if (opt_grad != None):
        #    if(get == "diffx" or get == "diffy" or get == "diffz"):
        cell = np.array(atoms.get_cell())
        shape = np.array(field.shape)
        dr = np.empty(3)
        for i in range(3):
            if (shape[i] % 2 == 1):
Ejemplo n.º 27
0
if not os.path.isfile(sys.argv[1]):
    print "\n** ERROR: Input file %s was not found." % sys.argv[1]
    sys.exit(0)

if not os.path.isfile(sys.argv[2]):
    print "\n** ERROR: Input file %s was not found." % sys.argv[1]
    sys.exit(0)

# Read information from command line
# First specify location of LOCPOT
LOCPOTfile = sys.argv[1].lstrip()
OUTCARfile = sys.argv[2].lstrip()

# Open geometry and density class objects
#-----------------------------------------
vasp_charge = VaspChargeDensity(filename=LOCPOTfile)
potl = vasp_charge.chg[-1]
atoms = vasp_charge.atoms[-1]
del vasp_charge

# Open outcar to find zval and ions_per_type
#-----------------------------------------
with open(OUTCARfile) as search:
    for line in search:
        line = line.rstrip()  # remove '\n' at end of line
        if "ZVAL" in line:
            ZVAL = line.split()[2:]
        elif "ions per type" in line:
            ions_per_type = line.split()[4:]

print "\nElectronic part"
Ejemplo n.º 28
0
def chgarith(chgf1, chgf2, op, filename, wcell):

    # chgf1 = args[0]
    # chgf2 = args[2]
    # op = args[1]

    chg1 = VaspChargeDensity(chgf1)
    chg2 = VaspChargeDensity(chgf2)

    # if options.wcell:
    #     wcell = int(options.wcell)
    if wcell == 0:
        chga = chg1
    elif wcell == 1:
        chga = chg2
    #     else:
    #         print ('Error, invalid argument to -w option')
    #         sys.exit(1)
    # else:
    # chga = chg1

    if len(chg1.chg) != len(chg2.chg):
        print(
            'Number of images in charge density files not equal. Using just   the final images in both files.'
        )
        print('len(chg.chg)', len(chg1.chg), len(chg2.chg))
        chg1.chg = [chg1.chg[-1]]
        chg1.atoms = [chg1.atoms[-1]]
        if chg1.is_spin_polarized():
            chg1.chgdiff = [chg1.chgdiff[-1]]
            chg2.chgdiff = [chg2.chgdiff[-1]]
        chg2.chg = [chg2.chg[-1]]
        chg2.atoms = [chg2.atoms[-1]]

    newchg = VaspChargeDensity(None)

    print('Start charge manipul')

    for i, atchg in enumerate(chg1.chg):
        c1 = atchg
        c2 = chg2.chg[i]
        newchg.atoms.append(chga.atoms[i].copy())
        if op == '+':
            nc = c1 + c2
            oplong = '_add_'
        elif op == '-':
            nc = c1 - c2
            oplong = '_sub_'
        elif op == '*':
            nc = c1 * c2
            oplong = '_mult_'
        elif op == '/':
            nc = c1 / c2
            oplong = '_div_'
        elif op == 'avg':
            nc = (c1 + c2) / 2
            oplong = '_avg_'
        newchg.chg.append(nc)

    if chg1.is_spin_polarized():
        print('Spin polarized')

        for i, cd in enumerate(chg1.chgdiff):
            cd2 = chg2.chgdiff[i]
            if op == '+':
                nd = cd + cd2
            elif op == '-':
                nd = cd - cd2
            elif op == '*':
                nd = cd * cd2
            elif op == '/':
                nd = cd / cd2
            elif op == 'avg':
                nd = (cd + cd2) / 2
            newchg.chgdiff.append(nd)

    # Screw doing anything fancy with the augmentation charges
    # Just take them from the same file as the embedded atoms object.
    newchg.aug = chga.aug
    newchg.augdiff = chga.augdiff

    # if options.outfile:
    #     fname = options.outfile
    # else:
    #     from os.path import basename
    #     fname = basename(chgf1) + oplong + basename(chgf2)

    newchg.write(filename)

    return filename
Ejemplo n.º 29
0
    # --------------------------------------------------------
    if chg2.shape != chg1.shape:
        print "\n**ERROR: Two sets of data are not on the same grid."
        print "Data from file %s on %dx%dx%d grid." % (CHGCARfile1, chg1.shape[0], chg1.shape[1], chg1.shape[2])
        print "Data from file %s on %dx%dx%d grid.\n" % (CHGCARfile2, chg2.shape[0], chg2.shape[1], chg2.shape[2])
        sys.exit(0)
    else:
        print "Subtracting data from file %s ..." % CHGCARfile2,
        sys.stdout.flush()

    # Take difference
    # -----------------
    chgdiff = chgdiff - chg2
    print "done."

vasp_charge_diff = VaspChargeDensity(filename=None)
vasp_charge_diff.atoms = [atoms1]
vasp_charge_diff.chg = [chgdiff]

# Print out charge density
# --------------------------
# Check whether CHGDIFF exists
if os.path.isfile("./CHGDIFF"):
    print "\n**WARNING: A file called CHGDIFF already exists in this directory."
    yesno = raw_input("Type y to continue and overwrite it, any other key to stop\n")
    if yesno != "y":
        sys.exit(0)


print "Writing density difference data to file CHGDIFF ...",
sys.stdout.flush()
Ejemplo n.º 30
0
    print "eg. splitparchg.py PARCHG ."                                         
    sys.exit(0)

if not os.path.isfile(sys.argv[1]):
    print "\n** ERROR: Input file %s was not found." % sys.argv[1]
    sys.exit(0)

# Read information from command line
# First specify location of PARCHG 
PARCHGfile = sys.argv[1].lstrip()

# Open geometry and density class objects
#-----------------------------------------
print "Reading potential data from file %s ..." % PARCHGfile,
sys.stdout.flush()
vasp_charge_data = VaspChargeDensity(filename=PARCHGfile)
print "done." 
# Check data is spin polarised
if not vasp_charge_data.is_spin_polarized():
    print "\n** ERROR: Input file does not contain spin polarised data."
    sys.exit(0)
# Make Atoms object and arrays of density data
geomdata = vasp_charge_data.atoms[-1]
parchg_sum = vasp_charge_data.chg[-1]
parchg_diff = vasp_charge_data.chgdiff[-1]

# Read in potential data
#------------------------
ngridpts = numpy.array(parchg_sum.shape)
totgridpts = ngridpts.prod()
print "Potential stored on a %dx%dx%d grid" % (ngridpts[0],ngridpts[1],ngridpts[2])