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 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
|
# Another simple example of how PyMOL can be controlled using a web browser
# using Python's built-in web server capabilities
try:
import BaseHTTPServer
except ImportError:
import http.server as BaseHTTPServer
import time
import cgi
import string
import threading
import traceback
import os, sys, re
from pymol import cmd
from chempy.sdf import SDF
# example 3D sd file
input_sdf = os.environ['PYMOL_PATH']+"/test/dat/ligs3d.sdf"
if not os.path.exists(input_sdf):
from inspect import getsourcefile
current_file_dir = os.path.dirname(os.path.abspath(getsourcefile(lambda:0)))
input_sdf = os.path.join(current_file_dir, "../../test/dat/ligs3d.sdf")
class SafeDict(dict):
'''
we will need to synchronize access if we later adopt a
multi-threaded approach
'''
pass
# global singleton class for holding server state
ServerState = SafeDict()
# we're not maintaining session tokens yet...
default_token = 0
def write_table(out, table):
out.write('<html>\n')
out.write('<header>\n')
out.write('<link rel="stylesheet" type="text/css" href="/pymol.css"></link>')
out.write('<script type="text/javascript" src="pymol.js"></script>\n')
out.write('</header>')
out.write('<body>\n')
out.write('<form action="./quit.pymol"><button type="submit">Quit</button></form>\n')
out.write('<table>\n')
header = table['header']
for heading in header:
out.write('<th>')
out.write(heading)
out.write('</th>')
body = table['body']
for row in body:
out.write('<tr>')
for col in row:
out.write('<td>')
out.write(col)
out.write('</td>')
out.write('</tr>\n')
out.write('</table>')
out.write('<iframe name="myStatus" width="500" height="60" frameborder=0>')
out.write('</iframe>\n')
out.write('<form name="hidden" target="myStatus"></form>')
out.write('</body></html>\n')
_server = None
def _shutdown(self_cmd=cmd):
global _server
if _server != None:
_server.socket.close()
self_cmd.quit()
class PymolHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def log_message(self, format, *args):
# nuke logging for the time being since it slows down PyMOL
pass
def do_css(self):
self.send_response(200)
self.send_header('Content-type','text/css')
self.end_headers()
self.wfile.write('''
table {
border-width: 1px 1px 1px 1px;
border-spacing: 1px;
border-style: outset outset outset outset;
border-color: gray gray gray gray;
border-collapse: separate;
background-color: gray;
}
table th {
border-width: 1px 1px 1px 1px;
padding: 2px 5px 2px 5px;
border-style: inset inset inset inset;
border-color: gray gray gray gray;
background-color: lightblue;
-moz-border-radius: 0px 0px 0px 0px;
}
table td {
border-width: 1px 1px 1px 1px;
padding: 2px 5px 2px 5px;
border-style: inset inset inset inset;
border-color: gray gray gray gray;
background-color: white;
-moz-border-radius: 0px 0px 0px 0px;
}
a:link {text-decoration: none; color: blue; }
a:visited {text-decoration: none; color: blue; }
a:active {text-decoration: none; color: blue; }
''')
def do_js(self):
self.send_response(200)
self.send_header('Content-type','text/javascript')
self.end_headers()
self.wfile.write('''
function load(molid)
{
// unnecessary...but keeping it around for later...
// this doesnt actually work anyway!
document.forms['hidden'].method='get';
document.forms['hidden'].action='http://localhost:8080/load.pymol?test=1&molid=' + molid;
document.forms['hidden'].submit();
}
''')
def do_pymol(self):
if "table.pymol" in self.path: # send table
session = ServerState[default_token]
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.send_header('Cache-control', 'no-cache')
self.send_header('Pragma', 'no-cache')
self.end_headers()
if 'table' not in session:
self.wfile.write("<p>No table defined.</p>\n")
else:
write_table(self.wfile, session['table'])
elif "quit.pymol" in self.path:
self.wfile.write('<html><body><p>Quitting...</p></body></html>')
self.wfile.flush()
_shutdown()
elif "load.pymol" in self.path:
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.send_header('Cache-control', 'no-cache')
self.send_header('Pragma', 'no-cache')
self.end_headers()
mo = re.search("molid\=([A-Z0-9]+)",self.path)
if mo:
mol_id = mo.groups(1)[0]
session = ServerState[default_token]
mol_dict = session['data']['mol_dict']
self_cmd = session['cmd']
if mol_id in self_cmd.get_names('objects'):
if mol_id in self_cmd.get_names('objects',enabled_only=1):
self.wfile.write("<p>Disabling %s...</p>"%mol_id)
self_cmd.disable(mol_id)
else:
self.wfile.write("<p>Enabling %s...</p>"%mol_id)
self_cmd.enable(mol_id)
else:
self.wfile.write("<p>Loading %s...</p>"%mol_id)
self_cmd.read_molstr(mol_dict[mol_id], mol_id)
self_cmd.show_as("sticks",mol_id)
else:
self.wfile.write("<p>Error processing query: %s</p>"%self.path)
else: # start page
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.send_header('Cache-control', 'no-cache')
self.send_header('Pragma', 'no-cache')
self.end_headers()
self.wfile.write("<p>Unhandled PyMOL request</p>")
self.wfile.flush()
def do_GET(self):
try:
doc = self.path.split('?')[0]
if doc.endswith('.pymol'): # PyMOL
try:
self.do_pymol()
except:
traceback.print_exc()
elif doc.endswith('.js'): # Javascript
self.do_js()
elif doc.endswith('.css'): # Javascript
self.do_css()
elif doc.endswith('.html'):
f = open('.'+self.path) # UNSAFE!!!
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(f.read())
f.close()
except IOError:
self.send_error(404,'File Not Found: %s' % self.path)
def do_POST(self): # not currently used
global rootnode
try:
ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
if ctype == 'multipart/form-data':
query=cgi.parse_multipart(self.rfile, pdict)
self.send_response(301)
self.end_headers()
upfilecontent = query.get('upfile')
print("filecontent", upfilecontent[0])
self.wfile.write('<HTML>POST OK.<BR><BR>');
self.wfile.write(upfilecontent[0]);
except :
pass
def table_from_data(data):
# pull MOLID to the far left
col_id_list = ['MOLID'] + [x for x in data['col_id_list'] if x!='MOLID']
content = data['content']
# create the header fields
header = []
for col_id in col_id_list:
header.append(col_id)
# create the body
body = []
for row_id in data['row_id_list']:
row = []
for col_id in col_id_list:
if col_id == 'MOLID':
text = content.get( (row_id,col_id),'')
row.append('<a target="myStatus" href="load.pymol?molid=%s">'%text +
text + '</a>')
else:
row.append( content.get( (row_id,col_id),'' ))
body.append(row)
return {
'header' : header,
'body' : body,
}
def data_from_sdf(sdf_file_path):
mol_dict = {}
row_id_list = []
row_id_dict = {}
col_id_list = []
col_id_dict = {}
# first pass, load the identifiers, MOL files, and tag names
col = 0
sdf = SDF(sdf_file_path)
while 1:
rec = sdf.read()
if not rec:
break
mol = rec.get('MOL')
# get the unique identifier
mol_id = mol[0].strip()
# store the MOL record
mol_dict[mol_id] = ''.join(mol)
# add row (assuming mol_id is unique)
row_id_list.append(mol_id)
row_id_dict[mol_id] = None
# add column (if new)
for key in rec.kees:
if key != 'MOL':
if key not in col_id_dict:
col_id_list.append(key)
col_id_dict[key] = None
# second pass, read the actual data into the table structure
content = {}
sdf = SDF(sdf_file_path)
while 1:
rec = sdf.read()
if not rec:
break
mol_id = rec.get('MOL')[0].strip()
for key in rec.kees:
if key != 'MOL':
content[ (mol_id,key) ] = rec.get(key)[0].strip()
return {
'content' : content,
'row_id_list' : row_id_list,
'col_id_list' : col_id_list,
'mol_dict' : mol_dict
}
def open_browser():
import webbrowser
time.sleep(1)
webbrowser.open('http://localhost:8080/table.pymol')
# import os
# os.system('open http://localhost:8080/start.pymol')
def main():
try:
global _server
_server = BaseHTTPServer.HTTPServer(('', 8080), PymolHandler)
print('started httpserver...')
_server.serve_forever()
except KeyboardInterrupt:
print('^C received, shutting down server')
_server.socket.close()
if __name__ == '__main__':
print("this script must be run from within PyMOL")
if __name__ == 'pymol':
session = SafeDict()
session['cmd'] = cmd # could replaced by instance instead of module
session['data'] = data_from_sdf(input_sdf)
session['table'] = table_from_data(session['data'])
ServerState[default_token] = session
t = threading.Thread(target=main)
t.setDaemon(1)
t.start()
t = threading.Thread(target=open_browser)
t.setDaemon(1)
t.start()
"""
"""
|