[yt-svn] commit/yt: 20 new changesets

commits-noreply at bitbucket.org commits-noreply at bitbucket.org
Thu Aug 20 09:39:07 PDT 2015


20 new commits in yt:

https://bitbucket.org/yt_analysis/yt/commits/db16b2c87538/
Changeset:   db16b2c87538
Branch:      yt
User:        ngoldbaum
Date:        2015-08-17 17:12:44+00:00
Summary:     Removing yt/visualization/volume_rendering/multi_texture.py

This does not appear to have had any substantial updates since 2010
(cset hashes 15ce2c8e0398 and 167c583e26f8). It is not used elsewhere in yt
and depends on an outside package (visvis).
Affected #:  1 file

diff -r bc21601eb3e3d89810ca3b5e914797f934fe1ef8 -r db16b2c87538ce46b4c5c62fda1ac23313781f5f yt/visualization/volume_rendering/multi_texture.py
--- a/yt/visualization/volume_rendering/multi_texture.py
+++ /dev/null
@@ -1,311 +0,0 @@
-"""
-A first-pass at a VisVis-based interactive viewer.
-
-Hi Matt,
-
-You could define your MultiTexture object (which would be a Wobject) and use
-multiple visvis.textures.TextureObject instances to represent the sub-textures.
-This TextureObject class is not a Wobject, but simply of a wrapper around an
-OpenGl texture that handles uploading, updating, etc. 
-
-The MultiTexture object you could derive from BaseTexture or maybe even
-Texture3D if your data is 3D. Or maybe just from Wobject if this makes more
-sense. Also, the visvis.textures.TextureObjectToVisualize might be used instead
-of the TextureObject class.
-
-I mentioned a lot of texture classes, let's make a small list:
-  * TextureObject - wraps an OpenGl texture
-  * TextureObjectToVisualize(TextureObject) - implements intensity scaling
-    (what is changed with the clim property)
-  * BaseTexture(Wobject) - the base visvis Wobject class to represent textures.
-    It *contains* one TextureObjectToVisualize and has several properties to
-    influence it's appearance.  * Texture2D(BaseTexture) - Implementation for 2D
-    textures.
-  * Texture3D(BaseTexture) - Implementation for 3D textures.
-  * YourNewMultiTexture(BaseTexture or ...) - contains multiple
-    TextureObjectToVisualize or TextureObject instances.
-
-This is I think the most sensible way to go about this. 
-
-Now in the OnDraw method, you can draw the textures one by one using the same
-settings. Or if you want a single draw in which you combine the information
-from all textures to determine the final color, you should write a new glsl
-shader to which you pass all textures.
-
-I hope this helps,
-  Almar
-"""
-from __future__ import print_function
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-from yt.mods import *
-from yt.funcs import *
-
-import visvis as vv
-import visvis.textures as vvt
-
-import OpenGL.GL as gl
-import OpenGL.GL.ARB.shader_objects as gla
-import OpenGL.GLU as glu
-
-import numpy as np
-
-class MultipleTexture(vv.Wobject):
-    def __init__(self, parent, data, global_size, renderStyle='mip'):
-        vv.Wobject.__init__(self, parent)
-
-        self._global_size = global_size
-        
-        # create colormap
-        self._colormap = vvt.Colormap()
-        
-        # create glsl program for this texture...
-        self._program1 = vvt.GlslProgram()
-        
-        # scale and translation transforms
-        self._trafo_scale = vv.Transform_Scale()
-        self._trafo_trans = vv.Transform_Translate()
-        self.transformations.append(self._trafo_trans)
-        self.transformations.append(self._trafo_scale)        
-
-        data = ensure_list(data)
-        self._textures = []
-        self._quads = {}
-        for obj in data:
-            tex = vvt.TextureObjectToVisualize(3, obj) 
-            self._textures.append(tex)
-            tex.SetData(obj)
-        self._program1.SetVertexShader(vvt.vshaders['calculateray'])
-        self._program1.SetFragmentShader(vvt.fshaders['mip'])
-        self._renderStyle = ''
-        self.renderStyle = renderStyle
-        if not self._renderStyle:
-            self.renderStyle = 'mip'
-        self._quadlists = None
-
-    def OnDrawShape(self, clr):
-        gl.glColor(clr[0], clr[1], clr[2], 1.0)
-        self._DrawQuads()
-
-    def OnDraw(self, fast=False):
-        # Prepare by setting things to their defaults. This might release some
-        # memory so result in a bigger chance that the shader is run in 
-        # hardware mode. On ATI, the line and point smoothing should be off
-        # if you want to use gl_FragCoord. (Yeah, I do not see the connection
-        # either...)
-        gl.glPointSize(1)
-        gl.glLineWidth(1)
-        gl.glDisable(gl.GL_LINE_STIPPLE)
-        gl.glDisable(gl.GL_LINE_SMOOTH)
-        gl.glDisable(gl.GL_POINT_SMOOTH)
-        
-        # only draw front-facing parts
-        gl.glEnable(gl.GL_CULL_FACE)
-        gl.glCullFace(gl.GL_BACK)
-        gl.glBlendFunc(gl.GL_ONE, gl.GL_ONE)
-        gl.glBlendEquation(gl.GL_MAX)
-        gl.glDisable(gl.GL_DEPTH_TEST)
-        
-        if self._program1.IsUsable():
-            self._program1.Enable()
-
-        if fast:
-            self._program1.SetUniformf('stepRatio', [0.4])
-        else:
-            self._program1.SetUniformf('stepRatio', [1.0])
-
-        self._program1.SetUniformi('texture', [0])        
-        self._colormap.Enable(1)
-        self._program1.SetUniformi('colormap', [1])
-
-        # enable this texture
-        t1 = time.time()
-        for i,tex in enumerate(self._textures):
-
-            tex.Enable(0)
-            
-            if not tex._shape:
-                continue
-
-            # fragment shader on
-                
-            # bind texture- and help-textures (create if it does not exist)
-            
-            # set uniforms: parameters
-            shape = tex._shape # as in opengl
-            self._program1.SetUniformf('shape',reversed(list(shape)) )
-            
-            # do the actual drawing
-
-            self._DrawQuads(tex, i)
-            tex.Disable()
-        
-        # clean up
-        gl.glFlush()
-        t2 = time.time()
-        print ("Rendering: %0.3e" % (t2-t1))
-        self._colormap.Disable()
-        self._program1.Disable()
-        #
-        gl.glBlendEquation(gl.GL_FUNC_ADD)
-        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
-        gl.glDisable(gl.GL_CULL_FACE)
-        gl.glEnable(gl.GL_LINE_SMOOTH)
-        gl.glEnable(gl.GL_POINT_SMOOTH)
-        gl.glEnable(gl.GL_DEPTH_TEST)
-        
-        
-    def _DrawQuads(self, tex, tex_id):
-        """ Draw the quads of the texture. 
-        This is done in a seperate method to reuse code in 
-        OnDraw() and OnDrawShape(). """        
-        
-        # should we draw?
-        if not tex._shape:
-            return 
-        
-        # should we create quads?
-        if tex_id not in self._quads:
-            self._CreateQuads(tex, tex_id)
-        
-        # get data
-        tex_coord, ver_coord, ind = self._quads[tex_id]
-        
-        # init vertex and texture array
-        gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
-        gl.glEnableClientState(gl.GL_TEXTURE_COORD_ARRAY)
-        gl.glVertexPointerf(ver_coord.data)
-        gl.glTexCoordPointerf(tex_coord.data)
-        
-        # draw
-        gl.glDrawElements(gl.GL_QUADS, len(ind), gl.GL_UNSIGNED_BYTE, ind)
-        
-        # disable vertex array        
-        gl.glDisableClientState(gl.GL_VERTEX_ARRAY)
-        gl.glDisableClientState(gl.GL_TEXTURE_COORD_ARRAY)
-    
-    
-    def _GetLimits(self):
-        """ _GetLimits()
-        Get the limits in world coordinates between which the object exists.
-        """
-        
-        x1, x2 = -0.5, -0.5 + self._global_size[2]
-        y1, y2 = -0.5, -0.5 + self._global_size[1]
-        z1, z2 = -0.5, -0.5 + self._global_size[0]
-
-        return vv.Wobject._GetLimits(self, x1, x2, y1, y2, z1, z2)
-    
-    
-    def _CreateQuads(self, tex, tex_id):
-        axes = self.GetAxes()
-        if not axes:
-            return
-        
-        # Store daspect so we can detect it changing
-        self._daspectStored = axes.daspect
-        
-        # Note that we could determine the world coordinates and use
-        # them directly here. However, the way that we do it now (using
-        # the transformations) is to be preferred, because that way the
-        # transformations are applied via the ModelView matrix stack,
-        # and can easily be made undone in the raycaster.
-        # The -0.5 offset is to center pixels/voxels. This works correctly
-        # for anisotropic data.
-
-        dr = tex._dataRef
-
-        ss = [s - 1 for s in tex._shape]
-
-        x0 = dr.origin[2] * self._global_size[2] - 0.5
-        x1 = x0 + ss[2] * dr.sampling[2] * self._global_size[2]
-
-        y0 = dr.origin[1] * self._global_size[1]
-        y1 = y0 + ss[1] * dr.sampling[1] * self._global_size[1]
-
-        z0 = dr.origin[0] * self._global_size[0]
-        z1 = z0 + ss[0] * dr.sampling[0] * self._global_size[0]
-        
-        # prepare texture coordinates
-        t0, t1 = 0, 1
-        
-        # if any axis are flipped, make sure the correct polygons are front
-        # facing
-        tmp = 1
-        for i in axes.daspect:
-            if i<0:
-                tmp*=-1        
-        if tmp==1:
-            t0, t1 = t1, t0
-            x0, x1 = x1, x0
-            y0, y1 = y1, y0
-            z0, z1 = z1, z0
-
-        # using glTexCoord* is the same as glMultiTexCoord*(GL_TEXTURE0)
-        # Therefore we need to bind the base texture to 0.
-        
-        # draw. So we draw the six planes of the cube (well not a cube,
-        # a 3d rectangle thingy). The inside is only rendered if the 
-        # vertex is facing front, so only 3 planes are rendered at a        
-        # time...                
-        
-        tex_coord, ver_coord = vvt.points.Pointset(3), vvt.points.Pointset(3)
-        indices = [0,1,2,3, 4,5,6,7, 3,2,6,5, 0,4,7,1, 0,3,5,4, 1,7,6,2]
-        
-        # bottom
-        tex_coord.Append((t0,t0,t0)); ver_coord.Append((x0, y0, z0)) # 0
-        tex_coord.Append((t1,t0,t0)); ver_coord.Append((x1, y0, z0)) # 1
-        tex_coord.Append((t1,t1,t0)); ver_coord.Append((x1, y1, z0)) # 2
-        tex_coord.Append((t0,t1,t0)); ver_coord.Append((x0, y1, z0)) # 3
-        # top
-        tex_coord.Append((t0,t0,t1)); ver_coord.Append((x0, y0, z1)) # 4    
-        tex_coord.Append((t0,t1,t1)); ver_coord.Append((x0, y1, z1)) # 5
-        tex_coord.Append((t1,t1,t1)); ver_coord.Append((x1, y1, z1)) # 6
-        tex_coord.Append((t1,t0,t1)); ver_coord.Append((x1, y0, z1)) # 7
-        
-        # Store quads
-        self._quads[tex_id] = (tex_coord, ver_coord, np.array(indices,dtype=np.uint8))
-
-def visvis_plot(vp):
-    """
-    This function accepts a volume rendering object, which it then tosses into
-    visvis for plotting.
-    """
-        
-    vp.partition_grids()
-    gs = vp.bricks
-
-    mi = min((g.my_data[0].min() for g in gs))
-    ma = max((g.my_data[0].max() for g in gs))
-
-    texes = []
-
-    ax = vv.gca()
-
-    for g in gs:
-        ss = ((g.RightEdge - g.LeftEdge) / (np.array(g.my_data[0].shape)-1)).tolist()
-        origin = g.LeftEdge.astype("float32").tolist()
-        dd = (g.my_data[0].astype("float32") - mi)/(ma - mi)
-        dd = np.clip(dd, 0.0, 1.0)
-        print (ss)
-        texes.append(vv.Aarray(dd, origin = origin, sampling = ss))
-
-    mtex = MultipleTexture(ax, texes, global_size=vp.ds.domain_dimensions)
-
-    ax.daspectAuto = False
-    ax.SetLimits()
-    ax.bgcolor = (0,0,0)
-
-    # set camera
-    ax.cameraType = '3d'
-
-    # done
-    ax.Draw()
-
-    return mtex, ax


https://bitbucket.org/yt_analysis/yt/commits/242969a4d535/
Changeset:   242969a4d535
Branch:      yt
User:        ngoldbaum
Date:        2015-08-17 17:14:56+00:00
Summary:     Removing yt/visualization/volume_rendering/camera_path.py

This removes camera_path.py, which was added back in 2012 by John Wise
(f6cc8e9297e8). It is untested, is not used elsewhere in yt, and is not exposed
in the public API.
Affected #:  1 file

diff -r db16b2c87538ce46b4c5c62fda1ac23313781f5f -r 242969a4d53536f127a0dadba48dd300158d5f70 yt/visualization/volume_rendering/camera_path.py
--- a/yt/visualization/volume_rendering/camera_path.py
+++ /dev/null
@@ -1,331 +0,0 @@
-"""
-Create smooth camera paths from keyframes.
-
-
-
-"""
-from __future__ import print_function
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-import random
-import numpy as np
-from .create_spline import create_spline
-
-class Keyframes(object):
-    def __init__(self, x, y, z=None, north_vectors=None, up_vectors=None,
-                 times=None, niter=50000, init_temp=10.0, alpha=0.999,
-                 fixed_start=False):
-        r"""Keyframes for camera path generation.
-
-        From a set of keyframes with position and optional up and
-        north vectors, an interpolated camera path is generated.
-
-        Parameters
-        ----------
-        x : array_like
-            The x positions of the keyframes
-        y : array_like
-            The y positions of the keyframes
-        z : array_like, optional
-            The z positions of the keyframes. Default: 0.0
-        north_vectors : array_like, optional
-            The north vectors of the keyframes. Default: None
-        up_vectors : array_like, optional
-            The up vectors of the keyframes. Default: None
-        times : array_like, optional
-            The times of the keyframes. Default: arange(N)
-        niter : integer, optional
-            Maximum number of iterations to find solution. Default: 50000
-        init_temp : float, optional
-            Intital temperature for simulated annealing when finding a
-            solution.  Lower initial temperatures result in an initial solution
-            in first several iterations that changes more rapidly. Default: 10.0
-        alpha : float, optional
-            Exponent in cooling function in simulated annealing.  Must be < 1.
-            In each iteration, the temperature_new = temperature_old * alpha.
-            Default: 0.999
-        fixed_start: boolean, optional
-            If true, the first point never changes when searching for shortest
-            path.  Default: False
-
-        Examples
-        --------
-
-        >>> import numpy as np
-        >>> import matplotlib.pyplot as plt
-        >>> from yt.visualization.volume_rendering.camera_path import *
-
-        # Make a camera path from 10 random (x,y,z) keyframes
-        >>> data = np.random.random.((10,3))
-        >>> kf = Keyframes(data[:,0], data[:,1], data[:,2])
-        >>> path = kf.create_path(250, shortest_path=False)
-
-        # Plot the keyframes in the x-y plane and camera path
-        plt.plot(kf.pos[:,0], kf.pos[:,1], 'ko')
-        plt.plot(path['position'][:,0], path['position'][:,1])
-        plt.savefig('path.png')
-        """
-        Nx = len(x)
-        Ny = len(y)
-        if z != None:
-            Nz = len(z)
-            ndims = 3
-        else:
-            Nz = 1
-            ndims = 2
-        if Nx*Ny*Nz != Nx**ndims:
-            print("Need Nx (%d) == Ny (%d) == Nz (%d)" % (Nx, Ny, Nz))
-            sys.exit()
-        self.nframes = Nx
-        self.pos = np.zeros((Nx,3))
-        self.pos[:,0] = x
-        self.pos[:,1] = y
-        if z != None:
-            self.pos[:,2] = z
-        else:
-            self.pos[:,2] = 0.0
-        self.north_vectors = north_vectors
-        self.up_vectors = up_vectors
-        if times == None:
-            self.times = np.arange(self.nframes)
-        else:
-            self.times = times
-        self.cartesian_matrix()
-        self.setup_tsp(niter, init_temp, alpha, fixed_start)
-
-    def setup_tsp(self, niter=50000, init_temp=10.0, alpha=0.999,
-                  fixed_start=False):
-        r"""Setup parameters for Travelling Salesman Problem.
-
-        Parameters
-        ----------
-        niter : integer, optional
-            Maximum number of iterations to find solution. Default: 50000
-        init_temp : float, optional
-            Intital temperature for simulated annealing when finding a
-            solution.  Lower initial temperatures result in an initial solution
-            in first several iterations that changes more rapidly. Default: 10.0
-        alpha : float, optional
-            Exponent in cooling function in simulated annealing.  Must be < 1.
-            In each iteration, the temperature_new = temperature_old * alpha.
-            Default: 0.999
-        fixed_start: boolean, optional
-            If true, the first point never changes when searching for shortest
-            path.  Default: False
-        """
-        # randomize tour
-        self.tour = range(self.nframes)
-        np.random.shuffle(self.tour)
-        if fixed_start:
-            first = self.tour.index(0)
-            self.tour[0], self.tour[first] = self.tour[first], self.tour[0]
-        self.max_iterations = niter
-        self.initial_temp = init_temp
-        self.alpha = alpha
-        self.fixed_start = fixed_start
-        self.best_score = None
-        self.best = None
-
-    def set_times(self, times):
-        self.times = times
-        
-    def rand_seq(self):
-        r"""
-        Generates values in random order, equivlanet to using shuffle
-        in random without generation all values at once.
-        """
-        values = range(self.nframes)
-        for i in range(self.nframes):
-            # pick a random index into remaining values
-            j = i + int(random.random() * (self.nframes-i))
-            # swap the values
-            values[j], values[i] = values[i], values[j]
-            # return the swapped value
-            yield values[i]
-
-    def all_pairs(self):
-        r"""
-        Generates all (i,j) pairs for (i,j) for 0-size
-        """
-        for i in self.rand_seq():
-            for j in self.rand_seq():
-                yield (i,j)
-    
-    def reversed_sections(self, tour):
-        r"""
-        Generator to return all possible variations where a section
-        between two cities are swapped.
-        """
-        for i,j in self.all_pairs():
-            if i == j: continue
-            copy = tour[:]
-            if i < j:
-                copy[i:j+1] = reversed(tour[i:j+1])
-            else:
-                copy[i+1:] = reversed(tour[:j])
-                copy[:j] = reversed(tour[i+1:])
-            if self.fixed_start:
-                ind = copy.index(0)
-                copy[0], copy[ind] = copy[ind], copy[0]
-            if copy != tour: # no point return the same tour
-                yield copy
-
-    def cartesian_matrix(self):
-        r"""
-        Create a distance matrix for the city coords that uses
-        straight line distance
-        """
-        self.dist_matrix = np.zeros((self.nframes, self.nframes))
-        xmat = np.zeros((self.nframes, self.nframes))
-        xmat[:,:] = self.pos[:,0]
-        dx = xmat - xmat.T
-        ymat = np.zeros((self.nframes, self.nframes))
-        ymat[:,:] = self.pos[:,1]
-        dy = ymat - ymat.T
-        zmat = np.zeros((self.nframes, self.nframes))
-        zmat[:,:] = self.pos[:,2]
-        dz = zmat - zmat.T
-        self.dist_matrix = np.sqrt(dx*dx + dy*dy + dz*dz)
-
-    def tour_length(self, tour):
-        r"""
-        Calculate the total length of the tour based on the distance
-        matrix
-        """
-        total = 0
-        num_cities = len(tour)
-        for i in range(num_cities):
-            j = (i+1) % num_cities
-            city_i = tour[i]
-            city_j = tour[j]
-            total += self.dist_matrix[city_i, city_j]
-        return -total
-
-    def cooling(self):
-        T = self.initial_temp
-        while True:
-            yield T
-            T = self.alpha * T
-
-    def prob(self, prev, next, temperature):
-        if next > prev:
-            return 1.0
-        else:
-            return np.exp( -abs(next-prev) / temperature )
-
-    def get_shortest_path(self):
-        r"""Determine shortest path between all keyframes.
-
-        Parameters
-        ----------
-        None.
-        """
-        self.setup_tsp(niter, init_temp, alpha, fixed_start)
-        num_eval = 1
-        cooling_schedule = self.cooling()
-        current = self.tour
-        current_score = self.tour_length(current)
-        for temperature in cooling_schedule:
-            done = False
-            # Examine moves around the current position
-            for next in self.reversed_sections(current):
-                if num_eval >= self.max_iterations:
-                    done = True
-                    break
-                next_score = self.tour_length(next)
-                num_eval += 1
-
-                # Anneal.  Accept new solution if a random number is
-                # greater than our "probability".
-                p = self.prob(current_score, next_score, temperature)
-                if random.random() < p:
-                    current = next
-                    self.current_score = next_score
-                    if self.current_score > self.best_score:
-                        #print num_eval, self.current_score, self.best_score, current
-                        self.best_score = self.current_score
-                        self.best = current
-                    break
-
-            if done:
-                break
-        self.pos = self.pos[self.tour,:]
-        if self.north_vectors != None:
-            self.north_vectors = self.north_vectors[self.tour]
-        if self.up_vectors != None:
-            self.up_vectors = self.up_vectors[self.tour]
-
-    def create_path(self, npoints, path_time=None, tension=0.5, shortest_path=False):
-        r"""Create a interpolated camera path from keyframes.
-
-        Parameters
-        ----------
-        npoints : integer
-            Number of points to interpolate from keyframes
-        path_time : array_like, optional
-            Times of interpolated points.  Default: Linearly spaced
-        tension : float, optional
-            Controls how sharp of a curve the spline takes.  A higher tension
-            allows for more sharp turns.  Default: 0.5
-        shortest_path : boolean, optional
-            If true, estimate the shortest path between the keyframes.
-            Default: False
-
-        Returns
-        -------
-        path : dict
-            Dictionary (time, position, north_vectors, up_vectors) of camera
-            path.  Also saved to self.path.
-        """
-        self.npoints = npoints
-        self.path = {"time": np.zeros(npoints),
-                     "position": np.zeros((npoints, 3)),
-                     "north_vectors": np.zeros((npoints,3)),
-                     "up_vectors": np.zeros((npoints,3))}
-        if shortest_path:
-            self.get_shortest_path()
-        if path_time == None:
-            path_time = np.linspace(0, self.nframes, npoints)
-        self.path["time"] = path_time
-        for dim in range(3):
-            self.path["position"][:,dim] = create_spline(self.times, self.pos[:,dim],
-                                                         path_time, tension=tension)
-            if self.north_vectors != None:
-                self.path["north_vectors"][:,dim] = \
-                    create_spline(self.times, self.north_vectors[:,dim],
-                                  path_time, tension=tension)
-            if self.up_vectors != None:
-                self.path["up_vectors"][:,dim] = \
-                    create_spline(self.times, self.up_vectors[:,dim],
-                                  path_time, tension=tension)
-        return self.path
-
-    def write_path(self, filename="path.dat"):
-        r"""Writes camera path to ASCII file
-
-        Parameters
-        ----------
-        filename : string, optional
-            Filename containing the camera path.  Default: path.dat
-        """
-        fp = open(filename, "w")
-        fp.write("#%11s %12s %12s %12s %12s %12s %12s %12s %12s\n" %
-                 ("x", "y", "z", "north_x", "north_y", "north_z",
-                  "up_x", "up_y", "up_z"))
-        for i in range(self.npoints):
-            fp.write("%.12f %.12f %.12f %.12f %.12f %.12f %.12f %.12f %.12f\n" %
-                     (self.path["position"][i,0], self.path["position"][i,1],
-                      self.path["position"][i,2], 
-                      self.path["north_vectors"][i,0], self.path["north_vectors"][i,1],
-                      self.path["north_vectors"][i,2], 
-                      self.path["up_vectors"][i,0], self.path["up_vectors"][i,1],
-                      self.path["up_vectors"][i,2]))
-        fp.close()
-


https://bitbucket.org/yt_analysis/yt/commits/e0d9183ff5ef/
Changeset:   e0d9183ff5ef
Branch:      yt
User:        ngoldbaum
Date:        2015-08-17 17:15:36+00:00
Summary:     Linting the rest of yt/visualization/volume_rendering
Affected #:  4 files

diff -r 242969a4d53536f127a0dadba48dd300158d5f70 -r e0d9183ff5ef02e3b2e29ffca2b69f8676f8c6e3 yt/visualization/volume_rendering/create_spline.py
--- a/yt/visualization/volume_rendering/create_spline.py
+++ b/yt/visualization/volume_rendering/create_spline.py
@@ -15,6 +15,7 @@
 #-----------------------------------------------------------------------------
 
 import numpy as np
+import sys
 
 def create_spline(old_x, old_y, new_x, tension=0.5, sorted=False):
     """

diff -r 242969a4d53536f127a0dadba48dd300158d5f70 -r e0d9183ff5ef02e3b2e29ffca2b69f8676f8c6e3 yt/visualization/volume_rendering/image_handling.py
--- a/yt/visualization/volume_rendering/image_handling.py
+++ b/yt/visualization/volume_rendering/image_handling.py
@@ -15,7 +15,7 @@
 import h5py
 import numpy as np
 
-from yt.funcs import *
+from yt.funcs import mylog
 
 def export_rgba(image, fn, h5=True, fits=False, ):
     """

diff -r 242969a4d53536f127a0dadba48dd300158d5f70 -r e0d9183ff5ef02e3b2e29ffca2b69f8676f8c6e3 yt/visualization/volume_rendering/setup.py
--- a/yt/visualization/volume_rendering/setup.py
+++ b/yt/visualization/volume_rendering/setup.py
@@ -1,10 +1,4 @@
 #!/usr/bin/env python
-import setuptools
-import os
-import sys
-import os.path
-
-#os.system("cython -a yt/extensions/volume_rendering/VolumeIntegrator.pyx")
 
 
 def configuration(parent_package='', top_path=None):

diff -r 242969a4d53536f127a0dadba48dd300158d5f70 -r e0d9183ff5ef02e3b2e29ffca2b69f8676f8c6e3 yt/visualization/volume_rendering/transfer_functions.py
--- a/yt/visualization/volume_rendering/transfer_functions.py
+++ b/yt/visualization/volume_rendering/transfer_functions.py
@@ -17,9 +17,11 @@
 import numpy as np
 from matplotlib.cm import get_cmap
 
-from yt.funcs import *
+from yt.funcs import \
+    mylog, ensure_list
 
-from yt.utilities.physical_constants import *
+from yt.utilities.physical_constants import \
+    clight, hcgs, kboltz
 
 class TransferFunction(object):
     r"""A transfer function governs the transmission of emission and
@@ -187,7 +189,9 @@
         >>> tf.add_gaussian(-9.0, 0.01, 1.0)
         >>> tf.plot("sample.png")
         """
-        import matplotlib;matplotlib.use("Agg");import pylab
+        import matplotlib
+        matplotlib.use("Agg")
+        import pylab
         pylab.clf()
         pylab.plot(self.x, self.y, 'xk-')
         pylab.xlim(*self.x_bounds)
@@ -209,7 +213,7 @@
         >>> tf.add_gaussian(-9.0, 0.01, 1.0)
         >>> tf.show()
         """
-        import matplotlib;import pylab
+        import pylab
         pylab.clf()
         pylab.plot(self.x, self.y, 'xk-')
         pylab.xlim(*self.x_bounds)
@@ -576,7 +580,7 @@
         ax.yaxis.set_ticks(xticks)
         def x_format(x, pos):
             val = x * (self.alpha.x[-1] - self.alpha.x[0]) / (self.alpha.x.size-1) + self.alpha.x[0]
-            if label_fmt == None:
+            if label_fmt is None:
                 if abs(val) < 1.e-3 or abs(val) > 1.e4:
                     e = np.floor(np.log10(abs(val)))
                     return r"${:.2f}\times 10^{:d}$".format(val/10.0**e, int(e))
@@ -849,7 +853,8 @@
             scat = (johnson_filters[f]["Lchar"]**-4 / mscat)*anorm
             tf = TransferFunction(rho_bounds)
             mylog.debug("Adding: %s with relative scattering %s" % (f, scat))
-            tf.y *= 0.0; tf.y += scat
+            tf.y *= 0.0
+            tf.y += scat
             self.add_field_table(tf, 1, weight_field_id = 1)
             self.link_channels(i+3, i+3)
 


https://bitbucket.org/yt_analysis/yt/commits/20eb1a608723/
Changeset:   20eb1a608723
Branch:      yt
User:        ngoldbaum
Date:        2015-08-17 18:57:46+00:00
Summary:     Linting yt/visualization/fixed_resolution.py
Affected #:  1 file

diff -r e0d9183ff5ef02e3b2e29ffca2b69f8676f8c6e3 -r 20eb1a608723e5b6d5339e8e2ee89242a1cbe435 yt/visualization/fixed_resolution.py
--- a/yt/visualization/fixed_resolution.py
+++ b/yt/visualization/fixed_resolution.py
@@ -13,7 +13,7 @@
 # The full license is in the file COPYING.txt, distributed with this software.
 #-----------------------------------------------------------------------------
 
-from yt.funcs import *
+from yt.funcs import mylog
 from yt.units.unit_object import Unit
 from .volume_rendering.api import off_axis_projection
 from .fixed_resolution_filters import apply_filter, filter_registry
@@ -27,6 +27,7 @@
 import numpy as np
 import weakref
 import re
+import types
 
 class FixedResolutionBuffer(object):
     r"""
@@ -160,7 +161,7 @@
     def _is_ion( self, fname ):
         p = re.compile("_p[0-9]+_")
         result = False
-        if p.search( fname ) != None:
+        if p.search( fname ) is not None:
             result = True
         return result
 
@@ -173,7 +174,7 @@
 
         p = re.compile("_p[0-9]+_")
         m = p.search( fname )
-        if m != None:
+        if m is not None:
             pstr = m.string[m.start()+1:m.end()-1]
             segments = fname.split("_")
             for i,s in enumerate(segments):


https://bitbucket.org/yt_analysis/yt/commits/239c282cf88a/
Changeset:   239c282cf88a
Branch:      yt
User:        ngoldbaum
Date:        2015-08-17 19:00:19+00:00
Summary:     Linting yt/visualization/image_writer.py
Affected #:  1 file

diff -r 20eb1a608723e5b6d5339e8e2ee89242a1cbe435 -r 239c282cf88a5382be8a3dfac4966ab8c003aca9 yt/visualization/image_writer.py
--- a/yt/visualization/image_writer.py
+++ b/yt/visualization/image_writer.py
@@ -13,12 +13,10 @@
 # The full license is in the file COPYING.txt, distributed with this software.
 #-----------------------------------------------------------------------------
 
-import types
-import imp
-import os
 import numpy as np
 
-from yt.funcs import *
+from yt.funcs import mylog, get_image_suffix
+from yt.units.yt_array import YTQuantity
 from yt.utilities.exceptions import YTNotInsideNotebook
 from .color_maps import mcm
 from . import _colormap_data as cmd
@@ -277,7 +275,7 @@
                 cmap = bmap.get_mpl_colormap(N=cmap_name[2])
             else:
                 cmap = mcm.get_cmap(cmap_name)
-            dummy = cmap(0.0)
+            cmap(0.0)
             lut = cmap._lut.T
         except ValueError:
             print("Your color map was not found in either the extracted" +\


https://bitbucket.org/yt_analysis/yt/commits/1b2e76d48c69/
Changeset:   1b2e76d48c69
Branch:      yt
User:        ngoldbaum
Date:        2015-08-17 19:08:16+00:00
Summary:     Linting yt/visualization/plot_modifications.py
Affected #:  1 file

diff -r 239c282cf88a5382be8a3dfac4966ab8c003aca9 -r 1b2e76d48c699b82db3cb3e84af17f9505ed3ee6 yt/visualization/plot_modifications.py
--- a/yt/visualization/plot_modifications.py
+++ b/yt/visualization/plot_modifications.py
@@ -5,9 +5,6 @@
 
 
 """
-from __future__ import absolute_import
-from yt.extern.six import string_types
-
 #-----------------------------------------------------------------------------
 # Copyright (c) 2013, yt Development Team.
 #
@@ -16,8 +13,12 @@
 # The full license is in the file COPYING.txt, distributed with this software.
 #-----------------------------------------------------------------------------
 
+from __future__ import absolute_import
+
+import warnings
+
+import matplotlib
 import numpy as np
-import h5py
 
 from distutils.version import LooseVersion
 
@@ -25,19 +26,14 @@
 from matplotlib.colors import colorConverter
 from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
 
-from yt.funcs import *
+from yt.funcs import \
+    mylog, iterable
 from yt.extern.six import add_metaclass
-from ._mpl_imports import *
-from yt.utilities.physical_constants import \
-    sec_per_Gyr, sec_per_Myr, \
-    sec_per_kyr, sec_per_year, \
-    sec_per_day, sec_per_hr
 from yt.units.yt_array import YTQuantity, YTArray
 from yt.visualization.image_writer import apply_colormap
 from yt.utilities.lib.geometry_utils import triangle_plane_intersect
 from yt.analysis_modules.cosmological_observation.light_ray.light_ray \
-     import periodic_ray
-import warnings
+    import periodic_ray
 
 from . import _MPL
 
@@ -113,13 +109,11 @@
 
         x0 = np.array(np.tile(plot.xlim[0],ncoord))
         x1 = np.array(np.tile(plot.xlim[1],ncoord))
-        x2 = np.array([0, 1])
         xx0 = np.tile(plot._axes.get_xlim()[0],ncoord)
         xx1 = np.tile(plot._axes.get_xlim()[1],ncoord)
 
         y0 = np.array(np.tile(plot.ylim[0],ncoord))
         y1 = np.array(np.tile(plot.ylim[1],ncoord))
-        y2 = np.array([0, 1])
         yy0 = np.tile(plot._axes.get_ylim()[0],ncoord)
         yy1 = np.tile(plot._axes.get_ylim()[1],ncoord)
 
@@ -229,7 +223,7 @@
         # For each label, set the font properties and color to the figure
         # defaults if not already set in the callback itself
         for label in labels:
-            if plot.font_color is not None and not 'color' in kwargs:
+            if plot.font_color is not None and 'color' not in kwargs:
                 label.set_color(plot.font_color)
             label.set_fontproperties(local_font_properties)
 
@@ -370,7 +364,7 @@
                              int(nx), int(ny),
                              (x0, x1, y0, y1), 0, # bounds, antialias
                              (period_x, period_y), periodic,
-                           ).transpose()
+                             ).transpose()
         pixY = _MPL.Pixelize(plot.data['px'],
                              plot.data['py'],
                              plot.data['pdx'],
@@ -379,7 +373,7 @@
                              int(nx), int(ny),
                              (x0, x1, y0, y1), 0, # bounds, antialias
                              (period_x, period_y), periodic,
-                           ).transpose()
+                             ).transpose()
         X,Y = np.meshgrid(np.linspace(xx0,xx1,nx,endpoint=True),
                           np.linspace(yy0,yy1,ny,endpoint=True))
         if self.normalize:


https://bitbucket.org/yt_analysis/yt/commits/5f5198bff432/
Changeset:   5f5198bff432
Branch:      yt
User:        ngoldbaum
Date:        2015-08-17 19:10:45+00:00
Summary:     Removing easy_plots.py

This was originally added in 2010 and has not been updated since. It is not used
elsewhere in yt and is not present in the public API.
Affected #:  1 file

diff -r 1b2e76d48c699b82db3cb3e84af17f9505ed3ee6 -r 5f5198bff43298c3c15c20f7328ae84666d3a231 yt/visualization/easy_plots.py
--- a/yt/visualization/easy_plots.py
+++ /dev/null
@@ -1,61 +0,0 @@
-"""
-Easy plotting.
-
-
-
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-from ._mpl_imports import *
-from yt.data_objects.profiles import BinnedProfile1D
-
-plot_type_registry = {}
-
-class EasyPlot(object):
-    class __metaclass__(type):
-        def __init__(cls, name, b, d):
-            type.__init__(cls, name, b, d)
-            if hasattr(cls, "_type_name"):
-                plot_type_registry[cls._type_name] = cls
-
-    def __init__(self):
-        pass
-
-    def save(self, fn):
-        canvas = FigureCanvasAgg(self.figure)
-        canvas.print_figure(fn)
-
-class EasyPDFPlot(EasyPlot):
-    _type_name = "PDF"
-
-    def __init__(self, data_source, x_field, x_log = True,
-                 n_bins = 128, y_log = True,
-                 plot_args = None,
-                 figure_args = None):
-        if plot_args is None: plot_args = {}
-        if figure_args is None: figure_args = {}
-        self.x_field = x_field
-        self.data_source = data_source
-        # Now we just make the plot
-        x_min, x_max = self.data_source.quantities["Extrema"](
-                x_field, non_zero = x_log)[0]
-        self.profile = BinnedProfile1D(self.data_source,
-            n_bins, self.x_field, x_min, x_max, x_log)
-        self.profile.add_fields(["CellMassMsun"], weight=None)
-        self.profile["CellMassMsun"] /= self.profile["CellMassMsun"].sum()
-        self.figure = matplotlib.figure.Figure(**figure_args)
-        self.axes = self.figure.add_subplot(1,1,1)
-        if y_log and x_log: f = self.axes.loglog
-        elif y_log: f = self.axes.semilogy
-        elif x_log: f = self.axes.semilogx
-        else: f = self.axes.plot
-        self.plot = f(self.profile[x_field], self.profile["CellMassMsun"],
-                      **plot_args)
-        self.axes.set_xlabel(data_source.ds.field_info[x_field].get_label())


https://bitbucket.org/yt_analysis/yt/commits/cb1242b8e37a/
Changeset:   cb1242b8e37a
Branch:      yt
User:        ngoldbaum
Date:        2015-08-17 19:25:54+00:00
Summary:     Removing pan_and_scan_widget.py

This has not been updated since 2010, is not part of the public API, and depends
on outside packages in the Enthought ecosystem that we do not depend on
elsewhere.
Affected #:  1 file

diff -r 5f5198bff43298c3c15c20f7328ae84666d3a231 -r cb1242b8e37af8b1dba9199e50b51da970cbe604 yt/visualization/image_panner/pan_and_scan_widget.py
--- a/yt/visualization/image_panner/pan_and_scan_widget.py
+++ /dev/null
@@ -1,324 +0,0 @@
-"""
-
-
-"""
-from __future__ import print_function
-from __future__ import absolute_import
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-# Major library imports
-from .vm_panner import VariableMeshPanner
-from numpy import linspace, meshgrid, pi, sin, mgrid, zeros
-
-# Enthought library imports
-from enthought.enable.api import Component, ComponentEditor, Window
-from enthought.traits.api import HasTraits, Instance, Button, Any, Callable, \
-        on_trait_change, Bool, DelegatesTo, List, Enum, Int, Property, Str, \
-        cached_property
-from enthought.traits.ui.api import \
-        Group, View, Item, VGroup, InstanceEditor
-
-# Chaco imports
-from enthought.chaco.api import ArrayPlotData, jet, Plot, HPlotContainer, \
-        ColorBar, DataRange1D, DataRange2D, LinearMapper, ImageData, \
-        CMapImagePlot, OverlayPlotContainer
-from enthought.chaco.tools.api import PanTool, ZoomTool, RangeSelection, \
-        RangeSelectionOverlay, RangeSelection
-from enthought.chaco.tools.image_inspector_tool import ImageInspectorTool, \
-     ImageInspectorOverlay
-
-if not hasattr(DataRange2D, "_subranges_updated"):
-    print ("You'll need to add _subranges updated to enthought/chaco/data_range_2d.py")
-    print ('Add this at the correct indentation level:')
-    print ()
-    print ('    @on_trait_change("_xrange.updated,_yrange.updated")')
-    print ('    def _subranges_updated(self):')
-    print ('        self.updated = True')
-    print ()
-    raise RuntimeError
-
-# We like the algae colormap; for now we re-implement it here.
-
-from enthought.chaco.api import \
-    ColorMapper, \
-    color_map_functions, color_map_dict, color_map_name_dict
-
-def algae(range, **traits):
-    _data = {'red':   ((0.0, 80/256., 80/256.),
-                       (0.2, 0.0, 0.0),
-                       (0.4, 0.0, 0.0),
-                       (0.6, 256/256., 256/256.),
-                       (0.95, 256/256., 256/256.),
-                       (1.0, 150/256., 150/256.)),
-             'green': ((0.0, 0/256., 0/256.),
-                       (0.2, 0/256., 0/256.),
-                       (0.4, 130/256., 130/256.),
-                       (0.6, 256/256., 256/256.),
-                       (1.0, 0.0, 0.0)),
-             'blue':  ((0.0, 80/256., 80/256.),
-                       (0.2, 220/256., 220/256.),
-                       (0.4, 0.0, 0.0),
-                       (0.6, 20/256., 20/256.),
-                       (1.0, 0.0, 0.0))}
-    return ColorMapper.from_segment_map(_data, range=range, **traits)
-color_map_functions.append(algae)
-color_map_dict[algae] = "algae"
-color_map_name_dict["algae"] = algae
-
-class FunctionImageData(ImageData):
-    # The function to call with the low and high values of the range.
-    # It should return an array of values.
-    func = Callable
-
-    # A reference to a datarange
-    data_range = Instance(DataRange2D)
-
-    def __init__(self, **kw):
-        # Explicitly call the AbstractDataSource constructor because
-        # the ArrayDataSource ctor wants a data array
-        ImageData.__init__(self, **kw)
-        self.recalculate()
-
-    @on_trait_change('data_range.updated')
-    def recalculate(self):
-        if self.func is not None and self.data_range is not None:
-            newarray = self.func(self.data_range.low, self.data_range.high)
-            ImageData.set_data(self, newarray)
-        else:
-            self._data = zeros((512,512),dtype=float)
-
-    def set_data(self, *args, **kw):
-        raise RuntimeError("Cannot set numerical data on a FunctionDataSource")
-
-    def set_mask(self, mask):
-        raise NotImplementedError
-
-    def remove_mask(self):
-        raise NotImplementedError
-
-class ImagePixelizerHelper(object):
-    index = None
-    def __init__(self, panner, run_callbacks = False):
-        self.panner = panner
-        self.run_callbacks = run_callbacks
-
-    def __call__(self, low, high):
-        b = self.panner.set_low_high(low, high)
-        if self.run_callbacks:
-            self.panner._run_callbacks()
-        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
-
-class ZoomedPlotUpdater(object):
-    fid = None
-    def __init__(self, panner, zoom_factor=4):
-        """
-        Supply this an a viewport_callback argument to a panner if you want to
-        update a second panner in a smaller portion at higher resolution.  If
-        you then set the *fid* property, you can also have it update a
-        FunctionImageData datarange.  *panner* is the panner to update (not the
-        one this is a callback to) and *zoom_factor* is how much to zoom in by.
-        """
-        self.panner = panner
-        self.zoom_factor = zoom_factor
-
-    def __call__(self, xlim, ylim):
-        self.panner.xlim = xlim
-        self.panner.ylim = ylim
-        self.panner.zoom(self.zoom_factor)
-        nxlim = self.panner.xlim
-        nylim = self.panner.ylim
-        if self.fid is not None:
-            self.fid.data_range.set_bounds(
-                (nxlim[0], nylim[0]), (nxlim[1], nylim[1]))
-
-class VMImagePlot(HasTraits):
-    plot = Instance(Plot)
-    fid = Instance(FunctionImageData)
-    img_plot = Instance(CMapImagePlot)
-    panner = Instance(VariableMeshPanner)
-    helper = Instance(ImagePixelizerHelper)
-    fields = List
-
-    def __init__(self, *args, **kwargs):
-        super(VMImagePlot, self).__init__(**kwargs)
-        self.add_trait("field", Enum(*self.fields))
-        self.field = self.panner.field
-
-    def _plot_default(self):
-        pd = ArrayPlotData()
-        plot = Plot(pd, padding = 0)
-        self.fid._data = self.panner.buffer
-
-        pd.set_data("imagedata", self.fid)
-
-        img_plot = plot.img_plot("imagedata", colormap=algae,
-                                 interpolation='nearest',
-                                 xbounds=(0.0, 1.0),
-                                 ybounds=(0.0, 1.0))[0]
-        self.fid.data_range = plot.range2d
-        self.helper.index = img_plot.index
-        self.img_plot = img_plot
-        return plot
-
-    def _field_changed(self, old, new):
-        self.panner.field = new
-        self.fid.recalculate()
-
-    def _fid_default(self):
-        return FunctionImageData(func = self.helper)
-
-    def _helper_default(self):
-        return ImagePixelizerHelper(self.panner)
-
-    def _panner_changed(self, old, new):
-        index = self.helper.index
-        self.helper = ImagePixelizerHelper(new)
-        self.helper.index = index
-        self.fid.func = self.helper
-        self.fid.recalculate()
-
-    def _fields_default(self):
-        keys = []
-        for field in self.panner.source.keys():
-            if field not in ['px','py','pdx','pdy',
-                             'pz','pdz','weight_field']:
-                keys.append(field)
-        return keys
-
-class VariableMeshPannerView(HasTraits):
-
-    plot = Instance(Plot)
-    spawn_zoom = Button
-    vm_plot = Instance(VMImagePlot)
-    use_tools = Bool(True)
-    full_container = Instance(HPlotContainer)
-    container = Instance(OverlayPlotContainer)
-    
-    traits_view = View(
-                    Group(
-                        Item('full_container',
-                             editor=ComponentEditor(size=(512,512)), 
-                             show_label=False),
-                        Item('field', show_label=False),
-                        orientation = "vertical"),
-                    width = 800, height=800,
-                    resizable=True, title="Pan and Scan",
-                    )
-
-    def _vm_plot_default(self):
-        return VMImagePlot(panner=self.panner)
-    
-    def __init__(self, **kwargs):
-        super(VariableMeshPannerView, self).__init__(**kwargs)
-        # Create the plot
-        self.add_trait("field", DelegatesTo("vm_plot"))
-
-        plot = self.vm_plot.plot
-        img_plot = self.vm_plot.img_plot
-
-        if self.use_tools:
-            plot.tools.append(PanTool(img_plot))
-            zoom = ZoomTool(component=img_plot, tool_mode="box", always_on=False)
-            plot.overlays.append(zoom)
-            imgtool = ImageInspectorTool(img_plot)
-            img_plot.tools.append(imgtool)
-            overlay = ImageInspectorOverlay(component=img_plot, image_inspector=imgtool,
-                                            bgcolor="white", border_visible=True)
-            img_plot.overlays.append(overlay)
-
-
-        image_value_range = DataRange1D(self.vm_plot.fid)
-        cbar_index_mapper = LinearMapper(range=image_value_range)
-        self.colorbar = ColorBar(index_mapper=cbar_index_mapper,
-                                 plot=img_plot,
-                                 padding_right=40,
-                                 resizable='v',
-                                 width=30)
-
-        self.colorbar.tools.append(
-            PanTool(self.colorbar, constrain_direction="y", constrain=True))
-        zoom_overlay = ZoomTool(self.colorbar, axis="index", tool_mode="range",
-                                always_on=True, drag_button="right")
-        self.colorbar.overlays.append(zoom_overlay)
-
-        # create a range selection for the colorbar
-        range_selection = RangeSelection(component=self.colorbar)
-        self.colorbar.tools.append(range_selection)
-        self.colorbar.overlays.append(
-                RangeSelectionOverlay(component=self.colorbar,
-                                      border_color="white",
-                                      alpha=0.8, fill_color="lightgray"))
-
-        # we also want to the range selection to inform the cmap plot of
-        # the selection, so set that up as well
-        range_selection.listeners.append(img_plot)
-
-        self.full_container = HPlotContainer(padding=30)
-        self.container = OverlayPlotContainer(padding=0)
-        self.full_container.add(self.colorbar)
-        self.full_container.add(self.container)
-        self.container.add(self.vm_plot.plot)
-
-class OutputSelector(HasTraits):
-    outputs = List
-    main_plot = Instance(VariableMeshPannerView)
-    main_panner = Property(depends_on = "ds")
-    weight_field = Str("Density")
-
-    ds = Any
-    source = Any
-    axis = Int(0)
-
-    traits_view = View(VGroup(
-                        Item('output'),
-                        Item('main_plot'),
-                        )
-                      )
-
-    def __init__(self, **kwargs):
-        super(OutputSelector, self).__init__(**kwargs)
-        self.add_trait("output", Enum(*self.outputs))
-        self.output = self.outputs[-1]
-        self.main_plot
-
-    def _output_default(self):
-        return self.outputs[0]
-
-    def _output_changed(self, old, new):
-        # We get a string here
-        import yt.mods
-        self.ds = yt.mods.load(new, dataset_type="enzo_packed_3d")
-        self.source = yt.mods.projload(self.ds, self.axis, "Density")
-        self.main_panner.field = self.main_plot.vm_plot.field
-        self.main_plot.panner = self.main_plot.vm_plot.panner = \
-            self.main_plot.vm_plot.helper.panner = self.main_panner
-        self.main_plot.vm_plot.field = self.main_panner.field
-
-    def _main_plot_default(self):
-        vmpv = VariableMeshPannerView(panner = self.main_panner)
-        vmpv.vm_plot.helper.run_callbacks = True
-        return vmpv
-
-    @cached_property
-    def _get_main_panner(self):
-        return self.ds.image_panner(self.source, (512, 512), "Density")
-
-def pan_and_scan_directory(dir_name):
-    import glob, os
-    fns = [ fn[:-10] for fn in
-            glob.glob(os.path.join(dir_name, "**", "*.index")) ]
-    selector = OutputSelector(outputs = fns)
-    return selector


https://bitbucket.org/yt_analysis/yt/commits/f3b5bedfd1bb/
Changeset:   f3b5bedfd1bb
Branch:      yt
User:        ngoldbaum
Date:        2015-08-17 20:08:58+00:00
Summary:     Linting the image_panner
Affected #:  2 files

diff -r cb1242b8e37af8b1dba9199e50b51da970cbe604 -r f3b5bedfd1bb6fea299a2cda85d299b08b6c35c5 yt/visualization/image_panner/setup.py
--- a/yt/visualization/image_panner/setup.py
+++ b/yt/visualization/image_panner/setup.py
@@ -1,8 +1,4 @@
 #!/usr/bin/env python
-import setuptools
-import os
-import sys
-import os.path
 
 
 def configuration(parent_package='', top_path=None):

diff -r cb1242b8e37af8b1dba9199e50b51da970cbe604 -r f3b5bedfd1bb6fea299a2cda85d299b08b6c35c5 yt/visualization/image_panner/vm_panner.py
--- a/yt/visualization/image_panner/vm_panner.py
+++ b/yt/visualization/image_panner/vm_panner.py
@@ -11,15 +11,14 @@
 # The full license is in the file COPYING.txt, distributed with this software.
 #-----------------------------------------------------------------------------
 
+import base64
+
 import numpy as np
-import types, os
-from yt.data_objects.construction_data_containers import YTOverlapProjBase
-from yt.data_objects.selection_data_containers import YTSliceBase
 from yt.visualization.fixed_resolution import \
-    FixedResolutionBuffer, ObliqueFixedResolutionBuffer
+    FixedResolutionBuffer
 from yt.data_objects.data_containers import \
     data_object_registry
-from yt.funcs import *
+from yt.funcs import iterable
 
 class VariableMeshPanner(object):
     _buffer = None
@@ -235,7 +234,7 @@
         for w in self.windows: w.zoom(factor)
 
     def pan(self, deltas):
-        for w in self.windows: w.pan(factor)
+        for w in self.windows: w.pan(deltas)
 
     def pan_x(self, delta):
         for w in self.windows: w.pan_x(delta)
@@ -264,7 +263,9 @@
         """
         self.tile_id = tile_id
 
-        import matplotlib;matplotlib.use("Agg");import pylab
+        import matplotlib
+        matplotlib.use("Agg")
+        import pylab
         self.pylab = pylab
         self.pylab.clf()
         fig = pylab.gcf()
@@ -299,6 +300,4 @@
         to_plot = np.clip(to_plot, 0, 255)
         s = write_png_to_string(to_plot)
         response_body = "data:image/png;base64," + base64.encodestring(s)
-        tf.close()
         self.transport.append(response_body)
-


https://bitbucket.org/yt_analysis/yt/commits/fe8922e45b7e/
Changeset:   fe8922e45b7e
Branch:      yt
User:        ngoldbaum
Date:        2015-08-17 20:09:24+00:00
Summary:     Linting eps_writer.py
Affected #:  1 file

diff -r f3b5bedfd1bb6fea299a2cda85d299b08b6c35c5 -r fe8922e45b7e0337e1e2c93d977bcd975b3c1e2d yt/visualization/eps_writer.py
--- a/yt/visualization/eps_writer.py
+++ b/yt/visualization/eps_writer.py
@@ -22,7 +22,7 @@
 from yt.utilities.logger import ytLogger as mylog
 from .plot_window import PlotWindow
 from .profile_plotter import PhasePlot, ProfilePlot
-from yt.units.yt_array import YTArray, YTQuantity
+from yt.units.yt_array import YTQuantity
 from yt.units.unit_object import Unit
 
 def convert_frac_to_tex(string):
@@ -271,7 +271,7 @@
                           (width=psize[0], height=psize[1],
                            x=xaxis, y=yaxis, x2=xaxis2, y2=yaxis2,
                            xpos=pos[0], ypos=pos[1])
-            if xdata == None:
+            if xdata is None:
                 self.canvas.plot(blank_data)
             else:
                 data = pyx.graph.data.points(np.array([xdata, ydata]).T, x=1, y=2)
@@ -281,7 +281,7 @@
                    (width=psize[0], height=psize[1],
                     x=xaxis, y=yaxis, x2=xaxis2, y2=yaxis2,
                     xpos=pos[0], ypos=pos[1])
-            if xdata == None:
+            if xdata is None:
                 plot.plot(blank_data)
             else:
                 data = pyx.graph.data.points(np.array([xdata, ydata]).T, x=1, y=2)
@@ -322,7 +322,7 @@
         if isinstance(plot, PlotWindow):
             data = plot.frb
             width = plot.width[0]
-            if units == None:
+            if units is None:
                 units = plot.ds.get_smallest_appropriate_unit(width)
             width = width.in_units(str(units))
             xc = 0.5*(plot.xlim[0] + plot.xlim[1])
@@ -335,7 +335,7 @@
                 _xlabel = ""
                 _ylabel = ""
             else:
-                if xlabel != None:
+                if xlabel is not None:
                     _xlabel = xlabel
                 else:
                     if data.axis != 4:
@@ -344,7 +344,7 @@
                         _xlabel = '%s (%s)' % (x_name, units)
                     else:
                         _xlabel = 'x (%s)' % (units)
-                if ylabel != None:
+                if ylabel is not None:
                     _ylabel = ylabel
                 else:
                     if data.axis != 4:
@@ -353,7 +353,7 @@
                         _ylabel = '%s (%s)' % (y_name, units)
                     else:
                         _ylabel = 'y (%s)' % (units)
-            if tickcolor == None:
+            if tickcolor is None:
                 _tickcolor = pyx.color.cmyk.white
         elif isinstance(plot, ProfilePlot):
             subplot = plot.axes.values()[0]
@@ -390,17 +390,17 @@
                 _xlabel = ""
                 _ylabel = ""
             else:
-                if xlabel != None:
+                if xlabel is not None:
                     _xlabel = xlabel
                 else:
                     _xlabel = plot[k].axes.get_xlabel()
-                if ylabel != None:
+                if ylabel is not None:
                     _ylabel = ylabel
                 else:
                     _ylabel = plot[k].axes.get_ylabel()
                 _xlabel = pyxize_label(_xlabel)
                 _ylabel = pyxize_label(_ylabel)
-            if tickcolor == None:
+            if tickcolor is None:
                 _tickcolor = None
         elif isinstance(plot, np.ndarray):
             ax = plt.gca()
@@ -412,15 +412,15 @@
                 _xlabel = ""
                 _ylabel = ""
             else:
-                if xlabel != None:
+                if xlabel is not None:
                     _xlabel = xlabel
                 else:
                     _xlabel = ax.get_xlabel()
-                if ylabel != None:
+                if ylabel is not None:
                     _ylabel = ylabel
                 else:
                     _ylabel = ax.get_ylabel()
-            if tickcolor == None:
+            if tickcolor is None:
                 _tickcolor = None
         else:
             _xrange = plot._axes.get_xlim()
@@ -431,17 +431,17 @@
                 _xlabel = ""
                 _ylabel = ""
             else:
-                if xlabel != None:
+                if xlabel is not None:
                     _xlabel = xlabel
                 else:
                     _xlabel = plot._x_label
-                if ylabel != None:
+                if ylabel is not None:
                     _ylabel = ylabel
                 else:
                     _ylabel = plot._y_label
-            if tickcolor == None:
+            if tickcolor is None:
                 _tickcolor = None
-        if tickcolor != None:
+        if tickcolor is not None:
             _tickcolor = tickcolor
         self.axis_box(xrange=_xrange, yrange=_yrange, xlabel=_xlabel,
                       ylabel=_ylabel, tickcolor=_tickcolor, xlog=_xlog,
@@ -468,7 +468,7 @@
         >>> d.insert_image("image.jpg")
         >>> d.save_fig()
         """
-        if size != None:
+        if size is not None:
             width = size[0]*self.figsize[0]
             height = size[1]*self.figsize[1]
         else:
@@ -514,7 +514,7 @@
         if self.canvas is None:
             self.canvas = pyx.canvas.canvas()
         if isinstance(plot, (PlotWindow, PhasePlot)):
-            if field == None:
+            if field is None:
                 self.field = plot.plots.keys()[0]
                 mylog.warning("No field specified.  Choosing first field (%s)" % \
                               str(self.field))
@@ -529,11 +529,11 @@
         elif isinstance(plot, ProfilePlot):
             _p1 = plot.figures.items()[0][1]
         elif isinstance(plot, np.ndarray):
-            fig = plt.figure()
+            plt.figure()
             iplot = plt.figimage(plot)
-            _p1 =  iplot.figure
+            _p1 = iplot.figure
             _p1.set_size_inches(self.figsize[0], self.figsize[1])
-            ax = plt.gca();
+            ax = plt.gca()
             _p1.add_axes(ax)
         else:
             raise RuntimeError("Unknown plot type")
@@ -646,14 +646,13 @@
                                                  width=size[0], height=size[1]))
 
         if tickcolor is None:
-            c1 = pyx.graph.axis.painter.regular\
-                 (tickattrs=[pyx.color.cmyk.black])
-            c2 = pyx.graph.axis.painter.regular\
-                 (tickattrs=[pyx.color.cmyk.black], labelattrs=None)
+            c1 = pyx.graph.axis.painter.regular(tickattrs=[pyx.color.cmyk.black])
+            pyx.graph.axis.painter.regular(tickattrs=[pyx.color.cmyk.black],
+                                           labelattrs=None)
         else:
             c1 = pyx.graph.axis.painter.regular(tickattrs=[tickcolor])
-            c2 = pyx.graph.axis.painter.regular(tickattrs=[tickcolor],
-                                                labelattrs=None)
+            pyx.graph.axis.painter.regular(tickattrs=[tickcolor],
+                                           labelattrs=None)
         if log:
             yaxis = pyx.graph.axis.log(min=zrange[0],max=zrange[1],
                                        title=label, painter=c1)
@@ -715,18 +714,16 @@
         if isinstance(plot, ProfilePlot):
             raise RuntimeError("When using ProfilePlots you must either set yt_nocbar=True or provide colorbar flags so that the profiles don't have colorbars")
         _cmap = None
-        if field != None:
+        if field is not None:
             self.field = plot.data_source._determine_fields(field)[0]
         if isinstance(plot, (PlotWindow, PhasePlot)):
             _cmap = plot._colormaps[self.field]
         else:
-            if plot.cmap != None:
+            if plot.cmap is not None:
                 _cmap = plot.cmap.name
-        if _cmap == None:
+        if _cmap is None:
             _cmap = 'algae'
         if isinstance(plot, (PlotWindow, PhasePlot)):
-            proj = plot._plot_type.endswith("Projection") and \
-                plot.data_source.weight_field == None
             if isinstance(plot, PlotWindow):
                 try:
                     _zlabel = plot.frb[self.field].info["label"]
@@ -743,11 +740,11 @@
                 _zlabel = pyxize_label(plot.z_title)
             _zlabel = _zlabel.replace("_","\;")
             _zlog = plot.get_log(self.field)[self.field]
-            if plot.plots[self.field].zmin == None:
+            if plot.plots[self.field].zmin is None:
                 zmin = plot.plots[self.field].image._A.min()
             else:
                 zmin = plot.plots[self.field].zmin
-            if plot.plots[self.field].zmax == None:
+            if plot.plots[self.field].zmax is None:
                 zmax = plot.plots[self.field].image._A.max()
             else:
                 zmax = plot.plots[self.field].zmax
@@ -756,7 +753,7 @@
             _zlabel = plot._z_label.replace("_","\;")
             _zlog = plot._log_z
             _zrange = (plot.norm.vmin, plot.norm.vmax)
-        if cb_labels != None:  #Overrides deduced labels
+        if cb_labels is not None:  #Overrides deduced labels
             _zlabel = cb_labels.pop()
         self.colorbar(_cmap, zrange=_zrange, label=_zlabel, log=_zlog, **kwargs)
 
@@ -940,7 +937,7 @@
         tbox = self.canvas.text(self.figsize[0]*loc[0],
                                 self.figsize[1]*loc[1],
                                 text, [color, valign, halign] + text_opts)
-        if bgcolor != None:
+        if bgcolor is not None:
             tpath = tbox.bbox().enlarged(2*pyx.unit.x_pt).path()
             self.canvas.draw(tpath, [pyx.deco.filled([bgcolor]),
                                      pyx.deco.stroked()])
@@ -1060,10 +1057,10 @@
     """
     # Error check
     npanels = ncol*nrow
-    if(cb_labels != None):
+    if(cb_labels is not None):
         cb_labels.reverse()   #Because I pop the list
     
-    if images != None:
+    if images is not None:
         if len(images) != npanels:
             raise RuntimeError("Number of images (%d) doesn't match nrow(%d)"\
                                " x ncol(%d)." % (len(images), nrow, ncol))
@@ -1071,13 +1068,13 @@
     if yt_plots is None and images is None:
         raise RuntimeError("Must supply either yt_plots or image filenames.")
         return
-    if yt_plots != None and images != None:
+    if yt_plots is not None and images is not None:
         mylog.warning("Given both images and yt plots.  Ignoring images.")
-    if yt_plots != None:
+    if yt_plots is not None:
         _yt = True
     else:
         _yt = False
-    if fields == None:
+    if fields is None:
         fields = [None] * npanels
 
     # If no ranges or labels given and given only images, fill them in.
@@ -1118,27 +1115,27 @@
                 yaxis = 1
             else:
                 yaxis = -1
-            if xdata == None:
+            if xdata is None:
                 _xdata = None
             else:
                 _xdata = xdata[index]
-            if ydata == None:
+            if ydata is None:
                 _ydata = None
             else:
                 _ydata = ydata[index]
-            if xaxis_flags != None:
-                if xaxis_flags[index] != None:
+            if xaxis_flags is not None:
+                if xaxis_flags[index] is not None:
                     xaxis = xaxis_flags[index]
-            if yaxis_flags != None:
-                if yaxis_flags[index] != None:
+            if yaxis_flags is not None:
+                if yaxis_flags[index] is not None:
                     yaxis = yaxis_flags[index]
             if _yt:
                 this_plot._setup_plots()
-                if xlabels != None:
+                if xlabels is not None:
                     xlabel = xlabels[i]
                 else:
                     xlabel = None
-                if ylabels != None:
+                if ylabels is not None:
                     ylabel = ylabels[j]
                 else:
                     ylabel = None
@@ -1156,8 +1153,8 @@
                            xlabel=xlabels[i], ylabel=ylabels[j],
                            bare_axes=bare_axes, xaxis_side=xaxis, yaxis_side=yaxis,
                            xdata=_xdata, ydata=_ydata)
-            if titles != None:
-                if titles[index] != None:
+            if titles is not None:
+                if titles[index] is not None:
                     d.title_box(titles[index],
                                 loc=(i+0.05+i*margins[0]/figsize[0],
                                      j+0.98+j*margins[1]/figsize[1]))
@@ -1174,11 +1171,11 @@
         for i in range(ncol):
             xpos0 = i*(figsize[0] + margins[0])
             index = j*ncol + i
-            if (not _yt and colorbars != None) or (_yt and not yt_nocbar):
-                if cb_flags != None:
-                    if cb_flags[index] == False:
+            if (not _yt and colorbars is not None) or (_yt and not yt_nocbar):
+                if cb_flags is not None:
+                    if not cb_flags[index]:
                         continue
-                if cb_location == None:
+                if cb_location is None:
                     if ncol == 1:
                         orientation = "right"
                     elif i == 0:
@@ -1219,10 +1216,10 @@
                                   "No colorbar displayed." % orientation)
                     orientation = None  # Marker for interior plot
 
-                if orientation != None:
+                if orientation is not None:
                     if _yt:
                         # Set field if undefined
-                        if fields[index] == None:
+                        if fields[index] is None:
                             fields[index] = d.return_field(yt_plots[index])
                                               
                         d.colorbar_yt(yt_plots[index],
@@ -1240,7 +1237,7 @@
                                    pos=[xpos,ypos],
                                    shrink=shrink_cb)
 
-    if savefig != None:
+    if savefig is not None:
         d.save_fig(savefig, format=format)
 
     return d
@@ -1281,7 +1278,7 @@
     # Determine whether the plots are organized in a PlotWindow, or list 
     # of PlotWindows
     if isinstance(plots, (PlotWindow, PhasePlot)):
-        if fields == None:
+        if fields is None:
             fields = plots.fields
         if len(fields) < nrow*ncol:
             raise RuntimeError("Number of plots is less "\
@@ -1338,7 +1335,7 @@
     d.axis_box_yt(plot, bare_axes=bare_axes, **kwargs)
     if colorbar:
         d.colorbar_yt(plot, orientation=cb_orient)
-    if savefig != None:
+    if savefig is not None:
         d.save_fig(savefig, format=file_format)
     return d
 


https://bitbucket.org/yt_analysis/yt/commits/5eae409aaf54/
Changeset:   5eae409aaf54
Branch:      yt
User:        ngoldbaum
Date:        2015-08-17 20:22:45+00:00
Summary:     Linting the rest of the visualization module
Affected #:  5 files

diff -r fe8922e45b7e0337e1e2c93d977bcd975b3c1e2d -r 5eae409aaf5449b58b4da6778ae201f9bced82b5 yt/visualization/color_maps.py
--- a/yt/visualization/color_maps.py
+++ b/yt/visualization/color_maps.py
@@ -22,7 +22,7 @@
 
 def check_color(name):
     try:
-        ss = cc.colorConverter.to_rgb(name)
+        cc.colorConverter.to_rgb(name)
         return True
     except ValueError:
         return False

diff -r fe8922e45b7e0337e1e2c93d977bcd975b3c1e2d -r 5eae409aaf5449b58b4da6778ae201f9bced82b5 yt/visualization/plot_window.py
--- a/yt/visualization/plot_window.py
+++ b/yt/visualization/plot_window.py
@@ -48,8 +48,7 @@
 from yt.extern.six import string_types
 from yt.funcs import \
     mylog, iterable, ensure_list, \
-    fix_axis, validate_width_tuple, \
-    fix_unitary
+    fix_axis, fix_unitary
 from yt.units.unit_object import \
     Unit
 from yt.units.unit_registry import \
@@ -68,7 +67,6 @@
     Orientation
 from yt.utilities.exceptions import \
     YTUnitNotRecognized, \
-    YTInvalidWidthError, \
     YTCannotParseUnitDisplayName, \
     YTUnitConversionError, \
     YTPlotCallbackError
@@ -231,7 +229,7 @@
         super(PlotWindow, self).__init__(data_source, window_size, fontsize)
         self._set_window(bounds) # this automatically updates the data and plot
         self.origin = origin
-        if self.data_source.center is not None and oblique == False:
+        if self.data_source.center is not None and oblique is False:
             ax = self.data_source.axis
             xax = self.ds.coordinates.x_axis[ax]
             yax = self.ds.coordinates.y_axis[ax]

diff -r fe8922e45b7e0337e1e2c93d977bcd975b3c1e2d -r 5eae409aaf5449b58b4da6778ae201f9bced82b5 yt/visualization/profile_plotter.py
--- a/yt/visualization/profile_plotter.py
+++ b/yt/visualization/profile_plotter.py
@@ -20,28 +20,24 @@
 import base64
 import os
 
-from functools import wraps
 import matplotlib
 import numpy as np
 from io import BytesIO
 
 
 from .base_plot_types import ImagePlotMPL
-from yt.units.yt_array import YTArray
 from .plot_container import \
     ImagePlotContainer, \
     log_transform, linear_transform, get_log_minorticks, \
     validate_plot, invalidate_plot
 from yt.data_objects.profiles import \
-    create_profile, \
-    sanitize_field_tuple_keys
+    create_profile
 from yt.utilities.exceptions import \
     YTNotInsideNotebook
 from yt.utilities.logger import ytLogger as mylog
 from . import _mpl_imports as mpl
 from yt.funcs import \
     ensure_list, \
-    iterable, \
     get_image_suffix, \
     get_ipython_api_version
 

diff -r fe8922e45b7e0337e1e2c93d977bcd975b3c1e2d -r 5eae409aaf5449b58b4da6778ae201f9bced82b5 yt/visualization/setup.py
--- a/yt/visualization/setup.py
+++ b/yt/visualization/setup.py
@@ -1,5 +1,4 @@
 #!/usr/bin/env python
-import setuptools
 
 
 def configuration(parent_package='', top_path=None):

diff -r fe8922e45b7e0337e1e2c93d977bcd975b3c1e2d -r 5eae409aaf5449b58b4da6778ae201f9bced82b5 yt/visualization/streamlines.py
--- a/yt/visualization/streamlines.py
+++ b/yt/visualization/streamlines.py
@@ -15,7 +15,8 @@
 
 import numpy as np
 from yt.data_objects.construction_data_containers import YTStreamlineBase
-from yt.funcs import *
+from yt.funcs import get_pbar
+from yt.units.yt_array import YTArray
 from yt.utilities.parallel_tools.parallel_analysis_interface import \
     ParallelAnalysisInterface, parallel_passthrough
 from yt.utilities.amr_kdtree.api import AMRKDTree


https://bitbucket.org/yt_analysis/yt/commits/9888a4a65bfc/
Changeset:   9888a4a65bfc
Branch:      yt
User:        ngoldbaum
Date:        2015-08-17 20:23:24+00:00
Summary:     Linting the visualization tests
Affected #:  3 files

diff -r 5eae409aaf5449b58b4da6778ae201f9bced82b5 -r 9888a4a65bfc4ecddf7334f1086414ee3e08ec94 yt/visualization/tests/test_callbacks.py
--- a/yt/visualization/tests/test_callbacks.py
+++ b/yt/visualization/tests/test_callbacks.py
@@ -13,7 +13,9 @@
 #
 # The full license is in the file COPYING.txt, distributed with this software.
 #-----------------------------------------------------------------------------
-import os, tempfile, shutil
+import tempfile
+import shutil
+
 from yt.testing import \
     fake_amr_ds
 import yt.units as u

diff -r 5eae409aaf5449b58b4da6778ae201f9bced82b5 -r 9888a4a65bfc4ecddf7334f1086414ee3e08ec94 yt/visualization/tests/test_plotwindow.py
--- a/yt/visualization/tests/test_plotwindow.py
+++ b/yt/visualization/tests/test_plotwindow.py
@@ -288,11 +288,6 @@
         self._assert_05_075cm()
         assert_true(self.slc._axes_unit_names == ('cm', 'cm'))
 
-    def test_tuple_of_tuples_neq(self):
-        self.slc.set_width(((0.5, 'cm'), (0.0075, 'm')))
-        self._assert_05_075cm()
-        assert_true(self.slc._axes_unit_names == ('cm', 'm'))
-
 
 class TestPlotWindowSave(unittest.TestCase):
 

diff -r 5eae409aaf5449b58b4da6778ae201f9bced82b5 -r 9888a4a65bfc4ecddf7334f1086414ee3e08ec94 yt/visualization/tests/test_profile_plots.py
--- a/yt/visualization/tests/test_profile_plots.py
+++ b/yt/visualization/tests/test_profile_plots.py
@@ -12,7 +12,6 @@
 #
 # The full license is in the file COPYING.txt, distributed with this software.
 #-----------------------------------------------------------------------------
-import itertools
 import os
 import tempfile
 import shutil


https://bitbucket.org/yt_analysis/yt/commits/22f235cc4157/
Changeset:   22f235cc4157
Branch:      yt
User:        ngoldbaum
Date:        2015-08-17 15:51:25+00:00
Summary:     Removing HEALpix, adaptive HEALpix, and MosaicFisheye cameras

All of these cameras are no longer function due to licensing concerns and bitrot.
While they may offer useful features, they would need work to get them functional
once again, so in the interest of code clarity I am removing them from the
codebase. If anyone is interested in re-enabling their functionality, the code
lives on the VCS history.
Affected #:  1 file

diff -r 9888a4a65bfc4ecddf7334f1086414ee3e08ec94 -r 22f235cc415755fdb2e46ac84d9b064e9c6b9fdb yt/visualization/volume_rendering/camera.py
--- a/yt/visualization/volume_rendering/camera.py
+++ b/yt/visualization/volume_rendering/camera.py
@@ -1342,213 +1342,6 @@
       [left_edge[:,0], right_edge[:,1], left_edge[:,2]],
     ], dtype='float64')
 
-class HEALpixCamera(Camera):
-
-    _sampler_object = None 
-    
-    def __init__(self, center, radius, nside,
-                 transfer_function = None, fields = None,
-                 sub_samples = 5, log_fields = None, volume = None,
-                 ds = None, use_kd=True, no_ghost=False, use_light=False,
-                 inner_radius = 10):
-        mylog.error('I am sorry, HEALpix Camera does not work yet in 3.0')
-        raise NotImplementedError
-        ParallelAnalysisInterface.__init__(self)
-        if ds is not None: self.ds = ds
-        self.center = np.array(center, dtype='float64')
-        self.radius = radius
-        self.inner_radius = inner_radius
-        self.nside = nside
-        self.use_kd = use_kd
-        if transfer_function is None:
-            transfer_function = ProjectionTransferFunction()
-        self.transfer_function = transfer_function
-
-        if isinstance(self.transfer_function, ProjectionTransferFunction):
-            self._sampler_object = InterpolatedProjectionSampler
-            self._needs_tf = 0
-        else:
-            self._sampler_object = VolumeRenderSampler
-            self._needs_tf = 1
-
-        if fields is None: fields = ["density"]
-        self.fields = fields
-        self.sub_samples = sub_samples
-        self.log_fields = log_fields
-        dd = ds.all_data()
-        efields = dd._determine_fields(self.fields)
-        if self.log_fields is None:
-            self.log_fields = [self.ds._get_field_info(*f).take_log for f in efields]
-        self.use_light = use_light
-        self.light_dir = None
-        self.light_rgba = None
-        if volume is None:
-            volume = AMRKDTree(self.ds, min_level=min_level,
-                               max_level=max_level, data_source=self.data_source)
-        self.use_kd = isinstance(volume, AMRKDTree)
-        self.volume = volume
-
-    def new_image(self):
-        image = np.zeros((12 * self.nside ** 2, 1, 4), dtype='float64', order='C')
-        return image
-
-    def get_sampler_args(self, image):
-        nv = 12 * self.nside ** 2
-        vs = arr_pix2vec_nest(self.nside, np.arange(nv))
-        vs.shape = (nv, 1, 3)
-        vs += 1e-8
-        uv = np.ones(3, dtype='float64')
-        positions = np.ones((nv, 1, 3), dtype='float64') * self.center
-        dx = min(g.dds.min() for g in self.ds.index.find_point(self.center)[0])
-        positions += self.inner_radius * dx * vs
-        vs *= self.radius
-        args = (positions, vs, self.center,
-                (0.0, 1.0, 0.0, 1.0),
-                image, uv, uv,
-                np.zeros(3, dtype='float64'))
-        if self._needs_tf:
-            args += (self.transfer_function,)
-        args += (self.sub_samples,)
-        return args
-
-    def _render(self, double_check, num_threads, image, sampler):
-        pbar = get_pbar("Ray casting", (self.volume.brick_dimensions + 1).prod(axis=-1).sum())
-        total_cells = 0
-        if double_check:
-            for brick in self.volume.bricks:
-                for data in brick.my_data:
-                    if np.any(np.isnan(data)):
-                        raise RuntimeError
-        
-        view_pos = self.center
-        for brick in self.volume.traverse(view_pos):
-            sampler(brick, num_threads=num_threads)
-            total_cells += np.prod(brick.my_data[0].shape)
-            pbar.update(total_cells)
-        
-        pbar.finish()
-        image = sampler.aimage
-
-        self.finalize_image(image)
-
-        return image
-
-    def finalize_image(self, image):
-        view_pos = self.center
-        image = self.volume.reduce_tree_images(image, view_pos)
-        return image
-
-    def get_information(self):
-        info_dict = {'fields':self.fields,
-                     'type':self.__class__.__name__,
-                     'center':self.center,
-                     'radius':self.radius,
-                     'dataset':self.ds.fullpath}
-        return info_dict
-
-
-    def snapshot(self, fn = None, clip_ratio = None, double_check = False,
-                 num_threads = 0, clim = None, label = None):
-        r"""Ray-cast the camera.
-
-        This method instructs the camera to take a snapshot -- i.e., call the ray
-        caster -- based on its current settings.
-
-        Parameters
-        ----------
-        fn : string, optional
-            If supplied, the image will be saved out to this before being
-            returned.  Scaling will be to the maximum value.
-        clip_ratio : float, optional
-            If supplied, the 'max_val' argument to write_bitmap will be handed
-            clip_ratio * image.std()
-
-        Returns
-        -------
-        image : array
-            An (N,M,3) array of the final returned values, in float64 form.
-        """
-        if num_threads is None:
-            num_threads=get_num_threads()
-        image = self.new_image()
-        args = self.get_sampler_args(image)
-        sampler = self.get_sampler(args)
-        self.volume.initialize_source()
-        image = ImageArray(self._render(double_check, num_threads, 
-                                        image, sampler),
-                           info=self.get_information())
-        self.save_image(image, fn=fn, clim=clim, label = label)
-        return image
-
-    def save_image(self, image, fn=None, clim=None, label = None):
-        if self.comm.rank == 0 and fn is not None:
-            # This assumes Density; this is a relatively safe assumption.
-            if label is None:
-                label = "Projected %s" % (self.fields[0])
-            if clim is not None:
-                cmin, cmax = clim
-            else:
-                cmin = cmax = None
-            plot_allsky_healpix(image[:,0,0], self.nside, fn, label, 
-                                cmin = cmin, cmax = cmax)
-
-class AdaptiveHEALpixCamera(Camera):
-    def __init__(self, center, radius, nside,
-                 transfer_function = None, fields = None,
-                 sub_samples = 5, log_fields = None, volume = None,
-                 ds = None, use_kd=True, no_ghost=False,
-                 rays_per_cell = 0.1, max_nside = 8192):
-        ParallelAnalysisInterface.__init__(self)
-        if ds is not None: self.ds = ds
-        self.center = np.array(center, dtype='float64')
-        self.radius = radius
-        self.use_kd = use_kd
-        if transfer_function is None:
-            transfer_function = ProjectionTransferFunction()
-        self.transfer_function = transfer_function
-        if fields is None: fields = ["density"]
-        self.fields = fields
-        self.sub_samples = sub_samples
-        self.log_fields = log_fields
-        if volume is None:
-            volume = AMRKDTree(self.ds, fields=self.fields, no_ghost=no_ghost,
-                               log_fields=log_fields)
-        self.use_kd = isinstance(volume, AMRKDTree)
-        self.volume = volume
-        self.initial_nside = nside
-        self.rays_per_cell = rays_per_cell
-        self.max_nside = max_nside
-
-    def snapshot(self, fn = None):
-        tfp = TransferFunctionProxy(self.transfer_function)
-        tfp.ns = self.sub_samples
-        self.volume.initialize_source()
-        mylog.info("Adaptively rendering.")
-        pbar = get_pbar("Ray casting",
-                        (self.volume.brick_dimensions + 1).prod(axis=-1).sum())
-        total_cells = 0
-        bricks = [b for b in self.volume.traverse(None, self.center, None)][::-1]
-        left_edges = np.array([b.LeftEdge for b in bricks])
-        right_edges = np.array([b.RightEdge for b in bricks])
-        min_dx = min(((b.RightEdge[0] - b.LeftEdge[0])/b.my_data[0].shape[0]
-                     for b in bricks))
-        # We jitter a bit if we're on a boundary of our initial grid
-        for i in range(3):
-            if bricks[0].LeftEdge[i] == self.center[i]:
-                self.center += 1e-2 * min_dx
-            elif bricks[0].RightEdge[i] == self.center[i]:
-                self.center -= 1e-2 * min_dx
-        ray_source = AdaptiveRaySource(self.center, self.rays_per_cell,
-                                       self.initial_nside, self.radius,
-                                       bricks, left_edges, right_edges, self.max_nside)
-        for i,brick in enumerate(bricks):
-            ray_source.integrate_brick(brick, tfp, i, left_edges, right_edges,
-                                       bricks)
-            total_cells += np.prod(brick.my_data[0].shape)
-            pbar.update(total_cells)
-        pbar.finish()
-        info, values = ray_source.get_rays()
-        return info, values
 
 class StereoPairCamera(Camera):
     def __init__(self, original_camera, relative_separation = 0.005):
@@ -1798,530 +1591,6 @@
 
 data_object_registry["mosaic_camera"] = MosaicCamera
 
-
-class MosaicFisheyeCamera(Camera):
-    r"""A fisheye lens camera, taking adantage of image plane decomposition
-    for parallelism.
-
-    The camera represents the eye of an observer, which will be used to
-    generate ray-cast volume renderings of the domain. In this case, the
-    rays are defined by a fisheye lens
-
-    Parameters
-    ----------
-    center : array_like
-        The current "center" of the observer, from which the rays will be
-        cast
-    radius : float
-        The radial distance to cast to
-    resolution : int
-        The number of pixels in each direction.  Must be a single int.
-    volume : `yt.extensions.volume_rendering.AMRKDTree`, optional
-        The volume to ray cast through.  Can be specified for finer-grained
-        control, but otherwise will be automatically generated.
-    fields : list of fields, optional
-        This is the list of fields we want to volume render; defaults to
-        Density.
-    log_fields : list of bool, optional
-        Whether we should take the log of the fields before supplying them to
-        the volume rendering mechanism.
-    sub_samples : int, optional
-        The number of samples to take inside every cell per ray.
-    ds : `~yt.data_objects.api.Dataset`
-        For now, this is a require parameter!  But in the future it will become
-        optional.  This is the dataset to volume render.
-    l_max: int, optional
-        Specifies the maximum level to be rendered.  Also
-        specifies the maximum level used in the AMRKDTree
-        construction.  Defaults to None (all levels), and only
-        applies if use_kd=True.
-    no_ghost: bool, optional
-        Optimization option.  If True, homogenized bricks will
-        extrapolate out from grid instead of interpolating from
-        ghost zones that have to first be calculated.  This can
-        lead to large speed improvements, but at a loss of
-        accuracy/smoothness in resulting image.  The effects are
-        less notable when the transfer function is smooth and
-        broad. Default: False
-    nimx: int, optional
-        The number by which to decompose the image plane into in the x
-        direction.  Must evenly divide the resolution.
-    nimy: int, optional
-        The number by which to decompose the image plane into in the y 
-        direction.  Must evenly divide the resolution.
-    procs_per_wg: int, optional
-        The number of processors to use on each sub-image. Within each
-        subplane, the volume will be decomposed using the AMRKDTree with
-        procs_per_wg processors.  
-
-    Notes
-    -----
-        The product of nimx*nimy*procs_per_wg must be equal to or less than
-        the total number of mpi processes.  
-
-        Unlike the non-Mosaic camera, this will only return each sub-image
-        to the root processor of each sub-image workgroup in order to save
-        memory.  To save the final image, one must then call
-        MosaicFisheyeCamera.save_image('filename')
-
-    Examples
-    --------
-
-    >>> from yt.mods import *
-    
-    >>> ds = load('DD1717')
-    
-    >>> N = 512 # Pixels (1024^2)
-    >>> c = (ds.domain_right_edge + ds.domain_left_edge)/2. # Center
-    >>> radius = (ds.domain_right_edge - ds.domain_left_edge)/2.
-    >>> fov = 180.0
-    
-    >>> field='Density'
-    >>> mi,ma = ds.all_data().quantities['Extrema']('Density')[0]
-    >>> mi,ma = np.log10(mi), np.log10(ma)
-    
-    # You may want to comment out the above lines and manually set the min and max
-    # of the log of the Density field. For example:
-    # mi,ma = -30.5,-26.5
-    
-    # Another good place to center the camera is close to the maximum density.
-    # v,c = ds.find_max('Density')
-    # c -= 0.1*radius
-    
-   
-    # Construct transfer function
-    >>> tf = ColorTransferFunction((mi-1, ma+1),nbins=1024)
-    
-    # Sample transfer function with Nc gaussians.  Use col_bounds keyword to limit
-    # the color range to the min and max values, rather than the transfer function
-    # bounds.
-    >>> Nc = 5
-    >>> tf.add_layers(Nc,w=0.005, col_bounds = (mi,ma), alpha=np.logspace(-2,0,Nc),
-    >>>         colormap='RdBu_r')
-    >>> 
-    # Create the camera object. Use the keyword: no_ghost=True if a lot of time is
-    # spent creating vertex-centered data. In this case I'm running with 8
-    # processors, and am splitting the image plane into 4 pieces and using 2
-    # processors on each piece.
-    >>> cam = MosaicFisheyeCamera(c, radius, fov, N,
-    >>>         transfer_function = tf, 
-    >>>         sub_samples = 5, 
-    >>>         ds=ds, 
-    >>>         nimx=2,nimy=2,procs_per_wg=2)
-    
-    # Take a snapshot
-    >>> im = cam.snapshot()
-    
-    # Save the image
-    >>> cam.save_image('fisheye_mosaic.png')
-
-    """
-    def __init__(self, center, radius, fov, resolution, focal_center=None,
-                 transfer_function=None, fields=None,
-                 sub_samples=5, log_fields=None, volume=None,
-                 ds=None, l_max=None, no_ghost=False,nimx=1, nimy=1, procs_per_wg=None,
-                 rotation=None):
-
-        ParallelAnalysisInterface.__init__(self)
-        self.image_decomp = self.comm.size>1
-        if self.image_decomp:
-            PP = ProcessorPool()
-            npatches = nimy*nimx
-            if procs_per_wg is None:
-                if (PP.size % npatches):
-                    raise RuntimeError("Cannot evenly divide %i procs to %i patches" % (PP.size,npatches))
-                else:
-                    procs_per_wg = PP.size / npatches
-            if (PP.size != npatches*procs_per_wg):
-               raise RuntimeError("You need %i processors to utilize %i procs per one patch in [%i,%i] grid" 
-                     % (npatches*procs_per_wg,procs_per_wg,nimx,nimy))
- 
-            for j in range(nimy):
-                for i in range(nimx):
-                    PP.add_workgroup(size=procs_per_wg, name='%04i_%04i'%(i,j))
-                    
-            for wg in PP.workgroups:
-                if self.comm.rank in wg.ranks:
-                    my_wg = wg
-            
-            self.global_comm = self.comm
-            self.comm = my_wg.comm
-            self.wg = my_wg
-            self.imi = int(self.wg.name[0:4])
-            self.imj = int(self.wg.name[5:9])
-            mylog.info('My new communicator has the name %s' % self.wg.name)
-            self.nimx = nimx
-            self.nimy = nimy
-        else:
-            self.imi = 0
-            self.imj = 0
-            self.nimx = 1
-            self.nimy = 1
-        if ds is not None: self.ds = ds
-        
-        if rotation is None: rotation = np.eye(3)
-        self.rotation_matrix = rotation
-        
-        self.normal_vector = np.array([0.,0.,1])
-        self.north_vector = np.array([1.,0.,0.])
-        self.east_vector = np.array([0.,1.,0.])
-        self.rotation_vector = self.north_vector
-
-        if iterable(resolution):
-            raise RuntimeError("Resolution must be a single int")
-        self.resolution = resolution
-        self.center = np.array(center, dtype='float64')
-        self.focal_center = focal_center
-        self.radius = radius
-        self.fov = fov
-        if transfer_function is None:
-            transfer_function = ProjectionTransferFunction()
-        self.transfer_function = transfer_function
-        if fields is None: fields = ["density"]
-        self.fields = fields
-        self.sub_samples = sub_samples
-        self.log_fields = log_fields
-        if volume is None:
-            volume = AMRKDTree(self.ds, fields=self.fields, no_ghost=no_ghost,
-                               log_fields=log_fields,l_max=l_max)
-        self.volume = volume
-        self.vp = None
-        self.image = None 
-
-    def get_vector_plane(self):
-        if self.focal_center is not None:
-            rvec =  np.array(self.focal_center) - np.array(self.center)
-            rvec /= (rvec**2).sum()**0.5
-            angle = np.arccos( (self.normal_vector*rvec).sum()/( (self.normal_vector**2).sum()**0.5 *
-                (rvec**2).sum()**0.5))
-            rot_vector = np.cross(rvec, self.normal_vector)
-            rot_vector /= (rot_vector**2).sum()**0.5
-            
-            self.rotation_matrix = get_rotation_matrix(angle,rot_vector)
-            self.normal_vector = np.dot(self.rotation_matrix,self.normal_vector)
-            self.north_vector = np.dot(self.rotation_matrix,self.north_vector)
-            self.east_vector = np.dot(self.rotation_matrix,self.east_vector)
-        else:
-            self.focal_center = self.center + self.radius*self.normal_vector  
-        dist = ((self.focal_center - self.center)**2).sum()**0.5
-        # We now follow figures 4-7 of:
-        # http://paulbourke.net/miscellaneous/domefisheye/fisheye/
-        # ...but all in Cython.
-        
-        self.vp = arr_fisheye_vectors(self.resolution, self.fov, self.nimx, 
-                self.nimy, self.imi, self.imj)
-        
-        self.vp = rotate_vectors(self.vp, self.rotation_matrix)
-
-        self.center = self.focal_center - dist*self.normal_vector
-        self.vp *= self.radius
-        nx, ny = self.vp.shape[0], self.vp.shape[1]
-        self.vp.shape = (nx*ny,1,3)
-
-    def snapshot(self):
-        if self.vp is None:
-            self.get_vector_plane()
-
-        nx,ny = self.resolution/self.nimx, self.resolution/self.nimy
-        image = np.zeros((nx*ny,1,3), dtype='float64', order='C')
-        uv = np.ones(3, dtype='float64')
-        positions = np.ones((nx*ny, 1, 3), dtype='float64') * self.center
-        vector_plane = VectorPlane(positions, self.vp, self.center,
-                        (0.0, 1.0, 0.0, 1.0), image, uv, uv)
-        tfp = TransferFunctionProxy(self.transfer_function)
-        tfp.ns = self.sub_samples
-        self.volume.initialize_source()
-        mylog.info("Rendering fisheye of %s^2", self.resolution)
-        pbar = get_pbar("Ray casting",
-                        (self.volume.brick_dimensions + 1).prod(axis=-1).sum())
-
-        total_cells = 0
-        for brick in self.volume.traverse(None, self.center, image):
-            brick.cast_plane(tfp, vector_plane)
-            total_cells += np.prod(brick.my_data[0].shape)
-            pbar.update(total_cells)
-        pbar.finish()
-        image.shape = (nx, ny, 3)
-
-        if self.image is not None:
-            del self.image
-        image = ImageArray(image,
-                           info=self.get_information())
-        self.image = image
-        return image
-
-    def save_image(self, fn, clip_ratio=None):
-        if '.png' not in fn:
-            fn = fn + '.png'
-        
-        try:
-            image = self.image
-        except:
-            mylog.error('You must first take a snapshot')
-            raise(UserWarning)
-        
-        image = self.image
-        nx,ny = self.resolution/self.nimx, self.resolution/self.nimy
-        if self.image_decomp:
-            if self.comm.rank == 0:
-                if self.global_comm.rank == 0:
-                    final_image = np.empty((nx*self.nimx, 
-                        ny*self.nimy, 3),
-                        dtype='float64',order='C')
-                    final_image[:nx, :ny, :] = image
-                    for j in range(self.nimy):
-                        for i in range(self.nimx):
-                            if i==0 and j==0: continue
-                            arr = self.global_comm.recv_array((self.wg.size)*(j*self.nimx + i), tag = (self.wg.size)*(j*self.nimx + i))
-
-                            final_image[i*nx:(i+1)*nx, j*ny:(j+1)*ny,:] = arr
-                            del arr
-                    if clip_ratio is not None:
-                        write_bitmap(final_image, fn, clip_ratio*final_image.std())
-                    else:
-                        write_bitmap(final_image, fn)
-                else:
-                    self.global_comm.send_array(image, 0, tag = self.global_comm.rank)
-        else:
-            if self.comm.rank == 0:
-                if clip_ratio is not None:
-                    write_bitmap(image, fn, clip_ratio*image.std())
-                else:
-                    write_bitmap(image, fn)
-        return
-
-    def rotate(self, theta, rot_vector=None, keep_focus=True):
-        r"""Rotate by a given angle
-
-        Rotate the view.  If `rot_vector` is None, rotation will occur
-        around the `north_vector`.
-
-        Parameters
-        ----------
-        theta : float, in radians
-             Angle (in radians) by which to rotate the view.
-        rot_vector  : array_like, optional
-            Specify the rotation vector around which rotation will
-            occur.  Defaults to None, which sets rotation around
-            `north_vector`
-
-        Examples
-        --------
-
-        >>> cam.rotate(np.pi/4)
-        """
-        if rot_vector is None:
-            rot_vector = self.north_vector
-
-        dist = ((self.focal_center - self.center)**2).sum()**0.5
-
-        R = get_rotation_matrix(theta, rot_vector)
-
-        self.vp = rotate_vectors(self.vp, R)
-        self.normal_vector = np.dot(R,self.normal_vector)
-        self.north_vector = np.dot(R,self.north_vector)
-        self.east_vector = np.dot(R,self.east_vector)
-
-        if keep_focus:
-            self.center = self.focal_center - dist*self.normal_vector
-
-    def rotation(self, theta, n_steps, rot_vector=None, keep_focus=True):
-        r"""Loop over rotate, creating a rotation
-
-        This will yield `n_steps` snapshots until the current view has been
-        rotated by an angle `theta`
-
-        Parameters
-        ----------
-        theta : float, in radians
-            Angle (in radians) by which to rotate the view.
-        n_steps : int
-            The number of look_at snapshots to make.
-        rot_vector  : array_like, optional
-            Specify the rotation vector around which rotation will
-            occur.  Defaults to None, which sets rotation around the
-            original `north_vector`
-
-        Examples
-        --------
-
-        >>> for i, snapshot in enumerate(cam.rotation(np.pi, 10)):
-        ...     iw.write_bitmap(snapshot, 'rotation_%04i.png' % i)
-        """
-
-        dtheta = (1.0*theta)/n_steps
-        for i in range(n_steps):
-            self.rotate(dtheta, rot_vector=rot_vector, keep_focus=keep_focus)
-            yield self.snapshot()
-
-    def move_to(self,final,n_steps,exponential=False):
-        r"""Loop over a look_at
-
-        This will yield `n_steps` snapshots until the current view has been
-        moved to a final center of `final`.
-
-        Parameters
-        ----------
-        final : array_like
-            The final center to move to after `n_steps`
-        n_steps : int
-            The number of look_at snapshots to make.
-        exponential : boolean
-            Specifies whether the move/zoom transition follows an
-            exponential path toward the destination or linear
-
-        Examples
-        --------
-
-        >>> for i, snapshot in enumerate(cam.move_to([0.2,0.3,0.6], 10)):
-        ...     cam.save_image('move_%04i.png' % i)
-        """
-        if exponential:
-            position_diff = (np.array(final)/self.center)*1.0
-            dx = position_diff**(1.0/n_steps)
-        else:
-            dx = (np.array(final) - self.center)*1.0/n_steps
-        for i in range(n_steps):
-            if exponential:
-                self.center *= dx
-            else:
-                self.center += dx
-            yield self.snapshot()
-
-def allsky_projection(ds, center, radius, nside, field, weight = None,
-                      inner_radius = 10, rotation = None, data_source = None):
-    r"""Project through a dataset, through an allsky-method
-    decomposition from HEALpix, and return the image plane.
-
-    This function will accept the necessary items to integrate through a volume
-    over 4pi and return the integrated field of view to the user.  Note that if
-    a weight is supplied, it will multiply the pre-interpolated values
-    together.
-
-    Parameters
-    ----------
-    ds : `~yt.data_objects.api.Dataset`
-        This is the dataset to volume render.
-    center : array_like
-        The current "center" of the view port -- the focal point for the
-        camera.
-    radius : float or list of floats
-        The radius to integrate out to of the image.
-    nside : int
-        The HEALpix degree.  The number of rays integrated is 12*(Nside**2)
-        Must be a power of two!
-    field : string
-        The field to project through the volume
-    weight : optional, default None
-        If supplied, the field will be pre-multiplied by this, then divided by
-        the integrated value of this field.  This returns an average rather
-        than a sum.
-    inner_radius : optional, float, defaults to 0.05
-        The radius of the inner clipping plane, in units of the dx at the point
-        at which the volume rendering is centered.  This avoids unphysical
-        effects of nearby cells.
-    rotation : optional, 3x3 array
-        If supplied, the vectors will be rotated by this.  You can construct
-        this by, for instance, calling np.array([v1,v2,v3]) where those are the
-        three reference planes of an orthogonal frame (see ortho_find).
-    data_source : data container, default None
-        If this is supplied, this gives the data source from which the all sky
-        projection pulls its data from.
-
-    Returns
-    -------
-    image : array
-        An ((Nside**2)*12,1,3) array of the final integrated values, in float64 form.
-
-    Examples
-    --------
-
-    >>> image = allsky_projection(ds, [0.5, 0.5, 0.5], 1.0/ds['mpc'],
-                      32, "temperature", "density")
-    >>> plot_allsky_healpix(image, 32, "healpix.png")
-
-    """
-    # We manually modify the ProjectionTransferFunction to get it to work the
-    # way we want, with a second field that's also passed through.
-    fields = [field]
-    center = np.array(center, dtype='float64')
-    if weight is not None:
-        # This is a temporary field, which we will remove at the end.
-        weightfield = ("index", "temp_weightfield")
-        def _make_wf(f, w):
-            def temp_weightfield(a, b):
-                tr = b[f].astype("float64") * b[w]
-                return b.apply_units(tr, a.units)
-            return temp_weightfield
-        ds.field_info.add_field(weightfield,
-            function=_make_wf(field, weight))
-        # Now we have to tell the dataset to add it and to calculate
-        # its dependencies..
-        deps, _ = ds.field_info.check_derived_fields([weightfield])
-        ds.field_dependencies.update(deps)
-        fields = [weightfield, weight]
-    nv = 12*nside**2
-    image = np.zeros((nv,1,4), dtype='float64', order='C')
-    vs = arr_pix2vec_nest(nside, np.arange(nv))
-    vs.shape = (nv, 1, 3)
-    if rotation is not None:
-        vs2 = vs.copy()
-        for i in range(3):
-            vs[:,:,i] = (vs2 * rotation[:,i]).sum(axis=2)
-    else:
-        vs += 1e-8
-    positions = np.ones((nv, 1, 3), dtype='float64', order='C') * center
-    dx = min(g.dds.min() for g in ds.index.find_point(center)[0])
-    positions += inner_radius * dx * vs
-    vs *= radius
-    uv = np.ones(3, dtype='float64')
-    if data_source is None:
-        data_source = ds.sphere(center, radius)
-    sampler = ProjectionSampler(positions, vs, center, (0.0, 0.0, 0.0, 0.0),
-                                image, uv, uv, np.zeros(3, dtype='float64'))
-    for i, (grid, mask) in enumerate(data_source.blocks):
-        data = [(grid[field] * mask).astype("float64") for field in fields]
-        pg = PartitionedGrid(
-            grid.id, data,
-            grid.LeftEdge, grid.RightEdge,
-            grid.ActiveDimensions.astype("int64"))
-        sampler(pg)
-    image = sampler.aimage
-    dd = self.ds.all_data()
-    field = dd._determine_fields([field])[0]
-    finfo = self.ds._get_field_info(*field)
-    if weight is None:
-        dl = radius * ds.units[finfo.projection_conversion]
-        image *= dl
-    else:
-        image[:,:,0] /= image[:,:,1]
-        image = ds.arr(image, finfo.units)
-        ds.field_info.pop(weightfield)
-        ds.field_dependencies.pop(weightfield)
-    return image[:,0,0]
-
-def plot_allsky_healpix(image, nside, fn, label = "", rotation = None,
-                        take_log = True, resolution=512, cmin=None, cmax=None):
-    import matplotlib.figure
-    import matplotlib.backends.backend_agg
-    if rotation is None: rotation = np.eye(3).astype("float64")
-
-    img, count = pixelize_healpix(nside, image, resolution, resolution, rotation)
-
-    fig = matplotlib.figure.Figure((10, 5))
-    ax = fig.add_subplot(1,1,1,projection='aitoff')
-    if take_log: func = np.log10
-    else: func = lambda a: a
-    implot = ax.imshow(func(img), extent=(-np.pi,np.pi,-np.pi/2,np.pi/2),
-                       clip_on=False, aspect=0.5, vmin=cmin, vmax=cmax)
-    cb = fig.colorbar(implot, orientation='horizontal')
-    cb.set_label(label)
-    ax.xaxis.set_ticks(())
-    ax.yaxis.set_ticks(())
-    canvas = matplotlib.backends.backend_agg.FigureCanvasAgg(fig)
-    canvas.print_figure(fn)
-    return img, count
-
 class ProjectionCamera(Camera):
     def __init__(self, center, normal_vector, width, resolution,
             field, weight=None, volume=None, no_ghost = False, 


https://bitbucket.org/yt_analysis/yt/commits/e8e8a0dd22a0/
Changeset:   e8e8a0dd22a0
Branch:      yt
User:        ngoldbaum
Date:        2015-08-17 15:51:57+00:00
Summary:     Linting yt/visualization/volume_rendering/camera.py
Affected #:  1 file

diff -r 22f235cc415755fdb2e46ac84d9b064e9c6b9fdb -r e8e8a0dd22a08cfda7a17a380c83e988aac29663 yt/visualization/volume_rendering/camera.py
--- a/yt/visualization/volume_rendering/camera.py
+++ b/yt/visualization/volume_rendering/camera.py
@@ -16,8 +16,9 @@
 from yt.extern.six.moves import builtins
 import numpy as np
 
-from yt.funcs import *
-from yt.utilities.math_utils import *
+from yt.funcs import \
+    iterable, mylog, get_pbar, \
+    get_num_threads, ensure_numpy_array
 from yt.units.yt_array import YTArray
 from yt.utilities.exceptions import YTNotInsideNotebook
 from copy import deepcopy
@@ -25,14 +26,11 @@
 from .transfer_functions import ProjectionTransferFunction
 
 from yt.utilities.lib.grid_traversal import \
-    arr_vec2pix_nest, arr_pix2vec_nest, \
-    arr_ang2pix_nest, arr_fisheye_vectors, \
+    arr_fisheye_vectors, \
     PartitionedGrid, ProjectionSampler, VolumeRenderSampler, \
-    LightSourceRenderSampler, InterpolatedProjectionSampler, \
-    arr_vec2pix_nest, arr_pix2vec_nest, arr_ang2pix_nest, \
-    pixelize_healpix, arr_fisheye_vectors
+    LightSourceRenderSampler, InterpolatedProjectionSampler
 from yt.utilities.lib.misc_utilities import \
-    lines, rotate_vectors
+    lines
 
 from yt.utilities.math_utils import get_rotation_matrix
 from yt.utilities.orientation import Orientation
@@ -40,10 +38,9 @@
 from yt.visualization.image_writer import write_bitmap, write_image, apply_colormap
 from yt.data_objects.data_containers import data_object_registry
 from yt.utilities.parallel_tools.parallel_analysis_interface import \
-    ParallelAnalysisInterface, ProcessorPool, parallel_objects
+    ParallelAnalysisInterface, parallel_objects
 from yt.utilities.amr_kdtree.api import AMRKDTree
-from .blenders import  enhance_rgba
-from numpy import pi
+from yt.visualization.volume_rendering.blenders import enhance_rgba
 
 def get_corners(le, re):
     return np.array([
@@ -895,7 +892,6 @@
         ...     iw.write_bitmap(snapshot, "move_%04i.png" % i)
         """
         dW = None
-        old_center = self.center.copy()
         if not isinstance(final, YTArray):
             final = self.ds.arr(final, input_units = "code_length")
         if exponential:
@@ -916,7 +912,7 @@
         else:
             if final_width is not None:
                 if not iterable(final_width):
-                    width = [final_width, final_width, final_width] 
+                    final_width = [final_width, final_width, final_width] 
                 if not isinstance(final_width, YTArray):
                     final_width = self.ds.arr(final_width, input_units="code_length")
                     # left/right, top/bottom, front/back
@@ -988,7 +984,6 @@
         """
         rot_vector = self.orienter.unit_vectors[0]
         R = get_rotation_matrix(theta, rot_vector)
-        normal_vector = self.front_center-self.center
         self.switch_view(
                 normal_vector=np.dot(R, self.orienter.unit_vectors[2]),
                 north_vector=np.dot(R, self.orienter.unit_vectors[1]))
@@ -1012,7 +1007,6 @@
         """
         rot_vector = self.orienter.unit_vectors[1]
         R = get_rotation_matrix(theta, rot_vector)
-        normal_vector = self.front_center-self.center
         self.switch_view(
                 normal_vector=np.dot(R, self.orienter.unit_vectors[2]))
  
@@ -1108,7 +1102,7 @@
         for i, frame in enumerate(self.frames):
             fn = basename + '_%04i.png'%i
             if clip_ratio is not None:
-                write_bitmap(frame, fn, clip_ratio*image.std())
+                write_bitmap(frame, fn, clip_ratio*frame.std())
             else:
                 write_bitmap(frame, fn)
 
@@ -1279,9 +1273,10 @@
             if np.arccos(sight_angle_cos) < 0.5 * np.pi:
                 sight_length = self.width[2] / sight_angle_cos
             else:
-            # The corner is on the backwards, then put it outside of the image
-            # It can not be simply removed because it may connect to other corner
-            # within the image, which produces visible domian boundary line
+                # The corner is on the backwards, then put it outside of the
+                # image It can not be simply removed because it may connect to
+                # other corner within the image, which produces visible domian
+                # boundary line
                 sight_length = np.sqrt(self.width[0]**2+self.width[1]**2) / \
                                np.sqrt(1 - sight_angle_cos**2)
             pos1[i] = self.center + sight_length * sight_vector[i]
@@ -1744,9 +1739,6 @@
         if num_threads is None:
             num_threads=get_num_threads()
 
-        fields = [self.field]
-        resolution = self.resolution
-
         image = self.new_image()
 
         args = self.get_sampler_args(image)


https://bitbucket.org/yt_analysis/yt/commits/b0dd5a780b59/
Changeset:   b0dd5a780b59
Branch:      yt
User:        ngoldbaum
Date:        2015-08-17 15:58:01+00:00
Summary:     Removing CUDARayCast script since it is not used by other code in yt
Affected #:  1 file

diff -r e8e8a0dd22a08cfda7a17a380c83e988aac29663 -r b0dd5a780b5936054770b80fa00cd37edc06eaa5 yt/visualization/volume_rendering/CUDARayCast.py
--- a/yt/visualization/volume_rendering/CUDARayCast.py
+++ /dev/null
@@ -1,161 +0,0 @@
-"""
-An attempt at putting the ray-casting operation into CUDA
-
-
-
-"""
-from __future__ import print_function
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-import sys;sys.path.insert(0,'.')
-
-from yt.mods import *
-import yt.extensions.HierarchySubset as hs
-import numpy as np
-import h5py, time
-from yt.utilities.physical_constants import \
-    mass_hydrogen_cgs
-
-import matplotlib;matplotlib.use("Agg");import pylab
-
-from yt.extensions.volume_rendering.TransferFunction import ColorTransferFunction
-
-if __name__ == "__main__":
-
-    # This is boilerplate code for setting up pycuda
-    import pycuda.driver as cuda
-    import pycuda.compiler as compiler
-    import pycuda.autoinit
-    import pycuda.gpuarray as gpuarray
-    cuda.init()
-    assert (cuda.Device.count() >= 1)
-
-    print ("Extracting hierarchy.")
-    ods = load("/u/ki/mturk/ki05/MSM96-SIM3-restart-J64/DataDump0081.dir/DataDump0081")
-    ds = hs.ExtractedParameterFile(ods, 20)
-
-    cpu = {}
-    gpu = {}
-
-    print ("Reading data.")
-    #fn = "DataDump0081_partitioned.h5"
-    fn = "RedshiftOutput0005_partitioned.h5"
-    f = h5py.File("/u/ki/mturk/ki05/%s" % fn)
-    cpu['grid_data'] = f["/PGrids/Data"][:].astype("float32")
-    cpu['dims'] = f["/PGrids/Dims"][:].astype("int32") - 1
-    cpu['left_edge'] = f["/PGrids/LeftEdges"][:].astype("float32")
-    cpu['right_edge'] = f["/PGrids/RightEdges"][:].astype("float32")
-
-    print ("Constructing transfer function.")
-    if "Data" in fn:
-        mh = np.log10(mass_hydrogen_cgs)
-        tf = ColorTransferFunction((7.5+mh, 14.0+mh))
-        tf.add_gaussian( 8.25+mh, 0.002, [0.2, 0.2, 0.4, 0.1])
-        tf.add_gaussian( 9.75+mh, 0.002, [0.0, 0.0, 0.3, 0.1])
-        tf.add_gaussian(10.25+mh, 0.004, [0.0, 0.3, 0.0, 0.1])
-        tf.add_gaussian(11.50+mh, 0.005, [1.0, 0.0, 0.0, 0.7])
-        tf.add_gaussian(12.75+mh, 0.010, [1.0, 1.0, 1.0, 1.0])
-    elif "Red" in fn:
-        tf = ColorTransferFunction((-31, -27))
-        tf.add_gaussian(-30.0, 0.05, [1.0, 0.0, 0.0, 0.1])
-        tf.add_gaussian(-29.5, 0.03, [0.0, 1.0, 0.0, 0.3])
-        tf.add_gaussian(-29.0, 0.05, [0.0, 0.0, 1.0, 0.5])
-        tf.add_gaussian(-28.5, 0.05, [1.0, 1.0, 1.0, 1.0])
-    else: raise RuntimeError
-
-    cpu['ngrids'] = np.array([cpu['dims'].shape[0]], dtype='int32')
-    cpu['tf_r'] = tf.red.y.astype("float32")
-    cpu['tf_g'] = tf.green.y.astype("float32")
-    cpu['tf_b'] = tf.blue.y.astype("float32")
-    cpu['tf_a'] = tf.alpha.y.astype("float32")
-
-    cpu['tf_bounds'] = np.array(tf.x_bounds, dtype='float32')
-
-    cpu['v_dir'] = np.array([0.3, 0.5, 0.6], dtype='float32')
-
-    c = np.array([0.47284317, 0.48062515, 0.58282089], dtype='float32')
-
-    print ("Getting cutting plane.")
-    cp = ds.cutting(cpu['v_dir'], c)
-
-    W = 2000.0/ds['au']
-    W = 0.25
-    Nvec = 128
-    back_c = c - cp._norm_vec * W
-    front_c = c + cp._norm_vec * W
-
-    px, py = np.mgrid[-W:W:Nvec*1j,-W:W:Nvec*1j]
-    xv = cp._inv_mat[0,0]*px + cp._inv_mat[0,1]*py + cp.center[0]
-    yv = cp._inv_mat[1,0]*px + cp._inv_mat[1,1]*py + cp.center[1]
-    zv = cp._inv_mat[2,0]*px + cp._inv_mat[2,1]*py + cp.center[2]
-    cpu['v_pos'] = np.array([xv, yv, zv], dtype='float32').transpose()
-
-    cpu['image_r'] = np.zeros((Nvec, Nvec), dtype='float32').ravel()
-    cpu['image_g'] = np.zeros((Nvec, Nvec), dtype='float32').ravel()
-    cpu['image_b'] = np.zeros((Nvec, Nvec), dtype='float32').ravel()
-    cpu['image_a'] = np.zeros((Nvec, Nvec), dtype='float32').ravel()
-
-    print ("Generating module")
-    source = open("yt/extensions/volume_rendering/_cuda_caster.cu").read()
-    mod = compiler.SourceModule(source)
-    func = mod.get_function("ray_cast")
-
-    for n, a in cpu.items():
-        ss = a.size * a.dtype.itemsize
-        print ("Allocating %0.3e megabytes for %s" % (ss/(1024*1024.), n))
-        gpu[n] = cuda.to_device(a.ravel('F'))
-        #pycuda.autoinit.context.synchronize()
-
-    BLOCK_SIZE = 8
-    grid_size = Nvec / BLOCK_SIZE
-
-    print ("Running ray_cast function.")
-    t1 = time.time()
-    ret = func(gpu['ngrids'],
-               gpu['grid_data'],
-               gpu['dims'],
-               gpu['left_edge'],
-               gpu['right_edge'],
-               gpu['tf_r'],
-               gpu['tf_g'],
-               gpu['tf_b'],
-               gpu['tf_a'],
-               gpu['tf_bounds'],
-               gpu['v_dir'],
-               gpu['v_pos'],
-               gpu['image_r'],
-               gpu['image_g'],
-               gpu['image_b'],
-               gpu['image_a'],
-         block=(BLOCK_SIZE,BLOCK_SIZE,1),
-         grid=(grid_size, grid_size), time_kernel=True)
-    t2 = time.time()
-    print ("BACK: %0.3e" % (t2-t1))
-
-    mi, ma = 1e300, -1e300
-    image = []
-    for im in 'rgb':
-        ii = 'image_%s' % im
-        sh, dtype = cpu[ii].shape, cpu[ii].dtype
-        del cpu[ii]
-        cpu[ii] = cuda.from_device(gpu[ii], sh, dtype).reshape((Nvec,Nvec))
-        mi, ma = min(cpu[ii].min(),mi), max(cpu[ii].max(), ma)
-        image.append(cpu[ii])
-        print ("Min/max of %s %0.3e %0.3e" % (
-                im, image[-1].min(), image[-1].max()))
-        pylab.clf()
-        pylab.imshow(image[-1], interpolation='nearest')
-        pylab.savefig("/u/ki/mturk/public_html/vr6/%s.png" % (ii))
-
-    image = np.array(image).transpose()
-    image = (image - mi) / (ma - mi)
-    pylab.clf()
-    pylab.imshow(image, interpolation='nearest')
-    pylab.savefig("/u/ki/mturk/public_html/vr6/image_rgb.png")


https://bitbucket.org/yt_analysis/yt/commits/09d2015cac9e/
Changeset:   09d2015cac9e
Branch:      yt
User:        ngoldbaum
Date:        2015-08-17 21:30:06+00:00
Summary:     Remove the classes that we've deleted from the docs and public API
Affected #:  2 files

diff -r b0dd5a780b5936054770b80fa00cd37edc06eaa5 -r 09d2015cac9e33c0adc3ef8b6d0c1ecc46b17ec8 doc/source/reference/api/api.rst
--- a/doc/source/reference/api/api.rst
+++ b/doc/source/reference/api/api.rst
@@ -610,10 +610,8 @@
 .. autosummary::
    :toctree: generated/
 
-   ~yt.visualization.volume_rendering.camera.MosaicFisheyeCamera
    ~yt.visualization.volume_rendering.camera.FisheyeCamera
    ~yt.visualization.volume_rendering.camera.MosaicCamera
-   ~yt.visualization.volume_rendering.camera.plot_allsky_healpix
    ~yt.visualization.volume_rendering.camera.PerspectiveCamera
    ~yt.utilities.amr_kdtree.amr_kdtree.AMRKDTree
    ~yt.visualization.volume_rendering.camera.StereoPairCamera

diff -r b0dd5a780b5936054770b80fa00cd37edc06eaa5 -r 09d2015cac9e33c0adc3ef8b6d0c1ecc46b17ec8 yt/visualization/volume_rendering/api.py
--- a/yt/visualization/volume_rendering/api.py
+++ b/yt/visualization/volume_rendering/api.py
@@ -21,8 +21,8 @@
                            plot_channel, plot_rgb
 
 from .camera import Camera, PerspectiveCamera, StereoPairCamera, \
-    off_axis_projection, FisheyeCamera, MosaicFisheyeCamera, \
-    HEALpixCamera, InteractiveCamera, ProjectionCamera, \
+    off_axis_projection, FisheyeCamera, \
+    InteractiveCamera, ProjectionCamera, \
     SphericalCamera, StereoSphericalCamera
 
 from .transfer_function_helper import TransferFunctionHelper


https://bitbucket.org/yt_analysis/yt/commits/1c17c5ad33b0/
Changeset:   1c17c5ad33b0
Branch:      yt
User:        ngoldbaum
Date:        2015-08-17 22:43:18+00:00
Summary:     Removing plot_type_registry from public API
Affected #:  1 file

diff -r 09d2015cac9e33c0adc3ef8b6d0c1ecc46b17ec8 -r 1c17c5ad33b09a3839ab5af2eeb20ebef8a2238e yt/visualization/api.py
--- a/yt/visualization/api.py
+++ b/yt/visualization/api.py
@@ -43,9 +43,6 @@
     PlotCallback, \
     callback_registry
 
-from .easy_plots import \
-    plot_type_registry
-
 from .streamlines import \
     Streamlines
 


https://bitbucket.org/yt_analysis/yt/commits/e15bcda96a05/
Changeset:   e15bcda96a05
Branch:      yt
User:        ngoldbaum
Date:        2015-08-18 00:19:38+00:00
Summary:     Backing out 242969a4d535
Affected #:  1 file

diff -r 1c17c5ad33b09a3839ab5af2eeb20ebef8a2238e -r e15bcda96a05852c87ba3136739861800256be35 yt/visualization/volume_rendering/camera_path.py
--- /dev/null
+++ b/yt/visualization/volume_rendering/camera_path.py
@@ -0,0 +1,331 @@
+"""
+Create smooth camera paths from keyframes.
+
+
+
+"""
+from __future__ import print_function
+
+#-----------------------------------------------------------------------------
+# Copyright (c) 2013, yt Development Team.
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+import random
+import numpy as np
+from .create_spline import create_spline
+
+class Keyframes(object):
+    def __init__(self, x, y, z=None, north_vectors=None, up_vectors=None,
+                 times=None, niter=50000, init_temp=10.0, alpha=0.999,
+                 fixed_start=False):
+        r"""Keyframes for camera path generation.
+
+        From a set of keyframes with position and optional up and
+        north vectors, an interpolated camera path is generated.
+
+        Parameters
+        ----------
+        x : array_like
+            The x positions of the keyframes
+        y : array_like
+            The y positions of the keyframes
+        z : array_like, optional
+            The z positions of the keyframes. Default: 0.0
+        north_vectors : array_like, optional
+            The north vectors of the keyframes. Default: None
+        up_vectors : array_like, optional
+            The up vectors of the keyframes. Default: None
+        times : array_like, optional
+            The times of the keyframes. Default: arange(N)
+        niter : integer, optional
+            Maximum number of iterations to find solution. Default: 50000
+        init_temp : float, optional
+            Intital temperature for simulated annealing when finding a
+            solution.  Lower initial temperatures result in an initial solution
+            in first several iterations that changes more rapidly. Default: 10.0
+        alpha : float, optional
+            Exponent in cooling function in simulated annealing.  Must be < 1.
+            In each iteration, the temperature_new = temperature_old * alpha.
+            Default: 0.999
+        fixed_start: boolean, optional
+            If true, the first point never changes when searching for shortest
+            path.  Default: False
+
+        Examples
+        --------
+
+        >>> import numpy as np
+        >>> import matplotlib.pyplot as plt
+        >>> from yt.visualization.volume_rendering.camera_path import *
+
+        # Make a camera path from 10 random (x,y,z) keyframes
+        >>> data = np.random.random.((10,3))
+        >>> kf = Keyframes(data[:,0], data[:,1], data[:,2])
+        >>> path = kf.create_path(250, shortest_path=False)
+
+        # Plot the keyframes in the x-y plane and camera path
+        plt.plot(kf.pos[:,0], kf.pos[:,1], 'ko')
+        plt.plot(path['position'][:,0], path['position'][:,1])
+        plt.savefig('path.png')
+        """
+        Nx = len(x)
+        Ny = len(y)
+        if z != None:
+            Nz = len(z)
+            ndims = 3
+        else:
+            Nz = 1
+            ndims = 2
+        if Nx*Ny*Nz != Nx**ndims:
+            print("Need Nx (%d) == Ny (%d) == Nz (%d)" % (Nx, Ny, Nz))
+            sys.exit()
+        self.nframes = Nx
+        self.pos = np.zeros((Nx,3))
+        self.pos[:,0] = x
+        self.pos[:,1] = y
+        if z != None:
+            self.pos[:,2] = z
+        else:
+            self.pos[:,2] = 0.0
+        self.north_vectors = north_vectors
+        self.up_vectors = up_vectors
+        if times == None:
+            self.times = np.arange(self.nframes)
+        else:
+            self.times = times
+        self.cartesian_matrix()
+        self.setup_tsp(niter, init_temp, alpha, fixed_start)
+
+    def setup_tsp(self, niter=50000, init_temp=10.0, alpha=0.999,
+                  fixed_start=False):
+        r"""Setup parameters for Travelling Salesman Problem.
+
+        Parameters
+        ----------
+        niter : integer, optional
+            Maximum number of iterations to find solution. Default: 50000
+        init_temp : float, optional
+            Intital temperature for simulated annealing when finding a
+            solution.  Lower initial temperatures result in an initial solution
+            in first several iterations that changes more rapidly. Default: 10.0
+        alpha : float, optional
+            Exponent in cooling function in simulated annealing.  Must be < 1.
+            In each iteration, the temperature_new = temperature_old * alpha.
+            Default: 0.999
+        fixed_start: boolean, optional
+            If true, the first point never changes when searching for shortest
+            path.  Default: False
+        """
+        # randomize tour
+        self.tour = range(self.nframes)
+        np.random.shuffle(self.tour)
+        if fixed_start:
+            first = self.tour.index(0)
+            self.tour[0], self.tour[first] = self.tour[first], self.tour[0]
+        self.max_iterations = niter
+        self.initial_temp = init_temp
+        self.alpha = alpha
+        self.fixed_start = fixed_start
+        self.best_score = None
+        self.best = None
+
+    def set_times(self, times):
+        self.times = times
+        
+    def rand_seq(self):
+        r"""
+        Generates values in random order, equivlanet to using shuffle
+        in random without generation all values at once.
+        """
+        values = range(self.nframes)
+        for i in range(self.nframes):
+            # pick a random index into remaining values
+            j = i + int(random.random() * (self.nframes-i))
+            # swap the values
+            values[j], values[i] = values[i], values[j]
+            # return the swapped value
+            yield values[i]
+
+    def all_pairs(self):
+        r"""
+        Generates all (i,j) pairs for (i,j) for 0-size
+        """
+        for i in self.rand_seq():
+            for j in self.rand_seq():
+                yield (i,j)
+    
+    def reversed_sections(self, tour):
+        r"""
+        Generator to return all possible variations where a section
+        between two cities are swapped.
+        """
+        for i,j in self.all_pairs():
+            if i == j: continue
+            copy = tour[:]
+            if i < j:
+                copy[i:j+1] = reversed(tour[i:j+1])
+            else:
+                copy[i+1:] = reversed(tour[:j])
+                copy[:j] = reversed(tour[i+1:])
+            if self.fixed_start:
+                ind = copy.index(0)
+                copy[0], copy[ind] = copy[ind], copy[0]
+            if copy != tour: # no point return the same tour
+                yield copy
+
+    def cartesian_matrix(self):
+        r"""
+        Create a distance matrix for the city coords that uses
+        straight line distance
+        """
+        self.dist_matrix = np.zeros((self.nframes, self.nframes))
+        xmat = np.zeros((self.nframes, self.nframes))
+        xmat[:,:] = self.pos[:,0]
+        dx = xmat - xmat.T
+        ymat = np.zeros((self.nframes, self.nframes))
+        ymat[:,:] = self.pos[:,1]
+        dy = ymat - ymat.T
+        zmat = np.zeros((self.nframes, self.nframes))
+        zmat[:,:] = self.pos[:,2]
+        dz = zmat - zmat.T
+        self.dist_matrix = np.sqrt(dx*dx + dy*dy + dz*dz)
+
+    def tour_length(self, tour):
+        r"""
+        Calculate the total length of the tour based on the distance
+        matrix
+        """
+        total = 0
+        num_cities = len(tour)
+        for i in range(num_cities):
+            j = (i+1) % num_cities
+            city_i = tour[i]
+            city_j = tour[j]
+            total += self.dist_matrix[city_i, city_j]
+        return -total
+
+    def cooling(self):
+        T = self.initial_temp
+        while True:
+            yield T
+            T = self.alpha * T
+
+    def prob(self, prev, next, temperature):
+        if next > prev:
+            return 1.0
+        else:
+            return np.exp( -abs(next-prev) / temperature )
+
+    def get_shortest_path(self):
+        r"""Determine shortest path between all keyframes.
+
+        Parameters
+        ----------
+        None.
+        """
+        self.setup_tsp(niter, init_temp, alpha, fixed_start)
+        num_eval = 1
+        cooling_schedule = self.cooling()
+        current = self.tour
+        current_score = self.tour_length(current)
+        for temperature in cooling_schedule:
+            done = False
+            # Examine moves around the current position
+            for next in self.reversed_sections(current):
+                if num_eval >= self.max_iterations:
+                    done = True
+                    break
+                next_score = self.tour_length(next)
+                num_eval += 1
+
+                # Anneal.  Accept new solution if a random number is
+                # greater than our "probability".
+                p = self.prob(current_score, next_score, temperature)
+                if random.random() < p:
+                    current = next
+                    self.current_score = next_score
+                    if self.current_score > self.best_score:
+                        #print num_eval, self.current_score, self.best_score, current
+                        self.best_score = self.current_score
+                        self.best = current
+                    break
+
+            if done:
+                break
+        self.pos = self.pos[self.tour,:]
+        if self.north_vectors != None:
+            self.north_vectors = self.north_vectors[self.tour]
+        if self.up_vectors != None:
+            self.up_vectors = self.up_vectors[self.tour]
+
+    def create_path(self, npoints, path_time=None, tension=0.5, shortest_path=False):
+        r"""Create a interpolated camera path from keyframes.
+
+        Parameters
+        ----------
+        npoints : integer
+            Number of points to interpolate from keyframes
+        path_time : array_like, optional
+            Times of interpolated points.  Default: Linearly spaced
+        tension : float, optional
+            Controls how sharp of a curve the spline takes.  A higher tension
+            allows for more sharp turns.  Default: 0.5
+        shortest_path : boolean, optional
+            If true, estimate the shortest path between the keyframes.
+            Default: False
+
+        Returns
+        -------
+        path : dict
+            Dictionary (time, position, north_vectors, up_vectors) of camera
+            path.  Also saved to self.path.
+        """
+        self.npoints = npoints
+        self.path = {"time": np.zeros(npoints),
+                     "position": np.zeros((npoints, 3)),
+                     "north_vectors": np.zeros((npoints,3)),
+                     "up_vectors": np.zeros((npoints,3))}
+        if shortest_path:
+            self.get_shortest_path()
+        if path_time == None:
+            path_time = np.linspace(0, self.nframes, npoints)
+        self.path["time"] = path_time
+        for dim in range(3):
+            self.path["position"][:,dim] = create_spline(self.times, self.pos[:,dim],
+                                                         path_time, tension=tension)
+            if self.north_vectors != None:
+                self.path["north_vectors"][:,dim] = \
+                    create_spline(self.times, self.north_vectors[:,dim],
+                                  path_time, tension=tension)
+            if self.up_vectors != None:
+                self.path["up_vectors"][:,dim] = \
+                    create_spline(self.times, self.up_vectors[:,dim],
+                                  path_time, tension=tension)
+        return self.path
+
+    def write_path(self, filename="path.dat"):
+        r"""Writes camera path to ASCII file
+
+        Parameters
+        ----------
+        filename : string, optional
+            Filename containing the camera path.  Default: path.dat
+        """
+        fp = open(filename, "w")
+        fp.write("#%11s %12s %12s %12s %12s %12s %12s %12s %12s\n" %
+                 ("x", "y", "z", "north_x", "north_y", "north_z",
+                  "up_x", "up_y", "up_z"))
+        for i in range(self.npoints):
+            fp.write("%.12f %.12f %.12f %.12f %.12f %.12f %.12f %.12f %.12f\n" %
+                     (self.path["position"][i,0], self.path["position"][i,1],
+                      self.path["position"][i,2], 
+                      self.path["north_vectors"][i,0], self.path["north_vectors"][i,1],
+                      self.path["north_vectors"][i,2], 
+                      self.path["up_vectors"][i,0], self.path["up_vectors"][i,1],
+                      self.path["up_vectors"][i,2]))
+        fp.close()
+


https://bitbucket.org/yt_analysis/yt/commits/0e6f92bca03e/
Changeset:   0e6f92bca03e
Branch:      yt
User:        ngoldbaum
Date:        2015-08-20 16:33:06+00:00
Summary:     Merging with mainline
Affected #:  23 files

diff -r e15bcda96a05852c87ba3136739861800256be35 -r 0e6f92bca03e001b00f8f130a47c6d9d6fabc1ce doc/source/analyzing/analysis_modules/absorption_spectrum.rst
--- a/doc/source/analyzing/analysis_modules/absorption_spectrum.rst
+++ b/doc/source/analyzing/analysis_modules/absorption_spectrum.rst
@@ -109,6 +109,16 @@
 
 .. note:: To write out a fits file, you must install the `astropy <http://www.astropy.org>`_ python library in order to access the astropy.io.fits module.  You can usually do this by simply running `pip install astropy` at the command line.
 
+Generating Spectra in Parallel
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The spectrum generator can be run in parallel simply by following the procedures 
+laid out in :ref:`parallel-computation` for running yt scripts in parallel.  
+Spectrum generation is parallelized using a multi-level strategy where each 
+absorption line is deposited by a different processor.  If the number of available 
+processors is greater than the number of lines, then the deposition of 
+individual lines will be divided over multiple processors.
+
 Fitting an Absorption Spectrum
 ------------------------------
 

diff -r e15bcda96a05852c87ba3136739861800256be35 -r 0e6f92bca03e001b00f8f130a47c6d9d6fabc1ce doc/source/examining/loading_data.rst
--- a/doc/source/examining/loading_data.rst
+++ b/doc/source/examining/loading_data.rst
@@ -771,7 +771,7 @@
 
 .. code-block:: python
 
-   from yt.frontends.sph.definitions import gadget_field_specs
+   from yt.frontends.gadget.definitions import gadget_field_specs
    gadget_field_specs["my_field_def"] = my_field_def
 
 Please also feel free to issue a pull request with any new field
@@ -871,7 +871,7 @@
 ----------------
 
 See :ref:`loading-numpy-array` and
-:func:`~yt.frontends.sph.data_structures.load_amr_grids` for more detail.
+:func:`~yt.frontends.stream.data_structures.load_amr_grids` for more detail.
 
 It is possible to create native yt dataset from Python's dictionary
 that describes set of rectangular patches of data of possibly varying

diff -r e15bcda96a05852c87ba3136739861800256be35 -r 0e6f92bca03e001b00f8f130a47c6d9d6fabc1ce doc/source/visualizing/callbacks.rst
--- a/doc/source/visualizing/callbacks.rst
+++ b/doc/source/visualizing/callbacks.rst
@@ -463,6 +463,35 @@
    s.annotate_streamlines('velocity_x', 'velocity_y')
    s.save()
 
+.. _annotate-line-integral-convolution:
+
+Overplot Line Integral Convolution
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. function:: annotate_line_integral_convolution(self, field_x, field_y, \
+                                                 texture=None, kernellen=50., \
+                                                 lim=(0.5,0.6), cmap='binary', \
+                                                 alpha=0.8, const_alpha=False)
+
+   (This is a proxy for
+   :class:`~yt.visualization.plot_modifications.LineIntegralConvolutionCallback`.)
+
+   Add line integral convolution to any plot, using the ``field_x`` and ``field_y`` 
+   from the associated data. A white noise background will be used for ``texture`` 
+   as default. Adjust the bounds of ``lim`` in the range of ``[0, 1]`` which applies 
+   upper and lower bounds to the values of line integral convolution and enhance 
+   the visibility of plots. When ``const_alpha=False``, alpha will be weighted 
+   spatially by the values of line integral convolution; otherwise a constant value 
+   of the given alpha is used.
+
+.. python-script::
+
+   import yt
+   ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030")
+   s = yt.SlicePlot(ds, 'z', 'density', center='c', width=(20, 'kpc'))
+   s.annotate_line_integral_convolution('velocity_x', 'velocity_y', lim=(0.5,0.65))
+   s.save()
+
 .. _annotate-text:
 
 Overplot Text

diff -r e15bcda96a05852c87ba3136739861800256be35 -r 0e6f92bca03e001b00f8f130a47c6d9d6fabc1ce yt/analysis_modules/absorption_spectrum/absorption_spectrum.py
--- a/yt/analysis_modules/absorption_spectrum/absorption_spectrum.py
+++ b/yt/analysis_modules/absorption_spectrum/absorption_spectrum.py
@@ -26,6 +26,10 @@
     boltzmann_constant_cgs, \
     speed_of_light_cgs
 from yt.utilities.on_demand_imports import _astropy
+from yt.utilities.parallel_tools.parallel_analysis_interface import \
+    _get_comm, \
+    parallel_objects, \
+    parallel_root_only
 
 pyfits = _astropy.pyfits
 
@@ -108,9 +112,9 @@
                                     'normalization': normalization,
                                     'index': index})
 
-    def make_spectrum(self, input_file, output_file='spectrum.h5',
-                      line_list_file='lines.txt',
-                      use_peculiar_velocity=True):
+    def make_spectrum(self, input_file, output_file="spectrum.h5",
+                      line_list_file="lines.txt",
+                      use_peculiar_velocity=True, njobs="auto"):
         """
         Make spectrum from ray data using the line list.
 
@@ -119,11 +123,35 @@
 
         input_file : string
            path to input ray data.
-        output_file : string
-           path for output file.  File formats are chosen based on the filename extension.
-           ``.h5`` for hdf5, ``.fits`` for fits, and everything else is ASCII.
-        use_peculiar_velocity : bool
+        output_file : optional, string
+           path for output file.  File formats are chosen based on the 
+           filename extension.  ``.h5`` for hdf5, ``.fits`` for fits, 
+           and everything else is ASCII.
+           Default: "spectrum.h5"
+        line_list_file : optional, string
+           path to file in which the list of all deposited lines 
+           will be saved.  If set to None, the line list will not 
+           be saved.  Note, when running in parallel, combining the 
+           line lists can be quite slow, so it is recommended to set 
+           this to None when running in parallel unless you really
+           want them.
+           Default: "lines.txt"
+        use_peculiar_velocity : optional, bool
            if True, include line of sight velocity for shifting lines.
+           Default: True
+        njobs : optional, int or "auto"
+           the number of process groups into which the loop over
+           absorption lines will be divided.  If set to -1, each 
+           absorption line will be deposited by exactly one processor.
+           If njobs is set to a value less than the total number of 
+           available processors (N), then the deposition of an 
+           individual line will be parallelized over (N / njobs)
+           processors.  If set to "auto", it will first try to 
+           parallelize over the list of lines and only parallelize 
+           the line deposition if there are more processors than
+           lines.  This is the optimal strategy for parallelizing 
+           spectrum generation.
+           Default: "auto"
         """
 
         input_fields = ['dl', 'redshift', 'temperature']
@@ -145,7 +173,12 @@
         self.tau_field = np.zeros(self.lambda_bins.size)
         self.spectrum_line_list = []
 
-        self._add_lines_to_spectrum(field_data, use_peculiar_velocity)
+        if njobs == "auto":
+            comm = _get_comm(())
+            njobs = min(comm.size, len(self.line_list))
+        
+        self._add_lines_to_spectrum(field_data, use_peculiar_velocity,
+                                    line_list_file is not None, njobs=njobs)
         self._add_continua_to_spectrum(field_data, use_peculiar_velocity)
 
         self.flux_field = np.exp(-self.tau_field)
@@ -156,7 +189,8 @@
             self._write_spectrum_fits(output_file)
         else:
             self._write_spectrum_ascii(output_file)
-        self._write_spectrum_line_list(line_list_file)
+        if line_list_file is not None:
+            self._write_spectrum_line_list(line_list_file)
 
         del field_data
         return (self.lambda_bins, self.flux_field)
@@ -196,7 +230,8 @@
                 pbar.update(i)
             pbar.finish()
 
-    def _add_lines_to_spectrum(self, field_data, use_peculiar_velocity):
+    def _add_lines_to_spectrum(self, field_data, use_peculiar_velocity,
+                               save_line_list, njobs=-1):
         """
         Add the absorption lines to the spectrum.
         """
@@ -205,7 +240,7 @@
         # Widen wavelength window until optical depth reaches a max value at the ends.
         max_tau = 0.001
 
-        for line in self.line_list:
+        for line in parallel_objects(self.line_list, njobs=njobs):
             column_density = field_data[line['field_name']] * field_data['dl']
             delta_lambda = line['wavelength'] * field_data['redshift']
             if use_peculiar_velocity:
@@ -238,7 +273,7 @@
                                    (right_index - left_index > 1))[0]
             pbar = get_pbar("Adding line - %s [%f A]: " % (line['label'], line['wavelength']),
                             valid_lines.size)
-            for i, lixel in enumerate(valid_lines):
+            for i, lixel in parallel_objects(enumerate(valid_lines), njobs=-1):
                 my_bin_ratio = spectrum_bin_ratio
                 while True:
                     lambda_bins, line_tau = \
@@ -261,7 +296,7 @@
                                           my_bin_ratio *
                                           width_ratio[lixel]).astype(int).clip(0, self.n_lambda)
                 self.tau_field[left_index[lixel]:right_index[lixel]] += line_tau
-                if line['label_threshold'] is not None and \
+                if save_line_list and line['label_threshold'] is not None and \
                         column_density[lixel] >= line['label_threshold']:
                     if use_peculiar_velocity:
                         peculiar_velocity = field_data['velocity_los'][lixel].in_units("km/s")
@@ -280,6 +315,13 @@
             del column_density, delta_lambda, thermal_b, \
                 center_bins, width_ratio, left_index, right_index
 
+        comm = _get_comm(())
+        self.tau_field = comm.mpi_allreduce(self.tau_field, op="sum")
+        if save_line_list:
+            self.spectrum_line_list = comm.par_combine_object(
+                self.spectrum_line_list, "cat", datatype="list")
+
+    @parallel_root_only
     def _write_spectrum_line_list(self, filename):
         """
         Write out list of spectral lines.
@@ -295,6 +337,7 @@
                                                 line['redshift'], line['v_pec']))
         f.close()
 
+    @parallel_root_only
     def _write_spectrum_ascii(self, filename):
         """
         Write spectrum to an ascii file.
@@ -307,6 +350,7 @@
                                     self.tau_field[i], self.flux_field[i]))
         f.close()
 
+    @parallel_root_only
     def _write_spectrum_fits(self, filename):
         """
         Write spectrum to a fits file.
@@ -318,6 +362,7 @@
         tbhdu = pyfits.BinTableHDU.from_columns(cols)
         tbhdu.writeto(filename, clobber=True)
 
+    @parallel_root_only
     def _write_spectrum_hdf5(self, filename):
         """
         Write spectrum to an hdf5 file.

diff -r e15bcda96a05852c87ba3136739861800256be35 -r 0e6f92bca03e001b00f8f130a47c6d9d6fabc1ce yt/data_objects/construction_data_containers.py
--- a/yt/data_objects/construction_data_containers.py
+++ b/yt/data_objects/construction_data_containers.py
@@ -682,11 +682,13 @@
     def RightEdge(self):
         return self.right_edge
 
-    def deposit(self, positions, fields = None, method = None):
+    def deposit(self, positions, fields = None, method = None,
+                kernel_name = 'cubic'):
         cls = getattr(particle_deposit, "deposit_%s" % method, None)
         if cls is None:
             raise YTParticleDepositionNotImplemented(method)
-        op = cls(self.ActiveDimensions.prod()) # We allocate number of zones, not number of octs
+        # We allocate number of zones, not number of octs
+        op = cls(self.ActiveDimensions.prod(), kernel_name)
         op.initialize()
         op.process_grid(self, positions, fields)
         vals = op.finalize()
@@ -1787,5 +1789,3 @@
         else:
             mylog.error("Problem uploading.")
         return upload_id
-
-

diff -r e15bcda96a05852c87ba3136739861800256be35 -r 0e6f92bca03e001b00f8f130a47c6d9d6fabc1ce yt/data_objects/derived_quantities.py
--- a/yt/data_objects/derived_quantities.py
+++ b/yt/data_objects/derived_quantities.py
@@ -542,16 +542,19 @@
         return rv
 
     def process_chunk(self, data, field):
+        axis_names = data.ds.coordinates.axis_name
         field = data._determine_fields(field)[0]
         ma = array_like_field(data, -HUGE, field)
-        mx = array_like_field(data, -1, "x")
-        my = array_like_field(data, -1, "y")
-        mz = array_like_field(data, -1, "z")
+        mx = array_like_field(data, -1, axis_names[0])
+        my = array_like_field(data, -1, axis_names[1])
+        mz = array_like_field(data, -1, axis_names[2])
         maxi = -1
         if data[field].size > 0:
             maxi = np.argmax(data[field])
             ma = data[field][maxi]
-            mx, my, mz = [data[ax][maxi] for ax in 'xyz']
+            mx, my, mz = [data[ax][maxi] for ax in (axis_names[0],
+                                                    axis_names[1],
+                                                    axis_names[2])]
         return (ma, maxi, mx, my, mz)
 
     def reduce_intermediate(self, values):

diff -r e15bcda96a05852c87ba3136739861800256be35 -r 0e6f92bca03e001b00f8f130a47c6d9d6fabc1ce yt/data_objects/grid_patch.py
--- a/yt/data_objects/grid_patch.py
+++ b/yt/data_objects/grid_patch.py
@@ -330,12 +330,14 @@
     def particle_operation(self, *args, **kwargs):
         raise NotImplementedError
 
-    def deposit(self, positions, fields = None, method = None):
+    def deposit(self, positions, fields = None, method = None,
+                kernel_name = 'cubic'):
         # Here we perform our particle deposition.
         cls = getattr(particle_deposit, "deposit_%s" % method, None)
         if cls is None:
             raise YTParticleDepositionNotImplemented(method)
-        op = cls(self.ActiveDimensions.prod()) # We allocate number of zones, not number of octs
+        # We allocate number of zones, not number of octs
+        op = cls(self.ActiveDimensions.prod(), kernel_name)
         op.initialize()
         op.process_grid(self, positions, fields)
         vals = op.finalize()

diff -r e15bcda96a05852c87ba3136739861800256be35 -r 0e6f92bca03e001b00f8f130a47c6d9d6fabc1ce yt/data_objects/octree_subset.py
--- a/yt/data_objects/octree_subset.py
+++ b/yt/data_objects/octree_subset.py
@@ -141,7 +141,8 @@
             self._domain_ind = di
         return self._domain_ind
 
-    def deposit(self, positions, fields = None, method = None):
+    def deposit(self, positions, fields = None, method = None,
+                kernel_name='cubic'):
         r"""Operate on the mesh, in a particle-against-mesh fashion, with
         exclusively local input.
 
@@ -176,7 +177,8 @@
             raise YTParticleDepositionNotImplemented(method)
         nz = self.nz
         nvals = (nz, nz, nz, (self.domain_ind >= 0).sum())
-        op = cls(nvals) # We allocate number of zones, not number of octs
+        # We allocate number of zones, not number of octs
+        op = cls(nvals, kernel_name)
         op.initialize()
         mylog.debug("Depositing %s (%s^3) particles into %s Octs",
             positions.shape[0], positions.shape[0]**0.3333333, nvals[-1])
@@ -192,7 +194,8 @@
         return np.asfortranarray(vals)
 
     def smooth(self, positions, fields = None, index_fields = None,
-               method = None, create_octree = False, nneighbors = 64):
+               method = None, create_octree = False, nneighbors = 64,
+               kernel_name = 'cubic'):
         r"""Operate on the mesh, in a particle-against-mesh fashion, with
         non-local input.
 
@@ -258,7 +261,7 @@
         nz = self.nz
         mdom_ind = self.domain_ind
         nvals = (nz, nz, nz, (mdom_ind >= 0).sum())
-        op = cls(nvals, len(fields), nneighbors)
+        op = cls(nvals, len(fields), nneighbors, kernel_name)
         op.initialize()
         mylog.debug("Smoothing %s particles into %s Octs",
             positions.shape[0], nvals[-1])
@@ -280,7 +283,7 @@
         return vals
 
     def particle_operation(self, positions, fields = None,
-            method = None, nneighbors = 64):
+            method = None, nneighbors = 64, kernel_name = 'cubic'):
         r"""Operate on particles, in a particle-against-particle fashion.
 
         This uses the octree indexing system to call a "smoothing" operation
@@ -335,7 +338,7 @@
         nz = self.nz
         mdom_ind = self.domain_ind
         nvals = (nz, nz, nz, (mdom_ind >= 0).sum())
-        op = cls(nvals, len(fields), nneighbors)
+        op = cls(nvals, len(fields), nneighbors, kernel_name)
         op.initialize()
         mylog.debug("Smoothing %s particles into %s Octs",
             positions.shape[0], nvals[-1])

diff -r e15bcda96a05852c87ba3136739861800256be35 -r 0e6f92bca03e001b00f8f130a47c6d9d6fabc1ce yt/data_objects/static_output.py
--- a/yt/data_objects/static_output.py
+++ b/yt/data_objects/static_output.py
@@ -713,6 +713,7 @@
                               unit_registry=self.unit_registry))
             setattr(self, "critical_density",
                     self.cosmology.critical_density(self.current_redshift))
+            self.scale_factor = 1.0 / (1.0 + self.current_redshift)
 
     def get_unit_from_registry(self, unit_str):
         """

diff -r e15bcda96a05852c87ba3136739861800256be35 -r 0e6f92bca03e001b00f8f130a47c6d9d6fabc1ce yt/data_objects/unstructured_mesh.py
--- a/yt/data_objects/unstructured_mesh.py
+++ b/yt/data_objects/unstructured_mesh.py
@@ -105,13 +105,15 @@
     def select_tcoords(self, dobj):
         raise NotImplementedError
 
-    def deposit(self, positions, fields = None, method = None):
+    def deposit(self, positions, fields = None, method = None,
+                kernel_name = 'cubic'):
         raise NotImplementedError
         # Here we perform our particle deposition.
         cls = getattr(particle_deposit, "deposit_%s" % method, None)
         if cls is None:
             raise YTParticleDepositionNotImplemented(method)
-        op = cls(self.ActiveDimensions.prod()) # We allocate number of zones, not number of octs
+        # We allocate number of zones, not number of octs
+        op = cls(self.ActiveDimensions.prod(), kernel_name)
         op.initialize()
         op.process_grid(self, positions, fields)
         vals = op.finalize()
@@ -200,4 +202,3 @@
             else:
                 self._last_count = mask.sum()
         return mask
-

diff -r e15bcda96a05852c87ba3136739861800256be35 -r 0e6f92bca03e001b00f8f130a47c6d9d6fabc1ce yt/fields/particle_fields.py
--- a/yt/fields/particle_fields.py
+++ b/yt/fields/particle_fields.py
@@ -766,8 +766,12 @@
 
 def add_volume_weighted_smoothed_field(ptype, coord_name, mass_name,
         smoothing_length_name, density_name, smoothed_field, registry,
-        nneighbors = None):
-    field_name = ("deposit", "%s_smoothed_%s" % (ptype, smoothed_field))
+        nneighbors = None, kernel_name = 'cubic'):
+    if kernel_name == 'cubic':
+        field_name = ("deposit", "%s_smoothed_%s" % (ptype, smoothed_field))
+    else:
+        field_name = ("deposit", "%s_%s_smoothed_%s" % (ptype, kernel_name,
+                      smoothed_field))
     field_units = registry[ptype, smoothed_field].units
     def _vol_weight(field, data):
         pos = data[ptype, coord_name]
@@ -789,7 +793,8 @@
         # volume_weighted smooth operations return lists of length 1.
         rv = data.smooth(pos, [mass, hsml, dens, quan],
                          method="volume_weighted",
-                         create_octree=True)[0]
+                         create_octree=True,
+                         kernel_name=kernel_name)[0]
         rv[np.isnan(rv)] = 0.0
         # Now some quick unit conversions.
         rv = data.apply_units(rv, field_units)
@@ -816,8 +821,12 @@
                        units = "code_length")
     return [field_name]
 
-def add_density_kernel(ptype, coord_name, mass_name, registry, nneighbors = 64):
-    field_name = (ptype, "smoothed_density")
+def add_density_kernel(ptype, coord_name, mass_name, registry, nneighbors = 64,
+                       kernel_name = 'cubic'):
+    if kernel_name == 'cubic':
+        field_name = (ptype, "smoothed_density")
+    else:
+        field_name = (ptype, "%s_smoothed_density" % (kernel_name))
     field_units = registry[ptype, mass_name].units
     def _nth_neighbor(field, data):
         pos = data[ptype, coord_name]
@@ -827,7 +836,8 @@
         densities = mass * 0.0
         data.particle_operation(pos, [mass, densities],
                          method="density",
-                         nneighbors = nneighbors)
+                         nneighbors = nneighbors,
+                         kernel_name = kernel_name)
         ones = pos.prod(axis=1) # Get us in code_length**3
         ones[:] = 1.0
         densities /= ones

diff -r e15bcda96a05852c87ba3136739861800256be35 -r 0e6f92bca03e001b00f8f130a47c6d9d6fabc1ce yt/frontends/artio/data_structures.py
--- a/yt/frontends/artio/data_structures.py
+++ b/yt/frontends/artio/data_structures.py
@@ -133,7 +133,8 @@
         tr = dict((field, v) for field, v in zip(fields, tr))
         return tr
 
-    def deposit(self, positions, fields = None, method = None):
+    def deposit(self, positions, fields = None, method = None,
+                kernel_name = 'cubic'):
         # Here we perform our particle deposition.
         if fields is None: fields = []
         cls = getattr(particle_deposit, "deposit_%s" % method, None)
@@ -141,7 +142,8 @@
             raise YTParticleDepositionNotImplemented(method)
         nz = self.nz
         nvals = (nz, nz, nz, self.ires.size)
-        op = cls(nvals) # We allocate number of zones, not number of octs
+        # We allocate number of zones, not number of octs
+        op = cls(nvals, kernel_name)
         op.initialize()
         mylog.debug("Depositing %s (%s^3) particles into %s Root Mesh",
             positions.shape[0], positions.shape[0]**0.3333333, nvals[-1])

diff -r e15bcda96a05852c87ba3136739861800256be35 -r 0e6f92bca03e001b00f8f130a47c6d9d6fabc1ce yt/frontends/artio/setup.py
--- a/yt/frontends/artio/setup.py
+++ b/yt/frontends/artio/setup.py
@@ -19,7 +19,8 @@
                          depends=artio_sources + 
                                  ["yt/utilities/lib/fp_utils.pxd",
                                   "yt/geometry/oct_container.pxd",
-                                  "yt/geometry/selection_routines.pxd"])
+                                  "yt/geometry/selection_routines.pxd",
+                                  "yt/geometry/particle_deposit.pxd"])
     config.make_config_py()  # installs __config__.py
     #config.make_svn_version_py()
     return config

diff -r e15bcda96a05852c87ba3136739861800256be35 -r 0e6f92bca03e001b00f8f130a47c6d9d6fabc1ce yt/frontends/ramses/data_structures.py
--- a/yt/frontends/ramses/data_structures.py
+++ b/yt/frontends/ramses/data_structures.py
@@ -491,26 +491,18 @@
         """
         Generates the conversion to various physical _units based on the parameter file
         """
-        #Please note that for all units given in the info file, the boxlen
-        #still needs to be folded in, as shown below!
+        # loading the units from the info file
+        boxlen=self.parameters['boxlen']
+        length_unit = self.parameters['unit_l']
+        density_unit = self.parameters['unit_d']
+        time_unit = self.parameters['unit_t']
 
-        boxlen=self.parameters['boxlen']
-        length_unit = self.parameters['unit_l'] * boxlen
-        density_unit = self.parameters['unit_d']/ boxlen**3
-
-        # In the mass unit, the factors of boxlen cancel back out, so this 
-        #is equivalent to unit_d*unit_l**3
-
-        mass_unit = density_unit * length_unit**3
-
-        # Cosmological runs are done in lookback conformal time. 
-        # To convert to proper time, the time unit is calculated from 
-        # the expansion factor. This is not yet  done here!
-
-        time_unit = self.parameters['unit_t']
+        # calculating derived units (except velocity and temperature, done below)
+        mass_unit = density_unit * length_unit**3     
         magnetic_unit = np.sqrt(4*np.pi * mass_unit /
                                 (time_unit**2 * length_unit))
         pressure_unit = density_unit * (length_unit / time_unit)**2
+
         # TODO:
         # Generalize the temperature field to account for ionization
         # For now assume an atomic ideal gas with cosmic abundances (x_H = 0.76)
@@ -518,13 +510,15 @@
 
         self.density_unit = self.quan(density_unit, 'g/cm**3')
         self.magnetic_unit = self.quan(magnetic_unit, "gauss")
+        self.pressure_unit = self.quan(pressure_unit, 'dyne/cm**2')
+        self.time_unit = self.quan(time_unit, "s")
+        self.mass_unit = self.quan(mass_unit, "g")
+        self.velocity_unit = self.quan(length_unit, 'cm') / self.time_unit
+        self.temperature_unit = (self.velocity_unit**2*mp* 
+                                 mean_molecular_weight_factor/kb).in_units('K')
+
+        # Only the length unit get scales by a factor of boxlen
         self.length_unit = self.quan(length_unit * boxlen, "cm")
-        self.mass_unit = self.quan(mass_unit, "g")
-        self.time_unit = self.quan(time_unit, "s")
-        self.velocity_unit = self.quan(length_unit, 'cm') / self.time_unit
-        self.temperature_unit = (self.velocity_unit**2 * mp *
-                                 mean_molecular_weight_factor / kb)
-        self.pressure_unit = self.quan(pressure_unit, 'dyne/cm**2')
 
     def _parse_parameter_file(self):
         # hardcoded for now

diff -r e15bcda96a05852c87ba3136739861800256be35 -r 0e6f92bca03e001b00f8f130a47c6d9d6fabc1ce yt/geometry/particle_deposit.pxd
--- a/yt/geometry/particle_deposit.pxd
+++ b/yt/geometry/particle_deposit.pxd
@@ -38,7 +38,7 @@
 # Standard SPH kernel for use with the Grid method #
 ####################################################
 
-cdef inline np.float64_t sph_kernel(np.float64_t x) nogil:
+cdef inline np.float64_t sph_kernel_cubic(np.float64_t x) nogil:
     cdef np.float64_t kernel
     if x <= 0.5:
         kernel = 1.-6.*x*x*(1.-x)
@@ -48,8 +48,55 @@
         kernel = 0.
     return kernel
 
+########################################################
+# Alternative SPH kernels for use with the Grid method #
+########################################################
+
+# quartic spline
+cdef inline np.float64_t sph_kernel_quartic(np.float64_t x):
+    cdef np.float64_t kernel
+    cdef np.float64_t C = 5.**6/512/np.pi
+    if x < 1:
+        kernel = (1.-x)**4
+        if x < 3./5:
+            kernel -= 5*(3./5-x)**4
+            if x < 1./5:
+                kernel += 10*(1./5-x)**4
+    else:
+        kernel = 0.
+    return kernel * C
+
+# quintic spline
+cdef inline np.float64_t sph_kernel_quintic(np.float64_t x):
+    cdef np.float64_t kernel
+    cdef np.float64_t C = 3.**7/40/np.pi
+    if x < 1:
+        kernel = (1.-x)**5
+        if x < 2./3:
+            kernel -= 6*(2./3-x)**5
+            if x < 1./3:
+                kernel += 15*(1./3-x)**5
+    else:
+        kernel = 0.
+    return kernel * C
+
+# I don't know the way to use a dict in a cdef class.
+# So in order to mimic a registry functionality,
+# I manually created a function to lookup the kernel functions.
+ctypedef np.float64_t (*kernel_func) (np.float64_t)
+cdef inline kernel_func get_kernel_func(str kernel_name):
+    if kernel_name == 'cubic':
+        return sph_kernel_cubic
+    elif kernel_name == 'quartic':
+        return sph_kernel_quartic
+    elif kernel_name == 'quintic':
+        return sph_kernel_quintic
+    else:
+        raise NotImplementedError
+
 cdef class ParticleDepositOperation:
     # We assume each will allocate and define their own temporary storage
+    cdef kernel_func sph_kernel
     cdef public object nvals
     cdef public int update_values
     cdef void process(self, int dim[3], np.float64_t left_edge[3],

diff -r e15bcda96a05852c87ba3136739861800256be35 -r 0e6f92bca03e001b00f8f130a47c6d9d6fabc1ce yt/geometry/particle_deposit.pyx
--- a/yt/geometry/particle_deposit.pyx
+++ b/yt/geometry/particle_deposit.pyx
@@ -25,9 +25,10 @@
     OctreeContainer, OctInfo
 
 cdef class ParticleDepositOperation:
-    def __init__(self, nvals):
+    def __init__(self, nvals, kernel_name):
         self.nvals = nvals
         self.update_values = 0 # This is the default
+        self.sph_kernel = get_kernel_func(kernel_name)
 
     def initialize(self, *args):
         raise NotImplementedError
@@ -227,7 +228,7 @@
                     dist = idist[0] + idist[1] + idist[2]
                     # Calculate distance in multiples of the smoothing length
                     dist = sqrt(dist) / fields[0]
-                    self.temp[gind(i,j,k,dim) + offset] = sph_kernel(dist)
+                    self.temp[gind(i,j,k,dim) + offset] = self.sph_kernel(dist)
                     kernel_sum += self.temp[gind(i,j,k,dim) + offset]
         # Having found the kernel, deposit accordingly into gdata
         for i from ib0[0] <= i <= ib1[0]:
@@ -493,4 +494,3 @@
         return self.onnfield
 
 deposit_nearest = NNParticleField
-

diff -r e15bcda96a05852c87ba3136739861800256be35 -r 0e6f92bca03e001b00f8f130a47c6d9d6fabc1ce yt/geometry/particle_smooth.pxd
--- a/yt/geometry/particle_smooth.pxd
+++ b/yt/geometry/particle_smooth.pxd
@@ -22,7 +22,7 @@
 
 from fp_utils cimport *
 from oct_container cimport Oct, OctAllocationContainer, OctreeContainer
-from .particle_deposit cimport sph_kernel, gind
+from .particle_deposit cimport kernel_func, get_kernel_func, gind
 
 cdef extern from "platform_dep.h":
     void *alloca(int)
@@ -34,6 +34,7 @@
 
 cdef class ParticleSmoothOperation:
     # We assume each will allocate and define their own temporary storage
+    cdef kernel_func sph_kernel
     cdef public object nvals
     cdef np.float64_t DW[3]
     cdef int nfields

diff -r e15bcda96a05852c87ba3136739861800256be35 -r 0e6f92bca03e001b00f8f130a47c6d9d6fabc1ce yt/geometry/particle_smooth.pyx
--- a/yt/geometry/particle_smooth.pyx
+++ b/yt/geometry/particle_smooth.pyx
@@ -74,7 +74,7 @@
     opos[2] = ipos[2]
 
 cdef class ParticleSmoothOperation:
-    def __init__(self, nvals, nfields, max_neighbors):
+    def __init__(self, nvals, nfields, max_neighbors, kernel_name):
         # This is the set of cells, in grids, blocks or octs, we are handling.
         cdef int i
         self.nvals = nvals
@@ -83,6 +83,7 @@
         self.neighbors = <NeighborList *> malloc(
             sizeof(NeighborList) * self.maxn)
         self.neighbor_reset()
+        self.sph_kernel = get_kernel_func(kernel_name)
 
     def initialize(self, *args):
         raise NotImplementedError
@@ -630,7 +631,7 @@
             # Usually this density has been computed
             dens = fields[2][pn]
             if dens == 0.0: continue
-            weight = mass * sph_kernel(sqrt(r2) / hsml) / dens
+            weight = mass * self.sph_kernel(sqrt(r2) / hsml) / dens
             # Mass of the particle times the value
             for fi in range(self.nfields - 3):
                 val = fields[fi + 3][pn]
@@ -756,7 +757,7 @@
         for pn in range(self.curn):
             mass = fields[0][self.neighbors[pn].pn]
             r2 = self.neighbors[pn].r2
-            lw = sph_kernel(sqrt(r2) / hsml)
+            lw = self.sph_kernel(sqrt(r2) / hsml)
             dens += mass * lw
         weight = (4.0/3.0) * 3.1415926 * hsml**3
         fields[1][offset] = dens/weight

diff -r e15bcda96a05852c87ba3136739861800256be35 -r 0e6f92bca03e001b00f8f130a47c6d9d6fabc1ce yt/utilities/lib/api.py
--- a/yt/utilities/lib/api.py
+++ b/yt/utilities/lib/api.py
@@ -29,3 +29,4 @@
 from .write_array import *
 from .mesh_utilities import *
 from .ContourFinding import *
+from .line_integral_convolution import *

diff -r e15bcda96a05852c87ba3136739861800256be35 -r 0e6f92bca03e001b00f8f130a47c6d9d6fabc1ce yt/utilities/lib/line_integral_convolution.pyx
--- /dev/null
+++ b/yt/utilities/lib/line_integral_convolution.pyx
@@ -0,0 +1,109 @@
+"""
+Utilities for line integral convolution annotation
+
+
+
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (c) 2015, yt Development Team.
+#
+# Code originally from Scipy Cookbook (http://wiki.scipy.org/Cookbook/LineIntegralConvolution),
+# with bug fixed which leads to crash when non equal-size vector field in two
+# dimensions is provided.
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+
+import numpy as np
+cimport numpy as np
+cimport cython
+
+ at cython.cdivision(True)
+cdef void _advance_2d(double vx, double vy,
+                     int* x, int* y,
+                     double* fx, double* fy,
+                     int w, int h):
+    cdef double tx, ty
+    if vx>=0:
+        tx = (1-fx[0])/vx
+    else:
+        tx = -fx[0]/vx
+    if vy>=0:
+        ty = (1-fy[0])/vy
+    else:
+        ty = -fy[0]/vy
+    if tx<ty:
+        if vx>=0:
+            x[0]+=1
+            fx[0]=0
+        else:
+            x[0]-=1
+            fx[0]=1
+        fy[0]+=tx*vy
+    else:
+        if vy>=0:
+            y[0]+=1
+            fy[0]=0
+        else:
+            y[0]-=1
+            fy[0]=1
+        fx[0]+=ty*vx
+    if x[0]>=w:
+        x[0]=w-1
+    if x[0]<0:
+        x[0]=0
+    if y[0]<0:
+        y[0]=0
+    if y[0]>=h:
+        y[0]=h-1
+
+def line_integral_convolution_2d(
+        np.ndarray[double, ndim=3] vectors,
+        np.ndarray[double, ndim=2] texture,
+        np.ndarray[double, ndim=1] kernel):
+    cdef int i,j,l,x,y
+    cdef int h,w,kernellen
+    cdef int t
+    cdef double fx, fy, tx, ty
+    cdef np.ndarray[double, ndim=2] result
+
+    w = vectors.shape[0]
+    h = vectors.shape[1]
+    t = vectors.shape[2]
+
+    kernellen = kernel.shape[0]
+    result = np.zeros((w,h),dtype=np.double)
+
+    vectors = vectors[...,::-1].copy()
+
+    for i in range(w):
+        for j in range(h):
+            x = i
+            y = j
+            fx = 0.5
+            fy = 0.5
+            
+            l = kernellen//2
+            result[i,j] += kernel[l]*texture[x,y]
+            while l<kernellen-1:
+                _advance_2d(vectors[x,y,0],vectors[x,y,1],
+                        &x, &y, &fx, &fy, w, h)
+                l+=1
+                result[i,j] += kernel[l]*texture[x,y]
+            
+            x = i
+            y = j
+            fx = 0.5
+            fy = 0.5
+            
+            while l>0:
+                _advance_2d(-vectors[x,y,0],-vectors[x,y,1],
+                        &x, &y, &fx, &fy, w, h)
+                l-=1
+                result[i,j] += kernel[l]*texture[x,y]
+                    
+    return result

diff -r e15bcda96a05852c87ba3136739861800256be35 -r 0e6f92bca03e001b00f8f130a47c6d9d6fabc1ce yt/utilities/lib/setup.py
--- a/yt/utilities/lib/setup.py
+++ b/yt/utilities/lib/setup.py
@@ -155,6 +155,8 @@
     config.add_extension("amr_kdtools", 
                          ["yt/utilities/lib/amr_kdtools.pyx"],
                          libraries=["m"], depends=["yt/utilities/lib/fp_utils.pxd"])
+    config.add_extension("line_integral_convolution",
+                         ["yt/utilities/lib/line_integral_convolution.pyx"])
     config.add_subpackage("tests")
 
     if os.environ.get("GPERFTOOLS", "no").upper() != "NO":

diff -r e15bcda96a05852c87ba3136739861800256be35 -r 0e6f92bca03e001b00f8f130a47c6d9d6fabc1ce yt/visualization/plot_modifications.py
--- a/yt/visualization/plot_modifications.py
+++ b/yt/visualization/plot_modifications.py
@@ -24,6 +24,7 @@
 
 from matplotlib.patches import Circle
 from matplotlib.colors import colorConverter
+from matplotlib import cm
 from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
 
 from yt.funcs import \
@@ -33,7 +34,11 @@
 from yt.visualization.image_writer import apply_colormap
 from yt.utilities.lib.geometry_utils import triangle_plane_intersect
 from yt.analysis_modules.cosmological_observation.light_ray.light_ray \
-    import periodic_ray
+     import periodic_ray
+from yt.utilities.lib.line_integral_convolution import \
+    line_integral_convolution_2d
+import warnings
+
 
 from . import _MPL
 
@@ -2049,3 +2054,120 @@
             lcb(plot)
 
         return plot
+
+class LineIntegralConvolutionCallback(PlotCallback):
+    """
+    annotate_line_integral_convolution(field_x, field_y, texture=None,
+                                       kernellen=50., lim=(0.5,0.6),
+                                       cmap='binary', alpha=0.8,
+                                       const_alpha=False):
+
+    Add the line integral convolution to the plot for vector fields 
+    visualization. Two component of vector fields needed to be provided
+    (i.e., velocity_x and velocity_y, magentic_field_x and magnetic_field_y).
+
+    Parameters
+    ----------
+
+    field_x, field_y : string
+        The names of two components of vector field which will be visualized
+
+    texture : 2-d array with the same shape of image, optional
+        Texture will be convolved when computing line integral convolution.
+        A white noise background will be used as default.
+
+    kernellen : float, optional
+        The lens of kernel for convolution, which is the length over which the
+        convolution will be performed. For longer kernellen, longer streamline
+        structure will appear.
+
+    lim : 2-element tuple, list, or array, optional
+        The value of line integral convolution will be clipped to the range
+        of lim, which applies upper and lower bounds to the values of line
+        integral convolution and enhance the visibility of plots. Each element
+        should be in the range of [0,1].
+
+    cmap : string, optional
+        The name of colormap for line integral convolution plot.
+
+    alpha : float, optional
+        The alpha value for line integral convolution plot.
+
+    const_alpha : boolean, optional
+        If set to False (by default), alpha will be weighted spatially by
+        the values of line integral convolution; otherwise a constant value
+        of the given alpha is used.
+
+    Example
+    -------
+
+    >>> import yt
+    >>> ds = yt.load('Enzo_64/DD0020/data0020')
+    >>> s = yt.SlicePlot(ds, 'z', 'density')
+    >>> s.annotate_line_integral_convolution('velocity_x', 'velocity_y',\
+                                             lim=(0.5,0.65))
+    """
+    _type_name = "line_integral_convolution"
+    def __init__(self, field_x, field_y, texture=None, kernellen=50.,
+                 lim=(0.5,0.6), cmap='binary', alpha=0.8, const_alpha=False):
+        PlotCallback.__init__(self)
+        self.field_x = field_x
+        self.field_y = field_y
+        self.texture = texture
+        self.kernellen = kernellen
+        self.lim = lim
+        self.cmap = cmap
+        self.alpha = alpha
+        self.const_alpha = const_alpha
+
+    def __call__(self, plot):
+        x0, x1 = plot.xlim
+        y0, y1 = plot.ylim
+        xx0, xx1 = plot._axes.get_xlim()
+        yy0, yy1 = plot._axes.get_ylim()
+        bounds = [x0,x1,y0,y1]
+        extent = [xx0,xx1,yy0,yy1]
+
+        plot._axes.hold(True)
+        nx = plot.image._A.shape[0]
+        ny = plot.image._A.shape[1]
+        pixX = plot.data.ds.coordinates.pixelize(plot.data.axis,
+                                                 plot.data,
+                                                 self.field_x,
+                                                 bounds,
+                                                 (nx,ny))
+        pixY = plot.data.ds.coordinates.pixelize(plot.data.axis,
+                                                 plot.data,
+                                                 self.field_y,
+                                                 bounds,
+                                                 (nx,ny))
+
+        vectors = np.concatenate((pixX[...,np.newaxis],
+                                  pixY[...,np.newaxis]),axis=2)
+
+        if self.texture == None:
+            self.texture = np.random.rand(nx,ny).astype(np.double)
+        elif self.texture.shape != (nx,ny):
+            raise SyntaxError("'texture' must have the same shape "
+                              "with that of output image (%d, %d)" % (nx,ny))
+
+        kernel = np.sin(np.arange(self.kernellen)*np.pi/self.kernellen)
+        kernel = kernel.astype(np.double)
+
+        lic_data = line_integral_convolution_2d(vectors,self.texture,kernel)
+        lic_data = np.flipud(lic_data / lic_data.max())
+        lic_data_clip = np.clip(lic_data,self.lim[0],self.lim[1])
+
+        if self.const_alpha:
+            plot._axes.imshow(lic_data_clip, extent=extent, cmap=self.cmap, 
+                              alpha=self.alpha)
+        else:
+            lic_data_rgba = cm.ScalarMappable(norm=None, cmap=self.cmap).\
+                            to_rgba(lic_data_clip)
+            lic_data_clip_rescale = (lic_data_clip - self.lim[0]) \
+                                    / (self.lim[1] - self.lim[0])
+            lic_data_rgba[...,3] = lic_data_clip_rescale * self.alpha
+            plot._axes.imshow(lic_data_rgba, extent=extent)
+        plot._axes.hold(False)
+
+        return plot

diff -r e15bcda96a05852c87ba3136739861800256be35 -r 0e6f92bca03e001b00f8f130a47c6d9d6fabc1ce yt/visualization/tests/test_callbacks.py
--- a/yt/visualization/tests/test_callbacks.py
+++ b/yt/visualization/tests/test_callbacks.py
@@ -54,6 +54,7 @@
 #  X scale
 #    material_boundary
 #  X ray
+#  X line_integral_convolution
 
 @contextlib.contextmanager
 def _cleanup_fname():
@@ -328,3 +329,25 @@
             max_level=3, cmap="gist_stern")
         p.save(prefix)
 
+def test_line_integral_convolution_callback():
+    with _cleanup_fname() as prefix:
+        ds = fake_amr_ds(fields =
+            ("density", "velocity_x", "velocity_y", "velocity_z"))
+        for ax in 'xyz':
+            p = ProjectionPlot(ds, ax, "density")
+            p.annotate_line_integral_convolution("velocity_x", "velocity_y")
+            yield assert_fname, p.save(prefix)[0]
+            p = ProjectionPlot(ds, ax, "density", weight_field="density")
+            p.annotate_line_integral_convolution("velocity_x", "velocity_y")
+            yield assert_fname, p.save(prefix)[0]
+            p = SlicePlot(ds, ax, "density")
+            p.annotate_line_integral_convolution("velocity_x", "velocity_y")
+            yield assert_fname, p.save(prefix)[0]
+        # Now we'll check a few additional minor things
+        p = SlicePlot(ds, "x", "density")
+        p.annotate_line_integral_convolution("velocity_x", "velocity_y", 
+                                             kernellen=100., lim=(0.4,0.7),
+                                             cmap='algae', alpha=0.9,
+                                             const_alpha=True)
+        p.save(prefix)
+


https://bitbucket.org/yt_analysis/yt/commits/deeb92e93357/
Changeset:   deeb92e93357
Branch:      yt
User:        chummels
Date:        2015-08-20 16:38:55+00:00
Summary:     Merged in ngoldbaum/yt (pull request #1704)

Linting yt.visualization, removing some unused code
Affected #:  27 files

diff -r 5f98bb340f15ac0d73ba37156dba9ed24d0691d6 -r deeb92e93357a433dd56e83a339a2192ca42e9e1 doc/source/reference/api/api.rst
--- a/doc/source/reference/api/api.rst
+++ b/doc/source/reference/api/api.rst
@@ -610,10 +610,8 @@
 .. autosummary::
    :toctree: generated/
 
-   ~yt.visualization.volume_rendering.camera.MosaicFisheyeCamera
    ~yt.visualization.volume_rendering.camera.FisheyeCamera
    ~yt.visualization.volume_rendering.camera.MosaicCamera
-   ~yt.visualization.volume_rendering.camera.plot_allsky_healpix
    ~yt.visualization.volume_rendering.camera.PerspectiveCamera
    ~yt.utilities.amr_kdtree.amr_kdtree.AMRKDTree
    ~yt.visualization.volume_rendering.camera.StereoPairCamera

diff -r 5f98bb340f15ac0d73ba37156dba9ed24d0691d6 -r deeb92e93357a433dd56e83a339a2192ca42e9e1 yt/visualization/api.py
--- a/yt/visualization/api.py
+++ b/yt/visualization/api.py
@@ -43,9 +43,6 @@
     PlotCallback, \
     callback_registry
 
-from .easy_plots import \
-    plot_type_registry
-
 from .streamlines import \
     Streamlines
 

diff -r 5f98bb340f15ac0d73ba37156dba9ed24d0691d6 -r deeb92e93357a433dd56e83a339a2192ca42e9e1 yt/visualization/color_maps.py
--- a/yt/visualization/color_maps.py
+++ b/yt/visualization/color_maps.py
@@ -22,7 +22,7 @@
 
 def check_color(name):
     try:
-        ss = cc.colorConverter.to_rgb(name)
+        cc.colorConverter.to_rgb(name)
         return True
     except ValueError:
         return False

diff -r 5f98bb340f15ac0d73ba37156dba9ed24d0691d6 -r deeb92e93357a433dd56e83a339a2192ca42e9e1 yt/visualization/easy_plots.py
--- a/yt/visualization/easy_plots.py
+++ /dev/null
@@ -1,61 +0,0 @@
-"""
-Easy plotting.
-
-
-
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-from ._mpl_imports import *
-from yt.data_objects.profiles import BinnedProfile1D
-
-plot_type_registry = {}
-
-class EasyPlot(object):
-    class __metaclass__(type):
-        def __init__(cls, name, b, d):
-            type.__init__(cls, name, b, d)
-            if hasattr(cls, "_type_name"):
-                plot_type_registry[cls._type_name] = cls
-
-    def __init__(self):
-        pass
-
-    def save(self, fn):
-        canvas = FigureCanvasAgg(self.figure)
-        canvas.print_figure(fn)
-
-class EasyPDFPlot(EasyPlot):
-    _type_name = "PDF"
-
-    def __init__(self, data_source, x_field, x_log = True,
-                 n_bins = 128, y_log = True,
-                 plot_args = None,
-                 figure_args = None):
-        if plot_args is None: plot_args = {}
-        if figure_args is None: figure_args = {}
-        self.x_field = x_field
-        self.data_source = data_source
-        # Now we just make the plot
-        x_min, x_max = self.data_source.quantities["Extrema"](
-                x_field, non_zero = x_log)[0]
-        self.profile = BinnedProfile1D(self.data_source,
-            n_bins, self.x_field, x_min, x_max, x_log)
-        self.profile.add_fields(["CellMassMsun"], weight=None)
-        self.profile["CellMassMsun"] /= self.profile["CellMassMsun"].sum()
-        self.figure = matplotlib.figure.Figure(**figure_args)
-        self.axes = self.figure.add_subplot(1,1,1)
-        if y_log and x_log: f = self.axes.loglog
-        elif y_log: f = self.axes.semilogy
-        elif x_log: f = self.axes.semilogx
-        else: f = self.axes.plot
-        self.plot = f(self.profile[x_field], self.profile["CellMassMsun"],
-                      **plot_args)
-        self.axes.set_xlabel(data_source.ds.field_info[x_field].get_label())

diff -r 5f98bb340f15ac0d73ba37156dba9ed24d0691d6 -r deeb92e93357a433dd56e83a339a2192ca42e9e1 yt/visualization/eps_writer.py
--- a/yt/visualization/eps_writer.py
+++ b/yt/visualization/eps_writer.py
@@ -22,7 +22,7 @@
 from yt.utilities.logger import ytLogger as mylog
 from .plot_window import PlotWindow
 from .profile_plotter import PhasePlot, ProfilePlot
-from yt.units.yt_array import YTArray, YTQuantity
+from yt.units.yt_array import YTQuantity
 from yt.units.unit_object import Unit
 
 def convert_frac_to_tex(string):
@@ -271,7 +271,7 @@
                           (width=psize[0], height=psize[1],
                            x=xaxis, y=yaxis, x2=xaxis2, y2=yaxis2,
                            xpos=pos[0], ypos=pos[1])
-            if xdata == None:
+            if xdata is None:
                 self.canvas.plot(blank_data)
             else:
                 data = pyx.graph.data.points(np.array([xdata, ydata]).T, x=1, y=2)
@@ -281,7 +281,7 @@
                    (width=psize[0], height=psize[1],
                     x=xaxis, y=yaxis, x2=xaxis2, y2=yaxis2,
                     xpos=pos[0], ypos=pos[1])
-            if xdata == None:
+            if xdata is None:
                 plot.plot(blank_data)
             else:
                 data = pyx.graph.data.points(np.array([xdata, ydata]).T, x=1, y=2)
@@ -322,7 +322,7 @@
         if isinstance(plot, PlotWindow):
             data = plot.frb
             width = plot.width[0]
-            if units == None:
+            if units is None:
                 units = plot.ds.get_smallest_appropriate_unit(width)
             width = width.in_units(str(units))
             xc = 0.5*(plot.xlim[0] + plot.xlim[1])
@@ -335,7 +335,7 @@
                 _xlabel = ""
                 _ylabel = ""
             else:
-                if xlabel != None:
+                if xlabel is not None:
                     _xlabel = xlabel
                 else:
                     if data.axis != 4:
@@ -344,7 +344,7 @@
                         _xlabel = '%s (%s)' % (x_name, units)
                     else:
                         _xlabel = 'x (%s)' % (units)
-                if ylabel != None:
+                if ylabel is not None:
                     _ylabel = ylabel
                 else:
                     if data.axis != 4:
@@ -353,7 +353,7 @@
                         _ylabel = '%s (%s)' % (y_name, units)
                     else:
                         _ylabel = 'y (%s)' % (units)
-            if tickcolor == None:
+            if tickcolor is None:
                 _tickcolor = pyx.color.cmyk.white
         elif isinstance(plot, ProfilePlot):
             subplot = plot.axes.values()[0]
@@ -390,17 +390,17 @@
                 _xlabel = ""
                 _ylabel = ""
             else:
-                if xlabel != None:
+                if xlabel is not None:
                     _xlabel = xlabel
                 else:
                     _xlabel = plot[k].axes.get_xlabel()
-                if ylabel != None:
+                if ylabel is not None:
                     _ylabel = ylabel
                 else:
                     _ylabel = plot[k].axes.get_ylabel()
                 _xlabel = pyxize_label(_xlabel)
                 _ylabel = pyxize_label(_ylabel)
-            if tickcolor == None:
+            if tickcolor is None:
                 _tickcolor = None
         elif isinstance(plot, np.ndarray):
             ax = plt.gca()
@@ -412,15 +412,15 @@
                 _xlabel = ""
                 _ylabel = ""
             else:
-                if xlabel != None:
+                if xlabel is not None:
                     _xlabel = xlabel
                 else:
                     _xlabel = ax.get_xlabel()
-                if ylabel != None:
+                if ylabel is not None:
                     _ylabel = ylabel
                 else:
                     _ylabel = ax.get_ylabel()
-            if tickcolor == None:
+            if tickcolor is None:
                 _tickcolor = None
         else:
             _xrange = plot._axes.get_xlim()
@@ -431,17 +431,17 @@
                 _xlabel = ""
                 _ylabel = ""
             else:
-                if xlabel != None:
+                if xlabel is not None:
                     _xlabel = xlabel
                 else:
                     _xlabel = plot._x_label
-                if ylabel != None:
+                if ylabel is not None:
                     _ylabel = ylabel
                 else:
                     _ylabel = plot._y_label
-            if tickcolor == None:
+            if tickcolor is None:
                 _tickcolor = None
-        if tickcolor != None:
+        if tickcolor is not None:
             _tickcolor = tickcolor
         self.axis_box(xrange=_xrange, yrange=_yrange, xlabel=_xlabel,
                       ylabel=_ylabel, tickcolor=_tickcolor, xlog=_xlog,
@@ -468,7 +468,7 @@
         >>> d.insert_image("image.jpg")
         >>> d.save_fig()
         """
-        if size != None:
+        if size is not None:
             width = size[0]*self.figsize[0]
             height = size[1]*self.figsize[1]
         else:
@@ -514,7 +514,7 @@
         if self.canvas is None:
             self.canvas = pyx.canvas.canvas()
         if isinstance(plot, (PlotWindow, PhasePlot)):
-            if field == None:
+            if field is None:
                 self.field = plot.plots.keys()[0]
                 mylog.warning("No field specified.  Choosing first field (%s)" % \
                               str(self.field))
@@ -529,11 +529,11 @@
         elif isinstance(plot, ProfilePlot):
             _p1 = plot.figures.items()[0][1]
         elif isinstance(plot, np.ndarray):
-            fig = plt.figure()
+            plt.figure()
             iplot = plt.figimage(plot)
-            _p1 =  iplot.figure
+            _p1 = iplot.figure
             _p1.set_size_inches(self.figsize[0], self.figsize[1])
-            ax = plt.gca();
+            ax = plt.gca()
             _p1.add_axes(ax)
         else:
             raise RuntimeError("Unknown plot type")
@@ -646,14 +646,13 @@
                                                  width=size[0], height=size[1]))
 
         if tickcolor is None:
-            c1 = pyx.graph.axis.painter.regular\
-                 (tickattrs=[pyx.color.cmyk.black])
-            c2 = pyx.graph.axis.painter.regular\
-                 (tickattrs=[pyx.color.cmyk.black], labelattrs=None)
+            c1 = pyx.graph.axis.painter.regular(tickattrs=[pyx.color.cmyk.black])
+            pyx.graph.axis.painter.regular(tickattrs=[pyx.color.cmyk.black],
+                                           labelattrs=None)
         else:
             c1 = pyx.graph.axis.painter.regular(tickattrs=[tickcolor])
-            c2 = pyx.graph.axis.painter.regular(tickattrs=[tickcolor],
-                                                labelattrs=None)
+            pyx.graph.axis.painter.regular(tickattrs=[tickcolor],
+                                           labelattrs=None)
         if log:
             yaxis = pyx.graph.axis.log(min=zrange[0],max=zrange[1],
                                        title=label, painter=c1)
@@ -715,18 +714,16 @@
         if isinstance(plot, ProfilePlot):
             raise RuntimeError("When using ProfilePlots you must either set yt_nocbar=True or provide colorbar flags so that the profiles don't have colorbars")
         _cmap = None
-        if field != None:
+        if field is not None:
             self.field = plot.data_source._determine_fields(field)[0]
         if isinstance(plot, (PlotWindow, PhasePlot)):
             _cmap = plot._colormaps[self.field]
         else:
-            if plot.cmap != None:
+            if plot.cmap is not None:
                 _cmap = plot.cmap.name
-        if _cmap == None:
+        if _cmap is None:
             _cmap = 'algae'
         if isinstance(plot, (PlotWindow, PhasePlot)):
-            proj = plot._plot_type.endswith("Projection") and \
-                plot.data_source.weight_field == None
             if isinstance(plot, PlotWindow):
                 try:
                     _zlabel = plot.frb[self.field].info["label"]
@@ -743,11 +740,11 @@
                 _zlabel = pyxize_label(plot.z_title)
             _zlabel = _zlabel.replace("_","\;")
             _zlog = plot.get_log(self.field)[self.field]
-            if plot.plots[self.field].zmin == None:
+            if plot.plots[self.field].zmin is None:
                 zmin = plot.plots[self.field].image._A.min()
             else:
                 zmin = plot.plots[self.field].zmin
-            if plot.plots[self.field].zmax == None:
+            if plot.plots[self.field].zmax is None:
                 zmax = plot.plots[self.field].image._A.max()
             else:
                 zmax = plot.plots[self.field].zmax
@@ -756,7 +753,7 @@
             _zlabel = plot._z_label.replace("_","\;")
             _zlog = plot._log_z
             _zrange = (plot.norm.vmin, plot.norm.vmax)
-        if cb_labels != None:  #Overrides deduced labels
+        if cb_labels is not None:  #Overrides deduced labels
             _zlabel = cb_labels.pop()
         self.colorbar(_cmap, zrange=_zrange, label=_zlabel, log=_zlog, **kwargs)
 
@@ -940,7 +937,7 @@
         tbox = self.canvas.text(self.figsize[0]*loc[0],
                                 self.figsize[1]*loc[1],
                                 text, [color, valign, halign] + text_opts)
-        if bgcolor != None:
+        if bgcolor is not None:
             tpath = tbox.bbox().enlarged(2*pyx.unit.x_pt).path()
             self.canvas.draw(tpath, [pyx.deco.filled([bgcolor]),
                                      pyx.deco.stroked()])
@@ -1060,10 +1057,10 @@
     """
     # Error check
     npanels = ncol*nrow
-    if(cb_labels != None):
+    if(cb_labels is not None):
         cb_labels.reverse()   #Because I pop the list
     
-    if images != None:
+    if images is not None:
         if len(images) != npanels:
             raise RuntimeError("Number of images (%d) doesn't match nrow(%d)"\
                                " x ncol(%d)." % (len(images), nrow, ncol))
@@ -1071,13 +1068,13 @@
     if yt_plots is None and images is None:
         raise RuntimeError("Must supply either yt_plots or image filenames.")
         return
-    if yt_plots != None and images != None:
+    if yt_plots is not None and images is not None:
         mylog.warning("Given both images and yt plots.  Ignoring images.")
-    if yt_plots != None:
+    if yt_plots is not None:
         _yt = True
     else:
         _yt = False
-    if fields == None:
+    if fields is None:
         fields = [None] * npanels
 
     # If no ranges or labels given and given only images, fill them in.
@@ -1118,27 +1115,27 @@
                 yaxis = 1
             else:
                 yaxis = -1
-            if xdata == None:
+            if xdata is None:
                 _xdata = None
             else:
                 _xdata = xdata[index]
-            if ydata == None:
+            if ydata is None:
                 _ydata = None
             else:
                 _ydata = ydata[index]
-            if xaxis_flags != None:
-                if xaxis_flags[index] != None:
+            if xaxis_flags is not None:
+                if xaxis_flags[index] is not None:
                     xaxis = xaxis_flags[index]
-            if yaxis_flags != None:
-                if yaxis_flags[index] != None:
+            if yaxis_flags is not None:
+                if yaxis_flags[index] is not None:
                     yaxis = yaxis_flags[index]
             if _yt:
                 this_plot._setup_plots()
-                if xlabels != None:
+                if xlabels is not None:
                     xlabel = xlabels[i]
                 else:
                     xlabel = None
-                if ylabels != None:
+                if ylabels is not None:
                     ylabel = ylabels[j]
                 else:
                     ylabel = None
@@ -1156,8 +1153,8 @@
                            xlabel=xlabels[i], ylabel=ylabels[j],
                            bare_axes=bare_axes, xaxis_side=xaxis, yaxis_side=yaxis,
                            xdata=_xdata, ydata=_ydata)
-            if titles != None:
-                if titles[index] != None:
+            if titles is not None:
+                if titles[index] is not None:
                     d.title_box(titles[index],
                                 loc=(i+0.05+i*margins[0]/figsize[0],
                                      j+0.98+j*margins[1]/figsize[1]))
@@ -1174,11 +1171,11 @@
         for i in range(ncol):
             xpos0 = i*(figsize[0] + margins[0])
             index = j*ncol + i
-            if (not _yt and colorbars != None) or (_yt and not yt_nocbar):
-                if cb_flags != None:
-                    if cb_flags[index] == False:
+            if (not _yt and colorbars is not None) or (_yt and not yt_nocbar):
+                if cb_flags is not None:
+                    if not cb_flags[index]:
                         continue
-                if cb_location == None:
+                if cb_location is None:
                     if ncol == 1:
                         orientation = "right"
                     elif i == 0:
@@ -1219,10 +1216,10 @@
                                   "No colorbar displayed." % orientation)
                     orientation = None  # Marker for interior plot
 
-                if orientation != None:
+                if orientation is not None:
                     if _yt:
                         # Set field if undefined
-                        if fields[index] == None:
+                        if fields[index] is None:
                             fields[index] = d.return_field(yt_plots[index])
                                               
                         d.colorbar_yt(yt_plots[index],
@@ -1240,7 +1237,7 @@
                                    pos=[xpos,ypos],
                                    shrink=shrink_cb)
 
-    if savefig != None:
+    if savefig is not None:
         d.save_fig(savefig, format=format)
 
     return d
@@ -1281,7 +1278,7 @@
     # Determine whether the plots are organized in a PlotWindow, or list 
     # of PlotWindows
     if isinstance(plots, (PlotWindow, PhasePlot)):
-        if fields == None:
+        if fields is None:
             fields = plots.fields
         if len(fields) < nrow*ncol:
             raise RuntimeError("Number of plots is less "\
@@ -1338,7 +1335,7 @@
     d.axis_box_yt(plot, bare_axes=bare_axes, **kwargs)
     if colorbar:
         d.colorbar_yt(plot, orientation=cb_orient)
-    if savefig != None:
+    if savefig is not None:
         d.save_fig(savefig, format=file_format)
     return d
 

diff -r 5f98bb340f15ac0d73ba37156dba9ed24d0691d6 -r deeb92e93357a433dd56e83a339a2192ca42e9e1 yt/visualization/fixed_resolution.py
--- a/yt/visualization/fixed_resolution.py
+++ b/yt/visualization/fixed_resolution.py
@@ -13,7 +13,7 @@
 # The full license is in the file COPYING.txt, distributed with this software.
 #-----------------------------------------------------------------------------
 
-from yt.funcs import *
+from yt.funcs import mylog
 from yt.units.unit_object import Unit
 from .volume_rendering.api import off_axis_projection
 from .fixed_resolution_filters import apply_filter, filter_registry
@@ -27,6 +27,7 @@
 import numpy as np
 import weakref
 import re
+import types
 
 class FixedResolutionBuffer(object):
     r"""
@@ -160,7 +161,7 @@
     def _is_ion( self, fname ):
         p = re.compile("_p[0-9]+_")
         result = False
-        if p.search( fname ) != None:
+        if p.search( fname ) is not None:
             result = True
         return result
 
@@ -173,7 +174,7 @@
 
         p = re.compile("_p[0-9]+_")
         m = p.search( fname )
-        if m != None:
+        if m is not None:
             pstr = m.string[m.start()+1:m.end()-1]
             segments = fname.split("_")
             for i,s in enumerate(segments):

diff -r 5f98bb340f15ac0d73ba37156dba9ed24d0691d6 -r deeb92e93357a433dd56e83a339a2192ca42e9e1 yt/visualization/image_panner/pan_and_scan_widget.py
--- a/yt/visualization/image_panner/pan_and_scan_widget.py
+++ /dev/null
@@ -1,324 +0,0 @@
-"""
-
-
-"""
-from __future__ import print_function
-from __future__ import absolute_import
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-# Major library imports
-from .vm_panner import VariableMeshPanner
-from numpy import linspace, meshgrid, pi, sin, mgrid, zeros
-
-# Enthought library imports
-from enthought.enable.api import Component, ComponentEditor, Window
-from enthought.traits.api import HasTraits, Instance, Button, Any, Callable, \
-        on_trait_change, Bool, DelegatesTo, List, Enum, Int, Property, Str, \
-        cached_property
-from enthought.traits.ui.api import \
-        Group, View, Item, VGroup, InstanceEditor
-
-# Chaco imports
-from enthought.chaco.api import ArrayPlotData, jet, Plot, HPlotContainer, \
-        ColorBar, DataRange1D, DataRange2D, LinearMapper, ImageData, \
-        CMapImagePlot, OverlayPlotContainer
-from enthought.chaco.tools.api import PanTool, ZoomTool, RangeSelection, \
-        RangeSelectionOverlay, RangeSelection
-from enthought.chaco.tools.image_inspector_tool import ImageInspectorTool, \
-     ImageInspectorOverlay
-
-if not hasattr(DataRange2D, "_subranges_updated"):
-    print ("You'll need to add _subranges updated to enthought/chaco/data_range_2d.py")
-    print ('Add this at the correct indentation level:')
-    print ()
-    print ('    @on_trait_change("_xrange.updated,_yrange.updated")')
-    print ('    def _subranges_updated(self):')
-    print ('        self.updated = True')
-    print ()
-    raise RuntimeError
-
-# We like the algae colormap; for now we re-implement it here.
-
-from enthought.chaco.api import \
-    ColorMapper, \
-    color_map_functions, color_map_dict, color_map_name_dict
-
-def algae(range, **traits):
-    _data = {'red':   ((0.0, 80/256., 80/256.),
-                       (0.2, 0.0, 0.0),
-                       (0.4, 0.0, 0.0),
-                       (0.6, 256/256., 256/256.),
-                       (0.95, 256/256., 256/256.),
-                       (1.0, 150/256., 150/256.)),
-             'green': ((0.0, 0/256., 0/256.),
-                       (0.2, 0/256., 0/256.),
-                       (0.4, 130/256., 130/256.),
-                       (0.6, 256/256., 256/256.),
-                       (1.0, 0.0, 0.0)),
-             'blue':  ((0.0, 80/256., 80/256.),
-                       (0.2, 220/256., 220/256.),
-                       (0.4, 0.0, 0.0),
-                       (0.6, 20/256., 20/256.),
-                       (1.0, 0.0, 0.0))}
-    return ColorMapper.from_segment_map(_data, range=range, **traits)
-color_map_functions.append(algae)
-color_map_dict[algae] = "algae"
-color_map_name_dict["algae"] = algae
-
-class FunctionImageData(ImageData):
-    # The function to call with the low and high values of the range.
-    # It should return an array of values.
-    func = Callable
-
-    # A reference to a datarange
-    data_range = Instance(DataRange2D)
-
-    def __init__(self, **kw):
-        # Explicitly call the AbstractDataSource constructor because
-        # the ArrayDataSource ctor wants a data array
-        ImageData.__init__(self, **kw)
-        self.recalculate()
-
-    @on_trait_change('data_range.updated')
-    def recalculate(self):
-        if self.func is not None and self.data_range is not None:
-            newarray = self.func(self.data_range.low, self.data_range.high)
-            ImageData.set_data(self, newarray)
-        else:
-            self._data = zeros((512,512),dtype=float)
-
-    def set_data(self, *args, **kw):
-        raise RuntimeError("Cannot set numerical data on a FunctionDataSource")
-
-    def set_mask(self, mask):
-        raise NotImplementedError
-
-    def remove_mask(self):
-        raise NotImplementedError
-
-class ImagePixelizerHelper(object):
-    index = None
-    def __init__(self, panner, run_callbacks = False):
-        self.panner = panner
-        self.run_callbacks = run_callbacks
-
-    def __call__(self, low, high):
-        b = self.panner.set_low_high(low, high)
-        if self.run_callbacks:
-            self.panner._run_callbacks()
-        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
-
-class ZoomedPlotUpdater(object):
-    fid = None
-    def __init__(self, panner, zoom_factor=4):
-        """
-        Supply this an a viewport_callback argument to a panner if you want to
-        update a second panner in a smaller portion at higher resolution.  If
-        you then set the *fid* property, you can also have it update a
-        FunctionImageData datarange.  *panner* is the panner to update (not the
-        one this is a callback to) and *zoom_factor* is how much to zoom in by.
-        """
-        self.panner = panner
-        self.zoom_factor = zoom_factor
-
-    def __call__(self, xlim, ylim):
-        self.panner.xlim = xlim
-        self.panner.ylim = ylim
-        self.panner.zoom(self.zoom_factor)
-        nxlim = self.panner.xlim
-        nylim = self.panner.ylim
-        if self.fid is not None:
-            self.fid.data_range.set_bounds(
-                (nxlim[0], nylim[0]), (nxlim[1], nylim[1]))
-
-class VMImagePlot(HasTraits):
-    plot = Instance(Plot)
-    fid = Instance(FunctionImageData)
-    img_plot = Instance(CMapImagePlot)
-    panner = Instance(VariableMeshPanner)
-    helper = Instance(ImagePixelizerHelper)
-    fields = List
-
-    def __init__(self, *args, **kwargs):
-        super(VMImagePlot, self).__init__(**kwargs)
-        self.add_trait("field", Enum(*self.fields))
-        self.field = self.panner.field
-
-    def _plot_default(self):
-        pd = ArrayPlotData()
-        plot = Plot(pd, padding = 0)
-        self.fid._data = self.panner.buffer
-
-        pd.set_data("imagedata", self.fid)
-
-        img_plot = plot.img_plot("imagedata", colormap=algae,
-                                 interpolation='nearest',
-                                 xbounds=(0.0, 1.0),
-                                 ybounds=(0.0, 1.0))[0]
-        self.fid.data_range = plot.range2d
-        self.helper.index = img_plot.index
-        self.img_plot = img_plot
-        return plot
-
-    def _field_changed(self, old, new):
-        self.panner.field = new
-        self.fid.recalculate()
-
-    def _fid_default(self):
-        return FunctionImageData(func = self.helper)
-
-    def _helper_default(self):
-        return ImagePixelizerHelper(self.panner)
-
-    def _panner_changed(self, old, new):
-        index = self.helper.index
-        self.helper = ImagePixelizerHelper(new)
-        self.helper.index = index
-        self.fid.func = self.helper
-        self.fid.recalculate()
-
-    def _fields_default(self):
-        keys = []
-        for field in self.panner.source.keys():
-            if field not in ['px','py','pdx','pdy',
-                             'pz','pdz','weight_field']:
-                keys.append(field)
-        return keys
-
-class VariableMeshPannerView(HasTraits):
-
-    plot = Instance(Plot)
-    spawn_zoom = Button
-    vm_plot = Instance(VMImagePlot)
-    use_tools = Bool(True)
-    full_container = Instance(HPlotContainer)
-    container = Instance(OverlayPlotContainer)
-    
-    traits_view = View(
-                    Group(
-                        Item('full_container',
-                             editor=ComponentEditor(size=(512,512)), 
-                             show_label=False),
-                        Item('field', show_label=False),
-                        orientation = "vertical"),
-                    width = 800, height=800,
-                    resizable=True, title="Pan and Scan",
-                    )
-
-    def _vm_plot_default(self):
-        return VMImagePlot(panner=self.panner)
-    
-    def __init__(self, **kwargs):
-        super(VariableMeshPannerView, self).__init__(**kwargs)
-        # Create the plot
-        self.add_trait("field", DelegatesTo("vm_plot"))
-
-        plot = self.vm_plot.plot
-        img_plot = self.vm_plot.img_plot
-
-        if self.use_tools:
-            plot.tools.append(PanTool(img_plot))
-            zoom = ZoomTool(component=img_plot, tool_mode="box", always_on=False)
-            plot.overlays.append(zoom)
-            imgtool = ImageInspectorTool(img_plot)
-            img_plot.tools.append(imgtool)
-            overlay = ImageInspectorOverlay(component=img_plot, image_inspector=imgtool,
-                                            bgcolor="white", border_visible=True)
-            img_plot.overlays.append(overlay)
-
-
-        image_value_range = DataRange1D(self.vm_plot.fid)
-        cbar_index_mapper = LinearMapper(range=image_value_range)
-        self.colorbar = ColorBar(index_mapper=cbar_index_mapper,
-                                 plot=img_plot,
-                                 padding_right=40,
-                                 resizable='v',
-                                 width=30)
-
-        self.colorbar.tools.append(
-            PanTool(self.colorbar, constrain_direction="y", constrain=True))
-        zoom_overlay = ZoomTool(self.colorbar, axis="index", tool_mode="range",
-                                always_on=True, drag_button="right")
-        self.colorbar.overlays.append(zoom_overlay)
-
-        # create a range selection for the colorbar
-        range_selection = RangeSelection(component=self.colorbar)
-        self.colorbar.tools.append(range_selection)
-        self.colorbar.overlays.append(
-                RangeSelectionOverlay(component=self.colorbar,
-                                      border_color="white",
-                                      alpha=0.8, fill_color="lightgray"))
-
-        # we also want to the range selection to inform the cmap plot of
-        # the selection, so set that up as well
-        range_selection.listeners.append(img_plot)
-
-        self.full_container = HPlotContainer(padding=30)
-        self.container = OverlayPlotContainer(padding=0)
-        self.full_container.add(self.colorbar)
-        self.full_container.add(self.container)
-        self.container.add(self.vm_plot.plot)
-
-class OutputSelector(HasTraits):
-    outputs = List
-    main_plot = Instance(VariableMeshPannerView)
-    main_panner = Property(depends_on = "ds")
-    weight_field = Str("Density")
-
-    ds = Any
-    source = Any
-    axis = Int(0)
-
-    traits_view = View(VGroup(
-                        Item('output'),
-                        Item('main_plot'),
-                        )
-                      )
-
-    def __init__(self, **kwargs):
-        super(OutputSelector, self).__init__(**kwargs)
-        self.add_trait("output", Enum(*self.outputs))
-        self.output = self.outputs[-1]
-        self.main_plot
-
-    def _output_default(self):
-        return self.outputs[0]
-
-    def _output_changed(self, old, new):
-        # We get a string here
-        import yt.mods
-        self.ds = yt.mods.load(new, dataset_type="enzo_packed_3d")
-        self.source = yt.mods.projload(self.ds, self.axis, "Density")
-        self.main_panner.field = self.main_plot.vm_plot.field
-        self.main_plot.panner = self.main_plot.vm_plot.panner = \
-            self.main_plot.vm_plot.helper.panner = self.main_panner
-        self.main_plot.vm_plot.field = self.main_panner.field
-
-    def _main_plot_default(self):
-        vmpv = VariableMeshPannerView(panner = self.main_panner)
-        vmpv.vm_plot.helper.run_callbacks = True
-        return vmpv
-
-    @cached_property
-    def _get_main_panner(self):
-        return self.ds.image_panner(self.source, (512, 512), "Density")
-
-def pan_and_scan_directory(dir_name):
-    import glob, os
-    fns = [ fn[:-10] for fn in
-            glob.glob(os.path.join(dir_name, "**", "*.index")) ]
-    selector = OutputSelector(outputs = fns)
-    return selector

diff -r 5f98bb340f15ac0d73ba37156dba9ed24d0691d6 -r deeb92e93357a433dd56e83a339a2192ca42e9e1 yt/visualization/image_panner/setup.py
--- a/yt/visualization/image_panner/setup.py
+++ b/yt/visualization/image_panner/setup.py
@@ -1,8 +1,4 @@
 #!/usr/bin/env python
-import setuptools
-import os
-import sys
-import os.path
 
 
 def configuration(parent_package='', top_path=None):

diff -r 5f98bb340f15ac0d73ba37156dba9ed24d0691d6 -r deeb92e93357a433dd56e83a339a2192ca42e9e1 yt/visualization/image_panner/vm_panner.py
--- a/yt/visualization/image_panner/vm_panner.py
+++ b/yt/visualization/image_panner/vm_panner.py
@@ -11,15 +11,14 @@
 # The full license is in the file COPYING.txt, distributed with this software.
 #-----------------------------------------------------------------------------
 
+import base64
+
 import numpy as np
-import types, os
-from yt.data_objects.construction_data_containers import YTOverlapProjBase
-from yt.data_objects.selection_data_containers import YTSliceBase
 from yt.visualization.fixed_resolution import \
-    FixedResolutionBuffer, ObliqueFixedResolutionBuffer
+    FixedResolutionBuffer
 from yt.data_objects.data_containers import \
     data_object_registry
-from yt.funcs import *
+from yt.funcs import iterable
 
 class VariableMeshPanner(object):
     _buffer = None
@@ -235,7 +234,7 @@
         for w in self.windows: w.zoom(factor)
 
     def pan(self, deltas):
-        for w in self.windows: w.pan(factor)
+        for w in self.windows: w.pan(deltas)
 
     def pan_x(self, delta):
         for w in self.windows: w.pan_x(delta)
@@ -264,7 +263,9 @@
         """
         self.tile_id = tile_id
 
-        import matplotlib;matplotlib.use("Agg");import pylab
+        import matplotlib
+        matplotlib.use("Agg")
+        import pylab
         self.pylab = pylab
         self.pylab.clf()
         fig = pylab.gcf()
@@ -299,6 +300,4 @@
         to_plot = np.clip(to_plot, 0, 255)
         s = write_png_to_string(to_plot)
         response_body = "data:image/png;base64," + base64.encodestring(s)
-        tf.close()
         self.transport.append(response_body)
-

diff -r 5f98bb340f15ac0d73ba37156dba9ed24d0691d6 -r deeb92e93357a433dd56e83a339a2192ca42e9e1 yt/visualization/image_writer.py
--- a/yt/visualization/image_writer.py
+++ b/yt/visualization/image_writer.py
@@ -13,12 +13,10 @@
 # The full license is in the file COPYING.txt, distributed with this software.
 #-----------------------------------------------------------------------------
 
-import types
-import imp
-import os
 import numpy as np
 
-from yt.funcs import *
+from yt.funcs import mylog, get_image_suffix
+from yt.units.yt_array import YTQuantity
 from yt.utilities.exceptions import YTNotInsideNotebook
 from .color_maps import mcm
 from . import _colormap_data as cmd
@@ -277,7 +275,7 @@
                 cmap = bmap.get_mpl_colormap(N=cmap_name[2])
             else:
                 cmap = mcm.get_cmap(cmap_name)
-            dummy = cmap(0.0)
+            cmap(0.0)
             lut = cmap._lut.T
         except ValueError:
             print("Your color map was not found in either the extracted" +\

diff -r 5f98bb340f15ac0d73ba37156dba9ed24d0691d6 -r deeb92e93357a433dd56e83a339a2192ca42e9e1 yt/visualization/plot_modifications.py
--- a/yt/visualization/plot_modifications.py
+++ b/yt/visualization/plot_modifications.py
@@ -5,9 +5,6 @@
 
 
 """
-from __future__ import absolute_import
-from yt.extern.six import string_types
-
 #-----------------------------------------------------------------------------
 # Copyright (c) 2013, yt Development Team.
 #
@@ -16,8 +13,12 @@
 # The full license is in the file COPYING.txt, distributed with this software.
 #-----------------------------------------------------------------------------
 
+from __future__ import absolute_import
+
+import warnings
+
+import matplotlib
 import numpy as np
-import h5py
 
 from distutils.version import LooseVersion
 
@@ -26,22 +27,19 @@
 from matplotlib import cm
 from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
 
-from yt.funcs import *
+from yt.funcs import \
+    mylog, iterable
 from yt.extern.six import add_metaclass
-from ._mpl_imports import *
-from yt.utilities.physical_constants import \
-    sec_per_Gyr, sec_per_Myr, \
-    sec_per_kyr, sec_per_year, \
-    sec_per_day, sec_per_hr
 from yt.units.yt_array import YTQuantity, YTArray
 from yt.visualization.image_writer import apply_colormap
 from yt.utilities.lib.geometry_utils import triangle_plane_intersect
 from yt.analysis_modules.cosmological_observation.light_ray.light_ray \
      import periodic_ray
-from yt.utilities.lib.line_integral_convolution \
-     import line_integral_convolution_2d
+from yt.utilities.lib.line_integral_convolution import \
+    line_integral_convolution_2d
 import warnings
 
+
 from . import _MPL
 
 callback_registry = {}
@@ -116,13 +114,11 @@
 
         x0 = np.array(np.tile(plot.xlim[0],ncoord))
         x1 = np.array(np.tile(plot.xlim[1],ncoord))
-        x2 = np.array([0, 1])
         xx0 = np.tile(plot._axes.get_xlim()[0],ncoord)
         xx1 = np.tile(plot._axes.get_xlim()[1],ncoord)
 
         y0 = np.array(np.tile(plot.ylim[0],ncoord))
         y1 = np.array(np.tile(plot.ylim[1],ncoord))
-        y2 = np.array([0, 1])
         yy0 = np.tile(plot._axes.get_ylim()[0],ncoord)
         yy1 = np.tile(plot._axes.get_ylim()[1],ncoord)
 
@@ -232,7 +228,7 @@
         # For each label, set the font properties and color to the figure
         # defaults if not already set in the callback itself
         for label in labels:
-            if plot.font_color is not None and not 'color' in kwargs:
+            if plot.font_color is not None and 'color' not in kwargs:
                 label.set_color(plot.font_color)
             label.set_fontproperties(local_font_properties)
 
@@ -373,7 +369,7 @@
                              int(nx), int(ny),
                              (x0, x1, y0, y1), 0, # bounds, antialias
                              (period_x, period_y), periodic,
-                           ).transpose()
+                             ).transpose()
         pixY = _MPL.Pixelize(plot.data['px'],
                              plot.data['py'],
                              plot.data['pdx'],
@@ -382,7 +378,7 @@
                              int(nx), int(ny),
                              (x0, x1, y0, y1), 0, # bounds, antialias
                              (period_x, period_y), periodic,
-                           ).transpose()
+                             ).transpose()
         X,Y = np.meshgrid(np.linspace(xx0,xx1,nx,endpoint=True),
                           np.linspace(yy0,yy1,ny,endpoint=True))
         if self.normalize:

diff -r 5f98bb340f15ac0d73ba37156dba9ed24d0691d6 -r deeb92e93357a433dd56e83a339a2192ca42e9e1 yt/visualization/plot_window.py
--- a/yt/visualization/plot_window.py
+++ b/yt/visualization/plot_window.py
@@ -48,8 +48,7 @@
 from yt.extern.six import string_types
 from yt.funcs import \
     mylog, iterable, ensure_list, \
-    fix_axis, validate_width_tuple, \
-    fix_unitary
+    fix_axis, fix_unitary
 from yt.units.unit_object import \
     Unit
 from yt.units.unit_registry import \
@@ -68,7 +67,6 @@
     Orientation
 from yt.utilities.exceptions import \
     YTUnitNotRecognized, \
-    YTInvalidWidthError, \
     YTCannotParseUnitDisplayName, \
     YTUnitConversionError, \
     YTPlotCallbackError
@@ -231,7 +229,7 @@
         super(PlotWindow, self).__init__(data_source, window_size, fontsize)
         self._set_window(bounds) # this automatically updates the data and plot
         self.origin = origin
-        if self.data_source.center is not None and oblique == False:
+        if self.data_source.center is not None and oblique is False:
             ax = self.data_source.axis
             xax = self.ds.coordinates.x_axis[ax]
             yax = self.ds.coordinates.y_axis[ax]

diff -r 5f98bb340f15ac0d73ba37156dba9ed24d0691d6 -r deeb92e93357a433dd56e83a339a2192ca42e9e1 yt/visualization/profile_plotter.py
--- a/yt/visualization/profile_plotter.py
+++ b/yt/visualization/profile_plotter.py
@@ -20,28 +20,24 @@
 import base64
 import os
 
-from functools import wraps
 import matplotlib
 import numpy as np
 from io import BytesIO
 
 
 from .base_plot_types import ImagePlotMPL
-from yt.units.yt_array import YTArray
 from .plot_container import \
     ImagePlotContainer, \
     log_transform, linear_transform, get_log_minorticks, \
     validate_plot, invalidate_plot
 from yt.data_objects.profiles import \
-    create_profile, \
-    sanitize_field_tuple_keys
+    create_profile
 from yt.utilities.exceptions import \
     YTNotInsideNotebook
 from yt.utilities.logger import ytLogger as mylog
 from . import _mpl_imports as mpl
 from yt.funcs import \
     ensure_list, \
-    iterable, \
     get_image_suffix, \
     get_ipython_api_version
 

diff -r 5f98bb340f15ac0d73ba37156dba9ed24d0691d6 -r deeb92e93357a433dd56e83a339a2192ca42e9e1 yt/visualization/setup.py
--- a/yt/visualization/setup.py
+++ b/yt/visualization/setup.py
@@ -1,5 +1,4 @@
 #!/usr/bin/env python
-import setuptools
 
 
 def configuration(parent_package='', top_path=None):

diff -r 5f98bb340f15ac0d73ba37156dba9ed24d0691d6 -r deeb92e93357a433dd56e83a339a2192ca42e9e1 yt/visualization/streamlines.py
--- a/yt/visualization/streamlines.py
+++ b/yt/visualization/streamlines.py
@@ -15,7 +15,8 @@
 
 import numpy as np
 from yt.data_objects.construction_data_containers import YTStreamlineBase
-from yt.funcs import *
+from yt.funcs import get_pbar
+from yt.units.yt_array import YTArray
 from yt.utilities.parallel_tools.parallel_analysis_interface import \
     ParallelAnalysisInterface, parallel_passthrough
 from yt.utilities.amr_kdtree.api import AMRKDTree

diff -r 5f98bb340f15ac0d73ba37156dba9ed24d0691d6 -r deeb92e93357a433dd56e83a339a2192ca42e9e1 yt/visualization/tests/test_callbacks.py
--- a/yt/visualization/tests/test_callbacks.py
+++ b/yt/visualization/tests/test_callbacks.py
@@ -13,7 +13,9 @@
 #
 # The full license is in the file COPYING.txt, distributed with this software.
 #-----------------------------------------------------------------------------
-import os, tempfile, shutil
+import tempfile
+import shutil
+
 from yt.testing import \
     fake_amr_ds
 import yt.units as u

diff -r 5f98bb340f15ac0d73ba37156dba9ed24d0691d6 -r deeb92e93357a433dd56e83a339a2192ca42e9e1 yt/visualization/tests/test_plotwindow.py
--- a/yt/visualization/tests/test_plotwindow.py
+++ b/yt/visualization/tests/test_plotwindow.py
@@ -288,11 +288,6 @@
         self._assert_05_075cm()
         assert_true(self.slc._axes_unit_names == ('cm', 'cm'))
 
-    def test_tuple_of_tuples_neq(self):
-        self.slc.set_width(((0.5, 'cm'), (0.0075, 'm')))
-        self._assert_05_075cm()
-        assert_true(self.slc._axes_unit_names == ('cm', 'm'))
-
 
 class TestPlotWindowSave(unittest.TestCase):
 

diff -r 5f98bb340f15ac0d73ba37156dba9ed24d0691d6 -r deeb92e93357a433dd56e83a339a2192ca42e9e1 yt/visualization/tests/test_profile_plots.py
--- a/yt/visualization/tests/test_profile_plots.py
+++ b/yt/visualization/tests/test_profile_plots.py
@@ -12,7 +12,6 @@
 #
 # The full license is in the file COPYING.txt, distributed with this software.
 #-----------------------------------------------------------------------------
-import itertools
 import os
 import tempfile
 import shutil

diff -r 5f98bb340f15ac0d73ba37156dba9ed24d0691d6 -r deeb92e93357a433dd56e83a339a2192ca42e9e1 yt/visualization/volume_rendering/CUDARayCast.py
--- a/yt/visualization/volume_rendering/CUDARayCast.py
+++ /dev/null
@@ -1,161 +0,0 @@
-"""
-An attempt at putting the ray-casting operation into CUDA
-
-
-
-"""
-from __future__ import print_function
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-import sys;sys.path.insert(0,'.')
-
-from yt.mods import *
-import yt.extensions.HierarchySubset as hs
-import numpy as np
-import h5py, time
-from yt.utilities.physical_constants import \
-    mass_hydrogen_cgs
-
-import matplotlib;matplotlib.use("Agg");import pylab
-
-from yt.extensions.volume_rendering.TransferFunction import ColorTransferFunction
-
-if __name__ == "__main__":
-
-    # This is boilerplate code for setting up pycuda
-    import pycuda.driver as cuda
-    import pycuda.compiler as compiler
-    import pycuda.autoinit
-    import pycuda.gpuarray as gpuarray
-    cuda.init()
-    assert (cuda.Device.count() >= 1)
-
-    print ("Extracting hierarchy.")
-    ods = load("/u/ki/mturk/ki05/MSM96-SIM3-restart-J64/DataDump0081.dir/DataDump0081")
-    ds = hs.ExtractedParameterFile(ods, 20)
-
-    cpu = {}
-    gpu = {}
-
-    print ("Reading data.")
-    #fn = "DataDump0081_partitioned.h5"
-    fn = "RedshiftOutput0005_partitioned.h5"
-    f = h5py.File("/u/ki/mturk/ki05/%s" % fn)
-    cpu['grid_data'] = f["/PGrids/Data"][:].astype("float32")
-    cpu['dims'] = f["/PGrids/Dims"][:].astype("int32") - 1
-    cpu['left_edge'] = f["/PGrids/LeftEdges"][:].astype("float32")
-    cpu['right_edge'] = f["/PGrids/RightEdges"][:].astype("float32")
-
-    print ("Constructing transfer function.")
-    if "Data" in fn:
-        mh = np.log10(mass_hydrogen_cgs)
-        tf = ColorTransferFunction((7.5+mh, 14.0+mh))
-        tf.add_gaussian( 8.25+mh, 0.002, [0.2, 0.2, 0.4, 0.1])
-        tf.add_gaussian( 9.75+mh, 0.002, [0.0, 0.0, 0.3, 0.1])
-        tf.add_gaussian(10.25+mh, 0.004, [0.0, 0.3, 0.0, 0.1])
-        tf.add_gaussian(11.50+mh, 0.005, [1.0, 0.0, 0.0, 0.7])
-        tf.add_gaussian(12.75+mh, 0.010, [1.0, 1.0, 1.0, 1.0])
-    elif "Red" in fn:
-        tf = ColorTransferFunction((-31, -27))
-        tf.add_gaussian(-30.0, 0.05, [1.0, 0.0, 0.0, 0.1])
-        tf.add_gaussian(-29.5, 0.03, [0.0, 1.0, 0.0, 0.3])
-        tf.add_gaussian(-29.0, 0.05, [0.0, 0.0, 1.0, 0.5])
-        tf.add_gaussian(-28.5, 0.05, [1.0, 1.0, 1.0, 1.0])
-    else: raise RuntimeError
-
-    cpu['ngrids'] = np.array([cpu['dims'].shape[0]], dtype='int32')
-    cpu['tf_r'] = tf.red.y.astype("float32")
-    cpu['tf_g'] = tf.green.y.astype("float32")
-    cpu['tf_b'] = tf.blue.y.astype("float32")
-    cpu['tf_a'] = tf.alpha.y.astype("float32")
-
-    cpu['tf_bounds'] = np.array(tf.x_bounds, dtype='float32')
-
-    cpu['v_dir'] = np.array([0.3, 0.5, 0.6], dtype='float32')
-
-    c = np.array([0.47284317, 0.48062515, 0.58282089], dtype='float32')
-
-    print ("Getting cutting plane.")
-    cp = ds.cutting(cpu['v_dir'], c)
-
-    W = 2000.0/ds['au']
-    W = 0.25
-    Nvec = 128
-    back_c = c - cp._norm_vec * W
-    front_c = c + cp._norm_vec * W
-
-    px, py = np.mgrid[-W:W:Nvec*1j,-W:W:Nvec*1j]
-    xv = cp._inv_mat[0,0]*px + cp._inv_mat[0,1]*py + cp.center[0]
-    yv = cp._inv_mat[1,0]*px + cp._inv_mat[1,1]*py + cp.center[1]
-    zv = cp._inv_mat[2,0]*px + cp._inv_mat[2,1]*py + cp.center[2]
-    cpu['v_pos'] = np.array([xv, yv, zv], dtype='float32').transpose()
-
-    cpu['image_r'] = np.zeros((Nvec, Nvec), dtype='float32').ravel()
-    cpu['image_g'] = np.zeros((Nvec, Nvec), dtype='float32').ravel()
-    cpu['image_b'] = np.zeros((Nvec, Nvec), dtype='float32').ravel()
-    cpu['image_a'] = np.zeros((Nvec, Nvec), dtype='float32').ravel()
-
-    print ("Generating module")
-    source = open("yt/extensions/volume_rendering/_cuda_caster.cu").read()
-    mod = compiler.SourceModule(source)
-    func = mod.get_function("ray_cast")
-
-    for n, a in cpu.items():
-        ss = a.size * a.dtype.itemsize
-        print ("Allocating %0.3e megabytes for %s" % (ss/(1024*1024.), n))
-        gpu[n] = cuda.to_device(a.ravel('F'))
-        #pycuda.autoinit.context.synchronize()
-
-    BLOCK_SIZE = 8
-    grid_size = Nvec / BLOCK_SIZE
-
-    print ("Running ray_cast function.")
-    t1 = time.time()
-    ret = func(gpu['ngrids'],
-               gpu['grid_data'],
-               gpu['dims'],
-               gpu['left_edge'],
-               gpu['right_edge'],
-               gpu['tf_r'],
-               gpu['tf_g'],
-               gpu['tf_b'],
-               gpu['tf_a'],
-               gpu['tf_bounds'],
-               gpu['v_dir'],
-               gpu['v_pos'],
-               gpu['image_r'],
-               gpu['image_g'],
-               gpu['image_b'],
-               gpu['image_a'],
-         block=(BLOCK_SIZE,BLOCK_SIZE,1),
-         grid=(grid_size, grid_size), time_kernel=True)
-    t2 = time.time()
-    print ("BACK: %0.3e" % (t2-t1))
-
-    mi, ma = 1e300, -1e300
-    image = []
-    for im in 'rgb':
-        ii = 'image_%s' % im
-        sh, dtype = cpu[ii].shape, cpu[ii].dtype
-        del cpu[ii]
-        cpu[ii] = cuda.from_device(gpu[ii], sh, dtype).reshape((Nvec,Nvec))
-        mi, ma = min(cpu[ii].min(),mi), max(cpu[ii].max(), ma)
-        image.append(cpu[ii])
-        print ("Min/max of %s %0.3e %0.3e" % (
-                im, image[-1].min(), image[-1].max()))
-        pylab.clf()
-        pylab.imshow(image[-1], interpolation='nearest')
-        pylab.savefig("/u/ki/mturk/public_html/vr6/%s.png" % (ii))
-
-    image = np.array(image).transpose()
-    image = (image - mi) / (ma - mi)
-    pylab.clf()
-    pylab.imshow(image, interpolation='nearest')
-    pylab.savefig("/u/ki/mturk/public_html/vr6/image_rgb.png")

diff -r 5f98bb340f15ac0d73ba37156dba9ed24d0691d6 -r deeb92e93357a433dd56e83a339a2192ca42e9e1 yt/visualization/volume_rendering/api.py
--- a/yt/visualization/volume_rendering/api.py
+++ b/yt/visualization/volume_rendering/api.py
@@ -21,8 +21,8 @@
                            plot_channel, plot_rgb
 
 from .camera import Camera, PerspectiveCamera, StereoPairCamera, \
-    off_axis_projection, FisheyeCamera, MosaicFisheyeCamera, \
-    HEALpixCamera, InteractiveCamera, ProjectionCamera, \
+    off_axis_projection, FisheyeCamera, \
+    InteractiveCamera, ProjectionCamera, \
     SphericalCamera, StereoSphericalCamera
 
 from .transfer_function_helper import TransferFunctionHelper

This diff is so big that we needed to truncate the remainder.

Repository URL: https://bitbucket.org/yt_analysis/yt/

--

This is a commit notification from bitbucket.org. You are receiving
this because you have the service enabled, addressing the recipient of
this email.


More information about the yt-svn mailing list