def test_species(self): """ This test is known to fail because RUMD sample do not return the particle types as array and therefore they are not propagated when particles are not sorted by species """ from atooms.backends.rumd import System # Create a new input file with one particle species changed self.input_file = os.path.join(os.path.dirname(__file__), '../data/ka_N256_rho1.185_rumd.xyz.gz') from atooms.core.utils import mkdir mkdir('/tmp/test_rumd_species/') with TrajectoryRUMD(self.input_file) as th: system = th[-1] system.particle[0].species = system.particle[-1].species with TrajectoryRUMD('/tmp/test_rumd_species/input.xyz.gz', 'w') as th: th.write(system) si = Simulation(self.backend, output_path='/tmp/test_rumd_species/trajectory', steps=2000, checkpoint_interval=100, restart=False) self.assertEqual(system.particle[0].species, system.particle[-1].species) si.add(write_config, 100) si.run() with SuperTrajectoryRUMD('/tmp/test_rumd_species/trajectory') as th: system = th[-1] self.assertEqual(system.particle[0].species, system.particle[-1].species, 'rumd requires ordered types')
def setUp(self): mkdir('/tmp/test_xyz') with open('/tmp/test_xyz/1.xyz', 'w') as fh: fh.write("""\ 1 metafmt:space,comma columns:id,x,y,z step:1 cell:5.0,5.0,5.0 B 1.0 -1.0 0.0 1 metafmt:space,comma columns:id,x,y,z step:2 cell:5.0,5.0,5.0 B 2.9 -2.9 0.0 1 metafmt:space,comma columns:id,x,y,z step:4 cell:5.0,5.0,5.0 B 2.9 -2.9 0.0 """) with open('/tmp/test_xyz/2.xyz', 'w') as fh: fh.write("""\ 1 metafmt:space,comma columns:id,x,y,z step:2 cell:5.0,5.0,5.0 B 1.0 -1.0 0.0 1 metafmt:space,comma columns:id,x,y,z step:3 cell:5.0,5.0,5.0 B 2.9 -2.9 0.0 1 metafmt:space,comma columns:id,x,y,z step:4 cell:5.0,5.0,5.0 B 2.9 -2.9 0.0 1 metafmt:space,comma columns:id,x,y,z step:5 cell:5.0,5.0,5.0 B 2.9 -2.9 0.0 """)
def setUp(self): if SKIP: self.skipTest('no rumd') self.dout = '/tmp/test_backends_rumd_out' self.finp = '/tmp/test_backends_rumd_in.xyz' with open(self.finp, 'w') as fh: fh.write(xyz) self.backend = Backend(self.finp) self.sim = self.backend.rumd_simulation self.backend.rumd_simulation.sample.SetOutputDirectory(self.dout) self.backend.rumd_simulation.suppressAllOutput = True p = rumd.Pot_LJ_12_6(cutoff_method=rumd.ShiftedPotential) p.SetVerbose(False) p.SetParams(0, 0, 1., 1., 2.5) self.backend.rumd_simulation.SetPotential(p) itg = rumd.IntegratorNVT(targetTemperature=2.0, timeStep=0.002) self.backend.rumd_simulation.SetIntegrator(itg) self.finp2 = '/tmp/test_backends_rumd_in2.xyz' with open(self.finp2, 'w') as fh: fh.write(xyz_2) self.sim2 = rumdSimulation(self.finp2, verbose=False) self.finp_io2 = '/tmp/test_backends_rumd_io2.xyz' with open(self.finp_io2, 'w') as fh: fh.write(xyz_io2) from atooms.core.utils import mkdir mkdir('/tmp/test_backends') self.finp_io2_base = '/tmp/test_backends/0000001.xyz' with open(self.finp_io2_base, 'w') as fh: fh.write(xyz_io2)
def scatter(args): """ Write frames in trajectory to individual files of the same file format """ from atooms import trajectory as trj from atooms.core.utils import mkdir for f in args.file_inp: fmt = args.inp t = trj.Trajectory(f, fmt=fmt) fmt_out = t.suffix # Define slice # We interpret --first N --last N as a request of step N if args.last == args.first and args.last is not None: args.last += 1 sl = fractional_slice(args.first, args.last, args.skip, len(t)) ts = trajectory.Sliced(t, sl) for i, system in enumerate(ts): f_out = args.file_out.format(step=t.steps[i], frame=i, base=os.path.splitext(f)[0], ext=os.path.splitext(f)[1]) mkdir(os.path.dirname(f_out)) with trj.Trajectory(f_out, fmt=fmt_out, mode='w') as th_out: if args.fields is not None: th_out.fields = args.fields.split(',') else: th_out.fields.append('radius') th_out.fields.append('radius') th_out.write(system, step=t.steps[i])
def convert(inp, out, fout, force=True, fields=None, exclude=None, include=None, steps=None): """ Convert trajectory into a different format. `inp`: input trajectory object `out`: output trajectory class `fout`: output file If `out` is a string, we look for a matching trajectory format else we assume out is a trajectory class. If `out` is None, we rely on the factory guessing the format from the filename suffix. Return: name of converted trajectory file """ from atooms.trajectory import Trajectory from atooms.trajectory.base import canonicalize_fields if isinstance(out, str): out_class = Trajectory.formats[out] else: out_class = out if fields is None and len(inp.fields) > 0 and (include is None or len(include) == 0): # We automatically include all fields from the input trajectory # Since the output trajectory may have extra fields, we do should not overwrite them include = canonicalize_fields(inp.fields) if fout != '/dev/stdout' and (os.path.exists(fout) and not force): print('File exists, conversion skipped') else: # Make sure parent folder exists from atooms.core.utils import mkdir mkdir(os.path.dirname(fout)) with out_class(fout, 'w') as conv: modify_fields(conv, fields, include, exclude) conv.precision = inp.precision conv.timestep = inp.timestep conv.block_size = inp.block_size # In python 3, zip returns a generator so this is ok # # for system, step in zip(inp, inp.steps): # conv.write(system, step) # # In python 2, zipping t and t.steps will load everything # in RAM. In this case, it is better to use enumerate() if steps is None: for i, system in progress(enumerate(inp), total=len(inp)): conv.write(system, inp.steps[i]) else: # Only include requested steps (useful to prune # non-periodic trajectories) for step in steps: idx = inp.steps.index(step) conv.write(inp[idx], step) return fout
def setUp(self): self.dirbase = '/tmp/test_core' self.dirout = self.dirbase + '/dir' utils.mkdir(self.dirout) with open(self.dirout + '/1', 'w'): pass with open(self.dirout + '/2', 'w'): pass utils.mkdir(self.dirout + '/3')
def main(params): if params.verbose: setup_logging(level=20) if params.debug: setup_logging(level=10) if params.T is not None: params.integrator = 'nvt' if os.path.exists(params.input_file + '.ff'): params.forcefield = params.input_file + '.ff' output_base = os.path.join(params.output_dir, 'trajectory') mkdir(output_base) cp(params.forcefield, output_base + '.ff') cp(params.forcefield, output_base + '.chk.ff') report_parameters(params.__dict__, output_base + '.params', '%s+%s' % (__version__, __commit__)) report_command(sys.argv[0], params.__dict__, ['output_dir'], output_base + '.cmd') s = RUMD(params.input_file, params.forcefield, integrator=params.integrator, temperature=params.T, dt=params.dt, fixcm_interval=params.fixcm_interval) sa = Simulation(s, output_path=output_base, checkpoint_interval=params.checkpoint_interval, steps=params.steps, restart=params.restart) if params.backend_output: s._suppress_all_output = False s._initialize_output = True s.rumd_simulation.sample.SetOutputDirectory(output_base) s.rumd_simulation.SetOutputScheduling("energies", "linear", interval=params.thermo_interval) s.rumd_simulation.SetOutputScheduling("trajectory", params.config_sampling, interval=params.config_interval) s.rumd_simulation.SetOutputMetaData("trajectory", precision=6, virials=False) if params.config_interval > 0 and params.config_sampling == "logarithmic": s.rumd_simulation.SetBlockSize(params.config_interval) else: s.rumd_simulation.SetBlockSize(params.steps) # Trim target steps to be a multiple of config_interval # params.steps = params.steps / params.config_interval * params.config_interval else: sa.add(write_thermo, Scheduler(params.thermo_interval)) sa.add(write_config, Scheduler(params.config_interval)) sa.run()
def setUp(self): mkdir('/tmp/test_xyz') super(TestRumd, self).setUp() ioformat_1 = """\ 2 ioformat=1 dt=0.005000000 boxLengths=6.000000000,6.000000000,6.000000000 numTypes=2 Nose-Hoover-Ps=-0.154678583 Barostat-Pv=0.000000000 mass=1.000000000,1.000000000 columns=type,x,y,z,imx,imy,imz,vx,vy,vz,fx,fy,fz,pe,vir 0 1.0 -1.0 0.0 0 0 1 -0.955896854 -2.176721811 0.771060944 14.875996590 -28.476327896 -15.786120415 -5.331668218 22.538120270 1 2.9 -2.9 0.0 0 0 -1 -0.717318892 -0.734904408 0.904034972 -28.532371521 13.714955330 0.387423307 -7.276362737 11.813765526 """ with open('/tmp/test_xyz/rumd.xyz', 'w') as fh: fh.write(ioformat_1) self.finp = fh.name
def setUp(self): self.dirname = '/tmp/test_folder' rmd(self.dirname) mkdir(self.dirname) for i in range(10, 13): fname = os.path.join(self.dirname, 'step_%d' % i) with open(fname, 'w') as fh: fh.write("""\ 2 step:%d A 1.0 -1.0 0.0 A 2.9 -2.9 0.0 """ % i)
def setUp(self): import copy particle = [ Particle(position=[0.0, 0.0, 0.0], species='A', mass=1.0), Particle(position=[1.0, 1.0, 1.0], species='B', mass=2.0), ] cell = Cell([2.0, 2.0, 2.0]) self.system = [] self.system.append(System(copy.deepcopy(particle), cell)) self.system.append(System(copy.deepcopy(particle), cell)) self.inpfile = '/tmp/test_trajectory' self.inpdir = '/tmp/test_trajectory.d' from atooms.core.utils import mkdir mkdir(self.inpdir)
def setUp(self): mkdir('/tmp/test_xyz') self.finp = '/tmp/test_xyz/pbc.xyz' self.fout = '/tmp/test_xyz/out.xyz' with open(self.finp, 'w') as fh: fh.write("""\ 2 Lattice="5.44 0.0 0.0 0.0 5.44 0.0 0.0 0.0 5.44" Properties=species:S:1:pos:R:3 Time=0.0 A 1.0 -1.0 0.0 B 2.9 -2.9 0.0 2 Lattice="5.44 0.0 0.0 0.0 5.44 0.0 0.0 0.0 5.44" Properties=species:S:1:pos:R:3 Time=0.0 A 1.1 -1.1 0.0 C -2.9 -2.9 0.0 """)
def setUp(self): mkdir('/tmp/test_xyz') self.finp = '/tmp/test_xyz/pbc.xyz' with open(self.finp, 'w') as fh: fh.write("""\ 2 cell:6.0,6.0,6.0 A 1.0 -1.0 0.0 A 2.9 -2.9 0.0 2 cell:6.0,6.0,6.0 A 1.1 -1.1 0.0 A -2.9 -2.9 0.0 2 cell:6.0,6.0,6.0 A 1.2 -1.2 0.0 A -2.9 2.9 0.0 2 cell:6.0,6.0,6.0 A 1.3 -1.3 0.0 A -2.8 2.8 0.0 """) # Test metadata recognition self.finp_meta = '/tmp/test_xyz/meta.xyz' with open(self.finp_meta, 'w') as fh: fh.write("""\ 2 metafmt:space,comma columns:id,x,y,z mass:1.0,2.0 step:1 cell:5.0,5.0,5.0 A 1.0 -1.0 0.0 B 2.9 -2.9 0.0 """) # Test 4-dim file self.finp_4d = '/tmp/test_xyz/4d.xyz' with open(self.finp_4d, 'w') as fh: fh.write("""\ 2 metafmt:space,comma columns:id,pos ndim:4 mass:1.0,2.0 step:1 A 1.0 -1.0 0.0 1.0 B 2.9 -2.9 0.0 2.0 2 metafmt:space,comma columns:id,pos mass:1.0,2.0 step:1 cell:5.0,5.0,5.0,5.0 A 1.0 -1.0 0.0 1.0 B 2.9 -2.9 0.0 2.0 2 metafmt:space,comma columns:id,pos mass:1.0,2.0 step:1 cell:5.0,5.0,5.0 A 1.0 -1.0 0.0 1.0 B 2.9 -2.9 0.0 2.0 """)
def test_trajectory_folder(self): import sys mkdir('/tmp/test_lammps.d') with open('/tmp/test_lammps.d/0.atom', 'w') as fh: fh.write("""\ ITEM: TIMESTEP 10 ITEM: NUMBER OF ATOMS 2 ITEM: BOX BOUNDS pp pp pp -3 3 -3 3 -3 3 ITEM: ATOMS id type xs ys zs 2 1 0.10 0.11 0.12 1 1 0.20 0.21 0.22 """) with open('/tmp/test_lammps.d/1.atom', 'w') as fh: fh.write("""\ ITEM: TIMESTEP 20 ITEM: NUMBER OF ATOMS 2 ITEM: BOX BOUNDS pp pp pp -4 4 -4 4 -4 4 ITEM: ATOMS id type xs ys zs 1 1 0.00 0.01 0.02 2 1 0.50 0.51 0.52 """) from atooms.trajectory import TrajectoryFolderLAMMPS def scale(pos, side): return [(x - 0.5) * L for x, L in zip(pos, side)] with TrajectoryFolderLAMMPS('/tmp/test_lammps.d') as th: self.assertEqual(th.steps, [10, 20]) self.assertEqual(list(th[0].cell.side), [6.0, 6.0, 6.0]) self.assertEqual(list(th[0].particle[0].position), scale([0.20, 0.21, 0.22], [6.0, 6.0, 6.0])) self.assertEqual(list(th[0].particle[1].position), scale([0.10, 0.11, 0.12], [6.0, 6.0, 6.0])) self.assertEqual(list(th[1].cell.side), [8.0, 8.0, 8.0]) self.assertEqual(list(th[1].particle[0].position), scale([0.00, 0.01, 0.02], [8.0, 8.0, 8.0])) self.assertEqual(list(th[1].particle[1].position), scale([0.50, 0.51, 0.52], [8.0, 8.0, 8.0]))
def __init__(self, backend, output_path=None, steps=0, checkpoint_interval=0, enable_speedometer=False, restart=False): """ Perform a simulation using the specified `backend` and optionally write output to `output_path`. This can be a file or directory path. Paths: to define output paths we rely on `output_path`, all other paths are defined based on it and on its base_path. """ self.backend = backend self.output_path = output_path self.steps = steps self._restart = restart self.current_step = 0 self.initial_step = 0 # We expect subclasses to keep a ref to the trajectory class # used to store configurations if hasattr(self.backend, 'trajectory_class'): self.trajectory_class = self.backend.trajectory_class else: self.trajectory_class = None # Make sure the dirname of output_path exists. For instance, # if output_path is data/trajectory.xyz, then data/ should # exist. This creates the data/ folder and its parents folders. if self.output_path is not None: mkdir(os.path.dirname(self.output_path)) # Internal variables self._callback = [] self._start_time = time.time() self._speedometer = None self._checkpoint_scheduler = Scheduler(checkpoint_interval) self._targeter_steps = target_steps self._cbk_params = {} # hold scheduler and parameters of callbacks if enable_speedometer: self._speedometer = Speedometer() self.add(self._speedometer, Scheduler(self.steps, calls=20))
def setUp(self): mkdir('/tmp/test_xyz')
def write(self): """ Write the correlation function and the analysis data to file The `output_path` instance variable is used to define the output files by interpolating the following variables: - symbol - short_name - long_name - tag - tag_description - trajectory The default is defined by core.pp_output_path, which currently looks like '{trajectory.filename}.pp.{symbol}.{tag}' """ def is_iterable(maybe_iterable): try: iter(maybe_iterable) except TypeError: return False else: return True # Pack grid and value into arrays to dump if is_iterable(self.grid[0]) and len(self.grid) == 2: x = numpy.array(self.grid[0]).repeat(len(self.value[0])) y = numpy.array(self.grid[1] * len(self.grid[0])) z = numpy.array(self.value).flatten() dump = numpy.transpose(numpy.array([x, y, z])) else: dump = numpy.transpose(numpy.array([self.grid, self.value])) # Comment line # Extract variables from parenthesis in symbol variables = self.short_name.split('(')[1][:-1] variables = variables.split(',') columns = variables + [self.short_name] #[self.symbol] if len(self.tag_description) > 0: conj = 'of' else: conj = '' comments = _dump( title='%s %s %s %s' % (self.long_name, self.short_name, conj, self.tag_description), columns=columns, command='atooms-pp', version=core.__version__, description=None, note=None, parents=self.trajectory.filename, inline=False) if self.comments is not None: comments += self.comments # Results of analysis analysis = "" for x, f in self.analysis.items(): if f is not None: analysis += '# %s: %s\n' % (x, f) # Put it all together # and make sure the path to the output file exists import os from atooms.core.utils import mkdir mkdir(os.path.dirname(self._output_file)) with open(self._output_file, 'w') as fh: fh.write(comments) if len(analysis) > 0: fh.write(analysis) numpy.savetxt(fh, dump, fmt="%g") fh.flush()
def show_ovito(particle, cell, outfile=None, radius=0.35, viewport=None, callback=None, tmpdir=None, camera_dir=(0, 1, 0), camera_pos=(0, -10, 0), size=(640, 480), zoom=True, perspective=False): """ Render particle in cell using ovito """ import os try: from ovito.io import import_file except ImportError: _log.warning('install ovito to display the particles') return from ovito.vis import Viewport, TachyonRenderer from ovito.vis import ParticlesVis import tempfile from atooms.core.utils import mkdir # Make sure dirname exists if outfile is not None: mkdir(os.path.dirname(outfile)) # Get a temporary file to write the sample fh = tempfile.NamedTemporaryFile('w', dir=tmpdir, suffix='.xyz', delete=False) tmp_file = fh.name # Self-contained EXYZ dump (it is not clean to use trajectories here) fh.write('{}\n'.format(len(particle))) fh.write( 'Properties=species:S:1:pos:R:3 Lattice="{},0.,0.,0.,{},0.,0.,0.,{}"\n' .format(*cell.side)) for p in particle: fh.write('{} {} {} {}\n'.format(p.species, *p.position)) fh.close() # Ovito stuff. Can be customized by client code. pipeline = import_file(tmp_file) # Ovito seems to ignore the lattice info of exyz file # so we forcibly set the cell info here pipeline.source.data.cell_[0, 0] = cell.side[0] pipeline.source.data.cell_[1, 1] = cell.side[1] pipeline.source.data.cell_[2, 2] = cell.side[2] pipeline.source.data.cell_[:, 3] = -cell.side / 2 # Scale radius by default vis_element = pipeline.source.data.particles.vis vis_element.radius = radius # Apply client code callback if callback: callback(pipeline) pipeline.add_to_scene() # Define viewport if viewport: vp = vieport else: if perspective: vp = Viewport(type=Viewport.Type.Perspective, camera_dir=camera_dir, camera_pos=camera_pos) else: vp = Viewport(type=Viewport.Type.Ortho, camera_dir=camera_dir, camera_pos=camera_pos) # Render if zoom: vp.zoom_all() if outfile is None: outfile = tmp_file + '.png' vp.render_image(filename=outfile, size=size, renderer=TachyonRenderer()) # Scene is a singleton, so we must clear it pipeline.remove_from_scene() from atooms.core.utils import rmf rmf(tmp_file) # Try to display the image (e.g. in a jupyter notebook) try: from IPython.display import Image return Image(outfile) except ImportError: return outfile