예제 #1
0
def write_dftb(filename, atoms):
    """Method to write atom structure in DFTB+ format
       (gen format)
    """
    import numpy as np

    #sort
    atoms.set_masses()
    masses = atoms.get_masses()
    indexes = np.argsort(masses)
    atomsnew = Atoms()
    for i in indexes:
        atomsnew = atomsnew + atoms[i]

    if isinstance(filename, str):
        myfile = open(filename, 'w')
    else:  # Assume it's a 'file-like object'
        myfile = filename

    ispbc = atoms.get_pbc()
    box = atoms.get_cell()

    if (any(ispbc)):
        myfile.write('%8d %2s \n' % (len(atoms), 'S'))
    else:
        myfile.write('%8d %2s \n' % (len(atoms), 'C'))

    chemsym = atomsnew.get_chemical_symbols()
    allchem = ''
    for i in chemsym:
        if i not in allchem:
            allchem = allchem + i + ' '
    myfile.write(allchem + ' \n')

    coords = atomsnew.get_positions()
    itype = 1
    for iatom, coord in enumerate(coords):
        if iatom > 0:
            if chemsym[iatom] != chemsym[iatom - 1]:
                itype = itype + 1
        myfile.write('%5i%5i  %19.16f %19.16f %19.16f \n' \
                    %(iatom+1, itype,
                      coords[iatom][0], coords[iatom][1], coords[iatom][2]))
    # write box
    if (any(ispbc)):
        #dftb dummy
        myfile.write(' %19.16f %19.16f %19.16f \n' % (0, 0, 0))
        myfile.write(' %19.16f %19.16f %19.16f \n' %
                     (box[0][0], box[0][1], box[0][2]))
        myfile.write(' %19.16f %19.16f %19.16f \n' %
                     (box[1][0], box[1][1], box[1][2]))
        myfile.write(' %19.16f %19.16f %19.16f \n' %
                     (box[2][0], box[2][1], box[2][2]))

    if type(filename) == str:
        myfile.close()
예제 #2
0
def test_successful_run():
    """test run and parent run"""
    with db.connect('database.db') as fdb:
        data = {'runner': copy(runner)}
        id_ = fdb.write(Atoms(), data=data, status='submit:terminal:test')
        data['runner']['parents'] = [id_]
        id_1 = fdb.write(Atoms(), data=data, status='submit:terminal:test')
        # waiting on next pass
        data = {'runner': copy(runner)}
        data['runner']['tasks'][0][1] = 'sleep 7'
        id_2 = fdb.write(Atoms(), data=data, status='submit:terminal:test')
        # test max jobs and keep run
        data['runner']['tasks'][0][1] = 'sleep 1'
        data['runner']['keep_run'] = True
        id_3 = fdb.write(Atoms(), data=data, status='submit:terminal:test')

    run = TerminalRunner('test', max_jobs=2)
    run.spool(_endless=False)
    fdb = db.connect('database.db')
    assert fdb.get(id_).status == 'running:terminal:test'
    assert fdb.get(id_1).status == 'submit:terminal:test'
    assert fdb.get(id_2).status == 'running:terminal:test'
    assert fdb.get(id_3).status == 'submit:terminal:test'
    time.sleep(5)
    run.spool(_endless=False)
    assert fdb.get(id_).status == 'done:terminal:test'
    assert fdb.get(id_1).status == 'running:terminal:test'
    assert fdb.get(id_2).status == 'running:terminal:test'
    assert fdb.get(id_3).status == 'submit:terminal:test'
    time.sleep(5)
    run.spool(_endless=False)
    assert fdb.get(id_).status == 'done:terminal:test'
    assert fdb.get(id_1).status == 'done:terminal:test'
    assert fdb.get(id_2).status == 'done:terminal:test'
    assert fdb.get(id_3).status == 'running:terminal:test'
    time.sleep(5)
    run.spool(_endless=False)
    assert fdb.get(id_3).status == 'done:terminal:test'

    assert not str(id_) in os.listdir(), 'no cleanup after done'
    assert not str(id_1) in os.listdir(), 'no cleanup after done'
    assert not str(id_2) in os.listdir(), 'no cleanup after done'
    assert str(id_3) in os.listdir(), 'keep_run failed'
예제 #3
0
파일: bulk.py 프로젝트: shuchingou/ase
def _build_rhl(name, a, alpha, basis):
    from ase.lattice import RHL
    lat = RHL(a, alpha)
    cell = lat.tocell()
    if basis is None:
        # RHL: Given by A&M as scaled coordinates "x" of cell.sum(0):
        basis_x = reference_states[atomic_numbers[name]]['basis_x']
        basis = basis_x[:, None].repeat(3, axis=1)
    natoms = len(basis)
    return Atoms([name] * natoms, cell=cell, scaled_positions=basis, pbc=True)
예제 #4
0
	def write_xyz(self):
		# writes a xyz file 
		# the import is only needed here
		from ase.io import write 
		bohr = 0.5291772105638411
		# unit conversion from bohr to angstroem 
		pos = np.array(self.calc.positions())*bohr 
                sym = self.get_chemical_symbols()
                atoms = Atoms(sym,pos)
		write('pyeff.xyz',atoms,'xyz')
예제 #5
0
	def view(self):
		# use ase.gui for visualization 
		# the import is only needed here 
		from ase.visualize import view
		bohr = 0.5291772105638411
                # unit conversion from bohr to angstroem 
		pos = np.array(self.calc.positions())*bohr 
		sym = self.get_chemical_symbols()
		atoms = Atoms(sym,pos)
		view(atoms)
예제 #6
0
파일: HEA.py 프로젝트: kaitrepte/porE
def get_ase(f_file, p_insert_red, s_insert_red):
    """ Combine framework and insert atoms to one ase structure
        f_file : framework file name
        p_insert_red: positions of reduced inserted species
        s_insert_red: symbols of reduced inserted species
    """
    struct = read(f_file)
    insert = Atoms(s_insert_red, p_insert_red)
    struct_tot = struct + insert
    view(struct_tot)
예제 #7
0
def read_pdb(fileobj, index=-1):
    """Read PDB files.

    The format is assumed to follow the description given in
    http://www.wwpdb.org/documentation/format32/sect8.html and
    http://www.wwpdb.org/documentation/format32/sect9.html."""
    if isinstance(fileobj, str):
        fileobj = open(fileobj)

    images = []
    orig = np.identity(3)
    trans = np.zeros(3)
    atoms = Atoms()
    for line in fileobj.readlines():
        if line.startswith('CRYST1'):
            cellpar = [float(word) for word in line[6:54].split()]
            atoms.set_cell(cellpar_to_cell(cellpar))
        for c in range(3):
            if line.startswith('ORIGX' + '123'[c]):
                pars = [float(word) for word in line[10:55].split()]
                orig[c] = pars[:3]
                trans[c] = pars[3]

        if line.startswith('ATOM') or line.startswith('HETATM'):
            try:
                # Atom name is arbitrary and does not necessarily contain the element symbol.
                # The specification requires the element symbol to be in columns 77+78.
                symbol = line[76:78].strip().lower().capitalize()
                words = line[30:55].split()
                position = np.array(
                    [float(words[0]),
                     float(words[1]),
                     float(words[2])])
                position = np.dot(orig, position) + trans
                atoms.append(Atom(symbol, position))
            except:
                pass
        if line.startswith('ENDMDL'):
            images.append(atoms)
            atoms = Atoms()
    if len(images) == 0:
        images.append(atoms)
    return images[index]
예제 #8
0
def test_write_dftb_velocities():
    atoms = Atoms('H2')

    velocities = np.linspace(-1, 2, num=6).reshape(2, 3)
    atoms.set_velocities(velocities)

    write_dftb_velocities(atoms, filename='velocities.txt')

    velocities = np.loadtxt('velocities.txt') * Bohr / AUT
    assert np.allclose(velocities, atoms.get_velocities())
예제 #9
0
def read_proteindatabank(fileobj, index=-1):
    """Read PDB files."""

    if isinstance(fileobj, basestring):
        fileobj = open(fileobj)

    images = []
    orig = np.identity(3)
    trans = np.zeros(3)
    atoms = Atoms()
    for line in fileobj.readlines():
        if line.startswith('CRYST1'):
            cellpar = [float(word) for word in line[6:54].split()]
            atoms.set_cell(cellpar_to_cell(cellpar))
            atoms.pbc = True
        for c in range(3):
            if line.startswith('ORIGX' + '123'[c]):
                pars = [float(word) for word in line[10:55].split()]
                orig[c] = pars[:3]
                trans[c] = pars[3]

        if line.startswith('ATOM') or line.startswith('HETATM'):
            try:
                # Atom name is arbitrary and does not necessarily
                # contain the element symbol.  The specification
                # requires the element symbol to be in columns 77+78.
                symbol = line[76:78].strip().lower().capitalize()
                words = line[30:55].split()
                position = np.array(
                    [float(words[0]),
                     float(words[1]),
                     float(words[2])])
                position = np.dot(orig, position) + trans
                atoms.append(Atom(symbol, position))
            except Exception as ex:
                warnings.warn(
                    'Discarding atom when reading PDB file: {}'.format(ex))
        if line.startswith('ENDMDL'):
            images.append(atoms)
            atoms = Atoms()
    if len(images) == 0:
        images.append(atoms)
    return images[index]
예제 #10
0
def graphene(formula='C2', a=2.460, size=(1, 1, 1), vacuum=None):
    """Create a graphene monolayer structure."""
    cell = [[a, 0, 0], [-a / 2, a * 3**0.5 / 2, 0], [0, 0, 0]]
    basis = [[0, 0, 0], [2./3, 1./3, 0]]
    atoms = Atoms(formula, cell=cell, pbc=(1, 1, 0))
    atoms.set_scaled_positions(basis)
    if vacuum is not None:
        atoms.center(vacuum, axis=2)
    atoms = atoms.repeat(size)
    return atoms
예제 #11
0
async def dumb_fio_task(cid, calc, atcor, ian, cell=None, pbc=None):
    import numpy as np
    from ase.atoms import Atoms
    mol = Atoms(numbers=ian, positions=atcor, cell=cell, pbc=pbc)
    mol.calc = calc
    mol._calc.write_input(mol, ['energy', 'forces'], [])
    return (
        0.0,
        np.zeros_like(atcor),
    )
예제 #12
0
    def test_co_kernel_derivative(self):
        direction = np.array([1., 2., 3.])
        direction /= np.linalg.norm(direction)
        atoms = Atoms(['C', 'O'],
                      positions=np.array([-0.5 * direction, 0.5 * direction]))
        atoms.set_calculator(EMT())

        def to_radius(x):
            xyzs = x.get_positions()
            r = np.sqrt(np.sum((xyzs[1, :] - xyzs[0, :])**2))
            dr = np.zeros((1, 6))
            dr[0, 0] = (xyzs[0, 0] - xyzs[1, 0]) / r
            dr[0, 1] = (xyzs[0, 1] - xyzs[1, 1]) / r
            dr[0, 2] = (xyzs[0, 2] - xyzs[1, 2]) / r
            dr[0, 3] = (xyzs[1, 0] - xyzs[0, 0]) / r
            dr[0, 4] = (xyzs[1, 1] - xyzs[0, 1]) / r
            dr[0, 5] = (xyzs[1, 2] - xyzs[0, 2]) / r
            return [r], dr

        kernel = RBFKernel(constant=100.0, length_scale=0.23)
        calc = NCGPRCalculator(input_transform=to_radius,
                               kernel=kernel,
                               C1=1e8,
                               C2=1e8,
                               opt_restarts=0)
        calc.add_data(atoms)
        K = calc.build_kernel_matrix()
        K_num = np.zeros_like(K)
        # kernel value is not tested:
        K_num[0, 0] = K[0, 0]
        x0 = atoms.get_positions()
        dx = 1e-4

        def K_fun(x, y):
            a = np.array([to_radius(Atoms(['C', 'O'], positions=x))[0]])
            b = np.array([to_radius(Atoms(['C', 'O'], positions=y))[0]])
            return calc.kernel(a, b, dx=True, dy=True)[0, 0]

        for i in range(6):
            dxi = np.zeros(6)
            dxi[i] = dx
            dxi = dxi.reshape((2, 3))
            # Test first derivative
            K_num[1 + i, 0] = self.num_dx_forth_order(K_fun, x0, x0, dxi)

            for j in range(6):
                dxj = np.zeros(6)
                dxj[j] = dx
                dxj = dxj.reshape((2, 3))
                K_num[1 + i, 1 + j] = self.num_dxdy_forth_order(
                    K_fun, x0, x0, dxi, dxj)

            # Test symmetry of derivatives
            K_num[0, 1 + i] = self.num_dy_forth_order(K_fun, x0, x0, dxi)
        np.testing.assert_allclose(K, K_num, atol=1E-5)
예제 #13
0
파일: etsf.py 프로젝트: essil1/ase-laser
 def read_atoms(self):
     var = self.nc.variables
     cell = var['primitive_vectors']
     assert cell.units == 'atomic units'
     species = var['atom_species'][:]
     spos = var['reduced_atom_positions'][:]
     numbers = var['atomic_numbers'][:]
     return Atoms(numbers=numbers[species - 1],
                  scaled_positions=spos,
                  cell=cell[:] * Bohr,
                  pbc=True)
예제 #14
0
def build_atoms(positions, method, cell, alat):
    """Creates the atoms for a quantum espresso in file."""
    if method != 'crystal':
        raise NotImplementedError('Only supported for crystal method of '
                                  'ATOMIC_POSITIONS, not %s.' % method)
    atoms = Atoms()
    for el, (x, y, z) in positions:
        atoms.append(Atom(el, (x, y, z)))
    cell *= f2f(alat) * units.Bohr
    atoms.set_cell(cell, scale_atoms=True)
    return atoms
예제 #15
0
def build_crystal(a, b, c, al, be, ga):
    from ase.atoms import Atoms
    if (al+be+ga > 350): return
    if (al+be < 1.1*ga): return
    if (al+ga < 1.1*be): return
    if (be+ga < 1.1*al): return

    atms = Atoms('Mg', positions=[(0, 0, 0)],
                 cell=[a, b, c, al, be, ga], pbc=True)
    atms._test_data = [a, b, c, al*pi/180, be*pi/180, ga*pi/180]
    return atms
예제 #16
0
파일: gaussian.py 프로젝트: grhawk/ASE
def read_gaussian_out(filename, index=-1, quantity='atoms'):
    """"Interface to GaussianReader and returns various quantities"""
    energy = 0.0

    data = GR(filename)[index]

    formula = data['Chemical_formula']
    positions = np.array(data['Positions'])
    method = data['Method']
    version = data['Version']

    if method.lower()[1:] in allowed_dft_functionals:
        method = 'HF'

    atoms = Atoms(formula, positions=positions)

    for key, value in data.items():
        if (key in method):
            energy = value

    try:
        # Re-read in the log file
        f = open(filename, 'r')
        lines = f.readlines()
        f.close()

        forces = list()
        for n, line in enumerate(lines):
            if ('Forces (Hartrees/Bohr)' in line):
                for j in range(len(atoms)):
                    forces += [[
                        float(lines[n + j + 3].split()[2]),
                        float(lines[n + j + 3].split()[3]),
                        float(lines[n + j + 3].split()[4])
                    ]]
        convert = ase.units.Hartree / ase.units.Bohr
        forces = np.array(forces) * convert
    except:
        forces = None

    energy *= ase.units.Hartree  # Convert the energy from a.u. to eV
    calc = SinglePointCalculator(atoms, energy=energy, forces=forces)
    atoms.set_calculator(calc)

    if (quantity == 'energy'):
        return energy
    elif (quantity == 'forces'):
        return forces
    elif (quantity == 'dipole'):
        return data['Dipole']
    elif (quantity == 'atoms'):
        return atoms
    elif (quantity == 'version'):
        return version
def getAseAtomsObjFromPylibUCell(inpUCell):
    scaledPositions = [x[:-1] for x in inpUCell.fractCoords
                       ]  #We remove the atom symbol from the end
    symbols = inpUCell._elementList  #Will be None if never set, which is fine
    lattVects = inpUCell.lattVects
    pbcs = True
    outObj = Atoms(scaled_positions=scaledPositions,
                   symbols=symbols,
                   cell=lattVects,
                   pbc=pbcs)
    return outObj
예제 #18
0
def test_read_dftb_explicit():
    x = 1.356773
    positions = [[0., 0., 0.], [x, x, x]]
    cell = [[2 * x, 2 * x, 0.], [0., 2 * x, 2 * x], [2 * x, 0., 2 * x]]
    atoms = Atoms('GaAs', cell=cell, positions=positions, pbc=True)

    atoms_new = read_dftb(fd_explicit)
    assert np.all(atoms_new.numbers == atoms.numbers)
    assert np.allclose(atoms_new.positions, atoms.positions)
    assert np.all(atoms_new.pbc == atoms.pbc)
    assert np.allclose(atoms_new.cell, atoms.cell)
예제 #19
0
파일: structure.py 프로젝트: adbX/ase
def _orthorhombic_bulk(name, x, a, covera=None):
    if x == 'fcc':
        b = a / sqrt(2)
        atoms = Atoms(2 * name,
                      cell=(b, b, a),
                      pbc=True,
                      scaled_positions=[(0, 0, 0), (0.5, 0.5, 0.5)])
    elif x == 'bcc':
        atoms = Atoms(2 * name,
                      cell=(a, a, a),
                      pbc=True,
                      scaled_positions=[(0, 0, 0), (0.5, 0.5, 0.5)])
    elif x == 'hcp':
        atoms = Atoms(4 * name,
                      cell=(a, a * sqrt(3), covera * a),
                      scaled_positions=[(0, 0, 0), (0.5, 0.5, 0),
                                        (0.5, 1.0 / 6.0, 0.5),
                                        (0, 2.0 / 3.0, 0.5)],
                      pbc=True)
    elif x == 'diamond':
        atoms = _orthorhombic_bulk(2 * name, 'zincblende', a)
    elif x == 'zincblende':
        s1, s2 = string2symbols(name)
        b = a / sqrt(2)
        atoms = Atoms(2 * name,
                      cell=(b, b, a),
                      pbc=True,
                      scaled_positions=[(0, 0, 0), (0.5, 0, 0.25),
                                        (0.5, 0.5, 0.5), (0, 0.5, 0.75)])
    elif x == 'rocksalt':
        s1, s2 = string2symbols(name)
        b = a / sqrt(2)
        atoms = Atoms(2 * name,
                      cell=(b, b, a),
                      pbc=True,
                      scaled_positions=[(0, 0, 0), (0.5, 0.5, 0),
                                        (0.5, 0.5, 0.5), (0, 0, 0.5)])
    else:
        raise RuntimeError

    return atoms
예제 #20
0
def unpack_reftraj_str_to_atoms(data):
    lines = data.split('\n')
    label = int(lines[0])
    n_atoms = int(lines[1])
    at = Atoms(symbols=[' ']*n_atoms, cell=np.eye(3))
    at.info['label'] = label
    for i in range(3):
        at.cell[:, i] = [float(x) for x in lines[i].split()]
    for i, line in enumerate(lines[4:]):
        t = [float(x) for x in line.split()]
        at.positions[i, :] = np.dot(at.cell.T, t)
    return at
예제 #21
0
 def __get_optimised_molecule_and_energy_from_xyz(self, fileobj):
     lines = fileobj.readlines()
     natoms = int(lines[0])
     total_energy_kcal_mol = float(lines[1].split()[1]) * Hartree * mol / kcal  # store energy in kcal/mol
     symbols = []
     positions = []
     for line in lines[2:2 + natoms]:
         symbol, x, y, z = line.split()[:4]
         symbol = symbol.lower().capitalize()
         symbols.append(symbol)
         positions.append([float(x), float(y), float(z)])
     return Atoms(symbols=symbols, positions=positions), total_energy_kcal_mol
예제 #22
0
파일: turbomole.py 프로젝트: slabanja/ase
def read_turbomole(filename='coord'):
    """Method to read turbomole coord file
    
    coords in bohr, atom types in lowercase, format:
    $coord
    x y z atomtype 
    x y z atomtype f
    $end
    Above 'f' means a fixed atom.
    """
    from ase import Atoms, Atom
    from ase.constraints import FixAtoms

    if isinstance(filename, str):
        f = open(filename)

    lines = f.readlines()
    atoms_pos = []
    atom_symbols = []
    dollar_count=0
    myconstraints=[]
    for line in lines:
        if ('$' in line):
            dollar_count = dollar_count + 1
            if (dollar_count >= 2):
                break
        else:
            x, y, z, symbolraw = line.split()[:4]
            symbolshort=symbolraw.strip()
            symbol=symbolshort[0].upper()+symbolshort[1:].lower()
            #print symbol
            atom_symbols.append(symbol)
            atoms_pos.append([float(x)*Bohr, float(y)*Bohr, float(z)*Bohr])
            cols = line.split()
            if (len(cols) == 5):
                fixedstr = line.split()[4].strip()
                if (fixedstr == "f"):
                    myconstraints.append(True)
                else:
                    myconstraints.append(False)
            else:
                myconstraints.append(False)
            
    if type(filename) == str:
        f.close()

    atoms = Atoms(positions = atoms_pos, symbols = atom_symbols, pbc = False)
    c = FixAtoms(myconstraints)
    atoms.set_constraint(c)
    #print c
    

    return atoms
예제 #23
0
 def as_ase(self):
     atoms = Atoms(positions=self.positions,
                   cell=self.cell,
                   pbc=self.pbc,
                   numbers=self.numbers)
     atoms.calc = self.calc  # DONE: e, f
     if atoms.calc is not None:
         atoms.calc.atoms = atoms
     vel = self.get_velocities()
     if vel is not None:
         atoms.set_velocities(vel)
     return atoms
예제 #24
0
 def createCH3(self):
     rot = xRotation(2 / 3 * pi)
     mpow = np.linalg.matrix_power
     h_coords = array((-cos(c_angle), 0, sin(c_angle))) * ch_length
     pos = [
         np.zeros((3)), h_coords,
         dot(rot, h_coords),
         dot(mpow(rot, 2), h_coords)
     ]
     atoms = Atoms('CH3', pos)
     atoms.info['bonds'] = Bonds(atoms, pairs=((0, 1), (0, 2), (0, 3)))
     return atoms
예제 #25
0
    def __getitem__(self, i=-1):
        if isinstance(i, slice):
            return [self[j] for j in range(*i.indices(len(self)))]

        N = len(self.offsets)
        if 0 <= i < N:
            self.fd.seek(self.offsets[i])
            try:
                d = pickle.load(self.fd, encoding='bytes')
                d = {
                    k.decode() if isinstance(k, bytes) else k: v
                    for k, v in d.items()
                }
            except EOFError:
                raise IndexError
            if i == N - 1:
                self.offsets.append(self.fd.tell())
            charges = d.get('charges')
            magmoms = d.get('magmoms')
            try:
                constraints = [c.copy() for c in self.constraints]
            except:
                constraints = []
                warnings.warn('Constraints did not unpickle correctly.')
            atoms = Atoms(positions=d['positions'],
                          numbers=self.numbers,
                          cell=d['cell'],
                          momenta=d['momenta'],
                          magmoms=magmoms,
                          charges=charges,
                          tags=self.tags,
                          masses=self.masses,
                          pbc=self.pbc,
                          info=unstringnify_info(d.get('info', {})),
                          constraint=constraints)
            if 'energy' in d:
                calc = SinglePointCalculator(atoms,
                                             energy=d.get('energy', None),
                                             forces=d.get('forces', None),
                                             stress=d.get('stress', None),
                                             magmoms=magmoms)
                atoms.set_calculator(calc)
            return atoms

        if i >= N:
            for j in range(N - 1, i + 1):
                atoms = self[j]
            return atoms

        i = len(self) + i
        if i < 0:
            raise IndexError('Trajectory index out of range.')
        return self[i]
예제 #26
0
def test_atoms_getitem():
    w = Atoms('H2O',
              positions=[[2.264, 0.639, 0.876], [0.792, 0.955, 0.608],
                         [1.347, 0.487, 1.234]],
              cell=[3, 3, 3],
              pbc=True)

    with pytest.raises(IndexError):
        w[True, False]

    assert (w[0, 1] == w[True, True, False])
    assert (w[0, 1] == w[0:2])
예제 #27
0
파일: ag.py 프로젝트: uu1477/MyAse
    def run(opt, args):
        images = Images()

        if opt.aneb:
            opt.image_number = '-1'

        if len(args) > 0:
            from ase.io import string2index
            try:
                images.read(args, string2index(opt.image_number))
            except IOError as e:
                if len(e.args) == 1:
                    parser.error(e.args[0])
                else:
                    parser.error(e.args[1] + ': ' + e.filename)
        else:
            images.initialize([Atoms()])

        if opt.interpolate:
            images.interpolate(opt.interpolate)

        if opt.aneb:
            images.aneb()

        if opt.repeat != '1':
            r = opt.repeat.split(',')
            if len(r) == 1:
                r = 3 * r
            images.repeat_images([int(c) for c in r])

        if opt.radii_scale:
            images.set_radii(opt.radii_scale)

        if opt.output is not None:
            images.write(opt.output,
                         rotations=opt.rotations,
                         show_unit_cell=opt.show_unit_cell)
            opt.terminal = True

        if opt.terminal:
            if opt.graph is not None:
                data = images.graph(opt.graph)
                for line in data.T:
                    for x in line:
                        print(x, end=' ')
                    print()
        else:
            from ase.gui.gui import GUI
            import ase.gui.gtkexcepthook
            ase
            gui = GUI(images, opt.rotations, opt.show_unit_cell, opt.bonds)
            gui.run(opt.graph)
예제 #28
0
파일: test_ase.py 프로젝트: awvwgk/tblite
def test_gfn1_xtb_3d():
    """Test ASE interface to GFN1-xTB"""
    thr = 5.0e-6

    atoms = Atoms(
        symbols="C4O8",
        positions=np.array([
            [0.9441259872, 0.9437851680, 0.9543505632],
            [3.7179966528, 0.9556570368, 3.7316862240],
            [3.7159517376, 3.7149292800, 0.9692330016],
            [0.9529872864, 3.7220864832, 3.7296981120],
            [1.6213905408, 1.6190616096, 1.6313879040],
            [0.2656685664, 0.2694175776, 0.2776540416],
            [4.3914553920, 1.6346256864, 3.0545920000],
            [3.0440834880, 0.2764611744, 4.4080419264],
            [4.3910577696, 3.0416409504, 0.2881058304],
            [3.0399936576, 4.3879335936, 1.6497353376],
            [0.2741322432, 4.4003734944, 3.0573754368],
            [1.6312174944, 3.0434586528, 4.4023048032],
        ]),
        cell=np.array([5.68032, 5.68032, 5.68032]),
        pbc=np.array([True, True, True]),
    )
    forces = np.array([
        [-0.08831700, -0.07001294, -0.07468651],
        [-0.03556765, -0.02242341, +0.03047788],
        [+0.03228896, -0.03948204, -0.02892694],
        [-0.02569098, +0.03373080, -0.03161988],
        [-1.90306812, -1.90236730, -1.90612450],
        [+1.98861177, +1.96958105, +1.97849378],
        [-1.88898997, -1.93509024, +1.91692369],
        [+1.92988257, +1.95061533, -1.94116843],
        [-1.93844982, +1.93069254, +1.96026641],
        [+1.91146115, -1.88620597, -1.93901862],
        [+1.94936349, -1.94760369, +1.92150003],
        [-1.93152440, +1.91856587, -1.88611692],
    ])
    stress = np.array([
        +4.49045792e-02,
        +4.49168887e-02,
        +4.49566951e-02,
        +3.38245641e-05,
        +1.52117499e-05,
        +1.13328271e-04,
    ])

    atoms.calc = TBLite(method="GFN1-xTB")
    assert atoms.pbc.all()

    assert approx(atoms.get_potential_energy(), abs=thr) == -1257.0801067985549
    assert approx(atoms.get_forces(), abs=thr) == forces
    assert approx(atoms.get_stress(), abs=thr) == stress
예제 #29
0
 def __init__(self, sisl_hamiltonian, spin=None):
     self.ham = sisl_hamiltonian
     # k2Rfactor : H(k) = \int_R H(R) * e^(k2Rfactor * k.R)
     self.R2kfactor = -2.0j*np.pi   # 
     if spin=='up':
         spin=0
     elif spin=='down':
         spin=1
     if spin not in [ None, 0, 1, 'merge']:
         raise ValueError("spin should be None/0/1, but is %s"%spin)
     self.spin=spin
     self.orbs=[]
     self.orb_dict=defaultdict(lambda:[])
     g=self.ham._geometry
     _atoms=self.ham._geometry._atoms
     atomic_numbers=[]
     self.positions=g.xyz
     self.cell=np.array(g.sc.cell)
     for ia, a in enumerate(_atoms):
         atomic_numbers.append(a.Z)
     self.atoms=Atoms(numbers=atomic_numbers, cell=self.cell, positions=self.positions)
     sdict=list(symbol_number(self.atoms).keys())
     if self.ham.spin.is_colinear and (self.spin in [0,1]):
         for ia, a in enumerate(_atoms):
             symnum=sdict[ia]
             try:
                 orb_names=[f"{symnum}|{x.name()}|up" for x in a.orbital]
             except:
                 orb_names=[f"{symnum}|{x.name()}|up" for x in a.orbitals]
             self.orbs+=orb_names
             self.orb_dict[ia]+=orb_names
         self.norb = len(self.orbs)
         self.nbasis=self.norb
     elif self.ham.spin.is_spinorbit or self.spin=='merge':
         for spin in {'up', 'down'}:
             for ia, a in enumerate(_atoms):
                 symnum=sdict[ia]
                 orb_names=[]
                 try:
                     for x in a.orbital:  # sisl < v0.10
                         orb_names.append(f"{symnum}|{x.name()}|{spin}")
                 except:
                     for x in a.orbitals:  # sisl >= v0.10
                         orb_names.append(f"{symnum}|{x.name()}|{spin}")
                 self.orbs+=orb_names
                 self.orb_dict[ia]+=orb_names
         #print(self.orb_dict)
         self.norb=len(self.orbs)//2
         #print(f"Norb: {self.norb}")
         self.nbasis= len(self.orbs)
     else:
         raise ValueError("The hamiltonian should be either spin-orbit or colinear")
예제 #30
0
def read_crystal(filename):
    """Method to read coordinates form 'fort.34' files
    additionally read information about
    periodic boundary condition
    """
    with open(filename, 'r') as myfile:
        lines = myfile.readlines()

    atoms_pos = []
    anumber_list = []
    my_pbc = [False, False, False]
    mycell = []

    if float(lines[4]) != 1:
        raise ValueError('High symmetry geometry is not allowed.')

    if float(lines[1].split()[0]) < 500.0:
        cell = [float(c) for c in lines[1].split()]
        mycell.append(cell)
        my_pbc[0] = True
    else:
        mycell.append([1, 0, 0])

    if float(lines[2].split()[1]) < 500.0:
        cell = [float(c) for c in lines[2].split()]
        mycell.append(cell)
        my_pbc[1] = True
    else:
        mycell.append([0, 1, 0])

    if float(lines[3].split()[2]) < 500.0:
        cell = [float(c) for c in lines[3].split()]
        mycell.append(cell)
        my_pbc[2] = True
    else:
        mycell.append([0, 0, 1])

    natoms = int(lines[9].split()[0])
    for i in range(natoms):
        index = 10 + i
        anum = int(lines[index].split()[0]) % 100
        anumber_list.append(anum)

        position = [float(p) for p in lines[index].split()[1:]]
        atoms_pos.append(position)

    atoms = Atoms(positions=atoms_pos,
                  numbers=anumber_list,
                  cell=mycell,
                  pbc=my_pbc)

    return atoms