def read(fn, **kwargs): """ Convenience function: Detect file extension and read via Atomistica or ASE. If reading a NetCDF files, frame numbers can be appended via '@'. e.g., a = read('traj.nc@5') """ ext = fn[fn.rfind('.'):].split('@') if len(ext) == 1: if ext[0] == '.out' or ext[0] == '.dat': dirname = os.path.dirname(fn) if len(dirname) == 0: dirname = '.' cycfn = dirname + '/cyc.dat' if os.path.exists(cycfn): return read_atoms(fn, cycfn=cycfn) return read_atoms(fn) elif ext[0] == '.nc': traj = NetCDFTrajectory(fn, **kwargs) return traj[-1] else: return ase.io.read(fn, **kwargs) elif len(ext) == 2: if ext[0] == '.nc': frame = int(ext[1]) fn = fn[:fn.rfind('@')] traj = NetCDFTrajectory(fn) return traj[frame] else: return ase.io.read(fn, **kwargs) else: return ase.io.read(fn, **kwargs)
def test_netcdf_with_nonconsecutive_index(netCDF4): nc = netCDF4.Dataset('7.nc', 'w') nc.createDimension('frame', None) nc.createDimension('atom', 3) nc.createDimension('spatial', 3) nc.createDimension('cell_spatial', 3) nc.createDimension('cell_angular', 3) nc.createVariable('atom_types', 'i', ('atom', )) nc.createVariable('coordinates', 'f4', ( 'frame', 'atom', 'spatial', )) nc.createVariable('cell_lengths', 'f4', ( 'frame', 'cell_spatial', )) nc.createVariable('cell_angles', 'f4', ( 'frame', 'cell_angular', )) nc.createVariable('id', 'i', ( 'frame', 'atom', )) r0 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=float) r1 = 2 * r0 nc.variables['atom_types'][:] = [1, 2, 3] nc.variables['coordinates'][0] = r0 nc.variables['coordinates'][1] = r1 nc.variables['cell_lengths'][:] = 0 nc.variables['cell_angles'][:] = 90 nc.variables['id'][0] = [13, 3, 5] nc.variables['id'][1] = [-1, 0, -5] nc.close() traj = NetCDFTrajectory('7.nc', 'r') assert (traj[0].numbers == [2, 3, 1]).all() assert (traj[1].numbers == [3, 1, 2]).all() traj.close()
def test_netcdf_with_variable_atomic_numbers(netCDF4): # Create a NetCDF file with a per-file definition of atomic numbers. ASE # NetCDFTrajectory can read but not write these types of files. nc = netCDF4.Dataset('6.nc', 'w') nc.createDimension('frame', None) nc.createDimension('atom', 2) nc.createDimension('spatial', 3) nc.createDimension('cell_spatial', 3) nc.createDimension('cell_angular', 3) nc.createVariable('atom_types', 'i', ('atom', )) nc.createVariable('coordinates', 'f4', ( 'frame', 'atom', 'spatial', )) nc.createVariable('cell_lengths', 'f4', ( 'frame', 'cell_spatial', )) nc.createVariable('cell_angles', 'f4', ( 'frame', 'cell_angular', )) r0 = np.array([[1, 2, 3], [4, 5, 6]], dtype=float) r1 = 2 * r0 nc.variables['atom_types'][:] = [1, 2] nc.variables['coordinates'][0] = r0 nc.variables['coordinates'][1] = r1 nc.variables['cell_lengths'][:] = 0 nc.variables['cell_angles'][:] = 90 nc.close() traj = NetCDFTrajectory('6.nc', 'r') assert np.allclose(traj[0].positions, r0) assert np.allclose(traj[1].positions, r1) traj.close()
def write(fn, a, **kwargs): """ Convenience function: Detect file extension and write via Atomistica or ASE. Has support for writing LAMMPS data files. """ ext = fn[fn.rfind('.'):].split('@') if ext[0] == '.out' or ext[0] == '.dat': return write_atoms(fn, a) elif ext[0] == '.lammps': return write_lammps_data(fn, a, velocities=True, **kwargs) elif ext[0] == '.nc': return NetCDFTrajectory(fn, 'w').write(a) else: return ase.io.write(fn, a, **kwargs)
import os import warnings import numpy as np from ase import Atom, Atoms from ase.io import read from ase.io import NetCDFTrajectory co = Atoms([Atom('C', (0, 0, 0)), Atom('O', (0, 0, 1.2))], cell=[3, 3, 3], pbc=True) traj = NetCDFTrajectory('1.nc', 'w', co) for i in range(5): co.positions[:, 2] += 0.1 traj.write() del traj traj = NetCDFTrajectory('1.nc', 'a') co = traj[-1] print(co.positions) co.positions[:] += 1 traj.write(co) del traj t = NetCDFTrajectory('1.nc', 'a') print(t[-1].positions) print('.--------') for i, a in enumerate(t): if i < 4: print(1, a.positions[-1, 2], 1.3 + i * 0.1)
from ase.test import NotAvailable import numpy as np import ase.io.netcdftrajectory as netcdftrajectory if not netcdftrajectory.have_nc: raise NotAvailable('No NetCDF module available (netCDF4-python, ' 'scipy.io.netcdf)') import os from ase import Atom, Atoms from ase.io import NetCDFTrajectory co = Atoms([Atom('C', (0, 0, 0)), Atom('O', (0, 0, 1.2))], pbc=True) traj = NetCDFTrajectory('1.nc', 'w', co) for i in range(5): co.positions[:, 2] += 0.1 traj.write() del traj if netcdftrajectory.have_nc == netcdftrajectory.NC_IS_NETCDF4: traj = NetCDFTrajectory('1.nc', 'a') co = traj[-1] print(co.positions) co.positions[:] += 1 traj.write(co) del traj t = NetCDFTrajectory('1.nc', 'a') else: t = NetCDFTrajectory('1.nc', 'r')
from ase.test import NotAvailable import ase.io.netcdftrajectory as netcdftrajectory if not netcdftrajectory.have_nc: raise NotAvailable('No NetCDF module available (netCDF4-python, ' 'scipy.io.netcdf)') import os from ase import Atom, Atoms from ase.io import NetCDFTrajectory co = Atoms([Atom('C', (0, 0, 0)), Atom('O', (0, 0, 1.2))], pbc=True) traj = NetCDFTrajectory('1.nc', 'w', co) for i in range(5): co.positions[:, 2] += 0.1 traj.write() del traj if netcdftrajectory.have_nc == netcdftrajectory.NC_IS_NETCDF4: traj = NetCDFTrajectory('1.nc', 'a') co = traj[-1] print(co.positions) co.positions[:] += 1 traj.write(co) del traj t = NetCDFTrajectory('1.nc', 'a') else: t = NetCDFTrajectory('1.nc', 'r') print(t[-1].positions) print('.--------')
import numpy as np from scipy.sparse import csr_matrix from ase.io import NetCDFTrajectory from ase.io import read import matscipy.calculators.pair_potential as calculator # Load atomic configuration MinStructure = NetCDFTrajectory( "structure/PBC.KA.N256.Min.nc", "r", keep_open=True) # Paramters for a binary Kob-Anderson glass. # Kob, Walter, and Hans C. Andersen. Phys. Rev. E 51.5 (1995): 4626. # The interaction is modeled via a quadratic shifted Lennard-Jones potential. parameters = {(1, 1): calculator.LennardJonesQuadratic(1, 1, 3), (1, 2): calculator.LennardJonesQuadratic( 1.5, 0.8, 2.4), (2, 2): calculator.LennardJonesQuadratic(0.5, 0.88, 2.64)} a = calculator.PairPotential(parameters) # Exemplary code for the calculation of the full hessian matrix. # Sparse H_sparse = a.calculate_hessian_matrix( MinStructure[len(MinStructure)-1], "sparse") # Dense H_dense = a.calculate_hessian_matrix( MinStructure[len(MinStructure)-1], "dense") # Compute the only rows of the Hessian matrix which correspong to atom Ids = 5,6 H_sparse1 = a.calculate_hessian_matrix( MinStructure[len(MinStructure)-1], "sparse", limits=(5, 7))
def test_netcdftrajectory(co): rng = np.random.RandomState(17) traj = NetCDFTrajectory('1.nc', 'w', co) for i in range(5): co.positions[:, 2] += 0.1 traj.write() del traj traj = NetCDFTrajectory('1.nc', 'a') co = traj[-1] print(co.positions) co.positions[:] += 1 traj.write(co) del traj t = NetCDFTrajectory('1.nc', 'a') print(t[-1].positions) print('.--------') for i, a in enumerate(t): if i < 4: print(1, a.positions[-1, 2], 1.3 + i * 0.1) assert abs(a.positions[-1, 2] - 1.3 - i * 0.1) < 1e-6 else: print(1, a.positions[-1, 2], 1.7 + i - 4) assert abs(a.positions[-1, 2] - 1.7 - i + 4) < 1e-6 assert a.pbc.all() co.positions[:] += 1 t.write(co) for i, a in enumerate(t): if i < 4: print(2, a.positions[-1, 2], 1.3 + i * 0.1) assert abs(a.positions[-1, 2] - 1.3 - i * 0.1) < 1e-6 else: print(2, a.positions[-1, 2], 1.7 + i - 4) assert abs(a.positions[-1, 2] - 1.7 - i + 4) < 1e-6 assert len(t) == 7 # Change atom type and append co[0].number = 1 t.write(co) t2 = NetCDFTrajectory('1.nc', 'r') co2 = t2[-1] assert (co2.numbers == co.numbers).all() del t2 co[0].number = 6 t.write(co) co.pbc = False o = co.pop(1) try: t.write(co) except ValueError: pass else: assert False co.append(o) co.pbc = True t.write(co) del t # append to a nonexisting file fname = '2.nc' t = NetCDFTrajectory(fname, 'a', co) del t fname = '3.nc' t = NetCDFTrajectory(fname, 'w', co) # File is not created before first write co.set_pbc([True, False, False]) d = co.get_distance(0, 1) with pytest.warns(None): t.write(co) del t # Check pbc for c in [1, 1000]: t = NetCDFTrajectory(fname, chunk_size=c) a = t[-1] assert a.pbc[0] and not a.pbc[1] and not a.pbc[2] assert abs(a.get_distance(0, 1) - d) < 1e-6 del t # Append something in Voigt notation t = NetCDFTrajectory(fname, 'a') for frame, a in enumerate(t): test = rng.random([len(a), 6]) a.set_array('test', test) t.write_arrays(a, frame, ['test']) del t # Check cell origin co.set_pbc(True) co.set_celldisp([1, 2, 3]) traj = NetCDFTrajectory('4.nc', 'w', co) traj.write(co) traj.close() traj = NetCDFTrajectory('4.nc', 'r') a = traj[0] assert np.all(abs(a.get_celldisp() - np.array([1, 2, 3])) < 1e-12) traj.close() # Add 'id' field and check if it is read correctly co.set_array('id', np.array([2, 1])) traj = NetCDFTrajectory('5.nc', 'w', co) traj.write(co, arrays=['id']) traj.close() traj = NetCDFTrajectory('5.nc', 'r') assert np.all(traj[0].numbers == [8, 6]) assert np.all( np.abs(traj[0].positions - np.array([[2, 2, 3.7], [2., 2., 2.5]])) < 1e-6) traj.close() a = read('5.nc') assert (len(a) == 2)
def test_types_to_numbers_argument(co): traj = NetCDFTrajectory('8.nc', 'w', co) traj.write() traj.close() d = {6: 15, 8: 15} traj = NetCDFTrajectory('8.nc', mode="r", types_to_numbers=d) assert np.allclose(traj[-1].get_masses(), 30.974) assert (traj[-1].numbers == [15, 15]).all() d = {3: 14} traj = NetCDFTrajectory('8.nc', mode="r", types_to_numbers=d) assert (traj[-1].numbers == [6, 8]).all() traj = NetCDFTrajectory('8.nc', 'r', types_to_numbers=[0, 0, 0, 0, 0, 0, 15]) assert (traj[-1].numbers == [15, 8]).all() traj.close()
#! /usr/bin/env python from __future__ import print_function import sys import numpy as np from ase.data import chemical_symbols from ase.io import NetCDFTrajectory from matscipy.neighbours import mic ### traj = NetCDFTrajectory(sys.argv[1]) ref_frame = traj[0] individual_elements = set(ref_frame.numbers) s = '#{:>9s}'.format('frame') if 'time' in ref_frame.info: s = '{} {:>10s}'.format(s, 'time') s = '{} {:>10s}'.format(s, 'tot. rms') for element in individual_elements: s = '{} {:>10s}'.format(s, 'rms ({})'.format(chemical_symbols[element])) print(s) last_frame = traj[0] displacements = np.zeros_like(ref_frame.positions) for i, frame in enumerate(traj[1:]): last_frame.set_cell(frame.cell, scale_atoms=True)
# You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ====================================================================== """ Run Voronoi analysis of a trajectory, and store the results into that trajectory. """ import os import sys from ase.io import NetCDFTrajectory from atomistica.analysis import voropp ### traj = NetCDFTrajectory(sys.argv[1], 'a') for i, a in enumerate(traj): sys.stdout.write('=== {0}/{1} ===\r'.format(i+1, len(traj))) vol, area = voropp(a, q='%v %F', fast=True) a.set_array('voronoi_volume', vol) a.set_array('voronoi_surface_area', area) traj.write_arrays(a, i, ['voronoi_volume', 'voronoi_surface_area']) traj.close()
# # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ====================================================================== """ Run Voronoi analysis of a trajectory, and store the results into that trajectory. """ import os import sys from ase.io import NetCDFTrajectory from atomistica.analysis import voropp ### traj = NetCDFTrajectory(sys.argv[1], 'a') for i, a in enumerate(traj): sys.stdout.write('=== {0}/{1} ===\r'.format(i + 1, len(traj))) vol, area = voropp(a, q='%v %F', fast=True) a.set_array('voronoi_volume', vol) a.set_array('voronoi_surface_area', area) traj.write_arrays(a, i, ['voronoi_volume', 'voronoi_surface_area']) traj.close()
from ase.test import NotAvailable import ase.io.netcdftrajectory as netcdftrajectory if not netcdftrajectory.have_nc: raise NotAvailable('No NetCDF module available (netCDF4-python, ' 'scipy.io.netcdf)') import os from ase import Atom, Atoms from ase.io import NetCDFTrajectory co = Atoms([Atom('C', (0, 0, 0)), Atom('O', (0, 0, 1.2))], pbc=True) traj = NetCDFTrajectory('1.nc', 'w', co) for i in range(5): co.positions[:, 2] += 0.1 traj.write() del traj if netcdftrajectory.have_nc == netcdftrajectory.NC_IS_NETCDF4: traj = NetCDFTrajectory('1.nc', 'a') co = traj[-1] print(co.positions) co.positions[:] += 1 traj.write(co) del traj t = NetCDFTrajectory('1.nc', 'a') else: t = NetCDFTrajectory('1.nc', 'r') print(t[-1].positions)
def test_netcdftrajectory(): import os import warnings import numpy as np from pytest import importorskip importorskip('netCDF4') from ase import Atom, Atoms from ase.io import read from ase.io import NetCDFTrajectory co = Atoms([Atom('C', (0, 0, 0)), Atom('O', (0, 0, 1.2))], cell=[3, 3, 3], pbc=True) traj = NetCDFTrajectory('1.nc', 'w', co) for i in range(5): co.positions[:, 2] += 0.1 traj.write() del traj traj = NetCDFTrajectory('1.nc', 'a') co = traj[-1] print(co.positions) co.positions[:] += 1 traj.write(co) del traj t = NetCDFTrajectory('1.nc', 'a') print(t[-1].positions) print('.--------') for i, a in enumerate(t): if i < 4: print(1, a.positions[-1, 2], 1.3 + i * 0.1) assert abs(a.positions[-1, 2] - 1.3 - i * 0.1) < 1e-6 assert a.pbc.all() else: print(1, a.positions[-1, 2], 1.7 + i - 4) assert abs(a.positions[-1, 2] - 1.7 - i + 4) < 1e-6 assert a.pbc.all() co.positions[:] += 1 t.write(co) for i, a in enumerate(t): if i < 4: print(2, a.positions[-1, 2], 1.3 + i * 0.1) assert abs(a.positions[-1, 2] - 1.3 - i * 0.1) < 1e-6 else: print(2, a.positions[-1, 2], 1.7 + i - 4) assert abs(a.positions[-1, 2] - 1.7 - i + 4) < 1e-6 assert len(t) == 7 # Change atom type and append co[0].number = 1 t.write(co) t2 = NetCDFTrajectory('1.nc', 'r') co2 = t2[-1] assert (co2.numbers == co.numbers).all() del t2 os.remove('1.nc') co[0].number = 6 co.pbc = True t.write(co) co.pbc = False o = co.pop(1) try: t.write(co) except ValueError: pass else: assert False co.append(o) co.pbc = True t.write(co) del t # append to a nonexisting file fname = '2.nc' if os.path.isfile(fname): os.remove(fname) t = NetCDFTrajectory(fname, 'a', co) del t fname = '3.nc' t = NetCDFTrajectory(fname, 'w', co) # File is not created before first write co.set_pbc([True, False, False]) d = co.get_distance(0, 1) with warnings.catch_warnings(): warnings.simplefilter('ignore', UserWarning) t.write(co) del t # Check pbc for c in [1, 1000]: t = NetCDFTrajectory(fname, chunk_size=c) a = t[-1] assert a.pbc[0] and not a.pbc[1] and not a.pbc[2] assert abs(a.get_distance(0, 1) - d) < 1e-6 del t # Append something in Voigt notation t = NetCDFTrajectory(fname, 'a') for frame, a in enumerate(t): test = np.random.random([len(a), 6]) a.set_array('test', test) t.write_arrays(a, frame, ['test']) del t os.remove(fname) # Check cell origin co.set_pbc(True) co.set_celldisp([1, 2, 3]) traj = NetCDFTrajectory('4.nc', 'w', co) traj.write(co) traj.close() traj = NetCDFTrajectory('4.nc', 'r') a = traj[0] assert np.all(abs(a.get_celldisp() - np.array([1, 2, 3])) < 1e-12) traj.close() os.remove('4.nc') # Add 'id' field and check if it is read correctly co.set_array('id', np.array([2, 1])) traj = NetCDFTrajectory('5.nc', 'w', co) traj.write(co, arrays=['id']) traj.close() traj = NetCDFTrajectory('5.nc', 'r') # assert np.all(traj[0].numbers == [8, 6]) assert np.all( np.abs(traj[0].positions - np.array([[2, 2, 3.7], [2., 2., 2.5]])) < 1e-6) traj.close() a = read('5.nc') assert (len(a) == 2) os.remove('5.nc') # Create a NetCDF file with a per-file definition of atomic numbers. ASE # NetCDFTrajectory can read but not write these types of files. import netCDF4 nc = netCDF4.Dataset('6.nc', 'w') nc.createDimension('frame', None) nc.createDimension('atom', 2) nc.createDimension('spatial', 3) nc.createDimension('cell_spatial', 3) nc.createDimension('cell_angular', 3) nc.createVariable('atom_types', 'i', ('atom', )) nc.createVariable('coordinates', 'f4', ( 'frame', 'atom', 'spatial', )) nc.createVariable('cell_lengths', 'f4', ( 'frame', 'cell_spatial', )) nc.createVariable('cell_angles', 'f4', ( 'frame', 'cell_angular', )) r0 = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float) r1 = 2 * r0 nc.variables['atom_types'][:] = [1, 2] nc.variables['coordinates'][0] = r0 nc.variables['coordinates'][1] = r1 nc.variables['cell_lengths'][:] = 0 nc.variables['cell_angles'][:] = 90 nc.close() traj = NetCDFTrajectory('6.nc', 'r') assert np.allclose(traj[0].positions, r0) assert np.allclose(traj[1].positions, r1) traj.close() os.remove('6.nc') # Create a NetCDF file with a non-consecutive index. import netCDF4 nc = netCDF4.Dataset('7.nc', 'w') nc.createDimension('frame', None) nc.createDimension('atom', 3) nc.createDimension('spatial', 3) nc.createDimension('cell_spatial', 3) nc.createDimension('cell_angular', 3) nc.createVariable('atom_types', 'i', ('atom', )) nc.createVariable('coordinates', 'f4', ( 'frame', 'atom', 'spatial', )) nc.createVariable('cell_lengths', 'f4', ( 'frame', 'cell_spatial', )) nc.createVariable('cell_angles', 'f4', ( 'frame', 'cell_angular', )) nc.createVariable('id', 'i', ( 'frame', 'atom', )) r0 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float) r1 = 2 * r0 nc.variables['atom_types'][:] = [1, 2, 3] nc.variables['coordinates'][0] = r0 nc.variables['coordinates'][1] = r1 nc.variables['cell_lengths'][:] = 0 nc.variables['cell_angles'][:] = 90 nc.variables['id'][0] = [13, 3, 5] nc.variables['id'][1] = [-1, 0, -5] nc.close() traj = NetCDFTrajectory('7.nc', 'r') assert (traj[0].numbers == [2, 3, 1]).all() assert (traj[1].numbers == [3, 1, 2]).all() traj.close() os.remove('7.nc')
import numpy as np import ase.io.netcdftrajectory as netcdftrajectory if not netcdftrajectory.have_nc: raise NotAvailable('No NetCDF module available (netCDF4-python, ' 'scipy.io.netcdf)') import os from ase import Atom, Atoms from ase.io import NetCDFTrajectory co = Atoms([Atom('C', (0, 0, 0)), Atom('O', (0, 0, 1.2))], cell=[3, 3, 3], pbc=True) traj = NetCDFTrajectory('1.nc', 'w', co) for i in range(5): co.positions[:, 2] += 0.1 traj.write() del traj if netcdftrajectory.have_nc == netcdftrajectory.NC_IS_NETCDF4: traj = NetCDFTrajectory('1.nc', 'a') co = traj[-1] print(co.positions) co.positions[:] += 1 traj.write(co) del traj t = NetCDFTrajectory('1.nc', 'a') else: t = NetCDFTrajectory('1.nc', 'r')