Exemplo n.º 1
0
    def __init__(self, restart=None, ignore_bad_restart_file=False,
                 label='g09', atoms=None, scratch=None, ioplist=list(),
                 basisfile=None, extra=None, addsec=None, **kwargs):

        """Constructs a Gaussian-calculator object.

        extra: any extra text to be included in the input card
        addsec: a list of strings to be included as "additional sections"

        """

        FileIOCalculator.__init__(self, restart, ignore_bad_restart_file,
                                  label, atoms, **kwargs)

        if restart is not None:
            try:
                self.read(restart)
            except ReadError:
                if ignore_bad_restart_file:
                    self.reset()
                else:
                    raise

        self.ioplist = ioplist
        self.scratch = scratch
        self.basisfile = basisfile

        # store extra parameters
        self.extra = extra
        self.addsec = addsec
Exemplo n.º 2
0
Arquivo: dftb.py Projeto: grhawk/ASE
    def write_input(self, atoms, properties=None, system_changes=None):
#        self.Ham_AtomsDependProp(atoms)
        from ase.io import write
        FileIOCalculator.write_input(\
            self, atoms, properties, system_changes)
        self.write_dftb_in()
        write('geo_end.gen', atoms)
Exemplo n.º 3
0
Arquivo: orca.py Projeto: PHOTOX/fuase
    def calculate(self, atoms=None, properties=['energy'],
                  system_changes=all_changes):

        if 'forces' in properties:
            self.parameters.task = 'gradient'

        FileIOCalculator.calculate(self, atoms, properties, system_changes)
Exemplo n.º 4
0
Arquivo: mopac.py Projeto: grhawk/ASE
    def __init__(self, label='mopac', restart=None, atoms=None, ignore_bad_restart_file=None,**kwargs):
        
        # set initial values
        self.default_parameters = dict(
            restart = 0,
            spin = 1,
            opt = False,
            functional = 'PM6',
            job_type = ['NOANCI','GRADIENTS', '1SCF'],
            relscf = 0.1,
            charge = 0
        )
        
        # save label and atoms
        self.label = label
        self.atoms = atoms

        FileIOCalculator.__init__(self, restart, ignore_bad_restart_file, label, atoms, **kwargs)

        #the input file written only once
        # self.write_mopac_in(self.atoms)

        # initialize the results
        self.version = None
        self.energy_zero = None
        self.energy_free = None
        self.forces = None
        self.charges = None
        self.stress = None
        
        # initialize the results
        self.occupations = None
Exemplo n.º 5
0
    def __init__(self, restart=None, ignore_bad_restart_file=False,
                 label='mopac', atoms=None, **kwargs):
        """Construct MOPAC-calculator object.

        Parameters
        ==========
        label: str
            Prefix for filenames (label.mop, label.out, ...)

        Examples
        ========
        Use default values to do a single SCF calculation and print
        the forces (task='1SCF GRADIENTS')

        >>> from ase.build import molecule
        >>> from ase.calculators.mopac import MOPAC
        >>> atoms = molecule('O2')
        >>> atoms.calc = MOPAC(label='O2')
        >>> atoms.get_potential_energy()
        >>> eigs = atoms.calc.get_eigenvalues()
        >>> somos = atoms.calc.get_somo_levels()
        >>> h**o, lumo = atoms.calc.get_homo_lumo_levels()

        Use the internal geometry optimization of Mopac
        >>> atoms = molecule('H2')
        >>> atoms.calc = MOPAC(label='H2', task='GRADIENTS')
        >>> atoms.get_potential_energy()

        Read in and start from output file
        >>> atoms = MOPAC.read_atoms('H2')
        >>> atoms.calc.get_homo_lumo_levels()

        """
        FileIOCalculator.__init__(self, restart, ignore_bad_restart_file,
                                  label, atoms, **kwargs)
Exemplo n.º 6
0
    def write_input(self, atoms, properties=None, system_changes=None):
        FileIOCalculator.write_input(self, atoms, properties, system_changes)
        p = self.parameters

        # Build string to hold .mop input file:
        s = p.method + ' ' + p.task + ' '

        if p.relscf:
            s += 'RELSCF={0} '.format(p.relscf)

        # Write charge:
        charge = atoms.get_initial_charges().sum()
        if charge != 0:
            s += 'CHARGE={0} '.format(int(round(charge)))

        magmom = int(round(abs(atoms.get_initial_magnetic_moments().sum())))
        if magmom:
            s += (['DOUBLET', 'TRIPLET', 'QUARTET', 'QUINTET'][magmom - 1] +
                  ' UHF ')

        s += '\nTitle: ASE calculation\n\n'

        # Write coordinates:
        for xyz, symbol in zip(atoms.positions, atoms.get_chemical_symbols()):
            s += ' {0:2} {1} 1 {2} 1 {3} 1\n'.format(symbol, *xyz)

        for v, p in zip(atoms.cell, atoms.pbc):
            if p:
                s += 'Tv {0} {1} {2}\n'.format(*v)

        with open(self.label + '.mop', 'w') as f:
            f.write(s)
Exemplo n.º 7
0
    def __init__(self, restart=None, ignore_bad_restart_file=False,
                 label='gamess_us', atoms=None, delold=False, **kwargs):
        """Construct GAMESS-US-calculator object."""
        FileIOCalculator.__init__(self, restart, ignore_bad_restart_file,
                                  label, atoms, **kwargs)

        self.delold = delold
Exemplo n.º 8
0
Arquivo: aims.py Projeto: PHOTOX/fuase
    def __init__(self, restart=None, ignore_bad_restart_file=False,
                 label=os.curdir, atoms=None, cubes=None, radmul=None, tier=None, **kwargs):
        """Construct FHI-aims calculator.
        
        The keyword arguments (kwargs) can be one of the ASE standard
        keywords: 'xc', 'kpts' and 'smearing' or any of FHI-aims'
        native keywords.
        
        Additional arguments:

        cubes: AimsCube object
            Cube file specification.
        radmul: int
            Set radial multiplier for the basis set of all atomic species.
        tier: int or array of ints
            Set basis set tier for all atomic species.
        """
        try:
            self.outfilename = kwargs.get('run_command').split()[-1]
        except:
            self.outfilename = 'aims.out'
        
        FileIOCalculator.__init__(self, restart, ignore_bad_restart_file,
                                  label, atoms, 
                                  command = kwargs.get('run_command'),
                                  **kwargs)
        self.cubes = cubes
        self.radmul = radmul
        self.tier = tier
Exemplo n.º 9
0
 def write_input(self, atoms, properties=None, system_changes=None):
     FileIOCalculator.write_input(self, atoms, properties,
                                  system_changes)
     struct = crys.atoms2struct(atoms)
     self.cell = common.str_arr(struct.cell)
     self.kpoints = pwscf.kpoints_str_pwin(kpts2mp(atoms, self.kpts))
     if isinstance(self.pp, types.StringType):
         pseudos = ["%s.%s" %(sym, self.pp) for sym in struct.symbols_unique]
     else: 
         assert len(self.pp) == struct.ntypat
         pseudos = []
         for sym in struct.symbols_unique:
             for ppi in self.pp:
                 if ppi.startswith(sym):
                     pseudos.append(ppi)
                     break
     assert len(pseudos) == struct.ntypat
     self.atspec = pwscf.atspec_str(symbols=struct.symbols_unique,
                                    masses=struct.mass_unique,
                                    pseudos=pseudos)
     self.atpos = pwscf.atpos_str(symbols=struct.symbols,
                                  coords=struct.coords_frac)
     self.natoms = struct.natoms
     self.ntyp = struct.ntypat
     
     if self.backup:
         for fn in [self.infile, self.outfile]:
             if os.path.exists(fn):
                 common.backup(fn)
     common.file_write(self.infile, self.fill_infile_templ())
Exemplo n.º 10
0
    def __init__(self, label='dftbddmc', atoms=None, dftbdict={}, ddmcdict={}, **kwargs):
        """Construct a DFTB+ and a dDMC calculator.
        """

        os.environ['ASE_DFTBDDMC_COMMAND'] = ''

        self.label = label
        self.dftbdict = dftbdict
        self.ddmcdict = ddmcdict
        
        ddmc_default_parameters = {}
        ddmc_default_parameters['param_a'] = 1.85705835084132
        ddmc_default_parameters['param_b'] = 1.01824853175310
        ddmc_default_parameters['param_c'] = 23.0
        ddmc_default_parameters['dftype'] = 3
        ddmc_default_parameters['tagtype'] = 'dftbp'

        for param in ddmc_default_parameters.keys():
            if not param in self.ddmcdict.keys():
                self.ddmcdict[param] = ddmc_default_parameters[param]


        restart = None
        ignore_bad_restart_file = None
        FileIOCalculator.__init__(self, restart, ignore_bad_restart_file,
                                  label, atoms, **kwargs)

        self.dftb_calc = Dftb(label=self.label)
        self.ddmc_calc = dDMC(label=self.label)
Exemplo n.º 11
0
    def __init__(self, label='mopacddmc', atoms=None, mopacdict={}, ddmcdict={}, **kwargs):
        """Construct a MOPAC and a dDMC calculator.
        """

        os.environ['ASE_MOPACDDMC_COMMAND'] = ''

        self.label = label
        self.mopacdict = mopacdict
        self.ddmcdict = ddmcdict

        ddmc_default_parameters = {}
        ddmc_default_parameters['param_a'] = 1.53014262236515
        ddmc_default_parameters['param_b'] = 1.04216259309481
        ddmc_default_parameters['param_c'] = 23.0
        ddmc_default_parameters['param_d'] = 1.84166256639050
        ddmc_default_parameters['dftype'] = 4
        ddmc_default_parameters['tagtype'] = 'column'

        for param in ddmc_default_parameters.keys():
            if not param in self.ddmcdict.keys():
                self.ddmcdict[param] = ddmc_default_parameters[param]


        restart = None
        ignore_bad_restart_file = None
        FileIOCalculator.__init__(self, restart, ignore_bad_restart_file,
                                  label, atoms, **kwargs)
Exemplo n.º 12
0
    def read_results(self):
        FileIOCalculator.read_results(self)

        onetep_file = self.label + '.out'

        warnings = []

        try:
            out = paropen(onetep_file, 'r')
        except IOError:
            raise ReadError('Could not open output file "%s"' % onetep_file)

        line = out.readline()
        while line:
            if '| Total' in line:
                self.results['energy'] = Hartree * float(line.split()[-2])
            elif ('Element  Atom         Cartesian components (Eh/a)'
                  in line):
                self._read_forces(out)
            elif 'warn' in line.lower():
                warnings.append(line)
            line = out.readline()

        if warnings:
            warn('WARNING: %s contains warnings' % onetep_file)
            for warning in warnings:
                warn(warning)
Exemplo n.º 13
0
    def __init__(self,
                 label='ase_dftd3',  # Label for dftd3 output files
                 command=None,  # Command for running dftd3
                 dft=None,  # DFT calculator
                 atoms=None,
                 **kwargs):

        self.dft = None
        FileIOCalculator.__init__(self, restart=None,
                                  ignore_bad_restart_file=False,
                                  label=label,
                                  atoms=atoms,
                                  command=command,
                                  dft=dft,
                                  **kwargs)

        # If the user is running DFTD3 with another DFT calculator, such as
        # GPAW, the DFT portion of the calculation should take much longer.
        # If we only checked for a valid command in self.calculate, the DFT
        # calculation would run before we realize that we don't know how
        # to run dftd3. So, we check here at initialization time, to avoid
        # wasting the user's time.
        if self.command is None:
            raise RuntimeError("Don't know how to run DFTD3! Please "
                               'set the ASE_DFTD3_COMMAND environment '
                               'variable, or explicitly pass the path '
                               'to the dftd3 executable to the D3 calculator!')
        if isinstance(self.command, str):
            self.command = self.command.split()
Exemplo n.º 14
0
 def write_input(self, atoms, properties=None, system_changes=None):
     FileIOCalculator.write_input(self, atoms, properties=properties,
                                  system_changes=system_changes)
     txt = generate_input(atoms, self.kwargs)
     fd = open(self._getpath('inp'), 'w')
     fd.write(txt)
     fd.close()
Exemplo n.º 15
0
    def write_input(self, atoms, properties=None, system_changes=None):
        FileIOCalculator.write_input(self, atoms, properties, system_changes)
        p = self.parameters

        # Build string to hold .gin input file:
        s = p.keywords
        s += '\ntitle\nASE calculation\nend\n\n'

        if all(self.atoms.pbc):
            cell_params = self.atoms.get_cell_lengths_and_angles()
            s += 'cell\n{0} {1} {2} {3} {4} {5}\n'.format(*cell_params)
            s += 'frac\n'
            coords = self.atoms.get_scaled_positions()
        else:
            s += 'cart\n'
            coords = self.atoms.get_positions()

        if self.conditions is not None:
            c = self.conditions
            labels = c.get_atoms_labels()
            self.atom_types = c.get_atom_types()
        else:
            labels = self.atoms.get_chemical_symbols()

        for xyz, symbol in zip(coords, labels):
            s += ' {0:2} core {1}  {2}  {3}\n'.format(symbol, *xyz)
            if symbol in p.shel:
                s += ' {0:2} shel {1}  {2}  {3}\n'.format(symbol, *xyz)

        s += '\nlibrary {0}\n'.format(p.library)
        if p.options:
            for t in p.options:
                s += '%s\n' % t
        with open(self.prefix + '.gin', 'w') as f:
            f.write(s)
Exemplo n.º 16
0
    def calculate(self,
                  atoms=None,
                  properties=['energy'],
                  system_changes=all_changes):
        """Capture the RuntimeError from FileIOCalculator.calculate
        and add a little debug information from the Siesta output.

        See base FileIocalculator for documentation.
        """

        try:
            FileIOCalculator.calculate(
                self,
                atoms=atoms,
                properties=properties,
                system_changes=system_changes)

        # Here a test to check if the potential are in the right place!!!
        except RuntimeError as e:
            try:
                with open(self.label + '.out', 'r') as f:
                    lines = f.readlines()
                debug_lines = 10
                print('##### %d last lines of the Siesta output' % debug_lines)
                for line in lines[-20:]:
                    print(line.strip())
                print('##### end of siesta output')
                raise e
            except:
                raise e
Exemplo n.º 17
0
    def __init__(self, restart=None, ignore_bad_restart_file=False,
                 label='abinit', atoms=None, scratch=None, **kwargs):
        """Construct ABINIT-calculator object.

        Parameters
        ==========
        label: str
            Prefix to use for filenames (label.in, label.txt, ...).
            Default is 'abinit'.

        Examples
        ========
        Use default values:

        >>> h = Atoms('H', calculator=Abinit(ecut=200, toldfe=0.001))
        >>> h.center(vacuum=3.0)
        >>> e = h.get_potential_energy()

        """

        self.scratch = scratch
        
        self.species = None
        self.ppp_list = None

        FileIOCalculator.__init__(self, restart, ignore_bad_restart_file,
                                  label, atoms, **kwargs)
Exemplo n.º 18
0
 def write_input(self, atoms=None, properties=None, system_changes=None):
     """
     Write input file(s). This is called by FileIOCalculator just before 
     it executes the external command.
     """
     # This is restarted calculation do not write anything.
     if self.restart : return
     
     self.set(prefix=self.prefix)
     self.atoms2params()
     FileIOCalculator.write_input(self, atoms, properties, system_changes)
     
     if set(['energy','stress','forces','bands','edos']) & set(properties) :
         write_pw_in(self.directory, atoms, self.parameters)
     if 'bands' in properties :
         write_bands_in(self.directory, atoms, self.parameters)
     if 'edos' in properties:
         write_edos_in(self.directory, atoms, self.parameters)
     if 'd2' in properties :
         write_ph_in(self.directory, atoms, self.parameters)
         write_q2r_in(self.directory, atoms, self.parameters)
     if 'frequencies' in properties :
         write_matdyn_in(self.directory, atoms, self.parameters)
     if 'phdos' in properties:
         write_phdos_in(self.directory, atoms, self.parameters)
Exemplo n.º 19
0
    def __init__(self, restart=None, ignore_bad_restart_file=False,
                 label='dmol_calc/tmp', atoms=None, **kwargs):
        """ Construct DMol3 calculator. """
        FileIOCalculator.__init__(self, restart, ignore_bad_restart_file,
                                  label, atoms, **kwargs)

        # tracks if DMol transformed coordinate system
        self.internal_transformation = False
Exemplo n.º 20
0
    def __init__(self,
                 restart=None,
                 label=None,
                 atoms=None,
                 command='octopus',
                 ignore_troublesome_keywords=None,
                 check_keywords=True,
                 _autofix_outputformats=False,
                 **kwargs):
        """Create Octopus calculator.

        Label is always taken as a subdirectory.
        Restart is taken to be a label."""

        # XXX support the specially defined ASE parameters,
        # "smear" etc.

        # We run oct-help to get a list of all keywords.
        # This makes us able to robustly construct the input file
        # in the face of changing octopus versions, and also of
        # early partial verification of user input.
        if check_keywords:
            try:
                octopus_keywords = get_octopus_keywords()
            except OSError as err:
                msg = ('Could not obtain Octopus keyword list from '
                       'command oct-help: %s.  Octopus not installed in '
                       'accordance with expectations.  '
                       'Use check_octopus_keywords=False to override.' % err)
                raise OSError(msg)
        else:
            octopus_keywords = None
        self.octopus_keywords = octopus_keywords
        self._autofix_outputformats = _autofix_outputformats

        if restart is not None:
            if label is not None and restart != label:
                raise ValueError('restart and label are mutually exclusive '
                                 'or must at the very least coincide.')
            label = restart

        if label is None:
            label = 'ink-pool'

        if ignore_troublesome_keywords:
            trouble = set(self.troublesome_keywords)
            for keyword in ignore_troublesome_keywords:
                trouble.remove(keyword)
            self.troublesome_keywords = trouble

        self.kwargs = {}

        FileIOCalculator.__init__(self, restart=restart,
                                  ignore_bad_restart_file=False,
                                  label=label,
                                  atoms=atoms,
                                  command=command, **kwargs)
Exemplo n.º 21
0
    def read_results(self):
        FileIOCalculator.read(self, self.label)
        if not os.path.isfile(self.label + '.got'):
            raise ReadError

        with open(self.label + '.got') as f:
            lines = f.readlines()

        cycles = -1
        self.optimized = None
        for i, line in enumerate(lines):
            m = re.match(r'\s*Total lattice energy\s*=\s*(\S+)\s*eV', line)
            if m:
                energy = float(m.group(1))
                self.results['energy'] = energy
                self.results['free_energy'] = energy

            elif line.find('Optimisation achieved') != -1:
                self.optimized = True

            elif line.find('Final Gnorm') != -1:
                self.Gnorm = float(line.split()[-1])

            elif line.find('Cycle:') != -1:
                cycles += 1

            elif line.find('Final Cartesian derivatives') != -1:
                s = i + 5
                forces = []
                while(True):
                    s = s + 1
                    if lines[s].find("------------") != -1:
                        break
                    if lines[s].find(" s ") != -1:
                        continue
                    g = lines[s].split()[3:6]
                    G = [-float(x) * eV / Ang for x in g]
                    forces.append(G)
                forces = np.array(forces)
                self.results['forces'] = forces

            elif line.find('Final cartesian coordinates of atoms') != -1:
                s = i + 5
                positions = []
                while True:
                    s = s + 1
                    if lines[s].find("------------") != -1:
                        break
                    if lines[s].find(" s ") != -1:
                        continue
                    xyz = lines[s].split()[3:6]
                    XYZ = [float(x) * Ang for x in xyz]
                    positions.append(XYZ)
                positions = np.array(positions)
                self.atoms.set_positions(positions)

        self.steps = cycles
Exemplo n.º 22
0
    def read(self, label):
        FileIOCalculator.read(self, label)
        if not os.path.isfile(self.label + '.out'):
            raise ReadError

        self.parameters = Parameters.read(self.label + '.ase')
        self.atoms = read_gamess_us_input(self.label + '.inp')

        self.read_results()
Exemplo n.º 23
0
Arquivo: dftb.py Projeto: grhawk/ASE
    def __init__(self, restart=None, ignore_bad_restart_file=False,
                 label='dftb', atoms=None, kpts=None,
                 **kwargs):
        """Construct a DFTB+ calculator.
        """

        from ase.dft.kpoints import monkhorst_pack

        if 'DFTB_PREFIX' in os.environ:
            slako_dir = os.environ['DFTB_PREFIX']
        else:
            slako_dir = './'

        self.default_parameters = dict(
            Hamiltonian_='DFTB',
            Driver_='ConjugateGradient',
            Driver_MaxForceComponent='1E-4',
            Driver_ConvergentForcesOnly = 'No',
            Driver_MaxSteps=0,
            Hamiltonian_SlaterKosterFiles_='Type2FileNames',
            Hamiltonian_SlaterKosterFiles_Prefix=slako_dir,
            Hamiltonian_SlaterKosterFiles_Separator='"-"',
            Hamiltonian_SlaterKosterFiles_Suffix='".skf"',
            Hamiltonian_SCC = 'No',
            Hamiltonian_Eigensolver = 'RelativelyRobust{}'
            )

        FileIOCalculator.__init__(self, restart, ignore_bad_restart_file,
                                  label, atoms, **kwargs)

        self.kpts = kpts
        # kpoint stuff by ase
        if self.kpts != None:
            mpgrid = kpts2mp(atoms, self.kpts)
            mp = monkhorst_pack(mpgrid)
            initkey = 'Hamiltonian_KPointsAndWeights'
            self.parameters[initkey + '_'] = ''
            for i, imp in enumerate(mp):
                key = initkey + '_empty' + str(i)
                self.parameters[key] = str(mp[i]).strip('[]') + ' 1.0'

        #the input file written only once
        if restart == None:
            self.write_dftb_in()
        else:
            if os.path.exists(restart):
                os.system('cp ' + restart + ' dftb_in.hsd')
            if not os.path.exists('dftb_in.hsd'):
                raise IOError('No file "dftb_in.hsd", use restart=None')

        #indexes for the result file
        self.first_time = True
        self.index_energy = None
        self.index_force_begin = None
        self.index_force_end = None
        self.index_charge_begin = None
        self.index_charge_end = None
Exemplo n.º 24
0
    def __init__(self, **kwargs):
        parameters = self.get_default_parameters()
        functional, authors = parameters['xc'].split('.')
        parameters['xc'] = XC(functional=functional, authors=authors)
        parameters.update(kwargs)

        FileIOCalculator.__init__(
                self,
                **parameters
                )
Exemplo n.º 25
0
 def run_calculation(self, atoms, properties, system_changes):
     '''
     Hook for the more involved remote calculator to link into.
     Actually invokes the parent calculation routine.
     '''
     # This is restarted calculation do not write anything.
     # Nothing to do - just return.
     if self.restart : return
     
     FileIOCalculator.calculate(self, atoms, properties, system_changes)
Exemplo n.º 26
0
 def calculate(self, atoms, properties=['energy'], system_changes=[]):
     """ overrides parent calculate() method for testing reason
         should not be in prod. version """
     try:
         FileIOCalculator.calculate(self, atoms, properties, system_changes)
         #~ self.read_results()           # to test
         #~ self.results['energy'] = self.residual()  # to test
     except RuntimeError:
         print('ERROR: RuntimeError')
         self.results['energy'] = 999  # big value
Exemplo n.º 27
0
    def read(self, label):
        """Read a onetep .out file into the current instance."""

        FileIOCalculator.read(self, label)

        onetep_file = self.label + '.out'

        warnings = []

        try:
            out = paropen(onetep_file, 'r')
        except IOError:
            raise ReadError('Could not open output file "%s"' % onetep_file)

        # keep track of what we've read in
        read_lattice = False
        read_species = False
        read_positions = False

        line = out.readline()

        if self.atoms is None:
            self.atoms = Atoms()
            self.atoms.calc = self

        while line:
            clean_line = line.strip().lower()
            if '%block lattice_cart' in clean_line:
                self._read_lattice(out)
                read_lattice = True
            elif '%block species_pot' in clean_line:
                self._read_species_pot(out)
            elif '%block species' in clean_line:
                self._read_species(out)
                read_species = True
            elif '%block positions_abs' in clean_line:
                self._read_positions(out)
                read_positions = True
            elif '%block species_cond' in clean_line:
                self._read_species_cond(out)
            elif 'warn' in line.lower():
                warnings.append(line)
            line = out.readline()
        out.close()

        if warnings:
            warn('WARNING: %s contains warnings' % onetep_file)
            for warning in warnings:
                warn(warning)

        if not (read_lattice and read_species and read_positions):
            raise ReadError('Failed to read in essential calculation'
                            ' data from output file "%s"' % onetep_file)

        self.read_results(label)
Exemplo n.º 28
0
Arquivo: abinit.py Projeto: grhawk/ASE
    def __init__(self, restart=None, ignore_bad_restart_file=False,
                 label='abinit', atoms=None, scratch=None, **kwargs):
        """Construct ABINIT-calculator object.

        Parameters
        ==========
        label: str
            Prefix to use for filenames (label.in, label.txt, ...).
            Default is 'abinit'.
        xc: str
            Exchange-correlation functional.  Must be one of LDA, PBE,
            revPBE, RPBE.
        kpts: list of three int
            Monkhost-Pack sampling.
        nbands: int
            Number of bands.
            For the values of occopt not equal to 0 or 2, nbands can be omitted.
        nstep: int
            Number of self-consistent field STEPS.
        width: float
            Fermi-distribution width in eV.
            Default is 0.04 Hartree.
        ecut: float
            Planewave cutoff energy in eV.
            No default.
        charge: float
            Total charge of the system.
            Default is 0.
        npulayit: int
            Number of old densities to use for Pulay mixing.
        diemix: float
            Mixing parameter between zero and one for density mixing.
        diemac: float
            Model DIElectric MACroscopic constant.
            The value of diemac should usually be bigger than 1.0d0,
            on physical grounds. If you let diemac to its default value,
            you might even never obtain the self-consistent convergence!

        Examples
        ========
        Use default values:

        >>> h = Atoms('H', calculator=Abinit(ecut=200, toldfe=0.001))
        >>> h.center(vacuum=3.0)
        >>> e = h.get_potential_energy()

        """

        self.scratch = scratch
        
        self.species = None
        self.ppp_list = None

        FileIOCalculator.__init__(self, restart, ignore_bad_restart_file,
                                  label, atoms, **kwargs)
Exemplo n.º 29
0
Arquivo: elk.py Projeto: PHOTOX/fuase
 def __init__(self, restart=None, ignore_bad_restart_file=False,
              label=os.curdir, atoms=None, **kwargs):
     """Construct ELK calculator.
     
     The keyword arguments (kwargs) can be one of the ASE standard
     keywords: 'xc', 'kpts' and 'smearing' or any of ELK'
     native keywords.
     """
     
     FileIOCalculator.__init__(self, restart, ignore_bad_restart_file,
                               label, atoms, **kwargs)
Exemplo n.º 30
0
    def write_input(self, atoms, properties=None, system_changes=None):
        """Write input (fdf)-file.
        See calculator.py for further details.

        Parameters:
            - atoms        : The Atoms object to write.
            - properties   : The properties which should be calculated.
            - system_changes : List of properties changed since last run.
        """
        # Call base calculator.
        FileIOCalculator.write_input(
            self,
            atoms=atoms,
            properties=properties,
            system_changes=system_changes)

        if system_changes is None and properties is None:
            return

        filename = self.label + '.fdf'

        # On any changes, remove all analysis files.
        if system_changes is not None:
            self.remove_analysis()

        # Start writing the file.
        with open(filename, 'w') as f:
            # First write explicitly given options to
            # allow the user to overwrite anything.
            self._write_fdf_arguments(f)

            # Use the saved density matrix if only 'cell' and 'positions'
            # haved changes.
            if (system_changes is None or
                ('numbers' not in system_changes and
                 'initial_magmoms' not in system_changes and
                 'initial_charges' not in system_changes)):
                f.write(format_fdf('DM.UseSaveDM', True))

            # Save density.
            if 'density' in properties:
                f.write(format_fdf('SaveRho', True))

            # Write system name and label.
            f.write(format_fdf('SystemName', self.label))
            f.write(format_fdf('SystemLabel', self.label))

            # Force siesta to return error on no convergence.
            f.write(format_fdf('SCFMustConverge', True))

            # Write the rest.
            self._write_species(f, atoms)
            self._write_kpts(f)
            self._write_structure(f, atoms)
Exemplo n.º 31
0
    def __init__(self, **kwargs):
        """ASE interface to the deMon code.

        Parameters:
            label    : str. relative path to the run directory
            atoms    : The Atoms onject
            command  : str. Command to run deMon. If not present the environment varable DEMON_COMMAND will be used
            restart  : str. Relative path to ASE restart directory for parameters and atoms object and results
            basis_path  : str. Relative path to the directory containing BASIS, AUXIS, ECPS, MCPS and AUGMENT
            ignore_bad_restart_file : bool. Ignore broken or missing ASE restart files
                                    By default, it is an error if the restart
                                    file is missing or broken.
            deMon_restart_path  : str. Relative path to the deMon restart dir
            title : str. Title in the deMon input file.
            scftype : str. Type of scf
            forces  : bool. If True a force calculation will be enforced.
            dipole  : bool. If True a dipole calculation will be enforced
            xc      : str. xc-functional
            guess   : str. guess for initial density and wave functions
            print_out : str|list. Options for the printing in deMon
            basis : dict. Definition of basis sets.
            ecps  : dict. Definition of ECPs.
            mcps  : dict. Definition of MCPs.
            auxis  : dict. Definition of AUXIS,
            augment : dict. Definition of AUGMENT.
            input_arguments: dict. Explicitly given input arguments. The key is the input keyword
                             and the value is either a str, a list of str (will be written on the same line as the keyword),
                             or a list of lists of str (first list is written on the first line, the others on following lines.)
                                                          
                            
        """
        parameters = Parameters_deMon(**kwargs)

        # Setup the run command
        command = parameters['command']
        if command is None:
            command = os.environ.get('DEMON_COMMAND')

        if command is None:
            mess = 'The "DEMON_COMMAND" environment is not defined.'
            raise ValueError(mess)
        else:
            parameters['command'] = command

        # Call the base class.
        FileIOCalculator.__init__(self, **parameters)
Exemplo n.º 32
0
 def check_state(self, atoms):
     system_changes = FileIOCalculator.check_state(self, atoms)
     # Ignore unit cell and boundary conditions:
     if 'cell' in system_changes:
         system_changes.remove('cell')
     if 'pbc' in system_changes:
         system_changes.remove('pbc')
     return system_changes
Exemplo n.º 33
0
    def read(self, label=None):
        if label is None:
            label = self.label
        FileIOCalculator.read(self, label)
        geometry = os.path.join(self.directory, 'geometry.in')
        control = os.path.join(self.directory, 'control.in')

        for filename in [geometry, control, self.out]:
            if not os.path.isfile(filename):
                raise ReadError

        self.atoms, symmetry_block = read_aims(geometry, True)
        self.parameters = Parameters.read(
            os.path.join(self.directory, 'parameters.ase'))
        if symmetry_block:
            self.parameters["symmetry_block"] = symmetry_block
        self.read_results()
Exemplo n.º 34
0
    def write_input(self, atoms, properties=None, system_changes=None):
        '''Initializes input parameters and xyz files. If force calculation is requested, add Force section to parameters if not exists.

        Parameters
        ==========
        atoms: ASE atoms object.
        properties: List of properties to be calculated. Should be element of self.implemented_properties.
        system_chages: Ignored.

        '''
        FileIOCalculator.write_input(self, atoms, properties, system_changes)
        with open(self.label + '.inp', 'w') as inputfile:
            xyz_name = "{}.xyz".format(self.label)
            atoms.write(xyz_name)

            run_parameters = self.prepare_input(xyz_name, properties)
            self.write_acemolecule_input(inputfile, run_parameters)
Exemplo n.º 35
0
    def read(self, label):
        FileIOCalculator.read(self, label)
        filename = self.label + ".log"

        with open(filename, 'r') as fd:
            lines = fd.readlines()
        if 'WARNING' in lines:
            raise ReadError(
                "Not convergy energy in log file {}.".format(filename))
        if '! total energy' not in lines:
            raise ReadError("Wrong ACE-Molecule log file {}.".format(filename))

        if not os.path.isfile(filename):
            raise ReadError(
                "Wrong ACE-Molecule input file {}.".format(filename))

        self.read_results()
Exemplo n.º 36
0
 def check_state(self, atoms):
     system_changes = FileIOCalculator.check_state(self, atoms)
     # Ignore unit cell for molecules:
     if not atoms.pbc.any() and 'cell' in system_changes:
         system_changes.remove('cell')
     if self.pcpot and self.pcpot.mmpositions is not None:
         system_changes.append('positions')
     return system_changes
Exemplo n.º 37
0
    def __init__(self, restart=None, ignore_bad_restart_file=False,
                 label=os.curdir, atoms=None, cubes=None, **kwargs):
        """Construct FHI-aims calculator.
        
        The keyword arguments (kwargs) can be one of the ASE standard
        keywords: 'xc', 'kpts' and 'smearing' or any of FHI-aims'
        native keywords.
        
        Additional arguments:

        cubes: AimsCube object
            Cube file specification.
        """

        FileIOCalculator.__init__(self, restart, ignore_bad_restart_file,
                                  label, atoms, **kwargs)
        self.cubes = cubes
Exemplo n.º 38
0
    def write_input(self, atoms=None, properties=None, system_changes=None):
        """Write input parameters to input file."""

        FileIOCalculator.write_input(self, atoms, properties, system_changes)
        #print self.parameters
        myfile = open(self.label + '.mdp', 'w')
        for key, val in self.parameters.items():
            if val is not None:
                if (self.params_doc.get(key) == None):
                    docstring = ''
                else:
                    docstring = self.params_doc[key]
                myfile.write('%-35s = %s ; %s\n' \
                            % (key, val, ';' + docstring))
        myfile.close()
        if self.freeze_qm:
            self.add_freeze_group()
Exemplo n.º 39
0
    def __init__(self,
                 restart=None,
                 ignore_bad_restart_file=FileIOCalculator._deprecated,
                 label='./openmx',
                 atoms=None,
                 command=None,
                 mpi=None,
                 pbs=None,
                 **kwargs):

        # Initialize and put the default parameters.
        self.initialize_pbs(pbs)
        self.initialize_mpi(mpi)
        self.initialize_output_setting(**kwargs)

        FileIOCalculator.__init__(self, restart, ignore_bad_restart_file,
                                  label, atoms, command, **kwargs)
Exemplo n.º 40
0
    def __init__(self, restart=None, ignore_bad_restart_file=False,
                 label='qchem', scratch=None, np=1, nt=1, pbs=False,
                 basisfile=None, ecpfile=None, atoms=None, **kwargs):
        """
        The scratch directory, number of processor and threads as well as a few
        other command line options can be set using the arguments explained
        below. The remaining kwargs are copied as options to the input file.
        The calculator will convert these options to lower case for storage
        and convert back to upper case (Q-Chem standard) when writing the
        input file.

        scratch: str
            path of the scratch directory
        np: int
            number of processors for the -np command line flag
        nt: int
            number of threads for the -nt command line flag
        pbs: boolean
            command line flag for pbs scheduler (see Q-Chem manual)
        basisfile: str
            path to file containing the basis. Use in combination with
            basis='gen' keyword argument.
        ecpfile: str
            path to file containing the effective core potential. Use in
            combination with ecp='gen' keyword argument.
        """

        FileIOCalculator.__init__(self, restart, ignore_bad_restart_file,
                                  label, atoms, **kwargs)

        # Augment the command by various flags
        if pbs:
            self.command = 'qchem -pbs '
        else:
            self.command = 'qchem '
        if np != 1:
            self.command += '-np %d ' % np
        if nt != 1:
            self.command += '-nt %d ' % nt
        self.command += 'PREFIX.inp PREFIX.out'
        if scratch is not None:
            self.command += ' %s' % scratch

        self.basisfile = basisfile
        self.ecpfile = ecpfile
Exemplo n.º 41
0
Arquivo: pmdrun.py Projeto: medgbb/nap
    def write_input(self, atoms, properties=None, system_changes=None):
        """Write input parameters to in.pmd file."""

        FileIOCalculator.write_input(self, atoms, properties, system_changes)

        if self.label == 'pmd':
            infname = 'in.pmd'
            # write_pmd(atoms,fname='pmdini',specorder=self.specorder)
            nsys = NAPSystem.from_ase_atoms(atoms, specorder=self.specorder)
            nsys.write_pmd(fname='pmdini')

        with open(infname, 'w') as f:
            fmvs, ifmvs = get_fmvs(atoms)
            for i in range(len(fmvs)):
                for ii in range(3):
                    if fmvs[i][ii] > 0.1 and not self.dimension[ii]:
                        fmvs[i][ii] = 0.0
            f.write(get_input_txt(self.parameters, fmvs))
Exemplo n.º 42
0
    def check_state(self, atoms):
        system_changes = FileIOCalculator.check_state(self, atoms)

        ignore = ['cell', 'pbc']
        for change in system_changes:
            if change in ignore:
                system_changes.remove(change)

        return system_changes
Exemplo n.º 43
0
 def __init__(self,
              restart=None,
              ignore_bad_restart_file=False,
              label=os.curdir,
              atoms=None,
              **kwargs):
     """ Constructor """
     FileIOCalculator.__init__(self, restart, ignore_bad_restart_file,
                               label, atoms, **kwargs)
     valid_args = ('atoms', 'fods', 'SYMBOL', 'ISYMGEN', 'basis', 'e_up',
                   'e_dn', 'calc', 'mode', 'xc', 'extra', 'FRMORB')
     # set any additional keyword arguments
     for arg, val in self.parameters.items():
         if arg in valid_args:
             setattr(self, arg, val)
         else:
             raise RuntimeError('unknown keyword arg "%s" : not in %s' %
                                (arg, valid_args))
    def write_input(self, atoms, properties=None, system_changes=None):
        FileIOCalculator.write_input(self, atoms, properties, system_changes)

        # Prepare perm and scratch directories
        perm = os.path.abspath(self.parameters.get('perm', self.label))
        scratch = os.path.abspath(self.parameters.get('scratch', self.label))
        os.makedirs(perm, exist_ok=True)
        os.makedirs(scratch, exist_ok=True)

        #io.write(self.label + '.nwi', atoms, properties=properties,
        #         label=self.label, **self.parameters)
        fd = open(self.label + '.nwi', 'w')
        write_nwchem_in(fd,
                        atoms,
                        properties=properties,
                        label=self.label,
                        **self.parameters)
        fd.close()
Exemplo n.º 45
0
    def write_input(self,
                    atoms,
                    properties=None,
                    system_changes=None,
                    ghosts=None):
        FileIOCalculator.write_input(self, atoms, properties, system_changes)

        have_lattice_vectors = atoms.pbc.any()
        have_k_grid = ('k_grid' in self.parameters
                       or 'kpts' in self.parameters)
        if have_lattice_vectors and not have_k_grid:
            raise RuntimeError('Found lattice vectors but no k-grid!')
        if not have_lattice_vectors and have_k_grid:
            raise RuntimeError('Found k-grid but no lattice vectors!')
        write_aims(os.path.join(self.directory, 'geometry.in'), atoms, ghosts)
        self.write_control(atoms, os.path.join(self.directory, 'control.in'))
        self.write_species(atoms, os.path.join(self.directory, 'control.in'))
        self.parameters.write(os.path.join(self.directory, 'parameters.ase'))
Exemplo n.º 46
0
    def __init__(self,
                 restart=None,
                 ignore_bad_restart_file=False,
                 label='wannier',
                 atoms=None,
                 **kwargs):
        """
        All options for wannier90 are copied verbatim to the input file

        """
        FileIOCalculator.__init__(self, restart, ignore_bad_restart_file,
                                  label, atoms, **kwargs)

        if atoms is not None:
            self.atoms = atoms
            self.atoms.calc = self

        self.calc = None
Exemplo n.º 47
0
    def set(self, **kwargs):
        xc = kwargs.get('xc')
        if xc:
            kwargs['xc'] = {'LDA': 'pw-lda', 'PBE': 'pbe'}.get(xc, xc)

        changed_parameters = FileIOCalculator.set(self, **kwargs)

        if changed_parameters:
            self.reset()
        return changed_parameters
Exemplo n.º 48
0
    def write_input(self, atoms, properties=None, system_changes=None):
        from ase.io import write
        # print("Calculated Properties: ...", properties)
        # if properties is not None:
        #     if 'forces' in properties or 'stress' in properties:
        #         self.do_forces = True
        self.do_forces = True
        FileIOCalculator.write_input(self, atoms, properties, system_changes)
        self.write_dftb_in(os.path.join(self.directory, 'dftb_in.hsd'))
        write(os.path.join(self.directory, self.geo_fname), atoms)
        # self.atoms is none until results are read out,
        # then it is set to the ones at writing input
        self.atoms_input = atoms
        self.atoms = None
        # jx: !!!
        if self.pcpot:
            self.pcpot.write_mmcharges('dftb_external_charges.dat')

        return
Exemplo n.º 49
0
    def read(self, label):
        # XXX label of restart file may not be the same as actual label!
        # This makes things rather tricky.  We first set the label to
        # that of the restart file and arbitrarily expect the remaining code
        # to rectify any consequent inconsistencies.
        self.set_label(label)

        FileIOCalculator.read(self, label)
        inp_path = self._getpath('inp')
        fd = open(inp_path)
        kwargs = parse_input_file(fd)
        if self.octopus_keywords is not None:
            self.check_keywords_exist(kwargs)

        self.atoms, kwargs = kwargs2atoms(kwargs)
        self.kwargs.update(kwargs)

        fd.close()
        self.read_results()
Exemplo n.º 50
0
    def __init__(self,
                 restart=None,
                 ignore_bad_restart_file=FileIOCalculator._deprecated,
                 label=None,
                 command=None,
                 atoms=None,
                 **kwargs):
        FileIOCalculator.__init__(self, restart, ignore_bad_restart_file,
                                  label, atoms, command, **kwargs)

        self.species = []
        self.species_cond = []
        self.pseudos = []
        self.core_wfs = []
        self.solvers = []
        self.solvers_cond = []
        self.restart = False
        self.prefix = label
        self.directory = '.'
Exemplo n.º 51
0
 def get_hirsh_charges(self):
     """
     return atomic charges as obtained by Hirshfeld analysis
     by Martin Stoehr ([email protected]) Oct 2015
     """
     atoms = self.atoms
     if ('output' in self.parameters
             and 'hirshfeld' not in self.parameters['output']):
         raise NotImplementedError
     return FileIOCalculator.get_property(self, 'hirsh_charges', atoms)
Exemplo n.º 52
0
    def __init__(self,
                 restart=None,
                 ignore_bad_restart_file=False,
                 label='g09',
                 atoms=None,
                 scratch=None,
                 ioplist=list(),
                 basisfile=None,
                 **kwargs):
        """Constructs a Gaussian-calculator object.

        """

        FileIOCalculator.__init__(self, restart, ignore_bad_restart_file,
                                  label, atoms, **kwargs)

        self.ioplist = ioplist
        self.scratch = scratch
        self.basisfile = basisfile
Exemplo n.º 53
0
    def calculate(self,
                  atoms=None,
                  properties=['energy'],
                  system_changes=all_changes):
        """Capture the RuntimeError from FileIOCalculator.calculate
        and add a little debug information from the Siesta output.

        See base FileIocalculator for documentation.
        """

        FileIOCalculator.calculate(self,
                                   atoms=atoms,
                                   properties=properties,
                                   system_changes=system_changes)

        # The below snippet would run if calculate() failed but I have
        # disabled it for now since it looks to be just for debugging.
        # --askhl
        """
Exemplo n.º 54
0
 def __init__(self,
              restart=None,
              ignore_bad_restart_file=False,
              label='gulp',
              atoms=None,
              optimized=None,
              Gnorm=1000.0,
              steps=1000,
              conditions=None,
              **kwargs):
     """Construct GULP-calculator object."""
     FileIOCalculator.__init__(self, restart, ignore_bad_restart_file,
                               label, atoms, **kwargs)
     self.optimized = optimized
     self.Gnorm = Gnorm
     self.steps = steps
     self.conditions = conditions
     self.library_check()
     self.atom_types = []
Exemplo n.º 55
0
    def __init__(
            self,
            label='ase_dftd3',  # Label for dftd3 output files
            command=None,  # Command for running dftd3
            dft=None,  # DFT calculator
            atoms=None,
            comm=world,
            **kwargs):

        self.dft = None
        FileIOCalculator.__init__(self,
                                  restart=None,
                                  label=label,
                                  atoms=atoms,
                                  command=command,
                                  dft=dft,
                                  **kwargs)

        self.comm = comm
Exemplo n.º 56
0
 def calculate(self, *args, **kwargs):
     gaussians = ('g16', 'g09', 'g03')
     if 'GAUSSIAN' in self.command:
         for gau in gaussians:
             if which(gau):
                 self.command = self.command.replace('GAUSSIAN', gau)
                 break
         else:
             #raise EnvironmentError('Missing Gaussian executable {}'
             #.format(gaussians))
             pass
     try:
         FileIOCalculator.calculate(self, *args, **kwargs)
     except:
         print('Gaussian error')
         i = 0
         while Path('gauserror' + str(i) + '.log').exists():
             i += 1
         copyfile(self.label + '.log', 'gauserror' + str(i) + '.log')
Exemplo n.º 57
0
 def get_mull_charges(self):
     """
     return atomic charges as obtained by Mulliken analysis
     by Martin Stoehr ([email protected]) Oct 2015
     """
     atoms = self.atoms
     if ('output' in self.parameters
             and 'mulliken' not in self.parameters['output']):
         raise NotImplementedError('Tell AIMS to do Mulliken analysis!')
     return FileIOCalculator.get_property(self, 'mull_charges', atoms)
Exemplo n.º 58
0
    def write_input(self, atoms, properties=None, system_changes=None):

        if not (np.all(atoms.pbc) or not np.any(atoms.pbc)):
            raise RuntimeError('PBC must be all true or all false')

        self.clean()  # Remove files from old run
        self.internal_transformation = False
        self.ase_positions = atoms.positions.copy()
        self.ase_cell = atoms.cell.copy()

        FileIOCalculator.write_input(self, atoms, properties, system_changes)

        if np.all(atoms.pbc):
            write_dmol_incoor(self.label + '.incoor', atoms)
        elif not np.any(atoms.pbc):
            write_dmol_car(self.label + '.car', atoms)

        self.write_input_file()
        self.parameters.write(self.label + '.parameters.ase')
Exemplo n.º 59
0
    def read_results(self):
        FileIOCalculator.read(self, self.label)
        if not os.path.isfile(self.label + '.out'):
            raise ReadError

        with open(self.label + '.out') as f:
            lines = f.readlines()

        for i, line in enumerate(lines):
            if line.find('TOTAL ENERGY') != -1:
                self.results['energy'] = float(line.split()[3])
            elif line.find('FINAL  POINT  AND  DERIVATIVES') != -1:
                forces = [
                    -float(line.split()[6])
                    for line in lines[i + 3:i + 3 + 3 * len(self.atoms)]
                ]
                forces = np.array(forces).reshape((-1, 3)) * kcal / mol
                self.results['forces'] = forces
                break
Exemplo n.º 60
0
    def __init__(self,
                 restart=None,
                 ignore_bad_restart_file=False,
                 label='ase/tmp_ase',
                 atoms=None,
                 scratch=None,
                 ioplist=list(),
                 basisfile=None,
                 extra=None,
                 addsec=None,
                 command=None,
                 **kwargs):
        """Constructs a Gaussian-calculator object.

        extra: any extra text to be included in the input card
        addsec: a list of strings to be included as "additional sections"

        """

        FileIOCalculator.__init__(self, restart, ignore_bad_restart_file,
                                  label, atoms, **kwargs)

        if restart is not None:
            try:
                self.read(restart)
            except ReadError:
                if ignore_bad_restart_file:
                    self.reset()
                else:
                    raise

        self.ioplist = ioplist
        self.scratch = scratch
        self.basisfile = basisfile

        # store extra parameters
        self.extra = extra
        self.addsec = addsec
        self.forces = None
        self.energy_free = None

        if command: self.command = command