gromologist 0.322__tar.gz → 0.332__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.322 → gromologist-0.332}/PKG-INFO +1 -1
  2. {gromologist-0.322 → gromologist-0.332}/README.md +29 -4
  3. {gromologist-0.322 → gromologist-0.332}/gromologist/Crooks.py +14 -18
  4. {gromologist-0.322 → gromologist-0.332}/gromologist/Entries.py +74 -25
  5. {gromologist-0.322 → gromologist-0.332}/gromologist/Gmx.py +451 -62
  6. {gromologist-0.322 → gromologist-0.332}/gromologist/Parser.py +42 -12
  7. {gromologist-0.322 → gromologist-0.332}/gromologist/Pdb.py +453 -96
  8. {gromologist-0.322 → gromologist-0.332}/gromologist/Section.py +306 -107
  9. {gromologist-0.322 → gromologist-0.332}/gromologist/Subsection.py +110 -17
  10. {gromologist-0.322 → gromologist-0.332}/gromologist/Topology.py +325 -113
  11. {gromologist-0.322 → gromologist-0.332}/gromologist/Utils.py +556 -5
  12. gromologist-0.332/gromologist/gromologist_gui.py +866 -0
  13. {gromologist-0.322 → gromologist-0.332}/gromologist.egg-info/PKG-INFO +1 -1
  14. {gromologist-0.322 → gromologist-0.332}/gromologist.egg-info/SOURCES.txt +5 -1
  15. gromologist-0.332/gromologist.egg-info/entry_points.txt +8 -0
  16. gromologist-0.332/setup.py +23 -0
  17. {gromologist-0.322 → gromologist-0.332}/tests/test_pdb.py +47 -2
  18. gromologist-0.332/tests/test_pdb_extended.py +104 -0
  19. gromologist-0.332/tests/test_top_section_entry.py +201 -0
  20. gromologist-0.322/setup.py +0 -11
  21. {gromologist-0.322 → gromologist-0.332}/LICENSE +0 -0
  22. {gromologist-0.322 → gromologist-0.332}/gromologist/DihOpt.py +0 -0
  23. {gromologist-0.322 → gromologist-0.332}/gromologist/Mutant.py +0 -0
  24. {gromologist-0.322 → gromologist-0.332}/gromologist/ThDiff.py +0 -0
  25. {gromologist-0.322 → gromologist-0.332}/gromologist/__init__.py +0 -0
  26. {gromologist-0.322 → gromologist-0.332}/gromologist.egg-info/dependency_links.txt +0 -0
  27. {gromologist-0.322 → gromologist-0.332}/gromologist.egg-info/not-zip-safe +0 -0
  28. {gromologist-0.322 → gromologist-0.332}/gromologist.egg-info/requires.txt +0 -0
  29. {gromologist-0.322 → gromologist-0.332}/gromologist.egg-info/top_level.txt +0 -0
  30. {gromologist-0.322 → gromologist-0.332}/setup.cfg +0 -0
  31. {gromologist-0.322 → gromologist-0.332}/tests/test_top.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: gromologist
3
- Version: 0.322
3
+ Version: 0.332
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
+ * [Adding Go terms](#adding-go-terms)
32
33
  * [Adding H-mass repartitioning](#adding-hmass-repartitioning)
33
34
  * [Explicitly listing parameters in topology & finding missing parameters](#explicitly-listing-parameters-in-topology---finding-missing-parameters)
34
35
  * [Explicitly listing identical molecules in topology](#explicitly-listing-identical-molecules-in-topology)
@@ -69,8 +70,7 @@ basic scientific libraries such as `numpy` or `sklearn`.
69
70
  ## How to cite
70
71
  <a name="how-to-cite"/>
71
72
 
72
- If you found Gromologist useful, cite our preprint! [Gromologist: a Gromacs-Oriented Utility Library for Structure and Topology Manipulation
73
- ](https://chemrxiv.org/engage/chemrxiv/article-details/628bf40843d1f07e2e36c6e1)
73
+ If you found Gromologist useful, cite our paper, out in SoftwareX! [Gromologist: A GROMACS-oriented utility library for structure and topology manipulation](https://www.sciencedirect.com/science/article/pii/S2352711025000858)
74
74
 
75
75
  ## Usage
76
76
  <a name="usage"/>
@@ -199,6 +199,18 @@ Other 1
199
199
  By analogy, the `.list_bonds()` method can be used to `list_angles`, `list_dihedrals`
200
200
  and `list_impropers`.
201
201
 
202
+ One can select from defined molecules in several ways, using attributes that narrow down
203
+ the selection of molecules available:
204
+
205
+ ```
206
+ # index among all molecules defined through [ moleculetype ]
207
+ >>> protein = t.molecules[0]
208
+ # index among all molecules declared in the [ system ] section, i.e. ignoring ones that are not used:
209
+ >>> protein = t.active_molecules[0]
210
+ # index among all molecules that have defined alchemical states A and B:
211
+ >>> protein = t.alchemical_molecules[0]
212
+ ```
213
+
202
214
  For structure files, several functions facilitate e.g. the identification of missing
203
215
  atoms (useful when parsing files freshly downloaded from PDB):
204
216
 
@@ -615,6 +627,19 @@ To generate an NBFIX (custom combination rule) entry, use the following snippet:
615
627
  This will introduce a term modifying the CT-HA Lennard-Jones interaction, increasing the default
616
628
  (Lorenz-Berthelot) sigma by 0.01 nm, and decreasing the default epsilon by 0.1 kJ/mol.
617
629
 
630
+ ##### Adding Go terms
631
+ <a name="adding-go-terms"/>
632
+
633
+ To add custom intramolecular Gō terms to Martini 3 topologies, use:
634
+
635
+ ```
636
+ >>> bead_pairs = np.loadtxt('precomputed_bead_pairs.dat').astype(int)
637
+ >>> t.molecules[0].add_go_terms(bead_pairs, bond_strength = 9.414)
638
+ ```
639
+
640
+ This creates Gō terms consistent with the Martini strategy (NBFIXes between bead-centered virtual sites).
641
+ In order to merge multiple molecules into one, follow [the tutorial](https://gitlab.com/KomBioMol/gromologist/-/wikis/creating-custom-Go-terms-for-Martini3).
642
+
618
643
  ##### Adding H-mass repartitioning
619
644
  <a name="adding-hmass-repartitioning"/>
620
645
 
@@ -629,7 +654,7 @@ it is more convenient to apply it to an existing topology:
629
654
  >>> t.hydrogen_mass_repartitioning()
630
655
  ```
631
656
 
632
- By default, the masses of hydrogens are set to 4.032 Da; this can be controlled with the `hmass` keyword.
657
+ By default, the masses of hydrogens are set to 3.032 Da; this can be controlled with the `hmass` keyword.
633
658
  The method skips all molecules with up to 5 atoms (intended not to affect water molecules).
634
659
 
635
660
 
@@ -722,7 +747,7 @@ into an .rtp entry (that can be used by `gmx pdb2gmx`), you can load the topolog
722
747
 
723
748
  ```
724
749
  itp = Top('new_residue.itp')
725
- itp.molecules[0].tp_rtp('new_entry.rtp')
750
+ itp.molecules[0].to_rtp('new_entry.rtp')
726
751
  ```
727
752
 
728
753
  Then copy the entry to the .rtp database of your chosen force field. Do not forget to update your
@@ -30,16 +30,7 @@ import gromologist as gml
30
30
  import os
31
31
  from math import ceil
32
32
  from shutil import copy
33
-
34
33
  import numpy as np
35
- try:
36
- from scipy.integrate import simps
37
- from scipy.optimize import fmin
38
- from sklearn.neighbors import KernelDensity
39
- from sklearn.model_selection import GridSearchCV
40
- from sklearn.model_selection import LeaveOneOut
41
- except ImportError:
42
- pass
43
34
 
44
35
 
45
36
  class CrooksPool:
@@ -121,7 +112,7 @@ class CrooksPool:
121
112
  :return: None
122
113
  """
123
114
  exec = ProcessPoolExecutor
124
- ncpu = self.ncpus()
115
+ ncpu = self.ncpu
125
116
  self.drop_frames()
126
117
  if self.mutate:
127
118
  print('mutating structures...'.format())
@@ -214,7 +205,8 @@ class CrooksPool:
214
205
  :param grid: np.array, the corresponding X values
215
206
  :return: np.array of shape [1,1]
216
207
  """
217
- return simps(np.sqrt(d0.reshape(-1) * d1.reshape(-1)), grid.reshape(-1)).reshape(-1, 1)
208
+ from scipy.integrate import simpson
209
+ return simpson(np.sqrt(d0.reshape(-1) * d1.reshape(-1)), grid.reshape(-1)).reshape(-1, 1)
218
210
 
219
211
  def analyze_convergence(self, w0, w1, grid):
220
212
  """
@@ -309,6 +301,9 @@ class CrooksPool:
309
301
  :param bandwidth: if None, optimize; if a float, use this value
310
302
  :return: np.array, the estimated density
311
303
  """
304
+ from sklearn.neighbors import KernelDensity
305
+ from sklearn.model_selection import GridSearchCV
306
+ from sklearn.model_selection import LeaveOneOut
312
307
  if bandwidth is None:
313
308
  bandwidths = 10 ** np.linspace([-1], [1], 20).reshape(-1)
314
309
  grid = GridSearchCV(estimator=KernelDensity(kernel='gaussian'), param_grid={'bandwidth': bandwidths},
@@ -445,9 +440,8 @@ class CrooksPool:
445
440
  """
446
441
  if runtype == 'mini' and not self.mini:
447
442
  return
448
- ncpus = self.ncpus()
449
- if len(self.workers) % ncpus != 0:
450
- raise RuntimeError("Number of simulations should be divisible by the number of available CPUs, but {} and {} were specified")
443
+ # if len(self.workers) % self.ncpu != 0:
444
+ # raise RuntimeError("Number of simulations should be divisible by the number of available CPUs, but {} and {} were specified")
451
445
  tpr = runtype if runtype in ['mini', 'eq'] else 'dyn'
452
446
  if self.plumed and runtype == 'eq':
453
447
  plu = ' -plumed plumed.dat '
@@ -456,9 +450,9 @@ class CrooksPool:
456
450
  multi = ['run{}_l{}'.format(w.id, w.initlambda) for w in self.workers]
457
451
  gmx_mpi = gml.find_gmx_dir(mpi=True)[1]
458
452
  if not all(['{}.gro'.format(tpr) in os.listdir('run{}_l{}'.format(w.id, w.initlambda)) for w in self.workers]):
459
- for multi_batch in [multi[ncpus*i : ncpus*(i+1)] for i in range(len(multi) // ncpus)]:
460
- print(gml.gmx_command(f'mpiexec {gmx_mpi}', 'mdrun', deffnm=tpr, v=plu, cpi=True,
461
- multidir=' '.join(multi_batch), answer=True))
453
+ for multi_batch in [multi[self.ncpu*i : self.ncpu*(i+1)] for i in range(np.ceil(len(multi) / self.ncpu).astype(int))]:
454
+ print(gml.gmx_command(f'mpiexec -n {len(multi_batch)} {gmx_mpi}', 'mdrun', deffnm=tpr, v=plu,
455
+ cpi=True, multidir=' '.join(multi_batch), answer=True))
462
456
 
463
457
  @staticmethod
464
458
  def ncpus():
@@ -578,6 +572,7 @@ class Crooks:
578
572
  job was restarted), and integrates dH/dl to calculate work
579
573
  :return: None
580
574
  """
575
+ from scipy.integrate import simpson
581
576
  dhdl = np.loadtxt('run{n}_l{l}/dyn.xvg'.format(n=self.id, l=self.initlambda), comments=['#', '@'])
582
577
  if not int(dhdl[-1, 0]) == int(self.master.sim_length):
583
578
  raise RuntimeError("In file run{}_l{}/dyn.xvg last line reads {}, less than the requested total "
@@ -585,10 +580,11 @@ class Crooks:
585
580
  dhdl_dict = {i: j for i, j in dhdl}
586
581
  dhdl = np.array([dhdl_dict[i] for i in sorted(list(dhdl_dict.keys()))]) # avoid duplicates in case of restarts
587
582
  endlambda = 1 if self.initlambda == 0 else 0
588
- self.work = simps(dhdl, np.linspace([self.initlambda], [endlambda], len(dhdl)).reshape(-1))
583
+ self.work = simpson(dhdl, np.linspace([self.initlambda], [endlambda], len(dhdl)).reshape(-1))
589
584
 
590
585
 
591
586
  def bar(forward_works, reverse_works, temperature):
587
+ from scipy.optimize import fmin
592
588
  kb = 0.00831447215 # in kJ units
593
589
  forward_works = np.array(forward_works)
594
590
  reverse_works = np.array(reverse_works)
@@ -46,6 +46,9 @@ class Entry:
46
46
  """
47
47
  def __init__(self, content, subsection):
48
48
  self.subsection = subsection
49
+ # Nested #ifdef/#ifndef context for this entry (outer -> inner)
50
+ # [{'keyword': str, 'negated': bool, 'else_branch': bool}, ...]
51
+ self.condition_frames = []
49
52
  semicol_index = content.find(';')
50
53
  if semicol_index >= 0:
51
54
  self.content = content[:semicol_index].strip().split()
@@ -139,6 +142,7 @@ class EntryBonded(Entry):
139
142
  ('bonds', '21'): (float, float), # for GENESIS
140
143
  ('pairs_nb', '1'): (float, float, float, float),
141
144
  ('pairs', '2'): (float, float, float, float, float),
145
+ ('pairs', '1'): (float, float),
142
146
  ('angles', '1'): (float, float),
143
147
  ('angles', '2'): (float, float),
144
148
  ('angles', '21'): (float, float, float), # for GENESIS
@@ -160,8 +164,8 @@ class EntryBonded(Entry):
160
164
  ('dihedral_restraints', '1'): (float, float, float),
161
165
  ('constraints', '2'): (float,),
162
166
  ('constraints', '1'): (float,),
163
- ('virtual_sitesn', '1'): (int,),
164
- ('virtual_sitesn', '2'): (int, int, int, int),
167
+ #('virtual_sitesn', '1'): (int,),
168
+ #('virtual_sitesn', '2'): (int, int, int, int), # any number of params; parameters are atom numbers
165
169
  ('virtual_sites2', '1'): (float,),
166
170
  ('virtual_sites3', '1'): (float, float),
167
171
  ('virtual_sites3', '2'): (float, float),
@@ -172,11 +176,17 @@ class EntryBonded(Entry):
172
176
  def __init__(self, content: str, subsection: "gml.Subsection"):
173
177
  super().__init__(content, subsection)
174
178
  if subsection.header == 'exclusions':
179
+ self.atoms_per_entry = len(self.content)
180
+ self.interaction_type = ''
181
+ self.atom_numbers = tuple([int(x) for x in self.content[:self.atoms_per_entry]])
182
+ elif subsection.header == 'virtual_sitesn':
175
183
  self.atoms_per_entry = len(self.content) - 1
184
+ self.interaction_type = self.content[1]
185
+ self.atom_numbers = tuple([int(self.content[0])] + [int(x) for x in self.content[2:]])
176
186
  else:
177
187
  self.atoms_per_entry = type(self.subsection).n_atoms[self.subsection.header]
178
- self.atom_numbers = tuple([int(x) for x in self.content[:self.atoms_per_entry]])
179
- self.interaction_type = self.content[self.atoms_per_entry]
188
+ self.interaction_type = self.content[self.atoms_per_entry]
189
+ self.atom_numbers = tuple([int(x) for x in self.content[:self.atoms_per_entry]])
180
190
  try:
181
191
  self.params_per_entry = len(EntryBonded.fstr_suff[(subsection.header, str(self.interaction_type))])
182
192
  except KeyError:
@@ -228,7 +238,7 @@ class EntryBonded(Entry):
228
238
  """
229
239
  if self.params_state_a and isinstance(self.params_state_a[0], str):
230
240
  try:
231
- self.params_state_a = self.subsection.section.top.defines[self.params_state_a[0]]
241
+ self.params_state_a = self.subsection.section.top.defines[self.params_state_a[0]][:]
232
242
  self.fstr_mod = [self.infer_type(x) for x in self.params_state_a]
233
243
  except:
234
244
  pass
@@ -284,6 +294,9 @@ class EntryBonded(Entry):
284
294
  raise RuntimeError("Cannot process: ", excess_params)
285
295
 
286
296
  def __str__(self) -> str:
297
+ if self.subsection.header == 'virtual_sitesn':
298
+ fields = [str(self.atom_numbers[0])] + [self.interaction_type] + [str(x) for x in self.atom_numbers[1:]]
299
+ return ' '.join(f"{i:8s}" for i in fields) + ' ' + self.comment + '\n'
287
300
  fmt_suff = ""
288
301
  for params in [self.params_state_a, self.params_state_b]:
289
302
  for parm in params:
@@ -309,15 +322,22 @@ class EntryParam(Entry):
309
322
  """
310
323
  def __init__(self, content: str, subsection: "gml.Subsection", processed: bool = False, perres=False):
311
324
  super().__init__(content, subsection)
325
+ # Preserve keyword-like parameters (e.g. #define symbols) instead of forcing float conversion
326
+ def _coerce(token):
327
+ try:
328
+ return float(token)
329
+ except ValueError:
330
+ return token
331
+
312
332
  self.atoms_per_entry = type(self.subsection).n_atoms[self.subsection.header]
313
333
  self.types = tuple(self.content[:self.atoms_per_entry])
314
334
  if self.subsection.header == 'cmaptypes' and processed:
315
335
  if perres:
316
336
  self.modifiers = self.content[self.atoms_per_entry + 1:self.atoms_per_entry + 4]
317
- self.params = [float(x) for x in self.content[self.atoms_per_entry + 4:]]
337
+ self.params = [_coerce(x) for x in self.content[self.atoms_per_entry + 4:]]
318
338
  else:
319
339
  self.modifiers = self.content[self.atoms_per_entry + 1:self.atoms_per_entry + 3]
320
- self.params = [float(x) for x in self.content[self.atoms_per_entry + 3:]]
340
+ self.params = [_coerce(x) for x in self.content[self.atoms_per_entry + 3:]]
321
341
  self.interaction_type = self.content[self.atoms_per_entry]
322
342
  elif self.subsection.header == 'cmaptypes' and not processed:
323
343
  self.modifiers = []
@@ -330,24 +350,27 @@ class EntryParam(Entry):
330
350
  elif self.subsection.header == 'atomtypes':
331
351
  if self.content[4] in 'ASVD':
332
352
  self.modifiers = self.content[self.atoms_per_entry:self.atoms_per_entry + 4]
333
- self.params = [float(x) for x in self.content[self.atoms_per_entry + 4:]]
353
+ self.params = [_coerce(x) for x in self.content[self.atoms_per_entry + 4:]]
334
354
  elif self.content[3] in 'ASVD':
335
355
  self.modifiers = [''] + self.content[self.atoms_per_entry:self.atoms_per_entry + 3]
336
- self.params = [float(x) for x in self.content[self.atoms_per_entry + 3:]]
356
+ self.params = [_coerce(x) for x in self.content[self.atoms_per_entry + 3:]]
337
357
  else:
338
358
  raise RuntimeError(f"Can't determine format of atomtype {self.content}")
339
359
  self.interaction_type = ''
340
360
  else:
341
- self.params = [float(x) for x in self.content[self.atoms_per_entry + 1:]]
361
+ self.params = [_coerce(x) for x in self.content[self.atoms_per_entry + 1:]]
342
362
  self.modifiers = []
343
363
  self.interaction_type = self.content[self.atoms_per_entry]
344
364
  if self.subsection.header == 'dihedraltypes':
345
365
  if any([self.infer_type(x) == float for x in self.types]):
346
366
  self.types = self.content[:2]
347
367
  self.interaction_type = self.content[2]
348
- self.params = [float(x) for x in self.content[3:]]
368
+ self.params = [_coerce(x) for x in self.content[3:]]
349
369
  if self.subsection.header == 'dihedraltypes' and self.interaction_type in ('9', '4', '1'):
350
- self.params[-1] = int(self.params[-1])
370
+ try:
371
+ self.params[-1] = int(self.params[-1])
372
+ except (ValueError, TypeError):
373
+ pass
351
374
  self.identifier = self.subsection.header + '-' + '-'.join(self.types) + '-' + self.interaction_type
352
375
 
353
376
  def format(self) -> str:
@@ -366,6 +389,7 @@ class EntryParam(Entry):
366
389
  ('dihedraltypes', '1'): "{:>8s} {:>8s} {:>8s} {:>8s} {:>6s} {:>13.6f} {:>13.6f} {:>6d} ",
367
390
  ('atomtypes', ''): "{:>6s} {} {:>6s} {:>13s} {:>9s} {:>3s} {:>16.12f} {:>9.5f} ",
368
391
  ('pairtypes', '1'): "{:>8s} {:>8s} {:>3s} {:>16.12f} {:>16.12f} ",
392
+ ('constrainttypes', '2'): "{:>8s} {:>8s} {:>3s} {:>16.12f} ",
369
393
  ('nonbond_params', '1'): "{:>8s} {:>8s} {:>3s} {:>20.16f} {:>20.16f} ",
370
394
  ('implicit_genborn_params', ''): " {:8s} {:8.4f} {:8.4f} {:8.4f} {:8.4f} {:8.4f} "}
371
395
  if (self.subsection.header, self.interaction_type) in fmt.keys():
@@ -424,6 +448,10 @@ class EntryParam(Entry):
424
448
  last = last + '\\\n' + \
425
449
  (((npar-10*int(npar/10)) * "{} ")[:-1]).format(*self.params[10*int(npar/10):]) + '\n'
426
450
  return first + last + '\n'
451
+ # If parameters contain string keywords (e.g. #define tokens), fall back to a simple join
452
+ if any(isinstance(p, str) for p in self.params):
453
+ fields = [*self.types, self.interaction_type, *self.modifiers, *[str(p) for p in self.params]]
454
+ return ' '.join(fields) + ' ' + self.comment + '\n'
427
455
  elif self.format():
428
456
  try:
429
457
  return self.format().format(*self.types, self.interaction_type, *self.modifiers, *self.params) +\
@@ -445,19 +473,23 @@ class EntryAtom(Entry):
445
473
  self.num, self.type, self.resid, self.resname, self.atomname, _, self.charge, self.mass = self.content[:8]
446
474
  except ValueError:
447
475
  self.num, self.type, self.resid, self.resname, self.atomname, _, self.charge = self.content[:7]
448
- atomtypes_scts = self.subsection.section.top.parameters.get_subsections('atomtypes') # at this stage some sections can be not merged yet
449
- matching = [atype for atomtypes in atomtypes_scts for atype in atomtypes if isinstance(atype, EntryParam) and atype.types[0] == self.type]
450
476
  try:
451
- self.mass = float(matching[0].modifiers[1])
452
- except IndexError:
453
- self.mass = 0
477
+ atomtypes_scts = self.subsection.section.top.parameters.get_subsections('atomtypes') # at this stage some sections can be not merged yet
478
+ matching = [atype for atomtypes in atomtypes_scts for atype in atomtypes if isinstance(atype, EntryParam) and atype.types[0] == self.type]
479
+ try:
480
+ self.mass = float(matching[0].modifiers[1])
481
+ except IndexError:
482
+ self.mass = 0
483
+ except:
484
+ self.mass = None
454
485
  self.num, self.resid = int(self.num), int(self.resid)
455
- self.charge, self.mass = float(self.charge), float(self.mass)
486
+ self.charge = float(self.charge)
487
+ self.mass = float(self.mass) if self.mass is not None else None
456
488
  if len(self.content) == 11:
457
489
  self.type_b, self.charge_b, self.mass_b = self.content[8], float(self.content[9]), float(self.content[10])
458
490
  else:
459
491
  self.type_b, self.charge_b, self.mass_b = None, None, None
460
- self.fstring = "{:>6d} {:>11s} {:>7d}{:>7s}{:>7s}{:>7d}"
492
+ self.fstring = "{:>6d} {:>11s} {:>7d} {:>7s} {:>7s} {:>7d} "
461
493
 
462
494
  def __eq__(self, other) -> bool:
463
495
  if not isinstance(other, gml.EntryAtom):
@@ -500,12 +532,12 @@ class EntryAtom(Entry):
500
532
  :return: bool, whether the atom is a hydrogen
501
533
  """
502
534
  if refstate == 'A':
503
- if self.type.startswith('opls'):
535
+ if self.type.startswith('opls') or self.type[0].upper() in 'XY':
504
536
  typecheck = self.atomname[0].upper() == 'H'
505
537
  else:
506
538
  typecheck = self.type[0].upper() == 'H'
507
539
  elif refstate == 'B':
508
- if self.type.startswith('opls'):
540
+ if self.type.startswith('opls') or self.type_b[0].upper() in 'XY':
509
541
  self.subsection.section.top.print("WARNING: in OPLS, we're inferring hydrogens for alchemical state B "
510
542
  "from atomname, this might be incorrect")
511
543
  typecheck = self.atomname[0].upper() == 'H'
@@ -553,6 +585,16 @@ class EntryAtom(Entry):
553
585
  """
554
586
  return len(self.bound_atoms)
555
587
 
588
+ def add_alchemical_state(self, type: str, charge: float, mass: float) -> None:
589
+ self.type_b = type
590
+ self.mass_b = mass
591
+ self.charge_b = charge
592
+
593
+ def add_alchemical_state_from_atom(self, atom: "gml.EntryAtom") -> None:
594
+ self.type_b = atom.type
595
+ self.mass_b = atom.mass
596
+ self.charge_b = atom.charge
597
+
556
598
  def _get_atomtype_entry(self):
557
599
  atomtypes = self.subsection.section.top.parameters.get_subsection('atomtypes')
558
600
  try:
@@ -561,13 +603,20 @@ class EntryAtom(Entry):
561
603
  raise RuntimeError(f"Couldn't find non-bonded parameters for atomtype {self.type}")
562
604
 
563
605
  def __str__(self) -> str:
564
- fstring = self.fstring + self.float_fmt(self.charge) + self.float_fmt(self.mass) + ' '
606
+ has_mass = False if self.mass is None else True
607
+ if has_mass:
608
+ fstring = self.fstring + self.float_fmt(self.charge) + self.float_fmt(self.mass) + ' '
609
+ else:
610
+ fstring = self.fstring + self.float_fmt(self.charge) + ' '
565
611
  if self.type_b:
566
612
  alch_fstring = "{:>11s}" + self.float_fmt(self.charge_b) + self.float_fmt(self.mass_b)
567
613
  fstring += alch_fstring
568
614
  return fstring.format(self.num, self.type, self.resid, self.resname, self.atomname, self.num,
569
615
  self.charge, self.mass, self.type_b, self.charge_b, self.mass_b) + self.comment + '\n'
570
616
  else:
571
- return fstring.format(self.num, self.type, self.resid, self.resname, self.atomname, self.num,
572
- self.charge, self.mass) + ' ' + self.comment + '\n'
573
-
617
+ if has_mass:
618
+ return fstring.format(self.num, self.type, self.resid, self.resname, self.atomname, self.num,
619
+ self.charge, self.mass) + ' ' + self.comment + '\n'
620
+ else:
621
+ return fstring.format(self.num, self.type, self.resid, self.resname, self.atomname, self.num,
622
+ self.charge) + ' ' + self.comment + '\n'