Example #1
0
    def _read_comment(self, frame):
        """Internal xyz method to get header metadata from comment line of given `frame`.

        We assume metadata format is a space-separated sequence of
        comma separated entries such as:

        columns:id,x,y,z step:10
        columns=id,x,y,z step=10
        """
        # Go to line and skip Npart info
        self.trajectory.seek(self._index_header[frame])
        npart = int(self.trajectory.readline())
        data = self.trajectory.readline()

        # Fill metadata dictionary
        meta = {}
        meta['npart'] = npart
        for e in data.split():
            s = re.search(r'(\S+)\W*[=:]\W*(\S+)', e)
            if s is not None:
                tag, data = s.group(1), s.group(2)
                # Remove dangling commas
                data = data.strip(',')
                # If there are commas, this is a list, else a scalar.
                # We convert the string to appropriate types
                if ',' in data:
                    meta[tag] = [tipify(_) for _ in data.split(',')]
                else:
                    meta[tag] = tipify(data)
        return meta
Example #2
0
def tabulate(potential,
             parameters,
             cutoff='c',
             rc=2.5,
             npoints=10000,
             rmin=0.5,
             fmt='lammps',
             metadata='',
             fileout=None,
             precision=14):
    """Tabulate a potential."""

    from atooms.core.utils import tipify
    from atooms.interaction.potential import PairPotential
    from atooms.interaction.cutoff import CutOff

    if isinstance(parameters, dict):
        param_dict = parameters
    else:
        param_dict = {}
        for param in parameters.split(','):
            key, value = param.split('=')
            param_dict[key] = tipify(value)

    potential = PairPotential(potential, param_dict, (1, 1))
    if cutoff is not None:
        potential.cutoff = CutOff(cutoff, rc)
    rsq, u0, u1, u2 = potential.tabulate(npoints, rmin=rmin, what='uwh')
    r = rsq**0.5
    if fmt == 'lammps':
        u1 *= r
        txt = """

POTENTIAL
N {}

""".format(len(rsq))
        i = 1
        for x, y, z in zip(r, u0, u1):
            txt += '{} {} {} {}\n'.format(i, x, y, z)
            i += 1

    elif fmt == 'uwh':
        txt = '# {} columns: r, u, w, h\n'.format(metadata)
        for x, y, z, w in zip(r, u0, u1, u2):
            txt += '{:.14g} {:.14g} {:.14g} {:.14g}\n'.format(x, y, z, w)

    else:
        u1 *= r
        txt = '# {} columns: r, u, f\n'.format(metadata)
        for x, y, z in zip(r, u0, u1):
            txt += '{} {} {}\n'.format(x, y, z)

    if fileout is None:
        return txt
    else:
        with open(fileout, 'w') as fh:
            fh.write(txt)
Example #3
0
    def _read_comment(self, frame):
        """
        Internal xyz method to get header metadata from comment line of
        given `frame`.
        """
        # Go to line and skip Npart info
        self.trajectory.seek(self._index_header[frame])
        npart = int(self.trajectory.readline())
        data = self.trajectory.readline()
        meta = {}

        # We first gather all keys
        keys = []
        for entry in data.split("=")[:-1]:
            keys.append(entry.split()[-1])

        # Now we extract the values for each key using a dynamic regexp
        import re
        regexp = ''
        for key in keys:
            regexp += '{}=(.*)'.format(key)
        match = re.match(regexp, data)
        for i, key in enumerate(keys):
            meta[key] = match.groups()[i].strip()

        # The Properties key is special so we deal with it first
        entries = meta['Properties'].split(':')
        assert len(entries) % 3 == 0, len(entries)
        properties = []
        for i in range(0, len(entries), 3):
            key, fmt, ndims = entries[i:i + 3]
            properties.append((key, fmt, ndims))

        meta['Properties'] = properties

        # Go through keys, listify and tipify them
        for key in meta:
            if key != 'Properties':
                if meta[key].startswith('"'):
                    meta[key] = meta[key].strip('"')
                    meta[key] = [tipify(_) for _ in meta[key].split()]
                else:
                    meta[key] = tipify(meta[key])

        return meta
Example #4
0
    def _read_comment(self, frame):
        """
        Internal xyz method to get header metadata from comment line of
        given `frame`.

        We assume metadata fmt is a space-separated sequence of comma
        separated entries such as:

        columns:id,x,y,z step:10
        columns=id,x,y,z step=10
        """
        # Go to line and skip Npart info
        self.trajectory.seek(self._index_header[frame])
        npart = int(self.trajectory.readline())
        data = self.trajectory.readline()
        meta = {}
        meta['npart'] = npart

        # Read metadata line
        if not ('=' in data or ':' in data):
            # The comment line contains a list of unspecified fields
            # We add them to the dict using a sequential integer key
            for i, value in enumerate(data.split()):
                meta[i] = tipify(value)

        else:
            # The comment line contains self descriptive fields
            # Remove spaces around : or = and replace = by :
            data = re.sub(r'\s*[=:]\s*', ':', data)
            # Tolerate spaces between entries of vectors
            data = re.sub(r'\s*,\s*', ',', data)

            # Fill metadata dictionary
            for e in data.split():
                s = re.search(r'(\S+):(\S+)', e)
                if s is not None:
                    tag, data = s.group(1), s.group(2)
                    # Remove dangling commas
                    data = data.strip(',')
                    # If there are commas, this is a list, else a scalar.
                    # We convert the string to appropriate types
                    if ',' in data:
                        meta[tag] = [tipify(_) for _ in data.split(',')]
                    else:
                        meta[tag] = tipify(data)

        # Apply an alias dict to tags, e.g. to add step if Cfg was found instead
        for alias, tag in self.alias.items():
            try:
                meta[tag] = meta[alias]
            except KeyError:
                pass

        # Fix dimensions based on side of cell.
        # Fallback to ndim metadata or 3.
        try:
            if 'ndim' not in meta:
                meta['ndim'] = len(meta['cell'])
        except TypeError:
            meta['ndim'] = 1  # it is a scalar
        except KeyError:
            meta['ndim'] = 3  # default

        # Make sure columns is a list
        if 'columns' in meta:
            if not isinstance(meta['columns'], list):
                meta['columns'] = [meta['columns']]

        return meta