episol 0.0.1__tar.gz

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.
@@ -0,0 +1,78 @@
1
+ # GNU LESSER GENERAL PUBLIC LICENSE
2
+
3
+ Version 3, 29 June 2007
4
+
5
+ Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
6
+
7
+ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
8
+
9
+ This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.
10
+
11
+ ## 0. Additional Definitions.
12
+
13
+ As used herein, “this License” refers to version 3 of the GNU Lesser General Public License, and the “GNU GPL” refers to version 3 of the GNU General Public License.
14
+
15
+ “The Library” refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.
16
+
17
+ An “Application” is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.
18
+
19
+ A “Combined Work” is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the “Linked Version”.
20
+
21
+ The “Minimal Corresponding Source” for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.
22
+
23
+ The “Corresponding Application Code” for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.
24
+
25
+ ## 1. Exception to Section 3 of the GNU GPL.
26
+
27
+ You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.
28
+
29
+ ## 2. Conveying Modified Versions.
30
+
31
+ If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:
32
+
33
+ a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or
34
+
35
+ b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.
36
+
37
+ ## 3. Object Code Incorporating Material from Library Header Files.
38
+
39
+ The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:
40
+
41
+ a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.
42
+
43
+ b) Accompany the object code with a copy of the GNU GPL and this license document.
44
+
45
+ ## 4. Combined Works.
46
+
47
+ You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:
48
+
49
+ a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.
50
+
51
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license document.
52
+
53
+ c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.
54
+
55
+ d) Do one of the following:
56
+
57
+ 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
58
+
59
+ 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.
60
+
61
+ e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)
62
+
63
+ ## 5. Combined Libraries.
64
+
65
+ You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:
66
+
67
+ a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.
68
+
69
+ b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
70
+
71
+ ## 6. Revised Versions of the GNU Lesser General Public License.
72
+
73
+ The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
74
+
75
+ Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.
76
+
77
+ If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.
78
+
episol-0.0.1/PKG-INFO ADDED
@@ -0,0 +1,21 @@
1
+ Metadata-Version: 2.4
2
+ Name: episol
3
+ Version: 0.0.1
4
+ Summary: Interface for EPISOL 3DRISM calculations
5
+ Project-URL: Homepage, https://github.com/EPISOLrelease/EPIPY
6
+ Project-URL: Issues, https://github.com/EPISOLrelease/EPIPY/issues
7
+ Author-email: Peter Swanson <pcswanson@wisc.edu>
8
+ License-Expression: GPL-3.0-only
9
+ License-File: LICENSE.md
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+
15
+ This is the Python interface for episol
16
+
17
+ Includes:
18
+ * setting up and running 3DRISM commands
19
+ * Placement of waters
20
+ * post-processing and selection tools
21
+
episol-0.0.1/README.md ADDED
@@ -0,0 +1,7 @@
1
+ This is the Python interface for episol
2
+
3
+ Includes:
4
+ * setting up and running 3DRISM commands
5
+ * Placement of waters
6
+ * post-processing and selection tools
7
+
@@ -0,0 +1,23 @@
1
+ [build-system]
2
+ requires = ["hatchling >= 1.26"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "episol"
7
+ version = "0.0.1"
8
+ authors = [
9
+ { name="Peter Swanson", email="pcswanson@wisc.edu" },
10
+ ]
11
+ description = "Interface for EPISOL 3DRISM calculations"
12
+ readme = "README.md"
13
+ requires-python = ">=3.9"
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Operating System :: OS Independent",
17
+ ]
18
+ license = "GPL-3.0-only"
19
+ #license-files = ["LICEN[CS]E*"]
20
+
21
+ [project.urls]
22
+ Homepage = "https://github.com/EPISOLrelease/EPIPY"
23
+ Issues = "https://github.com/EPISOLrelease/EPIPY/issues"
@@ -0,0 +1,2 @@
1
+
2
+ from epipy import *
@@ -0,0 +1,591 @@
1
+ import subprocess
2
+ import os
3
+ import threading
4
+ #import pandas as pd
5
+ #import matplotlib.pyplot as plt
6
+
7
+ class epipy:
8
+ def __init__(self,solute_structure,solute_topology,to_gro=False,gen_idc=False,
9
+ convert=False,recenter=False,box_size=[10,10,10]):
10
+ # moving solute and solvent to __init__ because it seems more natural
11
+ # user can still overwrite if need be
12
+ # initialize everything so the user can define the parameters
13
+ # on their own if need be
14
+ self.cmd_path = "" #path to eprism command
15
+ self.grid = [] # number of grids per unit cell LxWxH
16
+ self.closure = 'PSE3'
17
+ self.path = ""
18
+ self.ndiis = 5
19
+ self.solute_path = ""
20
+ self.solvent_path = ""#~/EPISOL-1.1.326/solvent/"
21
+ self.r_c = 1
22
+ self.coulomb = 'coulomb'
23
+ self.delvv = 0.5
24
+ self.err_tol = 1e-08
25
+ self.dynamic_delvv = 1
26
+ self.T = 298
27
+ self.log = 'episol_out.log'
28
+ self.threads = threading.active_count()
29
+ self.rism_args = str()
30
+ self.test_args = str()
31
+ self.rism_cmd = str()
32
+ #self.out_file = self.log#str()
33
+ self.get_eprism_path = ''.join([chr(i) for i in subprocess.check_output(['whereis eprism3d'],shell=True)[:-1]]).split()[1][:-8]
34
+ ## initialize solute and solvent right at the begining
35
+ # you can do this later onif you want to change files
36
+ self.solute(solute_structure,solute_topology,to_gro=False,gen_idc=False,convert=False,recenter=False,box_size=[10,10,10])
37
+ self.solvent()
38
+ ####################################################################################
39
+ # HERE I AM MOVING THIS TO __INIT__
40
+ ####################################################################################
41
+ def solute(self,solute_structure,solute_topology,to_gro=False,gen_idc=False,convert=False,recenter=False,box_size=[10,10,10]):
42
+ """solute file (solute/top/prmtop, or a folder)"""
43
+ self.structure_file = solute_structure
44
+ if convert:
45
+ subprocess.run([f"gmxtop2solute -p {solute_topology} -o {solute_topology[:-4]}.solute"],shell=True)
46
+ self.solute_top = f"{solute_topology[:-4]}.solute"
47
+ print(f"converted {solute_topology} to {solute_topology[:-4]}.solute")
48
+ if gen_idc:
49
+ subprocess.run([f"{self.get_eprism_path}generate-idc.sh {solute_topology[:-4]}.solute > idc_{solute_topology[:-4]}.solute"],shell=True)
50
+ self.solute_top = f'idc_{solute_topology[:-4]}.solute'
51
+ print(f"generated idc-enabled solute file to: idc_{solute_topology[:-4]}.solute ")
52
+ else:
53
+ self.solute_top = solute_topology
54
+ ####################################################################################
55
+ # THIS IS KIND OF TRASH TO INCLUDE: LET THEM USE GMX ON THEIR OWN IF THEY WANT
56
+ ####################################################################################
57
+ if recenter:
58
+ subprocess.run([f"gmx editconf -f {self.structure_file} -c yes -box {box_size[0]} {box_size[1]} {box_size[2]} -o {self.structure_file[:-4]}.gro"],shell=True)
59
+ self.structure_file = f"{self.structure_file[:-4]}.gro"
60
+ if to_gro:
61
+ subprocess.run([f"gmx editconf -f {self.structure_file} -o {self.structure_file[:-4]}.gro"],shell=True)
62
+ self.structure_file = f"{self.structure_file[:-4]}.gro"
63
+ #box = [box_size,box_size,box_size]
64
+ #self.rism_args += f" -f {self.path+self.solute_path+self.structure_file} -s {self.path+self.solute_path+self.solute_top}"
65
+ ####################################################################################
66
+ if f"{self.path+self.solute_path+self.structure_file}"[-3:] == 'pdb':
67
+ self.file_type = 'pdb'
68
+ with open(f"{self.path+self.solute_path+self.structure_file}",'r') as sol:
69
+ for line in sol:
70
+ tmp = line.split()
71
+ if tmp[0] == "CRYST1":
72
+ self.solute_box = [tmp[1],tmp[2],tmp[3]]
73
+ break
74
+ sol.close()
75
+
76
+ elif f"{self.path+self.solute_path+self.structure_file}"[-3:] == 'gro':
77
+ self.file_type = 'gro'
78
+ """https://stackoverflow.com/questions/3346430/
79
+ what-is-the-most-efficient-way-to-get-first-and-last-line-of-a-text-file/18603065#18603065"""
80
+ import os
81
+ with open(f"{self.path+self.solute_path+self.structure_file}", 'rb') as f:
82
+ try:
83
+ f.seek(-2, os.SEEK_END)
84
+ while f.read(1) != b'\n':
85
+ f.seek(-2, os.SEEK_CUR)
86
+ except OSError:
87
+ f.seek(0)
88
+ last_line = f.readline().decode()
89
+ self.solute_box = [float(val) for val in last_line.split()]
90
+
91
+ def solvent(self,solvent_topology='tip3p-amber14.01A.gaff'):
92
+ """iet parameter file, can be screen/con"""
93
+ self.solvent_top = solvent_topology
94
+ #self.rism_args += f" -p {self.path+self.solvent_path+self.solvent_top}"
95
+ ####################################################################################
96
+ ####################################################################################
97
+ def rism(self,step=500,resolution=1,args=('all')):
98
+ """
99
+ step :: int(), Number of SCF steps to perform
100
+ resolution :: int(), grid resolution of box (will override if previously set)
101
+ args :: string(), values to save to the dump file; options below:
102
+ ++++++++++++++++++++++++++ SAVE ARGS ++++++++++++++++++++++++++
103
+ all : reports all of the below
104
+ command : save the exact command that was run when the file was produced
105
+ guv : g(r) foreach grid point
106
+ ld : smoothed g(r) i.e. g(r) convolved with kernel
107
+ coul : coulombic potential at each grid
108
+ excess : mu^ex at each grid
109
+ """
110
+ self.rism_step = step
111
+ self.resolution = resolution
112
+ #self.rism_cmd += f" -cmd closure={self.closure} rism,step={self.rism_step}"#f" rism,step={self.rism_step}"
113
+ ###
114
+ tmp = self.solute_box
115
+ if self.file_type == 'gro':
116
+ # box is in nm
117
+ convert = (10)/resolution
118
+ self.grid = [i*convert for i in tmp]
119
+ if self.file_type == 'pdb':
120
+ # box is in Angstrom
121
+ convert = 1/resolution
122
+ self.grid = [i*convert for i in tmp]
123
+
124
+ self.save_command = f' save:{args}'
125
+
126
+ def report(self,out_file_name:str='episol_out',args=('all')):
127
+ self.log = out_file_name
128
+ cmd_string = " report:"
129
+ for arg in args:
130
+ cmd_string += f"{arg}"
131
+ self.to_report = f" {cmd_string}" #{self.rism_cmd} {cmd_string}"
132
+
133
+ def get_version(self):
134
+ temp = subprocess.check_output([f'{self.cmd_path}eprism3d --version'],shell=True)
135
+ return ''.join([chr(i) for i in temp[:-1]])
136
+
137
+ def get_help(self,search_str:str):
138
+ xx = subprocess.run(["eprism3d","--h",search_str],capture_output=True)
139
+ xv = ''.join([chr(i) for i in xx.stdout[:-1]])
140
+ print(xv)
141
+
142
+ def test(self,nt=1,v=1):
143
+ """
144
+ v :: int(), verbose rating
145
+ nt :: int(), number of threads to use
146
+ """
147
+ self.test_args += f" -f {self.path+self.solute_path+self.structure_file} -s {self.path+self.solute_path+self.solute_top}"
148
+ self.test_args += f" -p {self.path+self.solvent_path+self.solvent_top}"
149
+ self.test_args += f" -coulomb {self.coulomb}"
150
+ #self.rism_cmd += f' -cmd closure={self.closure} rism,step={self.rism_step}'
151
+ self.test_args += f" -rc {self.r_c} "
152
+ self.test_args += f" -T {self.T}"
153
+ self.test_args += f" -log {self.log}.log"
154
+ self.test_args += f" -nr {self.grid[0]}x{self.grid[1]}x{self.grid[2]}"
155
+ self.test_args += f" -ndiis {self.ndiis}"
156
+ self.test_args += f" -errtolrism {self.err_tol}"
157
+ self.test_args += f" -delvv {self.delvv}"
158
+ self.test_args += f" -dynamic-delvv {self.dynamic_delvv}"
159
+ self.test_args += " -pwd ./" #"~/mnt/f/water_proj"
160
+ self.test_args += f" -o {self.log}"
161
+ self.test_args += f" -cmd closure={self.closure} rism,step={self.rism_step}"#f" rism,step={self.rism_step}"#self.rism_cmd
162
+ self.test_args += self.to_report
163
+ self.test_args += self.save_command
164
+ ###
165
+ self.test_args += f' -nt {nt} -test'
166
+ subprocess.run([f"{self.cmd_path}eprism3d {self.test_args}"],shell=True)
167
+ self.test_args = ''
168
+
169
+ with open(f"{self.log}.log",'r') as f:
170
+ #mem = str()
171
+ for line in f:
172
+ tmp = line.split()
173
+ if tmp[0] == "Memory":
174
+ mem = f'{tmp[5]}{tmp[6]}'
175
+ break
176
+ f.close()
177
+ return mem
178
+
179
+ def kernel(self,nt=1,v=1):
180
+ """
181
+ v :: int(), verbose rating
182
+ nt :: int(), number of threads to use
183
+ """
184
+ self.rism_args += f" -f {self.path+self.solute_path+self.structure_file} -s {self.path+self.solute_path+self.solute_top}"
185
+ self.rism_args += f" -p {self.path+self.solvent_path+self.solvent_top}"
186
+ self.rism_args += f" -coulomb {self.coulomb}"
187
+ #self.rism_cmd += f' -cmd closure={self.closure} rism,step={self.rism_step}'
188
+ self.rism_args += f" -rc {self.r_c} "
189
+ self.rism_args += f" -T {self.T}"
190
+ self.rism_args += f" -log {self.log}.log"
191
+ self.rism_args += f" -nr {self.grid[0]}x{self.grid[1]}x{self.grid[2]}"
192
+ self.rism_args += f" -ndiis {self.ndiis}"
193
+ self.rism_args += f" -errtolrism {self.err_tol}"
194
+ self.rism_args += f" -delvv {self.delvv}"
195
+ self.rism_args += f" -dynamic-delvv {self.dynamic_delvv}"
196
+ self.rism_args += " -pwd ./" #"~/mnt/f/water_proj"
197
+ self.rism_args += f" -o {self.log}"
198
+ self.rism_args += f" -cmd closure={self.closure} rism,step={self.rism_step}"#f" rism,step={self.rism_step}"#self.rism_cmd
199
+ self.rism_args += self.to_report
200
+ self.rism_args += self.save_command
201
+ # using unix system is better to run subprocess as
202
+ # argument strings, rather than **args
203
+ # i.e. better "exe.exe -command value" than "exe.exe","command","value"
204
+ #self.rism_args += f' save:all -nt {nt} -v {v}'
205
+ self.rism_args += f' -nt {nt} -v {v}'
206
+ subprocess.run([f"{self.cmd_path}eprism3d {self.rism_args}"],shell=True)#,self.rism_args],shell=True)
207
+ self.rism_args = ''
208
+ with open(f'{self.log}.log','r') as f:
209
+ for line in f:
210
+ tmp = line.split()
211
+ if tmp[0][:4] == "RISM":
212
+ out = float(tmp[4])
213
+ step = tmp[2]
214
+ f.close()
215
+ if out > self.err_tol:
216
+ print(f"Failed to reach desired err_tol of {self.err_tol}")
217
+ print(f"Actual error: {out}")
218
+ print(f"Difference: {self.err_tol - out}")
219
+ print(f"RISM finished at step {step}")
220
+ else:
221
+ print(f"Calculation finished in {step} steps ")
222
+ print(f"err_tol: {self.err_tol} actual: {out} ")
223
+
224
+ def dump(self,file_name='',out_name=False,list_values=False,value_to_extract=1):
225
+ if not out_name:
226
+ out_name = file_name
227
+ if file_name == '':
228
+ file_name = f'{self.log}.ts4s'
229
+
230
+ if list_values:
231
+ thold = ''.join([chr(i) for i in subprocess.check_output([f"ts4sdump -f {file_name} -l"],shell=True)]).split('\n')
232
+ for item in thold:
233
+ print(item)
234
+ else:
235
+ subprocess.run([f"ts4sdump -f {file_name} -e {value_to_extract} > {out_name}.txt"],shell=True)
236
+ self.extracted_file = f'{out_name}.txt'
237
+
238
+ def err(self,log_file_name=False):
239
+ """
240
+ This function reads a log file and returns
241
+ the SCF stdev in an array
242
+ ======================== INPUT
243
+ log_file_name :: string, name of .log file
244
+ ======================== Returns
245
+ out_arr :: np.array() with shape (1, # steps)
246
+ array index represents the SCF step
247
+ """
248
+ if not log_file_name:
249
+ with open(f'{self.log}.log','r') as f:
250
+ out_arr = []
251
+ for line in f:
252
+ tmp = line.split()
253
+ if tmp[0][:4] == "RISM":
254
+ out_arr.append(float(tmp[4]))
255
+ #step = tmp[2]
256
+ f.close()
257
+ return np.array(out_arr)
258
+
259
+ def reader(self,file_in:str,laplacian=False,file_out:str='out',dx=False):
260
+ """
261
+ This function takes in an uncompressed dump file txt file
262
+ it reads the grid size and shape
263
+ If specified we can save/export to a dx file which can be loaded into pymol/vmd/etc.
264
+ =================================
265
+ file_in :: the decompress txt file from our ts4s dump command
266
+ grid_spacing :: [x,y,z] values for \delta grid, e.g. grid spacing of 0.5A would
267
+ have grid_spacing = [0.5,0.5,0.5]
268
+ ---------- IF DX=TRUE ---------------
269
+ file_out :: filename for saved dx file
270
+ ################# WARNINGS ################
271
+ since the dx file was made by IBM in the 90s
272
+ many nont-so-modern softwares will struggle to read
273
+ dx files with comments and it appears many follow their own
274
+ format specifications
275
+ """
276
+ from numpy import loadtxt,zeros,copy
277
+ from scipy.ndimage import laplace
278
+ grid_spacing = [self.resolution for _ in range(3)]
279
+ #[i/j for (i,j) in zip(self.solute_box,self.grid)]
280
+
281
+ xs,ys,zs = loadtxt(file_in)[-1][:3]
282
+ x = loadtxt(file_in,usecols=(3))
283
+ #xs,ys,zs
284
+ shaped = zeros((int(xs),int(ys),int(zs)))
285
+ cont = int()
286
+ for zval in range(int(zs)):
287
+ for yval in range(int(ys)):
288
+ for xval in range(int(xs)):
289
+ shaped[xval][yval][zval] = x[cont]#np.linalg.norm(x[cont])
290
+ cont +=1
291
+ if laplacian and not dx:
292
+ return laplace(shaped)
293
+ elif not dx:
294
+ return shaped
295
+ if dx:
296
+ with open(f'{file_out}.dx','w+') as outfile:
297
+ outfile.write(f"""object 1 class gridpositions counts {xs} {ys} {zs}
298
+ origin 0.0000 0.0000 0.0000
299
+ delta {grid_spacing[0]} 0 0
300
+ delta 0 {grid_spacing[1]} 0
301
+ delta 0 0 {grid_spacing[2]}
302
+ object 2 class gridconnections counts {xs} {ys} {zs}
303
+ object 3 class array type double rank 0 items {int(xs*ys*zs)} follows\n""")
304
+ for ind, val in enumerate(shaped.flatten()):
305
+ outfile.write(f"{val:0.5e} ")
306
+ if (ind != 0) and (ind % 3 == 0):
307
+ outfile.write("\n")
308
+ outfile.close()
309
+
310
+ def placement(self,num_waters_to_place:int,radius=1.9269073728633292,filename=False,grid_spacing=None,write_pdb=False,outname='out.pdb',weight=None):
311
+ import numpy as np
312
+ import datetime
313
+ """function selects top distribution
314
+ then places water there, then removes that density
315
+ and continues to look. kind of like placevent.
316
+ =============================
317
+ filename:: txt file containing density
318
+ inputgrid:: md.Grid object
319
+ outname:: string for pdb file
320
+ num_waters_to_place:: number of waters to place
321
+ radius:: distance around selected point to omit from remaining placement
322
+ ideal_radius = ((10**3)/(4/3)/(np.pi)/33.3679)**(1/3) based on number density of water
323
+ grid_spacing:: conversion from array indices to angstrom, units of 1/A
324
+ """
325
+ if grid_spacing is None:
326
+ # you can overide the grid spacing if need be
327
+ grid_spacing = self.resolution
328
+ if not filename:
329
+ filename = f'{self.log}.txt'
330
+
331
+ xs,ys,zs = np.loadtxt(filename)[-1][:3]
332
+ x = np.loadtxt(filename,usecols=(3))
333
+
334
+ shaped = np.zeros((int(xs),int(ys),int(zs)))
335
+ cont = int()
336
+ for zval in range(int(zs)):
337
+ for yval in range(int(ys)):
338
+ for xval in range(int(xs)):
339
+ shaped[xval][yval][zval] = x[cont]#np.linalg.norm(x[cont])
340
+ cont +=1
341
+
342
+ inputgrid = np.copy(shaped)
343
+ x = np.arange(0,inputgrid.shape[0])
344
+ y = np.arange(0,inputgrid.shape[1])
345
+ z = np.arange(0,inputgrid.shape[2])
346
+ out_array = []
347
+ for wat in range(num_waters_to_place):
348
+ r_x,r_y,r_z = np.where(inputgrid == np.max(inputgrid))
349
+ r_x,r_y,r_z = r_x[0],r_y[0],r_z[0]
350
+ out_array.append([float(r_x),float(r_y),float(r_z)])
351
+ mask = (x[:,np.newaxis,np.newaxis]-r_x)**2 + (y[np.newaxis,:,np.newaxis]-r_y)**2 + (z[np.newaxis,np.newaxis,:]-r_z)**2 < (radius/grid_spacing)**2
352
+ inputgrid[mask] = -1
353
+ ################################
354
+ if write_pdb:
355
+ x,y,z = self.grid
356
+ with open(f'{outname}.pdb','w+') as pdb:
357
+ pdb.write(f"CRYST1 {str(x).ljust(4,'0')} {str(y).ljust(4,'0')} {str(z).ljust(4,'0')} 90.00 90.00 90.00 P 1 1\n")
358
+ count = 1
359
+ for val in np.array(out_array)*grid_spacing:#guess2:
360
+ pdb.write(f"ATOM {str(count).rjust(4,' ')} O HOH A{str(count).rjust(3,' ')} {val[0]:8.3f} {val[1]:8.3f} {val[2]:8.3f}\n")
361
+ count +=1
362
+
363
+ return np.array(out_array)*grid_spacing
364
+
365
+ def select_coords(self,in_file:str,sele:str,atom_sele:str=None,conv_fact:int=10):
366
+ """
367
+ in_file: .gro file
368
+ sele: selection string -> resname only so far
369
+ returns:
370
+
371
+ ========
372
+ conv_fact: convert from nm to grid-bits
373
+ for .gro this is X nm*(10A/1nm)
374
+ """
375
+ import numpy as np
376
+ # this is where we select the selection string
377
+ tmp_string = sele.split()
378
+ # Xnm*(10A/1nm)
379
+ with open(f'{in_file}','r') as r:
380
+ count = int()
381
+ atom_count = int()
382
+ out_dict = {}
383
+ for line in r:
384
+ count += 1
385
+ if count == 2:
386
+ atom_count = int(line.split()[0])
387
+ if count == atom_count+2:
388
+ break # this is the end of the file
389
+ ###########
390
+ if count > 2: # ignore header
391
+ try:
392
+ res_id = line[:5].split()[0]
393
+ res_name = line[5:10].split()[0]
394
+ # there is probably a better way of doing this
395
+ if f"{res_name+res_id}" not in out_dict.keys():
396
+ # if the residue is not in the dictionary, add it
397
+ out_dict[f"{res_name+res_id}"] = {}
398
+ else:
399
+ #print(line[20:28].split()[0])
400
+ out_dict[f"{res_name+res_id}"][f"{line[10:15].split()}"] = conv_fact*np.array([float(line[20:28].split()[0]),
401
+ float(line[28:36].split()[0]),
402
+ float(line[36:44].split()[0])])
403
+ except ValueError:
404
+ print(f"ERROR OCCURED AT LINE: {count}")
405
+ continue
406
+ # now we return the x,y,z positions ONLY
407
+ out_array = np.array([])
408
+ for val in out_dict.keys():
409
+ if val[:3] == sele:
410
+ # this uh is a pretty bad way of doing this
411
+ out_array = np.append(out_array,[i for i in out_dict[val].values()])
412
+ #out_array = np.array(out_array)
413
+ #print('out array',out_array)
414
+ """if len(out_array.shape) > 2:
415
+ # this is a bad way of doing this
416
+ y,z,_ = out_array.shape
417
+ out_array = out_array.flatten()#.shape
418
+ out_array = out_array.reshape((y*z,3))"""
419
+ out_array = out_array.reshape((int(len(out_array)/3),3))
420
+
421
+ return out_array
422
+
423
+ def select_around(self,rism_grid,in_coords,around=5.0):
424
+ import numpy as np
425
+ """
426
+ function will take an input grid, select the values surrounding the input
427
+ coordinates according to the user, then return the array surrounding the coords
428
+ while the values greater than the cutoff distance are set to np.NaN
429
+ this is so plotting is easier
430
+ """
431
+ conversion = self.resolution
432
+ around = around/conversion # must convert A to grids
433
+ rism_grid = np.copy(rism_grid)
434
+ x = np.arange(0,rism_grid.shape[0])
435
+ y = np.arange(0,rism_grid.shape[1])
436
+ z = np.arange(0,rism_grid.shape[2])
437
+ #index_grid = np.ndarray(shape=(rism_grid.shape[0],rism_grid.shape[1],rism_grid.shape[2]))
438
+ index_grid = np.full((rism_grid.shape[0],rism_grid.shape[1],rism_grid.shape[2]),False,dtype=bool)
439
+ #print(index_grid.shape)
440
+ for coords in in_coords:
441
+ #print(coords)
442
+ #x_r,y_r,z_r = int(coords[0]),int(coords[1]),int(coords[2])
443
+ x_r,y_r,z_r = float(coords[0])/conversion,float(coords[1])/conversion,float(coords[2])/conversion
444
+ #mask = (x[np.newaxis,:,:]-x_r)**2+(y[:,np.newaxis,:]-y_r)**2+(z[:,:,np.newaxis]-z_r)**2 < around**2
445
+ #print(x[np.newaxis,:,:])
446
+ index_grid[(x[:,np.newaxis,np.newaxis]-x_r)**2+(y[np.newaxis,:,np.newaxis]-y_r)**2+(z[np.newaxis,np.newaxis,:]-z_r)**2 < around**2] = True
447
+ #rism_grid[(x[np.newaxis,:,:]-x_r)**2+(y[:,np.newaxis,:]-y_r)**2+(z[:,:,np.newaxis]-z_r)**2 < around**2] #= np.nan
448
+ #out_grid = rism_grid[index_grid]#np.where(rism_grid == rism_grid[index_grid])]
449
+ return np.where(index_grid == True,rism_grid,np.nan)
450
+
451
+ def extract_grid(self,input_file:str,sele:str='guv',out_name:str='out'):
452
+ """
453
+ This function extracts calc. data from the dump file
454
+ by searching for the value corresponding to the selection string
455
+ This way you dont need to list values to extract them
456
+ """
457
+ assert sele != 'cmd', 'you selected the saved command (cmd)'
458
+ thold = ''.join([chr(i) for i in subprocess.check_output([f"ts4sdump -f {input_file} -l"],shell=True)]).split('\n')
459
+ for val in thold:
460
+ try:
461
+ tmp_str = val.split('@')[0].split()#[1] #.index('guv')
462
+ if tmp_str[1] == sele.strip():
463
+ #print(tmp_str[0])
464
+ value_to_extract = tmp_str[0]
465
+ except IndexError:
466
+ continue
467
+ subprocess.run([f"ts4sdump -f {input_file} -e {value_to_extract} > {out_name}.txt"],shell=True)
468
+ #self.extracted_file = f'{out_name}.txt'
469
+ return
470
+
471
+ def select_grid(self,input_string:str='guv',coord_array=None):
472
+ """
473
+ select values in array based on the selection input string
474
+ +++++++++++++++++++++++++++++++++++++++++++
475
+ so far selection string is limited to selection of
476
+ grid-values around single residue names only: i.e. around 4 resname LYS
477
+ ==================================================
478
+ input_string : value to select and extract
479
+ default value is guv (atomic density)
480
+ if a selection is made value is passed to -> self.get_coords -> self.extract
481
+ else -> self.extract
482
+ """
483
+ from types import NoneType
484
+ from numpy import ndarray
485
+
486
+ if type(coord_array) == NoneType:
487
+ coord_flag = False
488
+ elif type(coord_array) == list:
489
+ coord_flag = True
490
+ coord_array = ndarray(coord_array)
491
+ # change array into np.array
492
+ elif type(coord_array) == ndarray:
493
+ coord_flag = True
494
+
495
+ # these are the possible names to extract
496
+ # we can add more but for now it is unlikely people
497
+ # will want to select weird values, i.e. hlr
498
+ names = {'guv','uuv','ex','ld','coul'}
499
+ # in the future need to add dictionary so people can
500
+ # use more strings, e.g. select g(r) or local density -> guv, ld
501
+ parser = input_string.split()
502
+ #print(parser)
503
+ item = None # this is our selection value i.e. resname
504
+ for name in names:
505
+ if name in parser:
506
+ val = name
507
+ break # can only select one calculation result
508
+
509
+ if 'around' in parser:
510
+ #print(parser.index('around'))
511
+ dist = float(parser[parser.index('around')+1])
512
+ else:
513
+ dist = None
514
+ # if no distance is specified then select everything
515
+
516
+ if 'get' in parser:
517
+ get_flag = True
518
+ #item = parser[parser.index('resname')+1].upper()
519
+ else:
520
+ get_flag = False
521
+ #print(get_flag)
522
+ if (dist or get_flag) and coord_flag:
523
+ # if the user includes an np.array
524
+ # of coordinates then these will be our coordinates to
525
+ # select around
526
+ item = coord_array
527
+
528
+ if 'resname' in parser:
529
+ # will override coordinate array
530
+ # in the future it would be nice to be able to include both
531
+ item = parser[parser.index('resname')+1].upper()
532
+
533
+
534
+ """ if (not coord_array) and dist:
535
+ # if we dont have an input array
536
+ # BUT we have a distance
537
+ item = parser[parser.index('around')+2]
538
+ else:
539
+ item = None"""
540
+ ############## Now extract ts4s file
541
+ self.extract_grid(f'{self.log}.ts4s',sele=val,out_name=f'{val}_{self.log}')
542
+ # read extracted data into a numpy array
543
+ t_grid = self.reader(file_in=f'{val}_{self.log}.txt')#,laplacian=False,file_out='out',dx=False)
544
+ #############
545
+
546
+ if (not coord_flag) and (dist):
547
+ # if we have a distance then that means we have a selection
548
+ # so we select values around our coordinates of the selection item
549
+ coords_ = self.select_coords(self.structure_file,item)
550
+ #print(coords_)
551
+ return self.select_around(t_grid,coords_,around=dist)
552
+
553
+ if (not get_flag) and (not dist):
554
+ # if we dont have a distance that means we dont
555
+ # have a selection and we merely return the entire array
556
+ return t_grid
557
+
558
+ if get_flag and (not coord_flag):
559
+ ee = np.array([],dtype=int)
560
+ max_x,max_y,max_z = np.float64(t_grid.shape)
561
+
562
+ for val in np.round(self.select_coords(self.structure_file,item)/self.resolution):
563
+ ee = np.append(ee,[int(val[0]),int(val[1]),int(val[2])])
564
+
565
+ ee[np.where(ee > max_x)] = max_x-1
566
+ ee[np.where(ee > max_y)] = max_y-1
567
+ ee[np.where(ee > max_z)] = max_z-1
568
+
569
+ ee = ee.reshape((int(len(ee)/3),3))
570
+ #x[ee]
571
+ return t_grid[ee[:,0],ee[:,1],ee[:,2]]
572
+
573
+
574
+ if get_flag and (coord_flag):
575
+ ee = np.array([],dtype=int)
576
+ max_x,max_y,max_z = np.float64(t_grid.shape)
577
+
578
+ for val in np.round(item/self.resolution):
579
+ ee = np.append(ee,[int(val[0]),int(val[1]),int(val[2])])
580
+
581
+ ee[np.where(ee > max_x)] = max_x-1
582
+ ee[np.where(ee > max_y)] = max_y-1
583
+ ee[np.where(ee > max_z)] = max_z-1
584
+
585
+ ee = ee.reshape((int(len(ee)/3),3))
586
+ #x[ee]
587
+ return t_grid[ee[:,0],ee[:,1],ee[:,2]]
588
+ else:
589
+ # if we have a distance and coord_array then we
590
+ # return the grid selected around the coord_array
591
+ return self.select_around(t_grid,item,around=dist)
@@ -0,0 +1,591 @@
1
+ import subprocess
2
+ import os
3
+ import threading
4
+ #import pandas as pd
5
+ #import matplotlib.pyplot as plt
6
+
7
+ class epipy:
8
+ def __init__(self,solute_structure,solute_topology,to_gro=False,gen_idc=False,
9
+ convert=False,recenter=False,box_size=[10,10,10]):
10
+ # moving solute and solvent to __init__ because it seems more natural
11
+ # user can still overwrite if need be
12
+ # initialize everything so the user can define the parameters
13
+ # on their own if need be
14
+ self.cmd_path = "" #path to eprism command
15
+ self.grid = [] # number of grids per unit cell LxWxH
16
+ self.closure = 'PSE3'
17
+ self.path = ""
18
+ self.ndiis = 5
19
+ self.solute_path = ""
20
+ self.solvent_path = ""#~/EPISOL-1.1.326/solvent/"
21
+ self.r_c = 1
22
+ self.coulomb = 'coulomb'
23
+ self.delvv = 0.5
24
+ self.err_tol = 1e-08
25
+ self.dynamic_delvv = 1
26
+ self.T = 298
27
+ self.log = 'episol_out.log'
28
+ self.threads = threading.active_count()
29
+ self.rism_args = str()
30
+ self.test_args = str()
31
+ self.rism_cmd = str()
32
+ #self.out_file = self.log#str()
33
+ self.get_eprism_path = ''.join([chr(i) for i in subprocess.check_output(['whereis eprism3d'],shell=True)[:-1]]).split()[1][:-8]
34
+ ## initialize solute and solvent right at the begining
35
+ # you can do this later onif you want to change files
36
+ self.solute(solute_structure,solute_topology,to_gro=False,gen_idc=False,convert=False,recenter=False,box_size=[10,10,10])
37
+ self.solvent()
38
+ ####################################################################################
39
+ # HERE I AM MOVING THIS TO __INIT__
40
+ ####################################################################################
41
+ def solute(self,solute_structure,solute_topology,to_gro=False,gen_idc=False,convert=False,recenter=False,box_size=[10,10,10]):
42
+ """solute file (solute/top/prmtop, or a folder)"""
43
+ self.structure_file = solute_structure
44
+ if convert:
45
+ subprocess.run([f"gmxtop2solute -p {solute_topology} -o {solute_topology[:-4]}.solute"],shell=True)
46
+ self.solute_top = f"{solute_topology[:-4]}.solute"
47
+ print(f"converted {solute_topology} to {solute_topology[:-4]}.solute")
48
+ if gen_idc:
49
+ subprocess.run([f"{self.get_eprism_path}generate-idc.sh {solute_topology[:-4]}.solute > idc_{solute_topology[:-4]}.solute"],shell=True)
50
+ self.solute_top = f'idc_{solute_topology[:-4]}.solute'
51
+ print(f"generated idc-enabled solute file to: idc_{solute_topology[:-4]}.solute ")
52
+ else:
53
+ self.solute_top = solute_topology
54
+ ####################################################################################
55
+ # THIS IS KIND OF TRASH TO INCLUDE: LET THEM USE GMX ON THEIR OWN IF THEY WANT
56
+ ####################################################################################
57
+ if recenter:
58
+ subprocess.run([f"gmx editconf -f {self.structure_file} -c yes -box {box_size[0]} {box_size[1]} {box_size[2]} -o {self.structure_file[:-4]}.gro"],shell=True)
59
+ self.structure_file = f"{self.structure_file[:-4]}.gro"
60
+ if to_gro:
61
+ subprocess.run([f"gmx editconf -f {self.structure_file} -o {self.structure_file[:-4]}.gro"],shell=True)
62
+ self.structure_file = f"{self.structure_file[:-4]}.gro"
63
+ #box = [box_size,box_size,box_size]
64
+ #self.rism_args += f" -f {self.path+self.solute_path+self.structure_file} -s {self.path+self.solute_path+self.solute_top}"
65
+ ####################################################################################
66
+ if f"{self.path+self.solute_path+self.structure_file}"[-3:] == 'pdb':
67
+ self.file_type = 'pdb'
68
+ with open(f"{self.path+self.solute_path+self.structure_file}",'r') as sol:
69
+ for line in sol:
70
+ tmp = line.split()
71
+ if tmp[0] == "CRYST1":
72
+ self.solute_box = [tmp[1],tmp[2],tmp[3]]
73
+ break
74
+ sol.close()
75
+
76
+ elif f"{self.path+self.solute_path+self.structure_file}"[-3:] == 'gro':
77
+ self.file_type = 'gro'
78
+ """https://stackoverflow.com/questions/3346430/
79
+ what-is-the-most-efficient-way-to-get-first-and-last-line-of-a-text-file/18603065#18603065"""
80
+ import os
81
+ with open(f"{self.path+self.solute_path+self.structure_file}", 'rb') as f:
82
+ try:
83
+ f.seek(-2, os.SEEK_END)
84
+ while f.read(1) != b'\n':
85
+ f.seek(-2, os.SEEK_CUR)
86
+ except OSError:
87
+ f.seek(0)
88
+ last_line = f.readline().decode()
89
+ self.solute_box = [float(val) for val in last_line.split()]
90
+
91
+ def solvent(self,solvent_topology='tip3p-amber14.01A.gaff'):
92
+ """iet parameter file, can be screen/con"""
93
+ self.solvent_top = solvent_topology
94
+ #self.rism_args += f" -p {self.path+self.solvent_path+self.solvent_top}"
95
+ ####################################################################################
96
+ ####################################################################################
97
+ def rism(self,step=500,resolution=1,args=('all')):
98
+ """
99
+ step :: int(), Number of SCF steps to perform
100
+ resolution :: int(), grid resolution of box (will override if previously set)
101
+ args :: string(), values to save to the dump file; options below:
102
+ ++++++++++++++++++++++++++ SAVE ARGS ++++++++++++++++++++++++++
103
+ all : reports all of the below
104
+ command : save the exact command that was run when the file was produced
105
+ guv : g(r) foreach grid point
106
+ ld : smoothed g(r) i.e. g(r) convolved with kernel
107
+ coul : coulombic potential at each grid
108
+ excess : mu^ex at each grid
109
+ """
110
+ self.rism_step = step
111
+ self.resolution = resolution
112
+ #self.rism_cmd += f" -cmd closure={self.closure} rism,step={self.rism_step}"#f" rism,step={self.rism_step}"
113
+ ###
114
+ tmp = self.solute_box
115
+ if self.file_type == 'gro':
116
+ # box is in nm
117
+ convert = (10)/resolution
118
+ self.grid = [i*convert for i in tmp]
119
+ if self.file_type == 'pdb':
120
+ # box is in Angstrom
121
+ convert = 1/resolution
122
+ self.grid = [i*convert for i in tmp]
123
+
124
+ self.save_command = f' save:{args}'
125
+
126
+ def report(self,out_file_name:str='episol_out',args=('all')):
127
+ self.log = out_file_name
128
+ cmd_string = " report:"
129
+ for arg in args:
130
+ cmd_string += f"{arg}"
131
+ self.to_report = f" {cmd_string}" #{self.rism_cmd} {cmd_string}"
132
+
133
+ def get_version(self):
134
+ temp = subprocess.check_output([f'{self.cmd_path}eprism3d --version'],shell=True)
135
+ return ''.join([chr(i) for i in temp[:-1]])
136
+
137
+ def get_help(self,search_str:str):
138
+ xx = subprocess.run(["eprism3d","--h",search_str],capture_output=True)
139
+ xv = ''.join([chr(i) for i in xx.stdout[:-1]])
140
+ print(xv)
141
+
142
+ def test(self,nt=1,v=1):
143
+ """
144
+ v :: int(), verbose rating
145
+ nt :: int(), number of threads to use
146
+ """
147
+ self.test_args += f" -f {self.path+self.solute_path+self.structure_file} -s {self.path+self.solute_path+self.solute_top}"
148
+ self.test_args += f" -p {self.path+self.solvent_path+self.solvent_top}"
149
+ self.test_args += f" -coulomb {self.coulomb}"
150
+ #self.rism_cmd += f' -cmd closure={self.closure} rism,step={self.rism_step}'
151
+ self.test_args += f" -rc {self.r_c} "
152
+ self.test_args += f" -T {self.T}"
153
+ self.test_args += f" -log {self.log}.log"
154
+ self.test_args += f" -nr {self.grid[0]}x{self.grid[1]}x{self.grid[2]}"
155
+ self.test_args += f" -ndiis {self.ndiis}"
156
+ self.test_args += f" -errtolrism {self.err_tol}"
157
+ self.test_args += f" -delvv {self.delvv}"
158
+ self.test_args += f" -dynamic-delvv {self.dynamic_delvv}"
159
+ self.test_args += " -pwd ./" #"~/mnt/f/water_proj"
160
+ self.test_args += f" -o {self.log}"
161
+ self.test_args += f" -cmd closure={self.closure} rism,step={self.rism_step}"#f" rism,step={self.rism_step}"#self.rism_cmd
162
+ self.test_args += self.to_report
163
+ self.test_args += self.save_command
164
+ ###
165
+ self.test_args += f' -nt {nt} -test'
166
+ subprocess.run([f"{self.cmd_path}eprism3d {self.test_args}"],shell=True)
167
+ self.test_args = ''
168
+
169
+ with open(f"{self.log}.log",'r') as f:
170
+ #mem = str()
171
+ for line in f:
172
+ tmp = line.split()
173
+ if tmp[0] == "Memory":
174
+ mem = f'{tmp[5]}{tmp[6]}'
175
+ break
176
+ f.close()
177
+ return mem
178
+
179
+ def kernel(self,nt=1,v=1):
180
+ """
181
+ v :: int(), verbose rating
182
+ nt :: int(), number of threads to use
183
+ """
184
+ self.rism_args += f" -f {self.path+self.solute_path+self.structure_file} -s {self.path+self.solute_path+self.solute_top}"
185
+ self.rism_args += f" -p {self.path+self.solvent_path+self.solvent_top}"
186
+ self.rism_args += f" -coulomb {self.coulomb}"
187
+ #self.rism_cmd += f' -cmd closure={self.closure} rism,step={self.rism_step}'
188
+ self.rism_args += f" -rc {self.r_c} "
189
+ self.rism_args += f" -T {self.T}"
190
+ self.rism_args += f" -log {self.log}.log"
191
+ self.rism_args += f" -nr {self.grid[0]}x{self.grid[1]}x{self.grid[2]}"
192
+ self.rism_args += f" -ndiis {self.ndiis}"
193
+ self.rism_args += f" -errtolrism {self.err_tol}"
194
+ self.rism_args += f" -delvv {self.delvv}"
195
+ self.rism_args += f" -dynamic-delvv {self.dynamic_delvv}"
196
+ self.rism_args += " -pwd ./" #"~/mnt/f/water_proj"
197
+ self.rism_args += f" -o {self.log}"
198
+ self.rism_args += f" -cmd closure={self.closure} rism,step={self.rism_step}"#f" rism,step={self.rism_step}"#self.rism_cmd
199
+ self.rism_args += self.to_report
200
+ self.rism_args += self.save_command
201
+ # using unix system is better to run subprocess as
202
+ # argument strings, rather than **args
203
+ # i.e. better "exe.exe -command value" than "exe.exe","command","value"
204
+ #self.rism_args += f' save:all -nt {nt} -v {v}'
205
+ self.rism_args += f' -nt {nt} -v {v}'
206
+ subprocess.run([f"{self.cmd_path}eprism3d {self.rism_args}"],shell=True)#,self.rism_args],shell=True)
207
+ self.rism_args = ''
208
+ with open(f'{self.log}.log','r') as f:
209
+ for line in f:
210
+ tmp = line.split()
211
+ if tmp[0][:4] == "RISM":
212
+ out = float(tmp[4])
213
+ step = tmp[2]
214
+ f.close()
215
+ if out > self.err_tol:
216
+ print(f"Failed to reach desired err_tol of {self.err_tol}")
217
+ print(f"Actual error: {out}")
218
+ print(f"Difference: {self.err_tol - out}")
219
+ print(f"RISM finished at step {step}")
220
+ else:
221
+ print(f"Calculation finished in {step} steps ")
222
+ print(f"err_tol: {self.err_tol} actual: {out} ")
223
+
224
+ def dump(self,file_name='',out_name=False,list_values=False,value_to_extract=1):
225
+ if not out_name:
226
+ out_name = file_name
227
+ if file_name == '':
228
+ file_name = f'{self.log}.ts4s'
229
+
230
+ if list_values:
231
+ thold = ''.join([chr(i) for i in subprocess.check_output([f"ts4sdump -f {file_name} -l"],shell=True)]).split('\n')
232
+ for item in thold:
233
+ print(item)
234
+ else:
235
+ subprocess.run([f"ts4sdump -f {file_name} -e {value_to_extract} > {out_name}.txt"],shell=True)
236
+ self.extracted_file = f'{out_name}.txt'
237
+
238
+ def err(self,log_file_name=False):
239
+ """
240
+ This function reads a log file and returns
241
+ the SCF stdev in an array
242
+ ======================== INPUT
243
+ log_file_name :: string, name of .log file
244
+ ======================== Returns
245
+ out_arr :: np.array() with shape (1, # steps)
246
+ array index represents the SCF step
247
+ """
248
+ if not log_file_name:
249
+ with open(f'{self.log}.log','r') as f:
250
+ out_arr = []
251
+ for line in f:
252
+ tmp = line.split()
253
+ if tmp[0][:4] == "RISM":
254
+ out_arr.append(float(tmp[4]))
255
+ #step = tmp[2]
256
+ f.close()
257
+ return np.array(out_arr)
258
+
259
+ def reader(self,file_in:str,laplacian=False,file_out:str='out',dx=False):
260
+ """
261
+ This function takes in an uncompressed dump file txt file
262
+ it reads the grid size and shape
263
+ If specified we can save/export to a dx file which can be loaded into pymol/vmd/etc.
264
+ =================================
265
+ file_in :: the decompress txt file from our ts4s dump command
266
+ grid_spacing :: [x,y,z] values for \delta grid, e.g. grid spacing of 0.5A would
267
+ have grid_spacing = [0.5,0.5,0.5]
268
+ ---------- IF DX=TRUE ---------------
269
+ file_out :: filename for saved dx file
270
+ ################# WARNINGS ################
271
+ since the dx file was made by IBM in the 90s
272
+ many nont-so-modern softwares will struggle to read
273
+ dx files with comments and it appears many follow their own
274
+ format specifications
275
+ """
276
+ from numpy import loadtxt,zeros,copy
277
+ from scipy.ndimage import laplace
278
+ grid_spacing = [self.resolution for _ in range(3)]
279
+ #[i/j for (i,j) in zip(self.solute_box,self.grid)]
280
+
281
+ xs,ys,zs = loadtxt(file_in)[-1][:3]
282
+ x = loadtxt(file_in,usecols=(3))
283
+ #xs,ys,zs
284
+ shaped = zeros((int(xs),int(ys),int(zs)))
285
+ cont = int()
286
+ for zval in range(int(zs)):
287
+ for yval in range(int(ys)):
288
+ for xval in range(int(xs)):
289
+ shaped[xval][yval][zval] = x[cont]#np.linalg.norm(x[cont])
290
+ cont +=1
291
+ if laplacian and not dx:
292
+ return laplace(shaped)
293
+ elif not dx:
294
+ return shaped
295
+ if dx:
296
+ with open(f'{file_out}.dx','w+') as outfile:
297
+ outfile.write(f"""object 1 class gridpositions counts {xs} {ys} {zs}
298
+ origin 0.0000 0.0000 0.0000
299
+ delta {grid_spacing[0]} 0 0
300
+ delta 0 {grid_spacing[1]} 0
301
+ delta 0 0 {grid_spacing[2]}
302
+ object 2 class gridconnections counts {xs} {ys} {zs}
303
+ object 3 class array type double rank 0 items {int(xs*ys*zs)} follows\n""")
304
+ for ind, val in enumerate(shaped.flatten()):
305
+ outfile.write(f"{val:0.5e} ")
306
+ if (ind != 0) and (ind % 3 == 0):
307
+ outfile.write("\n")
308
+ outfile.close()
309
+
310
+ def placement(self,num_waters_to_place:int,radius=1.9269073728633292,filename=False,grid_spacing=None,write_pdb=False,outname='out.pdb',weight=None):
311
+ import numpy as np
312
+ import datetime
313
+ """function selects top distribution
314
+ then places water there, then removes that density
315
+ and continues to look. kind of like placevent.
316
+ =============================
317
+ filename:: txt file containing density
318
+ inputgrid:: md.Grid object
319
+ outname:: string for pdb file
320
+ num_waters_to_place:: number of waters to place
321
+ radius:: distance around selected point to omit from remaining placement
322
+ ideal_radius = ((10**3)/(4/3)/(np.pi)/33.3679)**(1/3) based on number density of water
323
+ grid_spacing:: conversion from array indices to angstrom, units of 1/A
324
+ """
325
+ if grid_spacing is None:
326
+ # you can overide the grid spacing if need be
327
+ grid_spacing = self.resolution
328
+ if not filename:
329
+ filename = f'{self.log}.txt'
330
+
331
+ xs,ys,zs = np.loadtxt(filename)[-1][:3]
332
+ x = np.loadtxt(filename,usecols=(3))
333
+
334
+ shaped = np.zeros((int(xs),int(ys),int(zs)))
335
+ cont = int()
336
+ for zval in range(int(zs)):
337
+ for yval in range(int(ys)):
338
+ for xval in range(int(xs)):
339
+ shaped[xval][yval][zval] = x[cont]#np.linalg.norm(x[cont])
340
+ cont +=1
341
+
342
+ inputgrid = np.copy(shaped)
343
+ x = np.arange(0,inputgrid.shape[0])
344
+ y = np.arange(0,inputgrid.shape[1])
345
+ z = np.arange(0,inputgrid.shape[2])
346
+ out_array = []
347
+ for wat in range(num_waters_to_place):
348
+ r_x,r_y,r_z = np.where(inputgrid == np.max(inputgrid))
349
+ r_x,r_y,r_z = r_x[0],r_y[0],r_z[0]
350
+ out_array.append([float(r_x),float(r_y),float(r_z)])
351
+ mask = (x[:,np.newaxis,np.newaxis]-r_x)**2 + (y[np.newaxis,:,np.newaxis]-r_y)**2 + (z[np.newaxis,np.newaxis,:]-r_z)**2 < (radius/grid_spacing)**2
352
+ inputgrid[mask] = -1
353
+ ################################
354
+ if write_pdb:
355
+ x,y,z = self.grid
356
+ with open(f'{outname}.pdb','w+') as pdb:
357
+ pdb.write(f"CRYST1 {str(x).ljust(4,'0')} {str(y).ljust(4,'0')} {str(z).ljust(4,'0')} 90.00 90.00 90.00 P 1 1\n")
358
+ count = 1
359
+ for val in np.array(out_array)*grid_spacing:#guess2:
360
+ pdb.write(f"ATOM {str(count).rjust(4,' ')} O HOH A{str(count).rjust(3,' ')} {val[0]:8.3f} {val[1]:8.3f} {val[2]:8.3f}\n")
361
+ count +=1
362
+
363
+ return np.array(out_array)*grid_spacing
364
+
365
+ def select_coords(self,in_file:str,sele:str,atom_sele:str=None,conv_fact:int=10):
366
+ """
367
+ in_file: .gro file
368
+ sele: selection string -> resname only so far
369
+ returns:
370
+
371
+ ========
372
+ conv_fact: convert from nm to grid-bits
373
+ for .gro this is X nm*(10A/1nm)
374
+ """
375
+ import numpy as np
376
+ # this is where we select the selection string
377
+ tmp_string = sele.split()
378
+ # Xnm*(10A/1nm)
379
+ with open(f'{in_file}','r') as r:
380
+ count = int()
381
+ atom_count = int()
382
+ out_dict = {}
383
+ for line in r:
384
+ count += 1
385
+ if count == 2:
386
+ atom_count = int(line.split()[0])
387
+ if count == atom_count+2:
388
+ break # this is the end of the file
389
+ ###########
390
+ if count > 2: # ignore header
391
+ try:
392
+ res_id = line[:5].split()[0]
393
+ res_name = line[5:10].split()[0]
394
+ # there is probably a better way of doing this
395
+ if f"{res_name+res_id}" not in out_dict.keys():
396
+ # if the residue is not in the dictionary, add it
397
+ out_dict[f"{res_name+res_id}"] = {}
398
+ else:
399
+ #print(line[20:28].split()[0])
400
+ out_dict[f"{res_name+res_id}"][f"{line[10:15].split()}"] = conv_fact*np.array([float(line[20:28].split()[0]),
401
+ float(line[28:36].split()[0]),
402
+ float(line[36:44].split()[0])])
403
+ except ValueError:
404
+ print(f"ERROR OCCURED AT LINE: {count}")
405
+ continue
406
+ # now we return the x,y,z positions ONLY
407
+ out_array = np.array([])
408
+ for val in out_dict.keys():
409
+ if val[:3] == sele:
410
+ # this uh is a pretty bad way of doing this
411
+ out_array = np.append(out_array,[i for i in out_dict[val].values()])
412
+ #out_array = np.array(out_array)
413
+ #print('out array',out_array)
414
+ """if len(out_array.shape) > 2:
415
+ # this is a bad way of doing this
416
+ y,z,_ = out_array.shape
417
+ out_array = out_array.flatten()#.shape
418
+ out_array = out_array.reshape((y*z,3))"""
419
+ out_array = out_array.reshape((int(len(out_array)/3),3))
420
+
421
+ return out_array
422
+
423
+ def select_around(self,rism_grid,in_coords,around=5.0):
424
+ import numpy as np
425
+ """
426
+ function will take an input grid, select the values surrounding the input
427
+ coordinates according to the user, then return the array surrounding the coords
428
+ while the values greater than the cutoff distance are set to np.NaN
429
+ this is so plotting is easier
430
+ """
431
+ conversion = self.resolution
432
+ around = around/conversion # must convert A to grids
433
+ rism_grid = np.copy(rism_grid)
434
+ x = np.arange(0,rism_grid.shape[0])
435
+ y = np.arange(0,rism_grid.shape[1])
436
+ z = np.arange(0,rism_grid.shape[2])
437
+ #index_grid = np.ndarray(shape=(rism_grid.shape[0],rism_grid.shape[1],rism_grid.shape[2]))
438
+ index_grid = np.full((rism_grid.shape[0],rism_grid.shape[1],rism_grid.shape[2]),False,dtype=bool)
439
+ #print(index_grid.shape)
440
+ for coords in in_coords:
441
+ #print(coords)
442
+ #x_r,y_r,z_r = int(coords[0]),int(coords[1]),int(coords[2])
443
+ x_r,y_r,z_r = float(coords[0])/conversion,float(coords[1])/conversion,float(coords[2])/conversion
444
+ #mask = (x[np.newaxis,:,:]-x_r)**2+(y[:,np.newaxis,:]-y_r)**2+(z[:,:,np.newaxis]-z_r)**2 < around**2
445
+ #print(x[np.newaxis,:,:])
446
+ index_grid[(x[:,np.newaxis,np.newaxis]-x_r)**2+(y[np.newaxis,:,np.newaxis]-y_r)**2+(z[np.newaxis,np.newaxis,:]-z_r)**2 < around**2] = True
447
+ #rism_grid[(x[np.newaxis,:,:]-x_r)**2+(y[:,np.newaxis,:]-y_r)**2+(z[:,:,np.newaxis]-z_r)**2 < around**2] #= np.nan
448
+ #out_grid = rism_grid[index_grid]#np.where(rism_grid == rism_grid[index_grid])]
449
+ return np.where(index_grid == True,rism_grid,np.nan)
450
+
451
+ def extract_grid(self,input_file:str,sele:str='guv',out_name:str='out'):
452
+ """
453
+ This function extracts calc. data from the dump file
454
+ by searching for the value corresponding to the selection string
455
+ This way you dont need to list values to extract them
456
+ """
457
+ assert sele != 'cmd', 'you selected the saved command (cmd)'
458
+ thold = ''.join([chr(i) for i in subprocess.check_output([f"ts4sdump -f {input_file} -l"],shell=True)]).split('\n')
459
+ for val in thold:
460
+ try:
461
+ tmp_str = val.split('@')[0].split()#[1] #.index('guv')
462
+ if tmp_str[1] == sele.strip():
463
+ #print(tmp_str[0])
464
+ value_to_extract = tmp_str[0]
465
+ except IndexError:
466
+ continue
467
+ subprocess.run([f"ts4sdump -f {input_file} -e {value_to_extract} > {out_name}.txt"],shell=True)
468
+ #self.extracted_file = f'{out_name}.txt'
469
+ return
470
+
471
+ def select_grid(self,input_string:str='guv',coord_array=None):
472
+ """
473
+ select values in array based on the selection input string
474
+ +++++++++++++++++++++++++++++++++++++++++++
475
+ so far selection string is limited to selection of
476
+ grid-values around single residue names only: i.e. around 4 resname LYS
477
+ ==================================================
478
+ input_string : value to select and extract
479
+ default value is guv (atomic density)
480
+ if a selection is made value is passed to -> self.get_coords -> self.extract
481
+ else -> self.extract
482
+ """
483
+ from types import NoneType
484
+ from numpy import ndarray
485
+
486
+ if type(coord_array) == NoneType:
487
+ coord_flag = False
488
+ elif type(coord_array) == list:
489
+ coord_flag = True
490
+ coord_array = ndarray(coord_array)
491
+ # change array into np.array
492
+ elif type(coord_array) == ndarray:
493
+ coord_flag = True
494
+
495
+ # these are the possible names to extract
496
+ # we can add more but for now it is unlikely people
497
+ # will want to select weird values, i.e. hlr
498
+ names = {'guv','uuv','ex','ld','coul'}
499
+ # in the future need to add dictionary so people can
500
+ # use more strings, e.g. select g(r) or local density -> guv, ld
501
+ parser = input_string.split()
502
+ #print(parser)
503
+ item = None # this is our selection value i.e. resname
504
+ for name in names:
505
+ if name in parser:
506
+ val = name
507
+ break # can only select one calculation result
508
+
509
+ if 'around' in parser:
510
+ #print(parser.index('around'))
511
+ dist = float(parser[parser.index('around')+1])
512
+ else:
513
+ dist = None
514
+ # if no distance is specified then select everything
515
+
516
+ if 'get' in parser:
517
+ get_flag = True
518
+ #item = parser[parser.index('resname')+1].upper()
519
+ else:
520
+ get_flag = False
521
+ #print(get_flag)
522
+ if (dist or get_flag) and coord_flag:
523
+ # if the user includes an np.array
524
+ # of coordinates then these will be our coordinates to
525
+ # select around
526
+ item = coord_array
527
+
528
+ if 'resname' in parser:
529
+ # will override coordinate array
530
+ # in the future it would be nice to be able to include both
531
+ item = parser[parser.index('resname')+1].upper()
532
+
533
+
534
+ """ if (not coord_array) and dist:
535
+ # if we dont have an input array
536
+ # BUT we have a distance
537
+ item = parser[parser.index('around')+2]
538
+ else:
539
+ item = None"""
540
+ ############## Now extract ts4s file
541
+ self.extract_grid(f'{self.log}.ts4s',sele=val,out_name=f'{val}_{self.log}')
542
+ # read extracted data into a numpy array
543
+ t_grid = self.reader(file_in=f'{val}_{self.log}.txt')#,laplacian=False,file_out='out',dx=False)
544
+ #############
545
+
546
+ if (not coord_flag) and (dist):
547
+ # if we have a distance then that means we have a selection
548
+ # so we select values around our coordinates of the selection item
549
+ coords_ = self.select_coords(self.structure_file,item)
550
+ #print(coords_)
551
+ return self.select_around(t_grid,coords_,around=dist)
552
+
553
+ if (not get_flag) and (not dist):
554
+ # if we dont have a distance that means we dont
555
+ # have a selection and we merely return the entire array
556
+ return t_grid
557
+
558
+ if get_flag and (not coord_flag):
559
+ ee = np.array([],dtype=int)
560
+ max_x,max_y,max_z = np.float64(t_grid.shape)
561
+
562
+ for val in np.round(self.select_coords(self.structure_file,item)/self.resolution):
563
+ ee = np.append(ee,[int(val[0]),int(val[1]),int(val[2])])
564
+
565
+ ee[np.where(ee > max_x)] = max_x-1
566
+ ee[np.where(ee > max_y)] = max_y-1
567
+ ee[np.where(ee > max_z)] = max_z-1
568
+
569
+ ee = ee.reshape((int(len(ee)/3),3))
570
+ #x[ee]
571
+ return t_grid[ee[:,0],ee[:,1],ee[:,2]]
572
+
573
+
574
+ if get_flag and (coord_flag):
575
+ ee = np.array([],dtype=int)
576
+ max_x,max_y,max_z = np.float64(t_grid.shape)
577
+
578
+ for val in np.round(item/self.resolution):
579
+ ee = np.append(ee,[int(val[0]),int(val[1]),int(val[2])])
580
+
581
+ ee[np.where(ee > max_x)] = max_x-1
582
+ ee[np.where(ee > max_y)] = max_y-1
583
+ ee[np.where(ee > max_z)] = max_z-1
584
+
585
+ ee = ee.reshape((int(len(ee)/3),3))
586
+ #x[ee]
587
+ return t_grid[ee[:,0],ee[:,1],ee[:,2]]
588
+ else:
589
+ # if we have a distance and coord_array then we
590
+ # return the grid selected around the coord_array
591
+ return self.select_around(t_grid,item,around=dist)