From: <fer...@us...> - 2007-07-28 21:31:24
|
Revision: 3625 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3625&view=rev Author: fer_perez Date: 2007-07-28 14:31:18 -0700 (Sat, 28 Jul 2007) Log Message: ----------- Add Schrodinger equation example, contributed by James Nagel <na...@me...> Added Paths: ----------- trunk/py4science/examples/schrodinger/ trunk/py4science/examples/schrodinger/Schrodinger_FDTD.pdf trunk/py4science/examples/schrodinger/schrod_fdtd.py Added: trunk/py4science/examples/schrodinger/Schrodinger_FDTD.pdf =================================================================== (Binary files differ) Property changes on: trunk/py4science/examples/schrodinger/Schrodinger_FDTD.pdf ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/py4science/examples/schrodinger/schrod_fdtd.py =================================================================== --- trunk/py4science/examples/schrodinger/schrod_fdtd.py (rev 0) +++ trunk/py4science/examples/schrodinger/schrod_fdtd.py 2007-07-28 21:31:18 UTC (rev 3625) @@ -0,0 +1,258 @@ +#!/usr/bin/env python +#============================================================================= +# +# Quantum Mechanical Simulation using Finite-Difference +# Time-Domain (FDTD) Method +# +# This script simulates a probability wave in the presence of multiple +# potentials. The simulation is c arried out by using the FDTD algorithm +# applied to the Schrodinger equation. The program is intended to act as +# a demonstration of the FDTD algorithm and can be used as an educational +# aid for quantum mechanics and numerical methods. The simulation +# parameters are defined in the code constants and can be freely +# manipulated to see different behaviors. +# +# NOTES +# +# The probability density plots are amplified by a factor for visual +# purposes. The psi_p quanity contains the actual probability density +# without any rescaling. +# +# BEWARE: The time step, dt, has strict requirements or else the +# simulation becomes unstable. +# +# The code has three built-in potential functions for demonstration. +# +# 1) Constant potential: Demonstrates a free particle with dispersion. +# +# 2) Step potential: Demonstrates transmission and reflection. +# +# 3) Potential barrier: Demonstrates tunneling. +# +# By tweaking the height of the potential (V0 below) as well as the +# barrier thickness (THCK below), you can see different behaviors: full +# reflection with no noticeable transmission, transmission and +# reflection, or mostly transmission with tunneling. +# +# This script requires pylab and numpy to be installed with +# Python or else it will not run. +# +#============================================================================ +# Author: James Nagel <na...@me...> +# 5/25/07 +# +# Updates by Fernando Perez <Fer...@co...>, 7/28/07 +#============================================================================ + +# Numerical and plotting libraries +import numpy as np +import pylab + +# Set pylab to interactive mode so plots update when run outside ipython +pylab.ion() + +#============================================================================= + +# Utility functions + +# Defines a quick Gaussian pulse function to act as an envelope to the wave +# function. +def Gaussian(x,t,sigma): + """ A Gaussian curve. + x = Variable + t = time shift + sigma = standard deviation """ + return np.exp(-(x-t)**2/(2*sigma**2)) + +def free(npts): + "Free particle." + return np.zeros(npts) + +def step(npts,v0): + "Potential step" + v = free(npts) + v[npts/2:] = v0 + return v + +def barrier(npts,v0,thickness): + "Barrier potential" + v = free(npts) + v[npts/2:npts/2+thickness] = v0 + return v + +#============================================================================= +# +# Simulation Constants. Be sure to include decimal points on appropriate +# variables so they become floats instead of integers. +# +N = 1200 # Number of spatial points. +T = 5*N # Number of time steps. 5*N is a nice value for terminating + # before anything reaches the boundaries. +Tp = 40 # Number of time steps to increment before updating the plot. +dx = 1.0e0 # Spatial resolution +m = 1.0e0 # Particle mass +hbar = 1.0e0 # Plank's constant +X = dx*np.linspace(0,N,N) # Spatial axis. + +# Potential parameters. By playing with the type of potential and the height +# and thickness (for barriers), you'll see the various transmission/reflection +# regimes of quantum mechanical tunneling. +V0 = 1.0e-2 # Potential amplitude (used for steps and barriers) +THCK = 10 # "Thickness" of the potential barrier (if appropriate + # V-function is chosen) + +# Uncomment the potential type you want to use here: + +# Zero potential, packet propagates freely. +#POTENTIAL = 'free' + +# Potential step. The height (V0) of the potential chosen above will determine +# the amount of reflection/transmission you'll observe +#POTENTIAL = 'step' + +# Potential barrier. Note that BOTH the potential height (V0) and thickness +# of the barrier (THCK) affect the amount of tunneling vs reflection you'll +# observe. +POTENTIAL = 'barrier' + +# Initial wave function constants +sigma = 40.0 # Standard deviation on the Gaussian envelope (remember Heisenberg + # uncertainty). +x0 = round(N/2) - 5*sigma # Time shift +k0 = np.pi/20 # Wavenumber (note that energy is a function of k) + +#============================================================================= +# Code begins +# +# You shouldn't need to change anything below unless you want to actually play +# with the numerical algorithm or modify the plotting. +# +# Fill in the appropriate potential function (is there a Python equivalent to +# the SWITCH statement?). +if POTENTIAL=='free': + V = free(N) +elif POTENTIAL=='step': + V = step(N,V0) +elif POTENTIAL=='barrier': + V = barrier(N,V0,THCK) +else: + raise ValueError("Unrecognized potential type: %s" % POTENTIAL) + +# More simulation parameters. The maximum stable time step is a function of +# the potential, V. +Vmax = max(V) # Maximum potential of the domain. +dt = hbar/(2*hbar**2/(m*dx**2)+Vmax) # Critical time step. +c1 = hbar*dt/(m*dx**2) # Constant coefficient 1. +c2 = 2*dt/hbar # Constant coefficient 2. +c2V = c2*V # pre-compute outside of update loop + +# Print summary info +print 'One-dimensional Schrodinger equation - time evolution' +print 'Potential type: ',POTENTIAL +print 'Potential height V0: ',V0 +print 'Barrier thickness: ',THCK + +# Wave functions. Three states represent past, present, and future. +psi_r = np.zeros((3,N)) # Real +psi_i = np.zeros((3,N)) # Imaginary +psi_p = np.zeros(N,) # Observable probability (magnitude-squared + # of the complex wave function). + +# Temporal indexing constants, used for accessing rows of the wavefunctions. +PA = 0 # Past +PR = 1 # Present +FU = 2 # Future + +# Initialize wave function. A present-only state will "split" with half the +# wave function propagating to the left and the other half to the right. +# Including a "past" state will cause it to propagate one way. +xn = range(1,N/2) +x = X[xn]/dx # Normalized position coordinate +gg = Gaussian(x,x0,sigma) +cx = np.cos(k0*x) +sx = np.sin(k0*x) +psi_r[PR,xn] = cx*gg +psi_i[PR,xn] = sx*gg +psi_r[PA,xn] = cx*gg +psi_i[PA,xn] = sx*gg + +# Initial normalization of wavefunctions +# Compute the observable probability. +psi_p = psi_r[PR]**2 + psi_i[PR]**2 + +# Normalize the wave functions so that the total probability in the simulation +# is equal to 1. +P = dx * psi_p.sum() # Total probability. +nrm = np.sqrt(P) +psi_r /= nrm +psi_i /= nrm +psi_p /= P + +# Initialize the figure and axes. +pylab.figure() +ymax = 1.5*(psi_r[PR]).max() +pylab.axis([X.min(),X.max(),-ymax,ymax]) + +# Initialize the plots with their own line objects. The figures plot MUCH +# faster if you simply update the lines as opposed to redrawing the entire +# figure. For reference, include the potential function as well. +lineR, = pylab.plot(X,psi_r[PR],'b',alpha=0.7) # "Real" line +lineI, = pylab.plot(X,psi_i[PR],'r',alpha=0.7) # "Imag" line. +lineP, = pylab.plot(X,psi_p,'k') # "Probability" line +pylab.title('Potential height: %.2e' % V0) +pylab.legend(('Real','Imag','Prob')) + +# For non-zero potentials, plot them and shade the classically forbidden region +# in light red +if V.max() !=0 : + V_plot = V/V.max()*ymax/2 + pylab.plot(X,V_plot,':k',zorder=0) # Potential line. + # reverse x and y2 so the polygon fills in order + y1 = free(N) # lower boundary for polygon drawing + x = np.concatenate( (X,X[::-1]) ) + y = np.concatenate( (y1,V_plot[::-1]) ) + pylab.fill(x, y, facecolor='y', alpha=0.2,zorder=0) +pylab.draw() + +# Direct index assignment is MUCH faster than using a spatial FOR loop, so +# these constants are used in the update equations. Remember that Python uses +# zero-based indexing. +IDX1 = range(1,N-1) # psi [ k ] +IDX2 = range(2,N) # psi [ k + 1 ] +IDX3 = range(0,N-2) # psi [ k - 1 ] + +for t in range(0,T+1): + # Apply the update equations. + psi_i[FU,IDX1] = psi_i[PA,IDX1] + \ + c1*(psi_r[PR,IDX2] - 2*psi_r[PR,IDX1] + + psi_r[PR,IDX3]) + psi_i[FU] = psi_i[FU] - c2V*psi_r[PR] + + psi_r[FU,IDX1] = psi_r[PA,IDX1] - \ + c1*(psi_i[PR,IDX2] - 2*psi_i[PR,IDX1] + + psi_i[PR,IDX3]) + psi_r[FU] = psi_r[FU] + c2V*psi_i[PR] + + # Increment the time steps. PR -> PA and FU -> PR + psi_r[PA] = psi_r[PR] + psi_r[PR] = psi_r[FU] + psi_i[PA] = psi_i[PR] + psi_i[PR] = psi_i[FU] + + # Only plot after a few iterations to make the simulation run faster. + if t % Tp == 0: + # Compute observable probability for the plot. + psi_p = psi_r[PR]**2 + psi_i[PR]**2 + + # Update the plots. + lineR.set_ydata(psi_r[PR]) + lineI.set_ydata(psi_i[PR]) + # Note: we plot the probability density amplified by a factor so it's a + # bit easier to see. + lineP.set_ydata(6*psi_p) + + pylab.draw() + +# So the windows don't auto-close at the end if run outside ipython +pylab.ioff() +pylab.show() Property changes on: trunk/py4science/examples/schrodinger/schrod_fdtd.py ___________________________________________________________________ Name: svn:executable + * This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2007-10-20 21:23:57
|
Revision: 3972 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3972&view=rev Author: jdh2358 Date: 2007-10-20 14:23:56 -0700 (Sat, 20 Oct 2007) Log Message: ----------- added stock records CSV example Added Paths: ----------- trunk/py4science/examples/skel/stock_records_skel.py trunk/py4science/examples/stock_records.py Added: trunk/py4science/examples/skel/stock_records_skel.py =================================================================== --- trunk/py4science/examples/skel/stock_records_skel.py (rev 0) +++ trunk/py4science/examples/skel/stock_records_skel.py 2007-10-20 21:23:56 UTC (rev 3972) @@ -0,0 +1,71 @@ +""" +Download historical pricing record arrays for a universe of stocks +from Yahoo Finance using urllib. Load them into numpy record arrays +using matplotlib.mlab.csv2rec, and do some batch processing -- make +date vs price charts for each one, and compute the return since 2003 +for each stock. Sort the returns and print out the tickers of the 4 +biggest winners +""" +import os, datetime, urllib +import matplotlib.mlab as mlab # contains csv2rec +import numpy as npy +import pylab as p + +def fetch_stock(ticker): + """ + download the CSV file for stock with ticker and return a numpy + record array. Save the CSV file as TICKER.csv where TICKER is the + stock's ticker symbol. + + Extra credit for supporting a start date and end date, and + checking to see if the file already exists on the local file + system before re-downloading it + """ + fname = '%s.csv'%ticker + url = XXX # create the url for this ticker + + # the os.path module contains function for checking whether a file + # exists, and fetch it if not + XXX + + # load the CSV file intoo a numpy record array + r = XXX + + # note that the CSV file is sorted most recent date first, so you + # will probably want to sort the record array so most recent date + # is last + XXX + return r + +tickers = 'INTC', 'MSFT', 'YHOO', 'GOOG', 'GE', 'WMT', 'AAPL' + +# we want to compute returns since 2003, so define the start date as a +# datetime.datetime instance +startdate = XXX + +# we'll store a list of each return and ticker for analysis later +data = [] # a list of (return, ticker) for each stock +fig = p.figure() +for ticker in tickers: + print 'fetching', ticker + r = fetch_stock(ticker) + + # select the numpy records where r.date>=startdatre use numpy mask + # indexing to restrict r to just the dates > startdate + r = XXX + price = XXX # set price equal to the adjusted close + returns = XXX # return is the (price-p0)/p0 + XXX # store the data + + # plot the returns by date for each stock using pylab.plot, adding + # a label for the legend + XXX + +# use pylab legend command to build a legend +XXX + +# now sort the data by returns and print the results for each stock +XXX + +# show the figures +p.show() Added: trunk/py4science/examples/stock_records.py =================================================================== --- trunk/py4science/examples/stock_records.py (rev 0) +++ trunk/py4science/examples/stock_records.py 2007-10-20 21:23:56 UTC (rev 3972) @@ -0,0 +1,72 @@ +""" +Download historical pricing record arrays for a universe of stocks +from Yahoo Finance using urllib. Load them into numpy record arrays +using matplotlib.mlab.csv2rec, and do some batch processing -- make +date vs price charts for each one, and compute the return since 2003 +for each stock. Sort the returns and print out the tickers of the 4 +biggest winners +""" +import os, datetime, urllib +import matplotlib.mlab as mlab # contains csv2rec +import numpy as npy +import pylab as p + +def fetch_stock(ticker): + """ + download the CSV file for stock with ticker and return a numpy + record array. Save the CSV file as TICKER.csv where TICKER is the + stock's ticker symbol. + + Extra credit for supporting a start date and end date, and + checking to see if the file already exists on the local file + system before re-downloading it + """ + fname = '%s.csv'%ticker + url = 'http://ichart.finance.yahoo.com/table.csv?' +\ + 's=%s&d=9&e=20&f=2007&g=d&a=0&b=29&c=1993&ignore=.csv'%ticker + + # the os.path module contains function for checking whether a file + # exists + if not os.path.exists(fname): + urllib.urlretrieve(url, fname) + r = mlab.csv2rec(fname) + + # note that the CSV file is sorted most recent date first, so you + # will probably want to sort the record array so most recent date + # is last + r.sort() + return r + +tickers = 'INTC', 'MSFT', 'YHOO', 'GOOG', 'GE', 'WMT', 'AAPL' + +# we want to compute returns since 2003, so define the start date +startdate = datetime.datetime(2003,1,1) + +# we'll store a list of each return and ticker for analysis later +data = [] # a list of (return, ticker) for each stock +fig = p.figure() +for ticker in tickers: + print 'fetching', ticker + r = fetch_stock(ticker) + + # select the numpy records where r.date>=startdatre + + r = r[r.date>=startdate] + price = r.adj_close # set price equal to the adjusted close + returns = (price-price[0])/price[0] # return is the (price-p0)/p0 + data.append((returns[-1], ticker)) # store the data + + # plot the returns by date for each stock + p.plot(r.date, returns, label=ticker) + +p.legend(loc='upper left') + +# now sort the data by returns and print the results for each stock +data.sort() +for g, ticker in data: + print '%s: %1.1f%%'%(ticker, 100*g) + + +p.savefig('fig/stock_records.png', dpi=100) +p.savefig('fig/stock_records.eps') +p.show() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2007-10-21 21:08:35
|
Revision: 3978 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3978&view=rev Author: jdh2358 Date: 2007-10-21 14:08:33 -0700 (Sun, 21 Oct 2007) Log Message: ----------- minor tweaks to glass dots Modified Paths: -------------- trunk/py4science/examples/glass_dots1.py trunk/py4science/examples/skel/glass_dots_skel.py Modified: trunk/py4science/examples/glass_dots1.py =================================================================== --- trunk/py4science/examples/glass_dots1.py 2007-10-21 20:57:54 UTC (rev 3977) +++ trunk/py4science/examples/glass_dots1.py 2007-10-21 21:08:33 UTC (rev 3978) @@ -42,16 +42,13 @@ X1 = matrix(npy.random.rand(2,2000))-0.5 name = 'saddle' -#sx, sy, angle = 1.05, 0.95, 0. +sx, sy, angle = 1.05, 0.95, 0. -#name = 'focus' -#sx, sy, angle = 1.05, 0.95, 2.6 - #name = 'center' #sx, sy, angle = 1., 1., 2.5 -name= 'spiral' -sx, sy, angle = 0.95, 0.95, 2.5 +#name= 'stable focus' # spiral +#sx, sy, angle = 0.95, 0.95, 2.5 theta = angle * pi/180. @@ -72,7 +69,7 @@ avals = myeig(M) print 'analytic eigenvalues', avals -# transform X by the matrix +# transform X1 by the matrix X2 = M*X1 # plot the original x,y as green dots and the transformed x, y as red Modified: trunk/py4science/examples/skel/glass_dots_skel.py =================================================================== --- trunk/py4science/examples/skel/glass_dots_skel.py 2007-10-21 20:57:54 UTC (rev 3977) +++ trunk/py4science/examples/skel/glass_dots_skel.py 2007-10-21 21:08:33 UTC (rev 3978) @@ -36,10 +36,10 @@ name = 'saddle' #sx, sy, angle = XXX -#name = 'focus' +#name = 'center' #sx, sy, angle = XXX -#name = 'center' +#name = 'stable focus' # spiral #sx, sy, angle = XXX name= 'spiral' This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2007-10-25 19:39:32
|
Revision: 4005 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4005&view=rev Author: jdh2358 Date: 2007-10-25 12:39:31 -0700 (Thu, 25 Oct 2007) Log Message: ----------- fixed convolution example w/ zero padding Added Paths: ----------- trunk/py4science/examples/convolution_demo.py trunk/py4science/examples/data/moonlanding.png trunk/py4science/examples/skel/convolution_demo_skel.py Added: trunk/py4science/examples/convolution_demo.py =================================================================== --- trunk/py4science/examples/convolution_demo.py (rev 0) +++ trunk/py4science/examples/convolution_demo.py 2007-10-25 19:39:31 UTC (rev 4005) @@ -0,0 +1,74 @@ +""" +In signal processing, the output of a linear system to an arbitrary +input is given by the convolution of the impule response function (the +system response to a Dirac-delta impulse) and the input signal. + +Mathematically: + + y(t) = \int_0^\t x(\tau)r(t-\tau)d\tau + + +where x(t) is the input signal at time t, y(t) is the output, and r(t) +is the impulse response function. + +In this exercise, we will compute investigate the convolution of a +white noise process with a double exponential impulse response +function, and compute the results + + * using numpy.convolve + + * in Fourier space using the property that a convolution in the + temporal domain is a multiplication in the fourier domain +""" + +import numpy as npy +import matplotlib.mlab as mlab +from pylab import figure, show + +# build the time, input, output and response arrays +dt = 0.01 +t = npy.arange(0.0, 20.0, dt) # the time vector from 0..20 +Nt = len(t) + +def impulse_response(t): + 'double exponential response function' + return (npy.exp(-t) - npy.exp(-5*t))*dt + + +x = npy.random.randn(Nt) # gaussian white noise + +# evaluate the impulse response function, and numerically convolve it +# with the input x +r = impulse_response(t) # evaluate the impulse function +y = npy.convolve(x, r, mode='full') # convultion of x with r +y = y[:Nt] + +# compute y by applying F^-1[F(x) * F(r)]. The fft assumes the signal +# is periodic, so to avoid edge artificats, pad the fft with zeros up +# to the length of r + x do avoid circular convolution artifacts +R = npy.fft.fft(r, len(r)+len(x)-1) +X = npy.fft.fft(x, len(r)+len(x)-1) +Y = R*X + +# now inverse fft and extract just the part up to len(x) +yi = npy.fft.ifft(Y)[:len(x)].real + +# plot t vs x, t vs y and yi, and t vs r in three subplots +fig = figure() +ax1 = fig.add_subplot(311) +ax1.plot(t, x) +ax1.set_ylabel('input x') + +ax2 = fig.add_subplot(312) +ax2.plot(t, y, label='convolve') +ax2.set_ylabel('output y') + +ax3 = fig.add_subplot(313) +ax3.plot(t, r) +ax3.set_ylabel('input response') +ax3.set_xlabel('time (s)') + +ax2.plot(t, yi, label='fft') +ax2.legend(loc='best') + +show() Added: trunk/py4science/examples/data/moonlanding.png =================================================================== (Binary files differ) Property changes on: trunk/py4science/examples/data/moonlanding.png ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/py4science/examples/skel/convolution_demo_skel.py =================================================================== --- trunk/py4science/examples/skel/convolution_demo_skel.py (rev 0) +++ trunk/py4science/examples/skel/convolution_demo_skel.py 2007-10-25 19:39:31 UTC (rev 4005) @@ -0,0 +1,59 @@ +""" +In signal processing, the output of a linear system to an arbitrary +input is given by the convolution of the impule response function (the +system response to a Dirac-delta impulse) and the input signal. + +Mathematically: + + y(t) = \int_0^\t x(\tau)r(t-\tau)d\tau + + +where x(t) is the input signal at time t, y(t) is the output, and r(t) +is the impulse response function. + +In this exercise, we will compute investigate the convolution of a +white noise process with a double exponential impulse response +function, and compute the results + + * using numpy.convolve + + * in Fourier space using the property that a convolution in the + temporal domain is a multiplication in the fourier domain +""" + +import numpy as npy +import matplotlib.mlab as mlab +from pylab import figure, show + +# build the time, input, output and response arrays +dt = 0.01 +t = XXX # the time vector from 0..20 +Nt = len(t) + +def impulse_response(t): + 'double exponential response function' + return XXX + + +x = XXX # gaussian white noise + +# evaluate the impulse response function, and numerically convolve it +# with the input x +r = XXX # evaluate the impulse function +y = XXX # convultion of x with r +y = XXX # extract just the length Nt part + +# compute y by applying F^-1[F(x) * F(r)]. The fft assumes the signal +# is periodic, so to avoid edge artificats, pad the fft with zeros up +# to the length of r + x do avoid circular convolution artifacts +R = XXX # the zero padded FFT of r +X = XXX # the zero padded FFT of x +Y = XXX # the product of R and S + +# now inverse fft and extract the real part, just the part up to +# len(x) +yi = XXX + +# plot t vs x, t vs y and yi, and t vs r in three subplots +XXX +show() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2007-10-26 20:16:08
|
Revision: 4029 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4029&view=rev Author: jdh2358 Date: 2007-10-26 13:15:51 -0700 (Fri, 26 Oct 2007) Log Message: ----------- added stats distributions examples Modified Paths: -------------- trunk/py4science/examples/stats_descriptives.py trunk/py4science/examples/stats_distributions.py Modified: trunk/py4science/examples/stats_descriptives.py =================================================================== --- trunk/py4science/examples/stats_descriptives.py 2007-10-26 20:15:42 UTC (rev 4028) +++ trunk/py4science/examples/stats_descriptives.py 2007-10-26 20:15:51 UTC (rev 4029) @@ -76,21 +76,27 @@ c = C() N = 5 fig = c.fig = figfunc() + fig.subplots_adjust(hspace=0.3) ax = c.ax1 = fig.add_subplot(N,1,1) c.plot = ax.plot(data, fmt) + ax.set_ylabel('data') ax = c.ax2 = fig.add_subplot(N,1,2) c.hist = ax.hist(data, bins) + ax.set_ylabel('hist') - ax = c.ax3 = fig.add_subplot(N,1,3) - c.acorr = ax.acorr(data, detrend=detrend, usevlines=True, maxlags=maxlags) + c.acorr = ax.acorr(data, detrend=detrend, usevlines=True, + maxlags=maxlags, normed=True) + ax.set_ylabel('acorr') ax = c.ax4 = fig.add_subplot(N,1,4) c.psd = ax.psd(data, Fs=Fs, detrend=detrend) + ax.set_ylabel('psd') ax = c.ax5 = fig.add_subplot(N,1,5) c.specgtram = ax.specgram(data, Fs=Fs, detrend=detrend) + ax.set_ylabel('specgram') return c @@ -111,6 +117,9 @@ desc = Descriptives(data) print desc - c = desc.plots(pylab.figure, Fs=12, fmt='-o') + c = desc.plots(pylab.figure, Fs=12, fmt='-') c.ax1.set_title(fname) + + c.fig.savefig('stats_descriptives.png', dpi=150) + c.fig.savefig('stats_descriptives.eps') pylab.show() Modified: trunk/py4science/examples/stats_distributions.py =================================================================== --- trunk/py4science/examples/stats_distributions.py 2007-10-26 20:15:42 UTC (rev 4028) +++ trunk/py4science/examples/stats_distributions.py 2007-10-26 20:15:51 UTC (rev 4029) @@ -35,18 +35,18 @@ # 1/lambda. Plot all three on the same graph and make a legend. # Decorate your graphs with an xlabel, ylabel and title fig = figure() -ax = fig.add_subplot(111) +ax = fig.add_subplot(311) p, bins, patches = ax.hist(wait_times, 100, normed=True) l1, = ax.plot(bins, rate*numpy.exp(-rate * bins), lw=2, color='red') l2, = ax.plot(bins, scipy.stats.expon.pdf(bins, 0, 1./rate), lw=2, ls='--', color='green') -ax.set_xlabel('waiting time') + ax.set_ylabel('PDF') -ax.set_title('waiting time density of a %dHz Poisson emitter'%rate) +ax.set_title('waiting time densities of a %dHz Poisson emitter'%rate) +ax.text(0.05, 0.9, 'one interval', transform=ax.transAxes) ax.legend((patches[0], l1, l2), ('simulated', 'analytic', 'scipy.stats.expon')) - # plot the distribution of waiting times for two events; the # distribution of waiting times for N events should equal a N-th order # gamma distribution (the exponential distribution is a 1st order @@ -54,17 +54,15 @@ # Hint: you can stride your emission times array to get every 2nd # emission wait_times2 = numpy.diff(emit_times[::2]) -fig = figure() -ax = fig.add_subplot(111) +ax = fig.add_subplot(312) p, bins, patches = ax.hist(wait_times2, 100, normed=True) l1, = ax.plot(bins, scipy.stats.gamma.pdf(bins, 2, 0, 1./rate), lw=2, ls='-', color='red') -ax.set_xlabel('2 event waiting time 2 events') + ax.set_ylabel('PDF') -ax.set_title('waiting time density of a %dHz Poisson emitter'%rate) +ax.text(0.05, 0.9, 'two intervals', transform=ax.transAxes) ax.legend((patches[0], l1), ('simulated', 'scipy.stats.gamma')) - # plot the distribution of waiting times for 10 events; again the # distribution will be a 10th order gamma distribution so plot that # along with the empirical density. The central limit thm says that @@ -81,19 +79,20 @@ mu, var = 10*expon_mean, 10*expon_var sigma = numpy.sqrt(var) wait_times10 = numpy.diff(emit_times[::10]) -fig = figure() -ax = fig.add_subplot(111) +ax = fig.add_subplot(313) p, bins, patches = ax.hist(wait_times10, 100, normed=True) l1, = ax.plot(bins, scipy.stats.gamma.pdf(bins, 10, 0, 1./rate), lw=2, ls='-', color='red') l2, = ax.plot(bins, scipy.stats.norm.pdf(bins, mu, sigma), lw=2, ls='--', color='green') -ax.set_xlabel('waiting time 10 events') +ax.set_xlabel('waiting times') ax.set_ylabel('PDF') -ax.set_title('10 event waiting time density of a %dHz Poisson emitter'%rate) +ax.text(0.1, 0.9, 'ten intervals', transform=ax.transAxes) ax.legend((patches[0], l1, l2), ('simulated', 'scipy.stats.gamma', 'normal approx')) +fig.savefig('stats_distributions.png', dpi=150) +fig.savefig('stats_distributions.eps') show() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2007-10-28 15:00:39
|
Revision: 4038 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4038&view=rev Author: jdh2358 Date: 2007-10-28 08:00:36 -0700 (Sun, 28 Oct 2007) Log Message: ----------- added lotka example Modified Paths: -------------- trunk/py4science/examples/qsort.py Added Paths: ----------- trunk/py4science/examples/lotka_volterra.py trunk/py4science/examples/skel/lotka_volterra_skel.py Added: trunk/py4science/examples/lotka_volterra.py =================================================================== --- trunk/py4science/examples/lotka_volterra.py (rev 0) +++ trunk/py4science/examples/lotka_volterra.py 2007-10-28 15:00:36 UTC (rev 4038) @@ -0,0 +1,78 @@ +import numpy as n +import pylab as p +import scipy.integrate as integrate + +def dr(r, f): + return alpha*r - beta*r*f + +def df(r, f): + return gamma*r*f - delta*f + +def derivs(state, t): + """ + Map the state variable [rabbits, foxes] to the derivitives + [deltar, deltaf] at time t + """ + #print t, state + r, f = state # rabbits and foxes + deltar = dr(r, f) # change in rabbits + deltaf = df(r, f) # change in foxes + return deltar, deltaf + +alpha, delta = 1, .25 +beta, gamma = .2, .05 + +# the initial population of rabbits and foxes +r0 = 20 +f0 = 10 + +t = n.arange(0.0, 100, 0.1) + +y0 = [r0, f0] # the initial [rabbits, foxes] state vector +y = integrate.odeint(derivs, y0, t) +r = y[:,0] # extract the rabbits vector +f = y[:,1] # extract the foxes vector + +p.figure() +p.plot(t, r, label='rabbits') +p.plot(t, f, label='foxes') +p.xlabel('time (years)') +p.ylabel('population') +p.title('population trajectories') +p.grid() +p.legend() +p.savefig('lotka_volterra.png', dpi=150) +p.savefig('lotka_volterra.eps') + + +p.figure() +p.plot(r, f) +p.xlabel('rabbits') +p.ylabel('foxes') +p.title('phase plane') + + +# make a direction field plot with quiver +rmax = 1.1 * r.max() +fmax = 1.1 * f.max() +R, F = n.meshgrid(n.arange(-1, rmax), n.arange(-1, fmax)) +dR = dr(R, F) +dF = df(R, F) +p.quiver(R, F, dR, dF) + + +R, F = n.meshgrid(n.arange(-1, rmax, .1), n.arange(-1, fmax, .1)) +dR = dr(R, F) +dF = df(R, F) + +p.contour(R, F, dR, levels=[0], linewidths=3, colors='black') +p.contour(R, F, dF, levels=[0], linewidths=3, colors='black') +p.ylabel('foxes') +p.title('trajectory, direction field and null clines') + +p.savefig('lotka_volterra_pplane.png', dpi=150) +p.savefig('lotka_volterra_pplane.eps') + + +p.show() + Modified: trunk/py4science/examples/qsort.py =================================================================== --- trunk/py4science/examples/qsort.py 2007-10-27 12:36:39 UTC (rev 4037) +++ trunk/py4science/examples/qsort.py 2007-10-28 15:00:36 UTC (rev 4038) @@ -33,5 +33,7 @@ rseq = range(10) random.shuffle(rseq) sseq = qsort(rseq) + print tseq + print sseq self.assertEqual(tseq,sseq) main() Added: trunk/py4science/examples/skel/lotka_volterra_skel.py =================================================================== --- trunk/py4science/examples/skel/lotka_volterra_skel.py (rev 0) +++ trunk/py4science/examples/skel/lotka_volterra_skel.py 2007-10-28 15:00:36 UTC (rev 4038) @@ -0,0 +1,56 @@ +import numpy as n +import pylab as p +import scipy.integrate as integrate + +def dr(r, f): + 'return delta r' + XXX + +def df(r, f): + 'return delta f' + XXX +def derivs(state, t): + """ + Map the state variable [rabbits, foxes] to the derivitives + [deltar, deltaf] at time t + """ + XXX + +alpha, delta = 1, .25 +beta, gamma = .2, .05 + +# the initial population of rabbits and foxes +r0 = 20 +f0 = 10 + +t = XXX # pick a time vector (think about the time scales!) +y0 = [r0, f0] # the initial [rabbits, foxes] state vector +y = XXX # integrate derives over t starting at y0 +r = XXX # extract the rabbits vector +f = XXX # extract the foxes vector + + +# FIGURE 1: rabbits vs time and foxes vs time on the same plot with +# legend and xlabel, ylabel and title + +# FIGURE 2: the phase plane + +# plot r vs f and label the x and y axes +XXX + +# FIGURE 2 continued.... + +# use meshgrid to make a grid over R and F +# with a coarse 1 year sampling. evaluate dR and dF over the 2 s +# grids and make a quiver plot. See pylab.quiver and matplotlib +# examples/quiver_demo.py +XXX + +# FIGURE 2 continued... use contour to compute the null clines over +# dR (the rabbits null cline) and dF (the foxes null cline). You will +# need to do a finer meshgrid for accurate null clins and pass +# levels=[0] to contour +XXX + +p.show() + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <js...@us...> - 2007-11-21 20:52:56
|
Revision: 4411 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4411&view=rev Author: jswhit Date: 2007-11-21 12:52:25 -0800 (Wed, 21 Nov 2007) Log Message: ----------- added examples for 'Plotting on Maps' workbook chapter Added Paths: ----------- trunk/py4science/examples/basemap1.py trunk/py4science/examples/basemap2.py trunk/py4science/examples/basemap3.py trunk/py4science/examples/basemap4.py trunk/py4science/examples/basemap5.py Added: trunk/py4science/examples/basemap1.py =================================================================== --- trunk/py4science/examples/basemap1.py (rev 0) +++ trunk/py4science/examples/basemap1.py 2007-11-21 20:52:25 UTC (rev 4411) @@ -0,0 +1,28 @@ +import pylab, numpy +from matplotlib.toolkits.basemap import Basemap + +# create figure. +# background color will be used for 'wet' areas. +fig = pylab.figure() +fig.add_axes([0.1,0.1,0.8,0.8],axisbg='aqua') +# create map by specifying lat/lon values at corners. +resolution = 'l' +lon_0 = -50 +lat_0 = 60 +projection = 'lcc' +llcrnrlat, llcrnrlon = 8, -92 +urcrnrlat, urcrnrlon = 39, 63 +m = Basemap(lon_0=lon_0,lat_0=lat_0,\ + llcrnrlat=llcrnrlat,llcrnrlon=llcrnrlon,\ + urcrnrlat=urcrnrlat,urcrnrlon=urcrnrlon,\ + resolution=resolution,projection=projection) +# draw coastlines. Make liness a little thinner than default. +m.drawcoastlines(linewidth=0.5) +# fill continents. +m.fillcontinents(color='coral') +# draw states and countries. +m.drawcountries() +m.drawstates() +pylab.title('map region specified using corner lat/lon values') +pylab.savefig('basemap1.eps') +pylab.savefig('basemap1.png') Added: trunk/py4science/examples/basemap2.py =================================================================== --- trunk/py4science/examples/basemap2.py (rev 0) +++ trunk/py4science/examples/basemap2.py 2007-11-21 20:52:25 UTC (rev 4411) @@ -0,0 +1,27 @@ +import pylab, numpy +from matplotlib.toolkits.basemap import Basemap + +# create figure. +# background color will be used for 'wet' areas. +fig = pylab.figure() +fig.add_axes([0.1,0.1,0.8,0.8],axisbg='aqua') +# create map by specifying width and height in km. +resolution = 'l' +lon_0 = -50 +lat_0 = 60 +projection = 'lcc' +width = 12000000 +height = 0.75*width +m = Basemap(lon_0=lon_0,lat_0=lat_0,\ + width=width,height=height,\ + resolution=resolution,projection=projection) +# draw coastlines. +m.drawcoastlines(linewidth=0.5) +# fill continents. +m.fillcontinents(color='coral') +# draw states and countries. +m.drawcountries() +m.drawstates() +pylab.title('map region specified using width and height') +pylab.savefig('basemap2.eps') +pylab.savefig('basemap2.png') Added: trunk/py4science/examples/basemap3.py =================================================================== --- trunk/py4science/examples/basemap3.py (rev 0) +++ trunk/py4science/examples/basemap3.py 2007-11-21 20:52:25 UTC (rev 4411) @@ -0,0 +1,45 @@ +import pylab, numpy +from matplotlib.toolkits.basemap import Basemap + +# create figure. +# background color will be used for 'wet' areas. +fig = pylab.figure() +fig.add_axes([0.1,0.1,0.8,0.8],axisbg='aqua') +# create map by specifying width and height in km. +resolution = 'l' +lon_0 = -50 +lat_0 = 60 +projection = 'lcc' +width = 12000000 +height = 0.75*width +m = Basemap(lon_0=lon_0,lat_0=lat_0,\ + width=width,height=height,\ + resolution=resolution,projection=projection) +# nylat, nylon are lat/lon of New York +nylat = 40.78 +nylon = -73.98 +# lonlat, lonlon are lat/lon of London. +lonlat = 51.53 +lonlon = 0.08 +# convert these points to map projection coordinates +# (using __call__ method of Basemap instance) +ny_x, ny_y = m(nylon, nylat) +lon_x, lon_y = m(lonlon, lonlat) +# plot black dots at the two points. +# make sure dots are drawn on top of other plot elements (zorder=10) +m.scatter([ny_x,lon_x],[ny_y,lon_y],25,color='k',marker='o',zorder=10) +# connect the dots along a great circle. +m.drawgreatcircle(nylon,nylat,lonlon,lonlat,linewidth=2,color='k') +# put the names of the cities to the left of each dot, offset +# by a little. Use a bold font. +pylab.text(ny_x-100000,ny_y+100000,'New York',fontsize=12,\ + color='k',horizontalalignment='right',fontweight='bold') +pylab.text(lon_x-100000,lon_y+100000,'London',fontsize=12,\ + color='k',horizontalalignment='right',fontweight='bold') +m.drawcoastlines(linewidth=0.5) +m.fillcontinents(color='coral') +m.drawcountries() +m.drawstates() +pylab.title('NY to London Great Circle') +pylab.savefig('basemap3.eps') +pylab.savefig('basemap3.png') Added: trunk/py4science/examples/basemap4.py =================================================================== --- trunk/py4science/examples/basemap4.py (rev 0) +++ trunk/py4science/examples/basemap4.py 2007-11-21 20:52:25 UTC (rev 4411) @@ -0,0 +1,29 @@ +import pylab, numpy +from matplotlib.toolkits.basemap import Basemap +# create figure. +# background color will be used for 'wet' areas. +fig = pylab.figure() +fig.add_axes([0.1,0.1,0.8,0.8],axisbg='aqua') +# create map by specifying width and height in km. +resolution = 'l' +lon_0 = -50 +lat_0 = 60 +projection = 'lcc' +width = 12000000 +height = 0.75*width +m = Basemap(lon_0=lon_0,lat_0=lat_0,\ + width=width,height=height,\ + resolution=resolution,projection=projection) +m.drawcoastlines(linewidth=0.5) +m.fillcontinents(color='coral') +m.drawcountries() +m.drawstates() +# label meridians where they intersect the left, right and bottom +# of the plot frame. +m.drawmeridians(numpy.arange(-180,181,20),labels=[1,1,0,1]) +# label parallels where they intersect the left, right and top +# of the plot frame. +m.drawparallels(numpy.arange(-80,81,20),labels=[1,1,1,0]) +pylab.title('labelled meridians and parallels',y=1.075) +pylab.savefig('basemap4.eps') +pylab.savefig('basemap4.png') Added: trunk/py4science/examples/basemap5.py =================================================================== --- trunk/py4science/examples/basemap5.py (rev 0) +++ trunk/py4science/examples/basemap5.py 2007-11-21 20:52:25 UTC (rev 4411) @@ -0,0 +1,38 @@ +from matplotlib.toolkits.basemap import Basemap, NetCDFFile +import pylab, numpy +from numpy import ma + +# read in netCDF sea-surface temperature data +ncfile = NetCDFFile('data/sst.nc') +sstv = ncfile.variables['analysed_sst'] +sst = ma.masked_values(numpy.squeeze(sstv[:]), sstv._FillValue) +sst = sstv.scale_factor*sst + sstv.add_offset +lats = ncfile.variables['lat'][:] +lons = ncfile.variables['lon'][:] +print sst.shape, sst.min(), sst.max() + +# make sure middle of map region is middle of data grid. +lon_0 = lons.mean() +lat_0 = lats.mean() +# set colormap +cmap = pylab.cm.gist_ncar +# create Basemap instance for mollweide projection. +m = Basemap(projection='moll',lon_0=lon_0,lat_0=lat_0,resolution='l') +# compute map projection coordinates of grid. +x, y = m(*numpy.meshgrid(lons, lats)) +# plot with contour +#CS = m.contour(x,y,sst,20,linewidths=0.5,colors='k') +#CS = m.contourf(x,y,sst,20,cmap=cmap) +# plot with pcolor +im = m.pcolormesh(x,y,sst,shading='flat',cmap=cmap) +# fill the continents (data is not defined there). +m.fillcontinents(color='k',lake_color='k') +# draw parallels and meridians. +m.drawparallels(numpy.arange(-90.,120.,30.)) +m.drawmeridians(numpy.arange(0.,420.,60.)) +# draw line around map projection limb. +m.drawmapboundary() +# draw horizontal colorbar. +pylab.colorbar(orientation='horizontal') +pylab.savefig('basemap5.pdf') # eps files are too huge when pcolor used. +pylab.savefig('basemap5.png') This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <js...@us...> - 2007-11-21 21:33:43
|
Revision: 4414 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4414&view=rev Author: jswhit Date: 2007-11-21 13:33:25 -0800 (Wed, 21 Nov 2007) Log Message: ----------- bug fixes Modified Paths: -------------- trunk/py4science/examples/basemap1.py trunk/py4science/examples/basemap2.py Modified: trunk/py4science/examples/basemap1.py =================================================================== --- trunk/py4science/examples/basemap1.py 2007-11-21 21:25:27 UTC (rev 4413) +++ trunk/py4science/examples/basemap1.py 2007-11-21 21:33:25 UTC (rev 4414) @@ -7,12 +7,12 @@ fig.add_axes([0.1,0.1,0.8,0.8],axisbg='aqua') # create map by specifying lat/lon values at corners. resolution = 'l' +projection = 'lcc' +lat_0 = 60 lon_0 = -50 -lat_0 = 60 -projection = 'lcc' llcrnrlat, llcrnrlon = 8, -92 urcrnrlat, urcrnrlon = 39, 63 -m = Basemap(lon_0=lon_0,lat_0=lat_0,\ +m = Basemap(lat_0=lat_0,lon_0=lon_0,\ llcrnrlat=llcrnrlat,llcrnrlon=llcrnrlon,\ urcrnrlat=urcrnrlat,urcrnrlon=urcrnrlon,\ resolution=resolution,projection=projection) Modified: trunk/py4science/examples/basemap2.py =================================================================== --- trunk/py4science/examples/basemap2.py 2007-11-21 21:25:27 UTC (rev 4413) +++ trunk/py4science/examples/basemap2.py 2007-11-21 21:33:25 UTC (rev 4414) @@ -7,9 +7,9 @@ fig.add_axes([0.1,0.1,0.8,0.8],axisbg='aqua') # create map by specifying width and height in km. resolution = 'l' +projection = 'lcc' lon_0 = -50 lat_0 = 60 -projection = 'lcc' width = 12000000 height = 0.75*width m = Basemap(lon_0=lon_0,lat_0=lat_0,\ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <js...@us...> - 2007-11-23 17:54:49
|
Revision: 4428 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4428&view=rev Author: jswhit Date: 2007-11-23 09:54:40 -0800 (Fri, 23 Nov 2007) Log Message: ----------- update basemap example Modified Paths: -------------- trunk/py4science/examples/basemap5.py trunk/py4science/examples/skel/basemap5_skel.py Modified: trunk/py4science/examples/basemap5.py =================================================================== --- trunk/py4science/examples/basemap5.py 2007-11-23 13:47:36 UTC (rev 4427) +++ trunk/py4science/examples/basemap5.py 2007-11-23 17:54:40 UTC (rev 4428) @@ -22,12 +22,9 @@ # create Basemap instance for mollweide projection. # coastlines not used, so resolution set to None to skip # continent processing (this speeds things up a bit) -m = Basemap(projection='moll',lon_0=lon_0,lat_0=lat_0,resolution='l') +m = Basemap(projection='moll',lon_0=lon_0,lat_0=lat_0,resolution=None) # compute map projection coordinates of grid. x, y = m(*numpy.meshgrid(lons, lats)) -# plot with contour -#CS = m.contour(x,y,sst,20,linewidths=0.5,colors='k') -#CS = m.contourf(x,y,sst,20,cmap=cmap) # plot with pcolor im = m.pcolormesh(x,y,sst,shading='flat',cmap=cmap) # draw parallels and meridians, but don't bother labelling them. Modified: trunk/py4science/examples/skel/basemap5_skel.py =================================================================== --- trunk/py4science/examples/skel/basemap5_skel.py 2007-11-23 13:47:36 UTC (rev 4427) +++ trunk/py4science/examples/skel/basemap5_skel.py 2007-11-23 17:54:40 UTC (rev 4428) @@ -30,9 +30,6 @@ m = Basemap(projection=projection,lon_0=lon_0,lat_0=lat_0,resolution=None) # compute map projection coordinates of grid. x, y = m(*numpy.meshgrid(lons, lats)) -# plot with contour -#CS = m.contour(x,y,sst,20,linewidths=0.5,colors='k') -#CS = m.contourf(x,y,sst,20,cmap=cmap) # plot with pcolor im = m.pcolormesh(x,y,sst,shading='flat',cmap=cmap) # draw parallels and meridians, but don't bother labelling them. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <js...@us...> - 2007-12-02 13:23:26
|
Revision: 4543 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4543&view=rev Author: jswhit Date: 2007-12-02 05:23:22 -0800 (Sun, 02 Dec 2007) Log Message: ----------- save png output at 600 dpi (instead of eps/pdf) Modified Paths: -------------- trunk/py4science/examples/basemap1.py trunk/py4science/examples/basemap2.py trunk/py4science/examples/basemap3.py trunk/py4science/examples/basemap4.py trunk/py4science/examples/basemap5.py Modified: trunk/py4science/examples/basemap1.py =================================================================== --- trunk/py4science/examples/basemap1.py 2007-12-02 13:22:48 UTC (rev 4542) +++ trunk/py4science/examples/basemap1.py 2007-12-02 13:23:22 UTC (rev 4543) @@ -24,5 +24,4 @@ m.drawcountries() m.drawstates() pylab.title('map region specified using corner lat/lon values') -pylab.savefig('basemap1.eps') -pylab.savefig('basemap1.png') +pylab.savefig('basemap1.png',dpi=600) Modified: trunk/py4science/examples/basemap2.py =================================================================== --- trunk/py4science/examples/basemap2.py 2007-12-02 13:22:48 UTC (rev 4542) +++ trunk/py4science/examples/basemap2.py 2007-12-02 13:23:22 UTC (rev 4543) @@ -19,5 +19,4 @@ m.drawcountries() m.drawstates() pylab.title('map region specified using width and height') -pylab.savefig('basemap2.eps') -pylab.savefig('basemap2.png') +pylab.savefig('basemap2.png',dpi=600) Modified: trunk/py4science/examples/basemap3.py =================================================================== --- trunk/py4science/examples/basemap3.py 2007-12-02 13:22:48 UTC (rev 4542) +++ trunk/py4science/examples/basemap3.py 2007-12-02 13:23:22 UTC (rev 4543) @@ -40,5 +40,4 @@ m.drawcountries() m.drawstates() pylab.title('NY to London Great Circle') -pylab.savefig('basemap3.eps') -pylab.savefig('basemap3.png') +pylab.savefig('basemap3.png',dpi=600) Modified: trunk/py4science/examples/basemap4.py =================================================================== --- trunk/py4science/examples/basemap4.py 2007-12-02 13:22:48 UTC (rev 4542) +++ trunk/py4science/examples/basemap4.py 2007-12-02 13:23:22 UTC (rev 4543) @@ -24,5 +24,4 @@ # of the plot frame. m.drawparallels(numpy.arange(-80,81,20),labels=[1,1,1,0]) pylab.title('labelled meridians and parallels',y=1.075) -pylab.savefig('basemap4.eps') -pylab.savefig('basemap4.png') +pylab.savefig('basemap4.png',dpi=600) Modified: trunk/py4science/examples/basemap5.py =================================================================== --- trunk/py4science/examples/basemap5.py 2007-12-02 13:22:48 UTC (rev 4542) +++ trunk/py4science/examples/basemap5.py 2007-12-02 13:23:22 UTC (rev 4543) @@ -29,5 +29,4 @@ m.drawmapboundary(fill_color='k') # draw horizontal colorbar. pylab.colorbar(orientation='horizontal') -pylab.savefig('basemap5.pdf') -pylab.savefig('basemap5.png') +pylab.savefig('basemap5.png',dpi=600) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <js...@us...> - 2007-12-03 01:39:22
|
Revision: 4550 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4550&view=rev Author: jswhit Date: 2007-12-02 17:39:21 -0800 (Sun, 02 Dec 2007) Log Message: ----------- remove blank lines Modified Paths: -------------- trunk/py4science/examples/basemap1.py trunk/py4science/examples/basemap2.py trunk/py4science/examples/basemap3.py trunk/py4science/examples/basemap4.py trunk/py4science/examples/basemap5.py Modified: trunk/py4science/examples/basemap1.py =================================================================== --- trunk/py4science/examples/basemap1.py 2007-12-03 01:33:24 UTC (rev 4549) +++ trunk/py4science/examples/basemap1.py 2007-12-03 01:39:21 UTC (rev 4550) @@ -1,6 +1,5 @@ import pylab, numpy from matplotlib.toolkits.basemap import Basemap - # create figure. fig = pylab.figure() # create map by specifying lat/lon values at corners. @@ -24,4 +23,4 @@ m.drawcountries() m.drawstates() pylab.title('map region specified using corner lat/lon values') -pylab.savefig('basemap1.png',dpi=600) +pylab.show() Modified: trunk/py4science/examples/basemap2.py =================================================================== --- trunk/py4science/examples/basemap2.py 2007-12-03 01:33:24 UTC (rev 4549) +++ trunk/py4science/examples/basemap2.py 2007-12-03 01:39:21 UTC (rev 4550) @@ -1,6 +1,5 @@ import pylab, numpy from matplotlib.toolkits.basemap import Basemap - # create figure. fig = pylab.figure() # create map by specifying width and height in km. @@ -19,4 +18,4 @@ m.drawcountries() m.drawstates() pylab.title('map region specified using width and height') -pylab.savefig('basemap2.png',dpi=600) +pylab.show() Modified: trunk/py4science/examples/basemap3.py =================================================================== --- trunk/py4science/examples/basemap3.py 2007-12-03 01:33:24 UTC (rev 4549) +++ trunk/py4science/examples/basemap3.py 2007-12-03 01:39:21 UTC (rev 4550) @@ -1,6 +1,5 @@ import pylab, numpy from matplotlib.toolkits.basemap import Basemap - # create figure. fig = pylab.figure() # create map by specifying width and height in km. @@ -40,4 +39,4 @@ m.drawcountries() m.drawstates() pylab.title('NY to London Great Circle') -pylab.savefig('basemap3.png',dpi=600) +pylab.show() Modified: trunk/py4science/examples/basemap4.py =================================================================== --- trunk/py4science/examples/basemap4.py 2007-12-03 01:33:24 UTC (rev 4549) +++ trunk/py4science/examples/basemap4.py 2007-12-03 01:39:21 UTC (rev 4550) @@ -24,4 +24,4 @@ # of the plot frame. m.drawparallels(numpy.arange(-80,81,20),labels=[1,1,1,0]) pylab.title('labelled meridians and parallels',y=1.075) -pylab.savefig('basemap4.png',dpi=600) +pylab.show() Modified: trunk/py4science/examples/basemap5.py =================================================================== --- trunk/py4science/examples/basemap5.py 2007-12-03 01:33:24 UTC (rev 4549) +++ trunk/py4science/examples/basemap5.py 2007-12-03 01:39:21 UTC (rev 4550) @@ -25,4 +25,4 @@ m.drawmapboundary(fill_color='k') # draw horizontal colorbar. pylab.colorbar(orientation='horizontal') -pylab.savefig('basemap5.png',dpi=600) +pylab.show() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <js...@us...> - 2007-12-03 13:27:35
|
Revision: 4558 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4558&view=rev Author: jswhit Date: 2007-12-03 05:27:16 -0800 (Mon, 03 Dec 2007) Log Message: ----------- more cleanups of example scripts Modified Paths: -------------- trunk/py4science/examples/basemap1.py trunk/py4science/examples/basemap2.py trunk/py4science/examples/basemap3.py trunk/py4science/examples/basemap4.py trunk/py4science/examples/basemap5.py Modified: trunk/py4science/examples/basemap1.py =================================================================== --- trunk/py4science/examples/basemap1.py 2007-12-03 13:20:19 UTC (rev 4557) +++ trunk/py4science/examples/basemap1.py 2007-12-03 13:27:16 UTC (rev 4558) @@ -1,12 +1,8 @@ import pylab, numpy from matplotlib.toolkits.basemap import Basemap -# create figure. -fig = pylab.figure() # create map by specifying lat/lon values at corners. -resolution = 'l' -projection = 'lcc' -lat_0 = 60 -lon_0 = -50 +resolution = 'l'; projection = 'lcc' +lat_0 = 60; lon_0 = -50 llcrnrlat, llcrnrlon = 8, -92 urcrnrlat, urcrnrlon = 39, 63 m = Basemap(lat_0=lat_0,lon_0=lon_0,\ Modified: trunk/py4science/examples/basemap2.py =================================================================== --- trunk/py4science/examples/basemap2.py 2007-12-03 13:20:19 UTC (rev 4557) +++ trunk/py4science/examples/basemap2.py 2007-12-03 13:27:16 UTC (rev 4558) @@ -1,14 +1,9 @@ import pylab, numpy from matplotlib.toolkits.basemap import Basemap -# create figure. -fig = pylab.figure() # create map by specifying width and height in km. -resolution = 'l' -projection = 'lcc' -lon_0 = -50 -lat_0 = 60 -width = 12000000 -height = 0.75*width +resolution = 'l'; projection = 'lcc' +lon_0 = -50; lat_0 = 60 +width = 12000000; height = 0.75*width m = Basemap(lon_0=lon_0,lat_0=lat_0,\ width=width,height=height,\ resolution=resolution,projection=projection) Modified: trunk/py4science/examples/basemap3.py =================================================================== --- trunk/py4science/examples/basemap3.py 2007-12-03 13:20:19 UTC (rev 4557) +++ trunk/py4science/examples/basemap3.py 2007-12-03 13:27:16 UTC (rev 4558) @@ -1,16 +1,10 @@ import pylab, numpy from matplotlib.toolkits.basemap import Basemap -# create figure. -fig = pylab.figure() # create map by specifying width and height in km. -resolution = 'l' -lon_0 = -50 -lat_0 = 60 -projection = 'lcc' -width = 12000000 -height = 0.75*width -m = Basemap(lon_0=lon_0,lat_0=lat_0,\ - width=width,height=height,\ +resolution = 'l'; projection = 'lcc' +lon_0 = -50; lat_0 = 60 +width = 12000000; height = 0.75*width +m = Basemap(lon_0=lon_0,lat_0=lat_0,width=width,height=height, resolution=resolution,projection=projection) # nylat, nylon are lat/lon of New York nylat = 40.78 Modified: trunk/py4science/examples/basemap4.py =================================================================== --- trunk/py4science/examples/basemap4.py 2007-12-03 13:20:19 UTC (rev 4557) +++ trunk/py4science/examples/basemap4.py 2007-12-03 13:27:16 UTC (rev 4558) @@ -1,7 +1,5 @@ import pylab, numpy from matplotlib.toolkits.basemap import Basemap -# create figure. -fig = pylab.figure() # create map by specifying width and height in km. resolution = 'l' lon_0 = -50 @@ -9,8 +7,7 @@ projection = 'lcc' width = 12000000 height = 0.75*width -m = Basemap(lon_0=lon_0,lat_0=lat_0,\ - width=width,height=height,\ +m = Basemap(lon_0=lon_0,lat_0=lat_0,width=width,height=height, resolution=resolution,projection=projection) m.drawcoastlines(linewidth=0.5) m.drawmapboundary(fill_color='aqua') Modified: trunk/py4science/examples/basemap5.py =================================================================== --- trunk/py4science/examples/basemap5.py 2007-12-03 13:20:19 UTC (rev 4557) +++ trunk/py4science/examples/basemap5.py 2007-12-03 13:27:16 UTC (rev 4558) @@ -7,8 +7,6 @@ sst = ncfile.variables['analysed_sst'][:] lats = ncfile.variables['lat'][:] lons = ncfile.variables['lon'][:] -# set colormap -cmap = pylab.cm.gist_ncar # create Basemap instance for mollweide projection. # coastlines not used, so resolution set to None to skip # continent processing (this speeds things up a bit) @@ -16,7 +14,7 @@ # compute map projection coordinates of grid. x, y = m(*numpy.meshgrid(lons, lats)) # plot with pcolor -im = m.pcolormesh(x,y,sst,shading='flat',cmap=cmap) +im = m.pcolormesh(x,y,sst,shading='flat',cmap=pylab.cm.gist_ncar) # draw parallels and meridians, but don't bother labelling them. m.drawparallels(numpy.arange(-90.,120.,30.)) m.drawmeridians(numpy.arange(0.,420.,60.)) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <js...@us...> - 2007-12-03 17:30:49
|
Revision: 4567 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4567&view=rev Author: jswhit Date: 2007-12-03 09:30:46 -0800 (Mon, 03 Dec 2007) Log Message: ----------- update basemap example Modified Paths: -------------- trunk/py4science/examples/basemap5.py trunk/py4science/examples/data/sst.nc trunk/py4science/examples/skel/basemap5_skel.py Modified: trunk/py4science/examples/basemap5.py =================================================================== --- trunk/py4science/examples/basemap5.py 2007-12-03 17:15:06 UTC (rev 4566) +++ trunk/py4science/examples/basemap5.py 2007-12-03 17:30:46 UTC (rev 4567) @@ -4,7 +4,7 @@ # can be a local file, a URL for a remote opendap dataset, # or (if PyNIO is installed) a GRIB or HDF file. ncfile = NetCDFFile('data/sst.nc') -sst = ncfile.variables['analysed_sst'][:] +sst = ncfile.variables['sst'][:] lats = ncfile.variables['lat'][:] lons = ncfile.variables['lon'][:] # create Basemap instance for mollweide projection. Modified: trunk/py4science/examples/data/sst.nc =================================================================== (Binary files differ) Modified: trunk/py4science/examples/skel/basemap5_skel.py =================================================================== --- trunk/py4science/examples/skel/basemap5_skel.py 2007-12-03 17:15:06 UTC (rev 4566) +++ trunk/py4science/examples/skel/basemap5_skel.py 2007-12-03 17:30:46 UTC (rev 4567) @@ -5,12 +5,10 @@ # or (if PyNIO is installed) a GRIB or HDF file. # See http://nomads.ncdc.noaa.gov/ for some NOAA OPenDAP datasets. ncfile = NetCDFFile('data/sst.nc') -sst = ncfile.variables['analysed_sst'][:] -# uncommenting the next two lines will -# produce a very similar plot, but will read -# the data over the web instead of from a local file. +# uncommenting the next line will produce a very similar plot, +# but will read the data over the web instead of from a local file. #ncfile = NetCDFFile('http://nomads.ncdc.noaa.gov:8085/thredds/dodsC/oisst/2007/AVHRR/sst4-navy-eot.20071201.nc') -#sst = ncfile.variables['sst'][:] +sst = ncfile.variables['sst'][:] lats = ncfile.variables['lat'][:] lons = ncfile.variables['lon'][:] # Basemap comes with extra colormaps from Generic Mapping Tools This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2007-12-06 20:01:55
|
Revision: 4655 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4655&view=rev Author: jdh2358 Date: 2007-12-06 12:01:48 -0800 (Thu, 06 Dec 2007) Log Message: ----------- added pyrex simple sum demo Modified Paths: -------------- trunk/py4science/examples/lotka_volterra.py Added Paths: ----------- trunk/py4science/examples/pyrex/ trunk/py4science/examples/pyrex/Makefile trunk/py4science/examples/pyrex/c_numpy.pxd trunk/py4science/examples/pyrex/c_python.pxd trunk/py4science/examples/pyrex/numpyx.pyx trunk/py4science/examples/pyrex/run_test.py trunk/py4science/examples/pyrex/setup.py trunk/py4science/examples/pyrex/sums.pyx trunk/py4science/examples/pyrex/sums_test.py Modified: trunk/py4science/examples/lotka_volterra.py =================================================================== --- trunk/py4science/examples/lotka_volterra.py 2007-12-06 19:18:49 UTC (rev 4654) +++ trunk/py4science/examples/lotka_volterra.py 2007-12-06 20:01:48 UTC (rev 4655) @@ -34,24 +34,22 @@ f = y[:,1] # extract the foxes vector p.figure() -p.plot(t, r, label='rabbits') -p.plot(t, f, label='foxes') +p.subplots_adjust(hspace=0.3) +p.subplot(211) +p.plot(t, r, color='blue', label='rabbits', lw=2) +p.plot(t, f, color='green', label='foxes', lw=2) p.xlabel('time (years)') p.ylabel('population') -p.title('population trajectories') +p.title('population trajectories and phase plane') p.grid() p.legend() -p.savefig('lotka_volterra.png', dpi=150) -p.savefig('lotka_volterra.eps') -p.figure() -p.plot(r, f) +p.subplot(212, aspect='equal') +p.plot(r, f, 'k', lw=2) p.xlabel('rabbits') p.ylabel('foxes') -p.title('phase plane') - # make a direction field plot with quiver rmax = 1.1 * r.max() fmax = 1.1 * f.max() @@ -65,13 +63,13 @@ dR = dr(R, F) dF = df(R, F) -p.contour(R, F, dR, levels=[0], linewidths=3, colors='black') -p.contour(R, F, dF, levels=[0], linewidths=3, colors='black') +CSR = p.contour(R, F, dR, levels=[0], linewidths=3, colors='blue') +CSF = p.contour(R, F, dF, levels=[0], linewidths=3, colors='green') + p.ylabel('foxes') -p.title('trajectory, direction field and null clines') -p.savefig('lotka_volterra_pplane.png', dpi=150) -p.savefig('lotka_volterra_pplane.eps') +p.savefig('lotka_volterra.png', dpi=150) +p.savefig('lotka_volterra.eps') p.show() Added: trunk/py4science/examples/pyrex/Makefile =================================================================== --- trunk/py4science/examples/pyrex/Makefile (rev 0) +++ trunk/py4science/examples/pyrex/Makefile 2007-12-06 20:01:48 UTC (rev 4655) @@ -0,0 +1,9 @@ +all: + python setup.py build_ext --inplace + +test: all + python sums_test.py + +.PHONY: clean +clean: + rm -rf *~ *.so *.c *.o build Added: trunk/py4science/examples/pyrex/c_numpy.pxd =================================================================== --- trunk/py4science/examples/pyrex/c_numpy.pxd (rev 0) +++ trunk/py4science/examples/pyrex/c_numpy.pxd 2007-12-06 20:01:48 UTC (rev 4655) @@ -0,0 +1,125 @@ +# :Author: Travis Oliphant + +cdef extern from "numpy/arrayobject.h": + + cdef enum NPY_TYPES: + NPY_BOOL + NPY_BYTE + NPY_UBYTE + NPY_SHORT + NPY_USHORT + NPY_INT + NPY_UINT + NPY_LONG + NPY_ULONG + NPY_LONGLONG + NPY_ULONGLONG + NPY_FLOAT + NPY_DOUBLE + NPY_LONGDOUBLE + NPY_CFLOAT + NPY_CDOUBLE + NPY_CLONGDOUBLE + NPY_OBJECT + NPY_STRING + NPY_UNICODE + NPY_VOID + NPY_NTYPES + NPY_NOTYPE + + cdef enum requirements: + NPY_CONTIGUOUS + NPY_FORTRAN + NPY_OWNDATA + NPY_FORCECAST + NPY_ENSURECOPY + NPY_ENSUREARRAY + NPY_ELEMENTSTRIDES + NPY_ALIGNED + NPY_NOTSWAPPED + NPY_WRITEABLE + NPY_UPDATEIFCOPY + NPY_ARR_HAS_DESCR + + NPY_BEHAVED + NPY_BEHAVED_NS + NPY_CARRAY + NPY_CARRAY_RO + NPY_FARRAY + NPY_FARRAY_RO + NPY_DEFAULT + + NPY_IN_ARRAY + NPY_OUT_ARRAY + NPY_INOUT_ARRAY + NPY_IN_FARRAY + NPY_OUT_FARRAY + NPY_INOUT_FARRAY + + NPY_UPDATE_ALL + + cdef enum defines: + # Note: as of Pyrex 0.9.5, enums are type-checked more strictly, so this + # can't be used as an integer. + NPY_MAXDIMS + + ctypedef struct npy_cdouble: + double real + double imag + + ctypedef struct npy_cfloat: + double real + double imag + + ctypedef int npy_intp + + ctypedef extern class numpy.dtype [object PyArray_Descr]: + cdef int type_num, elsize, alignment + cdef char type, kind, byteorder, hasobject + cdef object fields, typeobj + + ctypedef extern class numpy.ndarray [object PyArrayObject]: + cdef char *data + cdef int nd + cdef npy_intp *dimensions + cdef npy_intp *strides + cdef object base + cdef dtype descr + cdef int flags + + ctypedef extern class numpy.flatiter [object PyArrayIterObject]: + cdef int nd_m1 + cdef npy_intp index, size + cdef ndarray ao + cdef char *dataptr + + ctypedef extern class numpy.broadcast [object PyArrayMultiIterObject]: + cdef int numiter + cdef npy_intp size, index + cdef int nd + # These next two should be arrays of [NPY_MAXITER], but that is + # difficult to cleanly specify in Pyrex. Fortunately, it doesn't matter. + cdef npy_intp *dimensions + cdef void **iters + + object PyArray_ZEROS(int ndims, npy_intp* dims, NPY_TYPES type_num, int fortran) + object PyArray_EMPTY(int ndims, npy_intp* dims, NPY_TYPES type_num, int fortran) + dtype PyArray_DescrFromTypeNum(NPY_TYPES type_num) + object PyArray_SimpleNew(int ndims, npy_intp* dims, NPY_TYPES type_num) + int PyArray_Check(object obj) + object PyArray_ContiguousFromAny(object obj, NPY_TYPES type, + int mindim, int maxdim) + npy_intp PyArray_SIZE(ndarray arr) + npy_intp PyArray_NBYTES(ndarray arr) + void *PyArray_DATA(ndarray arr) + object PyArray_FromAny(object obj, dtype newtype, int mindim, int maxdim, + int requirements, object context) + object PyArray_FROMANY(object obj, NPY_TYPES type_num, int min, + int max, int requirements) + object PyArray_NewFromDescr(object subtype, dtype newtype, int nd, + npy_intp* dims, npy_intp* strides, void* data, + int flags, object parent) + + void PyArray_ITER_NEXT(flatiter it) + + void import_array() Added: trunk/py4science/examples/pyrex/c_python.pxd =================================================================== --- trunk/py4science/examples/pyrex/c_python.pxd (rev 0) +++ trunk/py4science/examples/pyrex/c_python.pxd 2007-12-06 20:01:48 UTC (rev 4655) @@ -0,0 +1,20 @@ +# -*- Mode: Python -*- Not really, but close enough + +# Expose as much of the Python C API as we need here + +cdef extern from "stdlib.h": + ctypedef int size_t + +cdef extern from "Python.h": + ctypedef int Py_intptr_t + void* PyMem_Malloc(size_t) + void* PyMem_Realloc(void *p, size_t n) + void PyMem_Free(void *p) + char* PyString_AsString(object string) + object PyString_FromString(char *v) + object PyString_InternFromString(char *v) + int PyErr_CheckSignals() + object PyFloat_FromDouble(double v) + void Py_XINCREF(object o) + void Py_XDECREF(object o) + void Py_CLEAR(object o) # use instead of decref Added: trunk/py4science/examples/pyrex/numpyx.pyx =================================================================== --- trunk/py4science/examples/pyrex/numpyx.pyx (rev 0) +++ trunk/py4science/examples/pyrex/numpyx.pyx 2007-12-06 20:01:48 UTC (rev 4655) @@ -0,0 +1,128 @@ +# -*- Mode: Python -*- Not really, but close enough + +cimport c_python +cimport c_numpy +import numpy + +# Numpy must be initialized +c_numpy.import_array() + +def print_array_info(c_numpy.ndarray arr): + cdef int i + + print '-='*10 + print 'printing array info for ndarray at 0x%0lx'%(<c_python.Py_intptr_t>arr,) + print 'print number of dimensions:',arr.nd + print 'address of strides: 0x%0lx'%(<c_python.Py_intptr_t>arr.strides,) + print 'strides:' + for i from 0<=i<arr.nd: + # print each stride + print ' stride %d:'%i,<c_python.Py_intptr_t>arr.strides[i] + print 'memory dump:' + print_elements( arr.data, arr.strides, arr.dimensions, + arr.nd, sizeof(double), arr.dtype ) + print '-='*10 + print + + + +def sum_elements(c_numpy.ndarray arr): + cdef int i + cdef double x, val + + x = 0. + val = 0. + for i from 0<=i<arr.dimensions[0]: + val = (<double*>(arr.data + i*arr.strides[0]))[0] + x = x + val + + return x + + +def scale_elements(int N): + cdef int i + cdef double x, val + + x = 0. + val = 0. + for i from 0<=i<N: + val = 2.5 * i + x = x + val + return x + + +cdef print_elements(char *data, + c_python.Py_intptr_t* strides, + c_python.Py_intptr_t* dimensions, + int nd, + int elsize, + object dtype): + cdef c_python.Py_intptr_t i,j + cdef void* elptr + + if dtype not in [numpy.dtype(numpy.object_), + numpy.dtype(numpy.float64)]: + print ' print_elements() not (yet) implemented for dtype %s'%dtype.name + return + + if nd ==0: + if dtype==numpy.dtype(numpy.object_): + elptr = (<void**>data)[0] #[0] dereferences pointer in Pyrex + print ' ',<object>elptr + elif dtype==numpy.dtype(numpy.float64): + print ' ',(<double*>data)[0] + elif nd == 1: + for i from 0<=i<dimensions[0]: + if dtype==numpy.dtype(numpy.object_): + elptr = (<void**>data)[0] + print ' ',<object>elptr + elif dtype==numpy.dtype(numpy.float64): + print ' ',(<double*>data)[0] + data = data + strides[0] + else: + for i from 0<=i<dimensions[0]: + print_elements(data, strides+1, dimensions+1, nd-1, elsize, dtype) + data = data + strides[0] + + +def test_methods(c_numpy.ndarray arr): + """Test a few attribute accesses for an array. + + This illustrates how the pyrex-visible object is in practice a strange + hybrid of the C PyArrayObject struct and the python object. Some + properties (like .nd) are visible here but not in python, while others + like flags behave very differently: in python flags appears as a separate, + object while here we see the raw int holding the bit pattern. + + This makes sense when we think of how pyrex resolves arr.foo: if foo is + listed as a field in the c_numpy.ndarray struct description, it will be + directly accessed as a C variable without going through Python at all. + This is why for arr.flags, we see the actual int which holds all the flags + as bit fields. However, for any other attribute not listed in the struct, + it simply forwards the attribute lookup to python at runtime, just like + python would (which means that AttributeError can be raised for + non-existent attributes, for example).""" + + print 'arr.any() :',arr.any() + print 'arr.nd :',arr.nd + print 'arr.flags :',arr.flags + +def test(): + """this function is pure Python""" + arr1 = numpy.array(-1e-30,dtype=numpy.float64) + arr2 = numpy.array([1.0,2.0,3.0],dtype=numpy.float64) + + arr3 = numpy.arange(9,dtype=numpy.float64) + arr3.shape = 3,3 + + four = 4 + arr4 = numpy.array(['one','two',3,four],dtype=numpy.object_) + + arr5 = numpy.array([1,2,3]) # int types not (yet) supported by print_elements + + for arr in [arr1,arr2,arr3,arr4,arr5]: + print_array_info(arr) + + + arr = numpy.arange(10.0) + print 'sum el', sum_elements(arr) Added: trunk/py4science/examples/pyrex/run_test.py =================================================================== --- trunk/py4science/examples/pyrex/run_test.py (rev 0) +++ trunk/py4science/examples/pyrex/run_test.py 2007-12-06 20:01:48 UTC (rev 4655) @@ -0,0 +1,3 @@ +#!/usr/bin/env python +from numpyx import test +test() Property changes on: trunk/py4science/examples/pyrex/run_test.py ___________________________________________________________________ Name: svn:executable + * Added: trunk/py4science/examples/pyrex/setup.py =================================================================== --- trunk/py4science/examples/pyrex/setup.py (rev 0) +++ trunk/py4science/examples/pyrex/setup.py 2007-12-06 20:01:48 UTC (rev 4655) @@ -0,0 +1,42 @@ +#!/usr/bin/env python +"""Install file for example on how to use Pyrex with Numpy. + +For more details, see: +http://www.scipy.org/Cookbook/Pyrex_and_NumPy +http://www.scipy.org/Cookbook/ArrayStruct_and_Pyrex +""" + +from distutils.core import setup +from distutils.extension import Extension + +# Make this usable by people who don't have pyrex installed (I've committed +# the generated C sources to SVN). +try: + from Pyrex.Distutils import build_ext + has_pyrex = True +except ImportError: + has_pyrex = False + +import numpy + +# Define a pyrex-based extension module, using the generated sources if pyrex +# is not available. +if has_pyrex: + pyx_sources = ['sums.pyx'] + cmdclass = {'build_ext': build_ext} +else: + pyx_sources = ['numpyx.c'] + cmdclass = {} + + +pyx_ext = Extension('sums', + pyx_sources, + include_dirs = [numpy.get_include()]) + +# Call the routine which does the real work +setup(name = 'sums', + description = 'Small example on using Pyrex to write a Numpy extension', + url = 'http://www.scipy.org/Cookbook/Pyrex_and_NumPy', + ext_modules = [pyx_ext], + cmdclass = cmdclass, + ) Added: trunk/py4science/examples/pyrex/sums.pyx =================================================================== --- trunk/py4science/examples/pyrex/sums.pyx (rev 0) +++ trunk/py4science/examples/pyrex/sums.pyx 2007-12-06 20:01:48 UTC (rev 4655) @@ -0,0 +1,39 @@ +# -*- Mode: Python -*- Not really, but close enough + +cimport c_python +cimport c_numpy +import numpy + +# Numpy must be initialized +c_numpy.import_array() + +def sum_elements(c_numpy.ndarray arr): + cdef int i + cdef double x, val + + x = 0. + val = 0. + for i from 0<=i<arr.dimensions[0]: + val = (<double*>(arr.data + i*arr.strides[0]))[0] + x = x + val + + return x + + + +def sum_elements2(c_numpy.ndarray arr): + cdef int i + cdef double x, val + + arr = numpy.asarray(arr, numpy.float_) + + if arr.nd!=1: + raise RuntimeError('only 1D arrays supported; found shape=%s'%str(arr.shape)) + assert(arr.nd==1) + x = 0. + val = 0. + for i from 0<=i<arr.dimensions[0]: + val = (<double*>(arr.data + i*arr.strides[0]))[0] + x = x + val + + return x Added: trunk/py4science/examples/pyrex/sums_test.py =================================================================== --- trunk/py4science/examples/pyrex/sums_test.py (rev 0) +++ trunk/py4science/examples/pyrex/sums_test.py 2007-12-06 20:01:48 UTC (rev 4655) @@ -0,0 +1,29 @@ +import numpy +import sums + +def sumpy(arr): + + total = 0. + for val in x: + total += val + return total + +x = numpy.arange(10) +y = numpy.random.rand(10,10) + +print 'sum(x)', sums.sum_elements(x) +print 'sum2(x)', sums.sum_elements2(x) +print 'sum(y)', sums.sum_elements(y) +#print 'sum2(y)', sums.sum_elements2(y) + +x = numpy.arange(1e6) +import time +start = time.time() +s1 = sums.sum_elements2(x) +now = time.time() +print 'pyrex time', now - start + +start = time.time() +s1 = sumpy(x) +now = time.time() +print 'python time', now - start This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2007-12-08 16:23:50
|
Revision: 4674 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4674&view=rev Author: jdh2358 Date: 2007-12-08 08:23:40 -0800 (Sat, 08 Dec 2007) Log Message: ----------- added butter and filtfilt Modified Paths: -------------- trunk/py4science/examples/pyrex/movavg/movavg_ringbuf.py trunk/py4science/examples/pyrex/sums/numpyx.pyx Added Paths: ----------- trunk/py4science/examples/butter_filter.py trunk/py4science/examples/filtilt_demo.py Added: trunk/py4science/examples/butter_filter.py =================================================================== --- trunk/py4science/examples/butter_filter.py (rev 0) +++ trunk/py4science/examples/butter_filter.py 2007-12-08 16:23:40 UTC (rev 4674) @@ -0,0 +1,41 @@ +import numpy as n +import scipy.signal as signal +from pylab import figure, show + +dt = 0.01 +t = n.arange(0, 2, dt) +s = n.sin(2*n.pi*t) + +# sine corrupted wih gaussian white noise +sn = s + 0.1*n.random.randn(len(s)) # noisy sine + +# the nyquist frequency 1/(2dt) +Nyq = 0.5/dt + +cornerfreq = 2. # the corner frequency +stopfreq = 5. # the stop frequency + +# the corner and stop freqs as fractions of the nyquist +ws = cornerfreq/Nyq +wp = stopfreq/Nyq + + +# the order and butterworth natural frequency for use with butter +N, wn = signal.buttord(wp, ws, 3, 16) + +# return the butterworth filter coeffs for the given order and frequency +b, a = signal.butter(N, wn) + +# filter the data +sf = signal.lfilter(b, a, sn) + +fig = figure() +ax = fig.add_subplot(111) +ax.plot(t, s, label='original signal') +ax.plot(t, sn, label='noisy signal') +ax.plot(t, sf, label='filtered signal') +ax.legend() +ax.set_title('low pass butterworth filter of sine') +ax.set_xlabel('time (s)') +ax.grid() +show() Added: trunk/py4science/examples/filtilt_demo.py =================================================================== --- trunk/py4science/examples/filtilt_demo.py (rev 0) +++ trunk/py4science/examples/filtilt_demo.py 2007-12-08 16:23:40 UTC (rev 4674) @@ -0,0 +1,102 @@ +""" +Cookbook / FiltFilt : http://www.scipy.org/Cookbook/FiltFilt + +This sample code implements a zero phase delay filter that processes +the signal in the forward and backward direction removing the phase +delay. The order of the filter is the double of the original filter +order. The function also computes the initial filter parameters in +order to provide a more stable response (via lfilter_zi). The +following code has been tested with Python 2.4.4 and Scipy 0.5.1. + +""" +from numpy import vstack, hstack, eye, ones, zeros, linalg, \ +newaxis, r_, flipud, convolve, matrix, array +from scipy.signal import lfilter + +def lfilter_zi(b,a): + + #compute the zi state from the filter parameters. see [Gust96]. + + #Based on: [Gust96] Fredrik Gustafsson, Determining the initial + # states in forward-backward filtering, IEEE Transactions on + # Signal Processing, pp. 988--992, April 1996, Volume 44, Issue 4 + + n=max(len(a),len(b)) + + zin = ( eye(n-1) - hstack( (-a[1:n,newaxis], + vstack((eye(n-2), zeros(n-2)))))) + + zid = b[1:n] - a[1:n]*b[0] + + zi_matrix=linalg.inv(zin)*(matrix(zid).transpose()) + zi_return=[] + + #convert the result into a regular array (not a matrix) + for i in range(len(zi_matrix)): + zi_return.append(float(zi_matrix[i][0])) + + return array(zi_return) + + + + +def filtfilt(b,a,x): + #For now only accepting 1d arrays + ntaps=max(len(a),len(b)) + edge=ntaps*3 + + if x.ndim != 1: + raise ValueError, "Filiflit is only accepting 1 dimension arrays." + + #x must be bigger than edge + if x.size < edge: + raise ValueError, "Input vector needs to be bigger than 3 * max(len(a),len(b)." + + if len(a) < ntaps: + a=r_[a,zeros(len(b)-len(a))] + + if len(b) < ntaps: + b=r_[b,zeros(len(a)-len(b))] + + zi=lfilter_zi(b,a) + + #Grow the signal to have edges for stabilizing + #the filter with inverted replicas of the signal + s=r_[2*x[0]-x[edge:1:-1],x,2*x[-1]-x[-1:-edge:-1]] + #in the case of one go we only need one of the extrems + # both are needed for filtfilt + + (y,zf)=lfilter(b,a,s,-1,zi*s[0]) + + (y,zf)=lfilter(b,a,flipud(y),-1,zi*y[-1]) + + return flipud(y[edge-1:-edge+1]) + + + +if __name__=='__main__': + + import scipy.signal as signal + from scipy import sin, arange, pi, randn + + from pylab import plot, legend, show, hold + + t = arange(-1,1,.01) + x = sin(2*pi*t*.5+2) + + # add some noise to the signa + xn = x+randn(len(t))*0.05 + + # parameters for a butterworth lowpass filter + [b,a] = signal.butter(3,0.05) + + z = lfilter(b, a, xn) + y = filtfilt(b, a, xn) + + plot(x, 'c', label='original') + plot(xn, 'k', label='noisy signal') + plot(z, 'r', label='lfilter - butter 3 order') + plot(y, 'g', label='filtfilt - butter 3 order') + legend(loc='best') + show() + Modified: trunk/py4science/examples/pyrex/movavg/movavg_ringbuf.py =================================================================== --- trunk/py4science/examples/pyrex/movavg/movavg_ringbuf.py 2007-12-08 14:00:28 UTC (rev 4673) +++ trunk/py4science/examples/pyrex/movavg/movavg_ringbuf.py 2007-12-08 16:23:40 UTC (rev 4674) @@ -4,7 +4,7 @@ import numpy import ringbuf -r = ringbuf.Ringbuf(30) +r = ringbuf.Ringbuf(31) x = numpy.random.rand(10000) data = [] Modified: trunk/py4science/examples/pyrex/sums/numpyx.pyx =================================================================== --- trunk/py4science/examples/pyrex/sums/numpyx.pyx 2007-12-08 14:00:28 UTC (rev 4673) +++ trunk/py4science/examples/pyrex/sums/numpyx.pyx 2007-12-08 16:23:40 UTC (rev 4674) @@ -26,31 +26,6 @@ -def sum_elements(c_numpy.ndarray arr): - cdef int i - cdef double x, val - - x = 0. - val = 0. - for i from 0<=i<arr.dimensions[0]: - val = (<double*>(arr.data + i*arr.strides[0]))[0] - x = x + val - - return x - - -def scale_elements(int N): - cdef int i - cdef double x, val - - x = 0. - val = 0. - for i from 0<=i<N: - val = 2.5 * i - x = x + val - return x - - cdef print_elements(char *data, c_python.Py_intptr_t* strides, c_python.Py_intptr_t* dimensions, This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2007-12-08 16:35:27
|
Revision: 4675 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4675&view=rev Author: jdh2358 Date: 2007-12-08 08:35:17 -0800 (Sat, 08 Dec 2007) Log Message: ----------- added filter examples Modified Paths: -------------- trunk/py4science/examples/butter_filter.py Added Paths: ----------- trunk/py4science/examples/skel/butter_filter_skel.py Modified: trunk/py4science/examples/butter_filter.py =================================================================== --- trunk/py4science/examples/butter_filter.py 2007-12-08 16:23:40 UTC (rev 4674) +++ trunk/py4science/examples/butter_filter.py 2007-12-08 16:35:17 UTC (rev 4675) @@ -9,26 +9,38 @@ # sine corrupted wih gaussian white noise sn = s + 0.1*n.random.randn(len(s)) # noisy sine -# the nyquist frequency 1/(2dt) +# the nyquist frequency 1/(2dt) is the maximum frequency in a sampled +# signal Nyq = 0.5/dt +#the corner frequency represents a boundary in the system response at +#which energy entering the system begins to be attenuate, and the stop +#frequency is the frequency at which the signal is (practically) +#completely attenuated cornerfreq = 2. # the corner frequency stopfreq = 5. # the stop frequency -# the corner and stop freqs as fractions of the nyquist +# the scipy.signal routines accept corner an stop frequencies as a +# *fraction* of the nyquist ws = cornerfreq/Nyq wp = stopfreq/Nyq -# the order and butterworth natural frequency for use with butter +# call scipy.buttord to compute the order and natural frequency of the +# butterorth filter. See the help for signal.buttord. You will pass +# in ws and wp, as well as the attenuation in the pass and stop bands N, wn = signal.buttord(wp, ws, 3, 16) -# return the butterworth filter coeffs for the given order and frequency +# scipy.butter will take the output from buttord and return the +# lfilter coeefs for that filter b, a = signal.butter(N, wn) -# filter the data +# Now lfilter will filter the noisy sine with the filter parameters +# from butter sf = signal.lfilter(b, a, sn) +# plot the original, noisy and filtered sine, all on the same axes in +# pylab, and make a legend fig = figure() ax = fig.add_subplot(111) ax.plot(t, s, label='original signal') Added: trunk/py4science/examples/skel/butter_filter_skel.py =================================================================== --- trunk/py4science/examples/skel/butter_filter_skel.py (rev 0) +++ trunk/py4science/examples/skel/butter_filter_skel.py 2007-12-08 16:35:17 UTC (rev 4675) @@ -0,0 +1,46 @@ +import numpy as n +import scipy.signal as signal +from pylab import figure, show + +XXX = 0. # just so he XXX blanks will not crash +dt = 0.01 +t = n.arange(0, 2, dt) +s = XXX # a 1 Hz sine wave over t + +# sine corrupted wih gaussian white noise the sine wave s corrupted +# with gaussian white noise with sigma=0.1. See numpy.random.randn + +sn = XXX +# the nyquist frequency 1/(2dt) is the maximum frequency in a sampled +# signal +Nyq = XXX + +#the corner frequency represents a boundary in the system response at +#which energy entering the system begins to be attenuate, and the stop +#frequency is the frequency at which the signal is (practically) +#completely attenuated +cornerfreq = 2. # the corner frequency +stopfreq = 5. # the stop frequency + +# the scipy.signal routines accept corner an stop frequencies as a +# *fraction* of the nyquist +ws = XXX +wp = XXX + + +# call scipy.buttord to compute the order and natural frequency of the +# butterorth filter. See the help for signal.buttord. You will pass +# in ws and wp, as well as the attenuation in the pass and stop bands +N, wn = XXX, XXX # the output of signal.buttord + +# scipy.butter will take the output from buttord and return the +# lfilter coeefs for that filter. See help signal.butter +b, a = XXX, XXX # the output of signal.butter + +# Now lfilter will filter the noisy sine with the filter parameters +# from butter. See help signal.lfilter +sf = XXX # the filtered signal returned from lfi,ter + +# plot the original, noisy and filtered sine, all on the same axes in +# pylab, and make a legend +XXX This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <js...@us...> - 2008-05-30 20:26:10
|
Revision: 5337 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5337&view=rev Author: jswhit Date: 2008-05-30 13:25:57 -0700 (Fri, 30 May 2008) Log Message: ----------- convert to plt/np namespace, fix Basemap import for version 0.99 (mpl_toolkits) Modified Paths: -------------- trunk/py4science/examples/basemap1.py trunk/py4science/examples/basemap2.py trunk/py4science/examples/basemap3.py trunk/py4science/examples/basemap4.py trunk/py4science/examples/basemap5.py Modified: trunk/py4science/examples/basemap1.py =================================================================== --- trunk/py4science/examples/basemap1.py 2008-05-30 20:05:57 UTC (rev 5336) +++ trunk/py4science/examples/basemap1.py 2008-05-30 20:25:57 UTC (rev 5337) @@ -1,5 +1,5 @@ -import pylab, numpy -from matplotlib.toolkits.basemap import Basemap +from mpl_toolkits.basemap import Basemap +import matplotlib.pyplot as plt # create map by specifying lat/lon values at corners. resolution = 'l'; projection = 'lcc' lat_0 = 60; lon_0 = -50 @@ -18,5 +18,5 @@ # draw states and countries. m.drawcountries() m.drawstates() -pylab.title('map region specified using corner lat/lon values') -pylab.show() +plt.title('map region specified using corner lat/lon values') +plt.show() Modified: trunk/py4science/examples/basemap2.py =================================================================== --- trunk/py4science/examples/basemap2.py 2008-05-30 20:05:57 UTC (rev 5336) +++ trunk/py4science/examples/basemap2.py 2008-05-30 20:25:57 UTC (rev 5337) @@ -1,5 +1,5 @@ -import pylab, numpy -from matplotlib.toolkits.basemap import Basemap +from mpl_toolkits.basemap import Basemap +import matplotlib.pyplot as plt # create map by specifying width and height in km. resolution = 'l'; projection = 'lcc' lon_0 = -50; lat_0 = 60 @@ -12,5 +12,5 @@ m.fillcontinents(color='coral',lake_color='aqua') m.drawcountries() m.drawstates() -pylab.title('map region specified using width and height') -pylab.show() +plt.title('map region specified using width and height') +plt.show() Modified: trunk/py4science/examples/basemap3.py =================================================================== --- trunk/py4science/examples/basemap3.py 2008-05-30 20:05:57 UTC (rev 5336) +++ trunk/py4science/examples/basemap3.py 2008-05-30 20:25:57 UTC (rev 5337) @@ -1,5 +1,5 @@ -import pylab, numpy -from matplotlib.toolkits.basemap import Basemap +from mpl_toolkits.basemap import Basemap +import matplotlib.pyplot as plt # create map by specifying width and height in km. resolution = 'l'; projection = 'lcc' lon_0 = -50; lat_0 = 60 @@ -23,14 +23,14 @@ m.drawgreatcircle(nylon,nylat,lonlon,lonlat,linewidth=2,color='k') # put the names of the cities to the left of each dot, offset # by a little. Use a bold font. -pylab.text(ny_x-100000,ny_y+100000,'New York',fontsize=12,\ +plt.text(ny_x-100000,ny_y+100000,'New York',fontsize=12,\ color='k',horizontalalignment='right',fontweight='bold') -pylab.text(lon_x-100000,lon_y+100000,'London',fontsize=12,\ +plt.text(lon_x-100000,lon_y+100000,'London',fontsize=12,\ color='k',horizontalalignment='right',fontweight='bold') m.drawcoastlines(linewidth=0.5) m.drawmapboundary(fill_color='aqua') m.fillcontinents(color='coral',lake_color='aqua') m.drawcountries() m.drawstates() -pylab.title('NY to London Great Circle') -pylab.show() +plt.title('NY to London Great Circle') +plt.show() Modified: trunk/py4science/examples/basemap4.py =================================================================== --- trunk/py4science/examples/basemap4.py 2008-05-30 20:05:57 UTC (rev 5336) +++ trunk/py4science/examples/basemap4.py 2008-05-30 20:25:57 UTC (rev 5337) @@ -1,5 +1,6 @@ -import pylab, numpy -from matplotlib.toolkits.basemap import Basemap +from mpl_toolkits.basemap import Basemap +import matplotlib.pyplot as plt +import numpy as np # create map by specifying width and height in km. resolution = 'l' lon_0 = -50 @@ -16,9 +17,9 @@ m.drawstates() # label meridians where they intersect the left, right and bottom # of the plot frame. -m.drawmeridians(numpy.arange(-180,181,20),labels=[1,1,0,1]) +m.drawmeridians(np.arange(-180,181,20),labels=[1,1,0,1]) # label parallels where they intersect the left, right and top # of the plot frame. -m.drawparallels(numpy.arange(-80,81,20),labels=[1,1,1,0]) -pylab.title('labelled meridians and parallels',y=1.075) -pylab.show() +m.drawparallels(np.arange(-80,81,20),labels=[1,1,1,0]) +plt.title('labelled meridians and parallels',y=1.075) +plt.show() Modified: trunk/py4science/examples/basemap5.py =================================================================== --- trunk/py4science/examples/basemap5.py 2008-05-30 20:05:57 UTC (rev 5336) +++ trunk/py4science/examples/basemap5.py 2008-05-30 20:25:57 UTC (rev 5337) @@ -1,5 +1,6 @@ -from matplotlib.toolkits.basemap import Basemap, NetCDFFile -import pylab, numpy +from mpl_toolkits.basemap import Basemap, NetCDFFile +import matplotlib.pyplot as plt +import numpy as np # read in netCDF sea-surface temperature data # can be a local file, a URL for a remote opendap dataset, # or (if PyNIO is installed) a GRIB or HDF file. @@ -12,15 +13,15 @@ # continent processing (this speeds things up a bit) m = Basemap(projection='moll',lon_0=0,lat_0=0,resolution=None) # compute map projection coordinates of grid. -x, y = m(*numpy.meshgrid(lons, lats)) +x, y = m(*np.meshgrid(lons, lats)) # plot with pcolor -im = m.pcolormesh(x,y,sst,shading='flat',cmap=pylab.cm.gist_ncar) +im = m.pcolormesh(x,y,sst,shading='flat',cmap=plt.cm.gist_ncar) # draw parallels and meridians, but don't bother labelling them. -m.drawparallels(numpy.arange(-90.,120.,30.)) -m.drawmeridians(numpy.arange(0.,420.,60.)) +m.drawparallels(np.arange(-90.,120.,30.)) +m.drawmeridians(np.arange(0.,420.,60.)) # draw line around map projection limb. # color map region background black (missing values will be this color) m.drawmapboundary(fill_color='k') # draw horizontal colorbar. -pylab.colorbar(orientation='horizontal') -pylab.show() +plt.colorbar(orientation='horizontal') +plt.show() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2008-06-03 20:57:06
|
Revision: 5379 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5379&view=rev Author: jdh2358 Date: 2008-06-03 13:57:02 -0700 (Tue, 03 Jun 2008) Log Message: ----------- added sphinx template for doc unit Added Paths: ----------- trunk/py4science/examples/sphinx_template/ trunk/py4science/examples/sphinx_template/README.txt trunk/py4science/examples/sphinx_template/_static/ trunk/py4science/examples/sphinx_template/_templates/ trunk/py4science/examples/sphinx_template/build/ trunk/py4science/examples/sphinx_template/conf.py trunk/py4science/examples/sphinx_template/index.rst trunk/py4science/examples/sphinx_template/make.py trunk/py4science/examples/sphinx_template/model/ trunk/py4science/examples/sphinx_template/model/index.rst trunk/py4science/examples/sphinx_template/model/introduction.rst trunk/py4science/examples/sphinx_template/model/next_steps.rst trunk/py4science/examples/sphinx_template/model/sphinx_helpers.rst trunk/py4science/examples/sphinx_template/simulations/ trunk/py4science/examples/sphinx_template/simulations/code/ trunk/py4science/examples/sphinx_template/simulations/code/elegant.py trunk/py4science/examples/sphinx_template/simulations/code/hairy.py trunk/py4science/examples/sphinx_template/simulations/code/make.py trunk/py4science/examples/sphinx_template/simulations/finale.rst trunk/py4science/examples/sphinx_template/simulations/index.rst trunk/py4science/examples/sphinx_template/simulations/introduction.rst trunk/py4science/examples/sphinx_template/simulations/preliminary.rst Added: trunk/py4science/examples/sphinx_template/README.txt =================================================================== --- trunk/py4science/examples/sphinx_template/README.txt (rev 0) +++ trunk/py4science/examples/sphinx_template/README.txt 2008-06-03 20:57:02 UTC (rev 5379) @@ -0,0 +1,26 @@ +sphinx template sampledoc +========================= + +This is the top level build directory for the sphinx sampledoc +documentation. All of the documentation is written using sphinx, a +python documentation system built on top of ReST. This directory +contains + + +* model - A document describing a model + +* simulations - A document describing the simulations -- contains a + code subdir with python scripts and a make.py file to build them + into PNGs + +* make.py - the build script to build the html or PDF docs. Do + `python make.py html` or `python make.py latex` for PDF + +* index.rst - the top level include document for sampledocs document + +* conf.py - the sphinx configuration + +* _static - used by the sphinx build system + +* _templates - used by the sphinx build system + Added: trunk/py4science/examples/sphinx_template/conf.py =================================================================== --- trunk/py4science/examples/sphinx_template/conf.py (rev 0) +++ trunk/py4science/examples/sphinx_template/conf.py 2008-06-03 20:57:02 UTC (rev 5379) @@ -0,0 +1,161 @@ +# -*- coding: utf-8 -*- +# +# sampledoc documentation build configuration file, created by +# sphinx-quickstart on Tue Jun 3 12:40:24 2008. +# +# This file is execfile()d with the current directory set to its containing dir. +# +# The contents of this file are pickled, so don't put values in the namespace +# that aren't pickleable (module imports are okay, they're removed automatically). +# +# All configuration values have a default value; values that are commented out +# serve to show the default value. + +import sys, os + +# If your extensions are in another directory, add it here. If the directory +# is relative to the documentation root, use os.path.abspath to make it +# absolute, like shown here. +#sys.path.append(os.path.abspath('some/directory')) + +# General configuration +# --------------------- + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +#extensions = [] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The master toctree document. +master_doc = 'index' + +# General substitutions. +project = 'sampledoc' +copyright = '2008, John D. Hunter, Cast of Thousands' + +# The default replacements for |version| and |release|, also used in various +# other places throughout the built documents. +# +# The short X.Y version. +version = '0.1' +# The full version, including alpha/beta/rc tags. +release = '0.1' + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +today_fmt = '%B %d, %Y' + +# List of documents that shouldn't be included in the build. +#unused_docs = [] + +# List of directories, relative to source directories, that shouldn't be searched +# for source files. +#exclude_dirs = [] + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + + +# Options for HTML output +# ----------------------- + +# The style sheet to use for HTML and HTML Help pages. A file of that name +# must exist either in Sphinx' static/ path, or in one of the custom paths +# given in html_static_path. +html_style = 'default.css' + +# The name for this set of Sphinx documents. If None, it defaults to +# "<project> v<release> documentation". +#html_title = None + +# The name of an image file (within the static path) to place at the top of +# the sidebar. +#html_logo = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_use_modindex = True + +# If true, the reST sources are included in the HTML build as _sources/<name>. +#html_copy_source = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a <link> tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = '' + +# Output file base name for HTML help builder. +htmlhelp_basename = 'sampledoc' + + +# Options for LaTeX output +# ------------------------ + +# The paper size ('letter' or 'a4'). +#latex_paper_size = 'letter' + +# The font size ('10pt', '11pt' or '12pt'). +#latex_font_size = '10pt' + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, document class [howto/manual]). +latex_documents = [ + ('index', 'sampledoc.tex', 'sampledoc Documentation', 'John D. Hunter, Cast of Thousands', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# Additional stuff for the LaTeX preamble. +#latex_preamble = '' + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_use_modindex = True Added: trunk/py4science/examples/sphinx_template/index.rst =================================================================== --- trunk/py4science/examples/sphinx_template/index.rst (rev 0) +++ trunk/py4science/examples/sphinx_template/index.rst 2008-06-03 20:57:02 UTC (rev 5379) @@ -0,0 +1,23 @@ +.. sampledoc documentation master file, created by sphinx-quickstart on Tue Jun 3 12:40:24 2008. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to sampledoc's documentation! +===================================== + +Contents: + +.. toctree:: + :maxdepth: 2 + + model/index.rst + simulations/index.rst + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` + Added: trunk/py4science/examples/sphinx_template/make.py =================================================================== --- trunk/py4science/examples/sphinx_template/make.py (rev 0) +++ trunk/py4science/examples/sphinx_template/make.py 2008-06-03 20:57:02 UTC (rev 5379) @@ -0,0 +1,71 @@ +#!/usr/bin/env python +import fileinput +import glob +import os +import shutil +import sys + +def check_build(): + build_dirs = ['build', 'build/doctrees', 'build/html', 'build/latex', + '_static', '_templates'] + for d in build_dirs: + try: + os.mkdir(d) + except OSError: + pass + +def figs(): + os.system('cd simulations/code/ && python make.py') + +def html(): + check_build() + figs() + os.system('sphinx-build -b html -d build/doctrees . build/html') + +def latex(): + check_build() + figs() + if sys.platform != 'win32': + # LaTeX format. + os.system('sphinx-build -b latex -d build/doctrees . build/latex') + + # Produce pdf. + os.chdir('build/latex') + + # Copying the makefile produced by sphinx... + os.system('pdflatex sampledoc.tex') + os.system('pdflatex sampledoc.tex') + os.system('makeindex -s python.ist sampledoc.idx') + os.system('makeindex -s python.ist modsampledoc.idx') + os.system('pdflatex sampledoc.tex') + + os.chdir('../..') + else: + print 'latex build has not been tested on windows' + +def clean(): + shutil.rmtree('build') + +def all(): + figs() + html() + latex() + + +funcd = {'figs':figs, + 'html':html, + 'latex':latex, + 'clean':clean, + 'all':all, + } + + +if len(sys.argv)>1: + for arg in sys.argv[1:]: + func = funcd.get(arg) + if func is None: + raise SystemExit('Do not know how to handle %s; valid args are'%( + arg, funcd.keys())) + func() +else: + all() Added: trunk/py4science/examples/sphinx_template/model/index.rst =================================================================== --- trunk/py4science/examples/sphinx_template/model/index.rst (rev 0) +++ trunk/py4science/examples/sphinx_template/model/index.rst 2008-06-03 20:57:02 UTC (rev 5379) @@ -0,0 +1,14 @@ +.. _model-index: + +############## +My Fancy Model +############## + +:Release: |version| +:Date: |today| + +.. toctree:: + + introduction.rst + next_steps.rst + sphinx_helpers.rst Added: trunk/py4science/examples/sphinx_template/model/introduction.rst =================================================================== --- trunk/py4science/examples/sphinx_template/model/introduction.rst (rev 0) +++ trunk/py4science/examples/sphinx_template/model/introduction.rst 2008-06-03 20:57:02 UTC (rev 5379) @@ -0,0 +1,23 @@ +.. _model-introduction: + +****************** +Model Introduction +****************** + +Wherein I describe my fancy model + +.. _other-models: + +Other Models +============ + +Where in I describe + +* model A + +* model B + +* model C + +and why they all suck + Added: trunk/py4science/examples/sphinx_template/model/next_steps.rst =================================================================== --- trunk/py4science/examples/sphinx_template/model/next_steps.rst (rev 0) +++ trunk/py4science/examples/sphinx_template/model/next_steps.rst 2008-06-03 20:57:02 UTC (rev 5379) @@ -0,0 +1,8 @@ +.. _next-steps: + +********** +Next steps +********** + +Wherein I describe my next steps + Added: trunk/py4science/examples/sphinx_template/model/sphinx_helpers.rst =================================================================== --- trunk/py4science/examples/sphinx_template/model/sphinx_helpers.rst (rev 0) +++ trunk/py4science/examples/sphinx_template/model/sphinx_helpers.rst 2008-06-03 20:57:02 UTC (rev 5379) @@ -0,0 +1,127 @@ +.. _sphinx_helpers: + +****************** +Sphinx Cheat Sheet +****************** + +Wherein I show by example how to do some things in Sphinx (you can see +a literal version of this file below in :ref:`sphinx-literal`) + + +.. _making-a-list: + +Making a list +============= + +It is easy to make lists in rest + +Bullet points +------------- + +This is a subsection making bullet points + +* point A + +* point B + +* point C + + +Enumerated points +------------------ + +This is a subsection making numbered points + +#. point A + +#. point B + +#. point C + + +.. _making-a-table: + +Making a table +============== + +This shows you how to make a table -- if you only want to make a list see :ref:`making-a-list`. + +================== ============ +Name Age +================== ============ +John D Hunter 40 +Cast of Thousands 41 +And Still More 42 +================== ============ + +.. _making-links: + +Making links +============ + +It is easy to make a link to `yahoo <http://yahoo.com>`_ or to some +section inside this document (see :ref:`making-a-table`) or another +document (see :ref:`final-results`). + +.. _formatting-text: + +Formatting text +=============== + +You use inline markup to make text *italics*, **bold**, or ``monotype``. + +You can represent code blocks fairly easily:: + + import numpy as np + x = np.random.rand(12) + +Or literally include code: + +.. literalinclude:: ../simulations/code/elegant.py + + +.. _emacs-helpers: + +Emacs helpers +============= + +There is an emacs mode `rst.el +<http://docutils.sourceforge.net/tools/editors/emacs/rst.el>`_ which +automates many important ReST tasks like building and updateing +table-of-contents, and promoting or demoting section headings. Here +is the basic ``.emacs`` configuration:: + + (require 'rst) + (setq auto-mode-alist + (append '(("\\.txt$" . rst-mode) + ("\\.rst$" . rst-mode) + ("\\.rest$" . rst-mode)) auto-mode-alist)) + + +Some helpful functions:: + + C-c TAB - rst-toc-insert + + Insert table of contents at point + + C-c C-u - rst-toc-update + + Update the table of contents at point + + C-c C-l rst-shift-region-left + + Shift region to the left + + C-c C-r rst-shift-region-right + + Shift region to the right + + +.. _sphinx-literal: + +This file +========= + +.. literalinclude:: sphinx_helpers.rst + + Added: trunk/py4science/examples/sphinx_template/simulations/code/elegant.py =================================================================== --- trunk/py4science/examples/sphinx_template/simulations/code/elegant.py (rev 0) +++ trunk/py4science/examples/sphinx_template/simulations/code/elegant.py 2008-06-03 20:57:02 UTC (rev 5379) @@ -0,0 +1,4 @@ +import matplotlib.pyplot as plt +plt.plot([1,2,3], [4,5,6]) +plt.ylabel('some more numbers') + Added: trunk/py4science/examples/sphinx_template/simulations/code/hairy.py =================================================================== --- trunk/py4science/examples/sphinx_template/simulations/code/hairy.py (rev 0) +++ trunk/py4science/examples/sphinx_template/simulations/code/hairy.py 2008-06-03 20:57:02 UTC (rev 5379) @@ -0,0 +1,4 @@ +import matplotlib.pyplot as plt +plt.plot([1,2,3]) +plt.ylabel('some numbers') + Added: trunk/py4science/examples/sphinx_template/simulations/code/make.py =================================================================== --- trunk/py4science/examples/sphinx_template/simulations/code/make.py (rev 0) +++ trunk/py4science/examples/sphinx_template/simulations/code/make.py 2008-06-03 20:57:02 UTC (rev 5379) @@ -0,0 +1,58 @@ +#!/usr/bin/env python +import sys, os, glob +import matplotlib +import IPython.Shell +matplotlib.rcdefaults() +matplotlib.use('Agg') + +mplshell = IPython.Shell.MatplotlibShell('mpl') + +def figs(): + print 'making figs' + import matplotlib.pyplot as plt + for fname in glob.glob('*.py'): + if fname==__file__: continue + basename, ext = os.path.splitext(fname) + outfile = '%s.png'%basename + + if os.path.exists(outfile): + print ' already have %s'%outfile + continue + else: + print ' building %s'%fname + plt.close('all') # we need to clear between runs + mplshell.magic_run(basename) + plt.savefig('%s.png'%basename) + print 'all figures made' + + +def clean(): + patterns = ['#*', '*~', '*.png', '*pyc'] + for pattern in patterns: + for fname in glob.glob(pattern): + os.remove(fname) + print 'all clean' + + + +def all(): + figs() + +funcd = {'figs':figs, + 'clean':clean, + 'all':all, + } + +if len(sys.argv)>1: + for arg in sys.argv[1:]: + func = funcd.get(arg) + if func is None: + raise SystemExit('Do not know how to handle %s; valid args are'%( + arg, funcd.keys())) + func() +else: + all() + + + + Added: trunk/py4science/examples/sphinx_template/simulations/finale.rst =================================================================== --- trunk/py4science/examples/sphinx_template/simulations/finale.rst (rev 0) +++ trunk/py4science/examples/sphinx_template/simulations/finale.rst 2008-06-03 20:57:02 UTC (rev 5379) @@ -0,0 +1,17 @@ +.. _final-results: + +************* +Final Results +************* + + +After much head scratching, I wrote this big elegant piece of code + +.. literalinclude:: code/elegant.py + +which produced this elegant figure + +.. image:: code/elegant.png + :scale: 50 + + Added: trunk/py4science/examples/sphinx_template/simulations/index.rst =================================================================== --- trunk/py4science/examples/sphinx_template/simulations/index.rst (rev 0) +++ trunk/py4science/examples/sphinx_template/simulations/index.rst 2008-06-03 20:57:02 UTC (rev 5379) @@ -0,0 +1,15 @@ +.. _simulations-index: + +######################### +My Stupendous Simulations +######################### + +:Release: |version| +:Date: |today| + +.. toctree:: + + introduction.rst + preliminary.rst + finale.rst + Added: trunk/py4science/examples/sphinx_template/simulations/introduction.rst =================================================================== --- trunk/py4science/examples/sphinx_template/simulations/introduction.rst (rev 0) +++ trunk/py4science/examples/sphinx_template/simulations/introduction.rst 2008-06-03 20:57:02 UTC (rev 5379) @@ -0,0 +1,24 @@ +.. _simulations-introduction: + +******************** +Simulations overview +******************** + +Wherein I describe my fancy code and libraries to implement my fancy model (:ref:`model-introduction`) + +.. _python-libraries: + +The python libraries +==================== + +Why `matplotlib <http://matplotlib.sf.net>`_ rules + +.. _data-sources: + +The data sources +==================== + +Now how much would you pay? + + + Added: trunk/py4science/examples/sphinx_template/simulations/preliminary.rst =================================================================== --- trunk/py4science/examples/sphinx_template/simulations/preliminary.rst (rev 0) +++ trunk/py4science/examples/sphinx_template/simulations/preliminary.rst 2008-06-03 20:57:02 UTC (rev 5379) @@ -0,0 +1,17 @@ +.. _preliminary-tests: + +***************** +Preliminary tests +***************** + +I wrote this big hairy piece of code + +.. literalinclude:: code/hairy.py + + +which produced this lovely figure + +.. image:: code/hairy.png + :scale: 50 + + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |