Exemplo n.º 1
0
def test_magmom_ldau_2():
    '''Check if magmom is written twice in ldau calculations.  

    I have seen this and consider it a bug. This test catches the
    bug. This test also checks that a new keyword is written and a
    None keyword is removed by prepare_input_files.
    '''
    with jasp('ldau-magmom-1') as calc:
        calc.clone('ldau-magmom-2')

    with jasp('ldau-magmom-2',
              ibrion=None,
              ldauprint=2) as calc:
        calc.prepare_input_files()

    counter = 0
    ibrion_found = False
    found = False
    with open('ldau-magmom-2/INCAR') as f:
        for line in f:
            if 'IBRION' in line:
                ibrion_found = True
            if 'LDAUPRINT' in line:
                found = True
            if 'MAGMOM' in line:
                counter += 1

    assert not ibrion_found
    assert found
    assert counter == 1
Exemplo n.º 2
0
def test1_magmom():

    atoms = BodyCenteredCubic(directions=[[1,0,0],
                                          [0,1,0],
                                          [0,0,1]],
                              size=(1,1,1),
                              symbol='Fe')

    for atom in atoms:
        atom.magmom = 2

    with jasp('Fe-magmom',
          xc='PBE',
          encut=300,
          kpts=(4,4,4),
          ispin=2,
          atoms=atoms) as calc:
        calc.prepare_input_files()
        atoms.get_potential_energy()

    with jasp('Fe-magmom') as calc:
        atoms.get_potential_energy()
        
    counter = 0
    with open('Fe-magmom/INCAR') as f:
        for line in f:
            if 'MAGMOM' in line:
                counter += 1

    assert counter == 1
Exemplo n.º 3
0
def add_alloydata(**args):
    cov = args['cov']
    ads = args['ads']
    site = args['site']
    root = args['root']
    if root == None:
        nullstr = 'is null'
    else:
        nullstr = '= ?'
    alloytype = args['alloytype']
    slabdir = 'slab/{1}x{2}/'.format(args['host'], cov[0], cov[1])
    adsdir = '{2}_BE/{3}/{0}x{1}/'.format(cov[0], cov[1], ads, args['site'])
    str_index = len(ads) + 1

    for alldir in os.listdir(adsdir):
        alloy = alldir[:-str_index]
        if (not alloy.startswith(args['host'])):
            allsites = [string.split('_') for string in alloy.split('-')]
            isite = allsites[0][0]
            asite = allsites[1][0]
            hostnum = ele_dict[args['host']]
            solnum = ele_dict[allsites[0][1]]
            deltaz = abs(hostnum - solnum)
            cov = '{}x{}'.format(*args['cov'])
            efine = energies_are_fine(slabdir, adsdir, ads, alloy)

            queryargs = [
                args['host'], args['fac'], None, None, cov, alloy, root,
                alloytype
            ]
            data_exists = data_in_db(queryargs, nullstr, calctype='slab')
            if (not data_exists and efine):
                with jasp(slabdir + '/' + alloy) as calc:
                    try:
                        atoms = calc.get_atoms()
                        energy = atoms.get_potential_energy()
                        data = queryargs[:-2] + [deltaz, isite, asite, energy
                                                 ] + queryargs[-2:]
                        write_db(data)
                    except:
                        print alloy, 'Something went wrong: Slab'

            queryargs = [
                args['host'], args['fac'], ads, site, cov, alloy, root,
                alloytype
            ]
            data_exists = data_in_db(queryargs, nullstr, calctype='ads')
            if efine and data_exists == False:
                with jasp(adsdir + '/' + alloy + '_' + ads) as calc:
                    try:
                        atoms = calc.get_atoms()
                        energy = atoms.get_potential_energy()
                        data = queryargs[:-2] + [deltaz, isite, asite, energy
                                                 ] + queryargs[-2:]
                        write_db(data)
                    except:
                        print alloy, 'Something went wrong: Ads'
Exemplo n.º 4
0
def test4():
    "basic setup calculation that adds constraints so a calculation should be required"
    os.chdir(os.path.join(jaspdir, 'tests'))
    from ase.constraints import FixAtoms
    with jasp('c1') as calc:
        calc.clone('c2')

    with jasp('c2') as calc:
        atoms = calc.get_atoms()
        c = FixAtoms(mask=[atom.symbol == 'O' for atom in atoms])
        atoms.set_constraint(c)
        assert calc.calculation_required(atoms, ['energy'])
Exemplo n.º 5
0
def test4():
    "basic setup calculation that adds constraints so a calculation should be required"

    from ase.constraints import FixAtoms
    with jasp('c1') as calc:
        calc.clone('c2')

    with jasp('c2') as calc:
        atoms = calc.get_atoms()
        c = FixAtoms(mask=[atom.symbol == 'O' for atom in atoms])
        atoms.set_constraint(c)
        assert calc.calculation_required(atoms,['energy'])
Exemplo n.º 6
0
def test_ldauj():

    atoms = BodyCenteredCubic(directions=[[-1, 1, 1],
                                          [1, -1, 1],
                                          [1, 1, -1]],
                              size=(2, 2, 2),
                              symbol='Fe')

    with jasp('Fe-base',
              xc='PBE',
              sigma=0.1,
              kpts=(4, 4, 4),
              nbands=44,
              setups={'0': 'Fe'},
              ldau=True,
              ldautype=3,
              ldaul=[2, -1],
              ldauu=[0, 0],
              ldauj=[0, 0],
              ldauprint=2,
              lmaxmix=4,
              lorbit=11,
              debug=logging.DEBUG,
              atoms=atoms) as calc:
        assert not calc.calculation_required(calc.get_atoms(), ['energy'])
Exemplo n.º 7
0
def write_database(wd, db='data.db', overwrite=False):
    JASPRC['restart_unconverged'] = False

    db = os.path.join(os.path.abspath(os.getcwd()), db)

    if os.path.exists(db) and overwrite:
        os.unlink(db)

    for r, d, f in os.walk(wd):
        if 'OUTCAR' in f and 'XDATCAR' in f:
            try:
                with jasp(r) as calc:
                    try:
                        compile_trajectory(calc)
                        traj = Trajectory('out.traj')
                        n = len(traj)

                        for i, atoms in enumerate(traj):

                            makedb(calc,
                                   atoms=atoms,
                                   dbname=db,
                                   keys={'traj': int(n-i-1)})
                    except(VaspQueued, VaspSubmitted):
                        pass
            except(RuntimeError):
                os.unlink(os.path.join(r, 'out.traj'))
            except:
                print(r)
                print(sys.exc_info()[0])
                print('')
Exemplo n.º 8
0
def run(job, atoms):
  with jasp('224-co/vib/{0}'.format(job),
        xc='PBE',
#        ldau='True',   # turn DFT+U on
#        ldautype=2,  # select simplified rotationally invariant option
#        ldau_luj={'Ce':{'L':3,  'U':5.0, 'J':0.0},
#                   'O':{'L':-1, 'U':0.0, 'J':0.0}},
#        ldauprint=1,
#        lasph='True',
        kpts=[3, 3, 1],
        gamma=True,
        encut=400,
        ismear=0,
        sigma=0.05,
        ibrion=5,  # finite differences with symmetry
        nfree=2,  # central differences (default)
        potim=0.015,  # default as well
        ediff=1e-7,
        lreal='auto',
        prec='accurate',
        algo='fast',
#        lmaxmix=6, # L(S)DA+U calculations require in many cases an increase of LMAXMIX to 4 (or 6 for f-elements)
        nelm=100,
        nsw=1,
        atoms=atoms) as calc:
      e = atoms.get_potential_energy()
      c = 3e10  # cm/s
      h = 4.135667516e-15  # eV*s
      f, m = calc.get_vibrational_modes(0)
      #allfreq = calc.get_vibrational_modes()[0]
      print("{0}       {1}       {2}      {3} ".format(job, e, f, f / (h * c)))
Exemplo n.º 9
0
Arquivo: views.py Projeto: saisai/jasp
def jaspsum(request, path, format):
    'return summary of a vasp directory'
    vasppath = os.path.join(DATAROOT, path)
    if not os.path.isdir(vasppath):
        content = 'No data found for %s in jaspsum. format = %s' % (vasppath, format)
        content_type = 'text/html'
    else:
        with jasp(vasppath) as calc:
            if format == '/xml':
                content = calc.xml
                content_type = 'text/xml'
            elif format == '/json':
                content = calc.json
                content_type = 'application/json'
            elif format == '/python':
                content = repr(calc)
                content_type = 'application/x-python'
            elif format == '/html':
                calc_content = str(calc)
                content = '''
<pre>{calc_content}</pre>
<p><a href="file/INCAR">INCAR</a></p>
<p><a href="file/POSCAR">POSCAR</a></p>
<p><a href="file/KPOINTS">KPOINTS</a></p>
<p><a href="file/OUTCAR">OUTCAR</a></p>
'''.format(**locals())
                content_type='text/html'
            else:
                content = str(calc)
                content_type = 'text/plain'
    return HttpResponse(content=content,
                        content_type=content_type)
Exemplo n.º 10
0
def test1_magmom():
    '''Make sure magmom is not getting written twice'''
    atoms = BodyCenteredCubic(directions=[[1, 0, 0],
                                          [0, 1, 0],
                                          [0, 0, 1]],
                              size=(1, 1, 1),
                              symbol='Fe')

    for atom in atoms:
        atom.magmom = 2

    with jasp('Fe-magmom',
              xc='PBE',
              encut=300,
              kpts=(4, 4, 4),
              ispin=2,
              atoms=atoms) as calc:
        calc.prepare_input_files()

    counter = 0
    with open('Fe-magmom/INCAR') as f:
        for line in f:
            if 'MAGMOM' in line:
                counter += 1

    assert counter == 1
    shutil.rmtree('Fe-magmom')
Exemplo n.º 11
0
def test():
    '''This test copies an old calculation to a new calculation and makes
    sure that rereading results in a state that does not need a new
    calculation.
    '''
    a = 2.87
    a1 = np.array((-a / 2, a / 2, a / 2))
    a2 = np.array((a / 2, -a / 2, a / 2))
    a3 = np.array((a / 2, a / 2, -a / 2))
    bulk = Atoms([Atom('Fe', (0, 0, 0), magmom=5)], cell=(a1, a2, a3))
    os.chdir(os.path.join(jaspdir, 'tests'))
    with jasp('Fe-bcc-U',
              atoms=bulk,
              debug=logging.DEBUG,
              xc='PBE',
              kpts=(8, 8, 8),
              ispin=2,
              lorbit=11,
              ldau=True,
              ldau_luj={'Fe': {
                  'L': 2,
                  'U': 2,
                  'J': 0
              }},
              lwave=False) as calc:
        # no calculation should be required here.
        assert not calc.calculation_required(calc.get_atoms(), ['energy'])
Exemplo n.º 12
0
def test_magmom_ldau():

    atoms = Atoms([Atom('Mn', [0, 0, 0], magmom=2),
                   Atom('O', [1.6, 0, 0], magmom=2)],
                  cell=(8, 9, 10))

    atoms.center()

    with jasp('ldau-magmom-1',
              xc='PBE',
              sigma=0.1,
              ispin=2,
              ibrion=1, nsw=50, ediffg=-0.05,
              ldau=True,
              ldautype=3,
              ldaul=[2, -1],  # Eventually perturb d-orbital on Mn
              ldauu=[0, 0],
              ldauj=[0, 0],
              lorbit=11,  # this prints the orbital occupations
              atoms=atoms) as calc:
        calc.prepare_input_files()

    counter = 0
    with open('ldau-magmom-1/INCAR') as f:
        for line in f:
            if 'MAGMOM' in line:
                counter += 1

    assert counter == 1
Exemplo n.º 13
0
def run():
    # look for atat.json It contains all the data we want. If it
    # exists, just return so no new calculations get created.
    if os.path.exists('atat.json'):
        with open('atat.json') as f:
            data = json.loads(f.read())
            data['cwd'] = cwd
            print s.format(**data)
            return data

    # get the atoms object from str.out
    atoms = str2atoms()

    # adjust volume according to Vegard's law and set the magnetic moments
    vol = 0.0
    for atom in atoms:
        atom.magmom = MAGMOMS.get(atom.symbol, 0.0)
        vol += VOL[atom.symbol]
    atoms.set_volume(vol)

    kpts = get_kpts_from_kppra(atoms, KPPRA)

    # now we get the equation of state
    with jasp('.',
              kpts=kpts,
              atoms=atoms,
              **vasppars) as calc:
        calc.set_nbands(f=2)
        
        try:
            data = calc.get_eos()
        except:
            with open('error', 'w') as f:
                f.write('Error getting the equation of state')

        M = atoms.get_magnetic_moment()
        B = data['step2']['avgB']
            
        with open('energy', 'w') as f:
            f.write(repr(data['step3']['potential_energy']))

    # now we are done, we can delete some files
    for f in ['wait', 'jobid', 'error']:
        if os.path.exists(f):
            os.unlink(f)

    # create json data to store
    jsondata = {'cwd':cwd,
                'energy': data['step3']['potential_energy'],
                'volume': data['step3']['volume']/len(atoms),
                'B':B,
                'M':M}
    
    # save json data
    with open('atat.json','w') as f:
        f.write(json.dumps(jsondata))

    # print summary line
    print(s.format(**jsondata))
    return jsondata # in case this is ever called as a function
Exemplo n.º 14
0
def run(job, atoms):
  with jasp('pt1-2co/vib/{0}'.format(job)) as calc:
      atoms = calc.get_atoms()
      e = atoms.get_potential_energy()
      f, m = calc.get_vibrational_modes()
      allfreq = calc.get_vibrational_modes()
      print("{0}       {1}       {2}  {3}   ".format(job,  e,  f[0]/(h*c), f[1] / (h * c)))
Exemplo n.º 15
0
def run(job, atoms):
  with jasp('alter-pt1-co-vib/{0}'.format(job)) as calc:
      atoms = calc.get_atoms()
      e = atoms.get_potential_energy()
      f, m = calc.get_vibrational_modes(0)
      allfreq = calc.get_vibrational_modes()
      print("{0}       {1}       {2}     {3}".format(job,  e,  f, f / (h * c)))
Exemplo n.º 16
0
def call_jasp(atoms, kp, calcdir, spin, nsteps, qe, cluster):
    if cluster == 'frank':
        JASPRC['queue.walltime'] = '48:00:00'
        JASPRC['queue.options'] = '-q {} -j oe'.format(q_dict[qe][2])
        JASPRC['queue.nodes'] = q_dict[qe][0]
        JASPRC['queue.ppn'] = q_dict[qe][1]

    elif cluster == 'h2p' or cluster == 'mpi':
        JASPRC['queue.nodes'] = q_dict[qe][0]
        JASPRC['queue.ppn'] = q_dict[qe][1]
        JASPRC['queue.cluster'] = q_dict[qe][2]

    with jasp(calcdir,
        xc = 'PBE',
        kpts = [kp, kp, 1],
        encut = 350,
        nsw = nsteps,
        ibrion = 2,
        lwave = False,
        lcharg = False,
        ispin = spin,
        idipol = 3,
        ediff = 1e-05,
        ediffg = -0.05,
        atoms = atoms) as calc:
	    try:
	    	return atoms.get_potential_energy()
	    except (VaspSubmitted, VaspQueued):
	    	print "Submitted to queue"
Exemplo n.º 17
0
def run(job, atoms):
  with jasp('surfaces/al2o3-0001-al-ter-pt1-co-vib/{0}'.format(job)) as calc:
      atoms = calc.get_atoms()
      e = atoms.get_potential_energy()
      f, m = calc.get_vibrational_modes(0)
      #allfreq = calc.get_vibrational_modes()[0]
      print("{0}       {1}       {2}     {3}".format(job,  e,  f, f / (h * c)))
Exemplo n.º 18
0
def run(job, atoms):
  with jasp('pt1-2co/relax/{0}'.format(job),
        xc='PBE',
        ldau='True',   # turn DFT+U on
        ldautype=2,  # select simplified rotationally invariant option
        ldau_luj={'Ce':{'L':3,  'U':5.0, 'J':0.0},
                   'O':{'L':-1, 'U':0.0, 'J':0.0}},
        ldauprint=1,
        lasph='True',
        kpts=[3, 3, 1],
        gamma=True,
        encut=400,
        ismear=0,
        sigma=0.05,
        ibrion=2,
        ediff=1e-5,
        lreal='auto',
        prec='accurate',
        algo='fast',
        lmaxmix=6, # L(S)DA+U calculations require in many cases an increase of LMAXMIX to 4 (or 6 for f-elements)
        nelm=100,
        nsw=200,
        atoms=atoms) as calc:
      e = atoms.get_potential_energy()
      print("{0}     {1}".format(job, e))
Exemplo n.º 19
0
def test5():
    "basic setup calculation that tests if kpts are equal"
    os.chdir(os.path.join(jaspdir, 'tests'))
    with jasp('c1', kpts=(1, 1, 1)) as calc:
        print calc.input_params
        print calc.old_input_params
        assert not calc.calculation_required(calc.get_atoms(), [])
Exemplo n.º 20
0
def ChargeDensityFog3D(directory, save_file=None , DrawAtoms=True, DrawCell=True, opacity_range=[0,1]):
    # Get data from calculation files
    with jasp(directory) as calc:
        atoms = calc.get_atoms()
        x, y, z, cd = calc.get_charge_density()

    mlab.figure(bgcolor=(0,0,0), size=(640,480))

    # Draw atoms
    if DrawAtoms == True:
        for atom in atoms:
            mlab.points3d(atom.x,
                          atom.y,
                          atom.z,
                          scale_factor=vdw_radii[atom.number]/10.,
                          resolution=16,
                          color=tuple(cpk_colors[atom.number]),
                          scale_mode='none')
    # Draw unit cell
    if DrawCell == True:
        a1, a2, a3 = atoms.get_cell()
        origin = [0,0,0]
        cell_matrix = [[origin, a1],
                       [origin, a2],
                       [origin, a3],
                       [a1, a1+a2],
                       [a1, a1+a3],
                       [a2, a2+a1],
                       [a2, a2+a3],
                       [a3, a1+a3],
                       [a3, a2+a3],
                       [a1+a2, a1+a2+a3],
                       [a2+a3, a1+a2+a3],
                       [a1+a3, a1+a3+a2]] # contains all points on the box
        for p1, p2 in cell_matrix:
            mlab.plot3d([p1[0], p2[0]], # x-coords of box
                        [p1[1], p2[1]], # y-coords
                        [p1[2], p2[2]]) # z-coords

    # Plot the charge density
    src = mlab.pipeline.scalar_field(x, y, z, cd) #Source data
    vmin = cd.min() #find minimum and maximum value of CD data
    vmax = cd.max()
    vol = mlab.pipeline.volume(src) # Make a volumetric representation of the data

    # Set opacity transfer function
    from tvtk.util.ctf import PiecewiseFunction
    otf = PiecewiseFunction()
    otf.add_point(vmin, opacity_range[0]) #Transparency at zero electron density
    otf.add_point(vmax*1, opacity_range[1]) #Transparency at max electron density
    vol._otf=otf
    vol._volume_property.set_scalar_opacity(otf)

    #Show a legend
    mlab.colorbar(title="e- density\n(e/Ang^3)", orientation="vertical", nb_labels=5, label_fmt='%.2f')
    mlab.view(azimuth=-90, elevation=90, distance='auto') # Set viewing angle
    mlab.show()
    if save_file != None:
        mlab.savefig(save_file)
Exemplo n.º 21
0
def run():
    # look for atat.json It contains all the data we want. If it
    # exists, just return so no new calculations get created.
    if os.path.exists('atat.json'):
        with open('atat.json') as f:
            data = json.loads(f.read())
            data['cwd'] = cwd
            print s.format(**data)
            return data

    # get the atoms object from str.out
    atoms = str2atoms()

    # adjust volume according to Vegard's law and set the magnetic moments
    vol = 0.0
    for atom in atoms:
        atom.magmom = MAGMOMS.get(atom.symbol, 0.0)
        vol += VOL[atom.symbol]
    atoms.set_volume(vol)

    kpts = get_kpts_from_kppra(atoms, KPPRA)

    # now we get the equation of state
    with jasp('.', kpts=kpts, atoms=atoms, **vasppars) as calc:
        calc.set_nbands(f=2)

        try:
            data = calc.get_eos()
        except:
            with open('error', 'w') as f:
                f.write('Error getting the equation of state')

        M = atoms.get_magnetic_moment()
        B = data['step2']['avgB']

        with open('energy', 'w') as f:
            f.write(repr(data['step3']['potential_energy']))

    # now we are done, we can delete some files
    for f in ['wait', 'jobid', 'error']:
        if os.path.exists(f):
            os.unlink(f)

    # create json data to store
    jsondata = {
        'cwd': cwd,
        'energy': data['step3']['potential_energy'],
        'volume': data['step3']['volume'] / len(atoms),
        'B': B,
        'M': M
    }

    # save json data
    with open('atat.json', 'w') as f:
        f.write(json.dumps(jsondata))

    # print summary line
    print(s.format(**jsondata))
    return jsondata  # in case this is ever called as a function
Exemplo n.º 22
0
 def read_energy(self, calcdir):
     with jasp(calcdir) as calc:
         try:
             atoms = calc.get_atoms()
             energy = atoms.get_potential_energy()
             return energy
         except:
             print slabdir, 'Calc not completed'
Exemplo n.º 23
0
def test5():
    "basic setup calculation that tests if kpts are equal"

    with jasp('c1',
              kpts=(1,1,1)) as calc:
        print calc.input_params
        print calc.old_input_params
        assert not calc.calculation_required(calc.get_atoms(),[])
Exemplo n.º 24
0
def run(job, atoms):
  with jasp('surfaces/parallel/{0}'.format(job),
          xc='PBE',
          kpts=[9, 9, 9],
          encut=300,
          prec='accurate',
          atoms=atoms) as calc:
      print("{0}    {1}".format(job, atoms.get_potential_energy()))
Exemplo n.º 25
0
def ref_calc_is_ok(slabdir,adsdir):
    slabenergy = 0
    with jasp(slabdir) as calc:
        try:
            atoms = calc.get_atoms()
            slabenergy = atoms.get_potential_energy()
        except:
            print slabdir, 'Calc not completed'

    adsenergy = 0
    with jasp(adsdir) as calc:
        try:
            atoms = calc.get_atoms()
            adsenergy = atoms.get_potential_energy()
        except:
            print adsdir, 'Calc not completed'

    if (slabenergy == 0) or (adsenergy == 0):
        return False
    else:
        return True
Exemplo n.º 26
0
def run(job, atoms):
  with jasp('cluster/pt-nco/relax/{0}'.format(job),
          xc='PBE',
          encut=400,
          kpts=[3, 3, 3],
          ismear=0,
          sigma=0.05, # this is small for a molecule
          ibrion=2,   # conjugate gradient optimizer
          nsw=200,      # do at least 5 steps to relax
          ediff=1e-5,   # set precise energies
          atoms=atoms) as calc:
    e = atoms.get_potential_energy()
    print('{0:1.2f}  {1:1.4f}  '.format(job, e))
Exemplo n.º 27
0
Arquivo: views.py Projeto: saisai/jasp
def get_resource(request, path, resource):
    'get a resource from the path'
    vaspdir = os.path.join(DATAROOT, path)
    if not os.path.isdir(vaspdir):
        content = 'No data in {0}'.format(vaspdir)

    if resource.lower() == 'energy/':
        with jasp(vaspdir) as calc:
            atoms = calc.get_atoms()
            return HttpResponse(atoms.get_potential_energy(),
                                content_type='text/plain')
    else:
        return HttpResponse('Unknown resource: %s' % resource)
Exemplo n.º 28
0
def run(job, atoms):
    with jasp('alter-def-relax/{0}'.format(job),
          xc='PBE',
          kpts=[3, 3, 1],
          gamma=True,
          encut=400,
          ismear=0,
          ibrion=2,
          lreal='auto',
          prec='accurate',
          algo='fast',
          nsw=200,
          atoms=atoms) as calc:
        print("{0}    {1}".format(job, atoms.get_potential_energy()))
Exemplo n.º 29
0
def clone(self, newdir, extra_files=None):
    """Copy a vasp directory to a new directory.

    Does not overwrite existing files. newdir is relative to the the
    directory the calculator was created from, not the current working
    directory, unless an absolute path is used.

    what to do about METADATA, the uuid will be wrong!

    """
    if extra_files is None:
        extra_files = []

    if os.path.isabs(newdir):
        newdirpath = newdir
    else:
        newdirpath = os.path.join(self.cwd, newdir)

    import shutil
    if not os.path.isdir(newdirpath):
        os.makedirs(newdirpath)
    for vf in vaspfiles+extra_files:

        if (not os.path.exists(os.path.join(newdirpath, vf))
            and os.path.exists(vf)):
            shutil.copy(vf, newdirpath)

    # if we are an neb calculation we need to copy the image
    # directories
    if hasattr(self, 'neb'):
        import glob
        for imagedir in glob.glob('0[0-9]'):
            dst = os.path.join(newdirpath, imagedir)
            if not os.path.exists(dst):
                shutil.copytree(imagedir, dst)

    # update metadata. remember we are in the vaspdir
    d = {}
    d['uuid'] = str(uuid.uuid1())
    d['cloned on'] = time.ctime(time.time())

    os.chdir(self.cwd)

    from jasp import jasp
    with jasp(newdir) as calc:
        if hasattr(calc, 'metadata'):
            calc.metadata.update(d)
            calc.write_metadata()

    os.chdir(self.vaspdir)
Exemplo n.º 30
0
def clone(self, newdir, extra_files=None):
    """Copy a vasp directory to a new directory.

    Does not overwrite existing files. newdir is relative to the the
    directory the calculator was created from, not the current working
    directory, unless an absolute path is used.

    what to do about METADATA, the uuid will be wrong!

    """
    if extra_files is None:
        extra_files = []

    if os.path.isabs(newdir):
        newdirpath = newdir
    else:
        newdirpath = os.path.join(self.cwd, newdir)

    import shutil
    if not os.path.isdir(newdirpath):
        os.makedirs(newdirpath)
    for vf in vaspfiles + extra_files:

        if (not os.path.exists(os.path.join(newdirpath, vf))
                and os.path.exists(vf)):
            shutil.copy(vf, newdirpath)

    # if we are an neb calculation we need to copy the image
    # directories
    if hasattr(self, 'neb'):
        import glob
        for imagedir in glob.glob('0[0-9]'):
            dst = os.path.join(newdirpath, imagedir)
            if not os.path.exists(dst):
                shutil.copytree(imagedir, dst)

    # update metadata. remember we are in the vaspdir
    d = {}
    d['uuid'] = str(uuid.uuid1())
    d['cloned on'] = time.ctime(time.time())

    os.chdir(self.cwd)

    from jasp import jasp
    with jasp(newdir) as calc:
        if hasattr(calc, 'metadata'):
            calc.metadata.update(d)
            calc.write_metadata()

    os.chdir(self.vaspdir)
Exemplo n.º 31
0
    def jaspfunc(self, path, action):
        ''' evaluate the action at path'''
        if (not (action.startswith('atoms.')
                or action.startswith('calc.')
                or action.startswith('file:'))
            or (';' in action)):

                resp = Response(body='invalid action',
                                  content_type='text/plain')
                return resp
        elif ';' in action:
            pass

        print 'action = %s' % action

        if action.startswith('file:'):
            print 'running file:'
            try:
                f = action[5:]
                CWD = os.getcwd()
                os.chdir(ROOT)

                if os.path.exists(os.path.join(path,f)):
                    with open(os.path.join(path,f)) as fi:
                        contents = fi.readlines()
                        if f == 'POTCAR':
                            contents = contents[0]
                        else:
                            contents = ''.join(contents)
                else:
                    contents = 'No file {0} found in {1}'.format(f,os.getcwd())

                resp = Response(body=contents,
                                content_type='text/plain')
                return resp
            finally:
                print 'changing back'
                os.chdir(CWD)

        print 'running %s after file: code' % action
        dir = os.path.join(ROOT, path)
        if os.path.exists(dir):
            with jasp(dir) as calc:
                atoms = calc.get_atoms()
                val = eval(action)
                resp = Response(body='{0}'.format(val),
                                content_type='text/plain')
                return resp
        pass
Exemplo n.º 32
0
def run(sigma, atoms):
    with jasp('molecules/co-relax/sigma{0}'.format(sigma),
          xc='PBE',
          encut=400,
          kpts=[3, 3, 1],
          ismear=0,
          sigma=sigma, # this is small for a molecule
          ibrion=2,   # conjugate gradient optimizer
          nsw=100,      # do at least 5 steps to relax
          ediff=1e-5,   # set precise energies
          atoms=atoms) as calc:
        e = atoms.get_potential_energy()
        pos = atoms.get_positions()
        d = ((pos[0] - pos[1])**2).sum()**0.5
        print('{0:1.2f}  {1:1.4f}  {2:1.4f}'.format(sigma, e, d))
def run(job, atoms):
  with jasp('surfaces/al2o3-0001-al-ter-pt1-2co/relax/{0}'.format(job),
        xc='PBE',
        kpts=[3, 3, 1],
        gamma=True,
        encut=400,
        ismear=0,
        ibrion=2,
        lreal='auto',
        prec='accurate',
        algo='fast',
        nelm=100,
        nsw=200,
        atoms=atoms) as calc:
      print("{0}    {1}".format(job, atoms.get_potential_energy()))
Exemplo n.º 34
0
def test():
    a = 2.87
    a1 = np.array((-a/2, a/2, a/2))
    a2 = np.array((a/2, -a/2, a/2))
    a3 = np.array((a/2, a/2, -a/2))
    bulk = Atoms([Atom('Fe', (0, 0, 0), magmom=5)],
                 cell=(a1, a2, a3))
    with jasp('Fe-bcc-U', atoms=bulk,
              debug=logging.DEBUG,
              xc='PBE',
              kpts=(8, 8, 8),
              ispin=2, lorbit=11,
              ldau = True,
              ldau_luj={'Fe': {'L':2, 'U':2, 'J':0}},
              lwave=False) as calc:

        assert not calc.calculation_required(calc.get_atoms(),['energy'])
Exemplo n.º 35
0
    def jaspfunc(self, path, action):
        ''' evaluate the action at path'''
        if (not (action.startswith('atoms.') or action.startswith('calc.')
                 or action.startswith('file:')) or (';' in action)):

            resp = Response(body='invalid action', content_type='text/plain')
            return resp
        elif ';' in action:
            pass

        print 'action = %s' % action

        if action.startswith('file:'):
            print 'running file:'
            try:
                f = action[5:]
                CWD = os.getcwd()
                os.chdir(ROOT)

                if os.path.exists(os.path.join(path, f)):
                    with open(os.path.join(path, f)) as fi:
                        contents = fi.readlines()
                        if f == 'POTCAR':
                            contents = contents[0]
                        else:
                            contents = ''.join(contents)
                else:
                    contents = 'No file {0} found in {1}'.format(
                        f, os.getcwd())

                resp = Response(body=contents, content_type='text/plain')
                return resp
            finally:
                print 'changing back'
                os.chdir(CWD)

        print 'running %s after file: code' % action
        dir = os.path.join(ROOT, path)
        if os.path.exists(dir):
            with jasp(dir) as calc:
                atoms = calc.get_atoms()
                val = eval(action)
                resp = Response(body='{0}'.format(val),
                                content_type='text/plain')
                return resp
        pass
Exemplo n.º 36
0
def test():
    atoms = BodyCenteredCubic(directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]],
                              size=(1, 1, 1),
                              symbol='Fe')

    for k in [2, 3, 4]:
        with jasp('kpt-loop',
                  xc='PBE',
                  encut=300,
                  kpts=(k, k, k),
                  ispin=2,
                  atoms=atoms) as calc:
            calc.prepare_input_files()

            with open('KPOINTS') as f:
                lines = f.readlines()

            assert lines[3] == '{0} {0} {0}\n'.format(k)
Exemplo n.º 37
0
def run(job, atoms):
  with jasp('cluster/pt-nco/vib/{0}'.format(job),
          xc='PBE',
          encut=400,
          kpts=[3, 3, 3],
          ismear=0,     # Gaussian smearing
          sigma=0.05, # this is small for a molecule
          ibrion=5,     # finite differences
          nfree=2,      # central differences (default)
          potim=0.015,  # default as well
          ediff=1e-7,   # for vibrations you need precise energies
          nsw=1,        # Set to 1 for vibrational calculation
          atoms=atoms) as calc:
    e = atoms.get_potential_energy()
    # vibrational energies are in eV
    f, m = calc.get_vibrational_modes(0)
    c = 3e10  # cm/s
    h = 4.135667516e-15  # eV*s
    print('{0}    {1}'.format(job, f / (h * c)))
Exemplo n.º 38
0
def test():
    atoms = BodyCenteredCubic(directions=[[1,0,0],
                                          [0,1,0],
                                          [0,0,1]],
                              size=(1,1,1),
                              symbol='Fe')

    for k in [2, 3, 4]:
        with jasp('kpt-loop',
                  xc='PBE',
                  encut=300,
                  kpts=(k,k,k),
                  ispin=2,
                  atoms=atoms) as calc:
            calc.prepare_input_files()

            with open('KPOINTS') as f:
                lines = f.readlines()

            assert lines[3]== '{0} {0} {0}\n'.format(k)
def run(job, atoms):
  with jasp('surfaces/al2o3-0001-al-ter-pt1-co-vib/{0}'.format(job),
        xc='PBE',
        kpts=[3, 3, 1],
        gamma=True,
        encut=400,
        ismear=0,
        ibrion=5,  # finite differences with symmetry
        nfree=2,  # central differences (default)
        potim=0.015,  # default as well
        ediff=1e-8,
        lreal='auto',
        prec='accurate',
        algo='fast',
        nelm=100,
        nsw=1,
        atoms=atoms) as calc:
      e = atoms.get_potential_energy()
      f, m = calc.get_vibrational_modes(0)
      #allfreq = calc.get_vibrational_modes()[0]
      print("{0}       {1}       {2}      {3} ".format(job, e, f, f / (h * c)))
Exemplo n.º 40
0
def run(sigma, atoms):
  with jasp('molecules/co-vib/sigma{0}'.format(sigma),
          xc='PBE',
          encut=400,
          kpts=[5, 5, 5],
          ismear=0,     # Gaussian smearing
          sigma=sigma, # this is small for a molecule
          ibrion=5,     # finite differences
          nfree=2,      # central differences (default)
          potim=0.015,  # default as well
          ediff=1e-7,   # for vibrations you need precise energies
          nsw=1,        # Set to 1 for vibrational calculation
          atoms=atoms) as calc:
    e = atoms.get_potential_energy()
    pos = atoms.get_positions()
    d = ((pos[0] - pos[1])**2).sum()**0.5
    # vibrational energies are in eV
    f, m = calc.get_vibrational_modes(0)
    c = 3e10  # cm/s
    h = 4.135667516e-15  # eV*s
    print('{0}    {1}     {2}'.format(sigma, d, f / (h * c)))
Exemplo n.º 41
0
def test():
    '''This test copies an old calculation to a new calculation and makes
    sure that rereading results in a state that does not need a new
    calculation.
    '''
    a = 2.87
    a1 = np.array((-a/2, a/2, a/2))
    a2 = np.array((a/2, -a/2, a/2))
    a3 = np.array((a/2, a/2, -a/2))
    bulk = Atoms([Atom('Fe', (0, 0, 0), magmom=5)],
                 cell=(a1, a2, a3))
    os.chdir(os.path.join(jaspdir, 'tests'))
    with jasp('Fe-bcc-U', atoms=bulk,
              debug=logging.DEBUG,
              xc='PBE',
              kpts=(8, 8, 8),
              ispin=2, lorbit=11,
              ldau = True,
              ldau_luj={'Fe': {'L': 2, 'U': 2, 'J': 0}},
              lwave=False) as calc:
        # no calculation should be required here.
        assert not calc.calculation_required(calc.get_atoms(), ['energy'])
Exemplo n.º 42
0
    def jaspsum(self, path, format='text'):
        'prints jaspsum to the browser, format can be text, xml, json, python'

        dir = os.path.join(ROOT, path)
        if os.path.exists(dir):
            with jasp(dir) as calc:

                if format == 'json':
                    body = calc.json
                elif format == 'xml':
                    body = calc.xml
                elif format == 'python':
                    body = repr(calc)
                else:
                    body = str(calc)

                resp = Response(body=body, content_type='text/plain')
                return resp
        else:
            resp = Response(body='{0} not found'.format(path),
                            content_type='text/plain')
            return resp
Exemplo n.º 43
0
def analyze_eos(plot=False):
    '''make plot of EOS

    This may trigger calculations to be submitted to the queue. You should not run this function before the directories for the EOS are setup.

    must be called from within an atat directory'''
    if not os.path.isdir('eos-exp'):
        return None

    CWD = os.getcwd()
    head, wd = os.path.split(CWD)

    V,E = [],[]

    os.chdir('eos-exp')
    for d in os.listdir('.'):
        if (os.path.exists('%s/energy' % d)
            and not os.path.exists('%s/error' % d)):
            #print os.getcwd()+'/'+d
            with jasp(d) as calc:
                atoms = calc.get_atoms()
                V.append(atoms.get_volume())
                E.append(atoms.get_potential_energy())
    os.chdir(CWD)

    if (len(V) < 5 or len(E) < 5):
        return None

    eos = EquationOfState(V, E)

    try:
        v0, e0, B = eos.fit()
        CWD = os.getcwd()
        base,d = os.path.split(CWD)
        #print '| %s | %1.3f | %1.1f |' % (d, v0/len(atoms), B/GPa)
    except ValueError, e:
        print e
        return
Exemplo n.º 44
0
def analyze_eos(plot=False):
    '''make plot of EOS

    This may trigger calculations to be submitted to the queue. You should not run this function before the directories for the EOS are setup.

    must be called from within an atat directory'''
    if not os.path.isdir('eos-exp'):
        return None

    CWD = os.getcwd()
    head, wd = os.path.split(CWD)

    V, E = [], []

    os.chdir('eos-exp')
    for d in os.listdir('.'):
        if (os.path.exists('%s/energy' % d)
                and not os.path.exists('%s/error' % d)):
            #print os.getcwd()+'/'+d
            with jasp(d) as calc:
                atoms = calc.get_atoms()
                V.append(atoms.get_volume())
                E.append(atoms.get_potential_energy())
    os.chdir(CWD)

    if (len(V) < 5 or len(E) < 5):
        return None

    eos = EquationOfState(V, E)

    try:
        v0, e0, B = eos.fit()
        CWD = os.getcwd()
        base, d = os.path.split(CWD)
        #print '| %s | %1.3f | %1.1f |' % (d, v0/len(atoms), B/GPa)
    except ValueError, e:
        print e
        return
Exemplo n.º 45
0
def call_jasp(atoms, kp, calcdir, spin, nsteps, qe, cluster):

    JASPRC['queue.nodes'] = q_dict[qe][0]
    JASPRC['queue.ppn'] = q_dict[qe][1]
    JASPRC['queue.cluster'] = q_dict[qe][2]

    with jasp(calcdir,
              xc='PBE',
              kpts=[kp, kp, 1],
              encut=350,
              nsw=nsteps,
              ibrion=2,
              lwave=False,
              lcharg=False,
              ispin=spin,
              idipol=3,
              ediff=1e-05,
              ediffg=-0.05,
              atoms=atoms) as calc:
        try:
            return atoms.get_potential_energy()
        except (VaspSubmitted, VaspQueued):
            print "Submitted to queue"
Exemplo n.º 46
0
def test_ldauj():

    atoms = BodyCenteredCubic(directions=[[-1, 1, 1], [1, -1, 1], [1, 1, -1]],
                              size=(2, 2, 2),
                              symbol='Fe')

    with jasp('Fe-base',
              xc='PBE',
              sigma=0.1,
              kpts=(4, 4, 4),
              nbands=44,
              setups={'0': 'Fe'},
              ldau=True,
              ldautype=3,
              ldaul=[2, -1],
              ldauu=[0, 0],
              ldauj=[0, 0],
              ldauprint=2,
              lmaxmix=4,
              lorbit=11,
              debug=logging.DEBUG,
              atoms=atoms) as calc:
        assert not calc.calculation_required(calc.get_atoms(), ['energy'])
Exemplo n.º 47
0
    def jaspsum(self, path, format='text'):
        'prints jaspsum to the browser, format can be text, xml, json, python'

        dir = os.path.join(ROOT, path)
        if os.path.exists(dir):
            with jasp(dir) as calc:

                if format == 'json':
                    body = calc.json
                elif format == 'xml':
                    body = calc.xml
                elif format == 'python':
                    body = repr(calc)
                else:
                    body = str(calc)

                resp = Response(body=body,
                                content_type='text/plain')
                return resp
        else:
            resp = Response(body='{0} not found'.format(path),
                            content_type='text/plain')
            return resp
Exemplo n.º 48
0
from jasp import *
from ase import Atom, Atoms
atoms = Atoms([Atom('Cu',  [0.000, 0.000, 0.000])],
              cell= [[1.818, 0.000, 1.818],
                     [1.818, 1.818, 0.000],
                     [0.000, 1.818, 1.818]])
with jasp('bulk/alloy/cu',
          xc='PBE',
          encut=350,
          kpts=(13, 13, 13),
          nbands=9,
          ibrion=2,
          isif=4,
          nsw=10,
          atoms=atoms) as calc:
    print calc.get_valence_electrons()
Exemplo n.º 49
0
# Benzene on the slab
from jasp import *
from ase.lattice.surface import fcc111, add_adsorbate
from ase.structure import molecule
from ase.constraints import FixAtoms
atoms = fcc111('Au', size=(3,3,3), vacuum=10)
benzene = molecule('C6H6')
benzene.translate(-benzene.get_center_of_mass())
# I want the benzene centered on the position in the middle of atoms
# 20, 22, 23 and 25
p = (atoms.positions[20] +
     atoms.positions[22] +
     atoms.positions[23] +
     atoms.positions[25])/4.0 + [0.0, 0.0, 3.05]
benzene.translate(p)
atoms += benzene
# now we constrain the slab
c = FixAtoms(mask=[atom.symbol=='Au' for atom in atoms])
atoms.set_constraint(c)
#from ase.visualize import view; view(atoms)
with jasp('surfaces/Au-benzene-pbe',
          xc='PBE',
          encut=350,
          kpts=(4,4,1),
          ibrion=1,
          nsw=100,
          atoms=atoms) as calc:
    print atoms.get_potential_energy()
Exemplo n.º 50
0
            atom_data['fx'] = None
            atom_data['fy'] = None
            atom_data['fz'] = None

        db.execute(
            '''
insert into CONTCAR (vasp_id,
                    atom_index,
                    chemical_symbol,
                    tag,
                    x,y,z,
                    fx,fy,fz,
                    potential)
values (:vasp_id,
        :atom_index,
        :chemical_symbol,
        :tag,
        :x,:y,:z,
        :fx,:fy,:fz,
        :potential)''', atom_data)


if __name__ == '__main__':

    connection = apsw.Connection(DB)
    cursor = connection.cursor()

    from jasp import *
    with jasp('tests/O2-relax') as calc:
        insert_database_entry(calc)
Exemplo n.º 51
0
from jasp import *
with jasp('bulk/alloy/cu') as calc:
    print calc.xml
Exemplo n.º 52
0
# fit cubic polynomials to E(V) for rutile and anatase
from jasp import *
import matplotlib.pyplot as plt
import numpy as np

np.set_printoptions(precision=2)
# anatase equation of state
volumes = [30., 33., 35., 37., 39.]  # vol of one TiO2 formula unit
a_volumes, a_energies = [], []
for v in volumes:
    with jasp('bulk/TiO2/anatase/anatase-{0}'.format(v)) as calc:
        atoms = calc.get_atoms()
        nTiO2 = len(atoms) / 3.0
        a_volumes.append(atoms.get_volume() / nTiO2)
        a_energies.append(atoms.get_potential_energy() / nTiO2)
# rutile equation of state
volumes = [28., 30., 32., 34., 36.]  # vol of one TiO2
r_volumes, r_energies = [], []
for v in volumes:
    with jasp('bulk/TiO2/rutile/rutile-{0}'.format(v)) as calc:
        atoms = calc.get_atoms()
        nTiO2 = len(atoms) / 3.0
        r_volumes.append(atoms.get_volume() / nTiO2)
        r_energies.append(atoms.get_potential_energy() / nTiO2)
# cubic polynomial fit to equation of state E(V) = pars*[V^3 V^2 V^1 V^0]
apars = np.polyfit(a_volumes, a_energies, 3)
rpars = np.polyfit(r_volumes, r_energies, 3)
print 'E_anatase(V) = {0:1.2f}*V^3 + {1:1.2f}*V^2 + {2:1.2f}*V + {3:1.2f}'.format(
    *apars)
print 'E_rutile(V) =  {0:1.2f}*V^3 + {1:1.2f}*V^2 + {2:1.2f}*V + {3:1.2f}'.format(
    *rpars)
Exemplo n.º 53
0
# calculate O atom energy in orthorhombic boxes
from jasp import *
from ase import Atom, Atoms
# orthorhombic box origin
atoms = Atoms([Atom('O', [0, 0, 0], magmom=2)], cell=(8, 9, 10))
with jasp('molecules/O-orthorhombic-box-origin',
          xc='PBE',
          encut=400,
          ismear=0,
          sigma=0.01,
          ispin=2,
          atoms=atoms) as calc:
    try:
        print('Orthorhombic box (origin): E = {0} eV'.format(
            atoms.get_potential_energy()))
    except (VaspSubmitted, VaspQueued):
        pass
# orthrhombic box center
atoms = Atoms([Atom('O', [4, 4.5, 5], magmom=2)], cell=(8, 9, 10))
with jasp('molecules/O-orthorhombic-box-center',
          xc='PBE',
          encut=400,
          ismear=0,
          sigma=0.01,
          ispin=2,
          atoms=atoms) as calc:
    try:
        print('Orthorhombic box (center): E = {0} eV'.format(
            atoms.get_potential_energy()))
    except (VaspSubmitted, VaspQueued):
        pass
Exemplo n.º 54
0
from jasp import *
with jasp('molecules/CO-vacuum') as calc:
    calc.clone('molecules/CO-solvated')
with jasp(
        'molecules/CO-solvated',
        istart=1,  #
        lsol=True) as calc:
    print(calc.get_atoms().get_potential_energy())
    print(calc.get_atoms().get_forces())
    print('Calculation time: {} seconds'.format(calc.get_elapsed_time()))
Exemplo n.º 55
0
from ase import Atoms, Atom
from jasp import *
import numpy as np
np.set_printoptions(precision=3, suppress=True)
atoms = Atoms([Atom('C', [0, 0, 0]), Atom('O', [1.2, 0, 0])], cell=(6, 6, 6))
atoms.center()
ENCUTS = [250, 300, 350, 400, 450, 500]
energies = []
ready = True
for en in ENCUTS:
    with jasp('molecules/co-en-{0}'.format(en),
              encut=en,
              xc='PBE',
              atoms=atoms) as calc:
        try:
            energies.append(atoms.get_potential_energy())
        except (VaspSubmitted, VaspQueued):
            ready = False
if not ready:
    import sys
    sys.exit()
import matplotlib.pyplot as plt
plt.plot(ENCUTS, energies, 'bo-')
plt.xlabel('ENCUT (eV)')
plt.ylabel('Total energy (eV)')
plt.savefig('images/co-encut-v.png')
Exemplo n.º 56
0
from jasp import *
with jasp('molecules/h2o_vib_dfpt') as calc:
    print 'mode  Relative intensity'
    for i, intensity in enumerate(calc.get_infrared_intensities()):
        print '{0:02d}     {1:1.3f}'.format(i, intensity)
Exemplo n.º 57
0
from ase.structure import molecule
from jasp import *
# first we define our molecules. These will automatically be at the coordinates from the G2 database.
CO = molecule('CO')
CO.set_cell([8, 8, 8], scale_atoms=False)
H2O = molecule('H2O')
H2O.set_cell([8, 8, 8], scale_atoms=False)
CO2 = molecule('CO2')
CO2.set_cell([8, 8, 8], scale_atoms=False)
H2 = molecule('H2')
H2.set_cell([8, 8, 8], scale_atoms=False)
# now the calculators to get the energies
with jasp('molecules/wgs/CO',
          xc='PBE',
          encut=350,
          ismear=0,
          ibrion=2,
          nsw=10,
          atoms=CO) as calc:
    try:
        eCO = CO.get_potential_energy()
    except (VaspSubmitted, VaspQueued):
        eCO = None
with jasp('molecules/wgs/CO2',
          xc='PBE',
          encut=350,
          ismear=0,
          ibrion=2,
          nsw=10,
          atoms=CO2) as calc:
    try: