webmo 1.6.0__tar.gz → 1.7.0__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.
@@ -1,9 +1,9 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: webmo
3
- Version: 1.6.0
3
+ Version: 1.7.0
4
4
  Summary: A Python-based interface to WebMO
5
5
  Home-page: https://github.com/jrschmidt2/webmo-python
6
- Download-URL: https://github.com/jrschmidt2/webmo-python/archive/refs/tags/1.6.0.tar.gz
6
+ Download-URL: https://github.com/jrschmidt2/webmo-python/archive/refs/tags/1.7.0.tar.gz
7
7
  Author: J.R. Schmidt
8
8
  Author-email: schmidt@webmo.net
9
9
  License: MIT
@@ -18,6 +18,8 @@ Requires-Dist: PubChemPy; extra == "util"
18
18
  Provides-Extra: gui
19
19
  Requires-Dist: questionary; extra == "gui"
20
20
  Requires-Dist: ipywidgets; extra == "gui"
21
+ Provides-Extra: render
22
+ Requires-Dist: playwright; extra == "render"
21
23
  Provides-Extra: all
22
24
  Requires-Dist: numpy; extra == "all"
23
25
  Requires-Dist: PubChemPy; extra == "all"
webmo-1.7.0/README.md ADDED
@@ -0,0 +1,30 @@
1
+ # webmo-python
2
+ A Python-based interface to WebMO
3
+
4
+ ## Rendering images outside Jupyter
5
+
6
+ `display_job_property()` shows WebMO's molecule, orbital, surface and spectrum views inside a Jupyter
7
+ notebook. `render_job_property()` produces the same images from any Python script, using WebMO's
8
+ viewers in a headless browser. It needs WebMO 24 or later and an optional dependency:
9
+
10
+ ```bash
11
+ pip install 'webmo[render]'
12
+ python -m playwright install chromium
13
+ ```
14
+
15
+ On Linux, Chromium also needs some system libraries. On Debian/Ubuntu, run
16
+ `python -m playwright install-deps chromium`. On RHEL/Rocky/Fedora, install them with dnf,
17
+ e.g. `dnf install mesa-libgbm libdrm nss atk`.
18
+
19
+ ```python
20
+ from webmo import WebMOREST
21
+
22
+ rest = WebMOREST("https://server/cgi-bin/webmo/rest.cgi", "alice")
23
+ rest.render_job_property(123, "mo", "homo.png", property_index=12, width=600, height=600)
24
+ rest.render_job_property(123, "ir_spectrum", "ir.png")
25
+ png_bytes = rest.render_job_property(123, "esp")
26
+ ```
27
+
28
+ The browser starts on the first call and is reused for later ones, so rendering many images is
29
+ fast; `rest.close_renderer()` shuts it down. `render_job_property()` is synchronous and cannot be
30
+ used inside a Jupyter notebook; use `await rest.display_job_property(...)` there.
@@ -36,6 +36,7 @@ setup(
36
36
  "spectrum": ["numpy"],
37
37
  "util": ["PubChemPy"],
38
38
  "gui": ["questionary", "ipywidgets"],
39
+ "render": ["playwright"], #headless image rendering; also run: python -m playwright install chromium
39
40
  "all": ["numpy", "PubChemPy", "questionary", "ipywidgets"]
40
41
  }
41
42
  )
@@ -0,0 +1,181 @@
1
+ """Tests for the Javascript built for display_job_property / render_job_property.
2
+
3
+ No WebMO server or browser is needed: REST responses are mocked.
4
+
5
+ python -m unittest discover -s tests -v
6
+ """
7
+
8
+ import asyncio
9
+ import os
10
+ import sys
11
+ import unittest
12
+ from unittest import mock
13
+
14
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
15
+
16
+ from webmo import WebMOREST # noqa: E402
17
+ from webmo import render # noqa: E402
18
+
19
+ GEOMETRY = {"jobNumber": 42, "xyz": "O 0 0 0\nH 0 0.76 -0.47\nH 0 -0.76 -0.47", "connections": "", "charges": "",
20
+ "zmatrix": ""}
21
+
22
+ RESULTS = {
23
+ "symbols": ["O", "H", "H"],
24
+ "geometry": [0, 0, 0, 0, 0.76, -0.47, 0, -0.76, -0.47],
25
+ "properties": {
26
+ "dipole_moment": [1.0, 2.0, 2.0],
27
+ "partial_charges": {"mulliken": [-0.8, 0.4, 0.4]},
28
+ "vibrations": {
29
+ "frequencies": [1650.0, 3800.0, 3900.0],
30
+ "intensities": {"IR": [70.0, 5.0, 45.0], "raman": [1.0, 2.0, 3.0], "VCD": [0.1, 0.2, 0.3]},
31
+ "displacement": [[0.1] * 9, [0.2] * 9, [0.3] * 9],
32
+ },
33
+ "excited_states": {"transition_energies": [7.1, 8.2], "intensities": [0.05, 0.2], "units": "eV"},
34
+ "nmr_shifts": {"isotropic": [320.0, 31.0, 31.5], "anisotropy": [40.0, 10.0, 11.0]},
35
+ },
36
+ }
37
+
38
+
39
+ class FakeResponse:
40
+ def __init__(self, data):
41
+ self._data = data
42
+
43
+ def raise_for_status(self):
44
+ pass
45
+
46
+ def json(self):
47
+ return self._data
48
+
49
+
50
+ def fake_get(url, params=None, **kwargs):
51
+ if url.endswith("/geometry"):
52
+ return FakeResponse(GEOMETRY)
53
+ if url.endswith("/results"):
54
+ return FakeResponse(RESULTS)
55
+ raise AssertionError("unexpected request: %s" % url)
56
+
57
+
58
+ class OfflineREST(WebMOREST):
59
+ def __del__(self):
60
+ pass # there is no real session to log out of
61
+
62
+
63
+ def make_rest():
64
+ rest = OfflineREST.__new__(OfflineREST) # skip the login in __init__
65
+ rest._base_url = "https://server/rest.cgi"
66
+ rest._auth = {"username": "alice", "token": "T"}
67
+ return rest
68
+
69
+
70
+ class PropertyJavascriptTest(unittest.TestCase):
71
+ def setUp(self):
72
+ patcher = mock.patch("webmo.webmo_rest.requests.get", side_effect=fake_get)
73
+ patcher.start()
74
+ self.addCleanup(patcher.stop)
75
+ self.rest = make_rest()
76
+
77
+ def js(self, prop, **kwargs):
78
+ return self.rest._property_javascript(42, prop, **kwargs)
79
+
80
+ def test_geometry(self):
81
+ js = self.js("geometry", width=600, height=500, rotate=(10, 20, 30))
82
+ self.assertTrue(js.startswith("_call_when_ready(function(){") and js.endswith("})"))
83
+ for call in ("_set_moledit_size(600,500);", "_set_moledit_background(255,255,255);",
84
+ "_set_moledit_geometry(", "_rotate_moledit_view(10.000000,20.000000,30.000000);",
85
+ "_display_moledit_screenshot(0,false);"):
86
+ self.assertIn(call, js)
87
+
88
+ def test_callback_port_and_transparency(self):
89
+ js = self.js("geometry", transparent_background=True, callback_port=51234)
90
+ self.assertIn("_display_moledit_screenshot(51234,true);", js)
91
+
92
+ def test_dipole_moment(self):
93
+ self.assertIn("_set_moledit_dipole_moment('1.000000:2.000000:2.000000:3.000000');", self.js("dipole_moment"))
94
+
95
+ def test_partial_charges(self):
96
+ self.assertIn("_set_moledit_partial_charge('1,X,-0.800000:2,X,0.400000:3,X,0.400000');",
97
+ self.js("partial_charges"))
98
+
99
+ def test_vibrational_mode(self):
100
+ js = self.js("vibrational_mode", property_index=2)
101
+ self.assertIn("_set_moledit_vibrational_mode('1,0.200000,0.200000,0.200000:", js)
102
+ self.assertIn("', 2, 3800.000000, 1.000000);", js)
103
+
104
+ def test_orbital_screenshot_comes_from_callback(self):
105
+ js = self.js("mo", property_index=5, callback_port=7)
106
+ self.assertIn("_set_moledit_wavefunction(42,'mo', 5, 7, false);", js)
107
+ self.assertNotIn("_display_moledit_screenshot", js)
108
+
109
+ def test_surfaces_use_index_zero(self):
110
+ self.assertIn("_set_moledit_wavefunction(42,'esp', 0, 0, false);", self.js("esp", property_index=3))
111
+
112
+ def test_ir_spectrum(self):
113
+ js = self.js("ir_spectrum", x_range=(4000, 400))
114
+ self.assertIn("_set_datagrapher_ir_spectrum('1,-,1650.000000,70.000000:", js)
115
+ self.assertIn(", 40.000000);", js) # default peak width
116
+ self.assertIn("_set_x_range(4000.000000, 400.000000);", js)
117
+ self.assertIn("_display_datagrapher_screenshot(0);", js)
118
+
119
+ def test_raman_and_vcd_use_their_intensities(self):
120
+ self.assertIn("1,-,1650.000000,1.000000", self.js("raman_spectrum"))
121
+ self.assertIn("1,-,1650.000000,0.100000", self.js("vcd_spectrum"))
122
+
123
+ def test_uvvis(self):
124
+ js = self.js("uvvis_spectrum")
125
+ self.assertIn("_set_datagrapher_uvvis_spectrum('1,-,7.100000,0.050000:2,-,8.200000,0.200000', 'eV', 20.000000);", js)
126
+
127
+ def test_nmr(self):
128
+ self.assertIn("_set_datagrapher_nmr_spectrum('1,O,320.000000", self.js("cnmr_spectrum"))
129
+ js = self.js("hnmr_spectrum", tms_shift=32.0)
130
+ self.assertIn("2,H,1.000000,10.000000", js) # TMS shift applied to hydrogens only
131
+ self.assertIn("'H', 0.001000, 1);", js) # relative spectrum
132
+ js = self.js("hnmr_spectrum", proton_coupling=7.0)
133
+ self.assertIn("_set_datagrapher_h1nmr_spectrum(", js)
134
+
135
+ def test_missing_data_is_a_clear_error(self):
136
+ saved = RESULTS["properties"].pop("vibrations")
137
+ try:
138
+ with self.assertRaisesRegex(ValueError, r"Job 42 has no vibrational \(IR\) data for 'ir_spectrum'"):
139
+ self.js("ir_spectrum")
140
+ finally:
141
+ RESULTS["properties"]["vibrations"] = saved
142
+
143
+ def test_index_out_of_range(self):
144
+ with self.assertRaisesRegex(ValueError, "property_index 9 is out of range"):
145
+ self.js("vibrational_mode", property_index=9)
146
+
147
+ def test_invalid_arguments(self):
148
+ with self.assertRaisesRegex(ValueError, "Invalid property_name"):
149
+ self.js("nonsense")
150
+ with self.assertRaisesRegex(ValueError, "Invalid property_index"):
151
+ self.js("geometry", property_index=0)
152
+
153
+
154
+ class SetupAndGuardsTest(unittest.TestCase):
155
+ def test_viewer_setup_html(self):
156
+ html = make_rest()._viewer_setup_html({"url_html": "https://h/webmo", "url_cgi": "https://h/cgi-bin/webmo"})
157
+ self.assertIn("<script src='https://h/webmo/javascript/moledit_js/moledit_js.nocache.js'></script>", html)
158
+ self.assertIn("orbitalSrc='https://h/cgi-bin/webmo/get_orbital.cgi'", html)
159
+ self.assertIn("function _call_when_ready(func)", html)
160
+
161
+ def test_render_refuses_inside_event_loop(self):
162
+ async def call():
163
+ make_rest().render_job_property(42, "geometry")
164
+ with self.assertRaisesRegex(RuntimeError, "display_job_property"):
165
+ asyncio.run(call())
166
+
167
+ def test_launch_error_messages(self):
168
+ self.assertIn("playwright install chromium",
169
+ render._launch_error_message("Executable doesn't exist at /x/chrome"))
170
+ message = render._launch_error_message(
171
+ "chrome: error while loading shared libraries: libgbm.so.1: cannot open shared object file")
172
+ self.assertIn("libgbm.so.1 is missing", message)
173
+
174
+ def test_orbital_messages(self):
175
+ url = "https://h/get_orbital.cgi?jobNumber=7&type=mo&index=3&a=1"
176
+ self.assertIn("No mo data is available for job 7", render._orbital_message(url, 404))
177
+ self.assertIn("refused", render._orbital_message(url, 403))
178
+
179
+
180
+ if __name__ == "__main__":
181
+ unittest.main()
@@ -1,2 +1,2 @@
1
1
  from .webmo_rest import WebMOREST
2
- __version__ = "1.6.0"
2
+ __version__ = "1.7.0"
@@ -0,0 +1,147 @@
1
+ """Headless rendering of WebMO job properties (molecules, orbitals, surfaces, spectra) to PNG.
2
+
3
+ This drives WebMO's own MolEdit and DataGrapher viewers in a headless Chromium browser, the same
4
+ viewers that display_job_property uses inside Jupyter. It is used by WebMOREST.render_job_property
5
+ and requires the optional Playwright dependency:
6
+
7
+ pip install 'webmo[render]'
8
+ python -m playwright install chromium
9
+ """
10
+
11
+ import base64
12
+ import re
13
+ import time
14
+
15
+ INSTALL_HINT = "pip install 'webmo[render]' && python -m playwright install chromium"
16
+
17
+ #MolEdit draws with WebGL; headless Chromium needs software WebGL (SwiftShader) for that
18
+ _BROWSER_ARGS = ["--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--ignore-gpu-blocklist"]
19
+
20
+ #the viewer page is served by request interception, so this host is never contacted
21
+ _PAGE_URL = "http://webmo-render.invalid/"
22
+
23
+
24
+ class RenderError(RuntimeError):
25
+ """Rendering an image failed, e.g. the job's orbital data is missing or the image timed out."""
26
+
27
+
28
+ class RenderSetupError(RenderError):
29
+ """The headless browser or WebMO's viewers could not be started, so no image can be rendered."""
30
+
31
+
32
+ class HeadlessRenderer:
33
+ """A headless browser page with WebMO's viewers loaded, reused across renders.
34
+
35
+ Arguments:
36
+ setup_html(str): HTML that loads the viewers, from WebMOREST._viewer_setup_html
37
+ timeout(float, optional): Seconds to wait for the viewers to load
38
+ """
39
+
40
+ def __init__(self, setup_html, timeout=60):
41
+ try:
42
+ from playwright.sync_api import sync_playwright, Error as PlaywrightError
43
+ except ImportError:
44
+ raise ImportError("Rendering images requires Playwright: %s" % INSTALL_HINT) from None
45
+ self._playwright = None
46
+ self._browser = None
47
+ self._playwright = sync_playwright().start()
48
+ try:
49
+ self._browser = self._playwright.chromium.launch(args=_BROWSER_ARGS)
50
+ except PlaywrightError as e:
51
+ self.close()
52
+ raise RenderSetupError(_launch_error_message(str(e))) from None
53
+
54
+ self._console = []
55
+ self._orbital_error = None
56
+ page = self._page = self._browser.new_page()
57
+ page.on("console", lambda message: self._console.append(message.text))
58
+ page.on("pageerror", lambda error: self._console.append(str(error)))
59
+ page.on("response", self._check_orbital_response)
60
+ page.on("requestfailed", self._check_orbital_failure)
61
+ page.route(_PAGE_URL, lambda route: route.fulfill(
62
+ content_type="text/html",
63
+ body="<!DOCTYPE html><html><head><meta charset='utf-8'></head><body>%s</body></html>" % setup_html))
64
+ try:
65
+ page.goto(_PAGE_URL)
66
+ page.wait_for_function("document.getElementById('moledit-panel').children.length > 0 && "
67
+ "document.getElementById('datagrapher-panel').children.length > 0",
68
+ timeout=timeout * 1000)
69
+ except PlaywrightError:
70
+ self.close()
71
+ raise RenderSetupError("WebMO's viewers did not load within %g s. Browser messages: %s"
72
+ % (timeout, self._recent_console())) from None
73
+ #receive screenshots here instead of over the Jupyter websocket
74
+ page.evaluate("window._display_uri = function(uri) { _clear_lock(); window.__webmo_image = uri; }")
75
+
76
+ def render(self, javascript, timeout=60):
77
+ """Runs javascript (from WebMOREST._property_javascript) and returns the resulting PNG bytes."""
78
+ from playwright.sync_api import Error as PlaywrightError
79
+
80
+ page = self._page
81
+ self._console.clear()
82
+ self._orbital_error = None
83
+ #a failed render leaves WebMO's render lock set, which would delay this one by up to 5 s
84
+ page.evaluate("window.__webmo_image = null; _clear_lock()")
85
+ page.evaluate(javascript)
86
+ deadline = time.time() + timeout
87
+ #poll in short steps so a failed orbital download is reported right away
88
+ while True:
89
+ try:
90
+ page.wait_for_function("window.__webmo_image", timeout=250)
91
+ break
92
+ except PlaywrightError:
93
+ if self._orbital_error:
94
+ raise RenderError(self._orbital_error) from None
95
+ if time.time() > deadline:
96
+ raise RenderError("No image after %g s. Browser messages: %s"
97
+ % (timeout, self._recent_console())) from None
98
+ uri = page.evaluate("window.__webmo_image")
99
+ return base64.b64decode(uri.split(",", 1)[1])
100
+
101
+ def close(self):
102
+ """Closes the browser. Safe to call more than once."""
103
+ try:
104
+ if self._browser is not None:
105
+ self._browser.close()
106
+ except Exception:
107
+ pass
108
+ try:
109
+ if self._playwright is not None:
110
+ self._playwright.stop()
111
+ except Exception:
112
+ pass
113
+ self._browser = self._playwright = None
114
+
115
+ def _check_orbital_response(self, response):
116
+ if "get_orbital.cgi" in response.url and response.status >= 400:
117
+ self._orbital_error = _orbital_message(response.url, response.status)
118
+
119
+ def _check_orbital_failure(self, request):
120
+ #servers before WebMO 26 omit the CORS header on errors, so a missing file looks like a failed request
121
+ if "get_orbital.cgi" in request.url:
122
+ self._orbital_error = _orbital_message(request.url, None)
123
+
124
+ def _recent_console(self):
125
+ return "; ".join(self._console[-5:]) or "none"
126
+
127
+
128
+ def _orbital_message(url, status):
129
+ job = re.search(r"jobNumber=(\d+)", url)
130
+ kind = re.search(r"type=(\w+)", url)
131
+ what = "%s data" % (kind.group(1) if kind else "orbital")
132
+ job = "job %s" % job.group(1) if job else "this job"
133
+ if status == 403:
134
+ return "The WebMO server refused the %s request for %s (HTTP 403)." % (what, job)
135
+ return ("No %s is available for %s; the calculation probably did not save orbitals or surfaces%s."
136
+ % (what, job, "" if status else " (or the server could not be reached)"))
137
+
138
+
139
+ def _launch_error_message(error):
140
+ if "Executable doesn't exist" in error:
141
+ return "Chromium for Playwright is not installed. Run: python -m playwright install chromium"
142
+ library = re.search(r"error while loading shared libraries: (\S+?):", error)
143
+ if library:
144
+ return ("Chromium cannot start because the system library %s is missing. Install the browser's "
145
+ "system dependencies: on Debian/Ubuntu, 'python -m playwright install-deps chromium'; "
146
+ "on RHEL/Rocky/Fedora, e.g. 'dnf install mesa-libgbm libdrm nss atk'." % library.group(1))
147
+ return "Could not start headless Chromium: %s" % error.strip().splitlines()[0]
@@ -8,6 +8,19 @@ try:
8
8
  except ImportError:
9
9
  has_ipython = False
10
10
 
11
+ #the job results each property needs, for error messages
12
+ _PROPERTY_DATA = {
13
+ "dipole_moment": "dipole moment",
14
+ "partial_charges": "partial charge",
15
+ "vibrational_mode": "vibrational",
16
+ "ir_spectrum": "vibrational (IR)",
17
+ "raman_spectrum": "Raman",
18
+ "vcd_spectrum": "VCD",
19
+ "uvvis_spectrum": "excited-state (UV-Vis)",
20
+ "hnmr_spectrum": "NMR",
21
+ "cnmr_spectrum": "NMR",
22
+ }
23
+
11
24
  class WebMOREST:
12
25
  """The WebMOREST class provides an object-oriented Python API for the WebMO REST interface.
13
26
 
@@ -76,7 +89,10 @@ class WebMOREST:
76
89
 
77
90
  if getattr(self, '_callback_listener', None) is not None:
78
91
  self._callback_listener.close()
79
-
92
+
93
+ if getattr(self, '_renderer', None) is not None:
94
+ self._renderer.close()
95
+
80
96
  #
81
97
  # Users resource
82
98
  #
@@ -487,8 +503,6 @@ class WebMOREST:
487
503
  Returns:
488
504
  An EmbeddedImage object, which can be displayed and further manipulated.
489
505
  """
490
- from math import sqrt
491
-
492
506
  self._check_ipython()
493
507
 
494
508
  if self._init_javascript:
@@ -498,6 +512,87 @@ class WebMOREST:
498
512
  if self._callback_listener is None:
499
513
  await self._create_callback_listener()
500
514
 
515
+ javascript_string = self._property_javascript(job_number, property_name, property_index, peak_width, tms_shift,
516
+ proton_coupling, nmr_field, x_range, y_range, width, height, background_color, transparent_background,
517
+ rotate, self._callback_port)
518
+
519
+ #display the Javascript for execution
520
+ display(Javascript(javascript_string))
521
+ clear_output()
522
+ #wait for the Javascript callback and process / display the result
523
+ return await self._process_callback_response()
524
+
525
+ def render_job_property(self, job_number, property_name, filename=None, property_index=1, peak_width=0.0, tms_shift=0.0, proton_coupling=0.0, nmr_field=400.0, x_range=None, y_range=None, width=400, height=400, background_color=(255,255,255), transparent_background=False, rotate=(0.,0.,0.), timeout=60):
526
+ """Renders an image of the specified molecule and property in a headless browser, outside Jupyter.
527
+
528
+ This produces the same PNG-formatted image as display_job_property, but from any Python script,
529
+ using WebMO's viewers in headless Chromium. The browser is started on first use and reused for
530
+ later calls; call close_renderer() to shut it down early. Requires WebMO 24 or higher and the
531
+ optional Playwright dependency: pip install 'webmo[render]' && python -m playwright install chromium
532
+
533
+ This is a regular (synchronous) method and cannot be called inside a running asyncio event loop,
534
+ such as a Jupyter notebook; use 'await display_job_property(...)' there instead.
535
+
536
+ Arguments:
537
+ job_number(int): The job about whom to return information
538
+ property_name(str): The name of the property to display; see display_job_property for the choices
539
+ filename(str, optional): If given, the image is also saved to this path. A "png" extension is added, if not provided.
540
+ timeout(float, optional): Seconds to wait for the image (default 60)
541
+
542
+ All other arguments are as for display_job_property.
543
+
544
+ Returns:
545
+ The PNG-formatted image, as bytes.
546
+ """
547
+ from .render import HeadlessRenderer
548
+
549
+ #checked only before the browser starts: Playwright's sync API then runs its own event loop
550
+ if getattr(self, '_renderer', None) is None:
551
+ try:
552
+ asyncio.get_running_loop()
553
+ except RuntimeError:
554
+ pass
555
+ else:
556
+ raise RuntimeError("render_job_property cannot run inside an asyncio event loop (e.g. Jupyter); "
557
+ "use 'await display_job_property(...)' there instead")
558
+
559
+ javascript_string = self._property_javascript(job_number, property_name, property_index, peak_width, tms_shift,
560
+ proton_coupling, nmr_field, x_range, y_range, width, height, background_color, transparent_background,
561
+ rotate)
562
+
563
+ if getattr(self, '_renderer', None) is None:
564
+ config = self.get_status_info()
565
+ if int(config["version"].split(".")[0]) < 24:
566
+ raise RuntimeError("Rendering images requires WebMO 24 or higher")
567
+ self._renderer = HeadlessRenderer(self._viewer_setup_html(config), timeout)
568
+ data = self._renderer.render(javascript_string, timeout)
569
+
570
+ if filename:
571
+ if not filename.endswith(".png"):
572
+ filename += ".png"
573
+ with open(filename, 'wb') as fp:
574
+ fp.write(data)
575
+ return data
576
+
577
+ def close_renderer(self):
578
+ """Shuts down the headless browser started by render_job_property, if any."""
579
+ if getattr(self, '_renderer', None) is not None:
580
+ self._renderer.close()
581
+ self._renderer = None
582
+
583
+ def _property_javascript(self, job_number, property_name, property_index=1, peak_width=0.0, tms_shift=0.0,
584
+ proton_coupling=0.0, nmr_field=400.0, x_range=None, y_range=None, width=400, height=400,
585
+ background_color=(255,255,255), transparent_background=False, rotate=(0.,0.,0.), callback_port=0):
586
+ """Builds the Javascript that draws the specified property and requests a screenshot of it.
587
+
588
+ Shared by display_job_property (Jupyter) and render_job_property (headless browser); see
589
+ display_job_property for the arguments. callback_port is where the screenshot is sent in Jupyter.
590
+
591
+ Returns:
592
+ The Javascript to evaluate in a page prepared with _viewer_setup_html
593
+ """
594
+ from math import sqrt
595
+
501
596
  r = requests.get(self._base_url + "/jobs/%d/geometry" % job_number, params=self._auth)
502
597
  WebMOREST._check_status(r)
503
598
  geometryJSON = json.dumps(r.json())
@@ -515,107 +610,108 @@ class WebMOREST:
515
610
  property_string = ""
516
611
  WAVEFUNCTION_PROPERTIES = ["mo", "nao", "nho", "nbo", "esp", "nucleophilic", "electrophilic", "radical"]
517
612
  SURFACE_PROPERTIES = ["esp", "nucleophilic", "electrophilic", "radical"]
518
- if property_name == "geometry":
519
- #do nothing special
520
- pass
521
-
522
- elif property_name == "dipole_moment":
523
- dipole_moment = results['properties']['dipole_moment']
524
- total_dipole = sqrt(dipole_moment[0]**2 + dipole_moment[1]**2 + dipole_moment[2]**2)
525
- property_string = "%f:%f:%f:%f" % (*dipole_moment,total_dipole)
526
- javascript_string += self._set_moledit_dipole_moment(property_string)
613
+ try:
614
+ if property_name == "geometry":
615
+ #do nothing special
616
+ pass
617
+
618
+ elif property_name == "dipole_moment":
619
+ dipole_moment = results['properties']['dipole_moment']
620
+ total_dipole = sqrt(dipole_moment[0]**2 + dipole_moment[1]**2 + dipole_moment[2]**2)
621
+ property_string = "%f:%f:%f:%f" % (*dipole_moment,total_dipole)
622
+ javascript_string += self._set_moledit_dipole_moment(property_string)
527
623
 
528
- elif property_name == "partial_charges":
529
- partial_charges = results['properties']['partial_charges']['mulliken']
530
- for i in range(len(partial_charges)):
531
- property_string += "%d,X,%f:" % (i+1,partial_charges[i])
532
- property_string = property_string.rstrip(":")
533
- javascript_string += self._set_moledit_partial_charge(property_string)
624
+ elif property_name == "partial_charges":
625
+ partial_charges = results['properties']['partial_charges']['mulliken']
626
+ for i in range(len(partial_charges)):
627
+ property_string += "%d,X,%f:" % (i+1,partial_charges[i])
628
+ property_string = property_string.rstrip(":")
629
+ javascript_string += self._set_moledit_partial_charge(property_string)
534
630
 
535
- elif property_name == "vibrational_mode":
536
- frequency = results['properties']['vibrations']['frequencies'][property_index-1]
537
- displacements = results['properties']['vibrations']['displacement'][property_index-1]
538
- for i in range(len(displacements)//3):
539
- property_string += "%d,%f,%f,%f:" % (i+1,displacements[i*3+0],displacements[i*3+1],displacements[i*3+2])
540
- property_string = property_string.rstrip(":")
541
- javascript_string += self._set_moledit_vibrational_mode(property_string, property_index, frequency, 1.0)
631
+ elif property_name == "vibrational_mode":
632
+ frequency = results['properties']['vibrations']['frequencies'][property_index-1]
633
+ displacements = results['properties']['vibrations']['displacement'][property_index-1]
634
+ for i in range(len(displacements)//3):
635
+ property_string += "%d,%f,%f,%f:" % (i+1,displacements[i*3+0],displacements[i*3+1],displacements[i*3+2])
636
+ property_string = property_string.rstrip(":")
637
+ javascript_string += self._set_moledit_vibrational_mode(property_string, property_index, frequency, 1.0)
542
638
 
543
- elif property_name in WAVEFUNCTION_PROPERTIES:
544
- if property_name in SURFACE_PROPERTIES:
545
- property_index = 0 #this is required
546
- javascript_string += self._rotate_moledit_view(rotate[0],rotate[1],rotate[2])
547
- javascript_string += self._set_moledit_wavefunction(job_number, property_name, property_index, transparent_background) #handles screenshot in callback
639
+ elif property_name in WAVEFUNCTION_PROPERTIES:
640
+ if property_name in SURFACE_PROPERTIES:
641
+ property_index = 0 #this is required
642
+ javascript_string += self._rotate_moledit_view(rotate[0],rotate[1],rotate[2])
643
+ javascript_string += self._set_moledit_wavefunction(job_number, property_name, property_index, transparent_background, callback_port) #handles screenshot in callback
548
644
 
549
- elif property_name in ["ir_spectrum", "raman_spectrum", "vcd_spectrum"]:
550
- frequencies = results['properties']['vibrations']['frequencies']
551
- if property_name == "ir_spectrum":
552
- intensities = results['properties']['vibrations']['intensities']['IR']
553
- elif property_name == "raman_spectrum":
554
- intensities = results['properties']['vibrations']['intensities']['raman']
555
- else:
556
- intensities = results['properties']['vibrations']['intensities']['VCD']
557
-
558
- for i in range(len(frequencies)):
559
- property_string += "%d,-,%f,%f:" % (i+1,frequencies[i],intensities[i])
560
- property_string = property_string.rstrip(":")
561
-
562
- if property_name == "ir_spectrum":
563
- javascript_string += self._set_datagrapher_ir_spectrum(property_string, peak_width if peak_width > 0 else 40.0)
564
- elif property_name == "raman_spectrum":
565
- javascript_string += self._set_datagrapher_raman_spectrum(property_string, peak_width if peak_width > 0 else 40.0)
566
- else:
567
- javascript_string += self._set_datagrapher_vcd_spectrum(property_string, peak_width if peak_width > 0 else 40.0)
568
-
569
- elif property_name == "uvvis_spectrum":
570
- transition_energies = results['properties']['excited_states']['transition_energies']
571
- intensities = results['properties']['excited_states']['intensities']
572
- units = results['properties']['excited_states']['units']
573
-
574
- for i in range(len(transition_energies)):
575
- property_string += "%d,-,%f,%f:" % (i+1,transition_energies[i],intensities[i])
576
- property_string = property_string.rstrip(":")
577
-
578
- javascript_string += self._set_datagrapher_uvvis_spectrum(property_string, units, peak_width if peak_width > 0 else 20.0)
579
-
580
- elif property_name == "hnmr_spectrum" or property_name == "cnmr_spectrum":
581
- symbols = results['symbols']
582
- isotropic = results['properties']['nmr_shifts']['isotropic']
583
- anisotropy = results['properties']['nmr_shifts']['anisotropy']
584
-
585
- for i in range(len(isotropic)):
586
- if tms_shift > 0 and symbols[i] == "H":
587
- isotropic[i] = tms_shift - isotropic[i] #apply the TMS shift, if provided
588
- property_string += "%d,%s,%f,%f:" % (i+1,symbols[i],isotropic[i],anisotropy[i])
589
- property_string = property_string.rstrip(":")
645
+ elif property_name in ["ir_spectrum", "raman_spectrum", "vcd_spectrum"]:
646
+ frequencies = results['properties']['vibrations']['frequencies']
647
+ if property_name == "ir_spectrum":
648
+ intensities = results['properties']['vibrations']['intensities']['IR']
649
+ elif property_name == "raman_spectrum":
650
+ intensities = results['properties']['vibrations']['intensities']['raman']
651
+ else:
652
+ intensities = results['properties']['vibrations']['intensities']['VCD']
653
+
654
+ for i in range(len(frequencies)):
655
+ property_string += "%d,-,%f,%f:" % (i+1,frequencies[i],intensities[i])
656
+ property_string = property_string.rstrip(":")
657
+
658
+ if property_name == "ir_spectrum":
659
+ javascript_string += self._set_datagrapher_ir_spectrum(property_string, peak_width if peak_width > 0 else 40.0)
660
+ elif property_name == "raman_spectrum":
661
+ javascript_string += self._set_datagrapher_raman_spectrum(property_string, peak_width if peak_width > 0 else 40.0)
662
+ else:
663
+ javascript_string += self._set_datagrapher_vcd_spectrum(property_string, peak_width if peak_width > 0 else 40.0)
664
+
665
+ elif property_name == "uvvis_spectrum":
666
+ transition_energies = results['properties']['excited_states']['transition_energies']
667
+ intensities = results['properties']['excited_states']['intensities']
668
+ units = results['properties']['excited_states']['units']
669
+
670
+ for i in range(len(transition_energies)):
671
+ property_string += "%d,-,%f,%f:" % (i+1,transition_energies[i],intensities[i])
672
+ property_string = property_string.rstrip(":")
673
+
674
+ javascript_string += self._set_datagrapher_uvvis_spectrum(property_string, units, peak_width if peak_width > 0 else 20.0)
675
+
676
+ elif property_name == "hnmr_spectrum" or property_name == "cnmr_spectrum":
677
+ symbols = results['symbols']
678
+ isotropic = results['properties']['nmr_shifts']['isotropic']
679
+ anisotropy = results['properties']['nmr_shifts']['anisotropy']
680
+
681
+ for i in range(len(isotropic)):
682
+ if tms_shift > 0 and symbols[i] == "H":
683
+ isotropic[i] = tms_shift - isotropic[i] #apply the TMS shift, if provided
684
+ property_string += "%d,%s,%f,%f:" % (i+1,symbols[i],isotropic[i],anisotropy[i])
685
+ property_string = property_string.rstrip(":")
686
+
687
+ atom_type = "C" if property_name == "cnmr_spectrum" else "H"
688
+ peak_width = peak_width if peak_width > 0 else 0.001
689
+ relative_spectrum = 1 if tms_shift > 0 and atom_type == "H" else 0
690
+
691
+ if atom_type == "H" and proton_coupling > 0:
692
+ javascript_string += self._set_datagrapher_h1nmr_spectrum(property_string, peak_width, proton_coupling, nmr_field, relative_spectrum)
693
+ else:
694
+ javascript_string += self._set_datagrapher_nmr_spectrum(property_string, atom_type, peak_width, relative_spectrum)
590
695
 
591
- atom_type = "C" if property_name == "cnmr_spectrum" else "H"
592
- peak_width = peak_width if peak_width > 0 else 0.001
593
- relative_spectrum = 1 if tms_shift > 0 and atom_type == "H" else 0
594
-
595
- if atom_type == "H" and proton_coupling > 0:
596
- javascript_string += self._set_datagrapher_h1nmr_spectrum(property_string, peak_width, proton_coupling, nmr_field, relative_spectrum)
597
696
  else:
598
- javascript_string += self._set_datagrapher_nmr_spectrum(property_string, atom_type, peak_width, relative_spectrum)
697
+ raise ValueError("Invalid property_name specified")
698
+ except (KeyError, IndexError, TypeError):
699
+ raise ValueError("Job %d has no %s data for '%s'%s" % (job_number,
700
+ _PROPERTY_DATA.get(property_name, property_name), property_name,
701
+ " (or property_index %d is out of range)" % property_index if property_index > 1 else "")) from None
599
702
 
600
- else:
601
- raise ValueError("Invalid property_name specified")
602
-
603
703
  if not property_name in WAVEFUNCTION_PROPERTIES: #these are already done in the setWavefunction callback
604
704
  if property_name.endswith("spectrum"):
605
705
  if x_range is not None:
606
706
  javascript_string += self._set_x_range(x_range[0], x_range[1])
607
707
  if y_range is not None:
608
708
  javascript_string += self._set_y_range(y_range[0], y_range[1])
609
- javascript_string += self._display_datagrapher_screenshot()
709
+ javascript_string += self._display_datagrapher_screenshot(callback_port)
610
710
  else:
611
711
  javascript_string += self._rotate_moledit_view(rotate[0],rotate[1],rotate[2])
612
- javascript_string += self._display_moledit_screenshot(transparent_background)
712
+ javascript_string += self._display_moledit_screenshot(transparent_background, callback_port)
613
713
 
614
- #display the Javascript for execution
615
- display(Javascript("_call_when_ready(function(){%s})" % javascript_string))
616
- clear_output()
617
- #wait for the Javascript callback and process / display the result
618
- return await self._process_callback_response()
714
+ return "_call_when_ready(function(){%s})" % javascript_string
619
715
 
620
716
 
621
717
  #
@@ -694,20 +790,15 @@ class WebMOREST:
694
790
  return False
695
791
  return body.get('mfaRequired', False) and body.get('error') == 'MFA code required'
696
792
 
697
- def _inject_javascript(self):
698
- if self._init_javascript:
699
- config = self.get_status_info()
700
- major_version = int(config["version"].split(".")[0])
701
-
702
- #ensure WebMO support as well, otherwise disable IPython features
703
- if major_version < 24:
704
- global has_ipython
705
- has_ipython = False
706
- return
707
-
708
- try:
709
- ipython = get_ipython()
710
- ipython.run_cell_magic("html", "", "\
793
+ def _viewer_setup_html(self, config):
794
+ """Returns the HTML that loads WebMO's MolEdit and DataGrapher viewers into a page.
795
+
796
+ Used for the Jupyter notebook (_inject_javascript) and the headless renderer (render_job_property).
797
+
798
+ Arguments:
799
+ config(dict): The server status information, from get_status_info()
800
+ """
801
+ return "\
711
802
  <script src='%s/javascript/jquery.js'></script>\
712
803
  <script src='%s/javascript/moledit_js/moledit_js.nocache.js'></script>\
713
804
  <script src='%s/javascript/jupyter_moledit.js'></script>\
@@ -749,7 +840,22 @@ class WebMOREST:
749
840
  function _clear_lock() {\
750
841
  window.render_lock = 0;\
751
842
  }\
752
- </script>" % (config['url_html'], config['url_html'], config['url_html'], config['url_cgi']))
843
+ </script>" % (config['url_html'], config['url_html'], config['url_html'], config['url_cgi'])
844
+
845
+ def _inject_javascript(self):
846
+ if self._init_javascript:
847
+ config = self.get_status_info()
848
+ major_version = int(config["version"].split(".")[0])
849
+
850
+ #ensure WebMO support as well, otherwise disable IPython features
851
+ if major_version < 24:
852
+ global has_ipython
853
+ has_ipython = False
854
+ return
855
+
856
+ try:
857
+ ipython = get_ipython()
858
+ ipython.run_cell_magic("html", "", self._viewer_setup_html(config))
753
859
  self._init_javascript = False
754
860
  except:
755
861
  has_ipython = False
@@ -770,8 +876,8 @@ class WebMOREST:
770
876
  def _set_moledit_vibrational_mode(self, value, mode, freq, scale):
771
877
  return "_set_moledit_vibrational_mode('%s', %d, %f, %f);" % (value, mode, freq, scale)
772
878
 
773
- def _set_moledit_wavefunction(self, job_number, wavefunction_type, mo_index, transparent_background):
774
- return "_set_moledit_wavefunction(%d,'%s', %d, %d, %s);" % (job_number, wavefunction_type, mo_index, self._callback_port, 'true' if transparent_background else 'false')
879
+ def _set_moledit_wavefunction(self, job_number, wavefunction_type, mo_index, transparent_background, callback_port):
880
+ return "_set_moledit_wavefunction(%d,'%s', %d, %d, %s);" % (job_number, wavefunction_type, mo_index, callback_port, 'true' if transparent_background else 'false')
775
881
 
776
882
  def _set_datagrapher_ir_spectrum(self, value, peak_width):
777
883
  return "_set_datagrapher_ir_spectrum('%s', %f);" % (value, peak_width)
@@ -806,11 +912,11 @@ class WebMOREST:
806
912
  def _rotate_moledit_view(self,rx,ry,rz):
807
913
  return "_rotate_moledit_view(%f,%f,%f);" % (rx, ry, rz)
808
914
 
809
- def _display_moledit_screenshot(self, transparent_background):
810
- return "_display_moledit_screenshot(%d,%s);" % (self._callback_port, 'true' if transparent_background else 'false')
915
+ def _display_moledit_screenshot(self, transparent_background, callback_port):
916
+ return "_display_moledit_screenshot(%d,%s);" % (callback_port, 'true' if transparent_background else 'false')
811
917
 
812
- def _display_datagrapher_screenshot(self):
813
- return "_display_datagrapher_screenshot(%d);" % self._callback_port
918
+ def _display_datagrapher_screenshot(self, callback_port):
919
+ return "_display_datagrapher_screenshot(%d);" % callback_port
814
920
 
815
921
  #
816
922
  # Methods for handling WebSocket data connections and callbacks
@@ -1,9 +1,9 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: webmo
3
- Version: 1.6.0
3
+ Version: 1.7.0
4
4
  Summary: A Python-based interface to WebMO
5
5
  Home-page: https://github.com/jrschmidt2/webmo-python
6
- Download-URL: https://github.com/jrschmidt2/webmo-python/archive/refs/tags/1.6.0.tar.gz
6
+ Download-URL: https://github.com/jrschmidt2/webmo-python/archive/refs/tags/1.7.0.tar.gz
7
7
  Author: J.R. Schmidt
8
8
  Author-email: schmidt@webmo.net
9
9
  License: MIT
@@ -18,6 +18,8 @@ Requires-Dist: PubChemPy; extra == "util"
18
18
  Provides-Extra: gui
19
19
  Requires-Dist: questionary; extra == "gui"
20
20
  Requires-Dist: ipywidgets; extra == "gui"
21
+ Provides-Extra: render
22
+ Requires-Dist: playwright; extra == "render"
21
23
  Provides-Extra: all
22
24
  Requires-Dist: numpy; extra == "all"
23
25
  Requires-Dist: PubChemPy; extra == "all"
@@ -2,8 +2,10 @@ LICENSE
2
2
  README.md
3
3
  setup.cfg
4
4
  setup.py
5
+ tests/test_property_javascript.py
5
6
  webmo/__init__.py
6
7
  webmo/gui.py
8
+ webmo/render.py
7
9
  webmo/spectrum.py
8
10
  webmo/util.py
9
11
  webmo/webmo_rest.py
@@ -11,6 +11,9 @@ ipywidgets
11
11
  questionary
12
12
  ipywidgets
13
13
 
14
+ [render]
15
+ playwright
16
+
14
17
  [spectrum]
15
18
  numpy
16
19
 
webmo-1.6.0/README.md DELETED
@@ -1,2 +0,0 @@
1
- # webmo-python
2
- A Python-based interface to WebMO
File without changes
File without changes
File without changes
File without changes
File without changes