scitools-0.9.0/ChangeLog0000644000000000000000000002203111770270446013265 0ustar 00000000000000Version 0.9: * LaTeX support in legends and titles in Easyviz. The output is reasonable in most formats. * Updated movie module with a new encoder "HTML": javascript code for displaying PNG/JPG/GIF files as a movie in a webbrowser. * Gnuplot postscript plots has linewidth 4 instead of 1.2 for clearer line in hardcopy plots. * New commands in the scitools script: * replace for textual replacement (subst is the counterpart for regular expression replacements) * pyreport for a version of pyreport that works with both scitools.easyviz and matplotlib * Added misc.function_UI function for autogenerating a user interface to a module such that a range of functions can be called from the command line with arguments also given on the command line. Autogeneration of help too. * Added Recorder class for recording what happens with an object. Can be used to see how Easyviz actually works with the underlying module. In this way, it becomes apparent what Easyviz actually performs, and if desired, the actions can be done (manually) outside Easyviz. * Rewritten the scitools simplified profiler to take advantage of new profiling tools in Python. * Added a numpyutils.PiecewiseConstant class for piecewise constant functions. * Added the avplotter module for making vertical plots in the terminal window. Handy when experimenting with very long time series that can be plotted vertically, line by line. * Updated documentation. Version 0.8: * The syntax of Easyviz is extended to become more equal to Matplotlib (Pylab or basic Pyplot) such that one can switch between Easyviz and Matplolib just by the import statement in the top of the file. The extended syntax consists of 1) a savefig function, which is just a nickname for hardcopy, 2) the legend function can take a list of curve names, 3) new keywords loc and fancybox for the legend function allows steering where the legends appear in the figure and if a frame is written around the box with curve names. One can now write scripts that employ a syntax very close to Matlab where it is not necessary to make a specific choice between matplotlib.pylab or scitools.std import. (This has proved valuable in courses where students are familiar with Matlab, matplotlib.pylab or scitools.std). * New MovingPlotWindow.py tool for viewing (very) long time series. The tool enables three different types of a moving window. * A pause (time.sleep) is inserted when plotting many curves with the Gnuplot backend. This should fix the common problems with "thread error" in that backend. * Changed default settings for hardcopies made by Gnuplot so that the black-and-white figures look better in professional publications. Lines are not thicker, dashes are longer, and fonts are bigger. These new settings make the Gnuplot backend a very good backend when creating figures for scientific papers and thesis. * Updates for newer version of Gnuplot. * The Matplotlib backend now employs pyplot instead of pylab, which means that grabbing the backend by get_backend() returns matplotlib.pyplot. This is more in line with the recommendation by Matplotlib developers to use Pyplot and not Pylab. * Easyviz example files are updated and adjusted. * New option: scitools rename --no-backup implies no copying of old file before being renamed. Useful when changing names of big files. * FloatComparison (float_eq, float_lt, etc.): made rtol and atol static attributes such that all FloatComparison objects share the same tolerances. * The Grace backend in Easyviz now requires pygrace and not only grace_np. * Turned off the default use of LaTeX in the Matplotlib backend. * A lot of updates in the Easyviz documentation. * Switched to Sphinx for documentation. Version 0.7: * The most significant change for existing users is that Matplotlib is now the default plotting engine if you install SciTools manually via setup.py and if you have Matplotlib installed. Using Gnuplot (or another backend) as the default backend is achieved by the command python setup.py install --easyviz_backend gnuplot Existing users may want to still use Gnuplot as the default backend, especially if they have many programs with visualization of 2D scalar and vector fields (utilizing the surf and mesh commands). Easyviz does not yet support Matplotlib's recent functionality for elevated, colored surfaces in 3D. Binaries for Debian/Ubuntu still use Gnuplot as the default plotting engine since we face problems building SciTools with Matplotlib on some versions of Ubuntu. The particular plotting engine to be used can be controlled in several ways (config file, command-line option, explicit import), see the Easyviz tutorial. * Numerous bugfixes have been performed. Some documentation and code have been cleaned up. More examples are included. * The scitools script has a new option "rename" for renaming a bunch of files using regular expressions. Run scitools rename to see a powerful example. * A new module FloatComparison has been made for comparing floating-point numbers and arrays in a unified way (replacements of ==, !=, <, etc.). The old unified float_eq(a, b, atol=..., rtol=...) is still there and the main tool for doing a == b with a tolerance. * A new DoNothing class in misc.py is handy when you want to remove some actions in your code, but not change the code. See the doc string. A new function turn_off_plotting applies DoNothing to effectively make all plotting statements inactive (this is often desired during heavy debugging of the non-plotting parts of a program). Just write turn_off_plotting(globals()) before the first plot call. * The BoxGrid and BoxField classes for structured grids and associated scalar and vector fields are updated and applied more by the developers. * The old numpytools module is no longer supported, and we recommend to use plain numpy or numpyutils (=numpy + some utility functions). There is no longer (in general) support of Numeric and numarray in SciTools. Version 0.6: * Numerous bugfixes have been performed. * The all module is renamed to std, i.e., from scitools.all import * should now read from scitools.std import * The old name "all" is still available as a synonym for std, implying that old programs will work. (The "all" name is misleading as only a small portion of scitools is actually imported.) * Removed all the separate scripts subst.py, regression.py, etc. in the bin directory. Now there is only one scitools executable in bin, called scitools. The old scripts are recovered by giving their name (except the .py extension) to scitools. That is, the old subst.py, regression.py, ps2mpeg.py, file2interactive.py scripts are now run as scitools subst ... scitools regression ... scitools ps2mpeg ... scitools file2interactive ... and so forth for the other scripts. Type scitools --help to see more. The old script names subst.py, regression.py will be available if one installs the software associated with the book [1] (e.g., the subst.py script in that software package is just an execution of scitools subst). * Added ppmtompeg as alternative to mpeg_encode in ps2mpeg. * Renamed the save function in the matlab2 backend to save_m. * Changed all raise statements to function calls (preparation for Py 3.0). * Added support for more open commands in sound.play in order to support more Linux distributions. * Added (preliminary) support for a text function in easyviz. * Updated the Easyviz documentation. * Made an available_backends function for listing the backends for Easyviz. * Added some Matlab-style functions in numpyutils.py: orth, matrix_rank, null. Reworked all norm* functions. * Merged the modules DrawFunction.py, FuncDependenceViz.py, FunctionSelector.py, ParameterInterface.py and CanvasCoords.py into TkGUI.py to store all modules with Tk and Pmw graphics in one place (these modules are mostly used in the book [1]). For backward compatibility, __init__.py defines the old names. That is, from ParameterInterface import * will still work, but actually this means from TkGUI import *. * Improved bar plots in Easyviz. * The old plotdemo* files are moved to examples/old. * Removed hgtools.py as it was too specialized for qualifying for scitools. * Removed timer.py as this name is likely to clash with other scripts on a computer system. * Removed immature subpackages odeiface and pyPDE. * Removed the DocWriter module. It is now in the Doconce package (to be released - until then, send mail to hpl@simula.no to obtain that package). * Reimplemented the misc.str2type function in a smarter way. * New str2bool function in misc.py. Takes on, off, false, true, False, True, yes, no, etc. as input and turns the string to a bool. For user interfaces. * Removed the functions guesstype (not used) and findvalue. scitools.misc.str2obj now solves the problem in a better way. * Calling figure(...) in Easyviz now returns a Figure object. [1] H. P. Langtangen: Python Scripting for Computational Science. 3rd edition, 2nd printing, Springer, 2009. scitools-0.9.0/LICENSE0000644000000000000000000000770311770270446012531 0ustar 00000000000000Copyright (c) 2007-2009, Hans Petter Langtangen and Simula Resarch Laboratory. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Simula Research Laboratory nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------- Other files with different licenses: lib/scitools/Lumpy.py and lib/scitools/_Gui.py: Copyright 2005 Allen B. Downey This file contains wrapper classes I use with tkinter. It is mostly for my own use; I don't support it, and it is not very well documented. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see http://www.gnu.org/licenses/gpl.html or write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Permission has been granted by Allen B. Downey to inlcude modified versions of Lumpy.py and Gui.py under a BSD license: Hi Johannes, Yes, you are welcome to include modified versions of Gui.py and Lumpy.py in SciTools under a BSD license. Thanks for letting me know about your project. Did you make any changes you think I should integrate into my version? Cheers, Allen On 2/15/08, johannr@simula.no wrote: > > Hi, > > my name is Johannes Ring and I am working for Simula Research Laboratory > in Norway. Here we, especially Hans Petter Langtangen > (http://simula.no/~hpl), develop a software suite for scientific > programming in Python called SciTools. It is built on top of many other > useful Python packages like NumPy, SciPy, ScientificPython, etc. We have > also used slightly modified versions of your Python modules Lumpy.py and > Gui.py. Now we are ready to make a public release of SciTools and we have > chosen to release it under a BSD license. Lumpy.py and Gui.py are released > under GPL, however, we were wondering if it is okay with you that we > include these into SciTools? > > Regards, > Johannes Ring > > lib/scitools/pyreport/* Copyright (C) 2005-2009 Gael Varoquaux Distributed under the terms of the BSD License. scitools-0.9.0/MANIFEST.in0000644000000000000000000000030611770270446013252 0ustar 00000000000000recursive-include examples * recursive-include lib *.cfg recursive-include lib/scitools/easyviz/doc * recursive-include lib/scitools/easyviz/tests * include LICENSE include README include ChangeLog scitools-0.9.0/README0000644000000000000000000001574011770270446012404 0ustar 00000000000000Contents 1. Introduction 2. Dependencies 3. Installation 4. Configuration file 5. License 6. Credits 7. Contact ------------------------------------------------------------------------------- 1. Introduction SciTools is a Python package containing many useful tools for scientific computing in Python. The package is built on top of other widely used packages such as NumPy, SciPy, ScientificPython, Gnuplot, etc. ------------------------------------------------------------------------------- 2. Dependencies SciTools only requirements are Python (see http://python.org) and Numerical Python (see http://numpy.org). In the past, SciTools worked transparently with NumPy, Numeric, and Numarray, through its numpytools module. Although this module still works, we recommend users to use NumPy only. ------------------------------------------------------------------------------- 3. Installation There are several different ways of installing SciTools: - Normal install ([, ... ] means optional) python setup.py install [,--prefix=$PREFIX] This install makes SciTools use Matplotlib as plotting engine, if a a working Matplotlib is found. Otherwise Gnuplot is used (which requires both the Gnuplot program in C and the Python interface Gnuplot.py to be installed). If neither Matplotlib nor Gnuplot is found, Matplotlib is still used as default plotting engine. (The rest of SciTools will work well, of course.) Installing Matplotlib is easy on most platforms: just download the tarball, pack it out, and run python setup.py install. You can explicitly specify the desired plotting engine on the command line, using the --easyviz_backend option: python setup.py install --easyviz_backend gnuplot [,--prefix=$PREFIX] The default plotting engine is specified in the file scitools.cfg in the scitools package directory, and the --easyviz_backend option leads to an automatic edit of the "backend" line in the [easyviz] section of that configuration file. Don't edit the scitools.cfg file manually before installation (use the --easyviz_backend option) because setup.py will override your edits of the easyviz backend. However, all other edits of the configuration file can be edited. For example, the Matplotlib GUI is set to TkAgg (i.e., using Tkinter, which is standard in most Python installations). The GUI can be set to other values, such as Qt4Agg (provided you have Qt4 and a Python interface to it). After SciTools is installed, you may edit the installed version of scitools.cfg, or (better) have your own .scitools.cfg file in your home directory. - Setuptools using eggs First build the egg with the following command python setupegg.py [, egg_info --tag-svn-revision ] bdist_egg The --easyviz_backend option can be used, as described above, to change the default plotting engine. Then install the created egg using easy_install easy_install [, --prefix=$PREFIX] dist/Scitools-0.7-py2.6.egg (Version numbers of SciTools and Python in this filename may vary.) - Manual installation Put the lib subdirectory in a directory contained in PYTHONPATH, and the bin subdirectory in a directory contained in PATH. (This gives access to the directories for scitools, easyviz, etc.) Edit the scitools.cfg file to set the desired default plotting engine (look for the "backend =" line in the [easyviz] section). - Debian/Ubuntu packages If you have Debian, or a Debian based platform like Ubuntu, you can do sudo apt-get install python-scitools as SciTools is now a part of Debian. You can also find newer Debian packages for SciTools at googlecode.com. - Extended (not supported anymore) Run build_scitools++.py. This makes a new directory build/scitools++ that you can move to any convenient place. scitools++ contains scitools plus some standard Python modules like Gnuplot, IPython, epydoc, etc. Put scitools++/lib in PYTHONPATH and scitools++/bin in PATH. Or you may run scitools++/setup.py to install scitools++ in the official installation directories on your system. ------------------------------------------------------------------------------- 4. Configuration File The behavior of many parts of SciTools and in particular the subpackage Easyviz (for plotting) can be controlled in a configuration file. Please read the subsection "Setting Parameters in the Configuration File" under the section "Advanced Easyviz Topics" in the Easyviz tutorial (pydoc scitools.easyviz will show the tutorial). In particular, if you use Matplotlib as the default plotting engine, you may want to turn on the use of LaTeX for rendering legends, titles, and numbers. By default, LaTeX is turned off when SciTools is installed. It is easy to change this by locating the scitools.cfg file in the folder where the SciTools package is installed and edit the line with text.usetex in the [matplotlib] section of this file. A better solution is to copy the system scitools.cfg file to .scitools.cfg in your home folder and edit that file. You can also change the GUI used by Matplotlib. Users who do not apply Matplotlib for plotting will seldom need to edit the configuration file. ------------------------------------------------------------------------------- 5. License SciTools is licensed under the new BSD license, see the LICENSE file. Lumpy.py and Gui.py are licensed under GPL, however, permission is granted by Allen Downey to include these under a BSD license. ------------------------------------------------------------------------------- 6. Credits SciTools was initially mainly developed by Hans Petter Langtangen for his book "Python Scripting for Computational Science" (Springer, 1st edition 2003, 3rd edition 2009). The Easyviz package was mainly developed by Johannes H. Ring . Johannes H. Ring has been the principal maintainer of SciTools. Some modules included in SciTools are written by others: Allen B. Downey wrote Lumpy.py and Gui.py Imri Goldberg wrote aplotter.py Fred L. Drake, Jr. wrote pprint2.py Gael Varoquaux wrote pyreport Code contributors include: Rolv E. Bredesen Joachim B. Haga Mario Pernici Ilmar Wilbers Arve Knudsen ------------------------------------------------------------------------------- 7. Contact Comments, suggestions, bug fixes should be sent to scitools@googlegroups.com The latest release of SciTools can be obtained from http://scitools.googlecode.com while the latest Subversion revision can be obtained either anonymously (for non-members) by svn co http://scitools.googlecode.com/svn/trunk/ scitools while SciTools members should use svn co https://scitools.googlecode.com/svn/trunk/ scitools --username USERNAME See http://code.google.com/p/scitools/source/checkout for details. scitools-0.9.0/bin/scitools0000755000000000000000000005737511770270446014073 0ustar 00000000000000#!/usr/bin/env python legal_programs = ['subst', 'replace', 'rename', 'regression', 'profiler', 'ps2mpeg', 'floatdiff', 'file2interactive', 'movie', 'pyreport', ] __doc__ = \ """ The scitools script takes a command and runs a corresponding utility. The available commands are listed below. file2interactive: Utility for taking a set of Python statements in a file and creating the corresponding interactive Python shell session. floatdiff: Script for examining differences in regression tests involving floating-point numbers. Used in [1]. regression: Simple front-end script to the scitools.Regression module. Used in [1]. ps2mpeg: Utility for turning a set of PostScript files into an MPEG movie, using mpeg_encode or ppmtompeg. profiler: Script for simplifying the execution of Python's profiling tools. Used in [1]. rename: Script for renaming a set of files by substituting one string or regular expression with another. subst: Script for subsituting a phrase by another in a set of files. Accepts regular expressions. Treated in [1]. replace: Script for subsituting a phrase by another in a set of files. Does not use regular expressions, just plain text (well suited for substituting text with much use of backslashes, curly braces, and other special characters in regular expressions (e.g., LaTeX text). movie: Script for creating a movie file from a sequence of image files (frames). By default an HTML file for displaying the image (PNG) files are made. pyreport: Processes a Python script and pretty prints the results using LateX. If the script uses show() commands (from scitools.easyviz) they are caught by pyreport and the resulting graphs are inserted in the output pdf. Comments lines starting with \"#!\" are interpreted as rst lines and pretty printed accordingly in the pdf. Examples: 1. Substitute "compute_X(" calls, where X is any name, by "calculate_X(" in a series of files code*.py: scitools subst 'compute_(.+?)\(' 'calculate_\g<1>(' code*.py Options -s, -m and -x can be issued to turn on pattern matching modifies (regular expression flags): re.S/re.DOTALL, re.m/re.MULTILINE and re.X/re.VERBOSE, respectively. Alternatively, using replace, but without regex groups: scitools replace "compute_X(" "calculate_X" 2. Rename files with names like tmp_bergen_set15060.dat tmp_oslo_set31897.dat tmp_stavanger_set21864.dat tmp_trondheim_set15358.dat to files with names like set_15060_bergen.dat set_15358_trondheim.dat set_21864_stavanger.dat set_31897_oslo.dat scitools rename 'tmp_([a-z]+)_set(\d+)' 'set_\g<2>_\g<1>' tmp_*.dat A simple further rename is to replace the .dat extension with .data: scitools rename dat data set*.dat 3. Create an interactive session from a file with a list of statements: Unix> cat tmp2.py import os origdir = os.getcwd() os.chdir(os.pardir) os.getcwd() origdir Unix> scitools file2interactive tmp2.py >>> import os >>> origdir = os.getcwd() >>> os.chdir(os.pardir) >>> os.getcwd() '/Volumes/Shared/main/vc/scitools' >>> origdir '/Volumes/Shared/main/vc/scitools/test' [1] H. P. Langtangen: Python Scripting for Computational Science. Third edition, second printing. Springer, 2009. """ import os, re, sys, shutil, glob def wildcard_notation(files): """ On Unix, a command-line argument like *.py is expanded by the shell. This is not done on Windows, where we must use glob.glob inside Python. This function provides a uniform solution. """ if isinstance(files, basestring): files = [files] # ensure list if sys.platform[:3] == 'win': import glob, operator filelist = [glob.glob(arg) for arg in files] files = reduce(operator.add, filelist) # flatten return files def usage_movie(): print """Usage: scitools movie output_file=mymovie.html fps=4 file*.png scitools movie encoder=convert output_file=mymovie.gif fps=4 file*.jpg scitools movie encoder=ffmpeg output_file=mymovie.avi fps=4 file*.jpg scitools movie encoder=ffmpeg output_file=mymovie.mpeg fps=4 file*.jpg scitools movie encoder=ppmtompeg output_file=mymovie.mpeg fps=24 file*.png """ def main_movie(): if len(sys.argv) < 3: print usage_movie() sys.exit(1) # Search for arguments to movie function legal_kwargs = ['output_file', 'overwrite_output', 'quiet', 'cleanup', 'force_conversion', 'input_file', 'encoder', 'vbitrate', 'vbuffer', 'fps', 'vcodec', 'qscale', 'qmin', 'qmax', 'iqscale', 'pqscale', 'bqscale', 'pattern', 'size', 'aspect', 'preferred_package', 'gop_size'] kw_string_args = ['output_file', 'encoder', 'pattern', 'preferred_package', 'vcodec', 'vbuffer',] kwargs = [] kws = [] for i, arg in enumerate(sys.argv[2:]): if '=' in arg: kw = arg.split('=')[0].strip() if kw in legal_kwargs: # Special case: kw='value', else arg is kw=value if kw in kw_string_args: arg = kw + '=' + repr(arg.split('=')[1]) kwargs.append(arg) kws.append(kw) else: print '%s: unknown argument to movie' else: break if not 'encoder' in kws: kwargs.append('encoder="html"') # default files = wildcard_notation(sys.argv[i+2:]) import scitools.easyviz call = 'scitools.easyviz.movie(input_files=%s, %s)' % \ (str(files), ', '.join(kwargs)) #print call eval(call) def usage_replace(): print 'Usage: scitools replace from-text to-text file1 file2 ...' def main_replace(): if len(sys.argv) < 4: usage_replace() sys.exit(1) from_text = sys.argv[2] to_text = sys.argv[3] files = wildcard_notation(sys.argv[4:]) for filename in files: f = open(filename, 'r') text = f.read() f.close() if from_text in text: backup_filename = filename + '.old~~' shutil.copy(filename, backup_filename) print 'replacing %s by %s in' % (from_text, to_text), filename text = text.replace(from_text, to_text) f = open(filename, 'w') f.write(text) f.close() def usage_subst(): print 'Usage: scitools subst [-s -m -x --restore] pattern '\ 'replacement file1 file2 file3 ...' print '--restore brings back the backup files' print '-s is the re.DOTALL or re.S modifier' print '-m is the re.MULTILINE or re.M modifier' print '-x is the re.VERBODE or re.X modifier' from scitools.misc import subst def main_subst(): if len(sys.argv) < 4: usage_subst() sys.exit(1) from getopt import getopt optlist, args = getopt(sys.argv[2:], 'smx', ['restore']) restore = False pmm = 0 # pattern matching modifiers (re.compile flags) for opt, value in optlist: if opt in ('-s',): if not pmm: pmm = re.DOTALL else: pmm = pmm|re.DOTALL if opt in ('-m',): if not pmm: pmm = re.MULTILINE else: pmm = pmm|re.MULTILINE if opt in ('-x',): if not pmm: pmm = re.VERBOSE else: pmm = pmm|re.VERBOSE if opt in ('--restore',): restore = True if restore: for oldfile in args: newfile = re.sub(r'\.old~$', '', oldfile) if not os.path.isfile(oldfile): print '%s is not a file!' % oldfile; continue os.rename(oldfile, newfile) print 'restoring %s as %s' % (oldfile,newfile) else: pattern = args[0]; replacement = args[1] s = subst(pattern, replacement, wildcard_notation(args[2:]), pmm) print s # print info about substitutions def usage_rename(): print 'Usage: scitools rename from_regex to_regex file1 file2 ...' doc_rename = """ Rename a set of files using the power of regular expressions. Example: Suppose we have a set of files with names tmp_bergen_set15060.dat tmp_oslo_set31897.dat tmp_stavanger_set21864.dat tmp_trondheim_set15358.dat and that we want to rename these to set_15060_bergen.dat set_15358_trondheim.dat set_21864_stavanger.dat set_31897_oslo.dat The following command, utilizing regular expressions with two groups, performs the task: scitools rename 'tmp_([a-z]+)_set(\d+)' 'set_\g<2>_\g<1>' tmp_*.dat Copies of the old files are taken for backup and given an extension .old~~: tmp_bergen_set15060.dat.old~~ tmp_oslo_set31897.dat.old~~ tmp_stavanger_set21864.dat.old~~ tmp_trondheim_set15358.dat.old~~ Supply the command-line argument --no-backup to avoid backing up files (might increase speed when renaming large files). """ def rename(from_regex, to_regex, filenames, backup=True): from_regex_c = re.compile(from_regex) for filename in filenames: if from_regex_c.search(filename): newname = from_regex_c.sub(to_regex, filename) if backup: if os.path.isfile(filename): shutil.copy(filename, filename + '.old~~') elif os.path.isdir(filename): shutil.copytree(filename, filename + '.old~~') os.rename(filename, newname) print '%s renamed to %s' % (filename, newname) def main_rename(): if len(sys.argv) < 4: usage_rename() print doc_rename sys.exit(1) if '--no-backup' in sys.argv: backup = False sys.argv.remove('--no-backup') else: backup = True from_regex, to_regex = sys.argv[2], sys.argv[3] files = wildcard_notation(sys.argv[4:]) rename(from_regex, to_regex, files, backup) def usage_file2interactive(): print 'Usage: scitools file2interactive filename [human]' doc_file2interactive = """ Execute a Python script and present output such that it seems that each statement is executed in the interactive interpreter. A funny feature is to add 'human' as a second command-line argument: it then seems that the text in the interpreter is written by a human, char by char. This can be used to fake typing in an interactive shell ;-) Troubleshooting: Each multi-line command must be ended by a pure '\n' line. If there is more whitespace, the interpreter waits for additional lines and the command is corrupted. For example, when defining a class, blank lines between the methods must have some whitespace to ensure continuation, but the line below the class definition must be empty so the command is ended. """ from code import InteractiveInterpreter # see InteractiveConsole for example on using InteractiveInterpreter import sys, random, time def printline(prompt, line, human_typing=0): """ Print a line with Python code in the interpreter. If human_typing is not 0, the line will be printed as if a human types it. human_typing=1: characters are written with a random delay, human_typing=2: characters are written when the user hits any character on the keyboard (not yet implemented). """ # human_typing=2 can make use of a getch()-like function from # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 # or # http://www.freenetpages.co.uk/hp/alan.gauld/tutevent.htm if not human_typing: print prompt, line else: print prompt, # type one and one character with a random sleep in between max_delay = 0.6 # seconds for char in line: delay = random.uniform(0, max_delay) time.sleep(delay) sys.stdout.write(char) sys.stdout.flush() dummy = raw_input('') class RunFileInInterpreter(InteractiveInterpreter): def __init__(self, locals=None): self._ip = InteractiveInterpreter(locals=locals) def run(self, source_code): buffer = [] # collect lines that belong together prompt = '>>>' for line in source_code.split('\n'): #line = line.rstrip() # indicates wrong end of buffer list printline(prompt, line, human_typing) buffer.append(line) source = '\n'.join(buffer) try: need_more = self._ip.runsource(source) except (SyntaxError,OverflowError), e: print self._ip.showsyntaxerror() sys.exit(1) if need_more: #print 'need more..., source=\n', source prompt = '...' continue # proceed with new line else: #print 'successful execution of final source=\n',source prompt = '>>>' buffer = [] def file2interactive_test(): # just provide some demo code for testing: _sc = """ a = 1 def f(x): x = x + 2 return x b = f(2) dir() print 'correct?', b == 4 """ return _sc def main_file2interactive(): try: filename = sys.argv[2] except: usage_file2interactive() print doc_file2interactive sys.exit(1) global human_typing human_typing = 0 # global variable try: if sys.argv[3] == 'human': human_typing = 1 except: pass # define the complete source code file as _sc string: if filename == 'demo': _sc = file2interactive_test() else: _sc = open(filename, 'r').read() RunFileInInterpreter(locals()).run(_sc) def usage_profiler(): print "Usage: scitools profiler program [program options]" def main_profiler(): try: program = sys.argv[2] except: usage_profiler() sys.exit(1) resfile = '.tmp.profile' # add the directory of the script to sys.path in case the script # employs local modules from that directory: sys.path.insert(0, os.path.dirname(program)) program_options = ' '.join(["%s" % arg for arg in sys.argv[3:]]) # The cProfile or profile module will be used, depending on # the value of the environment variable PYPROFILE # (default is cProfile, the fastest of them) profiler_module = os.environ.get('PYPROFILE', 'cProfile') if profiler_module == 'profile': try: import profile except ImportError: raise ImportError('module profile was not found - must be installed') elif profiler_module == 'cProfile': try: import cProfile except ImportError: raise ImportError('module cProfile was not found - must be installed') cmd = 'python -m %(profiler_module)s -o %(resfile)s %(program)s %(program_options)s' % vars() print 'Running\n ', cmd failure = os.system(cmd) if failure: print 'Could not run\n', cmd sys.exit(1) try: import pstats except ImportError: raise ImportError('module pstats was not found - must be installed') p = pstats.Stats(resfile) #p.sort_stats('cumulative') p.sort_stats('time') p.print_stats(30) os.remove('.tmp.profile') def usage_ps2mpeg(): print "Usage: scitools ps2mpeg [-nocrop] frame0000.ps frame0001.ps ..."\ " [movie.mpeg] (series of ps files to be included in an MPEG "\ " movie movie.mpeg)" def main_ps2mpeg(): if len(sys.argv) < 3: usage_ps2mpeg() sys.exit(1) # check that we have mpeg_encode or ppmtompeg: from scitools.misc import findprograms if not findprograms('mpeg_encode') and not findprograms('ppmtompeg'): print """ ps2mpeg.py requires the mpeg_encode MPEG encoder program. Please install mpeg_encode, see URL: http://bmrc.berkeley.edu/frame/research/mpeg/mpeg_encode.html You may also use the ppmtompeg program included in the netpbm package which is available in most distros. """ sys.exit(1) encoder = 'mpeg_encode' if not findprograms(encoder): encoder = 'ppmtompeg' # cropping takes time so we can omit that step: crop = 1 if sys.argv[2] == "-nocrop": crop = 0 del sys.argv[2] # did the user supply a filename for the MPEG file? if sys.argv[-1][-3:] != '.ps' and sys.argv[-1][-4:] != '.eps': mpeg_file = sys.argv[-1] del sys.argv[-1] else: mpeg_file = "movie.mpeg" found = findprograms(('gs', 'convert', encoder), write_message=True) if not found: sys.exit(1) basename = "tmp_"; i = 0 # counter for psfile in sys.argv[2:]: ppmfile = "%s%04d.ppm" % (basename, i) gscmd = "gs -q -dBATCH -dNOPAUSE -sDEVICE=ppm "\ " -sOutputFile=%(ppmfile)s %(psfile)s" % vars() print gscmd failure = os.system(gscmd) if failure: print '....gs failed, jumping to next file...' continue if crop: # crop the image: tmp_ppmfile = ppmfile + "~" os.rename(ppmfile, tmp_ppmfile) os.system("convert -crop 0x0 ppm:%s ppm:%s" % \ (tmp_ppmfile,ppmfile)) # using pnmcrop: # direct std. error to /dev/null and std. output to file: #os.system("pnmcrop %s 2> /dev/null 1> %s" % \ # (tmp_ppmfile,ppmfile)) os.remove(tmp_ppmfile) print "%s transformed via gs to %s (%d Kb)" % \ (psfile,ppmfile,int(os.path.getsize(ppmfile)/1000)) i = i + 1 print 'ps2mpeg made the following ppm files:' for f in glob.glob('%s*.ppm' % basename): print f first_no = "%04d" % 0 # first number in ppmfiles last_no = "%04d" % (len(sys.argv)-3) # last number in ppmfiles mpeg_encode_file = "%s.mpeg_encode-input" % basename f = open(mpeg_encode_file, "w") f.write(""" # # lines can generally be in any order # only exception is the option 'INPUT' which must be followed by input # files in the order in which they must appear, followed by 'END_INPUT' PATTERN I # more compact files result from the following pattern, but xanim does not # work well (only a few of the frames are shown): #PATTERN IBBPBBPBBPBBPBB OUTPUT %(mpeg_file)s # mpeg_encode really only accepts 3 different file formats, but using a # conversion statement it can effectively handle ANY file format # # you must specify whether you will convert to PNM or PPM or YUV format BASE_FILE_FORMAT PPM # the conversion statement # # Each occurrence of '*' will be replaced by the input file # # e.g., if you have a bunch of GIF files, then this might be: # INPUT_CONVERT giftoppm * # # if you have a bunch of files like a.Y a.U a.V, etc., then: # INPUT_CONVERT cat *.Y *.U *.V # # if you are grabbing from laser disc you might have something like # INPUT_CONVERT goto frame *; grabppm # 'INPUT_CONVERT *' means the files are already in the base file format # INPUT_CONVERT * # number of frames in a GOP. # # since each GOP must have at least one I-frame, the encoder will find the # the first I-frame after GOP_SIZE frames to start the next GOP # # later, will add more flexible GOP signalling # GOP_SIZE 30 #GOP_SIZE 6 # number of slices in a frame # # 1 is a good number. another possibility is the number of macroblock rows # (which is the height divided by 16) # SLICES_PER_FRAME 1 # directory to get all input files from (makes this file easier to read) INPUT_DIR . INPUT # '*' is replaced by the numbers 01, 02, 03, 04 # if I instead do [01-11], it would be 01, 02, ..., 09, 10, 11 # if I instead do [1-11], it would be 1, 2, 3, ..., 9, 10, 11 # if I instead do [1-11+3], it would be 1, 4, 7, 10 # the program assumes none of your input files has a name ending in ']' # if you do, too bad!!! # # %(basename)s*.ppm [%(first_no)s-%(last_no)s] # can have more files here if you want...there is no limit on the number # of files END_INPUT # all of the remaining options have to do with the motion search and qscale # FULL or HALF -- must be upper case PIXEL HALF # means +/- this many pixels RANGE 10 # this must be one of {EXHAUSTIVE, SUBSAMPLE, LOGARITHMIC} PSEARCH_ALG LOGARITHMIC # this must be one of {SIMPLE, CROSS2, EXHAUSTIVE} # # note that EXHAUSTIVE is really, really, really slow # BSEARCH_ALG CROSS2 # # these specify the q-scale for I, P, and B frames # (values must be between 1 and 31) # IQSCALE 8 PQSCALE 10 BQSCALE 25 # this must be ORIGINAL or DECODED REFERENCE_FRAME ORIGINAL """ % vars()) f.close() failure = os.system(encoder + " " + mpeg_encode_file) if failure: print '\n\nps2mpeg.py: could not make MPEG movie' else: print "mpeg movie in output file", mpeg_file # remove the generated ppm files: for file in glob.glob("%s*.ppm" % basename): os.remove(file) def usage_regression(): print 'Usage: scitools regression verify|update|template rootdir|filename' def main_regression(): import scitools.Regression try: task = sys.argv[2] except IndexError: usage_regression() sys.exit(1) try: name = sys.argv[3] except IndexError: usage_regression() sys.exit(1) if task == 'verify' or task == 'update': v = scitools.Regression.Verify(root=name, task=task) elif task == 'template': scitools.Regression.verify_file_template(name) else: print "1st command-line argument must be verify, update, or template" def usage_floatdiff(): print "Usage: floatdiff.py file.vd file.rd" def main_floatdiff(): import Tkinter import scitools.Regression root = Tkinter.Tk() #Pmw.initialise(root, fontScheme='pmw1') root.title('intelligent float diff') if len(sys.argv) == 4: if not os.path.isfile(sys.argv[2]): print 'file "%s" does not exist' % sys.argv[2] return if not os.path.isfile(sys.argv[3]): print 'file "%s" does not exist' % sys.argv[3] return fd = scitools.Regression.FloatDiff(root, sys.argv[2], sys.argv[3]) if fd.GUI: root.mainloop() else: usage_floatdiff() def usage_pyreport(): print """Usage: scitools pyreport [options] pythonfile""" doc_pyreport = """ pyreport is a program that runs a Python script and captures its output, compiling it to a pretty report in a pdf or an html file. It can display the output embedded in the code that produced it and can process special comments (literate comments) according to markup languages (rst or LaTeX) to compile a very readable document. Note: This is a modified version of Gael Varoquaux's pyreport that enables the use of scitools.easyviz to do the plotting. The original pyreport can be downloaded from http://gael-varoquaux.info/computers/pyreport/. """ def main_pyreport(): if len(sys.argv) < 3: usage_pyreport() print doc_pyreport sys.exit(1) sys.argv = sys.argv[1:] from scitools.pyreport import pyreport pyreport.commandline_call() if __name__ == '__main__': try: program = sys.argv[1] except IndexError: print '%s: missing first argument, must be help, --help, -h or one of\n%s\n\n' % \ (sys.argv[0], str(legal_programs)[1:-1]) sys.exit(1) if program == 'subst': main_subst() elif program == 'replace': main_replace() elif program == 'rename': main_rename() elif program == 'file2interactive': main_file2interactive() elif program == 'profiler': main_profiler() elif program == 'ps2mpeg': main_ps2mpeg() elif program == 'regression': main_regression() elif program == 'floatdiff': main_floatdiff() elif program == 'movie': main_movie() elif program == 'pyreport': main_pyreport() elif program == 'help' or program == '--help' or program == '-h': for p in legal_programs: exec('usage_%s()' % p) print '\n', __doc__ else: print 'Cannot recognize command', program scitools-0.9.0/doc/man/man1/scitools.1.gz0000644000000000000000000000222211770270446016227 0ustar 00000000000000 hOVn6}WLӇMG[\EnY4+*Iq3[(Hs̅N8K1=B$oeS;ifj>di<"1lZLgt/8[LW^$m"Z^~CG=O֢kΕ.EU6ƒkjq8G-BVXMB*sAJiVf^KX@ Ѓ)`ؠ;8A_fQz>+G*fSa]sU>WEArD`1&Ѣ0X]6 XpkVh]/ܠ?|qjZ FK]%Ş1yW@id#; 6! I OQsAڶZ Gǁb|ŌjBex8Pc\⟖i AxVe׭W Eb4R)ȧʮV[;XQ {΀q}`%?PL7Yw=/-.["m-Ӏ!ChYt;FsMqUy8߄nX/EjF%̾ZR`z +jB~v\* J7թ&8ǤLF();jė8t㠠jv¬S5NJ]$p ՞;`|z:Wp8??\0<A;l){Ɔҙ[C.0`iu/m4i0>Y@2\l=2`h2==Akcn`dWV^P ='VUJ;}e&͋5 ej[ CYY@) D:Teq?WzFC7NOLRj $0O]zyp3VsH TypeError q1 is of wrong type (ndarray). """ scitools-0.9.0/examples/contour_demo.py0000755000000000000000000000224311770270446016406 0ustar 00000000000000#!/usr/bin/env python from scitools.std import * # A simple contour plot of the peaks function: contour(peaks()) figure() # Here we draw 15 red contour lines with double line width: xv, yv = ndgrid(linspace(-3,3,31),linspace(-3,3,31)) values = xv*exp(-xv**2-yv**2) contour(xv, yv, values, 15, 'r', linewidth=2) figure() # Draw contour lines with labels at -2, 0, 2, and 5: values = peaks(xv, yv) contour(xv, yv, values, [-2,0,2,5]) figure() # Here we combine a contour plot with a quiver plot (currently not # working with the Gnuplot backend): x = y = linspace(-2,2,21) xv, yv = ndgrid(x, y, sparse=False) values = sin(xv)*sin(yv)*exp(-xv**2 - xv**2) dx, dy = gradient(values) contour(xv, yv, values, 10, show=False) hold('on') quiver(xv, yv, dx, dy, 2, show=True) hold('off') figure() # Another example: x = linspace(-2,2,201) y = linspace(-1,1,31) xv, yv = ndgrid(x,y) values = sin(3*yv - xv**2 + 1) + cos(2*yv**2 - 2*xv) contour(xv,yv,values,clabels='on') # contour(x,y,values,..) also works figure() # The contourf command draws filled contours: values = peaks(201) contourf(values, 10, caxis=[-20, 20], title='Filled Contour Plot') raw_input('Press Return key to quit: ') scitools-0.9.0/examples/contourslice_demo1.py0000755000000000000000000000176711770270446017521 0ustar 00000000000000#!/usr/bin/env python # Example taken from: # http://www.mathworks.com/access/helpdesk/help/techdoc/ref/contourslice.html from scitools.easyviz import * from time import sleep setp(show=False) x, y, z, v = flow() h = contourslice(x,y,z,v,seq(1,9),[],[0],linspace(-8,2,10)) axis([0,10,-3,3,-3,3]) daspect([1,1,1]) camva(24) camproj('perspective') campos([-3,-15,5]) ax = gca() ax.setp(fgcolor=(1,1,1), bgcolor=(0,0,0)) box('on') view(3) # because camva, camproj, and campos currently not working setp(show=True) show() #hardcopy('tmp_contourslice1a.eps') #hardcopy('tmp_contourslice1a.png') figure() # alternative syntax: h = contourslice(x,y,z,v,seq(1,9),[],[0],linspace(-8,2,10), axis=[0,10,-3,3,-3,3], daspect=[1,1,1], camva=24, camproj='perspective', campos=[-3,-15,5], fgcolor=(1,1,1), bgcolor=(0,0,0), box='on') #hardcopy('tmp_contourslice1b.eps') #hardcopy('tmp_contourslice1b.png') #sleep(3) raw_input('Press Return key to quit: ') scitools-0.9.0/examples/contourslice_demo2.py0000755000000000000000000000152211770270446017507 0ustar 00000000000000#!/usr/bin/env python # Example taken from: # http://www.mathworks.com/access/helpdesk/help/techdoc/visualize/f5-3371.html from scitools.easyviz import * from time import sleep from scipy import io setp(interactive=False) mri = io.loadmat('mri_matlab_v6.mat') D = mri['D'] D = squeeze(D) image_num = 8 x = xlim; y = ylim; # Displaying a 2-D Contour Slice: contourslice(D,[],[],image_num,indexing='xy') axis('ij') xlim(x) ylim(y) daspect([1,1,1]) colormap('default') show() #hardcopy('tmp_contourslice2a.eps') #hardcopy('tmp_contourslice2a.png') figure() BUG = 1 phandles = contourslice(D,[],[],[1,12,19,27-BUG],8,indexing='xy') view(3) axis('tight') #set(phandles,'LineWidth',2) setp(phandles, linewidth=4) show() #sleep(3) raw_input('Press Return key to quit: ') ## hardcopy('tmp_contourslice2b.eps') ## hardcopy('tmp_contourslice2b.png') scitools-0.9.0/examples/demo_pyreport.py0000644000000000000000000000570211770270446016601 0ustar 00000000000000from scipy.integrate import ode # Demo of "scitools pyreport", a modification of the original # pyreport code to work with both matplotlib and scitools.easyviz. # Comment lines starting with #! employ reStructuredText syntax, # which has primitive math support but works well in HTML, # while comment lines starting with #$ employ LaTeX syntax, # which does not work in HTML but looks fine in PDF. #! Demonstrations #! ============== #! #! Run with ``-l -e`` options to turn on LaTeX support. #! ``-t pdf`` gives PDF output while ``-t html`` specifies #! HTML output. The name stem of the output file is specified #! by the ``-o`` option. """ scitools pyreport -l -e -t pdf -o report_mpl -a '0.05 9' demo_pyreport.py scitools pyreport -l -e -t html -o report_mpl -a '0.05 9' demo_pyreport.py scitools pyreport -l -e -t pdf -o report_evz -a '0.05 9 easyviz' demo_pyreport.py scitools pyreport -l -e -t html -o report_evz -a '0.05 9 easyviz' demo_pyreport.py """ #! Solving the logistic equation #! ============================= #! The (scaled) logistic equation reads #! #! .. math:: #! u'(t) = u(1-u), #! #! for :math:`t\in (0,T]` and with initial condition :math:`u(0)=\alpha`. # LaTeX version: #$ The (scaled) logistic equation reads #$ \[ u'(t) = u(1-u), \quad t\in (0,T] \] #$ with initial condition $u(0)=\alpha$. def f(t, u): return u*(1-u) # logistic equation try: alpha = float(sys.argv[1]) except IndexError: alpha = 0.1 # default try: T = float(sys.argv[2]) except IndexError: T = 8 #! We solve the logistic equation using the ``dopri5`` #! solver in ``scipy.integrate.ode``. This is a Dormand-Prince #! adaptive Runge-Kutta method of order 4-5. solver = ode(f) solver.set_integrator('dopri5', atol=1E-6, rtol=1E-4) solver.set_initial_value(alpha, 0) #! The solution is computed at equally spaced time steps #! :math:`t_i=i\Delta t`, with :math:`\Delta t=0.2`, :math:`i=1,2, ...`. #! The integration between :math:`t_i` and :math:`t_{i+1}` applies smaller, #! adaptive time steps, adjusted to meet the prescribed #! tolerances of the solution. # LaTeX version: #! The solution is computed at equally spaced time steps #! $t_i=i\Delta t$, with $\Delta t=0.2$, $i=1,2,3,\ldots$. #! The integration between $t_i$ and $t_{i+1}$ applies smaller, #! adaptive time steps, adjusted to meet the prescribed #! tolerances of the solution. dt = 0.2 # time step u = []; t = [] # store solution and times while solver.successful() and solver.t < T: solver.integrate(solver.t + dt) # current time is in solver.t, current solution in solver.y u.append(solver.y); t.append(solver.t) # Demonstrate plotting with matplotlib or scitools.easyviz plot = 'matplotlib' try: if sys.argv[3] == 'easyviz': plot = 'easyviz' except IndexError: pass if plot == 'matplotlib': import matplotlib.pyplot as plt else: import scitools.std as plt plt.plot(t, u) plt.xlabel('t') plt.ylabel('u') plt.axis([t[0], t[-1], 0, 1.1]) plt.show() scitools-0.9.0/examples/demo_pyreport.sh0000755000000000000000000000050611770270446016563 0ustar 00000000000000#!/bin/sh scitools pyreport -l -e -t pdf -o report_mpl -a '0.05 9' demo_pyreport.py scitools pyreport -l -e -t html -o report_mpl -a '0.05 9' demo_pyreport.py scitools pyreport -l -e -t pdf -o report_evz -a '0.05 9 easyviz' demo_pyreport.py scitools pyreport -l -e -t html -o report_evz -a '0.05 9 easyviz' demo_pyreport.py scitools-0.9.0/examples/fill_demo.py0000755000000000000000000000066611770270446015652 0ustar 00000000000000#!/usr/bin/env python """Examples taken from fill_demo.py and fill_demo2.py in Matplotlib.""" from scitools.std import * t = linspace(0.0, 1.0, 101) s = sin(2*2*pi*t) fill(t, s*exp(-5*t), 'r', grid=True) figure() t = linspace(0.0,3.0,301) s = sin(2*pi*t) c = sin(4*pi*t) fill(t, s, 'b', t, c, 'g', opacity=0.2) raw_input('Press Return key to quit: ') legend('domain1', 'domain2') clf() plot(t,s,legend='a') plot(t,s+2,legend='b') scitools-0.9.0/examples/grab_backend_demo.py0000755000000000000000000001060011770270446017273 0ustar 00000000000000#!/usr/bin/env python """ Demonstration on how to grab the backend after some Easyviz commands and add some backend specific commands. The example is based on the legend_demo.py file from Matplotlib. """ from scitools.std import * a = linspace(0,3,150) b = linspace(0,3,150) c = exp(a) d = c.tolist() d.reverse() d = array(d) setp(interactive=False) plot(a,c,'k--',a,d,'k:',a,c+d,'k') legend('Model length', 'Data length', 'Total message length') ylim([-1,20]) xlabel('Model complexity --->') ylabel('Message length --->') title('Minimum Message Length') show() print "Let us now tune the plot by grabbing the backend." raw_input('Press Return key to continue:') # Grab the backend and fine tune the plot: if backend == 'matplotlib': pyplot = get_backend() ax = pyplot.gca() # Remove tick labels: ax.set_xticklabels([]) ax.set_yticklabels([]) # The arrows in the x and y labels does not look good. Here we use # some LaTeX arrows instead: ax.set_xlabel(r'Model complexity $\longrightarrow$') ax.set_ylabel(r'Message length $\longrightarrow$') # Change legend box location: l = ax.get_legend() l._loc = 9 # upper center (is there a better way to set location?) # Add shadow to legend box: l.shadow = True pyplot.draw() elif backend == 'gnuplot': g = get_backend() # Remove tick labels: g('set xtics ("" 0, "" 0.5, "" 1, "" 1.5, "" 2, "" 2.5, "" 3)') g('set ytics ("" 0, "" 5, "" 10, "" 15, "" 20)') # Change location of legends: g('set key top center') # Create a box around the legends: g('set key box lt -1 lw 1 height 1 width 1') # Make the axes frame nice and thick: g('set border 1+2+4+8+16 linetype -1 linewidth 2') g.replot() elif backend == 'veusz': g = get_backend() # Remove tick labels: g.Set('/page1/graph1/x/TickLabels/hide', True) g.Set('/page1/graph1/y/TickLabels/hide', True) # Turn off minor tick marks: g.Set('/page1/graph1/x/MinorTicks/hide', True) g.Set('/page1/graph1/y/MinorTicks/hide', True) # Change legend box location: g.Set('/page1/graph1/key1/horzPosn', 'centre') g.Set('/page1/graph1/key1/vertPosn', 'top') # Adjust the placement of the title: g.Set('/page1/graph1/label1/xPos', 0.3) g.Set('/page1/graph1/label1/yPos', 1.02) g.window.showNormal() # We could also have done the changes interactively by saving the # session to a native Veusz file (.vsz) and open the file in Veusz: #save('tmp1.vsz') #os.system('veusz tmp1.vsz') elif backend == 'grace': # In Grace we can do the changes interactively in the GUI. pass elif backend == 'matlab': g = get_backend() # Remove tick labels: g.set_(g.gca(), 'XTickLabel', [], 'YTickLabel', [], nout=0) # Change legend location: h = g.findobj('Tag', 'legend', nout=1) # find the legend handle g.set_(h, 'Location', 'North', nout=0) elif backend == 'matlab2': g = get_backend() s = get_script() # Remove tick labels: s += "set(gca, 'XTickLabel', [], 'YTickLabel', [])\n" # Change legend location: s += "set(findobj('Tag', 'legend'), 'Location', 'North')\n" # Save the Matlab commands to a Matlab .m file: save('tmp1.m') # We can now open this file in Matlab (if Matlab is available): #os.system('matlab -r tmp1') elif backend == 'pyx': # There is currently no way to change properties in the PyX backend # after having made the plot. pass elif backend == 'blt': pass print "Now we store a hardcopy of the tuned plot." raw_input('Press Return key to continue:') #hardcopy('grab_backend1.eps') # Will destroy all changes! #hardcopy('grab_backend1.png') # Will destroy all changes! # We have made changes in the backend directly and a call to hardcopy in # Easyviz would normally destroy all these changes. However, setting the # keyword argument replot to False in the hardcopy function will make sure # that the changes are not destroyed: if backend == 'gnuplot': # Unfortunately, setting replot to False does not currently work in the # Gnuplot backend. So, in this case we must use the hardcopy command from # the Gnuplot.py module: g.hardcopy(filename='tmp_grab_backend1.eps', terminal='postscript', mode='eps') g.hardcopy(filename='tmp_grab_backend1.png', terminal='png') else: savefig('grab_backend1.eps', replot=False) if not backend == 'pyx': savefig('grab_backend1.png', replot=False) scitools-0.9.0/examples/grab_backend_matplotlib_ex1.py0000755000000000000000000000416611770270446021305 0ustar 00000000000000#!/usr/bin/env python """Configure a plot by grabbing the matplotlib backend This example demonstrates the use of setp and getp, which is a typical matlab/pyplot way to set properties of objects setp(handler, 'something', value) or getp(handler [, 'something']) will call set_something or get_something from handler getp with only the handler argument will show full property list """ __author__ = 'Rolv Erlend Bredesen