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)
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)
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)
def write_input(self, atoms, properties=None, system_changes=None): FileIOCalculator.write_input(self, atoms, properties, system_changes) write(self.label + '.com', atoms, properties=properties, format='gaussian-in', **self.parameters)
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)
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)
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()
def write_input(self, atoms, properties=None, system_changes=None, **kwargs): FileIOCalculator.write_input(self, atoms, properties, system_changes) self.initialize(atoms)
def write_input(self, atoms, properties=None, system_changes=None, ghosts=None, geo_constrain=None, scaled=False, velocities=None): FileIOCalculator.write_input(self, atoms, properties, system_changes) if geo_constrain is None: geo_constrain = "relax_geometry" in self.parameters if scaled is None: scaled = np.all(atoms.get_pbc()) if velocities is None: velocities = atoms.has('momenta') 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, scaled, geo_constrain, velocities=velocities, ghosts=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'))
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, bytes): 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())
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())
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)
def write_input(self, atoms, properties=None, system_changes=None): FileIOCalculator.write_input(self, atoms, properties, system_changes) at = atoms.get_atomic_numbers() cart = atoms.get_positions() BABmol = openbabel.OBMol() for i in range(0, at.size): a = BABmol.NewAtom() a.SetAtomicNum(int(at[i])) a.SetVector(float(cart[i, 0]), float(cart[i, 1]), float(cart[i, 2])) # Assign bonds and fill out angles and torsions BABmol.ConnectTheDots() BABmol.FindAngles() BABmol.FindTorsions() BABmol.PerceiveBondOrders() # Create converter object to convert from XYZ to smiles obConversion = openbabel.OBConversion() obConversion.SetInAndOutFormats("xyz", "mp") name = (obConversion.WriteString(BABmol)) name = name.replace("!memory,INSERT MEMORY HERE", "MEMORY,10000,M") name = name.replace("!hf", str(self.parameters['method'])) name = name.replace("!INSERT QM METHODS HERE", "hf") name = name.replace( "!basis,INSERT BASIS SET HERE", "basis," + str(self.parameters['basis'] + '\nNOSYM\n')) f = open(self.label + ".inp", "w") f.write(str(name)) f.close()
def write_input(self, atoms, properties=None, system_changes=None): """Write input (in)-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 + '/deMon.inp' # Start writing the file. with open(filename, 'w') as fd: # write keyword argument keywords value = self.parameters['title'] self._write_argument('TITLE', value, fd) fd.write('\n') # obtain forces through a single BOMD step # only if forces is in properties, or if keyword forces is True value = self.parameters['forces'] if 'forces' in properties or value: self._write_argument('MDYNAMICS', 'ZERO', fd) self._write_argument('MDSTEP', 'MAX=1', fd) #default timestep is 0.25 fs if not enough - uncomment the line below #self._write_argument('TIMESTEP', '0.1', fd) # print argument, here other options could change this value = self.parameters['print_out'] assert(isinstance(value, str)) if not len(value) == 0: self._write_argument('PRINT', value, fd) fd.write('\n') # write general input arguments self._write_input_arguments(fd) if 'BASISPATH' not in self.parameters['input_arguments']: value = self.parameters['basis_path'] fd.write(value) fd.write('\n') # write geometry self._write_atomic_coordinates(fd, atoms) # write xyz file for good measure. ase.io.write(self.label + '/deMon_atoms.xyz', self.atoms)
def write_input(self, atoms, properties=None, system_changes=None): FileIOCalculator.write_input(self, atoms, properties, system_changes) self.write_crystal_in(os.path.join(self.directory, 'INPUT')) write(os.path.join(self.directory, 'fort.34'), 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
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, process_special_kwargs(atoms, self.kwargs)) with open(self._getpath('inp'), 'w') as fd: fd.write(txt)
def write_input(self, atoms, properties=None, system_changes=None): FileIOCalculator.write_input(self, atoms, properties, system_changes) p = self.parameters p.write(self.label + '.ase') p['label'] = self.label if self.pcpot: # also write point charge file and add things to input p['pcpot'] = self.pcpot write_orca(atoms, **p)
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, self.octopus_keywords) fd = open(self._getpath('inp'), 'w') fd.write(txt) fd.close()
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: # Write system name and label. f.write(format_fdf('SystemName', self.label)) f.write(format_fdf('SystemLabel', self.label)) f.write("\n") # Write the minimal arg self._write_species(f, atoms) self._write_structure(f, atoms) # 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)) # Force siesta to return error on no convergence. # Why?? maybe we don't want to force convergency?? # f.write(format_fdf('SCFMustConverge', True)) self._write_kpts(f)
def write_input(self, atoms, properties=['energies'], system_changes=all_changes): """Write VASP inputfiles, INCAR, KPOINTS and POTCAR""" # Create the folders where we write the files, if we aren't in the # current working directory. FileIOCalculator.write_input(self, atoms, properties, system_changes) self.initialize(atoms) GenerateVaspInput.write_input(self, atoms, directory=self.directory)
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)
def write_input(self, atoms, properties=None, system_changes=None): from ase.io import write 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, 'geo_end.gen'), 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 if self.pcpot: self.pcpot.write_mmcharges('dftb_external_charges.dat')
def write_input(self, atoms, properties = None, system_charges = None): """ """ # Initialize the directories and setup correctly the working path FileIOCalculator.write_input(self, atoms, properties, system_charges) # Write the input input_dist = [] # Prepare the toy model info for CP2K input_dist.append(__TOY_MODEL_INFO__) # Insert the cell cell = atoms.get_cell() STR1 = "A [angstrom] %.16f %.16f %.16f\n" % (cell[0, 0], cell[0,1], cell[0,2]) STR2 = "B [angstrom] %.16f %.16f %.16f\n" % (cell[1, 0], cell[1,1], cell[1,2]) STR3 = "C [angstrom] %.16f %.16f %.16f\n" % (cell[2, 0], cell[2,1], cell[2,2]) input_dist.append(STR1) input_dist.append(STR2) input_dist.append(STR3) input_dist.append(__INPUT_SECOND_PART__) # Add the coordinate file write("%s.xyz" % self.label, atoms) STR_ATM = " COORD_FILE_NAME %s.xyz\n" % self.label input_dist.append(STR_ATM) PRINT_INFO = """&END &END SUBSYS &PRINT &FORCES ON ADD_LAST NUMERIC COMMON_ITERATION_LEVELS 1 FILENAME forces &END FORCES &STRESS_TENSOR ON ADD_LAST NUMERIC COMMON_ITERATION_LEVELS 1 FILENAME stress &END STRESS_TENSOR &END PRINT """ input_dist.append(PRINT_INFO) input_dist.append(__INPUT_END__) # Write the input in the PREFIX.in file specified in the command section f = open("%s.in" % self.label, "w") f.writelines(input_dist) f.close()
def write_input(self, atoms, properties=None, system_changes=None): FileIOCalculator.write_input(self, atoms, properties, system_changes) s = self.input_string(atoms, properties, system_changes) f = open(self.label + '.inp', 'w') f.write(s) f.close() # writing parameters using built-in ase format # TODO: Cannot write objects such as LJPotential self.parameters.write(self.label + '.ase')
def write_input(self, atoms, properties=None, system_changes=None): from ase.io import write FileIOCalculator.write_input( self, atoms, properties, system_changes) self.write_dftb_in(os.path.join(self.directory, 'dftb.inp'), atoms) self.atoms_input = atoms self.atoms = None
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 with open(self.label + '.mdp', 'w') as myfile: for key, val in self.parameters.items(): if val is not None: docstring = self.params_doc.get(key, '') myfile.write('%-35s = %s ; %s\n' % (key, val, ';' + docstring))
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)
def write_input(self,atoms,properties=None,system_changes=None): """ Writes the files that have to be written each timestep """ FileIOCalculator.write_input(self,atoms,properties,system_changes) # start the input mopac_input = '' #write functional and job_type mopac_input += self.parameters['functional']+' ' for value in self.parameters['job_type']: mopac_input += value + ' ' mopac_input += 'RELSCF=' + str(self.parameters['relscf']) + ' ' #write charge charge = sum(atoms.get_initial_charges()) charge = max([charge,self.parameters['charge']]) if charge != 0: mopac_input += 'CHARGE=%i ' % (int(charge)) #write spin spin = int(self.parameters['spin']) spin_keywords = { 1: 'SINGLET', 2: 'DOUBLET', 3: 'TRIPLET', } mopac_input += spin_keywords[spin]+' ' #input down mopac_input += '\n' mopac_input += 'Title: ASE job\n\n' symbols = atoms.get_chemical_symbols() coordinates = atoms.get_positions() for i in range(len(atoms)): mopac_input += ('%-10s' % symbols[i]) for j in range(3): mopac_input += ('%20.10f' % coordinates[i, j]) mopac_input += ('\n') if atoms.pbc.any(): for v in atoms.get_cell(): mopac_input += 'Tv %8.3f %8.3f %8.3f\n' % (v[0], v[1], v[2]) # write input myfile = open('mopac.mop', 'w') myfile.write(mopac_input) myfile.close()
def write_input(self, atoms, properties=None, system_changes=None): FileIOCalculator.write_input(self, atoms, properties=properties, system_changes=system_changes) octopus_keywords = self.octopus_keywords if octopus_keywords is None: # Will not do automatic pretty capitalization octopus_keywords = self.kwargs txt = generate_input(atoms, process_special_kwargs(atoms, self.kwargs), octopus_keywords) fd = open(self._getpath('inp'), 'w') fd.write(txt) fd.close()
def write_input(self, atoms, properties=None, system_changes=None): FileIOCalculator.write_input(self, atoms, properties, system_changes) parameters = dict(self.parameters) if 'forces' in properties: parameters['tforce'] = True directory = Path(self.directory) write(directory / 'elk.in', atoms, parameters=parameters, format='elk-in')
def write_input(self, atoms=None, properties=None, system_changes=None): """Writes all input files required for a calculation.""" # this creates the directory if needed FileIOCalculator.write_input(self, atoms, properties, system_changes) if 'spring' not in self.parameters: # do not write if NEB self.write_poscar() self.write_incar() if 'kspacing' not in self.parameters: self.write_kpoints() self.write_potcar() self.write_db()
def write_input(self, atoms, properties=None, system_changes=None): FileIOCalculator.write_input(self, atoms, properties=properties, system_changes=system_changes) octopus_keywords = self.octopus_keywords if octopus_keywords is None: # Will not do automatic pretty capitalization octopus_keywords = self.kwargs txt = generate_input(atoms, process_special_kwargs(atoms, self.kwargs), octopus_keywords) fd = open(self._getpath('inp'), 'w') fd.write(txt) fd.close()
def write_input(self, atoms=None, properties=None, system_changes=None): """Writes all input files required for a calculation.""" # this creates the directory if needed FileIOCalculator.write_input(self, atoms, properties, system_changes) if 'spring' not in self.parameters: # do not write if NEB self.write_poscar() self.write_incar() if 'kspacing' not in self.parameters: self.write_kpoints() self.write_potcar() self.write_db()
def write_input(self, atoms, properties=None, system_changes=None): from ase.io import write 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, 'geo_end.gen'), 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 if self.pcpot: self.pcpot.write_mmcharges('dftb_external_charges.dat')
def write_input(self, atoms, properties=None, system_changes=None): FileIOCalculator.write_input(self, atoms, properties, system_changes) filename = self.label + '.inp' with open(filename, 'w') as fileobj: fileobj.write('$comment\n ASE generated input file\n$end\n\n') fileobj.write('$rem\n') if self.parameters['jobtype'] is None: if 'forces' in properties: fileobj.write(' %-25s %s\n' % ('JOBTYPE', 'FORCE')) else: fileobj.write(' %-25s %s\n' % ('JOBTYPE', 'SP')) for prm in self.parameters: if prm not in ['charge', 'multiplicity']: if self.parameters[prm] is not None: fileobj.write( ' %-25s %s\n' % (prm.upper(), self.parameters[prm].upper())) # Not even a parameters as this is an absolute necessity fileobj.write(' %-25s %s\n' % ('SYM_IGNORE', 'TRUE')) fileobj.write('$end\n\n') fileobj.write('$molecule\n') # Following the example set by the gaussian calculator if ('multiplicity' not in self.parameters): tot_magmom = atoms.get_initial_magnetic_moments().sum() mult = tot_magmom + 1 else: mult = self.parameters['multiplicity'] # Default charge of 0 is defined in default_parameters fileobj.write(' %d %d\n' % (self.parameters['charge'], mult)) for a in atoms: fileobj.write(' %s %f %f %f\n' % (a.symbol, a.x, a.y, a.z)) fileobj.write('$end\n\n') if self.basisfile is not None: with open(self.basisfile, 'r') as f_in: basis = f_in.readlines() fileobj.write('$basis\n') fileobj.writelines(basis) fileobj.write('$end\n\n') if self.ecpfile is not None: with open(self.ecpfile, 'r') as f_in: ecp = f_in.readlines() fileobj.write('$ecp\n') fileobj.writelines(ecp) fileobj.write('$end\n\n')
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' # self.write_pmd(atoms) write_pmd(atoms,fname='pmd0000',specorder=self.specorder) with open(infname,'w') as f: fmvs,ifmvs = get_fmvs(atoms) f.write(get_input_txt(self.parameters,fmvs))
def write_input(self, atoms, properties=None, system_changes=None): FileIOCalculator.write_input(self, atoms, properties, system_changes) if self.backup: for fn in [self.infile, self.outfile, self.dumpfile, self.structfile, self.logfile]: if os.path.exists(fn): common.backup(fn) common.file_write(self.infile, self.fill_infile_templ()) io.write_lammps(self.structfile, crys.atoms2struct(atoms), symbolsbasename=os.path.basename(self.structfile) + \ '.symbols')
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'))
def write_input(self, atoms, properties=None, system_changes=None): FileIOCalculator.write_input(self, atoms, properties, system_changes) if self.backup: for fn in [ self.infile, self.outfile, self.dumpfile, self.structfile, self.logfile ]: if os.path.exists(fn): common.backup(fn) common.file_write(self.infile, self.fill_infile_templ()) io.write_lammps(self.structfile, crys.atoms2struct(atoms), symbolsbasename=os.path.basename(self.structfile) + \ '.symbols')
def write_input(self, atoms, properties=None, system_changes=None): """Writes the input file""" FileIOCalculator.write_input(self, atoms, properties, system_changes) self.parameters.write(self.label + '.ase') filename = self.label + '.inp' inputfile = open(filename, 'w') if self.extra is None: self.extra = "" route = '!' route += " %s" % self.parameters["method"] if self.parameters["basis"] is not None: route += " %s" % self.parameters["basis"] if self.parameters["COSMO"] is not None: route += " COSMO" if "cosmo" not in self.extra.lower(): self.extra += "\n%cosmo\n SMD true\n solvent \"" self.extra += self.parameters["COSMO"] + "\"\n end" if self.parameters["RunTyp"] is not None: if self.parameters["RunTyp"].upper() == "SP": self.parameters["RunTyp"] = "Energy" elif self.parameters["RunTyp"].upper() == "OPT": self.parameters["RunTyp"] = "Opt" elif self.parameters["RunTyp"].upper() == "ENGRAD": self.parameters["RunTyp"] = "Gradient" s = "\n%method\n RunTyp " + self.parameters["RunTyp"] + "\n end" if s not in self.extra: self.extra += s inputfile.write(route) inputfile.write(self.extra) charge = self.parameters["charge"] multiplicity = self.parameters["multiplicity"] inputfile.write("\n*xyz %d %d\n" % (charge, multiplicity)) # Input coordinates symbols = atoms.get_chemical_symbols() coordinates = atoms.get_positions() for i in range(len(atoms)): inputfile.write('%-10s' % symbols[i]) for j in range(3): inputfile.write('%20.10f' % coordinates[i, j]) inputfile.write('\n') inputfile.write("*") inputfile.close()
def write_input(self, atoms, properties=None, system_changes=None): from ase.io import write if properties is not None: if 'forces' in properties or 'stress' in properties: self.do_forces = True FileIOCalculator.write_input( self, atoms, properties, system_changes) with open(os.path.join(self.directory, 'dftb_in.hsd'), 'w') as fd: self.write_dftb_in(fd) write(os.path.join(self.directory, 'geo_end.gen'), 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 if self.pcpot: self.pcpot.write_mmcharges('dftb_external_charges.dat')
def write_input(self, atoms=None, parameters=None, properties=[], system_changes=[]): """Write input (dat)-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. if atoms is None: atoms = self.atoms FileIOCalculator.write_input(self, atoms, properties, system_changes) write_openmx(label=self.label, atoms=atoms, parameters=self.parameters, properties=properties, system_changes=system_changes)
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) 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))
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()
def write_input(self, atoms, properties=None, system_changes=None): FileIOCalculator.write_input( self, atoms=atoms, properties=properties, system_changes=system_changes, ) filename = self.label + '.fdf' fdf_dict = {} with open(filename, 'w') as f: f.write(format_fdf('SystemName', self.label)) f.write(format_fdf('SystemLabel', self.label)) self['solution_method'].write_fdf(f) self.__write_basis(f, atoms) self.__write_kpts(f) self.__write_structure(f, atoms) self['fdf_arguments'].write_fdf(f)
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')
def write_input(self, atoms, properties=None, system_changes=None): FileIOCalculator.write_input(self, atoms, properties, system_changes) p = self.parameters p.initial_magmoms = atoms.get_initial_magnetic_moments().tolist() p.write(self.label + '.ase') del p['initial_magmoms'] f = open(self.label + '.nw', 'w') if p.charge is not None: f.write('charge %s\n' % p.charge) write_nwchem(f, atoms, p.geometry) f.write('start\n') if p.basispar is not None: basispar = 'basis ' + p.basispar else: basispar = 'basis' def format_basis_set(string, tag=basispar): formatted = tag + '\n' lines = string.split('\n') if len(lines) > 1: formatted += string else: formatted += ' * library ' + string return formatted + '\nend\n' basis = format_basis_set(p.basis) if p.ecp is not None: basis += format_basis_set(p.ecp, 'ecp') if p.so is not None: basis += format_basis_set(p.so, 'so') f.write(basis) if p.xc == 'RHF': task = 'scf' elif p.xc == 'MP2': task = 'mp2' else: if p.spinorbit: task = 'sodft' else: task = 'dft' xc = {'LDA': 'slater pw91lda', 'PBE': 'xpbe96 cpbe96', 'revPBE': 'revpbe cpbe96', 'RPBE': 'rpbe cpbe96'}.get(p.xc, p.xc) f.write('\n' + task + '\n') f.write(' xc ' + xc + '\n') for key in p.convergence: if p.convergence[key] is not None: if key == 'lshift': if p.convergence[key] <= 0.0: f.write(' convergence nolevelshifting\n') else: f.write(' convergence %s %s\n' % (key, p.convergence[key] / Hartree)) else: f.write(' convergence %s %s\n' % (key, p.convergence[key])) if p.smearing is not None: assert p.smearing[0].lower() == 'gaussian', p.smearing f.write(' smear %s\n' % (p.smearing[1] / Hartree)) if 'mult' not in p: # Obtain multiplicity from magnetic momenta: tot_magmom = atoms.get_initial_magnetic_moments().sum() if tot_magmom < 0: mult = tot_magmom - 1 # fill minority bands else: mult = tot_magmom + 1 else: mult = p.mult if mult != int(mult): raise RuntimeError('Noninteger multiplicity not possible. ' + 'Check initial magnetic moments.') f.write(' mult %d\n' % mult) if p.odft: f.write(' odft\n') # open shell aka spin polarized dft for key in sorted(p.keys()): if key in ['charge', 'geometry', 'basis', 'basispar', 'ecp', 'so', 'xc', 'spinorbit', 'convergence', 'smearing', 'raw', 'mult', 'task', 'odft']: continue f.write(u" {0} {1}\n".format(key, p[key])) f.write('end\n') if p.raw: f.write(p.raw + '\n') f.write('\ntask ' + task + ' ' + p.task + '\n') f.close()
def write_input(self, atoms, properties=None, system_changes=None): FileIOCalculator.write_input(self, atoms, properties, system_changes) p = self.parameters p.magmoms = atoms.get_initial_magnetic_moments().tolist() p.write(self.label + ".ase") del p["magmoms"] f = open(self.label + ".nw", "w") if p.charge is not None: f.write("charge %s\n" % p.charge) write_nwchem(f, atoms, p.geometry) f.write("start\n") if p.basispar is not None: basispar = "basis " + p.basispar else: basispar = "basis" def format_basis_set(string, tag=basispar): formatted = tag + "\n" lines = string.split("\n") if len(lines) > 1: formatted += string else: formatted += " * library " + string + "\n" return formatted + "end\n" basis = format_basis_set(p.basis) if p.ecp is not None: basis += format_basis_set(p.ecp, "ecp") if p.so is not None: basis += format_basis_set(p.so, "so") f.write(basis) if p.xc == "RHF": task = "scf" else: if p.spinorbit: task = "sodft" else: task = "dft" xc = {"LDA": "slater pw91lda", "PBE": "xpbe96 cpbe96"}.get(p.xc, p.xc) f.write("\n" + task + "\n") f.write(" xc " + xc + "\n") for key in p.convergence: if p.convergence[key] is not None: if key == "lshift": if p.convergence[key] <= 0.0: f.write(" convergence nolevelshifting\n") else: f.write(" convergence %s %s\n" % (key, p.convergence[key] / Hartree)) else: f.write(" convergence %s %s\n" % (key, p.convergence[key])) if p.smearing is not None: assert p.smearing[0].lower() == "gaussian" f.write(" smear %s\n" % (p.smearing[1] / Hartree)) if "mult" not in p: # Obtain multiplicity from magnetic momenta: mult = 1 + atoms.get_initial_magnetic_moments().sum() else: mult = p.mult if mult != int(mult): raise RuntimeError("Noninteger multiplicity not possible. " + "Check initial magnetic moments.") f.write(" mult %d\n" % mult) for key in sorted(p.keys()): if key in [ "charge", "geometry", "basis", "basispar", "ecp", "so", "xc", "spinorbit", "convergence", "smearing", "raw", "mult", "task", ]: continue value = p[key] f.write("%s %s\n" % (key, value)) f.write("end\n") if p.raw: f.write(p.raw + "\n") f.write("\ntask " + task + " " + p.task + "\n") f.close()
def write_input(self, atoms=None, properties=None, system_changes=None): """Write updated coordinates to a file.""" FileIOCalculator.write_input(self, atoms, properties, system_changes) self.write_coordinates(atoms)
def write_input(self, atoms, properties=None, system_changes=None): FileIOCalculator.write_input(self, atoms, properties, system_changes) p = self.parameters p.initial_magmoms = atoms.get_initial_magnetic_moments().tolist() p.write(self.label + '.ase') del p['initial_magmoms'] f = open(self.label + '.inp', 'w') #FUDO| we'll construct a simple input line by default and everything special should be supplied under 'raw' input contrl_temp = '! %s %s' contrl = contrl_temp %(p.wfn, p.basis) cnadd = '' if p.xc is not 'HF': cnadd += ' %s' %p.xc contrl += cnadd contrl += '\n' if p.task == 'gradient': contrl += '!EnGrad\n' if 'mult' not in p: # Obtain multiplicity from magnetic momenta: tot_magmom = atoms.get_initial_magnetic_moments().sum() if tot_magmom < 0: mult = tot_magmom - 1 # fill minority bands else: mult = tot_magmom + 1 else: mult = p.mult f.write(contrl) if 'raw' in p: f.write(p.raw) #FUDO| assuming a neutral system if p.charge is not None: charge = p.charge else: charge = 0 write_orca(f, atoms, charge, mult) #-------orca also can use ECPs in principle, but I don't know how... #-------old NWChem input generation---------# #if p.ecp is not None: # basis += format_basis_set(p.ecp, 'ecp') #if p.so is not None: # basis += format_basis_set(p.so, 'so') #f.write(basis) ### for key in p.convergence: ### if p.convergence[key] is not None: ### if key == 'lshift': ### if p.convergence[key] <= 0.0: ### f.write(' convergence nolevelshifting\n') ### else: ### f.write(' convergence %s %s\n' % ### (key, p.convergence[key] / Hartree)) ### else: ### f.write(' convergence %s %s\n' % ### (key, p.convergence[key])) ### if p.smearing is not None: ### assert p.smearing[0].lower() == 'gaussian', p.smearing ### f.write(' smear %s\n' % (p.smearing[1] / Hartree)) ### ### if p.odft: ### f.write(' odft\n') # open shell aka spin polarized dft ### for key in sorted(p.keys()): ### if key in ['charge', 'geometry', 'basis', 'basispar', 'ecp', ### 'so', 'xc', 'spinorbit', 'convergence', 'smearing', ####FU| needed to add a key exception for bq, and charges... ### 'raw', 'mult', 'task', 'odft', 'bq', 'charges']: ####FU| ### continue ### f.write(u" {0} {1}\n".format(key, p[key])) ### f.write('end\n') #FU| for now we will implement external charges within the FFDATA/QUANPOL module, just without any parameters but charges defined if p.bq is not None: f.write('%%pointcharges "%s"' %(self.label + '.bq')) bqf = open(self.label + '.bq', 'w') bqf.write('%i\n' %len(p.bq)) for q in p.bq: bqf.write('%12.8f %12.8f %12.8f %12.8f\n' %(q[3], q[0], q[1], q[2])) #FU| careful in earlier NWChems this might be the wrong order: #FU| maybe it's better to put this into the raw input if p.charges is not None: if p.charges.find('ESP') > -1: print 'ESP or RESP charges not implemented for orca calculator' sys.exit ( 1 ) #FU| Mulliken and Lowdin charges are printed out by default #FU| and RESP is not implemented directly into orca, one would need an external program for that #FUDO| check, (R)ESP fits might actually be implemented into orca f.close()
def write_input(self, atoms, properties=None, system_changes=None): """Write input parameters to files-file.""" FileIOCalculator.write_input(self, atoms, properties, system_changes) if ('numbers' in system_changes or 'initial_magmoms' in system_changes): self.initialize(atoms) fh = open(self.label + '.files', 'w') fh.write('%s\n' % (self.prefix + '.in')) # input fh.write('%s\n' % (self.prefix + '.txt')) # output fh.write('%s\n' % (self.prefix + 'i')) # input fh.write('%s\n' % (self.prefix + 'o')) # output # XXX: # scratch files #scratch = self.scratch #if scratch is None: # scratch = dir #if not os.path.exists(scratch): # os.makedirs(scratch) #fh.write('%s\n' % (os.path.join(scratch, prefix + '.abinit'))) fh.write('%s\n' % (self.prefix + '.abinit')) # Provide the psp files for ppp in self.ppp_list: fh.write('%s\n' % (ppp)) # psp file path fh.close() # Abinit will write to label.txtA if label.txt already exists, # so we remove it if it's there: filename = self.label + '.txt' if os.path.isfile(filename): os.remove(filename) param = self.parameters param.write(self.label + '.ase') fh = open(self.label + '.in', 'w') inp = {} inp.update(param) for key in ['xc', 'smearing', 'kpts', 'pps', 'raw']: del inp[key] smearing = param.get('smearing') if 'tsmear' in param or 'occopt' in param: assert smearing is None if smearing is not None: inp['occopt'] = {'fermi-dirac': 3, 'gaussian': 7}[smearing[0].lower()] inp['tsmear'] = smearing[1] inp['natom'] = len(atoms) if 'nbands' in param: inp['nband'] = param.nbands del inp['nbands'] if 'ixc' not in param: inp['ixc'] = {'LDA': 7, 'PBE': 11, 'revPBE': 14, 'RPBE': 15, 'WC': 23}[param.xc] magmoms = atoms.get_initial_magnetic_moments() if magmoms.any(): inp['nsppol'] = 2 fh.write('spinat\n') for n, M in enumerate(magmoms): fh.write('%.14f %.14f %.14f\n' % (0, 0, M)) else: inp['nsppol'] = 1 for key in sorted(inp.keys()): value = inp[key] unit = keys_with_units.get(key) if unit is None: fh.write('%s %s\n' % (key, value)) else: if 'fs**2' in unit: value /= fs**2 elif 'fs' in unit: value /= fs fh.write('%s %e %s\n' % (key, value, unit)) if param.raw is not None: for line in param.raw: if isinstance(line, tuple): fh.write(' '.join(['%s' % x for x in line]) + '\n') else: fh.write('%s\n' % line) fh.write('#Definition of the unit cell\n') fh.write('acell\n') fh.write('%.14f %.14f %.14f Angstrom\n' % (1.0, 1.0, 1.0)) fh.write('rprim\n') for v in atoms.cell: fh.write('%.14f %.14f %.14f\n' % tuple(v)) fh.write('chkprim 0 # Allow non-primitive cells\n') fh.write('#Definition of the atom types\n') fh.write('ntypat %d\n' % (len(self.species))) fh.write('znucl') for n, Z in enumerate(self.species): fh.write(' %d' % (Z)) fh.write('\n') fh.write('#Enumerate different atomic species\n') fh.write('typat') fh.write('\n') self.types = [] for Z in atoms.numbers: for n, Zs in enumerate(self.species): if Z == Zs: self.types.append(n + 1) n_entries_int = 20 # integer entries per line for n, type in enumerate(self.types): fh.write(' %d' % (type)) if n > 1 and ((n % n_entries_int) == 1): fh.write('\n') fh.write('\n') fh.write('#Definition of the atoms\n') fh.write('xangst\n') for pos in atoms.positions: fh.write('%.14f %.14f %.14f\n' % tuple(pos)) if 'kptopt' not in param: mp = kpts2mp(atoms, param.kpts) fh.write('kptopt 1\n') fh.write('ngkpt %d %d %d\n' % tuple(mp)) fh.write('nshiftk 1\n') fh.write('shiftk\n') fh.write('%.1f %.1f %.1f\n' % tuple((np.array(mp) + 1) % 2 * 0.5)) fh.write('chkexit 1 # abinit.exit file in the running directory terminates after the current SCF\n') fh.close()
def write_input(self, atoms, properties=None, system_changes=None): FileIOCalculator.write_input(self, atoms, properties, system_changes) p = self.parameters p.initial_magmoms = atoms.get_initial_magnetic_moments().tolist() p.write(self.label + '.ase') del p['initial_magmoms'] f = open(self.label + '.inp', 'w') #CONTRL SECTION, COLLECT INPUT PARAMETER #scftyp: uhf, rohf, rhf #runtyp energy, gradient #maxit up to 199 #mult #icharg #dfttyp none, or functional, svwn (lda) #exetyp run, check, debug contrl_temp = ' $contrl scftyp=%s runtyp=%s exetyp=%s $end\n' # $contrl maxit=%i icharg=%i mult=%i $end #""" contrl = contrl_temp %(p.wfn, p.task, p.exet) cnadd = ' $contrl' if p.charge is not None: cnadd += ' icharg=%i' %p.charge if 'mult' not in p: # Obtain multiplicity from magnetic momenta: tot_magmom = atoms.get_initial_magnetic_moments().sum() if tot_magmom < 0: mult = tot_magmom - 1 # fill minority bands else: mult = tot_magmom + 1 else: mult = p.mult cnadd += ' mult=%i' %mult if p.xc is not 'HF': #FUDO| include different levels of Moller-Plesset (if possible) if p.xc == 'MP2': cnadd += ' mplevl=2' else: cnadd += ' dfttyp=%s' %p.xc cnadd += ' $end\n' contrl += cnadd cnadd = '' #-------here we still need to insert more options for GAMESS-US calculator #basis set, problem ispher options goes into general contrl options #now we can add additional diffuse and polarization functions #heavy atom polarization functions: ndfunc #number of heavy atom f-type polarization: nffunc #number of light atom p-type polarization: npfunc #diffuse heavy atom: DIFFSP #diffuse light atom: DIFFS #-------Figure out if we need ispher?! #-------Pople-style basis sets start with either 3-21, 6-31, can in principle start with any number in a certain range #they should all start with an integer if they are pople's style #or just create a dictionary with all valid identifiers pople = False dunning = False semiemp = False ndfunc = 0 nffunc = 0 npfunc = 0 diffsp = False diffs = False polar='common' tc = p.basis.strip()[0] try: ngauss = int(tc) pople = True basispar = ' $basis gbasis=%s ngauss=%i $end\n' if p.basis.find('-311') > -1: popn='N311' polar='popn311' elif p.basis.find('-31') > -1: popn='N31' polar='popn31' elif p.basis.find('-21') > -1: popn='N21' polar='common' except ValueError: pople = False if p.basis.find('cc-p') > -1: dunning = True if p.basis.find('AM1') > -1 or p.basis.find('PM3') > -1: semiemp = True if p.basis.find('+') > -1: diffsp = True if p.basis.find('++') > -1: diffs = True if p.basis.find('*') > -1: ndfunc = 1 if p.basis.find('**') > -1: npfunc = 1 if p.basis.find('(2d,2p)') > -1: ndfunc = 2 npfunc = 2 if p.basis.find('(2df,2pd)') > -1: ndfunc = 2 npfunc = 2 nffunc = 1 print "Please note, that the (2df, 2pd) polarization functions don't seem to work like they should and I don't know why" if p.basis.find('(3df,3pd)') > -1: ndfunc = 3 npfunc = 3 nffunc = 1 print 'Please note, that if you have Hydrogen in the system, currently one D function is not accounted for...' #FUDO| check, for some reason now a D function is missing for the hydrogen atoms #still need 6-311++G(3df,3dp), or however they are called cnapp = '' bsapp = '' basis = '' if pople: basis = ' $basis gbasis=%s ngauss=%i polar=%s $end\n' %(popn, ngauss, polar) bsapp = '' if diffs: bsapp += ' diffs=.true.' if diffsp: bsapp += ' diffsp=.true.' if ndfunc > 0: bsapp += ' ndfunc=%i' %ndfunc if npfunc > 0: bsapp += ' npfunc=%i' %npfunc if nffunc > 0: bsapp += ' nffunc=%i' %nffunc aug = False core = False wcr = False if dunning: ngauss = p.basis[-2] polar = 'dunning' bsapp = '' bstmp = '' if p.basis.startswith('aug'): aug = True bstmp += 'ACC' else: bstmp += 'CC' bstmp += ngauss if p.basis.find('pCV') > -1: core = True bstmp += 'C' if p.basis.find('pwCV') > -1: #FUDO| check the validity of the below statements and compare to GAMESS-US manual #if ngauss == 'T': wcr = True bstmp += 'WC' #else: # print 'omega form of core augmentation only available for triple-zeta basis set' # sys.exit ( 1 ) basis = ' $basis gbasis=%s polar=%s $end\n' %(bstmp,polar) if semiemp: basis = '' bsapp = 'gbasis=%s' %p.basis if bsapp != '': basis += ' $basis %s $end\n' %bsapp if dunning and p.basispar is None: #print 'this is basispar: ', p.basispar cnapp = ' $contrl ispher=1 $end\n' contrl += cnapp #-------Not exactly sure how to handle this here, because cannot just append anything to the basis set information cnapp = '' if p.basispar is not None: cnapp = p.basispar contrl += cnapp f.write(contrl) f.write(basis) if 'raw' in p: f.write(p.raw) write_gamess_us(f, atoms, p.geometry) #-------GAMESS-US also can use ECPs in principle, but I don't know how... #-------old NWChem input generation---------# #if p.ecp is not None: # basis += format_basis_set(p.ecp, 'ecp') #if p.so is not None: # basis += format_basis_set(p.so, 'so') #f.write(basis) ### for key in p.convergence: ### if p.convergence[key] is not None: ### if key == 'lshift': ### if p.convergence[key] <= 0.0: ### f.write(' convergence nolevelshifting\n') ### else: ### f.write(' convergence %s %s\n' % ### (key, p.convergence[key] / Hartree)) ### else: ### f.write(' convergence %s %s\n' % ### (key, p.convergence[key])) ### if p.smearing is not None: ### assert p.smearing[0].lower() == 'gaussian', p.smearing ### f.write(' smear %s\n' % (p.smearing[1] / Hartree)) ### ### if p.odft: ### f.write(' odft\n') # open shell aka spin polarized dft ### for key in sorted(p.keys()): ### if key in ['charge', 'geometry', 'basis', 'basispar', 'ecp', ### 'so', 'xc', 'spinorbit', 'convergence', 'smearing', ####FU| needed to add a key exception for bq, and charges... ### 'raw', 'mult', 'task', 'odft', 'bq', 'charges']: ####FU| ### continue ### f.write(u" {0} {1}\n".format(key, p[key])) ### f.write('end\n') #FU| for now we will implement external charges within the FFDATA/QUANPOL module, just without any parameters but charges defined if p.bq is not None: f.write(' $ffdata\n\nCOORDINATES\n') i = 0 for q in p.bq: f.write('%i 0 %12.8f %12.8f %12.8f\n' %(i, q[0], q[1], q[2])) i += 1 f.write('STOP\nPARAMETERS\n') #FUDO| maybe at some point we should get the actual QuanPol parameters here, that'd be awefully nice :) if p.pol is not None: #FUDO| could do a sanity check here and see if p.pol has the same length as p.bq if len(p.pol) != len(p.bq): print 'array with polarizabilities does not have the same length as the one with point charges' sys.exit ( 1 ) i = 0 for l, q in enumerate(p.bq): f.write('%i 0 %12.8f %12.8f 0 0 0 0\n' %(i, q[3], p.pol[l])) i += 1 else: i = 0 for q in p.bq: f.write('%i 0 %12.8f 0 0 0 0 0\n' %(i, q[3])) i += 1 f.write('STOP\n $end\n') #FU| maybe it's better to put this into the raw input if p.charges is not None: if p.charges.find('ESP') > -1: if p.charges.find('RESP') > -1: print 'RESP charges not implemented for GAMESS-US calculator' sys.exit ( 1 ) f.write(' $elpot iepot=1 where=pdc $end\n $pdc ptsel=chelpg constr=charge $end\n') #FU| Mulliken and Lowdin charges are printed out by default #FU| and RESP is not implemented directly into GAMESS-US, one would need an external program for that if p.wfn == 'MCSCF': det = ' $DET NCORE=%i NACT=%i NELS=%i STSYM=%s SZ=%3.1f $END\n' %(p.mcscf['ncore'], p.mcscf['nact'], p.mcscf['nels'], p.mcscf['stsym'], p.mcscf['sz']) det += ' $DET NSTATE=%i' %p.mcscf['nstate'] try: det += ' IROOT=%i' %p.mcscf['iroot'] except KeyError: det += ' IROOT=1' det += ' $END\n' #FU| check and maybe re-normalize wstate array at this point try: wstate = np.array(p.mcscf['wstate']) except KeyError: wstate = None if wstate is not None: #10 is kind of the maximum number of state weights that we can put on one line ncnt = len(wstate) / 10 det += ' $DET WSTATE(1)=' for w in range(0, ncnt): det += '%3.1f,%3.1f,%3.1f,%3.1f,%3.1f,%3.1f,%3.1f,%3.1f,%3.1f,%3.1f,\n' %(wstate[w*10+0],wstate[w*10+1],wstate[w*10+2],wstate[w*10+3],wstate[w*10+4],wstate[w*10+5],wstate[w*10+6],wstate[w*10+7],wstate[w*10+8],wstate[w*10+9]) resid = len(wstate) % 10 for w in range(resid): det += '%3.1f' %wstate[ncnt*10+w] if w != resid-1: det += ',' det += ' $END\n' f.write(det) #try: # det += ' $DET WSTATE(1)= #wstate if p.mcscf is not None and p.vec is not None: if p.norbs is None: norbs=int(p.vec[-2].split()[0]) else: norbs=p.norbs f.write(' $GUESS GUESS=MOREAD NORB=%i $END\n' %norbs) f.writelines(p.vec) f.close()
def write_input(self, atoms, properties=None, system_changes=None): FileIOCalculator.write_input(self, atoms, properties, system_changes) self.initialize(atoms) self.parameters.write(os.path.join(self.directory, 'parameters.ase')) if 'xctype' in self.parameters: if 'xc' in self.parameters: raise RuntimeError("You can't use both 'xctype' and 'xc'!") if self.parameters.get('autokpt'): if 'kpts' in self.parameters: raise RuntimeError("You can't use both 'autokpt' and 'kpts'!") if 'ngridk' in self.parameters: raise RuntimeError("You can't use both 'autokpt' and 'ngridk'!") if 'ngridk' in self.parameters: if 'kpts' in self.parameters: raise RuntimeError("You can't use both 'ngridk' and 'kpts'!") if self.parameters.get('autoswidth'): if 'smearing' in self.parameters: raise RuntimeError("You can't use both 'autoswidth' and 'smearing'!") if 'swidth' in self.parameters: raise RuntimeError("You can't use both 'autoswidth' and 'swidth'!") fd = open(os.path.join(self.directory, 'elk.in'), 'w') inp = {} inp.update(self.parameters) if 'xc' in self.parameters: xctype = {'LDA': 3, # PW92 'PBE': 20, 'REVPBE': 21, 'PBESOL': 22, 'WC06': 26, 'AM05': 30}[self.parameters.xc] inp['xctype'] = xctype del inp['xc'] if 'kpts' in self.parameters: mp = kpts2mp(atoms, self.parameters.kpts) inp['ngridk'] = tuple(mp) vkloff = [] # is this below correct? for nk in mp: if nk % 2 == 0: # shift kpoint away from gamma point vkloff.append(0.5 / nk) else: vkloff.append(0) inp['vkloff'] = vkloff del inp['kpts'] if 'smearing' in self.parameters: name = self.parameters.smearing[0].lower() if name == 'methfessel-paxton': stype = self.parameters.smearing[2] else: stype = {'gaussian': 0, 'fermi-dirac': 3, }[name] inp['stype'] = stype inp['swidth'] = self.parameters.smearing[1] del inp['smearing'] # convert keys to ELK units for key, value in inp.items(): if key in elk_parameters: inp[key] /= elk_parameters[key] # write all keys for key, value in inp.items(): fd.write('%s\n' % key) if isinstance(value, bool): fd.write('.%s.\n\n' % ('false', 'true')[value]) elif isinstance(value, (int, float)): fd.write('%s\n\n' % value) else: fd.write('%s\n\n' % ' '.join([str(x) for x in value])) # cell fd.write('avec\n') for vec in atoms.cell: fd.write('%.14f %.14f %.14f\n' % tuple(vec / Bohr)) fd.write('\n') # atoms species = {} symbols = [] for a, (symbol, m) in enumerate(zip(atoms.get_chemical_symbols(), atoms.get_initial_magnetic_moments())): if symbol in species: species[symbol].append((a, m)) else: species[symbol] = [(a, m)] symbols.append(symbol) fd.write('atoms\n%d\n' % len(species)) scaled = atoms.get_scaled_positions() for symbol in symbols: fd.write("'%s.in' : spfname\n" % symbol) fd.write('%d\n' % len(species[symbol])) for a, m in species[symbol]: fd.write('%.14f %.14f %.14f 0.0 0.0 %.14f\n' % (tuple(scaled[a])+ (m,))) # species species_path = self.parameters.get('species_dir') if species_path is None: species_path = os.environ.get('ELK_SPECIES_PATH') if species_path is None: raise RuntimeError( 'Missing species directory! Use species_dir ' + 'parameter or set $ELK_SPECIES_PATH environment variable.') # if sppath is present in elk.in it overwrites species blocks! fd.write("sppath\n'%s'\n\n" % species_path)
def set_memory(self, eff_loss=0.1): """ Sets the recommended memory needed for a VASP calculation Code retrieves memory estimate based on the following priority: 1) DB file 2) existing OUTCAR 3) run partial diagnostic calculation The final method determines the memory requirements from KPOINT calculations run locally before submission to the queue returns the memory estimate from the OUTCAR file :param eff_loss: Estimated loss in computational efficiency when parallelizing over multiple processors. 10% is a safe upper bound from personal experience. :type eff_loss: float """ # Attempt to get the recommended memory from DB memory = self.get_db('memory') if memory is None: # Check if an OUTCAR exists from a previous run # WARNING: if calculation was run with > 1 ppn, estimate # in OUTCAR will reflect that recommended memory for that # number of ppn. This can lead to over-estimation of memory # requirements on calculations where set_required_memory # was not used initially. if os.path.exists(os.path.join(self.directory, 'OUTCAR')): memory = self.get_memory() # Write the recommended memory to the DB file self.write_db(data={'memory': memory}) # If no OUTCAR exists, we run a 'dummy' calculation else: try: original_ialgo = self.parameters['ialgo'] except(KeyError): original_ialgo = None self.set(ialgo=-1) # Generate the base files needed for VASP calculation from ase.calculators.calculator import FileIOCalculator FileIOCalculator.write_input(self, None, None, None) self.write_poscar() self.write_incar() if 'kspacing' not in self.parameters: self.write_kpoints() self.write_potcar() # Need to pass a function to Timer for delayed execution def kill(): process.kill() # We only need the memory estimate, so we can greatly # accelerate the process by terminating after we have it cwd = os.getcwd() os.chdir(self.directory) from subprocess import Popen, PIPE process = Popen(VASPRC['vasp.executable.serial'], stdout=PIPE) from threading import Timer import time timer = Timer(20.0, kill) timer.start() while True: if timer.is_alive(): memory = self.get_memory() if memory: timer.cancel() process.terminate() break else: time.sleep(0.1) else: raise RuntimeError('Memory estimate timed out') os.chdir(cwd) # return to original settings if original_ialgo: self.set(ialgo=original_ialgo) else: del self.parameters['ialgo'] self.write_incar() # Write the recommended memory to the DB file self.write_db(data={'memory': memory}) # Remove all non-initialization files files = ['CHG', 'CHGCAR', 'CONTCAR', 'DOSCAR', 'EIGENVAL', 'IBZKPT', 'OSZICAR', 'PCDAT', 'vasprun.xml', 'OUTCAR', 'WAVECAR', 'XDATCAR'] for f in files: os.unlink(os.path.join(self.directory, f)) # One node will require the memory read from the OUTCAR processors = VASPRC['queue.ppn'] + VASPRC['queue.nodes'] # Apply eff_loss if processors > 1: eff_factor = 1 + (eff_loss * float(processors)) # Rounded up to the nearest GB, and set the memory import math total_memory = int(math.ceil(eff_factor * float(memory))) VASPRC['queue.mem'] = '{0}GB'.format(total_memory) # Return the memory as read from the OUTCAR return memory
def write_input(self, atoms, properties=None, system_changes=None): """Write input (in)-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 + '/deMon.inp' add_print = '' # Start writing the file. with open(filename, 'w') as f: # write keyword argument keywords value = self.parameters['title'] self._write_argument('TITLE', value, f) f.write('#\n') value = self.parameters['scftype'] self._write_argument('SCFTYPE', value, f) value = self.parameters['xc'] self._write_argument('VXCTYPE', value, f) value = self.parameters['guess'] self._write_argument('GUESS', value, f) # obtain forces through a single BOMD step # only if forces is in properties, or if keyword forces is True value = self.parameters['forces'] if 'forces' in properties or value: self._write_argument('DYNAMICS', ['INT=1', 'MAX=0', 'STEP=0'], f) self._write_argument('TRAJECTORY', 'FORCES', f) self._write_argument('VELOCITIES', 'ZERO', f) add_print = add_print + ' ' + 'MD OPT' # if dipole is True, enforce dipole calculation. # Otherwise only if asked for value = self.parameters['dipole'] if 'dipole' in properties or value: self._write_argument('DIPOLE', '', f) # print argument, here other options could change this value = self.parameters['print_out'] assert(type(value) is str) value = value + add_print if not len(value) == 0: self._write_argument('PRINT', value, f) f.write('#\n') # write general input arguments self._write_input_arguments(f) f.write('#\n') # write basis set, ecps, mcps, auxis, augment basis = self.parameters['basis'] if 'all' not in basis: basis['all'] = 'DZVP' self._write_basis(f, atoms, basis, string='BASIS') ecps = self.parameters['ecps'] if not len(ecps) == 0: self._write_basis(f, atoms, ecps, string='ECPS') mcps = self.parameters['mcps'] if not len(mcps) == 0: self._write_basis(f, atoms, mcps, string='MCPS') auxis = self.parameters['auxis'] if not len(auxis) == 0: self._write_basis(f, atoms, auxis, string='AUXIS') augment = self.parameters['augment'] if not len(augment) == 0: self._write_basis(f, atoms, augment, string='AUGMENT') # write geometry self._write_atomic_coordinates(f, atoms) # write pickle of Parameters pickle.dump(self.parameters, open(self.label + '/deMon_parameters.pckl', 'wb')) # write xyz file for good measure. ase.io.write(self.label + '/deMon_atoms.xyz', self.atoms)
def write_input(self, atoms, properties=None, system_changes=None): FileIOCalculator.write_input(self, atoms, properties, system_changes) self.initialize(atoms) self.parameters.write(os.path.join(self.directory, 'parameters.ase')) if 'xctype' in self.parameters: if 'xc' in self.parameters: raise RuntimeError("You can't use both 'xctype' and 'xc'!") if self.parameters.get('autokpt'): if 'kpts' in self.parameters: raise RuntimeError("You can't use both 'autokpt' and 'kpts'!") if 'ngridk' in self.parameters: raise RuntimeError("You can't use both 'autokpt' and 'ngridk'!") if 'ngridk' in self.parameters: if 'kpts' in self.parameters: raise RuntimeError("You can't use both 'ngridk' and 'kpts'!") if self.parameters.get('autoswidth'): if 'smearing' in self.parameters: raise RuntimeError("You can't use both 'autoswidth' and 'smearing'!") if 'swidth' in self.parameters: raise RuntimeError("You can't use both 'autoswidth' and 'swidth'!") fd = open(os.path.join(self.directory, 'elk.in'), 'w') # handle custom specifications of rmt # (absolute or relative to default) in Bohr # rmt = {'H': 0.7, 'O': -0.2, ...} if self.parameters.get('rmt', None) is not None: self.rmt = self.parameters['rmt'].copy() assert len(self.rmt.keys()) == len(list(set(self.rmt.keys()))), 'redundant rmt definitions' self.parameters.pop('rmt') # this is not an elk keyword! else: self.rmt = None inp = {} inp.update(self.parameters) if 'xc' in self.parameters: xctype = {'LDA': 3, # PW92 'PBE': 20, 'REVPBE': 21, 'PBESOL': 22, 'WC06': 26, 'AM05': 30}[self.parameters.xc] inp['xctype'] = xctype del inp['xc'] if 'kpts' in self.parameters: mp = kpts2mp(atoms, self.parameters.kpts) inp['ngridk'] = tuple(mp) vkloff = [] # is this below correct? for nk in mp: if nk % 2 == 0: # shift kpoint away from gamma point vkloff.append(0.5) else: vkloff.append(0) inp['vkloff'] = vkloff del inp['kpts'] if 'smearing' in self.parameters: name = self.parameters.smearing[0].lower() if name == 'methfessel-paxton': stype = self.parameters.smearing[2] else: stype = {'gaussian': 0, 'fermi-dirac': 3, }[name] inp['stype'] = stype inp['swidth'] = self.parameters.smearing[1] del inp['smearing'] # convert keys to ELK units for key, value in inp.items(): if key in elk_parameters: inp[key] /= elk_parameters[key] # write all keys for key, value in inp.items(): fd.write('%s\n' % key) if isinstance(value, bool): fd.write('.%s.\n\n' % ('false', 'true')[value]) elif isinstance(value, (int, float)): fd.write('%s\n\n' % value) else: fd.write('%s\n\n' % ' '.join([str(x) for x in value])) # cell fd.write('avec\n') for vec in atoms.cell: fd.write('%.14f %.14f %.14f\n' % tuple(vec / Bohr)) fd.write('\n') # atoms species = {} symbols = [] for a, (symbol, m) in enumerate( zip(atoms.get_chemical_symbols(), atoms.get_initial_magnetic_moments())): if symbol in species: species[symbol].append((a, m)) else: species[symbol] = [(a, m)] symbols.append(symbol) fd.write('atoms\n%d\n' % len(species)) #scaled = atoms.get_scaled_positions(wrap=False) scaled = np.linalg.solve(atoms.cell.T, atoms.positions.T).T for symbol in symbols: fd.write("'%s.in' : spfname\n" % symbol) fd.write('%d\n' % len(species[symbol])) for a, m in species[symbol]: fd.write('%.14f %.14f %.14f 0.0 0.0 %.14f\n' % (tuple(scaled[a])+ (m,))) # species species_path = self.parameters.get('species_dir') if species_path is None: species_path = os.environ.get('ELK_SPECIES_PATH') if species_path is None: raise RuntimeError( 'Missing species directory! Use species_dir ' + 'parameter or set $ELK_SPECIES_PATH environment variable.') # custom species definitions if self.rmt is not None: fd.write("\n") sfile = os.path.join(os.environ['ELK_SPECIES_PATH'], 'elk.in') assert os.path.exists(sfile) slines = open(sfile, 'r').readlines() # remove unused species for s in self.rmt.keys(): if s not in species.keys(): self.rmt.pop(s) # add undefined species with defaults for s in species.keys(): if s not in self.rmt.keys(): # use default rmt for undefined species self.rmt.update({s: 0.0}) # write custom species into elk.in skeys = list(set(self.rmt.keys())) # unique skeys.sort() for s in skeys: found = False for n, line in enumerate(slines): if line.find("'" + s + "'") > -1: begline = n - 1 for n, line in enumerate(slines[begline:]): if not line.strip(): # first empty line endline = n found = True break assert found fd.write("species\n") # set rmt on third line rmt = self.rmt[s] assert isinstance(rmt, (float,int)) if rmt <= 0.0: # relative # split needed because H is defined with comments newrmt = float(slines[begline + 3].split()[0].strip()) + rmt else: newrmt = rmt slines[begline + 3] = '%6s\n' % str(newrmt) for l in slines[begline: begline + endline]: fd.write('%s' % l) fd.write("\n") else: # use default species # if sppath is present in elk.in it overwrites species blocks! fd.write("sppath\n'%s'\n\n" % os.environ['ELK_SPECIES_PATH'])
def write_input(self, atoms, properties=None, system_changes=None): """Writes the input file""" FileIOCalculator.write_input(self, atoms, properties, system_changes) magmoms = atoms.get_initial_magnetic_moments().tolist() self.parameters.initial_magmoms = magmoms self.parameters.write(self.label + '.ase') # Set default behavior if ('multiplicity' not in self.parameters): tot_magmom = atoms.get_initial_magnetic_moments().sum() mult = tot_magmom + 1 else: mult = self.parameters['multiplicity'] filename = self.label + '.com' inputfile = open(filename, 'w') link0 = str() route = '#p %s/%s' % (self.parameters['method'], self.parameters['basis']) for key, val in self.parameters.items(): if key.lower() in link0_keys: link0 += ('%%%s=%s\n' % (key, val)) elif key.lower() in route_self_keys: if (val.lower() == key.lower()): route += (' ' + val) else: if ',' in val: route += ' %s(%s)' % (key, val) else: route += ' %s=%s' % (key, val) elif key.lower() in route_keys: route += ' %s=%s' % (key, val) if (self.ioplist): route += ' IOp(' for iop in self.ioplist: route += (' ' + iop) if (len(self.ioplist) > 1) and (iop != len(self.ioplist) - 1): route += ',' route += ')' inputfile.write(link0) inputfile.write(route) inputfile.write(' \n\n') inputfile.write('Gaussian input prepared by ASE\n\n') inputfile.write('%i %i\n' % (self.parameters['charge'], mult)) symbols = atoms.get_chemical_symbols() coordinates = atoms.get_positions() for i in range(len(atoms)): inputfile.write('%-10s' % symbols[i]) for j in range(3): inputfile.write('%20.10f' % coordinates[i, j]) inputfile.write('\n') inputfile.write('\n') if ('gen' in self.parameters['basis'].lower()): if (self.basisfile is None): raise RuntimeError('Please set basisfile.') elif (not os.path.isfile(self.basisfile)): error = 'Basis file %s does not exist.' % self.basisfile raise RuntimeError(error) else: f2 = open(self.basisfile, 'r') inputfile.write(f2.read()) f2.close() if atoms.get_pbc().any(): cell = atoms.get_cell() line = str() for v in cell: line += 'TV %20.10f%20.10f%20.10f\n' % (v[0], v[1], v[2]) inputfile.write(line) inputfile.write('\n\n') inputfile.close()