def dump_config(filename, pos=None, diam=None, ptypes=None, box=None, compress=None): file_ext = os.path.splitext(filename)[1] cell = Cell(side=box) npart = pos.shape[0] particles = [] for i in range(npart): p = Particle(species=ptypes[i], position=pos[i, :] - box / 2., radius=diam[i] / 2.) particles.append(p) system = System(particle=particles, cell=cell) with Trajectory(filename, "w") as traj: # Step is always 0 for now. traj.write(system, 0) if file_ext == ".xyz": compress = True else: compress = False if compress: subprocess.run(["gzip", "-f", filename])
def read_sample(self, frame): """ returns System instance. """ snap = self.trajectory[frame] ndim = snap.configuration.dimensions # Convert typeid from [0, 0, 1, ...] to ['A', 'A', 'B', ...] when snap.particles.types = ['A', 'B'] distinct_species = snap.particles.types distinct_typeids = list(range(len(distinct_species))) typeid_to_species = {} for i in distinct_typeids: typeid_to_species[i] = distinct_species[i] box = snap.configuration.box[: ndim] # atooms does not handle sheared boxes. cell = Cell(side=box) N = snap.particles.position.shape[0] particles = [] for i in range(N): p = Particle(mass=snap.particles.mass[i], species=typeid_to_species[snap.particles.typeid[i]], position=snap.particles.position[i, :ndim], velocity=snap.particles.velocity[i, :ndim], radius=snap.particles.diameter[i] / 2) particles.append(p) return System(particle=particles, cell=cell)
def read_init(self): # Grab cell from the end of file if it is there try: side = self._read_comment(0)['cell'] self._cell = Cell(side) except KeyError: self._cell = self._parse_cell()
def read_sample(self, frame): """ returns System instance. """ L = self.header[0] if self.ndim == 3: cell = Cell(side=[L, L, L]) elif self.ndim == 2: cell = Cell(side=[L, L]) N = self.data.shape[0] pos = self.data[:, :self.ndim] # Lerner group format has positions from [0, 1). pos = pos*L - L/2 if self.velocity_present: # Next is the velocity, if it exists. vel = self.data[:, self.ndim:2*self.ndim] # # In 2D, we add a zero z-coordinate to be consistent with other formats. # if self.ndim == 3: # # First ndim columns are always the position. # elif self.ndim == 2: # new_pos = np.zeros((N, 3)).astype(float) # new_pos[:, :self.ndim] = pos # pos = new_pos # if self.velocity_present: # vel = np.zeros((N, 3)).astype(float) # vel[:, :self.ndim] = self.data[:, self.ndim:2*self.ndim] particles = [] for i in range(N): p = Particle() p.position = pos[i, :] if self.velocity_present: p.velocity = vel[i, :] if self.species_present and self.radius_present: p.species = str( int(self.data[i, -1]) ) p.radius = self.data[i, -2] elif self.radius_present: p.radius = self.data[i, -1] elif self.species_present: p.species = str( int(self.data[i, -1]) ) particles.append(p) return System(particle=particles, cell=cell)
def _parse_cell(self): """Internal emergency method to grab the cell.""" cell = None if self._index_cell: self.trajectory.seek(self._index_cell) side = numpy.fromstring(self.trajectory.readline(), sep=' ') cell = Cell(side) return cell
def read_sample(self, frame): cfg, box, pos, typ, vel = self.__read_one(self.__f_frames[frame]) if vel is None: particle = [Particle(species=t, position=numpy.array(p)) for p, t in zip(pos, typ)] else: particle = [Particle(species=t, position=numpy.array(p), velocity=numpy.array(v)) for p, t, v in zip(pos, typ, vel)] cell = Cell(numpy.array(box)) return System(particle, cell)
def setUp(self): N = 100 L = 10.0 self.ref = System() self.ref.cell = Cell([L, L, L]) self.ref.particle = [] self.ref.thermostat = Thermostat(1.0) self.ref.barostat = Barostat(1.0) self.ref.reservoir = Reservoir(1.0) while len(self.ref.particle) <= N: pos = [(random.random() - 0.5) * L, (random.random() - 0.5) * L, (random.random() - 0.5) * L] self.ref.particle.append(Particle(position=pos))
def test_overlap_random(self): # This test may fail from time to time from atooms.system.particle import collective_overlap N = 1000 L = 5.0 sys = [System(), System()] sys[0].cell = Cell([L, L, L]) sys[1].cell = Cell([L, L, L]) sys[0].particle = [] sys[1].particle = [] for _ in range(N): pos = [(random.random() - 0.5) * L, (random.random() - 0.5) * L, (random.random() - 0.5) * L] sys[0].particle.append(Particle(position=pos)) for _ in range(N): pos = [(random.random() - 0.5) * L, (random.random() - 0.5) * L, (random.random() - 0.5) * L] sys[1].particle.append(Particle(position=pos)) a = 0.3 q_rand = ((a**3 * 4. / 3 * 3.1415) * N / sys[0].cell.volume) self.assertTrue( abs(q_rand - collective_overlap(sys[0].particle, sys[1].particle, a, sys[0].cell.side)) < 0.5)
def read_sample(self, frame): # Read metadata of this frame meta = self._read_comment(frame) # Get number of particles self.trajectory.seek(self._index_header[frame]) npart = int(self.trajectory.readline()) # Read frame now self.trajectory.seek(self._index_frame[frame]) particle = [] for ipart in range(npart): p = Particle() data = self.trajectory.readline().split() i = 0 for key, fmt, ndims in meta['Properties']: ndims = int(ndims) if key in self.alias: key = self.alias[key] if ndims == 1: if fmt == 'R': setattr(p, key, float(data[i])) elif fmt == 'I': setattr(p, key, int(data[i])) elif fmt == 'S': setattr(p, key, data[i]) else: raise ValueError('unknown format key') else: if fmt == 'R': setattr( p, key, numpy.array(data[i:i + ndims], dtype=numpy.float64)) elif fmt == 'I': setattr( p, key, numpy.array(data[i:i + ndims], dtype=numpy.int64)) elif fmt == 'S': setattr(p, key, numpy.array(data[i:i + ndims])) else: raise ValueError('unknown format key') i += ndims particle.append(p) side = meta["Lattice"] # TODO: remove hard coded cell = Cell([side[0], side[4], side[8]]) return System(particle, cell)
def test_ovito(self): try: import ovito except ImportError: self.skipTest('missing ovito') N = 3 L = 5.0 system = System() system.cell = Cell([L, L, L]) system.particle = [] for _ in range(N): pos = (numpy.random.random(len(system.cell.side)) - 0.5) * system.cell.side p = Particle(position=pos) system.particle.append(p) image = system.show('ovito')
def test_write_initial_state(self): p = [ PairPotential('lennard_jones', { 'epsilon': 1.0, 'sigma': 1.0 }, [1, 1], CutOff('CS', 2.5)) ] i = [Interaction(p, 'atomic')] s = System() s.cell = Cell([1.0, 1.0, 1.0]) t = TrajectoryHDF5('/tmp/test_potential.h5', 'w') t.write_interaction(i) t.close() t = TrajectoryHDF5('/tmp/test_potential.h5', 'r') i = t.read_interaction() t.close()
def read_sample(self, frame): meta = self._read_comment(frame) self.trajectory.seek(self._index_frame[frame]) # Read particles particle = [] for _ in range(meta['npart']): data = self.trajectory.readline().strip().split() species = data[0] r = numpy.array(data[1:4], dtype=float) particle.append(Particle(species=species, position=r)) # Read cell try: side = meta['cell'] self._cell = Cell(side) except KeyError: pass return System(particle, self._cell)
def read_sample(self, frame): # Setup fields again, in case they have changed if self.__cache_fields != self.fields: self._setup_fields() # Read metadata of this frame meta = self._read_comment(frame) # Define read callbacks list before reading lines callbacks_read = [] def _skip(p, data, meta): return data[1:] for key in self.fields: # If the key is associated to a explicit callback, go # for it. Otherwise we throw the field in an particle # attribute named key. If the key is None it means we skip # this column. if key is None: callbacks_read.append(_skip) elif key in self.callback_read: callbacks_read.append(self.callback_read[key]) else: # Trick. We instantiate dynamically a fallback function # to avoid adding `key` to the other callbacks' interface namespace = {} exec( """ from atooms.core.utils import tipify def fallback(p, data, meta): p.__dict__['%s'] = tipify(data[0]) return data[1:] """ % key, namespace) callbacks_read.append(namespace['fallback']) # Read frame now self.trajectory.seek(self._index_frame[frame]) particle = [] for i in range(meta['npart']): p = Particle() # Note: we cannot optimize by shifting an index instead of # cropping lists all the time data = self.trajectory.readline().split() for cbk in callbacks_read: data = cbk(p, data, meta) particle.append(p) # Fix the masses. # We assume masses read from the header are sorted by species name. # The mass metadata must be adjusted to the given frame. if 'mass' in meta: if isinstance(meta['mass'], list) or isinstance( meta['mass'], tuple): species = distinct_species(particle) # We must have as many mass entries as species if len(species) != len(meta['mass']): raise ValueError('mass metadata issue %s, %s' % (species, meta['mass'])) db = {} for key, value in zip(species, meta['mass']): db[key] = value for p in particle: p.mass = float(db[p.species]) else: for p in particle: p.mass = float(meta['mass']) # Add cell info if 'cell' in meta: cell = Cell(meta['cell']) else: cell = None return System(particle, cell)
def read_init(self): # read particles group = self.trajectory['/initialstate/particle'] n = self.trajectory['/initialstate/particle/number_of_particles'][0] rad = None for entry in group: # TODO: refactor this if entry == 'element': spe = group[entry][:] if entry == 'mass': mas = group[entry][:] if entry == 'position': pos = group[entry][:] if entry == 'velocity': vel = group[entry][:] if entry == 'radius': rad = group[entry][:] if rad is not None: particle = [ Particle(species=spe[i].decode().strip(), mass=mas[i], position=pos[i, :], velocity=vel[i, :], radius=rad[i]) for i in range(n) ] else: particle = [ Particle(species=spe[i].decode().strip(), mass=mas[i], position=pos[i, :], velocity=vel[i, :]) for i in range(n) ] # read cell group = self.trajectory['/initialstate/cell'] for entry in group: if entry == 'sidebox': sidebox = group[entry][:] cell = Cell(sidebox) # read interaction interaction = self.read_interaction() # build system self._system = System(particle, cell, interaction) # read matrix if 'matrix' in self.trajectory['/initialstate']: group = self.trajectory['/initialstate/matrix'] for entry in group: if entry == 'element': spe = group[entry][:] if entry == 'mass': mas = group[entry][:] if entry == 'position': pos = group[entry][:] matrix = [ Particle(species=spe[i].decode().strip(), mass=mas[i], position=pos[i, :]) for i in range(len(spe)) ] self._system.matrix = copy.deepcopy(matrix) return self._system
def cell(self): box = self.sample.GetSimulationBox() L = [box.GetLength(i) for i in range(3)] return Cell(L)