HTPolyNet 2.8.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.
- htpolynet/core/bondtemplate.py +28 -6
- htpolynet/core/molecule.py +1 -1
- htpolynet/core/runtime.py +47 -2
- htpolynet/core/topocoord.py +71 -5
- htpolynet/core/topology.py +18 -0
- htpolynet/cure/curecontroller.py +65 -7
- htpolynet/cure/expandreactions.py +115 -1
- htpolynet/repair/cyanate_cap.py +19 -22
- htpolynet/repair/topology_surgery.py +73 -7
- htpolynet/resources/example_depot/6-cyanate-ester.yaml +4 -1
- {htpolynet-2.8.0.dist-info → htpolynet-2.9.0.dist-info}/METADATA +1 -1
- {htpolynet-2.8.0.dist-info → htpolynet-2.9.0.dist-info}/RECORD +15 -15
- {htpolynet-2.8.0.dist-info → htpolynet-2.9.0.dist-info}/WHEEL +0 -0
- {htpolynet-2.8.0.dist-info → htpolynet-2.9.0.dist-info}/entry_points.txt +0 -0
- {htpolynet-2.8.0.dist-info → htpolynet-2.9.0.dist-info}/licenses/LICENSE +0 -0
htpolynet/core/bondtemplate.py
CHANGED
|
@@ -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
|
|
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):
|
htpolynet/core/molecule.py
CHANGED
|
@@ -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
|
htpolynet/core/topocoord.py
CHANGED
|
@@ -229,7 +229,7 @@ class TopoCoord:
|
|
|
229
229
|
anH = sum([int(x.upper().startswith('H')) for x in aneighnames])
|
|
230
230
|
return anH
|
|
231
231
|
|
|
232
|
-
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):
|
|
233
233
|
"""Updates angles, pairs, dihedrals, atom types, and charges, based on product templates associated with each bond in 'bdf'.
|
|
234
234
|
|
|
235
235
|
Args:
|
|
@@ -237,6 +237,12 @@ class TopoCoord:
|
|
|
237
237
|
moldict (dict): dictionary of template Molecules keyed by name
|
|
238
238
|
overcharge_threshhold (float): threshold for charge adjustment, defaults to 0.1
|
|
239
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
|
|
240
246
|
|
|
241
247
|
Raises:
|
|
242
248
|
Exception: if nan found in any attribute of any new system angle
|
|
@@ -282,7 +288,7 @@ class TopoCoord:
|
|
|
282
288
|
bystander_resids, bystander_resnames, bystander_atomidx, bystander_atomnames = self.get_bystanders(bb)
|
|
283
289
|
oneaway_resids, oneaway_resnames, oneaway_atomidx, oneaway_atomnames = self.get_oneaways(bb, chain_manager=chain_manager)
|
|
284
290
|
intraresidue = resids[0] == resids[1]
|
|
285
|
-
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))
|
|
286
292
|
RB = ReactionBond(bb, resids, order, bystander_resids, bystander_atomidx, oneaway_resids, oneaway_atomidx)
|
|
287
293
|
logger.debug(f'apparent bond template {str(BT)}')
|
|
288
294
|
logger.debug(f'apparent bond instance {str(RB)}')
|
|
@@ -293,7 +299,7 @@ class TopoCoord:
|
|
|
293
299
|
# copy all bond records matching these two bonds; should be only one!!
|
|
294
300
|
d = d[((d.ai == temp_i_idx) & (d.aj == temp_j_idx)) |
|
|
295
301
|
((d.ai == temp_j_idx) & (d.aj == temp_i_idx))].copy()
|
|
296
|
-
assert d.shape[0] == 1, f'Using {T.name} is sent inst-bond {
|
|
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()}'
|
|
297
303
|
''' check passed '''
|
|
298
304
|
temp_angles, temp_dihedrals, temp_pairs = T.get_angles_dihedrals((temp_i_idx, temp_j_idx))
|
|
299
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}')
|
|
@@ -317,7 +323,8 @@ class TopoCoord:
|
|
|
317
323
|
assert check,f'Error: bidirectional dicts are incompatible; bug\n{inst2temp}\b{temp2inst}'
|
|
318
324
|
# logger.debug(f'inst2temp {inst2temp}')
|
|
319
325
|
# logger.debug(f'temp2inst {temp2inst}')
|
|
320
|
-
|
|
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
|
|
321
328
|
_temp_i_idx, _temp_j_idx = inst2temp[i_idx], inst2temp[j_idx]
|
|
322
329
|
assert temp_i_idx == _temp_i_idx, f'mapping mismatch -- bug'
|
|
323
330
|
assert temp_j_idx == _temp_j_idx, f'mapping mismatch -- bug'
|
|
@@ -442,7 +449,9 @@ class TopoCoord:
|
|
|
442
449
|
# return temp_pairs
|
|
443
450
|
mapped_inst_atoms = list(set(mapped_inst_atoms))
|
|
444
451
|
logger.debug(f'System overcharge after mapping: {self.Topology.total_charge():.4f}')
|
|
445
|
-
|
|
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
|
|
446
455
|
|
|
447
456
|
def enumerate_1_4_pairs(self, at_idx):
|
|
448
457
|
"""Enumerates all 1-4 pair interactions resulting from new bonds in at_idx.
|
|
@@ -886,6 +895,52 @@ class TopoCoord:
|
|
|
886
895
|
result.append(j)
|
|
887
896
|
return result
|
|
888
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
|
+
|
|
889
944
|
def minimum_distance(self, other, self_excludes=None, other_excludes=None):
|
|
890
945
|
"""Computes the distance of closest approach between self's Coordinates and other's Coordinates.
|
|
891
946
|
|
|
@@ -1097,6 +1152,17 @@ class TopoCoord:
|
|
|
1097
1152
|
# logger.debug(f'write_mol2, other_attributes:\n{other_attributes.to_string()}')
|
|
1098
1153
|
if 'mol2_bonds' in self.Topology.D:
|
|
1099
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)
|
|
1100
1166
|
else:
|
|
1101
1167
|
self.Coordinates.write_mol2(filename,molname=molname,other_attributes=other_attributes)
|
|
1102
1168
|
|
htpolynet/core/topology.py
CHANGED
|
@@ -502,6 +502,24 @@ class Topology:
|
|
|
502
502
|
logger.debug(f'New total charge after adjustment: {self.total_charge():.6f}')
|
|
503
503
|
return self
|
|
504
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
|
+
|
|
505
523
|
def total_mass(self, units='gromacs'):
|
|
506
524
|
"""Returns total mass of all atoms in the Topology.
|
|
507
525
|
|
htpolynet/cure/curecontroller.py
CHANGED
|
@@ -38,6 +38,46 @@ def residue_reaction_counts(adf):
|
|
|
38
38
|
"""
|
|
39
39
|
return adf.groupby('resNum')['nreactions'].sum()
|
|
40
40
|
|
|
41
|
+
def cure_site_mask(adf,RL,MD):
|
|
42
|
+
"""Marks the atoms a cure-stage reaction can ever bond.
|
|
43
|
+
|
|
44
|
+
A residue's ``z + nreactions`` counts every reactive site it was built
|
|
45
|
+
with, and that includes bonds made at the param and build stages and
|
|
46
|
+
valences no cure reaction can consume -- in example 2 each HIE carries a
|
|
47
|
+
param-stage bond and a leftover valence on C4, so its four "sites" include
|
|
48
|
+
two the cure never touches. Functionality for asking whether the cure made
|
|
49
|
+
a network has to be counted on cure sites only.
|
|
50
|
+
|
|
51
|
+
The site set is read from the runtime reaction list, which has already been
|
|
52
|
+
symmetry- and stereo-expanded: a reaction written against ``TAZ:C1`` has
|
|
53
|
+
siblings for C2 and C3 there. Reading the configuration's reactions instead
|
|
54
|
+
would name one atom per symmetry class and undercount -- that version was
|
|
55
|
+
tried and silenced example 6's genuine check. Residue names are resolved the
|
|
56
|
+
way the bond search resolves them, through the reactant's sequence.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
adf (pandas.DataFrame): the global atom dataframe; must carry 'resName' and 'atomName'
|
|
60
|
+
RL (ReactionList): the runtime, symmetry-expanded reaction list
|
|
61
|
+
MD (MoleculeDict): molecule templates, for resolving a reactant's residue names
|
|
62
|
+
|
|
63
|
+
Returns:
|
|
64
|
+
pandas.Series: boolean per atom, aligned to adf; None if no cure sites can be determined
|
|
65
|
+
"""
|
|
66
|
+
if RL is None or MD is None or not all(c in adf.columns for c in ('resName','atomName')):
|
|
67
|
+
return None
|
|
68
|
+
sites=set()
|
|
69
|
+
for R in RL:
|
|
70
|
+
if R.stage!=reaction_stage.cure: continue
|
|
71
|
+
for rec in R.atoms.values():
|
|
72
|
+
try:
|
|
73
|
+
resname=MD[R.reactants[rec['reactant']]].get_resname(rec['resid'])
|
|
74
|
+
except (KeyError,IndexError,AttributeError,TypeError):
|
|
75
|
+
continue
|
|
76
|
+
sites.add((resname,rec['atom']))
|
|
77
|
+
if not sites:
|
|
78
|
+
return None
|
|
79
|
+
return pd.Series([k in sites for k in zip(adf['resName'],adf['atomName'])],index=adf.index)
|
|
80
|
+
|
|
41
81
|
def residue_functionality(adf):
|
|
42
82
|
"""Counts, per residue, how many reactive sites it started with.
|
|
43
83
|
|
|
@@ -794,7 +834,7 @@ class CureController:
|
|
|
794
834
|
self.state.current_stage[mode]=0
|
|
795
835
|
self.state._to_yaml()
|
|
796
836
|
|
|
797
|
-
def check_iterations_vs_functionality(self,TC:TopoCoord):
|
|
837
|
+
def check_iterations_vs_functionality(self,TC:TopoCoord,RL:ReactionList=None,MD:MoleculeDict=None):
|
|
798
838
|
"""Warns if the cure produced few or no complete crosslinkers.
|
|
799
839
|
|
|
800
840
|
A system whose crosslinkers did not complete has no junctions: it is a
|
|
@@ -830,13 +870,28 @@ class CureController:
|
|
|
830
870
|
|
|
831
871
|
Args:
|
|
832
872
|
TC (TopoCoord): global system topology and coordinates
|
|
873
|
+
RL (ReactionList): runtime reaction list; when given with MD, functionality and completion are counted on cure-reactive sites only (see :func:`cure_site_mask`)
|
|
874
|
+
MD (MoleculeDict): molecule templates, used with RL
|
|
833
875
|
"""
|
|
834
876
|
adf=TC.gro_DataFrame('atoms')
|
|
835
877
|
if adf is None or not all(c in adf.columns for c in ('resNum','resName','z','nreactions')): return
|
|
836
|
-
|
|
878
|
+
mask=cure_site_mask(adf,RL,MD)
|
|
879
|
+
sites=adf if mask is None else adf[mask]
|
|
880
|
+
if sites.empty: return
|
|
881
|
+
func=residue_functionality(sites)
|
|
837
882
|
if func.empty: return
|
|
838
883
|
fmax=int(func.max())
|
|
839
|
-
|
|
884
|
+
# A crosslink junction needs a residue with at least three reactive
|
|
885
|
+
# sites. When the most functional residue has two, every chain is linear
|
|
886
|
+
# (chain-growth polystyrene, say): a fully reacted difunctional unit is a
|
|
887
|
+
# chain interior, not a junction, and nothing can percolate however far
|
|
888
|
+
# the cure goes. Both checks below would then misfire -- the gel-point
|
|
889
|
+
# threshold (1/(f-1))**f is exactly 100% at f=2, so it fired unless every
|
|
890
|
+
# monomer was mid-chain.
|
|
891
|
+
if fmax<3:
|
|
892
|
+
if mask is not None:
|
|
893
|
+
logger.info('No residue carries three or more cure-reactive sites, so crosslink percolation is not assessed. That is correct for a linear polymer; a system that crosslinks through a multi-residue molecule -- a dimethacrylate, a multi-arm prepolymer -- is outside what this residue-level check can see.')
|
|
894
|
+
return
|
|
840
895
|
names=adf.loc[adf['resNum']==func.idxmax(),'resName']
|
|
841
896
|
resname=names.iloc[0] if len(names) else f'residue {func.idxmax()}'
|
|
842
897
|
iterations=self.state.iter
|
|
@@ -845,7 +900,9 @@ class CureController:
|
|
|
845
900
|
return
|
|
846
901
|
crosslinkers=func[func==fmax].index
|
|
847
902
|
if not len(crosslinkers): return
|
|
848
|
-
counts
|
|
903
|
+
# completion counts cure-site bonds only, or a bond made at the param
|
|
904
|
+
# stage (HIE's C4) would make a half-reacted residue look complete
|
|
905
|
+
counts=residue_reaction_counts(sites).reindex(crosslinkers).fillna(0)
|
|
849
906
|
complete=int((counts>=fmax).sum())
|
|
850
907
|
fraction=complete/len(crosslinkers)
|
|
851
908
|
logger.info(f'{complete} of {len(crosslinkers)} {resname} are fully reacted ({fraction:.1%})')
|
|
@@ -874,7 +931,7 @@ class CureController:
|
|
|
874
931
|
return None
|
|
875
932
|
return residue_reaction_counts(adf)
|
|
876
933
|
|
|
877
|
-
def _check_bias_side(self,adf,bdf):
|
|
934
|
+
def _check_bias_side(self,adf,bdf,RL=None,MD=None):
|
|
878
935
|
"""Warns, once per run, if the completion bias is ranking the less functional side.
|
|
879
936
|
|
|
880
937
|
The bias ranks on the ``B`` reactant because htpolynet's A2+B3 idiom
|
|
@@ -894,7 +951,8 @@ class CureController:
|
|
|
894
951
|
if self.bias_side_checked: return
|
|
895
952
|
if not all(c in adf.columns for c in ('z','nreactions')): return
|
|
896
953
|
self.bias_side_checked=True
|
|
897
|
-
|
|
954
|
+
mask=cure_site_mask(adf,RL,MD)
|
|
955
|
+
func=residue_functionality(adf if mask is None else adf[mask])
|
|
898
956
|
a=bdf['ri'].map(func).dropna()
|
|
899
957
|
b=bdf['rj'].map(func).dropna()
|
|
900
958
|
if a.empty or b.empty: return
|
|
@@ -1014,7 +1072,7 @@ class CureController:
|
|
|
1014
1072
|
reaction_counts=self._completion_bias_counts(adf)
|
|
1015
1073
|
bdf=rank_bond_candidates(bdf,reaction_counts)
|
|
1016
1074
|
if reaction_counts is not None:
|
|
1017
|
-
self._check_bias_side(adf,bdf)
|
|
1075
|
+
self._check_bias_side(adf,bdf,RL=RL,MD=MD)
|
|
1018
1076
|
nrx=bdf['rj'].map(reaction_counts).fillna(0).astype(int)
|
|
1019
1077
|
logger.debug(f'Completion bias: {int((nrx>0).sum())} of {bdf.shape[0]} candidates extend an already-reacted B-side residue (most bonds already carried: {int(nrx.max())})')
|
|
1020
1078
|
bdf['allowed']=[True for x in range(bdf.shape[0])]
|
|
@@ -5,7 +5,7 @@ Author: Cameron F. Abrams <cfa22@drexel.edu>
|
|
|
5
5
|
import logging
|
|
6
6
|
|
|
7
7
|
from copy import deepcopy
|
|
8
|
-
from itertools import product
|
|
8
|
+
from itertools import combinations, product
|
|
9
9
|
|
|
10
10
|
from ..core.molecule import Molecule, MoleculeList, MoleculeDict
|
|
11
11
|
from ..cure.reaction import reaction_stage, Reaction, ReactionList, generate_product_name, reactant_resid_to_presid
|
|
@@ -292,3 +292,117 @@ def generate_symmetry_reactions(RL:ReactionList,MD:MoleculeDict):
|
|
|
292
292
|
|
|
293
293
|
RL.extend(terminal_reactions)
|
|
294
294
|
return len(terminal_reactions)+tail_adds
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _second_shell_symmetry_siblings(M:Molecule, atom_name:str):
|
|
298
|
+
"""Names of the atoms symmetry-equivalent to atom_name that sit exactly two bonds from it in M.
|
|
299
|
+
|
|
300
|
+
Args:
|
|
301
|
+
M (Molecule): a generated monomer
|
|
302
|
+
atom_name (str): name of a cure-reactive atom of M
|
|
303
|
+
|
|
304
|
+
Returns:
|
|
305
|
+
list: sorted atom names; empty if atom_name has no such siblings
|
|
306
|
+
"""
|
|
307
|
+
candidates = set()
|
|
308
|
+
for symm_set in M.symmetry_relateds:
|
|
309
|
+
if atom_name in symm_set:
|
|
310
|
+
candidates.update(x for x in symm_set if x != atom_name)
|
|
311
|
+
if not candidates:
|
|
312
|
+
return []
|
|
313
|
+
TC = M.TopoCoord
|
|
314
|
+
A = TC.Coordinates.A
|
|
315
|
+
idx_of = dict(zip(A['atomName'], A['globalIdx'].astype(int)))
|
|
316
|
+
if atom_name not in idx_of:
|
|
317
|
+
return []
|
|
318
|
+
bl = TC.Topology.bondlist
|
|
319
|
+
a = idx_of[atom_name]
|
|
320
|
+
first = set(bl.partners_of(a))
|
|
321
|
+
second = {j for i in first for j in bl.partners_of(i)} - first - {a}
|
|
322
|
+
return sorted(n for n in candidates if n in idx_of and idx_of[n] in second)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def sibling_expand_reactions(molecules:MoleculeDict, reactions:ReactionList):
|
|
326
|
+
"""Generates templates for cure bonds that form next to atoms of the same residue that have already reacted.
|
|
327
|
+
|
|
328
|
+
A cure template is the product of one bond, so it shows every other
|
|
329
|
+
reactive atom of the residue unreacted. Where such an atom is close
|
|
330
|
+
enough to the bonding atom that the template splice overwrites its charge,
|
|
331
|
+
as the ring carbons of a triazine are, each later bond on the residue
|
|
332
|
+
resets the charges of the atoms that reacted before it. For every cure
|
|
333
|
+
reaction whose monomer reactant has symmetry-equivalent reactive atoms two
|
|
334
|
+
bonds from its bonding atom, this builds one product per non-empty set of
|
|
335
|
+
those atoms already bonded to the same partner, with the bond of interest
|
|
336
|
+
formed last so that it is the product's template bond. The templates'
|
|
337
|
+
sibling context (see TopoCoord.get_siblings) lets find_template pick them.
|
|
338
|
+
|
|
339
|
+
Note:
|
|
340
|
+
Must be called after the monomers and the cure products are generated.
|
|
341
|
+
|
|
342
|
+
Args:
|
|
343
|
+
molecules (MoleculeDict): all molecules generated so far
|
|
344
|
+
reactions (ReactionList): all reactions, symmetry-expanded
|
|
345
|
+
|
|
346
|
+
Returns:
|
|
347
|
+
tuple(ReactionList, MoleculeDict): the new param-stage reactions, and their products
|
|
348
|
+
in the order they must be generated
|
|
349
|
+
"""
|
|
350
|
+
extra_reactions:ReactionList = []
|
|
351
|
+
extra_molecules:MoleculeDict = {}
|
|
352
|
+
cure = [R for R in reactions if R.stage == reaction_stage.cure and len(R.reactants) == 2 and len(R.bonds) == 1]
|
|
353
|
+
for R in cure:
|
|
354
|
+
bond_keys = R.bonds[0]['atoms']
|
|
355
|
+
for s_key, o_key in (bond_keys, bond_keys[::-1]):
|
|
356
|
+
s_rec, o_rec = R.atoms[s_key], R.atoms[o_key]
|
|
357
|
+
if s_rec['reactant'] == o_rec['reactant']:
|
|
358
|
+
continue
|
|
359
|
+
s_name = R.reactants[s_rec['reactant']]
|
|
360
|
+
o_name = R.reactants[o_rec['reactant']]
|
|
361
|
+
if s_name not in molecules or len(molecules[s_name].sequence) != 1:
|
|
362
|
+
continue
|
|
363
|
+
siblings = _second_shell_symmetry_siblings(molecules[s_name], s_rec['atom'])
|
|
364
|
+
if not siblings:
|
|
365
|
+
continue
|
|
366
|
+
order = list(R.reactants.keys())
|
|
367
|
+
s_resid = sum(len(molecules[R.reactants[k]].sequence) for k in order[:order.index(s_rec['reactant'])]) + s_rec['resid']
|
|
368
|
+
for n in range(1, len(siblings) + 1):
|
|
369
|
+
for S in combinations(siblings, n):
|
|
370
|
+
# start from the cure product that bonds the first sibling to the same partner atom
|
|
371
|
+
base = [B for B in cure if B.reactants == R.reactants
|
|
372
|
+
and B.atoms[s_key]['atom'] == S[0] and B.atoms[o_key]['atom'] == o_rec['atom']
|
|
373
|
+
and B.atoms[s_key]['resid'] == s_rec['resid'] and B.atoms[o_key]['resid'] == o_rec['resid']]
|
|
374
|
+
if not base:
|
|
375
|
+
logger.debug(f'{R.name}: no cure product bonds {s_name} {S[0]} to {o_name} {o_rec["atom"]}; '
|
|
376
|
+
f'no sibling template for {S}')
|
|
377
|
+
continue
|
|
378
|
+
prev = base[0].product
|
|
379
|
+
prev_s_resid = s_resid
|
|
380
|
+
o_first = s_key == bond_keys[1]
|
|
381
|
+
for site in list(S[1:]) + [s_rec['atom']]:
|
|
382
|
+
# Molecule.prepare_new_bonds reads a bond's first atom from the first
|
|
383
|
+
# reactant, so reactant order follows the cure bond's atom order; when
|
|
384
|
+
# the partner comes first, it also shifts the bonding residue's resid
|
|
385
|
+
s_atom = {'resid': prev_s_resid, 'atom': site, 'z': 1}
|
|
386
|
+
o_atom = {'resid': o_rec['resid'], 'atom': o_rec['atom'], 'z': 1}
|
|
387
|
+
newR = Reaction()
|
|
388
|
+
if o_first:
|
|
389
|
+
newR.reactants = {1: o_name, 2: prev}
|
|
390
|
+
newR.atoms = {'A': {'reactant': 1, **o_atom}, 'B': {'reactant': 2, **s_atom}}
|
|
391
|
+
prev_s_resid += len(molecules[o_name].sequence)
|
|
392
|
+
else:
|
|
393
|
+
newR.reactants = {1: prev, 2: o_name}
|
|
394
|
+
newR.atoms = {'A': {'reactant': 1, **s_atom}, 'B': {'reactant': 2, **o_atom}}
|
|
395
|
+
newR.bonds = [{'atoms': ['A', 'B'], 'order': R.bonds[0].get('order', 1)}]
|
|
396
|
+
newR.stage = reaction_stage.param
|
|
397
|
+
newR.product = generate_product_name(newR)
|
|
398
|
+
newR.name = f'sibling:{newR.product}'
|
|
399
|
+
prev = newR.product
|
|
400
|
+
if newR.product in molecules or newR.product in extra_molecules:
|
|
401
|
+
continue
|
|
402
|
+
P = Molecule.New(newR.product, newR)
|
|
403
|
+
P.set_sequence_from_moldict({**molecules, **extra_molecules})
|
|
404
|
+
P.origin = 'unparameterized'
|
|
405
|
+
extra_molecules[newR.product] = P
|
|
406
|
+
extra_reactions.append(newR)
|
|
407
|
+
logger.debug(f'sibling template {newR.product}: {s_name} {site} bonds {o_name} {o_rec["atom"]}')
|
|
408
|
+
return extra_reactions, extra_molecules
|
htpolynet/repair/cyanate_cap.py
CHANGED
|
@@ -672,8 +672,13 @@ def triazine_to_cyanate_cap(TC, moldict, spec, reactions):
|
|
|
672
672
|
# ---- Phase 4: splice template params (forms BPA-O-C bond with full
|
|
673
673
|
# angle/dihedral/pair entries from the cap_template molecule) ----
|
|
674
674
|
pairs_to_add = [(int(rec['o']), int(rec['c']), 1) for rec in cap_records]
|
|
675
|
+
# Charge is settled once, per molecule, after phase 5's deletions. The
|
|
676
|
+
# splice's own system-wide adjustment would run while the sacrificial H's
|
|
677
|
+
# still exist, and phase 5 would then have to undo it on other atoms.
|
|
678
|
+
touched = set()
|
|
675
679
|
if pairs_to_add:
|
|
676
|
-
ts.add_bonds_with_template(TC, pairs_to_add, moldict, cap_template
|
|
680
|
+
touched |= {int(a) for a in ts.add_bonds_with_template(TC, pairs_to_add, moldict, cap_template,
|
|
681
|
+
adjust_charges=False)}
|
|
677
682
|
|
|
678
683
|
# Refresh the C-N triple-bond parameters: map_from_templates updated the
|
|
679
684
|
# CYN atom types (CA -> c1, NB -> n1) but only re-resolved the bond it
|
|
@@ -690,30 +695,22 @@ def triazine_to_cyanate_cap(TC, moldict, spec, reactions):
|
|
|
690
695
|
# ---- Phase 5: batched H + orphan-atom deletion (reindexes) ----
|
|
691
696
|
if h_to_delete:
|
|
692
697
|
logger.debug(f'triazine_to_cyanate_cap: deleting {len(h_to_delete)} sacrificial/orphan atoms')
|
|
693
|
-
#
|
|
694
|
-
# delete_atoms reindexes
|
|
695
|
-
# missing charge back across these neighbors so the system stays
|
|
696
|
-
# net-neutral. Otherwise the lost (typically positive) H charges
|
|
697
|
-
# leave the system with a several-electron net charge that gmx
|
|
698
|
-
# refuses to run with Ewald electrostatics.
|
|
699
|
-
affected_neighbors = set()
|
|
698
|
+
# the heavy atoms that lose a bonded H are touched too; collect them
|
|
699
|
+
# before delete_atoms reindexes
|
|
700
700
|
for d_idx in h_to_delete:
|
|
701
701
|
for nbr in TC.Topology.bondlist.partners_of(int(d_idx)):
|
|
702
|
-
|
|
703
|
-
|
|
702
|
+
touched.add(int(nbr))
|
|
703
|
+
touched -= {int(x) for x in h_to_delete}
|
|
704
704
|
idx_mapper = TC.delete_atoms(sorted(h_to_delete))
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
desired_charge=0.0,
|
|
715
|
-
msg='triazine_to_cyanate_cap post-deletion rebalance',
|
|
716
|
-
)
|
|
705
|
+
touched = {idx_mapper[a] for a in touched if a in idx_mapper}
|
|
706
|
+
# Each repaired molecule must end neutral, not just the system. A single
|
|
707
|
+
# system-wide rebalance left every molecule of a zero-conversion melt
|
|
708
|
+
# carrying +0.21 or -0.27 e, depending on which of its caps were formed
|
|
709
|
+
# in place and which were transferred.
|
|
710
|
+
neutral = ts.neutralize_touched_fragments(TC, touched)
|
|
711
|
+
if neutral['n_fragments']:
|
|
712
|
+
logger.info(f'triazine_to_cyanate_cap: neutralized {neutral["n_fragments"]} repaired molecule(s); '
|
|
713
|
+
f'largest excess before correction {neutral["max_excess"]:.4f} e')
|
|
717
714
|
|
|
718
715
|
return _completion_stats(cl['residue'], len(cl_residues), len(incomplete_plans),
|
|
719
716
|
placement=placement_summary,
|
|
@@ -8,6 +8,7 @@ reindexes everything); callers should batch deletions to the end of a
|
|
|
8
8
|
surgery pass so intermediate index references remain valid.
|
|
9
9
|
"""
|
|
10
10
|
import logging
|
|
11
|
+
import networkx as nx
|
|
11
12
|
import numpy as np
|
|
12
13
|
import pandas as pd
|
|
13
14
|
|
|
@@ -166,7 +167,70 @@ def refresh_bond_params(TC, pairs):
|
|
|
166
167
|
logger.debug(f'refresh_bond_params({ai},{aj}) failed: {e}')
|
|
167
168
|
|
|
168
169
|
|
|
169
|
-
def
|
|
170
|
+
def neutralize_touched_fragments(TC, touched, tol=1e-6):
|
|
171
|
+
"""Make every molecule the repair changed neutral again, correcting it
|
|
172
|
+
only on the atoms the repair changed.
|
|
173
|
+
|
|
174
|
+
A template splice writes exact template charges onto the atoms it maps,
|
|
175
|
+
but the rest of each molecule keeps charges from its earlier context,
|
|
176
|
+
and atoms deleted afterwards take their charge with them. So a
|
|
177
|
+
repaired molecule is left slightly off neutral. Settling that with one
|
|
178
|
+
system-wide adjustment keeps the total at zero, which is all Ewald
|
|
179
|
+
needs, but it moves charge between molecules: a zero-conversion
|
|
180
|
+
cyanate melt came out of repair as a liquid of +/-0.2 e ions.
|
|
181
|
+
|
|
182
|
+
Here each connected component that contains a touched atom is brought
|
|
183
|
+
to zero by an equal shift on its touched atoms. A component with no
|
|
184
|
+
touched atom is left alone. Whatever total that leaves (non-zero only
|
|
185
|
+
if an untouched component was already charged) is spread over all
|
|
186
|
+
touched atoms, so the system stays neutral for Ewald.
|
|
187
|
+
|
|
188
|
+
Args:
|
|
189
|
+
TC: TopoCoord, after all atom deletions
|
|
190
|
+
touched (Iterable[int]): current global indices of the atoms whose
|
|
191
|
+
charges the repair set, or whose bonded neighbours it deleted
|
|
192
|
+
tol (float): excess charge below which a component is left as is
|
|
193
|
+
|
|
194
|
+
Returns:
|
|
195
|
+
dict: ``n_fragments`` corrected and ``max_excess``, the largest
|
|
196
|
+
absolute component charge found before correcting
|
|
197
|
+
"""
|
|
198
|
+
T = TC.Topology
|
|
199
|
+
atoms = T.D['atoms']
|
|
200
|
+
touched = set(int(i) for i in touched) & set(atoms['nr'].astype(int))
|
|
201
|
+
stats = {'n_fragments': 0, 'max_excess': 0.0}
|
|
202
|
+
if not touched:
|
|
203
|
+
return stats
|
|
204
|
+
g = Bondlist.fromDataFrame(T.D['bonds']).graph()
|
|
205
|
+
g.add_nodes_from(touched)
|
|
206
|
+
charge = dict(zip(atoms['nr'].astype(int), atoms['charge'].astype(float)))
|
|
207
|
+
shift = {}
|
|
208
|
+
seen = set()
|
|
209
|
+
for i in sorted(touched):
|
|
210
|
+
if i in seen:
|
|
211
|
+
continue
|
|
212
|
+
component = nx.node_connected_component(g, i)
|
|
213
|
+
seen |= component
|
|
214
|
+
excess = sum(charge[a] for a in component)
|
|
215
|
+
stats['max_excess'] = max(stats['max_excess'], abs(excess))
|
|
216
|
+
if abs(excess) <= tol:
|
|
217
|
+
continue
|
|
218
|
+
here = [a for a in component if a in touched]
|
|
219
|
+
for a in here:
|
|
220
|
+
shift[a] = shift.get(a, 0.0) - excess / len(here)
|
|
221
|
+
stats['n_fragments'] += 1
|
|
222
|
+
if shift:
|
|
223
|
+
nr = atoms['nr'].astype(int)
|
|
224
|
+
atoms['charge'] = atoms['charge'] + nr.map(shift).fillna(0.0)
|
|
225
|
+
residual = T.total_charge()
|
|
226
|
+
if abs(residual) > tol:
|
|
227
|
+
logger.info(f'{residual:+.4f} e of net charge sits on molecules the repair did not touch; '
|
|
228
|
+
f'spreading it over the {len(touched)} repaired atoms to keep the system neutral')
|
|
229
|
+
T.adjust_charges(atoms=sorted(touched), desired_charge=0.0)
|
|
230
|
+
return stats
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def add_bonds_with_template(TC, pairs, moldict, product_name, chain_manager=None, adjust_charges=True):
|
|
170
234
|
"""Add new bonds and splice angles/dihedrals/pairs/types/charges from a
|
|
171
235
|
pre-parameterized linked-product template.
|
|
172
236
|
|
|
@@ -182,30 +246,32 @@ def add_bonds_with_template(TC, pairs, moldict, product_name, chain_manager=None
|
|
|
182
246
|
template parameters should be spliced into the system around
|
|
183
247
|
each new bond.
|
|
184
248
|
chain_manager: optional ChainManager owned by the caller.
|
|
249
|
+
adjust_charges: passed to map_from_templates. A caller that deletes
|
|
250
|
+
atoms afterwards passes False and settles the charge itself,
|
|
251
|
+
e.g. with neutralize_touched_fragments.
|
|
185
252
|
|
|
186
253
|
Returns:
|
|
187
|
-
list:
|
|
188
|
-
(empty when explicit_sacH={[]} for all pairs).
|
|
254
|
+
list: global indices of the atoms that received template charges
|
|
189
255
|
"""
|
|
190
256
|
if not pairs:
|
|
191
257
|
return []
|
|
192
258
|
explicit_sacH = {i: [] for i in range(len(pairs))}
|
|
193
|
-
|
|
194
|
-
chain_manager=chain_manager)
|
|
259
|
+
TC.make_bonds(pairs, explicit_sacH=explicit_sacH, chain_manager=chain_manager)
|
|
195
260
|
bdf = pd.DataFrame([{
|
|
196
261
|
'ai': int(ai),
|
|
197
262
|
'aj': int(aj),
|
|
198
263
|
'order': int(order),
|
|
199
264
|
'reactantName': product_name,
|
|
200
265
|
} for ai, aj, order in pairs])
|
|
201
|
-
TC.map_from_templates(bdf, moldict, chain_manager=chain_manager
|
|
266
|
+
mapped = TC.map_from_templates(bdf, moldict, chain_manager=chain_manager,
|
|
267
|
+
adjust_charges=adjust_charges)
|
|
202
268
|
# map_from_templates concats new rows that came from .map(temp2inst) onto
|
|
203
269
|
# the existing angles/dihedrals/pairs frames. Even with NaN-bearing rows
|
|
204
270
|
# filtered out before the concat, pandas can upcast int atom-index columns
|
|
205
271
|
# to float64 when intermediate rows held NaN. delete_atoms later asserts
|
|
206
272
|
# int dtype on these columns, so coerce back here.
|
|
207
273
|
_fix_atom_index_dtypes(TC)
|
|
208
|
-
return
|
|
274
|
+
return mapped
|
|
209
275
|
|
|
210
276
|
|
|
211
277
|
def _fix_atom_index_dtypes(TC):
|
|
@@ -198,7 +198,10 @@ reactions:
|
|
|
198
198
|
# A2+B3 step-growth: BPA's phenolic O forms an aryl ether with one of the
|
|
199
199
|
# triazine ring carbons, each side losing one H. The single reaction
|
|
200
200
|
# below is auto-expanded by htpolynet (via symmetry_equivalent_atoms on
|
|
201
|
-
# both monomers) into all 2 x 3 = 6 (O, C) permutations.
|
|
201
|
+
# both monomers) into all 2 x 3 = 6 (O, C) permutations. htpolynet also
|
|
202
|
+
# builds 18 templates for bonds to rings that already carry one or two
|
|
203
|
+
# BPAs, so later bonds on a ring do not reset the charges of its
|
|
204
|
+
# already-reacted carbons.
|
|
202
205
|
- name: etherify
|
|
203
206
|
stage: cure
|
|
204
207
|
reactants: {1: BPA, 2: TAZ}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: htpolynet
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.9.0
|
|
4
4
|
Summary: Automated MD System Builder for Amorphous Network Polymers
|
|
5
5
|
Project-URL: Source, https://github.com/cameronabrams/htpolynet
|
|
6
6
|
Project-URL: Documentation, https://htpolynet.readthedocs.io/
|
|
@@ -6,19 +6,19 @@ htpolynet/analysis/plot.py,sha256=ncLduM4cK7ncQjksE2qL0Z086gqQOCpMs66rlI7AbOk,33
|
|
|
6
6
|
htpolynet/analysis/postsim.py,sha256=7HvW6yPHfSddl63QUp8PbyzToMSm13Pw16cqCY8OnWw,16873
|
|
7
7
|
htpolynet/analysis/utils.py,sha256=jmQMfw8EDzRSEvqBHUQV2g15-MmZbreJYiJ7gan_z-c,17246
|
|
8
8
|
htpolynet/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
-
htpolynet/core/bondtemplate.py,sha256=
|
|
9
|
+
htpolynet/core/bondtemplate.py,sha256=_1vYMugonDuogysu15IsbpthvxYb6uJKC5ao7pQcWvg,9969
|
|
10
10
|
htpolynet/core/configuration.py,sha256=RKnsVz_SX7GrCxuL-1rXP9AQ23EcFyiQSYeLiG6CHc4,5191
|
|
11
11
|
htpolynet/core/coordinates.py,sha256=CGTHkdfw2ikc2ANacA5akRhZ9tOyM2IbELwQ2FVcKRw,23878
|
|
12
|
-
htpolynet/core/molecule.py,sha256=
|
|
12
|
+
htpolynet/core/molecule.py,sha256=MXTdgKXFc7JnCvFhorCaTBQNXrdhKhC9gALtBge4Ff0,52787
|
|
13
13
|
htpolynet/core/paramcache.py,sha256=3MTG96F4vtT5w-pn1RWNmXic0QKB7WVcwCrD-BSY3B0,4508
|
|
14
14
|
htpolynet/core/projectfilesystem.py,sha256=2U_EToZxN7yUGWu9BIRABVsYdp1AKkOuManwuFBz89k,20983
|
|
15
|
-
htpolynet/core/runtime.py,sha256=
|
|
16
|
-
htpolynet/core/topocoord.py,sha256=
|
|
17
|
-
htpolynet/core/topology.py,sha256=
|
|
15
|
+
htpolynet/core/runtime.py,sha256=uCTc-1-4UZsr_ygHnGl54mM4n7OPkzK1plkWuEfCXbg,58575
|
|
16
|
+
htpolynet/core/topocoord.py,sha256=GfxOf04jAMYB6_vgj87kG9lXR0LVXwDHWetG5sv5AIA,109249
|
|
17
|
+
htpolynet/core/topology.py,sha256=OZHb6_t52IxrVDSjCKQuvOG3xZkE1zM0Ft0rmTLgzWk,58393
|
|
18
18
|
htpolynet/cure/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
19
19
|
htpolynet/cure/chain.py,sha256=-d5BFE5xUKjFdNkxLfSnCnZIRSJCtr7xuxYzNHBeSgU,5344
|
|
20
|
-
htpolynet/cure/curecontroller.py,sha256=
|
|
21
|
-
htpolynet/cure/expandreactions.py,sha256=
|
|
20
|
+
htpolynet/cure/curecontroller.py,sha256=ulj9wpXRIEH6AAUSS23ssCMYvPKiOOL748fKK0jVjJI,58056
|
|
21
|
+
htpolynet/cure/expandreactions.py,sha256=LDVefyrCZI2QSqrTsrVIPYP6g_w-LiUsYZkN3lUAM74,19977
|
|
22
22
|
htpolynet/cure/reaction.py,sha256=S-w60HocYknKnGbq1_uwLpKTL5Fte_o7zxwk3FbyQ1I,10557
|
|
23
23
|
htpolynet/external/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
24
24
|
htpolynet/external/ambertools.py,sha256=W3Ut9z7XovJcrxfgkL8eyP-Q0tKmyK1awfAcEafNxB0,5307
|
|
@@ -38,8 +38,8 @@ htpolynet/io/gro.py,sha256=QGsAIlTIJlMRxtv_Juo0wdpbICAzyfQvSzzaMWrlMmA,7141
|
|
|
38
38
|
htpolynet/io/mol2.py,sha256=5aU3HmQ5DS0LBF7tBPCNYKzBScwj8V3xfEUcFIrsevk,7314
|
|
39
39
|
htpolynet/io/pdb.py,sha256=Np44dTbM0IcEAzfz6OGuH0rdQ63BGps3kOmkzH6syls,5293
|
|
40
40
|
htpolynet/repair/__init__.py,sha256=cP3i-P-Wc6s0MgoFDp63kbLomM-ti3mMGEgeQzUVKuY,1740
|
|
41
|
-
htpolynet/repair/cyanate_cap.py,sha256=
|
|
42
|
-
htpolynet/repair/topology_surgery.py,sha256=
|
|
41
|
+
htpolynet/repair/cyanate_cap.py,sha256=d-OqnoRwOMwijYuMLFhGoFkEa2qFyzCdGnICDK69VkQ,39063
|
|
42
|
+
htpolynet/repair/topology_surgery.py,sha256=twFNbdwb3liINypT3Fct9iVlmm_DHHQFnf_UqyXuCQI,13070
|
|
43
43
|
htpolynet/resources/README.md,sha256=epKLyqtcxtQOSzTYvaGlwhz970UA4vAU7r-iSBbbpmA,1432
|
|
44
44
|
htpolynet/resources/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
45
45
|
htpolynet/resources/claude/SKILL.md,sha256=1EWFhZVkeCtfgu9JV4i-4Cqs327-N9wUO3VlO8-9Cyw,7412
|
|
@@ -49,7 +49,7 @@ htpolynet/resources/example_depot/2-bisgma-styrene-thermoset.yaml,sha256=5pba6IW
|
|
|
49
49
|
htpolynet/resources/example_depot/3-pacm-dgeba-epoxy-thermoset.yaml,sha256=eewz2H3WcAY-f6tbhM1t-HLp5TmSVFiUg4xLJs8vN2k,4471
|
|
50
50
|
htpolynet/resources/example_depot/4-dfda-fde-epoxy-thermoset.yaml,sha256=VSY7EVwJsItcWN77HJlSMgY2VHFpvQXB_N27T7blfk4,4446
|
|
51
51
|
htpolynet/resources/example_depot/5-htpb-ipdi.yaml,sha256=2Ww8N3QMWpstxK2BChPB8Enltl78EFh7pn1vFkXrwhA,10616
|
|
52
|
-
htpolynet/resources/example_depot/6-cyanate-ester.yaml,sha256=
|
|
52
|
+
htpolynet/resources/example_depot/6-cyanate-ester.yaml,sha256=tsGZqvmK0i-0EQEDsRu4sz7WZ1aA65yKozFva-cQPO0,9799
|
|
53
53
|
htpolynet/resources/mdp/README.md,sha256=48RjM7HLRF776FUJXUxQIw8RZxc7z1ti6za3YB7_U80,20
|
|
54
54
|
htpolynet/resources/mdp/drag-min.mdp,sha256=CrMRQIzwtG4TlYRY-nB1P7HPgdwrpwSJJW6yoYdfahY,225
|
|
55
55
|
htpolynet/resources/mdp/drag-npt.mdp,sha256=vbU-LuDH-CLmB8s3kRx0SYkKMxR7Qjh8PuXGgpC2EGs,911
|
|
@@ -98,8 +98,8 @@ htpolynet/utils/logsetup.py,sha256=o0mlVXNzqcfua2SAlJPkGSh4lM_bmI10gWwpb9gqYu8,1
|
|
|
98
98
|
htpolynet/utils/profiling.py,sha256=su7qpGEz6FXVU4KT2HQDWG82bc1sgsfpDQBbAfPpsHc,7331
|
|
99
99
|
htpolynet/utils/stringthings.py,sha256=Mr6o55EM8o4YAaVYpjIJj2IxDToNdbPzb-lpQ3w3jFk,1176
|
|
100
100
|
htpolynet/utils/vmd_viz.py,sha256=Crk3Ln88PKiJ9X7DMMkFEVh2Ru6a1y0RUgj3w6EIgFc,10867
|
|
101
|
-
htpolynet-2.
|
|
102
|
-
htpolynet-2.
|
|
103
|
-
htpolynet-2.
|
|
104
|
-
htpolynet-2.
|
|
105
|
-
htpolynet-2.
|
|
101
|
+
htpolynet-2.9.0.dist-info/METADATA,sha256=csJ0C3IGcPfIQYAECEMBpvWVvMAwc4Vt9-vVY7qUddg,6588
|
|
102
|
+
htpolynet-2.9.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
|
|
103
|
+
htpolynet-2.9.0.dist-info/entry_points.txt,sha256=G5tx55llJf-IV9dIe7J8myGdyrhCVggCAhKrVNGP_s0,48
|
|
104
|
+
htpolynet-2.9.0.dist-info/licenses/LICENSE,sha256=piPSGqJdmTGyzF9HOnjlO2KvgOKT8NHwhCuGYM778tY,1071
|
|
105
|
+
htpolynet-2.9.0.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|