Remote Panner

Last night, using 0MQ I set up the image panner to use a remote renderer.  This let me start up a REP/REQ system, where on the remote system (bound to localhost and ssh tunneled) I waited for new requests that describe the limits I wanted to plot, and locally I had the image panning GUI send the new requests and receive the new image.  It worked great -- very easy to set up -- except that the arrays it was passing were 2MB each, so the latency to my home network was unbearably high.  Today I'll give it a shot at work, see if it's a workable solution.
Tagged python scipy yt

Figuring Out Stereo Volume Rendering

Last week I was approached by a friend and collaborator to prepare some large volume renderings using the aforementioned software volume renderer in yt.  In the past we've successfully made very, very large image renderings using yt -- Sam's even made one at 8192^2, although at extremely high resolution like that sometimes the lack of fidelity in the underlying volume renderer shows up; sometimes even artifacts in the AMR grid boundaries, but that's less common.  Making the very large volume renderings isn't too bad -- it scales roughly with the number of pixels, but we can dispatch many frames to be rendered at once on a cluster.  

There are a couple other, more important things to consider when making the big volume renderings.  For starters, the entire structure of volume rendering in yt was not really created to generate a series of images -- only a single image.  The idea was that you would prepare a specific image, make it, and move on.  However, for this project, I want to do a zoomin, or possibly a more complicated camera path.

Additionally, one of the first things that we did with the volume rendering was silly: we applied no normalization to the output images.  That was a mistake, I see now.  Part of the reason for this was uncertainty in the correct normalization -- the bias that the user wanted to apply may not be the natural bias from the image.  But more than that, because the rendering algorithm itself was some what holistically settled upon (the original implementation, which we used for shell-style renderings, was not a "correct" implementation of alpha blending) a natural mechanism for scaling did not immediately present itself.  One likely exists, possibly dependent on the field of view, I simply do not yet know it.  This will have to be rectified, because the mechanism used for scaling a set of images will have to be different than the mechanism for scaling an image in isolation, or else frames will jump in brightness during the movie's course.

The final thing that I wanted to change was to add support for stereo rendering.  Rather than repeat any of the amazing discussion from Paul Bourke's website, I'll simply direct you there.  Everything you ever wanted to know about stereo rendering.  (When I was a first year grad student, we actually bought a copy of his site to use locally -- it was our way of showing support for him putting it online, and it also came with a bunch of source code for example applications.)  I first attempted to apply the correct method for stereo, where the view direction is parallel and the total view frustum is shifted.

This did not work.  In fact, it made me realize that all this time, the yt method for volume rendering is in fact ... not really a volume rendering method inasmuch as it is a planar ray-casting method.  Typically when doing volume rendering, there's a perspective applied to the image: the rays all emanate from a single place, creating a frustum.  But for yt, we actually set up a single plane of vectors at the back of the volume and advance that forward across the image.  This is good and bad; it's good in the sense that it's more clear precisely what is going on.  But it's bad in the sense that correct stereo is more difficult.  (Of course, on Bourke's page he has a workaround that may work for this, but I have not yet attempted it.)  Here's a rough depiction of the different between the two methods.

Renderingmechanisminyt

The upshot is that stereo doesn't seem to work unless you go with the "toe-in" method that can cause eyestrain after a long time and shows visible parallax at the edges.  I'm not sure if this is going to be a problem, but because I am not right now eager to rewrite the rendering backend, this is the way it is for the moment.

To set up the stereo rendering, I separated out the rendering mechanism from the objects to be rendered.  Previously, there was a single VolumeRendering object that you could create, raycast through, then discard.  I created a new camera object that accepted a homogenized volume and would call "traverse" on that volume, feeding a back and a front point.  The Volume is then responsible for passing off fixed-resolution grids to the camera, which accumulates an image buffer by calling the ray traversal functions.  The front and back points are essentially the only thing needed to know this order, but the camera also stores its three orientation vectors and its position that describe it in 3D space.  By separating out these two conceptual objects, we undo some of the "single, carefully constructed image" bias that was in the original volume renderer.  (And, we open ourselves up to being able to use the Camera with a hardware volume renderer, should that day ever come.)

So now we have a camera, and it makes images like this:

C_0001

It's a little dim, but that's a task for another day.  The next step is taking that perspective and turning it into a set of stereo images.  To do that, I added a new class called StereoPairCamera.  It accepts a Camera object and turns it into two camera objects, where the final interocular distance is calculated relative to the image plane width.  As I mentioned above, this only operates via toe-in stereo, so it does this in the simplest manner possible: it moves each of the Left and Right cameras by half of the interocular distance away from the original location, and then recalculates a normal vector to point back at the original center.  Now we can generate left and right images:
Unfortunately, on my laptop (which is my primary/exclusive work computer) I don't have the ability to view these pairs.  To get around that, I wrote a simple stereo pair image viewer in OpenGL and imposed upon my friends that do have a stereo viz wall to test it out -- and after some fiddling with the interocular distance, we got what appeared to be workable stereo pairs.

The full code for generating camera paths as well as stereo pairs is already in yt, but the documentation is still being written; I might also clean up the interface a bit.  Additionally, at some point in the future, the issue of toe-in stereo versus correct parallel-frustum stereo will need to be dealt with; the last thing I really want to do is force people to only use a bad method for generating stereo pairs.  Hopefully that is something that can be dealt with at a later time.

Thanks to the wealth of resources out there for making this a relatively easy task: the aforementioned Paul Bourke website on stereo pairs, the PyOpenGL and PIL teams for making the image pair viewer easy, and everyone else whose work I've built on to make things like this.

L_0001

R_0001

Tagged python scipy viz yt

Remote Data Rendering

I've grown a bit weary of this pattern:

  1. Generate data on remote machine
  2. Generate and save images on a remote machine
  3. SFTP or SCP images to local machine
  4. Display images
It sure would be great if we could collapse 2-4 into a single item.  The issue I've been running into, however, is that X11 forwarding simply doesn't work that well.  VNC provides a slightly better solution, but both of these are clunky and difficult to synchronize with other windows.  Ideally, I'd want to be able to spawn an ssh tunnel and an IPython session, and then use that to control remote data, plotting in local windows.
 
Of course, the raw data could be brought back -- an sshfs mount, for instance.  But as long as my data lives on the super computer, why not let the images get created there, as well?
 
To that end, I used the IPython MultiEngineClient interface to set up an ipengine, an ipcontroller, and then to interact with them.  By creating a NonLocal data object that pushed new parameters and pulled back new buffers to display locally, I was able to drop this in as a replacement for the plotting engine in the pan and scan image display.  So now, I can directly pan and scan locally without having to pass images manually, without having to generate smaller data products and pass those, and without having to copy any data anywhere.  The code to run it is relatively simple, and at the end, it all pops up in a nice GUI.
 
I'm not sure this is precisely what IPython's remote interface was designed to do -- and it is somewhat showing, in the responsiveness and lag times.  To pass a single array back and forth, between a client and an engine both running on localhost, it costs about a second.  So FPS is around 1, which is pretty low, but still doable, and still within the limits of what I am willing to live with.  Some profiling suggests that the acquiring of thread locks for blocking communication is where the slowdown comes in, so perhaps there's a place to speed it up there -- the multiple layers of abstraction in IPython may not be doing me any favors, and I may benefit from investigating how to bypass some, or even use a different backend eventually.
 
But, again: this lets me chew through a lot of data, very easily, and without a lot of hassle.  It's a huge net win.  Next up is figuring out how to get some of our custom colormaps into Chaco, add a couple convenience buttons on the Traits window for my particular purposes, and then I'll be totally set.

Update: Evidently I can't get Posterous to include code properly.  I have no idea why.  Apologies.
Tagged python scipy

Bootstrapping into a GUI

I always resisted making a GUI for my analysis toolkit.  There, I said it.  I've come clean.  I don't really want to make one, and I like the scripting interface just fine.  But, as my datasets get larger, and I need to explore them faster, I'm starting to see their usefulness quite a bit more -- as I talked about a bit a few weeks ago.

A couple years ago I wrote one based on wxPython -- it had a system of events and notifications and so on, but it was brittle and had a lot of moving parts.  And I never really used it, which I think might have been the most important part.  So after I wrote it, it kind of underwent bitrot.

But now that I'm using Traits, I'm starting to feel like the right way to write a GUI is in bits.  Right now, I have a VTK bit that does one thing.  I've also got an image pan-and-scan widget that does a thing.  I'm not really interested right now in setting up a big framework that handles all of these things, because one of the coolest things about Traits is that if I ever end up with a lot of Little Things that I want to put together, the actual integration would be relatively straightforward.

So I guess that's the way forward: write things that do what I want right now, this instant, use them, and if they ever get too big for their britches, maybe they could all be strung together.  So for now, I'm going to just keep using the little things to do my research, one step at a time, and maybe some day down the road it'd be nice to get them to work all together.
Tagged python scipy yt

Some more fiddling with Chaco and AMR data

In a followup to a post from Friday, I fiddled a bit more with Chaco and the AMR data plotting today.  By mostly using components that I'd already created, I was able to make it switch between fields while panning and zooming.  By using Chaco and Enable a bit more cleverly, I managed to get a 25x zoomed in plot inset in the bottom left of the zoomed-out plot, and (as should come as little surprise) the necessary code was very short.  Here's what it looks like now, displaying a 512^3, refine everywhere, 7 level dataset:

L7_chaco

Panning and scanning and zooming through a dataset like this really is the only way to fly.  I'm now using it on data for my next paper, and I think it's about three lines of code from writing scripts to plot images based on clicking when I get to a scene I'd like.  There are a whole bunch of second-order fixes and improvements to make, but they have all been bumped to and unspecified time in the future now that it's functional to the extent that I can examine my data in detail!  But, I'll definitely push all of the changes necessary to get this type of interface back up into the main repository.  Perhaps somebody else will take it and run with it.

2D Data Visualization of AMR with Matplotlib and Chaco

With yt we have used matplotlib almost exclusively for 2D plotting of adaptive mesh refinement data.  This week, I implemented a plotter inside Chaco a plotting system designed for interactive exploration of data.

But first!  An interlude about how we visualize 2D AMR data.

Our data is naturally a patch-based format.  What that means is that higher resolution cells are grouped into grid patches -- this ultimately means that the data itself is relatively convenient to look at, and also for some post-processing computation we end up being able to make a lot of guesses at which data to look at or analyze based on its location in grid patches.  Additionally, these grid patches overlap at different resolution levels: finer resolution grids are inside coarser grids.

When generating a 2D representation, we typically will take either an orthogonal slice or a "projection" through the data.  (The additional spatially-organized 2D representation we have in yt is the oblique slice, but it's something of a special case.)  Back when designing the projection and slice algorithms, we decided it was the most efficient to construct a set of "flattened" data: by projecting through the data, we end up with a set of data that represents the finest resolution data available along every sightline through the domain.  This is represented by five values: (x, y, dx, dy, z) where x and y are in the plane of the projected domain.  For slices, we get something similar, but this time it's only the finest data available at any orthogonal slice.

Projection

The alternatively mechanism would be to generate fixed-resolution arrays and fill them in; this gives and takes various things, but ultimately while we provide support for this type of function, and it's the only way to project inline with the simulation (slices can be done adaptively inline), we prefer the "adaptive" projections.  An additional advantage, one that appeals to me particularly (as my AMR runs go to 30 or so levels of refinement) is that we only have to project once with the adaptive projections and we can zoom and pan as much as we like.  More on zooming and panning later!

In matplotlib, there are two natural ways to present this data: by constructing a set of rectangular patches that this data represents and then filling them with the appropriate value, or by pre-pixelizing, using a bit of our knowledge about how AMR data works, and then displaying an image.  The advantage of the first is that we are able to provide only a single set of data to matplotlib, once, and then we can adjust the limits inside the context of matplotlib and describe the data exclusively in the context of the domain.  However, there's a lot of overhead involved -- often we end up with projections that, with just the five values alone, run into the hundreds of megs.  (For very large simulations, particularly.)  Generating a second layer of objects, one for every cell at the finest resolution in the image plane, is probably going to add too much overhead.  So instead we run the pixelizer!  (Of course, at some stage matplotlib also runs a pixelizer, to turn the multiple patches into a single output image.  But it does so with a little less knowledge than we have about the nature of the data, so the generality costs would cost us.)

The pixelizer is relatively simple: for every datapoint in the projection or slice, if it falls within the bounds of our image, deposit it into the appropriate cells with which it overlaps.  If it fully overlaps, deposit the entire thing; otherwise, only deposit a fractional amount.  This process is relatively fast, but not without cost.  The biggest cost is actually in discarding the points that do not fall within the region -- the iteration itself!  Because our data is periodic, we have to check multiple times for most datapoints whether or not they are within a given region.  This also costs us.  Overall, however, the process is straightforward and fast.  (Of course, I do realize that the entire projection process: from the initial grid patches, to summing over an axis, to the compositing and the pixelizing, is something OpenGL was designed to do!  But, we do it all in C.)

So now we have a mechanism that takes multi-resolution AMR data and turns it into an image, given only the data itself, a resolution, and a 2D bounding box.  Typically this is used by yt to generate matplotlib plots.  This week, though, I have been working a bit on a tile display wall routine -- dispatching rendering jobs to different nodes and then having them feed back some portion of the render job to a display tool that broadcasts it to multiple monitors.  (More on that process in a future blog post.)

However, one thing that was always really lacking was an intuitive mechanism for interacting with a plot: in years past, I'd hacked up a matplotlib and wx-based GUI that had some neat features -- a slider to set the width and re-centering abilities.  But it was clunky, and kind of slow, and I hated maintaining it.  The book "wxPython in Action" was quite good, and wx is definitely a very capable toolset, but I ended up using the "pubsub" mechanism in wx and I eventually got lost in the events and handlers and couldn't find my way out.

Enthought's Chaco toolkit, though, was designed for interactive use -- whipping up GUIs around structured data (using the "Traits" interface) is easy and straightforward.  A couple years ago, they added the ability to get 1D data via functions -- so the data could be recalculated on the fly, as the range needed changed.  This week and last, with the help of the head Chaco developer, I was able to extend this to work with image data, as well.

First, a brief description of the UI I was hoping to get: Chaco very easily presents a "google maps" style interface to image data, where you can click and drag to pan and scroll your mouse wheel to zoom in and out.  I wanted to have it set up such that I could do this with the AMR data -- as you zoomed in, it would re-pixelize such that it was displaying a smaller portion at higher resolution, much like with normal google maps.  Almost all of this was available in the standard Chaco distribution -- the pan and zoom tools, the displaying of image data, and the setup for inserting callbacks between different components.  Displaying a single fixed image in Chaco, with the GUI and everything, is on the order of a dozen lines, many of which are boilerplate.

By adding a FunctionImageData class (almost identical to the FunctionDataSource class, except extended to 2D and subclassing Image Data) I was able to mock up the re-generation of data: as the range of data displayed changed, the data handed back was generated.  By inserting a callback to update the range that the data mapped to (i.e., not only generating higher resolution data, but mapping it back to a smaller data region, thus ensuring it fully filled the image plot) the entire experience was complete.

The FunctionImageData requires a callback function that receives a "low" and "high" value that describe the new bounds of the visible data, but I also had to update the "index" -- to do all of this together, I wrote this helper class:

 class ImagePixelizerHelper(object):
     index = None
     def __init__(self, panner):
         self.panner = panner
  
     def __call__(self, low, high):
         b = self.panner.set_low_high(low, high)
         if self.index is not None:
             num_x_ticks = b.shape[0] + 1
             num_y_ticks = b.shape[1] + 1
             xs = mgrid[low[0]:high[0]:num_x_ticks*1j]
             ys = mgrid[low[1]:high[1]:num_y_ticks*1j]
             self.index.set_data( xs, ys )
         return b
 

(Note that even though I sung the praises of Traits earlier, I don't really use them here.  That will happen, it just hasn't yet.)  The "panner" here is something that updates a pixelized image when the bounds change.  What the check for index inside __call__ does is mock up the re-generation of the image indices, if an index is supplied.  This also transforms the initialization of the image plot into a two-strep process:

         pd = ArrayPlotData()
         plot = Plot(pd)
         self.pd = pd
         helper = ImagePixelizerHelper(self.panner)
         fid = FunctionImageData(func = helper)
         fid._data = self.panner.buffer
         self.fid = fid
         bounds = self.panner.bounds
         pd.set_data("imagedata", fid)
  
         img_plot = plot.img_plot("imagedata", colormap=jet,
                                  interpolation='nearest',
                                  xbounds=(0.0, 1.0),
                                  ybounds=(0.0, 1.0))[0]
         helper.index = img_plot.index
         self.helper = helper
  
         fid.data_range = plot.range2d
 

So here I set up the array plot data, I set up the plot based on it, I create the pixelizer helper, then I add a default value to the pixelizer.  This is a crucial step, because it's how the image plot knows what shape the data is.  (There are some other things about the image plot I'm not fully sure of just now, and this is one I now sort of understand -- the relationship between mappers, indexers and plots.)  I've then set the helper to have access to the image plot's index, and the data range is set to the plot's data range.  At this point the two know how to talk together.  Below this I add a few tools for zooming and panning, and a colorbar too

At this point, our plot works.  And it's simple and easy and, best of all, very interactive.  Every time the data range changes the pixelizer updates and passes back a new image: so we've got the best of both worlds.  We only have to store in memory a relatively small amount of data, and it goes to the highest resolution possible.  Here's an example, where I am zooming into a dataset of mine.

Amr_chaco2

(download)

It could go on for a while -- this dataset is really quite deep (this was three scrolls, but I could probably do fifteen or so) but I think this gets the point across.  I was able to zoom in just by scrolling with my mouse, and I can click and drag.  It's intuitive, it's very very fast, and I only had to write a tiny bit of code to get it to go.  This is what I want!

I think that maybe it's time to revisit having a GUI.  I'd forgotten how much fun it is to explore my data, and if I can really get one going in such a short amount of code, it might be very effective to do this rather than constantly having to tweak scripts and scp images.  And with the vast amounts of data I am now sort of drowning in, this will be crucial.  The dataset I originally decided to do this for is just immense; I was struggling at coming up with a way to see it all, to see all the tiny features and structures, because it's at a time in the universe when such things are relatively far apart, but also quite numerous on the length scales we're simulation.  Using this kind of an interface will let me discuss individual halos with the other members of the project, and we'll be able to really see and share and converse, rather than just looking at static images over email.

Another huge advantage that only just occurred to me is that the same code I used to write the backend for the tile display wall could be used for remote visualization in this same manner.  By repurposing that to feed directly back into Chaco, instead of grabbing the arrays myself, we might be able to avoid any copying of data (even the pre-projected values) onto a GUI-able host.  That could be very awesome, too.  The entire Chaco/Traits/ETS toolkit is very powerful and I think I see it being an extremely valuable part of our future plans for interactive analysis.

(edit: evidently I messed up the options for code highlighting and for including all the images in a single slideshow, and from the post-edit area I can't figure out how to fix them..  I guess I have a bit more to learn about posterous!  Sorry about that.)

Tagged python scipy viz yt

CLyther dev documentation — CLyther v0.dev documentation

CLyther is a python tool similar to Cython. CLyther is a python language extension that makes writing OpenCL code as easy as Python itself. CLyther currently only supports a subset of the Python language definition but adds many new features to OpenCL. CLyther was inspired by PyCUDA and PyCUDA’s views on Metaprogramming.

This is a project to keep a very close eye on. On a related note, closures support in Cython seems to have been delayed until 0.14.

First Steps with OpenCL

I managed to get PyOpenCL to work as a projection engine for some AMR data.  This image is of a simple PyOpenCL driver I wrote using Enthought's Traits as a GUI.  The idea is that you can change some parameters, change the routine it calls, hit recompile, and it'll pass all the bricks back in.  I'd like to extend this concept, but first I've got to ensure that my OpenCL kernels are doing the right thing!

Pyopencl_projection
The kernel shown above (and visible as the subroutine "proj" in my OpenCL repo) does a simple projection.  The image might even be a MIP.  I've since been able to make it ray cast, but with a bunch of artifacts I haven't been able to track down, including one that has stymied plotting all three channels simultaneously.  Here's an image of the red channel from the ray caster, plotted against a different colormap:

Hi_0_gist_heat

So it's sort of working, but the artifacts will need some work before they're all sorted out.  Ultimately, I'd really like to support OpenCL as a rendering engine, as well as the current software engine we have now.  I think having the TVTK frontend that dumps to a software or OpenCL backend for ray-casting the full volume would be ideal.  I also think there's really something to the idea of having a generic engine (the simplest form of which I included a screencap above) that just passes data through a shader and plots the results.  I'm not the person to write one, I don't think, but I've heard rumblings one might be coming out of a pretty fancy coder up in the bay.

Packaging yt, NumPy, VTK on OS X Snow Leopard

Packaging is one of the hardest issues for distributing scientific applications.  For yt we actually don't have much of a problem for Linux systems -- everything usually installs right out of the box.  The only real issues are either wxPython, because the underlying X11 and GTK libraries aren't on the system (I'm looking at you, TeraGrid!) or a mismatch in the current compiler module that's loaded.  (For instance, having PGI loaded while trying to compile with GCC.  In my experience, the "module" system as a whole seems to give only epsilon more functionality than the headaches it gives, but that's neither here nor there.)

OS X, though, is an exceptionally different beast -- and with Snow Leopard, it only got worse.  The 64-bit setup, the 10.6 SDK, etc etc, only made things more headachy and complicated.  (I still don't have PyCUDA working, which one of the major reasons I've shifted over to OpenCL as a GPU platform!)  After much struggling with install paths and compiler locations, I managed to get our Numpy + Matplotlib + H5py + Python2.6 stack relocatable and strictly 10.6-based, however, and I finally set up an installer repository.  I've had a couple people test the installation script and it works, tossing all the packages out onto their system.  (If you've stumbled across this post hoping for a superpack installer, the installation script -- which will also install yt! -- is described here.  It doesn't include SciPy, though.)

However, there are a couple problems with 10.6 as a whole -- mainly the lack of easy solutions for wxPython (depends on Carbon), Pyglet (depends on Carbon) and PyCUDA, which despite supposedly being able to work in 32 bit mode has never successfully launched with my hand-rolled (fat-binary) Python 2.6.  Boost, also, required some mangling of the library path with install_name_tool, as it kept wanting to link against the wrong Python!

Anyway!  As the capabilities of yt expand, I really want to get more people on board with things like VTK, TVTK, ETS and maybe some other fun things.  Installing VTK was the biggest hurdle -- it's got a lot of moving parts, the installation is a bit non-trivial, and compilation on 10.6 has been tricky at times.  However, just by chance I was listening to the FLOSS Weekly show (#111) about CMake, where discussion of CPack led me to investigate it.  CMake is the underlying make system built by Kitware for things like ITK, VTK and other projects.  KDE uses it now, too.  CPack, evidently, was designed to make portability and installation much easier.

So, I gave it a whirl.  The VTKCPack.cmake file had to be modified such that it installed if VTK_WRAP_PYTHON were enabled (it defaults to VTK_WRAP_TCL) but after that, it Just Worked.  "cpack -G PackageMaker" happily and easily generated a .mpkg file.  The .mpkg file doesn't include the Python package, but a simple "setup.py mpkg_bdist" made a second one of those.  I've sent both out for more rigorous testing, but I think they should do just fine.  Once we have seeded those, I'll give a shot at making packages on Linux, as well -- and then maybe we can start distributing VTK and encouraging its use as a visualization system!  The problem has always been just in distribution, never in capability.  And the distribution problem, I guess, has been solved for a while -- we just didn't know it!  Kudos to the Kitware folks for this excellent system.

(As a side note, I really would prefer just to suggest people install EPD rather than my hand-rolled, difficult to maintain stack.  Unfortunately, we're still having trouble figuring out how to get our C-modules that interface with HDF5 on a low-level basis to play nice with EPD.)

PiCloud | Cloud Computing. Simplified.

Media_httpmediapiclou_umirf

EPD-enabled cloud computing. yt could probably run on this with a bit of effort, but the data passage would be intense. Depending on the backend, it could actually be extremely easy to store select datasets (in the several to many gigabyte range) on the cloud and dispatch yt analysis jobs there. For instance, the big Santa Fe Light Cone dataset is about 35 gigs a timestep. Amazon charges $0.15 per gig for storage, so dumping it up there would not be prohibitively expensive. Toss a yt job up there to analyze it, and it would be done. This is exciting.

Tagged hpc python scipy