You can subscribe to this list here.
2007 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
(115) |
Aug
(120) |
Sep
(137) |
Oct
(170) |
Nov
(461) |
Dec
(263) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2008 |
Jan
(120) |
Feb
(74) |
Mar
(35) |
Apr
(74) |
May
(245) |
Jun
(356) |
Jul
(240) |
Aug
(115) |
Sep
(78) |
Oct
(225) |
Nov
(98) |
Dec
(271) |
2009 |
Jan
(132) |
Feb
(84) |
Mar
(74) |
Apr
(56) |
May
(90) |
Jun
(79) |
Jul
(83) |
Aug
(296) |
Sep
(214) |
Oct
(76) |
Nov
(82) |
Dec
(66) |
2010 |
Jan
(46) |
Feb
(58) |
Mar
(51) |
Apr
(77) |
May
(58) |
Jun
(126) |
Jul
(128) |
Aug
(64) |
Sep
(50) |
Oct
(44) |
Nov
(48) |
Dec
(54) |
2011 |
Jan
(68) |
Feb
(52) |
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(1) |
2018 |
Jan
|
Feb
|
Mar
|
Apr
|
May
(1) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
S | M | T | W | T | F | S |
---|---|---|---|---|---|---|
|
|
|
|
|
|
1
(4) |
2
(9) |
3
(23) |
4
(34) |
5
(31) |
6
(25) |
7
(10) |
8
(7) |
9
(1) |
10
(18) |
11
(3) |
12
(18) |
13
(13) |
14
(6) |
15
(9) |
16
(6) |
17
(10) |
18
(12) |
19
(1) |
20
(8) |
21
(5) |
22
|
23
|
24
|
25
|
26
(4) |
27
(2) |
28
(4) |
29
|
30
|
31
|
|
|
|
|
|
Revision: 4572 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4572&view=rev Author: jdh2358 Date: 2007年12月03日 19:18:39 -0800 (2007年12月03日) Log Message: ----------- colormapped histogram Added Paths: ----------- trunk/matplotlib/examples/hist_colormapped.py Added: trunk/matplotlib/examples/hist_colormapped.py =================================================================== --- trunk/matplotlib/examples/hist_colormapped.py (rev 0) +++ trunk/matplotlib/examples/hist_colormapped.py 2007年12月04日 03:18:39 UTC (rev 4572) @@ -0,0 +1,24 @@ +import numpy as n +from pylab import figure, show +import matplotlib.cm as cm +import matplotlib.colors as colors + +fig = figure() +ax = fig.add_subplot(111) +Ntotal = 1000 +N, bins, patches = ax.hist(n.random.rand(Ntotal), 20) + +#I'll color code by height, but you could use any scalar + + +# we need to normalize the data to 0..1 for the full +# range of the colormap +fracs = N.astype(float)/N.max() +norm = colors.normalize(fracs.min(), fracs.max()) + +for thisfrac, thispatch in zip(fracs, patches): + color = cm.jet(norm(thisfrac)) + thispatch.set_facecolor(color) + + +show() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 4571 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4571&view=rev Author: jdh2358 Date: 2007年12月03日 18:06:52 -0800 (2007年12月03日) Log Message: ----------- applied barrys cocoaagg patch Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/backends/backend_cocoaagg.py Modified: trunk/matplotlib/lib/matplotlib/backends/backend_cocoaagg.py =================================================================== --- trunk/matplotlib/lib/matplotlib/backends/backend_cocoaagg.py 2007年12月03日 22:32:28 UTC (rev 4570) +++ trunk/matplotlib/lib/matplotlib/backends/backend_cocoaagg.py 2007年12月04日 02:06:52 UTC (rev 4571) @@ -78,8 +78,8 @@ self.plotWindow.setDelegate_(self)#.plotView) self.plotView.setImageFrameStyle_(NSImageFrameGroove) - self.plotView.image = NSImage.alloc().initWithSize_((0,0)) - self.plotView.setImage_(self.plotView.image) + self.plotView.image_ = NSImage.alloc().initWithSize_((0,0)) + self.plotView.setImage_(self.plotView.image_) # Make imageview first responder for key events self.plotWindow.makeFirstResponder_(self.plotView) @@ -112,10 +112,10 @@ w,h = self.canvas.get_width_height() # Remove all previous images - for i in xrange(self.image.representations().count()): - self.image.removeRepresentation_(self.image.representations().objectAtIndex_(i)) + for i in xrange(self.image_.representations().count()): + self.image_.removeRepresentation_(self.image_.representations().objectAtIndex_(i)) - self.image.setSize_((w,h)) + self.image_.setSize_((w,h)) brep = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_( (self.canvas.buffer_rgba(0,0),'','','',''), # Image data @@ -129,7 +129,7 @@ w*4, # row bytes 32) # bits per pixel - self.image.addRepresentation_(brep) + self.image_.addRepresentation_(brep) self.setNeedsDisplay_(True) def windowDidResize_(self, sender): This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 4570 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4570&view=rev Author: jswhit Date: 2007年12月03日 14:32:28 -0800 (2007年12月03日) Log Message: ----------- add default for altitude of geostationary orbit in 'geos' projection. Modified Paths: -------------- trunk/toolkits/basemap/examples/geos_demo.py trunk/toolkits/basemap/lib/matplotlib/toolkits/basemap/basemap.py Modified: trunk/toolkits/basemap/examples/geos_demo.py =================================================================== --- trunk/toolkits/basemap/examples/geos_demo.py 2007年12月03日 19:16:17 UTC (rev 4569) +++ trunk/toolkits/basemap/examples/geos_demo.py 2007年12月03日 22:32:28 UTC (rev 4570) @@ -3,12 +3,10 @@ # create Basemap instance for Geostationary (satellite view) projection. lon_0 = float(raw_input('enter reference longitude (lon_0):')) -#h = float(raw_input('enter satellite height above equator in meters (satellite_height):')) -h = 35785831.0 # map with land/sea mask plotted fig=figure() -m = Basemap(projection='geos',lon_0=lon_0,satellite_height=h,rsphere=(6378137.00,6356752.3142),resolution=None) +m = Basemap(projection='geos',lon_0=lon_0,rsphere=(6378137.00,6356752.3142),resolution=None) # plot land-sea mask. rgba_land = (0,255,0,255) # land green. rgba_ocean = (0,0,255,255) # ocean blue. @@ -18,11 +16,11 @@ m.drawparallels(arange(-90.,120.,30.)) m.drawmeridians(arange(0.,420.,60.)) m.drawmapboundary() -title('Geostationary Map Centered on Lon=%s, Satellite Height=%s' % (lon_0,h)) +title('Geostationary Map Centered on Lon=%s' % (lon_0)) # map with continents drawn and filled. fig = figure() -m = Basemap(projection='geos',lon_0=lon_0,satellite_height=h,rsphere=(6378137.00,6356752.3142),resolution='l') +m = Basemap(projection='geos',lon_0=lon_0,rsphere=(6378137.00,6356752.3142),resolution='l') m.drawcoastlines() m.drawmapboundary(fill_color='aqua') m.fillcontinents(color='coral',lake_color='aqua') @@ -31,5 +29,5 @@ m.drawparallels(arange(-90.,120.,30.)) m.drawmeridians(arange(0.,420.,60.)) m.drawmapboundary() -title('Geostationary Map Centered on Lon=%s, Satellite Height=%s' % (lon_0,h)) +title('Geostationary Map Centered on Lon=%s' % (lon_0)) show() Modified: trunk/toolkits/basemap/lib/matplotlib/toolkits/basemap/basemap.py =================================================================== --- trunk/toolkits/basemap/lib/matplotlib/toolkits/basemap/basemap.py 2007年12月03日 19:16:17 UTC (rev 4569) +++ trunk/toolkits/basemap/lib/matplotlib/toolkits/basemap/basemap.py 2007年12月03日 22:32:28 UTC (rev 4570) @@ -212,7 +212,7 @@ on the north or south pole. The longitude lon_0 is at 6-o'clock, and the latitude circle boundinglat is tangent to the edge of the map at lon_0. satellite_height - height of satellite (in m) above equator - - only relevant for geostationary projections ('geos'). + only relevant for geostationary projections ('geos'). Default 35,786 km. Here are the most commonly used class methods (see the docstring for each for more details): @@ -324,7 +324,7 @@ lat_0=None, lon_0=None, lon_1=None, lon_2=None, suppress_ticks=True, - satellite_height=None, + satellite_height=35786000, boundinglat=None, anchor='C', ax=None): @@ -362,7 +362,7 @@ _insert_validated(projparams, lon_0, 'lon_0', -360, 720) _insert_validated(projparams, lon_1, 'lon_1', -360, 720) _insert_validated(projparams, lon_2, 'lon_2', -360, 720) - if satellite_height is not None: + if projection == 'geos': projparams['h'] = satellite_height # check for sane values of projection corners. using_corners = (None not in [llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat]) @@ -488,8 +488,8 @@ if npy.abs(lat_0) < 1.e-2: lat_0 = 1.e-2 projparams['lat_0'] = lat_0 elif projection == 'geos': - if lon_0 is None and satellite_height is None: - raise ValueError, 'must specify lon_0 and satellite_height for Geostationary basemap' + if lon_0 is None: + raise ValueError, 'must specify lon_0 for Geostationary basemap' if width is not None or height is not None: print 'warning: width and height keywords ignored for %s projection' % self.projection if not using_corners: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 4569 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4569&view=rev Author: mdboom Date: 2007年12月03日 11:16:17 -0800 (2007年12月03日) Log Message: ----------- Fix exception when a particular contour doesn't exist. Modified Paths: -------------- branches/transforms/lib/matplotlib/axes.py Modified: branches/transforms/lib/matplotlib/axes.py =================================================================== --- branches/transforms/lib/matplotlib/axes.py 2007年12月03日 19:07:36 UTC (rev 4568) +++ branches/transforms/lib/matplotlib/axes.py 2007年12月03日 19:16:17 UTC (rev 4569) @@ -1137,7 +1137,8 @@ self._set_artist_props(collection) collection.set_clip_path(self.axesPatch) if autolim: - self.update_datalim(collection.get_datalim(self.transData)) + if len(collection._paths): + self.update_datalim(collection.get_datalim(self.transData)) collection._remove_method = lambda h: self.collections.remove(h) def add_line(self, line): This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 4568 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4568&view=rev Author: mdboom Date: 2007年12月03日 11:07:36 -0800 (2007年12月03日) Log Message: ----------- Fix image interpolation edges for Agg 2.4. It no longer needs funny workarounds with memory copies to interpolate the edges of the image correctly. Modified Paths: -------------- branches/transforms/lib/matplotlib/image.py branches/transforms/src/_image.cpp Modified: branches/transforms/lib/matplotlib/image.py =================================================================== --- branches/transforms/lib/matplotlib/image.py 2007年12月03日 17:30:46 UTC (rev 4567) +++ branches/transforms/lib/matplotlib/image.py 2007年12月03日 19:07:36 UTC (rev 4568) @@ -156,9 +156,6 @@ sx = dxintv/self.axes.viewLim.width sy = dyintv/self.axes.viewLim.height - if im.get_interpolation()!=_image.NEAREST: - im.apply_translation(-1, -1) - # the viewport translation tx = (xmin-self.axes.viewLim.x0)/dxintv * numcols ty = (ymin-self.axes.viewLim.y0)/dyintv * numrows @@ -382,7 +379,7 @@ if s != None and s != 'nearest': raise NotImplementedError('Only nearest neighbor supported') AxesImage.set_interpolation(self, s) - + def get_extent(self): if self._A is None: raise RuntimeError('Must set data first') Modified: branches/transforms/src/_image.cpp =================================================================== --- branches/transforms/src/_image.cpp 2007年12月03日 17:30:46 UTC (rev 4567) +++ branches/transforms/src/_image.cpp 2007年12月03日 19:07:36 UTC (rev 4568) @@ -379,57 +379,11 @@ double x0, y0, x1, y1; - if (interpolation==NEAREST) { - x0 = 0.0; - x1 = colsIn; - y0 = 0.0; - y1 = rowsIn; - } - else { - // if interpolation != nearest, create a new input buffer with the - // edges mirrored on all size. Then new buffer size is colsIn+2 by - // rowsIn+2 + x0 = 0.0; + x1 = colsIn; + y0 = 0.0; + y1 = rowsIn; - x0 = 1.0; - x1 = colsIn+1; - y0 = 1.0; - y1 = rowsIn+1; - - - bufferPad = new agg::int8u[(rowsIn+2) * (colsIn+2) * BPP]; - if (bufferPad ==NULL) - throw Py::MemoryError("Image::resize could not allocate memory"); - rbufPad.attach(bufferPad, colsIn+2, rowsIn+2, (colsIn+2) * BPP); - - pixfmt pixfpad(rbufPad); - renderer_base rbpad(pixfpad); - - pixfmt pixfin(*rbufIn); - renderer_base rbin(pixfin); - - rbpad.copy_from(*rbufIn, 0, 1, 1); - - agg::rect_base<int> firstrow(0, 0, colsIn-1, 0); - rbpad.copy_from(*rbufIn, &firstrow, 1, 0); - - agg::rect_base<int> lastrow(0, rowsIn-1, colsIn-1, rowsIn-1); - rbpad.copy_from(*rbufIn, &lastrow, 1, 2); - - agg::rect_base<int> firstcol(0, 0, 0, rowsIn-1); - rbpad.copy_from(*rbufIn, &firstcol, 0, 1); - - agg::rect_base<int> lastcol(colsIn-1, 0, colsIn-1, rowsIn-1); - rbpad.copy_from(*rbufIn, &lastcol, 2, 1); - - rbpad.copy_pixel(0, 0, rbin.pixel(0,0) ); - rbpad.copy_pixel(0, colsIn+1, rbin.pixel(0,colsIn-1) ); - rbpad.copy_pixel(rowsIn+1, 0, rbin.pixel(rowsIn-1,0) ); - rbpad.copy_pixel(rowsIn+1, colsIn+1, rbin.pixel(rowsIn-1,colsIn-1) ); - - - } - - path.move_to(x0, y0); path.line_to(x1, y0); path.line_to(x1, y1); @@ -439,7 +393,7 @@ ras.add_path(imageBox); typedef agg::image_accessor_clip<pixfmt> img_accessor_type; - + pixfmt pixfmtin(*rbufIn); img_accessor_type ia(pixfmtin, background); switch(interpolation) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 4567 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4567&view=rev Author: jswhit Date: 2007年12月03日 09:30:46 -0800 (2007年12月03日) 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.
Revision: 4566 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4566&view=rev Author: mdboom Date: 2007年12月03日 09:15:06 -0800 (2007年12月03日) Log Message: ----------- Use non-equal dimensions for mesh to highlight bug in pcolormesh (if it ever returns). Modified Paths: -------------- branches/transforms/examples/quadmesh_demo.py Modified: branches/transforms/examples/quadmesh_demo.py =================================================================== --- branches/transforms/examples/quadmesh_demo.py 2007年12月03日 17:14:20 UTC (rev 4565) +++ branches/transforms/examples/quadmesh_demo.py 2007年12月03日 17:15:06 UTC (rev 4566) @@ -13,7 +13,8 @@ n = 56 x = npy.linspace(-1.5,1.5,n) -X,Y = npy.meshgrid(x,x); +y = npy.linspace(-1.5,1.5,n*2) +X,Y = npy.meshgrid(x,y); Qx = npy.cos(Y) - npy.cos(X) Qz = npy.sin(Y) + npy.sin(X) Qx = (Qx + 1.1) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 4565 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4565&view=rev Author: mdboom Date: 2007年12月03日 09:14:20 -0800 (2007年12月03日) Log Message: ----------- Fix bug in pcolormesh. Modified Paths: -------------- branches/transforms/src/_backend_agg.cpp Modified: branches/transforms/src/_backend_agg.cpp =================================================================== --- branches/transforms/src/_backend_agg.cpp 2007年12月03日 16:08:12 UTC (rev 4564) +++ branches/transforms/src/_backend_agg.cpp 2007年12月03日 17:14:20 UTC (rev 4565) @@ -1145,7 +1145,7 @@ inline unsigned vertex(unsigned idx, double* x, double* y) { size_t m = (idx & 0x2) ? (m_m + 1) : m_m; size_t n = (idx+1 & 0x2) ? (m_n + 1) : m_n; - double* pair = (double*)PyArray_GETPTR2(m_coordinates, m, n); + double* pair = (double*)PyArray_GETPTR2(m_coordinates, n, m); *x = *pair++; *y = *pair; return (idx) ? agg::path_cmd_line_to : agg::path_cmd_move_to; @@ -1172,7 +1172,7 @@ inline QuadMeshGenerator(size_t meshWidth, size_t meshHeight, const Py::Object& coordinates) : m_meshWidth(meshWidth), m_meshHeight(meshHeight), m_coordinates(NULL) { - PyArrayObject* coordinates_array = (PyArrayObject*)PyArray_FromObject(coordinates.ptr(), PyArray_DOUBLE, 1, 3); + PyArrayObject* coordinates_array = (PyArrayObject*)PyArray_FromObject(coordinates.ptr(), PyArray_DOUBLE, 3, 3); if (!coordinates_array) { throw Py::ValueError("Invalid coordinates array."); } @@ -1189,7 +1189,7 @@ } inline path_iterator operator()(size_t i) const { - return QuadMeshPathIterator(i % m_meshHeight, i / m_meshHeight, m_coordinates); + return QuadMeshPathIterator(i % m_meshWidth, i / m_meshWidth, m_coordinates); } }; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 4564 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4564&view=rev Author: jswhit Date: 2007年12月03日 08:08:12 -0800 (2007年12月03日) Log Message: ----------- include OPenDAP URL Modified Paths: -------------- trunk/py4science/examples/skel/basemap5_skel.py Modified: trunk/py4science/examples/skel/basemap5_skel.py =================================================================== --- trunk/py4science/examples/skel/basemap5_skel.py 2007年12月03日 15:49:35 UTC (rev 4563) +++ trunk/py4science/examples/skel/basemap5_skel.py 2007年12月03日 16:08:12 UTC (rev 4564) @@ -5,10 +5,12 @@ # 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') -# this will produce a very similar plot, but will read +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. #ncfile = NetCDFFile('http://nomads.ncdc.noaa.gov:8085/thredds/dodsC/oisst/2007/AVHRR/sst4-navy-eot.20071201.nc') -sst = ncfile.variables['analysed_sst'][:] +#sst = ncfile.variables['sst'][:] lats = ncfile.variables['lat'][:] lons = ncfile.variables['lon'][:] # Basemap comes with extra colormaps from Generic Mapping Tools @@ -18,7 +20,7 @@ projection = XX # try moll, robin, sinu or ortho. # coastlines not used, so resolution set to None to skip # continent processing (this speeds things up a bit) -m = Basemap(projection=projection,lon_0=0,lat_0=0,resolution=None) +m = Basemap(projection=projection,lon_0=lons.mean(),lat_0=0,resolution=None) # compute map projection coordinates of grid. x, y = m(*numpy.meshgrid(lons, lats)) # plot with pcolor This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 4563 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4563&view=rev Author: jswhit Date: 2007年12月03日 07:49:35 -0800 (2007年12月03日) Log Message: ----------- add an OPenDAP example URL Modified Paths: -------------- trunk/py4science/examples/skel/basemap5_skel.py Modified: trunk/py4science/examples/skel/basemap5_skel.py =================================================================== --- trunk/py4science/examples/skel/basemap5_skel.py 2007年12月03日 15:27:33 UTC (rev 4562) +++ trunk/py4science/examples/skel/basemap5_skel.py 2007年12月03日 15:49:35 UTC (rev 4563) @@ -5,6 +5,9 @@ # 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') +# this 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['analysed_sst'][:] lats = ncfile.variables['lat'][:] lons = ncfile.variables['lon'][:] This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 4562 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4562&view=rev Author: mdboom Date: 2007年12月03日 07:27:33 -0800 (2007年12月03日) Log Message: ----------- Merged revisions 4506-4561 via svnmerge from http://matplotlib.svn.sf.net/svnroot/matplotlib/trunk/matplotlib ........ r4507 | jdh2358 | 2007年11月29日 15:16:48 -0500 (2007年11月29日) | 2 lines Applied Ludwigs build tkagg w/o x11 server patch ........ r4509 | jdh2358 | 2007年11月29日 17:19:26 -0500 (2007年11月29日) | 2 lines commited ludwigs axes3d patch ........ r4512 | cmoad | 2007年11月29日 21:40:30 -0500 (2007年11月29日) | 1 line minor rev bump ........ r4513 | cmoad | 2007年11月29日 21:41:01 -0500 (2007年11月29日) | 1 line minor rev bump ........ r4514 | cmoad | 2007年11月29日 21:47:06 -0500 (2007年11月29日) | 1 line minor rev bump ........ r4515 | cmoad | 2007年11月29日 22:42:35 -0500 (2007年11月29日) | 1 line CXX/WrapPython.h missing from MANIFEST ........ r4516 | cmoad | 2007年11月29日 23:00:16 -0500 (2007年11月29日) | 1 line ttconv missing from MANFEST ........ r4517 | cmoad | 2007年11月29日 23:09:48 -0500 (2007年11月29日) | 1 line added setup.cfg.template ........ r4532 | mdboom | 2007年11月30日 14:48:41 -0500 (2007年11月30日) | 2 lines Fix mathtext in example. ........ r4537 | astraw | 2007年12月01日 15:12:05 -0500 (2007年12月01日) | 2 lines Fix loading of AAPL data in get_two_stock_data() ........ r4557 | mdboom | 2007年12月03日 08:20:19 -0500 (2007年12月03日) | 2 lines Fix missing font file error. ........ r4560 | jdh2358 | 2007年12月03日 10:23:32 -0500 (2007年12月03日) | 2 lines fixed a gtk import else block in mlab ........ r4561 | mdboom | 2007年12月03日 10:23:47 -0500 (2007年12月03日) | 3 lines Remove paragraph about MATPLOTLIBDATA environment variable, since it doesn't really apply anymore. ........ Modified Paths: -------------- branches/transforms/API_CHANGES branches/transforms/CHANGELOG branches/transforms/CODING_GUIDE branches/transforms/INSTALL branches/transforms/MANIFEST.in branches/transforms/examples/data_helper.py branches/transforms/examples/loadrec.py branches/transforms/examples/text_themes.py branches/transforms/lib/matplotlib/__init__.py branches/transforms/lib/matplotlib/axes3d.py branches/transforms/lib/matplotlib/mathtext.py branches/transforms/setupext.py Property Changed: ---------------- branches/transforms/ Property changes on: branches/transforms ___________________________________________________________________ Name: svnmerge-integrated - /trunk/matplotlib:1-4505 + /trunk/matplotlib:1-4561 Modified: branches/transforms/API_CHANGES =================================================================== --- branches/transforms/API_CHANGES 2007年12月03日 15:23:47 UTC (rev 4561) +++ branches/transforms/API_CHANGES 2007年12月03日 15:27:33 UTC (rev 4562) @@ -169,6 +169,8 @@ END OF TRANSFORMS REFACTORING +0.91.1 Released + 0.91.0 Released Changed cbook.is_file_like to cbook.is_writable_file_like and Modified: branches/transforms/CHANGELOG =================================================================== --- branches/transforms/CHANGELOG 2007年12月03日 15:23:47 UTC (rev 4561) +++ branches/transforms/CHANGELOG 2007年12月03日 15:27:33 UTC (rev 4562) @@ -1,4 +1,7 @@ =============================================================== +2007年11月27日 Released 0.91.1 at revision 4517 +たす +たす=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ=わ 2007年11月27日 Released 0.91.0 at revision 4478 2007年11月13日 All backends now support writing to a file-like object, not Modified: branches/transforms/CODING_GUIDE =================================================================== --- branches/transforms/CODING_GUIDE 2007年12月03日 15:23:47 UTC (rev 4561) +++ branches/transforms/CODING_GUIDE 2007年12月03日 15:27:33 UTC (rev 4562) @@ -117,7 +117,7 @@ -for older versions of emacs (emacs<22) you may need to do +for older versions of emacs (emacs<22) you need to do (add-hook 'python-mode-hook (lambda () Modified: branches/transforms/INSTALL =================================================================== --- branches/transforms/INSTALL 2007年12月03日 15:23:47 UTC (rev 4561) +++ branches/transforms/INSTALL 2007年12月03日 15:27:33 UTC (rev 4562) @@ -14,7 +14,7 @@ more. If you want to produce PNGs or GUI images that support all of matplotlib's features, you should compile matplotlib with agg support and use one of the GUI agg backends: GTKAgg, WXAgg, TkAgg or - FLTKAgg. + FLTKAgg. COMPILING @@ -36,7 +36,7 @@ As discussed above, most users will want to set 'BUILD_AGG = 1' and one or more of the GUI backends to True. Exceptions to this are if you know you don't need a GUI (eg a web server) or you only want to - produce vector graphics. + produce vector graphics. If you have installed prerequisites to nonstandard places and need to inform matplotlib where they are, edit setupext.py an add the @@ -53,16 +53,12 @@ with matplotlib, it is important that you have *both* present and in your PYTHONPATH when you compile matplotlib. - Note that if you install matplotlib anywhere other than the default - location, you will need to set the MATPLOTLIBDATA environment - variable to point to the install base dir. - Once you have everything above set to your liking, just do the usual thing python setup.py build python setup.py install - + WINDOWS If you don't already have python installed, you may want to consider @@ -106,7 +102,7 @@ To build all the backends on a binary linux distro such as redhat, you need to install a number of the devel libs (and whatever dependencies they require), I suggest - + matplotlib core: zlib, zlib-devel, libpng, libpng-devel, freetype, freetype-devel, freetype-utils @@ -134,7 +130,7 @@ http://www.freshports.org/math/py-matplotlib/ Gentoo - + http://www.gentoo-portage.com/dev-python/matplotlib OS X Modified: branches/transforms/MANIFEST.in =================================================================== --- branches/transforms/MANIFEST.in 2007年12月03日 15:23:47 UTC (rev 4561) +++ branches/transforms/MANIFEST.in 2007年12月03日 15:27:33 UTC (rev 4562) @@ -1,7 +1,7 @@ include API_CHANGES CHANGELOG KNOWN_BUGS INSTALL NUMARRAY_ISSUES include INTERACTIVE TODO include Makefile MANIFEST.in MANIFEST -include matplotlibrc.template matplotlibrc +include matplotlibrc.template matplotlibrc setup.cfg.template include __init__.py setupext.py setup.py setupegg.py makeswig.py include examples/data/* include lib/matplotlib/toolkits @@ -12,7 +12,8 @@ recursive-include examples README *.py prune examples/_tmp_* recursive-include src *.cpp *.c *.h -recursive-include CXX *.cxx *.hxx *.c +recursive-include CXX *.cxx *.hxx *.c *.h recursive-include agg23 * recursive-include lib * recursive-include swig * +recursive-include ttconv *.cpp *.h Modified: branches/transforms/examples/data_helper.py =================================================================== --- branches/transforms/examples/data_helper.py 2007年12月03日 15:23:47 UTC (rev 4561) +++ branches/transforms/examples/data_helper.py 2007年12月03日 15:27:33 UTC (rev 4562) @@ -15,7 +15,7 @@ M1 = resize(M1, (M1.shape[0]/2,2) ) M2 = fromstring( file('data/%s.dat' % ticker2, 'rb').read(), '<d') - M2 = resize(M1, (M2.shape[0]/2,2) ) + M2 = resize(M2, (M2.shape[0]/2,2) ) d1, p1 = M1[:,0], M1[:,1] d2, p2 = M2[:,0], M2[:,1] Modified: branches/transforms/examples/loadrec.py =================================================================== --- branches/transforms/examples/loadrec.py 2007年12月03日 15:23:47 UTC (rev 4561) +++ branches/transforms/examples/loadrec.py 2007年12月03日 15:27:33 UTC (rev 4562) @@ -2,6 +2,7 @@ from pylab import figure, show a = mlab.csv2rec('data/msft.csv') +a.sort() print a.dtype fig = figure() Modified: branches/transforms/examples/text_themes.py =================================================================== --- branches/transforms/examples/text_themes.py 2007年12月03日 15:23:47 UTC (rev 4561) +++ branches/transforms/examples/text_themes.py 2007年12月03日 15:27:33 UTC (rev 4562) @@ -17,7 +17,7 @@ plot(t1, f(t1), 'bo', t2, f(t2), 'k') title('Damped exponential decay', font, size='large', color='r') -text(2, 0.65, 'cos(2 pi t) exp(-t)', font, color='k', family='monospace' ) +text(2, 0.65, r'$\cos(2 \pi t) \exp(-t)$', color='k') xlabel('time (s)', font, style='italic') ylabel('voltage (mV)', font) Modified: branches/transforms/lib/matplotlib/__init__.py =================================================================== --- branches/transforms/lib/matplotlib/__init__.py 2007年12月03日 15:23:47 UTC (rev 4561) +++ branches/transforms/lib/matplotlib/__init__.py 2007年12月03日 15:27:33 UTC (rev 4562) @@ -55,7 +55,7 @@ """ from __future__ import generators -__version__ = '0.91.0' +__version__ = '0.91.1' __revision__ = '$Revision$' __date__ = '$Date$' Modified: branches/transforms/lib/matplotlib/axes3d.py =================================================================== --- branches/transforms/lib/matplotlib/axes3d.py 2007年12月03日 15:23:47 UTC (rev 4561) +++ branches/transforms/lib/matplotlib/axes3d.py 2007年12月03日 15:27:33 UTC (rev 4562) @@ -313,9 +313,10 @@ def mouse_init(self): self.button_pressed = None - self.figure.canvas.mpl_connect('motion_notify_event', self.on_move) - self.figure.canvas.mpl_connect('button_press_event', self.button_press) - self.figure.canvas.mpl_connect('button_release_event', self.button_release) + if self.figure.canvas != None: + self.figure.canvas.mpl_connect('motion_notify_event', self.on_move) + self.figure.canvas.mpl_connect('button_press_event', self.button_press) + self.figure.canvas.mpl_connect('button_release_event', self.button_release) def button_press(self, event): self.button_pressed = event.button Modified: branches/transforms/lib/matplotlib/mathtext.py =================================================================== --- branches/transforms/lib/matplotlib/mathtext.py 2007年12月03日 15:23:47 UTC (rev 4561) +++ branches/transforms/lib/matplotlib/mathtext.py 2007年12月03日 15:27:33 UTC (rev 4562) @@ -16,8 +16,19 @@ s = r'$\mathcal{R}\prod_{i=\alpha\mathcal{B}}^\infty a_i\sin(2 \pi f x_i)$' - The fonts \cal, \rm, \it, and \tt are allowed. + Different fonts may be selected: + \mathcal Calligraphic fonts + \mathrm Roman (upright) font + \mathit Italic font + \mathtt Typewriter (monospaced) font, similar to Courier + Additionally, if using the STIX fonts: + \mathbb Blackboard (double-struck) font + \mathcircled Circled characters + \mathfrak Fraktur (Gothic-style) font + \mathscr Script (cursive) font + \mathsf Sans-serif font + The following accents are provided: \hat, \breve, \grave, \bar, \acute, \tilde, \vec, \dot, \ddot. All of them have the same syntax, eg to make an overbar you do \bar{o} or to make an o umlaut @@ -539,10 +550,7 @@ cached_font = self._fonts.get(basename) if cached_font is None: - try: - font = FT2Font(basename) - except RuntimeError: - return None + font = FT2Font(basename) cached_font = self.CachedFont(font) self._fonts[basename] = cached_font self._fonts[font.postscript_name] = cached_font @@ -650,13 +658,20 @@ if fontname in self.fontmap and latex_to_bakoma.has_key(sym): basename, num = latex_to_bakoma[sym] slanted = (basename == "cmmi10") or sym in self._slanted_symbols - cached_font = self._get_font(basename) - symbol_name = cached_font.font.get_glyph_name(num) - num = cached_font.glyphmap[num] + try: + cached_font = self._get_font(basename) + except RuntimeError: + pass + else: + symbol_name = cached_font.font.get_glyph_name(num) + num = cached_font.glyphmap[num] elif len(sym) == 1: slanted = (fontname == "it") - cached_font = self._get_font(fontname) - if cached_font is not None: + try: + cached_font = self._get_font(fontname) + except RuntimeError: + pass + else: num = ord(sym) gid = cached_font.charmap.get(num) if gid is not None: @@ -793,9 +808,12 @@ new_fontname = 'rm' slanted = (new_fontname == 'it') or sym in self._slanted_symbols - cached_font = self._get_font(new_fontname) found_symbol = False - if cached_font is not None: + try: + cached_font = self._get_font(new_fontname) + except RuntimeError: + pass + else: try: glyphindex = cached_font.charmap[uniindex] found_symbol = True Modified: branches/transforms/setupext.py =================================================================== --- branches/transforms/setupext.py 2007年12月03日 15:23:47 UTC (rev 4561) +++ branches/transforms/setupext.py 2007年12月03日 15:27:33 UTC (rev 4562) @@ -94,25 +94,26 @@ BUILT_PATH = False AGG_VERSION = 'agg24' +TCL_TK_CACHE = None # for nonstandard installation/build with --prefix variable numpy_inc_dirs = [] # matplotlib build options, which can be altered using setup.cfg -options = {'display_status': True, - 'verbose': False, - 'provide_pytz': 'auto', - 'provide_dateutil': 'auto', - 'provide_configobj': 'auto', - 'provide_traits': 'auto', - 'build_agg': True, - 'build_gtk': 'auto', - 'build_gtkagg': 'auto', - 'build_tkagg': 'auto', - 'build_wxagg': 'auto', - 'build_image': True, - 'build_windowing': True, - 'backend': None, +options = {'display_status': True, + 'verbose': False, + 'provide_pytz': 'auto', + 'provide_dateutil': 'auto', + 'provide_configobj': 'auto', + 'provide_traits': 'auto', + 'build_agg': True, + 'build_gtk': 'auto', + 'build_gtkagg': 'auto', + 'build_tkagg': 'auto', + 'build_wxagg': 'auto', + 'build_image': True, + 'build_windowing': True, + 'backend': None, 'numerix': None} # Based on the contents of setup.cfg, determine the build options @@ -799,51 +800,6 @@ # or else you'll build for a wrong version of the Tcl # interpreter (leading to nasty segfaults). -class FoundTclTk: - pass - -def find_tcltk(): - """Finds Tcl/Tk includes/libraries/version by interrogating Tkinter.""" - # By this point, we already know that Tkinter imports correctly - import Tkinter - o = FoundTclTk() - try: - tk=Tkinter.Tk() - except Tkinter.TclError: - o.tcl_lib = "/usr/local/lib" - o.tcl_inc = "/usr/local/include" - o.tk_lib = "/usr/local/lib" - o.tk_inc = "/usr/local/include" - o.tkv = "" - else: - tk.withdraw() - o.tcl_lib = os.path.normpath(os.path.join(str(tk.getvar('tcl_library')), '../')) - o.tk_lib = os.path.normpath(os.path.join(str(tk.getvar('tk_library')), '../')) - o.tkv = str(Tkinter.TkVersion)[:3] - o.tcl_inc = os.path.normpath(os.path.join(str(tk.getvar('tcl_library')), - '../../include/tcl'+o.tkv)) - if not os.path.exists(o.tcl_inc): - o.tcl_inc = os.path.normpath(os.path.join(str(tk.getvar('tcl_library')), - '../../include')) - o.tk_inc = os.path.normpath(os.path.join(str(tk.getvar('tk_library')), - '../../include/tk'+o.tkv)) - if not os.path.exists(o.tk_inc): - o.tk_inc = os.path.normpath(os.path.join(str(tk.getvar('tk_library')), - '../../include')) - - if ((not os.path.exists(os.path.join(o.tk_inc,'tk.h'))) and - os.path.exists(os.path.join(o.tcl_inc,'tk.h'))): - o.tk_inc = o.tcl_inc - - if not os.path.exists(o.tcl_inc): - # this is a hack for suse linux, which is broken - if (sys.platform.startswith('linux') and - os.path.exists('/usr/include/tcl.h') and - os.path.exists('/usr/include/tk.h')): - o.tcl_inc = '/usr/include/' - o.tk_inc = '/usr/include/' - return o - def check_for_tk(): gotit = False explanation = None @@ -855,28 +811,26 @@ explanation = 'Tkinter present but import failed' else: if Tkinter.TkVersion < 8.3: - explanation = "Tcl/Tk v8.3 or later required\n" - sys.exit(1) + explanation = "Tcl/Tk v8.3 or later required" else: - try: - tk = Tkinter.Tk() - tk.withdraw() - except Tkinter.TclError: - explanation = """\ -Using default library and include directories for Tcl and Tk because a -Tk window failed to open. You may need to define DISPLAY for Tk to work -so that setup can determine where your libraries are located.""" gotit = True if gotit: module = Extension('test', []) try: - add_tk_flags(module) + explanation = add_tk_flags(module) except RuntimeError, e: explanation = str(e) gotit = False - if not find_include_file(module.include_dirs, "tk.h"): - explanation = 'Tkinter present, but header files are not installed. You may need to install development packages.' + else: + if not find_include_file(module.include_dirs, "tk.h"): + message = 'Tkinter present, but header files are not found. ' + \ + 'You may need to install development packages.' + if explanation is not None: + explanation += '\n' + message + else: + explanation = message + gotit = False if gotit: print_status("Tkinter", "Tkinter: %s, Tk: %s, Tcl: %s" % @@ -887,22 +841,62 @@ print_message(explanation) return gotit +def query_tcltk(): + """Tries to open a Tk window in order to query the Tk object about its library paths. + This should never be called more than once by the same process, as Tk intricacies + may cause the Python interpreter to hang. The function also has a workaround if + no X server is running (useful for autobuild systems).""" + global TCL_TK_CACHE + # Use cached values if they exist, which ensures this function only executes once + if TCL_TK_CACHE is not None: + return TCL_TK_CACHE + + # By this point, we already know that Tkinter imports correctly + import Tkinter + tcl_lib_dir = '' + tk_lib_dir = '' + # First try to open a Tk window (requires a running X server) + try: + tk = Tkinter.Tk() + except Tkinter.TclError: + # Next, start Tcl interpreter without opening a Tk window (no need for X server) + # This feature is available in python version 2.4 and up + try: + tcl = Tkinter.Tcl() + except AttributeError: # Python version not high enough + pass + except Tkinter.TclError: # Something went wrong while opening Tcl + pass + else: + tcl_lib_dir = str(tcl.getvar('tcl_library')) + # Guess Tk location based on Tcl location + tk_lib_dir = tcl_lib_dir.replace('Tcl', 'Tk').replace('tcl', 'tk') + else: + # Obtain Tcl and Tk locations from Tk widget + tk.withdraw() + tcl_lib_dir = str(tk.getvar('tcl_library')) + tk_lib_dir = str(tk.getvar('tk_library')) + + # Save directories and version string to cache + TCL_TK_CACHE = tcl_lib_dir, tk_lib_dir, str(Tkinter.TkVersion)[:3] + return TCL_TK_CACHE + def add_tk_flags(module): 'Add the module flags to build extensions which use tk' - if sys.platform=='win32': + message = None + if sys.platform == 'win32': major, minor1, minor2, s, tmp = sys.version_info - if major==2 and minor1 in [3, 4, 5]: + if major == 2 and minor1 in [3, 4, 5]: module.include_dirs.extend(['win32_static/include/tcl8.4']) module.libraries.extend(['tk84', 'tcl84']) - elif major==2 and minor1==2: + elif major == 2 and minor1 == 2: module.include_dirs.extend(['win32_static/include/tcl8.3']) module.libraries.extend(['tk83', 'tcl83']) else: raise RuntimeError('No tk/win32 support for this python version yet') module.library_dirs.extend([os.path.join(sys.prefix, 'dlls')]) - return - elif sys.platform == 'darwin' : + elif sys.platform == 'darwin': # this config section lifted directly from Imaging - thanks to # the effbot! @@ -914,7 +908,7 @@ join(os.getenv('HOME'), '/Library/Frameworks') ] - # Find the directory that contains the Tcl.framwork and Tk.framework + # Find the directory that contains the Tcl.framework and Tk.framework # bundles. # XXX distutils should support -F! tk_framework_found = 0 @@ -947,15 +941,55 @@ module.include_dirs.extend(tk_include_dirs) module.extra_link_args.extend(frameworks) module.extra_compile_args.extend(frameworks) - return - # you're still here? ok we'll try it this way - o = find_tcltk() # todo: try/except - module.include_dirs.extend([o.tcl_inc, o.tk_inc]) - module.library_dirs.extend([o.tcl_lib, o.tk_lib]) - module.libraries.extend(['tk'+o.tkv, 'tcl'+o.tkv]) + # you're still here? ok we'll try it this way... + else: + # Query Tcl/Tk system for library paths and version string + tcl_lib_dir, tk_lib_dir, tk_ver = query_tcltk() # todo: try/except + # Process base directories to obtain include + lib dirs + if tcl_lib_dir != '' and tk_lib_dir != '': + tcl_lib = os.path.normpath(os.path.join(tcl_lib_dir, '../')) + tk_lib = os.path.normpath(os.path.join(tk_lib_dir, '../')) + tcl_inc = os.path.normpath(os.path.join(tcl_lib_dir, + '../../include/tcl' + tk_ver)) + if not os.path.exists(tcl_inc): + tcl_inc = os.path.normpath(os.path.join(tcl_lib_dir, + '../../include')) + tk_inc = os.path.normpath(os.path.join(tk_lib_dir, + '../../include/tk' + tk_ver)) + if not os.path.exists(tk_inc): + tk_inc = os.path.normpath(os.path.join(tk_lib_dir, + '../../include')) + if ((not os.path.exists(os.path.join(tk_inc,'tk.h'))) and + os.path.exists(os.path.join(tcl_inc,'tk.h'))): + tk_inc = tcl_inc + + if not os.path.exists(tcl_inc): + # this is a hack for suse linux, which is broken + if (sys.platform.startswith('linux') and + os.path.exists('/usr/include/tcl.h') and + os.path.exists('/usr/include/tk.h')): + tcl_inc = '/usr/include' + tk_inc = '/usr/include' + else: + message = """\ +Using default library and include directories for Tcl and Tk because a +Tk window failed to open. You may need to define DISPLAY for Tk to work +so that setup can determine where your libraries are located.""" + tcl_inc = "/usr/local/include" + tk_inc = "/usr/local/include" + tcl_lib = "/usr/local/lib" + tk_lib = "/usr/local/lib" + tk_ver = "" + # Add final versions of directories and libraries to module lists + module.include_dirs.extend([tcl_inc, tk_inc]) + module.library_dirs.extend([tcl_lib, tk_lib]) + module.libraries.extend(['tk' + tk_ver, 'tcl' + tk_ver]) + + return message + def add_windowing_flags(module): 'Add the module flags to build extensions using windowing api' module.include_dirs.extend(['C:/include']) @@ -1019,7 +1053,7 @@ add_ft2font_flags(module) add_pygtk_flags(module) add_numpy_flags(module) - + ext_modules.append(module) BUILT_GTKAGG = True @@ -1034,9 +1068,6 @@ deps, ) - # add agg flags before pygtk because agg only supports freetype1 - # and pygtk includes freetype2. This is a bit fragile. - add_tk_flags(module) # do this first add_agg_flags(module) add_ft2font_flags(module) @@ -1130,7 +1161,7 @@ ext_modules.append(module) BUILT_PATH = True - + def build_image(ext_modules, packages): global BUILT_IMAGE if BUILT_IMAGE: return # only build it if you you haven't already This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 4561 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4561&view=rev Author: mdboom Date: 2007年12月03日 07:23:47 -0800 (2007年12月03日) Log Message: ----------- Remove paragraph about MATPLOTLIBDATA environment variable, since it doesn't really apply anymore. Modified Paths: -------------- trunk/matplotlib/INSTALL Modified: trunk/matplotlib/INSTALL =================================================================== --- trunk/matplotlib/INSTALL 2007年12月03日 15:23:32 UTC (rev 4560) +++ trunk/matplotlib/INSTALL 2007年12月03日 15:23:47 UTC (rev 4561) @@ -14,7 +14,7 @@ more. If you want to produce PNGs or GUI images that support all of matplotlib's features, you should compile matplotlib with agg support and use one of the GUI agg backends: GTKAgg, WXAgg, TkAgg or - FLTKAgg. + FLTKAgg. COMPILING @@ -36,7 +36,7 @@ As discussed above, most users will want to set 'BUILD_AGG = 1' and one or more of the GUI backends to True. Exceptions to this are if you know you don't need a GUI (eg a web server) or you only want to - produce vector graphics. + produce vector graphics. If you have installed prerequisites to nonstandard places and need to inform matplotlib where they are, edit setupext.py an add the @@ -53,16 +53,12 @@ with matplotlib, it is important that you have *both* present and in your PYTHONPATH when you compile matplotlib. - Note that if you install matplotlib anywhere other than the default - location, you will need to set the MATPLOTLIBDATA environment - variable to point to the install base dir. - Once you have everything above set to your liking, just do the usual thing python setup.py build python setup.py install - + WINDOWS If you don't already have python installed, you may want to consider @@ -106,7 +102,7 @@ To build all the backends on a binary linux distro such as redhat, you need to install a number of the devel libs (and whatever dependencies they require), I suggest - + matplotlib core: zlib, zlib-devel, libpng, libpng-devel, freetype, freetype-devel, freetype-utils @@ -134,7 +130,7 @@ http://www.freshports.org/math/py-matplotlib/ Gentoo - + http://www.gentoo-portage.com/dev-python/matplotlib OS X This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 4560 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4560&view=rev Author: jdh2358 Date: 2007年12月03日 07:23:32 -0800 (2007年12月03日) Log Message: ----------- fixed a gtk import else block in mlab Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/mlab.py Modified: trunk/matplotlib/lib/matplotlib/mlab.py =================================================================== --- trunk/matplotlib/lib/matplotlib/mlab.py 2007年12月03日 14:41:11 UTC (rev 4559) +++ trunk/matplotlib/lib/matplotlib/mlab.py 2007年12月03日 15:23:32 UTC (rev 4560) @@ -2441,9 +2441,9 @@ pass except RuntimeError: pass +else: - def gtkformat_factory(format, colnum): """ copy the format, perform any overrides, and attach an gtk style attrs This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 4559 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4559&view=rev Author: jswhit Date: 2007年12月03日 06:41:11 -0800 (2007年12月03日) Log Message: ----------- cleanup basemap examples. Modified Paths: -------------- trunk/py4science/examples/skel/basemap1_skel.py trunk/py4science/examples/skel/basemap2_skel.py trunk/py4science/examples/skel/basemap3_skel.py trunk/py4science/examples/skel/basemap4_skel.py trunk/py4science/examples/skel/basemap5_skel.py Modified: trunk/py4science/examples/skel/basemap1_skel.py =================================================================== --- trunk/py4science/examples/skel/basemap1_skel.py 2007年12月03日 13:27:16 UTC (rev 4558) +++ trunk/py4science/examples/skel/basemap1_skel.py 2007年12月03日 14:41:11 UTC (rev 4559) @@ -1,8 +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. projection = 'lcc' # map projection resolution = XX # resolution of boundaries ('c','l','i',or 'h') Modified: trunk/py4science/examples/skel/basemap2_skel.py =================================================================== --- trunk/py4science/examples/skel/basemap2_skel.py 2007年12月03日 13:27:16 UTC (rev 4558) +++ trunk/py4science/examples/skel/basemap2_skel.py 2007年12月03日 14:41:11 UTC (rev 4559) @@ -1,8 +1,5 @@ import pylab, numpy from matplotlib.toolkits.basemap import Basemap, supported_projections - -# create figure. -fig = pylab.figure() # create map by specifying width and height in km. projection = XX # map projection ('lcc','stere','laea','aea' etc) # 'print supported_projections' gives a list Modified: trunk/py4science/examples/skel/basemap3_skel.py =================================================================== --- trunk/py4science/examples/skel/basemap3_skel.py 2007年12月03日 13:27:16 UTC (rev 4558) +++ trunk/py4science/examples/skel/basemap3_skel.py 2007年12月03日 14:41:11 UTC (rev 4559) @@ -1,27 +1,15 @@ import pylab, numpy from matplotlib.toolkits.basemap import Basemap - -# create figure. -# background color will be used for 'wet' areas. -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) # lat/lon and name of location 1. -lat1 = XX -lon1 = XX -name1 = XX +lat1 = XX; lon1 = XX; name = XX # ditto for location 2. -lat2 = XX -lon2 = XX -name2 = XX +lat2 = XX; lon2 = XX; name2 = XX # convert these points to map projection coordinates # (using __call__ method of Basemap instance) x1, y1 = m(lon1, lat1) Modified: trunk/py4science/examples/skel/basemap4_skel.py =================================================================== --- trunk/py4science/examples/skel/basemap4_skel.py 2007年12月03日 13:27:16 UTC (rev 4558) +++ trunk/py4science/examples/skel/basemap4_skel.py 2007年12月03日 14:41:11 UTC (rev 4559) @@ -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) m.drawcoastlines(linewidth=0.5) m.drawmapboundary(fill_color='aqua') Modified: trunk/py4science/examples/skel/basemap5_skel.py =================================================================== --- trunk/py4science/examples/skel/basemap5_skel.py 2007年12月03日 13:27:16 UTC (rev 4558) +++ trunk/py4science/examples/skel/basemap5_skel.py 2007年12月03日 14:41:11 UTC (rev 4559) @@ -1,16 +1,13 @@ from matplotlib.toolkits.basemap import Basemap, NetCDFFile, cm import pylab, numpy - # 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. +# See http://nomads.ncdc.noaa.gov/ for some NOAA OPenDAP datasets. ncfile = NetCDFFile('data/sst.nc') sst = ncfile.variables['analysed_sst'][:] lats = ncfile.variables['lat'][:] lons = ncfile.variables['lon'][:] - -print sst.shape, sst.min(), sst.max() - # Basemap comes with extra colormaps from Generic Mapping Tools # (imported as cm, pylab colormaps in pylab.cm) cmap = XX @@ -23,6 +20,8 @@ x, y = m(*numpy.meshgrid(lons, lats)) # plot with pcolor im = m.pcolormesh(x,y,sst,shading='flat',cmap=cmap) +# or try 100 filled contours. +#CS = m.contourf(x,y,sst,100,cmap=cmap) # 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.
Revision: 4558 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4558&view=rev Author: jswhit Date: 2007年12月03日 05:27:16 -0800 (2007年12月03日) 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.
Revision: 4557 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4557&view=rev Author: mdboom Date: 2007年12月03日 05:20:19 -0800 (2007年12月03日) Log Message: ----------- Fix missing font file error. Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/mathtext.py Modified: trunk/matplotlib/lib/matplotlib/mathtext.py =================================================================== --- trunk/matplotlib/lib/matplotlib/mathtext.py 2007年12月03日 08:22:16 UTC (rev 4556) +++ trunk/matplotlib/lib/matplotlib/mathtext.py 2007年12月03日 13:20:19 UTC (rev 4557) @@ -16,8 +16,19 @@ s = r'$\mathcal{R}\prod_{i=\alpha\mathcal{B}}^\infty a_i\sin(2 \pi f x_i)$' - The fonts \cal, \rm, \it, and \tt are allowed. + Different fonts may be selected: + \mathcal Calligraphic fonts + \mathrm Roman (upright) font + \mathit Italic font + \mathtt Typewriter (monospaced) font, similar to Courier + Additionally, if using the STIX fonts: + \mathbb Blackboard (double-struck) font + \mathcircled Circled characters + \mathfrak Fraktur (Gothic-style) font + \mathscr Script (cursive) font + \mathsf Sans-serif font + The following accents are provided: \hat, \breve, \grave, \bar, \acute, \tilde, \vec, \dot, \ddot. All of them have the same syntax, eg to make an overbar you do \bar{o} or to make an o umlaut @@ -541,10 +552,7 @@ cached_font = self._fonts.get(basename) if cached_font is None: - try: - font = FT2Font(basename) - except RuntimeError: - return None + font = FT2Font(basename) cached_font = self.CachedFont(font) self._fonts[basename] = cached_font self._fonts[font.postscript_name] = cached_font @@ -652,13 +660,20 @@ if fontname in self.fontmap and latex_to_bakoma.has_key(sym): basename, num = latex_to_bakoma[sym] slanted = (basename == "cmmi10") or sym in self._slanted_symbols - cached_font = self._get_font(basename) - symbol_name = cached_font.font.get_glyph_name(num) - num = cached_font.glyphmap[num] + try: + cached_font = self._get_font(basename) + except RuntimeError: + pass + else: + symbol_name = cached_font.font.get_glyph_name(num) + num = cached_font.glyphmap[num] elif len(sym) == 1: slanted = (fontname == "it") - cached_font = self._get_font(fontname) - if cached_font is not None: + try: + cached_font = self._get_font(fontname) + except RuntimeError: + pass + else: num = ord(sym) gid = cached_font.charmap.get(num) if gid is not None: @@ -795,9 +810,12 @@ new_fontname = 'rm' slanted = (new_fontname == 'it') or sym in self._slanted_symbols - cached_font = self._get_font(new_fontname) found_symbol = False - if cached_font is not None: + try: + cached_font = self._get_font(new_fontname) + except RuntimeError: + pass + else: try: glyphindex = cached_font.charmap[uniindex] found_symbol = True This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 4556 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4556&view=rev Author: fer_perez Date: 2007年12月03日 00:22:16 -0800 (2007年12月03日) Log Message: ----------- Reorganize a bit. Waste 2 hours dealing with utf-8 problems with latex... Modified Paths: -------------- trunk/py4science/workbook/intro_to_python.tex trunk/py4science/workbook/ipython_tut.tex trunk/py4science/workbook/main.tex trunk/py4science/workbook/matplotlib_tut.tex trunk/py4science/workbook/qsort.tex trunk/py4science/workbook/why_python.tex trunk/py4science/workbook/wrapping.tex Added Paths: ----------- trunk/py4science/workbook/introduction.tex Modified: trunk/py4science/workbook/intro_to_python.tex =================================================================== --- trunk/py4science/workbook/intro_to_python.tex 2007年12月03日 04:56:57 UTC (rev 4555) +++ trunk/py4science/workbook/intro_to_python.tex 2007年12月03日 08:22:16 UTC (rev 4556) @@ -734,13 +734,12 @@ \end{lyxcode} -There are two string methods, \texttt{split} and \texttt{join}, that -arise frequenctly in Numeric processing, specifically in the context -of processing data files that have comma, tab, or space separated -numbers in them. \texttt{split} takes a single string, and splits -it on the indicated character to a sequence of strings. This is useful -to take a single line of space or comma separated values and split -them into individual numbers +There are two string methods, \texttt{split} and \texttt{join}, that arise +frequenctly in numerical processing, specifically in the context of processing +data files that have comma, tab, or space separated numbers in +them. \texttt{split} takes a single string, and splits it on the indicated +character to a sequence of strings. This is useful to take a single line of +space or comma separated values and split them into individual numbers \begin{lyxcode} \textcolor{blue}{\#~s~is~a~single~string~and~we~split~it~into~a~list~of~strings} Added: trunk/py4science/workbook/introduction.tex =================================================================== --- trunk/py4science/workbook/introduction.tex (rev 0) +++ trunk/py4science/workbook/introduction.tex 2007年12月03日 08:22:16 UTC (rev 4556) @@ -0,0 +1,41 @@ +\chapter*{Introduction} + +This book is currently a work in progress, and ultimately we hope it will +evolve into an open, community-driven document developed in tandem with the +underlying tools, by the same scientists who have written them. + +The book is aimed at practicing scientists, students and in general anyone who +is looking for a modern, high-level and open platform for scientific +computing. The Python language is in the opinion of the authors the leading +candidate today for this role. + +The book is broadly divided in two parts: the first is a general discussion of +the Python tools used for scientific work, with an explanatory approach. It is +not a complete Python reference book, as there are many excellent resources for +the base language, both in print and online. But beyond the basic language and +the NumPy book, it should serve as reasonably self-contained description of the +core libraries for common numerical tasks. + +The second part is meant as a practical workbook, and the build system used to +produce the document will in the future allow users to create custom versions +with only the examples that they deem practical for any given audience. This +workbook approach grew out of a sequence of workshops taught by the editors at +a number of research institutions and universities, and we've found it to be +extremely convenient. + +The workbook is structured as a collection of problems, meant to be solved by +the reader as programming exercises. The entire book can be compiled in one of +two forms: either with the examples in `skeleton' form, where they contain +incomplete code meant to be filled in, or with the full solution code. This +should enable instructors to hand out the skeleton workbook at courses and +workshops, with the solutions being available as well for after the teaching is +over. + +We hope that the community will continue to contribute many more examples, so +that ultimately the projects allows for the easy construction of custom +workbooks tailored to the needs of different audiences. + +\begin{flushright} +John D. Hunter and Fernando P\xE9rez, editors. + +\end{flushright} Modified: trunk/py4science/workbook/ipython_tut.tex =================================================================== --- trunk/py4science/workbook/ipython_tut.tex 2007年12月03日 04:56:57 UTC (rev 4555) +++ trunk/py4science/workbook/ipython_tut.tex 2007年12月03日 08:22:16 UTC (rev 4556) @@ -1020,8 +1020,6 @@ \item \texttt{\$HOME/.ipython/ipythonrc}: load basic things you always want. \item \texttt{\$HOME/.ipython/ipythonrc-math}: load (1) and basic math-related modules. -\item \texttt{\$HOME/.ipython/ipythonrc-numeric}: load (1) and Numeric and -plotting modules. \end{enumerate} Since it is possible to create an endless loop by having circular file inclusions, IPython will stop if it reaches 15 recursive inclusions. Modified: trunk/py4science/workbook/main.tex =================================================================== --- trunk/py4science/workbook/main.tex 2007年12月03日 04:56:57 UTC (rev 4555) +++ trunk/py4science/workbook/main.tex 2007年12月03日 08:22:16 UTC (rev 4556) @@ -45,6 +45,9 @@ \usepackage{babel} \makeatother + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Begin main document - front matter + \begin{document} \title{ \vspace{3cm} @@ -67,10 +70,15 @@ \tableofcontents{} -\part{Discussion} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Main document - body +\input{introduction.tex} + +\part{General Discussion} + % In this part, each tex file is a chapter by itself, since it is more or less % meant to be used in whole. + \input{why_python.tex} \input{intro_to_python.tex} @@ -83,7 +91,8 @@ -\part{Workbook} +\part{Workbook\\ +A Problem Collection} % This part specifies the chapter declarations in the main file, while the % chapters are made of individual TeX files which themselves should be written @@ -91,26 +100,19 @@ % few closely related topics, and to allow users to build them with as many or % as few actual sections as desired for a given audience. -\chapter{Introduction} - +\chapter{Introduction to the workbook} \input{intro.tex} -\chapter{Simple non-numerical problems} - +\chapter{Simple non-numerical Problems} \input{qsort.tex} - \input{wordfreqs.tex} \chapter{Working with files, the internet, and numpy arrays} - \input{files_etc.tex} -\chapter{Elementary Numerics} - +\chapter{Elementary numerics} \input{wallis_pi.tex} - \input{trapezoid.tex} - \input{quad_newton.tex} \chapter{Linear algebra} @@ -122,7 +124,7 @@ \input{convolution.tex} \input{fft_imdenoise.tex} -\chapter{Dynamical Systems} +\chapter{Dynamical systems} \input{intro_dynsys.tex} \input{lotka_volterra.tex} @@ -131,9 +133,11 @@ \input{stats_descriptives.tex} \input{stats_distributions.tex} -\chapter{Plotting on Maps} +\chapter{Plotting on maps} \input{basemap.tex} +%%% Bibliography section + \bibliographystyle{plain} \bibliography{python,python2} Modified: trunk/py4science/workbook/matplotlib_tut.tex =================================================================== --- trunk/py4science/workbook/matplotlib_tut.tex 2007年12月03日 04:56:57 UTC (rev 4555) +++ trunk/py4science/workbook/matplotlib_tut.tex 2007年12月03日 08:22:16 UTC (rev 4556) @@ -6,17 +6,16 @@ matplotlib is a library for making 2D plots of arrays in python.% \footnote{This short guide is not meant as a complete guide or tutorial. There -is a more comprehensive user's guide and tutorial on the matplotlib -web-site at http://matplotlib.sf.net.% -} Although it has its origins in emulating the Matlab graphics commands, -it does not require matlab, and has a pure, object oriented API. Although -matplotlib is written primarily in python, it makes heavy use of Numeric/numarray -and other extension code to provide good performance even for large -arrays. matplotlib is designed with the philosophy that you should -be able to create simple plots with just a few commands, or just one! -If you want to see a histogram of your data, you shouldn't need to -instantiate objects, call methods, set properties, and so on; it should -just work. + is a more comprehensive user's guide and tutorial on the matplotlib web-site + at http://matplotlib.sf.net.% +} Although it has its origins in emulating the Matlab graphics commands, it +does not require matlab, and has a pure, object oriented API. Although +matplotlib is written primarily in python, it makes heavy use of NumPy and +other extension code to provide good performance even for large +arrays. matplotlib is designed with the philosophy that you should be able to +create simple plots with just a few commands, or just one! If you want to see +a histogram of your data, you shouldn't need to instantiate objects, call +methods, set properties, and so on; it should just work. The matplotlib code is divided into three parts: the \textit{pylab interface} is the set of functions provided by the \texttt{pylab} @@ -355,68 +354,7 @@ In~{[}25]:~set(t,~fontsize=20,~color='darkslategray')~ \end{lyxcode} -\section[numerix]{A common interface to Numeric and numarray} -Currently the python computing community is in a state of having too -many array pacakges, none of which satisfy everyone's needs. Although -Numeric and numarray both provide the same set of core functions, -they are organized differently, and matplotlib provides a compatibility -later so you can use either one in your matplotlib scripts without -having to change your code. - -Several numarray/Numeric developers are codevelopers of matplotlib, -giving matplotlib full Numeric and numarray compatibility, thanks -in large part to Todd Miller's \texttt{matplotlib.numerix} module -and the numarray compatibility layer for extension code. This allows -you to choose between Numeric or numarray at the prompt or in a config -file. Thus when you do - -\begin{lyxcode} -\textcolor{blue}{\#~import~matplotlib~and~all~the~numerix~functions} - -from~pylab~import~{*} -\end{lyxcode} -you'll not only get all the matplotlib pylab interface commands, but -most of the Numeric or numarray package as well (depending on your -\texttt{numerix} setting). All of the array creation and manipulation -functions are imported, such as \texttt{array}, \texttt{arange}, \texttt{take}, -\texttt{where}, etc, as are the external module functions which reside -in \texttt{mlab, fft} and \texttt{linear\_algebra.} - -Even if you don't want to import all of the numerix symbols from the -pytlab interface, to make your matplotlib scripts as portable as possible -with respect to your choice of array packages, it is advised not to -explicitly import Numeric or numarray. Rather, you should use \texttt{matplotlib.numerix} -where possible, either by using the functions imported by \texttt{pylab}, -or by explicitly importing the \texttt{numerix} module, as in - -\begin{lyxcode} -\textcolor{blue}{\#~create~a~numerix~namespace} - -import~matplotlib.numerix~as~n - -from~matplotlib.numerix.mlab~import~mean - -x~=~n.arange(100) - -y~=~n.take(x,~range(10,20)) - -print~mean(y) -\end{lyxcode} -For the remainder of this manual, the term \texttt{numerix} is used -to mean either the Numeric or numarray package. To select numarray -or Numeric from the prompt, run your matplotlib script with - -\begin{lyxcode} -~~>~python~myscript.py~-{}-numarray~~\textcolor{blue}{\#~use~numarray} - -~~>~python~myscript.py~-{}-Numeric~~~\textcolor{blue}{\#~use~Numeric} -\end{lyxcode} -Typically, however, users will choose one or the other and make this -setting in their rc file using either \texttt{numerix : Numeric} or -\texttt{numerix : numarray}. - - \section[matplotlibrc]{Customizing the default behavior with the rc file} matplotlib is designed to work in a variety of settings: some people @@ -436,13 +374,13 @@ \begin{lyxcode} C:\textbackslash{}Python23\textbackslash{}share\textbackslash{}matplotlib\textbackslash{}.matplotlibrc~\textcolor{blue}{\#~windows}~/usr/share/matplotlib/.matplotlibrc~~\textcolor{blue}{\#~linux} \end{lyxcode} -By default, the installer will overwrite the existing file in the -install path, so if you want to preserve your's, please move it to -your \texttt{HOME} dir and set the environment variable if necessary. -In the rc file, you can set your backend , your numerix setting , -whether you'll be working interactively and default values for most -of the figure properties. +By default, the installer will overwrite the existing file in the install path, +so if you want to preserve yours, please move it to your \texttt{HOME} dir and +set the environment variable if necessary. In the rc file, you can set your +backend, whether you'll be working interactively and default values for most of +the figure properties. + In the RC file, blank lines, or lines starting with a comment symbol, are ignored, as are trailing comments. Other lines must have the format Modified: trunk/py4science/workbook/qsort.tex =================================================================== --- trunk/py4science/workbook/qsort.tex 2007年12月03日 04:56:57 UTC (rev 4555) +++ trunk/py4science/workbook/qsort.tex 2007年12月03日 08:22:16 UTC (rev 4556) @@ -30,12 +30,16 @@ \subsection*{Hints} \begin{itemize} -\item Python has no particular syntactic requirements for implementing recursion, -but it does have a maximum recursion depth. This value can be queried -via the function \texttt{sys.getrecursionlimit()}, and it can be changed -with \texttt{sys.setrecursionlimit(new\_value)}. + +\item Python has no particular syntactic requirements for implementing + recursion, but it does have a maximum recursion depth. This value can be + queried via the function \texttt{sys.getrecursionlimit()}, and it can be + changed with \texttt{sys.setrecursionlimit(new\_value)}. + \item Like in all recursive problems, don't forget to implement an exit -condition! + condition! + \item If \texttt{L} is a list, the call \texttt{len(L)} provides its length. + \end{itemize} Modified: trunk/py4science/workbook/why_python.tex =================================================================== --- trunk/py4science/workbook/why_python.tex 2007年12月03日 04:56:57 UTC (rev 4555) +++ trunk/py4science/workbook/why_python.tex 2007年12月03日 08:22:16 UTC (rev 4556) @@ -43,7 +43,7 @@ group at the Scripps Research Institute uses Python extensively to build a suite of applications for molecular visualization and exploration of drug/molecule interactions using virtual reality and 3D printing -technology\cite{Sanner2005a,Sanner2005b}. Engineers at Google use +technology \cite{Sanner2005a,Sanner2005b}. Engineers at Google use Python in automation, control and tuning of their computational grid, and use \texttt{SWIG} generated Python of their in-house C++ libraries in virtually all facets of their work \cite{Beazley1998,Stein2005}. @@ -116,7 +116,7 @@ Complementing these built-in features, Python is also readily extensible, giving it a wealth of libraries for scientific computing that have been in development for many years \cite{Dubois1996b,Dubois1996c}. -\texttt{Numeric Python} supports large array manipulations, math, +\texttt{NumPy} supports large array manipulations, math, optimized linear algebra, efficient Fourier transforms and random numbers. \texttt{scipy} is a collection of Python wrappers of high performance FORTRAN code (eg LAPACK, ODEPACK) for numerical analysis @@ -239,8 +239,8 @@ 256x256 pixels, and each pixel is a 2 byte integer. We read this into a string using python's \texttt{file} function -- the 'rb' flag says to open the file in \texttt{read/binary} mode. We can then use the -numerix \texttt{fromstring} method to convert this to an array, passing -the type of the data (\texttt{Int16}) as an argument. We reshape the +numpy \texttt{fromstring} method to convert this to an array, passing +the type of the data (\texttt{int16}) as an argument. We reshape the array by changing the array shape attribute to 256 by 256, and pass this off to the matplotlib pylab command \texttt{imshow} for plotting. matplotlib has a number of colormaps, and the default one is jet; @@ -277,7 +277,7 @@ \end{lyxcode} creates a 20x30 array of zeros (default integer type; details on how to specify other types will follow). Note that the dimensions ({}``shape'' -in numarray parlance) are specified by giving the dimensions as a +in numpy parlance) are specified by giving the dimensions as a comma-separated list within parentheses. The parentheses aren't necessary for a single dimension. As an aside, the parentheses used this way are being used to specify a Python tuple; more will be said about @@ -333,36 +333,35 @@ \subsection{Array numeric types} -numarray supports all standard numeric types. The default integer +numpy supports all standard numeric types. The default integer matches what Python uses for integers, usually 32 bit integers or -what numarray calls \texttt{Int32}. The same is true for floats, i.e., -generally 64-bit doubles called \texttt{Float64} in numarray. The -default complex type is \texttt{Complex64}. Many of the functions +what numpy calls \texttt{int32}. The same is true for floats, i.e., +generally 64-bit doubles called \texttt{float64} in numpy. The +default complex type is \texttt{complex64}. Many of the functions accept a type argument. For example \begin{lyxcode} ->,円{}>,円{}>~zeros(3,~Int8)~\#~Signed~byte +>,円{}>,円{}>~zeros(3,~int8)~\#~Signed~byte ->,円{}>,円{}>~zeros(3,~type=UInt8)~\#~Unsigned~byte +>,円{}>,円{}>~zeros(3,~dtype=uint8)~\#~Unsigned~byte ->,円{}>,円{}>~array({[}2,3],~type=Float32) +>,円{}>,円{}>~array({[}2,3],~dtype=float32) ->,円{}>,円{}>~arange(4,~type=Complex64) +>,円{}>,円{}>~arange(4,~dtype=complex64) \end{lyxcode} -The possible types are \texttt{Int8, UInt8, Int16, UInt16, Int32, -UInt32, Int64, UInt64, Float32, Float64, Complex32, Complex64.} To -find out the type of an array use the .type() method. E.g., +The possible types are \texttt{int8, uint8, int16, uint16, int32, +uint32, int64, uint64, float32, float64, complex32, complex64.} To +find out the type of an array use the .dtype() method. E.g., \begin{lyxcode} ->,円{}>,円{}>~arr.type() - -Float32 +>,円{}>,円{}>~arr.dtype() +dtype('float32') \end{lyxcode} To convert an array to a different type use the \texttt{astype()} method, e.g, \begin{lyxcode} ->,円{}>,円{}>~a~=~arr.astype(Float64) +>,円{}>,円{}>~a~=~arr.astype(float64) \end{lyxcode} \subsection{Printing arrays} @@ -537,7 +536,7 @@ All of the indexing tools available for 1-D arrays apply to \emph{n}-dimensional arrays as well (though combining index arrays with slices is not currently permitted). To understand all the indexing options in their full detail, -read sections 4.6, 4.7 and 6 of the numarray manual. +read sections 4.6, 4.7 and 6 of the numpy manual. \subsection{Compatibility of dimensions} @@ -711,7 +710,7 @@ \subsection{Array functions} There are many array utility functions. The following lists the more -useful ones with a one line description. See the numarray manual for +useful ones with a one line description. See the numpy manual for details on how they are used. Arguments shown with argument=value indicate what the default value is if called without a value for that argument. @@ -858,9 +857,7 @@ \item [{\texttt{\emph{a}}\texttt{.repeat}\textmd{(a,repeats,axis=0):}}]~ \item [{\texttt{\emph{a}}\texttt{.resize}\textmd{(shape):}}]~ \item [{\texttt{\emph{a}}\texttt{.size}\textmd{():}}] same as nelements -\item [{\texttt{\emph{a}}\texttt{.type}\textmd{():}}] returns type of array -\item [{\texttt{\emph{a}}\texttt{.typecode}\textmd{():}}] returns corresponding -typecode character used by Numeric +\item [{\texttt{\emph{a}}\texttt{.dtype}\textmd{():}}] returns type of array \item [{\texttt{\emph{a}}\texttt{.tofile}\textmd{(}\textmd{\emph{file}}\textmd{):}}] write binary data to file \item [{\texttt{\emph{a}}\texttt{.tolist}\textmd{():}}] convert data to Modified: trunk/py4science/workbook/wrapping.tex =================================================================== --- trunk/py4science/workbook/wrapping.tex 2007年12月03日 04:56:57 UTC (rev 4555) +++ trunk/py4science/workbook/wrapping.tex 2007年12月03日 08:22:16 UTC (rev 4556) @@ -125,8 +125,8 @@ causes f2py to keep cached copies of the scratch areas, so no unnecessary mallocs should be triggered. -Since f2py relies on Numeric arrays, all dimensions can be determined -from the arrays themselves and it is not necessary to pass them explicitly. +Since f2py relies on NumPy arrays, all dimensions can be determined from the +arrays themselves and it is not necessary to pass them explicitly. With all this, the resulting f2py-generated docstring becomes: @@ -232,7 +232,7 @@ \subsection{Passing offset arrays to Fortran routines} It is possible to pass offset arrays (like pointers to the middle -of other arrays) by using Numeric's slice notation. +of other arrays) by using NumPy's slice notation. The print\_dvec function below simply prints its argument as \char`\"{}print{*},'x',x\char`\"{}. We show some examples of how it behaves with both 1 and 2-d arrays: @@ -339,7 +339,7 @@ \subsection{On matrix ordering and in-memory copies} -Numeric (which f2py relies on) is C-based, and therefore its arrays +NumPy (which f2py relies on) is C-based, and therefore its arrays are stored in row-major order. Fortran stores its arrays in column-major order. This means that copying issues must be dealt with. Below we reproduce some comments from Pearu on this topic given in the f2py @@ -348,7 +348,7 @@ \begin{quote} To avoid copying, you should create array that has internally Fortran data ordering. This is achived, for example, by reading/creating your -data in Fortran ordering to Numeric array and then doing Numeric.transpose +data in Fortran ordering to NumPy array and then doing numpy.transpose on that. Every f2py generated extension module provides also function has\_column\_major\_storage @@ -360,7 +360,7 @@ Also note that copying done by f2py generated interface is carried out in C on the raw data and therefore it is extremely fast compared -to if you would make a copy in Python, even when using Numeric. Tests +to if you would make a copy in Python, even when using NumPy. Tests with say 1000x1000 matrices show that there is no noticable performance hit when copying is carried out, in fact, sometimes making a copy may speed up things a bit -- I was quite surprised about that myself. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 4555 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4555&view=rev Author: jdh2358 Date: 2007年12月02日 20:56:57 -0800 (2007年12月02日) Log Message: ----------- updated win32 requirements doc Modified Paths: -------------- trunk/py4science/doc/requirements.txt Modified: trunk/py4science/doc/requirements.txt =================================================================== --- trunk/py4science/doc/requirements.txt 2007年12月03日 04:56:40 UTC (rev 4554) +++ trunk/py4science/doc/requirements.txt 2007年12月03日 04:56:57 UTC (rev 4555) @@ -38,9 +38,10 @@ matplotlib requires a user interface toolkit, for example Tk, GTK, wxPython or Qt. Tk comes with python, so that should work out of the box, but some of the other code we will be demoing work best with -wxPython, so we also recommend you install wxPython -(http://www.wxpython.org/) +wxPython, so we also recommend you install wxPython_ +.. _wxPython: http://www.wxpython.org + We will detail the optional packages that will be used in the workshop below. It will be great if you can get all the optional packages as well, but since most of the workshop depends on these four @@ -126,16 +127,48 @@ In [11]: matplotlib.__version__ Out[11]: '0.91.1' + + Platform specific instructions ============================== -linux +Linux +===== -os x +TODO -win32 +OS X +==== +TODO +Microsoft Windows +================= + +- Install the latest windows `python MSI installer`_ from + +- install the win32com_ extensions. IPython needs these to set up the start menu properly and they have lots of useful goodies for windows users anyhow, like the abiliy to read and write MS Office documents via the COM API. + +- ipython: grab the latest win32 exe installer from the `ipython distributions`_ page + +- numpy: grab the latest exe or msi installer for your version of python at `numpy download`_ + +- scipy: grab the latest exe or msi installer from the "Binary installation for Windows" distribution from the `scipy download`_ page. + +- matplotlib: grab the latest exe from the `matplotlib download`_ page + +.. _`python MSI installer`: http://www.python.org/download/releases/2.5.1/ + +.. _win32com: http://sourceforge.net/project/showfiles.php?group_id=78018&package_id=79063&release_id=449591 + +.. _`ipython distributions`: http://ipython.scipy.org/dist/ + +.. _`numpy download`: http://sourceforge.net/project/showfiles.php?group_id=1369&package_id=175103 + +.. _`scipy download`: http://www.scipy.org/Download + +.. _`matplotlib download`: http://sourceforge.net/project/showfiles.php?group_id=80706&package_id=82474&release_id=558083 + Optional packages ================= @@ -171,13 +204,15 @@ - pyrex_ : lets you mix c and python for writing high performance python extensions - - basemap_ : a matplotlib toolkit for workin with geographic data and map projections. Available for download at the matplotlib download page http://sourceforge.net/project/platformdownload.php?group_id=80706 - +- svn_ : we wil be teaching open source software development + processes, which require svn. Windows users should consider + `tortise svn`_ + .. _pytables: http://www.pytables.org/moin .. _basemap: http://matplotlib.sourceforge.net/matplotlib.toolkits.basemap.basemap.html @@ -187,3 +222,8 @@ .. _`enthought tool suite`: http://code.enthought.com/ets/ .. _pydap: http://pydap.org. + +.. _svn: http://subversion.tigris.org/ + +.. `tortise svn`_: http://tortoisesvn.tigris.org/ + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 4554 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4554&view=rev Author: jdh2358 Date: 2007年12月02日 20:56:40 -0800 (2007年12月02日) Log Message: ----------- updated win32 requirements doc Modified Paths: -------------- trunk/py4science/workbook/README Modified: trunk/py4science/workbook/README =================================================================== --- trunk/py4science/workbook/README 2007年12月03日 03:27:09 UTC (rev 4553) +++ trunk/py4science/workbook/README 2007年12月03日 04:56:40 UTC (rev 4554) @@ -4,14 +4,12 @@ it in. We use the latex listing package for including python source code. -For every unit, create an example in ../examples/your_example.py, a -skeleton in ../examples/your_example_skel.py, and a symlink from -../examples/your_example_skel.py -> examples_skel/your_example.py -(../examples is in the top level of the py4science repository). If -there are any figures, you should create a PNG and EPS version of each -and add them to the fig subdirectory of the workbook directory. You -will need to svn add your tex file, example, skeleton, skeleton -symlink, and figures. +For every unit, create an example in +../problems_solved/your_problem.py, and a skeleton in +../problems_skel/your_problem_skel.py. If there are any figures, you +should create a PNG and EPS version of each and add them to the fig +subdirectory of the workbook directory. You will need to svn add your +tex file, problem, skeleton, skeleton symlink, and figures. You can build the workbook in skeleton form with This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 4553 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4553&view=rev Author: jdh2358 Date: 2007年12月02日 19:27:09 -0800 (2007年12月02日) Log Message: ----------- updated requirements links Modified Paths: -------------- trunk/py4science/doc/requirements.txt Modified: trunk/py4science/doc/requirements.txt =================================================================== --- trunk/py4science/doc/requirements.txt 2007年12月03日 03:24:57 UTC (rev 4552) +++ trunk/py4science/doc/requirements.txt 2007年12月03日 03:27:09 UTC (rev 4553) @@ -17,13 +17,13 @@ The four python packages you will need for this course are - - ipython_: an interactive python shell + - ipython_: an interactive python shell - numpy_: high performance numerical arrays - scipy_: algorithms and numerics - - matplotlib_: plotting + - matplotlib_: plotting .. _ipython: http://ipython.scipy.org @@ -31,7 +31,7 @@ .. _scipy: http://scipy.org -.. _matplotlib: http://matplotlib.sf.net +.. _matplotlib: http://matplotlib.sf.net With these four packages, you will be able to do about 90% of the exercises in the course. In addition, to generate plot windows, @@ -151,32 +151,39 @@ server, you can long in to do the exercises if you are missing a package on your local machine. +- pytables_ : a package for managing large datasets efficiently + (also requires hdf5) -- pytables : a package for managing large datasets efficiently - http://www.pytables.org/moin (also requires hdf5) +- pydap_ : a python implementation of the Data Access Protocol + (DAP). -- pydap : a python implementation of the Data Access Protocol - (DAP). http://pydap.org. - -- enthought tool suite (ETS) : provides traits, a package for strong +- `enthought tool suite`_ (ETS) : provides traits, a package for strong typing in python that also facilitates automatic user interface generation and more. Also provides tvtk and mayavi2 for 3D - visualization. http://code.enthought.com/ets/ + visualization. - weave : a package for inlining C and C++ in your python code. Comes - with scipy but requires a working compiler suite (eg gcc and g++) + with scipy but requires a working compiler suite (eg, gcc and g++) - f2py : comes with scipy but requires a working fortran compiler. See http://scipy.org/Installing_SciPy for platform specific instructions -- pyrex : lets you mix c and python for writing high performance +- pyrex_ : lets you mix c and python for writing high performance python extensions - http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/ + -- basemap : a matplotlib toolkit for workin with geographic data and - map projections. Available for download at the matplotlib downloa +- basemap_ : a matplotlib toolkit for workin with geographic data and + map projections. Available for download at the matplotlib download page http://sourceforge.net/project/platformdownload.php?group_id=80706 - with documentation at - http://matplotlib.sourceforge.net/matplotlib.toolkits.basemap.basemap.html + +.. _pytables: http://www.pytables.org/moin + +.. _basemap: http://matplotlib.sourceforge.net/matplotlib.toolkits.basemap.basemap.html + +.. _pyrex: http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/ + +.. _`enthought tool suite`: http://code.enthought.com/ets/ + +.. _pydap: http://pydap.org. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 4552 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4552&view=rev Author: jdh2358 Date: 2007年12月02日 19:24:57 -0800 (2007年12月02日) Log Message: ----------- updated requirements links Modified Paths: -------------- trunk/py4science/doc/requirements.txt trunk/py4science/doc/rest_basics.txt Modified: trunk/py4science/doc/requirements.txt =================================================================== --- trunk/py4science/doc/requirements.txt 2007年12月03日 01:50:55 UTC (rev 4551) +++ trunk/py4science/doc/requirements.txt 2007年12月03日 03:24:57 UTC (rev 4552) @@ -17,14 +17,22 @@ The four python packages you will need for this course are - - ipython: an interactive python shell http://ipython.scipy.org + - ipython_: an interactive python shell - - numpy: high performance numerical arrays http://numpy.scipy.org + - numpy_: high performance numerical arrays - - scipy: algorithms and numerics http://scipy.org + - scipy_: algorithms and numerics - - matplotlib: plotting http://matplotlib.sf.net + - matplotlib_: plotting +.. _ipython: http://ipython.scipy.org + +.. _numpy: http://numpy.scipy.org + +.. _scipy: http://scipy.org + +.. _matplotlib: http://matplotlib.sf.net + With these four packages, you will be able to do about 90% of the exercises in the course. In addition, to generate plot windows, matplotlib requires a user interface toolkit, for example Tk, GTK, Modified: trunk/py4science/doc/rest_basics.txt =================================================================== --- trunk/py4science/doc/rest_basics.txt 2007年12月03日 01:50:55 UTC (rev 4551) +++ trunk/py4science/doc/rest_basics.txt 2007年12月03日 03:24:57 UTC (rev 4552) @@ -1,4 +1,4 @@ -================================= +_================================= reST (reSTructured Text) basics =================================k .. Author: Fernando Perez This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 4551 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4551&view=rev Author: fer_perez Date: 2007年12月02日 17:50:55 -0800 (2007年12月02日) Log Message: ----------- Update reST in requirements doc Modified Paths: -------------- trunk/py4science/classes/0712_ncar_agenda.txt trunk/py4science/doc/requirements.txt trunk/py4science/workbook/main.tex Modified: trunk/py4science/classes/0712_ncar_agenda.txt =================================================================== --- trunk/py4science/classes/0712_ncar_agenda.txt 2007年12月03日 01:39:21 UTC (rev 4550) +++ trunk/py4science/classes/0712_ncar_agenda.txt 2007年12月03日 01:50:55 UTC (rev 4551) @@ -4,161 +4,149 @@ Initials indicate who presents what: -JDH - John D. Hunter -FP - Fernando Perez -JW - Jeff Whitaker + * JDH: John D. Hunter + * FP: Fernando Perez + * JW: Jeff Whitaker Day 1 (Friday December 7) ========================= -830-900 Installation and configuration (optional) -This half hour will be spent helping with installation issues, before the -real workshop begins. If you've already set things up on your system -(meaning you have ipython, numpy, matplotlib and scipy installed and -running), feel free to skip this. +830-900: Installation and configuration (optional) + This half hour will be spent helping with installation issues, before the + real workshop begins. If you've already set things up on your system + (meaning you have ipython, numpy, matplotlib and scipy installed and + running), feel free to skip this. -900-905 Introduction -Official start of the workshop, introduce instructors. +900-905: Introduction + Official start of the workshop, introduce instructors. -905-945 JDH: Python for scientific computing -A high-level overview of the topic of Python in a scientific context. +905-945 (JDH): Python for scientific computing + A high-level overview of the topic of Python in a scientific context. -950-1045 FP: Workflow, guided by a simple example: trapezoid integration. +950-1045 (FP): Workflow, guided by a simple examples. + This section will be used to illustrate basic workflow for students, by + having them 'type along' a very simple exercise, trapezoid rule integration. + We'll discuss the basics of numpy arrays and will solve the trapezoid + integration exercise together. -This section will be used to illustrate basic workflow for students, by having -them 'type along' a very simple exercise, trapezoid rule integration. We'll -discuss the basics of numpy arrays and will solve the trapezoid integration -exercise together. +---- -Editor: (X)Emacs, Vi(m), etc. +1045-1100: Coffee break -ipython. Saving and reloading files, interactive use of variables, %run, -%debug, %xmode verbose. +---- -Getting help: - - pydoc (-g, -p) +1100-1145 (FP): Introductory examples. + We'll have two exercises, so students who finish the first one early don't + get bored and can do a second one: - - The standard docs (bookmark them) + * FFTs: 2-d image denoising via FFT. + * Numerical integration and root finding. - - ipython ?/??, help(), the tab key. numpy.*cos*? search. +---- - - The open source process: mailing lists, wikis, svn. Python - cookbook. Participate! +1145-1230: Lunch Break -Basic setup: - - ipython - - matplotlib (latex, etc). - - Modules: import/reload, PYTHONPATH. +---- -- Urllib Yahoo finance demo. - -ToDo: Add numerical error measure of trapezoid rule. +1300-1400 (JDH): Basic numpy/pylab usage. + A linear algebra/2d data visualization demo using numpy and matplotlib will + then be extended as an exercise by the students. If time allows, an ODE + example will be presented: -ToDo Add in workflow comparison with scipy's integration. compare timing and - eror. + * Glass2 demo: linear algebra, event handling in interactive plots. + * Glass1 exercise: simplified version of the above as an exercise. + * ODEs - Lotka Volterra equations. -ToDo: write cheat-sheet. +1400-1500 (JW): Basemap: geographical datasets. + Basemap_ is a matplotlib toolkit that plots data on map projections (with + continental and political boundaries). -1045:1100 --- Coffee break --- +.. _Basemap: http://matplotlib.sourceforge.net/matplotlib.toolkits.basemap.basemap.html +---- -1100:1145 FP: Introductory examples. +1500 End of main work for Friday -We'll have two exercises, so students who finish the first one early don't get -bored and can do a second one. +---- -FFTs: 2-d image denoising via FFT. +1500-1700: Open data access standards and protocols (optional material) + We realize there's a Christmas party, so we'll keep this part optional, feel + free to skip out as the needs for wine and cheese dictate. We'll look at the + Python implementation of the OpenDAP protocol and a package for easy + construction and manipulation of HDF5 datsets: -Numerical integration and root finding: Find t such that + * (FP) - OpenDAP_ via the PyDAP_ implementation. + * (JDH) - PyTables_: an HDF5 library. - \int_0^t{ f(s) ds} = u +.. _OPenDAP: http://pydap.org +.. _PyDAP: http://opendap.org +.. _PyTables: http://www.pytables.org -for a known, monotonically increasing f(s) and a fixed u. - -.&checktime(1145,12,30,':') --- Lunch Break --- - -1300:1400 JDH: Basic numpy/pylab - -* Glass2 demo: linear algebra, event handling in interactive plots. -* Glass1 exercise: simplified version of the above as an exercise. -* ODEs - Lotka Volterra equations. - -1400:1500 JW, Basemap: geographical datasets. - -1500 --- End of main work for Friday --- - -1500:1700: Optional material (there's a Christmas party) - -PyDAP/OpenDAP -PyTables - - + Day 2 (Saturday December 8) =========================== -900:930 FP: Traits, Mayavi2 demo. Automatic GUI generation, VTK library, the -MayaVi visualization application. This is a demo of capabilities, not an -exercise. +900-930 (FP): Traits_, TVTK_ and MayaVi2_ + Automatic GUI generation, VTK library, the MayaVi visualization application. + This is a demo of capabilities, not an exercise. -930:1030 FP - Lightweight tools for low-level code reuse +.. _Traits: http://code.enthought.com/traits +.. _TVTK: https://svn.enthought.com/enthought/wiki/TVTK +.. _MayaVi2: http://code.enthought.com/mayavi2 + +9300-1030 (FP): - Lightweight tools for low-level code reuse + These two tools ship by default with NumPy (f2py) and SciPy (weave), and + allow you to easily access low-level codes or optimize numerical hotspots: + + * f2py: Fortran code wrapping exercise. + * weave: C/C++ inlining exercise. -f2py: Fortran code wrapping exercise. -weave: C/C++ inlining exercise. +---- -1030:1045 --- Coffee break --- +1030-1045: Coffee break -1045:1200 JDH - Other tools for C/C++ code reuse, demos/slides. +---- -* ctypes: easy access to dynamically linked libraries. -* pyrex: blend of python/C for automatic generation of native code. -* SWIG: automatic wrapping of C/C++ libraries. -* Boost.Python: automatic wrapping of C++ libraries with template support. -* A tour of scipy's code base, which uses several of these techniques. - -1200:1300 --- Lunch break --- +1045-1200 (JDH): Other tools for C/C++ code reuse + This will be a demo of a number of other tools that exist in Python for + accessing C and C++ codes, each with its own set of strengths: + + * ctypes_: easy access to dynamically linked libraries. + * pyrex_: blend of python/C for automatic generation of native code. + * SWIG_: automatic wrapping of C/C++ libraries. + * `Boost.Python`_: automatic wrapping of C++ libraries with template support. + * A tour of scipy's code base, which uses several of these techniques. -1300:1330: JDH - SVN workflow, contributing to the workbook. (optional mailing list - subscription) +.. _ctypes: http://python.net/crew/theller/ctypes +.. _pyrex: http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex +.. _SWIG: http://www.swig.org +.. _`Boost.Python`: http://www.boost.org/libs/python/doc -1330:1400: JDH - Type along data smoothing, convolutions, scipy.filter +---- -1400:1430: FP - Basic data fitting, scipy.optimize +1200-1300: Lunch break -1430:1500: FP - Sage intro/demo. +---- -1500:1515 - Wrapup. +1300-1330 (JDH): Participating in the open source process + We'll discuss the SVN workflow, contributing to the workbook and the projects + used in this course, etc. +1330-1400 (JDH): Data smoothing + Type along data smoothing, convolutions, scipy.filter +1400-1430 (FP): Fitting + Basic data fitting, scipy.optimize exercise. -Unused examples and exercises, extra ideas -========================================== +1430-1500 (FP): SAGE + An overview and brief demo of the Sage_ project, an ambitious and rapidly + growing Python project to offer free mathematical software (as well as + integration with commercial systems). -* Visual (VPython): Show some examples, explain. Target shooting exercise. +.. _Sage: http://sagemath.org -* One-dimensional FFT - Bode plot. - -* Spectral interpolation. - -* Steinman interpolation. - -* Extended precision root finding: manually implement newton's method using - clnum or mpfr. - -* Bessel functions: special functions library, array manipulations to check -recursion relation (30 min). - -* Descriptive statistics, statistical distributions (1 hr). - -* SVD/eigenfaces (1 hr). - -* Logistic map (1 hr). - -* Beautiful soup: screen-scraping HTML for data extraction (30 min). - -* Word frequencies: use of dictionaries and text processing (20 min). - -* Prime numbers: the Sieve of Erathostenes. Illustrates lists and sets (30 - min). - -* Wallis' pi: arbitrary precision integers (30 min). +1500-1515: Wrapup + We'll have a bit of time for discussion, feedback and any questions that may + have been left. + \ No newline at end of file Modified: trunk/py4science/doc/requirements.txt =================================================================== --- trunk/py4science/doc/requirements.txt 2007年12月03日 01:39:21 UTC (rev 4550) +++ trunk/py4science/doc/requirements.txt 2007年12月03日 01:50:55 UTC (rev 4551) @@ -1,3 +1,17 @@ +====================================== + Requirements for the Python workshop +====================================== + +.. contents:: +.. + 1 Core requirements + 2 Basic configuration + 3 Testing + 4 Checking your versions + 5 Platform specific instructions + 6 Optional packages + + Core requirements ================= @@ -42,7 +56,7 @@ with the rest of your matplotlib install. Create a directory in your home directory called .matplotlib and copy this file into it (or simply edit in place in mpl-data) and change the line that starts with -'backend' to +'backend' to:: backend : WXAgg @@ -53,7 +67,7 @@ If you can execute the following commands w/o error, and have a plot window pop up, you have an installation that will work for 90% of the -exercises in the workshop +exercises in the workshop:: > ipython -pylab Python 2.5 (r25:51918, Sep 19 2006, 08:49:13) @@ -82,7 +96,7 @@ - scipy >= 0.5.2 -The example code below shows you how to check your versions: +The example code below shows you how to check your versions:: In [4]: import numpy @@ -113,6 +127,7 @@ win32 + Optional packages ================= @@ -157,4 +172,3 @@ with documentation at http://matplotlib.sourceforge.net/matplotlib.toolkits.basemap.basemap.html - Modified: trunk/py4science/workbook/main.tex =================================================================== --- trunk/py4science/workbook/main.tex 2007年12月03日 01:39:21 UTC (rev 4550) +++ trunk/py4science/workbook/main.tex 2007年12月03日 01:50:55 UTC (rev 4551) @@ -22,7 +22,7 @@ \providecommand{\tabularnewline}{\\} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Textclass specific LaTeX commands. - \theoremstyle{plain} +\theoremstyle{plain} \newtheorem{thm}{Theorem}[section] \newenvironment{lyxcode} {\begin{list}{}{ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 4550 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4550&view=rev Author: jswhit Date: 2007年12月02日 17:39:21 -0800 (2007年12月02日) 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.
Revision: 4549 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4549&view=rev Author: jswhit Date: 2007年12月02日 17:33:24 -0800 (2007年12月02日) Log Message: ----------- remove blank lines Modified Paths: -------------- trunk/py4science/examples/basemap5.py Modified: trunk/py4science/examples/basemap5.py =================================================================== --- trunk/py4science/examples/basemap5.py 2007年12月03日 00:12:18 UTC (rev 4548) +++ trunk/py4science/examples/basemap5.py 2007年12月03日 01:33:24 UTC (rev 4549) @@ -1,6 +1,5 @@ from matplotlib.toolkits.basemap import Basemap, NetCDFFile import pylab, numpy - # 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. @@ -8,9 +7,6 @@ sst = ncfile.variables['analysed_sst'][:] lats = ncfile.variables['lat'][:] lons = ncfile.variables['lon'][:] - -print sst.shape, sst.min(), sst.max() - # set colormap cmap = pylab.cm.gist_ncar # create Basemap instance for mollweide projection. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 4548 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4548&view=rev Author: fer_perez Date: 2007年12月02日 16:12:18 -0800 (2007年12月02日) Log Message: ----------- Commits to continue the merged book. Modified Paths: -------------- trunk/py4science/workbook/Makefile trunk/py4science/workbook/basemap.tex trunk/py4science/workbook/convolution.tex trunk/py4science/workbook/fft_imdenoise.tex trunk/py4science/workbook/files_etc.tex trunk/py4science/workbook/glass_dots.tex trunk/py4science/workbook/lotka_volterra.tex trunk/py4science/workbook/main.tex trunk/py4science/workbook/qsort.tex trunk/py4science/workbook/quad_newton.tex trunk/py4science/workbook/stats_descriptives.tex trunk/py4science/workbook/stats_distributions.tex trunk/py4science/workbook/template.tex trunk/py4science/workbook/trapezoid.tex trunk/py4science/workbook/wallis_pi.tex trunk/py4science/workbook/wordfreqs.tex Added Paths: ----------- trunk/py4science/workbook/examples trunk/py4science/workbook/fig/hothead.png trunk/py4science/workbook/fig/ipscr_code.png trunk/py4science/workbook/fig/ipscr_meth_src.png trunk/py4science/workbook/fig/ipscr_traceback.png trunk/py4science/workbook/fig/load_ascii.png trunk/py4science/workbook/fig/mpl_image_hot.png trunk/py4science/workbook/fig/mpl_image_jet.png trunk/py4science/workbook/fig/mpl_one_two_three.png trunk/py4science/workbook/fig/mpl_ratner.png trunk/py4science/workbook/fig/mpl_set_get1.png trunk/py4science/workbook/fig/mpl_set_get2.png trunk/py4science/workbook/fig/mpl_subplot_demo.png trunk/py4science/workbook/fig/mpl_toolbar.png trunk/py4science/workbook/intro_to_python.tex trunk/py4science/workbook/ipython_tut.tex trunk/py4science/workbook/matplotlib_tut.tex trunk/py4science/workbook/problems_solved trunk/py4science/workbook/python.bib trunk/py4science/workbook/python2.bib trunk/py4science/workbook/snippets trunk/py4science/workbook/why_python.tex trunk/py4science/workbook/wrapping.tex Modified: trunk/py4science/workbook/Makefile =================================================================== --- trunk/py4science/workbook/Makefile 2007年12月02日 17:27:41 UTC (rev 4547) +++ trunk/py4science/workbook/Makefile 2007年12月03日 00:12:18 UTC (rev 4548) @@ -1,14 +1,16 @@ solved: - rm -f examples - ln -s examples_solved examples + rm -f problems + ln -s problems_solved problems rm -f workbook_solved.tex ln -s main.tex workbook_solved.tex pdflatex workbook_solved + bibtex workbook_solved + pdflatex workbook_solved rm -f workbook_solved.tex skeletons: - rm -f examples - ln -s examples_skel examples + rm -f problems + ln -s problems_skel problems rm -f workbook_skeletons.tex ln -s main.tex workbook_skeletons.tex pdflatex workbook_skeletons Modified: trunk/py4science/workbook/basemap.tex =================================================================== --- trunk/py4science/workbook/basemap.tex 2007年12月02日 17:27:41 UTC (rev 4547) +++ trunk/py4science/workbook/basemap.tex 2007年12月03日 00:12:18 UTC (rev 4548) @@ -27,7 +27,7 @@ Here is an example script that creates a map by specifying the latitudes and longitudes of the four corners -\lstinputlisting[label=code:basemap1_skel,caption={IGNORED}]{../examples/basemap1.py} +\lstinputlisting[label=code:basemap1_skel,caption={IGNORED}]{problems/basemap1.py} After running this script, you should see a plot that looks similar to Figure 1. @@ -44,7 +44,7 @@ Here is an example script that creates a map by specifying the center of the map, plus the width and height in meters. -\lstinputlisting[label=code:basemap2_skel,caption={IGNORED}]{../examples/basemap2.py} +\lstinputlisting[label=code:basemap2_skel,caption={IGNORED}]{problems/basemap2.py} After running this script, you should see a plot that looks nearly identical to Figure 1.\medskip{} @@ -59,7 +59,7 @@ method drawgreatcircle is then used to draw the great circle route between these cities on the map. -\lstinputlisting[label=code:basemap3_skel,caption={IGNORED}]{../examples/basemap3.py} +\lstinputlisting[label=code:basemap3_skel,caption={IGNORED}]{problems/basemap3.py} This should produce something similar to Figure 2. @@ -79,7 +79,7 @@ is an example script that draws a graticule on the map we've been working with. -\lstinputlisting[label=code:basemap4_skel,caption={IGNORED}]{../examples/basemap4.py} +\lstinputlisting[label=code:basemap4_skel,caption={IGNORED}]{problems/basemap4.py} Running this script should produce a plot that looks like Figure 3. @@ -109,7 +109,7 @@ of how to read sea-surface temperature data from a NetCDF file and plot it on a global mollweide projection. -\lstinputlisting[label=code:basemap5_skel,caption={IGNORED}]{../examples/basemap5.py} +\lstinputlisting[label=code:basemap5_skel,caption={IGNORED}]{problems/basemap5.py} The resulting plot should look like Figure 4. Modified: trunk/py4science/workbook/convolution.tex =================================================================== --- trunk/py4science/workbook/convolution.tex 2007年12月02日 17:27:41 UTC (rev 4547) +++ trunk/py4science/workbook/convolution.tex 2007年12月03日 00:12:18 UTC (rev 4548) @@ -87,7 +87,7 @@ multiplication property to perform the same convolution in Fourier space to confirm the numerical result from \texttt{numpy.convolve}. -\lstinputlisting[label=code:convolution_demo,caption={IGNORED}]{examples/convolution_demo.py} +\lstinputlisting[label=code:convolution_demo,caption={IGNORED}]{problems/convolution_demo.py} Added: trunk/py4science/workbook/examples =================================================================== --- trunk/py4science/workbook/examples (rev 0) +++ trunk/py4science/workbook/examples 2007年12月03日 00:12:18 UTC (rev 4548) @@ -0,0 +1 @@ +link ../book/examples \ No newline at end of file Property changes on: trunk/py4science/workbook/examples ___________________________________________________________________ Name: svn:special + * Modified: trunk/py4science/workbook/fft_imdenoise.tex =================================================================== --- trunk/py4science/workbook/fft_imdenoise.tex 2007年12月02日 17:27:41 UTC (rev 4547) +++ trunk/py4science/workbook/fft_imdenoise.tex 2007年12月03日 00:12:18 UTC (rev 4548) @@ -41,7 +41,7 @@ to one. This serves to enhance contrast among the darker elements of the image, so it is not completely dominated by the brighter segments -\lstinputlisting[label=code:fft_imdenoise,caption={IGNORED}]{examples/fft_imdenoise.py} +\lstinputlisting[label=code:fft_imdenoise,caption={IGNORED}]{problems/fft_imdenoise.py} \begin{figure} \begin{centering}\includegraphics[width=4in]{fig/fft_imdenoise}\par\end{centering} Added: trunk/py4science/workbook/fig/hothead.png =================================================================== (Binary files differ) Property changes on: trunk/py4science/workbook/fig/hothead.png ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/py4science/workbook/fig/ipscr_code.png =================================================================== (Binary files differ) Property changes on: trunk/py4science/workbook/fig/ipscr_code.png ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/py4science/workbook/fig/ipscr_meth_src.png =================================================================== (Binary files differ) Property changes on: trunk/py4science/workbook/fig/ipscr_meth_src.png ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/py4science/workbook/fig/ipscr_traceback.png =================================================================== (Binary files differ) Property changes on: trunk/py4science/workbook/fig/ipscr_traceback.png ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/py4science/workbook/fig/load_ascii.png =================================================================== (Binary files differ) Property changes on: trunk/py4science/workbook/fig/load_ascii.png ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/py4science/workbook/fig/mpl_image_hot.png =================================================================== (Binary files differ) Property changes on: trunk/py4science/workbook/fig/mpl_image_hot.png ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/py4science/workbook/fig/mpl_image_jet.png =================================================================== (Binary files differ) Property changes on: trunk/py4science/workbook/fig/mpl_image_jet.png ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/py4science/workbook/fig/mpl_one_two_three.png =================================================================== (Binary files differ) Property changes on: trunk/py4science/workbook/fig/mpl_one_two_three.png ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/py4science/workbook/fig/mpl_ratner.png =================================================================== (Binary files differ) Property changes on: trunk/py4science/workbook/fig/mpl_ratner.png ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/py4science/workbook/fig/mpl_set_get1.png =================================================================== (Binary files differ) Property changes on: trunk/py4science/workbook/fig/mpl_set_get1.png ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/py4science/workbook/fig/mpl_set_get2.png =================================================================== (Binary files differ) Property changes on: trunk/py4science/workbook/fig/mpl_set_get2.png ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/py4science/workbook/fig/mpl_subplot_demo.png =================================================================== (Binary files differ) Property changes on: trunk/py4science/workbook/fig/mpl_subplot_demo.png ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/py4science/workbook/fig/mpl_toolbar.png =================================================================== (Binary files differ) Property changes on: trunk/py4science/workbook/fig/mpl_toolbar.png ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Modified: trunk/py4science/workbook/files_etc.tex =================================================================== --- trunk/py4science/workbook/files_etc.tex 2007年12月02日 17:27:41 UTC (rev 4547) +++ trunk/py4science/workbook/files_etc.tex 2007年12月03日 00:12:18 UTC (rev 4548) @@ -44,7 +44,7 @@ Here is the exercise skeleton of the script to create and plot the data file -\lstinputlisting[label=code:noisy_sine,caption={IGNORED}]{examples/noisy_sine.py} +\lstinputlisting[label=code:noisy_sine,caption={IGNORED}]{problems/noisy_sine.py} and the graph will look something like Figure~\ref{fig:noisy_sine} @@ -189,7 +189,7 @@ in 2003 and held to the present) for each stock. Here is the exercise skeleton.: -\lstinputlisting[label=code:stock_records,caption={IGNORED}]{examples/stock_records.py} +\lstinputlisting[label=code:stock_records,caption={IGNORED}]{problems/stock_records.py} The graph will look something like Figure~\ref{fig:stock_records}. Modified: trunk/py4science/workbook/glass_dots.tex =================================================================== --- trunk/py4science/workbook/glass_dots.tex 2007年12月02日 17:27:41 UTC (rev 4547) +++ trunk/py4science/workbook/glass_dots.tex 2007年12月03日 00:12:18 UTC (rev 4548) @@ -38,7 +38,7 @@ \textit{stable node}, if one is greater than one and the other less than one, we have a \textit{saddle node}. -\lstinputlisting[label=code:glass_dots1,caption={IGNORED}]{examples/glass_dots1.py} +\lstinputlisting[label=code:glass_dots1,caption={IGNORED}]{problems/glass_dots1.py} Added: trunk/py4science/workbook/intro_to_python.tex =================================================================== --- trunk/py4science/workbook/intro_to_python.tex (rev 0) +++ trunk/py4science/workbook/intro_to_python.tex 2007年12月03日 00:12:18 UTC (rev 4548) @@ -0,0 +1,1474 @@ + +\chapter[Python intro]{A whirlwind tour of python and the standard library} + +This is a quick-and-dirty introduction to the python language for +the impatient scientist. There are many top notch, comprehensive introductions +and tutorials for python. For absolute beginners, there is the \textit{Python +Beginner's Guide}.% +\footnote{http://www.python.org/moin/BeginnersGuide% +} The official \textit{Python Tutorial} can be read online% +\footnote{http://docs.python.org/tut/tut.html% +} or downloaded% +\footnote{http://docs.python.org/download.html% +} in a variety of formats. There are over 100 python tutorials collected +online.% +\footnote{http://www.awaretek.com/tutorials.html% +} + +There are also many excellent books. Targetting newbies is Mark Pilgrim's +\textit{Dive into Python} which in available in print and for free +online% +\footnote{http://diveintopython.org/toc/index.html% +}, though for absolute newbies even this may be too hard \cite{Dive}. +For experienced programmers, David Beasley's \textit{Python Essential +Reference} is an excellent introduction to python, but is a bit dated +since it only covers python2.1 \cite{Beasley}. Likwise Alex Martelli's +\textit{Python in a Nutshell} is highly regarded and a bit more current +-- a 2nd edition is in the works\cite{Nutshell}. And \textit{The +Python Cookbook} is an extremely useful collection of python idioms, +tips and tricks \cite{Cookbook}. + +But the typical scientist I encounter wants to solve a specific problem, +eg, to make a certain kind of graph, to numerically integrate an equation, +or to fit some data to a parametric model, and doesn't have the time +or interest to read several books or tutorials to get what they want. +This guide is for them: a short overview of the language to help them +get to what they want as quickly as possible. We get to advanced material +pretty quickly, so it may be touch sledding if you are a python newbie. +Take in what you can, and if you start getting dizzy, skip ahead to +the next section; you can always come back to absorb more detail later, +after you get your real work done. + + +\section{Hello Python} + +Python is a dynamically typed, object oriented, interpreted language. +Interpreted means that your program interacts with the python interpreter, +similar to Matlab, Perl, Tcl and Java, and unlike FORTRAN, C, or C++ +which are compiled. So let's fire up the python interpreter and get +started. I'm not going to cover installing python -- it's standard +on most linux boxes and for windows there is a friendly GUI installer. +To run the python interpreter, on windows, you can click \texttt{Start->All +Programs->Python 2.4->Python (command line)} or better yet, install +\texttt{ipython}, a python shell on steroids, and use that. On linux +/ unix systems, you just need to type \texttt{python} or \texttt{ipython} +at the command line. The \texttt{>,円{}>,円{}>} is the default python +shell prompt, so don't type it in the examples below + +\begin{lyxcode} +>,円{}>,円{}>~print~'hello~world' + +hello~world + + +\end{lyxcode} +As this example shows, \textit{hello world} in python is pretty easy +-- one common phrase you hear in the python community is that {}``it +fits your brain''. -- the basic idea is that coding in python feels +natural. Compare python's version with \textit{hello world} in C++ + +\begin{lyxcode} +//~C++ + +\#include~<iostream> + +int~main~() + +\{~~~ + +~~std::cout~<,円{}<~\char`\"{}Hello~World\char`\"{}~<,円{}<~std::endl; + +~~return~0; + +\} +\end{lyxcode} + +\section[Calculator]{\label{sec:into_calculator}Python is a calculator} + +Aside from my daughter's solar powered cash-register calculator, Python +is the only calculator I use. From the python shell, you can type +arbitrary arithmetic expressions. + +\begin{lyxcode} +>,円{}>,円{}>~2+2 + +4 + +>,円{}>,円{}>~2{*}{*}10 + +1024 + +>,円{}>,円{}>~10/5 + +2 + +>,円{}>,円{}>~2+(24.3~+~.9)/.24 + +107.0 + +>,円{}>,円{}>~2/3 + +0 +\end{lyxcode} +The last line is a standard newbie gotcha -- if both the left and +right operands are integers, python returns an integer. To do floating +point division, make sure at least one of the numbers is a float + +\begin{lyxcode} +>,円{}>,円{}>~2.0/3 + +0.66666666666666663 +\end{lyxcode} +The distinction between integer and floating point division is a common +source of frustration among newbies and is slated for destruction +in the mythical Python 3000.% +\footnote{Python 3000 is a future python release that will clean up several +things that Guido considers to be warts.% +} Since default integer division will be removed in the future, you +can invoke the time machine with the \texttt{from \_\_future\_\_} +directives; these directives allow python programmers today to use +features that will become standard in future releases but are not +included by default because they would break existing code. From future +directives should be among the first lines you type in your python +code if you are going to use them, otherwise they may not work. The +future division operator will assume floating point division by default,% +\footnote{You may have noticed that 2/3 was represented as 0.66666666666666663 +and not 0.66666666666666666 as might be expected. This is because +computers are binary calculators, and there is no exact binary representation +of 2/3, just as there is no exact binary representation of 0.1 + +\begin{lyxcode} +>,円{}>,円{}>~0.1 + +0.10000000000000001 +\end{lyxcode} +Some languages try and hide this from you, but python is explicit.% +}and provides another operator // to do classic integer division. + +\begin{lyxcode} +>,円{}>,円{}>~from~\_\_future\_\_~import~division + +>,円{}>,円{}>~2/3 + +0.66666666666666663 + +>,円{}>,円{}>~2//3 + +0 +\end{lyxcode} +python has four basic numeric types: int, long, float and complex, +but unlike C++, BASIC, FORTRAN or Java, you don't have to declare +these types. python can infer them + +\begin{lyxcode} +>,円{}>,円{}>~type(1) + +<type~'int'> + +>,円{}>,円{}>~type(1.0) + +<type~'float'> + +>,円{}>,円{}>~type(2{*}{*}200) + +<type~'long'> + + +\end{lyxcode} +2ドル^{200}$is a huge number! + +\begin{lyxcode} +>,円{}>,円{}>~2{*}{*}200 + +1606938044258990275541962092341162602522202993782792835301376L +\end{lyxcode} +but python will blithely compute it and much larger numbers for you +as long as you have CPU and memory to handle them. The integer type, +if it overflows, will automatically convert to a python \texttt{long} +(as indicated by the appended \texttt{L} in the output above) and +has no built-in upper bound on size, unlike C/C++ longs. + +Python has built in support for complex numbers. Eg, we can verify +$i^{2}=-1$ + +\begin{lyxcode} +>,円{}>,円{}>~x~=~complex(0,1) + +>,円{}>,円{}>~x{*}x + +(-1+0j) +\end{lyxcode} +To access the real and imaginary parts of a complex number, use the +\texttt{real} and \texttt{imag} attributes + +\begin{lyxcode} +>,円{}>,円{}>~x.real + +0.0 + +>,円{}>,円{}>~x.imag + +1.0 +\end{lyxcode} +If you come from other languages like Matlab, the above may be new +to you. In matlab, you might do something like this (>,円{}> is the +standard matlab shell prompt) + +\begin{lyxcode} +>,円{}>~x~=~0+j + +x~= + +~~~0.0000~+~1.0000i + + + +>,円{}>~real(x) + +ans~= + +~~~~~0 + + + +>,円{}>~imag(x) + +ans~= + +~~~~~1 + + + + +\end{lyxcode} +That is, in Matlab, you use a \textit{function} to access the real +and imaginary parts of the data, but in python these are attributes +of the complex object itself. This is a core feature of python and +other object oriented languages: an object carries its data and methods +around with it. One might say: {}``a complex number knows it's real +and imaginary parts'' or {}``a complex number knows how to take +its conjugate'', you don't need external functions for these operations + +\begin{lyxcode} +>,円{}>,円{}>~x.conjugate + +<built-in~method~conjugate~of~complex~object~at~0xb6a62368> + +>,円{}>,円{}>~x.conjugate() + +-1j +\end{lyxcode} +On the first line, I just followed along from the example above with +\texttt{real} and \texttt{imag} and typed \texttt{x.conjugate} and +python printed the representation \texttt{<built-in method conjugate +of complex object at 0xb6a62368>.} This means that \texttt{conjugate} +is a \textit{method}, a.k.a a function, and in python we need to use +parentheses to call a function. If the method has arguments, like +the \texttt{x} in \texttt{sin(x)}, you place them inside the parentheses, +and if it has no arguments, like \texttt{conjugate}, you simply provide +the open and closing parentheses. \texttt{real}, \texttt{imag} and +\texttt{conjugate} are attributes of the complex object, and \texttt{conjugate} +is a \textit{callable} attribute, known as a \textit{method}. + +OK, now you are an object oriented programmer. There are several key +ideas in object oriented programming, and this is one of them: an +object carries around with it data (simple attributes) and methods +(callable attributes) that provide additional information about the +object and perform services. It's one stop shopping -- no need to +go to external functions and libraries to deal with it -- the object +knows how to deal with itself. + + +\section[Standard Library]{Accessing the standard library} + +Arithmetic is fine, but before long you may find yourself tiring of +it and wanting to compute logarithms and exponents, sines and cosines + +\begin{lyxcode} +>,円{}>,円{}>~log(10) + +Traceback~(most~recent~call~last): + +~~File~\char`\"{}<stdin>\char`\"{},~line~1,~in~? + +NameError:~name~'log'~is~not~defined +\end{lyxcode} +These functions are not built into python, but don't despair, they +are built into the python standard library. To access a function from +the standard library, or an external library for that matter, you +must import it. + +\begin{lyxcode} +>,円{}>,円{}>~import~math + +>,円{}>,円{}>~math.log(10) + +2.3025850929940459 + +>,円{}>,円{}>~math.sin(math.pi) + +1.2246063538223773e-16 +\end{lyxcode} +Note that the default \texttt{log} function is a base 2 logarithm +(use \texttt{math.log10} for base 10 logs) and that floating point +math is inherently imprecise, since analytically$\sin(\pi)=0$. + +It's kind of a pain to keep typing \texttt{math.log} and \texttt{math.sin} +and \texttt{math.p}i, and python is accomodating. There are additional +forms of \texttt{import} that will let you save more or less typing +depending on your desires + +\begin{lyxcode} +\textcolor{blue}{\#~Appreviate~the~module~name:~m~is~an~alias} + +>,円{}>,円{}>~import~math~as~m + +>,円{}>,円{}>~m.cos(2{*}m.pi) + +1.0 + + + +\textcolor{blue}{\#~Import~just~the~names~you~need} + +>,円{}>,円{}>~from~math~import~exp,~log + +>,円{}>,円{}>~log(exp(1)) + +1.0 + + + +\textcolor{blue}{\#~Import~everything~-~use~with~caution!} + +>,円{}>,円{}>~from~math~import~{*} + +>,円{}>,円{}>~sin(2{*}pi{*}10) + +-2.4492127076447545e-15 +\end{lyxcode} +To help you learn more about what you can find in the math library, +python has nice introspection capabilities -- introspection is a way +of asking an object about itself. For example, to find out what is +available in the math library, we can get a directory of everything +available with the \texttt{dir} command% +\footnote{In addition to the introdpection and help provided in the python interpreter, +the official documentation of the python standard library is very +good and up-to-date http://docs.python.org/lib/lib.html .% +} + +\begin{lyxcode} +>,円{}>,円{}>~dir(math) + +{[}'\_\_doc\_\_',~'\_\_file\_\_',~'\_\_name\_\_',~'acos',~'asin',~'atan',~'atan2',~'ceil',~'cos',~'cosh',~'degrees',~'e',~'exp',~'fabs',~'floor',~'fmod',~'frexp',~'hypot',~'ldexp',~'log',~'log10',~'modf',~'pi',~'pow',~'radians',~'sin',~'sinh',~'sqrt',~'tan',~'tanh'] +\end{lyxcode} +This gives us just a listing of the names that are in the math module +-- they are fairly self descriptive, but if you want more, you can +call \texttt{help} on any of these functions for more information + +\begin{lyxcode} +>,円{}>,円{}>~help(math.sin)~ + +Help~on~built-in~function~sin: + +sin(...) + +sin(x) + +Return~the~sine~of~x~(measured~in~radians). +\end{lyxcode} +and for the whole math library + +\begin{lyxcode} +>,円{}>,円{}>~help(math)~ + +Help~on~module~math: + +~ + +NAME + +~~~~math + +~ + +FILE + +~~~~/usr/local/lib/python2.3/lib-dynload/math.so + +~ + +DESCRIPTION + +~~~~This~module~is~always~available.~~It~provides~access~to~the + +~~~~mathematical~functions~defined~by~the~C~standard. + +~ + +FUNCTIONS + +~~~~acos(...) + +~~~~~~~~acos(x) + +~~~~~~~~~ + +~~~~~~~~Return~the~arc~cosine~(measured~in~radians)~of~x. + +~~~~~ + +~~~~asin(...) + +~~~~~~~~asin(x) + +~~~~~~~~~ + +~~~~~~~~Return~the~arc~sine~(measured~in~radians)~of~x. + +~~~~~ +\end{lyxcode} +And much more which is snipped. Likewise, we can get information on +the complex object in the same way + +\begin{lyxcode} +>,円{}>,円{}>~x~=~complex(0,1) + +>,円{}>,円{}>~dir(x) + +{[}'\_\_abs\_\_',~'\_\_add\_\_',~'\_\_class\_\_',~'\_\_coerce\_\_',~'\_\_delattr\_\_',~'\_\_div\_\_',~'\_\_divmod\_\_',~'\_\_doc\_\_',~'\_\_eq\_\_',~'\_\_float\_\_',~'\_\_floordiv\_\_',~'\_\_ge\_\_',~'\_\_getattribute\_\_',~'\_\_getnewargs\_\_',~'\_\_gt\_\_',~'\_\_hash\_\_',~'\_\_init\_\_',~'\_\_int\_\_',~'\_\_le\_\_',~'\_\_long\_\_',~'\_\_lt\_\_',~'\_\_mod\_\_',~'\_\_mul\_\_',~'\_\_ne\_\_',~'\_\_neg\_\_',~'\_\_new\_\_',~'\_\_nonzero\_\_',~'\_\_pos\_\_',~'\_\_pow\_\_',~'\_\_radd\_\_',~'\_\_rdiv\_\_',~'\_\_rdivmod\_\_',~'\_\_reduce\_\_',~'\_\_reduce\_ex\_\_',~'\_\_repr\_\_',~'\_\_rfloordiv\_\_',~'\_\_rmod\_\_',~'\_\_rmul\_\_',~'\_\_rpow\_\_',~'\_\_rsub\_\_',~'\_\_rtruediv\_\_',~'\_\_setattr\_\_',~'\_\_str\_\_',~'\_\_sub\_\_',~'\_\_truediv\_\_',~'conjugate',~'imag',~'real'] + + +\end{lyxcode} +Notice that called \texttt{dir} or \texttt{help} on the \texttt{math} +\textit{module}, the \texttt{math.sin} \textit{function}, and the +\texttt{complex} \textit{number} \texttt{x}. That's because modules, +functions and numbers are all \textit{objects}, and we use the same +object introspection and help capabilites on them. We can find out +what type of object they are by calling \texttt{type} on them, which +is another function in python's introspection arsenal + +\begin{lyxcode} +>,円{}>,円{}>~type(math) + +<type~'module'> + +>,円{}>,円{}>~type(math.sin) + +<type~'builtin\_function\_or\_method'> + +>,円{}>,円{}>~type(x) + +<type~'complex'> + + +\end{lyxcode} +Now, you may be wondering: what were all those god-awful looking double +underscore methods, like \texttt{\_\_abs\_\_} and \texttt{\_\_mul\_\_} +in the \texttt{dir} listing of the complex object above? These are +methods that define what it means to be a numeric type in python, +and the complex object implements these methods so that complex numbers +act like the way should, eg \texttt{\_\_mul\_\_} implements the rules +of complex multiplication. The nice thing about this is that python +specifies an application programming interface (API) that is the definition +of what it means to be a number in python. And this means you can +define your own numeric types, as long as you implement the required +special double underscore methods for your custom type. double underscore +methods are very important in python; although the typical newbie +never sees them or thinks about them, they are there under the hood +providing all the python magic, and more importantly, showing the +way to let you make magic. + + +\section{\label{sec:intro_string}Strings} + +We've encountered a number of types of objects above: int, float, +long, complex, method/function and module. We'll continue our tour +with an introduction to strings, which are critical components of +almost every program. You can create strings in a number of different +ways, with single quotes, double quotes, or triple quotes -- this +diversity of methods makes it easy if you need to embed string characters +in the string itself + +\begin{lyxcode} +\textcolor{blue}{\#~single,~double~and~triple~quoted~strings} + +>,円{}>,円{}>~s~=~'Hi~Mom!' + +>,円{}>,円{}>~s~=~\char`\"{}Hi~Mom!\char`\"{} + +>,円{}>,円{}>~s~=~\char`\"{}\char`\"{}\char`\"{}Porky~said,~\char`\"{}That's~all~folks!\char`\"{}~\char`\"{}\char`\"{}\char`\"{} +\end{lyxcode} +You can add strings together to concatenate them + +\begin{lyxcode} +\textcolor{blue}{\#~concatenating~strings} + +>,円{}>,円{}>~first~=~'John' + +>,円{}>,円{}>~last~=~'Hunter' + +>,円{}>,円{}>~first+last + +'JohnHunter' +\end{lyxcode} +or call string methods to process them: upcase them or downcase them, +or replace one character with another + +\begin{lyxcode} +\textcolor{blue}{\#~string~methods} + +>,円{}>,円{}>~last.lower() + +'hunter' + +>,円{}>,円{}>~last.upper() + +'HUNTER' + +>,円{}>,円{}>~last.replace('h',~'p') + +'Hunter' + +>,円{}>,円{}>~last.replace('H',~'P') + +'Punter'~ +\end{lyxcode} +Note that in all of these examples, the string \texttt{last} is unchanged. +All of these methods operate on the string and return a new string, +leaving the original unchanged. In fact, python strings cannot be +changed by any python code at all: they are \textit{immutable} (unchangeable). +The concept of mutable and immutable objects in python is an important +one, and it will come up again, because only immutable objects can +be used as keys in python dictionaries and elements of python sets. + +You can access individual characters, or slices of the string (substrings), +using indexing. A string in sequence of characters, and strings implement +the sequence protocol in python -- we'll see more examples of python +sequences later -- and all sequences have the same syntax for accessing +their elements. Python uses 0 based indexing which means the first +element is at index 0; you can use negative indices to access the +last elements in the sequence + +\begin{lyxcode} +\textcolor{blue}{\#~string~indexing} + +>,円{}>,円{}>~last~=~'Hunter' + +>,円{}>,円{}>~last{[}0] + +'H' + +>,円{}>,円{}>~last{[}1] + +'u' + +>,円{}>,円{}>~last{[}-1]~ + +'r'~ +\end{lyxcode} +To access substrings, or generically in terms of the sequence protocol, +slices, you use a colon to indicate a range + +\begin{lyxcode} +\textcolor{blue}{\#~string~slicing} + +>,円{}>,円{}>~last{[}0:2] + +'Hu' + +>,円{}>,円{}>~last{[}2:4] + +'nt' +\end{lyxcode} +As this example shows, python uses {}``one-past-the-end'' indexing +when defining a range; eg, in the range \texttt{indmin:indmax}, the +element of \texttt{imax} is not included. You can use negative indices +when slicing too; eg, to get everything before the last character + +\begin{lyxcode} +>,円{}>,円{}>~last{[}0:-1] + +'Hunte' +\end{lyxcode} +You can also leave out either the min or max indicator; if they are +left out, 0 is assumed to be the \texttt{indmin} and one past the +end of the sequence is assumed to be \texttt{indmax} + +\begin{lyxcode} +>,円{}>,円{}>~last{[}:3] + +'Hun' + +>,円{}>,円{}>~last{[}3:] + +'ter' +\end{lyxcode} +There is a third number that can be placed in a slice, a step, with +syntax indmin:indmax:step; eg, a step of 2 will skip every second +letter + +\begin{lyxcode} +>,円{}>,円{}>~last{[}1:6:2] + +'utr' +\end{lyxcode} +Although this may be more that you want to know about slicing strings, +the time spent here is worthwhile. As mentioned above, all python +sequences obey these rules. In addition to strings, lists and tuples, +which are built-in python sequence data types and are discussed in +the next section, the numeric arrays widely used in scientific computing +also implement the sequence protocol, and thus have the same slicing +rules. + +\begin{xca} +What would you expect last{[}:] to return? +\end{xca} +One thing that comes up all the time is the need to create strings +out of other strings and numbers, eg to create filenames from a combination +of a base directory, some base filename, and some numbers. Scientists +like to create lots of data files like and then write code to loop +over these files and analyze them. We're going to show how to do that, +starting with the newbie way and progressively building up to the +way of python zen master. All of the methods below \textit{work}, +but the zen master way will more efficient, more scalable (eg to larger +numbers of files) and cross-platform.% +\footnote{{}``But it works'' is a common defense of bad code; my rejoinder +to this is {}``A computer scientist is someone who fixes things that +aren't broken''. % +} Here's the newbie way: we also introduce the for-loop here in the +spirit of diving into python -- note that python uses whitespace indentation +to delimit the for-loop code block + +\begin{lyxcode} +\textcolor{blue}{\#~The~newbie~way} + +for~i~in~(1,2,3,4): + +~~~~fname~=~'data/myexp0'~+~str(i)~+~'.dat' + +~~~~print~fname +\end{lyxcode} +Now as promised, this will print out the 4 file names above, but it +has three flaws: it doesn't scale to 10 or more files, it is inefficient, +and it is not cross platform. It doesn't scale because it hard-codes +the '\texttt{0}' after \texttt{myexp}, it is inefficient because to +add several strings requires the creation of temporary strings, and +it is not cross-platform because it hard-codes the directory separator +'/'. + +\begin{lyxcode} +\textcolor{blue}{\#~On~the~path~to~elightenment} + +for~i~in~(1,2,3,4): + +~~~~fname~=~'data/myexp\%02d.dat'\%i + +~~~~print~fname +\end{lyxcode} +This example uses string interpolation, the funny \% thing. If you +are familiar with C programming, this will be no surprise to you (on +linux/unix systems do \texttt{man sprintf} at the unix shell). The +percent character is a string formatting character: \texttt{\%02d} +means to take an integer (the \texttt{d} part) and print it with two +digits, padding zero on the left (the \texttt{\%02} part). There is +more to be said about string interpolation, but let's finish the job +at hand. This example is better than the newbie way because is scales +up to files numbered 0-99, and it is more efficient because it avoids +the creation of temporary strings. For the platform independent part, +we go to the python standard library \texttt{os.path}, which provides +a host of functions for platform-independent manipulations of filenames, +extensions and paths. Here we use \texttt{os.path.join} to combine +the directory with the filename in a platform independent way. On +windows, it will use the windows path separator '\textbackslash{}' +and on unix it will use '/'. + +\begin{lyxcode} +\textcolor{blue}{\#~the~zen~master~approach} + +import~os + +for~i~in~(1,2,3,4): + +~~~~fname~=~os.path.join('data',~'myexp\%02d.dat'\%i) + +~~~~print~fname +\end{lyxcode} +\begin{xca} +Suppose you have data files named like +\end{xca} +\begin{lyxcode} +data/2005/exp0100.dat + +data/2005/exp0101.dat + +data/2005/exp0102.dat + +... + +data/2005/exp1000.dat +\end{lyxcode} +Write the python code that iterates over these files, constructing +the filenames as strings in using \texttt{os.path.join} to construct +the paths in a platform-independent way. \textit{Hint}: read the help +for \texttt{os.path.join}! + +OK, I promised to torture you a bit more with string interpolation +-- don't worry, I remembered. The ability to properly format your +data when printing it is crucial in scientific endeavors: how many +signficant digits do you want, do you want to use integer, floating +point representation or exponential notation? These three choices +are provided with \texttt{\%d}, \texttt{\%f} and \texttt{\%e}, with +lots of variations on the theme to indicate precision and more + +\begin{lyxcode} +>,円{}>,円{}>~'warm~for~\%d~minutes~at~\%1.1f~C'~\%~(30,~37.5) + +'warm~for~30~minutes~at~37.5~C' + + + +>,円{}>,円{}>~'The~mass~of~the~sun~is~\%1.4e~kg'\%~(1.98892{*}10{*}{*}30) + +'The~mass~of~the~sun~is~1.9889e+30~kg' + + +\end{lyxcode} +There are two string methods, \texttt{split} and \texttt{join}, that +arise frequenctly in Numeric processing, specifically in the context +of processing data files that have comma, tab, or space separated +numbers in them. \texttt{split} takes a single string, and splits +it on the indicated character to a sequence of strings. This is useful +to take a single line of space or comma separated values and split +them into individual numbers + +\begin{lyxcode} +\textcolor{blue}{\#~s~is~a~single~string~and~we~split~it~into~a~list~of~strings} + +\textcolor{blue}{\#~for~further~processing} + +>,円{}>,円{}>~s~=~'1.0~2.0~3.0~4.0~5.0' + +>,円{}>,円{}>~s.split('~') + +{[}'1.0',~'2.0',~'3.0',~'4.0',~'5.0'] +\end{lyxcode} +The return value, with square brackets, indicates that python has +returned a list of strings. These individual strings need further +processing to convert them into actual floats, but that is the first +step. The conversion to floats will be discussed in the next session, +when we learn about list comprehensions. The converse method is join, +which is often used to create string output to an ASCII file from +a list of numbers. In this case you want to join a list of numbers +into a single line for printing to a file. The example below will +be clearer after the next section, in which lists are discussed + +\begin{lyxcode} +\textcolor{blue}{\#~vals~is~a~list~of~floats~and~we~convert~it~to~a~single} + +\textcolor{blue}{\#~space~separated~string} + +>,円{}>,円{}>~vals~=~{[}1.0,~2.0,~3.0,~4.0,~5.0] + +>,円{}>,円{}>~'~'.join({[}str(val)~for~val~in~vals]) + +'1.0~2.0~3.0~4.0~5.0' +\end{lyxcode} +There are two new things in the example above. One, we called the +join method directly on a string itself, and not on a variable name. +Eg, in the previous examples, we always used the name of the object +when accessing attributes, eg \texttt{x.real} or \texttt{s.upper()}. +In this example, we call the \texttt{join} method on the string which +is a single space. The second new feature is that we use a list comprehension +\texttt{{[}str(val) for val in vals]} as the argument to \texttt{join}. +\texttt{join} requires a sequence of strings, and the list comprehension +converts a list of floats to a strings. This can be confusing at first, +so don't dispair if it is. But it is worth bringing up early because +list comprehensions are a very useful feature of python. To help elucidate, +compare \texttt{vals}, which is a list of floats, with the conversion +of \texttt{vals} to a list of strings using list comprehensions in +the next line + +\begin{lyxcode} +\textcolor{blue}{\#~converting~a~list~of~floats~to~a~list~of~strings} + +>,円{}>,円{}>~vals + +{[}1.0,~2.0,~3.0,~4.0,~5.0] + +>,円{}>,円{}>~{[}str(val)~for~val~in~vals]~ + +{[}'1.0',~'2.0',~'3.0',~'4.0',~'5.0'] +\end{lyxcode} + +\section[Data Structures]{The basic python data structures} + +Strings, covered in the last section, are sequences of characters. +python has two additional built-in sequence types which can hold arbitrary +elements: tuples and lists. tuples are created using parentheses, +and lists are created using square brackets + +\begin{lyxcode} +\textcolor{blue}{\#~a~tuple~and~a~list~of~elements~of~the~same~type} + +\textcolor{blue}{\#~(homogeneous)} + +>,円{}>,円{}>~t~=~(1,2,3,4)~~\#~tuple + +>,円{}>,円{}>~l~=~{[}1,2,3,4]~~\#~list +\end{lyxcode} +Both tuples and lists can also be used to hold elements of different +types + +\begin{lyxcode} +\textcolor{blue}{\#~a~tuple~and~list~of~int,~string,~float} + +>,円{}>,円{}>~t~=~(1,'john',~3.0) + +>,円{}>,円{}>~l~=~{[}1,'john',~3.0] +\end{lyxcode} +Tuples and lists have the same indexing and slicing rules as each +other, and as string discussed above, because both implement the python +sequence protocol, with the only difference being that tuple slices +return tuples (indicated by the parentheses below) and list slices +return lists (indicated by the square brackets) + +\begin{lyxcode} +\#~indexing~and~slicing~tuples~and~lists + +>,円{}>,円{}>~t{[}0] + +1 + +>,円{}>,円{}>~l{[}0] + +1 + +>,円{}>,円{}>~t{[}:-1] + +(1,~'john') + +>,円{}>,円{}>~l{[}:-1] + +{[}1,~'john'] +\end{lyxcode} +So why the difference between tuples and lists? A number of explanations +have been offered on the mailing lists, but the only one that makes +a difference to me is that tuples are immutable, like strings, and +hence can be used as keys to python dictionaries and included as elements +of sets, and lists are mutable, and cannot. So a tuple, once created, +can never be changed, but a list can. For example, if we try to reassign +the first element of the tuple above, we get an error + +\begin{lyxcode} +>,円{}>,円{}>~t{[}0]~=~'why~not?' + +Traceback~(most~recent~call~last): + +~File~\char`\"{}<stdin>\char`\"{},~line~1,~in~? + +TypeError:~object~doesn't~support~item~assignment +\end{lyxcode} +But the same operation is perfectly accetable for lists + +\begin{lyxcode} +>,円{}>,円{}>~l{[}0]~=~'why~not?' + +>,円{}>,円{}>~l + +{[}'why~not?',~'john',~3.0] +\end{lyxcode} +lists also have a lot of methods, tuples have none, save the special +double underscore methods that are required for python objects and +sequences + +\begin{lyxcode} +\textcolor{blue}{\#~tuples~contain~only~{}``hidden''~double~underscore~methods} + +>,円{}>,円{}>~dir(t) + +{[}'\_\_add\_\_',~'\_\_class\_\_',~'\_\_contains\_\_',~'\_\_delattr\_\_',~'\_\_doc\_\_',~'\_\_eq\_\_',~'\_\_ge\_\_',~'\_\_getattribute\_\_',~'\_\_getitem\_\_',~'\_\_getnewargs\_\_',~'\_\_getslice\_\_',~'\_\_gt\_\_',~'\_\_hash\_\_',~'\_\_init\_\_',~'\_\_iter\_\_',~'\_\_le\_\_',~'\_\_len\_\_',~'\_\_lt\_\_',~'\_\_mul\_\_',~'\_\_ne\_\_',~'\_\_new\_\_',~'\_\_reduce\_\_',~'\_\_reduce\_ex\_\_',~'\_\_repr\_\_',~'\_\_rmul\_\_',~'\_\_setattr\_\_',~'\_\_str\_\_'] + + + +\textcolor{blue}{\#~but~lists~contain~other~methods,~eg~append,~extend~and} + +\textcolor{blue}{\#~reverse} + +>,円{}>,円{}>~dir(l) + +{[}'\_\_add\_\_',~'\_\_class\_\_',~'\_\_contains\_\_',~'\_\_delattr\_\_',~'\_\_delitem\_\_',~'\_\_delslice\_\_',~'\_\_doc\_\_',~'\_\_eq\_\_',~'\_\_ge\_\_',~'\_\_getattribute\_\_',~'\_\_getitem\_\_',~'\_\_getslice\_\_',~'\_\_gt\_\_',~'\_\_hash\_\_',~'\_\_iadd\_\_',~'\_\_imul\_\_',~'\_\_init\_\_',~'\_\_iter\_\_',~'\_\_le\_\_',~'\_\_len\_\_',~'\_\_lt\_\_',~'\_\_mul\_\_',~'\_\_ne\_\_',~'\_\_new\_\_',~'\_\_reduce\_\_',~'\_\_reduce\_ex\_\_',~'\_\_repr\_\_',~'\_\_rmul\_\_',~'\_\_setattr\_\_',~'\_\_setitem\_\_',~'\_\_setslice\_\_',~'\_\_str\_\_',~'append',~'count',~'extend',~'index',~'insert',~'pop',~'remove',~'reverse',~'sort'] +\end{lyxcode} +Many of these list methods change, or mutate, the list, eg append +adds an element to the list\texttt{: extend} extends the list with +a sequence of elements, \texttt{sort} sorts the list in place, \texttt{reverse} +reverses it in place, \texttt{pop} takes an element off the list and +returns it. + +We've seen a couple of examples of creating a list above -- let's +look at some more using list methods + +\begin{lyxcode} +>,円{}>,円{}>~x~=~{[}]~~~~~~~~~~~~~~~~~~~\textcolor{blue}{\#~create~the~empty~list} + +>,円{}>,円{}>~x.append(1)~~~~~~~~~~~~~~\textcolor{blue}{\#~add~the~integer~one~to~it} + +>,円{}>,円{}>~x.extend({[}'hi',~'mom'])~~\textcolor{blue}{\#~append~two~strings~to~it} + +>,円{}>,円{}>~x + +{[}1,~'hi',~'mom'] + +>,円{}>,円{}>~x.reverse()~~~~~~~~~~~~~~\textcolor{blue}{\#~reverse~the~list,~in~place} + +>,円{}>,円{}>~x + +{[}'mom',~'hi',~1] + +>,円{}>,円{}>~len(x) + +3 +\end{lyxcode} +We mentioned list comprehensions in the last section when discussing +string methods. List comprehensions are a way of creating a list +using a for loop in a single line of python. Let's create a list of +the perfect cubes from 1 to 10, first with a for loop and then with +a list comprehension. The list comprehension code will not only be +shorter and more elegant, it can be much faster (the dots are the +indentation block indicator from the python shell and should not be +typed) + +\begin{lyxcode} +\textcolor{blue}{\#~a~list~of~perfect~cubes~using~a~for-loop} + +>,円{}>,円{}>~cubes~=~{[}] + +>,円{}>,円{}>~for~i~in~range(1,10): + +...~~~~~cubes.append(i{*}{*}3) + +...~ + +>,円{}>,円{}>~cubes + +{[}1,~8,~27,~64,~125,~216,~343,~512,~729] + + + +\textcolor{blue}{\#~functionally~equivalent~code~using~list~comprehensions} + +>,円{}>,円{}>~cubes~=~{[}i{*}{*}3~for~i~in~range(1,10)] + +>,円{}>,円{}>~cubes + +{[}1,~8,~27,~64,~125,~216,~343,~512,~729] +\end{lyxcode} +The list comprehension code is faster because it all happens at the +C level. In the simple for-loop version, the python expression which +appends the cube of \texttt{i} has to be evaluated by the python interpreter +for each element of the loop. In the list comprehension example, the +single line is parsed once and executed at the C level. The difference +in speed can be considerable, and the list comprehension example is +shorter and more elegant to boot. + +The remaining essential built-in data strucuture in python is the +dictionary, which is an associative array that maps arbitrary immutable +objects to arbitrary objects. int, long, float, string and tuple are +all immutable and can be used as keys; to a dictionary list and dict +are mutable and cannot. A dictionary takes one kind of object as the +key, and this key points to another object which is the value. In +a contrived but easy to comprehent examples, one might map names to +ages + +\begin{lyxcode} +>,円{}>,円{}>~ages~=~\{\}~~~~~~~~~~~~\textcolor{blue}{\#~create~an~empty~dict} + +>,円{}>,円{}>~ages{[}'john']~=~36 + +>,円{}>,円{}>~ages{[}'fernando']~=~33 + +>,円{}>,円{}>~ages~~~~~~~~~~~~~~~~~\textcolor{blue}{\#~view~the~whole~dict} + +\{'john':~36,~'fernando':~33\} + +>,円{}>,円{}>~ages{[}'john'] + +36 + +>,円{}>,円{}>~ages{[}'john']~=~37~~~~\textcolor{blue}{\#~reassign~john's~age} + +>,円{}>,円{}>~ages{[}'john'] + +37 +\end{lyxcode} +Dictionary lookup is very fast; Tim Peter's once joked that any python +program which uses a dictionary is automatically 10 times faster than +any C program, which is of course false, but makes two worthy points +in jest: dictionary lookup is fast, and dictionaries can be used for +important optimizations, eg, creating a cache of frequently used values. +As a simple eaxample, suppose you needed to compute the product of +two numbers between 1 and 100 in an inner loop -- you could use a +dictionary to cache the cube of all odd of numbers < 100; if you were +inteterested in all numbers, you might simply use a list to store +the cached cubes -- I am cacheing only the odd numbers to show you +how a dictionary can be used to represent a sparse data structure + +\begin{lyxcode} + + +>,円{}>,円{}>~cubes~=~dict({[}~(~i,~i{*}{*}3~)~for~i~in~range(1,100,2)]) + +>,円{}>,円{}>~cubes{[}5] + +125 +\end{lyxcode} +The last example is syntactically a bit challenging, but bears careful +study. We are initializing a dictionary with a list comprehension. + The list comprehension is made up of length 2 tuples \texttt{( i, +i{*}{*}3} ). When a dictionary is initialized with a sequence of +length 2 tuples, it assumes the first element of the tuple \texttt{i} +is the \textit{key} and the second element i{*}{*}3is the \textit{value}. + Thus we have a lookup table from odd integers to to cube. Creating +dictionaries from list comprehensions as in this example is something +that hard-core python programmers do almost every day, and you should +too. + +\begin{xca} +Create a lookup table of the product of all pairs of numbers less +than 100. The key will be a tuple of the two numbers \texttt{(i,j)} +and the value will be the product. Hint: you can loop over multiple +ranges in a list comprehension, eg \texttt{{[} something for i in +range(Ni) for j in range(Nj)]} +\end{xca} + +\section[Zen]{The Zen of Python} + +\begin{xca} +\texttt{>,円{}>,円{}> import this} +\end{xca} + +\section{Functions and classes} + +You can define functions just about anywhere in python code. The typical +function definition takes zero or more arguments, zero or more keyword +arguments, and is followed by a documentation string and the function +definition, optionally returing a value. Here is a function to compute +the hypoteneuse of a right triange + +\begin{lyxcode} +def~hypot(base,~height): + +~~~'compute~the~hypoteneuse~of~a~right~triangle' + +~~~import~math + +~~~return~math.sqrt(base{*}{*}2~+~height{*}{*}2) +\end{lyxcode} +As in the case of the for-loop, leading white space is significant +and is used to delimt the start and end of the function. In the example +below, x = 1 is not in the function, because it is not indented + +\begin{lyxcode} +def~growone(l): + +~~~'append~1~to~a~list~l' + +~~~l.append(1) + +x~=~1 +\end{lyxcode} +Note that this function does not return anything, because the append +method modifies the list that was passed in. You should be careful +when designing functions that have side effects such as modifying +the structures that are passed in; they should be named and documented +in such a way that these side effects are clear. + +Python is pretty flexible with functions: you can define functions +within function definitions (just be mindful of your indentation), +you can attach attributes to functions (like other objects), you can +pass functions as arguments to other functions. A function keyword +argument defines a default value for a function that can be overridden. +Below is an example which provides a normalize keyword argument. The +default argument is \texttt{normalize=None}; the value None is a standard +python idiom which usually means either do the default thing or do +nothing. If \texttt{normalize} is not \texttt{None}, we assume it +is a function that can be called to normalize our data + +\begin{lyxcode} +def~psd(x,~normalize=None): + +~~~~'compute~the~power~spectral~density~of~x' + +~~~~if~normalize~is~not~None:~x~=~normalize(x) + +~~~\textcolor{blue}{~\#~compute~the~power~spectra~of~x~and~return~it} +\end{lyxcode} +This function could be called with or without a \texttt{normalize} +keyword argument, since if the argument is not passed, the default +of \texttt{None} is used and no normalization is done. + +\begin{lyxcode} + + +\textcolor{blue}{\#~no~normalize~argument;~do~the~default~thing} + +>,円{}>,円{}>~psd(x)~~~ + + + +\textcolor{blue}{\#~define~a~custom~normalize~function~unitstd~as~pass~it} + +\textcolor{blue}{\#~to~psd} + +>,円{}>,円{}>~def~unitstd(x):~return~x/std(x) + +>,円{}>,円{}>~psd(x,~normalize=unitstd) + + +\end{lyxcode} +In Section\ref{sec:into_calculator} we noticed that complex objects +have the real and imag data attributes, and the conjugate method. +An object is an instance of a class that defines it, and in python +you can easily define your own classes. In that section, we emphasized +that one of the important features of a classes/objects is that they +carry around their data and methods in a single bundle. Let's look +at the mechnics of defining classes, and creating instances (a.k.a. +objects) of these classes. Classes have a special double underscore +method \_\_init\_\_ that is used as the function to initialize the +class. For this example, we'll continue with the normalize theme above, +but in this case the normalization requires some data parameters. +This example arises when you want to normalize an image which may +range over 0-255 (8 bit image) or from 0-65535 (16 bit image) to the +0-1 interval. For 16 bit images, you would normally divide everything +by 65525, but you might want to configure this to a smaller number +if your data doesn't use the whole intensity range to enhance contrast. +For simplicitly, let's suppose our normalize class is only interested +in the pixel maximum, and will divide all the data by that value. + +\begin{lyxcode} +from~\_\_future\_\_~import~division~~\textcolor{blue}{\#~make~sure~we~do~float~division} + +class~Normalize: + +~~~~\char`\"{}\char`\"{}\char`\"{} + +~~~~A~class~to~normalize~data~by~dividing~it~by~a~maximum~value + +~~~~\char`\"{}\char`\"{}\char`\"{} + +~~~~def~\_\_init\_\_(self,~maxval): + +~~~~~~~~'maxval~will~be~mapped~to~1' + +~~~~~~~~self.maxval~=~maxval + +~~~~def~\_\_call\_\_(self,~data): + +~~~~~~~~'do~the~normalization' + +~~~~~~~~\textcolor{blue}{\#~in~real~life~you~would~also~want~to~clip~all~values~of} + +~\textcolor{blue}{~~~~~~~\#~data>maxval~so~that~the~returned~value~will~be~in~the~unit} + +~\textcolor{blue}{~~~~~~~\#~interval} + +~~~~~~~~return~data/self.maxval +\end{lyxcode} +The triple quoted string following the definition of class Normalize +is the class documentation stringd, and it will bre shown to the user +when they do \texttt{help(Normalize)}. A commonly used convention +is to name classes with \textit{UpperCase}, but this is not required. +self is a special variable that a class can use to refer to its own +data and methods, and must be the first argument to all the class +methods. The \texttt{\_\_init\_\_} method stores the normalization +value maxval as a class attribute in \texttt{self.maxval}, and this +value can later be reused by other class methods (as it is in \texttt{\_\_call\_\_}) +and it can be altered by the user of the class, as will illustrate +below. The \texttt{\_\_call\_\_} method is another piece of python +double underscore magic, it allows class instances to be used as \textit{functions}, +eg you can call them just like you can call any function. OK, now +let's see how you could use this. + +The first line use used to create an \textit{instance} of the \textit{class} +\texttt{Normalize}, and the special method \texttt{\_\_init\_\_} is +implicitly called. The second line implicitly calls the special \texttt{\_\_call\_\_}method + +\begin{lyxcode} +>,円{}>,円{}>~norm~=~Normalize(65356)~\textcolor{blue}{\#~good~for~16~bit~images} + +>,円{}>,円{}>~norm(255)~~~~~~~~~~~~~~~\textcolor{blue}{\#~call~this~function} + +0.0039017075708427688 + + + +\textcolor{blue}{\#~We~can~reset~the~maxval~attribute,~and~the~call~method~} + +\textcolor{blue}{\#~is~automagically~updated} + +>,円{}>,円{}>~norm.maxval~=~255~~~~~~~\textcolor{blue}{\#~reset~the~maxval} + +>,円{}>,円{}>~norm(255)~~~~~~~~~~~~~~~\textcolor{blue}{\#~and~call~it~again} + +1.0 + + + +\textcolor{blue}{\#~We~can~pass~the~norm~instance~to~the~psd~function~we~defined~above,~which~} + +\textcolor{blue}{\#~is~expecting~a~function} + +>,円{}>,円{}>~pdf(X,~normalize=norm)~~~~~~~~~~~~ +\end{lyxcode} +\begin{xca} +Pretend that \texttt{complex} were not built-in to the python core, +and write your own complex class \texttt{MyComplex}. Provide \texttt{real} +and \texttt{imag} attributes and the \texttt{conjugate} method. Define +\texttt{\_\_abs\_\_}, \texttt{\_\_mul\_\_} and \texttt{\_\_add\_\_} +to implement the absolute value of complex numbers, multiplication +of complex numbers and addition of complex numbers. See the API definition +of the python number protocol; although this is written for C programmers, +it contains information about the required function call signatures +for each of the double underscore methods that define the number protocol +in python; where they use \texttt{o1} on that page, you would use +\texttt{self} in python, and where they use \texttt{o2} you might +use \texttt{other} in python.% +\footnote{http://www.python.org/doc/current/api/number.html% +} To get you started, I'll show you what the \texttt{\_\_add\_\_} method +should look like +\end{xca} +\begin{lyxcode} +\textcolor{blue}{\#~An~example~double~underscore~method~required~in~your~MyComplex} + +\textcolor{blue}{\#~implementation} + +def~\_\_add\_\_(self,~other): + +~~~~'add~self~to~other~and~return~a~new~MyComplex~instance' + +~~~~r~=~self.real~+~other.real + +~~~~i~=~self.imag~+~other.imag + +~~~~return~MyComplex(r,i) + + + +\textcolor{blue}{\#~When~you~are~finished,~test~your~implementation~with~} + +>,円{}>,円{}>~x~=~MyComplex(2,3) + +>,円{}>,円{}>~y~=~MyComplex(0,1) + +>,円{}>,円{}>~x.real + +2.0 + +>,円{}>,円{}>~y.imag + +1.0 + +>,円{}>,円{}>~x.conjugate() + +(2-3j) + +>,円{}>,円{}>~x+y + +(2+4j) + +>,円{}>,円{}>~x{*}y + +(-3+2j) + +>,円{}>,円{}>~abs(x{*}y) + +3.6055512754639891 + + +\end{lyxcode} + +\section[Files]{Files and file like objects} + +Working with files is one of the most common and important things +we do in scientific computing because that is usually where the data +lives. In Section\ref{sec:intro_string}, we went through the mechanics +of automatically building file names like + +\begin{lyxcode} +data/myexp01.dat + +data/myexp02.dat + +data/myexp03.dat + +data/myexp04.dat +\end{lyxcode} +but we didn't actually do anything with these files. Here we'll show +how to read in the data and do something with it. Python makes working +with files easy and dare I say fun. The test data set lives in \texttt{data/family.csv} +and is a standard comma separated value file that contains information +about my family: first name, last name, age, height in cm, weight +in kg and birthdate. We'll open this file and parse it -- note that +python has a standard module for parsing CSV files that is much more +sophisticated than what I am doing here. Nevertheless, it serves as +an easy to understand example that is close enough to real life that +it is worth doing. Here is what the data file looks like + +\begin{lyxcode} +First,Last,Age,Weight,Height,Birthday + +John,Hunter,36,175,180,1968年03月05日 + +Miriam,Sierig,33,135,177,1971年05月04日 + +Rahel,Hunter,7,55,134,1998年02月25日 + +Ava,Hunter,3,45,121,2001年04月26日 + +Clara,Hunter,0,15,55,2004年10月02日 +\end{lyxcode} +Here is the code to parse that file + +\begin{lyxcode} +\textcolor{blue}{\#~open~the~file~for~reading} + +fh~=~file('../data/family.csv',~'r') + +\textcolor{blue}{\#~slurp~the~header,~splitting~on~the~comma} + +headers~=~fh.readline().split(',') + +\textcolor{blue}{\#~now~loop~over~the~remaining~lines~in~the~file~and~parse~them} + +for~line~in~fh: + +~~~~\textcolor{blue}{\#~remove~any~leading~or~trailing~white~space} + +~~~~line~=~line.strip() + +~~~~\textcolor{blue}{\#~split~the~line~on~the~comma~into~separate~variables} + +~~~~first,~last,~age,~weight,~height,~dob~=~line.split(',') + +~~~~\textcolor{blue}{\#~convert~some~of~these~strings~to~floats} + +~~~~age,~weight,~height~=~{[}float(val)~for~val~in~(age,~weight,~height)] + +~~~~print~first,~last,~age,~weight,~height,~dob +\end{lyxcode} +This example illustrates several interesting things. The syntax for +opening a file is \texttt{file(filename, mode)} and the \texttt{mode} +is a string like \texttt{'r'} or \texttt{'w'} that determines whether +you are opening in read or write mode. You can also read and write +binary files with \texttt{'rb'} and \texttt{'wb'}. There are more +options and you should do \texttt{help(file)} to learn about them. +We then use the file \texttt{readline} method to read in the first +line of the file. This returns a string (the line of text) and we +call the string method \texttt{split(',')} to split that string wherever +it sees a comma, and this returns a list of strings which are the +headers + +\begin{lyxcode} +>,円{}>,円{}>~headers + +{[}'First',~'Last',~'Age',~'Weight',~'Height',~'Birthday\textbackslash{}n'] +\end{lyxcode} +The new line character \texttt{'\textbackslash{}n'} at the end of +\texttt{'Birthday\textbackslash{}n'} indicates we forgot to strip +the string of whitespace. To fix that, we should have done + +\begin{lyxcode} +>,円{}>,円{}>~headers~=~fh.readline().strip().split(',') + +>,円{}>,円{}>~headers + +{[}'First',~'Last',~'Age',~'Weight',~'Height',~'Birthday']~ +\end{lyxcode} +Notice how this works like a pipeline: \texttt{fh.readline} returns +a line of text as a string; we call the string method \texttt{strip} +which returns a string with all white space (spaces, tabs, newlines) +removed from the left and right; we then call the \texttt{split} method +on this stripped string to split it into a list of strings. + +Next we start to loop over the file -- this is a nice feature of python +file handles, you can iterate over them as a sequence. We've learned +our lesson about trailing newlines, so we first strip the line with +\texttt{line = line.strip()}. The rest is string processing, splitting +the line on a comma as we did for the head... [truncated message content]