HTPolyNet 1.0.7.2__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.
Files changed (93) hide show
  1. HTPolyNet/__init__.py +1 -0
  2. HTPolyNet/ambertools.py +94 -0
  3. HTPolyNet/analyze.py +258 -0
  4. HTPolyNet/banner.py +26 -0
  5. HTPolyNet/bondlist.py +206 -0
  6. HTPolyNet/bondtemplate.py +111 -0
  7. HTPolyNet/checkpoint.py +88 -0
  8. HTPolyNet/command.py +42 -0
  9. HTPolyNet/configuration.py +240 -0
  10. HTPolyNet/coordinates.py +1071 -0
  11. HTPolyNet/countTime.py +26 -0
  12. HTPolyNet/curecontroller.py +767 -0
  13. HTPolyNet/dataframetools.py +130 -0
  14. HTPolyNet/driver.py +250 -0
  15. HTPolyNet/expandreactions.py +154 -0
  16. HTPolyNet/gromacs.py +333 -0
  17. HTPolyNet/inputcheck.py +51 -0
  18. HTPolyNet/linkcell.py +322 -0
  19. HTPolyNet/molecule.py +1279 -0
  20. HTPolyNet/plot.py +607 -0
  21. HTPolyNet/postsim.py +444 -0
  22. HTPolyNet/projectfilesystem.py +483 -0
  23. HTPolyNet/reaction.py +282 -0
  24. HTPolyNet/resources/README.md +20 -0
  25. HTPolyNet/resources/__init__.py +0 -0
  26. HTPolyNet/resources/cfg/DGE-PAC-hi.yaml +115 -0
  27. HTPolyNet/resources/cfg/DGE-PAC-lo.yaml +115 -0
  28. HTPolyNet/resources/cfg/FDE-DFDA-hi.yaml +116 -0
  29. HTPolyNet/resources/cfg/FDE-DFDA-lo.yaml +116 -0
  30. HTPolyNet/resources/cfg/GMASTY-hi.yaml +158 -0
  31. HTPolyNet/resources/cfg/GMASTY-lo.yaml +158 -0
  32. HTPolyNet/resources/cfg/README.md +1 -0
  33. HTPolyNet/resources/cfg/STY.yaml +23 -0
  34. HTPolyNet/resources/cfg/pMSTY-hi.yaml +101 -0
  35. HTPolyNet/resources/cfg/pMSTY-lo.yaml +101 -0
  36. HTPolyNet/resources/cfg/pSTY-hi.yaml +101 -0
  37. HTPolyNet/resources/cfg/pSTY-lo.yaml +101 -0
  38. HTPolyNet/resources/example_depot/0-liquid-styrene.tgz +0 -0
  39. HTPolyNet/resources/example_depot/1-polystyrene.tgz +0 -0
  40. HTPolyNet/resources/example_depot/2-polymethylstyrene.tgz +0 -0
  41. HTPolyNet/resources/example_depot/3-bisgma-styrene-thermoset.tgz +0 -0
  42. HTPolyNet/resources/example_depot/4-pacm-dgeba-epoxy-thermoset.tgz +0 -0
  43. HTPolyNet/resources/example_depot/5-dfda-fde-epoxy-thermoset.tgz +0 -0
  44. HTPolyNet/resources/mdp/README.md +1 -0
  45. HTPolyNet/resources/mdp/drag-min.mdp +13 -0
  46. HTPolyNet/resources/mdp/drag-npt.mdp +36 -0
  47. HTPolyNet/resources/mdp/drag-nvt.mdp +31 -0
  48. HTPolyNet/resources/mdp/min.mdp +14 -0
  49. HTPolyNet/resources/mdp/npt.mdp +37 -0
  50. HTPolyNet/resources/mdp/nvt.mdp +29 -0
  51. HTPolyNet/resources/mdp/relax-min.mdp +13 -0
  52. HTPolyNet/resources/mdp/relax-npt.mdp +37 -0
  53. HTPolyNet/resources/mdp/relax-nvt.mdp +31 -0
  54. HTPolyNet/resources/mdp/single-molecule-min.mdp +12 -0
  55. HTPolyNet/resources/mdp/single-molecule-nvt.mdp +25 -0
  56. HTPolyNet/resources/molecules/inputs/DFA.pdb +62 -0
  57. HTPolyNet/resources/molecules/inputs/DGE.mol2 +115 -0
  58. HTPolyNet/resources/molecules/inputs/EMB.mol2 +50 -0
  59. HTPolyNet/resources/molecules/inputs/FDE.pdb +72 -0
  60. HTPolyNet/resources/molecules/inputs/GMA.mol2 +163 -0
  61. HTPolyNet/resources/molecules/inputs/PAC.mol2 +91 -0
  62. HTPolyNet/resources/molecules/inputs/STY.mol2 +44 -0
  63. HTPolyNet/resources/molecules/make-monomers.sh +64 -0
  64. HTPolyNet/resources/molecules/pics/DFA.png +0 -0
  65. HTPolyNet/resources/molecules/pics/DGE.png +0 -0
  66. HTPolyNet/resources/molecules/pics/EMB.png +0 -0
  67. HTPolyNet/resources/molecules/pics/FDE.png +0 -0
  68. HTPolyNet/resources/molecules/pics/GMA.png +0 -0
  69. HTPolyNet/resources/molecules/pics/PAC.png +0 -0
  70. HTPolyNet/resources/molecules/pics/STY.png +0 -0
  71. HTPolyNet/resources/molecules/sample-inputs/DFA.pdb +62 -0
  72. HTPolyNet/resources/molecules/sample-inputs/DGE.mol2 +115 -0
  73. HTPolyNet/resources/molecules/sample-inputs/EMB.mol2 +50 -0
  74. HTPolyNet/resources/molecules/sample-inputs/FDE.pdb +72 -0
  75. HTPolyNet/resources/molecules/sample-inputs/GMA.mol2 +163 -0
  76. HTPolyNet/resources/molecules/sample-inputs/PAC.mol2 +91 -0
  77. HTPolyNet/resources/molecules/sample-inputs/STY.mol2 +44 -0
  78. HTPolyNet/resources/tcl/readbonds.tcl +32 -0
  79. HTPolyNet/resources/tcl/readgrx.tcl +46 -0
  80. HTPolyNet/resources/tcl/render.tcl +74 -0
  81. HTPolyNet/ring.py +155 -0
  82. HTPolyNet/runtime.py +709 -0
  83. HTPolyNet/software.py +106 -0
  84. HTPolyNet/stringthings.py +39 -0
  85. HTPolyNet/topocoord.py +1877 -0
  86. HTPolyNet/topology.py +1288 -0
  87. HTPolyNet/unused_symmetry_stuff.py +291 -0
  88. HTPolyNet/utils.py +405 -0
  89. htpolynet-1.0.7.2.dist-info/METADATA +84 -0
  90. htpolynet-1.0.7.2.dist-info/RECORD +93 -0
  91. htpolynet-1.0.7.2.dist-info/WHEEL +4 -0
  92. htpolynet-1.0.7.2.dist-info/entry_points.txt +2 -0
  93. htpolynet-1.0.7.2.dist-info/licenses/LICENSE +21 -0
HTPolyNet/topology.py ADDED
@@ -0,0 +1,1288 @@
1
+ """
2
+
3
+ .. module:: topology
4
+ :synopsis: Class for managing gromacs .top file data
5
+
6
+ .. moduleauthor: Cameron F. Abrams, <cfa22@drexel.edu>
7
+
8
+ """
9
+ import logging
10
+ import json
11
+ import os
12
+ import pandas as pd
13
+ import numpy as np
14
+ import networkx as nx
15
+ from scipy.constants import physical_constants
16
+ from networkx.readwrite import json_graph
17
+ from itertools import product
18
+ from HTPolyNet.bondlist import Bondlist
19
+
20
+ logger=logging.getLogger(__name__)
21
+
22
+ def typeorder(a):
23
+ """typeorder correctly order the tuple of atom types for particular
24
+ interaction types to maintain sorted type dataframes
25
+
26
+ :param a: tuple of atom indicies/types from a [ bond ], [ pair ], [ angle ], or [ dihedral ] record
27
+ :type a: tuple
28
+ :return: same atom indices/types correctly ordered to allow for easy searching/sorting
29
+ :rtype: tuple
30
+ """
31
+ assert type(a)==tuple, 'error: typeorder() requires a tuple argument'
32
+ if len(a)==2: # bond
33
+ return a if a[0]<a[1] else a[::-1]
34
+ elif len(a)==3: # angle
35
+ return a if a[0]<a[2] else a[::-1]
36
+ elif len(a)==4: # dihedral
37
+ if a[1]==a[2]:
38
+ return a if a[0]<a[3] else a[::-1]
39
+ return a if a[1]<a[2] else a[::-1]
40
+ idxorder=typeorder # same syntax to order global atom indices in an interaction index
41
+
42
+ def repeat_check(t,msg=''):
43
+ """repeat_check Check for repeated index tuples
44
+
45
+ :param t: list of index tuples
46
+ :type t: list
47
+ :param msg: optional message, defaults to ''
48
+ :type msg: str, optional
49
+ """
50
+ for i in range(len(t)):
51
+ for j in range(i+1,len(t)):
52
+ assert t[i]!=t[j],f'Error: repeated index in {len(t)}-tuple {t}: t({i})={t[i]}\n{msg}'
53
+
54
+ def df_typeorder(df,typs):
55
+ """df_typeorder type-orders the atom type attributes in each row of dataframe df
56
+
57
+ :param df: a Topology type-directive dataframe; [ atomtypes ], [ bondtypes ], etc.
58
+ :type df: pandas.DataFrame
59
+ :param typs: list of type-attribute names; typically ['i','j',...]
60
+ :type typs: list
61
+ """
62
+ for i in df.index:
63
+ df.loc[i,typs]=typeorder(tuple(df.loc[i,typs]))
64
+
65
+ def treadmill(L):
66
+ """treadmill Move first element of list L to end and return new list
67
+
68
+ :param L: a list
69
+ :type L: list
70
+ :return: a new list
71
+ :rtype: list
72
+ """
73
+ nL=L[1:]
74
+ nL.append(L[0])
75
+ return nL
76
+
77
+ def treadmills(L):
78
+ """treadmills perform one complete cycle of treadmilling increments and store each increment as its own list and return list of such lists
79
+
80
+ :param L: a list
81
+ :type L: list
82
+ :return: list of new lists, each a treadmill increment of passed-in list
83
+ :rtype: list of lists
84
+ """
85
+ N=len(L)
86
+ nL=L
87
+ r=[]
88
+ for i in range(1,N):
89
+ nnL=treadmill(nL)
90
+ r.append(nnL)
91
+ nL=nnL
92
+ return r
93
+
94
+ def _get_unique_cycles_dict(G,min_length=-1):
95
+ """_get_unique_cycles_dict generates dictionary identifying all unique covalent cycles from the digraph G
96
+
97
+ :param G: a digraph representing atomic connectivity
98
+ :type G: networkx.DiGraph
99
+ :param min_length: minimum length cycle length, defaults to -1 (no limit; 3 would be a better choice)
100
+ :type min_length: int, optional
101
+ :return: dictionary of cycles keyed on cycle length with values being lists of lists of indices
102
+ :rtype: dict
103
+ """
104
+ ucycles={}
105
+ counts_by_length={}
106
+ for u in nx.simple_cycles(G):
107
+ sl=len(u)
108
+ if min_length<=sl:
109
+ # logger.debug(f'a cycle {u}')
110
+ if not sl in counts_by_length:
111
+ counts_by_length[sl]=0
112
+ counts_by_length[sl]+=1
113
+ if not sl in ucycles:
114
+ ucycles[sl]=[]
115
+ utl=treadmills(u)
116
+ ur=list(reversed(u))
117
+ urtl=treadmills(ur)
118
+ eqv=utl+[ur]+urtl
119
+ ll=min_length if min_length!=-1 else min(counts_by_length.keys())
120
+ uu=max(counts_by_length.keys())
121
+ for l in range(ll,uu+1):
122
+ if len(u)==l:
123
+ found=False
124
+ for e in eqv:
125
+ if e in ucycles[l]:
126
+ found=True
127
+ break
128
+ if not found:
129
+ ucycles[l].append(u)
130
+ return ucycles
131
+
132
+ def _present_and_contiguous(subL,L):
133
+ """_present_and_contiguous returns True is elements in subL appear as a contiguous sub-block in
134
+ periodic and bidirectional list L
135
+
136
+ :param subL: a sublist
137
+ :type subL: list
138
+ :param L: a list, treated as periodic and bidirectional
139
+ :type L: list
140
+ :return: True if sublist appears as part L
141
+ :rtype: boolean
142
+ """
143
+ pretest=all([x in L for x in subL])
144
+ if not pretest:
145
+ return False
146
+ for A in [L,L[::-1]]:
147
+ T=treadmills(A)
148
+ for t in T:
149
+ testL=t[:len(subL)]
150
+ # logger.debug(f'___ {subL} {testL}')
151
+ if all([x==y for x,y in zip(subL,testL)]):
152
+ return True
153
+ return False
154
+
155
+ _GromacsIntegers_=('nr','atnum','resnr','ai','aj','ak','al','#mols','nrexcl','funct','func','nbfunc','comb-rule')
156
+ _GromacsFloats_=('charge','mass','chargeB','massB',*tuple([f'c{i}' for i in range(5)]),
157
+ 'b0','kb','th0','cth','rub','kub','phase','kd','pn','fudgeLJ','fudgeQQ')
158
+ def typedata(h,s):
159
+ if h in _GromacsIntegers_:
160
+ return int(s)
161
+ if h in _GromacsFloats_:
162
+ return float(s)
163
+ return s
164
+
165
+ _GromacsExtensiveDirectives_=['atoms','pairs','bonds','angles','dihedrals']
166
+ _NonGromacsExtensiveDirectives_=['mol2_bonds']
167
+ _GromacsTopologyDirectiveOrder_=['defaults','atomtypes','bondtypes','angletypes','dihedraltypes','moleculetype','atoms','pairs','bonds','angles','dihedrals','system','molecules']
168
+ _GromacsTopologyDirectiveHeaders_={
169
+ 'atoms':['nr', 'type', 'resnr', 'residue', 'atom', 'cgnr', 'charge', 'mass','typeB', 'chargeB', 'massB'],
170
+ 'pairs':['ai', 'aj', 'funct', 'c0', 'c1'],
171
+ 'bonds':['ai', 'aj', 'funct', 'c0', 'c1'],
172
+ 'angles':['ai', 'aj', 'ak', 'funct', 'c0', 'c1'],
173
+ 'dihedrals':['ai', 'aj', 'ak', 'al', 'funct', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5'],
174
+ 'atomtypes':['name', 'atnum', 'mass', 'charge', 'ptype', 'sigma', 'epsilon'],
175
+ 'moleculetype':['name', 'nrexcl'],
176
+ 'bondtypes':['i','j','func','b0','kb'],
177
+ 'angletypes':['i','j','k','func','th0','cth','rub','kub'],
178
+ 'dihedraltypes':['i','j','k','l','func','phase','kd','pn'],
179
+ 'system':['Name'],
180
+ 'molecules':['Compound','#mols'],
181
+ 'defaults':['nbfunc','comb-rule','gen-pairs','fudgeLJ','fudgeQQ']
182
+ }
183
+
184
+ _GromacsTopologyHashables_={
185
+ 'atoms':['nr'],
186
+ 'pairs':['ai', 'aj'],
187
+ 'bonds':['ai', 'aj'],
188
+ 'angles':['ai', 'aj', 'ak'],
189
+ 'dihedrals':['ai', 'aj', 'ak', 'al',],
190
+ 'atomtypes':['name'],
191
+ 'bondtypes':['i','j'],
192
+ 'angletypes':['i','j','k'],
193
+ 'dihedraltypes':['i','j','k','l']
194
+ }
195
+
196
+ _GromacsTopologyDirectiveDefaults_={
197
+ 'system':['A_generic_system'],
198
+ 'molecules':['None',1],
199
+ 'moleculetype':['None',3],
200
+ 'defaults':[1,2,'yes',0.5,0.83333333]
201
+ }
202
+
203
+ def select_topology_type_option(options,typename='dihedraltypes',rule='stiffest'):
204
+ """select_topology_type_option select from a list of topological interaction options of type typename using the provided rule
205
+
206
+ :param options: list of parameterization options for a particular interaction
207
+ :type options: list
208
+ :param typename: string designation of interaction type, defaults to 'dihedraltypes'
209
+ :type typename: str, optional
210
+ :param rule: string describing the selection rule, defaults to 'stiffest'
211
+ :type rule: str, optional
212
+ :return: the selection parameterization option
213
+ :rtype: element of options (dict)
214
+ """
215
+ hashables=_GromacsTopologyHashables_[typename]
216
+ headers=_GromacsTopologyDirectiveHeaders_[typename].copy()
217
+ for i in hashables:
218
+ headers.remove(i)
219
+ if rule=='stiffest' or rule=='softest':
220
+ if typename=='bondtypes':
221
+ parindex=headers.index('kb')
222
+ elif typename=='angletypes':
223
+ parindex=headers.index('cth')
224
+ elif typename=='dihedraltypes':
225
+ parindex=headers.index('kd')
226
+ sorted_options=list(sorted(options,key=lambda x: x[parindex]))
227
+ if rule=='stiffest':
228
+ return sorted_options[-1]
229
+ elif rule=='softest':
230
+ return sorted_options[0]
231
+ return []
232
+
233
+ class Topology:
234
+ """ Class for handling gromacs top data
235
+ """
236
+ def __init__(self,system_name=''):
237
+ """__init__ Constructor for Topology class
238
+
239
+ :param system_name: optional name of system, defaults to ''
240
+ :type system_name: str, optional
241
+ """
242
+ ''' D: a dictionay keyed on Gromacs topology directives with values that are lists of
243
+ one or more pandas dataframes corresponding to sections '''
244
+ self.D:dict[str:pd.DataFrame]={}
245
+ for k,v in _GromacsTopologyDirectiveDefaults_.items():
246
+ hdr=_GromacsTopologyDirectiveHeaders_[k]
247
+ dfdict={kk:[a] for kk,a in zip(hdr,v)}
248
+ self.D[k]=pd.DataFrame(dfdict)
249
+ self.D['system']=pd.DataFrame({'name':[system_name]})
250
+ ''' bondlist: a class that owns a dictionary keyed on atom global index with values that are lists of global atom indices bound to the key '''
251
+ self.bondlist=Bondlist()
252
+ self.residue_network=nx.DiGraph()
253
+ self.empty=True
254
+
255
+ @classmethod
256
+ def read_gro(cls,filename):
257
+ """read_gro Reads a Gromacs-style topology file 'filename' and returns a dictionary keyed on directive names.
258
+ Each value in the dictionary is a pandas dataframe. Each
259
+ dataframe represents an individual section found with its directive in the file, with columns corresponding to the fields in the section. Note that the we allow for input topology/itp files to have two 'dihedrals' and 'dihedraltypes' sections; these
260
+ are merged in the result.
261
+
262
+ :param filename: name of gromacs top file to read
263
+ :type filename: str
264
+ :raises KeyError: If an unrecognized topology directive is encountered, program exits on error
265
+ :return: a Topology instance
266
+ :rtype: Topology
267
+ """
268
+ assert os.path.exists(filename), f'Error: {filename} not found.'
269
+ inst=cls()
270
+ inst.filename=filename
271
+ dirname=os.path.dirname(filename)
272
+ inst.includes=[]
273
+ with open(filename,'r') as f:
274
+ data=f.read().split('[')
275
+ stanzas=[('['+x).split('\n') for x in data][1:]
276
+ for s in stanzas:
277
+ directive=s[0].split()[1].strip()
278
+ contentlines=[l for l in s[1:] if not (len(l.strip())==0 or l.strip().startswith(';'))]
279
+ if not directive in _GromacsTopologyDirectiveHeaders_:
280
+ raise KeyError(f'unrecognized topology directive "{directive}"')
281
+ header=_GromacsTopologyDirectiveHeaders_[directive]
282
+ series={k:[] for k in header}
283
+ for line in contentlines:
284
+ if line.startswith('#include'):
285
+ tokens=[x.strip() for x in line.split()]
286
+ inst.includes.append(tokens[1].replace('"',''))
287
+ continue
288
+ # ignore anything after a ';'
289
+ line=line.split(';')[0].strip()
290
+ if directive!='system': # no need to split line
291
+ tokens=[x.strip() for x in line.split()]
292
+ else:
293
+ tokens=[line]
294
+ padded=[typedata(k,_) for _,k in zip(tokens,header)]
295
+ # pad with NaN's so that it is same length as series
296
+ for _ in range(len(tokens),len(header)):
297
+ padded.append(pd.NA)
298
+ assert len(padded)==len(header), f'Error: Padding solution does not work! {directive} {len(tokens)}:{len(padded)}!={len(header)} {",".join(tokens)} {",".join(header)}'
299
+ for k,v in zip(header,padded):
300
+ series[k].append(v)
301
+ tdf=pd.DataFrame(series)
302
+ if directive=='dihedraltypes':
303
+ if directive in inst.D:
304
+ # logger.info(f'Found second set of {len(tdf)} [ dihedraltypes ] in {inst.filename}; merging into set of {len(inst.D["dihedraltypes"])} types already read in...')
305
+ # we have already read-in a dihedraltypes section
306
+ # so let's append this one
307
+ inst.D['dihedraltypes']=pd.concat([inst.D['dihedraltypes'],tdf],ignore_index=True).drop_duplicates()
308
+ # logger.info(f' -> now there are {len(inst.D["dihedraltypes"])} dihedral types.')
309
+ else:
310
+ inst.D[directive]=tdf
311
+ elif directive=='dihedrals':
312
+ # if there is already a dihedrals section, assume
313
+ if directive in inst.D:
314
+ inst.D['dihedrals']=pd.concat([inst.D['dihedrals'],tdf],ignore_index=True)
315
+ else:
316
+ inst.D[directive]=tdf
317
+ else:
318
+ inst.D[directive]=tdf
319
+ # we must assume the 'atoms' are sorted by global index; however, all other
320
+ # sections need not be sorted. For convenience, we will keep them sorted by
321
+ # atom indices or atom type name, where appropriate.
322
+ inst.null_check(msg=f'read from {filename}')
323
+ if 'atomtypes' in inst.D:
324
+ inst.D['atomtypes']=inst.D['atomtypes'].sort_values(by='name').reset_index(drop=True)
325
+ # inst.D['atomtypes'].sort_values(by='name',inplace=True)
326
+ if 'bonds' in inst.D:
327
+ inst.D['bonds']=inst.D['bonds'].sort_values(by=['ai','aj']).reset_index(drop=True)
328
+ inst.bondlist=Bondlist.fromDataFrame(inst.D['bonds'])
329
+ if 'bondtypes' in inst.D:
330
+ df_typeorder(inst.D['bondtypes'],typs=['i','j'])
331
+ # inst.D['bondtypes'].sort_values(by=['i','j'],inplace=True)
332
+ inst.D['bondtypes']=inst.D['bondtypes'].sort_values(by=['i','j']).reset_index(drop=True)
333
+ if 'pairs' in inst.D:
334
+ inst.D['pairs']=inst.D['pairs'].sort_values(by=['ai','aj']).reset_index(drop=True)
335
+ if 'pairtypes' in inst.D:
336
+ df_typeorder(inst.D['pairtypes'],typs=['i','j'])
337
+ # inst.D['pairtypes'].sort_values(by=['i','j'],inplace=True)
338
+ inst.D['pairtypes']=inst.D['pairtypes'].sort_values(by=['i','j']).reset_index(drop=True)
339
+ if 'angles' in inst.D:
340
+ # central atom (aj) is the primary index
341
+ inst.D['angles']=inst.D['angles'].sort_values(by=['aj','ai','ak']).reset_index(drop=True)
342
+ if 'angletypes' in inst.D:
343
+ df_typeorder(inst.D['angletypes'],typs=['i','j','k'])
344
+ # inst.D['angletypes'].sort_values(by=['j','i','k'],inplace=True)
345
+ inst.D['angletypes']=inst.D['angletypes'].sort_values(by=['j','i','k']).reset_index(drop=True)
346
+ if 'dihedrals' in inst.D:
347
+ # central atoms (aj,ak) are the primary index
348
+ inst.D['dihedrals']=inst.D['dihedrals'].sort_values(by=['aj','ak','ai','al']).reset_index(drop=True)
349
+ if 'dihedraltypes' in inst.D:
350
+ df_typeorder(inst.D['dihedraltypes'],typs=['i','j','k','l'])
351
+ # print(f' -> pre sort: now there are {len(inst.D["dihedraltypes"])} dihedral types.')
352
+ # inst.D['dihedraltypes'].sort_values(by=['j','k','i','l'],inplace=True)
353
+ inst.D['dihedraltypes']=inst.D['dihedraltypes'].sort_values(by=['j','k','i','l']).reset_index(drop=True)
354
+ # print(f' -> post sort: now there are {len(inst.D["dihedraltypes"])} dihedral types.')
355
+ for f in inst.includes:
356
+ # print(f'reading included topology {f}')
357
+ inst.merge(Topology.read_gro(os.path.join(dirname,f)))
358
+ inst.empty=False
359
+ return inst
360
+
361
+ def bond_source_check(self):
362
+ """bond_source_check Checks to ensure the 'bonds' dataframe and 'mol2_bonds' dataframe contain the same bonds. A mol2 dataframe is only created when a mol2 file is read by the Coordinates module.
363
+ """
364
+ if 'bonds' in self.D and 'mol2_bonds' in self.D:
365
+ # logger.debug(f'Consistency check between gromacs-top bonds and mol2-bonds requested.')
366
+ grobonds=self.D['bonds'].sort_values(by=['ai','aj'])
367
+ bmi=grobonds.set_index(['ai','aj']).index
368
+ mol2bonds=self.D['mol2_bonds'].sort_values(by=['ai','aj'])
369
+ mbmi=mol2bonds.set_index(['ai','aj']).index
370
+ check=all([x==y for x,y in zip(bmi,mbmi)])
371
+ # logger.debug(f'Result: {check}')
372
+ if not check:
373
+ logger.error(f'Gromacs/Mol2 bond inconsistency detected')
374
+ logger.debug(f'GROMACS:')
375
+ logger.debug(grobonds[['ai','aj']].head().to_string())
376
+ logger.debug(f'MOL2:')
377
+ logger.debug(mol2bonds[['ai','aj']].head().to_string())
378
+ for x,y in zip(bmi,mbmi):
379
+ logger.debug(f'{x} {y} {x==y}')
380
+
381
+ def shiftatomsidx(self,idxshift,directive,rows=[],idxlabels=[]):
382
+ """shiftatomsidx shifts all atoms indexes in topology directive dataframe
383
+
384
+ :param idxshift: integer index shift
385
+ :type idxshift: int
386
+ :param directive: name of gromacs topology directive ('atoms','bonds','pairs','angles','dihedrals')
387
+ :type directive: string
388
+ :param rows: row boundaries, defaults to []
389
+ :type rows: list, optional
390
+ :param idxlabels: names of columns that contain atom indexes, defaults to []
391
+ :type idxlabels: list, optional
392
+ """
393
+ if directive in self.D:
394
+ cols=self.D[directive].columns.get_indexer(idxlabels)
395
+ self.D[directive].iloc[rows[0]:rows[1],cols]+=idxshift
396
+
397
+ def detect_cycles(self):
398
+ """detect_cycles detect unique cycles in the topology
399
+
400
+ :return: cycle dict (length:list-of-cycles-by-atom-indices)
401
+ :rtype: dict
402
+ """
403
+ g=self.bondlist.graph()
404
+ cycles=_get_unique_cycles_dict(g,min_length=3)
405
+ return cycles
406
+
407
+ def rep_ex(self,count=0):
408
+ """Replicate extensive topology components (atoms, pairs, bonds, angles, dihedrals)
409
+
410
+ :param count: number of replicas to generate, defaults to 0
411
+ :type count: int, optional
412
+ :raises Exception: Dies if self is missing an atoms dataframe
413
+ """
414
+ if count>0:
415
+ counts={k:0 for k in _GromacsExtensiveDirectives_}
416
+ counts.update({k:0 for k in _NonGromacsExtensiveDirectives_})
417
+ for t in _GromacsExtensiveDirectives_:
418
+ if t in self.D:
419
+ counts[t]=len(self.D[t])
420
+ for t in _NonGromacsExtensiveDirectives_:
421
+ if t in self.D:
422
+ counts[t]=len(self.D[t])
423
+ try:
424
+ idxshift=counts['atoms']
425
+ except:
426
+ raise Exception(f'Error: expected an "atoms" dataframe')
427
+ for t in _GromacsExtensiveDirectives_:
428
+ if t in self.D:
429
+ # print(f'replicating {t} by {count}')
430
+ self.D[t]=pd.concat([self.D[t]]*count,ignore_index=True)
431
+ # print(f'new raw atom count (pre-index-shifted) {len(self.D["atoms"])}')
432
+ for c in range(1,count):
433
+ # if c%100 == 0:
434
+ # print(f' -> shifting indices in replica {c}...')
435
+ # print(f' -> atoms')
436
+ self.shiftatomsidx(idxshift*c,'atoms',rows=[(c*counts['atoms']),((c+1)*counts['atoms'])],idxlabels=['nr'])
437
+ self.shiftatomsidx(c,'atoms',rows=[(c*counts['atoms']),((c+1)*counts['atoms'])],idxlabels=['resnr'])
438
+ # print(f' -> bonds')
439
+ self.shiftatomsidx(idxshift*c,'bonds',rows=[(c*counts['bonds']),((c+1)*counts['bonds'])],idxlabels=['ai','aj'])
440
+ self.shiftatomsidx(idxshift*c,'mol2_bonds',rows=[(c*counts['mol2_bonds']),((c+1)*counts['mol2_bonds'])],idxlabels=['ai','aj'])
441
+ # print(f' -> pairs')
442
+ self.shiftatomsidx(idxshift*c,'pairs',rows=[(c*counts['pairs']),((c+1)*counts['pairs'])],idxlabels=['ai','aj'])
443
+ self.shiftatomsidx(idxshift*c,'angles',rows=[(c*counts['angles']),((c+1)*counts['angles'])],idxlabels=['ai','aj','ak'])
444
+ self.shiftatomsidx(idxshift*c,'dihedrals',rows=[(c*counts['dihedrals']),((c+1)*counts['dihedrals'])],idxlabels=['ai','aj','ak','al'])
445
+ if 'bonds' in self.D:
446
+ self.bondlist=Bondlist.fromDataFrame(self.D['bonds'])
447
+
448
+ @classmethod
449
+ def from_ex(cls,other):
450
+ """from_ex make a new Topology instance by copying only the extensive dataframes
451
+ from an existing topology
452
+
453
+ :param other: the other topology
454
+ :type other: Topology
455
+ :return: a new Topology generated by the extensive dataframes of other
456
+ :rtype: Topology
457
+ """
458
+ ''' '''
459
+ inst=cls()
460
+ for t in _GromacsExtensiveDirectives_:
461
+ if t in other.D:
462
+ inst.D[t]=other.D[t].copy()
463
+ return inst
464
+
465
+ def to_file(self,filename):
466
+ """to_file Write topology to a gromacs-format file
467
+
468
+ :param filename: name of top file to write
469
+ :type filename: str
470
+ """
471
+ # prevent buggy writing of NaNs
472
+ self.null_check(msg=f'writing {filename}')
473
+ with open(filename,'w') as f:
474
+ f.write('; Gromacs-format topology written by HTPolyNet\n')
475
+ assert 'defaults' in self.D, 'Error: no [ defaults ] in topology?'
476
+ for k in _GromacsTopologyDirectiveOrder_:
477
+ if k in self.D:
478
+ # columns=_GromacsTopologyDirectiveHeaders_[k]
479
+ with open(filename,'a') as f:
480
+ f.write(f'[ {k} ]\n; ')
481
+ if k in _GromacsTopologyHashables_:
482
+ odf=self.D[k].sort_values(by=_GromacsTopologyHashables_[k])
483
+ odf.to_csv(filename,sep=' ',mode='a',index=False,header=True,doublequote=False)
484
+ else:
485
+ self.D[k].to_csv(filename,sep=' ',mode='a',index=False,header=True,doublequote=False)
486
+ with open(filename,'a') as f:
487
+ f.write('\n')
488
+ with open(filename,'a') as f:
489
+ f.write('; end\n')
490
+
491
+ def null_check(self,msg=''):
492
+ """Paranoid checking for NaNs in dataframe locations that SHOULD NEVER HAVE NANS
493
+
494
+ :param msg: a nice message, defaults to ''
495
+ :type msg: str, optional
496
+ :raises Exception: exits if a NaN is found
497
+ """
498
+ check = True
499
+ for k in _GromacsTopologyDirectiveOrder_:
500
+ if k in self.D:
501
+ if k in _GromacsTopologyHashables_:
502
+ for a in _GromacsTopologyHashables_[k]:
503
+ check=any(self.D[k][a].isnull())
504
+ if check:
505
+ logger.debug(f'{msg} null in {k} {a}\n{self.D[k].to_string()}')
506
+ raise Exception('NaN error')
507
+
508
+ def total_charge(self):
509
+ """Compute and return total system charge
510
+
511
+ :return: charge
512
+ :rtype: float
513
+ """
514
+ if 'atoms' in self.D:
515
+ return self.D['atoms']['charge'].sum()
516
+ return 0.0
517
+
518
+ def adjust_charges(self,atoms=[],desired_charge=0.0,overcharge_threshhold=0.1,msg=''):
519
+ """Adjust atom partial charges a tiny bit so that total system charge is zero
520
+
521
+ :param desired_charge: target system charge, defaults to 0.0
522
+ :type desired_charge: float, optional
523
+ :param overcharge_threshhold: threshold overcharge that triggers a message, defaults to 0.1
524
+ :type overcharge_threshhold: float, optional
525
+ :param msg: A message to write if pre-adjusted system charge is too high, defaults to ''
526
+ :type msg: str, optional
527
+ :return: self topology
528
+ :rtype: Topology
529
+ """
530
+ apparent_charge=self.total_charge()
531
+ overcharge=apparent_charge-desired_charge
532
+ logger.debug(f'Adjusting charges of {len(atoms)} atoms due to overcharge of {overcharge:.6f}')
533
+ if np.abs(overcharge)>overcharge_threshhold:
534
+ logger.debug(f'{msg}')
535
+ cpa=-overcharge/len(atoms)
536
+ logger.debug(f'Adjustment is {cpa:.4e} per atom')
537
+ for i in atoms:
538
+ self.D['atoms'].loc[i-1,'charge']+=cpa
539
+ logger.debug(f'New total charge after adjustment: {self.total_charge():.6f}')
540
+ return self
541
+
542
+ def total_mass(self,units='gromacs'):
543
+ """Returns total mass of all atoms in the Topology.
544
+
545
+ :param units: unit system designation; if 'SI' returns kg, defaults to 'gromacs'
546
+ :type units: str, optional
547
+ :return: mass (in amu if units is 'gromacs' or kg if units is 'SI')
548
+ :rtype: float
549
+ """
550
+ fac=1.0
551
+ if units=='SI':
552
+ fac=physical_constants['atomic mass constant'][0]
553
+ if 'atoms' in self.D:
554
+ M_amu=self.D['atoms']['mass'].sum()
555
+ logger.debug(f'mass {M_amu} fac {fac}')
556
+ return M_amu*fac
557
+ return 0.0
558
+
559
+ def atomcount(self):
560
+ """atomcount Returns the total number of atoms
561
+
562
+ :return: number of atoms
563
+ :rtype: int
564
+ """
565
+ if 'atoms' in self.D:
566
+ return self.D['atoms'].shape[0]
567
+ return 0
568
+
569
+ def add_restraints(self,pairdf,typ=6,kb=300000.):
570
+ """Add type-6 (non-topoogical) bonds to help drag atoms destined to be bonded
571
+ closer together in a series of dragging simulations
572
+
573
+ :param pairdf: dataframe of pairs ['ai','aj']
574
+ :type pairdf: pandas DataFrame
575
+ :param typ: bond type, defaults to 6
576
+ :type typ: int, optional
577
+ :param kb: bond spring constant (kJ/mol/nm^2), defaults to 300000
578
+ :type kb: float, optional
579
+ """
580
+ bmi=self.D['bonds'].set_index(['ai','aj']).sort_index().index
581
+ for i,b in pairdf.iterrows():
582
+ ai,aj=idxorder((b['ai'],b['aj']))
583
+ b0=b['initial_distance']
584
+ if not (ai,aj) in bmi:
585
+ h=_GromacsTopologyDirectiveHeaders_['bonds']
586
+ data=[ai,aj,typ,b0,kb] # this new bond will have override parameters
587
+ bonddict={k:[v] for k,v in zip(h,data)}
588
+ bdtoadd=pd.DataFrame(bonddict)
589
+ self.D['bonds']=pd.concat((self.D['bonds'],bdtoadd),ignore_index=True)
590
+
591
+ def remove_restraints(self,pairdf):
592
+ """Remove all bonds represented in in pairdf.
593
+ These are interpreted as non-topological
594
+ restraints, so deleting these 'bonds' does
595
+ not influence angles or dihedrals
596
+
597
+ :param pairdf: dataframe of pairs ['ai','aj']
598
+ :type pairdf: pandas DataFrame
599
+ """
600
+ d=self.D['bonds']
601
+ to_drop=[]
602
+ for i,b in pairdf.iterrows():
603
+ ai,aj=idxorder((b['ai'],b['aj']))
604
+ to_drop.append(d[(d.ai==ai)&(d.aj==aj)].index.values[0])
605
+ self.D['bonds']=self.D['bonds'].drop(to_drop)
606
+
607
+ def add_bonds(self,pairs=[]):
608
+ """add_bonds Adds bonds indicated in list pairs to the topology
609
+
610
+ :param pairs: list of pairs of atom indexes, defaults to []
611
+ :type pairs: list, optional
612
+ :raises Exception: dies if an existing bond is in the list of pairs
613
+ """
614
+ # logger.debug('begins')
615
+ at=self.D['atoms']
616
+ ij=self.D['bondtypes'].set_index(['i','j'])
617
+ #mb=self.D['mol2_bonds']
618
+ bmi=self.D['bonds'].set_index(['ai','aj']).sort_index().index
619
+ pmi=self.D['pairs'].set_index(['ai','aj']).sort_index().index
620
+ newbonds=[]
621
+ for b in pairs:
622
+ # logger.debug(f'{b}')
623
+ # assert type(b[0])==int
624
+ bondtuple=(int(b[0]),int(b[1]))
625
+ order=int(b[2])
626
+ ai,aj=idxorder(bondtuple)
627
+ assert type(ai)==int
628
+ assert type(aj)==int
629
+ '''
630
+ if this bond is not in the topology, then add it
631
+ '''
632
+ if not (ai,aj) in bmi:
633
+ newbonds.append((ai,aj))
634
+ # logger.debug(f'asking types of {ai} and {aj}; at.shape {at.shape}')
635
+ it=at.iloc[ai-1].type
636
+ jt=at.iloc[aj-1].type
637
+ idx=typeorder((it,jt))
638
+ if idx in ij.index:
639
+ bt=ij.loc[idx,'func'] # why don't i need need values[0]
640
+ kb=ij.loc[idx,'kb']
641
+ b0=ij.loc[idx,'b0']
642
+ else:
643
+ logger.debug(f'no bondtype {idx} found; using placeholder parameters')
644
+ bt=1
645
+ b0=0.15
646
+ kb=999999
647
+ # raise Exception(f'no bondtype {idx} found.')
648
+ '''
649
+ add a new bond!
650
+ '''
651
+ h=_GromacsTopologyDirectiveHeaders_['bonds']
652
+ data=[ai,aj,bt,b0,kb] # this new bond will have override parameters
653
+ assert len(h)==len(data), 'Error: not enough data for new bond?'
654
+ bonddict={k:[v] for k,v in zip(h,data)}
655
+ bdtoadd=pd.DataFrame(bonddict)
656
+ self.D['bonds']=pd.concat((self.D['bonds'],bdtoadd),ignore_index=True)
657
+ # logger.info(f'add_bond:\n{bdtoadd.to_string()}')
658
+ logger.debug(f'just added {bonddict}')
659
+ if 'mol2_bonds' in self.D:
660
+ data=[len(self.D['mol2_bonds']),ai,aj,1] # assume single bond
661
+ bonddict={k:[v] for k,v in zip(['bondIdx','ai','aj','order'],data)}
662
+ self.D['mol2_bonds']=pd.concat((self.D['mol2_bonds'],pd.DataFrame(bonddict)),ignore_index=True)
663
+ # remove this pair from pairs if it's in there (it won't be)
664
+ if idx in pmi:
665
+ logger.debug(f'Warning: new bond {ai}-{aj} was evidently in the [ pairs ]!')
666
+ d=self.D['pairs']
667
+ indexes_to_drop=d[(d.ai.isin(idx))&(d.aj.isin(idx))].index
668
+ logger.debug(f'Dropping [ pair ]:\n{d[indexes_to_drop].to_string()}')
669
+ indexes_to_keep=set(range(d.shape[0]))-set(indexes_to_drop)
670
+ self.D['pairs']=d.take(list(indexes_to_keep)).reset_index(drop=True)
671
+ else:
672
+ '''
673
+ if it is, do nothing; it will be templated; if mol2_bonds are present (usually
674
+ because a Topology is part of a molecule being parameterized), update the order
675
+ of the bond.
676
+ '''
677
+ if 'mol2_bonds' in self.D:
678
+ mb=self.D['mol2_bonds']
679
+ bi=(mb['ai']==ai)&(mb['aj']==aj)
680
+ mb.loc[bi,'order']=order
681
+ '''
682
+ update the bondlist
683
+ '''
684
+ for b in newbonds:
685
+ self.bondlist.append(b)
686
+ logger.debug(f'Added {len(newbonds)} new bonds')
687
+
688
+
689
+ def delete_atoms(self,idx=[],reindex=True,return_idx_of=[],**kwargs):
690
+ """Delete atoms from topology
691
+
692
+ :param idx: list of atom indexes to delete, defaults to []
693
+ :type idx: list, optional
694
+ :param reindex: reindex atoms after deleting, defaults to True
695
+ :type reindex: bool, optional
696
+ :param return_idx_of: list of old indices to report new indices of, defaults to []
697
+ :type return_idx_of: list, optional
698
+ :return: old-index-to-new-index mapper
699
+ :rtype: dict
700
+ """
701
+ #logger.debug(f'Delete atoms: {idx}')
702
+ paranoid_about_pairs=kwargs.get('paranoid_about_pairs',False)
703
+ self.null_check(msg='beginning of delete atoms')
704
+ # logger.debug(f'idx {idx}')
705
+ d=self.D['atoms']
706
+ new_idx=[]
707
+ indexes_to_drop=d[d.nr.isin(idx)].index
708
+ total_missing_charge=d.loc[indexes_to_drop]['charge'].sum()
709
+ logger.debug(f'Deleting {d.loc[indexes_to_drop].shape[0]} [ atoms ]; charge to make up: {total_missing_charge:.4f}')#:\n{d.loc[indexes_to_drop].to_string()}')
710
+ indexes_to_keep=set(range(d.shape[0]))-set(indexes_to_drop)
711
+ self.D['atoms']=d.take(list(indexes_to_keep)).reset_index(drop=True)
712
+ mapper={}
713
+ if reindex:
714
+ d=self.D['atoms']
715
+ oldGI=d['nr'].copy()
716
+ d['nr']=d.index+1
717
+ mapper={k:v for k,v in zip(oldGI,d['nr'])}
718
+ # logger.debug(f'mapper {mapper}')
719
+ assert not any([x in mapper for x in idx]),f'Error: Some deleted atoms in mapper.'
720
+ k=np.array(list(mapper.keys()))
721
+ v=np.array(list(mapper.values()))
722
+ if any(np.isnan(k)):
723
+ logger.error('null in mapper keys')
724
+ if any(np.isnan(v)):
725
+ logger.error('null in mapper values')
726
+ # logger.debug(f'delete_atoms: mapper {mapper}')
727
+ if len(return_idx_of)>0:
728
+ # logger.info(f'Asking for updated global indexes of {return_idx_of}')
729
+ new_idx=[mapper[o] for o in return_idx_of]
730
+ #d['nr_shift']=d['nr']-oldGI # probably not necessary
731
+ ptt=['bonds','mol2_bonds','pairs']
732
+ for pt in ptt:
733
+ if pt in self.D:
734
+ d=self.D[pt]
735
+ # logger.debug(f'delete atom: {pt} df prior to deleting')
736
+ # logger.debug(d.to_string())
737
+ indexes_to_drop=d[(d.ai.isin(idx))|(d.aj.isin(idx))].index
738
+ logger.debug(f'Deleting {d.loc[indexes_to_drop].shape[0]} [ {pt} ]')
739
+ indexes_to_keep=set(range(d.shape[0]))-set(indexes_to_drop)
740
+ self.D[pt]=d.take(list(indexes_to_keep)).reset_index(drop=True)
741
+ if reindex:
742
+ d=self.D[pt]
743
+ assert not any([x in idx for x in d.ai]),f'Error: deleted atom survived in {pt} ai'
744
+ assert not any([x in idx for x in d.aj]),f'Error: deleted atom survived in {pt} aj'
745
+ assert all([x in mapper for x in d.ai]),f'Error: surviving {pt} atom ai old idx not in mapper'
746
+ assert all([x in mapper for x in d.aj]),f'Error: surviving {pt} atom aj old idx not in mapper'
747
+ #logger.debug(f'delete atom: {pt} df prior to reindexing')
748
+ #logger.debug(d.to_string())
749
+ # pairs deleted here were deleted because either ai or aj was among
750
+ # the atoms to delete. We assert than any dihedral for which
751
+ # the i atom is ai and l atom is aj will necessarily be deleted
752
+ # below. The only other pairs that should be deleted would
753
+ # be ones in which the dihedral j or k atom is among those to be
754
+ # deleted.
755
+ if pt!='pairs': # don't remap these yet; need to delete pairs that
756
+ # might arise from dihedrals that are deleted.
757
+ d.ai=d.ai.map(mapper)
758
+ d.aj=d.aj.map(mapper)
759
+ if pt=='bonds':
760
+ # logger.debug(f'Updating bondlist using (first 10 shown)\n{d.head(10).to_string()}')
761
+ self.bondlist=Bondlist.fromDataFrame(d)
762
+ if pt=='mol2_bonds':
763
+ nBonds=self.D[pt].shape[0]
764
+ self.D[pt]['bondIdx']=list(range(1,nBonds+1))
765
+ d=self.D['angles']
766
+ # assert d.ai.dtype==int,f'pre-delete lost angle ai dtype {d.ai.dtype}'
767
+ # assert d.aj.dtype==int,f'pre-delete lost angle aj dtype {d.aj.dtype}'
768
+ # assert d.ak.dtype==int,f'pre-delete lost angle ak dtype {d.ak.dtype}'
769
+ # logger.debug(f'ai {d.ai.isin(idx).to_string()}')
770
+ # logger.debug(f'aj {d.aj.isin(idx).to_string()}')
771
+ # logger.debug(f'ak {d.ak.isin(idx).to_string()}')
772
+ indexes_to_drop=d[(d['ai'].isin(idx))|(d['aj'].isin(idx))|(d['ak'].isin(idx))].index
773
+ # extras=d[d['ak'].isin(idx)].index
774
+ logger.debug(f'Deleting {len(indexes_to_drop)} [ angles ]')
775
+ indexes_to_keep=set(range(d.shape[0]))-set(indexes_to_drop)
776
+ # logger.debug(f'drop {list(sorted(list(set(indexes_to_drop))))}')
777
+ # logger.debug(f'keep {indexes_to_keep}')
778
+ self.D['angles']=d.take(list(indexes_to_keep)).reset_index(drop=True)
779
+ assert d.ai.dtype==int,f'post-delete lost angle ai dtype {d.ai.dtype}'
780
+ assert d.aj.dtype==int,f'post-delete lost angle aj dtype {d.aj.dtype}'
781
+ assert d.ak.dtype==int,f'post-delete lost angle ak dtype {d.ak.dtype}'
782
+ self.null_check(msg='inside delete atoms before angles reindex')
783
+ if reindex:
784
+ d=self.D['angles']
785
+ assert not any([x in idx for x in d.ai]),'Error: deleted atom survived in angle ai'
786
+ assert not any([x in idx for x in d.aj]),'Error: deleted atom survived in angle aj'
787
+ zombie_tags=[x in idx for x in d.ak]
788
+ if any(zombie_tags):
789
+ logger.debug(f'Zombie ak angles:\n{self.D["angles"][zombie_tags].to_string()}')
790
+ assert not any(zombie_tags),'Error: deleted atom survived in angle ak'
791
+ assert all([x in mapper for x in d.ai]),'Error: surviving angle atom ai old idx not in mapper'
792
+ assert all([x in mapper for x in d.aj]),'Error: surviving angle atom aj old idx not in mapper'
793
+ assert all([x in mapper for x in d.ak]),'Error: surviving angle atom ak old idx not in mapper'
794
+ d.ai=d.ai.map(mapper)
795
+ d.aj=d.aj.map(mapper)
796
+ d.ak=d.ak.map(mapper)
797
+ self.null_check(msg='inside delete atoms after angles reindex')
798
+ d=self.D['dihedrals']
799
+ indexes_to_drop=d[(d.ai.isin(idx))|(d.aj.isin(idx))|(d.ak.isin(idx))|(d.al.isin(idx))].index
800
+ logger.debug(f'Deleting {d.loc[indexes_to_drop].shape[0]} [ dihedrals ]')
801
+ # if the atoms we have deleted are truly just H's, then there will be no other
802
+ # spurious pairs after all dihedrals containing deleted atoms are deleted.
803
+ # However, we may want to still search for such pairs, so let's leave this
804
+ # as an option:
805
+ if paranoid_about_pairs:
806
+ dp=self.D['pairs']
807
+ ddp=d.loc[indexes_to_drop] # these are dihedrals marked for deletion
808
+ # determine pairs deriving from these dihedrals and delete them!
809
+ pai=ddp.ai.to_list()
810
+ pal=ddp.al.to_list()
811
+ dd=[]
812
+ for pi,pl in zip(pai,pal):
813
+ dwpi=dp[((dp.ai==pi)&(dp.aj==pl))|((dp.ai==pl)&(dp.aj==pi))].index.to_list()
814
+ dd.extend(dwpi)
815
+ ptk=set(range(dp.shape[0]))-set(dwpi)
816
+ if dp.loc[dwpi].shape[0]>0:
817
+ logger.debug(f' -> and deleting {dp.loc[dwpi].shape[0]} [ pairs ] from those dihedrals')
818
+ # Note that we expect this to be zero if we are only deleting H's, since
819
+ # an H can never be a 'j' or 'k' in a dihedral!
820
+ self.D['pairs']=dp.take(list(ptk)).reset_index(drop=True)
821
+ indexes_to_keep=set(range(d.shape[0]))-set(indexes_to_drop)
822
+ self.D['dihedrals']=d.take(list(indexes_to_keep)).reset_index(drop=True)
823
+ if reindex:
824
+ d=self.D['dihedrals']
825
+ d.ai=d.ai.map(mapper)
826
+ d.aj=d.aj.map(mapper)
827
+ d.ak=d.ak.map(mapper)
828
+ d.al=d.al.map(mapper)
829
+ d=self.D['pairs']
830
+ d.ai=d.ai.map(mapper)
831
+ d.aj=d.aj.map(mapper)
832
+ tp=[]
833
+ pdrops=[]
834
+ for i,r in d.iterrows():
835
+ ai,aj=min([r.ai,r.aj]),max([r.ai,r.aj])
836
+ if not [ai,aj] in tp:
837
+ tp.append([ai,aj])
838
+ else:
839
+ pdrops.append(i)
840
+ logger.debug(f'Deleting {len(pdrops)} duplicate 1-4 pair descriptors -- this is likely due to a bug somewhere')
841
+ self.D['pairs']=d.drop(pdrops).reset_index(drop=True)
842
+ self.null_check(msg='end of delete atoms')
843
+ logger.debug('finished.')
844
+ if len(return_idx_of)>0:
845
+ return new_idx
846
+ return mapper
847
+
848
+ def _myconcat(self,other,directive='',idxlabel=[],idxshift=0,drop_duplicates=False):
849
+ if not directive in other.D:
850
+ return
851
+ if directive in self.D:
852
+ # shift atom indices
853
+ for i in idxlabel:
854
+ other.D[directive][i]+=idxshift
855
+ if drop_duplicates:
856
+ self.D[directive]=pd.concat((self.D[directive],other.D[directive]),ignore_index=True).drop_duplicates()
857
+ else:
858
+ self.D[directive]=pd.concat((self.D[directive],other.D[directive]),ignore_index=True)
859
+ else:
860
+ self.D[directive]=other.D[directive]
861
+
862
+ def merge(self,other):
863
+ """Merge topologies
864
+
865
+ :param other: a topology
866
+ :type other: Topology
867
+ """
868
+ # logger.debug('Topology.merge begins')
869
+ # look for duplicated types between self and other. If any are found, delete those types from other and copy their parameters into the explicit interactions they correspond to.
870
+ self.merge_ex(other)
871
+ self.merge_types(other)
872
+ # logger.debug('Topology.merge ends')
873
+
874
+ # def handle_duplicate_types(self,other,copy_directive='other_to_self',typename='',funcidx=4):
875
+ # if not typename in self.D or not typename in other.D:
876
+ # return
877
+ # stdf=self.D[typename]
878
+ # otdf=other.D[typename]
879
+ # hashables=_GromacsTopologyHashables_[typename]
880
+ # headers=_GromacsTopologyDirectiveHeaders_[typename].copy()
881
+ # logger.debug(f'{hashables} {headers}')
882
+ # for i in hashables:
883
+ # headers.remove(i)
884
+ # common=[]
885
+ # fi=headers.index('func')
886
+ # copy_idx_pairs=[]
887
+ # for idx,r in otdf.iterrows():
888
+ # typidx=typeorder(tuple([r[i] for i in hashables]))
889
+ # idata=[r[i] for i in headers]
890
+ # for jdx,q in stdf.iterrows():
891
+ # typjdx=typeorder(tuple([q[i] for i in hashables]))
892
+ # jdata=[q[i] for i in headers]
893
+ # if typidx==typjdx and idata==jdata:
894
+ # common.append(typidx)
895
+ # for jdx,q in stdf.iterrows():
896
+ # typjdx=typeorder(tuple([q[i] for i in hashables]))
897
+ # jdata=[q[i] for i in headers]
898
+ # if typidx==typjdx and idata!=jdata and not typidx in common and idata[fi]==funcidx and jdata[fi]==funcidx:
899
+ # logger.debug(f'duplicate {typename} {typidx}')
900
+ # logger.debug(f'o {idx} {idata}')
901
+ # logger.debug(f's {jdx} {jdata}')
902
+ # if not (idx,jdx) in copy_idx_pairs:
903
+ # copy_idx_pairs.append((idx,jdx))
904
+ # if copy_directive=='other_to_self' and len(copy_idx_pairs)>0:
905
+ # for o,s in copy_idx_pairs:
906
+ # self.D[typename].iloc[s]=other.D[typename].iloc[o]
907
+ # elif copy_directive=='self_to_other' and len(copy_idx_pairs)>0:
908
+ # for o,s in copy_idx_pairs:
909
+ # other.D[typename].iloc[o]=self.D[typename].iloc[s]
910
+ # # logger.debug(f'{typidx}')
911
+ # # pass
912
+ def report_type(self,typidx_q,typename='',funcidx=-1):
913
+ if not typename in self.D:
914
+ return
915
+ stdf=self.D[typename]
916
+ hashables=_GromacsTopologyHashables_[typename]
917
+ headers=_GromacsTopologyDirectiveHeaders_[typename].copy()
918
+ for i in hashables:
919
+ headers.remove(i)
920
+ fi=headers.index('func')
921
+ for idx,r in stdf.iterrows():
922
+ typidx=typeorder(tuple([r[i] for i in hashables]))
923
+ idata=[r[i] for i in headers]
924
+ if typidx==typidx_q and idata[fi]==funcidx:
925
+ return [r[i] for i in headers]
926
+ return []
927
+ '''
928
+ 'bonds': ['ai', 'aj', 'funct', 'c0', 'c1'],
929
+ 'bondtypes': [ 'i', 'j', 'func', 'b0', 'kb'],
930
+ 'angles': ['ai', 'aj', 'ak', 'funct', 'c0', 'c1'],
931
+ 'angletypes': [ 'i', 'j', 'k', 'func', 'th0', 'cth', 'rub', 'kub'],
932
+ 'dihedrals': ['ai', 'aj', 'ak', 'al', 'funct', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5'],
933
+ 'dihedraltypes':[ 'i', 'j', 'k', 'l', 'func', 'phase', 'kd', 'pn'],
934
+ '''
935
+ def reset_override_from_type(self,interactionname,typename,inst_idx):
936
+ if not typename in self.D:
937
+ return
938
+ typ_hashables=_GromacsTopologyHashables_[typename]
939
+ stdf=self.D[typename].set_index(typ_hashables)
940
+ sidf=self.D[interactionname]
941
+ typ_headers=_GromacsTopologyDirectiveHeaders_[typename].copy()
942
+ ins_hashables=_GromacsTopologyHashables_[interactionname]
943
+ ins_headers=_GromacsTopologyDirectiveHeaders_[interactionname].copy()
944
+ typidx=[self.D['atoms'].iloc[x-1]['type'] for x in inst_idx]
945
+ typidx=typeorder(tuple(typidx))
946
+ for i in typ_hashables:
947
+ typ_headers.remove(i)
948
+ for i in ins_hashables:
949
+ ins_headers.remove(i)
950
+ iidx=idxorder(tuple(inst_idx))
951
+ idx=-1
952
+ for i,r in sidf.iterrows():
953
+ jdx=tuple([r[a] for a in ins_hashables])
954
+ if iidx==jdx:
955
+ idx=i
956
+ break
957
+ assert idx!=-1
958
+ num_data=min([len(typ_headers),len(ins_headers)])
959
+ typ_headers=typ_headers[:num_data]
960
+ ins_headers=ins_headers[:num_data]
961
+ typrec=stdf.loc[typidx][typ_headers]
962
+ cols=self.D[interactionname].columns.get_indexer(ins_headers)
963
+ logger.debug(f'Resetting override in {interactionname} for {inst_idx} from')
964
+ for ln in self.D[interactionname].iloc[idx,cols].to_string().split('\n'):
965
+ logger.debug(ln)
966
+ logger.debug('to')
967
+ self.D[interactionname].iloc[idx,cols]=typrec
968
+ for ln in self.D[interactionname].iloc[idx,cols].to_string().split('\n'):
969
+ logger.debug(ln)
970
+
971
+
972
+ def reset_type(self,typename,typidx_t,values):
973
+ if not typename in self.D:
974
+ return
975
+ stdf=self.D[typename]
976
+ hashables=_GromacsTopologyHashables_[typename]
977
+ headers=_GromacsTopologyDirectiveHeaders_[typename].copy()
978
+ for i in hashables:
979
+ headers.remove(i)
980
+ cols=self.D[typename].columns.get_indexer(headers)
981
+ idxs=[]
982
+ for idx,r in stdf.iterrows():
983
+ typidx=typeorder(tuple([r[i] for i in hashables]))
984
+ if typidx==typidx_t:
985
+ idxs.append(idx)
986
+ assert len(headers)==len(values)
987
+ logger.debug(f'Resetting {len(idxs)} entries {headers} to {values}')
988
+ for idx in idxs:
989
+ self.D[typename].iloc[idx,cols]=values
990
+ for ln in self.D[typename].iloc[idx][headers].to_string().split('\n'):
991
+ logger.debug(ln)
992
+
993
+ def report_duplicate_types(self,other,typename='',funcidx=4):
994
+ if not typename in self.D or not typename in other.D:
995
+ return
996
+ stdf=self.D[typename]
997
+ otdf=other.D[typename]
998
+ hashables=_GromacsTopologyHashables_[typename]
999
+ headers=_GromacsTopologyDirectiveHeaders_[typename].copy()
1000
+ # logger.debug(f'{hashables} {headers}')
1001
+ for i in hashables:
1002
+ headers.remove(i)
1003
+ common=[]
1004
+ fi=headers.index('func')
1005
+ true_duplicate_types=[]
1006
+ for idx,r in otdf.iterrows():
1007
+ typidx=typeorder(tuple([r[i] for i in hashables]))
1008
+ idata=[r[i] for i in headers]
1009
+ for jdx,q in stdf.iterrows():
1010
+ typjdx=typeorder(tuple([q[i] for i in hashables]))
1011
+ jdata=[q[i] for i in headers]
1012
+ if typidx==typjdx and idata==jdata:
1013
+ common.append(typidx)
1014
+ for idx,r in otdf.iterrows():
1015
+ typidx=typeorder(tuple([r[i] for i in hashables]))
1016
+ idata=[r[i] for i in headers]
1017
+ for jdx,q in stdf.iterrows():
1018
+ typjdx=typeorder(tuple([q[i] for i in hashables]))
1019
+ jdata=[q[i] for i in headers]
1020
+ if typidx==typjdx and idata!=jdata and not typidx in common and idata[fi]==funcidx and jdata[fi]==funcidx:
1021
+ # logger.debug(f'duplicate {typename} {typidx}')
1022
+ true_duplicate_types.append(typidx)
1023
+ return true_duplicate_types
1024
+
1025
+ def dup_check(self,die=True):
1026
+ """Check for duplicate type-like topology records
1027
+
1028
+ :param die: flag telling HTPolyNet to exit if duplicate found, defaults to True
1029
+ :type die: bool, optional
1030
+ :raises Exception: Exception raised if duplicate found and die is True
1031
+ """
1032
+ L=['atomtypes','bondtypes','angletypes']
1033
+ Not=' not' if not die else ''
1034
+ logger.debug(f'Checking for duplicate {L}; will{Not} die if found.')
1035
+ for t in L:
1036
+ i=_GromacsTopologyHashables_[t]
1037
+ ''' checking for types with duplicate atom-type indices '''
1038
+ dups=self.D[t].duplicated(subset=i,keep=False)
1039
+ if any(dups):
1040
+ logger.error(f'Duplicate {t} with different parameters detected\n'+self.D[t][dups].to_string())
1041
+ if die:
1042
+ raise Exception('duplicate topology types with different parameters detected')
1043
+
1044
+ def merge_types(self,other):
1045
+ """Merge type-like topology dataframes from other to self
1046
+
1047
+ :param other: topology containing attribute D, a dictionary of dataframes
1048
+ :type other: Topology
1049
+ """
1050
+ # self.handle_duplicate_types(other,typename='dihedraltypes',funcidx=4,drop_directive='drop_from_self')
1051
+ L=['atomtypes','bondtypes','angletypes','dihedraltypes']
1052
+ for t in L:
1053
+ self._myconcat(other,directive=t,drop_duplicates=True)
1054
+
1055
+ def merge_ex(self,other):
1056
+ # print(' extensive merging...')
1057
+ ''' merge EXTENSIVE quantities '''
1058
+ idxshift=0 if 'atoms' not in self.D else len(self.D['atoms'])
1059
+ rdxshift=0 if 'atoms' not in self.D else self.D['atoms'].iloc[-1]['resnr']
1060
+ if 'atoms' in other.D:
1061
+ other.D['atoms']['resnr']+=rdxshift
1062
+ self._myconcat(other,directive='atoms',idxlabel=['nr'],idxshift=idxshift)
1063
+ self._myconcat(other,directive='bonds',idxlabel=['ai','aj'],idxshift=idxshift)
1064
+ if 'bonds' in other.D:
1065
+ self.bondlist.update(other.D['bonds'])
1066
+ if 'mol2_bonds' in self.D and 'mol2_bonds' in other.D:
1067
+ other.D['mol2_bonds'].bondIdx+=self.D['mol2_bonds'].shape[0]
1068
+ self._myconcat(other,directive='mol2_bonds',idxlabel=['ai','aj'],idxshift=idxshift)
1069
+ self._myconcat(other,directive='pairs',idxlabel=['ai','aj'],idxshift=idxshift)
1070
+ self._myconcat(other,directive='angles',idxlabel=['ai','aj','ak'],idxshift=idxshift)
1071
+ self._myconcat(other,directive='dihedrals',idxlabel=['ai','aj','ak','al'],idxshift=idxshift)
1072
+
1073
+ def get_atom_attribute(self,idx,attribute):
1074
+ """Return value of attribute of atom idx
1075
+
1076
+ :param idx: global atom index
1077
+ :type idx: int
1078
+ :param attribute: atom attribute name
1079
+ :type attribute: str
1080
+ :return: atom attribute value
1081
+ :rtype: varies
1082
+ """
1083
+ return self.D['atoms'].iloc[idx-1][attribute]
1084
+
1085
+ def get_atomtype(self,idx):
1086
+ """Get atom type of atom with global index idx
1087
+
1088
+ :param idx: atom global index
1089
+ :type idx: int
1090
+ :return: atom typ
1091
+ :rtype: str
1092
+ """
1093
+ # logger.debug(f'Asking get_atomtype for type of atom with index {idx}')
1094
+ return self.D['atoms'].iloc[idx-1].type
1095
+
1096
+ def build_interresidue_graph(self,G,ri):
1097
+ if ri in G:
1098
+ return
1099
+ adf=self.D['atoms']
1100
+ ri_at_idx=adf[adf['resnr']==ri]['nr'].to_list()
1101
+ residues=adf['resnr'].unique()
1102
+ ri_partners=[]
1103
+ for rn in residues:
1104
+ skip=False
1105
+ rj_at_idx=adf[adf['resnr']==rn]['nr'].to_list()
1106
+ for i,j in product(ri_at_idx,rj_at_idx):
1107
+ # logger.debug(f'### {i} in {self.bondlist.partners_of(j)}?')
1108
+ if i in self.bondlist.partners_of(j):
1109
+ if not rn in ri_partners:
1110
+ ri_partners.append(rn)
1111
+ skip=True
1112
+ continue
1113
+ if skip: continue
1114
+ # logger.debug(f'rn partners {ri_partners}')
1115
+ G.add_node(ri)
1116
+ for rj in ri_partners:
1117
+ self.build_interresidue_graph(G,rj)
1118
+
1119
+ def local_resid_cluster(self,ri):
1120
+ G=nx.DiGraph()
1121
+ # logger.debug(str(self.bondlist))
1122
+ self.build_interresidue_graph(G,ri)
1123
+ return [x for x in G]
1124
+
1125
+ def make_resid_graph(self,json_file=None):
1126
+ adf=self.D['atoms']
1127
+ N=adf.shape[0]
1128
+ self.residue_network=nx.DiGraph()
1129
+ residues=adf['residue'].unique()
1130
+ for rn in residues:
1131
+ rs=adf[adf['residue']==rn]['resnr'].unique()
1132
+ self.residue_network.add_nodes_from(rs,resName=rn)
1133
+
1134
+ resnrs=adf['resnr'].unique()
1135
+ for i in resnrs:
1136
+ # atom global indexes in this resnr
1137
+ ats=adf[adf['resnr']==i]['nr'].to_list()
1138
+ connectors=[]
1139
+ for a in ats:
1140
+ an=self.bondlist.partners_of(a)
1141
+ natsrn=adf[adf['nr'].isin(an)]['resnr'].unique()
1142
+ if len(natsrn)>1:
1143
+ for n in natsrn:
1144
+ if n!=i: # this is an inter-residue connection
1145
+ connectors.append((a,n))
1146
+ for c in connectors:
1147
+ a,n=c
1148
+ bondtype="cross"
1149
+ if not self.residue_network.has_edge(i,n):
1150
+ self.residue_network.add_edge(i,n,bondtype=bondtype)
1151
+ if json_file:
1152
+ the_data=json_graph.node_link_data(self.residue_network)
1153
+ assert type(the_data)==dict,f'Error: node_link_data returns a {type(the_data)} but should return a dict'
1154
+ logger.debug(f'writing graph node_link_data to {json_file}')
1155
+ the_data_str=str(the_data)
1156
+ the_data_str=the_data_str.replace('True','"True"')
1157
+ the_data_str=the_data_str.replace('False','"False"')
1158
+ if "'" in the_data_str:
1159
+ logger.debug(f'json_graph.node_link_data produces single-quoted dict keys -- this is not JSON standard')
1160
+ json_compatible_string=the_data_str.replace("'",'"')
1161
+ try:
1162
+ the_data=json.loads(json_compatible_string)
1163
+ except Exception as msg:
1164
+ logger.debug(str(msg))
1165
+ logger.debug(f'json.loads fails to encode string:\n{json_compatible_string}')
1166
+ with open (json_file,'w') as f:
1167
+ try:
1168
+ json.dump(the_data,f)
1169
+ except Exception as msg:
1170
+ logger.debug(str(msg))
1171
+ logger.debug(f'writing resid graph to JSON not currently supported')
1172
+ f.write(str(the_data)+'\n')
1173
+ # if draw:
1174
+ # network_graph(self.residue_network,draw)
1175
+
1176
+ def copy_bond_parameters(self,bonds):
1177
+ """Generate and return a copy of a bonds dataframe that contains all bonds
1178
+ listed in bonds
1179
+
1180
+ :param bonds: dataframe of bonds managed by runtime, 'ai','aj','reactantName'
1181
+ :type bonds: pandas.DataFrame
1182
+ :return: [ bonds ] dataframe extracted from system with all parameters
1183
+ :rtype: pandas.DataFrame
1184
+ """
1185
+ bdf=self.D['bonds']
1186
+ saveme=pd.DataFrame(columns=bdf.columns)
1187
+ for b in bonds.itertuples():
1188
+ ai,aj=idxorder((b.ai,b.aj))
1189
+ # logger.debug(f'copy parameters for ai {ai} aj {aj}')
1190
+ saveme=pd.concat((saveme,bdf[(bdf['ai']==ai)&(bdf['aj']==aj)].copy()),ignore_index=True)
1191
+ # logger.info(f'saved bond override params\n{saveme.to_string()}')
1192
+ return saveme
1193
+
1194
+ def attenuate_bond_parameters(self,bondsdf,stage,max_stages,minimum_distance=0.0,init_colname='initial_distance'):
1195
+ """Alter the kb and b0 parameters for new crosslink bonds according to the values prior to
1196
+ relaxation (stored in lengths), their equilibrium values, and the ratio stage/max_stages.
1197
+ Let stage/max_stages be x, and 1/max_stages <= x <= 1. The spring constant for each
1198
+ bond is multiplied by x and the distance is 1 xth of the way from its maximum value
1199
+ to its equilibrium value.
1200
+
1201
+ :param bonds: dataframe of bonds managed by runtime, 'ai','aj','reactantName'
1202
+ :type bonds: pandas.DataFrame
1203
+ :param stage: index of stage in the series of post-bond-formation relaxation ("R" of SCUR)
1204
+ :type stage: int
1205
+ :param max_stages: total number of relaxation stages for this iteration
1206
+ :type max_stages: int
1207
+ :param minimum_distance: minimum bondlegth allowed, overriding type-specific b0 (if greater than 0)
1208
+ :type lengths: float
1209
+ """
1210
+ bdf=self.D['bonds']
1211
+ factor=(stage+1)/max_stages
1212
+ logger.debug(f'Attenuating {bondsdf.shape[0]} bond{"s" if bondsdf.shape[0]>1 else ""} in stage {stage+1}/{max_stages}')
1213
+ jdx=list(bondsdf.columns).index(init_colname)
1214
+ for b in bondsdf.itertuples(index=False):
1215
+ ai,aj=idxorder((b.ai,b.aj))
1216
+ rij=b[jdx]
1217
+ b0,kb=self.get_bond_parameters(ai,aj)
1218
+ if minimum_distance>0.0:
1219
+ b0=minimum_distance
1220
+ new_b0=rij-factor*(rij-b0)
1221
+ new_kb=kb*factor
1222
+ # logger.debug(f'bond attenuation target for {ai}-{aj}:\nb0 {b0:.5f} kb {kb:.2f}; using b0 {new_b0:.5f} kb {new_kb:.2f}')
1223
+ bdf.loc[(bdf['ai']==ai)&(bdf['aj']==aj),'c0']=new_b0
1224
+ bdf.loc[(bdf['ai']==ai)&(bdf['aj']==aj),'c1']=new_kb
1225
+
1226
+ def get_bond_parameters(self,ai,aj):
1227
+ """Gets b0 and kb for bond between atoms with global indexes ai and aj
1228
+
1229
+ :param ai: global atom index
1230
+ :type ai: int
1231
+ :param aj: global atom index
1232
+ :type aj: int
1233
+ :return: b0, kb -- equilibrium bond length and spring constant
1234
+ :rtype: 2-tuple
1235
+ """
1236
+ ai,aj=idxorder((ai,aj))
1237
+ adf=self.D['atoms']
1238
+ bdf=self.D['bonds']
1239
+ tdf=self.D['bondtypes']
1240
+ b0=bdf.loc[(bdf['ai']==ai)&(bdf['aj']==aj),'c0'].values[0]
1241
+ kb=bdf.loc[(bdf['ai']==ai)&(bdf['aj']==aj),'c1'].values[0]
1242
+ if pd.isna(b0) or pd.isna(kb):
1243
+ ''' no overrides for this bond, so take from types '''
1244
+ it=adf.loc[adf['nr']==ai,'type'].values[0]
1245
+ jt=adf.loc[adf['nr']==aj,'type'].values[0]
1246
+ it,jt=typeorder((it,jt))
1247
+ b0=tdf.loc[(tdf['i']==it)&(tdf['j']==jt),'b0'].values[0]
1248
+ kb=tdf.loc[(tdf['i']==it)&(tdf['j']==jt),'kb'].values[0]
1249
+ return b0,kb
1250
+
1251
+ def restore_bond_parameters(self,df):
1252
+ """Copy data from all bonds in dataframe df to global dataframe
1253
+
1254
+ :param df: dataframe of bonds ['ai','aj','c0','c1']
1255
+ :type df: pandas DataFrame
1256
+ """
1257
+ bdf=self.D['bonds']
1258
+ for r in df.itertuples():
1259
+ ai,aj=r.ai,r.aj
1260
+ c0,c1=r.c0,r.c1
1261
+ bdf.loc[(bdf['ai']==ai)&(bdf['aj']==aj),'c0']=c0
1262
+ bdf.loc[(bdf['ai']==ai)&(bdf['aj']==aj),'c1']=c1
1263
+
1264
+ def attenuate_pair_parameters(self,pairsdf,stage,max_stages,draglimit_nm=0.3):
1265
+ """Alter the kb and b0 parameters for new pre-crosslink pairs according
1266
+ to the values prior to dragging (stored in pairdf['initial_distances']),
1267
+ the desired lower limit of interatomic distance 'draglimit_nm',
1268
+ and the ratio stage/max_stages.
1269
+
1270
+ :param pairdf: pairs dataframe (['ai'],['aj'],['initial_distance'])
1271
+ :type pairdf: pandas.DataFrame
1272
+ :param stage: index of stage in the series of pre-bond-formation dragging
1273
+ :type stage: int
1274
+ :param max_stages: total number of drag stages for this iteration
1275
+ :type max_stages: int
1276
+ :param draglimit_nm: lower limit of interatomic distance requested from drag
1277
+ :type draglimit_nm: float
1278
+ """
1279
+ pdf=self.D['pairs']
1280
+ ess='s' if pairsdf.shape[0]>1 else ''
1281
+ factor=(stage+1)/max_stages
1282
+ logger.debug(f'Attenuating {pairsdf.shape[0]} pair{ess} in stage {stage+1}/{max_stages}')
1283
+ for b in pairsdf.itertuples():
1284
+ ai,aj=idxorder((b.ai,b.aj))
1285
+ b0=b.initial_distance
1286
+ kb=pdf.loc[(pdf['ai']==ai)&(pdf['aj']==aj),'c1'].values[0]
1287
+ pdf.loc[(pdf['ai']==ai)&(pdf['aj']==aj),'c0']=draglimit_nm-factor*(b0-draglimit_nm)
1288
+ pdf.loc[(pdf['ai']==ai)&(pdf['aj']==aj),'c1']=kb*factor