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/__init__.py ADDED
@@ -0,0 +1 @@
1
+ HTPOLYNET_VERSION='1.0.7.1'
@@ -0,0 +1,94 @@
1
+ """
2
+
3
+ .. module:: ambertools
4
+ :synopsis: Manages execution of AmberTools antechamber, parmchk2.
5
+
6
+ .. moduleauthor: Cameron F. Abrams, <cfa22@drexel.edu>
7
+
8
+ """
9
+ import logging
10
+ import hashlib
11
+ import shutil
12
+ import parmed
13
+ from HTPolyNet.command import Command
14
+ from HTPolyNet.coordinates import Coordinates
15
+ logger=logging.getLogger(__name__)
16
+
17
+ def GAFFParameterize(inputPrefix,outputPrefix,input_structure_format='mol2',**kwargs):
18
+ """GAFFParameterize manages execution of antechamber, tleap, and parmchk2 to generate
19
+ GAFF parameters
20
+
21
+ :param inputPrefix: basename of input structure file
22
+ :type inputPrefix: str
23
+ :param outputPrefix: basename of output files
24
+ :type outputPrefix: str
25
+ :param input_structure_format: format of input structure file, defaults to 'mol2'; 'pdb' is other option
26
+ :type input_structure_format: str, optional
27
+ :raises parmed.exceptions.GromacsError: if parmed fails
28
+ """
29
+ ambertools_dict=kwargs.get('ambertools',{})
30
+ if ambertools_dict:
31
+ chargemethod=ambertools_dict.get('charge_method','bcc')
32
+ else:
33
+ chargemethod=kwargs.get('charge_method','bcc')
34
+ logger.info(f'AmberTools> generating GAFF parameters from {inputPrefix}.{input_structure_format}')
35
+ structin=f'{inputPrefix}.{input_structure_format}'
36
+ mol2out=f'{outputPrefix}.mol2'
37
+ frcmodout=f'{outputPrefix}.frcmod'
38
+ new_structin=structin
39
+ if structin==mol2out:
40
+ new_structin=inputPrefix+f'-input.{input_structure_format}'
41
+ logger.debug(f'AmberTools> Antechamber overwrites input {structin}; backing up to {new_structin}')
42
+ shutil.copy(structin,new_structin)
43
+ groOut=f'{outputPrefix}.gro'
44
+ topOut=f'{outputPrefix}.top'
45
+ itpOut=f'{outputPrefix}.itp'
46
+ c=Command('antechamber',j=4,fi=input_structure_format,fo='mol2',c=chargemethod,at='gaff',i=new_structin,o=mol2out,pf='Y',nc=0,eq=1,pl=10)
47
+ c.run(quiet=False)
48
+ logger.debug(f'AmberTools> Antechamber generated {mol2out}')
49
+ c=Command('parmchk2',i=mol2out,o=frcmodout,f='mol2',s='gaff')
50
+ c.run(quiet=False)
51
+ # Antechamber ignores SUBSTRUCTURES but we would like tleap to
52
+ # recognize them. So we will simply use the antechamber-INPUT mol2 file
53
+ # resName and resNum atom record fields over the antechamber-OUTPUT mol2 file
54
+ # to generate the tleap-INPUT mol2 file. Also, since tleap can't handle
55
+ # wacky filenames, we'll hash the outputPrefix temporarily.
56
+ if input_structure_format=='mol2':
57
+ goodMol2=Coordinates.read_mol2(new_structin)
58
+ acOutMol2=Coordinates.read_mol2(mol2out)
59
+ adf=acOutMol2.A
60
+ adf['resName']=goodMol2.A['resName'].copy()
61
+ adf['resNum']=goodMol2.A['resNum'].copy()
62
+ goodMol2.A=adf
63
+ else:
64
+ goodMol2=Coordinates.read_mol2(mol2out)
65
+ leapprefix=hashlib.shake_128(outputPrefix.encode("utf-8")).hexdigest(16).replace('e','x')
66
+ goodMol2.write_mol2(f'{leapprefix}.mol2')
67
+ logger.debug(f'Replacing string "{outputPrefix}" with hash "{leapprefix}" for leap input files.')
68
+ Command(f'cp {frcmodout} {leapprefix}.frcmod').run()
69
+ with open(f'{inputPrefix}-tleap.in', 'w') as f:
70
+ f.write(f'source leaprc.gaff\n')
71
+ f.write(f'mymol = loadmol2 {leapprefix}.mol2\n')
72
+ f.write(f'check mymol\n')
73
+ f.write(f'loadamberparams {leapprefix}.frcmod\n')
74
+ f.write(f'saveamberparm mymol {leapprefix}-tleap.top {leapprefix}-tleap.crd\n')
75
+ f.write('quit\n')
76
+ c=Command('tleap',f=f'{inputPrefix}-tleap.in')
77
+ c.run(override=('Error!','Unspecified tleap error'))
78
+ Command(f'rm -f {leapprefix}.frcmod').run()
79
+ Command(f'mv {leapprefix}.mol2 {outputPrefix}.mol2').run()
80
+ Command(f'mv {leapprefix}-tleap.top {outputPrefix}-tleap.top').run()
81
+ Command(f'mv {leapprefix}-tleap.crd {outputPrefix}-tleap.crd').run()
82
+ # save the results of the antechamber/parmchk2/tleap sequence as Gromacs gro and top files
83
+ try:
84
+ file=parmed.load_file(f'{outputPrefix}-tleap.top', xyz=f'{outputPrefix}-tleap.crd')
85
+ logger.debug(f'Writing {groOut}, {topOut}, and {itpOut}')
86
+ file.save(groOut,overwrite=True)
87
+ file.save(topOut,parameters=itpOut,overwrite=True)
88
+ except Exception as m:
89
+ logger.error('Unspecified parmed error')
90
+ raise parmed.exceptions.GromacsError(m)
91
+
92
+
93
+
94
+
HTPolyNet/analyze.py ADDED
@@ -0,0 +1,258 @@
1
+ """
2
+
3
+ .. module:: analyze
4
+ :synopsis: handles the analyze subcommand
5
+
6
+ .. moduleauthor: Cameron F. Abrams, <cfa22@drexel.edu>
7
+
8
+ """
9
+ import logging
10
+ import os
11
+ import json
12
+ import yaml
13
+ import HTPolyNet.projectfilesystem as pfs
14
+ from HTPolyNet.gromacs import gmx_command
15
+ import HTPolyNet.software as software
16
+ from HTPolyNet.configuration import Configuration
17
+ from pathlib import Path
18
+
19
+ logger=logging.getLogger(__name__)
20
+
21
+ class Analyze:
22
+ allowed_keys=['gromacs','command','subdir','options','links','outfile','console-input','matchlines']
23
+ required_keys=['command','subdir']
24
+ default_params={
25
+ 'gromacs' : {
26
+ 'gmx': 'gmx'
27
+ },
28
+ }
29
+ def __init__(self,indict,strict=True):
30
+ self.params={}
31
+ for p,v in self.default_params.items():
32
+ self.params[p]=indict.get(p,v)
33
+ for p,v in indict.items():
34
+ if not p in self.allowed_keys:
35
+ if strict:
36
+ logger.info(f'Ignoring directive \'{p}\' in yaml input file')
37
+ if p in self.default_params:
38
+ logger.info(f'Overwriting default {p} value')
39
+ self.params[p]=v
40
+ self.console_output=None
41
+
42
+ def do(self,**gromacs_dict):
43
+ """do handles executing the analysis
44
+
45
+ """
46
+ p=self.params
47
+ print(p)
48
+ for rk in self.required_keys:
49
+ assert rk in p, f'Error: no {rk} value found'
50
+ # logger.info(f'do {p}')
51
+ # if a gromacs dict is passed in, assume this overrides the one read in from the file
52
+ if gromacs_dict:
53
+ software.set_gmx_preferences(gromacs_dict)
54
+ else:
55
+ software.set_gmx_preferences(p['gromacs'])
56
+ logger.info(f'going to {p["subdir"]}')
57
+ pfs.go_to(p['subdir'])
58
+ # make symlinks to requested files
59
+ symlinks=p.get('links',[])
60
+ for input_file in symlinks:
61
+ srcnm=os.path.join(pfs.proj(),input_file)
62
+ bsnm=os.path.basename(srcnm)
63
+ chk=Path(bsnm)
64
+ if not chk.is_symlink():
65
+ os.symlink(srcnm,bsnm)
66
+ else:
67
+ logger.info(f'Symlink {bsnm} already exists.')
68
+ cfile=''
69
+ if 'console-input' in p:
70
+ cfile='console-in.txt'
71
+ ci=p['console-input']
72
+ with open(cfile,'w') as f:
73
+ for ch in ci:
74
+ f.write(ch+'\n')
75
+ self.console_output=gmx_command(p['command'],p.get('options',{}),console_in=cfile)
76
+ logger.info(f'Command {p["command"]} completed.')
77
+
78
+ def parse_console_output(self):
79
+ if not self.console_output:
80
+ logger.info(f'No console output')
81
+ return
82
+ p=self.params
83
+ # either we are grepping out lines from console output or putting it all out there
84
+ if not 'outfile' in p:
85
+ logger.info(f'Here is the console output')
86
+ logger.info(self.console_output)
87
+ else:
88
+ if not 'matchlines' in p:
89
+ with open(p['outfile'],'w') as f:
90
+ f.write(self.console_output)
91
+ else:
92
+ svlns=[]
93
+ console_lines=self.console_output.split('\n')
94
+ for cl in console_lines:
95
+ for ml in p['matchlines']:
96
+ if ml in cl:
97
+ svlns.append(cl)
98
+ with open(p['outfile'],'w') as f:
99
+ for s in svlns:
100
+ f.write(s+'\n')
101
+ logger.info(f'Created {p["outfile"]} in {p["subdir"]}')
102
+
103
+ class AnalyzeDensity(Analyze):
104
+ """ Analyze class for handling trajectory density profile calculation
105
+ """
106
+ default_params={
107
+ 'subdir': 'analyze/density',
108
+ 'links': ['postsim/equilibrate/equilibrate.tpr','postsim/equilibrate/equilibrate.trr'],
109
+ 'gromacs' : {
110
+ 'gmx': 'gmx'
111
+ },
112
+ 'command': 'density',
113
+ 'options': {
114
+ 's':'equilibrate.tpr',
115
+ 'f':'equilibrate.trr',
116
+ 'o':'density.xvg',
117
+ 'xvg': 'none',
118
+ 'b': 0,
119
+ 'd': 'Z',
120
+ 'sl': 50
121
+ },
122
+ 'console-input': ['0']
123
+ }
124
+
125
+ class AnalyzeFFV(Analyze):
126
+ default_params={
127
+ 'subdir': 'analyze/freevolume',
128
+ 'links': ['postsim/equilibrate/equilibrate.tpr','postsim/equilibrate/equilibrate.trr'],
129
+ 'gromacs' : {
130
+ 'gmx': 'gmx'
131
+ },
132
+ 'command': 'freevolume',
133
+ 'options': {
134
+ 's':'equilibrate.tpr',
135
+ 'f':'equilibrate.trr',
136
+ 'o':'ffv.xvg',
137
+ 'xvg': 'none',
138
+ 'b': 0.0
139
+ },
140
+ 'outfile': 'ffv.dat',
141
+ 'matchlines': ['Free volume','Total volume','Number of molecules','Average molar mass','Density','Molecular volume Vm assuming homogeneity:','Molecular van der Waals volume assuming homogeneity:','Fractional free volume']
142
+ }
143
+
144
+
145
+ class AnalyzeConfiguration:
146
+ """ handles reading and parsing an analysis input config file.
147
+ Config file format
148
+
149
+ - { key1: {<paramdict>}}
150
+ - { key2: {<paramdict>}}
151
+
152
+ ...
153
+
154
+ The config file is a list of single-element dictionaries, whose single keyword
155
+ indicates the type of analysis to be run; analyses are run in the order
156
+ they appear in the config file.
157
+
158
+ """
159
+ default_class=Analyze
160
+ predefined_classes={'density':AnalyzeDensity,'freevolume':AnalyzeFFV}
161
+ def __init__(self):
162
+ self.cfgFile=''
163
+ self.baselist=[]
164
+ self.stagelist=[]
165
+
166
+ @classmethod
167
+ def read(cls,filename,parse=True,**kwargs):
168
+ """read generates a new PostsimConfiguration object by reading in the JSON or YAML file indicated by filename
169
+
170
+ :param filename: name of file from which to read new PostsimConfiguration object
171
+ :type filename: str
172
+ :param parse: if True, parse the input configuration file, defaults to True
173
+ :type parse: bool, optional
174
+ :raises Exception: if extension of filename is not '.json' or '.yaml' or '.yml'
175
+ :return: a new PostsimConfiguration object
176
+ :rtype: PostsimConfiguration
177
+ """
178
+ basename,extension=os.path.splitext(filename)
179
+ if extension=='.json':
180
+ return cls._read_json(filename,parse,**kwargs)
181
+ elif extension=='.yaml' or extension=='.yml':
182
+ return cls._read_yaml(filename,parse,**kwargs)
183
+ else:
184
+ raise Exception(f'Unknown config file extension {extension}')
185
+
186
+ @classmethod
187
+ def _read_json(cls,filename,parse=True,**kwargs):
188
+ """_read_json create a new PostsimConfiguration object by reading from JSON input
189
+
190
+ :param filename: name of JSON file
191
+ :type filename: str
192
+ :param parse: if True, parse the JSON data, defaults to True
193
+ :type parse: bool, optional
194
+ :return: a new PostsimConfiguration object
195
+ :rtype: PostsimConfiguration
196
+ """
197
+ inst=cls()
198
+ inst.cfgFile=filename
199
+ with open(filename,'r') as f:
200
+ inst.baselist=json.load(f)
201
+ assert type(inst.baselist)==list,f'Poorly formatted {filename}'
202
+ if parse: inst.parse(**kwargs)
203
+ return inst
204
+
205
+ @classmethod
206
+ def _read_yaml(cls,filename,parse=True,**kwargs):
207
+ """_read_yaml create a new PostsimConfiguration object by reading from YAML input
208
+
209
+ :param filename: name of YAML file
210
+ :type filename: str
211
+ :param parse: if True, parse the YAML data, defaults to True
212
+ :type parse: bool, optional
213
+ :return: a new PostsimConfiguration object
214
+ :rtype: PostsimConfiguration
215
+ """
216
+ inst=cls()
217
+ inst.cfgFile=filename
218
+ with open(filename,'r') as f:
219
+ inst.baselist=yaml.safe_load(f)
220
+ assert type(inst.baselist)==list,f'Poorly formatted {filename}'
221
+ if parse: inst.parse(**kwargs)
222
+ return inst
223
+
224
+ def parse(self,**kwargs):
225
+ """parse parses a PostsimConfiguration file to build the list of stages to run
226
+ """
227
+ for content in self.baselist:
228
+ analysistype=content['command']
229
+ if analysistype in self.predefined_classes:
230
+ self.stagelist.append(self.predefined_classes[analysistype](content))
231
+ else:
232
+ self.stagelist.append(self.default_class(content))
233
+
234
+ def analyze(args):
235
+ """postsim handles the analyze subcommand for managing gromacs-based trajectory analyses
236
+
237
+ :param args: command-line arguments
238
+ :type args: argparse.Namespace
239
+ """
240
+ loglevel_numeric=getattr(logging, args.loglevel.upper())
241
+ logging.basicConfig(format='%(levelname)s> %(message)s',level=loglevel_numeric)
242
+ ess='y' if len(args.proj)==0 else 'ies'
243
+ ogromacs={}
244
+ if args.ocfg:
245
+ ocfg=Configuration.read(args.ocfg,parse=False)
246
+ ogromacs=ocfg.basedict.get('gromacs',{})
247
+ cfg=AnalyzeConfiguration.read(args.cfg)
248
+ logger.debug(f'{cfg.baselist}')
249
+ logger.info(f'Project director{ess}: {args.proj}')
250
+ software.sw_setup()
251
+ logger.debug(f'ogromacs {ogromacs}')
252
+ for d in args.proj:
253
+ pfs.pfs_setup(root=os.getcwd(),topdirs=['molecules','systems','plots','postsim','analyze'],verbose=True,projdir=d,reProject=False,userlibrary=args.lib)
254
+ pfs.go_to('analyze')
255
+ for stage in cfg.stagelist:
256
+ stage.do(**ogromacs)
257
+ stage.parse_console_output()
258
+ pfs.go_root()
HTPolyNet/banner.py ADDED
@@ -0,0 +1,26 @@
1
+ """
2
+
3
+ .. module:: banner
4
+ :synopsis: Defines the banner method for printing the banner to a logging channel
5
+
6
+ .. moduleauthor: Cameron F. Abrams, <cfa22@drexel.edu>
7
+
8
+ """
9
+ from HTPolyNet.stringthings import my_logger
10
+ from HTPolyNet.__init__ import HTPOLYNET_VERSION
11
+
12
+ banner_message="""
13
+ HTPolyNet {:s}
14
+ https://abramsgroup.github.io/HTPolyNet/
15
+
16
+ Ming Huang
17
+ mh3429@dragons.drexel.edu
18
+
19
+ Cameron F. Abrams
20
+ cfa22@drexel.edu
21
+
22
+ Supported in part by Grants W911NF-17-2-0227
23
+ and W911NF-12-R-0011 from the US Army Research Lab
24
+ """.format(HTPOLYNET_VERSION)
25
+ def banner(logf):
26
+ my_logger(banner_message,logf,fill=' ',just='<')
HTPolyNet/bondlist.py ADDED
@@ -0,0 +1,206 @@
1
+ """
2
+
3
+ .. module:: bondlist
4
+ :synopsis: Manages bidirectional interatomic bondlists
5
+
6
+ .. moduleauthor: Cameron F. Abrams, <cfa22@drexel.edu>
7
+
8
+ """
9
+
10
+ import numpy as np
11
+ import networkx as nx
12
+ import pandas as pd
13
+
14
+ import logging
15
+ logger=logging.getLogger(__name__)
16
+
17
+ class Bondlist:
18
+ """ The member "B" is a dictionary keyed on atom index whose values of lists
19
+ of atom indices indicating bond partners of the key atom
20
+ """
21
+ def __init__(self):
22
+ self.B={}
23
+
24
+ @classmethod
25
+ def fromDataFrame(cls,df:pd.DataFrame):
26
+ inst=cls()
27
+ inst.update(df)
28
+ return inst
29
+
30
+ def update(self,df:pd.DataFrame):
31
+ """update updates the bondlist using data in the parameter dataframe df
32
+
33
+ :param df: dataframe with minimally columns named 'ai' and 'aj'
34
+ :type df: pd.DataFrame
35
+ :raises Exception: if no column 'ai' or 'aj' in df
36
+ """
37
+ if not 'ai' in df.columns and not 'aj' in df.columns:
38
+ raise Exception('Bondlist expects a dataframe with columns "ai" and "aj".')
39
+ assert df['ai'].dtype==int
40
+ assert df['aj'].dtype==int
41
+ aiset=set(df.ai)
42
+ ajset=set(df.aj)
43
+ keyset=aiset.union(ajset)
44
+ keys=sorted(list(keyset))
45
+ self.B.update({k:[] for k in keys})
46
+ assert all([type(x)==int for x in self.B.keys()])
47
+ for r in df.itertuples():
48
+ ai=r.ai
49
+ aj=r.aj
50
+ self.B[ai].append(aj)
51
+ self.B[aj].append(ai)
52
+ for k,v in self.B.items():
53
+ this_check=all([type(x)==int for x in v])
54
+ if not this_check:
55
+ logger.error(f'{k} {v}')
56
+ assert this_check
57
+
58
+ def __str__(self):
59
+ retstr=''
60
+ for k,v in self.B.items():
61
+ retstr+=f'{k}: '+' '.join(str(vv) for vv in v)+'\n'
62
+ return retstr
63
+
64
+ def partners_of(self,idx):
65
+ """partners_of returns a copy of the value of self.B[idx]
66
+
67
+ :param idx: atom index
68
+ :type idx: int
69
+ :return: list of indices of atoms to which atom 'idx' is bound
70
+ :rtype: list
71
+ """
72
+ if idx in self.B:
73
+ assert all([type(x)==int for x in self.B[idx]])
74
+ return self.B[idx][:]
75
+ return []
76
+
77
+ def are_bonded(self,idx,jdx):
78
+ """are_bonded returns True if atoms with indices idx and jdx are bonded neighbors
79
+
80
+ :param idx: atom index
81
+ :type idx: int
82
+ :param jdx: another atom index
83
+ :type jdx: int
84
+ :return: True if idx and jdx are bonded neighbors
85
+ :rtype: bool
86
+ """
87
+ if idx in self.B and jdx in self.B:
88
+ return jdx in self.B[idx]
89
+ return False
90
+
91
+ def append(self,pair):
92
+ """append appends the bonded pair in parameter 'pair' to the bondlist
93
+
94
+ :param pair: pair atom indices
95
+ :type pair: list-like container
96
+ """
97
+ assert len(pair)==2
98
+ ai,aj=min(pair),max(pair)
99
+ assert type(ai)==int
100
+ assert type(aj)==int
101
+ if not ai in self.B:
102
+ self.B[ai]=[]
103
+ self.B[ai].append(aj)
104
+ if not aj in self.B:
105
+ self.B[aj]=[]
106
+ self.B[aj].append(ai)
107
+
108
+ def delete_atoms(self,idx):
109
+ """delete_atoms deletes all instances of atoms in the list idx from the bondlist
110
+
111
+ :param idx: list of indices for atoms to delete
112
+ :type idx: list
113
+ """
114
+ ''' delete entries '''
115
+ for i in idx:
116
+ if i in self.B:
117
+ del self.B[i]
118
+ ''' delete members in other entries '''
119
+ for k,v in self.B.items():
120
+ for i in idx:
121
+ if i in v:
122
+ self.B[k].remove(i)
123
+
124
+ def adjacency_matrix(self):
125
+ """adjacency_matrix generate and return an adjacency matrix built from the bondlist
126
+
127
+ :return: _description_
128
+ :rtype: _type_
129
+ """
130
+ N=len(self.B)
131
+ A=np.zeros((N,N)).astype(int)
132
+ for i,n in self.B.items():
133
+ for j in n:
134
+ A[i-1,j-1]=1
135
+ A[j-1,i-1]=1
136
+ return A
137
+
138
+ def as_list(self,root,depth):
139
+ """as_list recursively build a list of all atoms that form a bonded cluster by traversing maximally depth bonds
140
+
141
+ :param root: root bond
142
+ :type root: list-like container of two ints
143
+ :param depth: number of bonds to traverse to define bonded cluster
144
+ :type depth: int
145
+ :return: list of atom indices in the bonded cluster
146
+ :rtype: list
147
+ """
148
+ if depth==0:
149
+ return [root]
150
+ a,b=root
151
+ abranch=[]
152
+ for an in self.partners_of(a):
153
+ if an!=b:
154
+ abranch.extend(self.as_list([a,an],depth-1))
155
+ bbranch=[]
156
+ for bn in self.partners_of(b):
157
+ if bn!=a:
158
+ bbranch.extend(self.as_list([b,bn],depth-1))
159
+ result=[root]
160
+ result.extend(abranch)
161
+ result.extend(bbranch)
162
+ # sort entries, remove duplicates
163
+ for i in range(len(result)):
164
+ if result[i][0]>result[i][1]:
165
+ result[i]=result[i][::-1]
166
+ return result
167
+
168
+ def half_as_list(self,root,depth):
169
+ """half_as_list returns bonded cluster defined by atom b in root found by traversing depth bonds excluding the bond to atom a in root
170
+
171
+ :param root: root bond
172
+ :type root: list-like container of two ints
173
+ :param depth: number of bonds to traverse
174
+ :type depth: int
175
+ :return: list of atom indices in bonded cluster "owned" by atom b not containing atom a
176
+ :rtype: list
177
+ """
178
+ a,b=root
179
+ self.delete_atoms([a])
180
+ bbranch=[root]
181
+ for bn in self.partners_of(b):
182
+ if bn!=a:
183
+ bbranch.extend(self.as_list([b,bn],depth-1))
184
+ for i in range(len(bbranch)):
185
+ if bbranch[i][0]>bbranch[i][1]:
186
+ bbranch[i]=bbranch[i][::-1]
187
+ bbranch.sort()
188
+ red=[]
189
+ for b in bbranch:
190
+ if not b in red:
191
+ red.append(b)
192
+ return red
193
+
194
+ def graph(self):
195
+ """graph generate a networkx Directed Graph object from the bondlist
196
+
197
+ :return: a networkx DiGraph object
198
+ :rtype: networkx.DiGraph
199
+ """
200
+ g=nx.DiGraph()
201
+ N=len(self.B)
202
+ g.add_nodes_from(list(range(N)))
203
+ for i,n in self.B.items():
204
+ for j in n:
205
+ g.add_edge(i,j)
206
+ return g