Exemplo n.º 1
0
def write_clr(f, atoms):
    """Write extra color and radius code to a CLR-file (for use with AtomEye).
       Hit F12 in AtomEye to use.
       See: http://mt.seas.upenn.edu/Archive/Graphics/A/
    """
    color   = None
    radius  = None
    if atoms.has('color'):
        color  = atoms.get_array('color')
    if atoms.has('radius'):
        radius  = atoms.get_array('radius')

    if color is None:
        color  = np.zeros([len(atoms),3], dtype=float)
        for a in atoms:
            color[a.index, :]  = default_color[a.get_symbol()]

    if radius is None:
        radius  = np.zeros(len(atoms), dtype=float)
        for a in atoms:
            radius[a.index]  = default_radius[a.get_symbol()]

    radius.shape = (-1, 1)

    if isinstance(f, str):
        f = paropen(f, 'w')   
    for c1, c2, c3, r in np.append(color, radius, axis=1):
        f.write('%f %f %f %f\n' % ( c1, c2, c3, r ))
Exemplo n.º 2
0
def write_xyz(fileobj, images):
    if isinstance(fileobj, str):
        fileobj = paropen(fileobj, 'w')

    if not isinstance(images, (list, tuple)):
        images = [images]

    symbols = images[0].get_chemical_symbols()
    natoms = len(symbols)
    for atoms in images:
        fileobj.write('%d\n' % natoms)
        Strcell = "Lattice=\""
        for c in atoms.get_cell()[:]:
            Strcell += ('%f %f %f ' % (c[0], c[1], c[2]))
        fileobj.write(Strcell[:-1] + "\" Properties=species:S:1:pos:R:3\n")

        for s, (x, y, z) in zip(symbols, atoms.get_positions()):
            fileobj.write('%-2s %22.15f %22.15f %22.15f\n' % (s, x, y, z))
Exemplo n.º 3
0
def write_cube(fileobj, atoms, data=None):
    if isinstance(fileobj, str):
        fileobj = paropen(fileobj, 'w')

    if isinstance(atoms, list):
        if len(atoms) > 1:
            raise ValueError('Can only write one configuration '
                             'to a cube file!')
        atoms = atoms[0]

    if data is None:
        data = np.ones((2, 2, 2))
    data = np.asarray(data)

    if data.dtype == complex:
        data = np.abs(data)

    fileobj.write('cube file from ase_ext.n')
    fileobj.write('OUTER LOOP: X, MIDDLE LOOP: Y, INNER LOOP: Z\n')

    cell = atoms.get_cell()
    shape = np.array(data.shape)

    corner = np.zeros(3)
    for i in range(3):
        if shape[i] % 2 == 1:
            shape[i] += 1
            corner += cell[i] / shape[i] / Bohr

    fileobj.write('%5d%12.6f%12.6f%12.6f\n' %
                  (len(atoms), corner[0], corner[1], corner[2]))

    for i in range(3):
        n = data.shape[i]
        d = cell[i] / shape[i] / Bohr
        fileobj.write('%5d%12.6f%12.6f%12.6f\n' % (n, d[0], d[1], d[2]))

    positions = atoms.get_positions() / Bohr
    numbers = atoms.get_atomic_numbers()
    for Z, (x, y, z) in zip(numbers, positions):
        fileobj.write('%5d%12.6f%12.6f%12.6f%12.6f\n' % (Z, 0.0, x, y, z))

    data.tofile(fileobj, sep='\n', format='%e')
Exemplo n.º 4
0
def write_mol2_charges(fileobj, images):
    if isinstance(fileobj, str):
        fileobj = paropen(fileobj, 'w')

    if not isinstance(images, (list, tuple)):
        images = [images]

    symbols = images[0].get_chemical_symbols()
    natoms = len(symbols)
    for atoms in images:
        fileobj.write('%d\n' % natoms)
        Strcell = ""
        for c in atoms.get_cell()[:]:
            Strcell += ('%f %f %f ' % (c[0], c[1], c[2]))
        fileobj.write(Strcell + "\n")

        for s, (x, y, z), c in zip(symbols, atoms.get_positions(),
                                   atoms.get_charges()):
            fileobj.write('%-2s %22.15f %22.15f %22.15f %22.15f\n' %
                          (s, x, y, z, c))
Exemplo n.º 5
0
def write_exciting(fileobj, images):
    """writes exciting input structure in XML
    
    Parameters
    ----------
    fileobj : File object
        Filehandle to which data should be written
    images : Atom Object or List of Atoms objects
        This function will write the first Atoms object to file 
    
    Returns
    -------
    """
    from lxml import etree as ET
    if isinstance(fileobj, str):
        fileobj = paropen(fileobj, 'w')
    root = atoms2etree(images)
    fileobj.write(ET.tostring(root, method='xml', 
                              pretty_print=True,
                              xml_declaration=True,
                              encoding='UTF-8'))
Exemplo n.º 6
0
    def initialize(self, file=None, initialwannier='random', seed=None):
        """Re-initialize current rotation matrix.

        Keywords are identical to those of the constructor.
        """
        Nw = self.nwannier
        Nb = self.nbands

        if file is not None:
            self.Z_dknn, self.U_kww, self.C_kul = load(paropen(file))
        elif initialwannier == 'bloch':
            # Set U and C to pick the lowest Bloch states
            self.U_kww = np.zeros((self.Nk, Nw, Nw), complex)
            self.C_kul = []
            for U, M, L in zip(self.U_kww, self.fixedstates_k, self.edf_k):
                U[:] = np.identity(Nw, complex)
                if L > 0:
                    self.C_kul.append(np.identity(Nb - M, complex)[:, :L])
                else:
                    self.C_kul.append([])
        elif initialwannier == 'random':
            # Set U and C to random (orthogonal) matrices
            self.U_kww = np.zeros((self.Nk, Nw, Nw), complex)
            self.C_kul = []
            for U, M, L in zip(self.U_kww, self.fixedstates_k, self.edf_k):
                U[:] = random_orthogonal_matrix(Nw, seed, real=False)
                if L > 0:
                    self.C_kul.append(
                        random_orthogonal_matrix(Nb - M, seed=seed,
                                                 real=False)[:, :L])
                else:
                    self.C_kul.append(np.array([]))
        else:
            # Use initial guess to determine U and C
            self.C_kul, self.U_kww = self.calc.initial_wannier(
                initialwannier, self.kptgrid, self.fixedstates_k, self.edf_k,
                self.spin)
        self.update()
Exemplo n.º 7
0
def write_pdb(fileobj, images):
    """Write images to PDB-file."""
    if isinstance(fileobj, str):
        fileobj = paropen(fileobj, 'w')

    if not isinstance(images, (list, tuple)):
        images = [images]

    format = 'ATOM  %5d %-4s              %8.3f%8.3f%8.3f  0.00  0.00\n'

    # RasMol complains if the atom index exceeds 100000. There might
    # be a limit of 5 digit numbers in this field.
    MAXNUM = 100000

    symbols = images[0].get_chemical_symbols()
    natoms = len(symbols)

    for atoms in images:
        fileobj.write('MODEL         1\n')
        p = atoms.get_positions()
        for a in range(natoms):
            x, y, z = p[a]
            fileobj.write(format % (a % MAXNUM, symbols[a], x, y, z))
        fileobj.write('ENDMDL\n')
Exemplo n.º 8
0
 def __init__(self, name):
     self.f = paropen(name + '.csv', 'w')
Exemplo n.º 9
0
def write_xsf(fileobj, images, data=None):
    if isinstance(fileobj, str):
        fileobj = paropen(fileobj, 'w')
        
    if not isinstance(images, (list, tuple)):
        images = [images]

    fileobj.write('ANIMSTEPS %d\n' % len(images))

    numbers = images[0].get_atomic_numbers()
    
    pbc = images[0].get_pbc()
    if pbc[2]:
        fileobj.write('CRYSTAL\n')
    elif pbc[1]:
        fileobj.write('SLAB\n')
    elif pbc[0]:
        fileobj.write('POLYMER\n')
    else:
        fileobj.write('MOLECULE\n')

    for n, atoms in enumerate(images):
        if pbc.any():
            fileobj.write('PRIMVEC %d\n' % (n + 1))
            cell = atoms.get_cell()
            for i in range(3):
                fileobj.write(' %.14f %.14f %.14f\n' % tuple(cell[i]))

        fileobj.write('PRIMCOORD %d\n' % (n + 1))

        # Get the forces if it's not too expensive:
        calc = atoms.get_calculator()
        if (calc is not None and
            (hasattr(calc, 'calculation_required') and
             not calc.calculation_required(atoms,
                                           ['energy', 'forces', 'stress']))):
            forces = atoms.get_forces()
        else:
            forces = None

        pos = atoms.get_positions()

        fileobj.write(' %d 1\n' % len(pos))
        for a in range(len(pos)):
            fileobj.write(' %2d' % numbers[a])
            fileobj.write(' %20.14f %20.14f %20.14f' % tuple(pos[a]))
            if forces is None:
                fileobj.write('\n')
            else:
                fileobj.write(' %20.14f %20.14f %20.14f\n' % tuple(forces[a]))
            
    if data is None:
        return

    fileobj.write('BEGIN_BLOCK_DATAGRID_3D\n')
    fileobj.write(' data\n')
    fileobj.write(' BEGIN_DATAGRID_3Dgrid#1\n')

    data = np.asarray(data)
    if data.dtype == complex:
        data = np.abs(data)

    shape = data.shape
    fileobj.write('  %d %d %d\n' % shape)

    cell = atoms.get_cell()
    origin = np.zeros(3)
    for i in range(3):
        if not pbc[i]:
            origin += cell[i] / shape[i]
    fileobj.write('  %f %f %f\n' % tuple(origin))

    for i in range(3):
        fileobj.write('  %f %f %f\n' %
                      tuple(cell[i] * (shape[i] + 1) / shape[i]))

    for x in range(shape[2]):
        for y in range(shape[1]):
            fileobj.write('   ')
            fileobj.write(' '.join(['%f' % d for d in data[x, y]]))
            fileobj.write('\n')
        fileobj.write('\n')

    fileobj.write(' END_DATAGRID_3D\n')
    fileobj.write('END_BLOCK_DATAGRID_3D\n')
Exemplo n.º 10
0
def write_cfg(f, a):
    """Write atomic configuration to a CFG-file (native AtomEye format).
       See: http://mt.seas.upenn.edu/Archive/Graphics/A/
    """
    if isinstance(f, str):
        f = paropen(f, 'w')

    f.write('Number of particles = %i\n' % len(a))
    f.write('A = 1.0 Angstrom\n')
    cell = a.get_cell()
    for i in range(3):
        for j in range(3):
            f.write('H0(%1.1i,%1.1i) = %f A\n' % ( i + 1, j + 1, cell[i, j] ))

    entry_count  = 3
    for x in list(a.arrays.keys()):
        if not x in cfg_default_fields:
            if len(a.get_array(x).shape) == 1:
                entry_count += 1
            else:
                entry_count += a.get_array(x).shape[1]

    vels = a.get_velocities()
    if type(vels) == np.ndarray:
        entry_count += 3
    else:
        f.write('.NO_VELOCITY.\n')

    f.write('entry_count = %i\n' % entry_count)

    i = 0
    for name, aux in a.arrays.items():
        if not name in cfg_default_fields:
            if len(aux.shape) == 1:
                f.write('auxiliary[%i] = %s [a.u.]\n' % ( i, name ))
                i += 1
            else:
                for j in range(aux.shape[1]):
                    f.write('auxiliary[%i] = %s_%1.1i [a.u.]\n' % ( i, name, j ))
                    i += 1

    # Distinct elements
    spos = a.get_scaled_positions()
    for i in a:
        el  = i.get_symbol()

        f.write('%f\n' % ase_ext.data.atomic_masses[ase.data.chemical_symbols.index(el)])
        f.write('%s\n' % el)

        x, y, z = spos[i.index, :]
        s =  '%e %e %e ' % ( x, y, z )

        if type(vels) == np.ndarray:
            vx, vy, vz  = vels[i.index, :]
            s  = s + ' %e %e %e ' % ( vx, vy, vz )

        for name, aux in a.arrays.items():
            if not name in cfg_default_fields:
                if len(aux.shape) == 1:
                    s += ' %e' % aux[i.index]
                else:
                    s += ( aux.shape[1]*' %e' ) % tuple(aux[i.index].tolist())
                         
        f.write('%s\n' % s)
Exemplo n.º 11
0
    def summary(self,
                method='standard',
                direction='central',
                T=298.,
                threshold=10,
                freq=None,
                log=sys.stdout):
        """Print a summary of the frequencies and derived thermodynamic
        properties. The equations for the calculation of the enthalpy and 
        entropy diverge for zero frequencies and a threshold value is used
        to ignore extremely low frequencies (default = 10 cm^-1).

        Parameters:

        method : string
            Can be 'standard'(default) or 'Frederiksen'.
        direction: string
            Direction for finite differences. Can be one of 'central'
            (default), 'forward', 'backward'.
        T : float
            Temperature in K at which thermodynamic properties are calculated.
        threshold : float
            Threshold value for low frequencies (default 10 cm^-1).
        freq : numpy array
            Optional. Can be used to create a summary on a set of known
            frequencies.
        destination : string or object with a .write() method
            Where to print the summary info. Default is to print to
            standard output. If another string is given, it creates that
            text file and writes the output to it. If a file object (or any
            object with a .write(string) function) is given, it writes to that
            file.

        Notes:

        The enthalpy and entropy calculations are very sensitive to low
        frequencies and the threshold value must be used with caution."""

        if isinstance(log, str):
            log = paropen(log, 'a')
        write = log.write

        s = 0.01 * units._e / units._c / units._hplanck
        if freq != None:
            hnu = freq / s
        else:
            hnu = self.get_energies(method, direction)
        write('---------------------\n')
        write('  #    meV     cm^-1\n')
        write('---------------------\n')
        for n, e in enumerate(hnu):
            if e.imag != 0:
                c = 'i'
                e = e.imag
            else:
                c = ' '
            write('%3d %6.1f%s  %7.1f%s\n' % (n, 1000 * e, c, s * e, c))
        write('---------------------\n')
        write('Zero-point energy: %.3f eV\n' %
              self.get_zero_point_energy(freq=freq))
        write('Thermodynamic properties at %.2f K\n' % T)
        write('Enthalpy: %.3f eV\n' % self.get_enthalpy(method=method,
                                                        direction=direction,
                                                        T=T,
                                                        threshold=threshold,
                                                        freq=freq))
        write('Entropy : %.3f meV/K\n' %
              (1E3 * self.get_entropy(method=method,
                                      direction=direction,
                                      T=T,
                                      threshold=threshold,
                                      freq=freq)))
        write('T*S     : %.3f eV\n' %
              (T * self.get_entropy(method=method,
                                    direction=direction,
                                    T=T,
                                    threshold=threshold,
                                    freq=freq)))
        write('E->G    : %.3f eV\n' %
              (self.get_zero_point_energy(freq=freq) + self.get_enthalpy(
                  method=method,
                  direction=direction,
                  T=T,
                  threshold=threshold,
                  freq=freq) - T * self.get_entropy(method=method,
                                                    direction=direction,
                                                    T=T,
                                                    threshold=threshold,
                                                    freq=freq)))
Exemplo n.º 12
0
 def __init__(self, logname, descriptions=1, verbosity=1):
     self.f = paropen(logname, 'w')
     unittest.TextTestRunner.__init__(self, self.f, descriptions, verbosity)
Exemplo n.º 13
0
 def save(self, file):
     """Save information on localization and rotation matrices to file."""
     dump((self.Z_dknn, self.U_kww, self.C_kul), paropen(file, 'w'))