HTPolyNet 2.7.0__py3-none-any.whl → 2.9.0__py3-none-any.whl

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.
@@ -15,7 +15,7 @@ logger = logging.getLogger(__name__)
15
15
 
16
16
 
17
17
  class BondTemplate:
18
- def __init__(self, names, resnames, intraresidue, order, bystander_resnames, bystander_atomnames, oneaway_resnames, oneaway_atomnames):
18
+ def __init__(self, names, resnames, intraresidue, order, bystander_resnames, bystander_atomnames, oneaway_resnames, oneaway_atomnames, siblings=None):
19
19
  """Creates a BondTemplate object.
20
20
 
21
21
  Args:
@@ -27,6 +27,10 @@ class BondTemplate:
27
27
  bystander_atomnames (list of two list-like containers of strs): lists of names of atoms in bystander residues (parallel to bystander_resnames)
28
28
  oneaway_resnames (list-like container of strs): names of one-away residues (residues bound one bond away from the new interresidue bond; only relevant for C=C free-radical polymerization)
29
29
  oneaway_atomnames (list-like container of strs): names of atoms in one-away residues
30
+ siblings (list of two lists of (str, str) tuples): for each atom in names, the
31
+ (atomName, partner resName) of every other atom in its residue, within two
32
+ intraresidue bonds, that is already bonded to another residue; defaults to
33
+ none on either side. See TopoCoord.get_siblings.
30
34
  """
31
35
  self.names = names
32
36
  self.resnames = resnames
@@ -36,6 +40,7 @@ class BondTemplate:
36
40
  self.oneaway_resnames = oneaway_resnames
37
41
  self.oneaway_atomnames = oneaway_atomnames
38
42
  self.order = order
43
+ self.siblings = [sorted(tuple(t) for t in x) for x in siblings] if siblings else [[], []]
39
44
 
40
45
  def reverse(self):
41
46
  """Reverses the order of all parallel lists in a BondTemplate object."""
@@ -45,9 +50,10 @@ class BondTemplate:
45
50
  self.bystander_atomnames = self.bystander_atomnames[::-1]
46
51
  self.oneaway_resnames = self.oneaway_resnames[::-1]
47
52
  self.oneaway_atomnames = self.oneaway_atomnames[::-1]
53
+ self.siblings = self.siblings[::-1]
48
54
 
49
55
  def __str__(self):
50
- return f'BondTemplate {self.names} resnames {self.resnames} intraresidue? {self.intraresidue} order {self.order} bystander-resnames {self.bystander_resnames} bystander-atomnames {self.bystander_atomnames} oneaway-resnames {self.oneaway_resnames} oneaway-atomnames {self.oneaway_atomnames}'
56
+ return f'BondTemplate {self.names} resnames {self.resnames} intraresidue? {self.intraresidue} order {self.order} bystander-resnames {self.bystander_resnames} bystander-atomnames {self.bystander_atomnames} oneaway-resnames {self.oneaway_resnames} oneaway-atomnames {self.oneaway_atomnames} siblings {self.siblings}'
51
57
 
52
58
  def __eq__(self,other):
53
59
  check = self.names == other.names
@@ -57,6 +63,7 @@ class BondTemplate:
57
63
  check = check and self.bystander_atomnames == other.bystander_atomnames
58
64
  check = check and self.oneaway_resnames == other.oneaway_resnames
59
65
  check = check and self.oneaway_atomnames == other.oneaway_atomnames
66
+ check = check and self.siblings == other.siblings
60
67
  return check
61
68
 
62
69
  def is_reverse_of(self,other):
@@ -73,13 +80,15 @@ class BondTemplate:
73
80
  return self == rb
74
81
 
75
82
  def bystander_count(self):
76
- """Total number of bystander (resname, atomname) pairs across both sides.
83
+ """Total number of bystander (resname, atomname) pairs and siblings across both sides.
77
84
 
78
- Used by find_template's best-match selection: more bystanders = more
85
+ Used by find_template's best-match selection: more context = more
79
86
  specific template, which should win when multiple templates can match
80
- an instance under subset semantics.
87
+ an instance under subset semantics. Siblings count here so that a
88
+ triazine template with two ring carbons already bonded beats the one
89
+ with one, which beats the bare one.
81
90
  """
82
- return sum(len(s) for s in self.bystander_resnames)
91
+ return sum(len(s) for s in self.bystander_resnames) + sum(len(s) for s in self.siblings)
83
92
 
84
93
  def matches(self, other):
85
94
  """Return True if `self` (a parameterization-stage template) is a
@@ -111,6 +120,13 @@ class BondTemplate:
111
120
  force the cure reactant to mirror every inter-residue partner
112
121
  the instance carries, which forecloses the small-fragment idiom.
113
122
 
123
+ Subset semantics on siblings, for the same reason. A sibling is
124
+ another atom of a bonding residue, close enough to the bonding atom
125
+ that the template overwrites its charge, that is already bonded to
126
+ another residue. A template declaring a sibling describes that atom
127
+ as reacted, so it must not be used where the atom has not; a template
128
+ declaring none has always been used regardless, and still is.
129
+
114
130
  Args:
115
131
  other (BondTemplate): the instance bond to test for compatibility
116
132
 
@@ -133,6 +149,12 @@ class BondTemplate:
133
149
  remaining.remove(tp)
134
150
  else:
135
151
  return False
152
+ remaining = list(other.siblings[side])
153
+ for sib in self.siblings[side]:
154
+ if sib in remaining:
155
+ remaining.remove(sib)
156
+ else:
157
+ return False
136
158
  return True
137
159
 
138
160
  def matches_reverse_of(self, other):
@@ -1,16 +1,41 @@
1
1
  """Manages reading and parsing of YAML configuration files.
2
2
 
3
3
  Author: Cameron F. Abrams <cfa22@drexel.edu>
4
+
5
+ Configurations are validated against ``htpolynet/schema/base.yaml`` by
6
+ ycleptic, which also fills in every documented default. Before that, this
7
+ module read the file and ``.get()``-ed the keys it recognized, so an
8
+ unrecognized section or a misspelled key was discarded in silence -- a
9
+ ``desired_converson`` typo produced a default-value build and no message.
10
+
11
+ Keys whose *presence* changes behavior are declared ``required: false`` in the
12
+ schema so ycleptic leaves them absent rather than filling them in; see the
13
+ comments on ``densification.initial_boxsize``, ``reactive_atoms`` and
14
+ ``rename_atoms`` there.
4
15
  """
5
16
  import json
6
17
  import logging
7
18
  import os
8
19
 
20
+ from importlib.resources import as_file, files
21
+
9
22
  import yaml
10
23
 
24
+ from ycleptic.errors import YclepticError
25
+ from ycleptic.yclept import Yclept
26
+
11
27
  logger = logging.getLogger(__name__)
12
28
 
13
29
 
30
+ def schema_path():
31
+ """Context manager yielding a real path to the packaged base config.
32
+
33
+ Returns:
34
+ contextlib.AbstractContextManager: yields a pathlib.Path to base.yaml
35
+ """
36
+ return as_file(files('htpolynet').joinpath('schema/base.yaml'))
37
+
38
+
14
39
  class Configuration:
15
40
  """Pure data container for a build configuration file.
16
41
 
@@ -54,16 +79,44 @@ class Configuration:
54
79
  inst = cls()
55
80
  inst.cfgfile = filename
56
81
  if ext == '.json':
82
+ # ycleptic reads YAML; round-trip JSON through a temporary file so
83
+ # both formats get the same validation rather than only one
57
84
  with open(filename, 'r') as f:
58
- inst.basedict = json.load(f)
85
+ raw = json.load(f)
86
+ inst.basedict = inst._validate(raw)
59
87
  elif ext in ('.yaml', '.yml'):
60
88
  with open(filename, 'r') as f:
61
- inst.basedict = yaml.safe_load(f)
89
+ raw = yaml.safe_load(f)
90
+ inst.basedict = inst._validate(raw)
62
91
  else:
63
92
  raise Exception(f'Unknown config file extension {ext}')
64
93
  inst._parse()
65
94
  return inst
66
95
 
96
+ def _validate(self, raw):
97
+ """Validates a raw config against the packaged schema and fills defaults.
98
+
99
+ Args:
100
+ raw (dict): the configuration as read from disk
101
+
102
+ Raises:
103
+ Exception: with ycleptic's message, if the configuration is invalid
104
+
105
+ Returns:
106
+ dict: the validated configuration, with defaults filled in
107
+ """
108
+ import tempfile
109
+ with schema_path() as base:
110
+ with tempfile.TemporaryDirectory() as td:
111
+ userfile = os.path.join(td, 'user.yaml')
112
+ with open(userfile, 'w') as f:
113
+ yaml.dump(raw, f, default_flow_style=False, sort_keys=False)
114
+ try:
115
+ y = Yclept(basefile=str(base), userfile=userfile)
116
+ except YclepticError as e:
117
+ raise Exception(f'{self.cfgfile}: {e}') from None
118
+ return y['user']
119
+
67
120
  def _parse(self):
68
121
  """Populates named attributes from self.basedict."""
69
122
  self.title = self.basedict.get('Title', 'No title provided')
@@ -506,7 +506,7 @@ class Molecule:
506
506
  # logger.debug(f'{self.name} oneaways {oneaway_resids} {oneaway_resnames} {oneaway_atomidx} {oneaway_atomnames}')
507
507
  self.reaction_bonds.append(ReactionBond(atom_idx, in_product_resids, order, bystander_resids, bystander_atomidx, oneaway_resids, oneaway_atomidx))
508
508
  intraresidue = in_product_resids[0] == in_product_resids[1]
509
- self.bond_templates.append(BondTemplate(atom_names, in_product_resnames, intraresidue, order, bystander_resnames, bystander_atomnames, oneaway_resnames, oneaway_atomnames))
509
+ self.bond_templates.append(BondTemplate(atom_names, in_product_resnames, intraresidue, order, bystander_resnames, bystander_atomnames, oneaway_resnames, oneaway_atomnames, siblings=TC.get_siblings(atom_idx)))
510
510
 
511
511
  def idx_mappers(self, otherTC: TopoCoord, other_bond, bystanders, oneaways, uniq_atom_idx: set):
512
512
  """Computes the mapping dictionary from molecule template index to instance index in the other TopoCoord.
htpolynet/core/runtime.py CHANGED
@@ -23,7 +23,7 @@ from ..core.topocoord import TopoCoord
23
23
  from ..core.topology import select_topology_type_option
24
24
  from ..cure.chain import ChainManager
25
25
  from ..cure.curecontroller import CureController, CureState
26
- from ..cure.expandreactions import bondchain_expand_reactions, generate_stereo_reactions, generate_symmetry_reactions
26
+ from ..cure.expandreactions import bondchain_expand_reactions, generate_stereo_reactions, generate_symmetry_reactions, sibling_expand_reactions
27
27
  from ..cure.reaction import Reaction, ReactionList, parse_reaction_list, extract_molecule_reactions, is_reactant, reaction_stage
28
28
  from ..external import software as software
29
29
  from ..external.gromacs import insert_molecules, mdp_modify, mdp_get
@@ -320,6 +320,17 @@ class Runtime:
320
320
  self.molecules[mname]=M
321
321
  logger.debug(f'Generated {mname}')
322
322
 
323
+ new_reactions,new_molecules=sibling_expand_reactions(self.molecules,self.reactions)
324
+ if len(new_molecules)>0:
325
+ ess='' if len(new_molecules)==1 else 's'
326
+ logger.info(f'{len(new_molecules)} molecule{ess} implied by cure bonds next to already-reacted atoms')
327
+ self.reactions.extend(new_reactions)
328
+ for mname,M in new_molecules.items():
329
+ self._generate_molecule(M,force_parameterization=force_parameterization,force_checkin=force_checkin)
330
+ assert M.origin!='unparameterized'
331
+ self.molecules[mname]=M
332
+ logger.debug(f'Generated {mname}')
333
+
323
334
  for M in self.molecules:
324
335
  self.molecules[M].is_reactant=is_reactant(M,self.reactions,stage=reaction_stage.cure)
325
336
 
@@ -443,12 +454,13 @@ class Runtime:
443
454
  cure_finished=cc.is_cured()
444
455
  if not cure_finished:
445
456
  cure_finished=cc.next_iter()
446
- cc.check_iterations_vs_functionality(TC)
457
+ cc.check_iterations_vs_functionality(TC,RL,MD)
447
458
  ''' perform capping if necessary '''
448
459
  my_logger(f'Capping begins',logger.info)
449
460
  pfs.go_to(pfs.Dirs.systems_capping)
450
461
  with profiling.stage('capping'):
451
462
  cc.do_capping(TC,RL,MD,gromacs_dict=gromacs_dict)
463
+ self._report_molecule_charges('after cure')
452
464
  my_logger('Connect-Update-Relax-Equilibrate (CURE) ends',logger.info)
453
465
 
454
466
  @cp.enableCheckpoint
@@ -476,6 +488,7 @@ class Runtime:
476
488
  n_repaired, repair_stats = run_repair(TC, self.molecules, specs, self.reactions)
477
489
  my_logger(f'Postcure repair performed {n_repaired} dismantle operations', logger.info)
478
490
  self._report_repair_conversion(repair_stats)
491
+ self._report_molecule_charges('after repair')
479
492
  # Write out the repaired system so the relaxation can pick it up
480
493
  TC.write_grx_attributes('repaired.grx')
481
494
  TC.write_gro('repaired.gro')
@@ -565,6 +578,7 @@ class Runtime:
565
578
  dropped = TC.Topology.prune_stale_14_pairs()
566
579
  if dropped:
567
580
  logger.info(f'Pruned {dropped} stale [ pairs ] entries left over from cure-induced path shortening')
581
+ self._report_molecule_charges(f'in {result_name}')
568
582
  TC.write_grx_attributes(f'{result_name}.grx')
569
583
  TC.write_gro(f'{result_name}.gro')
570
584
  TC.write_top(f'{result_name}.top')
@@ -572,6 +586,37 @@ class Runtime:
572
586
  self._write_vmd_viz_files(result_name)
573
587
  return {c:os.path.basename(x) for c,x in TC.files.items() if c!='mol2'}
574
588
 
589
+ def _report_molecule_charges(self, when, tol=0.01):
590
+ """Logs whether every covalently bonded molecule in the system is neutral.
591
+
592
+ The system total is zero by construction, so a charged molecule is
593
+ otherwise invisible: a template or repair step that moves charge
594
+ between molecules leaves no other trace. A percolated network is one
595
+ molecule and neutral by construction, so this cannot see charge
596
+ misplaced inside it.
597
+
598
+ Args:
599
+ when (str): stage label for the message, e.g. 'after cure'
600
+ tol (float): largest net charge, in e, treated as neutral, defaults to 0.01
601
+
602
+ Returns:
603
+ list: (number of atoms, net charge) of each molecule carrying more than tol
604
+ """
605
+ molecules = self.TopoCoord.Topology.molecule_charges()
606
+ if not molecules:
607
+ return []
608
+ charged = [m for m in molecules if abs(m[1]) > tol]
609
+ ess = '' if len(molecules) == 1 else 's'
610
+ if not charged:
611
+ logger.info(f'Molecule charges {when}: all {len(molecules)} molecule{ess} neutral to within {tol} e')
612
+ return charged
613
+ worst = max(charged, key=lambda m: abs(m[1]))
614
+ logger.warning(f'Molecule charges {when}: {len(charged)} of {len(molecules)} molecule{ess} carry more than '
615
+ f'{tol} e of net charge; the largest is {worst[1]:+.3f} e on a {worst[0]}-atom molecule. '
616
+ f'The system total is {self.TopoCoord.Topology.total_charge():+.4f} e, so this is charge '
617
+ f'moved between molecules, which parameterization does not intend.')
618
+ return charged
619
+
575
620
  def _write_vmd_viz_files(self, result_name='final'):
576
621
  """Writes a PSF (real bond topology for VMD) and a TCL helper that
577
622
  trims bonds spanning periodic boundaries so VMD doesn't render the
@@ -18,6 +18,7 @@ from ..core import projectfilesystem as pfs
18
18
  from ..core.bondtemplate import BondTemplate, ReactionBond
19
19
  from ..core.coordinates import Coordinates
20
20
  from ..core.topology import Topology
21
+ from ..utils.convergence import series_converged
21
22
  from ..external.gromacs import grompp_and_mdrun,mdp_get, mdp_modify, gmx_energy_trace
22
23
  from ..geometry.matrix4 import Matrix4
23
24
  from ..io.gro import GRX_ATTRIBUTES, GRX_GLOBALLY_UNIQUE, GRX_UNSET_DEFAULTS
@@ -228,7 +229,7 @@ class TopoCoord:
228
229
  anH = sum([int(x.upper().startswith('H')) for x in aneighnames])
229
230
  return anH
230
231
 
231
- def map_from_templates(self, bdf, moldict, overcharge_threshhold=0.1, chain_manager=None):
232
+ def map_from_templates(self, bdf, moldict, overcharge_threshhold=0.1, chain_manager=None, adjust_charges=True):
232
233
  """Updates angles, pairs, dihedrals, atom types, and charges, based on product templates associated with each bond in 'bdf'.
233
234
 
234
235
  Args:
@@ -236,6 +237,12 @@ class TopoCoord:
236
237
  moldict (dict): dictionary of template Molecules keyed by name
237
238
  overcharge_threshhold (float): threshold for charge adjustment, defaults to 0.1
238
239
  chain_manager: optional ChainManager owned by the caller; passed to get_oneaways
240
+ adjust_charges (bool): if True (the default), spread any resulting system overcharge
241
+ uniformly over every mapped atom; a caller that deletes atoms afterwards, and so
242
+ can only settle the charge once those are gone, passes False
243
+
244
+ Returns:
245
+ list: global indices of every system atom that received template attributes
239
246
 
240
247
  Raises:
241
248
  Exception: if nan found in any attribute of any new system angle
@@ -281,7 +288,7 @@ class TopoCoord:
281
288
  bystander_resids, bystander_resnames, bystander_atomidx, bystander_atomnames = self.get_bystanders(bb)
282
289
  oneaway_resids, oneaway_resnames, oneaway_atomidx, oneaway_atomnames = self.get_oneaways(bb, chain_manager=chain_manager)
283
290
  intraresidue = resids[0] == resids[1]
284
- BT = BondTemplate(names, resnames, intraresidue, order, bystander_resnames, bystander_atomnames, oneaway_resnames, oneaway_atomnames)
291
+ BT = BondTemplate(names, resnames, intraresidue, order, bystander_resnames, bystander_atomnames, oneaway_resnames, oneaway_atomnames, siblings=self.get_siblings(bb))
285
292
  RB = ReactionBond(bb, resids, order, bystander_resids, bystander_atomidx, oneaway_resids, oneaway_atomidx)
286
293
  logger.debug(f'apparent bond template {str(BT)}')
287
294
  logger.debug(f'apparent bond instance {str(RB)}')
@@ -292,7 +299,7 @@ class TopoCoord:
292
299
  # copy all bond records matching these two bonds; should be only one!!
293
300
  d = d[((d.ai == temp_i_idx) & (d.aj == temp_j_idx)) |
294
301
  ((d.ai == temp_j_idx) & (d.aj == temp_i_idx))].copy()
295
- assert d.shape[0] == 1, f'Using {T.name} is sent inst-bond {i_idx}-{j_idx} which is claimed to map to {temp_i_idx}-{temp_j_idx}, but no such unique bond is found:\n{T.TopoCoord.Topology.D["bonds"].to_string()}'
302
+ assert d.shape[0] == 1, f'Using {T.name} is sent inst-bond {RB.idx[0]}-{RB.idx[1]} which is claimed to map to {temp_i_idx}-{temp_j_idx}, but no such unique bond is found:\n{T.TopoCoord.Topology.D["bonds"].to_string()}'
296
303
  ''' check passed '''
297
304
  temp_angles, temp_dihedrals, temp_pairs = T.get_angles_dihedrals((temp_i_idx, temp_j_idx))
298
305
  logger.debug(f'Mapping {temp_angles.shape[0]} angles, {temp_dihedrals.shape[0]} dihedrals, and {temp_pairs.shape[0]} pairs from template {T.name}')
@@ -316,7 +323,8 @@ class TopoCoord:
316
323
  assert check,f'Error: bidirectional dicts are incompatible; bug\n{inst2temp}\b{temp2inst}'
317
324
  # logger.debug(f'inst2temp {inst2temp}')
318
325
  # logger.debug(f'temp2inst {temp2inst}')
319
- i_idx, j_idx = bb
326
+ # RB, not bb: a template that matched the reversed bond has reversed RB to line up with it
327
+ i_idx, j_idx = RB.idx
320
328
  _temp_i_idx, _temp_j_idx = inst2temp[i_idx], inst2temp[j_idx]
321
329
  assert temp_i_idx == _temp_i_idx, f'mapping mismatch -- bug'
322
330
  assert temp_j_idx == _temp_j_idx, f'mapping mismatch -- bug'
@@ -441,7 +449,9 @@ class TopoCoord:
441
449
  # return temp_pairs
442
450
  mapped_inst_atoms = list(set(mapped_inst_atoms))
443
451
  logger.debug(f'System overcharge after mapping: {self.Topology.total_charge():.4f}')
444
- self.Topology.adjust_charges(atoms=mapped_inst_atoms, overcharge_threshhold=overcharge_threshhold, msg=f'overcharge magnitude exceeds {overcharge_threshhold}')
452
+ if adjust_charges:
453
+ self.Topology.adjust_charges(atoms=mapped_inst_atoms, overcharge_threshhold=overcharge_threshhold, msg=f'overcharge magnitude exceeds {overcharge_threshhold}')
454
+ return mapped_inst_atoms
445
455
 
446
456
  def enumerate_1_4_pairs(self, at_idx):
447
457
  """Enumerates all 1-4 pair interactions resulting from new bonds in at_idx.
@@ -885,6 +895,52 @@ class TopoCoord:
885
895
  result.append(j)
886
896
  return result
887
897
 
898
+ def get_siblings(self, atom_idx):
899
+ """Identifies already-reacted atoms two bonds from each atom of a bond, inside its own residue.
900
+
901
+ A template splice overwrites the charges of every template atom that
902
+ shares an angle, dihedral or 1-4 pair with the new bond, which reaches
903
+ two bonds into each residue. If one of those atoms has already bonded
904
+ to another residue, a template that shows it unreacted gives it the
905
+ wrong charge: in a triazine, the second and third ring carbons to react
906
+ each reset the carbons that reacted before them. Recording these
907
+ atoms lets find_template prefer a template that shows them reacted.
908
+
909
+ Only the second shell counts. A reacted atom directly bonded to the
910
+ bonding atom is the C=C chain case, which the one-away context already
911
+ describes; counting it too would change which template every chain
912
+ polymerization uses.
913
+
914
+ Args:
915
+ atom_idx: container of two global atom indices specifying a bond
916
+
917
+ Returns:
918
+ list: two sorted lists of (atomName, partner resName) tuples, one per atom in
919
+ atom_idx, excluding the bond itself
920
+ """
921
+ A = self.Coordinates.A
922
+ bl = self.Topology.bondlist
923
+ result = [[], []]
924
+ for x in (0, 1):
925
+ a, b = atom_idx[x], atom_idx[1 - x]
926
+ resnum = A.iloc[a - 1]['resNum']
927
+ seen = {a}
928
+ frontier = [a]
929
+ for _ in range(2):
930
+ reached = []
931
+ for i in frontier:
932
+ for j in bl.partners_of(i):
933
+ if j not in seen and A.iloc[j - 1]['resNum'] == resnum:
934
+ seen.add(j)
935
+ reached.append(j)
936
+ frontier = reached
937
+ for sib in frontier:
938
+ for j in bl.partners_of(sib):
939
+ if j != b and A.iloc[j - 1]['resNum'] != resnum:
940
+ result[x].append((A.iloc[sib - 1]['atomName'], A.iloc[j - 1]['resName']))
941
+ result[x].sort()
942
+ return result
943
+
888
944
  def minimum_distance(self, other, self_excludes=None, other_excludes=None):
889
945
  """Computes the distance of closest approach between self's Coordinates and other's Coordinates.
890
946
 
@@ -1096,6 +1152,17 @@ class TopoCoord:
1096
1152
  # logger.debug(f'write_mol2, other_attributes:\n{other_attributes.to_string()}')
1097
1153
  if 'mol2_bonds' in self.Topology.D:
1098
1154
  self.Coordinates.write_mol2(filename,molname=molname,bondsDF=self.Topology.D['mol2_bonds'],other_attributes=other_attributes)
1155
+ elif 'bonds' in self.Topology.D and not self.Topology.D['bonds'].empty:
1156
+ # A molecule built by copying a parent's topology -- a symmetry
1157
+ # sibling such as GMAS-4 -- is loaded from top+gro and never gets a
1158
+ # mol2 bond table, so this used to write a bondless MOL2 and warn.
1159
+ # Its topology does carry every bond; write those instead. Bond
1160
+ # orders are not in a GROMACS topology, so they are written as single,
1161
+ # the same assumption Topology.add_bonds makes for a new bond.
1162
+ b=self.Topology.D['bonds'][['ai','aj']].reset_index(drop=True)
1163
+ topo_bonds=pd.DataFrame({'bondIdx':range(1,len(b)+1),'ai':b['ai'],'aj':b['aj'],'order':'1'})
1164
+ logger.debug(f'{filename}: no mol2 bond table; writing {len(b)} bonds from the topology as single bonds')
1165
+ self.Coordinates.write_mol2(filename,molname=molname,bondsDF=topo_bonds,other_attributes=other_attributes)
1099
1166
  else:
1100
1167
  self.Coordinates.write_mol2(filename,molname=molname,other_attributes=other_attributes)
1101
1168
 
@@ -1794,21 +1861,106 @@ class TopoCoord:
1794
1861
  logger.info(f'Running Gromacs: {msg}')
1795
1862
  self.grompp_and_mdrun(out=f'{deffnm}-{ens}',mdp=new_mdp,quiet=False,**gromacs_dict)
1796
1863
  edr_list=[f'{deffnm}-{ens}']
1864
+ density=None
1797
1865
  if ens=='npt':
1798
- box=self.Coordinates.box.diagonal()
1799
- logger.info(f'Current box side lengths: {box[0]:.3f} nm x {box[1]:.3f} nm x {box[2]:.3f} nm')
1800
- gmx_energy_trace(f'{deffnm}-{ens}',['Density'],report_averages=True,**gromacs_dict)
1866
+ self._log_box()
1867
+ density=self._density_series(f'{deffnm}-{ens}',gromacs_dict)
1801
1868
  for rep in range(repeat):
1802
1869
  logger.info(f'Repeat {rep+1} out of {repeat}')
1803
1870
  this_deffnm=f'{deffnm}-repeat-{rep+1}-{ens}'
1804
1871
  self.grompp_and_mdrun(out=this_deffnm,mdp=new_mdp,quiet=False,**gromacs_dict)
1805
1872
  edr_list.append(this_deffnm)
1806
1873
  if ens=='npt':
1807
- box=self.Coordinates.box.diagonal()
1808
- logger.info(f'Current box side lengths: {box[0]:.3f} nm x {box[1]:.3f} nm x {box[2]:.3f} nm')
1809
- gmx_energy_trace(this_deffnm,['Density'],report_averages=True,**gromacs_dict)
1874
+ self._log_box()
1875
+ density=self._density_series(this_deffnm,gromacs_dict)
1876
+ converge=edict.get('converge',{}) or {}
1877
+ if converge and ens=='npt':
1878
+ edr_list+=self._converge_density(deffnm,new_mdp,converge,density,gromacs_dict)
1879
+ elif converge:
1880
+ logger.warning(f'ignoring "converge" on a {ens} stage; density convergence needs npt')
1810
1881
  return edr_list
1811
1882
 
1883
+ def _log_box(self):
1884
+ """Logs the current box side lengths."""
1885
+ box=self.Coordinates.box.diagonal()
1886
+ logger.info(f'Current box side lengths: {box[0]:.3f} nm x {box[1]:.3f} nm x {box[2]:.3f} nm')
1887
+
1888
+ def _density_series(self,edr_pfx,gromacs_dict={}):
1889
+ """Density trace from one edr, as a plain array, or None.
1890
+
1891
+ Args:
1892
+ edr_pfx (str): edr basename, without the '.edr' extension
1893
+ gromacs_dict (dict): gromacs directives passed through to gmx energy
1894
+
1895
+ Returns:
1896
+ numpy.ndarray: the Density column in kg/m^3, or None if unavailable
1897
+ """
1898
+ try:
1899
+ df=gmx_energy_trace(edr_pfx,['Density'],report_averages=True,**gromacs_dict)
1900
+ except Exception as e:
1901
+ logger.debug(f'no density available from {edr_pfx}: {e}')
1902
+ return None
1903
+ if df.empty or 'Density' not in df.columns: return None
1904
+ return df['Density'].to_numpy(dtype=float)
1905
+
1906
+ def _converge_density(self,deffnm,mdp,converge,density,gromacs_dict={}):
1907
+ """Repeats an NPT stage until its density settles, or until a ceiling.
1908
+
1909
+ This is the fixed-``repeat`` mechanism with a measured stopping rule
1910
+ instead of a counted one. Densification is the right place for it:
1911
+ the 200 -> ~1100 kg/m^3 compaction is one-shot, involves a large volume
1912
+ change, and otherwise runs for however many steps someone guessed.
1913
+
1914
+ Each extension is a fresh ``mdrun``, so velocities are regenerated
1915
+ between segments exactly as ``repeat`` already does; the criterion is
1916
+ therefore applied to the *last* segment rather than to a concatenation
1917
+ of segments that do not share a velocity history.
1918
+
1919
+ A build that never settles says so, loudly, rather than silently
1920
+ reporting whatever density it reached.
1921
+
1922
+ Args:
1923
+ deffnm (str): output file basename of the stage being extended
1924
+ mdp (str): name of the mdp file to rerun
1925
+ converge (dict): 'tolerance' (kg/m^3), 'max_repeats', 'min_samples', 'drift_sems'
1926
+ density (numpy.ndarray): density trace of the stage just run, or None
1927
+ gromacs_dict (dict): gromacs directives
1928
+
1929
+ Returns:
1930
+ list: edr basenames of any extension segments run
1931
+ """
1932
+ tol=float(converge.get('tolerance',1.0))
1933
+ ceiling=int(converge.get('max_repeats',10))
1934
+ min_samples=int(converge.get('min_samples',50))
1935
+ drift_sems=float(converge.get('drift_sems',2.0))
1936
+ extra=[]
1937
+ for attempt in range(ceiling+1):
1938
+ if density is None:
1939
+ logger.warning('density convergence requested but no Density trace is available; not gating')
1940
+ return extra
1941
+ r=series_converged(density,tol,min_samples=min_samples,drift_sems=drift_sems)
1942
+ if r['converged']:
1943
+ logger.info(
1944
+ f'Density converged after {attempt} extension(s): '
1945
+ f'{r["mean"]:.1f} +/- {r["sem"]:.2f} kg/m^3 '
1946
+ f'(tau_int {r["tau_int"]:.0f} samples, drift {r["drift"]:+.2f})'
1947
+ )
1948
+ return extra
1949
+ if attempt==ceiling:
1950
+ logger.warning(
1951
+ f'Density did NOT converge after {ceiling} extension(s) -- {r["reason"]}. '
1952
+ f'The last window averaged {r["mean"]:.1f} kg/m^3; treat that as an '
1953
+ f'unsettled box, not as this system\'s density'
1954
+ )
1955
+ return extra
1956
+ logger.info(f'Density not settled ({r["reason"]}); extending, {attempt+1} of {ceiling}')
1957
+ this_deffnm=f'{deffnm}-converge-{attempt+1}-npt'
1958
+ self.grompp_and_mdrun(out=this_deffnm,mdp=mdp,quiet=False,**gromacs_dict)
1959
+ extra.append(this_deffnm)
1960
+ self._log_box()
1961
+ density=self._density_series(this_deffnm,gromacs_dict)
1962
+ return extra
1963
+
1812
1964
  def get_resid_sets(self,atom_pair):
1813
1965
  """Identifies individual sets of separate resids owned by unbonded atoms i and j.
1814
1966
 
@@ -121,10 +121,19 @@ _GromacsTopologyHashables_ = { # attributes/columns that should always have valu
121
121
  'dihedraltypes': ['i', 'j', 'k', 'l']
122
122
  }
123
123
 
124
+ # htpolynet writes an entire build as ONE moleculetype, on purpose: a cured
125
+ # network is a single covalently connected molecule, and leftover monomers
126
+ # ride along in the same block. The name used to default to the string
127
+ # 'None', which reads to a user like an unset field or a bug -- and users who
128
+ # hit GROMACS's "inconsistent shifts" warning under trjconv -pbc whole go
129
+ # looking at exactly this line. The name must match between [ moleculetype ]
130
+ # and [ molecules ], so both defaults change together.
131
+ _WHOLE_SYSTEM_MOLECULETYPE_ = 'whole_system'
132
+
124
133
  _GromacsTopologyDirectiveDefaults_ = {
125
134
  'system': ['A_generic_system'],
126
- 'molecules': ['None', 1],
127
- 'moleculetype': ['None', 3],
135
+ 'molecules': [_WHOLE_SYSTEM_MOLECULETYPE_, 1],
136
+ 'moleculetype': [_WHOLE_SYSTEM_MOLECULETYPE_, 3],
128
137
  'defaults': [1, 2, 'yes', 0.5, 0.83333333]
129
138
  }
130
139
 
@@ -493,6 +502,24 @@ class Topology:
493
502
  logger.debug(f'New total charge after adjustment: {self.total_charge():.6f}')
494
503
  return self
495
504
 
505
+ def molecule_charges(self):
506
+ """Returns the size and net charge of every covalently bonded molecule.
507
+
508
+ Returns:
509
+ list: (number of atoms, net charge) tuples, one per connected component of the bond
510
+ graph, largest molecule first
511
+ """
512
+ if 'atoms' not in self.D or self.D['atoms'].empty:
513
+ return []
514
+ atoms = self.D['atoms']
515
+ charge = dict(zip(atoms['nr'].astype(int), atoms['charge'].astype(float)))
516
+ g = nx.Graph()
517
+ g.add_nodes_from(charge)
518
+ if 'bonds' in self.D and not self.D['bonds'].empty:
519
+ g.add_edges_from(zip(self.D['bonds']['ai'].astype(int), self.D['bonds']['aj'].astype(int)))
520
+ result = [(len(c), sum(charge[a] for a in c)) for c in nx.connected_components(g)]
521
+ return sorted(result, key=lambda x: -x[0])
522
+
496
523
  def total_mass(self, units='gromacs'):
497
524
  """Returns total mass of all atoms in the Topology.
498
525