Coverage for dynasor / trajectory / atomic_indices.py: 100%

22 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-03-16 12:31 +0000

1import os 

2import re 

3import numpy as np 

4from dynasor.logging_tools import logger 

5 

6 

7def parse_gromacs_index_file(fname: str) -> dict[str, list[int]]: 

8 """ 

9 Parses a gromacs style index (ndx) file. 

10 Returns a dict with key values as 

11 `group-name: [1, 3, 8]`. 

12 

13 Note 

14 ---- 

15 The atomic indices in gromacs-ndx file starts with 1, but the returned dict starts with 0. 

16 """ 

17 

18 if not os.path.isfile(fname): 

19 raise ValueError('Index file not found') 

20 

21 atomic_indices = dict() 

22 header_re = re.compile(r'^ *\[ *([a-zA-Z0-9_.-]+) *\] *$') 

23 with open(fname, 'r') as fobj: 

24 for line in fobj.readlines(): 

25 match = header_re.match(line) 

26 if match is not None: # get name of group 

27 name = match.group(1) 

28 if name in atomic_indices.keys(): 

29 logger.warning(f'Group name {name} appears twice in index file, only one used.') 

30 atomic_indices[name] = [] 

31 else: # get indices for group 

32 indices = [int(i) for i in line.split()] 

33 atomic_indices[name].extend(indices) 

34 

35 # cast to indices to numpy arrays and shift so indices start with 0 

36 for name, indices in atomic_indices.items(): 

37 atomic_indices[name] = np.array(indices) - 1 

38 

39 return atomic_indices