def test_combine(testdir): dirname = 'subdir' vibname = 'ir' with workdir(dirname, mkdir=True): atoms = molecule('C2H6') ir = Infrared(atoms) assert ir.name == vibname ir.calc = RandomCalculator() ir.run() freqs = ir.get_frequencies() ints = ir.intensities assert ir.combine() == 49 ir = Infrared(atoms) assert (freqs == ir.get_frequencies()).all() assert (ints == ir.intensities).all() vib = Vibrations(atoms, name=vibname) assert (freqs == vib.get_frequencies()).all() # Read the data from other working directory with workdir('..'): ir = Infrared(atoms, name=f'{dirname}/{vibname}') assert (freqs == ir.get_frequencies()).all() ir = Infrared(atoms) assert ir.split() == 1 assert (freqs == ir.get_frequencies()).all() assert (ints == ir.intensities).all() vib = Vibrations(atoms, name=vibname) assert (freqs == vib.get_frequencies()).all() assert ir.clean() == 49
def use_tmp_workdir(tmp_path): # Pytest can on some systems provide a Path from pathlib2. Normalize: path = Path(str(tmp_path)) with workdir(path, mkdir=True): yield tmp_path # We print the path so user can see where test failed, if it failed. print(f'Testpath: {path}')
def test_bandstructure_transform_mcl(testdir): # Test that bandpath() correctly transforms the band path from # reference (canonical) cell to actual cell provided by user. def _atoms(cell): atoms = Atoms(cell=cell, pbc=True) atoms.calc = FreeElectrons() return atoms # MCL with beta > 90, which is a common convention -- but ours is # alpha < 90. We want the bandpath returned by that cell to yield the # exact same band structure as our own (alpha < 90) version of the # same cell. cell = Cell.new([3., 5., 4., 90., 110., 90.]) lat = cell.get_bravais_lattice() density = 10.0 cell0 = lat.tocell() path0 = lat.bandpath(density=density) print(cell.cellpar().round(3)) print(cell0.cellpar().round(3)) with workdir('files', mkdir=True): bs = calculate_band_structure(_atoms(cell), cell.bandpath(density=density)) bs.write('bs.json') # bs.plot(emin=0, emax=20, filename='fig.bs.svg') bs0 = calculate_band_structure(_atoms(cell0), path0) bs0.write('bs0.json') # bs0.plot(emin=0, emax=20, filename='fig.bs0.svg') maxerr = np.abs(bs.energies - bs0.energies).max() assert maxerr < 1e-12, maxerr
def write_input(self, atoms, properties, system_changes): """Write input parameters to files-file.""" with workdir(self.directory, mkdir=True): io.write_all_inputs(atoms, properties, parameters=self.parameters, label=self.prefix)
def test_ch4(tmp_path, spec): # XXX Convert to string since pytest can sometimes gives us tmp_path # as a pathlib2 path. with workdir(str(tmp_path), mkdir=True): e_ch4 = _calculate(spec, 'CH4') e_c2h2 = _calculate(spec, 'C2H2') e_h2 = _calculate(spec, 'H2') energy = e_ch4 - 0.5 * e_c2h2 - 1.5 * e_h2 print(energy) ref_energy = -2.8 assert abs(energy - ref_energy) < 0.3
def sessionlevel_testing_path(tmp_path_factory): # We cd into a tempdir so tests and fixtures won't create files # elsewhere (e.g. in the unsuspecting user's directory). # # However we regard it as an error if the tests leave files there, # because they can access each others' files and hence are not # independent. Therefore we want them to explicitly use the # "testdir" fixture which ensures that each has a clean directory. path = Path(tmp_path_factory.mktemp('ase-test-workdir')) with workdir(path): yield path raise_if_stale_files(path)
def test_bands(): from ase.build import bulk from ase.calculators.siesta import Siesta from ase.utils import workdir from ase.dft.band_structure import calculate_band_structure atoms = bulk('Si') with workdir('files', mkdir=True): path = atoms.cell.bandpath('GXWK', density=10) atoms.calc = Siesta(kpts=[2, 2, 2]) bs = calculate_band_structure(atoms, path) print(bs) bs.write('bs.json')
def test_lattice_bandstructure(i, lat): with workdir('files', mkdir=True): xid = '{:02d}.{}'.format(i, lat.variant) path = lat.bandpath(density=10) path.write('path.{}.json'.format(xid)) atoms = Atoms(cell=lat.tocell(), pbc=True) atoms.calc = FreeElectrons(nvalence=0, kpts=path.kpts) bs = calculate_band_structure(atoms, path) bs.write('bs.{}.json'.format(xid)) ax = plt.gca() bs.plot(ax=ax, emin=0, emax=20, filename='fig.{}.png'.format(xid)) ax.clear()
def get_userscr(prefix, command): prefix_test = prefix + '_test' command = command.replace('PREFIX', prefix_test) with workdir(prefix_test, mkdir=True): try: call(command, shell=True, timeout=2) except TimeoutExpired: pass try: with open(prefix_test + '.log') as fd: for line in fd: if line.startswith('GAMESS supplementary output files'): return ' '.join(line.split(' ')[8:]).strip() except FileNotFoundError: return None return None
def run(atoms, name): dirname = 'test-abinit/{}'.format(name) with workdir(dirname, mkdir=True): header = 'test {} in {}'.format(name, dirname) print() print(header) print('=' * len(header)) print('input:', atoms.calc.parameters) atoms.get_potential_energy() atoms.get_forces() print(sorted(atoms.calc.results)) for key, value in atoms.calc.results.items(): if isinstance(value, np.ndarray): print(key, value.shape, value.dtype) else: print(key, value) for name in required_quantities: assert name in atoms.calc.results return atoms.calc.results
def sessionlevel_testing_path(): # We cd into a tempdir so tests and fixtures won't create files # elsewhere (e.g. in the unsuspecting user's directory). # # However we regard it as an error if the tests leave files there, # because they can access each others' files and hence are not # independent. Therefore we want them to explicitly use the # "testdir" fixture which ensures that each has a clean directory. # # To prevent tests from writing files, we chmod the directory. # But if the tests are killed, we cannot clean it up and it will # disturb other pytest runs if we use the pytest tempdir factory. # # So we use the tempfile module for this temporary directory. import tempfile with tempfile.TemporaryDirectory(prefix='ase-test-workdir-') as tempdir: path = Path(tempdir) path.chmod(0o555) with workdir(path): yield path path.chmod(0o755)
def read(self, label): """Read results from ABINIT's text-output file.""" # XXX I think we should redo the concept of 'restarting'. # It makes sense to load a previous calculation as # # * static, calculator-independent results # * an actual calculator capable of calculating # # Either of which is simpler than our current mechanism which # implies both at the same time. Moreover, we don't need # something like calc.read(label). # # What we need for these two purposes is # # * calc = MyCalculator.read(basefile) # (or maybe it should return Atoms with calc attached) # * results = read_results(basefile, format='abinit') # # where basefile determines the file tree. FileIOCalculator.read(self, label) with workdir(self.directory): self.atoms, self.parameters = io.read_ase_and_abinit_inputs( self.prefix) self.results = io.read_results(self.prefix)
def run(name, par): if name not in test_calculator_names: return with workdir(name + '-test', mkdir=True): h2(name, par)
from ase.build import bulk from ase.calculators.siesta import Siesta from ase.utils import workdir from ase.dft.band_structure import calculate_band_structure atoms = bulk('Si') with workdir('files', mkdir=True): path = atoms.cell.bandpath('GXWK', density=10) atoms.calc = Siesta(kpts=[2, 2, 2]) bs = calculate_band_structure(atoms, path) print(bs) bs.write('bs.json')
def create_png_files(raise_exceptions=False): from ase.utils import workdir try: check_call(['povray', '-h'], stderr=DEVNULL) except (FileNotFoundError, CalledProcessError): warnings.warn('No POVRAY!') # Replace write_pov with write_png: from ase.io import pov from ase.io.png import write_png def write_pov(filename, atoms, povray_settings={}, isosurface_data=None, **generic_projection_settings): write_png( Path(filename).with_suffix('.png'), atoms, **generic_projection_settings) class DummyRenderer: def render(self): pass return DummyRenderer() pov.write_pov = write_pov for dir, pyname, outnames in creates(): path = join(dir, pyname) t0 = os.stat(path)[ST_MTIME] run = False for outname in outnames: try: t = os.stat(join(dir, outname))[ST_MTIME] except OSError: run = True break else: if t < t0: run = True break if run: print('running:', path) with workdir(dir): import matplotlib.pyplot as plt plt.figure() try: runpy.run_path(pyname) except KeyboardInterrupt: return except Exception: if raise_exceptions: raise else: traceback.print_exc() for n in plt.get_fignums(): plt.close(n) for outname in outnames: print(dir, outname)
def use_tmp_workdir(tmp_path): # Pytest can on some systems provide a Path from pathlib2. Normalize: path = Path(str(tmp_path)) with workdir(path, mkdir=True): yield tmp_path
def read_results(self): with workdir(self.directory): self.results = io.read_results(self.prefix)
h2 = read('h2.traj') assert abs(e - h2.get_potential_energy()) < 1e-12 assert abs(f - h2.get_forces()).max() < 1e-12 parameters = { 'abinit': dict(ecut=200, toldfe=0.0001), 'aims': dict(sc_accuracy_rho=5.e-3, sc_accuracy_forces=1e-4, xc='LDA'), 'crystal': dict(basis='sto-3g'), 'gpaw': dict(mode={'name': 'lcao', 'interpolation': 'fft'}, basis='sz(dzp)'), 'elk': dict(tasks=0, rgkmax=5.0, epsengy=1.0, epspot=1.0, tforce=True, pbc=True), 'jacapo': dict(pbc=True), 'vasp': dict(xc='LDA'), 'Psi4': dict(), # XXX we don't have the pseudopotential for Espresso. # We need some kind of installation/config system for managing that. # Disabling espresso test until we get that. --askhl #'espresso': dict(pbc=True, tprnfor=True, # pseudopotentials={'H': 'H.pbe-rrkjus_psl.0.1.UPF'}), 'emt': {}} for name in parameters: if name not in test_calculator_names: continue par = parameters[name] with workdir(name + '-test', mkdir=True): h2(name, par)
def _calculate(code, name): atoms = molecule(name) atoms.center(vacuum=3.5) with workdir('test-{}'.format(name), mkdir=True): atoms.calc = code.calc() return atoms.get_potential_energy()