py3Dmol 3.0.0__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.
py3Dmol/__init__.py
ADDED
|
@@ -0,0 +1,458 @@
|
|
|
1
|
+
import time
|
|
2
|
+
import json
|
|
3
|
+
import sys
|
|
4
|
+
import re
|
|
5
|
+
from urllib.parse import urlsplit, urlunsplit
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
import IPython.display
|
|
9
|
+
_has_IPython = True
|
|
10
|
+
except ImportError:
|
|
11
|
+
_has_IPython = False
|
|
12
|
+
|
|
13
|
+
if sys.version_info >= (3, 8):
|
|
14
|
+
from importlib import metadata
|
|
15
|
+
else:
|
|
16
|
+
import importlib_metadata as metadata
|
|
17
|
+
|
|
18
|
+
__version__ = metadata.version('py3Dmol')
|
|
19
|
+
|
|
20
|
+
#surface type constants
|
|
21
|
+
VDW =1
|
|
22
|
+
MS=2
|
|
23
|
+
SAS=3
|
|
24
|
+
SES=4
|
|
25
|
+
|
|
26
|
+
def using_ipython(func):
|
|
27
|
+
|
|
28
|
+
def inner(*args, **kwargs):
|
|
29
|
+
if not _has_IPython:
|
|
30
|
+
raise ImportError("This function requires an active IPython notebook.")
|
|
31
|
+
return func(*args, **kwargs)
|
|
32
|
+
|
|
33
|
+
return inner
|
|
34
|
+
|
|
35
|
+
def tostr(arg):
|
|
36
|
+
'''convert an argument to javascript string,
|
|
37
|
+
can handle top-level numpy/torch arrays'''
|
|
38
|
+
try:
|
|
39
|
+
return json.dumps(arg)
|
|
40
|
+
except TypeError:
|
|
41
|
+
return json.dumps(arg.tolist()) #numpy arrays and torch tensor
|
|
42
|
+
|
|
43
|
+
class view(object):
|
|
44
|
+
'''Construct HTML/JavaScript views for IPython notebooks and exported pages.
|
|
45
|
+
Displayed views remain interactive without a running kernel. Python queues
|
|
46
|
+
browser commands; JavaScript results and events are not returned to Python.
|
|
47
|
+
The page still needs JavaScript, WebGL, and any referenced network resources.
|
|
48
|
+
|
|
49
|
+
A viewergrid tuple (rows, columns) creates a grid sharing one canvas.
|
|
50
|
+
Commands apply to all cells unless viewer=(row, column) selects one cell
|
|
51
|
+
using zero-based indices. getModel requires a cell when a grid is enabled.
|
|
52
|
+
|
|
53
|
+
Forwarded methods use the GLViewer API with JSON-serializable positional
|
|
54
|
+
arguments and return this Python view for chaining, not JavaScript results.
|
|
55
|
+
getModel returns a proxy for queuing GLModel calls. Python callbacks and
|
|
56
|
+
browser-side promises are not supported across this one-way interface.
|
|
57
|
+
https://3dmol.org/doc/GLViewer.html
|
|
58
|
+
'''
|
|
59
|
+
def __init__(self,query='',width=640,height=480,viewergrid=None,data=None,style=None,linked=True,options=dict(),format=None,js=None,
|
|
60
|
+
edit=False,trajectory=False,learning=False,ui_js=None):
|
|
61
|
+
'''Create a 3Dmol.js view.
|
|
62
|
+
width -- container width in pixels (int) or a CSS dimension string
|
|
63
|
+
height -- container height in pixels (int) or a CSS dimension string
|
|
64
|
+
query -- optional argument to provide to $3Dmol.download
|
|
65
|
+
viewergrid -- optional tuple (rows,columns) to define grid
|
|
66
|
+
linked -- whether mouse controls affect all grid cells (default True)
|
|
67
|
+
data -- molecular data to provide to addModel, with viewer grid can be indexed (r,c)
|
|
68
|
+
format -- format of provided data
|
|
69
|
+
style -- style to apply, with viewer grid can be indexed (r,c)
|
|
70
|
+
options -- optional options to provide to $3Dmol.download or addModel
|
|
71
|
+
js -- core bundle URL; defaults to the same pinned npm release for all
|
|
72
|
+
views, with or without controls. The first load wins.
|
|
73
|
+
edit -- show the edit-menu button (default False)
|
|
74
|
+
trajectory -- show trajectory controls when frames are present (default False)
|
|
75
|
+
learning -- True for a classroom button, or a LearningConfig dictionary;
|
|
76
|
+
hidden mode requires {'mode': 'hidden', 'session': 'unique-id'}.
|
|
77
|
+
The server defaults to https://3dmol.csb.pitt.edu.
|
|
78
|
+
ui_js -- optional UI bundle URL, otherwise inferred alongside js;
|
|
79
|
+
use matching core and UI builds when overriding either URL
|
|
80
|
+
Controls require a single viewer (viewergrid=(1,1) is also supported).
|
|
81
|
+
Python queues commands; classroom events do not call back into Python.'''
|
|
82
|
+
if not isinstance(learning, (bool, dict)):
|
|
83
|
+
raise TypeError('learning must be a boolean or a configuration dictionary')
|
|
84
|
+
if isinstance(learning, dict):
|
|
85
|
+
mode = learning.get('mode', 'button')
|
|
86
|
+
if mode not in ('button', 'hidden'):
|
|
87
|
+
raise ValueError("learning mode must be 'button' or 'hidden'")
|
|
88
|
+
session = learning.get('session')
|
|
89
|
+
if mode == 'hidden' and (not isinstance(session, str) or not session.strip()):
|
|
90
|
+
raise ValueError('Hidden classroom mode requires a nonblank session identifier')
|
|
91
|
+
has_ui = bool(edit or trajectory or learning is True or isinstance(learning, dict))
|
|
92
|
+
if has_ui and viewergrid and tuple(viewergrid) != (1, 1):
|
|
93
|
+
raise ValueError('Controls require a single viewer; use separate views instead of a multi-cell viewergrid')
|
|
94
|
+
if js is None:
|
|
95
|
+
js = 'https://cdn.jsdelivr.net/npm/3dmol@3.0.0/build/3Dmol-min.js'
|
|
96
|
+
if has_ui and ui_js is None:
|
|
97
|
+
parts = urlsplit(js)
|
|
98
|
+
path, matches = re.subn(r'(^|/)3Dmol(-min)?\.js$', r'\g<1>3Dmol.ui\g<2>.js', parts.path)
|
|
99
|
+
if not matches:
|
|
100
|
+
raise ValueError('Specify ui_js when js does not end in 3Dmol.js or 3Dmol-min.js')
|
|
101
|
+
ui_js = urlunsplit(parts._replace(path=path))
|
|
102
|
+
# These values live inside an inline script, not just a JavaScript string.
|
|
103
|
+
# Escape '<' so a session identifier or URL cannot close the script tag.
|
|
104
|
+
ui_config = json.dumps({'edit': bool(edit), 'trajectory': bool(trajectory),
|
|
105
|
+
'learning': learning}).replace('<', '\\u003c')
|
|
106
|
+
divid = "3dmolviewer_UNIQUEID"
|
|
107
|
+
warnid = "3dmolwarning_UNIQUEID"
|
|
108
|
+
self.uniqueid = None
|
|
109
|
+
#convert numerical width/height to pixels
|
|
110
|
+
if type(width) == int:
|
|
111
|
+
width = '%dpx'%width
|
|
112
|
+
if type(height) == int:
|
|
113
|
+
height = '%dpx'%height
|
|
114
|
+
self.startjs = '''<div id="%s" style="position: relative; width: %s; height: %s;">
|
|
115
|
+
<p id="%s" style="background-color:#ffcccc;color:black">3Dmol.js failed to load for some reason. Please check your browser console for error messages.<br></p>
|
|
116
|
+
</div>\n''' % (divid,width,height,warnid)
|
|
117
|
+
self.startjs += '<script>\n'
|
|
118
|
+
self.endjs = '</script>'
|
|
119
|
+
|
|
120
|
+
self.updatejs = '' # code added since last show
|
|
121
|
+
#load 3dmol, but only once, can't use jquery :-(
|
|
122
|
+
#https://medium.com/@vschroeder/javascript-how-to-execute-code-from-an-asynchronously-loaded-script-although-when-it-is-not-bebcbd6da5ea
|
|
123
|
+
self.startjs += """
|
|
124
|
+
var loadScriptAsync = function(uri){
|
|
125
|
+
return new Promise((resolve, reject) => {
|
|
126
|
+
//this is to ignore the existence of requirejs amd
|
|
127
|
+
var savedexports, savedmodule;
|
|
128
|
+
if (typeof exports !== 'undefined') savedexports = exports;
|
|
129
|
+
else exports = {}
|
|
130
|
+
if (typeof module !== 'undefined') savedmodule = module;
|
|
131
|
+
else module = {}
|
|
132
|
+
|
|
133
|
+
var tag = document.createElement('script');
|
|
134
|
+
tag.src = uri;
|
|
135
|
+
tag.async = true;
|
|
136
|
+
tag.onload = () => {
|
|
137
|
+
exports = savedexports;
|
|
138
|
+
module = savedmodule;
|
|
139
|
+
resolve();
|
|
140
|
+
};
|
|
141
|
+
tag.onerror = () => {
|
|
142
|
+
exports = savedexports;
|
|
143
|
+
module = savedmodule;
|
|
144
|
+
reject(new Error('Unable to load ' + uri));
|
|
145
|
+
};
|
|
146
|
+
var firstScriptTag = document.getElementsByTagName('script')[0];
|
|
147
|
+
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
|
|
148
|
+
});
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
if(typeof $3Dmolpromise === 'undefined') {
|
|
152
|
+
$3Dmolpromise = typeof $3Dmol === 'undefined' ? loadScriptAsync(%s) : Promise.resolve();
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
var viewer_UNIQUEID = null;
|
|
156
|
+
""" % json.dumps(js).replace('<', '\\u003c')
|
|
157
|
+
|
|
158
|
+
dependency = '$3Dmolpromise'
|
|
159
|
+
if has_ui:
|
|
160
|
+
self.startjs += """
|
|
161
|
+
if(typeof $3DmolUIpromise === 'undefined') {
|
|
162
|
+
$3DmolUIpromise = $3Dmolpromise.then(function() {
|
|
163
|
+
if (typeof $3Dmol.StateManager === 'function') return;
|
|
164
|
+
return loadScriptAsync(%s);
|
|
165
|
+
}).then(function() {
|
|
166
|
+
if (typeof $3Dmol.StateManager !== 'function') {
|
|
167
|
+
throw new Error('The UI bundle does not provide StateManager. Use matching core and UI builds.');
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
""" % json.dumps(ui_js).replace('<', '\\u003c')
|
|
172
|
+
dependency = '$3DmolUIpromise'
|
|
173
|
+
|
|
174
|
+
self.startjs += 'var viewer_ready_UNIQUEID = %s.then(function() {\n' % dependency
|
|
175
|
+
self.startjs += """
|
|
176
|
+
var warn = document.getElementById("%s");
|
|
177
|
+
if(warn) {
|
|
178
|
+
warn.parentNode.removeChild(warn);
|
|
179
|
+
}
|
|
180
|
+
""" % warnid
|
|
181
|
+
|
|
182
|
+
self.endjs = '''});
|
|
183
|
+
viewer_ready_UNIQUEID.catch(function(error) {
|
|
184
|
+
var host = document.getElementById("%s");
|
|
185
|
+
if (host) {
|
|
186
|
+
var warning = document.getElementById("%s") || document.createElement('p');
|
|
187
|
+
warning.id = "%s";
|
|
188
|
+
warning.style.cssText = 'position:absolute;top:0;background:#ffcccc;color:black';
|
|
189
|
+
warning.textContent = '3Dmol.js failed to initialize: ' + error.message;
|
|
190
|
+
host.appendChild(warning);
|
|
191
|
+
}
|
|
192
|
+
console.error(error);
|
|
193
|
+
});
|
|
194
|
+
</script>''' % (divid, warnid, warnid)
|
|
195
|
+
self.viewergrid = None
|
|
196
|
+
|
|
197
|
+
if viewergrid: #create split view
|
|
198
|
+
if len(viewergrid) != 2:
|
|
199
|
+
raise ValueError("Incorrectly formated viewergrid arguments. Must specify rows x columns",viewergrid)
|
|
200
|
+
self.startjs += "var viewergrid_UNIQUEID = null;\n";
|
|
201
|
+
self.startjs += 'viewergrid_UNIQUEID = $3Dmol.createViewerGrid(document.getElementById("%s"),{rows: %d, cols: %d, control_all: %s},{backgroundColor:"white"});\n' % (divid, viewergrid[0],viewergrid[1],'true' if linked else 'false')
|
|
202
|
+
self.startjs += "viewer_UNIQUEID = viewergrid_UNIQUEID[0][0];\n"
|
|
203
|
+
self.viewergrid = viewergrid
|
|
204
|
+
else:
|
|
205
|
+
self.startjs += 'viewer_UNIQUEID = $3Dmol.createViewer(document.getElementById("%s"),{backgroundColor:"white"});\n' % divid
|
|
206
|
+
if query:
|
|
207
|
+
if viewergrid:
|
|
208
|
+
for r in range(viewergrid[0]):
|
|
209
|
+
for c in range(viewergrid[1]):
|
|
210
|
+
self.startjs += 'return $3Dmol.download(%s, viewergrid_UNIQUEID[%d][%d], %s).then(function() {\n' % (json.dumps(query),r,c,json.dumps(options))
|
|
211
|
+
self.endjs = "});\n" + self.endjs
|
|
212
|
+
else:
|
|
213
|
+
self.startjs += 'return $3Dmol.download(%s, viewer_UNIQUEID, %s).then(function() {\n' % (json.dumps(query),json.dumps(options))
|
|
214
|
+
self.endjs = "});\n" + self.endjs
|
|
215
|
+
|
|
216
|
+
finish = ''
|
|
217
|
+
if has_ui:
|
|
218
|
+
if learning is True or isinstance(learning, dict):
|
|
219
|
+
finish += "if (typeof $3Dmol.LearningSession !== 'function') throw new Error('This UI bundle does not support classrooms. Use matching current core and UI builds.');\n"
|
|
220
|
+
finish += 'new $3Dmol.StateManager(viewer_UNIQUEID, %s);\n' % ui_config
|
|
221
|
+
self.endjs = finish + 'return viewer_UNIQUEID;\n' + self.endjs
|
|
222
|
+
|
|
223
|
+
if viewergrid:
|
|
224
|
+
for r in range(viewergrid[0]):
|
|
225
|
+
for c in range(viewergrid[1]):
|
|
226
|
+
cmds = ''
|
|
227
|
+
if data:
|
|
228
|
+
try:
|
|
229
|
+
if type(data) == str:
|
|
230
|
+
d = data
|
|
231
|
+
else:
|
|
232
|
+
d = data[r][c]
|
|
233
|
+
except:
|
|
234
|
+
d = data
|
|
235
|
+
try:
|
|
236
|
+
if type(format) == str:
|
|
237
|
+
f = format
|
|
238
|
+
else:
|
|
239
|
+
f = format[r][c]
|
|
240
|
+
except:
|
|
241
|
+
f = format
|
|
242
|
+
self.startjs += f"viewergrid_UNIQUEID[{r}][{c}].addModel({json.dumps(d)},{json.dumps(f) if f else 'undefined'},{json.dumps(options) if options else 'undefined'});\n"
|
|
243
|
+
if style:
|
|
244
|
+
try:
|
|
245
|
+
s = style[r][c]
|
|
246
|
+
except:
|
|
247
|
+
s = style
|
|
248
|
+
cmds += "viewergrid_UNIQUEID[%d][%d].setStyle(%s);\n"%(r,c,json.dumps(s))
|
|
249
|
+
self.startjs += cmds+"viewergrid_UNIQUEID[%d][%d].zoomTo();"%(r,c)
|
|
250
|
+
self.endjs = "viewergrid_UNIQUEID[%d][%d].render();\n"%(r,c)+self.endjs;
|
|
251
|
+
else:
|
|
252
|
+
cmds = ''
|
|
253
|
+
if data:
|
|
254
|
+
cmds = f"viewer_UNIQUEID.addModel({json.dumps(data)},{json.dumps(format) if format else 'undefined'},{json.dumps(options) if options else 'undefined'});\n"
|
|
255
|
+
if style:
|
|
256
|
+
cmds += "viewer_UNIQUEID.setStyle(%s);\n"%json.dumps(style)
|
|
257
|
+
self.startjs += cmds + "viewer_UNIQUEID.zoomTo();\n"
|
|
258
|
+
self.endjs = "viewer_UNIQUEID.render();\n" + self.endjs;
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
@using_ipython
|
|
262
|
+
def show(self):
|
|
263
|
+
'''Instantiate a new viewer window. Calling this will orphan any previously instantiated viewer windows.'''
|
|
264
|
+
self.updatejs = ''
|
|
265
|
+
html = self._make_html()
|
|
266
|
+
return IPython.display.publish_display_data({'application/3dmoljs_load.v0':html, 'text/html': html},metadata={})
|
|
267
|
+
|
|
268
|
+
@using_ipython
|
|
269
|
+
def insert(self, containerid):
|
|
270
|
+
'''Instead of inserting into notebook here, insert html
|
|
271
|
+
into existing container'''
|
|
272
|
+
html = self._make_html()
|
|
273
|
+
html += '''<script>document.getElementById("%s").append(document.getElementById("3dmolviewer_%s")); </script>'''%(containerid,self.uniqueid)
|
|
274
|
+
return IPython.display.publish_display_data({'application/3dmoljs_load.v0':html, 'text/html': html},metadata={})
|
|
275
|
+
|
|
276
|
+
def _make_html(self):
|
|
277
|
+
self.uniqueid = str(time.time()).replace('.','')
|
|
278
|
+
self.updatejs = ''
|
|
279
|
+
html = (self.startjs+self.endjs).replace('UNIQUEID',self.uniqueid)
|
|
280
|
+
return html
|
|
281
|
+
|
|
282
|
+
@using_ipython
|
|
283
|
+
def _repr_html_(self):
|
|
284
|
+
html = self._make_html()
|
|
285
|
+
return IPython.display.publish_display_data({'application/3dmoljs_load.v0':html, 'text/html': html},metadata={})
|
|
286
|
+
|
|
287
|
+
@using_ipython
|
|
288
|
+
def update(self):
|
|
289
|
+
'''Apply commands to existing viewer (will auto-instantiate if necessary).'''
|
|
290
|
+
script = ''
|
|
291
|
+
if self.uniqueid == None:
|
|
292
|
+
script = self._make_html()
|
|
293
|
+
script += '''<script>
|
|
294
|
+
viewer_ready_%s.then(function() { //wait for this view's scene and controls
|
|
295
|
+
%s
|
|
296
|
+
viewer_%s.render();
|
|
297
|
+
if (viewer_%s.ui) viewer_%s.ui.refresh();
|
|
298
|
+
});
|
|
299
|
+
</script>''' % (self.uniqueid,self.updatejs.replace('UNIQUEID',self.uniqueid),self.uniqueid,self.uniqueid,self.uniqueid)
|
|
300
|
+
self.updatejs = ''
|
|
301
|
+
return IPython.display.publish_display_data({'application/3dmoljs_load.v0':script, 'text/html': script},metadata={})
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def write_html(self, f=None, fullpage=False):
|
|
305
|
+
'''Export the queued scene as HTML without requiring notebook display.
|
|
306
|
+
f -- file name (str) or writable file object; omitted returns an HTML fragment
|
|
307
|
+
fullpage -- fill the page instead of using the configured size when writing f;
|
|
308
|
+
this option is not applied when returning a string
|
|
309
|
+
Referenced scripts and remote molecular data are not embedded by this method.
|
|
310
|
+
'''
|
|
311
|
+
|
|
312
|
+
if f == None:
|
|
313
|
+
return self._make_html()
|
|
314
|
+
|
|
315
|
+
if type(f) == str:
|
|
316
|
+
f = open(f,'wt')
|
|
317
|
+
html = self._make_html()
|
|
318
|
+
html = f'''<html>
|
|
319
|
+
<body style="margin: 0; padding: 0; display: block;">
|
|
320
|
+
{html}
|
|
321
|
+
</body>
|
|
322
|
+
</html>'''
|
|
323
|
+
if fullpage:
|
|
324
|
+
html = re.sub(r'width: (\S+);', 'width: 100%;', html)
|
|
325
|
+
html = re.sub(r'height: (\S+);', 'height: 100vh;', html)
|
|
326
|
+
|
|
327
|
+
f.write(html)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
@using_ipython
|
|
331
|
+
def png(self):
|
|
332
|
+
'''Display a PNG of an already instantiated viewer in notebook output.
|
|
333
|
+
The image is generated in the browser; no image bytes are returned to Python.
|
|
334
|
+
'''
|
|
335
|
+
if not self.uniqueid:
|
|
336
|
+
raise AssertionError('Must instantiate viewer before generating image.')
|
|
337
|
+
script = '''<img id="img_{0}">
|
|
338
|
+
<script>
|
|
339
|
+
viewer_ready_{0}.then(function() {{
|
|
340
|
+
var png = viewer_{0}.pngURI()
|
|
341
|
+
document.getElementById('img_{0}').src = png;
|
|
342
|
+
}});
|
|
343
|
+
</script>'''.format(self.uniqueid)
|
|
344
|
+
return IPython.display.publish_display_data({'application/3dmoljs_load.v0':script, 'text/html': script},metadata={})
|
|
345
|
+
|
|
346
|
+
@using_ipython
|
|
347
|
+
def apng(self, nframes=1):
|
|
348
|
+
'''Display an APNG of an already instantiated viewer in notebook output.
|
|
349
|
+
Capture nframes rendered changes; no image bytes are returned to Python.
|
|
350
|
+
'''
|
|
351
|
+
if not self.uniqueid:
|
|
352
|
+
raise AssertionError('Must instantiate viewer before generating animated image.')
|
|
353
|
+
script = '''<img id="img_{0}">
|
|
354
|
+
<script>
|
|
355
|
+
viewer_ready_{0}.then(function() {{
|
|
356
|
+
viewer_{0}.apngURI({1}).then(png => {{
|
|
357
|
+
document.getElementById('img_{0}').src = png; }});
|
|
358
|
+
}});
|
|
359
|
+
</script>'''.format(self.uniqueid,nframes)
|
|
360
|
+
return IPython.display.publish_display_data({'application/3dmoljs_load.v0':script, 'text/html': script},metadata={})
|
|
361
|
+
|
|
362
|
+
class model(object):
|
|
363
|
+
'''Wrapper for referencing a model within a viewer'''
|
|
364
|
+
def __init__(self, viewer, accesscmd):
|
|
365
|
+
self.accesscmd = accesscmd
|
|
366
|
+
self.viewer = viewer
|
|
367
|
+
|
|
368
|
+
def __getattr__(self,name):
|
|
369
|
+
'''auto-instantiate javascript calls through model'''
|
|
370
|
+
if name.startswith('_'): #object to ipython canary functions
|
|
371
|
+
raise AttributeError("%r object has no attribute %r" % (self.__class__, name))
|
|
372
|
+
|
|
373
|
+
def makejs(*args,**kwargs):
|
|
374
|
+
cmd = '\t%s.%s(' % (self.accesscmd,name);
|
|
375
|
+
for arg in args:
|
|
376
|
+
cmd += '%s,' % tostr(arg)
|
|
377
|
+
cmd = cmd.rstrip(',')
|
|
378
|
+
cmd += ');\n';
|
|
379
|
+
|
|
380
|
+
self.viewer.startjs += cmd
|
|
381
|
+
self.viewer.updatejs += cmd
|
|
382
|
+
return self.viewer
|
|
383
|
+
return makejs #return from getattr
|
|
384
|
+
|
|
385
|
+
def getModel(self,*args,**kwargs):
|
|
386
|
+
"""Return a proxy for queuing GLModel methods, not its atom data.
|
|
387
|
+
Positional arguments are forwarded to GLViewer.getModel. With a viewer grid,
|
|
388
|
+
viewer=(row, column) is required. Proxy calls return the parent Python view.
|
|
389
|
+
"""
|
|
390
|
+
if self.viewergrid:
|
|
391
|
+
if kwargs and 'viewer' in kwargs:
|
|
392
|
+
coords = kwargs['viewer']
|
|
393
|
+
if len(coords) != 2 or coords[0] >= self.viewergrid[0] or coords[1] >= self.viewergrid[1] or coords[0] < 0 or coords[1] < 0:
|
|
394
|
+
raise ValueError("Incorrectly formated viewer argument. Must specify row and column",self.viewergrid)
|
|
395
|
+
cmd = '\tviewergrid_UNIQUEID[%d][%d].getModel(' % (coords[0],coords[1]);
|
|
396
|
+
for arg in args:
|
|
397
|
+
cmd += '%s,' % tostr(arg)
|
|
398
|
+
cmd = cmd.rstrip(',')
|
|
399
|
+
cmd += ')';
|
|
400
|
+
else:
|
|
401
|
+
raise ValueError('Must specify specific viewer with getModel and viewergrid enabled')
|
|
402
|
+
else:
|
|
403
|
+
cmd = '\tviewer_UNIQUEID.getModel(';
|
|
404
|
+
for arg in args:
|
|
405
|
+
cmd += '%s,' % tostr(arg)
|
|
406
|
+
cmd = cmd.rstrip(',')
|
|
407
|
+
cmd += ')';
|
|
408
|
+
return self.model(self,cmd)
|
|
409
|
+
|
|
410
|
+
def __getattr__(self,name):
|
|
411
|
+
'''auto-instantiate javascript calls based on whatever the user provided'''
|
|
412
|
+
if name.startswith('_') or name == 'getdoc': #object to ipython canary functions
|
|
413
|
+
raise AttributeError("%r object has no attribute %r" % (self.__class__, name))
|
|
414
|
+
|
|
415
|
+
print_result = False
|
|
416
|
+
if name.startswith('print_to_console_'):
|
|
417
|
+
print_result = True
|
|
418
|
+
name = name[17:]
|
|
419
|
+
|
|
420
|
+
def makejs(*args,**kwargs):
|
|
421
|
+
|
|
422
|
+
def make_viewer_cmd(vname, name, *args, **kwargs):
|
|
423
|
+
cmd = '\t'
|
|
424
|
+
if print_result:
|
|
425
|
+
cmd += 'console.log('
|
|
426
|
+
cmd += f'{vname}.{name}('
|
|
427
|
+
for arg in args:
|
|
428
|
+
cmd += '%s,' % tostr(arg)
|
|
429
|
+
cmd = cmd.rstrip(',')
|
|
430
|
+
if print_result:
|
|
431
|
+
cmd += ')'
|
|
432
|
+
cmd += ');\n'
|
|
433
|
+
|
|
434
|
+
return cmd
|
|
435
|
+
|
|
436
|
+
if self.viewergrid:
|
|
437
|
+
if kwargs and 'viewer' in kwargs:
|
|
438
|
+
coords = kwargs['viewer']
|
|
439
|
+
if len(coords) != 2 or coords[0] >= self.viewergrid[0] or coords[1] >= self.viewergrid[1] or coords[0] < 0 or coords[1] < 0:
|
|
440
|
+
raise ValueError("Incorrectly formated viewer argument. Must specify row and column",self.viewergrid)
|
|
441
|
+
cmd = make_viewer_cmd('viewergrid_UNIQUEID[%d][%d]'%(coords[0],coords[1]),name,*args,**kwargs)
|
|
442
|
+
else: #apply to every viewer
|
|
443
|
+
cmd = ''
|
|
444
|
+
for r in range(self.viewergrid[0]):
|
|
445
|
+
for c in range(self.viewergrid[1]):
|
|
446
|
+
cmd += make_viewer_cmd('viewergrid_UNIQUEID[%d][%d]'%(r,c),name,*args,**kwargs)
|
|
447
|
+
else:
|
|
448
|
+
cmd = make_viewer_cmd('viewer_UNIQUEID',name,*args,**kwargs)
|
|
449
|
+
|
|
450
|
+
self.startjs += cmd
|
|
451
|
+
self.updatejs += cmd
|
|
452
|
+
if print_result:
|
|
453
|
+
self.update()
|
|
454
|
+
return "Inspect the JavaScript console for your requested result."
|
|
455
|
+
else:
|
|
456
|
+
return self
|
|
457
|
+
|
|
458
|
+
return makejs
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: py3Dmol
|
|
3
|
+
Version: 3.0.0
|
|
4
|
+
Summary: An IPython interface for embedding 3Dmol.js views in Jupyter notebooks
|
|
5
|
+
Home-page: https://3dmol.org
|
|
6
|
+
Author: David Koes
|
|
7
|
+
Author-email: dkoes@pitt.edu
|
|
8
|
+
License: MIT
|
|
9
|
+
Keywords: molecule protein visualization
|
|
10
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Chemistry
|
|
14
|
+
Classifier: Topic :: Scientific/Engineering :: Visualization
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE.txt
|
|
20
|
+
Provides-Extra: ipython
|
|
21
|
+
Requires-Dist: IPython; extra == "ipython"
|
|
22
|
+
Dynamic: author
|
|
23
|
+
Dynamic: author-email
|
|
24
|
+
Dynamic: classifier
|
|
25
|
+
Dynamic: description
|
|
26
|
+
Dynamic: description-content-type
|
|
27
|
+
Dynamic: home-page
|
|
28
|
+
Dynamic: keywords
|
|
29
|
+
Dynamic: license
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
Dynamic: provides-extra
|
|
32
|
+
Dynamic: summary
|
|
33
|
+
|
|
34
|
+
py3Dmol
|
|
35
|
+
=======
|
|
36
|
+
|
|
37
|
+
A simple [IPython/Jupyter](http://jupyter.org/) widget to
|
|
38
|
+
embed an interactive [3Dmol.js](http://3dmol.org) viewer in a notebook.
|
|
39
|
+
|
|
40
|
+
The widget emits HTML and JavaScript. Once displayed, it remains interactive
|
|
41
|
+
without a running IPython kernel, but communication is one-way: Python queues
|
|
42
|
+
commands for the browser and cannot read JavaScript return values or receive
|
|
43
|
+
viewer events. Exported pages still need JavaScript and WebGL enabled, plus access
|
|
44
|
+
to the configured library URL and any remotely loaded molecular data.
|
|
45
|
+
|
|
46
|
+
If you experience problems, please file
|
|
47
|
+
an [issue](https://github.com/3dmol/3Dmol.js/issues).
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
[An example notebook](http://nbviewer.jupyter.org/github/3dmol/3Dmol.js/blob/master/py3Dmol/examples.ipynb)
|
|
51
|
+
|
|
52
|
+
Installation
|
|
53
|
+
------------
|
|
54
|
+
|
|
55
|
+
From PyPI:
|
|
56
|
+
|
|
57
|
+
pip install py3Dmol
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
Usage
|
|
61
|
+
-----
|
|
62
|
+
|
|
63
|
+
Open a notebook
|
|
64
|
+
|
|
65
|
+
jupyter notebook
|
|
66
|
+
|
|
67
|
+
and issue
|
|
68
|
+
|
|
69
|
+
```Python
|
|
70
|
+
import py3Dmol
|
|
71
|
+
view = py3Dmol.view(query='pdb:1ubq')
|
|
72
|
+
view.setStyle({'cartoon':{'color':'spectrum'}})
|
|
73
|
+
view
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
API
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
Use the [$3Dmol.GLViewer reference](https://3dmol.org/doc/GLViewer.html) for
|
|
80
|
+
method names and argument objects. The wrapper translates positional arguments
|
|
81
|
+
into JavaScript using JSON serialization; use Python dictionaries for selections
|
|
82
|
+
and styles, and Python `True`, `False`, and `None` for their JSON equivalents.
|
|
83
|
+
Python functions cannot be passed as JavaScript callbacks.
|
|
84
|
+
|
|
85
|
+
Most forwarded methods queue a command and return the Python `view` for chaining,
|
|
86
|
+
not the JavaScript result. For example, a forwarded `addModel` call does not return
|
|
87
|
+
a model object, and a forwarded `selectedAtoms` call does not return atoms to
|
|
88
|
+
Python. `getModel()` is a wrapper-specific exception: it returns a model proxy
|
|
89
|
+
whose methods queue calls to the JavaScript [GLModel](https://3dmol.org/doc/GLModel.html).
|
|
90
|
+
Promises and browser-side values do not cross back into Python.
|
|
91
|
+
|
|
92
|
+
Display and export helpers
|
|
93
|
+
--------------------------
|
|
94
|
+
|
|
95
|
+
| Operation | Python helper |
|
|
96
|
+
| --- | --- |
|
|
97
|
+
| Display a new viewer | Evaluate the view as the last notebook expression, or call `show()` |
|
|
98
|
+
| Apply queued commands to the displayed viewer | `update()` |
|
|
99
|
+
| Return embeddable HTML as a Python string | `write_html()` |
|
|
100
|
+
| Write an HTML page to a path or writable file object | `write_html(f)`; `fullpage=True` fills the page when writing a file |
|
|
101
|
+
| Display a still or animated image in notebook output | `png()` or `apng(nframes)` after the viewer has been displayed |
|
|
102
|
+
|
|
103
|
+
Repeated `show()` calls create new displays; subsequent `update()` calls target the
|
|
104
|
+
most recently displayed instance. Image helpers publish browser output rather
|
|
105
|
+
than returning image bytes to Python. Notebook output must allow the embedded
|
|
106
|
+
JavaScript to run; if the viewer fails to load, inspect the browser console.
|
|
107
|
+
|
|
108
|
+
Use `viewergrid=(rows, columns)` to create a grid. Forwarded commands apply to
|
|
109
|
+
every cell unless `viewer=(row, column)` selects one, with zero-based indices.
|
|
110
|
+
`getModel` requires an explicit `viewer` when a grid is enabled. Constructor
|
|
111
|
+
option `linked=True` links mouse controls across the grid.
|
|
112
|
+
|
|
113
|
+
The `js` constructor argument selects the 3Dmol.js bundle URL. Match that bundle
|
|
114
|
+
to the API documentation you use. The library is loaded once per page, so changing
|
|
115
|
+
`js` on a later view does not replace an already loaded library.
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
Editing, trajectory, and classroom controls
|
|
119
|
+
-------------------------------------------
|
|
120
|
+
|
|
121
|
+
These optional constructor arguments enable browser controls in notebooks and
|
|
122
|
+
exported HTML. All three features are disabled by default.
|
|
123
|
+
|
|
124
|
+
| Argument | Behavior |
|
|
125
|
+
| --- | --- |
|
|
126
|
+
| `edit=True` | Show the edit button for models, styles, surfaces, volumes, and measurements |
|
|
127
|
+
| `trajectory=True` | Enable trajectory controls for models loaded with frames, such as through `addModelsAsFrames` |
|
|
128
|
+
| `learning=True` | Show the classroom button and session-name dialog |
|
|
129
|
+
| `learning={...}` | Configure the classroom with the options below |
|
|
130
|
+
| `ui_js="..."` | Override the optional UI bundle URL |
|
|
131
|
+
|
|
132
|
+
All views default to the same pinned 3Dmol.js release on jsDelivr, with or without
|
|
133
|
+
controls. The UI bundle loads automatically when any controls are requested;
|
|
134
|
+
its URL is the sibling `3Dmol.ui.js` or `3Dmol.ui-min.js` of the core `js` URL.
|
|
135
|
+
To use another release or a hosted build, set `js` explicitly and use matching
|
|
136
|
+
core and UI builds. For a custom core filename, supply `ui_js` explicitly.
|
|
137
|
+
Use the same bundle URLs for every view on a page: the first core and UI bundles
|
|
138
|
+
loaded are reused by later views. Restart the notebook output page to switch
|
|
139
|
+
bundles. The examples below use the default released bundles.
|
|
140
|
+
|
|
141
|
+
Controls apply to one viewer. Grids with more than one cell share a container and
|
|
142
|
+
canvas, so they cannot use these options; create separate `view` objects for
|
|
143
|
+
independent controls or classrooms. A `viewergrid=(1, 1)` is supported.
|
|
144
|
+
|
|
145
|
+
<!-- example: viewer-controls -->
|
|
146
|
+
```python
|
|
147
|
+
import py3Dmol
|
|
148
|
+
|
|
149
|
+
frames = ("2\nFrame 0\nC 0 0 0\nO 1.2 0 0\n"
|
|
150
|
+
"2\nFrame 1\nC 0 0 0\nO 1.5 0 0\n")
|
|
151
|
+
view = py3Dmol.view(width=640, height=400, edit=True, trajectory=True,
|
|
152
|
+
learning=True)
|
|
153
|
+
view.addModelsAsFrames(frames, "xyz")
|
|
154
|
+
view.setStyle({}, {"stick": {}, "sphere": {"scale": 0.3}})
|
|
155
|
+
view.zoomTo()
|
|
156
|
+
html = view.write_html()
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Display `view` in a notebook, or save `html` to embed the same controls in a page.
|
|
160
|
+
Use the classroom button to create a session or join an existing one. Pass a
|
|
161
|
+
dictionary such as `learning={"mode": "button", "session": "my-class"}` to
|
|
162
|
+
prefill the session name. Browser edits and classroom events are not returned to
|
|
163
|
+
Python; `write_html()` exports the commands queued in Python, not subsequent
|
|
164
|
+
browser edits.
|
|
165
|
+
|
|
166
|
+
For hidden activation, set `mode` to `"hidden"` and provide a nonempty, unique
|
|
167
|
+
`session` identifier. Give every participant the same identifier and server.
|
|
168
|
+
The classroom button stays hidden while waiting. Focus the instructor's viewer
|
|
169
|
+
and press **Ctrl+Alt+I** to start; other active viewers with that configuration
|
|
170
|
+
automatically join as students, including viewers opened later.
|
|
171
|
+
|
|
172
|
+
<!-- example: hidden-classroom -->
|
|
173
|
+
```python
|
|
174
|
+
import py3Dmol
|
|
175
|
+
|
|
176
|
+
xyz = "2\nCarbon monoxide\nC 0 0 0\nO 1.2 0 0\n"
|
|
177
|
+
view = py3Dmol.view(width=640, height=400, data=xyz, format="xyz",
|
|
178
|
+
style={"sphere": {"scale": 0.3}, "stick": {}},
|
|
179
|
+
learning={"mode": "hidden", "session": "py3dmol-bonding-class-a"})
|
|
180
|
+
html = view.write_html()
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Replace the example session identifier with one unique to your class and viewer.
|
|
184
|
+
The instructor gets the usual editing, trajectory, and classroom controls.
|
|
185
|
+
Student editing and trajectory controls are disabled while following; students
|
|
186
|
+
can still rotate, zoom, and answer atom queries. A session ends when the
|
|
187
|
+
instructor leaves or closes their viewer.
|
|
188
|
+
|
|
189
|
+
The `learning` dictionary accepts the JSON options from
|
|
190
|
+
[`LearningConfig`](https://3dmol.org/doc/LearningConfig.html): `mode`, `session`,
|
|
191
|
+
`server`, `hotkey`, and `clientURL`. `server` defaults to `"https://3dmol.csb.pitt.edu"`;
|
|
192
|
+
set it to your session server's origin, including protocol and port when needed,
|
|
193
|
+
for example `"http://127.0.0.1:5072"`. `hotkey` changes the hidden activation
|
|
194
|
+
shortcut, and `clientURL` overrides the Socket.IO browser-client script. Python
|
|
195
|
+
callbacks, including `socketFactory` and adapter hooks, are not supported.
|
|
196
|
+
|
|
197
|
+
See the [learning-environment guide](https://github.com/3dmol/3Dmol.js/blob/master/tutorials/learning_environment.md)
|
|
198
|
+
for shared scene behavior, classroom controls, and server setup. Hidden mode
|
|
199
|
+
changes how controls appear; it does not authenticate instructors.
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
Export a grid with independent styles
|
|
203
|
+
------------------------------------
|
|
204
|
+
|
|
205
|
+
This example puts the same inline molecule in two cells, then styles each cell's
|
|
206
|
+
model separately. `addModel` and `zoomTo` target both cells; `getModel` selects one
|
|
207
|
+
cell. `write_html()` returns an HTML fragment that can be saved or embedded in a
|
|
208
|
+
page without an active notebook kernel. The fragment still loads the JavaScript
|
|
209
|
+
bundle from the configured URL.
|
|
210
|
+
|
|
211
|
+
<!-- example: exported-grid -->
|
|
212
|
+
```python
|
|
213
|
+
import py3Dmol
|
|
214
|
+
|
|
215
|
+
xyz = "2\nCarbon monoxide\nC 0 0 0\nO 1.2 0 0\n"
|
|
216
|
+
view = py3Dmol.view(width=640, height=320, viewergrid=(1, 2), linked=False)
|
|
217
|
+
view.addModel(xyz, "xyz")
|
|
218
|
+
view.getModel(viewer=(0, 0)).setStyle({}, {"sphere": {"radius": 0.45, "color": "red"}})
|
|
219
|
+
view.getModel(viewer=(0, 1)).setStyle({}, {"stick": {"radius": 0.15, "color": "blue"}})
|
|
220
|
+
view.zoomTo()
|
|
221
|
+
html = view.write_html()
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
Run `npm run test:examples:browser` from the repository root to exercise the grid
|
|
225
|
+
and both controls examples above with the local Python wrapper and JavaScript
|
|
226
|
+
bundles. The checks use Python's standard library and Chromium via the existing
|
|
227
|
+
Puppeteer dependency; they do not require Jupyter or network downloads. Run
|
|
228
|
+
`npm run test:python` for constructor validation and HTML serialization checks.
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
License
|
|
232
|
+
-------
|
|
233
|
+
|
|
234
|
+
MIT
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
py3Dmol/__init__.py,sha256=U-8spY_jKJc1Db_nytxFKivcdz3-S0qMlvYt1CQLFCU,20818
|
|
2
|
+
py3dmol-3.0.0.dist-info/licenses/LICENSE.txt,sha256=_YCib7s_ZErx-plBNERnApMpaFGXlyJ-B6E2jeqA8Lw,1023
|
|
3
|
+
py3dmol-3.0.0.dist-info/METADATA,sha256=94TvX1SA8TG33GYA4jL5KOF2MiabPNDtPRrte8Z9SPY,9834
|
|
4
|
+
py3dmol-3.0.0.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
|
|
5
|
+
py3dmol-3.0.0.dist-info/top_level.txt,sha256=4i8ZNo6c2gcIx9RDW9HfNxf7WfKRQ7lBqTndSVvTCLM,8
|
|
6
|
+
py3dmol-3.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
2
|
+
|
|
3
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
4
|
+
|
|
5
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
py3Dmol
|