PyDSTool temporary web pages

 


 

Getting Started

 

  1. Installation and setup
    1. Python version and library dependencies
      1. PyDSTool 0.84 and later
      2. PyDSTool 0.83.3 and earlier
      3. For C-based integrator and AUTO support (optional)
        1. 64-bit machines
      4. Windows-specific information
        1. Vista
      5. Mac-specific information
      6. Other library issues
    2. Integrated Development Environment (IDE)
    3. Installing PyDSTool
    4. Setting up on Linux / OS X
      1. Python installation quirks for C/Fortran-based integrators (Dopri and Radau)
        1. 64 bit Mac specifics
      2. Path
      3. Linear algebra library problems with SciPy
      4. Configuring MatPlotLib for interactive plotting
      5. Supporting C-code integrators
        1. Install SWIG
        2. Compiler problems with SciPy
    5. Setting up on Win32
      1. Path
      2. Linear algebra library issues
      3. Configuring MatPlotLib for interactive plotting
      4. Supporting C-code integrators
        1. MinGW (or Cygwin) gcc
        2. Create libpython23.a (for Python 2.3 and earlier only)
        3. Tweak distutils (for Python 2.2 and earlier only)
        4. Install SWIG
        5. Compiler availability
  2. Compatibility between PyDSTool 0.88 saved data files and earlier versions
  3. Running the tests and examples
  4. First steps and basic orientation
    1. Assumed background
    2. Introspection
    3. Common API features of objects
    4. Running and understanding a test script
      1. An interpolated data table
      2. A simple ODE
    5. Tutorial and next steps

 


 

 

1. Installation and setup

1.1. Python version and library dependencies

Further information about the packages mentioned here can be found from the page: [WWW] http://wiki.python.org/moin/NumericAndScientific

1.1.1. PyDSTool 0.84 and later

PyDSTool requires Python version 2.4--2.7 ([WWW] download it here). It is not yet ported to Python 3.x. I will fix this in due course. Multiple versions of python can usually be installed on a machine concurrently.

PyDSTool relies on the following packages, which can be installed in this order over Python before using PyDSTool:

Optional packages:

1.1.2. PyDSTool 0.83.3 and earlier

This old version of PyDSTool requires Python version 2.3.5 or 2.4 ([WWW] download it here). Users have reported difficulties with some components of PyDSTool working properly with Python 2.3.4 (which has inferior support for pickling), and so we now recommend one of the 2.3.5 releases.

PyDSTool relies on the following packages, which can be installed in this order over Python 2.3.5 before using PyDSTool:

1.1.3. For C-based integrator and AUTO support (optional)

You can try PyDSTool without installing these additional packages, but you will be able to use only the scipy-provided VODE integrator. It is at least an order of magnitude slower to solve ODEs with this integrator.

1.1.3.1. 64-bit machines

If you are using a 64 bit machine, the default libraries may be incompatible with the 32 bit code that comes with PyDSTool. For now, it is unresolved whether you will be able to get the legacy C-based integrators to compile correctly in 64-bit mode. In some cases, this is a limitation of how your numpy and python installations themselves. The 0.90 version release of PyDSTool will resolve this if numpy and python are correctly set up. If you have any success in tweaking the code yourself to work on a 64 bit machine, please send me details so that I can incorporate them in future releases.

In the meantime, there are some things you can try. If the Dopri and Radau tests don't run out of the box, try removing the '-m32' flags in the files mentioned in the FAQ that is provided in the PyDSTool root directory. If you are on linux, make sure that the 'dev' version of python is installed, as well as the 32-bit compatible libraries: these may include things like ia32-libs, libc6-i386, and libc6-dev-i386, and a 'build-essential' package (on Ubuntu).

There may also be problems with the compatibility of the compilers that numpy sees by default and those which PyDSTool tries to use. Details of investigating and resolving this for AMD and Intel linux are detailed in these notes.

1.1.4. Windows-specific information

Some people find the all-in-one platform independent distribution for Python from [WWW] ActiveState or [WWW] Enthought preferable. However, installation of the individual components from binary installers is very simple windows, and gives you more control over the versions that will be most compatible with the current PyDSTool version. We strongly recommend installing the packages individually, especially with 64 bit architectures.

For the older version of PyDSTool, the Enthought distribution contains the recommended versions of Python, SciPy, SWIG, MinGW, IPython, among other libraries (which you may not need), but does not contain MatPlotLib. You will have to install those separately. Also (very important!), you will have to retrograde the included Numeric 24.2 (and possibly Numarray) versions simply by running their installers for the above-mentioned recommended versions available at the sites mentioned above. But unless you can't put MinGW and SWIG together yourself, I don't think you'll be in better shape than if you install all the recommended versions individually. I ended up with the same pickling error as Python 2.3.4 gave me when I tried installing with Enthought, so I don't really recommend this route. If you get it work and have any advice, please let me know so that I can update this information.

1.1.4.1. Vista (and possibly Windows 7)

You must remove Vista's User Account Control before installing any of the python core and library software, otherwise you will get confusing error messages claiming that libraries are not present when you attempt to import them.

  1. Click Start, and then click Control Panel.

  2. In Control Panel, click User Accounts.

  3. In the User Accounts window, click User Accounts.

  4. In the User Accounts tasks window, click Turn User Account Control on or off.

  5. If UAC is currently configured in Admin Approval Mode, the User Account Control message appears. Click Continue.

  6. Clear the Use User Account Control (UAC) to help protect your computer check box, and then click OK.

  7. Click Restart Now to apply the change right away, or click Restart Later and close the User Accounts tasks window.

It might be the case that you can switch this back on once every package that you want (numpy, scipy, etc.) has been installed. I'm not certain, I don't use Vista.

You may also have to do this add the python folder installation (e.g. C:\python27) to the PATH environment variable:

  1. First go to the Windows button, and open control panel. You will need the classic view which is in the upper left hand corner.

  2. Click the System icon.

  3. Click on the Advanced system settings which is in the upper left hand corner.

  4. Once this opens, click the Advanced tab.

    1. Click the Environment Variables button.

    • b. In the second box labeled System variables, scroll down to the variable called Path and double click on this.

      c. You will need to add some text to this box. NOTE: Do not delete what is already there!! Add C:\Python27; to the front of the existing string. Then press Ok and its ready to go. It should look something like C:\Python27;%\...........

      d. Some people have reported that they need to put the C:\Python27 in double quotes... i.e. "C:\Python27";

There are known problems with the PyWin32 libraries on Windows Vista / 7 which can make using python IDE functionality and graphics through IPython or PyScripter problematic.

Additionally, Python's distutils has had some problems building extensions for the C-based integrators if you use path names that include spaces. I don't know if these problems have gone away for the latest Python versions, but it is hard to patch distutils to fix this, and you would be better off changing your filespace to avoid spaces in filenames.

1.1.5. Mac-specific information

First, you will need to have installed XCode on your Mac. There is an installation disk for "Developer Tools" that comes with your Mac. You can install it from there. The very latest version is not important. We recommend using [WWW] fink to install Python and the related packages. (Numpy, etc. are not available through Macports.) Install the Fink binary and run it. Fink will then create a /sw directory where everything will be installed. You should ignore the python system in Framework because it's hard to configure and adapt that to our needs. The two are fine co-existing, but you will just need to update your path and alisases so that the fink-installed version is default. To install with fink, I recommend the command line interface (but FinkCommander is also available). In a terminal window:

$ fink configure

in which you must select the use of the "unstable" branch of packages in order to get access to numpy, etc. This is not sketchy in the way that it sounds! Then run

$ fink selfupdate

which may take a LONG time to complete. Then run

$ fink index
$ fink scanpackages
$ fink install scipy-py27
$ fink install matplotlib-py27
$ fink install swig

where the last package, SWIG, is optional, but necessary to run the C-based integrators Dopri and Radau. Lastly, see the additional set-up notes below for OS X / Linuxl.

For installing the older version of PyDSTool (0.83.3), dependent package versions are often somewhat older. We have posted .deb files for the important ones [WWW] here.

 

1.1.6. Other library issues

Pylab's MatPlotLib is the 2D graphics library used by PyDSTool at present. MatPlotLib appears to be the de facto standard for 2D graphics in Python, and there is progress in extending this to 3D graphics (see [WWW] mplot3D). It also requires a minimal number of additional libraries to be installed. MatPlotLib has several dependencies, depending on which backend you wish to use with it. You may have to install wxPython, PyGTK (including the development package), GLIB, tkinter, libpng, among others. There are some OS and IDE compatibility issues with the different [WWW] backends, which are discussed further in a sub-section below.

Gnuplot is optional (apparently support for this via a SciPy interface is dwindling, although I think it fills a need), but is recommended to support basic 3-dimensional plotting.

gcc 4.0 has given us problems with g77 support for the Radau C-based integrator (see page Generators), and we recommend using only 3.X versions.

Some parts of PyDSTool can also take advantage of [WWW] Psyco optimization, although this only works for x86 platforms.

 

1.2. Integrated Development Environment (IDE)

We recommend installing the platform-independent [WWW] IPython IDE for PyDSTool, although IDLE on Windows (bundled with Python) works well too, and comes with its own script editor. It may be difficult to make [WWW] PythonWin work with MatPlotLib, depending on the availability of the different graphics back-ends (see platform-specific notes below). Follow the platform-specific instructions later in this page for tweaking MatPlotLib to work with your IDE.

Note that on Windows you will need to install [WWW] ctypes, [WWW] readline, and the [WWW] PyWin32 tools for optimum use of IPython. Latest versions of these tools can be found on SourceForge.

1.3. Installing PyDSTool

The PyDSTool package does not need to be installed per se. You simply unzip it to its target directory (e.g., c:\PyDSTool\). No call to setup (part of the distutils package) is necessary (and you do not have to copy the code to Python's lib\site-packages directory). We aim to provide a setup.py installer in version 0.90.

However, there are several things you may need to do in order to run PyDSTool successfully.

For instance, you will need to update your system's path so that Python can find the package. We now explain how to do this, depending on your platform.

We recommend you run the test scripts of the package dependencies (SciPy, MatPlotLib, etc.) to check that they are OK before running any PyDSTool test scripts (discussed in Section 2). In case you encounter problems, the following sub-sections describe how to configure your system correctly.

1.4. Setting up on Linux / OS X

You will need to edit the $HOME/.profile file to add a variable PYTHONPATH with all the directories leading up to PyDSTool, and a variable PYTHON set to /sw/bin/python2.6. You may also wish to make an alias for python and ipython to point to the versions in this bin directory in case of conflicts with any built-in or previously installed versions of python.

We recommend the GTKagg backend to Matplotlib, which seems to be the most reliable in its interaction with ipython on these platforms.

If you happen to use Gentoo you might find Shai Revzen's page InstallOnGentoo helpful, although Shai has other good advice there for linux systems in general. You will need a backend such as Tkinter for graphics if you don't already have one installed.

You must ensure that you have write permissions in the unzipped PyDSTool folder (a.k.a. "installation directory") for Python to write .pyc files from the .py code. You can do this with the command chmod -R a+rwx PyDSTool.

1.4.1. Python installation quirks for C/Fortran-based integrators (Dopri and Radau)

Depending on your linux flavor, you may need to be add some non-default packages to your python installation to be able to use PyDSTool. For both integrators you must have the '-dev' version of python that includes the header files necessary for distutils to compile extensions using numpy types. You will need a fortran compiler (g77 or gfortran) for Radau to work.

One further quirk is that on Ubuntu Hardy with numpy 1.1 and Python 2.5, cfunc.h was provided in the "wrong" directory and needed to be copied into its parent directory in order that the standard library includes during the gcc calls to build the Dopri and Radau integrators.

1.4.1.1. 64 bit Mac specifics

Leopard and Snow Leopard are nominally 64-bit OS's, but it is common to be installing 32-bit software on these systems. If that is the case (especially packages on fink) you will need some special tweaks for getting Dopri, Radau, and AUTO (via PyCont) to work. See the notes earlier for 64 bit installation issues.

1.4.2. Path

You will need to add the following lines in your shell's rc file so that the Python interpreter knows where to find the PyDSTool package, assuming you installed PyDSTool directly in your home directory.

Using .bashrc

PYTHONPATH=$PYTHONPATH:$HOME/:$HOME/PyDSTool/:$HOME/PyDSTool/tests/
export PYTHONPATH

Using .cshrc

setenv PYTHONPATH $PYTHONPATH:$HOME/:$HOME/PyDSTool:$HOME/PyDSTool/tests/

You may also want to make sure that Python's site-packages directory is included in your path, if it is not set correctly by Python already. e.g. prepend the paths in the above examples with something like /usr/local/lib/python2.4/site-packages:.

You may have to add the following file to your Python installation, in order to instruct Python where to look for your package: /usr/local/lib/python2.4/site-packages/PyDSTool.pth. This file should contain text resembling the following:

$HOME/
$HOME/src/
$HOME/src/PyDSTool/

or whatever your PyDSTool path is. It seems that if you don't explicitly add the parent directories to this file then Python cannot see any the sub-directories.

1.4.3. Linear algebra library problems with SciPy

If the ATLAS libraries have not been properly installed as part of SciPy, you may find that certain of SciPy's linear algebra library functions (those from LAPACK, I believe) will not import. One solution is to remove the ATLAS libraries from the installation sequence of SciPy.

Some linux distributions (e.g. Fedora Core 4) have LAPACK and BLAS rpms in their "Extras" collection. Installation of these (or other ATLAS-free sources) prior to a rebuild of SciPy may make everything work as desired.

Further information can be found at the "Known installation problems" sub-section of the [WWW] SciPy FAQ.

1.4.4. Configuring MatPlotLib for interactive plotting

On a Linux installation with MatPlotLib 0.82 and above the default setup may have problems with interactive plotting. For instance, we had to close the plot window to get back to the python prompt, precluding having more than one plot window open at at time.

To fix this on your system, you might want to change the back-end used for windowing:

1. Download a copy of the .matplotlibrc file provided [WWW] here. You can place this in your home directory's .matplotlib directory, which will now override the built-in default rc file for matplotlib. (On binary-only linux/OSX installations, the default rc file may be in /etc if you really want to edit that).

2. Change the "backend" line to TkAgg.

3. Change the "interactive" line to True.

4. If not using IPython, you might only be able to regain a prompt after plotting by commenting out the line "Tk.mainloop()" in the show function of site-packages/matplotlib/backends/backend_tkagg.py. If you are using a binary-based installation you will not have this option!

See [WWW] this page for more information about interactive plotting. Also see [WWW] this post for a discussion at the comp.lang.python newsgroup.

Mac OS X users: This fix is known to work for TclTk version 8.4.6-2.

Also, making this change fixes a problem with XWindow session forwarding -- now local plotting graphs created on a remote terminal works if you have used ssh -X to login to the remote machine.

Depending on your setup, you may need to remove the final show() statements from your scripts (and our test scripts) in order to have the figures appear "and" return you to the interactive prompt. For instance, I know this is what I needed to do with Python 2.4, matplotlib 0.90 on Windows XP.

1.4.5. Supporting C-code integrators

You do not need to follow these instructions to use the inbuilt (scipy-provided) VODE integrator.

1.4.5.1. Install SWIG

SWIG is a wrapper for C/C++ sources. It allows you to use C/C++ functions and classes from withing Python with a minimum effort.

Download SWIG from [WWW] http://www.swig.org (use macswig for Mac OS/X). Follow the instructions to compile and build the package.

1.4.5.2. Compiler problems with SciPy

PyDStool appears to be compatible only with version 3.X of gcc. We have had problems with the Radau integrator with version 4.0.

If you are expecting to use gcc to compile C code versions of vector fields (e.g. with the Dopri integrator), then you should ensure that the CC variable is set to gcc in the Python installation Makefile

<python_installation_root>/lib/python2.3/config/Makefile

If this is not properly set when you try to activate PyDSTool's Dopri code you may get an error (see the FAQ on the MainProjectPage).

The CC environment variable of your unix shell may also need to be set to gcc (or whatever compiler you wish to be using).

1.5. Setting up on Win32

If you only intend to use native Python/SciPy functionality within PyDSTool, you only need to follow the instructions under the Path and MatPlotLib sub-headings, otherwise to use C-based integrators you should read all of the instructions below.

1.5.1. Path

On a Windows platform, you may have to add the following file to your Python installation, in order to instruct Python where to look for your package: C:\Python-2.3.5\Lib\site-packages\PyDSTool.pth. This file should contain text resembling the following:

C:\\
C:\\Tools\\
C:\\Tools\\PyDSTool\\

or whatever your PyDSTool path is. It seems that if you don't explicitly add the parent directories to this file then Python cannot see any sub-directories of it! If you are using the PythonWin IDE, you can make these changes to the path from the Tools -> Edit Python Path menu.

If you have not done so already, you may also wish to add the path to python.exe to your AUTOEXEC.BAT file and to the Windows Environment Variables (in Control Panel\System) so that python can be run directly on scripts from the command prompt. The paths of MinGW, CygWin, and SWIG will have to be added the same way if you are using those for C-based integrators.

We recommend the IDLE environment for working with PyDSTool in Windows, as it is the most easy to work with MatPlotLib.

1.5.2. Linear algebra library issues

If you install SciPy from binaries then there should be no problem getting the LAPACK and ATLAS libraries to work correctly. If you are compiling from sources you may need to follow the instructions given above for Linux / OS X platforms.

1.5.3. Configuring MatPlotLib for interactive plotting

Make sure you install the [WWW] PythonWin extensions first. See the following links for information on how to configure your system for bug-free interactive graphing with MatPlotLib.

Your matplotlibrc file can probably be found in C:\Python23\share\matplotlib\, otherwise download a copy of the .matplotlibrc file provided [WWW] here, and copy it to that directory (create it if necessary), removing the leading dot in the name (that file was intended for linux)!

The TkAgg back-end is probably the easiest to configure, so choose that one if it's not already selected. Then set the 'interactive' option to True.

MatPlotLib configuration problems will depend on which IDE you choose. We recommend using [WWW] IPython or [WWW] IDLE (with the -n option built into your shortcut -- see below).

Instructions for IDLE:

In the start menu, change the properties for the link to idle from

C:\Python23\pythonw.exe "C:\Python23\Lib\idlelib\idle.pyw"

to

C:\Python23\pythonw.exe "C:\Python23\Lib\idlelib\idle.pyw" "-n"

For IPython:

Beware that the -pylab switch to calling IPython may actually interfere with the correct threading for interactive plotting, even though it is a recommended option on some python guides.

To fix interactive plotting on your system, you might want to change the back-end used for windowing:

1. Download a copy of the matplotlibrc file provided [WWW] here, and put it in your python installation's libs/share directory.

2. Change the "backend" line to TkAgg (unfortunately this option is not compatible with PythonWin, but works with IPython and IDLE on Win32 with the -n option -- see below).

3. Change the "interactive" line to True.

4. If not using IPython, you might only be able to regain a prompt after plotting by commenting out the line "Tk.mainloop()" in the show function of site-packages/matplotlib/backends/backend_tkagg.py.

Now try "import pylab" from the python prompt. If you get an error about a DLL not found, it is most likely msvcp71.dll that is missing from your Windows\System directory, in which case you can download it from a reputable website such as [WWW] http://dll-files.com.

1.5.4. Supporting C-code integrators

You do not need to follow these instructions to use the inbuilt (scipy-provided) VODE integrator.

1.5.4.1. MinGW (or Cygwin) gcc

Next, install MinGW gcc. This is the recommended way to use gcc with PyDSTool on Win32 platforms. There is a version of the MinGW gcc compiler available through Cygwin, but you'll still need to change the compiler name in any scripts you run that use the C integrators (see Compiler Availability subsection below).

At present, the most recent versions of MinGW include versions of gcc that are not compatible with the SciPy runtime libraries. Versions of MinGW before 3.3 are recommended, and the .exe installer for version 3.1 can be downloaded [WWW] here or by an internet search for "MinGW-3.1.0". Other downloads are available at [WWW] http://www.mingw.org. You only need to download the installer for MinGW, which contains the whole compiler, support utilities, documentation, libraries and header files. This gcc compiler runs under Windows and compiled programs are more independent from the runtime system than when using Cygwin gcc (from what I've been told).

Once uncompressed, you should add the \bin directory of MinGW to your path environment variable. (Example : Under Windows 95/98/ME, if you installed MinGW to c:\gcc, you would add SET PATH=c:\gcc\bin;%PATH% to your AUTOEXEC.BAT.)

If installed properly, you should be able to run gcc --version anywhere.

Now, create the file c:\\Python2.5\\Lib\\distutils\\distutils.cfg or the equivalent path for your python installation. It will contain these lines:

[build]
compiler=mingw32
1.5.4.2. Create libpython23.a (for Python 2.3 and earlier only)

""Note, for Python 2.4 or later you do not have to create the corresponding libpython24.a file, it is already present.""

In order for PyDSTool to create Python extensions, as part of using C-based integrators, it needs to link against the Python library. Unfortunately, most Python distributions are provided with Python23.lib, a library in Microsoft Visual C++ format. GCC expects a .a file (libpython23.a to be precise.). Here's how to convert python23.lib to libpython23.a if it is not already present in your C:\python23\libs\ directory:

Download pexport (e.g., from [WWW] Starship). Get Python23.dll (it should be in C:\WINNT\System32\). Run:

pexports python23.dll > python23.def

This will extract all symbols from python23.dll and write them into python23.def. Now run:

dlltool --dllname python23.dll --def python23.def --output-lib libpython23.a

This will create libpython23.a (dlltool is part of MinGW utilities). Copy libpython23.a to C:\python23\libs\ (in the same directory as python23.lib). This trick should work for all Python versions, including future releases of Python. You can also use this trick to convert other libraries.

Advice on other web pages has also recommended copying python23.dll from C:\WINNT\System32\ to your Python libs directory.

1.5.4.3. Tweak distutils (for Python 2.2 and earlier only)

This tweak is necessary with Python 2.2, but it is fixed in 2.3.5 and later. I don't know at which version change in-between these the fix was made. So just in case you need to do it yourself...

Locate build_ext.py in your Python directory (should be somewhere around C:\Python22\Lib\distutils\command\).

Change the following two lines:

#new_sources.append(base + target_ext) # old
new_sources.append(base + '_wrap' + target_ext) # new

#swig_cmd = [swig, "-python", "-dnone", "-ISWIG"] # old
swig_cmd = [swig, "-python"] # new
1.5.4.4. Install SWIG

SWIG is a wrapper for C/C++ sources. It allows you to use C/C++ functions and classes from withing Python with a minimum effort.

Download SWIG binaries for Windows from [WWW] http://www.swig.org, uncompress them and add the SWIG directory to your path in AUTOEXEC.BAT (i.e., the directory where swig.exe is located).

Set these environment variables, usually from the Control Panel\System\Advanced\Environment Variables dialog.

PYTHON_INCLUDE : Set this to the directory that contains python.h PYTHON_LIB : Set this to the python library including path for linking

Example using Python 2.3:

PYTHON_INCLUDE: d:\python23\include
PYTHON_LIB: d:\python23\libs\python23.lib

Also see [WWW] http://www.mingw.org/MinGWiki/index.php/Python%20extensions.

1.5.4.5. Compiler availability

On Win32 platforms, it is assumed that "mingw32" is present in your Python installation. Any use of modules that require compilation in C will require you to be sure that you have a C compiler available and visible to PyDSTool. On Linux-type platforms, this should only require you to not provide a 'compiler' option in the initialization of any such objects, unless you wish to specify a particular compiler.

If you only use Cygwin on a Win32 platforms, you need to specify the compiler option as "cygwin" in initialization of any C-code based Generator. PyDSTool uses the numpy_distutils version of the distutils interface to the gcc compiler, although for Cygwin-based compilation you will need to add this [WWW] cygwinccompiler.py file to your C:\Python23\Lib\site-packages\numpy_distutils\ directory in order to get the Radau integrator to work.

2. Compatibility between PyDSTool 0.88 saved data files and earlier versions

If you are upgrading to PyDSTool 0.88 from an earlier version, and you have previously saved PyDSTool or Scipy data objects, you may be able to still use loadObjects, etc. to load the data. If you install numarray 1.5.2 alongside numpy, this makes the old PyDSTool array classes visible to loadObjects when it tries to recover old data. This installation will not conflict with the numpy namespace if you remember not to import from numarray yourself! Note that this compatibility is not available through the numpy.oldnumeric module.

3. Running the tests and examples

In the directory PyDSTool/tests/ you will find a number of basic tests and examples.

Once you have set up your system you may like to run all the tests in batch mode. This can be done by running the script /tests/run_all_tests.py, e.g. by calling python -i run_all_tests.py from the prompt, in the tests directory. There is a simple option at the top of that file that you may need to edit in order to select whether the external compiler tests should be run (in case you do not have gcc working on your system). By default the script assumes that you have gcc working.

Note that on some platforms you will see an error report when the script tries to automatically close graph windows, to the effect of:

Fatal Python error: PyEval_RestoreThread: NULL tstate.

This error can be ignored. Depending on the settings for your matplotlib installation, you may also (a) get a slew of warnings at end of each test script, and (b) need to close any plot windows yourself in order to proceed to the next test. The batch script should report any errors that you get from the test scripts if they fail, in which case please let us know so that we can address the problem.

A few of the tests depend on files already having been created by other tests, so read the preamble of the files first if you wish to run them individually. Some of the scripts are rather substantial examples of mini-projects, and may take a long time to run and produce a lot of output. In most cases, the scripts themselves provide instruction on basic PyDSTool features and the screen output may simulate live interactions at the prompt.

The default compiler for PyDSTool in Windows is assumed to be MinGW, so if you are running Cygwin instead then you will need to add the keyword compiler='cygwin' to all initializations of C-based integrators (Dopri and Radau) in order for them to correctly access gcc through Cygwin.

Note that the most problematic issue seems to be running g77 as part of the Radau integrator's setup. If you see g77 compiler errors as part of these tests then please let us know what the problem is and we'll try to help you figure it out. You may like to remove those scripts from the list to execute in run_all_tests.py or use Dopri instead (where possible).

4. First steps and basic orientation

4.1. Assumed background

In this section we will assume that you have set up PyDSTool successfully, and that you are already familiar with using Python, SciPy, and Numeric. Tutorials on these can be found at [WWW] http://www.python.org and [WWW] http://www.scipy.org/SciPy_Tutorial and [WWW] http://homes.esat.kuleuven.be/~python/doc/numpy/array.html.

If you are used to an environment such as Matlab rather than Python, you might like to consult this page about [WWW] NumPy for Matlab users.

4.2. Introspection

The most helpful Python feature available during an interactive PyDSTool session is introspection. There is a great article on this in the PythonResources section. Typing dir(<object_name>) will list the method and attribute names associated with that object. type(<name>) will tell you what type is associated with that name, so that you can understand how to use it.

Most PyDSTool objects have the method info, which provides various levels of detail depending on the optional "verbose level" argument. The default value for this level is usually 0, but is sometimes 1. Some objects provide even more detailed information at level 2. (For PyDSTool objects, typing help(<object_name>) is equivalent to printing the results from the info method called with its default verbose level.)

For instance, suppose we have a Pointset object p in memory.

 

>>> print p.info(0)
Pointset
>>> print p.info(1)
Pointset
Independent variable:
t:  [ 0.  1.  2.  3.]
Coordinates:
x0:  [ 4.456    4.11103  7.3431   5.443  ]
x1:  [-1.00336000e+001 -5.60000000e-001 -3.23221000e+000 -1.00000000e-002]
x2:  [ 300000.    4000.  330000.  280000.]

 

PyDSTool provides the function who, which works in a similar way to the Matlab function of the same name. This function returns information about all the PyDSTool objects currently defined. The optional keyword argument verboselevel selects the level of detail that will be displayed about each object, via the objects' info methods. An optional typelist list of PyDSTool types makes who return only objects of those types. The general-purpose pretty printer function info is also useful to display the contents of objects and dictionaries when they do not have a dedicated info method.

4.3. Common API features of objects

Not all objects possess all of the following, depending on their appropriateness. Names followed by braces are methods, otherwise they are attributes.

The warning and error attributes are often available in "pretty-printed" form from an object's showWarnings or showErrors methods. Errors and warnings generally accumulate in the object on repeated usage of the object, and may be cleared using the clearWarnings and clearErrors methods. (The object.info method may or may not give different information to a info(object) function call.)

4.4. Running and understanding a test script

cd PyDSTool/tests
python -i interp_vode_test.py

The principal import statement in this script is from PyDSTool import *, from which most of the names from scipy, numarray, and math, become available without prefixing, in addition to the core PyDSTool names.

4.4.1. An interpolated data table

The first section of code in this test creates a "trajectory" from a small interpolated data table.

 

print '-------- Test: InterpolateTable'
xnames = ['x1', 'x2']
timeData = array([0, 11, 20])
x1data = array([10.2, -1.4, 4.1])
x2data = array([0.1, 0.01, 0.4])
print "names for variables: xnames = ", xnames
print "timeData = ", timeData
print "x1data = ", x1data
print "x2data = ", x2data
xData = makeDataDict(xnames, [x1data, x2data])

 

Here, we make use of the makeDataDict() utility function exported from utils.py to create a dictionary of "name: array" key-value pair mappings. This is the primary way in which PyDSTool becomes "index free" (see above). This dictionary is passed to the initialization method of a Generator (See page Generators) sub-class known as InterpolateTable, and the returned object (fully initialized) is returned and assigned to the variable interptable.

 

DSargs = args(tdata=timeData, ics=xData, name='interp')
interptable = Generator.InterpolateTable(DSargs)
itabletraj = interptable.compute('interp')

 

In this simple example, only three arguments are needed to initialize the interpolated table. Several other parameters, in their omission, were given default values. Generally, many parameters may need to be given in order to initialize PyDSTool objects. To avoid long calling sequences at object creation, and having to remember the correct order of arguments to pass, PyDSTool makes use of the key-value form of argument passing, whereby the keys and values constitute an unordered dictionary or args object that is passed as the sole argument to an object's initialization method.

There are several ways in which the trajectory defined by the table can be accessed:

 

>>> interptable.variables['x1'](0.4)
9.77818181818
>>> itabletraj(11, 'x1')  #   preferred syntax for individual values
-1.4
>>> itabletraj(11)  # returns a Point
x1:  -1.4
x2:  0.01
>>> itabletraj(11, ['x2','x1'])  # returns a Point
x1:  -1.4
x2:  0.01

 

4.4.2. A simple ODE

The subsequent code in this test file defines an ODE. It is intended to show off features of its specification syntax and usage of PyDSTool, rather than representing anything mathematically meaningful.

 

print '-------- Test: ODE system'

wfn_str = '100 - (1 + a)*w*heav(0.2-sin(t+1))-2*itable - k*auxval1(t, w)*auxval2(y)'
yfn_str = '50 - (w/100)*y'
auxfndict = {'auxval1': (['t', 'x'], 'if(x>100,2*cos(10*t/pi),-0.5)'),
           'auxval2': (['x'], 'x/2')}

 

These lines create string representations of the right-hand sides of the two-dimensional ODE, and defines two auxiliary functions for use in those specifications. The list of argument names in the first 2-tuple entry of an auxiliary function definition provides information about the calling sequence of that function.

In the first specification, we use the heaviside function, the sine function, a reference to an autonomous external input 'itable' (see below), and two 'auxiliary' functions 'auxval1' and 'auxval2'. Here, we also use an alternative, more convenient, form for providing the arguments to the Generator.

 

DSargs = args(name='ODEtest')
DSargs.tdomain = [0,10]
DSargs.pars = {'k':1, 'a':2}
DSargs.inputs = {'itable' : itabletraj.variables['x1']}
DSargs.varspecs = {'w': wfn_str, 'y': yfn_str}
DSargs.fnspecs = auxfndict
DSargs.algparams = {'init_step' :0.02, 'strictopt':False}
DSargs.ics = {'w':30.0, 'y': 80}

testODE = Generator.Vode_ODEsystem(DSargs)

 

This code builds the initialization arguments of the ODE system in the argument structure DSargs (which behaves just like a dictionary except that at initialization you can include some argument definitions by keyword). An advantage of building DSargs separately from the call to the initialization method of a class is that the set-up information can be re-used, or queried later. The VODE class is entirely implemented in Python -- we will look at a C implementation of a numerical integrator later.

Notice that an autonomous, external input is provided to the RHS of this system from the previously defined interpolation table's trajectory.

The next thing to do is compute a trajectory using the new testODE object.

 

print 'Integrating...'
start = clock()
testtraj = testODE.compute('test')
print '  ... finished in %.3f seconds.\n' % (clock()-start)

 

This code segment also demonstrates how to time operations. (We imported the module "time" in the header.) Note that initial conditions for the integrator are given by the 'ics' key, and the initial time is assumed to be zero unless explicitly set using the key 'tdata'.

We may now introspect the 'testtraj' object to investigate its properties, using the object's info() method and the inbuilt function dir(). (For attributes info() gives much more useful output than the basic inbuilt call to dir(), but does not indicate the object's available methods.)

 

>>> dir(testtraj)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', '_name_ix_map', 'checklevel', 'coordtype', 'copy', 'depdomain', 'dimension', 'globalt0', 'indepdomain', 'indepvarname', 'indepvartype', 'info', 'name', 'parameterized', 'sample', 'underlyingMesh', 'variables', 'varnames']

 

We can ignore the underscored names here as they do not refer to "public" attributes and methods.

 

>>> print testtraj.info(1)  # verbose level 1
Trajectory test
  of variables: ['y', 'w']
  over domains: {'y': Interval traj_dep_bd, 'w': Interval traj_dep_bd}

 

The 'indepdomain' attribute is an Interval object. The 'depdomain' attribute is a dictionary of Interval objects, one for each dependent variable.

 

>>> print testtraj.indepdomain.info()
Interval traj_indep_bd
  float: traj_indep_bd = [0,10.0] @ eps = 1e-014
>>> print testtraj.depdomain['w'].info()
Interval traj_dep_bd
  float: traj_dep_bd = [30.0,315.701094773] @ eps = 1e-014

 

The @ eps = 1e-014 information is of no general significance to users. It denotes the error tolerance with which interval endpoints are resolved, when issues of arithmetic precision impede on the comparison of interval endpoints.

Finally, we look turning the Trajectory object into a form that can be displayed in a plot. We use the sample() method of the trajectory to extract values at a desired resolution. The result of this call is a Pointset object (which is essentially a context-laden and index-free array of time and variable values).

 

plotData = testtraj.sample(dt=0.1)  # Pointset
yaxislabelstr = 'w, y, for k = ' + str(DSargs.pars['k'])
pylab.ylabel(yaxislabelstr)
pylab.xlabel('t')
wline=pylab.plot(plotData['t'], plotData['w'])
yline=pylab.plot(plotData['t'], plotData['y'])
show()  # you may or may not need to call this depending on the configuration of your matplotlib back-end

 

4.5. Tutorial and next steps

There are two sources of further help. One is to read and run the other examples in the PyDSTool/tests/ directory. Many of these contain significant code commenting to explain the set ups, and also display graphs and text-based information about the examples. There is also a growing online Tutorial.

 


 

 

PyDSTool source code is hosted by SourceForge:

Get PyDSTool at SourceForge.net. Fast, secure and Free Open Source software downloads