Friday, April 30, 2010

Monday, April 26, 2010

ipython from a script

calling ipython from the shebang doesn't execute the script; it just starts an interactive shell. i found a way to access ipython magic from vanilla python, however: from IPython.Shell import IPShellEmbed ipshell = IPShellEmbed() _ip = ipshell.IP then i can time things, just like with %timeit, like this. print _ip.magic_timeit(locals+"import convolve3w;convolve3w.naive_convolve(f, g)")

Tuesday, April 13, 2010

rotating numpy arrays

finally found a good way to operate on rotated numpy arrays. numpy.roll returns the array that i would need as an operand, but it makes a copy so i would need 3 times the memory footprint of the original array by the time i do the operation. slicing makes a view, not a copy, so it will only require 2 times. (i think; maybe it would still need as much due to the concatenation. should i look at numpy.lib.stride_tricks? i think numpy.take still makes a copy, too.) r = 2 # roll 2 index steps np.concatenate((a[:,r:]- a[:,:-r],a[:,:r]-a[:,-r:]),axis=1) the axis=1 makes it equivalent to hstack; axis=0 would be vstack (make sure to change the slices to r:,: etc.) EDIT: i don't know why i've been so thick-headed about this. the way to control (and conserve) memory is to allocate it first and use a slice/fancy indexing to access it. dp = n.empty_like(p) dp[:,:-1] = p[:,1:]-p[:,:-1]; dp[:,-1:] = p[:,:1]-p[:,-1:]

histograms with chaco

i searched in vain for a quick and easy histogram plotter in chaco from enthought. found this snippet for using numpy.histogram, which i should be able to adapt to chaco if i need to later.

Histograms

The NumPy's function histogram applied to an array returns a pair of vectors: the histogram of the array and the vector of bins. Beware:matplotlib has also a function to build histograms (called hist, as in matlab) different from that of NumPy. The main difference is thatpylab.hist plots the histogram automatically, while numpy.histogram only generates the data.

import numpy import pylab # Build a vector of 10000 normal deviates with variance 0.5^2 and mean 2 mu, sigma = 2, 0.5 v = numpy.random.normal(mu,sigma,10000) # Plot a normalized histogram with 50 bins pylab.hist(v, bins=50, normed=1)       # matplotlib version (plot) pylab.show() # Compute the histogram with numpy and then plot it (n, bins) = numpy.histogram(v, bins=50, normed=1)  # NumPy version (no plot) pylab.plot(.5*(bins[1:]+bins[:-1]), n) pylab.show()