diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..0b09677 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,70 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source + +.PHONY: help clean html web pickle htmlhelp latex changes linkcheck + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " pickle to make pickle files (usable by e.g. sphinx-web)" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " changes to make an overview over all changed/added/deprecated items" + @echo " linkcheck to check all external links for integrity" + +clean: + -rm -rf build/* + +html: + mkdir -p build/html build/doctrees + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) build/html + @echo + @echo "Build finished. The HTML pages are in build/html." + +pickle: + mkdir -p build/pickle build/doctrees + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) build/pickle + @echo + @echo "Build finished; now you can process the pickle files or run" + @echo " sphinx-web build/pickle" + @echo "to start the sphinx-web server." + +web: pickle + +htmlhelp: + mkdir -p build/htmlhelp build/doctrees + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) build/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in build/htmlhelp." + +latex: + mkdir -p build/latex build/doctrees + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) build/latex + @echo + @echo "Build finished; the LaTeX files are in build/latex." + @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ + "run these through (pdf)latex." + +changes: + mkdir -p build/changes build/doctrees + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) build/changes + @echo + @echo "The overview file is in build/changes." + +linkcheck: + mkdir -p build/linkcheck build/doctrees + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) build/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in build/linkcheck/output.txt." diff --git a/docs/source/changes/changes.txt b/docs/source/changes/changes.txt new file mode 100644 index 0000000..8b69303 --- /dev/null +++ b/docs/source/changes/changes.txt @@ -0,0 +1,104 @@ +=================== +Changes in IPython +=================== + +.. contents:: + +Release 0.3 +=========== + +New features +------------ + + * Much improved ``setup.py`` and ``setupegg.py`` scripts. Because Twisted + and zope.interface are now easy installable, we can declare them as dependencies + in our setupegg.py script. + * IPython is now compatible with Twisted 2.5.0 and 8.x. + * Added a new example of how to use :mod:`ipython1.kernel.asynclient`. + * Initial draft of a process daemon in :mod:`ipython1.daemon`. + * The ``TaskController`` now has methods for getting the queue status. + * The ``TaskResult`` objects not have information about how long the task + took to run. + * We are attaching additional attributes to exceptions ``(_ipython_*)`` that + we use to carry additional info around. + * New top-level module :mod:`asynclient` that has asynchronous versions (that + return deferreds) of the client classes. This is designed to users who want + to run their own Twisted reactor + * All the clients in :mod:`client` are now based on Twisted. This is done by + running the Twisted reactor in a separate thread and using the + :func:`blockingCallFromThread` function that is in recent versions of Twisted. + * Functions can now be pushed/pulled to/from engines using + :meth:`MultiEngineClient.push_function` and :meth:`MultiEngineClient.pull_function`. + * Gather/scatter are now implemented in the client to reduce the work load + of the controller and improve performance. + * Complete rewrite of the IPython docuementation. All of the documentation + from the IPython website has been moved into docs/source as restructured + text documents. PDF and HTML documentation are being generated using + Sphinx. + * New developer oriented documentation: development guidelines and roadmap. + * Traditional ``ChangeLog`` has been changed to a more useful ``changes.txt`` file + that is organized by release and is meant to provide something more relevant + for users. + +Bug fixes +--------- + + * Created a proper ``MANIFEST.in`` file to create source distributions. + * Fixed a bug in the ``MultiEngine`` interface. Previously, multi-engine + actions were being collected with a :class:`DeferredList` with + ``fireononeerrback=1``. This meant that methods were returning + before all engines had given their results. This was causing extremely odd + bugs in certain cases. To fix this problem, we have 1) set + ``fireononeerrback=0`` to make sure all results (or exceptions) are in + before returning and 2) introduced a :exc:`CompositeError` exception + that wraps all of the engine exceptions. This is a huge change as it means + that users will have to catch :exc:`CompositeError` rather than the actual + exception. + +Backwards incompatible changes +------------------------------ + + * All names have been renamed to conform to the lowercase_with_underscore + convention. This will require users to change references to all names like + ``queueStatus`` to ``queue_status``. + * Previously, methods like :meth:`MultiEngineClient.push` and + :meth:`MultiEngineClient.push` used ``*args`` and ``**kwargs``. This was + becoming a problem as we weren't able to introduce new keyword arguments into + the API. Now these methods simple take a dict or sequence. This has also allowed + us to get rid of the ``*All`` methods like :meth:`pushAll` and :meth:`pullAll`. + These things are now handled with the ``targets`` keyword argument that defaults + to ``'all'``. + * The :attr:`MultiEngineClient.magicTargets` has been renamed to + :attr:`MultiEngineClient.targets`. + * All methods in the MultiEngine interface now accept the optional keyword argument + ``block``. + * Renamed :class:`RemoteController` to :class:`MultiEngineClient` and + :class:`TaskController` to :class:`TaskClient`. + * Renamed the top-level module from :mod:`api` to :mod:`client`. + * Most methods in the multiengine interface now raise a :exc:`CompositeError` exception + that wraps the user's exceptions, rather than just raising the raw user's exception. + * Changed the ``setupNS`` and ``resultNames`` in the ``Task`` class to ``push`` + and ``pull``. + +Version 0.8.2 +============= + +Changes made since version 0.8.1 was released: + +* %pushd/%popd behave differently; now "pushd /foo" pushes CURRENT directory + and jumps to /foo. The current behaviour is closer to the documented + behaviour, and should not trip anyone. + +Version 0.8.3 +============= + +* pydb is now disabled by default (due to %run -d problems). You can enable +it by passing -pydb command line argument to IPython. Note that setting +it in config file won't work. + +Releases prior to 0.3 +===================== + +Changes prior to version 0.3 of IPython are described in the older file ``ChangeLog``. +Please refer to this document for details. + diff --git a/docs/source/conf.py b/docs/source/conf.py index 3708400..1fae1be 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # # IPython documentation build configuration file, created by -# sphinx-quickstart.py on Sat Mar 29 15:36:13 2008. +# sphinx-quickstart on Thu May 8 16:45:02 2008. # # This file is execfile()d with the current directory set to its containing dir. # @@ -11,38 +11,40 @@ # All configuration values have a default value; values that are commented out # serve to show the default value. -import sys +import sys, os -# If your extensions are in another directory, add it here. -#sys.path.append('some/directory') +# If your extensions are in another directory, add it here. If the directory +# is relative to the documentation root, use os.path.abspath to make it +# absolute, like shown here. +#sys.path.append(os.path.abspath('some/directory')) # General configuration # --------------------- # Add any Sphinx extension module names here, as strings. They can be extensions -# coming with Sphinx (named 'sphinx.addons.*') or your custom ones. +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. #extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. -source_suffix = '.rst' +source_suffix = '.txt' # The master toctree document. -master_doc = 'ipython' +master_doc = 'index' # General substitutions. project = 'IPython' -copyright = '2008, Fernando Perez' +copyright = '2008, The IPython Development Team' # The default replacements for |version| and |release|, also used in various # other places throughout the built documents. # # The short X.Y version. -version = '0.8.3' +version = '0.8.4' # The full version, including alpha/beta/rc tags. -release = '0.8.3' +release = '0.8.4' # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: @@ -53,6 +55,10 @@ today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] +# List of directories, relative to source directories, that shouldn't be searched +# for source files. +#exclude_dirs = [] + # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True @@ -76,6 +82,14 @@ pygments_style = 'sphinx' # given in html_static_path. html_style = 'default.css' +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# The name of an image file (within the static path) to place at the top of +# the sidebar. +#html_logo = None + # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". @@ -89,9 +103,6 @@ html_last_updated_fmt = '%b %d, %Y' # typographically correct entities. #html_use_smartypants = True -# Content template for the index page. -#html_index = '' - # Custom sidebar templates, maps document names to template names. #html_sidebars = {} @@ -105,6 +116,14 @@ html_last_updated_fmt = '%b %d, %Y' # If true, the reST sources are included in the HTML build as _sources/. #html_copy_source = True +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = '' + # Output file base name for HTML help builder. htmlhelp_basename = 'IPythondoc' @@ -113,14 +132,24 @@ htmlhelp_basename = 'IPythondoc' # ------------------------ # The paper size ('letter' or 'a4'). -latex_paper_size = 'a4' +latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). -latex_documents = [('ipython','ipython.tex','IPython Documentation','Fernando Perez (and contributors)','manual')] +latex_documents = [ + ('index', 'IPython.tex', 'IPython Documentation', 'The IPython Development Team', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' diff --git a/docs/source/core/api_changes.txt b/docs/source/core/api_changes.txt deleted file mode 100644 index dc81fce..0000000 --- a/docs/source/core/api_changes.txt +++ /dev/null @@ -1,35 +0,0 @@ -============= - API Changes -============= - -.. contents:: -.. - 1 Purpose - 2 Version 0.8.2 - - -Purpose -======= - -This file documents backwards-incompatible changes to the IPython API, -including user-visible changes of commands, magics, etc. - -It should be filled in reverse chronological order, with one section for each -release (which means changes since the previous release). - - -Version 0.8.2 -============= - -Changes made since version 0.8.1 was released: - -* %pushd/%popd behave differently; now "pushd /foo" pushes CURRENT directory - and jumps to /foo. The current behaviour is closer to the documented - behaviour, and should not trip anyone. - -Version 0.8.3 -============= - -* pydb is now disabled by default (due to %run -d problems). You can enable -it by passing -pydb command line argument to IPython. Note that setting -it in config file won't work. \ No newline at end of file diff --git a/docs/source/core/index.txt b/docs/source/core/index.txt new file mode 100644 index 0000000..51d55c9 --- /dev/null +++ b/docs/source/core/index.txt @@ -0,0 +1,7 @@ +IPython Documentation +===================== + +.. toctree:: + :maxdepth: 2 + + ipython.txt \ No newline at end of file diff --git a/docs/source/development/development.txt b/docs/source/development/development.txt new file mode 100644 index 0000000..75cb395 --- /dev/null +++ b/docs/source/development/development.txt @@ -0,0 +1,315 @@ +.. _development: + +================================== +IPython development guidelines +================================== + +.. contents:: +.. + 1 Overview + 2 Project organization + 2.1 Subpackages + 2.2 Installation and dependencies + 2.3 Specific subpackages + 3 Version control + 4 Documentation + 4.1 Standalone documentation + 4.2 Docstring format + 5 Coding conventions + 5.1 General + 5.2 Naming conventions + 6 Testing + 7 Configuration +.. + + +Overview +======== + +IPython is the next generation of IPython. It is named such for two reasons: + +- Eventually, IPython will become IPython version 1.0. +- This new code base needs to be able to co-exist with the existing IPython until + it is a full replacement for it. Thus we needed a different name. We couldn't + use ``ipython`` (lowercase) as some files systems are case insensitive. + +There are two, no three, main goals of the IPython effort: + +1. Clean up the existing codebase and write lots of tests. +2. Separate the core functionality of IPython from the terminal to enable IPython + to be used from within a variety of GUI applications. +3. Implement a system for interactive parallel computing. + +While the third goal may seem a bit unrelated to the main focus of IPython, it turns +out that the technologies required for this goal are nearly identical with those +required for goal two. This is the main reason the interactive parallel computing +capabilities are being put into IPython proper. Currently the third of these goals is +furthest along. + +This document describes IPython from the perspective of developers. + + +Project organization +==================== + +Subpackages +----------- + +IPython is organized into semi self-contained subpackages. Each of the subpackages will have its own: + +- **Dependencies**. One of the most important things to keep in mind in + partitioning code amongst subpackages, is that they should be used to cleanly + encapsulate dependencies. +- **Tests**. Each subpackage shoud have its own ``tests`` subdirectory that + contains all of the tests for that package. For information about writing tests + for IPython, see the `Testing System`_ section of this document. +- **Configuration**. Each subpackage should have its own ``config`` subdirectory + that contains the configuration information for the components of the + subpackage. For information about how the IPython configuration system + works, see the `Configuration System`_ section of this document. +- **Scripts**. Each subpackage should have its own ``scripts`` subdirectory that + contains all of the command line scripts associated with the subpackage. + +Installation and dependencies +----------------------------- + +IPython will not use `setuptools`_ for installation. Instead, we will use standard +``setup.py`` scripts that use `distutils`_. While there are a number a extremely nice +features that `setuptools`_ has (like namespace packages), the current implementation +of `setuptools`_ has performance problems, particularly on shared file systems. In +particular, when Python packages are installed on NSF file systems, import times +become much too long (up towards 10 seconds). + +Because IPython is being used extensively in the context of high performance +computing, where performance is critical but shared file systems are common, we feel +these performance hits are not acceptable. Thus, until the performance problems +associated with `setuptools`_ are addressed, we will stick with plain `distutils`_. We +are hopeful that these problems will be addressed and that we will eventually begin +using `setuptools`_. Because of this, we are trying to organize IPython in a way that +will make the eventual transition to `setuptools`_ as painless as possible. + +Because we will be using `distutils`_, there will be no method for automatically installing dependencies. Instead, we are following the approach of `Matplotlib`_ which can be summarized as follows: + +- Distinguish between required and optional dependencies. However, the required + dependencies for IPython should be only the Python standard library. +- Upon installation check to see which optional dependencies are present and tell + the user which parts of IPython need which optional dependencies. + +It is absolutely critical that each subpackage of IPython has a clearly specified set +of dependencies and that dependencies are not carelessly inherited from other IPython +subpackages. Furthermore, tests that have certain dependencies should not fail if +those dependencies are not present. Instead they should be skipped and print a +message. + +.. _setuptools: http://peak.telecommunity.com/DevCenter/setuptools +.. _distutils: http://docs.python.org/lib/module-distutils.html +.. _Matplotlib: http://matplotlib.sourceforge.net/ + +Specific subpackages +-------------------- + +``core`` + This is the core functionality of IPython that is independent of the + terminal, network and GUIs. Most of the code that is in the current + IPython trunk will be refactored, cleaned up and moved here. + +``kernel`` + The enables the IPython core to be expose to a the network. This is + also where all of the parallel computing capabilities are to be found. + +``config`` + The configuration package used by IPython. + +``frontends`` + The various frontends for IPython. A frontend is the end-user application + that exposes the capabilities of IPython to the user. The most basic frontend + will simply be a terminal based application that looks just like today 's + IPython. Other frontends will likely be more powerful and based on GUI toolkits. + +``notebook`` + An application that allows users to work with IPython notebooks. + +``tools`` + This is where general utilities go. + + +Version control +=============== + +In the past, IPython development has been done using `Subversion`__. We are currently trying out `Bazaar`__ and `Launchpad`__. + +.. __: http://subversion.tigris.org/ +.. __: http://bazaar-vcs.org/ +.. __: http://www.launchpad.net/ipython + +Documentation +============= + +Standalone documentation +------------------------ + +All standalone documentation should be written in plain text (``.txt``) files using +`reStructuredText`_ for markup and formatting. All such documentation should be placed +in the top level directory ``docs`` of the IPython source tree. Or, when appropriate, +a suitably named subdirectory should be used. The documentation in this location will +serve as the main source for IPython documentation and all existing documentation +should be converted to this format. + +In the future, the text files in the ``docs`` directory will be used to generate all +forms of documentation for IPython. This include documentation on the IPython website +as well as *pdf* documentation. + +.. _reStructuredText: http://docutils.sourceforge.net/rst.html + +Docstring format +---------------- + +Good docstrings are very important. All new code will use `Epydoc`_ for generating API +docs, so we will follow the `Epydoc`_ conventions. More specifically, we will use +`reStructuredText`_ for markup and formatting, since it is understood by a wide +variety of tools. This means that if in the future we have any reason to change from +`Epydoc`_ to something else, we'll have fewer transition pains. + +Details about using `reStructuredText`_ for docstrings can be found `here +`_. + +.. _Epydoc: http://epydoc.sourceforge.net/ + +Additional PEPs of interest regarding documentation of code: + +- `Docstring Conventions `_ +- `Docstring Processing System Framework `_ +- `Docutils Design Specification `_ + + +Coding conventions +================== + +General +------- + +In general, we'll try to follow the standard Python style conventions as described here: + +- `Style Guide for Python Code `_ + + +Other comments: + +- In a large file, top level classes and functions should be + separated by 2-3 lines to make it easier to separate them visually. +- Use 4 spaces for indentation. +- Keep the ordering of methods the same in classes that have the same + methods. This is particularly true for classes that implement + similar interfaces and for interfaces that are similar. + +Naming conventions +------------------ + +In terms of naming conventions, we'll follow the guidelines from the `Style Guide for +Python Code`_. + +For all new IPython code (and much existing code is being refactored), we'll use: + +- All ``lowercase`` module names. + +- ``CamelCase`` for class names. + +- ``lowercase_with_underscores`` for methods, functions, variables and attributes. + +This may be confusing as most of the existing IPython codebase uses a different convention (``lowerCamelCase`` for methods and attributes). Slowly, we will move IPython over to the new +convention, providing shadow names for backward compatibility in public interfaces. + +There are, however, some important exceptions to these rules. In some cases, IPython +code will interface with packages (Twisted, Wx, Qt) that use other conventions. At some level this makes it impossible to adhere to our own standards at all times. In particular, when subclassing classes that use other naming conventions, you must follow their naming conventions. To deal with cases like this, we propose the following policy: + +- If you are subclassing a class that uses different conventions, use its + naming conventions throughout your subclass. Thus, if you are creating a + Twisted Protocol class, used Twisted's ``namingSchemeForMethodsAndAttributes.`` + +- All IPython's official interfaces should use our conventions. In some cases + this will mean that you need to provide shadow names (first implement ``fooBar`` + and then ``foo_bar = fooBar``). We want to avoid this at all costs, but it + will probably be necessary at times. But, please use this sparingly! + +Implementation-specific *private* methods will use ``_single_underscore_prefix``. +Names with a leading double underscore will *only* be used in special cases, as they +makes subclassing difficult (such names are not easily seen by child classes). + +Occasionally some run-in lowercase names are used, but mostly for very short names or +where we are implementing methods very similar to existing ones in a base class (like +``runlines()`` where ``runsource()`` and ``runcode()`` had established precedent). + +The old IPython codebase has a big mix of classes and modules prefixed with an +explicit ``IP``. In Python this is mostly unnecessary, redundant and frowned upon, as +namespaces offer cleaner prefixing. The only case where this approach is justified is +for classes which are expected to be imported into external namespaces and a very +generic name (like Shell) is too likely to clash with something else. We'll need to +revisit this issue as we clean up and refactor the code, but in general we should +remove as many unnecessary ``IP``/``ip`` prefixes as possible. However, if a prefix +seems absolutely necessary the more specific ``IPY`` or ``ipy`` are preferred. + +.. _devel_testing: + +Testing system +============== + +It is extremely important that all code contributed to IPython has tests. Tests should +be written as unittests, doctests or as entities that the `Nose`_ testing package will +find. Regardless of how the tests are written, we will use `Nose`_ for discovering and +running the tests. `Nose`_ will be required to run the IPython test suite, but will +not be required to simply use IPython. + +.. _Nose: http://code.google.com/p/python-nose/ + +Tests of `Twisted`__ using code should be written by subclassing the ``TestCase`` class +that comes with ``twisted.trial.unittest``. When this is done, `Nose`_ will be able to +run the tests and the twisted reactor will be handled correctly. + +.. __: http://www.twistedmatrix.com + +Each subpackage in IPython should have its own ``tests`` directory that contains all +of the tests for that subpackage. This allows each subpackage to be self-contained. If +a subpackage has any dependencies beyond the Python standard library, the tests for +that subpackage should be skipped if the dependencies are not found. This is very +important so users don't get tests failing simply because they don't have dependencies. + +We also need to look into use Noses ability to tag tests to allow a more modular +approach of running tests. + +.. _devel_config: + +Configuration system +==================== + +IPython uses `.ini`_ files for configuration purposes. This represents a huge +improvement over the configuration system used in IPython. IPython works with these +files using the `ConfigObj`_ package, which IPython includes as +``ipython1/external/configobj.py``. + +Currently, we are using raw `ConfigObj`_ objects themselves. Each subpackage of IPython +should contain a ``config`` subdirectory that contains all of the configuration +information for the subpackage. To see how configuration information is defined (along +with defaults) see at the examples in ``ipython1/kernel/config`` and +``ipython1/core/config``. Likewise, to see how the configuration information is used, +see examples in ``ipython1/kernel/scripts/ipengine.py``. + +Eventually, we will add a new layer on top of the raw `ConfigObj`_ objects. We are +calling this new layer, ``tconfig``, as it will use a `Traits`_-like validation model. +We won't actually use `Traits`_, but will implement something similar in pure Python. +But, even in this new system, we will still use `ConfigObj`_ and `.ini`_ files +underneath the hood. Talk to Fernando if you are interested in working on this part of +IPython. The current prototype of ``tconfig`` is located in the IPython sandbox. + +.. _.ini: http://docs.python.org/lib/module-ConfigParser.html +.. _ConfigObj: http://www.voidspace.org.uk/python/configobj.html +.. _Traits: http://code.enthought.com/traits/ + + + + + + + + + + diff --git a/docs/source/development/index.txt b/docs/source/development/index.txt new file mode 100644 index 0000000..0589edb --- /dev/null +++ b/docs/source/development/index.txt @@ -0,0 +1,8 @@ +Developing IPython +================== + +.. toctree:: + :maxdepth: 2 + + development.txt + roadmap.txt diff --git a/docs/source/development/roadmap.txt b/docs/source/development/roadmap.txt new file mode 100644 index 0000000..f6ee969 --- /dev/null +++ b/docs/source/development/roadmap.txt @@ -0,0 +1,96 @@ +.. _roadmap: + +=================== +Development roadmap +=================== + +.. contents:: + +IPython is an ambitious project that is still under heavy development. However, we want IPython to become useful to as many people as possible, as quickly as possible. To help us accomplish this, we are laying out a roadmap of where we are headed and what needs to happen to get there. Hopefully, this will help the IPython developers figure out the best things to work on for each upcoming release. + +Speaking of releases, we are going to begin releasing a new version of IPython every four weeks. We are hoping that a regular release schedule, along with a clear roadmap of where we are headed will propel the project forward. + +Where are we headed +=================== + +Our goal with IPython is simple: to provide a *powerful*, *robust* and *easy to use* framework for parallel computing. While there are other secondary goals you will hear us talking about at various times, this is the primary goal of IPython that frames the roadmap. + +Steps along the way +=================== + +Here we describe the various things that we need to work on to accomplish this goal. + +Setting up for regular release schedule +--------------------------------------- + +We would like to begin to release IPython regularly (probably a 4 week release cycle). To get ready for this, we need to revisit the development guidelines and put in information about releasing IPython. + +Process startup and management +------------------------------ + +IPython is implemented using a distributed set of processes that communicate using TCP/IP network channels. Currently, users have to start each of the various processes separately using command line scripts. This is both difficult and error prone. Furthermore, there are a number of things that often need to be managed once the processes have been started, such as the sending of signals and the shutting down and cleaning up of processes. + +We need to build a system that makes it trivial for users to start and manage IPython processes. This system should have the following properties: + + * It should possible to do everything through an extremely simple API that users + can call from their own Python script. No shell commands should be needed. + * This simple API should be configured using standard .ini files. + * The system should make it possible to start processes using a number of different + approaches: SSH, PBS/Torque, Xgrid, Windows Server, mpirun, etc. + * The controller and engine processes should each have a daemon for monitoring, + signaling and clean up. + * The system should be secure. + * The system should work under all the major operating systems, including + Windows. + +Initial work has begun on the daemon infrastructure, and some of the needed logic is contained in the ipcluster script. + +Ease of use/high-level approaches to parallelism +------------------------------------------------ + +While our current API for clients is well designed, we can still do a lot better in designing a user-facing API that is super simple. The main goal here is that it should take *almost no extra code* for users to get their code running in parallel. For this to be possible, we need to tie into Python's standard idioms that enable efficient coding. The biggest ones we are looking at are using context managers (i.e., Python 2.5's ``with`` statement) and decorators. Initial work on this front has begun, but more work is needed. + +We also need to think about new models for expressing parallelism. This is fun work as most of the foundation has already been established. + +Security +-------- + +Currently, IPython has no built in security or security model. Because we would like IPython to be usable on public computer systems and over wide area networks, we need to come up with a robust solution for security. Here are some of the specific things that need to be included: + + * User authentication between all processes (engines, controller and clients). + * Optional TSL/SSL based encryption of all communication channels. + * A good way of picking network ports so multiple users on the same system can + run their own controller and engines without interfering with those of others. + * A clear model for security that enables users to evaluate the security risks + associated with using IPython in various manners. + +For the implementation of this, we plan on using Twisted's support for SSL and authentication. One things that we really should look at is the `Foolscap`_ network protocol, which provides many of these things out of the box. + +.. _Foolscap: http://foolscap.lothar.com/trac + +The security work needs to be done in conjunction with other network protocol stuff. + +Latent performance issues +------------------------- + +Currently, we have a number of performance issues that are waiting to bite users: + + * The controller store a large amount of state in Python dictionaries. Under heavy + usage, these dicts with get very large, causing memory usage problems. We need to + develop more scalable solutions to this problem, such as using a sqlite database + to store this state. This will also help the controller to be more fault tolerant. + * Currently, the client to controller connections are done through XML-RPC using + HTTP 1.0. This is very inefficient as XML-RPC is a very verbose protocol and + each request must be handled with a new connection. We need to move these network + connections over to PB or Foolscap. + * We currently don't have a good way of handling large objects in the controller. + The biggest problem is that because we don't have any way of streaming objects, + we get lots of temporary copies in the low-level buffers. We need to implement + a better serialization approach and true streaming support. + * The controller currently unpickles and repickles objects. We need to use the + [push|pull]_serialized methods instead. + * Currently the controller is a bottleneck. We need the ability to scale the + controller by aggregating multiple controllers into one effective controller. + + + diff --git a/docs/source/history.txt b/docs/source/history.txt new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/docs/source/history.txt diff --git a/docs/source/index.txt b/docs/source/index.txt new file mode 100644 index 0000000..73b1978 --- /dev/null +++ b/docs/source/index.txt @@ -0,0 +1,16 @@ +IPython Documentation +===================== + +.. toctree:: + :maxdepth: 1 + + core/index.txt + dev/index.txt + kernel/index.txt + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` \ No newline at end of file diff --git a/docs/source/install/index.txt b/docs/source/install/index.txt new file mode 100644 index 0000000..c6df8ac --- /dev/null +++ b/docs/source/install/index.txt @@ -0,0 +1,16 @@ +IPython kernel documentation +============================ + +User Documentation +------------------ + +.. toctree:: + :maxdepth: 2 + + install.txt + parallel_intro.txt + parallel_multiengine.txt + parallel_task.txt + parallel_mpi.txt + changes.txt + faq.txt diff --git a/docs/source/interactive/index.txt b/docs/source/interactive/index.txt new file mode 100644 index 0000000..73b1978 --- /dev/null +++ b/docs/source/interactive/index.txt @@ -0,0 +1,16 @@ +IPython Documentation +===================== + +.. toctree:: + :maxdepth: 1 + + core/index.txt + dev/index.txt + kernel/index.txt + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` \ No newline at end of file diff --git a/docs/source/core/ipython.txt b/docs/source/interactive/ipython.txt similarity index 100% rename from docs/source/core/ipython.txt rename to docs/source/interactive/ipython.txt diff --git a/docs/source/license_and_copyright.txt b/docs/source/license_and_copyright.txt new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/docs/source/license_and_copyright.txt diff --git a/docs/source/parallel/faq.txt b/docs/source/parallel/faq.txt new file mode 100644 index 0000000..1405261 --- /dev/null +++ b/docs/source/parallel/faq.txt @@ -0,0 +1,115 @@ +.. _faq: + +================ +FAQ for IPython +================ + +General questions +================= + +What is the difference between IPython and IPython? +---------------------------------------------------- + +IPython is the next generation of IPython. It is being created with three main goals in +mind: + + 1. Clean up the existing codebase and write lots of tests. + 2. Separate the core functionality of IPython from the terminal to enable IPython + to be used from within a variety of GUI applications. + 3. Implement a system for interactive parallel computing. + +Currently, IPython is not a full replacement for IPython and until that happens, +IPython will be developed as a separate project. IPython currently provides a stable +and powerful architecture for parallel computing that can be used with IPython or even +the default Python shell. For more information, see our `introduction to parallel +computing with IPython`__. + +.. __: ./parallel_intro + +What is the history of IPython? +-------------------------------- + +Questions about parallel computing with IPython +================================================ + +Will IPython speed my Python code up? +-------------------------------------- + +Yes and no. When converting a serial code to run in parallel, there often many +difficulty questions that need to be answered, such as: + + * How should data be decomposed onto the set of processors? + * What are the data movement patterns? + * Can the algorithm be structured to minimize data movement? + * Is dynamic load balancing important? + +We can't answer such questions for you. This is the hard (but fun) work of parallel +computing. But, once you understand these things IPython will make it easier for you to +implement a good solution quickly. Most importantly, you will be able to use the +resulting parallel code interactively. + +With that said, if your problem is trivial to parallelize, IPython has a number of +different interfaces that will enable you to parallelize things is almost no time at +all. A good place to start is the ``map`` method of our `multiengine interface`_. + +.. _multiengine interface: ./parallel_multiengine + +What is the best way to use MPI from Python? +-------------------------------------------- + +What about all the other parallel computing packages in Python? +--------------------------------------------------------------- + +Some of the unique characteristic of IPython are: + + * IPython is the only architecture that abstracts out the notion of a + parallel computation in such a way that new models of parallel computing + can be explored quickly and easily. If you don't like the models we + provide, you can simply create your own using the capabilities we provide. + * IPython is asynchronous from the ground up (we use `Twisted`_). + * IPython's architecture is designed to avoid subtle problems + that emerge because of Python's global interpreter lock (GIL). + * While IPython'1 architecture is designed to support a wide range + of novel parallel computing models, it is fully interoperable with + traditional MPI applications. + * IPython has been used and tested extensively on modern supercomputers. + * IPython's networking layers are completely modular. Thus, is + straightforward to replace our existing network protocols with + high performance alternatives (ones based upon Myranet/Infiniband). + * IPython is designed from the ground up to support collaborative + parallel computing. This enables multiple users to actively develop + and run the *same* parallel computation. + * Interactivity is a central goal for us. While IPython does not have + to be used interactivly, is can be. + +.. _Twisted: http://www.twistedmatrix.com + +Why The IPython controller a bottleneck in my parallel calculation? +------------------------------------------------------------------- + +A golden rule in parallel computing is that you should only move data around if you +absolutely need to. The main reason that the controller becomes a bottleneck is that +too much data is being pushed and pulled to and from the engines. If your algorithm +is structured in this way, you really should think about alternative ways of +handling the data movement. Here are some ideas: + + 1. Have the engines write data to files on the locals disks of the engines. + 2. Have the engines write data to files on a file system that is shared by + the engines. + 3. Have the engines write data to a database that is shared by the engines. + 4. Simply keep data in the persistent memory of the engines and move the + computation to the data (rather than the data to the computation). + 5. See if you can pass data directly between engines using MPI. + +Isn't Python slow to be used for high-performance parallel computing? +--------------------------------------------------------------------- + + + + + + + + + + diff --git a/docs/source/parallel/index.txt b/docs/source/parallel/index.txt new file mode 100644 index 0000000..c6df8ac --- /dev/null +++ b/docs/source/parallel/index.txt @@ -0,0 +1,16 @@ +IPython kernel documentation +============================ + +User Documentation +------------------ + +.. toctree:: + :maxdepth: 2 + + install.txt + parallel_intro.txt + parallel_multiengine.txt + parallel_task.txt + parallel_mpi.txt + changes.txt + faq.txt diff --git a/docs/source/parallel/install.txt b/docs/source/parallel/install.txt new file mode 100644 index 0000000..690ee45 --- /dev/null +++ b/docs/source/parallel/install.txt @@ -0,0 +1,169 @@ +.. _install: + +=================== +Installing IPython +=================== + +.. contents:: + +Introduction +============ + +IPython enables parallel applications to be developed in Python. This document +describes the steps required to install IPython. For an overview of IPython's +architecture as it relates to parallel computing, see our :ref:`introduction to +parallel computing with IPython `. + +Please let us know if you have problems installing IPython or any of its +dependencies. We have tested IPython extensively with Python 2.4 and 2.5. + +.. warning:: + + IPython will not work with Python 2.3 or below. + +IPython has three required dependencies: + + 1. `IPython`__ + 2. `Zope Interface`__ + 3. `Twisted`__ + 4. `Foolscap`__ + +.. __: http://ipython.scipy.org +.. __: http://pypi.python.org/pypi/zope.interface +.. __: http://twistedmatrix.com +.. __: http://foolscap.lothar.com/trac + +It also has the following optional dependencies: + + 1. pexpect (used for certain tests) + 2. nose (used to run our test suite) + 3. sqlalchemy (used for database support) + 4. mpi4py (for MPI support) + 5. Sphinx and pygments (for building documentation) + 6. pyOpenSSL (for security) + +Getting IPython +================ + +IPython development has been moved to `Launchpad`_. The development branch of IPython can be checkout out using `Bazaar`_:: + + $ bzr branch lp:///~ipython/ipython/ipython1-dev + +.. _Launchpad: http://www.launchpad.net/ipython +.. _Bazaar: http://bazaar-vcs.org/ + +Installation using setuptools +============================= + +The easiest way of installing IPython and its dependencies is using +`setuptools`_. If you have setuptools installed you can simple use the ``easy_install`` +script that comes with setuptools (this should be on your path if you have setuptools):: + + $ easy_install ipython1 + +This will download and install the latest version of IPython as well as all of its dependencies. For this to work, you will need to be connected to the internet when you run this command. This will install everything info the ``site-packages`` directory of your Python distribution. If this is the system wide Python, you will likely need admin privileges. For information about installing Python packages to other locations (that don't require admin privileges) see the `setuptools`_ documentation. + +.. _setuptools: http://peak.telecommunity.com/DevCenter/setuptools + +If you don't want `setuptools`_ to automatically install the dependencies, you can also get the dependencies yourself, using ``easy_install``:: + + $ easy_install IPython + $ easy_install zope.interface + $ easy_install Twisted + $ easy_install foolscap + +or by simply downloading and installing the dependencies manually. + +If you want to have secure (highly recommended) network connections, you will also +need to get `pyOpenSSL`__, version 0.6, or just do: + + $ easy_install ipython1[security] + +.. hint:: If you want to do development on IPython and want to always + run off your development branch, you can run + :command:`python setupegg.py develop` in the IPython source tree. + +.. __: http://pyopenssl.sourceforge.net/ + +Installation using plain distutils +================================== + +If you don't have `setuptools`_ installed or don't want to use it, you can also install IPython and its dependencies using ``distutils``. In this approach, you will need to get the most recent stable releases of IPython's dependencies and install each of them by doing:: + + $ python setup.py install + +The dependencies need to be installed before installing IPython. After installing the dependencies, install IPython by running:: + + $ cd ipython1-dev + $ python setup.py install + +.. note:: Here we are using setup.py rather than setupegg.py. + +.. _install_config: + +Configuration +============= + +IPython has a configuration system. When running IPython for the first time, +reasonable defaults are used for the configuration. The configuration of IPython +can be changed in two ways: + + * Configuration files + * Commands line options (which override the configuration files) + +IPython has a separate configuration file for each subpackage. Thus, the main +configuration files are (in your ``~/.ipython`` directory): + + * ``ipython1.core.ini`` + * ``ipython1.kernel.ini`` + * ``ipython1.notebook.ini`` + +To create these files for the first time, do the following:: + + from ipython1.kernel.config import config_manager as kernel_config + kernel_config.write_default_config_file() + +But, you should only need to do this if you need to modify the defaults. If needed +repeat this process with the ``notebook`` and ``core`` configuration as well. If you +are running into problems with IPython, you might try deleting these configuration +files. + +.. _install_testing: + +Testing +======= + +Once you have completed the installation of the IPython kernel you can run our test suite +with the command:: + + trial ipython1 + +Or if you have `nose`__ installed:: + + nosetests -v ipython1 + +The ``trial`` command is part of Twisted and allows asynchronous network based +applications to be tested using Python's unittest framework. Please let us know +if the tests do not pass. The best way to get in touch with us is on the `IPython +developer mailing list`_. + +.. __: http://somethingaboutorange.com/mrl/projects/nose/ +.. _IPython developer mailing list: http://projects.scipy.org/mailman/listinfo/ipython-dev + +MPI Support +=========== + +IPython includes optional support for the Message Passing Interface (`MPI`_), +which enables the IPython Engines to pass data between each other using `MPI`_. To use MPI with IPython, the minimal requirements are: + + * An MPI implementation (we recommend `Open MPI`_) + * A way to call MPI (we recommend `mpi4py`_) + +But, IPython should work with any MPI implementation and with any code +(Python/C/C++/Fortran) that uses MPI. Please contact us for more information about +this. + +.. _MPI: http://www-unix.mcs.anl.gov/mpi/ +.. _mpi4py: http://mpi4py.scipy.org/ +.. _Open MPI: http://www.open-mpi.org/ + diff --git a/docs/source/parallel/parallel_intro.txt b/docs/source/parallel/parallel_intro.txt new file mode 100644 index 0000000..773efe7 --- /dev/null +++ b/docs/source/parallel/parallel_intro.txt @@ -0,0 +1,270 @@ +.. _ip1par: + +====================================== +Using IPython for parallel computing +====================================== + +.. contents:: + +Introduction +============ + +This file gives an overview of IPython. IPython has a sophisticated and +powerful architecture for parallel and distributed computing. This +architecture abstracts out parallelism in a very general way, which +enables IPython to support many different styles of parallelism +including: + + * Single program, multiple data (SPMD) parallelism. + * Multiple program, multiple data (MPMD) parallelism. + * Message passing using ``MPI``. + * Task farming. + * Data parallel. + * Combinations of these approaches. + * Custom user defined approaches. + +Most importantly, IPython enables all types of parallel applications to +be developed, executed, debugged and monitored *interactively*. Hence, +the ``I`` in IPython. The following are some example usage cases for IPython: + + * Quickly parallelize algorithms that are embarrassingly parallel + using a number of simple approaches. Many simple things can be + parallelized interactively in one or two lines of code. + * Steer traditional MPI applications on a supercomputer from an + IPython session on your laptop. + * Analyze and visualize large datasets (that could be remote and/or + distributed) interactively using IPython and tools like + matplotlib/TVTK. + * Develop, test and debug new parallel algorithms + (that may use MPI) interactively. + * Tie together multiple MPI jobs running on different systems into + one giant distributed and parallel system. + * Start a parallel job on your cluster and then have a remote + collaborator connect to it and pull back data into their + local IPython session for plotting and analysis. + * Run a set of tasks on a set of CPUs using dynamic load balancing. + +Architecture overview +===================== + +The IPython architecture consists of three components: + + * The IPython engine. + * The IPython controller. + * Various controller Clients. + +IPython engine +--------------- + +The IPython engine is a Python instance that takes Python commands over a +network connection. Eventually, the IPython engine will be a full IPython +interpreter, but for now, it is a regular Python interpreter. The engine +can also handle incoming and outgoing Python objects sent over a network +connection. When multiple engines are started, parallel and distributed +computing becomes possible. An important feature of an IPython engine is +that it blocks while user code is being executed. Read on for how the +IPython controller solves this problem to expose a clean asynchronous API +to the user. + +IPython controller +------------------ + +The IPython controller provides an interface for working with a set of +engines. At an general level, the controller is a process to which +IPython engines can connect. For each connected engine, the controller +manages a queue. All actions that can be performed on the engine go +through this queue. While the engines themselves block when user code is +run, the controller hides that from the user to provide a fully +asynchronous interface to a set of engines. Because the controller +listens on a network port for engines to connect to it, it must be +started before any engines are started. + +The controller also provides a single point of contact for users who wish +to utilize the engines connected to the controller. There are different +ways of working with a controller. In IPython these ways correspond to different interfaces that the controller is adapted to. Currently we have two default interfaces to the controller: + + * The MultiEngine interface. + * The Task interface. + +Advanced users can easily add new custom interfaces to enable other +styles of parallelism. + +.. note:: + + A single controller and set of engines can be accessed + through multiple interfaces simultaneously. This opens the + door for lots of interesting things. + +Controller clients +------------------ + +For each controller interface, there is a corresponding client. These +clients allow users to interact with a set of engines through the +interface. + +Security +-------- + +By default (as long as `pyOpenSSL` is installed) all network connections between the controller and engines and the controller and clients are secure. What does this mean? First of all, all of the connections will be encrypted using SSL. Second, the connections are authenticated. We handle authentication in a `capabilities`__ based security model. In this model, a "capability (known in some systems as a key) is a communicable, unforgeable token of authority". Put simply, a capability is like a key to your house. If you have the key to your house, you can get in, if not you can't. + +.. __: http://en.wikipedia.org/wiki/Capability-based_security + +In our architecture, the controller is the only process that listens on network ports, and is thus responsible to creating these keys. In IPython, these keys are known as Foolscap URLs, or FURLs, because of the underlying network protocol we are using. As a user, you don't need to know anything about the details of these FURLs, other than that when the controller starts, it saves a set of FURLs to files named something.furl. The default location of these files is your ~./ipython directory. + +To connect and authenticate to the controller an engine or client simply needs to present an appropriate furl (that was originally created by the controller) to the controller. Thus, the .furl files need to be copied to a location where the clients and engines can find them. Typically, this is the ~./ipython directory on the host where the client/engine is running (which could be a different host than the controller). Once the .furl files are copied over, everything should work fine. + +Getting Started +=============== + +To use IPython for parallel computing, you need to start one instance of +the controller and one or more instances of the engine. The controller +and each engine can run on different machines or on the same machine. +Because of this, there are many different possibilities for setting up +the IP addresses and ports used by the various processes. + +Starting the controller and engine on your local machine +-------------------------------------------------------- + +This is the simplest configuration that can be used and is useful for +testing the system and on machines that have multiple cores and/or +multple CPUs. The easiest way of doing this is using the ``ipcluster`` +command:: + + $ ipcluster -n 4 + +This will start an IPython controller and then 4 engines that connect to +the controller. Lastly, the script will print out the Python commands +that you can use to connect to the controller. It is that easy. + +Underneath the hood, the ``ipcluster`` script uses two other top-level +scripts that you can also use yourself. These scripts are +``ipcontroller``, which starts the controller and ``ipengine`` which +starts one engine. To use these scripts to start things on your local +machine, do the following. + +First start the controller:: + + $ ipcontroller & + +Next, start however many instances of the engine you want using (repeatedly) the command:: + + $ ipengine & + +.. warning:: + + The order of the above operations is very important. You *must* + start the controller before the engines, since the engines connect + to the controller as they get started. + +On some platforms you may need to give these commands in the form +``(ipcontroller &)`` and ``(ipengine &)`` for them to work properly. The +engines should start and automatically connect to the controller on the +default ports, which are chosen for this type of setup. You are now ready +to use the controller and engines from IPython. + +Starting the controller and engines on different machines +--------------------------------------------------------- + +This section needs to be updated to reflect the new Foolscap capabilities based +model. + +Specifying custom ports +----------------------- + +This section needs to be updated to reflect the new Foolscap capabilities based +model. + +Using ``ipcluster`` with ``ssh`` +-------------------------------- + +The ``ipcluster`` command can also start a controller and engines using +``ssh``. We need more documentation on this, but for now here is any +example startup script:: + + controller = dict(host='myhost', + engine_port=None, # default is 10105 + control_port=None, + ) + + # keys are hostnames, values are the number of engine on that host + engines = dict(node1=2, + node2=2, + node3=2, + node3=2, + ) + +Starting engines using ``mpirun`` +--------------------------------- + +The IPython engines can be started using ``mpirun``/``mpiexec``, even if +the engines don't call MPI_Init() or use the MPI API in any way. This is +supported on modern MPI implementations like `Open MPI`_.. This provides +an really nice way of starting a bunch of engine. On a system with MPI +installed you can do:: + + mpirun -n 4 ipengine --controller-port=10000 --controller-ip=host0 + +.. _Open MPI: http://www.open-mpi.org/ + +More details on using MPI with IPython can be found :ref:`here `. + +Log files +--------- + +All of the components of IPython have log files associated with them. +These log files can be extremely useful in debugging problems with +IPython and can be found in the directory ``~/.ipython/log``. Sending +the log files to us will often help us to debug any problems. + +Security and firewalls +---------------------- + +The only process in IPython's architecture that listens on a network +port is the controller. Thus the controller is the main security concern. +Through the controller, an attacker can execute arbitrary code on the +engines. Thus, we highly recommend taking the following precautions: + + * Don't run the controller on a machine that is exposed to the + internet. + * Don't run the controller on a machine that could have hostile + users on it. + * If you need to connect to a controller that is behind a firewall, + tunnel everything through ssh. + +Currently, IPython does not have any built-in security. Thus, it +is up to you to be aware of the security risks associated with using IPython and to take steps to mitigate those risks. + +However, we do have plans to add security measures to IPython itself. +This will probably take the form of using SSL for encryption and some +authentication scheme. + +Next Steps +========== + +Once you have started the IPython controller and one or more engines, you +are ready to use the engines to do somnething useful. To make sure +everything is working correctly, try the following commands:: + + In [1]: from ipython1.kernel import client + + In [2]: mec = client.MultiEngineClient() # This looks for .furl files in ~./ipython + + In [4]: mec.get_ids() + Out[4]: [0, 1, 2, 3] + + In [5]: mec.execute('print "Hello World"') + Out[5]: + + [0] In [1]: print "Hello World" + [0] Out[1]: Hello World + + [1] In [1]: print "Hello World" + [1] Out[1]: Hello World + + [2] In [1]: print "Hello World" + [2] Out[1]: Hello World + + [3] In [1]: print "Hello World" + [3] Out[1]: Hello World + +If this works, you are ready to learn more about the :ref:`MultiEngine ` and :ref:`Task ` interfaces to the controller. diff --git a/docs/source/parallel/parallel_mpi.txt b/docs/source/parallel/parallel_mpi.txt new file mode 100644 index 0000000..27f41a1 --- /dev/null +++ b/docs/source/parallel/parallel_mpi.txt @@ -0,0 +1,22 @@ +.. _parallelmpi: + +======================= +Using MPI with IPython +======================= + +The simplest way of getting started with MPI is to install an MPI implementation +(we recommend `Open MPI`_) and `mpi4py`_ and then start the engines using the +``mpirun`` command:: + + mpirun -n 4 ipengine --mpi=mpi4py + +This will automatically import `mpi4py`_ and make sure that `MPI_Init` is called +at the right time. We also have built in support for `PyTrilinos`_, which can be +used (assuming `PyTrilinos`_ is installed) by starting the engines with:: + + mpirun -n 4 ipengine --mpi=pytrilinos + +.. _MPI: http://www-unix.mcs.anl.gov/mpi/ +.. _mpi4py: http://mpi4py.scipy.org/ +.. _Open MPI: http://www.open-mpi.org/ +.. _PyTrilinos: http://trilinos.sandia.gov/packages/pytrilinos/ \ No newline at end of file diff --git a/docs/source/parallel/parallel_multiengine.txt b/docs/source/parallel/parallel_multiengine.txt new file mode 100644 index 0000000..9928c05 --- /dev/null +++ b/docs/source/parallel/parallel_multiengine.txt @@ -0,0 +1,728 @@ +.. _parallelmultiengine: + +================================= +IPython's MultiEngine interface +================================= + +.. contents:: + +The MultiEngine interface represents one possible way of working with a +set of IPython engines. The basic idea behind the MultiEngine interface is +that the capabilities of each engine are explicitly exposed to the user. +Thus, in the MultiEngine interface, each engine is given an id that is +used to identify the engine and give it work to do. This interface is very +intuitive and is designed with interactive usage in mind, and is thus the +best place for new users of IPython to begin. + +Starting the IPython controller and engines +=========================================== + +To follow along with this tutorial, you will need to start the IPython +controller and four IPython engines. The simplest way of doing this is to +use the ``ipcluster`` command:: + + $ ipcluster -n 4 + +For more detailed information about starting the controller and engines, see our :ref:`introduction ` to using IPython for parallel computing. + +Creating a ``MultiEngineClient`` instance +========================================= + +The first step is to import the IPython ``client`` module and then create a ``MultiEngineClient`` instance:: + + In [1]: from ipython1.kernel import client + + In [2]: mec = client.MultiEngineClient() + +To make sure there are engines connected to the controller, use can get a list of engine ids:: + + In [3]: mec.get_ids() + Out[3]: [0, 1, 2, 3] + +Here we see that there are four engines ready to do work for us. + +Running Python commands +======================= + +The most basic type of operation that can be performed on the engines is to execute Python code. Executing Python code can be done in blocking or non-blocking mode (blocking is default) using the ``execute`` method. + +Blocking execution +------------------ + +In blocking mode, the ``MultiEngineClient`` object (called ``mec`` in +these examples) submits the command to the controller, which places the +command in the engines' queues for execution. The ``execute`` call then +blocks until the engines are done executing the command:: + + # The default is to run on all engines + In [4]: mec.execute('a=5') + Out[4]: + + [0] In [1]: a=5 + [1] In [1]: a=5 + [2] In [1]: a=5 + [3] In [1]: a=5 + + In [5]: mec.execute('b=10') + Out[5]: + + [0] In [2]: b=10 + [1] In [2]: b=10 + [2] In [2]: b=10 + [3] In [2]: b=10 + +Python commands can be executed on specific engines by calling execute using the ``targets`` keyword argument:: + + In [6]: mec.execute('c=a+b',targets=[0,2]) + Out[6]: + + [0] In [3]: c=a+b + [2] In [3]: c=a+b + + + In [7]: mec.execute('c=a-b',targets=[1,3]) + Out[7]: + + [1] In [3]: c=a-b + [3] In [3]: c=a-b + + + In [8]: mec.execute('print c') + Out[8]: + + [0] In [4]: print c + [0] Out[4]: 15 + + [1] In [4]: print c + [1] Out[4]: -5 + + [2] In [4]: print c + [2] Out[4]: 15 + + [3] In [4]: print c + [3] Out[4]: -5 + +This example also shows one of the most important things about the IPython engines: they have a persistent user namespaces. The ``execute`` method returns a Python ``dict`` that contains useful information:: + + In [9]: result_dict = mec.execute('d=10; print d') + + In [10]: for r in result_dict: + ....: print r + ....: + ....: + {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 0, 'stdout': '10\n'} + {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 1, 'stdout': '10\n'} + {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 2, 'stdout': '10\n'} + {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 3, 'stdout': '10\n'} + +Non-blocking execution +---------------------- + +In non-blocking mode, ``execute`` submits the command to be executed and then returns a +``PendingResult`` object immediately. The ``PendingResult`` object gives you a way of getting a +result at a later time through its ``get_result`` method or ``r`` attribute. This allows you to +quickly submit long running commands without blocking your local Python/IPython session:: + + # In blocking mode + In [6]: mec.execute('import time') + Out[6]: + + [0] In [1]: import time + [1] In [1]: import time + [2] In [1]: import time + [3] In [1]: import time + + # In non-blocking mode + In [7]: pr = mec.execute('time.sleep(10)',block=False) + + # Now block for the result + In [8]: pr.get_result() + Out[8]: + + [0] In [2]: time.sleep(10) + [1] In [2]: time.sleep(10) + [2] In [2]: time.sleep(10) + [3] In [2]: time.sleep(10) + + # Again in non-blocking mode + In [9]: pr = mec.execute('time.sleep(10)',block=False) + + # Poll to see if the result is ready + In [10]: pr.get_result(block=False) + + # A shorthand for get_result(block=True) + In [11]: pr.r + Out[11]: + + [0] In [3]: time.sleep(10) + [1] In [3]: time.sleep(10) + [2] In [3]: time.sleep(10) + [3] In [3]: time.sleep(10) + +Often, it is desirable to wait until a set of ``PendingResult`` objects are done. For this, there is a the method ``barrier``. This method takes a tuple of ``PendingResult`` objects and blocks until all of the associated results are ready:: + + In [72]: mec.block=False + + # A trivial list of PendingResults objects + In [73]: pr_list = [mec.execute('time.sleep(3)') for i in range(10)] + + # Wait until all of them are done + In [74]: mec.barrier(pr_list) + + # Then, their results are ready using get_result or the r attribute + In [75]: pr_list[0].r + Out[75]: + + [0] In [20]: time.sleep(3) + [1] In [19]: time.sleep(3) + [2] In [20]: time.sleep(3) + [3] In [19]: time.sleep(3) + + +The ``block`` and ``targets`` keyword arguments and attributes +-------------------------------------------------------------- + +Most commands in the multiengine interface (like ``execute``) accept ``block`` and ``targets`` +as keyword arguments. As we have seen above, these keyword arguments control the blocking mode +and which engines the command is applied to. The ``MultiEngineClient`` class also has ``block`` +and ``targets`` attributes that control the default behavior when the keyword arguments are not +provided. Thus the following logic is used for ``block`` and ``targets``: + + * If no keyword argument is provided, the instance attributes are used. + * Keyword argument, if provided override the instance attributes. + +The following examples demonstrate how to use the instance attributes:: + + In [16]: mec.targets = [0,2] + + In [17]: mec.block = False + + In [18]: pr = mec.execute('a=5') + + In [19]: pr.r + Out[19]: + + [0] In [6]: a=5 + [2] In [6]: a=5 + + # Note targets='all' means all engines + In [20]: mec.targets = 'all' + + In [21]: mec.block = True + + In [22]: mec.execute('b=10; print b') + Out[22]: + + [0] In [7]: b=10; print b + [0] Out[7]: 10 + + [1] In [6]: b=10; print b + [1] Out[6]: 10 + + [2] In [7]: b=10; print b + [2] Out[7]: 10 + + [3] In [6]: b=10; print b + [3] Out[6]: 10 + +The ``block`` and ``targets`` instance attributes also determine the behavior of the parallel +magic commands... + + +Parallel magic commands +----------------------- + +We provide a few IPython magic commands (``%px``, ``%autopx`` and ``%result``) that make it more pleasant to execute Python commands on the engines interactively. These are simply shortcuts to ``execute`` and ``get_result``. The ``%px`` magic executes a single Python command on the engines specified by the `magicTargets``targets` attribute of the ``MultiEngineClient`` instance (by default this is 'all'):: + + # Make this MultiEngineClient active for parallel magic commands + In [23]: mec.activate() + + In [24]: mec.block=True + + In [25]: import numpy + + In [26]: %px import numpy + Executing command on Controller + Out[26]: + + [0] In [8]: import numpy + [1] In [7]: import numpy + [2] In [8]: import numpy + [3] In [7]: import numpy + + + In [27]: %px a = numpy.random.rand(2,2) + Executing command on Controller + Out[27]: + + [0] In [9]: a = numpy.random.rand(2,2) + [1] In [8]: a = numpy.random.rand(2,2) + [2] In [9]: a = numpy.random.rand(2,2) + [3] In [8]: a = numpy.random.rand(2,2) + + + In [28]: %px print numpy.linalg.eigvals(a) + Executing command on Controller + Out[28]: + + [0] In [10]: print numpy.linalg.eigvals(a) + [0] Out[10]: [ 1.28167017 0.14197338] + + [1] In [9]: print numpy.linalg.eigvals(a) + [1] Out[9]: [-0.14093616 1.27877273] + + [2] In [10]: print numpy.linalg.eigvals(a) + [2] Out[10]: [-0.37023573 1.06779409] + + [3] In [9]: print numpy.linalg.eigvals(a) + [3] Out[9]: [ 0.83664764 -0.25602658] + +The ``%result`` magic gets and prints the stdin/stdout/stderr of the last command executed on each engine. It is simply a shortcut to the ``get_result`` method:: + + In [29]: %result + Out[29]: + + [0] In [10]: print numpy.linalg.eigvals(a) + [0] Out[10]: [ 1.28167017 0.14197338] + + [1] In [9]: print numpy.linalg.eigvals(a) + [1] Out[9]: [-0.14093616 1.27877273] + + [2] In [10]: print numpy.linalg.eigvals(a) + [2] Out[10]: [-0.37023573 1.06779409] + + [3] In [9]: print numpy.linalg.eigvals(a) + [3] Out[9]: [ 0.83664764 -0.25602658] + +The ``%autopx`` magic switches to a mode where everything you type is executed on the engines given by the ``targets`` attribute:: + + In [30]: mec.block=False + + In [31]: %autopx + Auto Parallel Enabled + Type %autopx to disable + + In [32]: max_evals = [] + + + In [33]: for i in range(100): + ....: a = numpy.random.rand(10,10) + ....: a = a+a.transpose() + ....: evals = numpy.linalg.eigvals(a) + ....: max_evals.append(evals[0].real) + ....: + ....: + + + In [34]: %autopx + Auto Parallel Disabled + + In [35]: mec.block=True + + In [36]: px print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) + Executing command on Controller + Out[36]: + + [0] In [13]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) + [0] Out[13]: Average max eigenvalue is: 10.1387247332 + + [1] In [12]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) + [1] Out[12]: Average max eigenvalue is: 10.2076902286 + + [2] In [13]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) + [2] Out[13]: Average max eigenvalue is: 10.1891484655 + + [3] In [12]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) + [3] Out[12]: Average max eigenvalue is: 10.1158837784 + +Using the ``with`` statement of Python 2.5 +------------------------------------------ + +Python 2.5 introduced the ``with`` statement. The ``MultiEngineClient`` can be used with the ``with`` statement to execute a block of code on the engines indicated by the ``targets`` attribute:: + + In [3]: with mec: + ...: client.remote() # Required so the following code is not run locally + ...: a = 10 + ...: b = 30 + ...: c = a+b + ...: + ...: + + In [4]: mec.get_result() + Out[4]: + + [0] In [1]: a = 10 + b = 30 + c = a+b + + [1] In [1]: a = 10 + b = 30 + c = a+b + + [2] In [1]: a = 10 + b = 30 + c = a+b + + [3] In [1]: a = 10 + b = 30 + c = a+b + +This is basically another way of calling execute, but one with allows you to avoid writing code in strings. When used in this way, the attributes ``targets`` and ``block`` are used to control how the code is executed. For now, if you run code in non-blocking mode you won't have access to the ``PendingResult``. + +Moving Python object around +=========================== + +In addition to executing code on engines, you can transfer Python objects to and from your +IPython session and the engines. In IPython, these operations are called ``push`` (sending an +object to the engines) and ``pull`` (getting an object from the engines). + +Basic push and pull +------------------- + +Here are some examples of how you use ``push`` and ``pull``:: + + In [38]: mec.push(dict(a=1.03234,b=3453)) + Out[38]: [None, None, None, None] + + In [39]: mec.pull('a') + Out[39]: [1.03234, 1.03234, 1.03234, 1.03234] + + In [40]: mec.pull('b',targets=0) + Out[40]: [3453] + + In [41]: mec.pull(('a','b')) + Out[41]: [[1.03234, 3453], [1.03234, 3453], [1.03234, 3453], [1.03234, 3453]] + + In [42]: mec.zip_pull(('a','b')) + Out[42]: [(1.03234, 1.03234, 1.03234, 1.03234), (3453, 3453, 3453, 3453)] + + In [43]: mec.push(dict(c='speed')) + Out[43]: [None, None, None, None] + + In [44]: %px print c + Executing command on Controller + Out[44]: + + [0] In [14]: print c + [0] Out[14]: speed + + [1] In [13]: print c + [1] Out[13]: speed + + [2] In [14]: print c + [2] Out[14]: speed + + [3] In [13]: print c + [3] Out[13]: speed + +In non-blocking mode ``push`` and ``pull`` also return ``PendingResult`` objects:: + + In [47]: mec.block=False + + In [48]: pr = mec.pull('a') + + In [49]: pr.r + Out[49]: [1.03234, 1.03234, 1.03234, 1.03234] + + +Push and pull for functions +--------------------------- + +Functions can also be pushed and pulled using ``push_function`` and ``pull_function``:: + + In [53]: def f(x): + ....: return 2.0*x**4 + ....: + + In [54]: mec.push_function(dict(f=f)) + Out[54]: [None, None, None, None] + + In [55]: mec.execute('y = f(4.0)') + Out[55]: + + [0] In [15]: y = f(4.0) + [1] In [14]: y = f(4.0) + [2] In [15]: y = f(4.0) + [3] In [14]: y = f(4.0) + + + In [56]: px print y + Executing command on Controller + Out[56]: + + [0] In [16]: print y + [0] Out[16]: 512.0 + + [1] In [15]: print y + [1] Out[15]: 512.0 + + [2] In [16]: print y + [2] Out[16]: 512.0 + + [3] In [15]: print y + [3] Out[15]: 512.0 + + +Dictionary interface +-------------------- + +As a shorthand to ``push`` and ``pull``, the ``MultiEngineClient`` class implements some of the Python dictionary interface. This make the remote namespaces of the engines appear as a local dictionary. Underneath, this uses ``push`` and ``pull``:: + + In [50]: mec.block=True + + In [51]: mec['a']=['foo','bar'] + + In [52]: mec['a'] + Out[52]: [['foo', 'bar'], ['foo', 'bar'], ['foo', 'bar'], ['foo', 'bar']] + +Scatter and gather +------------------ + +Sometimes it is useful to partition a sequence and push the partitions to different engines. In +MPI language, this is know as scatter/gather and we follow that terminology. However, it is +important to remember that in IPython ``scatter`` is from the interactive IPython session to +the engines and ``gather`` is from the engines back to the interactive IPython session. For +scatter/gather operations between engines, MPI should be used:: + + In [58]: mec.scatter('a',range(16)) + Out[58]: [None, None, None, None] + + In [59]: px print a + Executing command on Controller + Out[59]: + + [0] In [17]: print a + [0] Out[17]: [0, 1, 2, 3] + + [1] In [16]: print a + [1] Out[16]: [4, 5, 6, 7] + + [2] In [17]: print a + [2] Out[17]: [8, 9, 10, 11] + + [3] In [16]: print a + [3] Out[16]: [12, 13, 14, 15] + + + In [60]: mec.gather('a') + Out[60]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + +Other things to look at +======================= + +Parallel map +------------ + +Python's builtin ``map`` functions allows a function to be applied to a sequence element-by-element. This type of code is typically trivial to parallelize. In fact, the MultiEngine interface in IPython already has a parallel version of ``map`` that works just like its serial counterpart:: + + In [63]: serial_result = map(lambda x:x**10, range(32)) + + In [64]: parallel_result = mec.map(lambda x:x**10, range(32)) + + In [65]: serial_result==parallel_result + Out[65]: True + +As you would expect, the parallel version of ``map`` is also influenced by the ``block`` and ``targets`` keyword arguments and attributes. + +How to do parallel list comprehensions +-------------------------------------- + +In many cases list comprehensions are nicer than using the map function. While we don't have fully parallel list comprehensions, it is simple to get the basic effect using ``scatter`` and ``gather``:: + + In [66]: mec.scatter('x',range(64)) + Out[66]: [None, None, None, None] + + In [67]: px y = [i**10 for i in x] + Executing command on Controller + Out[67]: + + [0] In [19]: y = [i**10 for i in x] + [1] In [18]: y = [i**10 for i in x] + [2] In [19]: y = [i**10 for i in x] + [3] In [18]: y = [i**10 for i in x] + + + In [68]: y = mec.gather('y') + + In [69]: print y + [0, 1, 1024, 59049, 1048576, 9765625, 60466176, 282475249, 1073741824,...] + +Parallel Exceptions +------------------- + +In the MultiEngine interface, parallel commands can raise Python exceptions, just like serial commands. But, it is a little subtle, because a single parallel command can actually raise multiple exceptions (one for each engine the command was run on). To express this idea, the MultiEngine interface has a ``CompositeError`` exception class that will be raised in most cases. The ``CompositeError`` class is a special type of exception that wraps one or more other types of exceptions. Here is how it works:: + + In [76]: mec.block=True + + In [77]: mec.execute('1/0') + --------------------------------------------------------------------------- + CompositeError Traceback (most recent call last) + + /ipython1-client-r3021/docs/examples/ in () + + /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in execute(self, lines, targets, block) + 432 targets, block = self._findTargetsAndBlock(targets, block) + 433 result = blockingCallFromThread(self.smultiengine.execute, lines, + --> 434 targets=targets, block=block) + 435 if block: + 436 result = ResultList(result) + + /ipython1-client-r3021/ipython1/kernel/twistedutil.pyc in blockingCallFromThread(f, *a, **kw) + 72 result.raiseException() + 73 except Exception, e: + ---> 74 raise e + 75 return result + 76 + + CompositeError: one or more exceptions from call to method: execute + [0:execute]: ZeroDivisionError: integer division or modulo by zero + [1:execute]: ZeroDivisionError: integer division or modulo by zero + [2:execute]: ZeroDivisionError: integer division or modulo by zero + [3:execute]: ZeroDivisionError: integer division or modulo by zero + +Notice how the error message printed when ``CompositeError`` is raised has information about the individual exceptions that were raised on each engine. If you want, you can even raise one of these original exceptions:: + + In [80]: try: + ....: mec.execute('1/0') + ....: except client.CompositeError, e: + ....: e.raise_exception() + ....: + ....: + --------------------------------------------------------------------------- + ZeroDivisionError Traceback (most recent call last) + + /ipython1-client-r3021/docs/examples/ in () + + /ipython1-client-r3021/ipython1/kernel/error.pyc in raise_exception(self, excid) + 156 raise IndexError("an exception with index %i does not exist"%excid) + 157 else: + --> 158 raise et, ev, etb + 159 + 160 def collect_exceptions(rlist, method): + + ZeroDivisionError: integer division or modulo by zero + +If you are working in IPython, you can simple type ``%debug`` after one of these ``CompositeError`` is raised, and inspect the exception instance:: + + In [81]: mec.execute('1/0') + --------------------------------------------------------------------------- + CompositeError Traceback (most recent call last) + + /ipython1-client-r3021/docs/examples/ in () + + /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in execute(self, lines, targets, block) + 432 targets, block = self._findTargetsAndBlock(targets, block) + 433 result = blockingCallFromThread(self.smultiengine.execute, lines, + --> 434 targets=targets, block=block) + 435 if block: + 436 result = ResultList(result) + + /ipython1-client-r3021/ipython1/kernel/twistedutil.pyc in blockingCallFromThread(f, *a, **kw) + 72 result.raiseException() + 73 except Exception, e: + ---> 74 raise e + 75 return result + 76 + + CompositeError: one or more exceptions from call to method: execute + [0:execute]: ZeroDivisionError: integer division or modulo by zero + [1:execute]: ZeroDivisionError: integer division or modulo by zero + [2:execute]: ZeroDivisionError: integer division or modulo by zero + [3:execute]: ZeroDivisionError: integer division or modulo by zero + + In [82]: %debug + > + + /ipython1-client-r3021/ipython1/kernel/twistedutil.py(74)blockingCallFromThread() + 73 except Exception, e: + ---> 74 raise e + 75 return result + + # With the debugger running, e is the exceptions instance. We can tab complete + # on it and see the extra methods that are available. + ipdb> e. + e.__class__ e.__getitem__ e.__new__ e.__setstate__ e.args + e.__delattr__ e.__getslice__ e.__reduce__ e.__str__ e.elist + e.__dict__ e.__hash__ e.__reduce_ex__ e.__weakref__ e.message + e.__doc__ e.__init__ e.__repr__ e._get_engine_str e.print_tracebacks + e.__getattribute__ e.__module__ e.__setattr__ e._get_traceback e.raise_exception + ipdb> e.print_tracebacks() + [0:execute]: + --------------------------------------------------------------------------- + ZeroDivisionError Traceback (most recent call last) + + /ipython1-client-r3021/docs/examples/ in () + + ZeroDivisionError: integer division or modulo by zero + + [1:execute]: + --------------------------------------------------------------------------- + ZeroDivisionError Traceback (most recent call last) + + /ipython1-client-r3021/docs/examples/ in () + + ZeroDivisionError: integer division or modulo by zero + + [2:execute]: + --------------------------------------------------------------------------- + ZeroDivisionError Traceback (most recent call last) + + /ipython1-client-r3021/docs/examples/ in () + + ZeroDivisionError: integer division or modulo by zero + + [3:execute]: + --------------------------------------------------------------------------- + ZeroDivisionError Traceback (most recent call last) + + /ipython1-client-r3021/docs/examples/ in () + + ZeroDivisionError: integer division or modulo by zero + +All of this same error handling magic even works in non-blocking mode:: + + In [83]: mec.block=False + + In [84]: pr = mec.execute('1/0') + + In [85]: pr.r + --------------------------------------------------------------------------- + CompositeError Traceback (most recent call last) + + /ipython1-client-r3021/docs/examples/ in () + + /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in _get_r(self) + 170 + 171 def _get_r(self): + --> 172 return self.get_result(block=True) + 173 + 174 r = property(_get_r) + + /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in get_result(self, default, block) + 131 return self.result + 132 try: + --> 133 result = self.client.get_pending_deferred(self.result_id, block) + 134 except error.ResultNotCompleted: + 135 return default + + /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in get_pending_deferred(self, deferredID, block) + 385 + 386 def get_pending_deferred(self, deferredID, block): + --> 387 return blockingCallFromThread(self.smultiengine.get_pending_deferred, deferredID, block) + 388 + 389 def barrier(self, pendingResults): + + /ipython1-client-r3021/ipython1/kernel/twistedutil.pyc in blockingCallFromThread(f, *a, **kw) + 72 result.raiseException() + 73 except Exception, e: + ---> 74 raise e + 75 return result + 76 + + CompositeError: one or more exceptions from call to method: execute + [0:execute]: ZeroDivisionError: integer division or modulo by zero + [1:execute]: ZeroDivisionError: integer division or modulo by zero + [2:execute]: ZeroDivisionError: integer division or modulo by zero + [3:execute]: ZeroDivisionError: integer division or modulo by zero + + diff --git a/docs/source/parallel/parallel_task.txt b/docs/source/parallel/parallel_task.txt new file mode 100644 index 0000000..0f44dde --- /dev/null +++ b/docs/source/parallel/parallel_task.txt @@ -0,0 +1,240 @@ +.. _paralleltask: + +================================= +The IPython Task interface +================================= + +.. contents:: + +The ``Task`` interface to the controller presents the engines as a fault tolerant, dynamic load-balanced system or workers. Unlike the ``MultiEngine`` interface, in the ``Task`` interface, the user have no direct access to individual engines. In some ways, this interface is simpler, but in other ways it is more powerful. Best of all the user can use both of these interfaces at the same time to take advantage or both of their strengths. When the user can break up the user's work into segments that do not depend on previous execution, the ``Task`` interface is ideal. But it also has more power and flexibility, allowing the user to guide the distribution of jobs, without having to assign Tasks to engines explicitly. + +Starting the IPython controller and engines +=========================================== + +To follow along with this tutorial, the user will need to start the IPython +controller and four IPython engines. The simplest way of doing this is to +use the ``ipcluster`` command:: + + $ ipcluster -n 4 + +For more detailed information about starting the controller and engines, see our :ref:`introduction ` to using IPython for parallel computing. + +The magic here is that this single controller and set of engines is running both the MultiEngine and ``Task`` interfaces simultaneously. + +QuickStart Task Farming +======================= + +First, a quick example of how to start running the most basic Tasks. +The first step is to import the IPython ``client`` module and then create a ``TaskClient`` instance:: + + In [1]: from ipython1.kernel import client + + In [2]: tc = client.TaskClient() + +Then the user wrap the commands the user want to run in Tasks:: + + In [3]: tasklist = [] + In [4]: for n in range(1000): + ... tasklist.append(client.Task("a = %i"%n, pull="a")) + +The first argument of the ``Task`` constructor is a string, the command to be executed. The most important optional keyword argument is ``pull``, which can be a string or list of strings, and it specifies the variable names to be saved as results of the ``Task``. + +Next, the user need to submit the Tasks to the ``TaskController`` with the ``TaskClient``:: + + In [5]: taskids = [ tc.run(t) for t in tasklist ] + +This will give the user a list of the TaskIDs used by the controller to keep track of the Tasks and their results. Now at some point the user are going to want to get those results back. The ``barrier`` method allows the user to wait for the Tasks to finish running:: + + In [6]: tc.barrier(taskids) + +This command will block until all the Tasks in ``taskids`` have finished. Now, the user probably want to look at the user's results:: + + In [7]: task_results = [ tc.get_task_result(taskid) for taskid in taskids ] + +Now the user have a list of ``TaskResult`` objects, which have the actual result as a dictionary, but also keep track of some useful metadata about the ``Task``:: + + In [8]: tr = ``Task``_results[73] + + In [9]: tr + Out[9]: ``TaskResult``[ID:73]:{'a':73} + + In [10]: tr.engineid + Out[10]: 1 + + In [11]: tr.submitted, tr.completed, tr.duration + Out[11]: ("2008/03/08 03:41:42", "2008/03/08 03:41:44", 2.12345) + +The actual results are stored in a dictionary, ``tr.results``, and a namespace object ``tr.ns`` which accesses the result keys by attribute:: + + In [12]: tr.results['a'] + Out[12]: 73 + + In [13]: tr.ns.a + Out[13]: 73 + +That should cover the basics of running simple Tasks. There are several more powerful things the user can do with Tasks covered later. The most useful probably being using a ``MutiEngineClient`` interface to initialize all the engines with the import dependencies necessary to run the user's Tasks. + +There are many options for running and managing Tasks. The best way to learn further about the ``Task`` interface is to study the examples in ``docs/examples``. If the user do so and learn a lots about this interface, we encourage the user to expand this documentation about the ``Task`` system. + +Overview of the Task System +=========================== + +The user's view of the ``Task`` system has three basic objects: The ``TaskClient``, the ``Task``, and the ``TaskResult``. The names of these three objects well indicate their role. + +The ``TaskClient`` is the user's ``Task`` farming connection to the IPython cluster. Unlike the ``MultiEngineClient``, the ``TaskControler`` handles all the scheduling and distribution of work, so the ``TaskClient`` has no notion of engines, it just submits Tasks and requests their results. The Tasks are described as ``Task`` objects, and their results are wrapped in ``TaskResult`` objects. Thus, there are very few necessary methods for the user to manage. + +Inside the task system is a Scheduler object, which assigns tasks to workers. The default scheduler is a simple FIFO queue. Subclassing the Scheduler should be easy, just implementing your own priority system. + +The TaskClient +============== + +The ``TaskClient`` is the object the user use to connect to the ``Controller`` that is managing the user's Tasks. It is the analog of the ``MultiEngineClient`` for the standard IPython multiplexing interface. As with all client interfaces, the first step is to import the IPython Client Module:: + + In [1]: from ipython1.kernel import client + +Just as with the ``MultiEngineClient``, the user create the ``TaskClient`` with a tuple, containing the ip-address and port of the ``Controller``. the ``client`` module conveniently has the default address of the ``Task`` interface of the controller. Creating a default ``TaskClient`` object would be done with this:: + + In [2]: tc = client.TaskClient(client.default_task_address) + +or, if the user want to specify a non default location of the ``Controller``, the user can specify explicitly:: + + In [3]: tc = client.TaskClient(("192.168.1.1", 10113)) + +As discussed earlier, the ``TaskClient`` only has a few basic methods. + + * ``tc.run(task)`` + ``run`` is the method by which the user submits Tasks. It takes exactly one argument, a ``Task`` object. All the advanced control of ``Task`` behavior is handled by properties of the ``Task`` object, rather than the submission command, so they will be discussed later in the `Task`_ section. ``run`` returns an integer, the ``Task``ID by which the ``Task`` and its results can be tracked and retrieved:: + + In [4]: ``Task``ID = tc.run(``Task``) + + * ``tc.get_task_result(taskid, block=``False``)`` + ``get_task_result`` is the method by which results are retrieved. It takes a single integer argument, the ``Task``ID`` of the result the user wish to retrieve. ``get_task_result`` also takes a keyword argument ``block``. ``block`` specifies whether the user actually want to wait for the result. If ``block`` is false, as it is by default, ``get_task_result`` will return immediately. If the ``Task`` has completed, it will return the ``TaskResult`` object for that ``Task``. But if the ``Task`` has not completed, it will return ``None``. If the user specify ``block=``True``, then ``get_task_result`` will wait for the ``Task`` to complete, and always return the ``TaskResult`` for the requested ``Task``. + * ``tc.barrier(taskid(s))`` + ``barrier`` is a synchronization method. It takes exactly one argument, a ``Task``ID or list of taskIDs. ``barrier`` will block until all the specified Tasks have completed. In practice, a barrier is often called between the ``Task`` submission section of the code and the result gathering section:: + + In [5]: taskIDs = [ tc.run(``Task``) for ``Task`` in myTasks ] + + In [6]: tc.get_task_result(taskIDs[-1]) is None + Out[6]: ``True`` + + In [7]: tc.barrier(``Task``ID) + + In [8]: results = [ tc.get_task_result(tid) for tid in taskIDs ] + + * ``tc.queue_status(verbose=``False``)`` + ``queue_status`` is a method for querying the state of the ``TaskControler``. ``queue_status`` returns a dict of the form:: + + {'scheduled': Tasks that have been submitted but yet run + 'pending' : Tasks that are currently running + 'succeeded': Tasks that have completed successfully + 'failed' : Tasks that have finished with a failure + } + + if @verbose is not specified (or is ``False``), then the values of the dict are integers - the number of Tasks in each state. if @verbose is ``True``, then each element in the dict is a list of the taskIDs in that state:: + + In [8]: tc.queue_status() + Out[8]: {'scheduled': 4, + 'pending' : 2, + 'succeeded': 5, + 'failed' : 1 + } + + In [9]: tc.queue_status(verbose=True) + Out[9]: {'scheduled': [8,9,10,11], + 'pending' : [6,7], + 'succeeded': [0,1,2,4,5], + 'failed' : [3] + } + + * ``tc.abort(taskid)`` + ``abort`` allows the user to abort Tasks that have already been submitted. ``abort`` will always return immediately. If the ``Task`` has completed, ``abort`` will raise an ``IndexError ``Task`` Already Completed``. An obvious case for ``abort`` would be where the user submits a long-running ``Task`` with a number of retries (see ``Task``_ section for how to specify retries) in an interactive session, but realizes there has been a typo. The user can then abort the ``Task``, preventing certain failures from cluttering up the queue. It can also be used for parallel search-type problems, where only one ``Task`` will give the solution, so once the user find the solution, the user would want to abort all remaining Tasks to prevent wasted work. + * ``tc.spin()`` + ``spin`` simply triggers the scheduler in the ``TaskControler``. Under most normal circumstances, this will do nothing. The primary known usage case involves the ``Task`` dependency (see `Dependencies`_). The dependency is a function of an Engine's ``properties``, but changing the ``properties`` via the ``MutliEngineClient`` does not trigger a reschedule event. The main example case for this requires the following event sequence: + * ``engine`` is available, ``Task`` is submitted, but ``engine`` does not have ``Task``'s dependencies. + * ``engine`` gets necessary dependencies while no new Tasks are submitted or completed. + * now ``engine`` can run ``Task``, but a ``Task`` event is required for the ``TaskControler`` to try scheduling ``Task`` again. + + ``spin`` is just an empty ping method to ensure that the Controller has scheduled all available Tasks, and should not be needed under most normal circumstances. + +That covers the ``TaskClient``, a simple interface to the cluster. With this, the user can submit jobs (and abort if necessary), request their results, synchronize on arbitrary subsets of jobs. + +.. _task: The Task Object + +The Task Object +=============== + +The ``Task`` is the basic object for describing a job. It can be used in a very simple manner, where the user just specifies a command string to be executed as the ``Task``. The usage of this first argument is exactly the same as the ``execute`` method of the ``MultiEngine`` (in fact, ``execute`` is called to run the code):: + + In [1]: t = client.Task("a = str(id)") + +This ``Task`` would run, and store the string representation of the ``id`` element in ``a`` in each worker's namespace, but it is fairly useless because the user does not know anything about the state of the ``worker`` on which it ran at the time of retrieving results. It is important that each ``Task`` not expect the state of the ``worker`` to persist after the ``Task`` is completed. +There are many different situations for using ``Task`` Farming, and the ``Task`` object has many attributes for use in customizing the ``Task`` behavior. All of a ``Task``'s attributes may be specified in the constructor, through keyword arguments, or after ``Task`` construction through attribute assignment. + +Data Attributes +*************** +It is likely that the user may want to move data around before or after executing the ``Task``. We provide methods of sending data to initialize the worker's namespace, and specifying what data to bring back as the ``Task``'s results. + + * pull = [] + The obvious case is as above, where ``t`` would execute and store the result of ``myfunc`` in ``a``, it is likely that the user would want to bring ``a`` back to their namespace. This is done through the ``pull`` attribute. ``pull`` can be a string or list of strings, and it specifies the names of variables to be retrieved. The ``TaskResult`` object retrieved by ``get_task_result`` will have a dictionary of keys and values, and the ``Task``'s ``pull`` attribute determines what goes into it:: + + In [2]: t = client.Task("a = str(id)", pull = "a") + + In [3]: t = client.Task("a = str(id)", pull = ["a", "id"]) + + * push = {} + A user might also want to initialize some data into the namespace before the code part of the ``Task`` is run. Enter ``push``. ``push`` is a dictionary of key/value pairs to be loaded from the user's namespace into the worker's immediately before execution:: + + In [4]: t = client.Task("a = f(submitted)", push=dict(submitted=time.time()), pull="a") + +push and pull result directly in calling an ``engine``'s ``push`` and ``pull`` methods before and after ``Task`` execution respectively, and thus their api is the same. + +Namespace Cleaning +****************** +When a user is running a large number of Tasks, it is likely that the namespace of the worker's could become cluttered. Some Tasks might be sensitive to clutter, while others might be known to cause namespace pollution. For these reasons, Tasks have two boolean attributes for cleaning up the namespace. + + * ``clear_after`` + if clear_after is specified ``True``, the worker on which the ``Task`` was run will be reset (via ``engine.reset``) upon completion of the ``Task``. This can be useful for both Tasks that produce clutter or Tasks whose intermediate data one might wish to be kept private:: + + In [5]: t = client.Task("a = range(1e10)", pull = "a",clear_after=True) + + + * ``clear_before`` + as one might guess, clear_before is identical to ``clear_after``, but it takes place before the ``Task`` is run. This ensures that the ``Task`` runs on a fresh worker:: + + In [6]: t = client.Task("a = globals()", pull = "a",clear_before=True) + +Of course, a user can both at the same time, ensuring that all workers are clear except when they are currently running a job. Both of these default to ``False``. + +Fault Tolerance +*************** +It is possible that Tasks might fail, and there are a variety of reasons this could happen. One might be that the worker it was running on disconnected, and there was nothing wrong with the ``Task`` itself. With the fault tolerance attributes of the ``Task``, the user can specify how many times to resubmit the ``Task``, and what to do if it never succeeds. + + * ``retries`` + ``retries`` is an integer, specifying the number of times a ``Task`` is to be retried. It defaults to zero. It is often a good idea for this number to be 1 or 2, to protect the ``Task`` from disconnecting engines, but not a large number. If a ``Task`` is failing 100 times, there is probably something wrong with the ``Task``. The canonical bad example: + + In [7]: t = client.Task("os.kill(os.getpid(), 9)", retries=99) + + This would actually take down 100 workers. + + * ``recovery_task`` + ``recovery_task`` is another ``Task`` object, to be run in the event of the original ``Task`` still failing after running out of retries. Since ``recovery_task`` is another ``Task`` object, it can have its own ``recovery_task``. The chain of Tasks is limitless, except loops are not allowed (that would be bad!). + +Dependencies +************ +Dependencies are the most powerful part of the ``Task`` farming system, because it allows the user to do some classification of the workers, and guide the ``Task`` distribution without meddling with the controller directly. It makes use of two objects - the ``Task``'s ``depend`` attribute, and the engine's ``properties``. See the `MultiEngine`_ reference for how to use engine properties. The engine properties api exists for extending IPython, allowing conditional execution and new controllers that make decisions based on properties of its engines. Currently the ``Task`` dependency is the only internal use of the properties api. + +.. _MultiEngine: ./parallel_multiengine + +The ``depend`` attribute of a ``Task`` must be a function of exactly one argument, the worker's properties dictionary, and it should return ``True`` if the ``Task`` should be allowed to run on the worker and ``False`` if not. The usage in the controller is fault tolerant, so exceptions raised by ``Task.depend`` will be ignored and functionally equivalent to always returning ``False``. Tasks`` with invalid ``depend`` functions will never be assigned to a worker:: + + In [8]: def dep(properties): + ... return properties["RAM"] > 2**32 # have at least 4GB + In [9]: t = client.Task("a = bigfunc()", depend=dep) + +It is important to note that assignment of values to the properties dict is done entirely by the user, either locally (in the engine) using the EngineAPI, or remotely, through the ``MultiEngineClient``'s get/set_properties methods. + + + + + +