Coverage for local_installation/dynasor/trajectory/atomic_indices.py: 100%
22 statements
« prev ^ index » next coverage.py v7.3.2, created at 2024-12-21 12:02 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2024-12-21 12:02 +0000
1import os
2import re
3import numpy as np
4from dynasor.logging_tools import logger
7def parse_gromacs_index_file(fname):
8 """
9 Parses a gromacs style index (ndx) file.
10 Returns a dict with key values as
11 group-name: [1, 3, 8]
13 Note that atomic indices in gromacs-ndx file starts with 1, but the returned dict starts with 0
14 """
16 if not os.path.isfile(fname):
17 raise ValueError('Index file not found')
19 atomic_indices = dict()
20 header_re = re.compile(r'^ *\[ *([a-zA-Z0-9_.-]+) *\] *$')
21 with open(fname, 'r') as fobj:
22 for line in fobj.readlines():
23 match = header_re.match(line)
24 if match is not None: # get name of group
25 name = match.group(1)
26 if name in atomic_indices.keys():
27 logger.warning(f'Group name {name} appears twice in index file, only one used.')
28 atomic_indices[name] = []
29 else: # get indices for group
30 indices = [int(i) for i in line.split()]
31 atomic_indices[name].extend(indices)
33 # cast to indices to numpy arrays and shift so indices start with 0
34 for name, indices in atomic_indices.items():
35 atomic_indices[name] = np.array(indices) - 1
37 return atomic_indices