3D/4D graphics with Python and wxPython? - python

In my day job as a PhD student, I do geological modeling. In my spare time (mainly for fun), I am learning Python and trying to write a simple program to view 3D geocellular models.
geological model http://img710.imageshack.us/img710/6503/sgems.png
The geocellular model is just a 3D grid where every grid cell has some value (as shown in the right figure). So, I would want my viewer to be able to display a 3D grid model like the picture on the right side. As well, I would like it to be able to display cross sections through the model in the x, y and z directions (this is shown in the left figure).
I would also want the models to be able to rotate around all three axes and zoom in and out.
I've done some preliminary investigation (mainly here) and it seems like VisVis and VTK are two potential options. I am trying to use wxPython for the main GUI and it looks like both options will work with wxPython as far as I can tell.
Questions:
Am I right when I say that I think VisVis and VTK would work for what I want? Is one preferable to the other?
Which of these two options would be the easiest to implement?
Is there another option that I also should consider?
Keep in mind that I'm newish to Python and very new to wxPython.

What you are looking for is called voxel visualization, voxel grid or such. I would seriously consider MayaVi (never used it, but I keep eye on it), it seems to have something very close here.
Paraview, built atop VTK just like MayaVi, might be a good option, too.
I think going straight to VTK for visualization is difficult, it is too low-level and will probably make you just frustrated. That said, you will want to save your data in as VTK datasets for opening in MayaVi/Paraview; it is not difficult, you just have to pick the right structure (vtkGrid, vtkUnstructedGrid, ...).

In my case, I chose to use directly the VTK bindings for Python. To be honest I found it simpler to get going with VTK than Mayavi, partly because the documentation is better (many many examples!). It felt like Mayavi was adding another layer of complexity on my way to get the job done. But tom10 is right. After you've started, using Mayavi may be easier.
Apart from that, Mayavi offers a library called TVTK which is a more pythonic version of the VTK bindings but in the end I chose plain VTK in order to minimize the number of dependencies. But you should check it out. Perhaps it will be just what you are searching for.
At the beginning I found very helpful this tutorial. It is not about Python, it is about tcl, but translating the examples is trivial and it helps you understand the way vtk works.
Also, in order to get you started, you can check the examples at the VTK Wiki. If they are not enough, you can always check the C++ examples and translate them to Python. The translation is not difficult as the names of methods and properties are the same. If you do, you are encouraged to add the examples at the wiki. There are even more examples in the source.
While you are learning VTK, you will (re)discover that Ipython is awesome! Having the whole VTK namespace at your fingertips helps enormously.
In case you need more specific help, the vtk-users mailing list is quite active. Lastly there are books about VTK, and some of them are free!They are not about Python though.
I haven't tried wxPython and VTK together, but that is because I prefer PyQt4 over wxPython. AFAIK there are no problems with the integration of VTK with either library. In any case, before spending time writing a GUI, check out thoroughly ParaView. It probably already does what you want, and if it doesn't, it is python scriptable too! (I've never checked it though).

Just as a simple example of using Mayavi's mlab interface to do this (With some geologic data, even!):
from mayavi import mlab
import geoprobe
vol = geoprobe.volume('Volumes/example.vol')
data = vol.load() #"data" here is just a 3D numpy array of uint8's
fig = mlab.figure(bgcolor=(1., 1., 1.), fgcolor=(0., 0., 0.), size=(800,800))
grid = mlab.pipeline.scalar_field(data)
# Have things display in kilometers with no vertical exxageration
# Each voxel actually represents a 12.5 by 18.5 by 5 meter volume.
grid.spacing = [vol.dxW / 1000, vol.dyW / 1000, vol.dz / 1000]
# Now, let's display a few cut planes. These are interactive, and are set up to
# be dragged around through the volume. If you'd prefer non-interactive cut
# planes, have a look at mlab.pipeline.scalar_cut_plane instead.
orientations = ['x', 'x', 'y', 'z']
starting_positions = [vol.nx//4, 3*vol.nx//4, vol.ny//2, vol.nz]
for orientation, start_pos in zip(orientations, starting_positions):
plane = mlab.pipeline.image_plane_widget(grid, colormap='gray',
plane_orientation='%s_axes' % orientation, slice_index=start_pos)
# High values should be black, low values should be white...
plane.module_manager.scalar_lut_manager.reverse_lut = True
mlab.show()
(The data and data-format-handling code (the geoprobe module) are available here: http://code.google.com/p/python-geoprobe/ )
While I'd agree that learning VTK is better in the long run, you can get up-and-running quite quickly with Mayavi. The big advantage is not having to jump through hoops to get your data into VTK format. TVTK and Mayavi allow you to directly use numpy arrays.

If you want an easier way of getting into the VTK/MayaVi world (see eudoxos' fine answer), look at the mlab API to it. This brings matplotlib-like convenience to basic volume visualizations and I've yet to find the need to dig deeper into the underlying platform.

vpython is simpler to use than mayavi, but it has fewer features.
http://vpython.org/contents/bounce_example.html

Related

Simple 3D Graphics in Python

I am working in a project where 3D visualizations are important to see what is happening during the setup stage and perhaps for visual validation by making a short videos of what is happening.
The problem that I have is that 3D visualizations in Python are too sophisticated, and complicated to learn for what I need. I find that Mathematica is the perfect kind of software...but it is not portable and is very expensive.
Question
Is there any Python package similar to Mathematica?
Clarification
I don't want a "plotting" program, since plotting is not what I am looking for. I want to generate simple geometric shapes like spheres and cubes that can move around, this is more than enough. Give some coordinates, perhaps a rotation, and the program just shows the desired image(s) to export as a .png or make a quick video; as in Mathematica.
Packages like Pygame, Panda3D, Pyglet, etc., look too complicated and an overkill for what I need, as well as software like Blender, etc. Jupyter notebooks are similar, but they don't have the 3D graphics capabilities. I found a Python module named Fresnel, but it looks too sophisticated for what I need.
I have read several answers to this question here in Stack Overflow, but they seem outdated and not really what I am looking for.
Further Clarification
To draw spheres in Mathematica you do:
coordinates = Flatten[Table[Table[Table[ {i,j,k}, {k,1,10}], {j,1,10}], {i,1,10}],1]
spheres= Flatten[Table[Graphics3D[{Sphere[coordinates[[i]],0.5]}],{i,1,Length[coordinates]}]]
Show[{spheres}]
This is a simple quick and easy way of displaying a group of spheres. To use any program in Python to do the same, it seems like you must be an expert in 3D graphics to do this simple thing.
Programs that have capabilities of using Python scripts, like Blender, make it difficult to use the interface in a straight forward way (try doing the same in Blender, it will take a while just to learn the basics!).
I know several other user-friendly plotting libraries than matplotlib, but not a lot provide an interactive view. There is of course the well known vtk but it's not for end-user
plotly
For usage in a notebook, like jupyter and mathematica, you probably would go for plotly It's using a browser-based interface with plots very similar to mathematica
pymadcad
If you need a more offline version and what you are looking for is some view you can rotate/zoom/pan to look on your geometry by different sides, you can take a look at pymadcad
It even works with touchscreens.
It is not centered on 3D visualization, so it's a bit overkill to use it only for it, but for 3D curves, 3D surfaces, spheres and cubes as you said, it can do the job
simple plots with pymadcad:
from madcad import *
from madcad.rendering import Displayable
from madcad.displays import GridDisplay
# create a wire from custom points
s = 100
mycurve = Wire([ vec3(sin(t/s), cos(t/s), 0.1*t/s)
for t in range(int(s*6*pi)) ])
# create a sphere
mysphere = uvsphere(vec3(0), 0.5)
# display in a separated window
show([
mycurve, # displaying the curve
mysphere, # displaying the sphere
Displayable(GridDisplay, vec3(0)), # this is to have a 2D grid centered on origin
])
result:
(The window is dark because so is my system theme, but likely it will adapt to yours)

Is there an equivalent to the Matlab figure window in Python (with all tools)?

I'm just wondering if it exists an equivalent to the Matlab figure window in Python where we can modify plots directly from the figure window, or add some features (text, box , arrow, and so on), or make curve fitting, etc.
Matplotlib is good, but it is not as high-level as the Matlab figure. We need to code everything and if we want to modify plots, we need to modify the code directly (except for some basic stuffs like modifing the line color)
With matplotlib, you will indeed remain in the "code it all" workflow. This is not directly the answer you expect but the matplotlib documentation recently gained a very instructive figure that will probably help you if you stay with matplotlib: http://matplotlib.org/examples/showcase/anatomy.html shows the "anatomy" of the figure with all the proper designations for the parts of the figure.
Overall, I could always find examples of what I needed in their excellent gallery http://matplotlib.org/gallery.html
In my opinion, you'll save time by coding these customizations instead of doing them by hand. You may indeed feel otherwise but if not there is a ton of examples of matplotlib code on SO, in their docs and a large community of people around it :-)

Can I get imshow() like behaviour in a wx.lib.plot.PlotCanvas?

I'm new to wxpython but have been a matplotlib user for some time now. I am developing a wxpython app in which I would like to have a simple frame with a single panel (actually, a wx.lib.plot.PlotCanvas instance). In the panel I want to show some data, which is in the form of a binary array (called imarr), like this one:
The array will always be of shape (64,N), and N can vary between about 400 and 1200 (I can sort out the panel sizing myself).
To do this in matplotlib I would use something like:
fig=figure(figsize=(12,2))
ax=fig.add_subplot(111)
ax.set_ylim(0,63)
ax.set_xlim(0,imarr.shape[0])
ax.set_aspect('equal')
matplotlib.imshow(imarr)
But I'm completely lost in wxpython. I have been looking into wx.lib.plot, but apart from the nice line and marker plotting capabilities, there doesn't seem to be an equivalent to imshow (or pcolor).
One (ugly) solution I have is to use matplotlib as above to create a png image and then use some wx magic to display the image on a panel (please set me straight if this won't be easy).
I'd much prefer to do it from within wxpython, for portability and general tidiness. Any advice on how to display a binary array on a wx.lib.plot.PlotCanvas (or a more generic wx.Panel) would be very useful!
Why don't you combine wxPython and matplotlib together? wx.lib.plot.PlotCanvas has limited functionality comparing to matplotlib. Have a look at an example in this answer and an example from the matplotlib documentation. Sorry that I didn't answer exactly what you are asking for but I think this is the right way to go.

Interactive plotting in Python?

Matlab and Mathematica both have features that allow the user to manipulate the contents of a plot using, say, a slider. For example, if you have a set of 3D data, it is easy to make a small program that lets you view 2D slices of a set of 3D data where the user can slide a slider to move through which slice is displayed. Is there anything in python that allows for this sort of capability without tons of effort? For example, is it possible to do such a thing in matplotlib, or something similar? I
Thanks.
My first thought would be Mayavi, which is great for data visualization, especially in 3D. It relies on VTK. It is included in the Enthought flavoured version of Python, together with Chaco for 2D plotting. To get an idea, look at Travis Vaught's nice screencast in Multidimensional Data Visualization in Python - Mixing Chaco and Mayavi.
It also possible to embed basic interactive functionalities (like slider) to Matplotlib, see matplotlib.widgets and the widget examples.
Finally, you can use rpy (or better, rpy2) and benefit from the R interface.
Have you looked at Vtk? http://www.vtk.org/ One of their demos does exactly what you're asking.
In principle, you can do it by help of MathGL. This is cross-platform GPL library for plotting.
For each mouse clicks you can find the x,y,z position in plot or clicked object and adjust (replot) some other information correspondingly. However you should handle mouse clicks by yourself (for example, using PyQt).
Another option is to use python within the SAGE computation interface/environment, which has the #interact command (see here for specific help on this command)

real time gui for python using only traits

Is it possible to create a ui using traits from python to make an interface for a cellular automata simulation?
Of course, you can do anything with Traits that can with Python!
Seriously though, I presume your question is really about generating a GUI in which to display the CA. In that case I can recommend Mayavi which is based on Traits. It has a surf function which plots an array of regularly-spaced data as a 3D surface. There are docs on animating the data which shows how to change the underlying surface data for very fast rendering, which I have used and works well. I have a 3D numpy array shape=(x,y,time) and then for each step I pass a slice to surface objects data object:
surf.mlab_source.scalars = array[:,:,timepoint_index]
Alternatively you could use Matplotlib's imshow for a 2D plot of the same data. There is a very good tutorial on embedding matplotlib in traits.
One issue with using these large libraries (which themselves have many, many dependencies) is being able to distribute your application along with the libraries. I have successfully frozen a Mayavi/matplotlib/traits app on Mac using py2app and Windows using py2exe, starting from the Enthought Python Distribution, but it wasn't easy. However, if you just need it to work on your computer and generate results then both of these approaches will save you time over writing a graphics system for your cellular automata.
Having said all that I also hear good things about GarlicSim (as cool-RR mentioned), which would seem to be custom-made for your purpose.
Can't post links because this is my first post, I will add them later.

Categories