def read_results(self): """Reads the output file using GaussianReader""" from ase.io.gaussian import read_gaussian_out filename = self.label + '.log' self.results['energy'] = read_gaussian_out(filename, quantity='energy') self.results['forces'] = read_gaussian_out(filename, quantity='forces') self.results['dipole'] = read_gaussian_out(filename, quantity='dipole')
def read_output(self, filename, quantity): """Reads the output file using GaussianReader""" from ase.io.gaussian import read_gaussian_out if (quantity == 'energy'): return read_gaussian_out(filename, quantity='energy') elif (quantity == 'forces'): forces = read_gaussian_out(filename, quantity='forces') return forces elif (quantity == 'dipole'): return read_gaussian_out(filename, quantity='dipole') elif (quantity == 'version'): return read_gaussian_out(filename, quantity='version')
def read_results(self): """Reads the output file using GaussianReader""" from ase.io.gaussian import read_gaussian_out filename = self.label + '.log' quantities = ['energy', 'forces', 'dipole'] with open(filename, 'r') as fileobj: for quant in quantities: self.results[quant] = read_gaussian_out(fileobj, quantity=quant) self.results['magmom'] = read_gaussian_out(fileobj, quantity='multiplicity') self.results['magmom'] -= 1
def read(self, label): """Used to read the results of a previous calculation if restarting""" FileIOCalculator.read(self, label) from ase.io.gaussian import read_gaussian_out filename = self.label + '.log' if not os.path.isfile(filename): raise ReadError self.atoms = read_gaussian_out(filename, quantity='atoms') self.parameters = Parameters.read(self.label + '.ase') initial_magmoms = self.parameters.pop('initial_magmoms') self.atoms.set_initial_magnetic_moments(initial_magmoms) self.read_results()
def get_qmdata(self, file_path=None): "A helper function to fill in the qmdata using CCLib" parser = ccread(file_path) atoms = read_gaussian_out(file_path) self.groundStateDegeneracy = parser.mult self.atomNumbers = atoms.numbers self.atomCoords = (atoms.arrays["positions"], "angstrom") self.stericEnergy = None # Need to fix this self.molecularMass = (parser.atommasses.sum(), "amu") self.energy = (atoms.get_potential_energy(), "eV/molecule") self.atomicNumbers = parser.atomnos self.rotationalConstants = ([], "cm^-1") # Need to fix this self.frequencies = (parser.vibfreqs, "cm^-1") self.source = None self.method = parser.metadata["functional"]
def read(filename, index=None, format=None): """Read Atoms object(s) from file. filename: str Name of the file to read from. index: int or slice If the file contains several configurations, the last configuration will be returned by default. Use index=n to get configuration number n (counting from zero). format: str Used to specify the file-format. If not given, the file-format will be guessed by the *filetype* function. Known formats: ========================= ============= format short name ========================= ============= GPAW restart-file gpw Dacapo netCDF output file dacapo Old ASE netCDF trajectory nc Virtual Nano Lab file vnl ASE pickle trajectory traj ASE bundle trajectory bundle GPAW text output gpaw-text CUBE file cube XCrySDen Structure File xsf Dacapo text output dacapo-text XYZ-file xyz VASP POSCAR/CONTCAR file vasp VASP OUTCAR file vasp_out SIESTA STRUCT file struct_out ABINIT input file abinit V_Sim ascii file v_sim Protein Data Bank pdb CIF-file cif FHI-aims geometry file aims FHI-aims output file aims_out VTK XML Image Data vti VTK XML Structured Grid vts VTK XML Unstructured Grid vtu TURBOMOLE coord file tmol TURBOMOLE gradient file tmol-gradient exciting input exi AtomEye configuration cfg WIEN2k structure file struct DftbPlus input file dftb CASTEP geom file cell CASTEP output file castep CASTEP trajectory file geom ETSF format etsf.nc DFTBPlus GEN format gen CMR db/cmr-file db CMR db/cmr-file cmr LAMMPS dump file lammps EON reactant.con file eon Gromacs coordinates gro Gaussian com (input) file gaussian Gaussian output file gaussian_out Quantum espresso in file esp_in Quantum espresso out file esp_out Extended XYZ file extxyz NWChem input file nw ========================= ============= """ if isinstance(filename, str) and ('.json@' in filename or '.db@' in filename or filename.startswith('pg://') and '@' in filename): filename, index = filename.rsplit('@', 1) if index.isdigit(): index = int(index) else: if isinstance(filename, str): p = filename.rfind('@') if p != -1: try: index = string2index(filename[p + 1:]) except ValueError: pass else: filename = filename[:p] if isinstance(index, str): index = string2index(index) if format is None: format = filetype(filename) if format.startswith('gpw'): import gpaw r = gpaw.io.open(filename, 'r') positions = r.get('CartesianPositions') * Bohr numbers = r.get('AtomicNumbers') cell = r.get('UnitCell') * Bohr pbc = r.get('BoundaryConditions') tags = r.get('Tags') magmoms = r.get('MagneticMoments') energy = r.get('PotentialEnergy') * Hartree if r.has_array('CartesianForces'): forces = r.get('CartesianForces') * Hartree / Bohr else: forces = None atoms = Atoms(positions=positions, numbers=numbers, cell=cell, pbc=pbc) if tags.any(): atoms.set_tags(tags) if magmoms.any(): atoms.set_initial_magnetic_moments(magmoms) else: magmoms = None atoms.calc = SinglePointDFTCalculator(atoms, energy=energy, forces=forces, magmoms=magmoms) kpts = [] if r.has_array('IBZKPoints'): for w, kpt, eps_n, f_n in zip(r.get('IBZKPointWeights'), r.get('IBZKPoints'), r.get('Eigenvalues'), r.get('OccupationNumbers')): kpts.append( SinglePointKPoint(w, kpt[0], kpt[1], eps_n[0], f_n[0])) atoms.calc.kpts = kpts return atoms if format in ['json', 'db', 'postgresql']: from ase.db.core import connect, dict2atoms if index == slice(None, None): index = None images = [ dict2atoms(d) for d in connect(filename, format).select(index) ] if len(images) == 1: return images[0] else: return images if index is None: index = -1 if format == 'castep': from ase.io.castep import read_castep return read_castep(filename, index) if format == 'castep_cell': import ase.io.castep return ase.io.castep.read_cell(filename, index) if format == 'castep_geom': import ase.io.castep return ase.io.castep.read_geom(filename, index) if format == 'exi': from ase.io.exciting import read_exciting return read_exciting(filename, index) if format in ['xyz', 'extxyz']: from ase.io.extxyz import read_xyz return read_xyz(filename, index) if format == 'traj': from ase.io.trajectory import read_trajectory return read_trajectory(filename, index) if format == 'bundle': from ase.io.bundletrajectory import read_bundletrajectory return read_bundletrajectory(filename, index) if format == 'cube': from ase.io.cube import read_cube return read_cube(filename, index) if format == 'nc': from ase.io.netcdf import read_netcdf return read_netcdf(filename, index) if format == 'gpaw-text': from ase.io.gpawtext import read_gpaw_text return read_gpaw_text(filename, index) if format == 'dacapo-text': from ase.io.dacapo import read_dacapo_text return read_dacapo_text(filename) if format == 'dacapo': from ase.io.dacapo import read_dacapo return read_dacapo(filename) if format == 'xsf': from ase.io.xsf import read_xsf return read_xsf(filename, index) if format == 'vasp': from ase.io.vasp import read_vasp return read_vasp(filename) if format == 'vasp_out': from ase.io.vasp import read_vasp_out return read_vasp_out(filename, index) if format == 'abinit': from ase.io.abinit import read_abinit return read_abinit(filename) if format == 'v_sim': from ase.io.v_sim import read_v_sim return read_v_sim(filename) if format == 'mol': from ase.io.mol import read_mol return read_mol(filename) if format == 'pdb': from ase.io.pdb import read_pdb return read_pdb(filename, index) if format == 'cif': from ase.io.cif import read_cif return read_cif(filename, index) if format == 'struct': from ase.io.wien2k import read_struct return read_struct(filename) if format == 'struct_out': from ase.io.siesta import read_struct return read_struct(filename) if format == 'vti': from ase.io.vtkxml import read_vti return read_vti(filename) if format == 'vts': from ase.io.vtkxml import read_vts return read_vts(filename) if format == 'vtu': from ase.io.vtkxml import read_vtu return read_vtu(filename) if format == 'aims': from ase.io.aims import read_aims return read_aims(filename) if format == 'aims_out': from ase.io.aims import read_aims_output return read_aims_output(filename, index) if format == 'iwm': from ase.io.iwm import read_iwm return read_iwm(filename) if format == 'Cmdft': from ase.io.cmdft import read_I_info return read_I_info(filename) if format == 'tmol': from ase.io.turbomole import read_turbomole return read_turbomole(filename) if format == 'tmol-gradient': from ase.io.turbomole import read_turbomole_gradient return read_turbomole_gradient(filename) if format == 'cfg': from ase.io.cfg import read_cfg return read_cfg(filename) if format == 'dftb': from ase.io.dftb import read_dftb return read_dftb(filename) if format == 'sdf': from ase.io.sdf import read_sdf return read_sdf(filename) if format == 'etsf': from ase.io.etsf import ETSFReader return ETSFReader(filename).read_atoms() if format == 'gen': from ase.io.gen import read_gen return read_gen(filename) if format == 'cmr': from ase.io.cmr_io import read_db return read_db(filename, index) if format == 'lammps': from ase.io.lammpsrun import read_lammps_dump return read_lammps_dump(filename, index) if format == 'eon': from ase.io.eon import read_reactant_con return read_reactant_con(filename) if format == 'gromacs': from ase.io.gromacs import read_gromacs return read_gromacs(filename) if format == 'gaussian': from ase.io.gaussian import read_gaussian return read_gaussian(filename) if format == 'gaussian_out': from ase.io.gaussian import read_gaussian_out return read_gaussian_out(filename, index) if format == 'esp_in': from ase.io.espresso import read_espresso_in return read_espresso_in(filename) if format == 'esp_out': from ase.io.espresso import read_espresso_out return read_espresso_out(filename, index) if format == 'nw': from ase.io.nwchem import read_nwchem_input return read_nwchem_input(filename) raise RuntimeError('File format descriptor ' + format + ' not recognized!')
def read(filename, index=None, format=None): """Read Atoms object(s) from file. filename: str Name of the file to read from. index: int or slice If the file contains several configurations, the last configuration will be returned by default. Use index=n to get configuration number n (counting from zero). format: str Used to specify the file-format. If not given, the file-format will be guessed by the *filetype* function. Known formats: ========================= ============= format short name ========================= ============= GPAW restart-file gpw Dacapo netCDF output file dacapo Old ASE netCDF trajectory nc Virtual Nano Lab file vnl ASE pickle trajectory traj ASE bundle trajectory bundle GPAW text output gpaw-text CUBE file cube XCrySDen Structure File xsf Dacapo text output dacapo-text XYZ-file xyz VASP POSCAR/CONTCAR file vasp VASP OUTCAR file vasp_out VASP XDATCAR file vasp_xdatcar SIESTA STRUCT file struct_out ABINIT input file abinit V_Sim ascii file v_sim Protein Data Bank pdb CIF-file cif FHI-aims geometry file aims FHI-aims output file aims_out VTK XML Image Data vti VTK XML Structured Grid vts VTK XML Unstructured Grid vtu TURBOMOLE coord file tmol TURBOMOLE gradient file tmol-gradient exciting input exi AtomEye configuration cfg WIEN2k structure file struct DftbPlus input file dftb CASTEP geom file cell CASTEP output file castep CASTEP trajectory file geom ETSF format etsf.nc DFTBPlus GEN format gen CMR db/cmr-file db CMR db/cmr-file cmr LAMMPS dump file lammps EON reactant.con file eon Gromacs coordinates gro Gaussian com (input) file gaussian Gaussian output file gaussian_out Quantum espresso in file esp_in Quantum espresso out file esp_out Extended XYZ file extxyz NWChem input file nw Materials Studio file xsd ========================= ============= Many formats allow on open file-like object to be passed instead of ``filename``. In this case the format cannot be auto-decected, so the ``format`` argument should be explicitly given. """ if isinstance(filename, str) and ( '.json@' in filename or '.db@' in filename or filename.startswith('pg://') and '@' in filename): filename, index = filename.rsplit('@', 1) if index.isdigit(): index = int(index) else: if isinstance(filename, str): p = filename.rfind('@') if p != -1: try: index = string2index(filename[p + 1:]) except ValueError: pass else: filename = filename[:p] if isinstance(index, str): index = string2index(index) if format is None: format = filetype(filename) if format.startswith('gpw'): import gpaw r = gpaw.io.open(filename, 'r') positions = r.get('CartesianPositions') * Bohr numbers = r.get('AtomicNumbers') cell = r.get('UnitCell') * Bohr pbc = r.get('BoundaryConditions') tags = r.get('Tags') magmoms = r.get('MagneticMoments') energy = r.get('PotentialEnergy') * Hartree if r.has_array('CartesianForces'): forces = r.get('CartesianForces') * Hartree / Bohr else: forces = None atoms = Atoms(positions=positions, numbers=numbers, cell=cell, pbc=pbc) if tags.any(): atoms.set_tags(tags) if magmoms.any(): atoms.set_initial_magnetic_moments(magmoms) else: magmoms = None atoms.calc = SinglePointDFTCalculator(atoms, energy=energy, forces=forces, magmoms=magmoms) kpts = [] if r.has_array('IBZKPoints'): for w, kpt, eps_n, f_n in zip(r.get('IBZKPointWeights'), r.get('IBZKPoints'), r.get('Eigenvalues'), r.get('OccupationNumbers')): kpts.append(SinglePointKPoint(w, kpt[0], kpt[1], eps_n[0], f_n[0])) atoms.calc.kpts = kpts return atoms if format in ['json', 'db', 'postgresql']: if index == slice(None, None): index = None from ase.db.core import connect images = [row.toatoms() for row in connect(filename, format).select(index)] if len(images) == 1: return images[0] else: return images if index is None: index = -1 if format == 'castep': from ase.io.castep import read_castep return read_castep(filename, index) if format == 'castep_cell': import ase.io.castep return ase.io.castep.read_cell(filename, index) if format == 'castep_geom': import ase.io.castep return ase.io.castep.read_geom(filename, index) if format == 'exi': from ase.io.exciting import read_exciting return read_exciting(filename, index) if format in ['xyz', 'extxyz']: from ase.io.extxyz import read_xyz return read_xyz(filename, index) if format == 'traj': from ase.io.trajectory import read_trajectory return read_trajectory(filename, index) if format == 'trj': from ase.io.pickletrajectory import read_trajectory return read_trajectory(filename, index) if format == 'bundle': from ase.io.bundletrajectory import read_bundletrajectory return read_bundletrajectory(filename, index) if format == 'cube': from ase.io.cube import read_cube return read_cube(filename, index) if format == 'nc': from ase.io.netcdf import read_netcdf return read_netcdf(filename, index) if format == 'gpaw-text': from ase.io.gpawtext import read_gpaw_text return read_gpaw_text(filename, index) if format == 'dacapo-text': from ase.io.dacapo import read_dacapo_text return read_dacapo_text(filename) if format == 'dacapo': from ase.io.dacapo import read_dacapo return read_dacapo(filename) if format == 'xsf': from ase.io.xsf import read_xsf return read_xsf(filename, index) if format == 'vasp': from ase.io.vasp import read_vasp return read_vasp(filename) if format == 'vasp_out': from ase.io.vasp import read_vasp_out return read_vasp_out(filename, index) if format == 'vasp_xdatcar': from ase.io.vasp import read_vasp_xdatcar return read_vasp_xdatcar(filename, index) if format == 'abinit': from ase.io.abinit import read_abinit return read_abinit(filename) if format == 'v_sim': from ase.io.v_sim import read_v_sim return read_v_sim(filename) if format == 'mol': from ase.io.mol import read_mol return read_mol(filename) if format == 'pdb': from ase.io.pdb import read_pdb return read_pdb(filename, index) if format == 'cif': from ase.io.cif import read_cif return read_cif(filename, index) if format == 'struct': from ase.io.wien2k import read_struct return read_struct(filename) if format == 'struct_out': from ase.io.siesta import read_struct return read_struct(filename) if format == 'vti': from ase.io.vtkxml import read_vti return read_vti(filename) if format == 'vts': from ase.io.vtkxml import read_vts return read_vts(filename) if format == 'vtu': from ase.io.vtkxml import read_vtu return read_vtu(filename) if format == 'aims': from ase.io.aims import read_aims return read_aims(filename) if format == 'aims_out': from ase.io.aims import read_aims_output return read_aims_output(filename, index) if format == 'iwm': from ase.io.iwm import read_iwm return read_iwm(filename) if format == 'Cmdft': from ase.io.cmdft import read_I_info return read_I_info(filename) if format == 'tmol': from ase.io.turbomole import read_turbomole return read_turbomole(filename) if format == 'tmol-gradient': from ase.io.turbomole import read_turbomole_gradient return read_turbomole_gradient(filename) if format == 'cfg': from ase.io.cfg import read_cfg return read_cfg(filename) if format == 'dftb': from ase.io.dftb import read_dftb return read_dftb(filename) if format == 'sdf': from ase.io.sdf import read_sdf return read_sdf(filename) if format == 'etsf': from ase.io.etsf import ETSFReader return ETSFReader(filename).read_atoms() if format == 'gen': from ase.io.gen import read_gen return read_gen(filename) if format == 'cmr': from ase.io.cmr_io import read_db return read_db(filename, index) if format == 'lammps': from ase.io.lammpsrun import read_lammps_dump return read_lammps_dump(filename, index) if format == 'eon': from ase.io.eon import read_reactant_con return read_reactant_con(filename) if format == 'gromacs': from ase.io.gromacs import read_gromacs return read_gromacs(filename) if format == 'gaussian': from ase.io.gaussian import read_gaussian return read_gaussian(filename) if format == 'gaussian_out': from ase.io.gaussian import read_gaussian_out return read_gaussian_out(filename, index) if format == 'esp_in': from ase.io.espresso import read_espresso_in return read_espresso_in(filename) if format == 'esp_out': from ase.io.espresso import read_espresso_out return read_espresso_out(filename, index) if format == 'nw': from ase.io.nwchem import read_nwchem_input return read_nwchem_input(filename) if format == 'xsd': from ase.io.xsd import read_xsd return read_xsd(filename) raise RuntimeError('File format descriptor ' + format + ' not recognized!')
def process(self, label, root=1, nstates=5, clean=False, **kwargs): """Generalized process for optimization, ground state, frequency and TD """ root = int(root) nstates = int(nstates) if label not in proc_params.keys(): raise KeyError("Process parameter not correct!") self._set_label(label) # Causing writing label.com file # Clean up then return if clean: parprint("Clean up previous calculations for {0}".format(label)) self.clean() return True params = proc_params[label] # in_atoms used to generate input try: in_file = self.base / params["input"] in_atoms = read(in_file) except Exception: raise out_files = [ "{0}.chk".format(self.label), "{0}.log".format(self.label) ] if "output" in params.keys(): out_struct = self.base / params["output"].format(root=root, nstates=nstates) out_files.append(out_struct) else: out_struct = None # Calculation finished if all([Path(o_).exists() for o_ in out_files]): parprint("Calculation process {0} is finished".format(label)) #TODO: add post processing functions return True # Copy chk file from previous state if "inchk" in params.keys(): utils.copy_chk(self.base, params["inchk"], label) # Update parameters kw_mod = { k: v.format(root=root, nstates=nstates, **kwargs) for k, v in params["kw"].items() } self.set(**kw_mod) # Get environment nproc = utils.get_nproc() if nproc is None: nproc = 1 mem = max(1024 * nproc, 8192) self.set(mem="{0}MB".format(mem), nprocshared=nproc, chk="{0}.chk".format(self.label)) # Execute job now self.write_input(in_atoms) ec = utils.run_job(self.label) if ec != 0: # Some error parprint("Process {0} failed, please check".format(label)) out_atoms = read_gaussian_out("{0}.log".format(self.label), quantity="structures")[-1] if out_struct is not None: write(out_struct, out_atoms)
def calculate(self, autotst_object, calc): """ A method to perform a calculation given a calculator and an AutoTST object. If the corresponding log file already exists, we will skip it :params: autotst_object: (AutoTST_Molecule, AutoTST_TS, AutoTST_Reaction) an AutoTST object that you want to run calculations on calc: (ase.calculators.calculator) the calculator that you want to run """ def update_from_ase(autotst_obj, ase_object): """ A function designed to update all objects based off of their ase objects """ if isinstance(autotst_obj, autotst.molecule.AutoTST_Molecule): autotst_obj.ase_molecule = ase_object autotst_obj.update_from_ase_mol() if isinstance(autotst_obj, autotst.reaction.AutoTST_Reaction): autotst_obj.ts.ase_ts = ase_object autotst_obj.ts.update_from_ase_ts() if isinstance(autotst_obj, autotst.reaction.AutoTST_TS): autotst_obj.ase_ts = ase_object autotst_obj.update_from_ase_ts() return autotst_obj current_path = os.getcwd() scratch_path = os.path.expanduser( calc.scratch) new_file_name = calc.label.replace( "left", "(").replace("right", ")") + ".log" old_file_name = calc.label + ".log" if isinstance(autotst_object, AutoTST_Molecule): ase_object = autotst_object.ase_molecule elif isinstance(autotst_object, AutoTST_Reaction): ase_object = autotst_object.ts.ase_ts elif isinstance(autotst_object, AutoTST_TS): ase_object = autotst_object.ase_ts os.chdir(scratch_path) if os.path.exists(new_file_name): # We found a finished file file... it should be fixed logging.info( "Found previous file for {}, verifying it...".format(new_file_name)) complete, success = self.verify_output_file(new_file_name) if success: logging.info("Old output file verified, reading it in...") ase_object = read_gaussian_out(new_file_name) autotst_object = update_from_ase(autotst_object, ase_object) os.chdir(current_path) return autotst_object, True elif complete: logging.info( "Output file did not converge, attempting to run one last time...") try: calc.calculate(ase_object) ase_object = read_gaussian_out( old_file_name) autotst_object = update_from_ase( autotst_object, ase_object) os.chdir(current_path) return autotst_object, True except: # TODO: add error for seg fault logging.info("{} failed... again...".format(new_file_name)) os.chdir(current_path) return autotst_object, False elif (new_file_name == old_file_name) and (not complete): # The file names are identical and the job isn't complete yet logging.info( "Job appears to be running for this calculation, waiting for it to complete...") from time import sleep f = open(old_file_name) lines = f.readlines()[:5] for line in lines: if "Entering Link" in line: num = line.split()[-1][:-1] scratch_file = "Gau-" + num + ".int" while os.path.exists(scratch_file): sleep(60) logging.info("Job complete, reading in results now by running calculate again...") sleep(30) # waiting a lil while to make sure that the file is fixed... just in case... try: ase_object = read_gaussian_out( old_file_name) autotst_object = update_from_ase( autotst_object, ase_object) os.chdir(current_path) return autotst_object, True except IndexError: logging.info("It appears that the previous log file wasn't finished... removing the files and rerunning") os.remove(old_file_name) os.remove(old_file_name.replace(".log", ".ase")) os.remove(old_file_name.replace(".log", ".com")) return self.calculate(autotst_object, calc) else: logging.info( "Something went wrong... File is neither complete nor successful...") return autotst_object, False elif os.path.exists(old_file_name): complete, success = self.verify_output_file(old_file_name) if not complete: logging.info( "Job appears to be running already, waiting for it to complete...") from time import sleep f = open(old_file_name) lines = f.readlines()[:5] for line in lines: if "Entering Link" in line: num = line.split()[-1][:-1] scratch_file = "Gau-" + num + ".int" while os.path.exists(scratch_file): sleep(60) logging.info("Job complete, reading in results now by running calculate again...") sleep(30) # waiting a lil while to make sure that the file is fixed... just in case... return self.calculate(autotst_object, calc) else: logging.info( "Found previous file for {}, verifying it...".format(old_file_name)) if success: logging.info("Old output file verified, reading it in...") ase_object = read_gaussian_out(old_file_name) autotst_object = update_from_ase(autotst_object, ase_object) os.chdir(current_path) return autotst_object, True else: logging.info( "Something went wrong... File is neither complete nor successful...") return autotst_object, False # Seeing if the file exists else: # File doesn't exist, running calculations logging.info( "Starting calculation for {}...".format(new_file_name)) try: calc.calculate(ase_object) ase_object = read_gaussian_out(old_file_name) autotst_object = update_from_ase(autotst_object, ase_object) os.chdir(current_path) return autotst_object, True except: # TODO: add error for seg fault # first calc failed, trying it once more logging.info( "Failed first attempt for {}. Trying it once more...".format(new_file_name)) try: calc.calculate(ase_object) ase_object = read_gaussian_out(old_file_name) autotst_object = update_from_ase( autotst_object, ase_object) os.chdir(current_path) return autotst_object, True except: # TODO: add error for seg fault logging.info( "{} failed first and second attempt...".format(new_file_name)) os.chdir(current_path) return autotst_object, False
def calculate(self, conformer=None, calc=None): """ A method to perform a calculation given a calculator and an AutoTST object. If the corresponding log file already exists, we will skip it :params: autotst_object: (Molecule, TS, Reaction) an AutoTST object that you want to run calculations on calc: (ase.calculators.calculator) the calculator that you want to run """ assert conformer, "A Conformer or TS object needs to be provided to run calculate..." assert calc, "An ASECalculator object must be provided to run calculate..." current_path = os.getcwd() scratch_path = os.path.expanduser( calc.scratch) new_file_name = calc.label.replace( "left", "(").replace("right", ")") + ".log" old_file_name = calc.label + ".log" os.chdir(scratch_path) if os.path.exists(new_file_name): # We found a finished file file... it should be fixed logging.info( "Found previous file for {}, verifying it...".format(new_file_name)) complete, success = self.verify_output_file(new_file_name) if success: logging.info("Old output file verified, reading it in...") conformer.ase_molecule = read_gaussian_out(new_file_name) conformer.energy = conformer.ase_molecule.get_potential_energy() conformer.update_coords() os.chdir(current_path) return conformer, True elif complete: logging.info( "Output file did not converge, attempting to run one last time...") try: calc.calculate(conformer.ase_molecule) conformer.ase_molecule = read_gaussian_out( old_file_name) conformer.energy = conformer.ase_molecule.get_potential_energy() conformer.update_coords() os.chdir(current_path) return conformer, True except BaseException: # TODO: add error for seg fault logging.info("{} failed... again...".format(new_file_name)) os.chdir(current_path) return conformer, False elif (new_file_name == old_file_name) and (not complete): # The file names are identical and the job isn't complete yet logging.info( "Job appears to be running for this calculation, waiting for it to complete...") from time import sleep f = open(old_file_name) lines = f.readlines()[:5] num = "" for line in lines: if "Entering Link" in line: num = line.split()[-1][:-1] scratch_file = "Gau-" + num + ".int" while os.path.exists(scratch_file): sleep(60) logging.info( "Job complete, reading in results now by running calculate again...") # waiting a lil while to make sure that the file is fixed... # just in case... sleep(15) try: conformer.ase_molecule = read_gaussian_out( old_file_name) conformer.energy = conformer.ase_molecule.get_potential_energy() conformer.update_coords() os.chdir(current_path) return conformer, True except IndexError: logging.info( "It appears that the previous log file wasn't finished... removing the files and rerunning") os.remove(old_file_name) os.remove(old_file_name.replace(".log", ".ase")) os.remove(old_file_name.replace(".log", ".com")) return self.calculate(conformer, calc) else: logging.info( "Something went wrong... File is neither complete nor successful...") return conformer, False elif os.path.exists(old_file_name): complete, success = self.verify_output_file(old_file_name) if not complete: logging.info( "Job appears to be running already, waiting for it to complete...") from time import sleep f = open(old_file_name) lines = f.readlines()[:5] num = None for line in lines: if "Entering Link" in line: num = line.split()[-1][:-1] if not num: logging.info( "Something is wrong... it seems this run was interupted...") logging.info( "deleting {} and recalculating...".format(old_file_name)) os.remove(old_file_name) return self.calculate(conformer, calc) scratch_file = "Gau-" + num + ".int" while os.path.exists(scratch_file): sleep(60) logging.info( "Job complete, reading in results now by running calculate again...") # waiting a lil while to make sure that the file is fixed... # just in case... sleep(30) return self.calculate(conformer, calc) else: logging.info( "Found previous file for {}, verifying it...".format(old_file_name)) if success: logging.info("Old output file verified, reading it in...") conformer.ase_molecule = read_gaussian_out(old_file_name) conformer.energy = conformer.ase_molecule.get_potential_energy() conformer.update_coords() os.chdir(current_path) return conformer, True else: logging.info( "Something went wrong... File is neither complete nor successful...") return conformer, False # Seeing if the file exists else: # File doesn't exist, running calculations logging.info( "Starting calculation for {}...".format(new_file_name)) try: calc.calculate(conformer.ase_molecule) conformer.ase_molecule = read_gaussian_out(old_file_name) conformer.energy = conformer.ase_molecule.get_potential_energy() conformer.update_coords() os.chdir(current_path) return conformer, True except BaseException: # TODO: add error for seg fault # first calc failed, trying it once more logging.info( "Failed first attempt for {}. Trying it once more...".format(new_file_name)) try: calc.calculate(conformer.ase_molecule) conformer.ase_molecule = read_gaussian_out(old_file_name) conformer.energy = conformer.ase_molecule.get_potential_energy() conformer.update_coords() os.chdir(current_path) return conformer, True except BaseException: # TODO: add error for seg fault logging.info( "{} failed first and second attempt...".format(new_file_name)) os.chdir(current_path) return conformer, False