HTPolyNet 2.10.2__py3-none-any.whl → 2.11.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.
@@ -57,6 +57,7 @@ class Configuration:
57
57
  self.postcure_repair = [] # list of postcure topology-repair specs
58
58
  self.postcure = {}
59
59
  self.cure = {}
60
+ self.ring_cure = {}
60
61
  self.gaff = {}
61
62
  self.ambertools = {}
62
63
  self.resolve_type_discrepancies = []
@@ -129,6 +130,7 @@ class Configuration:
129
130
  self.postcure_repair = self.basedict.get('postcure_repair', [])
130
131
  self.postcure = self.basedict.get('postcure', {})
131
132
  self.cure = self.basedict.get('CURE', {})
133
+ self.ring_cure = self.basedict.get('ring_cure', {})
132
134
  self.gaff = self.basedict.get('GAFF', {})
133
135
  self.ambertools = self.basedict.get('ambertools', {})
134
136
  self.resolve_type_discrepancies = self.basedict.get('resolve_type_discrepancies', [])
@@ -17,11 +17,13 @@ from ..core import projectfilesystem as pfs
17
17
  from ..core.bondtemplate import BondTemplate, BondTemplateList, ReactionBond, ReactionBondList
18
18
  from ..core.topocoord import TopoCoord
19
19
  from ..cure.chain import ChainManager
20
- from ..cure.reaction import Reaction, ReactionList, reaction_stage
20
+ from ..cure.reaction import (Reaction, ReactionList, consumes_sacrificial_h, reaction_stage,
21
+ spanning_and_closing_bonds)
21
22
  from ..external.ambertools import GAFFParameterize
22
23
  from ..external.command import run
23
24
  from ..external.gromacs import mdp_modify,gro_from_trr
24
25
  from ..geometry.matrix4 import Matrix4
26
+ from ..geometry.placement import min_distance, place_group, rotate_about_axis
25
27
  from ..io.gro import GRX_ATTRIBUTES
26
28
 
27
29
  logger=logging.getLogger(__name__)
@@ -62,33 +64,10 @@ minimization; below 1 A they have been seen to stop sqm converging (a TMB ring
62
64
  methyl H 0.82 A from a triazine N).
63
65
  """
64
66
 
65
-
66
- def _rotate_about_axis(xyz, point, axis, theta):
67
- """Rotates points by theta about the line through point along unit vector axis (Rodrigues).
68
-
69
- Args:
70
- xyz (numpy.ndarray): (n, 3) positions
71
- point (numpy.ndarray): a point on the axis
72
- axis (numpy.ndarray): unit vector along the axis
73
- theta (float): angle in radians
74
-
75
- Returns:
76
- numpy.ndarray: rotated (n, 3) positions
77
- """
78
- if theta == 0.0:
79
- return xyz.copy()
80
- k = axis / np.linalg.norm(axis)
81
- K = np.array([[0, -k[2], k[1]], [k[2], 0, -k[0]], [-k[1], k[0], 0]])
82
- R = np.eye(3) + np.sin(theta) * K + (1.0 - np.cos(theta)) * (K @ K)
83
- return (xyz - point) @ R.T + point
84
-
85
-
86
- def _min_distance(a, b):
87
- """Smallest distance between any point of a and any point of b; inf if either is empty."""
88
- if len(a) == 0 or len(b) == 0:
89
- return np.inf
90
- diff = a[:, np.newaxis, :] - b[np.newaxis, :, :]
91
- return float(np.sqrt((diff * diff).sum(axis=2)).min())
67
+ # the turn scan and the addition placement want the same geometry; one copy of it
68
+ # lives in geometry.placement
69
+ _rotate_about_axis = rotate_about_axis
70
+ _min_distance = min_distance
92
71
 
93
72
 
94
73
  class Molecule:
@@ -352,6 +331,102 @@ class Molecule:
352
331
  self.initialize_molecule_rings()
353
332
  self.TopoCoord.write_tpx(f'{outname}.tpx')
354
333
 
334
+ def place_for_addition(self, at_idx, from_idx, from_resids, bond_length=0.147):
335
+ """Positions the residues of an incoming reactant against an atom it will bond to.
336
+
337
+ ``transrot`` aligns two reactants on the sacrificial hydrogens they are about
338
+ to lose, so it cannot place an addition: in a cyclotrimerization neither the
339
+ cyanate carbon nor its nitrogen carries a hydrogen, and nothing is lost. This
340
+ positions the incoming piece instead -- attaching atom a bond length from its
341
+ partner, in the direction and at the turn that leave the most room.
342
+
343
+ Args:
344
+ at_idx (int): global index of the atom already in place
345
+ from_idx (int): global index of the incoming atom that will carry the bond
346
+ from_resids (list): resNums of every residue that moves with from_idx
347
+ bond_length (float): distance to leave between the two atoms, in nm
348
+
349
+ Returns:
350
+ float: closest approach between the moved piece and everything else, in nm
351
+ """
352
+ TC = self.TopoCoord
353
+ A = TC.Coordinates.A
354
+ moving = A['resNum'].isin(from_resids).to_numpy()
355
+ group = A.loc[moving, ['posX', 'posY', 'posZ']].to_numpy(dtype=float)
356
+ attach = int(np.flatnonzero(A.loc[moving, 'globalIdx'].to_numpy() == from_idx)[0])
357
+ fixed = A.loc[~moving, ['posX', 'posY', 'posZ']].to_numpy(dtype=float)
358
+ anchor = A.loc[A['globalIdx'] == at_idx, ['posX', 'posY', 'posZ']].to_numpy(dtype=float)[0]
359
+ placed, clearance = place_group(group, attach, anchor, fixed, bond_length)
360
+ A.loc[moving, ['posX', 'posY', 'posZ']] = placed
361
+ logger.debug(f'{self.name}: placed residues {from_resids} for addition at {at_idx}-{from_idx}, '
362
+ f'clearance {clearance:.3f} nm')
363
+ return clearance
364
+
365
+ def close_ring_geometry(self, pairdf, target=0.15, nstages=8, kb=300000.0, deffnm=''):
366
+ """Pulls the atoms of a ring-closing bond together before the bond is formed.
367
+
368
+ A spanning bond positions the piece it attaches, so its two atoms end up a
369
+ bond length apart. A closing bond gets no such chance -- by the time it is
370
+ reached, both of its residues are already placed -- so its atoms are typically
371
+ several angstroms apart, and forming the bond there hands AmberTools a
372
+ geometry with a ring that does not close.
373
+
374
+ So the ring is pulled shut first. The merged topology of the reactants is
375
+ valid for MD as it stands, and a type-6 restraint needs no atom types, so the
376
+ pair can be walked in by minimization under a restraint whose equilibrium
377
+ length is stepped down to a bond length. This is the same mechanism as
378
+ CURE's drag, at the scale of one template.
379
+
380
+ Args:
381
+ pairdf (pandas.DataFrame): the closing pairs, with ai, aj and initial_distance
382
+ target (float): restraint length of the last stage, in nm, defaults to 0.15
383
+ nstages (int): how many stages to step down over, defaults to 8
384
+ kb (float): restraint stiffness, in kJ/mol/nm^2, defaults to 300000
385
+ deffnm (str): output basename, defaults to '<name>-ringclose'
386
+
387
+ Returns:
388
+ pandas.DataFrame: the pairs, with a final_distance column
389
+ """
390
+ TC = self.TopoCoord
391
+ deffnm = deffnm or f'{self.name}-ringclose'
392
+ work = pairdf.copy().reset_index(drop=True)
393
+ if work['initial_distance'].isna().any():
394
+ raise ValueError(f'{self.name}: ring-closing pair with no initial distance; '
395
+ f'the pair frame and its lengths are misaligned')
396
+ logger.info(f'{self.name}: closing {work.shape[0]} ring bond(s) from '
397
+ f'{work["initial_distance"].max():.3f} nm over {nstages} stages')
398
+ TC.Topology.add_restraints(work, typ=6)
399
+ mdp_prefix = 'single-molecule-min'
400
+ pfs.checkout(pfs.Dirs.mdp_file(mdp_prefix))
401
+ for stage in range(nstages):
402
+ # a prescribed ladder, not attenuate_bond_parameters: see
403
+ # Topology.set_restraint_parameters for why that compounds here
404
+ frac = (stage + 1) / nstages
405
+ lengths = work['initial_distance'] + frac * (target - work['initial_distance'])
406
+ TC.Topology.set_restraint_parameters(work, lengths, kb)
407
+ boxsize = np.array(TC.maxspan()) + 5 * np.ones(3)
408
+ TC.center_coords(new_boxsize=boxsize)
409
+ # the merged product has no files of its own yet, and grompp_and_mdrun runs
410
+ # from what is on disk; the restraints change every stage, so write both
411
+ TC.write_top(f'{deffnm}.top')
412
+ TC.write_gro(f'{deffnm}.gro')
413
+ # grompp_and_mdrun copies the new coordinates back itself, which preserves
414
+ # the extended per-atom attributes that read_gro would drop
415
+ TC.grompp_and_mdrun(out=f'{deffnm}-{stage + 1}', mdp=mdp_prefix, boxSize=boxsize,
416
+ single_molecule=True, wrap_coords=False)
417
+ TC.add_length_attribute(work, attr_name='current_distance')
418
+ logger.debug(f'{self.name}: ring-close stage {stage + 1}/{nstages} '
419
+ f'max {work["current_distance"].max():.3f} nm')
420
+ TC.Topology.remove_restraints(work)
421
+ TC.add_length_attribute(work, attr_name='final_distance')
422
+ worst = work['final_distance'].max()
423
+ logger.info(f'{self.name}: ring closed to {worst:.3f} nm (target {target:.3f})')
424
+ if worst > 2.0 * target:
425
+ logger.warning(f'{self.name}: a ring-closing pair is still {worst:.3f} nm apart after '
426
+ f'{nstages} stages, against a target of {target:.3f} nm; the template '
427
+ f'geometry handed to AmberTools may not close')
428
+ return work
429
+
355
430
  def minimize(self, outname=''):
356
431
  """Manages invocation of vacuum minimization.
357
432
 
@@ -515,27 +590,22 @@ class Molecule:
515
590
  self.bond_templates = []
516
591
  TC = self.TopoCoord
517
592
  # logger.debug(f'prepare_new_bonds {self.name}: chainlists {TC.idx_lists["bondchain"]}')
593
+ # Each reactant's residues occupy a contiguous block of the product, in the
594
+ # order Molecule.generate merged them, which is the order of R.reactants. So
595
+ # a reactant's resid offset is the total length of the reactants before it.
596
+ # Computed over ALL reactants, not just the two a given bond joins: with three
597
+ # or more, a bond between the first and third needs the second counted too.
598
+ resid_offset, product_sequence = {}, []
599
+ for key, rname in R.reactants.items():
600
+ resid_offset[key] = len(product_sequence)
601
+ product_sequence.extend(available_molecules[rname].sequence)
518
602
  for bondrec in R.bonds:
519
603
  atom_keys = bondrec['atoms']
520
604
  order = bondrec['order']
521
605
  assert len(atom_keys) == 2
522
606
  atomrecs = [R.atoms[x] for x in atom_keys]
523
607
  atom_names = [x['atom'] for x in atomrecs]
524
- reactant_keys = [x['reactant'] for x in atomrecs]
525
- in_reactant_resids = [x['resid'] for x in atomrecs]
526
- if reactant_keys[0] == reactant_keys[1]: # this is an intraresidue bond
527
- reactant_names = [R.reactants[reactant_keys[0]]]
528
- else:
529
- reactant_names = [R.reactants[x] for x in reactant_keys]
530
- reactant_sequences = [available_molecules[x].sequence for x in reactant_names]
531
- product_sequence = []
532
- for seq in reactant_sequences:
533
- product_sequence.extend(seq)
534
- # logger.debug(f'product_sequence {product_sequence}')
535
- sequence_residue_idx_origins = [0, 0]
536
- if len(reactant_sequences) == 2:
537
- sequence_residue_idx_origins[1] = len(reactant_sequences[0])
538
- in_product_resids = [in_reactant_resids[x] + sequence_residue_idx_origins[x] for x in [0, 1]]
608
+ in_product_resids = [x['resid'] + resid_offset[x['reactant']] for x in atomrecs]
539
609
  # logger.debug(f'in_product_resids {in_product_resids}')
540
610
  in_product_resnames = [product_sequence[in_product_resids[x] - 1] for x in [0, 1]]
541
611
  atom_idx = [TC.get_gro_attribute_by_attributes('globalIdx', {'resNum': in_product_resids[x], 'atomName': atom_names[x]}) for x in [0, 1]]
@@ -806,13 +876,39 @@ class Molecule:
806
876
  """
807
877
  TC = self.TopoCoord
808
878
  explicit_sacrificial_Hs = {}
879
+ # A closing bond's two residues are already placed by the bonds before it, so
880
+ # there is nothing to position and transrot must not run; its geometry is
881
+ # handled separately (see ROADMAP: ring closure). bdf rows are in R.bonds
882
+ # order, which is what spanning_and_closing_bonds indexes.
883
+ closing = set(spanning_and_closing_bonds(self.generator)[1]) if self.generator else set()
809
884
  for i, r in bdf.iterrows():
810
885
  aname, bname = [TC.get_gro_attribute_by_attributes('atomName', {'globalIdx': x}) for x in [r.ai, r.rj]]
811
886
  logger.debug(f'generating {self.name} bond {r.ri}:{aname}:{r.ai}-{r.rj}:{bname}:{r.aj} order {r.order}')
812
- if r.ri != r.rj:
887
+ keeps_h = self.generator is not None and not consumes_sacrificial_h(self.generator.bonds[i])
888
+ if keeps_h:
889
+ # an addition: nothing is lost, so no hydrogen is offered up
890
+ explicit_sacrificial_Hs[i] = []
891
+ if r.ri != r.rj and i not in closing:
813
892
  resid_sets = TC.get_resid_sets([r.ai, r.aj])
814
- hxi, hxj = self.transrot(r.ai, r.ri, r.aj, r.rj, connected_resids=resid_sets[1])
815
- explicit_sacrificial_Hs[i] = [hxi, hxj]
893
+ if keeps_h:
894
+ # an addition has no hydrogens to align on; place the piece instead
895
+ self.place_for_addition(r.ai, r.aj, [r.rj] + list(resid_sets[1]))
896
+ else:
897
+ hxi, hxj = self.transrot(r.ai, r.ri, r.aj, r.rj, connected_resids=resid_sets[1])
898
+ explicit_sacrificial_Hs[i] = [hxi, hxj]
899
+ if closing:
900
+ # Every piece is placed now, so the ring can be pulled shut before any of
901
+ # its bonds exist -- see close_ring_geometry. Restrain EVERY pair of the
902
+ # ring, not only the closing one: none of these bonds exists yet, so a
903
+ # ladder on one pair alone lets the other pieces drift apart while it
904
+ # pulls, and the ring never takes shape.
905
+ # A merged product has no box yet, and distances are measured under the
906
+ # minimum image convention, which divides by the box vectors -- so measure
907
+ # nothing until there is one.
908
+ TC.center_coords(new_boxsize=np.array(TC.maxspan()) + 5 * np.ones(3))
909
+ ring = bdf[bdf['ri'] != bdf['rj']][['ai', 'aj']].copy().reset_index(drop=True)
910
+ TC.add_length_attribute(ring, attr_name='initial_distance')
911
+ self.close_ring_geometry(ring)
816
912
  if stage in [reaction_stage.cure, reaction_stage.param, reaction_stage.cap, reaction_stage.repair]:
817
913
  template_source = 'ambertools'
818
914
  else:
@@ -18,6 +18,7 @@ libraries keep working rather than silently re-parameterizing wholesale.
18
18
  Author: Cameron F. Abrams <cfa22@drexel.edu>
19
19
  """
20
20
  import hashlib
21
+ import re
21
22
  import json
22
23
  import logging
23
24
  import os
@@ -34,6 +35,15 @@ _KEY_FIELDS = (
34
35
  )
35
36
  """Fields that determine the parameters, with human-readable labels."""
36
37
 
38
+ VERSION_FIELD = 'ambertools_version'
39
+ """Record field holding the AmberTools version that produced the parameters.
40
+
41
+ The same directives give different numbers under different AmberTools
42
+ releases, and htpolynet's CPU and CUDA images have not always shipped the same
43
+ one. Compared only when both the record and the current run know it, so
44
+ records written before it existed, or runs that cannot tell, still match.
45
+ """
46
+
37
47
  FRCMOD_FIELD = 'frcmod'
38
48
  """Record field holding a digest of the user frcmod files loaded after parmchk2's.
39
49
 
@@ -59,7 +69,19 @@ def frcmod_digest(frcmods):
59
69
  return h.hexdigest()[:16]
60
70
 
61
71
 
62
- def build_key(ambertools=None):
72
+ def ambertools_version():
73
+ """Returns the AmberTools version of the running installation, or None if unknown.
74
+
75
+ Returns:
76
+ str or None: version string, e.g. '26.0'
77
+ """
78
+ from ..external import software
79
+ v = software.versions.get('ambertools', '')
80
+ m = re.search(r'ver\.\s*([0-9][0-9A-Za-z.\-]*)', v or '')
81
+ return m.group(1) if m else None
82
+
83
+
84
+ def build_key(ambertools=None, version='detect'):
63
85
  """Returns the provenance record describing a parameterization run under
64
86
  the given AmberTools directives.
65
87
 
@@ -68,6 +90,8 @@ def build_key(ambertools=None):
68
90
 
69
91
  Args:
70
92
  ambertools (dict, optional): ambertools configuration directives
93
+ version (str, optional): AmberTools version to record; 'detect' (the default) asks the
94
+ running installation, and None records none
71
95
 
72
96
  Returns:
73
97
  dict: provenance record
@@ -79,6 +103,10 @@ def build_key(ambertools=None):
79
103
  digest = frcmod_digest(ambertools.get(FRCMOD_FIELD))
80
104
  if digest:
81
105
  key[FRCMOD_FIELD] = digest
106
+ if version == 'detect':
107
+ version = ambertools_version()
108
+ if version:
109
+ key[VERSION_FIELD] = version
82
110
  return key
83
111
 
84
112
 
@@ -158,6 +186,9 @@ def describe_mismatch(stored, requested):
158
186
  continue
159
187
  if stored[field] != requested.get(field):
160
188
  diffs.append(f'{label} {stored[field]!r} cached, {requested.get(field)!r} requested')
189
+ stored_v, requested_v = stored.get(VERSION_FIELD), requested.get(VERSION_FIELD)
190
+ if stored_v and requested_v and stored_v != requested_v:
191
+ diffs.append(f'AmberTools {stored_v} cached, {requested_v} running')
161
192
  # unlike the fields above, an absent frcmod digest is a statement: none was loaded
162
193
  if stored.get(FRCMOD_FIELD) != requested.get(FRCMOD_FIELD):
163
194
  diffs.append(f'user frcmod {stored.get(FRCMOD_FIELD) or "none"} cached, '
@@ -0,0 +1,266 @@
1
+ """Splices a whole product template onto the residues of one reaction event.
2
+
3
+ ``TopoCoord.map_from_templates`` works one bond at a time: it identifies each new
4
+ bond by its local context, then copies the interactions that contain that bond from
5
+ whichever template matches. That is right for a reaction that forms one bond between
6
+ two reactants, and it cannot form a ring.
7
+
8
+ A cyclotrimerization bonds three cyanate groups 1-2, 2-3 and 3-1. In the trimer
9
+ template all three ring bonds exist; in the system, partway through the batch, only
10
+ some do. So the bond-by-bond context of an instance bond never matches the
11
+ template's, in either direction, and the per-bond path cannot be made to work by
12
+ ordering the bonds differently.
13
+
14
+ This module takes the other route: given the participating residues, make the mapped
15
+ region of the system match the template exactly -- atom types, charges, and every
16
+ bonded interaction among those residues. The caller says which residues correspond
17
+ to which template residues, so no context matching is needed at all.
18
+
19
+ Author: Cameron F. Abrams <cfa22@drexel.edu>
20
+ """
21
+ import logging
22
+
23
+ import networkx as nx
24
+ import numpy as np
25
+ import pandas as pd
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ _SECTIONS_ = ('bonds', 'angles', 'dihedrals', 'pairs')
30
+ """Interaction sections copied from the template, in the order they are applied."""
31
+
32
+ _ATOM_COLUMNS_ = {'bonds': ('ai', 'aj'), 'angles': ('ai', 'aj', 'ak'),
33
+ 'dihedrals': ('ai', 'aj', 'ak', 'al'), 'pairs': ('ai', 'aj')}
34
+
35
+
36
+ def _key(section, row):
37
+ """Returns a direction-independent key for one interaction row.
38
+
39
+ Bonds and pairs are unordered; an angle is the same read either way, so its end
40
+ atoms are sorted with the apex held; a dihedral is the same read either way.
41
+ """
42
+ idx = tuple(int(row[c]) for c in _ATOM_COLUMNS_[section])
43
+ if section == 'angles':
44
+ i, j, k = idx
45
+ return (min(i, k), j, max(i, k))
46
+ return min(idx, idx[::-1])
47
+
48
+
49
+ def _keys_of(section, df):
50
+ """Returns the set of keys present in an interaction dataframe."""
51
+ if df is None or df.empty:
52
+ return set()
53
+ return {_key(section, r) for _, r in df.iterrows()}
54
+
55
+
56
+ def nearer_site_atoms(template, resnr, home, other):
57
+ """Names of one residue's atoms that belong to one reactive site rather than another.
58
+
59
+ A monomer with two reactive sites -- a dicyanate's two cyanate arms -- can join two
60
+ different rings, and a template shows only one of them reacted. Splicing the whole
61
+ residue from it would reset the other arm to unreacted types, undoing an earlier
62
+ ring. So each atom is assigned to whichever site is closer through the residue's
63
+ own bonds, and only the reacting site's share is spliced.
64
+
65
+ Args:
66
+ template (Molecule): the product template
67
+ resnr (int): which of its residues to partition
68
+ home (iterable): atom names of the site the template reacted
69
+ other (iterable): atom names of the site it did not
70
+
71
+ Returns:
72
+ set: names of the atoms nearer the home site, ties included
73
+ """
74
+ T = template.TopoCoord.Topology
75
+ at = T.D['atoms']
76
+ mine = at[at['resnr'] == resnr]
77
+ idx = set(int(x) for x in mine['nr'])
78
+ name = dict(zip(mine['nr'].astype(int), mine['atom']))
79
+ g = nx.Graph()
80
+ g.add_nodes_from(idx)
81
+ for r in T.D['bonds'].itertuples():
82
+ i, j = int(r.ai), int(r.aj)
83
+ if i in idx and j in idx:
84
+ g.add_edge(i, j)
85
+ by_name = {v: k for k, v in name.items()}
86
+
87
+ def spread(seeds):
88
+ d = {}
89
+ for s in seeds:
90
+ if s not in by_name:
91
+ continue
92
+ for node, dist in nx.single_source_shortest_path_length(g, by_name[s]).items():
93
+ d[node] = min(d.get(node, dist), dist)
94
+ return d
95
+
96
+ dh, do = spread(home), spread(other)
97
+ return {name[n] for n in idx if dh.get(n, np.inf) <= do.get(n, np.inf)}
98
+
99
+
100
+ def atom_map(instance_atoms, template_atoms, resid_map, name_maps=None, atom_names=None):
101
+ """Maps template atoms to instance atoms, residue by residue, on atom name.
102
+
103
+ A residue may react through a different equivalent site than the template shows.
104
+ A bisphenol dicyanate has two cyanate arms, and the trimer template is built with
105
+ one of them reacted; a residue that rings through the other needs the template's
106
+ names translated onto its own, or the reacted arm's parameters would land on the
107
+ arm that is still free. ``name_maps`` carries that translation, and comes from
108
+ the constituent's ``symmetry_equivalent_atoms``.
109
+
110
+ Args:
111
+ instance_atoms (pandas.DataFrame): the system's [ atoms ], with nr, atom, resnr
112
+ template_atoms (pandas.DataFrame): the template's [ atoms ], same columns
113
+ resid_map (dict): {template resnr: instance resnr} for every participating residue
114
+ name_maps (dict): {template resnr: {template atom name: instance atom name}},
115
+ for residues reacting through a site other than the template's
116
+ atom_names (set): template atom names to map, for splicing one reactive site's
117
+ share of a residue rather than all of it; None maps everything
118
+
119
+ Returns:
120
+ tuple: (temp2inst, unmapped) -- the mapping, and the template atom numbers that
121
+ have no instance counterpart
122
+ """
123
+ temp2inst = {}
124
+ name_maps = name_maps or {}
125
+ for t_res, i_res in resid_map.items():
126
+ t = template_atoms[template_atoms['resnr'] == t_res][['nr', 'atom']].copy()
127
+ if atom_names is not None:
128
+ t = t[t['atom'].isin(atom_names)]
129
+ translate = name_maps.get(t_res)
130
+ if translate:
131
+ t['atom'] = [translate.get(a, a) for a in t['atom']]
132
+ i = instance_atoms[instance_atoms['resnr'] == i_res][['nr', 'atom']]
133
+ merged = t.merge(i, on='atom', how='left', suffixes=('_t', '_i'))
134
+ for _, r in merged.iterrows():
135
+ if pd.notna(r['nr_i']):
136
+ temp2inst[int(r['nr_t'])] = int(r['nr_i'])
137
+ mapped_t = set(temp2inst)
138
+ wanted = template_atoms[template_atoms['resnr'].isin(resid_map)]
139
+ if atom_names is not None:
140
+ wanted = wanted[wanted['atom'].isin(atom_names)]
141
+ unmapped = [int(x) for x in wanted['nr'] if int(x) not in mapped_t]
142
+ return temp2inst, unmapped
143
+
144
+
145
+ def map_product_from_template(TC, template, resid_map, new_bonds=(), strict=True, name_maps=None,
146
+ atom_names=None):
147
+ """Makes the mapped residues of TC match a product template exactly.
148
+
149
+ Copies atom types and charges for every mapped atom, and every bond, angle,
150
+ dihedral and 1-4 pair of the template whose atoms are all mapped -- replacing the
151
+ instance's own parameters where they exist and adding them where they do not.
152
+ That is what a ring closure needs: the interactions it changes include ones
153
+ wholly inside a residue (a cyanate C#N becoming a ring bond), which a per-bond
154
+ splice never touches.
155
+
156
+ The caller is responsible for creating the new bonds themselves (and for any
157
+ sacrificial-atom deletion) before calling this, exactly as with
158
+ ``map_from_templates``, and for settling the system charge afterwards -- the
159
+ touched atoms are returned for that purpose.
160
+
161
+ Args:
162
+ TC (TopoCoord): the system
163
+ template (Molecule): the product template
164
+ resid_map (dict): {template resnr: instance resnr} for every participating residue
165
+ new_bonds (iterable): (ai, aj) instance pairs formed for this event, checked against
166
+ the template
167
+ strict (bool): raise when the template and instance disagree about which bonds
168
+ exist among the mapped residues; defaults to True
169
+ name_maps (dict): per-residue atom-name translation, for a residue reacting
170
+ through a site other than the one the template shows; see :func:`atom_map`
171
+ atom_names (set): template atom names to splice, for a monomer with more than one
172
+ reactive site; see :func:`nearer_site_atoms`
173
+
174
+ Returns:
175
+ dict: ``atoms`` (instance atom numbers touched), ``types`` and ``charges``
176
+ (how many changed), ``added`` and ``replaced`` (per section), and
177
+ ``unmapped`` (template atoms with no counterpart)
178
+
179
+ Raises:
180
+ ValueError: if a new bond has no counterpart in the template, or, under
181
+ strict, if a template bond among mapped residues is missing from the
182
+ instance
183
+ """
184
+ inst_top, temp_top = TC.Topology, template.TopoCoord.Topology
185
+ # The template's interactions are written in terms of its atom types, and a system
186
+ # built from unreacted monomers has never seen the ones a closed ring introduces
187
+ # (aromatic carbon and nitrogen, here). Without their type tables the new bonds
188
+ # have no parameters to resolve and grompp refuses the topology. merge_types drops
189
+ # duplicates, so this is idempotent across rings and iterations.
190
+ inst_top.merge_types(temp_top)
191
+ temp2inst, unmapped = atom_map(inst_top.D['atoms'], temp_top.D['atoms'], resid_map,
192
+ name_maps=name_maps, atom_names=atom_names)
193
+ if unmapped:
194
+ logger.debug(f'{len(unmapped)} template atom(s) have no instance counterpart and are skipped')
195
+
196
+ # Every bond the caller formed must be one the template has, or the residue map is
197
+ # wrong and everything below would be quietly misapplied.
198
+ inst2temp = {v: k for k, v in temp2inst.items()}
199
+ temp_bond_keys = _keys_of('bonds', temp_top.D.get('bonds'))
200
+ for ai, aj in new_bonds:
201
+ t = (inst2temp.get(int(ai)), inst2temp.get(int(aj)))
202
+ if None in t or min(t, t[::-1]) not in temp_bond_keys:
203
+ raise ValueError(f'new bond {ai}-{aj} maps to {t}, which is not a bond of template '
204
+ f'{template.name}; the residue map is wrong')
205
+
206
+ stats = {'atoms': sorted(temp2inst.values()), 'types': 0, 'charges': 0,
207
+ 'added': {}, 'replaced': {}, 'unmapped': unmapped}
208
+
209
+ # types and charges, atom by atom
210
+ iat, tat = inst_top.D['atoms'], temp_top.D['atoms']
211
+ t_by_nr = tat.set_index('nr')
212
+ for t_nr, i_nr in temp2inst.items():
213
+ t_row = t_by_nr.loc[t_nr]
214
+ mask = iat['nr'] == i_nr
215
+ if iat.loc[mask, 'type'].iloc[0] != t_row['type']:
216
+ iat.loc[mask, 'type'] = t_row['type']
217
+ stats['types'] += 1
218
+ if iat.loc[mask, 'charge'].iloc[0] != t_row['charge']:
219
+ iat.loc[mask, 'charge'] = float(t_row['charge'])
220
+ stats['charges'] += 1
221
+
222
+ for section in _SECTIONS_:
223
+ t_df = temp_top.D.get(section)
224
+ if t_df is None or t_df.empty:
225
+ continue
226
+ cols = _ATOM_COLUMNS_[section]
227
+ keep = t_df[[all(int(r[c]) in temp2inst for c in cols) for _, r in t_df.iterrows()]]
228
+ if keep.empty:
229
+ continue
230
+ mapped = keep.copy()
231
+ for c in cols:
232
+ mapped[c] = [temp2inst[int(x)] for x in keep[c]]
233
+ i_df = inst_top.D.get(section)
234
+ existing = _keys_of(section, i_df)
235
+ new_keys = {_key(section, r) for _, r in mapped.iterrows()}
236
+ if section == 'bonds':
237
+ missing = new_keys - existing
238
+ if missing and strict:
239
+ raise ValueError(f'template {template.name} has {len(missing)} bond(s) among the mapped '
240
+ f'residues that the instance does not: {sorted(missing)[:4]}. Form the '
241
+ f'reaction bonds before splicing, or fix the residue map.')
242
+ # replace the instance's own version of every interaction the template covers
243
+ if i_df is not None and not i_df.empty:
244
+ drop = [_key(section, r) in new_keys for _, r in i_df.iterrows()]
245
+ stats['replaced'][section] = int(sum(drop)) if any(drop) else 0
246
+ inst_top.D[section] = pd.concat([i_df[[not d for d in drop]], mapped], ignore_index=True)
247
+ else:
248
+ stats['replaced'][section] = 0
249
+ inst_top.D[section] = mapped.reset_index(drop=True)
250
+ stats['added'][section] = len(new_keys) - stats['replaced'][section]
251
+
252
+ # pandas upcasts an int column to float wherever a concat had to align frames, and
253
+ # the topology writer and delete_atoms both assert int atom indices
254
+ for section in _SECTIONS_:
255
+ df = inst_top.D.get(section)
256
+ if df is None or df.empty:
257
+ continue
258
+ for c in _ATOM_COLUMNS_[section] + ('funct',):
259
+ if c in df.columns:
260
+ df[c] = df[c].astype(int)
261
+ if 'bonds' in inst_top.D:
262
+ from ..geometry.bondlist import Bondlist
263
+ inst_top.bondlist = Bondlist.fromDataFrame(inst_top.D['bonds'])
264
+ logger.debug(f'product splice from {template.name}: {stats["types"]} type(s) and '
265
+ f'{stats["charges"]} charge(s) changed, added {stats["added"]}, replaced {stats["replaced"]}')
266
+ return stats