コード例 #1
0
ファイル: operators.py プロジェクト: mdavezac/LaDa
def mix_poscars(s1,s2, roll=True):
  """ Crossover operations where atoms are from one and cell from other.

      Mating operation on two parent structures s1 and s2.
      Done on scaled atomic positions (cubic systems) by
      interchanging their cells and scaled positions.
      Returns two offspring structures each with the same 
      number of atoms as the parent from which the atoms 
      are inhereted.
  """
  from random import choice
  from numpy import dot
  from numpy.linalg import det
  from ..crystal import Structure

  # swap structures randomly.
  if choice([True, False]): s1, s2 = s2, s1

  # chem. symbols and scaled positions of the two parents
  sc_pos2 = zip([atom.type for atom in s2],fractional_pos(s2, roll))

  # cell from s1
  result = Structure(s1.cell, scal=s1.scale)

  # atoms from s2
  for type, pos in sc_pos2:
    result.add_atom(*dot(result.cell, pos), type=type)

  result.scale =  s1.scale * (float(len(result)) / float(len(s1)))**(1./3.)
  return result
コード例 #2
0
ファイル: operators.py プロジェクト: mdavezac/LaDa
def mix_atoms(s1, s2, roll=True):
  """ Randomly mix cell and atoms from parents.

      Mating operation on two parent structures s1 and s2.
      Done by mixing randomly atoms from s1 and s2 into the 
      cell coming from one of them. Returns two offspring 
      structures.
  """
  from random import choice
  from itertools import chain
  from numpy.linalg import det
  from numpy import dot, abs
  from ..crystal import Structure

  # swap structures randomly.
  if choice([True, False]): s1, s2 = s2, s1

  # chem. symbols and scaled positions of the two parents
  sc_pos1 = zip([atom.type for atom in s1], fractional_pos(s1, roll))
  sc_pos2 = zip([atom.type for atom in s2], fractional_pos(s2, roll))

  result = Structure(s1.cell)

  for pos, type in chain(sc_pos1, sc_pos2):
    if choice([True, False]):
      result.add_atom(*dot(result.cell, pot), type=type)

  result.scale =  s1.scale * (float(len(result)) / float(len(s1)))**(1./3.)

  return result
コード例 #3
0
def icsd_cif_b(filename):
    from os.path import basename
    from numpy import dot, transpose
    from pylada.crystal import Structure, primitive
    from . import readCif

    rdr = readCif.CifReader(0, filename)    # buglevel = 0
    vaspMap = rdr.getVaspMap()
    cellBasis = vaspMap['cellBasis']

    structure = Structure(
        transpose(cellBasis),
        scale=1,
        name=basename(filename))

    usyms = vaspMap['uniqueSyms']
    posVecs = vaspMap['posVecs']

    # multiplicities = num atoms of each type.
    mults = [len(x) for x in posVecs]

    # For each unique type of atom ...
    for ii in range(len(usyms)):
        # For each atom of that type ...
        for jj in range(mults[ii]):
            atpos = dot(transpose(cellBasis), posVecs[ii][jj])
            structure.add_atom(atpos[0], atpos[1], atpos[2], usyms[ii])


    prim = primitive(structure)
    logger.info("  crystal/read: icsd_cif_b: structure: %s" % structure)

    return prim
コード例 #4
0
def get_madelungenergy(latt_vec_array, charge, epsilon, cutoff):
    """ Function returns leading first order correction term, i.e.,
        screened Madelung-like lattice energy of point charge
    Reference: M. Leslie and M. J. Gillan, J. Phys. C: Solid State Phys. 18 (1985) 973

    Parameters
        defect = pylada.vasp.Extract object
        charge = charge of point defect. Default 1e0 elementary charge
        epsilon = dimensionless relative permittivity, SKW: isotropic average of dielectric constant
        cutoff = Ewald cutoff parameter

    Returns
        Madelung (electrostatic) energy in eV                                                                                                                

    Note:
        1. Units in this function are either handled by the module Quantities, or\
        defaults to Angstrom and elementary charges
        2. Function is adopted from Haowei Peng's version in pylada.defects modules
    """

    ewald_cutoff = cutoff * Ry

    cell_scale = 1.0  # SKW: In notebook workflow cell parameters are converted to Cartesians and units of Angstroms
    # SKW: Create point charge in pylada.crystal.structure class (used for charge model)
    # http://pylada.github.io/pylada/userguide/crystal.html
    struc = Structure()
    struc.cell = latt_vec_array
    struc.scale = cell_scale
    struc.add_atom(0., 0., 0., "P", charge=charge)

    #Anuj_05/22/18: added "cutoff" in ewald syntax
    result = ewald(struc, cutoff=ewald_cutoff).energy / epsilon
    return -1 * result.rescale(eV)
コード例 #5
0
def from_spglib(strc):
    """
    converting the pylada structure object
    from the spglib format to pylada
    """

    import numpy as np
    from pylada import periodic_table
    from pylada.crystal import Structure

    out_s = Structure()
    out_s.scale = 1.

    cell      = strc[0]
    positions = strc[1]
    symbols   = strc[2]

    out_s.cell = np.transpose(cell)

    for ii in range(len(positions)):
        pp=np.dot(np.transpose(cell),positions[ii])
        ss=periodic_table.symbols[symbols[ii]-1]
        out_s.add_atom(pp[0],pp[1],pp[2],ss)

    return out_s
コード例 #6
0
ファイル: read.py プロジェクト: pylada/pylada-light
def icsd_cif_b(filename):
    from os.path import basename
    from numpy import dot, transpose
    from pylada.crystal import Structure, primitive
    from . import readCif

    rdr = readCif.CifReader(0, filename)    # buglevel = 0
    vaspMap = rdr.getVaspMap()
    cellBasis = vaspMap['cellBasis']

    structure = Structure(
        transpose(cellBasis),
        scale=1,
        name=basename(filename))

    usyms = vaspMap['uniqueSyms']
    posVecs = vaspMap['posVecs']

    # multiplicities = num atoms of each type.
    mults = [len(x) for x in posVecs]

    # For each unique type of atom ...
    for ii in range(len(usyms)):
        # For each atom of that type ...
        for jj in range(mults[ii]):
            atpos = dot(transpose(cellBasis), posVecs[ii][jj])
            structure.add_atom(atpos[0], atpos[1], atpos[2], usyms[ii])


    prim = primitive(structure)
    logger.info("  crystal/read: icsd_cif_b: structure: %s" % structure)

    return prim
コード例 #7
0
ファイル: read.py プロジェクト: hbwzhsh/pylada-light
def crystal(file='fort.34'):
  """ Reads CRYSTAL's external format. """
  from numpy import array, abs, zeros, any, dot
  from numpy.linalg import inv
  from ..crystal import which_site
  from ..misc import RelativePath
  from ..error import IOError
  from ..periodic_table import find as find_specie
  from . import Structure

  if isinstance(file, str):
    if file.find('\n') == -1:
      with open(RelativePath(file).path, 'r') as file: return crystal(file)
    else: file = file.splitlines().__iter__()
  # read first line
  try: line = file.next()
  except StopIteration: raise IOError('Premature end of stream.')
  else: dimensionality, centering, type = [int(u) for u in line.split()[:3]]
  # read cell
  try: cell = array( [file.next().split()[:3] for i in xrange(3)],
                     dtype='float64' ).T
  except StopIteration: raise IOError('Premature end of stream.')
  result = Structure( cell=cell, centering=centering,
                      dimensionality=dimensionality, type=type, scale=1e0 )
  # read symmetry operators
  result.spacegroup = []
  try: N = int(file.next())
  except StopIteration: raise IOError('Premature end of stream.')
  for i in xrange(N):
    try: op = array( [file.next().split()[:3] for j in xrange(4)],
                     dtype='float64' )
    except StopIteration: raise IOError('Premature end of stream.')
    else: op[:3] = op[:3].copy().T
    result.spacegroup.append(op)
  result.spacegroup = array(result.spacegroup)

  # read atoms.
  try: N = int(file.next())
  except StopIteration: raise IOError('Premature end of stream.')

  for i in xrange(N):
    try: line = file.next().split()
    except StopIteration: raise IOError('Premature end of stream.')
    else: type, pos = int(line[0]), array(line[1:4], dtype='float64')
    if type < 100: type = find_specie(atomic_number=type).symbol
    result.add_atom(pos=pos, type=type, asymmetric=True)

  # Adds symmetrically equivalent structures.
  identity = zeros((4, 3), dtype='float64')
  for i in xrange(3): identity[i, i] == 1
  symops = [u for u in result.spacegroup if any(abs(u - identity) > 1e-8)]
  invcell = inv(result.cell)
  for atom in [u for u in result]:
    for op in symops:
      pos = dot(op[:3], atom.pos) + op[3]
      if which_site(pos, result, invcell=invcell) == -1:
        result.add_atom(pos=pos, type=atom.type, asymmetric=False)

  return result
コード例 #8
0
ファイル: read.py プロジェクト: hbwzhsh/pylada-light
def icsd_cif_b( filename):
  from os.path import basename
  from numpy import dot, transpose
  from pylada.crystal import Structure, primitive
  from pylada.misc import bugLev
  from . import readCif

  rdr = readCif.CifReader( 0, filename)    # buglevel = 0
  vaspMap = rdr.getVaspMap()
  cellBasis = vaspMap['cellBasis']

  structure = Structure(
    transpose( cellBasis),
    scale = 1,
    name = basename( filename))

  usyms = vaspMap['uniqueSyms']
  posVecs = vaspMap['posVecs']

  # multiplicities = num atoms of each type.
  mults = [len(x) for x in posVecs]
  if bugLev >= 5:
    print "    crystal/read: len(usyms): %d  usyms: %s" \
      % (len( usyms), usyms,)
    print "    crystal/read: len(posVecs): %d" % (len(posVecs),)
    print "    crystal/read: len(mults):   %d  mults:   %s" \
      % (len( mults), mults,)

  # For each unique type of atom ...
  for ii in range( len( usyms)):
    if bugLev >= 5:
      print "    crystal/read: icsd_cif_b: ii: ", ii, \
        "  usym: ", usyms[ii], \
        "  mult: ", mults[ii], \
        "  posVecs: ", posVecs[ii]
    # crystal/read: i:  0   symbol:  Mo   len position:  2

    # For each atom of that type ...
    for jj in range( mults[ii]):
      atpos = dot( transpose( cellBasis), posVecs[ii][jj])
      if bugLev >= 5:
        print "      jj: ", jj, "  pos: ", posVecs[ii][jj]
        print "        atpos: ", atpos
      #  j:  0   pos:  [0.3333, 0.6666000000000001, 0.25]
      #  atpos:  [  6.32378655e-16   1.81847148e+00   3.07500000e+00]

      structure.add_atom( atpos[0], atpos[1], atpos[2], usyms[ii])

  if bugLev >= 2:
    print "  crystal/read: icsd_cif_b: structure:\n", structure
  
  prim = primitive( structure)
  if bugLev >= 2:
    print "  crystal/read: icsd_cif_b: primitive structure:\n", prim
  
  return prim
コード例 #9
0
ファイル: jobs.py プロジェクト: ftherrien/pythonQE
 def to_pylada(self):
     A = Structure(self.cell)
     if self.unit == "alat":
         for elem in self.atomic_pos:
             for pos in self.atomic_pos[elem]:
                 A.add_atom(pos[0], pos[1], pos[2], elem)
     elif self.unit == "crystal":
         for elem in self.atomic_pos:
             for pos in self.atomic_pos[elem]:
                 pos.dot(self.cell)
                 A.add_atom(pos[0], pos[1], pos[2], elem)
     else:
         raise RuntimeError("Wrong unit must be alat or crystal")
     return A
コード例 #10
0
ファイル: Helpers.py プロジェクト: rtrottie/VTST-Tools
def pmg_to_pyl(pmg : Structure):
    from pylada.crystal import Structure as Pyl_Structure
    from pylada.crystal import Atom
    pyl = Pyl_Structure(np.transpose(pmg.lattice.matrix))
    for i in range(len(pmg)):
        if pmg.site_properties:
            kwargs = {x: pmg.site_properties[x][i] for x in pmg.site_properties}
        else:
            kwargs = {}
        coords = pmg[i].coords
        specie = str(pmg[i].specie)
        pyl_atom = Atom(coords[0], coords[1], coords[2], specie, **kwargs)
        pyl.add_atom(pyl_atom)
    return pyl
コード例 #11
0
def first_order_charge_correction(structure,
                                  charge=None,
                                  epsilon=1e0,
                                  cutoff=20.0,
                                  **kwargs):
    """ First order charge correction of +1 charge in given supercell. 

        Units in this function are either handled by the module Quantities, or
        defaults to Angstroems and elementary charges.

        :Parameters:
          structure : `pylada.crystal.Structure`
            Defect supercell, with cartesian positions in angstrom.
          charge 
            Charge of the point-defect. Defaults to 1e0 elementary charge. If no
            units are attached, expects units of elementary charges.
          epsilon 
            dimensionless relative permittivity.
          cutoff 
            Ewald cutoff parameter.

        :return: Electrostatic energy in eV.
    """
    from quantities import elementary_charge, eV
    from pylada.crystal import Structure
    from pylada.physics import Ry
    from pylada.ewald import ewald

    if charge is None:
        charge = 1
    elif charge == 0:
        return 0e0 * eV
    if hasattr(charge, "units"):
        charge = float(charge.rescale(elementary_charge))

    ewald_cutoff = cutoff * Ry

    struc = Structure()
    struc.cell = structure.cell
    struc.scale = structure.scale
    struc.add_atom(0e0, 0, 0, "A", charge=charge)

    result = ewald(struc, ewald_cutoff).energy / epsilon
    return -result.rescale(eV)
コード例 #12
0
def get_madelungenergy(defect, charge=None, epsilon=1e0, cutoff=100.0):
    """ Function returns leading first order correction term, i.e.,
        screened Madelung-like lattice energy of point charge
    Reference: M. Leslie and M. J. Gillan, J. Phys. C: Solid State Phys. 18 (1985) 973

    Parameters
        defect = pylada.vasp.Extract object
        charge = charge of point defect. Default 1e0 elementary charge
        epsilon = dimensionless relative permittivity
        cutoff = Ewald cutoff parameter

    Returns
        Madelung (electrostatic) energy in eV                                                                                                                

    Note:
        1. Units in this function are either handled by the module Quantities, or\
        defaults to Angstrom and elementary charges
        2. Function is adopted from Haowei Peng's version in pylada.defects modules
    """

    from quantities import elementary_charge, eV
    from pylada.crystal import Structure
    from pylada.physics import Ry
    from pylada.ewald import ewald

    if charge is None: charge = 1
    elif charge == 0: return 0e0 * eV
    if hasattr(charge, "units"):
        charge = float(charge.rescale(elementary_charge))

    ewald_cutoff = cutoff * Ry

    structure = defect.structure

    struc = Structure()
    struc.cell = structure.cell
    struc.scale = structure.scale
    struc.add_atom(0., 0., 0., "P", charge=charge)

    #Anuj_05/22/18: added "cutoff" in ewald syntax
    result = ewald(struc, cutoff=ewald_cutoff).energy / epsilon
    return -1 * result.rescale(eV)
コード例 #13
0
ファイル: __init__.py プロジェクト: pylada/pylada-light
def first_order_charge_correction(structure, charge=None, epsilon=1e0, cutoff=20.0, **kwargs):
    """ First order charge correction of +1 charge in given supercell. 

        Units in this function are either handled by the module Quantities, or
        defaults to Angstroems and elementary charges.

        :Parameters:
          structure : `pylada.crystal.Structure`
            Defect supercell, with cartesian positions in angstrom.
          charge 
            Charge of the point-defect. Defaults to 1e0 elementary charge. If no
            units are attached, expects units of elementary charges.
          epsilon 
            dimensionless relative permittivity.
          cutoff 
            Ewald cutoff parameter.

        :return: Electrostatic energy in eV.
    """
    from quantities import elementary_charge, eV
    from pylada.crystal import Structure
    from pylada.physics import Ry
    from pylada.ewald import ewald

    if charge is None:
        charge = 1
    elif charge == 0:
        return 0e0 * eV
    if hasattr(charge, "units"):
        charge = float(charge.rescale(elementary_charge))

    ewald_cutoff = cutoff * Ry

    struc = Structure()
    struc.cell = structure.cell
    struc.scale = structure.scale
    struc.add_atom(0e0, 0, 0, "A", charge=charge)

    result = ewald(struc, ewald_cutoff).energy / epsilon
    return -result.rescale(eV)
コード例 #14
0
ファイル: operators.py プロジェクト: mdavezac/LaDa
def cut_and_splice(s1, s2, roll=True):
  """ Cut-n-splice GSGO crossover operation

      Mating operation on two parent structures s1 and s2.
      Done on scaled atomic positions (cubic systems) by
      cutting them in half and mixing their upper and 
      lower parts.
  """
  from random import choice, random
  from numpy import dot, abs
  from numpy.linalg import det
  from pylada.crystal import Structure

  # swap structures randomly.
  if choice([True, False]): s1, s2 = s2, s1

  # chem. symbols and scaled positions of the two parents
  sc_pos1 = zip([atom.type for atom in s1],fractional_pos(s1, roll=True))
  sc_pos2 = zip([atom.type for atom in s2],fractional_pos(s2, roll=True))

  result = Structure(s1.cell, scale=s1.scale)

  # choose random positions of split-plane
  xsep = 0.5 - (random() * 0.45 + 0.15)
  # choose direction of split-plane randomly from cell-vectors.
  direction = choice(range(3))

  for type, pos in sc_pos1:
    if pos[direction] >= xsep: result.add_atom(*dot(result.cell, pos), type=type)

  for type, pos in sc_pos2:
    if pos[direction] < xsep: result.add_atom(*dot(result.cell, pos), type=type)

  result.scale =  s1.scale * (float(len(result)) / float(len(s1)))**(1./3.)

  return result
コード例 #15
0
ファイル: test.py プロジェクト: georgeyumnam/pylada
from pylada.physics import a0, Ry
from quantities import angstrom, eV, hartree

clj  = Clj()
""" Point charge + r^12 + r^6 model. """
clj.ewald_cutoff = 80 * Ry

clj.charges["A"] = -1.0
clj.charges["B"] =  1.0

structure = Structure()
structure.set_cell = (1,0,0),\
                     (0,1,0),\
                     (0,0,1)
structure.scale = 50
structure.add_atom = (0,0,0), "A"
structure.add_atom = (a0.rescale(angstrom)/structure.scale,0,0), "B"

print clj.ewald(structure).energy, hartree.rescale(eV)


from pylada.crystal.A2BX4 import b5
from pylada.crystal import fill_structure
from numpy import array
clj.ewald_cutoff = 20 * Ry
lattice = b5()
lattice.sites[4].type='A'
structure = fill_structure(lattice.cell, lattice)
structure.scale = 8.0

clj.charges["A"] =  3.0
コード例 #16
0
ファイル: test_restart.py プロジェクト: hbwzhsh/pylada-light
def test_istruc():
  from collections import namedtuple
  from pickle import loads, dumps
  from os import remove
  from os.path import join, exists
  from shutil import rmtree
  from tempfile import mkdtemp
  from pylada.vasp.files import POSCAR, CONTCAR
  from pylada.vasp import Vasp
  from pylada.crystal import Structure, read, specieset, write
  from pylada.error import ValueError

  structure = Structure([[0, 0.5, 0.5],[0.5, 0, 0.5], [0.5, 0.5, 0]], scale=5.43, name='has a name')\
                       .add_atom(0,0,0, "Si")\
                       .add_atom(0.25,0.25,0.25, "Si")

  Extract = namedtuple("Extract", ['directory', 'success', 'structure'])
  a = Vasp()
  o = a._input['istruc']
  d = {'IStruc': o.__class__}

  directory = mkdtemp()
  try: 
    assert a.istruc == 'auto'
    assert o.output_map(vasp=a, outdir=directory, structure=structure) is None
    assert eval(repr(o), d).value == 'auto'
    assert loads(dumps(o)).value == 'auto'
    assert exists(join(directory, POSCAR))
    remove(join(directory, POSCAR))

    # check reading from outcar but only on success.
    a.restart = Extract(directory, False, structure.copy())
    a.restart.structure[1].pos[0] += 0.02
    assert a.istruc == 'auto'
    assert o.output_map(vasp=a, outdir=directory, structure=structure) is None
    assert exists(join(directory, POSCAR))
    other = read.poscar(join(directory, POSCAR), types=specieset(structure))
    assert abs(other[1].pos[0] - 0.25) < 1e-8
    assert abs(other[1].pos[0] - 0.27) > 1e-8
    # check reading from outcar but only on success.
    a.restart = Extract(directory, True, structure.copy())
    a.restart.structure[1].pos[0] += 0.02
    assert a.istruc == 'auto'
    assert o.output_map(vasp=a, outdir=directory, structure=structure) is None
    assert exists(join(directory, POSCAR))
    other = read.poscar(join(directory, POSCAR), types=specieset(structure))
    assert abs(other[1].pos[0] - 0.25) > 1e-8
    assert abs(other[1].pos[0] - 0.27) < 1e-8

    # Now check CONTCAR
    write.poscar(structure, join(directory, CONTCAR))
    assert a.istruc == 'auto'
    assert o.output_map(vasp=a, outdir=directory, structure=structure) is None
    assert exists(join(directory, POSCAR))
    other = read.poscar(join(directory, POSCAR), types=specieset(structure))
    assert abs(other[1].pos[0] - 0.25) < 1e-8
    assert abs(other[1].pos[0] - 0.27) > 1e-8

    # Check some failure modes.
    write.poscar(structure, join(directory, CONTCAR))
    structure[0].type = 'Ge'
    a.restart = None
    try: o.output_map(vasp=a, outdir=directory, structure=structure)
    except ValueError: pass
    else: raise Exception()
    structure[0].type = 'Si'
    structure.add_atom(0.25,0,0, 'Si')
    try: o.output_map(vasp=a, outdir=directory, structure=structure)
    except ValueError: pass
    else: raise Exception()

  finally: rmtree(directory)
コード例 #17
0
def test_istruc():
    from collections import namedtuple
    from pickle import loads, dumps
    from os import remove
    from os.path import join, exists
    from shutil import rmtree
    from tempfile import mkdtemp
    from pylada.vasp.files import POSCAR, CONTCAR
    from pylada.vasp import Vasp
    from pylada.crystal import Structure, read, specieset, write
    from pylada.error import ValueError

    structure = Structure([[0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]], scale=5.43, name='has a name')\
        .add_atom(0, 0, 0, "Si")\
        .add_atom(0.25, 0.25, 0.25, "Si")

    Extract = namedtuple("Extract", ['directory', 'success', 'structure'])
    a = Vasp()
    o = a._input['istruc']
    d = {'IStruc': o.__class__}

    directory = mkdtemp()
    try:
        assert a.istruc == 'auto'
        assert o.output_map(vasp=a, outdir=directory,
                            structure=structure) is None
        assert eval(repr(o), d).value == 'auto'
        assert loads(dumps(o)).value == 'auto'
        assert exists(join(directory, POSCAR))
        remove(join(directory, POSCAR))

        # check reading from outcar but only on success.
        a.restart = Extract(directory, False, structure.copy())
        a.restart.structure[1].pos[0] += 0.02
        assert a.istruc == 'auto'
        assert o.output_map(vasp=a, outdir=directory,
                            structure=structure) is None
        assert exists(join(directory, POSCAR))
        other = read.poscar(join(directory, POSCAR),
                            types=specieset(structure))
        assert abs(other[1].pos[0] - 0.25) < 1e-8
        assert abs(other[1].pos[0] - 0.27) > 1e-8
        # check reading from outcar but only on success.
        a.restart = Extract(directory, True, structure.copy())
        a.restart.structure[1].pos[0] += 0.02
        assert a.istruc == 'auto'
        assert o.output_map(vasp=a, outdir=directory,
                            structure=structure) is None
        assert exists(join(directory, POSCAR))
        other = read.poscar(join(directory, POSCAR),
                            types=specieset(structure))
        assert abs(other[1].pos[0] - 0.25) > 1e-8
        assert abs(other[1].pos[0] - 0.27) < 1e-8

        # Now check CONTCAR
        write.poscar(structure, join(directory, CONTCAR))
        assert a.istruc == 'auto'
        assert o.output_map(vasp=a, outdir=directory,
                            structure=structure) is None
        assert exists(join(directory, POSCAR))
        other = read.poscar(join(directory, POSCAR),
                            types=specieset(structure))
        assert abs(other[1].pos[0] - 0.25) < 1e-8
        assert abs(other[1].pos[0] - 0.27) > 1e-8

        # Check some failure modes.
        write.poscar(structure, join(directory, CONTCAR))
        structure[0].type = 'Ge'
        a.restart = None
        try:
            o.output_map(vasp=a, outdir=directory, structure=structure)
        except ValueError:
            pass
        else:
            raise Exception()
        structure[0].type = 'Si'
        structure.add_atom(0.25, 0, 0, 'Si')
        try:
            o.output_map(vasp=a, outdir=directory, structure=structure)
        except ValueError:
            pass
        else:
            raise Exception()

    finally:
        rmtree(directory)
コード例 #18
0
def icsd_cif_a(filename):
    """ Reads lattice from the ICSD \*cif files.

        It will not work in the case of other \*cif.
        It is likely to produce wrong output if the site occupations are fractional.
        If the occupation is > 0.5 it will treat it as 1 and
        in the case occupation < 0.5 it will treat it as 0 and
        it will accept all occupation = 0.5 as 1 and create a mess!
    """
    from pylada import logger
    import re
    from os.path import basename
    from numpy.linalg import norm
    from numpy import array, transpose
    from numpy import pi, sin, cos, sqrt, dot

    lines = open(filename, 'r').readlines()
    logger.info("crystal/read: icsd_cif_a: %s" % filename)

    sym_big = 0
    sym_end = 0
    pos_big = 0
    pos_end = 0

    for l in lines:
        x = l.split()
        if len(x) > 0:
                    # CELL
            if x[0] == '_cell_length_a':
                if '(' in x[-1]:
                    index = x[-1].index('(')
                else:
                    index = len(x[-1])
                a = float(x[-1][:index])

            if x[0] == '_cell_length_b':
                if '(' in x[-1]:
                    index = x[-1].index('(')
                else:
                    index = len(x[-1])
                b = float(x[-1][:index])

            if x[0] == '_cell_length_c':
                if '(' in x[-1]:
                    index = x[-1].index('(')
                else:
                    index = len(x[-1])
                c = float(x[-1][:index])

            if x[0] == '_cell_angle_alpha':
                if '(' in x[-1]:
                    index = x[-1].index('(')
                else:
                    index = len(x[-1])
                alpha = float(x[-1][:index])

            if x[0] == '_cell_angle_beta':
                if '(' in x[-1]:
                    index = x[-1].index('(')
                else:
                    index = len(x[-1])
                beta = float(x[-1][:index])

            if x[0] == '_cell_angle_gamma':
                if '(' in x[-1]:
                    index = x[-1].index('(')
                else:
                    index = len(x[-1])
                gamma = float(x[-1][:index])

        # SYMMETRY OPERATIONS

        if len(x) > 0 and x[0] == '_symmetry_equiv_pos_as_xyz':
            sym_big = lines.index(l)

        if len(x) > 0 and x[0] == '_atom_type_symbol':
            sym_end = lines.index(l)

        # WYCKOFF POSITIONS

        if len(x) > 0 and x[0] == '_atom_site_attached_hydrogens':
            pos_big = lines.index(l)

        if len(x) > 0 and x[0] == '_atom_site_B_iso_or_equiv':
            pos_big = lines.index(l)

        if len(x) > 0 and x[0] == '_atom_site_U_iso_or_equiv':
            pos_big = lines.index(l)

        if len(x) > 0 and x[0] == '_atom_site_0_iso_or_equiv':
            pos_big = lines.index(l)

        # if pos_end == 0 and l in ['\n', '\r\n'] and lines.index(l) > pos_big:
        if pos_end == 0 and pos_big > 0 \
                and (l in ['\n', '\r\n'] or l.startswith('#')) \
                and lines.index(l) > pos_big:
            pos_end = lines.index(l)

    # _symmetry_equiv_pos_* lines are like:
    #     1     'x, x-y, -z+1/2'
    logger.debug("crystal/read: icsd_cif_a: sym_big: %s" % sym_big)
    logger.debug("crystal/read: icsd_cif_a: sym_end: %s" % sym_end)

    symm_ops = ['(' + x.split()[1][1:] + x.split()[2] + x.split()[3][:-1] + ')'
                for x in lines[sym_big + 1:sym_end - 1]]
    logger.debug("crystal/read: icsd_cif_a: symm_ops a: %s" % symm_ops)
    # ['(x,x-y,-z+1/2)', '(-x+y,y,-z+1/2)', ...]

    # Insert decimal points after integers
    symm_ops = [re.sub(r'(\d+)', r'\1.', x) for x in symm_ops]
    logger.debug("crystal/read: icsd_cif_a: symm_ops b: %s" % symm_ops)
    # ['(x,x-y,-z+1./2.)', '(-x+y,y,-z+1./2.)', ...]

    # _atom_site_* lines are like:
    #   Mo1 Mo4+ 2 c 0.3333 0.6667 0.25 1. 0
    logger.debug("crystal/read: icsd_cif_a: pos_big: %s" % pos_big)
    logger.debug("crystal/read: icsd_cif_a: pos_end: %s" % pos_end)
    wyckoff = [[x.split()[0], [x.split()[4], x.split()[5], x.split()[6]], x.split()[7]]
               for x in lines[pos_big + 1:pos_end]]
    logger.debug("crystal/read: icsd_cif_a: wyckoff a: %s" % wyckoff)
    # [['Mo1', ['0.3333', '0.6667', '0.25'], '1.'], ['S1', ['0.3333', '0.6667', '0.621(4)'], '1.']]

    wyckoff = [w for w in wyckoff if int(float(w[-1][:4]) + 0.5) != 0]
    logger.debug("crystal/read: icsd_cif_a: wyckoff b: %s" % wyckoff)
    # [['Mo1', ['0.3333', '0.6667', '0.25'], '1.'], ['S1', ['0.3333', '0.6667', '0.621(4)'], '1.']]

    # Setting up a good wyckoff list

    for w in wyckoff:
        # Strip trailing numerals from w[0] == 'Mo1'
        pom = 0
        for i in range(len(w[0])):
            try:
                int(w[0][i])
                if pom == 0:
                    pom = i
            except:
                pass

        w[0] = w[0][:pom]

        # Strip trailing standard uncertainty, if any, from w[1], ..., w[3]
        for i in range(3):
            if '(' in w[1][i]:
                index = w[1][i].index('(')
            else:
                index = len(w[1][i])
            w[1][i] = float(w[1][i][:index])

        # Delete w[4]
        del w[-1]
    ##########################################

    # List of unique symbols ["Mo", "S"]
    symbols = list({w[0] for w in wyckoff})
    logger.debug("crystal/read: icsd_cif_a: symbols: %s" % symbols)

    # List of position vectors for each symbol
    positions = [[] for i in range(len(symbols))]

    for w in wyckoff:
        symbol = w[0]
        x, y, z = w[1][0], w[1][1], w[1][2]
        logger.debug("symbol: %s  x: %s   y: %s  z: %s" % (symbol, x, y, z))
        for i in range(len(symm_ops)):
            # Set pom = new position based on symmetry transform
            pom = list(eval(symm_ops[i]))
            logger.debug("i: %s  pom a: %s" % (i, pom))
            # [0.3333, -0.3334, 0.25]

            # Move positions to range [0,1]:
            for j in range(len(pom)):
                if pom[j] < 0.:
                    pom[j] = pom[j] + 1.
                if pom[j] >= 0.999:
                    pom[j] = pom[j] - 1.
            logger.debug("i: %s   pom b: %s" % (i, pom))
            # [0.3333, 0.6666, 0.25]

            # If pom is not in positions[symbol], append pom
            if not any(norm(array(u) - array(pom)) < 0.01 for u in positions[symbols.index(symbol)]):
                ix = symbols.index(symbol)
                positions[ix].append(pom)
                logger.debug("new positions for %s: %s" % (symbol, repr(positions[ix])))

    ################ CELL ####################

    a1 = a * array([1., 0., 0.])
    a2 = b * array([cos(gamma * pi / 180.), sin(gamma * pi / 180.), 0.])
    c1 = c * cos(beta * pi / 180.)
    c2 = c / sin(gamma * pi / 180.) * (-cos(beta * pi / 180.) *
                                       cos(gamma * pi / 180.) + cos(alpha * pi / 180.))
    a3 = array([c1, c2, sqrt(c**2 - (c1**2 + c2**2))])
    cell = array([a1, a2, a3])
    logger.debug("crystal/read: icsd_cif_a: a1: %s" % a1)
    logger.debug("crystal/read: icsd_cif_a: a2: %s" % a2)
    logger.debug("crystal/read: icsd_cif_a: a3: %s" % a3)
    ##########################################

    from pylada.crystal import Structure, primitive
    logger.debug("crystal/read: icsd_cif_a: cell: %s" % cell)

    structure = Structure(
        transpose(cell),
        scale=1,
        name=basename(filename))

    for i in range(len(symbols)):
        logger.debug("crystal/read: icsd_cif_a: i: %s  symbol: %s  len(position): %i" % (
            i,  symbols[i], len(positions[i])
        ))
        # crystal/read: i:  0   symbol:  Mo   len position:  2

        for j in range(len(positions[i])):
            atpos = dot(transpose(cell), positions[i][j])
            logger.debug("j: %s  pos: %s" % (j, positions[i][j]))
            logger.debug("atpos: " % atpos)
            #  j:  0   pos:  [0.3333, 0.6666000000000001, 0.25]
            #  atpos:  [  6.32378655e-16   1.81847148e+00   3.07500000e+00]

            structure.add_atom(atpos[0], atpos[1], atpos[2], symbols[i])

    logger.info("crystal/read: icsd_cif_a: structure: %s" % structure)

    prim = primitive(structure)
    logger.info("crystal/read: icsd_cif_a: primitive structure: %s" % prim)

    return prim
コード例 #19
0
def crystal(file='fort.34'):
    """ Reads CRYSTAL's external format. """
    from six import next
    from numpy import array, abs, zeros, any, dot
    from numpy.linalg import inv
    from ..crystal import which_site
    from ..misc import RelativePath
    from .. import error
    from ..periodic_table import find as find_specie
    from . import Structure

    if isinstance(file, str):
        if file.find('\n') == -1:
            with open(RelativePath(file).path, 'r') as file:
                return crystal(file)
        else:
            file = file.splitlines().__iter__()
    # read first line
    try:
        line = next(file)
    except StopIteration:
        raise error.IOError('Premature end of stream.')
    else:
        dimensionality, centering, type = [int(u) for u in line.split()[:3]]
    # read cell
    try:
        cell = array([next(file).split()[:3] for i in range(3)],
                     dtype='float64').T
    except StopIteration:
        raise error.IOError('Premature end of stream.')
    result = Structure(cell=cell, centering=centering,
                       dimensionality=dimensionality, type=type, scale=1e0)
    # read symmetry operators
    result.spacegroup = []
    try:
        N = int(next(file))
    except StopIteration:
        raise error.IOError('Premature end of stream.')
    for i in range(N):
        try:
            op = array([next(file).split()[:3] for j in range(4)],
                       dtype='float64')
        except StopIteration:
            raise error.IOError('Premature end of stream.')
        else:
            op[:3] = op[:3].copy().T
        result.spacegroup.append(op)
    result.spacegroup = array(result.spacegroup)

    # read atoms.
    try:
        N = int(next(file))
    except StopIteration:
        raise error.IOError('Premature end of stream.')

    for i in range(N):
        try:
            line = next(file).split()
        except StopIteration:
            raise error.IOError('Premature end of stream.')
        else:
            type, pos = int(line[0]), array(line[1:4], dtype='float64')
        if type < 100:
            type = find_specie(atomic_number=type).symbol
        result.add_atom(pos=pos, type=type, asymmetric=True)

    # Adds symmetrically equivalent structures.
    identity = zeros((4, 3), dtype='float64')
    for i in range(3):
        identity[i, i] == 1
    symops = [u for u in result.spacegroup if any(abs(u - identity) > 1e-8)]
    invcell = inv(result.cell)
    for atom in [u for u in result]:
        for op in symops:
            pos = dot(op[:3], atom.pos) + op[3]
            if which_site(pos, result, invcell=invcell) == -1:
                result.add_atom(pos=pos, type=atom.type, asymmetric=False)

    return result
コード例 #20
0
def poscar(path="POSCAR", types=None):
    """ Tries to read a VASP POSCAR file.

         :param path: Path to the POSCAR file. Can also be an object with
           file-like behavior.
         :type path: str or file object
         :param types: Species in the POSCAR.
         :type types: None or sequence of str

        :return: `pylada.crystal.Structure` instance.
    """
    import re
    from os.path import join, exists, isdir
    from copy import deepcopy
    from numpy import array, dot, transpose
    from numpy.linalg import det
    from quantities import angstrom
    from . import Structure
    from .. import error

    # if types is not none, converts to a list of strings.
    if types is not None:
        if isinstance(types, str):
            types = [types]  # can't see another way of doing this...
        elif not hasattr(types, "__iter__"):
            types = [str(types)]  # single lone vasp.specie.Specie
        else:
            types = [str(s) for s in types]

    if path is None:
        path = "POSCAR"
    if not hasattr(path, 'read'):
        assert exists(path), IOError("Could not find path %s." % (path))
        if isdir(path):
            assert exists(join(path, "POSCAR")), IOError("Could not find POSCAR in %s." % (path))
            path = join(path, "POSCAR")
    result = Structure()
    poscar = path if hasattr(path, "read") else open(path, 'r')

    try:
        # gets name of structure
        result.name = poscar.readline().strip()
        if len(result.name) > 0 and result.name[0] == "#":
            result.name = result.name[1:].strip()
        # reads scale
        scale = float(poscar.readline().split()[0])
        # gets cell vectors.
        cell = []
        for i in range(3):
            line = poscar.readline()
            assert len(line.split()) >= 3,\
                RuntimeError("Could not read column vector from poscar: %s." % (line))
            cell.append([float(f) for f in line.split()[:3]])
        result.cell = transpose(array(cell))
        vol = det(cell)
        if scale < 1.E-8:
            scale = abs(scale / vol) ** (1.0 / 3)
        print(result)
        print(scale)
        result.scale = scale * angstrom
        # checks for vasp 5 input.
        is_vasp_5 = True
        line = poscar.readline().split()
        for i in line:
            if not re.match(r"[A-Z][a-z]?", i):
                is_vasp_5 = False
                break
        if is_vasp_5:
            text_types = deepcopy(line)
            if types is not None and not set(text_types).issubset(set(types)):
                raise error.ValueError("Unknown species in poscar: {0} not in {1}."
                                       .format(text_types, types))
            types = text_types
            line = poscar.readline().split()
        if types is None:
            raise RuntimeError("No atomic species given in POSCAR or input.")
        #  checks/reads for number of each specie
        if len(types) < len(line):
            raise RuntimeError("Too many atomic species in POSCAR.")
        nb_atoms = [int(u) for u in line]
        # Check whether selective dynamics, cartesian, or direct.
        first_char = poscar.readline().strip().lower()[0]
        selective_dynamics = False
        if first_char == 's':
            selective_dynamics = True
            first_char = poscar.readline().strip().lower()[0]
        # Checks whether cartesian or direct.
        is_direct = first_char not in ['c', 'k']
        # reads atoms.
        for n, specie in zip(nb_atoms, types):
            for i in range(n):
                line = poscar.readline().split()
                pos = array([float(u) for u in line[:3]], dtype="float64")
                if is_direct:
                    pos = dot(result.cell, pos)
                result.add_atom(pos=pos, type=specie)
                if selective_dynamics:
                    for which, freeze in zip(line[3:], ['x', 'y', 'z']):
                        if which.lower()[0] == 't':
                            result[-1].freeze = getattr(result[-1], 'freeze', '') + freeze
    finally:
        poscar.close()

    return result
コード例 #21
0
def castep(file):
    """ Tries to read a castep structure file. """
    from numpy import array, dot
    from ..periodic_table import find as find_specie
    from ..misc import RelativePath
    from . import Structure
    from .. import error
    if isinstance(file, str):
        if file.find('\n') == -1:
            with open(RelativePath(file).path, 'r') as file:
                return castep(file)
        else:
            file = file.splitlines()

    file = [l for l in file]

    def parse_input(input):
        """ Retrieves blocks from CASTEP input file. """
        current_block = None
        result = {}
        for line in file:
            if '#' in line:
                line = line[:line.find('#')]
            if current_block is not None:
                if line.split()[0].lower() == '%endblock':
                    current_block = None
                    continue
                result[current_block] += line
            elif len(line.split()) == 0:
                continue
            elif len(line.split()[0]) == 0:
                continue
            elif line.split()[0].lower() == '%block':
                name = line.split()[1].lower().replace('.', '').replace('_', '')
                if name in result:
                    raise error.ValueError('Found two {0} blocks in input.'.format(name))
                result[name] = ""
                current_block = name
            else:
                name = line.split()[0].lower().replace('.', '').replace('_', '')
                if name[-1] in ['=' or ':']:
                    name = name[:-1]
                if name in result:
                    raise error.ValueError('Found two {0} tags in input.'.format(name))
                data = line.split()[1:]
                if len(data) == 0:
                    result[name] = None
                    continue
                if data[0] in [':', '=']:
                    data = data[1:]
                result[name] = ' '.join(data)
        return result

    def parse_units(line):
        from quantities import a0, meter, centimeter, millimeter, angstrom, emass, \
            amu, second, millisecond, microsecond, nanosecond,  \
            picosecond, femtosecond, elementary_charge, coulomb,\
            hartree, eV, meV, Ry, joule, cal, erg, hertz,       \
            megahertz, gigahertz, tera, kelvin, newton, dyne,   \
            h_bar, UnitQuantity, pascal, megapascal, gigapascal,\
            bar, atm, milli, mol

        auv = UnitQuantity('auv', a0 * Ry / h_bar)  # velocity
        units = {'a0': a0, 'bohr': a0, 'm': meter, 'cm': centimeter,
                 'mm': millimeter, 'ang': angstrom, 'me': emass, 'amu': amu,
                 's': second, 'ms': millisecond, 'mus': microsecond,
                 'ns': nanosecond, 'ps': picosecond, 'fs': femtosecond,
                 'e': elementary_charge, 'c': coulomb, 'hartree': hartree,
                 'ha': hartree, 'mha': 1e-3 * hartree, 'ev': eV, 'mev': meV,
                 'ry': Ry, 'mry': 1e-3 * Ry, 'kj': 1e3 * joule, 'mol': mol,
                 'kcal': 1e3 * cal, 'j': joule, 'erg': erg, 'hz': hertz,
                 'mhz': megahertz, 'ghz': gigahertz, 'thz': tera * hertz,
                 'k': kelvin, 'n': newton, 'dyne': dyne, 'auv': auv, 'pa': pascal,
                 'mpa': megapascal, 'gpa': gigapascal, 'atm': atm, 'bar': bar,
                 'atm': atm, 'mbar': milli * bar}
        line = line.replace('cm-1', '1/cm')
        return eval(line, units)

    input = parse_input(file)
    if 'latticecart' in input:
        data = input['latticecart'].splitlines()
        if len(data) == 4:
            units = parse_units(data[0])
            data = data[1:]
        else:
            units = 1
        cell = array([l.split() for l in data], dtype='float64')
    elif 'latticeabc' in input:
        raise error.NotImplementedError('Cannot read lattice in ABC format yet.')
    else:
        raise error.ValueError('Could not find lattice block in input.')

    # create structure
    result = Structure(cell, scale=units)

    # now look for position block.
    units = None
    if 'positionsfrac' in input:
        posdata, isfrac = input['positionsfrac'].splitlines(), True
    elif 'positionsabs' in input:
        posdata, isfrac = input['positionsabs'].splitlines(), False
        try:
            units = parse_units(posdata[0])
        except:
            units = None
        else:
            posdata = posdata[1:]
    else:
        raise error.ValueError('Could not find position block in input.')
    # and parse it
    for line in posdata:
        line = line.split()
        if len(line) < 2:
            raise error.IOError(
                'Wrong file format: line with less than two items in positions block.')
        pos = array(line[1:4], dtype='float64')
        if isfrac:
            pos = dot(result.cell, pos)
        try:
            dummy = int(line[0])
        except:
            type = line[0]
        else:
            type = find_specie(atomic_number=dummy).symbol
        result.add_atom(pos=pos, type=type)
        if len(line) == 5:
            result[-1].magmom = float(line[4])
    return result
コード例 #22
0
ファイル: read.py プロジェクト: hbwzhsh/pylada-light
def icsd_cif_a( filename):
  """ Reads lattice from the ICSD \*cif files.

      It will not work in the case of other \*cif.
      It is likely to produce wrong output if the site occupations are fractional.
      If the occupation is > 0.5 it will treat it as 1 and
      in the case occupation < 0.5 it will treat it as 0 and
      it will accept all occupation = 0.5 as 1 and create a mess!
  """
  import re
  from os.path import basename
  from numpy.linalg import norm
  from numpy import array, transpose
  from numpy import pi, sin, cos, sqrt, dot
  from pylada.misc import bugLev

  lines = open(filename,'r').readlines()
  if bugLev >= 2:
    print "  crystal/read: icsd_cif_a: filename: ", filename

  sym_big = 0
  sym_end = 0
  pos_big = 0
  pos_end = 0

  for l in lines:
      x = l.split()
      if len(x)>0:
          # CELL
          if x[0] == '_cell_length_a':
              if '(' in x[-1]:
                  index = x[-1].index('(')
              else:
                  index = len(x[-1])
              a = float(x[-1][:index])

          if x[0] == '_cell_length_b':
              if '(' in x[-1]:
                  index = x[-1].index('(')
              else:
                  index = len(x[-1])
              b = float(x[-1][:index])

          if x[0] == '_cell_length_c':
              if '(' in x[-1]:
                  index = x[-1].index('(')
              else:
                  index = len(x[-1])
              c = float(x[-1][:index])

          if x[0] == '_cell_angle_alpha':
              if '(' in x[-1]:
                  index = x[-1].index('(')
              else:
                  index = len(x[-1])
              alpha = float(x[-1][:index])

          if x[0] == '_cell_angle_beta':
              if '(' in x[-1]:
                  index = x[-1].index('(')
              else:
                  index = len(x[-1])
              beta = float(x[-1][:index])

          if x[0] == '_cell_angle_gamma':
              if '(' in x[-1]:
                  index = x[-1].index('(')
              else:
                  index = len(x[-1])
              gamma = float(x[-1][:index])

      # SYMMETRY OPERATIONS

      if len(x)>0 and x[0] == '_symmetry_equiv_pos_as_xyz':
          sym_big = lines.index(l)

      if len(x)>0 and x[0] == '_atom_type_symbol':
          sym_end = lines.index(l)

      # WYCKOFF POSITIONS

      if len(x)>0 and x[0] == '_atom_site_attached_hydrogens':
          pos_big = lines.index(l)

      if len(x)>0 and x[0] == '_atom_site_B_iso_or_equiv':
          pos_big = lines.index(l)

      if len(x)>0 and x[0] == '_atom_site_U_iso_or_equiv':
          pos_big = lines.index(l)

      if len(x)>0 and x[0] == '_atom_site_0_iso_or_equiv':
          pos_big = lines.index(l)

      #if pos_end == 0 and l in ['\n', '\r\n'] and lines.index(l) > pos_big:
      if pos_end == 0 and pos_big > 0 \
        and (l in ['\n', '\r\n'] or l.startswith('#')) \
        and lines.index(l) > pos_big:
          pos_end = lines.index(l)


  # _symmetry_equiv_pos_* lines are like:
  #     1     'x, x-y, -z+1/2'
  if bugLev >= 5:
    print "  crystal/read: icsd_cif_a: sym_big: ", sym_big
    print "  crystal/read: icsd_cif_a: sym_end: ", sym_end

  symm_ops = [ '(' + x.split()[1][1:] + x.split()[2] + x.split()[3][:-1] + ')'\
               for x in lines[sym_big+1:sym_end-1] ]
  if bugLev >= 5:
    print "  crystal/read: icsd_cif_a: symm_ops a: ", symm_ops
  # ['(x,x-y,-z+1/2)', '(-x+y,y,-z+1/2)', ...]

  # Insert decimal points after integers
  symm_ops = [re.sub(r'(\d+)', r'\1.', x) for x in symm_ops]
  if bugLev >= 5:
    print "  crystal/read: icsd_cif_a: symm_ops b: ", symm_ops
  # ['(x,x-y,-z+1./2.)', '(-x+y,y,-z+1./2.)', ...]

  # _atom_site_* lines are like:
  #   Mo1 Mo4+ 2 c 0.3333 0.6667 0.25 1. 0
  if bugLev >= 5:
    print "  crystal/read: icsd_cif_a: pos_big: ", pos_big
    print "  crystal/read: icsd_cif_a: pos_end: ", pos_end
  wyckoff = [ [x.split()[0],[x.split()[4],x.split()[5],x.split()[6]],x.split()[7]]\
              for x in lines[pos_big+1:pos_end] ]
  if bugLev >= 5:
    print "  crystal/read: icsd_cif_a: wyckoff a: ", wyckoff
  # [['Mo1', ['0.3333', '0.6667', '0.25'], '1.'], ['S1', ['0.3333', '0.6667', '0.621(4)'], '1.']]

  wyckoff = [w for w in wyckoff if int(float(w[-1][:4])+0.5) != 0]
  if bugLev >= 5:
    print "  crystal/read: icsd_cif_a: wyckoff b: ", wyckoff
  # [['Mo1', ['0.3333', '0.6667', '0.25'], '1.'], ['S1', ['0.3333', '0.6667', '0.621(4)'], '1.']]

  ############## Setting up a good wyckoff list

  for w in wyckoff:
      # Strip trailing numerals from w[0] == 'Mo1'
      pom = 0
      for i in range(len(w[0])):
          try:
              int(w[0][i])
              if pom ==0: pom=i
          except:
              pass

      w[0] = w[0][:pom]

      # Strip trailing standard uncertainty, if any, from w[1], ..., w[3]
      for i in range(3):
          if '(' in w[1][i]:
              index = w[1][i].index('(')
          else:
              index = len(w[1][i])
          w[1][i] = float(w[1][i][:index])

      # Delete w[4]
      del w[-1]
  ##########################################

  # List of unique symbols ["Mo", "S"]
  symbols = list(set([w[0] for w in wyckoff]))
  if bugLev >= 5:
    print "  crystal/read: icsd_cif_a: symbols: ", symbols

  # List of position vectors for each symbol
  positions = [[] for i in range(len(symbols))]

  for w in wyckoff:
      symbol = w[0]
      x,y,z = w[1][0],w[1][1],w[1][2]
      if bugLev >= 5:
        print "    symbol: ", symbol, "  x: ", x, "  y: ", y, "  z: ", z
      for i in range(len(symm_ops)):
          # Set pom = new position based on symmetry transform
          pom = list(eval(symm_ops[i]))
          if bugLev >= 5:
            print "      i: ", i, "  pom a: ", pom
          # [0.3333, -0.3334, 0.25]

          # Move positions to range [0,1]:
          for j in range(len(pom)):
              if pom[j] <  0.: pom[j] = pom[j]+1.
              if pom[j] >= 0.999: pom[j] = pom[j]-1.
          if bugLev >= 5:
            print "      i: ", i, "  pom b: ", pom
          # [0.3333, 0.6666, 0.25]

          # If pom is not in positions[symbol], append pom
          if not any(norm(array(u)-array(pom)) < 0.01 for u in positions[symbols.index(symbol)]):
              ix = symbols.index(symbol)
              positions[ix].append(pom)
              if bugLev >= 5:
                print "      new positions for ", symbol, ": ", positions[ix]

  ################ CELL ####################

  a1 = a*array([1.,0.,0.])
  a2 = b*array([cos(gamma*pi/180.),sin(gamma*pi/180.),0.])
  c1 = c*cos(beta*pi/180.)
  c2 = c/sin(gamma*pi/180.)*(-cos(beta*pi/180.)*cos(gamma*pi/180.) + cos(alpha*pi/180.))
  a3 = array([c1, c2, sqrt(c**2-(c1**2+c2**2))])
  cell = array([a1,a2,a3])
  if bugLev >= 2:
    print "  crystal/read: icsd_cif_a: a1: ", a1
    print "  crystal/read: icsd_cif_a: a2: ", a2
    print "  crystal/read: icsd_cif_a: a3: ", a3
  #  a1:  [ 3.15  0.    0.  ]
  #  a2:  [-1.575       2.72798002  0.        ]
  #  a3:  [  7.53157781e-16   1.30450754e-15   1.23000000e+01]
  ##########################################


  from pylada.crystal import Structure, primitive
  if bugLev >= 2:
    print "  crystal/read: icsd_cif_a: cell: ", cell
  #  [[  3.15000000e+00   0.00000000e+00   0.00000000e+00]
  #   [ -1.57500000e+00   2.72798002e+00   0.00000000e+00]
  #   [  7.53157781e-16   1.30450754e-15   1.23000000e+01]]

  structure = Structure(
    transpose( cell),
    scale = 1,
    name = basename( filename))

  for i in range(len(symbols)):
    if bugLev >= 5:
      print "    crystal/read: icsd_cif_a: i: ", i, \
        "  symbol: ", symbols[i], \
        "  len position: ", len(positions[i])
    # crystal/read: i:  0   symbol:  Mo   len position:  2

    for j in range(len(positions[i])):
      atpos = dot( transpose(cell), positions[i][j])
      if bugLev >= 5:
        print "      j: ", j, "  pos: ", positions[i][j]
        print "        atpos: ", atpos
      #  j:  0   pos:  [0.3333, 0.6666000000000001, 0.25]
      #  atpos:  [  6.32378655e-16   1.81847148e+00   3.07500000e+00]

      structure.add_atom( atpos[0], atpos[1], atpos[2], symbols[i])

  if bugLev >= 2:
    print "  crystal/read: icsd_cif_a: structure:\n", structure
  
  prim = primitive( structure)
  if bugLev >= 2:
    print "  crystal/read: icsd_cif_a: primitive structure:\n", prim
  
  return prim
コード例 #23
0
ファイル: read.py プロジェクト: hbwzhsh/pylada-light
def poscar(path="POSCAR", types=None):
  """ Tries to read a VASP POSCAR file.

       :param path: Path to the POSCAR file. Can also be an object with
         file-like behavior.
       :type path: str or file object
       :param types: Species in the POSCAR.
       :type types: None or sequence of str

      :return: `pylada.crystal.Structure` instance.
  """
  import re
  from os.path import join, exists, isdir
  from copy import deepcopy
  from numpy import array, dot, transpose
  from numpy.linalg import det
  from quantities import angstrom
  from . import Structure

  # if types is not none, converts to a list of strings.
  if types is not None:
    if isinstance(types, str): types = [types] # can't see another way of doing this...
    elif not hasattr(types, "__iter__"): types = [str(types)] # single lone vasp.specie.Specie
    else: types = [str(s) for s in types]

  if path is None: path = "POSCAR"
  if not hasattr(path, 'read'):
    assert exists(path), IOError("Could not find path %s." % (path))
    if isdir(path):
      assert exists(join(path, "POSCAR")), IOError("Could not find POSCAR in %s." % (path))
      path = join(path, "POSCAR")
  result = Structure()
  poscar = path if hasattr(path, "read") else open(path, 'r')

  try:
    # gets name of structure
    result.name = poscar.readline().strip()
    if len(result.name) > 0:
      if result.name[0] == "#": result.name = result.name[1:].strip()
    # reads scale
    scale = float(poscar.readline().split()[0])
    # gets cell vectors.
    cell = []
    for i in range(3):
      line = poscar.readline()
      assert len(line.split()) >= 3,\
             RuntimeError("Could not read column vector from poscar: %s." % (line))
      cell.append( [float(f) for f in line.split()[:3]] )
    result.cell = transpose(array(cell))
    vol = det(cell)
    if scale < 1.E-8 : scale = abs(scale/vol) **(1.0/3)
    result.scale = scale * angstrom
    # checks for vasp 5 input.
    is_vasp_5 = True
    line = poscar.readline().split()
    for i in line:
      if not re.match(r"[A-Z][a-z]?", i):
        is_vasp_5 = False
        break
    if is_vasp_5:
      text_types = deepcopy(line)
      if types is not None and not set(text_types).issubset(set(types)):
        raise RuntimeError( "Unknown species in poscar: {0} not in {1}."\
                            .format(text_types, types) )
      types = text_types
      line = poscar.readline().split()
    assert types is not None, RuntimeError("No atomic species given in POSCAR or input.")
    #  checks/reads for number of each specie
    assert len(types) >= len(line), RuntimeError("Too many atomic species in POSCAR.")
    nb_atoms = [int(u) for u in line]
    # Check whether selective dynamics, cartesian, or direct.
    first_char = poscar.readline().strip().lower()[0]
    selective_dynamics = False
    if first_char == 's':
      selective_dynamics = True
      first_char = poscar.readline().strip().lower()[0]
    # Checks whether cartesian or direct.
    is_direct = first_char not in ['c', 'k']
    # reads atoms.
    for n, specie in zip(nb_atoms, types):
      for i in range(n):
        line = poscar.readline().split()
        pos = array([float(u) for u in line[:3]], dtype="float64")
        if is_direct: pos = dot(result.cell, pos)
        result.add_atom(pos=pos, type=specie)
        if selective_dynamics:
          for which, freeze in zip(line[3:], ['x', 'y', 'z']):
            if which.lower()[0] == 't':
              result[-1].freeze = getattr(result[-1], 'freeze', '') + freeze
  finally: poscar.close()

  return result
コード例 #24
0
ファイル: read.py プロジェクト: hbwzhsh/pylada-light
def castep(file):
  """ Tries to read a castep structure file. """
  from numpy import array, dot
  from ..periodic_table import find as find_specie
  from ..error import IOError, NotImplementedError, input as InputError
  from ..misc import RelativePath
  from . import Structure
  if isinstance(file, str):
    if file.find('\n') == -1:
      with open(RelativePath(file).path, 'r') as file: return castep(file)
    else: file = file.splitlines()

  file = [l for l in file]

  def parse_input(input):
    """ Retrieves blocks from CASTEP input file. """
    current_block = None
    result = {}
    for line in file:
      if '#' in line: line = line[:line.find('#')]
      if current_block is not None:
        if line.split()[0].lower() == '%endblock':
          current_block = None
          continue
        result[current_block] += line
      elif len(line.split()) == 0: continue
      elif len(line.split()[0]) == 0: continue
      elif line.split()[0].lower() == '%block':
        name = line.split()[1].lower().replace('.', '').replace('_', '')
        if name in result:
          raise InputError('Found two {0} blocks in input.'.format(name))
        result[name] = ""
        current_block = name
      else:
        name = line.split()[0].lower().replace('.', '').replace('_', '')
        if name[-1] in ['=' or ':']: name = name[:-1]
        if name in result:
          raise InputError('Found two {0} tags in input.'.format(name))
        data = line.split()[1:]
        if len(data) == 0: result[name] = None; continue
        if data[0] in [':', '=']: data = data[1:]
        result[name] = ' '.join(data)
    return result

  def parse_units(line):
    from quantities import a0, meter, centimeter, millimeter, angstrom, emass, \
                           amu, second, millisecond, microsecond, nanosecond,  \
                           picosecond, femtosecond, elementary_charge, coulomb,\
                           hartree, eV, meV, Ry, joule, cal, erg, hertz,       \
                           megahertz, gigahertz, tera, kelvin, newton, dyne,   \
                           h_bar, UnitQuantity, pascal, megapascal, gigapascal,\
                           bar, atm, milli, mol

    auv = UnitQuantity('auv', a0*Ry/h_bar) # velocity
    units = { 'a0': a0, 'bohr': a0, 'm': meter, 'cm': centimeter,
              'mm': millimeter, 'ang': angstrom, 'me': emass, 'amu': amu,
              's': second, 'ms': millisecond, 'mus': microsecond,
              'ns': nanosecond, 'ps': picosecond, 'fs': femtosecond,
              'e': elementary_charge, 'c': coulomb, 'hartree': hartree,
              'ha': hartree, 'mha': 1e-3*hartree, 'ev': eV, 'mev': meV,
              'ry': Ry, 'mry': 1e-3*Ry, 'kj': 1e3*joule, 'mol': mol,
              'kcal': 1e3*cal, 'j': joule, 'erg': erg, 'hz': hertz,
              'mhz': megahertz, 'ghz': gigahertz, 'thz': tera*hertz,
              'k': kelvin, 'n': newton, 'dyne': dyne, 'auv': auv, 'pa': pascal,
              'mpa': megapascal, 'gpa': gigapascal, 'atm': atm, 'bar': bar,
              'atm': atm, 'mbar': milli*bar }
    line = line.replace('cm-1', '1/cm')
    return eval(line, units)


  input = parse_input(file)
  if 'latticecart' in input:
    data = input['latticecart'].splitlines()
    if len(data) == 4:
      units = parse_units(data[0])
      data = data[1:]
    else: units = 1
    cell = array([l.split() for l in data], dtype='float64')
  elif 'latticeabc' in input:
    raise NotImplementedError('Cannot read lattice in ABC format yet.')
  else:
    raise InputError('Could not find lattice block in input.')

  # create structure
  result = Structure(cell, scale=units)

  # now look for position block.
  units = None
  if 'positionsfrac' in input:
    posdata, isfrac = input['positionsfrac'].splitlines(), True
  elif 'positionsabs' in input:
    posdata, isfrac = input['positionsabs'].splitlines(), False
    try: units = parse_units(posdata[0])
    except: units = None
    else: posdata = posdata[1:]
  else: raise InputError('Could not find position block in input.')
  # and parse it
  for line in posdata:
    line = line.split()
    if len(line) < 2:
      raise IOError( 'Wrong file format: line with less '                      \
                     'than two items in positions block.')
    pos = array(line[1:4], dtype='float64')
    if isfrac: pos = dot(result.cell, pos)
    try: dummy = int(line[0])
    except: type = line[0]
    else: type = find_specie(atomic_number=dummy).symbol
    result.add_atom(pos=pos, type=type)
    if len(line) == 5: result[-1].magmom = float(line[4])
  return result
コード例 #25
0
ファイル: read.py プロジェクト: pylada/pylada-light
def icsd_cif_a(filename, make_primitive=True):
    """ Reads lattice from the ICSD \*cif files.

        It will not work in the case of other \*cif.
        It is likely to produce wrong output if the site occupations are fractional.
        If the occupation is > 0.5 it will treat it as 1 and
        in the case occupation < 0.5 it will treat it as 0 and
        it will accept all occupation = 0.5 as 1 and create a mess!
    """
    from pylada import logger
    import re
    from copy import deepcopy
    from os.path import basename
    from numpy.linalg import norm
    from numpy import array, transpose
    from numpy import pi, sin, cos, sqrt, dot

    lines = open(filename, 'r').readlines()
    logger.info("crystal/read: icsd_cif_a: %s" % filename)

    sym_big = 0
    sym_end = 0
    pos_big = 0
    pos_end = 0

    for l in lines:
        x = l.split()
        if len(x) > 0:
                    # CELL
            if x[0] == '_cell_length_a':
                if '(' in x[-1]:
                    index = x[-1].index('(')
                else:
                    index = len(x[-1])
                a = float(x[-1][:index])

            if x[0] == '_cell_length_b':
                if '(' in x[-1]:
                    index = x[-1].index('(')
                else:
                    index = len(x[-1])
                b = float(x[-1][:index])

            if x[0] == '_cell_length_c':
                if '(' in x[-1]:
                    index = x[-1].index('(')
                else:
                    index = len(x[-1])
                c = float(x[-1][:index])

            if x[0] == '_cell_angle_alpha':
                if '(' in x[-1]:
                    index = x[-1].index('(')
                else:
                    index = len(x[-1])
                alpha = float(x[-1][:index])

            if x[0] == '_cell_angle_beta':
                if '(' in x[-1]:
                    index = x[-1].index('(')
                else:
                    index = len(x[-1])
                beta = float(x[-1][:index])

            if x[0] == '_cell_angle_gamma':
                if '(' in x[-1]:
                    index = x[-1].index('(')
                else:
                    index = len(x[-1])
                gamma = float(x[-1][:index])

        # SYMMETRY OPERATIONS

        if len(x) > 0 and x[0] == '_symmetry_equiv_pos_as_xyz':
            sym_big = lines.index(l)

        if len(x) > 0 and x[0] == '_atom_type_symbol':
            sym_end = lines.index(l)

        # WYCKOFF POSITIONS

        if len(x) > 0 and x[0] == '_atom_site_attached_hydrogens':
            pos_big = lines.index(l)

        if len(x) > 0 and x[0] == '_atom_site_B_iso_or_equiv':
            pos_big = lines.index(l)

        if len(x) > 0 and x[0] == '_atom_site_U_iso_or_equiv':
            pos_big = lines.index(l)

        if len(x) > 0 and x[0] == '_atom_site_0_iso_or_equiv':
            pos_big = lines.index(l)

        # if pos_end == 0 and l in ['\n', '\r\n'] and lines.index(l) > pos_big:
        if pos_end == 0 and pos_big > 0 \
                and (l in ['\n', '\r\n'] or l.startswith('#')) \
                and lines.index(l) > pos_big:
            pos_end = lines.index(l)

    # _symmetry_equiv_pos_* lines are like:
    #     1     'x, x-y, -z+1/2'
    logger.debug("crystal/read: icsd_cif_a: sym_big: %s" % sym_big)
    logger.debug("crystal/read: icsd_cif_a: sym_end: %s" % sym_end)

    symm_ops = ['(' + x.split()[1][1:] + x.split()[2] + x.split()[3][:-1] + ')'
                for x in lines[sym_big + 1:sym_end - 1]]
    logger.debug("crystal/read: icsd_cif_a: symm_ops a: %s" % symm_ops)
    # ['(x,x-y,-z+1/2)', '(-x+y,y,-z+1/2)', ...]

    # Insert decimal points after integers
    symm_ops = [re.sub(r'(\d+)', r'\1.', x) for x in symm_ops]
    logger.debug("crystal/read: icsd_cif_a: symm_ops b: %s" % symm_ops)
    # ['(x,x-y,-z+1./2.)', '(-x+y,y,-z+1./2.)', ...]

    # _atom_site_* lines are like:
    #   Mo1 Mo4+ 2 c 0.3333 0.6667 0.25 1. 0
    logger.debug("crystal/read: icsd_cif_a: pos_big: %s" % pos_big)
    logger.debug("crystal/read: icsd_cif_a: pos_end: %s" % pos_end)
    wyckoff = [[x.split()[0], [x.split()[4], x.split()[5], x.split()[6]], x.split()[7]]
               for x in lines[pos_big + 1:pos_end]]
    logger.debug("crystal/read: icsd_cif_a: wyckoff a: %s" % wyckoff)
    # [['Mo1', ['0.3333', '0.6667', '0.25'], '1.'], ['S1', ['0.3333', '0.6667', '0.621(4)'], '1.']]

    wyckoff = [w for w in wyckoff if int(float(w[-1][:4]) + 0.5) != 0]
    logger.debug("crystal/read: icsd_cif_a: wyckoff b: %s" % wyckoff)
    # [['Mo1', ['0.3333', '0.6667', '0.25'], '1.'], ['S1', ['0.3333', '0.6667', '0.621(4)'], '1.']]

    # Setting up a good wyckoff list

    for w in wyckoff:
        # Strip trailing numerals from w[0] == 'Mo1'
        pom = 0
        for i in range(len(w[0])):
            try:
                int(w[0][i])
                if pom == 0:
                    pom = i
            except:
                pass

        w[0] = w[0][:pom]

        # Strip trailing standard uncertainty, if any, from w[1], ..., w[3]
        for i in range(3):
            if '(' in w[1][i]:
                index = w[1][i].index('(')
            else:
                index = len(w[1][i])
            w[1][i] = float(w[1][i][:index])

        # Delete w[4]
        del w[-1]
    ##########################################

    # List of unique symbols ["Mo", "S"]
    symbols = list({w[0] for w in wyckoff})
    logger.debug("crystal/read: icsd_cif_a: symbols: %s" % symbols)

    # List of position vectors for each symbol
    positions = [[] for i in range(len(symbols))]

    for w in wyckoff:
        symbol = w[0]
        x, y, z = w[1][0], w[1][1], w[1][2]
        logger.debug("symbol: %s  x: %s   y: %s  z: %s" % (symbol, x, y, z))
        for i in range(len(symm_ops)):
            # Set pom = new position based on symmetry transform
            pom = list(eval(symm_ops[i]))
            logger.debug("i: %s  pom a: %s" % (i, pom))
            # [0.3333, -0.3334, 0.25]

            # Move positions to range [0,1]:
            for j in range(len(pom)):
                if pom[j] < 0.:
                    pom[j] = pom[j] + 1.
                if pom[j] >= 0.999:
                    pom[j] = pom[j] - 1.
            logger.debug("i: %s   pom b: %s" % (i, pom))
            # [0.3333, 0.6666, 0.25]

            # If pom is not in positions[symbol], append pom
            if not any(norm(array(u) - array(pom)) < 0.01 for u in positions[symbols.index(symbol)]):
                ix = symbols.index(symbol)
                positions[ix].append(pom)
                logger.debug("new positions for %s: %s" % (symbol, repr(positions[ix])))

    ################ CELL ####################

    a1 = a * array([1., 0., 0.])
    a2 = b * array([cos(gamma * pi / 180.), sin(gamma * pi / 180.), 0.])
    c1 = c * cos(beta * pi / 180.)
    c2 = c / sin(gamma * pi / 180.) * (-cos(beta * pi / 180.) *
                                       cos(gamma * pi / 180.) + cos(alpha * pi / 180.))
    a3 = array([c1, c2, sqrt(c**2 - (c1**2 + c2**2))])
    cell = array([a1, a2, a3])
    logger.debug("crystal/read: icsd_cif_a: a1: %s" % a1)
    logger.debug("crystal/read: icsd_cif_a: a2: %s" % a2)
    logger.debug("crystal/read: icsd_cif_a: a3: %s" % a3)
    ##########################################

    from pylada.crystal import Structure, primitive
    logger.debug("crystal/read: icsd_cif_a: cell: %s" % cell)

    structure = Structure(
        transpose(cell),
        scale=1,
        name=basename(filename))

    for i in range(len(symbols)):
        logger.debug("crystal/read: icsd_cif_a: i: %s  symbol: %s  len(position): %i" % (
            i,  symbols[i], len(positions[i])
        ))
        # crystal/read: i:  0   symbol:  Mo   len position:  2

        for j in range(len(positions[i])):
            atpos = dot(transpose(cell), positions[i][j])
            logger.debug("j: %s  pos: %s" % (j, positions[i][j]))
            logger.debug("atpos: " % atpos)
            #  j:  0   pos:  [0.3333, 0.6666000000000001, 0.25]
            #  atpos:  [  6.32378655e-16   1.81847148e+00   3.07500000e+00]

            structure.add_atom(atpos[0], atpos[1], atpos[2], symbols[i])

    logger.info("crystal/read: icsd_cif_a: structure: %s" % structure)

    if make_primitive:
        prim = primitive(structure)
    else:
        prim = deepcopy(structure)
    logger.info("crystal/read: icsd_cif_a: primitive structure: %s" % prim)

    return prim
コード例 #26
0
def make_surface(structure=None, miller=None, nlayers=5, vacuum=15, acc=5):
    """Returns a slab from the 3D structure 

       Takes a structure and makes a slab defined by the miller indices 
       with nlayers number of layers and vacuum defining the size 
       of the vacuum thickness. Variable acc determines the number of 
       loops used to get the direct lattice vectors perpendicular 
       and parallel to miller. For high index surfaces use larger acc value 
       .. warning: (1) cell is always set such that miller is alogn z-axes
                   (2) nlayers and vacuum are always along z-axes.

       :param structure: LaDa structure
       :param miller: 3x1 float64 array
           Miller indices defining the slab    
       :param nlayers: integer
           Number of layers in the slab
       :param vacuum: real
           Vacuum thicness in angstroms
       :param acc: integer
           number of loops for finding the cell vectors of the slab structure
    """
    direct_cell = transpose(structure.cell)
    reciprocal_cell = 2 * pi * transpose(inv(direct_cell))

    orthogonal = []  # lattice vectors orthogonal to miller

    for n1 in arange(-acc, acc + 1):
        for n2 in arange(-acc, acc + 1):
            for n3 in arange(-acc, acc + 1):

                pom = array([n1, n2, n3])
                if dot(pom, miller) == 0 and dot(pom, pom) != 0:
                    orthogonal.append(array([n1, n2, n3]))

    # chose the shortest parallel and set it to be a3 lattice vector
    norm_orthogonal = [sqrt(dot(dot(x, direct_cell), dot(x, direct_cell))) for x in orthogonal]
    a1 = orthogonal[norm_orthogonal.index(min(norm_orthogonal))]

    # chose the shortest orthogonal to miller and not colinear with a1 and set it as a2
    in_plane = []

    for x in orthogonal:
        if dot(x, x) > 1e-3:
            v = cross(dot(x, direct_cell), dot(a1, direct_cell))
            v = sqrt(dot(v, v))
            if v > 1e-3:
                in_plane.append(x)

    norm_in_plane = [sqrt(dot(dot(x, direct_cell), dot(x, direct_cell))) for x in in_plane]
    a2 = in_plane[norm_in_plane.index(min(norm_in_plane))]

    a1 = dot(a1, direct_cell)
    a2 = dot(a2, direct_cell)

    # new cartesian axes z-along miller, x-along a1, and y-to define the right-hand orientation
    e1 = a1 / sqrt(dot(a1, a1))
    e2 = a2 - dot(e1, a2) * e1
    e2 = e2 / sqrt(dot(e2, e2))
    e3 = cross(e1, e2)

    # find vectors parallel to miller and set the shortest to be a3
    parallel = []

    for n1 in arange(-acc, acc + 1):
        for n2 in arange(-acc, acc + 1):
            for n3 in arange(-acc, acc + 1):
                pom = dot(array([n1, n2, n3]), direct_cell)
                if sqrt(dot(pom, pom)) - dot(e3, pom) < 1e-8 and sqrt(dot(pom, pom)) > 1e-3:
                    parallel.append(pom)

    # if there are no lattice vectors parallel to miller
    if len(parallel) == 0:
        for n1 in arange(-acc, acc + 1):
            for n2 in arange(-acc, acc + 1):
                for n3 in arange(-acc, acc + 1):
                    pom = dot(array([n1, n2, n3]), direct_cell)
                    if dot(e3, pom) > 1e-3:
                        parallel.append(pom)

    parallel = [x for x in parallel if sqrt(
        dot(x - dot(e1, x) * e1 - dot(e2, x) * e2, x - dot(e1, x) * e1 - dot(e2, x) * e2)) > 1e-3]
    norm_parallel = [sqrt(dot(x, x)) for x in parallel]

    assert len(norm_parallel) != 0, "Increase acc, found no lattice vectors parallel to (hkl)"

    a3 = parallel[norm_parallel.index(min(norm_parallel))]

    # making a structure in the new unit cell - defined by the a1,a2,a3
    new_direct_cell = array([a1, a2, a3])

    assert abs(det(new_direct_cell)) > 1e-5, "Something is wrong your volume is equal to zero"

    # make sure determinant is positive
    if det(new_direct_cell) < 0.:
        new_direct_cell = array([-a1, a2, a3])

    #structure = fill_structure(transpose(new_direct_cell),structure.to_lattice())
    structure = supercell(lattice=structure, supercell=transpose(new_direct_cell))

    # transformation matrix to new coordinates x' = dot(m,x)
    m = array([e1, e2, e3])

    # seting output structure
    out_structure = Structure()
    out_structure.scale = structure.scale
    out_structure.cell = transpose(dot(new_direct_cell, transpose(m)))

    for atom in structure:
        p = dot(m, atom.pos)
        out_structure.add_atom(p[0], p[1], p[2], atom.type)

    # repaeting to get nlayers and vacuum
    repeat_cell = dot(out_structure.cell, array([[1., 0., 0.], [0., 1., 0.], [0., 0., nlayers]]))
    out_structure = supercell(lattice=out_structure, supercell=repeat_cell)

    # checking whether there are atoms close to the cell faces and putting them back to zero
    for i in range(len(out_structure)):
        scaled_pos = dot(out_structure[i].pos, inv(transpose(out_structure.cell)))
        for j in range(3):
            if abs(scaled_pos[j] - 1.) < 1e-5:
                scaled_pos[j] = 0.
        out_structure[i].pos = dot(scaled_pos, transpose(out_structure.cell))

    # adding vaccum to the cell
    out_structure.cell = out_structure.cell + \
        array([[0., 0., 0.], [0., 0., 0.], [0., 0., float(vacuum) / float(out_structure.scale)]])

    # translating atoms so that center of the slab and the center of the cell along z-axes coincide
    max_z = max([x.pos[2] for x in out_structure])
    min_z = min([x.pos[2] for x in out_structure])
    center_atoms = 0.5 * (max_z + min_z)
    center_cell = 0.5 * out_structure.cell[2][2]

    for i in range(len(out_structure)):
        out_structure[i].pos = out_structure[i].pos + array([0., 0., center_cell - center_atoms])

    # exporting the final structure
    return out_structure
コード例 #27
0
ファイル: read_icsd.py プロジェクト: Ash-Pera/cutsurfaces
def icsd_cif_a(filename, make_primitive=True):
    """ Reads lattice from the ICSD \*cif files.

        It will not work in the case of other \*cif.
        It is likely to produce wrong output if the site occupations are fractional.
        If the occupation is > 0.5 it will treat it as 1 and
        in the case occupation < 0.5 it will treat it as 0 and
        it will accept all occupation = 0.5 as 1 and create a mess!
    """
    import re
    from copy import deepcopy
    from os.path import basename
    from numpy.linalg import norm
    from numpy import array, transpose
    from numpy import pi, sin, cos, sqrt, dot
    from sys import version_info

    if version_info[0] >= 3:
        lines = open(filename, 'r', encoding='latin1').readlines()
    else:
        lines = open(filename, 'r').readlines()

    sym_big = 0
    sym_end = 0
    pos_big = 0
    pos_end = 0

    for l in lines:
        x = l.split()
        if len(x) > 0:
            # CELL
            if x[0] == '_cell_length_a':
                if '(' in x[-1]:
                    index = x[-1].index('(')
                else:
                    index = len(x[-1])
                a = float(x[-1][:index])

            if x[0] == '_cell_length_b':
                if '(' in x[-1]:
                    index = x[-1].index('(')
                else:
                    index = len(x[-1])
                b = float(x[-1][:index])

            if x[0] == '_cell_length_c':
                if '(' in x[-1]:
                    index = x[-1].index('(')
                else:
                    index = len(x[-1])
                c = float(x[-1][:index])

            if x[0] == '_cell_angle_alpha':
                if '(' in x[-1]:
                    index = x[-1].index('(')
                else:
                    index = len(x[-1])
                alpha = float(x[-1][:index])

            if x[0] == '_cell_angle_beta':
                if '(' in x[-1]:
                    index = x[-1].index('(')
                else:
                    index = len(x[-1])
                beta = float(x[-1][:index])

            if x[0] == '_cell_angle_gamma':
                if '(' in x[-1]:
                    index = x[-1].index('(')
                else:
                    index = len(x[-1])
                gamma = float(x[-1][:index])

        if len(x) > 0 and x[0] == '_symmetry_Int_Tables_number':
            spg = int(x[1])

        # SYMMETRY OPERATIONS

        if len(x) > 0 and x[0] == '_symmetry_equiv_pos_as_xyz':
            sym_big = lines.index(l)

        if len(x) > 0 and x[0] == '_atom_type_symbol':
            sym_end = lines.index(l)

        ## FT: reads oxydation states
        # OXYDATION STATE

        if len(x) > 0 and x[0] == '_atom_site_label':
            ox_end = lines.index(l)

        # WYCKOFF POSITIONS

        if len(x) > 0 and x[0] == '_atom_site_attached_hydrogens':
            pos_big = lines.index(l)

        if len(x) > 0 and x[0] == '_atom_site_B_iso_or_equiv':
            pos_big = lines.index(l)

        if len(x) > 0 and x[0] == '_atom_site_U_iso_or_equiv':
            pos_big = lines.index(l)

        if len(x) > 0 and x[0] == '_atom_site_0_iso_or_equiv':
            pos_big = lines.index(l)

        # if pos_end == 0 and l in ['\n', '\r\n'] and lines.index(l) > pos_big:
        if pos_end == 0 and pos_big > 0 \
                and (l in ['\n', '\r\n'] or l.startswith('#')) \
                and lines.index(l) > pos_big:
            pos_end = lines.index(l)

    # _symmetry_equiv_pos_* lines are like:
    #     1     'x, x-y, -z+1/2'

    symm_ops = [
        '(' + x.split()[1][1:] + x.split()[2] + x.split()[3][:-1] + ')'
        for x in lines[sym_big + 1:sym_end - 1]
    ]

    # ['(x,x-y,-z+1/2)', '(-x+y,y,-z+1/2)', ...]

    # Insert decimal points after integers
    symm_ops = [re.sub(r'(\d+)', r'\1.', x) for x in symm_ops]
    # ['(x,x-y,-z+1./2.)', '(-x+y,y,-z+1./2.)', ...]

    # _atom_site_* lines are like:
    #   Mo1 Mo4+ 2 c 0.3333 0.6667 0.25 1. 0
    ## FT: replaced [0] by [1] to take the ion name instead (ex: Mo4+ instead of Mo1)
    wyckoff = [[
        x.split()[1], [x.split()[4], x.split()[5],
                       x.split()[6]],
        x.split()[7]
    ] for x in lines[pos_big + 1:pos_end]]
    # [['Mo1', ['0.3333', '0.6667', '0.25'], '1.'], ['S1', ['0.3333', '0.6667', '0.621(4)'], '1.']]

    wyckoff = [w for w in wyckoff if int(float(w[-1][:4]) + 0.5) != 0]
    # [['Mo1', ['0.3333', '0.6667', '0.25'], '1.'], ['S1', ['0.3333', '0.6667', '0.621(4)'], '1.']]

    ##FT: reading the proper oxidation states
    oxidation = [[x.split()[0],
                  int(round(float(x.split()[1]), 0))]
                 for x in lines[sym_end + 2:ox_end - 1]]

    # Setting up a good wyckoff list

    for w in wyckoff:

        ## FT: Not stripping anymore to keep different oxydation states different
        # Strip trailing numerals from w[0] == 'Mo1'
        # pom = 0
        # for i in range(len(w[0])):
        #     try:
        #         int(w[0][i])
        #         if pom == 0:
        #             pom = i
        #     except:
        #         pass

        # w[0] = w[0][:pom]

        # Strip trailing standard uncertainty, if any, from w[1], ..., w[3]
        for i in range(3):
            if '(' in w[1][i]:
                index = w[1][i].index('(')
            else:
                index = len(w[1][i])
            w[1][i] = float(w[1][i][:index])

        # Delete w[4]
        del w[-1]
    ##########################################

    # List of unique symbols ["Mo", "S"]
    symbols = list({w[0] for w in wyckoff})

    # List of position vectors for each symbol
    positions = [[] for i in range(len(symbols))]

    for w in wyckoff:
        symbol = w[0]
        x, y, z = w[1][0], w[1][1], w[1][2]
        for i in range(len(symm_ops)):
            # Set pom = new position based on symmetry transform
            pom = list(eval(symm_ops[i]))
            # [0.3333, -0.3334, 0.25]

            # Move positions to range [0,1]:
            for j in range(len(pom)):
                if pom[j] < 0.:
                    pom[j] = pom[j] + 1.
                if pom[j] >= 0.999:
                    pom[j] = pom[j] - 1.
            # [0.3333, 0.6666, 0.25]

            # If pom is not in positions[symbol], append pom
            if not any(
                    norm(array(u) - array(pom)) < 0.01
                    for u in positions[symbols.index(symbol)]):
                ix = symbols.index(symbol)
                positions[ix].append(pom)

    ################ CELL ####################

    a1 = a * array([1., 0., 0.])
    a2 = b * array([cos(gamma * pi / 180.), sin(gamma * pi / 180.), 0.])
    c1 = c * cos(beta * pi / 180.)
    c2 = c / sin(
        gamma * pi / 180.) * (-cos(beta * pi / 180.) * cos(gamma * pi / 180.) +
                              cos(alpha * pi / 180.))
    a3 = array([c1, c2, sqrt(c**2 - (c1**2 + c2**2))])
    cell = array([a1, a2, a3])
    ##########################################

    from pylada.crystal import Structure, primitive

    structure = Structure(transpose(cell),
                          scale=1,
                          name=basename(filename),
                          group=spg)

    for i in range(len(symbols)):
        # crystal/read: i:  0   symbol:  Mo   len position:  2

        for j in range(len(positions[i])):
            atpos = dot(transpose(cell), positions[i][j])
            #  j:  0   pos:  [0.3333, 0.6666000000000001, 0.25]
            #  atpos:  [  6.32378655e-16   1.81847148e+00   3.07500000e+00]

            ## FT: Finds the corresponding oxidation
            for o in oxidation:
                if o[0] == symbols[i]:
                    ox = o[1]
                    break

            structure.add_atom(atpos[0], atpos[1], atpos[2], symbols[i], ox=ox)

    if make_primitive:
        prim = primitive(structure)
    else:
        prim = deepcopy(structure)

    return prim
コード例 #28
0
import numpy as np
from pylada.crystal import supercell, Structure
from prepare import reciprocal
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

tol = 1e-12

# Primittive structure
A = Structure([[0.5, 0.5, 0], [0.5, 0, 0.5], [0, 0.5, 0.5]])
A.add_atom(0, 0, 0, 'Si')
A.add_atom(0.25, 0.25, 0.25, 'Si')

# Building the (perfect) supercell
Asc = supercell(A, [[3, 0, 0], [0, 3, 0], [0, 0, 3]])

rpc = reciprocal(A.cell)  #reciprocal lattice of PC
irpc = np.linalg.inv(rpc)  #inverse of reciprocal lattice of PC

rsc = reciprocal(Asc.cell)  #reciprocal lattice of SC
irsc = np.linalg.inv(rsc)  #inverse of reciprocal lattice of SC

# big square
# Finds the furthest corner
corner = np.array([[0, 0, 0]])
for i in range(2):
    for j in range(2):
        for k in range(2):
            corner = np.reshape(
コード例 #29
0
ファイル: test.py プロジェクト: georgeyumnam/pylada
                     (0, 1,   0),\
                     (0, 0, 0.5)
structure = fill_structure(structure.cell)
for i, atom in enumerate(structure.atoms):
  atom.type = "Si" if i < len(structure.atoms)/2 else "Ge"


result_str = Structure()
result_str.scale = 5.450000e+00
result_str.set_cell = (4.068890e+00, -4.235770e-18, 5.083297e-01),\
                     (-1.694308e-17, 1.016103e+00, 2.238072e-18),\
                     (-2.252168e-03, 8.711913e-18, 5.083297e-01)
result_str.weight = 1.000000e+00
result_str.name = ""
result_str.energy = 0.0938967086716
result_str.add_atom = (0.000000e+00, 0.000000e+00, 0.000000e+00), "Si", 0,  0
result_str.add_atom = (2.541649e-01, 2.473273e-01, 2.541649e-01), "Si", 1,  0
result_str.add_atom = (3.567265e+00, 5.062000e-01, -8.956567e-03), "Si", 0,  0
result_str.add_atom = (3.821430e+00, 7.572301e-01, 2.452083e-01), "Si", 1,  0
result_str.add_atom = (3.065136e+00, -1.851371e-03, -1.515736e-02), "Si", 0,  0
result_str.add_atom = (3.319301e+00, 2.491787e-01, 2.390075e-01), "Si", 1,  0
result_str.add_atom = (2.563510e+00, 5.080514e-01, -2.186176e-02), "Si", 0,  0
result_str.add_atom = (2.817675e+00, 7.553787e-01, 2.323031e-01), "Si", 1,  0
result_str.add_atom = (2.055673e+00, -6.642716e-03, -2.235452e-02), "Ge", 0,  0
result_str.add_atom = (2.309838e+00, 2.539701e-01, 2.318104e-01), "Ge", 1,  0
result_str.add_atom = (1.539450e+00, 5.026981e-01, -1.446032e-02), "Ge", 0,  0
result_str.add_atom = (1.793614e+00, 7.607320e-01, 2.397046e-01), "Ge", 1,  0
result_str.add_atom = (1.024061e+00, -5.353269e-03, -7.401445e-03), "Ge", 0,  0
result_str.add_atom = (1.278226e+00, 2.526806e-01, 2.467634e-01), "Ge", 1,  0
result_str.add_atom = (5.078370e-01, 5.014086e-01, 4.927555e-04), "Ge", 0,  0
result_str.add_atom = (7.620018e-01, 7.620214e-01, 2.546576e-01), "Ge", 1,  0
コード例 #30
0
ファイル: setexample.py プロジェクト: ftherrien/PhononCode
from pythonQE import *
from copy import deepcopy
import os
from pylada.crystal import supercell, Structure
import pylada.periodic_table as pt
import pickle
import numpy as np

nproc = 96

# Primittive structure
perfectStruc = Structure([[0.5, 0.5, 0], [0.5, 0, 0.5], [0, 0.5, 0.5]])
perfectStruc.add_atom(0, 0, 0, 'Si')
perfectStruc.add_atom(0.25, 0.25, 0.25, 'Si')

# Building the (perfect) supercell
perfectStrucsc = supercell(perfectStruc, 4 * perfectStruc.cell)

# Primitive Cell Calculations ########################################################

# Relaxation
pwrelax = pwcalc()
pwrelax.name = "pcPara"
pwrelax.calc_type = "vc-relax"
pwrelax.restart_mode = "from_scratch"
pwrelax.pseudo_dir = os.path.expanduser("~/scratch/pseudo_pz-bhs/")
pwrelax.celldm = 10.7
pwrelax.ecutwfc = 45.0
pwrelax.ecutrho = 400.0
pwrelax.nbnd = len(perfectStruc) * 4
pwrelax.occupations = "fixed"