我正在尝试将Mayavi与Jupyter Notebook中的工作流集成。下面的精简代码示例可能看起来不必要复杂,但这些都是我不允许更改的限制。
类Test
用于将某些东西绘制成mlab
图形。类Wrapper
实例化Test
类,而wrapper_func()
函数则向用户公开:它返回Wrapper
实例,并且在关键字参数show=True
时应显示mlab
图形。
注意:我不允许更改Wrapper
和wrapper_func
。此外,Test
类应该实现show()
方法。
from mayavi import mlab
mlab.init_notebook()
import numpy as np
class Test:
def __init__(self):
self.fig = mlab.figure()
self._add_data()
def _add_data(self):
pi = np.pi
cos = np.cos
sin = np.sin
dphi, dtheta = pi / 250.0, pi / 250.0
[phi, theta] = np.mgrid[0:pi + dphi * 1.5:dphi,
0:2 * pi + dtheta * 1.5:dtheta]
m0 = 4; m1 = 3; m2 = 2; m3 = 3
m4 = 6; m5 = 2; m6 = 6; m7 = 4
r = sin(m0 * phi) ** m1 + cos(m2 * phi) ** m3 +
sin(m4 * theta) ** m5 + cos(m6 * theta) ** m7
x = r * sin(phi) * cos(theta)
y = r * cos(phi)
z = r * sin(phi) * sin(theta)
mlab.mesh(x, y, z, figure=self.fig)
def show(self):
return self.fig
class Wrapper:
def __init__(self):
self.t = Test()
def show(self):
self.t.show()
def wrapper_func(show=True):
w = Wrapper()
if show:
w.show()
return w
然后,在Jupyter Notebook的单元格中,用户写道:
wrapper_func()
这将在输出单元格中显示绘图。遗憾的是,没有显示该数字。
或者,用户可以执行以下操作:
w = wrapper_func(show=False)
w.show()
如何在输出单元格中显示图形?
在Test类中创建网格时,将其分配给
self.surf=mlab.mesh( ... )
和return self.surf in show()
在prgram中用作:
t=Test();
t.show()
from mayavi import mlab
mlab.init_notebook()
import numpy as np
class Test:
def __init__(self):
self.fig = mlab.figure()
self._add_data()
def _add_data(self):
pi = np.pi
cos = np.cos
sin = np.sin
dphi, dtheta = pi / 250.0, pi / 250.0
[phi, theta] = np.mgrid[0:pi + dphi * 1.5:dphi,
0:2 * pi + dtheta * 1.5:dtheta]
m0 = 4; m1 = 3; m2 = 2; m3 = 3
m4 = 6; m5 = 2; m6 = 6; m7 = 4
r = sin(m0 * phi) ** m1 + cos(m2 * phi) ** m3 +
sin(m4 * theta) ** m5 + cos(m6 * theta) ** m7
x = r * sin(phi) * cos(theta)
y = r * cos(phi)
z = r * sin(phi) * sin(theta)
self.surf = mlab.mesh(x, y, z, figure=self.fig)
def show(self):
return self.surf
t=Test()
t.show()