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
@@ -0,0 +1,1071 @@
1
+ """
2
+
3
+ .. module:: coordinates
4
+ :synopsis: Class for managing gromacs .gro file data
5
+
6
+ .. moduleauthor: Cameron F. Abrams, <cfa22@drexel.edu>
7
+
8
+ """
9
+
10
+ import pandas as pd
11
+ import numpy as np
12
+ from io import StringIO
13
+ import os
14
+ import logging
15
+ from itertools import product
16
+
17
+ from HTPolyNet.bondlist import Bondlist
18
+ from HTPolyNet.linkcell import Linkcell
19
+ from HTPolyNet.ring import Ring,Segment
20
+ from HTPolyNet.dataframetools import *
21
+
22
+ logger=logging.getLogger(__name__)
23
+
24
+ GRX_ATTRIBUTES =[ 'z','nreactions','reactantName','sea_idx','cycle','cycle_idx','chain','chain_idx','molecule','molecule_name']
25
+ """Extended atom attributes
26
+
27
+ - 'z' number of sacrificial H's on atom
28
+ - 'nreactions' number of H's sacrificed so far to form bonds
29
+ - 'reactantName' name of most recent reactant to which atom belonged
30
+ - 'sea_idx' index of the group of symmetry-related atoms this atom belongs to (atoms with the same sea_idx in the same resid are considered symmetry-equivalent)
31
+ - 'cycle' index of the unique cycle this atom belongs to
32
+ - 'cycle_idx' index of this atom within this cycle
33
+ - 'chain' index of the unique chain this atom belongs to
34
+ - 'chain_idx' index of this atom within this chain
35
+ - 'molecule' index of the unique molecule this atom belongs to
36
+ - 'molecule_name' name of that molecule
37
+ """
38
+ GRX_GLOBALLY_UNIQUE=[False, False, False, True, True, False, True, False, True, False]
39
+ GRX_UNSET_DEFAULTS =[ 0, 0, 'UNSET', -1, -1, -1, -1, -1, -1, 'UNSET']
40
+
41
+ def dfrotate(df:pd.DataFrame,R):
42
+ """dfrotate applies rotation matrix R to coordinates in dataframe
43
+
44
+ :param df: coordinates dataframe; must have 'posX', 'posY', and 'posZ' columns
45
+ :type df: pd.DataFrame
46
+ :param R: rotation matrix
47
+ :type R: np.ndarray((3,3))
48
+ """
49
+ for i,srow in df.iterrows():
50
+ ri=srow[['posX','posY','posZ']].values
51
+ newri=np.matmul(R,ri)
52
+ df.loc[i,'posX':'posZ']=newri
53
+
54
+ class Coordinates:
55
+ """ Handles atom coordinates.
56
+
57
+ The primary object is `A`, a pandas DataFrame with one row per atom. Each atom has attributes that may be found in a `gro` file and/or a `mol2` file, along with so-called extended attributes, which are used solely by HTPolyNet.
58
+
59
+ """
60
+ gro_attributes = ['resNum', 'resName', 'atomName', 'globalIdx', 'posX', 'posY', 'posZ', 'velX', 'velY', 'velZ']
61
+ """GRO format atom attributes
62
+
63
+ - 'resNum' unique index of residue to which atom belongs
64
+ - 'resName' name of that residue (usually a 3-letter designation)
65
+ - 'atomName' name of this atom, must be unique within a residue
66
+ - 'globalIdx' global index of atom in whole system
67
+ - 'posX', 'posY', 'posZ' cartesian coordinates
68
+ - 'velX', 'velY', 'velZ' cartesian velocities
69
+ """
70
+ mol2_atom_attributes = ['globalIdx','atomName','posX','posY','posZ','type','resNum','resName','charge']
71
+ """MOL2 format atom attributes
72
+
73
+ - 'globalIdx' global index of atom in whole system
74
+ - 'atomName' name of this atom, must be unique within a residue
75
+ - 'posX', 'posY', 'posZ' cartesian coordinates
76
+ - 'resNum' unique index of residue to which atom belongs
77
+ - 'resName' name of that residue (usually a 3-letter designation)
78
+ - 'charge' charge on atom
79
+ """
80
+ mol2_bond_attributes = ['bondIdx','ai','aj','order']
81
+ mol2_bond_types = {k:v for k,v in zip(mol2_bond_attributes, [int, int, int, str])}
82
+
83
+ def __init__(self,name=''):
84
+ """__init__ contructs an empty Coordinates object
85
+
86
+ :param name: a name string, defaults to ''
87
+ :type name: str, optional
88
+ """
89
+ self.name=name
90
+ self.metadat={}
91
+ self.N=0
92
+ self.A=pd.DataFrame()
93
+ self.mol2_bonds=pd.DataFrame()
94
+ self.mol2_bondlist=Bondlist()
95
+ self.linkcell=Linkcell(pbc_wrapper=self.wrap_point)
96
+ self.empty=True
97
+ self.box=np.zeros((3,3))
98
+ self.grx_attributes=GRX_ATTRIBUTES
99
+
100
+ @classmethod
101
+ def read_gro(cls,filename,wrap_coords=True):
102
+ """read_gro Read a Gromacs gro file
103
+
104
+ :param filename: name of gro file
105
+ :type filename: str
106
+ :return: a new Coordinates instance
107
+ :rtype: Coordinates
108
+ """
109
+ inst=cls(filename)
110
+ if filename!='':
111
+ with open(filename,'r') as f:
112
+ data=f.read().split('\n')
113
+ while '' in data:
114
+ data.remove('')
115
+ inst.name=data[0]
116
+ inst.N=int(data[1])
117
+ inst.metadat['N']=inst.N
118
+ series={k:[] for k in cls.gro_attributes}
119
+ lc_globalIdx=1
120
+ for x in data[2:-1]:
121
+ series['resNum'].append(int(x[0:5].strip()))
122
+ series['resName'].append(x[5:10].strip())
123
+ series['atomName'].append(x[10:15].strip())
124
+ ''' if formatted correctly, globalIdx is row index + 1 always! '''
125
+ series['globalIdx'].append(lc_globalIdx)
126
+ lc_globalIdx+=1
127
+ # split won't work since sometimes there might be no spaces
128
+ # "%5d%-5s%5s%5d%8.3f%8.3f%8.3f%8.4f%8.4f%8.4f"
129
+ #numbers=list(map(float,[y.strip() for y in x[20:].split()]))
130
+ numbers=list(map(float,[x[20+8*i:20+8*(i+1)] for i in range(0,3)]))
131
+ if len(x)>44:
132
+ numbers.extend(list(map(float,[x[44+8*i:44+8*(i+1)] for i in range(0,3)])))
133
+ series['posX'].append(numbers[0])
134
+ series['posY'].append(numbers[1])
135
+ series['posZ'].append(numbers[2])
136
+ if len(numbers)==6:
137
+ series['velX'].append(numbers[3])
138
+ series['velY'].append(numbers[4])
139
+ series['velZ'].append(numbers[5])
140
+ if len(series['velX'])==0:
141
+ del series['velX']
142
+ del series['velY']
143
+ del series['velZ']
144
+ assert inst.N==len(series['globalIdx']), f'Atom count mismatch inside {filename}'
145
+ # for k,v in series.items():
146
+ # logger.debug(f'in coordinates.read_gro: {k} has {len(v)} items.')
147
+ inst.A=pd.DataFrame(series)
148
+ boxdataline=data[-1]
149
+ boxdata=list(map(float,boxdataline.split()))
150
+ # logger.debug(f'boxdata {boxdata}')
151
+ inst.box[0][0]=boxdata[0]
152
+ inst.box[1][1]=boxdata[1]
153
+ inst.box[2][2]=boxdata[2]
154
+ # logger.debug(f'box: {inst.box}')
155
+ if len(boxdata)==9:
156
+ inst.box[0][1],inst.box[0][2],inst.box[1][0],inst.box[1][2],inst.box[2][0],inst.box[2][1]=boxdata[3:]
157
+ inst.empty=False
158
+ # logger.debug(f'{inst.checkbox()}')
159
+ # logger.debug('Box vectors:')
160
+ # for ln in str(inst.box).split('\n'):
161
+ # logger.debug(ln)
162
+ if wrap_coords:
163
+ inst.wrap_coords()
164
+ return inst
165
+
166
+ @classmethod
167
+ def read_mol2(cls,filename):
168
+ """read_mol2 Reads in a Sybyl MOL2 file into a Coordinates instance.
169
+ Note that this method only reads in
170
+ MOLECULE, ATOM, and BOND sections.
171
+
172
+ :param filename: name of input mol2 file
173
+ :type filename: str
174
+ :return: a new Coordinates instance
175
+ :rtype: Coordinates
176
+ """
177
+ '''***ALL LENGTHS CONVERTED FROM ANGSTROMS TO NM***'''
178
+ inst=cls(name=filename)
179
+ ''' Length units in MOL2 are always Ångström '''
180
+ with open(filename,'r') as f:
181
+ rawsections=f.read().split('@<TRIPOS>')[1:]
182
+ sections={}
183
+ for rs in rawsections:
184
+ s=rs.split('\n')
185
+ key=s[0].strip().lower()
186
+ val=[a.strip() for a in s[1:] if len(a)>0]
187
+ if key=='atom' or key=='bond':
188
+ val=StringIO('\n'.join(val))
189
+ sections[key]=val
190
+ inst.name=sections['molecule'][0]
191
+ imetadat=list(map(int,sections['molecule'][1].strip().split()))
192
+ inst.metadat['N']=inst.N=imetadat[0]
193
+ inst.metadat['nBonds']=imetadat[1]
194
+ inst.metadat['nSubs']=imetadat[2]
195
+ inst.metadat['nFeatures']=imetadat[3]
196
+ inst.metadat['nSets']=imetadat[4]
197
+ inst.metadat['mol2type']=sections['molecule'][2]
198
+ inst.metadat['mol2chargetype']=sections['molecule'][3]
199
+ inst.A=pd.read_csv(sections['atom'],sep='\s+',names=Coordinates.mol2_atom_attributes)
200
+ inst.A[['posX','posY','posZ']]*=[0.1,0.1,0.1]
201
+ inst.N=inst.A.shape[0]
202
+ inst.mol2_bonds=pd.read_csv(sections['bond'],sep='\s+',names=Coordinates.mol2_bond_attributes,dtype=Coordinates.mol2_bond_types)
203
+ # sort so atom indices are increasing in each bond
204
+ for i,r in inst.mol2_bonds.iterrows():
205
+ ai=r['ai']
206
+ aj=r['aj']
207
+ if aj<ai:
208
+ logger.debug(f'mol2 bonds swapping {ai} and {aj}')
209
+ inst.mol2_bonds.iloc[i,inst.mol2_bonds.columns=='ai']=aj
210
+ inst.mol2_bonds.iloc[i,inst.mol2_bonds.columns=='aj']=ai
211
+ inst.mol2_bondlist=Bondlist.fromDataFrame(inst.mol2_bonds)
212
+ inst.empty=False
213
+ return inst
214
+
215
+ @classmethod
216
+ def fcc(cls,a,nc=[1,1,1]):
217
+ """fcc generates a Coordinates object that represents an FCC crystal
218
+
219
+ :param a: lattice parameter
220
+ :type a: float
221
+ :param nc: number of unit cells in the three lattice vector directions, defaults to [1,1,1]
222
+ :type nc: list, optional
223
+ :return: a Coordinates object
224
+ :rtype: Coordinates
225
+ """
226
+ inst=cls()
227
+ basis=np.identity(3)*a
228
+ base_atoms=np.array([[0.0,0.0,0.0],[0.5,0.5,0.0],[0.5,0.0,0.5],[0.0,0.5,0.5]])*a
229
+ n=0
230
+ p=[]
231
+ x=[list(range(n)) for n in nc]
232
+ for i,j,k in product(*x):
233
+ ll=np.dot(basis,np.array([i,j,k]))
234
+ for m in range(len(base_atoms)):
235
+ p.append(ll+base_atoms[m])
236
+ # print(p)
237
+ posn=np.array(p)
238
+ # print(posn)
239
+ N=len(posn)
240
+ adf=inst.A
241
+ adf['globalIdx']=list(range(1,N+1))
242
+ adf['atomName']='AL'
243
+ adf['resNum']=list(range(1,N+1))
244
+ adf['posX']=posn[:,0]
245
+ adf['posY']=posn[:,1]
246
+ adf['posZ']=posn[:,2]
247
+ adf['resName']='MET'
248
+ inst.N=N
249
+ return inst
250
+
251
+ def set_box(self,box:np.ndarray):
252
+ """set_box Set the box size from box
253
+
254
+ :param box: 3-by-1 or 3-by-3 box size matrix
255
+ :type box: numpy.ndarray
256
+ """
257
+ if box.shape==(3,1):
258
+ for i in range(3):
259
+ self.box[i,i]=box[i]
260
+ elif box.shape==(3,3):
261
+ self.box=np.copy(box)
262
+
263
+ def total_volume(self,units='gromacs'):
264
+ """Returns total volume of box.
265
+
266
+ :param units: unit system designation; if 'SI' returns m^3, defaults to 'gromacs'
267
+ :type units: str, optional
268
+ :return: volume (in nm^3 if units is 'gromacs' or m^3 if units is 'SI')
269
+ :rtype: float
270
+ """
271
+ nm_per_m=1.e9
272
+ vol=np.prod(self.box.diagonal()) # nm^3
273
+ return vol if units!='SI' else vol/(nm_per_m**3)
274
+
275
+ def copy_coords(self,other):
276
+ """copy_coords copy_coords copy the posX, posY, and posZ atom attributes, and the box size,
277
+ from other.A to self.A
278
+
279
+ :param other: the other Coordinates instance
280
+ :type other: Coordinates
281
+ """
282
+ assert self.A.shape[0]==other.A.shape[0],f'Cannot copy -- atom count mismatch {self.A.shape[0]} vs {other.A.shape[0]}'
283
+ for c in ['posX','posY','posZ']:
284
+ otherpos=other.A[c].copy()
285
+ self.A[c]=otherpos
286
+ self.box=np.copy(other.box)
287
+
288
+ def subcoords(self,sub_adf:pd.DataFrame):
289
+ """subcoords generates a new Coordinates object to hold the atoms dataframe in 'sub_adf' parameter
290
+
291
+ :param sub_adf: an atom dataframe
292
+ :type sub_adf: pd.DataFrame
293
+ :return: a new Coordinates object
294
+ :rtype: Coordinates
295
+ """
296
+ newC=Coordinates()
297
+ newC.set_box(self.box)
298
+ newC.A=sub_adf
299
+ newC.N=sub_adf.shape[0]
300
+ return newC
301
+
302
+ def reconcile_subcoords(self,subc,attr):
303
+ """moves all values of attribute name contained in attr from Coordinates object subc to self
304
+
305
+ :param subc: A separate, independent Coordinates object
306
+ :type subc: Coordinates
307
+ :param attr: attribute name whose value is to be copied from subc to self
308
+ :type attr: str
309
+ """
310
+ jdx=list(subc.A.columns).index(attr)
311
+ for r in subc.A.itertuples(index=False):
312
+ idx=r.globalIdx
313
+ lc_idx=r[jdx]
314
+ self.A.loc[idx-1,attr]=lc_idx
315
+
316
+ def unwrap(self,P,O,pbc):
317
+ """unwrap shifts point P to its unwrapped closest periodic image to point O
318
+
319
+ :param P: a point
320
+ :type P: np.ndarray(3,float)
321
+ :param O: origin
322
+ :type O: np.ndarray(3,float)
323
+ :param pbc: directions in which pbc are applied
324
+ :type pbc: np.ndarray(3,int)
325
+ :return: a point
326
+ :rtype: nd.ndarray(3,float)
327
+ """
328
+ ROP=self.mic(O-P,pbc)
329
+ PCPI=O-ROP
330
+ return PCPI
331
+
332
+ def pierces(self,B:pd.DataFrame,C:pd.DataFrame,pbc):
333
+ """pierces determines whether or not bond represented by two points in B pierces ring represented by N points in C
334
+
335
+ :param B: two points defining a bond
336
+ :type B: pd.DataFrame
337
+ :param C: N points defining a ring
338
+ :type C: pd.DataFrame
339
+ :param pbc: periodic boundary condition flags, one per dimension
340
+ :type pbc: list
341
+ :return: True if ring is pierced
342
+ :rtype: bool
343
+ """
344
+ BC=np.array(B[['posX','posY','posZ']])
345
+ CC=np.array(C[['posX','posY','posZ']])
346
+ # get both atoms in bond into CPI
347
+ # get all atoms in ring into CPI (but not necessarily wrt bond)
348
+ CC[1:]=np.array([self.unwrap(c,CC[0],pbc) for c in CC[1:]])
349
+ BC[0]=self.unwrap(BC[0],CC[0],pbc)
350
+ BC[1]=self.unwrap(BC[1],BC[0],pbc)
351
+ B[['posX','posY','posZ']]=BC
352
+ C[['posX','posY','posZ']]=CC
353
+ S=Segment(BC)
354
+ R=Ring(CC)
355
+ R.analyze()
356
+ do_it,point=R.segint(S)
357
+ return do_it
358
+
359
+ def linkcell_initialize(self,cutoff=0.0,ncpu=1,populate=True,force_repopulate=False,save=True):
360
+ """linkcell_initialize initializes link-cell structure for ring-pierce testing
361
+
362
+ :param cutoff: cutoff radius for link-cell structure, defaults to 0.0
363
+ :type cutoff: float, optional
364
+ :param ncpu: number of cpus to use to populate link-cell structure, defaults to 1
365
+ :type ncpu: int, optional
366
+ :param populate: If True, an actual population of the link-cell structure is performed; defaults to True
367
+ :type populate: bool, optional
368
+ :param force_repopulate: If True and this link-cell structure is already populated, a repopulation is performed based on the current Coordinates; defaults to False
369
+ :type force_repopulate: bool, optional
370
+ :param save: If true, all atoms' linkcell_idx attributes are written to an output file; defaults to True
371
+ :type save: bool, optional
372
+ """
373
+ logger.debug('Initializing link-cell structure')
374
+ self.linkcell.create(cutoff,self.box)
375
+ if populate:
376
+ lc_file=f'linkcell-{cutoff:.2f}.grx'
377
+ if os.path.exists(lc_file) and not force_repopulate:
378
+ logger.debug(f'Found {lc_file}; no need to populate.')
379
+ results=self.read_atomset_attributes(lc_file)
380
+ logger.debug(f'Read linkcell_idx from {lc_file} {("linkcell_idx" in self.A)} {results}')
381
+ self.linkcell.make_memberlists(self.A)
382
+ else:
383
+ self.set_atomset_attribute('linkcell_idx',-1*np.ones(self.A.shape[0]).astype(int))
384
+ sc=self.subcoords(self.A[(self.A['cycle_idx']>0)|(self.A['z']>0)].copy())
385
+ self.linkcell.populate(sc,ncpu=ncpu)
386
+ self.reconcile_subcoords(sc,'linkcell_idx')
387
+ if save:
388
+ self.write_atomset_attributes(['linkcell_idx'],lc_file)
389
+
390
+ def linkcelltest(self,i,j):
391
+ """linkcelltest returns True if atoms i and j are within potential interaction
392
+ range based on current link-cell structure
393
+
394
+ :param i: An atom index
395
+ :type i: int
396
+ :param j: another atom index
397
+ :type j: int
398
+ :return: True if i and j are in the same cell or in neighboring cells
399
+ :rtype: bool
400
+ """
401
+ ci=self.get_atom_attribute('linkcell_idx',{'globalIdx':i})
402
+ cj=self.get_atom_attribute('linkcell_idx',{'globalIdx':j})
403
+ if ci==cj:
404
+ return True
405
+ if self.linkcell.are_ldx_neighbors(ci,cj):
406
+ return True
407
+ return False
408
+
409
+ def geometric_center(self):
410
+ """geometric_center computes and returns the geometric center of the atoms in self's A dataframe
411
+
412
+ :return: geometric center
413
+ :rtype: np.ndarray(3,float)
414
+ """
415
+ a=self.A
416
+ return np.array([a.posX.mean(),a.posY.mean(),a.posZ.mean()])
417
+
418
+ def rij(self,i,j,pbc=[1,1,1]):
419
+ """rij compute distance between atoms i and j
420
+
421
+ :return: distance between i and j
422
+ :rtype: float
423
+ """
424
+ if np.any(pbc) and not np.any(self.box):
425
+ logger.warning('Interatomic distance calculation using PBC with no boxsize set.')
426
+ ri=self.get_R(i)
427
+ rj=self.get_R(j)
428
+ Rij=self.mic(ri-rj,pbc)
429
+ return np.sqrt(Rij.dot(Rij))
430
+
431
+ def mic(self,r,pbc):
432
+ """mic applies minimum image convention to displacement vector r
433
+
434
+ :param r: displacement vector
435
+ :type r: np.ndarray(3,float)
436
+ :param pbc: periodic boundary condition
437
+ :type pbc: _type_
438
+ :return: _description_
439
+ :rtype: _type_
440
+ """
441
+ ''' '''
442
+ for c in range(0,3):
443
+ if pbc[c]:
444
+ hbx=self.box[c][c]/2
445
+ while r[c]<-hbx:
446
+ r[c]+=self.box[c][c]
447
+ while r[c]>hbx:
448
+ r[c]-=self.box[c][c]
449
+ return r
450
+
451
+ def wrap_point(self,ri):
452
+ """wrap_point wraps point ri into the central periodic image
453
+
454
+ :param ri: a point
455
+ :type ri: np.ndarray(3,float)
456
+ :return: a tuple containing (1) the wrapped point and (2) number of box lengths required to wrap this point, per dimension
457
+ :rtype: tuple
458
+ """
459
+ R=ri.copy()
460
+ box_lengths=np.array([0,0,0],dtype=int)
461
+ for i in range(3):
462
+ while R[i]<0:
463
+ R[i]+=self.box[i][i]
464
+ box_lengths[i]+=1
465
+ while R[i]>=self.box[i][i]:
466
+ R[i]-=self.box[i][i]
467
+ box_lengths[i]-=1
468
+ return R,box_lengths
469
+
470
+ def wrap_coords(self):
471
+ """wrap_coords Wraps all atomic coordinates into box
472
+ """
473
+ assert np.any(self.box),f'Cannot wrap if boxsize is not set: {self.box}'
474
+ sp=self.A[['posX','posY','posZ']]
475
+ boxL=[]
476
+ for i,srow in sp.iterrows():
477
+ p,box_lengths=self.wrap_point(srow.values)
478
+ self.A.loc[i,'posX':'posZ']=p
479
+ boxL.append(box_lengths)
480
+ boxL=np.array(boxL)
481
+ self.A['boxLx']=boxL[:,0]
482
+ self.A['boxLy']=boxL[:,1]
483
+ self.A['boxLz']=boxL[:,2]
484
+ # logger.debug(f'Wrapped {self._nwrap}/{self.A.shape[0]*3} coordinates.')
485
+
486
+ def merge(self,other):
487
+ """merge Merge two Coordinates objects
488
+
489
+ :param other: the other Coordinates object
490
+ :type other: Coordinates
491
+ :return: integer shifts in atom index, bond index, and residue index as a 3-tuple
492
+ :rtype: tuple
493
+ """
494
+ idxshift=self.A.shape[0]
495
+ bdxshift=self.mol2_bonds.shape[0]
496
+ rdxshift=0 if self.A.empty else self.A.iloc[-1]['resNum']
497
+ nOtherBonds=0
498
+ if not other.A.empty:
499
+ oa=other.A.copy()
500
+ ''' shift residue indices in other before merging '''
501
+ oa['globalIdx']+=idxshift
502
+ oa['resNum']+=rdxshift
503
+ self.A=pd.concat((self.A,oa),ignore_index=True)
504
+ self.N+=oa.shape[0]
505
+ if not other.mol2_bonds.empty:
506
+ ob=other.mol2_bonds.copy()
507
+ ''' count number of mol2_bonds in other '''
508
+ nOtherBonds=ob.shape[0]
509
+ ''' shift bond indices in other '''
510
+ ob['bondIdx']+=bdxshift
511
+ for i in ['ai','aj']:
512
+ ob[i]+=idxshift
513
+ self.mol2_bonds=pd.concat((self.mol2_bonds,ob),ignore_index=True)
514
+ self.mol2_bondlist.update(ob)
515
+ self.metadat['N']=self.N
516
+ if 'nBonds' in self.metadat:
517
+ self.metadat['nBonds']+=nOtherBonds
518
+ else:
519
+ self.metadat['nBonds']=nOtherBonds
520
+
521
+ return (idxshift,bdxshift,rdxshift)
522
+
523
+ def write_atomset_attributes(self,attributes,filename,formatters=[]):
524
+ """write_atomset_attributes Writes atom attributes to a file
525
+
526
+ :param attributes: List of attribute names to write
527
+ :type attributes: list, optional
528
+ :param filename: Name of file to write
529
+ :type filename: str
530
+ :param formatters: formatting methods per attribute, defaults to []
531
+ :type formatters: list
532
+ :raises Exception: All items in attributes must exist in the coordinates dataframe
533
+ """
534
+ for a in attributes:
535
+ if not a in self.A.columns:
536
+ raise Exception(f'There is no column "{a}" in this atoms dataframe')
537
+ with open(filename,'w') as f:
538
+ if len(formatters)>0:
539
+ f.write(self.A[['globalIdx']+attributes].to_string(header=True,index=False,formatters=formatters)+'\n')
540
+ else:
541
+ f.write(self.A[['globalIdx']+attributes].to_string(header=True,index=False)+'\n')
542
+
543
+ def read_atomset_attributes(self,filename,attributes=[]):
544
+ """Reads atomic attributes from input file
545
+
546
+ :param filename: name of file
547
+ :type filename: str
548
+ :param attributes: list of attributes to take, defaults to [] (take all)
549
+ :type attributes: list, optional
550
+ """
551
+ assert os.path.exists(filename),f'Error: {filename} not found'
552
+ # if no particular attributes are asked for, read them all in
553
+ if len(attributes)==0:
554
+ df=pd.read_csv(filename,sep='\s+',header=0)
555
+ assert 'globalIdx' in df,f'Error: {filename} does not have a \'globalIdx\' column'
556
+ attributes_read=list(df.columns)
557
+ attributes_read.remove('globalIdx')
558
+ else:
559
+ df=pd.read_csv(filename,sep='\s+',names=['globalIdx']+attributes,header=0)
560
+ attributes_read=attributes
561
+ logger.debug(f'Read from {filename}\n{df.head().to_string()}')
562
+ logger.debug(f'Merge:\n{self.A.head().to_string()}\nand\n{df.head().to_string()}')
563
+ self.A=self.A.merge(df,how='outer',on='globalIdx')
564
+ logger.debug(f'Result:\n{self.A.head().to_string()}')
565
+ return attributes_read
566
+
567
+ def set_atomset_attribute(self,attribute,srs):
568
+ """set_atomset_attribute sets attribute of atoms to srs
569
+
570
+ :param attribute: name of attribute
571
+ :type attribute: str
572
+ :param srs: scalar or list-like attribute values in same ordering as self.A
573
+ :type srs: scalar or list-like
574
+ """
575
+ self.A[attribute]=srs
576
+
577
+ def atomcount(self):
578
+ """atomcount returns the number of atoms in the Coordinates object
579
+
580
+ :return: number of atoms
581
+ :rtype: int
582
+ """
583
+ return self.N
584
+
585
+ def decrement_z(self,pairs):
586
+ """decrement_z decrements value of z attributes of all atoms found in pairs
587
+
588
+ :param pairs: list of atom index pairs, interpreted as new bonds that just formed
589
+ :type pairs: list of 2-tuples
590
+ """
591
+ for b in pairs:
592
+ ai,aj=b
593
+ # ain=self.get_atom_attribute('atomName',{'globalIdx':ai})
594
+ # ajn=self.get_atom_attribute('atomName',{'globalIdx':aj})
595
+ iz=self.get_atom_attribute('z',{'globalIdx':ai})-1
596
+ assert iz>=0,f'Error: decrementing z of atom {ai} gives erroneous z {iz}'
597
+ jz=self.get_atom_attribute('z',{'globalIdx':aj})-1
598
+ assert jz>=0,f'Error: decrementing z of atom {aj} gives erroneous z {jz}'
599
+ # logger.debug(f'Setting z of {ain}-{ai} to {iz}')
600
+ # logger.debug(f'Setting z of {ajn}-{aj} to {jz}')
601
+ self.set_atom_attribute('z',iz,{'globalIdx':ai})
602
+ self.set_atom_attribute('z',jz,{'globalIdx':aj})
603
+ inr=self.get_atom_attribute('nreactions',{'globalIdx':ai})+1
604
+ jnr=self.get_atom_attribute('nreactions',{'globalIdx':aj})+1
605
+ # logger.debug(f'Setting z of {ain}-{ai} to {iz}')
606
+ # logger.debug(f'Setting z of {ajn}-{aj} to {jz}')
607
+ self.set_atom_attribute('nreactions',inr,{'globalIdx':ai})
608
+ self.set_atom_attribute('nreactions',jnr,{'globalIdx':aj})
609
+
610
+ def show_z_report(self):
611
+ """show_z_report generates a little text-based histogram displaying number of atoms with each value of z between 0 and 3; atoms are keyed by resname:atomname.
612
+ """
613
+ zhists={}
614
+ for r in self.A.itertuples():
615
+ n=r.atomName
616
+ nn=r.resName
617
+ k=f'{nn}:{n}'
618
+ z=r.z
619
+ if not k in zhists:
620
+ zhists[k]=np.zeros(4).astype(int)
621
+ zhists[k][z]+=1
622
+ for n in zhists:
623
+ if any([zhists[n][i]>0 for i in range(1,4)]):
624
+ logger.debug(f'Z-hist for {n} atoms:')
625
+ for i in range(4):
626
+ logger.debug(f'{i:>5d} ({zhists[n][i]:>6d}): '+'*'*(zhists[n][i]//10))
627
+
628
+ def return_bond_lengths(self,bdf):
629
+ """return_bond_lengths returns an ordered list of bond lengths computed based on bonds indicated by the parallel 'ai' and 'aj' columns of the parameter dataframe bdf
630
+
631
+ :param bdf: a pandas dataframe with 'ai' and 'aj' columns of atom indices indicating bonds
632
+ :type bdf: pd.DataFrame
633
+ :return: list of atom distances
634
+ :rtype: list
635
+ """
636
+ lengths=[]
637
+ for b in bdf.itertuples():
638
+ lengths.append(self.rij(b.ai,b.aj))
639
+ return lengths
640
+
641
+ def add_length_attribute(self,bdf,attr_name='length'):
642
+ """add_length_attribute computes bond lengths based on bonds indicated by the parallel 'ai' and 'aj' columns of the parameter dataframe bdf and stores result in a new column called attr_name
643
+
644
+ :param bdf: a pandas dataframe with 'ai' and 'aj' columns of atom indices indicating bonds
645
+ :type bdf: pd.DataFrame
646
+ :param attr_name: name of length attribute column, defaults to 'length'
647
+ :type attr_name: str, optional
648
+ """
649
+ lengths=[]
650
+ for b in bdf.itertuples():
651
+ lengths.append(self.rij(b.ai,b.aj))
652
+ bdf[attr_name]=lengths
653
+
654
+ def minimum_distance(self,other,self_excludes=[],other_excludes=[]):
655
+ """minimum_distance Computes and returns distance of closest approach between two sets of atoms
656
+
657
+ :param other: other Coordinates instance
658
+ :type other: Coordinates
659
+ :param self_excludes: list of atom indexes in self to NOT consider, defaults to []
660
+ :type self_excludes: list, optional
661
+ :param other_excludes: list of atom indexes in other to NOT consider, defaults to []
662
+ :type other_excludes: list, optional
663
+ :return: distance of closest approach: i.e., the distance between the two atoms, one from self and one from other, that are closest together
664
+ :rtype: float
665
+ """
666
+ sp=self.A[~self.A['globalIdx'].isin(self_excludes)][['posX','posY','posZ']]
667
+ op=other.A[~other.A['globalIdx'].isin(other_excludes)][['posX','posY','posZ']]
668
+ minD=1.e9
669
+ for i,srow in sp.iterrows():
670
+ ri=srow.values
671
+ for j,orow in op.iterrows():
672
+ rj=orow.values
673
+ rij=ri-rj
674
+ D=np.sqrt(np.dot(rij,rij))
675
+ if D<minD:
676
+ minD=D
677
+ return minD
678
+
679
+ def rotate(self,R):
680
+ """rotate Rotates all coordinate vectors by rotation matrix R
681
+
682
+ :param R: rotation matrix (3x3)
683
+ :type R: numpy.ndarray
684
+ """
685
+ sp=self.A[['posX','posY','posZ']]
686
+ for i,srow in sp.iterrows():
687
+ ri=srow.values
688
+ newri=np.matmul(R,ri)
689
+ self.A.loc[i,'posX':'posZ']=newri
690
+
691
+ def translate(self,L):
692
+ """translate Translates all coordinate vectors by displacement vector L
693
+
694
+ :param L: displacement vector (nm)
695
+ :type L: numpy.ndarray
696
+ """
697
+ sp=self.A[['posX','posY','posZ']]
698
+ for i,srow in sp.iterrows():
699
+ self.A.loc[i,'posX':'posZ']=srow.values+L
700
+
701
+ def maxspan(self):
702
+ """Returns dimensions of orthorhombic convex hull enclosing Coordinates
703
+
704
+ :return: array of x-span, y-span, z-span
705
+ :rtype: numpy.ndarray
706
+ """
707
+ sp=self.A[['posX','posY','posZ']]
708
+ return np.array(
709
+ [
710
+ sp.posX.max()-sp.posX.min(),
711
+ sp.posY.max()-sp.posY.min(),
712
+ sp.posZ.max()-sp.posZ.min()
713
+ ]
714
+ )
715
+
716
+ def minmax(self):
717
+ """minmax returns the coordinates of the atoms at the lower-leftmost and upper-rightmost positions in the constellation of points in the atoms dataframe
718
+
719
+ :return: tuple of two points, lower-leftmost and upper-rightmost, respectively
720
+ :rtype: tuple(np.ndarray(3,float),np.ndarray(3,float))
721
+ """
722
+ sp=self.A[['posX','posY','posZ']]
723
+ return np.array([sp.posX.min(),sp.posY.min(),sp.posZ.min()]),np.array([sp.posX.max(),sp.posY.max(),sp.posZ.max()])
724
+
725
+ def checkbox(self):
726
+ """checkbox checks that the entire constellation of points in the atoms dataframe fits within the designated box for this Configuration object
727
+
728
+ :return: True,True if both lower-leftmost and upper-rightmost points are within the box
729
+ :rtype: tuple(bool,bool)
730
+ """
731
+ mm,MM=self.minmax()
732
+ bb=self.box.diagonal()
733
+ return mm<bb,MM>bb
734
+
735
+ def get_idx(self,attributes):
736
+ """get_idx returns the global atom index of the atom in the atoms dataframe which has the attribute:value pairs indicated in the parameter attributes
737
+
738
+ :param attributes: dictionary of attribute:value pairs that identify the atom
739
+ :type attributes: dict
740
+ :return: global atom index
741
+ :rtype: int
742
+ """
743
+ df=self.A
744
+ return get_row_attribute(df,'globalIdx',attributes)
745
+
746
+ def get_R(self,idx):
747
+ """get_R return the cartesian position of atom with global index idx
748
+
749
+ :param idx: global index of atom
750
+ :type idx: int
751
+ :return: its cartesian position
752
+ :rtype: numpy.ndarray(3,float)
753
+ """
754
+ df=self.A
755
+ return get_row_attribute(df,['posX','posY','posZ'],{'globalIdx':idx})
756
+
757
+ def get_atom_attribute(self,name,attributes):
758
+ """get_atom_attribute return values of attributes listed in name from atoms specified by attribute:value pairs in attributes
759
+
760
+ :param name: list of attributes whose values are to be returned
761
+ :type name: list
762
+ :param attributes: dictionary of attribute:value pairs that specify the set of atoms to be considered
763
+ :type attributes: dict
764
+ :return: scalar or list of one or more return attribute values
765
+ :rtype: list if name is a list; scalar otherwise
766
+ """
767
+ df=self.A
768
+ if type(name)==list:
769
+ assert all([i in self.A.columns for i in name])
770
+ else:
771
+ assert name in self.A.columns,f'{name} not found in attributes\n{df.columns}'
772
+ return get_row_attribute(df,name,attributes)
773
+
774
+ def spew_atom(self,attributes):
775
+ """spew_atom outputs all attributes of atom identified by the attributes dict
776
+
777
+ :param attributes: dictionary of attribute:value pairs that specify the set of atoms to be considered
778
+ :type attributes: dict
779
+ :return: stringified dataframe
780
+ :rtype: string
781
+ """
782
+ df=self.A
783
+ return get_row_as_string(df,attributes)
784
+
785
+ def get_atoms_w_attribute(self,name,attributes):
786
+ """get_atoms_w_attribute returns all rows of atoms dataframe and columns named in names of atoms identified by the attributes dict
787
+
788
+ :param name: list of attributes to be in the rows that are returned
789
+ :type name: list
790
+ :param attributes: dictionary of attribute:value pairs that specify the set of atoms to be considered
791
+ :type attributes: dict
792
+ :return: a dataframe segment
793
+ :rtype: pd.DataFrame
794
+ """
795
+ df=self.A
796
+ return get_rows_w_attribute(df,name,attributes)
797
+
798
+ def set_atom_attribute(self,name,value,attributes):
799
+ """set_atom_attribute set the attributes named in name to values named in values (names||values) for the set of atoms specified in the attributes dict
800
+
801
+ :param name: list of names of attributes
802
+ :type name: list
803
+ :param value: list of values of attributes to be set
804
+ :type value: list
805
+ :param attributes: dictionary of attribute:value pairs that specify the set of atoms to be considered
806
+ :type attributes: dict
807
+ """
808
+ df=self.A
809
+ set_row_attribute(df,name,value,attributes)
810
+
811
+ def has_atom_attributes(self,attributes):
812
+ """has_atom_attributes returns True if all atoms in atoms dataframe have the attribute named in attributes
813
+
814
+ :param attributes: list of attribute names to look for
815
+ :type attributes: list or list-like container
816
+ :return: True if all atoms have the attributes
817
+ :rtype: bool
818
+ """
819
+ df=self.A
820
+ return all([name in df for name in attributes])
821
+
822
+ def find_sacrificial_H(self,pairs,T,rename=False,explicit_sacH={}):
823
+ """find_sacrificial_H identifies all appropriate sacrificial hydrogen atoms determined by the bonds indicated in the pairs list of 3-tuples (ai,aj,order)
824
+
825
+ :param pairs: list of atom pairs/order tuples
826
+ :type pairs: tuple(int,int,int)
827
+ :param T: the global Topology
828
+ :type T: Topology
829
+ :param rename: If true, renames any remaining H atoms so that it appears as though highest-order named H atoms are the ones sacrificed, defaults to False
830
+ :type rename: bool, optional
831
+ :param explicit_sacH: dictionary of pre-chosen sacrificial H atoms, keyed by pair index, defaults to {}
832
+ :type explicit_sacH: dict, optional
833
+ :return: list of global atom indices to delete
834
+ :rtype: list
835
+ """
836
+ idx_to_delete=[]
837
+ for i,b in enumerate(pairs):
838
+ if not i in explicit_sacH:
839
+ ai,aj,o=b
840
+ idx_to_delete.extend(self.sacH(ai,aj,T,rename=rename))
841
+ else:
842
+ idx_to_delete.extend(explicit_sacH[i])
843
+ return idx_to_delete
844
+
845
+ def sacH(self,ai,aj,T,rename=False):
846
+ """sacH Find the two H's, one bound to ai, the other to aj, that are closest to each other
847
+
848
+ :param ai: index of one atom in bond
849
+ :type ai: int
850
+ :param aj: index of other atom in bond
851
+ :type aj: int
852
+ :param T: global topology
853
+ :type T: Topology
854
+ :param rename: whether to rename remaining H atoms bound to ai and aj so that it appears highest-sorted by name atoms are found, defaults to False
855
+ :type rename: bool, optional
856
+ :return: global indexes of two H atoms
857
+ :rtype: list
858
+ """
859
+ bondlist=T.bondlist
860
+ i_partners=bondlist.partners_of(ai)
861
+ j_partners=bondlist.partners_of(aj)
862
+ i_Hpartners={k:v for k,v in zip(i_partners,[self.A[self.A['globalIdx']==i]['atomName'].values[0] for i in i_partners]) if v.startswith('H')}
863
+ j_Hpartners={k:v for k,v in zip(j_partners,[self.A[self.A['globalIdx']==i]['atomName'].values[0] for i in j_partners]) if v.startswith('H')}
864
+ assert len(i_Hpartners)>0,f'Error: atom {ai} does not have a deletable H atom!'
865
+ assert len(j_Hpartners)>0,f'Error: atom {aj} does not have a deletable H atom!'
866
+ minHH=(1.e9,-1,-1)
867
+ for ih in i_Hpartners:
868
+ RiH=self.get_R(ih)
869
+ for jh in j_Hpartners:
870
+ RjH=self.get_R(jh)
871
+ RijH=RiH-RjH
872
+ rijh=np.sqrt(RijH.dot(RijH))
873
+ if rijh<minHH[0]:
874
+ minHH=(rijh,ih,jh)
875
+ ''' rename remaining H atoms '''
876
+ if rename:
877
+ # reverse sort names of hydrogen ligands by their number
878
+ i_avails=list(sorted(i_Hpartners.values(),key=lambda x: int(x.split('H')[1] if x.split('H')[1]!='' else '0')))[:-1]
879
+ j_avails=list(sorted(j_Hpartners.values(),key=lambda x: int(x.split('H')[1] if x.split('H')[1]!='' else '0')))[:-1]
880
+ logger.debug(f'i_avails {i_avails}')
881
+ logger.debug(f'j_avails {j_avails}')
882
+ # remove the globalIdx of the sacrificial H's from their atom's dictionaries of H-atoms
883
+ del i_Hpartners[ih]
884
+ del j_Hpartners[jh]
885
+ Top=T.D['atoms']
886
+ Cor=self.A
887
+ # for all remaining H neighbor globalIdx of each atom, rename starting from lowest number
888
+ for h in i_Hpartners:
889
+ i_Hpartners[h]=i_avails.pop(0)
890
+ Top.iloc[h-1,Top.columns=='atom']=i_Hpartners[h]
891
+ Cor.iloc[h-1,Cor.columns=='atomName']=i_Hpartners[h]
892
+ logger.debug(f'i: changed name of {h} to {i_Hpartners[h]}')
893
+ for h in j_Hpartners:
894
+ j_Hpartners[h]=j_avails.pop(0)
895
+ Top.iloc[h-1,Top.columns=='atom']=j_Hpartners[h]
896
+ Cor.iloc[h-1,Cor.columns=='atomName']=j_Hpartners[h]
897
+ logger.debug(f'j: changed name of {h} to {j_Hpartners[h]}')
898
+ # this makes sure that it always looks like the same atom was deleted
899
+ return [ih,jh] # return the globalIdx's of the two sacrificial H's
900
+
901
+ def delete_atoms(self,idx=[],reindex=True):
902
+ """delete_atoms Deletes atoms whose global indices appear in the list idx.
903
+ If parameter 'reindex' is true, then the global indices
904
+ are recalculated so that they are sequential starting at 1 with no
905
+ gaps, and two new columns are added to self.DF: 'oldGlobalIdx' contains the global index values before the deletion, and 'globalIdxShift' is the change from the old to the new global index for each atom.
906
+
907
+ :param idx: list of atom indexes to delete, defaults to []
908
+ :type idx: list, optional
909
+ :param reindex: reindex remaining atoms, defaults to True
910
+ :type reindex: bool, optional
911
+ """
912
+ # logger.debug(f'Coordinates:delete_atoms {idx}')
913
+ adf=self.A
914
+ indexes_to_drop=adf[adf.globalIdx.isin(idx)].index
915
+ indexes_to_keep=set(range(adf.shape[0]))-set(indexes_to_drop)
916
+ self.A=adf.take(list(indexes_to_keep)).reset_index(drop=True)
917
+ if reindex:
918
+ adf=self.A
919
+ oldGI=adf['globalIdx'].copy()
920
+ adf['globalIdx']=adf.index+1
921
+ mapper={k:v for k,v in zip(oldGI,adf['globalIdx'])}
922
+ self.N-=len(idx)
923
+ ''' delete appropriate bonds '''
924
+ if not self.mol2_bonds.empty:
925
+ d=self.mol2_bonds
926
+ indexes_to_drop=d[(d.ai.isin(idx))|(d.aj.isin(idx))].index
927
+ indexes_to_keep=set(range(d.shape[0]))-set(indexes_to_drop)
928
+ self.mol2_bonds=d.take(list(indexes_to_keep)).reset_index(drop=True)
929
+ if reindex:
930
+ d=self.mol2_bonds
931
+ d.ai=d.ai.map(mapper)
932
+ d.aj=d.aj.map(mapper)
933
+ d.bondIdx=d.index+1
934
+ if 'nBonds' in self.metadat:
935
+ self.metadat['nBonds']=len(self.mol2_bonds)
936
+ self.bondlist=Bondlist.fromDataFrame(self.mol2_bonds)
937
+
938
+ def write_gro(self,filename,grotitle=''):
939
+ """write_gro Write coordinates and if present, velocities, to a Gromacs-format coordinate file
940
+
941
+ :param filename: name of file to write
942
+ :type filename: str
943
+ """
944
+ title=self.name if not grotitle else grotitle
945
+ has_vel='velX' in self.A.columns
946
+ with open(filename,'w') as f:
947
+ f.write(title+'\n')
948
+ f.write(f'{self.N:>5d}\n')
949
+ # C-format: “%5i%5s%5s%5i%8.3f%8.3f%8.3f%8.4f%8.4f%8.4f”
950
+ # Note that the gro atom number is not used; gromacs assigns atom indicies based
951
+ # on counting input lines! We will wrap the index so that it only has 5 digits.
952
+ atomformatters = [
953
+ lambda x: f'{x:>5d}',
954
+ lambda x: f'{x:<5s}',
955
+ lambda x: f'{x:>5s}',
956
+ lambda x: f'{x%10000:5d}']+[lambda x: f'{x:8.3f}']*3 + [lambda x: f'{x:8.4f}']*3
957
+ # unfortunately, DataFrame.to_string() can't write fields with zero whitespace
958
+ for i,r in self.A.iterrows():
959
+ if has_vel:
960
+ f.write(''.join([atomformatters[i](v) for i,v in enumerate(list(r[self.gro_attributes]))])+'\n')
961
+ else:
962
+ f.write(''.join([atomformatters[i](v) for i,v in enumerate(list(r[self.gro_attributes[:-3]]))])+'\n')
963
+ if not np.any(self.box):
964
+ logger.debug('Writing Gromacs coordinates file but boxsize is not set.')
965
+ f.write(f'{self.box[0][0]:10.5f}{self.box[1][1]:10.5f}{self.box[2][2]:10.5f}')
966
+ # output off-diagonals only if at least one of them is non-zero
967
+ x,y=self.box.nonzero()
968
+ if not all(x==y):
969
+ f.write(f'{self.box[0][1]:10.5f}{self.box[0][2]:10.5f}')
970
+ f.write(f'{self.box[1][0]:10.5f}{self.box[1][2]:10.5f}')
971
+ f.write(f'{self.box[2][0]:10.5f}{self.box[2][1]:10.5f}')
972
+ f.write('\n')
973
+
974
+ def write_mol2(self,filename,bondsDF=pd.DataFrame(),molname='',other_attributes=pd.DataFrame()):
975
+ """write_mol2 Write a mol2-format file from coordinates, and optionally, a bonds DataFrame
976
+ provided externally and passed in as "bondsDF" (typically this would be
977
+ from a Topology instance).
978
+
979
+ :param filename: name of file name to write
980
+ :type filename: str, optional
981
+ :param bondsDF: dataframe of bonds ['ai','aj'], defaults to pd.DataFrame()
982
+ :type bondsDF: pandas.DataFrame, optional
983
+ :param molname: name of molecule, defaults to ''
984
+ :type molname: str, optional
985
+ :param other_attributes: auxiliary dataframe of attributes, defaults to pd.DataFrame()
986
+ :type other_attributes: pandas.DataFrame, optional
987
+ """
988
+ # logger.debug(f'write_mol2 {filename}')
989
+ acopy=self.A.copy()
990
+ bdf=pd.DataFrame()
991
+ if bondsDF.empty and self.mol2_bonds.empty:
992
+ logger.warning(f'Cannot write any bonds to MOL2 file {filename}')
993
+ elif (not self.mol2_bonds.empty) and bondsDF.empty:
994
+ bdf=self.mol2_bonds
995
+ elif (not bondsDF.empty) and self.mol2_bonds.empty:
996
+ bdf=bondsDF
997
+ else:
998
+ logger.info('Coordinates.write_mol2 provided with both a bondsDF parameter and a mol2_bonds attribute')
999
+ logger.info('Using the parameter')
1000
+ bdf=bondsDF
1001
+ for i in other_attributes.columns: #self.mol2_atom_attributes:
1002
+ # logger.debug(f'importing/overwriting other_attribute {i}...')
1003
+ acopy[i]=other_attributes[i]
1004
+ # logger.debug(f'Updated [ atoms ]:\n{acopy.to_string()}')
1005
+ com=self.geometric_center()
1006
+ if filename!='':
1007
+ atomformatters = [
1008
+ lambda x: f'{x:>7d}',
1009
+ lambda x: f'{x:<8s}',
1010
+ lambda x: f'{x:>9.4f}',
1011
+ lambda x: f'{x:>9.4f}',
1012
+ lambda x: f'{x:>9.4f}',
1013
+ lambda x: f'{x:<5s}',
1014
+ lambda x: f'{x:>3d}',
1015
+ lambda x: f' {x:<7s}',
1016
+ lambda x: f'{x:>9.4f}'
1017
+ ]
1018
+ bondformatters = [
1019
+ lambda x: f'{x:>6d}',
1020
+ lambda x: f'{x:>5d}',
1021
+ lambda x: f'{x:>5d}',
1022
+ lambda x: f'{str(x):>4s}'
1023
+ ]
1024
+ substructureformatters = [
1025
+ lambda x: f'{x:>6d}',
1026
+ lambda x: f'{x:<7s}',
1027
+ lambda x: f'{x:>6d}',
1028
+ lambda x: f'{x:<7s}'
1029
+ ]
1030
+ with open(filename,'w') as f:
1031
+ f.write('@<TRIPOS>MOLECULE\n')
1032
+ if molname=='':
1033
+ f.write(f'{self.name}\n')
1034
+ else:
1035
+ f.write(f'{molname}\n')
1036
+ N=acopy.shape[0] #self.N
1037
+ # Infer the residue names and resids from the atom records
1038
+ rdf=acopy[['resNum','resName']].copy().drop_duplicates()
1039
+ rdf['rootatom']=[1]*len(rdf)
1040
+ rdf['residue']=['RESIDUE']*len(rdf)
1041
+ nBonds=bdf.shape[0]
1042
+ nSubs=len(rdf)
1043
+ nFeatures=self.metadat.get('nFeatures',0)
1044
+ nSets=self.metadat.get('nSets',0)
1045
+ f.write('{:>6d}{:>6d}{:>3d}{:>3d}{:>3d}\n'.format(N,nBonds,nSubs, nFeatures,nSets))
1046
+ f.write(f"{self.metadat.get('mol2type','SMALL')}\n")
1047
+ f.write(f"{self.metadat.get('mol2chargetype','GASTEIGER')}\n")
1048
+ f.write('\n')
1049
+ f.write('@<TRIPOS>ATOM\n')
1050
+ # remember to convert to Angstroms
1051
+ pos=(acopy.loc[:,['posX','posY','posZ']]-com)*10.0
1052
+ acopy.loc[:,['posX','posY','posZ']]=pos
1053
+ f.write(acopy.to_string(columns=self.mol2_atom_attributes,header=False,index=False,formatters=atomformatters))
1054
+ f.write('\n')
1055
+ f.write('@<TRIPOS>BOND\n')
1056
+ if not bondsDF.empty:
1057
+ logger.debug(f'Mol2 bonds from outside')
1058
+ bdf=bondsDF[['bondIdx','ai','aj','order']].copy()
1059
+ bdf['bondIdx']=bdf['bondIdx'].astype(int)
1060
+ bdf['ai']=bdf['ai'].astype(int)
1061
+ bdf['aj']=bdf['aj'].astype(int)
1062
+ f.write(bdf.to_string(columns=self.mol2_bond_attributes,header=False,index=False,formatters=bondformatters))
1063
+ elif not self.mol2_bonds.empty:
1064
+ logger.debug(f'write_mol2 ({filename}): Mol2 bonds from mol2_bonds attribute')
1065
+ f.write(self.mol2_bonds.to_string(columns=self.mol2_bond_attributes,header=False,index=False,formatters=bondformatters))
1066
+ f.write('\n')
1067
+ ''' write substructure section '''
1068
+ f.write('@<TRIPOS>SUBSTRUCTURE\n')
1069
+ f.write(rdf.to_string(header=False,index=False,formatters=substructureformatters))
1070
+ f.write('\n')
1071
+