-
Notifications
You must be signed in to change notification settings - Fork 1
/
refine_model_tasks.py
282 lines (257 loc) · 7.86 KB
/
refine_model_tasks.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
"""
Created on 23.10.2015
@author: daniel
"""
import os
# import pprint
from FragmentDB.helper_functions import REL_RESTR_CARDS, SHX_CARDS, remove_partsymbol
try:
import olx # @UnresolvedImport
from olexFunctions import OlexFunctions
from ImageTools import ImageTools
except:
pass
try:
OV = OlexFunctions()
IT = ImageTools()
except:
pass
# import cProfile
# import pstats
# cp = cProfile.Profile()
# cp.enable(subcalls=True, builtins=True)
class Refmod(object):
"""
handles the refinement model of olex2
"""
def __init__(self):
"""
Constructor
"""
self.htm = html_Table()
def fileparser(self, lstfile):
"""
gathers the residuals of the lst file
It searches for the final cycle summary and then for " Disagreeable restraints".
End is reached with ' Summary of restraints'
"""
if not lstfile:
return
disag = False
final = False
disargeelist = []
num = 0
with open(lstfile, 'r') as f:
for line in f:
splitline = line.split()
if not splitline:
continue
if splitline[0].startswith('Observed'):
continue
if line.startswith(" Final Structure Factor"):
final = True
if final and line.startswith(' Disagreeable restraints'):
disag = True
continue
if line.startswith(' Summary of restraints'):
final = False
disag = False
if "RIGU" in line:
continue
if disag:
# in this case, the desired line is found:
fline = self.lineformatter(splitline)
# fline is a list of list
disargeelist.append(fline)
num = num + 1
if num > 1000:
print('Cutting restraints list. Too many restraints...')
return disargeelist
return disargeelist
def lineformatter(self, line):
"""
takes care of some extra things with different restraints. For example
RIGU xy should be in one column
:type line: list
"""
for num, i in enumerate(line):
i = i.replace('/', ' ')
if i[0].isalpha():
pos = num
break
# remove the part symbol from e.g. F1_2a:
for num, i in enumerate(line):
line[num] = remove_partsymbol(i)
# joining columns without numbers:
line[pos:] = [' '.join(line[pos:])]
tline = ' '.join(line)
for n in REL_RESTR_CARDS:
if n in tline:
# adding placeholders for empty fields:
line = ['-', '-'] + line
break
return line
def get_listfile(self):
"""
returns the path of the current SHELXL list file
"""
try:
lstfile = os.path.abspath(OV.FilePath() + os.path.sep + OV.FileName() + '.lst')
if not os.path.isfile(lstfile):
# print('No list file found.')
return ''
except:
print('Something is wrong with the lst file path.')
return ''
return lstfile
def results(self):
"""
prepare the results for the plugin
"""
filedata = self.fileparser(self.get_listfile()) # raw table
if not filedata:
filedata = []
html = self.htm.table_maker(filedata)
return html
class html_Table(object):
"""
html table generator
"""
def __init__(self):
try:
# more than two colors here are too crystmas treelike:
grade_2_colour = OV.GetParam('gui.skin.diagnostics.colour_grade2')
self.grade_2_colour = self.rgb2hex(IT.adjust_colour(grade_2_colour, luminosity=1.8))
grade_4_colour = OV.GetParam('gui.skin.diagnostics.colour_grade4')
self.grade_4_colour = self.rgb2hex(IT.adjust_colour(grade_4_colour, luminosity=1.8))
except(ImportError, NameError):
self.grade_2_colour = '#FFD100'
self.grade_4_colour = '#FF1030'
def rgb2hex(self, rgb):
"""
return the hexadecimal string representation of an rgb colour
"""
return '#%02x%02x%02x' % rgb
def table_maker(self, tabledata=None):
"""
builds a html table out of a datalist from the final
cycle summary of a shelxl list file.
"""
if tabledata is None:
tabledata = []
table = []
for line in tabledata:
table.append(self.row(line))
footer = ""
empty_data = """
<table width="100%" border="0" cellpadding="0" cellspacing="3" >
<tr>
<td align='center'> Observed </td>
<td align='center'> Target </td>
<td align='center'> Error </td>
<td align='center'> Sigma </td>
<td align='left'> Restraint </td>
</tr>
<tr>
<td align='center'> -- </td>
<td align='center'> -- </td>
<td align='center'> -- </td>
<td align='center'> -- </td>
<td align='center'> -- </td>
</tr>
</table>"""
html = r"""
<table width="100%" border="0" cellpadding="0" cellspacing="3">
<tr>
<td align='center'> Observed </td>
<td align='center'> Target </td>
<td align='center'> Error </td>
<td align='center'> Sigma </td>
<td align='left'> Restraint </td>
</tr>
{0}
</table>
{1}
""".format('\n'.join(table), footer)
if not table:
return empty_data
return html
def row(self, rowdata):
"""
creates a table row for the restraints list.
:type rowdata: list
"""
td = []
bgcolor = ''
try:
if abs(float(rowdata[2])) > 2.5 * float(rowdata[3]):
bgcolor = r"""bgcolor='{}'""".format(self.grade_2_colour)
if abs(float(rowdata[2])) > 3.5 * float(rowdata[3]):
bgcolor = r"""bgcolor='{}'""".format(self.grade_4_colour)
except ValueError:
print("Unknown restraint occured.")
for num, item in enumerate(rowdata):
try:
# align right for numbers:
float(item)
if num < 2:
# do not colorize the first two columns:
td.append(r"""<td align='right'> {} </td>""".format(item))
else:
td.append(r"""<td align='right' {0}> {1} </td>""".format(bgcolor, item))
except:
if item.startswith('-'):
# only a minus sign
td.append(r"""<td align='center'> {} </td>""".format(item))
else:
if num < 4:
td.append(r"""<td align='right'> {} </td>""".format(item))
continue
# align left for words:
td.append(r"""
<td align='left'>
{}
<a href="spy.Refmod.edit_restraints({})"> edit </a>
</td>""".format(item, item))
if not td:
row = "<tr> No (disagreeable) restraints found in .lst file. </tr>"
else:
row = "<tr> {} </tr>".format(''.join(td))
return row
def edit_restraints(self, restr):
"""
this method gets the atom list of a disagreeable restraint in olex2.
The text string is then formated so that "editatom" can handle it.
editatom opens an editor window with the respective atoms.
:type restr: string like "SAME/SADI Co N11 Co N22"
"""
# separate SAME/SADI:
restr = restr.replace('/', ' ')
restrlist = restr.split()
atoms = []
for i in restrlist:
if i in SHX_CARDS:
continue
if i in ['xz', 'yz', 'xy', 'etc.']:
continue
else:
# atoms.append(remove_partsymbol(i)) # Have to remove this, because new names needed for 'edit'
atoms.append(i)
OV.cmd('editatom {}'.format(' '.join(atoms)))
htm = html_Table()
try:
OV.registerFunction(htm.edit_restraints, False, "Refmod")
except:
pass
if __name__ == '__main__':
# import cProfile
# cp = cProfile.Profile()
# cp.enable(subcalls=True, builtins=True)
ref = Refmod()
lst = ref.fileparser(r'Z:\dkratzer\Strukturen\service\!Ehemalige\Tobi_Engesser\01_IKte_litcapf\p1_a.lst')
# lst = ref.fileparser(r'D:\tmp\big_strukt\p-1.lst')
# lst = ref.fileparser('/Users/daniel/Documents/DSR/example/p21c.lst')
tab = htm.table_maker(lst)
print(tab)
# cp.disable()
# pstats.Stats(cp).strip_dirs().sort_stats('cumtime').print_stats(30)