gromologist 0.332__tar.gz → 0.333__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. {gromologist-0.332 → gromologist-0.333}/PKG-INFO +1 -1
  2. {gromologist-0.332 → gromologist-0.333}/README.md +29 -1
  3. {gromologist-0.332 → gromologist-0.333}/gromologist/Gmx.py +80 -4
  4. {gromologist-0.332 → gromologist-0.333}/gromologist/Parser.py +7 -5
  5. {gromologist-0.332 → gromologist-0.333}/gromologist/Pdb.py +18 -44
  6. {gromologist-0.332 → gromologist-0.333}/gromologist/Section.py +3 -3
  7. {gromologist-0.332 → gromologist-0.333}/gromologist/Topology.py +26 -0
  8. {gromologist-0.332 → gromologist-0.333}/gromologist/Utils.py +434 -10
  9. {gromologist-0.332 → gromologist-0.333}/gromologist.egg-info/PKG-INFO +1 -1
  10. {gromologist-0.332 → gromologist-0.333}/gromologist.egg-info/SOURCES.txt +1 -0
  11. {gromologist-0.332 → gromologist-0.333}/gromologist.egg-info/entry_points.txt +2 -0
  12. {gromologist-0.332 → gromologist-0.333}/setup.py +3 -1
  13. gromologist-0.333/tests/test_release_regressions.py +47 -0
  14. {gromologist-0.332 → gromologist-0.333}/LICENSE +0 -0
  15. {gromologist-0.332 → gromologist-0.333}/gromologist/Crooks.py +0 -0
  16. {gromologist-0.332 → gromologist-0.333}/gromologist/DihOpt.py +0 -0
  17. {gromologist-0.332 → gromologist-0.333}/gromologist/Entries.py +0 -0
  18. {gromologist-0.332 → gromologist-0.333}/gromologist/Mutant.py +0 -0
  19. {gromologist-0.332 → gromologist-0.333}/gromologist/Subsection.py +0 -0
  20. {gromologist-0.332 → gromologist-0.333}/gromologist/ThDiff.py +0 -0
  21. {gromologist-0.332 → gromologist-0.333}/gromologist/__init__.py +0 -0
  22. {gromologist-0.332 → gromologist-0.333}/gromologist/gromologist_gui.py +0 -0
  23. {gromologist-0.332 → gromologist-0.333}/gromologist.egg-info/dependency_links.txt +0 -0
  24. {gromologist-0.332 → gromologist-0.333}/gromologist.egg-info/not-zip-safe +0 -0
  25. {gromologist-0.332 → gromologist-0.333}/gromologist.egg-info/requires.txt +0 -0
  26. {gromologist-0.332 → gromologist-0.333}/gromologist.egg-info/top_level.txt +0 -0
  27. {gromologist-0.332 → gromologist-0.333}/setup.cfg +0 -0
  28. {gromologist-0.332 → gromologist-0.333}/tests/test_pdb.py +0 -0
  29. {gromologist-0.332 → gromologist-0.333}/tests/test_pdb_extended.py +0 -0
  30. {gromologist-0.332 → gromologist-0.333}/tests/test_top.py +0 -0
  31. {gromologist-0.332 → gromologist-0.333}/tests/test_top_section_entry.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: gromologist
3
- Version: 0.332
3
+ Version: 0.333
4
4
  Summary: Library to handle various GROMACS-related stuff
5
5
  Author: Milosz Wieczor
6
6
  Author-email: milafternoon@gmail.com
@@ -29,6 +29,7 @@ For a growing base of common applications, workflows and use cases, check out [t
29
29
  * [Editing the contents of the system](#editing-contents-system)
30
30
  * [Modifying Lennard-Jones parameters](#modifying-lj-terms)
31
31
  * [Adding NBFIX terms](#adding-nbfix-terms)
32
+ * [Generating GHBFIX pairs](#generating-ghbfix-pairs)
32
33
  * [Adding Go terms](#adding-go-terms)
33
34
  * [Adding H-mass repartitioning](#adding-hmass-repartitioning)
34
35
  * [Explicitly listing parameters in topology & finding missing parameters](#explicitly-listing-parameters-in-topology---finding-missing-parameters)
@@ -627,6 +628,33 @@ To generate an NBFIX (custom combination rule) entry, use the following snippet:
627
628
  This will introduce a term modifying the CT-HA Lennard-Jones interaction, increasing the default
628
629
  (Lorenz-Berthelot) sigma by 0.01 nm, and decreasing the default epsilon by 0.1 kJ/mol.
629
630
 
631
+ ##### Generating GHBFIX pairs
632
+ <a name="generating-ghbfix-pairs"/>
633
+
634
+ To generate atom pairs and type/scaling tables for the PLUMED
635
+ [`GHBFIX`](https://www.plumed.org/doc-v2.10/user-doc/html/_g_h_b_f_i_x.html) action, prepare a text file
636
+ containing two topology atom types followed by either one or three scaling parameters on each line:
637
+
638
+ ```
639
+ OA HN 1.25
640
+ OS HO 0.80 0.25 0.10
641
+ ```
642
+
643
+ The pairs can then be generated from Python:
644
+
645
+ ```
646
+ >>> from gromologist import make_ghbfix_pairs
647
+ >>> make_ghbfix_pairs('topol.top', hbfix='hbfix.dat')
648
+ ```
649
+
650
+ By default, this writes `scalingParameters.dat` and `typesTable.dat`, and prints the corresponding
651
+ `GHBFIX` directive. Output paths can be changed with the `scaling_parm` and `types_table` arguments.
652
+ The same operation is available as a command-line tool:
653
+
654
+ ```
655
+ gml-make-ghbfix-pairs topol.top [hbfix.dat [scalingParameters.dat [typesTable.dat]]]
656
+ ```
657
+
630
658
  ##### Adding Go terms
631
659
  <a name="adding-go-terms"/>
632
660
 
@@ -1153,4 +1181,4 @@ with the following example command:
1153
1181
  Newly created files include: `forcefield.itp`, `ffparams.itp`, `*.rtp` (rna, dna, aminoacids - depending on the defined
1154
1182
  residues), and `atomtypes.atp`. In the case of non-standard residues, please check for correct addition of improper dihedrals.
1155
1183
 
1156
- Report bugs and issues to [milosz.wieczor\@irbbarcelona.org](mailto:milosz.wieczor@irbbarcelona.org?subject=gromologist).
1184
+ Report bugs and issues to [milosz.wieczor\@irbbarcelona.org](mailto:milosz.wieczor@irbbarcelona.org?subject=gromologist).
@@ -11,6 +11,7 @@ Description:
11
11
  Contents:
12
12
  Functions:
13
13
  gmx_command
14
+ plumed_command
14
15
  gen_mdp
15
16
  find_gmx_dir
16
17
  read_xvg
@@ -54,8 +55,9 @@ from datetime import datetime
54
55
  from pathlib import Path
55
56
 
56
57
  import gromologist as gml
57
- from typing import Optional, Iterable, Union
58
+ from typing import Optional, Iterable, Union, Tuple
58
59
  from glob import glob
60
+ import shlex
59
61
 
60
62
 
61
63
  def _gmx_command(gmx_exe: str, command: str = 'grompp', answer: bool = False, pass_values: Optional[Iterable] = None,
@@ -100,6 +102,71 @@ def gmx_command(*args, **kwargs):
100
102
  return result
101
103
 
102
104
 
105
+ def plumed_command(plumed_exe: str = 'plumed', command: str = 'driver', answer: bool = False,
106
+ quiet: bool = False, fail_on_error: bool = False,
107
+ mpi: Optional[Union[str, Iterable[str]]] = None, **params) -> Union[Tuple[str, str], Tuple[str, str, str]]:
108
+ """
109
+ Runs a PLUMED command, optionally using an MPI launcher.
110
+
111
+ :param plumed_exe: str, executable name or path
112
+ :param command: str, PLUMED command to launch, default driver
113
+ :param answer: bool, whether to append captured stdout/stderr to the returned tuple
114
+ :param quiet: bool, whether to suppress printing command output
115
+ :param fail_on_error: bool, whether to raise RuntimeError on a nonzero exit code
116
+ :param mpi: optional launcher prefix, e.g. 'mpiexec -n 1' or ['mpiexec', '-n', '1']
117
+ :param params: keyword options passed as --key value; True adds a flag,
118
+ False and None omit it. Double underscores in keys become hyphens.
119
+ :return: (filename, variable) from the first PRINT directive with a FILE option;
120
+ with answer=True, returns (filename, variable, captured_output).
121
+ Comma-separated ARG values are returned unchanged as a single string.
122
+ :raises ValueError: if no PRINT output filename or its ARG value is found
123
+
124
+ Reads the input specified by plumed (default plumed.dat) before launching.
125
+ Filenames are returned as written in the input file.
126
+
127
+ Example::
128
+
129
+ gml.plumed_command(mpi='mpiexec -n 1', plumed='plumed.dat',
130
+ ixtc='../dyn_100wat.xtc')
131
+ """
132
+ plumed_input = params.get('plumed', 'plumed.dat')
133
+ filename = variable = None
134
+ with open(plumed_input) as source:
135
+ for line in source:
136
+ tokens = shlex.split(line, comments=True)
137
+ if tokens and tokens[0].endswith(':'):
138
+ tokens = tokens[1:]
139
+ if not tokens or tokens[0] != 'PRINT':
140
+ continue
141
+ options = dict(token.split('=', 1) for token in tokens[1:] if '=' in token)
142
+ if options.get('FILE'):
143
+ filename = options['FILE']
144
+ variable = options.get('ARG')
145
+ break
146
+ if filename is None:
147
+ raise ValueError(f"No PRINT output FILE found in {plumed_input!r}")
148
+ if not variable:
149
+ raise ValueError(f"No ARG found for PRINT output {filename!r} in {plumed_input!r}")
150
+
151
+ call_command = shlex.split(mpi) if isinstance(mpi, str) else list(mpi or [])
152
+ call_command.extend([str(plumed_exe), command])
153
+ for key, value in params.items():
154
+ if value is None or value is False:
155
+ continue
156
+ call_command.append('--' + key.replace('__', '-'))
157
+ if value is not True:
158
+ call_command.append(str(value))
159
+ result = run(call_command, stderr=PIPE, stdout=PIPE, check=False)
160
+ output = result.stdout.decode(errors='replace') + result.stderr.decode(errors='replace')
161
+ if not quiet:
162
+ print(output)
163
+ if result.returncode != 0 and fail_on_error:
164
+ raise RuntimeError(f"Command {call_command!r} failed with exit code {result.returncode}:\n{output}")
165
+ if answer:
166
+ return filename, variable, output
167
+ return filename, variable
168
+
169
+
103
170
  def gen_mdp(fname: str, runtype: str = 'md', **extra_args):
104
171
  """
105
172
  Produces a default .mdp file for the rerun
@@ -161,7 +228,7 @@ def read_xvg(fname: str, cols: Optional[list] = None) -> np.array:
161
228
  """
162
229
  Reads an .xvg file into a 2D list
163
230
  :param fname: str, .xvg file to read
164
- :param cols: list of int, columns to select
231
+ :param cols: list of int, columns to select (0-based)
165
232
  :return: np.array, numeric data from the .xvg file
166
233
  """
167
234
  content = [[float(x) for x in line.split()[1:]] for line in open(fname) if not line.startswith(('#', '@'))]
@@ -260,7 +327,7 @@ def calc_gmx_energy(struct: str, topfile: str, gmx: str = '', quiet: bool = Fals
260
327
  terms: Optional[Union[str, list]] = None, cleanup: bool = True, group_a: Optional[str] = None,
261
328
  group_b: Optional[str] = None, sum_output: bool = False, savetxt: Optional[str] = None,
262
329
  nb_cutoff: Optional[float] = 2.0, mdp: Optional[str] = None, set_omp: Optional[bool] = None,
263
- **kwargs) -> dict:
330
+ plumed: Optional[str] = None, **kwargs) -> dict:
264
331
  """
265
332
  Calculates selected energy terms given a structure/topology pair or structure/topology/trajectory set.
266
333
  :param struct: str, path to the structure file
@@ -277,6 +344,7 @@ def calc_gmx_energy(struct: str, topfile: str, gmx: str = '', quiet: bool = Fals
277
344
  :param nb_cutoff: float, cutoff for non-bonded interactions (Coulomb and VdW), default 1.2 nm
278
345
  :param mdp: str, use it to specify a custom .mdp file
279
346
  :param set_omp: bool, will set OMP threads to 1
347
+ :param plumed: str, Plumed input that returns a single extra energy term that will be added to the result
280
348
  :param kwargs: dict, options that will be added to the .mdp file
281
349
  :return: dict of lists, one list of per-frame values per each selected term
282
350
  """
@@ -329,7 +397,7 @@ def calc_gmx_energy(struct: str, topfile: str, gmx: str = '', quiet: bool = Fals
329
397
  passv = [legend[i.lower()] for i in terms]
330
398
  except KeyError:
331
399
  raise RuntimeError(f'Could not process query {terms}; available keywords are: {legend.keys()}')
332
- gmx_command(gmx, 'energy', quiet=quiet, pass_values=passv, f='rerun')
400
+ gmx_command(gmx, 'energy', quiet=quiet, pass_values=passv, f='rerun.edr')
333
401
  out = read_xvg('energy.xvg')
334
402
  if cleanup:
335
403
  to_remove = ['rerun.mdp', 'mdout.mdp', 'rerun.tpr', 'rerun.edr', 'rerun.log', 'energy.xvg']
@@ -345,6 +413,14 @@ def calc_gmx_energy(struct: str, topfile: str, gmx: str = '', quiet: bool = Fals
345
413
  except:
346
414
  pass
347
415
  values = {term: out[:,onum] for term, onum in zip(terms, range(len(out[0])))}
416
+ if plumed:
417
+ if not traj:
418
+ raise NotImplementedError("Plumed terms are only implemented for trajectories") # TODO
419
+ plu_filename, plu_variable, _ = gml.plumed_command(mpi='mpiexec -n 1', plumed=plumed, ixtc=traj, answer=True)
420
+ plu_values = read_xvg(plu_filename, cols=[0])
421
+ if len(plu_values) != len(out):
422
+ raise ValueError("PLUMED and GROMACS frame counts differ")
423
+ values[plu_variable] = plu_values
348
424
  if sum_output:
349
425
  nframes = len(values[list(values.keys())[0]])
350
426
  values['sum'] = [sum([values[k][n] for k in values.keys()]) for n in range(nframes)]
@@ -48,8 +48,10 @@ class SelectionParser:
48
48
  selection_string = selection_string.strip()
49
49
  protein_selection = "resname ACE NME NMA " + " ".join(list(Pdb.prot_map.keys()))
50
50
  dna_selection = "resname DA DG DC DT DA5 DG5 DC5 DT5 DA3 DG3 DC3 DT3"
51
- rna_selection = "resname RA RG RC RU RA5 RG5 RC5 RU5 RA3 RG3 RC3 RU3 A G C U A3 A5 G3 G5 C3 C5 U 3 U5"
52
- solvent_selection = "resname HOH TIP3 SOL OPC SPC WAT K CL NA POT K+ NA+ CLA CL-"
51
+ rna_selection = "resname RA RG RC RU RA5 RG5 RC5 RU5 RA3 RG3 RC3 RU3 A G C U A3 A5 G3 G5 C3 C5 U3 U5"
52
+ water_selection = ("resname H2O HOH OHH OH2 SOL WAT TIP TIP3 TIP3P TIPS3P T3P T3H W "
53
+ "TIP4 TIP4P TIP4PEW TIP4PD T4P TIP5 TIP5P T5P SPC SPCE OPC OPC3 POL3")
54
+ solvent_selection = water_selection + " K CL NA POT K+ NA+ CLA CL-"
53
55
  backbone_selection = ("name P O1P O2P OP1 OP2 O5' H5T C5' H5'1 H5'2 H5' H5'' C4' H4' O4' C1' H1' C3' H3' C2' "
54
56
  "H2'1 H2'2 H2' H2'' O2' HO2' O3' H3T 1H5' 2H5' 1H2' 2H2' N HN CA HA C O HA1 HA2 H HO'2")
55
57
  ion_selection = "resname K CL NA POT K+ NA+ CLA CL- MG MGA ZN"
@@ -57,7 +59,7 @@ class SelectionParser:
57
59
  noh_selection = "not element H"
58
60
  self.keyword_selections = {
59
61
  "solvent": solvent_selection,
60
- "water": "resname HOH TIP3 SOL OPC SPC WAT",
62
+ "water": water_selection,
61
63
  "protein": protein_selection,
62
64
  "backbone": backbone_selection,
63
65
  "nucleic": f"({dna_selection} or {rna_selection})",
@@ -223,10 +225,10 @@ class SelectionParser:
223
225
  end = float(sel_string.split('<=')[1].strip())
224
226
  for n, a in enumerate(atomlist):
225
227
  if not rev:
226
- if float(a.__getattribute__(matchings[keyw])) < end:
228
+ if float(a.__getattribute__(matchings[keyw])) <= end:
227
229
  chosen.append(n)
228
230
  else:
229
- if float(a.__getattribute__(matchings[keyw])) >= end:
231
+ if float(a.__getattribute__(matchings[keyw])) > end:
230
232
  chosen.append(n)
231
233
  elif ">=" in sel_string:
232
234
  try:
@@ -1117,7 +1117,11 @@ class Pdb:
1117
1117
  """
1118
1118
  for a in self.atoms:
1119
1119
  if (not a.element) or force:
1120
- a.element = [x for x in a.atomname if not x.isdigit()][0]
1120
+ try:
1121
+ a.element = [x for x in a.atomname if not x.isdigit()][0]
1122
+ except:
1123
+ print(f'Setting element "X" for unknown atom {a.atomname}')
1124
+ a.element = 'X'
1121
1125
 
1122
1126
  def add_qt(self) -> None:
1123
1127
  """
@@ -2621,51 +2625,21 @@ class Traj:
2621
2625
  :return: None
2622
2626
  """
2623
2627
 
2624
- def compute_cumulative_distance(points):
2625
- """Compute the cumulative distance along a path defined by 'points'."""
2626
- deltas = np.diff(points, axis=0)
2627
- segment_lengths = np.sqrt(np.sum(deltas ** 2, axis=1))
2628
- return np.insert(np.cumsum(segment_lengths), 0, 0)
2629
-
2630
- def interpolate_between_points(point1, point2, fraction):
2631
- """Interpolate between two points given a fraction."""
2632
- return point1 + fraction * (point2 - point1)
2633
-
2634
- def resample_by_distance(points, distance):
2635
- """Resample a path defined by 'points' such that the new points are approximately 'distance' apart."""
2636
- cumulative_distances = compute_cumulative_distance(points)
2637
- max_distance = cumulative_distances[-1]
2638
- # Start with the first point
2639
- new_points = [points[0]]
2640
- current_distance = distance
2641
- while current_distance < max_distance:
2642
- # Find two points which are before and after the current distance
2643
- idx = np.searchsorted(cumulative_distances, current_distance) - 1
2644
- point_before, point_after = points[idx], points[idx + 1]
2645
- distance_before, distance_after = cumulative_distances[idx], cumulative_distances[idx + 1]
2646
- # Interpolate between the two points for the resampled point
2647
- fraction = (current_distance - distance_before) / (distance_after - distance_before)
2648
- new_point = interpolate_between_points(point_before, point_after, fraction)
2649
- new_points.append(new_point)
2650
- current_distance += distance
2651
- return np.array(new_points)
2652
-
2653
- def find_optimal_distance(points, num_points, tolerance=1e-3, max_iterations=100):
2654
- total_length = compute_cumulative_distance(points)[-1]
2655
- guessed_distance = total_length / (num_points - 1)
2656
- for iteration in range(max_iterations):
2657
- resampled = resample_by_distance(points, guessed_distance)
2658
- if len(resampled) == num_points:
2659
- return guessed_distance
2660
- elif len(resampled) < num_points:
2661
- guessed_distance *= 0.99
2662
- else:
2663
- guessed_distance *= 1.01
2664
- raise ValueError("Couldn't converge to a solution in given max_iterations.")
2665
-
2628
+ if len(self) < 3:
2629
+ return
2666
2630
  for natom in range(len(self.atoms)):
2667
2631
  atom_path = np.array([struct.atoms[natom].coords for struct in self.structures])
2668
- resampled_path = resample_by_distance(atom_path, find_optimal_distance(atom_path, len(self)))
2632
+ distances = np.linalg.norm(np.diff(atom_path, axis=0), axis=1)
2633
+ cumulative = np.insert(np.cumsum(distances), 0, 0)
2634
+ if cumulative[-1] == 0:
2635
+ continue
2636
+ # Drop repeated positions so interpolation has strictly increasing distances.
2637
+ keep = np.concatenate(([True], distances > 0))
2638
+ targets = np.linspace(0, cumulative[-1], len(self))
2639
+ resampled_path = np.column_stack([
2640
+ np.interp(targets, cumulative[keep], atom_path[keep, axis])
2641
+ for axis in range(3)
2642
+ ])
2669
2643
  for struct, coords in zip(self.structures[1:-1], resampled_path[1:-1]):
2670
2644
  struct.atoms[natom].set_coords(coords)
2671
2645
 
@@ -1597,16 +1597,16 @@ class SectionMol(Section):
1597
1597
  neigh_atoms_2 = [[b+offset for b in bond if b != atom_other][0] for bond in other.bonds if atom_other in bond]
1598
1598
  # atoms only neighboring with atoms from the above lists
1599
1599
  neigh_atoms_11 = [list(set(bond).difference(set(neigh_atoms_1)))[0] for bond in self.bonds
1600
- if set(neigh_atoms_1) & set(bond) and atom_own not in bond]
1600
+ if len(set(neigh_atoms_1) & set(bond)) == 1 and atom_own not in bond]
1601
1601
  neigh_atoms_21 = [list(set(tuple(b+offset for b in bond)).difference(set(neigh_atoms_2)))[0] for bond in other.bonds
1602
- if set(neigh_atoms_2) & set(bond) and atom_other not in bond]
1602
+ if len(set(neigh_atoms_2) & {b+offset for b in bond}) == 1 and atom_other not in bond]
1603
1603
  new_pairs = list(product(neigh_atoms_1, neigh_atoms_2)) + list(product([atom_own], neigh_atoms_21)) + \
1604
1604
  list(product([atom_other+offset], neigh_atoms_11))
1605
1605
  new_dihedrals = [(a, atom_own, atom_other+offset, d) for a, d in list(product(neigh_atoms_1, neigh_atoms_2))]
1606
1606
  new_dihedrals += [(a, b, atom_own, atom_other+offset) for a in neigh_atoms_11 for b in neigh_atoms_1
1607
1607
  if (a, b) in self.bonds or (b, a) in self.bonds]
1608
1608
  new_dihedrals += [(atom_own, atom_other+offset, c, d) for d in neigh_atoms_21 for c in neigh_atoms_2
1609
- if (c, d) in self.bonds or (d, c) in self.bonds]
1609
+ if (c-offset, d-offset) in other.bonds or (d-offset, c-offset) in other.bonds]
1610
1610
  # cleanup same-1-4 cases for 3-membered rings etc
1611
1611
  # TODO also remove pairs for 4- and 5-membered rings
1612
1612
  # TODO make sure there are no replicates wrt existing terms
@@ -274,6 +274,32 @@ class Top:
274
274
  mol2 = self.molecules[molname2] if isinstance(molname2, int) else self.get_molecule(molname2)
275
275
  mol1.merge_two(mol2, -1, -1)
276
276
 
277
+ def set_number_of_molecules(self, molname: Union[str, int], nmol: int) -> None:
278
+ """
279
+ Sets the number of copies of a defined molecule in the [ molecules ] section.
280
+ Adds an entry (and creates the section if needed) when the molecule is not
281
+ listed in the system. Multiple entries for the same molecule are rejected
282
+ to avoid ambiguity in the ordering of molecules.
283
+ :param molname: str or int, molecule name or 0-based index among defined molecules
284
+ :param nmol: int, non-negative number of molecule copies (zero is allowed)
285
+ :return: None
286
+ """
287
+ if isinstance(nmol, bool) or not isinstance(nmol, int) or nmol < 0:
288
+ raise ValueError("The number of molecules must be a non-negative integer")
289
+ mol = self.molecules[molname] if isinstance(molname, int) else self.get_molecule(molname)
290
+ system_subsections = [s.get_subsection('molecules') for s in self.sections
291
+ if 'molecules' in [ss.header for ss in s.subsections]]
292
+ if len(system_subsections) > 1:
293
+ raise RuntimeError("Multiple 'molecules' subsection found in the topology, this is not allowed")
294
+ entries = [e for e in system_subsections[0].entries
295
+ if e.content and e.content[0] == mol.mol_name] if system_subsections else []
296
+ if len(entries) > 1:
297
+ raise RuntimeError(f"Multiple [ molecules ] entries corresponding to molecule {mol.mol_name}")
298
+ if entries:
299
+ entries[0].content = [mol.mol_name, str(nmol)]
300
+ else:
301
+ self.add_molecules_to_system(molname=mol.mol_name, nmol=nmol)
302
+
277
303
  def explicit_multiple_molecules(self, molname: Union[str, int], renumber_residues: bool = True) -> None:
278
304
  """
279
305
  If a molecule has multiple copies, this transforms it to an explicit
@@ -9,6 +9,7 @@ Description:
9
9
 
10
10
  Contents:
11
11
  Functions:
12
+ tpr2pdb
12
13
  generate_dftb3_aa
13
14
  generate_gaussian_input
14
15
  parse_frcmod
@@ -48,10 +49,12 @@ Notes:
48
49
 
49
50
  import math
50
51
  import os, re, sys
52
+ import tempfile
53
+ from contextlib import nullcontext
51
54
  from glob import glob
52
55
  from subprocess import run, PIPE
53
56
  from shutil import copy2, rmtree
54
- from itertools import permutations
57
+ from itertools import permutations, groupby
55
58
 
56
59
  import gromologist as gml
57
60
  from typing import Optional, Iterable, Union, Dict, List, Tuple
@@ -1334,6 +1337,162 @@ class ConvergeLambdas:
1334
1337
  return new_lambdas
1335
1338
 
1336
1339
 
1340
+ def parse_x3dna_output(basename, sin_cos=False, float_only=False):
1341
+ """Read do_x3dna output into one DataFrame aligned by base-pair identity.
1342
+
1343
+ ``basename`` is a run suffix (e.g. ``sideB_replica1``), optionally with a
1344
+ directory and glob wildcards (e.g. ``results/side*_replica*``).
1345
+ The index is ``(basename, time, res_I, res_II)``. Every frame of a run has
1346
+ one row for every pair observed anywhere in that run, including frames
1347
+ with no detected pairs. ``pair_detected`` marks the actual assignments;
1348
+ unavailable descriptors are NaN. Different runs can have different pair
1349
+ sets. Missing descriptor files are allowed; inconsistent row counts or
1350
+ times raise ValueError rather than silently mislabeling data.
1351
+
1352
+ Descriptor columns are named ``<file prefix>.<descriptor>``. Step values
1353
+ belong to their starting pair; ``next_res_I`` and ``next_res_II`` identify
1354
+ the next detected pair in that frame. The last pair has no step values.
1355
+ Dash-only values become NaN; puckering labels remain strings.
1356
+
1357
+ If ``sin_cos=True``, replace backbone/chi torsions, sugar v0-v4 torsions,
1358
+ and sugar pseudorotation phase P (in degrees) with ``_sin`` and ``_cos``
1359
+ columns. Sugar amplitude tm, geometric angles, and categorical puckering
1360
+ labels are unchanged. NaN values remain NaN.
1361
+
1362
+ If ``float_only=True``, retain only floating-point descriptor columns,
1363
+ after any sin/cos conversion. Boolean flags, strings, and integer columns
1364
+ (including next-pair residue identifiers) are removed. The row index,
1365
+ including its residue identifiers, is preserved.
1366
+ """
1367
+ import pandas as pd
1368
+ import numpy as np
1369
+
1370
+ def read_frames(filename, ncols):
1371
+ frames = {}
1372
+ time = None
1373
+ with open(filename) as handle:
1374
+ for lineno, line in enumerate(handle, 1):
1375
+ line = line.strip()
1376
+ match = re.match(r'#\s*Time\s*=\s*(\S+)', line)
1377
+ if match:
1378
+ time = float(match.group(1))
1379
+ if time in frames:
1380
+ raise ValueError(f'{filename}:{lineno}: duplicate time {time}')
1381
+ frames[time] = []
1382
+ elif line and not line.startswith('#'):
1383
+ if time is None:
1384
+ raise ValueError(f'{filename}:{lineno}: data before first time marker')
1385
+ fields = line.split()
1386
+ if len(fields) != ncols:
1387
+ raise ValueError(f'{filename}:{lineno}: expected {ncols} columns, got {len(fields)}')
1388
+ frames[time].append(fields)
1389
+ return frames
1390
+
1391
+ strand_columns = lambda names: [f'{name}_{strand}' for strand in ('I', 'II') for name in names]
1392
+ # Step tables have one fewer row than the current frame's base-pair list.
1393
+ schemas = {
1394
+ 'h-bond': (['h-bonds'], False),
1395
+ 'L-BP': ('Shear Stretch Stagger Buckle Propeller Opening'.split(), False),
1396
+ 'L-BPS': ('Shift Slide Rise Tilt Roll Twist'.split(), True),
1397
+ 'L-BPH': ('X-disp Y-disp h-Rise Incl. Tip h-Twist'.split(), True),
1398
+ 'HelAxis': ('Px Py Pz Hx Hy Hz'.split(), True),
1399
+ 'HelixRad': (strand_columns(['P', "O4'", "C1'"]), True),
1400
+ 'MGroove': (['Minor_P-P', 'Minor_Refined', 'Major_P-P', 'Major_Refined'], True),
1401
+ 'BackBoneCHiDihedrals': (strand_columns('alpha beta gamma delta epsilon zeta chi'.split()), False),
1402
+ 'SugarDihedrals': (strand_columns('v0 v1 v2 v3 v4 tm P Puckering'.split()), False),
1403
+ }
1404
+ directory, pattern = os.path.split(os.fspath(basename))
1405
+ assignment_files = sorted(glob(os.path.join(directory, f'base_pairs_{pattern}.dat')))
1406
+ if not assignment_files:
1407
+ raise FileNotFoundError(f'No base-pair assignment files match {basename!r}')
1408
+
1409
+ indices, records = {}, {}
1410
+ grid = []
1411
+ next_pairs = {}
1412
+ for assignment_file in assignment_files:
1413
+ run_name = os.path.basename(assignment_file)[len('base_pairs_'):-len('.dat')]
1414
+ assignments = read_frames(assignment_file, 2)
1415
+ pairs = {}
1416
+ for time, rows in assignments.items():
1417
+ pairs[time] = [tuple(map(int, row)) for row in rows]
1418
+ for pair in pairs[time]:
1419
+ indices.setdefault('base_pairs', []).append((run_name, time, *pair))
1420
+ records.setdefault('base_pairs', []).append(pair)
1421
+ run_pairs = sorted({pair for frame_pairs in pairs.values() for pair in frame_pairs})
1422
+ grid.extend((run_name, time, *pair) for time in assignments for pair in run_pairs)
1423
+ for time, frame_pairs in pairs.items():
1424
+ for pair, next_pair in zip(frame_pairs, frame_pairs[1:]):
1425
+ next_pairs[(run_name, time, *pair)] = next_pair
1426
+ # Keep an empty assignment table when no pairs were detected at all.
1427
+ records.setdefault('base_pairs', [])
1428
+ indices.setdefault('base_pairs', [])
1429
+ for prefix, (columns, is_step) in schemas.items():
1430
+ filename = os.path.join(directory, f'{prefix}_{run_name}.dat')
1431
+ if not os.path.isfile(filename):
1432
+ continue
1433
+ frames = read_frames(filename, len(columns))
1434
+ if frames.keys() != assignments.keys():
1435
+ raise ValueError(f'{filename}: times do not match {assignment_file}')
1436
+ records.setdefault(prefix, [])
1437
+ indices.setdefault(prefix, [])
1438
+ for time, rows in frames.items():
1439
+ frame_pairs = pairs[time]
1440
+ expected = max(0, len(frame_pairs) - int(is_step))
1441
+ if len(rows) != expected:
1442
+ raise ValueError(f'{filename}: time {time}: expected {expected} rows from '
1443
+ f'base-pair assignments, got {len(rows)}')
1444
+ for i, row in enumerate(rows):
1445
+ label = (run_name, time, *frame_pairs[i])
1446
+ if is_step:
1447
+ label += frame_pairs[i + 1]
1448
+ indices[prefix].append(label)
1449
+ records[prefix].append([
1450
+ (value if column.startswith('Puckering_') else float(value))
1451
+ if value.strip('-') else float('nan')
1452
+ for column, value in zip(columns, row)
1453
+ ])
1454
+
1455
+ names = ['basename', 'time', 'res_I', 'res_II']
1456
+ index = pd.MultiIndex.from_tuples(grid, names=names)
1457
+ result = pd.DataFrame(index=index)
1458
+ detected = pd.MultiIndex.from_tuples(indices['base_pairs'], names=names)
1459
+ result['pair_detected'] = index.isin(detected)
1460
+ neighbors = pd.DataFrame(
1461
+ list(next_pairs.values()),
1462
+ index=pd.MultiIndex.from_tuples(list(next_pairs), names=names),
1463
+ columns=['next_res_I', 'next_res_II'],
1464
+ )
1465
+ result = result.join(neighbors.astype('Int64'))
1466
+ for prefix, rows in records.items():
1467
+ if prefix == 'base_pairs':
1468
+ continue
1469
+ columns, is_step = schemas[prefix]
1470
+ # The next pair is stored explicitly above, so all descriptors share
1471
+ # the same four index levels and can be joined without losing rows.
1472
+ labels = [label[:4] for label in indices[prefix]]
1473
+ table = pd.DataFrame(rows, index=pd.MultiIndex.from_tuples(labels, names=names), columns=columns)
1474
+ if sin_cos:
1475
+ if prefix == 'BackBoneCHiDihedrals':
1476
+ angular_columns = columns
1477
+ elif prefix == 'SugarDihedrals':
1478
+ angular_columns = strand_columns(['v0', 'v1', 'v2', 'v3', 'v4', 'P'])
1479
+ else:
1480
+ angular_columns = []
1481
+ encoded = {}
1482
+ for column in table.columns:
1483
+ if column in angular_columns:
1484
+ radians = np.deg2rad(table[column].astype(float))
1485
+ encoded[f'{column}_sin'] = np.sin(radians)
1486
+ encoded[f'{column}_cos'] = np.cos(radians)
1487
+ else:
1488
+ encoded[column] = table[column]
1489
+ table = pd.DataFrame(encoded, index=table.index)
1490
+ result = result.join(table.add_prefix(f'{prefix}.'))
1491
+ if float_only:
1492
+ result = result.select_dtypes(include=['floating'])
1493
+ return result
1494
+
1495
+
1337
1496
  def plumed_maker(struct: "gml.Pdb", selections: list, label_core: str, command: str, params: str = ''):
1338
1497
  """
1339
1498
  Can make multiple Plumed group/COM/center/... definitions based on a list of selections.
@@ -1565,17 +1724,158 @@ def hydrogen_mass_repartitioning(argv=sys.argv[1:]):
1565
1724
  t.save_top(top.split('.')[0] + '_hmr.' + top.split('.')[1])
1566
1725
 
1567
1726
 
1727
+ def keep_waters(trajectory: str, tpr: str, solute_selection: str, n_waters: int,
1728
+ keep_ions: bool = False, water_selection: str = 'water', quiet: bool = True,
1729
+ cluster: Union[bool, str] = 'auto', keep_intermediates: bool = False) -> Tuple[str, str]:
1730
+ """Keeps the closest ``n_waters`` waters to a solute in each trajectory frame.
1731
+
1732
+ Set ``quiet=False`` to print processing stages as they begin.
1733
+ Set ``cluster=True`` to make molecules whole and cluster the selected solute
1734
+ before centering and ranking waters. Use ``cluster='auto'`` to enable this
1735
+ only when the selected solute has multiple nonblank chain IDs in the
1736
+ extracted structure. Missing chain IDs require an explicit ``True``.
1737
+ Clustering assumes that the selected solute forms one associated complex.
1738
+ Set ``keep_intermediates=True`` to retain intermediate trajectories, the
1739
+ initial structure, and the index in a unique ``<output-prefix>_intermediates_*``
1740
+ directory beside the output, including on failure. Its path is printed when
1741
+ ``quiet=False``. The returned pair of output paths is unchanged.
1742
+ """
1743
+ if cluster is not True and cluster is not False and cluster != 'auto':
1744
+ raise ValueError("cluster must be True, False, or 'auto'")
1745
+
1746
+ def progress(message):
1747
+ if not quiet:
1748
+ print(f"gml-keep-waters: {message}", flush=True)
1749
+
1750
+ progress('Locating GROMACS...')
1751
+ gmx = gml.find_gmx_dir(suppress=True)[1]
1752
+ prefix = os.path.splitext(trajectory)[0] + f'_{n_waters}waters'
1753
+
1754
+ if keep_intermediates:
1755
+ intermediate_dir = tempfile.mkdtemp(
1756
+ prefix=os.path.basename(prefix) + '_intermediates_',
1757
+ dir=os.path.dirname(os.path.abspath(prefix)))
1758
+ progress(f'Keeping intermediate files in {intermediate_dir}')
1759
+ workspace = nullcontext(intermediate_dir)
1760
+ else:
1761
+ workspace = tempfile.TemporaryDirectory()
1762
+
1763
+ with workspace as tmpdir:
1764
+ pdb, ndx, centered, wrapped, ordered = [os.path.join(tmpdir, f) for f in
1765
+ ('frame0.pdb', 'gml.ndx', 'centered.xtc', 'wrapped.xtc', 'ordered.xtc')]
1766
+ progress('Extracting the initial structure...')
1767
+ gml.gmx_command(gmx, 'trjconv', s=tpr, f=trajectory, o=pdb, dump=0, pass_values=['System'],
1768
+ quiet=True, answer=True, fail_on_error=True)
1769
+ progress('Selecting atoms and preparing index groups...')
1770
+ struct = gml.Pdb(pdb)
1771
+ selected_waters = set(struct.get_atom_indices(water_selection))
1772
+ residue_key = lambda at: (at.resnum, at.resname, at.chain, at.insert)
1773
+ water_residues = []
1774
+ for _, atoms in groupby(struct.atoms, key=residue_key):
1775
+ residue = list(atoms)
1776
+ if any(at.index in selected_waters for at in residue):
1777
+ water_residues.append(residue)
1778
+ assert 0 <= n_waters <= len(water_residues), "Invalid number of water molecules"
1779
+ water_size = len(water_residues[0])
1780
+ assert all(len(res) == water_size for res in water_residues), "Inconsistent water molecule sizes"
1781
+
1782
+ waters = [at.index for res in water_residues for at in res]
1783
+ kept_waters = [at.index for res in water_residues[:n_waters] for at in res]
1784
+ ions = struct.get_atom_indices('ions') if keep_ions else []
1785
+ solute = struct.get_atom_indices(solute_selection)
1786
+ chains = {struct.atoms[i].chain.strip() for i in solute if struct.atoms[i].chain.strip()}
1787
+ do_cluster = cluster is True or (cluster == 'auto' and len(chains) > 1)
1788
+ progress(f'Clustering {"enabled" if do_cluster else "disabled"}; '
1789
+ f'{len(chains)} nonblank chain IDs in the selected solute.')
1790
+ kept = solute + kept_waters + ions
1791
+ selections = ['all', solute_selection, 'index ' + ' '.join(str(n) for n in waters), 'ions',
1792
+ 'index ' + ' '.join(str(n) for n in kept)]
1793
+ gml.ndx(struct, selections, fname=ndx, group_names=['System', 'Solute', 'Water', 'Ions', 'Keep'])
1794
+ common = dict(n=ndx, quiet=True, answer=True, fail_on_error=True)
1795
+ input_trajectory = trajectory
1796
+ if do_cluster:
1797
+ whole = os.path.join(tmpdir, 'whole.xtc')
1798
+ clustered = os.path.join(tmpdir, 'clustered.xtc')
1799
+ progress('Making molecules whole before clustering...')
1800
+ gml.gmx_command(gmx, 'trjconv', s=tpr, f=input_trajectory, o=whole, pbc='whole',
1801
+ pass_values=['System'], **common)
1802
+ progress('Clustering the selected solute...')
1803
+ gml.gmx_command(gmx, 'trjconv', s=tpr, f=whole, o=clustered, pbc='cluster',
1804
+ pass_values=['Solute', 'System'], **common)
1805
+ input_trajectory = clustered
1806
+ progress('Centering the solute...')
1807
+ gml.gmx_command(gmx, 'trjconv', s=tpr, f=input_trajectory, o=centered,
1808
+ center=True, pass_values=['Solute', 'System'], **common)
1809
+ progress('Wrapping molecules into the compact unit cell...')
1810
+ gml.gmx_command(gmx, 'trjconv', s=tpr, f=centered, o=wrapped, pbc='mol',
1811
+ ur='compact', pass_values=['System'], **common)
1812
+ progress('Ordering waters by distance to the solute in each frame...')
1813
+ gml.gmx_command(gmx, 'trjorder', s=tpr, f=wrapped, o=ordered, na=water_size, da=0,
1814
+ pass_values=['Solute', 'Water'], **common)
1815
+ progress(f'Writing trajectory to {prefix}.xtc...')
1816
+ gml.gmx_command(gmx, 'trjconv', s=tpr, f=ordered, o=prefix + '.xtc',
1817
+ pass_values=['Keep'], **common)
1818
+ progress(f'Writing structure to {prefix}.gro...')
1819
+ gml.gmx_command(gmx, 'trjconv', s=tpr, f=ordered, o=prefix + '.gro', dump=0,
1820
+ pass_values=['Keep'], **common)
1821
+ progress('Done.')
1822
+ return prefix + '.xtc', prefix + '.gro'
1823
+
1824
+
1825
+ def keep_waters_cli(argv=sys.argv[1:]):
1826
+ keep_intermediates = '--keep-intermediates' in argv
1827
+ argv = [arg for arg in argv if arg != '--keep-intermediates']
1828
+ if argv and argv[0] in ['-h', '--help']:
1829
+ print("usage: gml-keep-waters TRAJECTORY TPR SOLUTE_SELECTION "
1830
+ "N_WATERS [KEEP_IONS] [WATER_SELECTION] [CLUSTER] [--keep-intermediates]\n"
1831
+ "\n"
1832
+ "Keeps the N_WATERS closest water molecules to the solute in each frame.\n"
1833
+ "CLUSTER: true, false, or auto (default) for multiple selected chains.\n"
1834
+ "--keep-intermediates retains diagnostic files beside the output, including on failure.")
1835
+ return
1836
+ if len(argv) not in [4, 5, 6, 7]:
1837
+ print("syntax: gml-keep-waters TRAJECTORY TPR SOLUTE_SELECTION "
1838
+ "N_WATERS [KEEP_IONS] [WATER_SELECTION] [CLUSTER] [--keep-intermediates]")
1839
+ return
1840
+ keep_ions = argv[4].lower() == 'true' if len(argv) >= 5 else False
1841
+ assert len(argv) == 4 or argv[4].lower() in ['true', 'false'], "KEEP_IONS must be true or false"
1842
+ water_selection = argv[5] if len(argv) >= 6 else 'water'
1843
+ cluster_arg = argv[6].lower() if len(argv) == 7 else 'auto'
1844
+ if cluster_arg not in ['true', 'false', 'auto']:
1845
+ raise ValueError("CLUSTER must be true, false, or auto")
1846
+ cluster = 'auto' if cluster_arg == 'auto' else cluster_arg == 'true'
1847
+ keep_waters(*argv[:3], int(argv[3]), keep_ions, water_selection, quiet=False, cluster=cluster,
1848
+ keep_intermediates=keep_intermediates)
1849
+
1850
+
1568
1851
  def nojump_per_chain(argv=sys.argv[1:]):
1569
1852
  if argv and argv[0] in ['-h', '--help']:
1570
- print("usage: gml-pbc-from-template traj.xtc struct.pdb [comma_separated_chain_ids]\n"
1853
+ print("usage: gml-pbc-from-template traj.xtc struct.pdb "
1854
+ "[fit_selection] [--reference-frame first|last|FRAME]\n"
1571
1855
  "\n"
1572
- "Removes per-chain PBC jumps by tracking each chain independently.\n"
1856
+ "Places chains relative to the reference structure, then removes\n"
1857
+ "per-chain PBC jumps by tracking each chain independently.\n"
1858
+ "The reference frame is aligned to the PDB first, and tracking\n"
1859
+ "then proceeds both forward and backward from that frame. FRAME\n"
1860
+ "is a zero-based trajectory frame number and defaults to first.\n"
1861
+ "If fit_selection is provided, aligns the corrected complex to\n"
1862
+ "the reference structure using that Gromologist atom selection.\n"
1573
1863
  "Writes `*_nojump.xtc` next to the input trajectory.\n"
1574
1864
  "\n"
1575
- "If chain IDs are omitted, all chains present in the structure are used.")
1865
+ "All chains present in the reference structure are processed.")
1576
1866
  return
1867
+ argv = list(argv)
1868
+ reference_frame = 'first'
1869
+ if '--reference-frame' in argv:
1870
+ option_index = argv.index('--reference-frame')
1871
+ if option_index == len(argv) - 1:
1872
+ print("syntax: --reference-frame requires first, last, or a zero-based frame number")
1873
+ return
1874
+ reference_frame = argv[option_index + 1]
1875
+ del argv[option_index:option_index + 2]
1577
1876
  if len(argv) < 2 or len(argv) > 3:
1578
- print("syntax: gml-pbc-from-template traj.xtc struct.pdb [comma_separated_chain_ids]")
1877
+ print("syntax: gml-pbc-from-template traj.xtc struct.pdb "
1878
+ "[fit_selection] [--reference-frame first|last|FRAME]")
1579
1879
  return
1580
1880
  try:
1581
1881
  import mdtraj as md
@@ -1584,7 +1884,8 @@ def nojump_per_chain(argv=sys.argv[1:]):
1584
1884
  return
1585
1885
 
1586
1886
  xtc, pdb = argv[0], argv[1]
1587
- chains = [ch.strip() for ch in argv[2].split(',')] if len(argv) == 3 else None
1887
+ chains = None
1888
+ fit_selection = argv[2] if len(argv) == 3 else None
1588
1889
 
1589
1890
  out_xtc = xtc.replace('.xtc', '_nojump.xtc')
1590
1891
  if os.path.exists(out_xtc):
@@ -1614,15 +1915,31 @@ def nojump_per_chain(argv=sys.argv[1:]):
1614
1915
  if traj.unitcell_vectors is None:
1615
1916
  raise ValueError("Trajectory lacks unitcell information.")
1616
1917
 
1918
+ reference = md.load(pdb)
1919
+ if reference.n_atoms != traj.n_atoms:
1920
+ raise ValueError("Reference structure and trajectory contain different numbers of atoms.")
1921
+
1617
1922
  new = traj.slice(range(traj.n_frames), copy=True)
1618
1923
  xyz = new.xyz
1619
1924
  cell = new.unitcell_vectors
1620
- prev_refs = _chain_reference_points(xyz[0], chain_atom_indices)
1621
- for t in range(new.n_frames):
1925
+
1926
+ if reference_frame == 'first':
1927
+ anchor_frame = 0
1928
+ elif reference_frame == 'last':
1929
+ anchor_frame = new.n_frames - 1
1930
+ else:
1931
+ try:
1932
+ anchor_frame = int(reference_frame)
1933
+ except ValueError:
1934
+ raise ValueError("Reference frame must be 'first', 'last', or a zero-based frame number.")
1935
+ if anchor_frame < 0 or anchor_frame >= new.n_frames:
1936
+ raise ValueError(f"Reference frame {anchor_frame} is outside a trajectory with {new.n_frames} frames.")
1937
+
1938
+ def _place_frame_near(t, previous_refs):
1622
1939
  A = cell[t]
1623
1940
  invA = np.linalg.inv(A)
1624
1941
  cur_refs = _chain_reference_points(xyz[t], chain_atom_indices)
1625
- prev_f = np.dot(prev_refs, invA)
1942
+ prev_f = np.dot(previous_refs, invA)
1626
1943
  cur_f = np.dot(cur_refs, invA)
1627
1944
  delta_f = cur_f - prev_f
1628
1945
  shift_int = -np.round(delta_f)
@@ -1630,12 +1947,119 @@ def nojump_per_chain(argv=sys.argv[1:]):
1630
1947
  if np.any(shift_int[c] != 0):
1631
1948
  dr = np.dot(shift_int[c], A)
1632
1949
  xyz[t, idx, :] += dr
1633
- prev_refs = cur_refs
1950
+ return _chain_reference_points(xyz[t], chain_atom_indices)
1951
+
1952
+ anchor_refs = _place_frame_near(
1953
+ anchor_frame, _chain_reference_points(reference.xyz[0], chain_atom_indices)
1954
+ )
1955
+ prev_refs = anchor_refs
1956
+ for t in range(anchor_frame + 1, new.n_frames):
1957
+ prev_refs = _place_frame_near(t, prev_refs)
1958
+ prev_refs = anchor_refs
1959
+ for t in range(anchor_frame - 1, -1, -1):
1960
+ prev_refs = _place_frame_near(t, prev_refs)
1961
+
1634
1962
  new.xyz = xyz
1963
+ if fit_selection is not None:
1964
+ fit_indices = np.asarray(struct.get_atom_indices(fit_selection), dtype=int)
1965
+ if len(fit_indices) == 0:
1966
+ raise ValueError(f"Empty fit selection detected for '{fit_selection}'.")
1967
+ new.superpose(reference, atom_indices=fit_indices, ref_atom_indices=fit_indices)
1635
1968
  new.save_xtc(out_xtc)
1636
1969
  return out_xtc
1637
1970
 
1638
1971
 
1972
+ def make_ghbfix_pairs(top: Union[str, "gml.Top"], hbfix: str='hbfix.dat', scaling_parm: str='scalingParameters.dat',
1973
+ types_table: str='typesTable.dat', rerun: bool=False) -> None:
1974
+ """
1975
+ Generates atom pairs and type/scaling tables for the PLUMED GHBFIX action.
1976
+ Each row of the input file should contain two atom types followed by either one or three scaling parameters.
1977
+ All matching pairs of atoms in the topology are included, except pairs containing the same atom twice.
1978
+ :param top: str or gml.Top, topology used to find atoms with the requested types
1979
+ :param hbfix: str, input file containing atom-type pairs and their scaling parameters
1980
+ :param scaling_parm: str, output file for scaling parameters indexed by atom type
1981
+ :param types_table: str, output file assigning a type index to each atom in the generated pair groups
1982
+ :param rerun: bool, sets stride=1 when set to True
1983
+ :return: None
1984
+ """
1985
+ from itertools import product
1986
+ top = gml.obj_or_str(top=top, suppress=True)
1987
+ with open(hbfix) as hbfix_file:
1988
+ data = [line.split() for line in hbfix_file]
1989
+ all_types = [t for l in data for t in l[:2]]
1990
+ unique_types = sorted(list(set(all_types)))
1991
+ uniques_dict = {t:n for n, t in enumerate(unique_types)}
1992
+ type_pair_indices = [[uniques_dict[l[0]], uniques_dict[l[1]]] for l in data]
1993
+ # EntryAtom.num is local to a molecule definition, so it is repeated when a
1994
+ # molecule occurs more than once in [ molecules ]. Enumerating the expanded
1995
+ # Top.atoms list gives the corresponding one-based, system-wide atom numbers.
1996
+ mol_atoms = {n: [] for n in range(len(unique_types))}
1997
+ type_each_atom = {}
1998
+ for atom_num, atom in enumerate(top.atoms, start=1):
1999
+ if atom.type in uniques_dict:
2000
+ type_index = uniques_dict[atom.type]
2001
+ mol_atoms[type_index].append(atom_num)
2002
+ type_each_atom[atom_num] = type_index
2003
+ all_pairs = []
2004
+ for type_pair in type_pair_indices:
2005
+ numsA = mol_atoms[type_pair[0]]
2006
+ numsB = mol_atoms[type_pair[1]]
2007
+ all_pairs.extend([p for p in product(numsA, numsB) if p[0] != p[1]])
2008
+ final_unique = sorted(set(type_each_atom[i] for j in all_pairs for i in j))
2009
+ final_map = {f: n for n, f in enumerate(final_unique)}
2010
+ with open(types_table, 'w') as out_t:
2011
+ out_t.write("#! FIELDS itype\n")
2012
+ for i in [a[0] for a in all_pairs]:
2013
+ out_t.write(str(final_map[type_each_atom[i]]) + '\n')
2014
+ for i in [a[1] for a in all_pairs]:
2015
+ out_t.write(str(final_map[type_each_atom[i]]) + '\n')
2016
+ with open(scaling_parm, 'w') as out_s:
2017
+ if len(data[0]) > 3:
2018
+ out_s.write("#! FIELDS itype jtype eta d0 dmax\n")
2019
+ else:
2020
+ out_s.write("#! FIELDS itype jtype eta\n")
2021
+ for d in data:
2022
+ try:
2023
+ t1, t2 = final_map[uniques_dict[d[0]]], final_map[uniques_dict[d[1]]]
2024
+ except KeyError:
2025
+ continue
2026
+ if len(d) > 3:
2027
+ out_s.write(f"{t1} {t2} {d[2]} {d[3]} {d[4]}\n")
2028
+ else:
2029
+ out_s.write(f"{t1} {t2} {d[2]}\n")
2030
+ stride = 1 if rerun else 1000
2031
+ print(f"ghb: GHBFIX PAIR GROUPA={','.join([str(a[0]) for a in all_pairs])} GROUPB={','.join([str(a[1]) for a in all_pairs])} C=0.8 TYPES={types_table} PARAMS={scaling_parm}")
2032
+ print(f"PRINT ARG=ghb FILE=hbfix.ener STRIDE={stride}")
2033
+
2034
+
2035
+ def make_ghbfix_pairs_cli(argv=None):
2036
+ if argv is None:
2037
+ argv = sys.argv[1:]
2038
+ if argv and argv[0] in ['-h', '--help']:
2039
+ print("usage: gml-make-ghbfix-pairs topology.top [hbfix.dat "
2040
+ "[scalingParameters.dat [typesTable.dat [False]]]]\n"
2041
+ "\n"
2042
+ "Generates GHBFIX atom pairs and their type/scaling tables.\n"
2043
+ "\n"
2044
+ "Arguments:\n"
2045
+ " topology.top input GROMACS topology\n"
2046
+ " hbfix.dat atom-type pair parameters, default hbfix.dat\n"
2047
+ " scalingParameters.dat output scaling parameters, default scalingParameters.dat\n"
2048
+ " typesTable.dat output atom type table, default typesTable.dat\n"
2049
+ " True/False whether file is intended for a rerun, default False")
2050
+ return
2051
+ if len(argv) < 1 or len(argv) > 5:
2052
+ print("syntax: gml-make-ghbfix-pairs topology.top [hbfix.dat "
2053
+ "[scalingParameters.dat [typesTable.dat [False]]]]")
2054
+ return
2055
+ if len(argv) == 5:
2056
+ value = argv[4].lower()
2057
+ if value not in ('true', 'false'):
2058
+ raise SystemExit("rerun must be True or False")
2059
+ argv = [*argv[:4], value == 'true']
2060
+ make_ghbfix_pairs(*argv)
2061
+
2062
+
1639
2063
  def make_grid_movies(argv=sys.argv[1:]):
1640
2064
  if argv and argv[0] in ['-h', '--help']:
1641
2065
  print("usage: gml-grid-of-movies pattern/of/files [animation_time] [fit_selection]\n"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: gromologist
3
- Version: 0.332
3
+ Version: 0.333
4
4
  Summary: Library to handle various GROMACS-related stuff
5
5
  Author: Milosz Wieczor
6
6
  Author-email: milafternoon@gmail.com
@@ -24,5 +24,6 @@ gromologist.egg-info/requires.txt
24
24
  gromologist.egg-info/top_level.txt
25
25
  tests/test_pdb.py
26
26
  tests/test_pdb_extended.py
27
+ tests/test_release_regressions.py
27
28
  tests/test_top.py
28
29
  tests/test_top_section_entry.py
@@ -2,6 +2,8 @@
2
2
  gml-grid-of-movies = gromologist.Utils:make_grid_movies
3
3
  gml-hydrogen-mass-repartitioning = gromologist.Utils:hydrogen_mass_repartitioning
4
4
  gml-interpolate-structures = gromologist.Pdb:ext_interpolate_structures
5
+ gml-keep-waters = gromologist.Utils:keep_waters_cli
6
+ gml-make-ghbfix-pairs = gromologist.Utils:make_ghbfix_pairs_cli
5
7
  gml-make-index = gromologist.Gmx:make_index
6
8
  gml-pbc-from-template = gromologist.Utils:nojump_per_chain
7
9
  gml-replica-exchange-statistics = gromologist.Utils:replica_exchange_statistics
@@ -1,7 +1,7 @@
1
1
  from setuptools import setup
2
2
 
3
3
  setup(name='gromologist',
4
- version='0.332',
4
+ version='0.333',
5
5
  description='Library to handle various GROMACS-related stuff',
6
6
  author='Milosz Wieczor',
7
7
  author_email='milafternoon@gmail.com',
@@ -14,7 +14,9 @@ setup(name='gromologist',
14
14
  'gml-report-timings = gromologist.Gmx:report_timings',
15
15
  'gml-hydrogen-mass-repartitioning = gromologist.Utils:hydrogen_mass_repartitioning',
16
16
  'gml-grid-of-movies = gromologist.Utils:make_grid_movies',
17
+ 'gml-make-ghbfix-pairs = gromologist.Utils:make_ghbfix_pairs_cli',
17
18
  'gml-replica-exchange-statistics = gromologist.Utils:replica_exchange_statistics',
19
+ 'gml-keep-waters = gromologist.Utils:keep_waters_cli',
18
20
  'gml-make-index = gromologist.Gmx:make_index',
19
21
  'gml-interpolate-structures = gromologist.Pdb:ext_interpolate_structures',
20
22
  'gml-pbc-from-template = gromologist.Utils:nojump_per_chain'
@@ -0,0 +1,47 @@
1
+ """Regression tests for selection boundaries and ring-adjacent bond generation."""
2
+ import unittest
3
+ from types import SimpleNamespace
4
+
5
+ import gromologist as gml
6
+
7
+
8
+ class SelectionBoundaryTest(unittest.TestCase):
9
+ def setUp(self):
10
+ self.pdb = gml.Pdb()
11
+ self.pdb.atoms = [
12
+ gml.Atom('ATOM 1 N ALA A 1 0.000 0.000 0.000 1.00 0.00 N', 0),
13
+ gml.Atom('ATOM 2 CA ALA A 1 1.500 0.000 0.000 1.00 0.00 C', 1),
14
+ gml.Atom('ATOM 3 C ALA A 1 3.000 0.000 0.000 1.00 0.00 C', 2),
15
+ ]
16
+
17
+ def test_less_equal_includes_boundary(self):
18
+ for selection, expected in [
19
+ ('serial <= 2', [0, 1]),
20
+ ('not serial <= 2', [2]),
21
+ ('x <= 1.5', [0, 1]),
22
+ ('not x <= 1.5', [2]),
23
+ ('serial < 2', [0]),
24
+ ('not serial < 2', [1, 2]),
25
+ ]:
26
+ with self.subTest(selection=selection):
27
+ self.assertEqual(self.pdb.get_atom_indices(selection), expected)
28
+
29
+
30
+ class RingBondGenerationTest(unittest.TestCase):
31
+ def test_triangle_on_either_side_of_new_bond(self):
32
+ ring = SimpleNamespace(bonds=[(1, 2), (1, 3), (2, 3)])
33
+ chain = SimpleNamespace(bonds=[(1, 2), (2, 3)])
34
+ for offset in (10, 20):
35
+ with self.subTest(offset=offset, ring_side='own'):
36
+ pairs, dihedrals = gml.SectionMol._generate_14(ring, chain, 1, 1, offset)
37
+ self.assertCountEqual(pairs, [(2, 2+offset), (3, 2+offset), (1, 3+offset)])
38
+ expected = [(2, 1, 1+offset, 2+offset), (3, 1, 1+offset, 2+offset),
39
+ (1, 1+offset, 2+offset, 3+offset)]
40
+ self.assertCountEqual(dihedrals, [d for d in expected if d[0] != d[-1]])
41
+ with self.subTest(offset=offset, ring_side='other'):
42
+ pairs, dihedrals = gml.SectionMol._generate_14(chain, ring, 1, 1, offset)
43
+ expected = [(2, 2+offset), (2, 3+offset), (1+offset, 3)]
44
+ self.assertCountEqual(pairs, [p for p in expected if p[0] != p[-1]])
45
+ expected = [(2, 1, 1+offset, 2+offset), (2, 1, 1+offset, 3+offset),
46
+ (3, 2, 1, 1+offset)]
47
+ self.assertCountEqual(dihedrals, [d for d in expected if d[0] != d[-1]])
File without changes
File without changes