Calculation algorithm "*4DVAR*"
-------------------------------
-.. ------------------------------------ ..
-.. include:: snippets/Header2Algo00.rst
-
.. ------------------------------------ ..
.. include:: snippets/Header2Algo01.rst
Calculation algorithm "*DifferentialEvolution*"
----------------------------------------------------
-.. ------------------------------------ ..
-.. include:: snippets/Header2Algo00.rst
-
.. ------------------------------------ ..
.. include:: snippets/Header2Algo01.rst
Checking algorithm "*LocalSensitivityTest*"
-------------------------------------------
-.. ------------------------------------ ..
-.. include:: snippets/Header2Algo00.rst
-
.. ------------------------------------ ..
.. include:: snippets/Header2Algo01.rst
.. index:: single: Optimal positioning of measurements
.. index:: single: Measurement locations
.. index:: single: Measurements (Optimal positioning)
+.. index:: single: Ensemble of simulations
+.. index:: single: Ensemble of snapshots
+.. index:: single: Simulations (Ensemble)
+.. index:: single: Snapshots (Ensemble)
.. _section_ref_algorithm_MeasurementsOptimalPositioningTask:
Task algorithm "*MeasurementsOptimalPositioningTask*"
.. include:: snippets/Header2Algo10.rst
.. literalinclude:: scripts/simple_ParallelFunctionTest.res
+ :language: none
.. ------------------------------------ ..
.. include:: snippets/Header2Algo06.rst
Algorithme de calcul "*4DVAR*"
------------------------------
-.. ------------------------------------ ..
-.. include:: snippets/Header2Algo00.rst
-
.. ------------------------------------ ..
.. include:: snippets/Header2Algo01.rst
Algorithme de calcul "*DifferentialEvolution*"
----------------------------------------------
-.. ------------------------------------ ..
-.. include:: snippets/Header2Algo00.rst
-
.. ------------------------------------ ..
.. include:: snippets/Header2Algo01.rst
Algorithme de vérification "*LocalSensitivityTest*"
---------------------------------------------------
-.. ------------------------------------ ..
-.. include:: snippets/Header2Algo00.rst
-
.. ------------------------------------ ..
.. include:: snippets/Header2Algo01.rst
)
self.setAttributes(tags=(
"Reduction",
+ "Checking",
))
def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
--- /dev/null
+This is to announce the release of version 1.8 of Gnuplot.py.
+
+Gnuplot.py is a Python [1] package that allows you to create graphs
+from within Python using the gnuplot [2] plotting program.
+
+Gnuplot.py can be obtained from
+
+ http://gnuplot-py.sourceforge.net/
+
+Prerequisites (see footnotes):
+ the Python interpreter [1]
+ the Python numpy module [3]
+ the gnuplot program [2]
+
+or, to use it under Java (experimental):
+ a Java interpreter
+ the Jython interpreter [4]
+ the Jython version of the Numeric module [5]
+ the gnuplot program [2]
+
+Some ways this package can be used:
+
+1. Interactive data processing: Use Python's excellent numpy package
+ to create and manipulate arrays of numbers, and use Gnuplot.py to
+ visualize the results.
+2. Web graphics: write CGI scripts in Python that use gnuplot to
+ output plots in (for example) PNG format and return them to the
+ client.
+3. Glue for numerical applications (this is my favorite): wrap your
+ C++/C/Fortran subroutines so that they are callable from Python,
+ then you can perform numerical computations interactively from
+ scripts or from the command line and use Gnuplot.py to plot the
+ output on the fly.
+4. Compute a series of datasets in Python and plot them one after the
+ other using Gnuplot.py to produce a crude animation.
+
+New features in this version:
+ + Various bug fixes
+ + an option "filename" to Data and GridDat
+ This allows saving the data to a permanent, rather than temporary
+ + pdf terminal definition
+
+Features already present in older versions:
+
+ + Two and three-dimensional plots.
+ + Plot data from memory, from a file, or from an expression.
+ + Support for multiple simultaneous gnuplot sessions.
+ + Can pass arbitrary commands to the gnuplot program.
+ + Object oriented, extensible design with several built-in types
+ of plot items.
+ + Portable and easy to install (nothing to compile except on
+ Windows).
+ + Support for Unix (including Linux and Mac OS X), MS Windows, and
+ Mac OS. The platform-dependent layer is fairly well abstracted
+ out, so it shouldn't be too difficult to add support for other
+ platforms.
+ + Support for sending data to gnuplot as `inline' or `binary' data.
+ These are optimizations that also remove the need for temporary
+ files.
+ + Partly table-driven to make it easy to extend. New terminal
+ types can be supported easily by adding data to a table.
+ + Install via distutils.
+ + LGPL license .
+ + Support for sending data to gnuplot via FIFOs (named pipes, linux only).
+ + Preliminary support for running Gnuplot.py under Jython
+
+Footnotes:
+----------
+[1] Python <http://www.python.org> is an excellent object-oriented
+ scripting/rapid development language that is also especially good
+ at gluing programs together.
+[2] gnuplot <http://www.gnuplot.info/> is a free, popular, very
+ portable plotting program with a command-line interface. It can
+ make 2-d and 3-d plots and can output to myriad printers and
+ graphics terminals.
+[3] The numpy Python extension <http://www.scipy.org> is a
+ Python module that adds fast and convenient array manipulations to
+ the Python language.
+[4] Jython <http://www.jython.org> is a Python interpreter that runs
+ within a Java virtual machine.
+[5] JNumeric <http://jnumerical.sourceforge.net/> is a version of the
+ Numeric module that runs under Java/Jython.
+
--- /dev/null
+CREDITS:
+
+Gnuplot.py was written by Michael Haggerty <mhagger@alum.mit.edu>,
+inspired by and partly derived from an earlier version by Konrad
+Hinsen. I maintain it and continue to develop it, though by now it
+has most of the features that I had planned for it.
+
+I would like to acknowledge and express my appreciation to the
+following people for their contributions:
+
+Konrad Hinsen <hinsen@ibs.ibs.fr> wrote the first, procedural
+interface version of Gnuplot.py. His code is still present in many
+components of the current version. The oldplot.py module, which used
+to be included in Gnuplot.py for backwards compatibility with his
+version, hasn't been supported for a while so I deleted it.
+
+Berthold Hoellmann <bhoel@starship.python.net> introduced me to the
+helpful `pythondoc' package, and contributed some docstring changes to
+allow web documentation to be generated from the Gnuplot.py source.
+He also submitted a setup.py file to be used with Python distutils.
+
+Craig Schardt <lazrnerd@ufl.edu> and Francois Ladouceur
+<f.ladouceur@virtualphotonics.com> contributed changes to enable
+Gnuplot.py to work under MS-Windows.
+
+Tony Ingraldi <a.m.ingraldi@larc.nasa.gov> got Gnuplot.py to work on
+the Macintosh and Noburu Yamamoto also contributed to this code.
+
+Stuard Reynolds <S.I.Reynolds@cs.bham.ac.uk> made some helpful
+suggestions for automating the tabulation of function values.
+
+Jannie Hofmeyr <jhsh@iafrica.com> suggested using "from os import
+popen" in gp_win32.py for versions of Python subsequent to 2.0.
+
+Daehyok Shin <sdhyok@email.unc.edu> pointed out that support for the
+`axes' keyword was missing.
+
+Jon Moody suggested some changes for Mac OS.
+
+Andy Main contributed terminal_opts for metapost output.
+
+Matthew Fulmer contributed a patch to add the "filename" argument to
+Data and GridData.
+
+Benny Malengier will push out new versions if the need arises starting
+from 1.8
+
--- /dev/null
+# Id: Errors.py 244 2003-04-21 09:44:09Z mhagger
+
+# Copyright (C) 2001-2003 Michael Haggerty <mhagger@alum.mit.edu>
+#
+# This file is licensed under the GNU Lesser General Public License
+# (LGPL). See LICENSE.txt for details.
+
+"""Exception types that can be raised by Gnuplot.py."""
+
+
+class Error(Exception):
+ """All our exceptions are derived from this one."""
+ pass
+
+
+class OptionError(Error):
+ """Raised for unrecognized option(s)"""
+ pass
+
+
+class DataError(Error):
+ """Raised for data in the wrong format"""
+ pass
+
+
--- /dev/null
+# Id: FAQ.txt 294 2006-11-07 02:33:08Z parejkoj
+
+Frequently Asked Questions
+
+This file is meant to answer the most frequently asked questions about
+the Gnuplot.py package. If you want to suggest additional questions
+(with or without answers!) please mail them to the Gnuplot.py users
+mailing list, <gnuplot-py-users@lists.sourceforge.net>.
+
+======================================================================
+
+Q1:
+
+When running the following script
+
+------------------------------------------------
+#! /usr/bin/python2
+
+import Gnuplot, Gnuplot.funcutils
+from numpy import *
+
+g = Gnuplot.Gnuplot()
+g.plot([[0,1.1], [1,5.8], [2,3.3], [3,4.2]])
+------------------------------------------------
+
+I get the error
+
+ gnuplot> plot '/tmp/@24463.2'
+ ^
+ can't read data file "/tmp/@24463.2"
+ line 0: (No such file or directory)
+
+However, the same commands work fine if I type them into the
+interpreter! What's wrong?
+
+A1:
+
+The problem is that in many cases Gnuplot.py sends data to gnuplot via
+a temporary file. But Gnuplot.py has no way of knowing when it is
+safe to delete the temporary file. So it deletes it when the
+corresponding PlotItem object is deleted, which is typically when the
+next Gnuplot.plot() command is executed or when the python script
+ends. (Until you plot something else, the Gnuplot object keeps a
+reference to all of the old plot items to prevent their being garbage
+collected.)
+
+To prevent this problem, there are several possibilities:
+
+1. Switch to Unix. On that platform, Gnuplot.py now uses FIFOs (named
+ pipes) by default to send data to gnuplot. This seems to provide a
+ robust and somewhat elegant solution to this problem.
+
+2. Use "inline data" instead of temporary files to communicate with
+ gnuplot. This is already available in gnuplot for most plotting
+ modes if you specify the "inline=1" option to the constructor of
+ the Data object, or if you set GnuplotOpts.prefer_inline_data=1.
+ Since inline data doesn't involve temporary files, the problem goes
+ away.
+
+3. Introduce a delay between the time you plot and the time you allow
+ the Data object to be deleted. You could just use time.sleep(), or
+ if you are producing a graphics file you might watch for the
+ creation of the output file and at that point assume that gnuplot
+ is done with the temporary file. One idea is to explicitly create
+ a PlotItem to represent the data, and keep a reference to the
+ PlotItem for some time after the plot() command is executed; e.g.,
+
+ data = Gnuplot.Data([[0,1.1], [1,5.8], [2,3.3], [3,4.2]])
+ g.plot(data)
+ # ... do something guaranteed to last a couple seconds
+ del data # temporary file is deleted at this moment
+
+4. Change Gnuplot.py itself to implement two-way communication between
+ gnuplot and Gnuplot.py. Then, for example, Gnuplot.py could delete
+ temporary files when the next gnuplot prompt appears. This would
+ be a lot of work but it would allow other new features such as
+ detecting gnuplot errors, reading gnuplot fit command output back
+ to python, etc.
+
+======================================================================
+
+Q2:
+
+Does Gnuplot.py work under Jython/Java?
+
+A2:
+
+Partly. Version 1.7 added the low-level interface gp_java.py for
+communicating with gnuplot using the Java libraries, and that part
+seems to work.
+
+However, Gnuplot.py relies on the Python Numeric library, which is a C
+library. The Jython equivalent, called JNumeric
+<http://jnumerical.sourceforge.net/>, therefore has to be installed.
+However, JNumeric is still at beta level, and operation under Jython
+hasn't been tested much at all, so feedback is welcome!
+
+======================================================================
+
+Q3:
+
+[from Tate Wilson]
+
+I am trying to set up your gnuplot/python package on my mac (osX).
+The readme file says I need to convert the files to mac text files.
+The coverter I usually use, maclink, won't handle these files. Can
+you give me a hint how to convert the files or where to look for help?
+
+A3:
+
+I don't know. But the same user later reported what worked for him:
+
+I did have to convert the files. It may not be true for all mac
+Python users, but I suspect it is. I'm using a graphical Python
+development environment called "Python IDE for mac" which may have its
+own pickiness, but still, it wouldn't even recognize the files in your
+package as being the type it could open. I tried a few different file
+converters with no luck. Then I just opened all the files with
+BBedit, changed something so I would be prompted to save it on closing
+(like add and remove a letter), and closed BBedit. Then all the files
+were 'mac' files and the Python interpreter recognised them.
+
+======================================================================
+
+Q4:
+
+I am using Windows and I get an error like
+
+> Traceback (most recent call last):
+> [...]
+> File "C:\Python23\Lib\site-packages\Gnuplot\gp_win32.py",
+> line 125, in __call__
+> self.write(s + '\n')
+> IOError: [Errno 22] Invalid argument
+
+What is the problem?
+
+A4:
+
+This is apparently the error that results when Gnuplot.py cannot start
+the pgnuplot.exe executable under Windows. It could be that gnuplot
+(the plotting program, as opposed to Gnuplot.py) is not installed, or
+that it is not in your PATH. If your pgnuplot.exe executable is named
+differently, or you do not want to add its directory to your PATH, you
+can change gnuplot_command in gp_win32.py to indicate the precise path
+to the executable.
+
--- /dev/null
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL. It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it. You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+ When we speak of free software, we are referring to freedom of use,
+not price. Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+ To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights. These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ To protect each distributor, we want to make it very clear that
+there is no warranty for the free library. Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+\f
+ Finally, software patents pose a constant threat to the existence of
+any free program. We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder. Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+ Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License. This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License. We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+ When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library. The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom. The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+ We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License. It also provides other free software developers Less
+of an advantage over competing non-free programs. These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries. However, the Lesser license provides advantages in certain
+special circumstances.
+
+ For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard. To achieve this, non-free programs must be
+allowed to use the library. A more frequent case is that a free
+library does the same job as widely used non-free libraries. In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+ In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software. For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+ Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+\f
+ GNU LESSER GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+\f
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+\f
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+\f
+ 6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (1) uses at run time a
+ copy of the library already present on the user's computer system,
+ rather than copying library functions into the executable, and (2)
+ will operate properly with a modified version of the library, if
+ the user installs one, as long as the modified version is
+ interface-compatible with the version that the work was made with.
+
+ c) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ d) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ e) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+\f
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+\f
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+\f
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+\f
+ How to Apply These Terms to Your New Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the library's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+ <signature of Ty Coon>, 1 April 1990
+ Ty Coon, President of Vice
+
+That's all there is to it!
+
+
--- /dev/null
+Id: NEWS.txt 302 2008-01-14 22:15:19Z bmcage
+
+This file describes the changes introduced in each version of the
+Gnuplot.py package.
+
+Version ?.?
+
+Version 1.8:
+
+* hardcopy allows for terminal='svg' (using a patch from Spyros Blanas)
+
+* Use with_ instead of with as that will be a python keyword in the
+ future.
+
+* Added an option "filename" to Data and GridData in PlotItems.py.
+ This allows saving the data to a permanent, rather than temporary,
+ file. (Patch contributed by Matthew Fulmer.)
+
+* Added a 'pdf' terminal definition (using a patch from Jim Kleckner).
+
+* Added close() and __del__() methods to the Gnuplot class. This
+ might help with some cases of premature temporary file deletion.
+ (Suggested by Jim Kleckner.)
+
+
+Version 1.7:
+
+* Relaxed license from GPL to LGPL.
+
+* Significant reorganization of PlotItem.py:
+
+ + Deleted the AnyFile classes from PlotItem: AnyFile, TempFile,
+ ArrayFile, and TempArrayFile. Those classes weren't pulling their
+ weight.
+
+ + Added a new _FileItem class to represent all forms of data that
+ gnuplot treats as a file.
+
+ + Added a new _TempFileItem class to represent PlotItems that are
+ based on a temporary file.
+
+ + Added a new _InlineFileItem class to represent PlotItems whose
+ data is passed to gnuplot inline.
+
+ + Changed PlotItems.File() and PlotItems.Data from classes into
+ factory functions that produce instances of the classes mentioned
+ above.
+
+* Slightly changed the PlotItem interface to support the new derived
+ classes:
+
+ + Removed the basecommand argument to the constructor. Instead
+ added a get_base_command_string() method to retrieve that string.
+ This function is not defined in PlotItem so it is added to the
+ derived classes. (This function is used by _FIFOFileItem as the
+ hook where _FIFOWriters are created.
+
+ + Added a new get_command_option_string() method which abstracts out
+ the construction of the option part of the command() method.
+
+* Added support for sending data to gnuplot via FIFOs (named pipes)
+ via a new _FIFOFileItem class. This mechanism removes the ambiguity
+ about when temporary files should be deleted, therefore making it
+ easier to use Gnuplot.py in script environments, etc. This feature
+ is only implemented under *nix because Python doesn't implement the
+ required threading module and os.mkfifo() on other operating
+ systems. Added two new configuration options, support_fifo and
+ prefer_fifo_data, to the gp_*.py files to switch the new feature on
+ and off.
+
+* Started adding support for running Gnuplot.py under Jython/Java.
+ Added gp_java.py, which is a functioning low-level interface to
+ gnuplot via java.lang.Process objects. The rest might work, too, if
+ you have JNumeric <http://jnumerical.sourceforge.net/> installed.
+ (Gnuplot.py relies on the Numeric library; JNumeric is the Jython
+ equivalent.) If I find the time I might try to produce a version
+ that doesn't require Numeric at all, under either Python or Jython.
+
+* Removed the oldplot.py module: (1) I doubt anybody is still using
+ it. (2) It seems to be broken anyway. (3) I don't have the energy to
+ fix or maintain it. Let me know if I'm wrong about point 1.
+
+* Started a new FAQ.txt file and added an answer to the single most
+ frequently asked question.
+
+
+Version 1.6:
+
+* Introduced a general mechanism to make it easy to support multiple
+ gnuplot terminal types in the Gnuplot.hardcopy() function. Added
+ definitions for 'postscript', 'png', 'fig', and 'cgm'. Other
+ terminal types can now be added easily.
+
+* Changed names of Exceptions to be more consistent with other
+ modules: OptionException -> OptionError and DataException ->
+ DataError. Moved both to Errors.py and derive both from
+ Errors.Error.
+
+* Incorporated several changes for Mac OS suggested by Jon Moody.
+
+* Added a gp_macosx.py file to support Mac OS X. The only difference
+ between this and gp_unix.py is the default terminal selection.
+
+* Moved import statement in demo.py to global scope for Python 2.2.
+
+* Removed claims that demo.py can be run before installing Gnuplot.py.
+
+
+Version 1.5:
+
+* Broke up the module a bit for better maintainability. The most
+ commonly-used facilities are still available through "import
+ Gnuplot", but a few more specialized things have been moved to
+ separate modules, in particular funcutils.py and PlotItems.py.
+ __init__.py now just imports things from other modules.
+
+* funcutils.tabulate_function() can be used to evaluate a function
+ on a 1-D or 2-D grid of points (this replaces grid_function,
+ which only worked with 2-D grids).
+
+* Added two helper functions, funcutils.compute_Data and
+ funcutils.compute_GridData, which compute a function's values on
+ a set of points and package the results into a PlotItem.
+
+* GridFunc is no longer an independent class; it is now a factory
+ function that returns a GridData. GridFunc is deprecated in
+ favor of funcutils.compute_GridData.
+
+* Changed set_option to work from a table, so that it doesn't need to
+ be overloaded so often.
+
+* Made changes like those submitted by Matthew Martin
+ <r47854@email.sps.mot.com> to allow the `smooth' option.
+
+* Implemented test_persist for each platform to make it easier for
+ users to determine whether the `-persist' option is supported.
+
+* Added a prefer_persist option to serve as the default `persist'
+ choice.
+
+* Following a suggestion by Jannie Hofmeyr <jhsh@iafrica.com>, use
+ "from os import popen" for Python 2.0 under Windows. I don't use
+ Windows, so let me know how this works.
+
+* Added a setup.py file so that Gnuplot.py can be installed using
+ Python distutils.
+
+* Added support for the `axes' parameter of the `plot' command.
+
+* Reworked the comment strings in an effort to make them work nicely
+ with happydoc.
+
+
+Version 1.4:
+
+* Added support for the Macintosh, thanks to help from Tony Ingraldi.
+
+* Split the platform-dependent code, including the configuration
+ options, into separate modules: gp.py, gp_mac.py, and gp_win32.py.
+ The GnuplotProcess class defined in those files is a lightweight
+ interface to the gnuplot program that could also conceivably be
+ useful to somebody.
+
+* Allow access to all of the postscript printer driver options through
+ the hardcopy() method.
+
+* Fixed an import problem in test.py.
+
+
+Version 1.3:
+
+* Converted to package format. The main file is now called
+ __init__.py, so that it can be loaded by typing 'import Gnuplot'.
+
+* Passing GridData a callable function was basically broken because of
+ the kludgey way of overloading the argument. Instead of trying to
+ fix it, I moved that functionality to a new type of PlotItem
+ called 'GridFunc'.
+
+* Added a new keyword argument, 'ufunc', to grid_function and to
+ GridFunc. If that argument is nonzero, then the function is
+ evaluated matrix-wise (in that case it must be composed only of
+ ufunctions or ufunction-like routines).
+
+* Fixed a 'typecode' problem with grid_function (typecode is
+ apparently a positional, not a keyword, argument in the Numeric
+ library).
+
+* Separated the demonstration code into a separate file, demo.py, to
+ shorten __init__.py a bit.
+
+
+Version 1.2 (8 Aug 1999):
+
+* Support for MS Windows, using the `pgnuplot.exe' program.
+ Thanks go especially to Craig Schardt for help with this.
+
+* Support for using binary files to send grid data to splot.
+ This saves a lot of time and usually saves space compared with
+ the old text files. (Only works with recent versions of
+ gnuplot.)
+
+* Support for sending data to gnuplot as `inline data' (i.e., "plot
+ '-'"). This method should be faster than the alternate method,
+ temporary files. (Only works with recent versions of gnuplot.)
+
+* Allows PlotItem options to be modified after the PlotItem is
+ constructed.
+
+* Simplified the PlotItem inheritance hierarchy (Data and GridData are
+ no longer derived from File).
+
+* Added several configuration options (see top of Gnuplot.py).
+
+* Separated function-based interface into a separate file
+ (Gnuplot_plot.py).
+
+* Added a test module, Gnuplot_test.py, which tests most of the
+ features of Gnuplot.py.
+
+* A README file, lots of documentation changes, etc.
+
+
+Version 1.1a (9 Apr 1999):
+
+This version just addresses a couple of minor portability issues.
+
+
+Version 1.1 (31 Jan 1999):
+
+* 3-D plots are now supported through the new 'splot' method:
+ + To create a scatter plot, pass splot a 2-D array containing
+ (x,y,z) triplets;
+ + To create a grid plot, pass a 3-D array consisting of a 2-D array
+ of (x,y,z) triplets; or
+ + Use the new `GridData' PlotItem to plot gridded data (data
+ tabulated on a rectangular grid).
+
+* It is now easier to pass data to gnuplot. The 'Data' PlotItem now
+ accepts multiple arguments representing subsequent 'columns' of the
+ dataset; e.g., what used to be written as
+
+ g = Gnuplot.Gnuplot()
+ x = numpy.arange(100)/10.0
+ y = x**2
+ # Create an array of (x,y) pairs:
+ g.plot(Gnuplot.Data(numpy.transpose((x, y))))
+
+ can now be shortened to
+
+ # Plot y vs. x directly:
+ g.plot(Gnuplot.Data(x, y))
+
+ (both examples plot x squared vs. x). Similarly, splot can be
+ passed three arrays representing the values of x, y, and z.
+ Note that the old interpretation is still used if a single
+ argument is passed to `Data'.
+
--- /dev/null
+# Id: PlotItems.py 299 2007-03-30 12:52:17Z mhagger
+
+# Copyright (C) 1998-2003 Michael Haggerty <mhagger@alum.mit.edu>
+#
+# This file is licensed under the GNU Lesser General Public License
+# (LGPL). See LICENSE.txt for details.
+
+"""PlotItems.py -- Objects that can be plotted by Gnuplot.
+
+This module contains several types of PlotItems. PlotItems can be
+plotted by passing them to a Gnuplot.Gnuplot object. You can derive
+your own classes from the PlotItem hierarchy to customize their
+behavior.
+
+"""
+
+import os, string, tempfile, types
+
+from io import StringIO
+
+import numpy
+
+import gp
+import Gnuplot.Errors as Errors
+import Gnuplot.utils as utils
+
+
+class _unset:
+ """Used to represent unset keyword arguments."""
+
+ pass
+
+
+class PlotItem:
+ """Plotitem represents an item that can be plotted by gnuplot.
+
+ For the finest control over the output, you can create 'PlotItems'
+ yourself with additional keyword options, or derive new classes
+ from 'PlotItem'.
+
+ The handling of options is complicated by the attempt to allow
+ options and their setting mechanism to be inherited conveniently.
+ Note first that there are some options that can only be set in the
+ constructor then never modified, and others that can be set in the
+ constructor and/or modified using the 'set_option()' member
+ function. The former are always processed within '__init__'. The
+ latter are always processed within 'set_option', which is called
+ by the constructor.
+
+ 'set_option' is driven by a class-wide dictionary called
+ '_option_list', which is a mapping '{ <option> : <setter> }' from
+ option name to the function object used to set or change the
+ option. <setter> is a function object that takes two parameters:
+ 'self' (the 'PlotItem' instance) and the new value requested for
+ the option. If <setter> is 'None', then the option is not allowed
+ to be changed after construction and an exception is raised.
+
+ Any 'PlotItem' that needs to add options can add to this
+ dictionary within its class definition. Follow one of the
+ examples in this file. Alternatively it could override the
+ 'set_option' member function if it needs to do wilder things.
+
+ Members:
+
+ '_basecommand' -- a string holding the elementary argument that
+ must be passed to gnuplot's `plot' command for this item;
+ e.g., 'sin(x)' or '"filename.dat"'.
+
+ '_options' -- a dictionary of (<option>,<string>) tuples
+ corresponding to the plot options that have been set for
+ this instance of the PlotItem. <option> is the option as
+ specified by the user; <string> is the string that needs to
+ be set in the command line to set that option (or None if no
+ string is needed). Example::
+
+ {'title' : ('Data', 'title "Data"'),
+ 'with' : ('linespoints', 'with linespoints')}
+
+ """
+
+ # For _option_list explanation, see docstring for PlotItem.
+ _option_list = {
+ 'axes' : lambda self, axes: self.set_string_option(
+ 'axes', axes, None, 'axes %s'),
+ 'with' : lambda self, with_: self.set_string_option(
+ 'with', with_, None, 'with %s'),
+ 'title' : lambda self, title: self.set_string_option(
+ 'title', title, 'notitle', 'title "%s"'),
+ }
+ _option_list['with_'] = _option_list['with']
+
+ # order in which options need to be passed to gnuplot:
+ _option_sequence = [
+ 'binary',
+ 'index', 'every', 'thru', 'using', 'smooth',
+ 'axes', 'title', 'with'
+ ]
+
+ def __init__(self, **keyw):
+ """Construct a 'PlotItem'.
+
+ Keyword options:
+
+ 'with_=<string>' -- choose how item will be plotted, e.g.,
+ with_='points 3 3'.
+
+ 'title=<string>' -- set the title to be associated with the item
+ in the plot legend.
+
+ 'title=None' -- choose 'notitle' option (omit item from legend).
+
+ Note that omitting the title option is different than setting
+ 'title=None'; the former chooses gnuplot's default whereas the
+ latter chooses 'notitle'.
+
+ """
+
+ self._options = {}
+ self.set_option(**keyw)
+
+ def get_option(self, name):
+ """Return the setting of an option. May be overridden."""
+
+ try:
+ return self._options[name][0]
+ except:
+ raise KeyError('option %s is not set!' % name)
+
+ def set_option(self, **keyw):
+ """Set or change a plot option for this PlotItem.
+
+ See documentation for '__init__' for information about allowed
+ options. This function can be overridden by derived classes
+ to allow additional options, in which case those options will
+ also be allowed by '__init__' for the derived class. However,
+ it is easier to define a new '_option_list' variable for the
+ derived class.
+
+ """
+
+ for (option, value) in keyw.items():
+ try:
+ setter = self._option_list[option]
+ except KeyError:
+ raise Errors.OptionError('%s=%s' % (option,value))
+ if setter is None:
+ raise Errors.OptionError(
+ 'Cannot modify %s option after construction!', option)
+ else:
+ setter(self, value)
+
+ def set_string_option(self, option, value, default, fmt):
+ """Set an option that takes a string value."""
+
+ if value is None:
+ self._options[option] = (value, default)
+ elif type(value) is str:
+ self._options[option] = (value, fmt % value)
+ else:
+ Errors.OptionError('%s=%s' % (option, value,))
+
+ def clear_option(self, name):
+ """Clear (unset) a plot option. No error if option was not set."""
+
+ try:
+ del self._options[name]
+ except KeyError:
+ pass
+
+ def get_base_command_string(self):
+ raise NotImplementedError()
+
+ def get_command_option_string(self):
+ cmd = []
+ for opt in self._option_sequence:
+ (val,str) = self._options.get(opt, (None,None))
+ if str is not None:
+ cmd.append(str)
+ return " ".join(cmd)
+
+ def command(self):
+ """Build the plot command to be sent to gnuplot.
+
+ Build and return the plot command, with options, necessary to
+ display this item. If anything else needs to be done once per
+ plot, it can be done here too.
+
+ """
+
+ return " ".join([
+ self.get_base_command_string(),
+ self.get_command_option_string(),
+ ])
+
+ def pipein(self, f):
+ """Pipe necessary inline data to gnuplot.
+
+ If the plot command requires data to be put on stdin (i.e.,
+ 'plot "-"'), this method should put that data there. Can be
+ overridden in derived classes.
+
+ """
+
+ pass
+
+
+class Func(PlotItem):
+ """Represents a mathematical expression to plot.
+
+ Func represents a mathematical expression that is to be computed by
+ gnuplot itself, as if you would type for example::
+
+ gnuplot> plot sin(x)
+
+ into gnuplot itself. The argument to the contructor is a string
+ that should be a mathematical expression. Example::
+
+ g.plot(Func('sin(x)', with_='line 3'))
+
+ As shorthand, a string passed to the plot method of a Gnuplot
+ object is also treated as a Func::
+
+ g.plot('sin(x)')
+
+ """
+
+ def __init__(self, function, **keyw):
+ PlotItem.__init__(self, **keyw)
+ self.function = function
+
+ def get_base_command_string(self):
+ return self.function
+
+
+class _FileItem(PlotItem):
+ """A PlotItem representing a file that contains gnuplot data.
+
+ This class is not meant for users but rather as a base class for
+ other types of FileItem.
+
+ """
+
+ _option_list = PlotItem._option_list.copy()
+ _option_list.update({
+ 'binary' : lambda self, binary: self.set_option_binary(binary),
+ 'index' : lambda self, value: self.set_option_colonsep('index', value),
+ 'every' : lambda self, value: self.set_option_colonsep('every', value),
+ 'using' : lambda self, value: self.set_option_colonsep('using', value),
+ 'smooth' : lambda self, smooth: self.set_string_option(
+ 'smooth', smooth, None, 'smooth %s'
+ ),
+ })
+
+ def __init__(self, filename, **keyw):
+ """Represent a PlotItem that gnuplot treates as a file.
+
+ This class holds the information that is needed to construct
+ the plot command line, including options that are specific to
+ file-like gnuplot input.
+
+ <filename> is a string representing the filename to be passed
+ to gnuplot within quotes. It may be the name of an existing
+ file, '-' for inline data, or the name of a named pipe.
+
+ Keyword arguments:
+
+ 'using=<int>' -- plot that column against line number
+
+ 'using=<tuple>' -- plot using a:b:c:d etc. Elements in
+ the tuple that are None are output as the empty
+ string.
+
+ 'using=<string>' -- plot `using <string>' (allows gnuplot's
+ arbitrary column arithmetic)
+
+ 'every=<value>' -- plot 'every <value>'. <value> is
+ formatted as for 'using' option.
+
+ 'index=<value>' -- plot 'index <value>'. <value> is
+ formatted as for 'using' option.
+
+ 'binary=<boolean>' -- data in the file is in binary format
+ (this option is only allowed for grid data for splot).
+
+ 'smooth=<string>' -- smooth the data. Option should be
+ 'unique', 'csplines', 'acsplines', 'bezier', or
+ 'sbezier'.
+
+ The keyword arguments recognized by 'PlotItem' can also be
+ used here.
+
+ Note that the 'using' option is interpreted by gnuplot, so
+ columns must be numbered starting with 1.
+
+ By default, gnuplot uses the name of the file plus any 'using'
+ option as the dataset title. If you want another title, set
+ it explicitly using the 'title' option.
+
+ """
+
+ self.filename = filename
+
+ PlotItem.__init__(self, **keyw)
+
+ def get_base_command_string(self):
+ return gp.double_quote_string(self.filename)
+
+ def set_option_colonsep(self, name, value):
+ if value is None:
+ self.clear_option(name)
+ elif type(value) in [str, int]:
+ self._options[name] = (value, '%s %s' % (name, value,))
+ elif type(value) is tuple:
+ subopts = []
+ for subopt in value:
+ if subopt is None:
+ subopts.append('')
+ else:
+ subopts.append(str(subopt))
+ self._options[name] = (
+ value,
+ '%s %s' % (name, ":".join(subopts),),
+ )
+ else:
+ raise Errors.OptionError('%s=%s' % (name, value,))
+
+ def set_option_binary(self, binary):
+ if binary:
+ if not gp.GnuplotOpts.recognizes_binary_splot:
+ raise Errors.OptionError(
+ 'Gnuplot.py is currently configured to reject binary data')
+ self._options['binary'] = (1, 'binary')
+ else:
+ self._options['binary'] = (0, None)
+
+
+class _NewFileItem(_FileItem):
+ def __init__(self, content, filename=None, **keyw):
+
+ binary = keyw.get('binary', 0)
+ if binary:
+ mode = 'wb'
+ else:
+ mode = 'w'
+
+ if filename:
+ # This is a permanent file
+ self.temp = False
+ f = open(filename, mode)
+ else:
+ self.temp = True
+ if hasattr(tempfile, 'mkstemp'):
+ # Use the new secure method of creating temporary files:
+ (fd, filename,) = tempfile.mkstemp(
+ suffix='.gnuplot', text=(not binary)
+ )
+ f = os.fdopen(fd, mode)
+ else:
+ # for backwards compatibility to pre-2.3:
+ filename = tempfile.mktemp()
+ f = open(filename, mode)
+
+ f.write(content)
+ f.close()
+
+ # If the user hasn't specified a title, set it to None so
+ # that the name of the temporary file is not used:
+ if self.temp and 'title' not in keyw:
+ keyw['title'] = None
+
+ _FileItem.__init__(self, filename, **keyw)
+
+ def __del__(self):
+ if self.temp:
+ os.unlink(self.filename)
+
+
+class _InlineFileItem(_FileItem):
+ """A _FileItem that actually indicates inline data.
+
+ """
+
+ def __init__(self, content, **keyw):
+ # If the user hasn't specified a title, set it to None so that
+ # '-' is not used:
+ if 'title' not in keyw:
+ keyw['title'] = None
+
+ if keyw.get('binary', 0):
+ raise Errors.OptionError('binary inline data is not supported')
+
+ _FileItem.__init__(self, '-', **keyw)
+
+ if content[-1] == '\n':
+ self.content = content
+ else:
+ self.content = content + '\n'
+
+ def pipein(self, f):
+ f.write(self.content + 'e\n')
+
+
+if gp.GnuplotOpts.support_fifo:
+ import threading
+
+ class _FIFOWriter(threading.Thread):
+ """Create a FIFO (named pipe), write to it, then delete it.
+
+ The writing takes place in a separate thread so that the main
+ thread is not blocked. The idea is that once the writing is
+ finished we know that gnuplot is done with the data that were in
+ the file so we can delete the file. This technique removes the
+ ambiguity about when the temporary files should be deleted.
+
+ Since the tempfile module does not provide an easy, secure way
+ to create a FIFO without race conditions, we instead create a
+ temporary directory using mkdtemp() then create the FIFO
+ within that directory. When the writer thread has written the
+ full information to the FIFO, it deletes both the FIFO and the
+ temporary directory that contained it.
+
+ """
+
+ def __init__(self, content, mode='w'):
+ self.content = content
+ self.mode = mode
+ if hasattr(tempfile, 'mkdtemp'):
+ # Make the file within a temporary directory that is
+ # created securely:
+ self.dirname = tempfile.mkdtemp(suffix='.gnuplot')
+ self.filename = os.path.join(self.dirname, 'fifo')
+ else:
+ # For backwards compatibility pre-2.3, just use
+ # mktemp() to create filename:
+ self.dirname = None
+ self.filename = tempfile.mktemp()
+ threading.Thread.__init__(
+ self,
+ name=('FIFO Writer for %s' % (self.filename,)),
+ )
+ os.mkfifo(self.filename)
+ self.start()
+
+ def run(self):
+ f = open(self.filename, self.mode)
+ f.write(self.content)
+ f.close()
+ os.unlink(self.filename)
+ if self.dirname is not None:
+ os.rmdir(self.dirname)
+
+
+ class _FIFOFileItem(_FileItem):
+ """A _FileItem based on a FIFO (named pipe).
+
+ This class depends on the availablity of os.mkfifo(), which only
+ exists under Unix.
+
+ """
+
+ def __init__(self, content, **keyw):
+ # If the user hasn't specified a title, set it to None so that
+ # the name of the temporary FIFO is not used:
+ if 'title' not in keyw:
+ keyw['title'] = None
+
+ _FileItem.__init__(self, '', **keyw)
+ self.content = content
+ if keyw.get('binary', 0):
+ self.mode = 'wb'
+ else:
+ self.mode = 'w'
+
+ def get_base_command_string(self):
+ """Create the gnuplot command for plotting this item.
+
+ The basecommand is different each time because each FIFOWriter
+ creates a new FIFO.
+
+ """
+
+ # Create a new FIFO and a thread to write to it. Retrieve the
+ # filename of the FIFO to be used in the basecommand.
+ fifo = _FIFOWriter(self.content, self.mode)
+ return gp.double_quote_string(fifo.filename)
+
+
+def File(filename, **keyw):
+ """Construct a _FileItem object referring to an existing file.
+
+ This is a convenience function that just returns a _FileItem that
+ wraps the filename.
+
+ <filename> is a string holding the filename of an existing file.
+ The keyword arguments are the same as those of the _FileItem
+ constructor.
+
+ """
+
+ if type(filename) is not str:
+ raise Errors.OptionError(
+ 'Argument (%s) must be a filename' % (filename,)
+ )
+ return _FileItem(filename, **keyw)
+
+
+def Data(*data, **keyw):
+ """Create and return a _FileItem representing the data from *data.
+
+ Create a '_FileItem' object (which is a type of 'PlotItem') out of
+ one or more Float Python numpy arrays (or objects that can be
+ converted to a float numpy array). If the routine is passed a
+ single with multiple dimensions, then the last index ranges over
+ the values comprising a single data point (e.g., [<x>, <y>,
+ <sigma>]) and the rest of the indices select the data point. If
+ passed a single array with 1 dimension, then each point is
+ considered to have only one value (i.e., by default the values
+ will be plotted against their indices). If the routine is passed
+ more than one array, they must have identical shapes, and then
+ each data point is composed of one point from each array. E.g.,
+ 'Data(x,x**2)' is a 'PlotItem' that represents x squared as a
+ function of x. For the output format, see the comments for
+ 'write_array()'.
+
+ How the data are written to gnuplot depends on the 'inline'
+ argument and preference settings for the platform in use.
+
+ Keyword arguments:
+
+ 'cols=<tuple>' -- write only the specified columns from each
+ data point to the file. Since cols is used by python, the
+ columns should be numbered in the python style (starting
+ from 0), not the gnuplot style (starting from 1).
+
+ 'inline=<bool>' -- transmit the data to gnuplot 'inline'
+ rather than through a temporary file. The default is the
+ value of gp.GnuplotOpts.prefer_inline_data.
+
+ 'filename=<string>' -- save data to a permanent file.
+
+ The keyword arguments recognized by '_FileItem' can also be used
+ here.
+
+ """
+
+ if len(data) == 1:
+ # data was passed as a single structure
+ data = utils.float_array(data[0])
+
+ # As a special case, if passed a single 1-D array, then it is
+ # treated as one value per point (by default, plotted against
+ # its index):
+ if len(data.shape) == 1:
+ data = data[:,numpy.newaxis]
+ else:
+ # data was passed column by column (for example,
+ # Data(x,y)); pack it into one big array (this will test
+ # that sizes are all the same):
+ data = utils.float_array(data)
+ dims = len(data.shape)
+ # transpose so that the last index selects x vs. y:
+ data = numpy.transpose(data, (dims-1,) + tuple(range(dims-1)))
+ if 'cols' in keyw:
+ cols = keyw['cols']
+ del keyw['cols']
+ if isinstance(cols, int):
+ cols = (cols,)
+ data = numpy.take(data, cols, -1)
+
+ if 'filename' in keyw:
+ filename = keyw['filename'] or None
+ del keyw['filename']
+ else:
+ filename = None
+
+ if 'inline' in keyw:
+ inline = keyw['inline']
+ del keyw['inline']
+ if inline and filename:
+ raise Errors.OptionError(
+ 'cannot pass data both inline and via a file'
+ )
+ else:
+ inline = (not filename) and gp.GnuplotOpts.prefer_inline_data
+
+ # Output the content into a string:
+ f = StringIO()
+ utils.write_array(f, data)
+ content = f.getvalue()
+ if inline:
+ return _InlineFileItem(content, **keyw)
+ elif filename:
+ return _NewFileItem(content, filename=filename, **keyw)
+ elif gp.GnuplotOpts.prefer_fifo_data:
+ return _FIFOFileItem(content, **keyw)
+ else:
+ return _NewFileItem(content, **keyw)
+
+
+def GridData(
+ data, xvals=None, yvals=None, inline=_unset, filename=None, **keyw
+ ):
+ """Return a _FileItem representing a function of two variables.
+
+ 'GridData' represents a function that has been tabulated on a
+ rectangular grid. The data are written to a file; no copy is kept
+ in memory.
+
+ Arguments:
+
+ 'data' -- the data to plot: a 2-d array with dimensions
+ (numx,numy).
+
+ 'xvals' -- a 1-d array with dimension 'numx'
+
+ 'yvals' -- a 1-d array with dimension 'numy'
+
+ 'binary=<bool>' -- send data to gnuplot in binary format?
+
+ 'inline=<bool>' -- send data to gnuplot "inline"?
+
+ 'filename=<string>' -- save data to a permanent file.
+
+ Note the unusual argument order! The data are specified *before*
+ the x and y values. (This inconsistency was probably a mistake;
+ after all, the default xvals and yvals are not very useful.)
+
+ 'data' must be a data array holding the values of a function
+ f(x,y) tabulated on a grid of points, such that 'data[i,j] ==
+ f(xvals[i], yvals[j])'. If 'xvals' and/or 'yvals' are omitted,
+ integers (starting with 0) are used for that coordinate. The data
+ are written to a temporary file; no copy of the data is kept in
+ memory.
+
+ If 'binary=0' then the data are written to a datafile as 'x y
+ f(x,y)' triplets (y changes most rapidly) that can be used by
+ gnuplot's 'splot' command. Blank lines are included each time the
+ value of x changes so that gnuplot knows to plot a surface through
+ the data.
+
+ If 'binary=1' then the data are written to a file in a binary
+ format that 'splot' can understand. Binary format is faster and
+ usually saves disk space but is not human-readable. If your
+ version of gnuplot doesn't support binary format (it is a
+ recently-added feature), this behavior can be disabled by setting
+ the configuration variable
+ 'gp.GnuplotOpts.recognizes_binary_splot=0' in the appropriate
+ gp*.py file.
+
+ Thus if you have three arrays in the above format and a Gnuplot
+ instance called g, you can plot your data by typing
+ 'g.splot(Gnuplot.GridData(data,xvals,yvals))'.
+
+ """
+
+ # Try to interpret data as an array:
+ data = utils.float_array(data)
+ try:
+ (numx, numy) = data.shape
+ except ValueError:
+ raise Errors.DataError('data array must be two-dimensional')
+
+ if xvals is None:
+ xvals = numpy.arange(numx)
+ else:
+ xvals = utils.float_array(xvals)
+ if xvals.shape != (numx,):
+ raise Errors.DataError(
+ 'The size of xvals must be the same as the size of '
+ 'the first dimension of the data array')
+
+ if yvals is None:
+ yvals = numpy.arange(numy)
+ else:
+ yvals = utils.float_array(yvals)
+ if yvals.shape != (numy,):
+ raise Errors.DataError(
+ 'The size of yvals must be the same as the size of '
+ 'the second dimension of the data array')
+
+ # Binary defaults to true if recognizes_binary_plot is set;
+ # otherwise it is forced to false.
+ binary = keyw.get('binary', 1) and gp.GnuplotOpts.recognizes_binary_splot
+ keyw['binary'] = binary
+
+ if inline is _unset:
+ inline = (
+ (not binary) and (not filename)
+ and gp.GnuplotOpts.prefer_inline_data
+ )
+ elif inline and filename:
+ raise Errors.OptionError(
+ 'cannot pass data both inline and via a file'
+ )
+
+ # xvals, yvals, and data are now all filled with arrays of data.
+ if binary:
+ if inline:
+ raise Errors.OptionError('binary inline data not supported')
+
+ # write file in binary format
+
+ # It seems that the gnuplot documentation for binary mode
+ # disagrees with its actual behavior (as of v. 3.7). The
+ # documentation has the roles of x and y exchanged. We ignore
+ # the documentation and go with the code.
+
+ mout = numpy.zeros((numy + 1, numx + 1), numpy.float32)
+ mout[0,0] = numx
+ mout[0,1:] = xvals.astype(numpy.float32)
+ mout[1:,0] = yvals.astype(numpy.float32)
+ try:
+ # try copying without the additional copy implied by astype():
+ mout[1:,1:] = numpy.transpose(data)
+ except:
+ # if that didn't work then downcasting from double
+ # must be necessary:
+ mout[1:,1:] = numpy.transpose(data.astype(numpy.float32))
+
+ content = mout.tostring()
+ if (not filename) and gp.GnuplotOpts.prefer_fifo_data:
+ return _FIFOFileItem(content, **keyw)
+ else:
+ return _NewFileItem(content, filename=filename, **keyw)
+ else:
+ # output data to file as "x y f(x)" triplets. This
+ # requires numy copies of each x value and numx copies of
+ # each y value. First reformat the data:
+ set = numpy.transpose(
+ numpy.array(
+ (numpy.transpose(numpy.resize(xvals, (numy, numx))),
+ numpy.resize(yvals, (numx, numy)),
+ data)), (1,2,0))
+
+ # Now output the data with the usual routine. This will
+ # produce data properly formatted in blocks separated by blank
+ # lines so that gnuplot can connect the points into a grid.
+ f = StringIO()
+ utils.write_array(f, set)
+ content = f.getvalue()
+
+ if inline:
+ return _InlineFileItem(content, **keyw)
+ elif filename:
+ return _NewFileItem(content, filename=filename, **keyw)
+ elif gp.GnuplotOpts.prefer_fifo_data:
+ return _FIFOFileItem(content, **keyw)
+ else:
+ return _NewFileItem(content, **keyw)
+
+
--- /dev/null
+Gnuplot.py -- A pipe-based interface to the gnuplot plotting program.
+
+The Gnuplot.py home page is
+
+ http://gnuplot-py.sourceforge.net
+
+There you can get the latest version, view the documentation, or
+report bugs. There is also a mailing list for Gnuplot.py users. You
+can subscribe to the mailing list or view the archive of old articles
+at
+
+ http://lists.sourceforge.net/mailman/listinfo/gnuplot-py-users
+
+
+Documentation
+-------------
+
+The quickest way to learn how to use Gnuplot.py is to install it and
+run the simple demonstration by typing `python demo.py', then look at
+the demo.py file to see the commands that created the demo. One of
+the examples is probably similar to what you want to do.
+
+Don't forget to read the Gnuplot.html, README.txt, and FAQ.txt files
+in the Gnuplot.py distribution.
+
+HTML documentation for the Python classes is included in the doc/
+directory of the distribution and is also available online (follow
+links from the home page). This documentation is extracted
+automatically from the package's docstrings using happydoc and should
+be helpful though it is known to have some formatting problems.
+Alternatively, you can look at the docstrings yourself by opening the
+python files in an editor.
+
+Finally, there is a new mailing list for Gnuplot.py users. For more
+information about subscribing to the list or viewing the archive of
+old articles, please go to
+
+ http://lists.sourceforge.net/lists/listinfo/gnuplot-py-users
+
+To get good use out of Gnuplot.py, you will want to know something
+about gnuplot, for which a good source is the gnuplot help (run
+gnuplot then type `help', or read it online at
+
+ http://www.gnuplot.info/gnuplot.html
+
+).
+
+For a relatively thorough test of Gnuplot.py, type `python test.py'
+which goes systematically through most Gnuplot.py features.
+
+
+Installation
+------------
+
+Quick instructions:
+
+1. Download gnuplot-py-1.8.tar.gz or gnuplot-py-1.8.zip.
+
+2. Extract the archive to a temporary directory.
+
+3. Install by changing to the directory and typing "python setup.py
+ install".
+
+More information:
+
+Obviously, you must have the gnuplot program if Gnuplot.py is to be of
+any use to you. Gnuplot can be obtained via
+<http://www.gnuplot.info>. You also need a copy of the numpy package, which
+is available from the Scipy group at <http://www.scipy.org/Download>.
+
+Gnuplot.py uses Python distutils
+<http://www.python.org/doc/current/inst/inst.html> and can be
+installed by untarring the package, changing into the top-level
+directory, and typing "python setup.py install". The Gnuplot.py
+package is pure Python--no compilation is necessary.
+
+Gnuplot.py is structured as a python package. That means that it
+installs itself as a subdirectory called `Gnuplot' under a directory
+of your python path (usually site-packages). If you don't want to use
+distutils you can just move the main Gnuplot.py directory there and
+rename it to "Gnuplot".
+
+There are some configuration options that can be set near the top of
+the platform-dependent files gp-unix.py (Unix), gp_mac.py (Macintosh),
+gp_macosx.py (Mac OS X), gp_win32.py (Windows), and gp_java.py
+(Jython/Java). (Obviously, you should change the file corresponding
+to your platform.) See the extensive comments in gp_unix.py for a
+description of the meaning of each configuration variable. Sensible
+values are already chosen, so it is quite possible that you don't have
+to change anything.
+
+Import the main part of the package into your python programs using
+`import Gnuplot'. Some other features can be found in the modules
+Gnuplot.funcutils and Gnuplot.PlotItems.
+
+
+Installation via RPM (for Linux/Unix)
+-------------------------------------
+
+I decided that it doesn't make sense to package up RPM versions of
+Gnuplot.py, since the place where the files need to be installed
+depends on what version of Python you are using. But if you want the
+benefits of RPM management, it's easy for you to create your own RPM
+from the source distribution then install the RPM:
+
+1. Change into the source directory.
+
+2. Create the RPM:
+
+ $ python ./setup.py bdist --format=rpm
+
+3. Install it (as root):
+
+ # rpm -ivh dist/gnuplot-py-1.7-1.noarch.rpm
+
+
+Installation on Windows
+-----------------------
+
+I don't run Windows, but thanks to the help of users there is now a
+way to use Gnuplot.py on that platform. Any feedback or additional
+suggestions having to do with Windows would be especially appreciated.
+
+Because the main MS-Windows gnuplot executable (wgnuplot.exe) doesn't
+accept commands on standard input, Gnuplot.py cannot communicate with
+it directly. However, there is a simple little program called
+`pgnuplot.exe' that accepts commands on stdin and passes them to
+wgnuplot. So to run Gnuplot.py on Windows, you need to make sure that
+pgnuplot.exe is installed. It comes with gnuplot since at least
+version 3.7.1. Alternatively you can get pgnuplot.exe alone by
+downloading `testing/windows-stdin.zip' from one of the gnuplot
+archives (e.g.,
+<ftp://ftp.gnuplot.info/pub/gnuplot/testing/windows-stdin.zip>).
+
+Continue installing Gnuplot.py by following the instructions in the
+previous section.
+
+
+Installation on the Macintosh
+-----------------------------
+
+Thanks to more user help, Gnuplot.py should work on the Macintosh too.
+(Here I am referring to Mac OS versions prior to OS X; OS X is unix so
+no special considerations apply there.)
+
+Since pipes don't exist on the Mac, communication with gnuplot is via
+a python module called gnuplot_Suites.py (included) which uses
+AppleEvents. Note that you will have to convert the python files to
+Mac text files (different end-of-line character). Currently it is not
+possible to print directly to a printer; however, it should be
+possible to print to a postscript file and print that file manually.
+Also, inline data does not seem to be supported. Let me know if you
+find other problems or have patches to fix Mac limitations.
+
+
+Assistance
+----------
+
+If you are having trouble installing or using Gnuplot.py, please check
+the following sources for help:
+
+1. Read the documentation! For simple questions, start with the
+ Gnuplot.html, README.txt, and FAQ.txt files in the distribution.
+ For more detailed information, check the online class documentation
+ at
+
+ http://gnuplot-py.sourceforge.net/doc/
+
+2. Check the mailing list archives. Chances are that somebody has
+ already asked a similar questions and you are one quick search away
+ from the answer. Information about the mailing list is available
+ at
+
+ http://lists.sourceforge.net/mailman/listinfo/gnuplot-py-users
+
+3. Ask your question on the mailing list. I am trying to move most
+ email traffic about Gnuplot.py to the mailing list, partly because
+ there are many questions (for example about Windows or Macintosh
+ platforms) that I am completely unable to answer. The mailing list
+ also provides an archive of old articles which should build up into
+ a valuable resource, and a place to exchange ideas about future
+ changes.
+
+
+Feedback
+--------
+
+I would love to have feedback from people letting me know whether they
+find Gnuplot.py useful. And certainly let me know about any problems,
+suggestions, or enhancements. For most purposes, please send your
+emails to the Gnuplot.py users mailing list:
+
+ gnuplot-py-users@lists.sourceforge.net
+
+Information about the mailing list can be obtained at
+
+ http://lists.sourceforge.net/mailman/listinfo/gnuplot-py-users
+
+
+Compatibility
+-------------
+
+Gnuplot.py has been tested with version 3.7 of gnuplot, and I believe
+it should work with version 3.5 (though some features, like enhanced
+postscript mode and binary splot mode, will not work). Let me know if
+you have trouble.
+
+Gnuplot.py was developed under Linux and Digital Unix; it should work
+without much problem on other versions of Unix. If you need to modify
+it for your system tell me what was necessary and I'll include your
+changes in a future release.
+
+Gnuplot.py should also work under Windows and Macintosh (see above).
+Feedback for these platforms is especially appreciated since I can't
+test them myself.
+
+
+License
+-------
+
+See the file LICENSE.txt for license info. In brief, Gnuplot is LGPL.
+
+
+Credits
+-------
+
+See CREDITS.txt for a list of people who have contributed code and/or
+ideas to Gnuplot.py. Thanks especially to Konrad Hinsen
+<hinsen@ibs.ibs.fr>, who wrote the first, procedural interface version
+of Gnuplot.py.
+
+
+--
+Michael Haggerty
+<mhagger@alum.mit.edu>
+(But please use the mailing list for Gnuplot.py-related issues.)
--- /dev/null
+Id: TODO.txt 294 2006-11-07 02:33:08Z parejkoj
+
+Some ideas for future work. I don't know whether I'll get around to
+any of these items; some of them are probably better left undone
+anyway. Of course if anybody else wants to take one up...
+
+* Implement missing values. Gnuplot allows you to specify that values
+ are missing from data files via the `set missing' command. This
+ should probably be implemented via Numeric's masked arrays.
+ (Comments?) The real benefit of dealing with values is that (I
+ think) gnuplot can still put a mesh on a surface even if the surface
+ has holes.
+
+* Figure out how to suck gnuplot error messages back into Python and
+ turn them into exceptions. This would be tricky: for one thing, not
+ all gnuplot output is indicative of an error. Moreover,
+ implementation on Windows and Mac would require additional effort to
+ change their GnuplotProcess classes. The output from the 'show'
+ command could be processed in a similar manner.
+
+* Implement multiple graphs on a single page. I haven't used this
+ feature of gnuplot much myself, so I'm not sure how difficult it
+ would be to build it into the Gnuplot.py framework. Ideally one
+ would like to be able to spawn multiple GnuplotWindow's from a
+ single Gnuplot instance, each one behaving much like a Gnuplot
+ object. Or maybe treat sub-windows as a kind of meta-PlotItem that
+ can itself contain PlotItems.
+
+* Add a way to use Gnuplot.py without Numeric. This would probably
+ not require too much work, and would also be convenient for Jython
+ users since JNumeric is not as far along as Numeric.
+
+* Support gnuplot's new abilities to allow user interaction via the
+ mouse. I believe this will require 2-way communication between
+ Gnuplot.py and gnuplot.
--- /dev/null
+Original versions of Gnuplot.py are described in NEWS.txt.
+
+The original 1.8 version was maintained in order to support the compatibility
+with Python and Gnuplot evolutions, up to the supported versions for SALOME and
+ADAO. The "Id" historical fields have been freeze in each source file. The
+compatibility maintenance versions are numbered using a third digit in the
+historical version number, beginning with '1.8.10' in order to show the
+maintenance modification.
+
+All maintenance modifications or versions are under LGPL license.
--- /dev/null
+# Id: _Gnuplot.py 305 2008-01-17 20:10:44Z bmcage
+
+# Copyright (C) 1998-2003 Michael Haggerty <mhagger@alum.mit.edu>
+#
+# This file is licensed under the GNU Lesser General Public License
+# (LGPL). See LICENSE.txt for details.
+
+"""_Gnuplot.py -- An object that represents a running gnuplot process.
+
+This file implements the Gnuplot plotter object, which is an abstract
+interface to a running gnuplot process.
+
+"""
+
+import sys, string, types
+
+import gp, PlotItems, termdefs
+import Gnuplot.Errors as Errors
+
+
+class _GnuplotFile:
+ """A file to which gnuplot commands can be written.
+
+ Sometimes it is convenient to write gnuplot commands to a command
+ file for later evaluation. In that case, one of these objects is
+ used as a mock gnuplot process. Note that temporary files may be
+ deleted before you have time to execute the file!
+
+ Members:
+
+ 'gnuplot' -- the file object gathering the commands.
+
+ Methods:
+
+ '__init__' -- open the file.
+
+ '__call__' -- write a gnuplot command to the file, followed by a
+ newline.
+
+ 'write' -- write an arbitrary string to the file.
+
+ 'flush' -- cause pending output to be written immediately.
+
+ """
+
+ def __init__(self, filename):
+ """Open the file for writing."""
+
+ self.gnuplot = open(filename, 'w')
+ # forward write and flush methods:
+ self.write = self.gnuplot.write
+ self.flush = self.gnuplot.flush
+
+ def __call__(self, s):
+ """Write a command string to the file, followed by newline."""
+
+ self.write(s + '\n')
+ self.flush()
+
+
+class Gnuplot:
+ """Interface to a gnuplot program.
+
+ A Gnuplot represents a higher-level interface to a gnuplot
+ program. It can plot 'PlotItem's, which represent each thing to
+ be plotted on the current graph. It keeps a reference to each of
+ the 'PlotItems' used in the current plot, so that they (and their
+ associated temporary files) are not deleted prematurely.
+
+ Members:
+
+ 'itemlist' -- a list of the PlotItems that are associated with
+ the current plot. These are deleted whenever a new plot
+ command is issued via the 'plot' method.
+
+ 'plotcmd' -- 'plot' or 'splot', depending on what was the last
+ plot command.
+
+ Methods:
+
+ '__init__' -- if a filename argument is specified, the
+ commands will be written to that file instead of being
+ piped to gnuplot.
+
+ 'plot' -- clear the old plot and old 'PlotItems', then plot
+ the arguments in a fresh plot command. Arguments can be:
+ a 'PlotItem', which is plotted along with its internal
+ options; a string, which is plotted as a 'Func'; or
+ anything else, which is plotted as a 'Data'.
+
+ 'splot' -- like 'plot', except for 3-d plots.
+
+ 'hardcopy' -- replot the plot to a postscript file (if
+ filename argument is specified) or pipe it to the printer
+ as postscript othewise. If the option 'color' is set to
+ true, then output color postscript.
+
+ 'replot' -- replot the old items, adding any arguments as
+ additional items as in the plot method.
+
+ 'refresh' -- issue (or reissue) the plot command using the
+ current 'PlotItems'.
+
+ '__call__' -- pass an arbitrary string to the gnuplot process,
+ followed by a newline.
+
+ 'xlabel', 'ylabel', 'zlabel', 'title' -- set corresponding plot
+ attribute.
+
+ 'interact' -- read lines from stdin and send them, one by one,
+ to the gnuplot interpreter. Basically you can type
+ commands directly to the gnuplot command processor.
+
+ 'load' -- load a file (using the gnuplot 'load' command).
+
+ 'save' -- save gnuplot commands to a file (using gnuplot
+ 'save' command) If any of the 'PlotItem's is a temporary
+ file, it will be deleted at the usual time and the save
+ file will be pretty useless :-).
+
+ 'clear' -- clear the plot window (but not the itemlist).
+
+ 'reset' -- reset all gnuplot settings to their defaults and
+ clear the current itemlist.
+
+ 'set_string' -- set or unset a gnuplot option whose value is a
+ string.
+
+ '_clear_queue' -- clear the current 'PlotItem' list.
+
+ '_add_to_queue' -- add the specified items to the current
+ 'PlotItem' list.
+
+ """
+
+ # optiontypes tells how to set parameters. Specifically, the
+ # parameter will be set using self.set_<type>(option, value),
+ # where <type> is a string looked up in the following table.
+ optiontypes = {
+ 'title' : 'string',
+ 'xlabel' : 'string',
+ 'ylabel' : 'string',
+ 'zlabel' : 'string',
+ 'xrange' : 'range',
+ 'yrange' : 'range',
+ 'zrange' : 'range',
+ 'trange' : 'range',
+ 'urange' : 'range',
+ 'vrange' : 'range',
+ 'parametric' : 'boolean',
+ 'polar' : 'boolean',
+ 'output' : 'string',
+ }
+
+ def __init__(self, filename=None, persist=None, debug=0):
+ """Create a Gnuplot object.
+
+ Create a 'Gnuplot' object. By default, this starts a gnuplot
+ process and prepares to write commands to it.
+
+ Keyword arguments:
+
+ 'filename=<string>' -- if a filename is specified, the
+ commands are instead written to that file (e.g., for
+ later use using 'load').
+
+ 'persist=1' -- start gnuplot with the '-persist' option
+ (which creates a new plot window for each plot command).
+ (This option is not available on older versions of
+ gnuplot.)
+
+ 'debug=1' -- echo the gnuplot commands to stderr as well as
+ sending them to gnuplot.
+
+ """
+
+ if filename is None:
+ self.gnuplot = gp.GnuplotProcess(persist=persist)
+ else:
+ if persist is not None:
+ raise Errors.OptionError(
+ 'Gnuplot with output to file does not allow '
+ 'persist option.')
+ self.gnuplot = _GnuplotFile(filename)
+ self._clear_queue()
+ self.debug = debug
+ self.plotcmd = 'plot'
+ self('set terminal %s' % (gp.GnuplotOpts.default_term,))
+
+ def close(self):
+ # This may cause a wait for the gnuplot process to finish
+ # working, which is generally a good thing because it delays
+ # the deletion of temporary files.
+ if self.gnuplot is not None:
+ self.gnuplot.close()
+ self.gnuplot = None
+
+ def __del__(self):
+ self.close()
+ self._clear_queue()
+
+ def __call__(self, s):
+ """Send a command string to gnuplot.
+
+ Send the string s as a command to gnuplot, followed by a
+ newline. All communication with the gnuplot process (except
+ for inline data) is through this method.
+
+ """
+
+ self.gnuplot(s)
+ if self.debug:
+ # also echo to stderr for user to see:
+ sys.stderr.write('gnuplot> %s\n' % (s,))
+
+ def refresh(self):
+ """Refresh the plot, using the current 'PlotItem's.
+
+ Refresh the current plot by reissuing the gnuplot plot command
+ corresponding to the current itemlist.
+
+ """
+
+ plotcmds = []
+ for item in self.itemlist:
+ plotcmds.append(item.command())
+ self(self.plotcmd + ' ' + ", ".join(plotcmds))
+ for item in self.itemlist:
+ # Uses self.gnuplot.write():
+ item.pipein(self.gnuplot)
+ self.gnuplot.flush()
+
+ def _clear_queue(self):
+ """Clear the 'PlotItems' from the queue."""
+
+ self.itemlist = []
+
+ def _add_to_queue(self, items):
+ """Add a list of items to the itemlist (but don't plot them).
+
+ 'items' is a sequence of items, each of which should be a
+ 'PlotItem' of some kind, a string (interpreted as a function
+ string for gnuplot to evaluate), or a numpy array (or
+ something that can be converted to a numpy array).
+
+ """
+
+ for item in items:
+ if isinstance(item, PlotItems.PlotItem):
+ self.itemlist.append(item)
+ elif type(item) is str:
+ self.itemlist.append(PlotItems.Func(item))
+ else:
+ # assume data is an array:
+ self.itemlist.append(PlotItems.Data(item))
+
+ def plot(self, *items, **keyw):
+ """Draw a new plot.
+
+ Clear the current plot and create a new 2-d plot containing
+ the specified items. Each arguments should be of the
+ following types:
+
+ 'PlotItem' (e.g., 'Data', 'File', 'Func') -- This is the most
+ flexible way to call plot because the PlotItems can
+ contain suboptions. Moreover, PlotItems can be saved to
+ variables so that their lifetime is longer than one plot
+ command; thus they can be replotted with minimal overhead.
+
+ 'string' (e.g., 'sin(x)') -- The string is interpreted as
+ 'Func(string)' (a function that is computed by gnuplot).
+
+ Anything else -- The object, which should be convertible to an
+ array, is passed to the 'Data' constructor, and thus
+ plotted as data. If the conversion fails, an exception is
+ raised.
+
+ """
+
+ if keyw:
+ self.set(**keyw)
+
+ self.plotcmd = 'plot'
+ self._clear_queue()
+ self._add_to_queue(items)
+ self.refresh()
+
+ def splot(self, *items, **keyw):
+ """Draw a new three-dimensional plot.
+
+ Clear the current plot and create a new 3-d plot containing
+ the specified items. Arguments can be of the following types:
+
+ 'PlotItem' (e.g., 'Data', 'File', 'Func', 'GridData' ) -- This
+ is the most flexible way to call plot because the
+ PlotItems can contain suboptions. Moreover, PlotItems can
+ be saved to variables so that their lifetime is longer
+ than one plot command--thus they can be replotted with
+ minimal overhead.
+
+ 'string' (e.g., 'sin(x*y)') -- The string is interpreted as a
+ 'Func()' (a function that is computed by gnuplot).
+
+ Anything else -- The object is converted to a Data() item, and
+ thus plotted as data. Note that each data point should
+ normally have at least three values associated with it
+ (i.e., x, y, and z). If the conversion fails, an
+ exception is raised.
+
+ """
+
+ if keyw:
+ self.set(**keyw)
+
+ self.plotcmd = 'splot'
+ self._clear_queue()
+ self._add_to_queue(items)
+ self.refresh()
+
+ def replot(self, *items, **keyw):
+ """Replot the data, possibly adding new 'PlotItem's.
+
+ Replot the existing graph, using the items in the current
+ itemlist. If arguments are specified, they are interpreted as
+ additional items to be plotted alongside the existing items on
+ the same graph. See 'plot' for details.
+
+ """
+
+ if keyw:
+ self.set(**keyw)
+
+ self._add_to_queue(items)
+ self.refresh()
+
+ def interact(self):
+ """Allow user to type arbitrary commands to gnuplot.
+
+ Read stdin, line by line, and send each line as a command to
+ gnuplot. End by typing C-d.
+
+ """
+
+ import time
+ if sys.platform == 'win32':
+ sys.stderr.write('Press Ctrl-z twice to end interactive input\n')
+ else:
+ # What should this be for the Macintosh?
+ sys.stderr.write('Press C-d to end interactive input\n')
+ while 1:
+ try:
+ line = input('gnuplot>>> ')
+ except EOFError:
+ break
+ self(line)
+ time.sleep(0.2) # give a little time for errors to be written
+ sys.stderr.write('\n')
+
+ def clear(self):
+ """Clear the plot window (without affecting the current itemlist)."""
+
+ self('clear')
+
+ def reset(self):
+ """Reset all gnuplot settings to their defaults and clear itemlist."""
+
+ self('reset')
+ self.itemlist = []
+
+ def load(self, filename):
+ """Load a file using gnuplot's 'load' command."""
+
+ self("load '%s'" % (filename,))
+
+ def save(self, filename):
+ """Save the current plot commands using gnuplot's 'save' command."""
+
+ self("save '%s'" % (filename,))
+
+ def set_string(self, option, s=None):
+ """Set a string option, or if s is omitted, unset the option."""
+
+ if s is None:
+ self('set %s' % (option,))
+ else:
+ self('set %s "%s"' % (option, s))
+
+ def set_label(self, option, s=None, offset=None, font=None):
+ """Set or clear a label option, which can include an offset or font.
+
+ If offset is specified, it should be a tuple of two integers
+ or floats.
+
+ If font is specified, it is appended to the command as a
+ string in double quotes. Its interpretation is
+ terminal-dependent; for example, for postscript it might be
+ 'Helvetica,14' for 14 point Helvetica.
+
+ """
+
+ cmd = ['set', option]
+ if s is not None:
+ cmd.append('"%s"' % (s,))
+
+ if offset is not None:
+ cmd.append('%s,%s' % offset)
+
+ if font is not None:
+ cmd.append('"%s"' % (font,))
+
+ self(" ".join(cmd))
+
+ def set_boolean(self, option, value):
+ """Set an on/off option. It is assumed that the way to turn
+ the option on is to type `set <option>' and to turn it off,
+ `set no<option>'."""
+
+ if value:
+ self('set %s' % option)
+ else:
+ self('set no%s' % option)
+
+ def set_range(self, option, value):
+ """Set a range option (xrange, yrange, trange, urange, etc.).
+ The value can be a string (which is passed as-is, without
+ quotes) or a tuple (minrange,maxrange) of numbers or string
+ expressions recognized by gnuplot. If either range is None
+ then that range is passed as `*' (which means to
+ autoscale)."""
+
+ if value is None:
+ self('set %s [*:*]' % (option,))
+ elif type(value) is str:
+ self('set %s %s' % (option, value,))
+ else:
+ # Must be a tuple:
+ (minrange,maxrange) = value
+ if minrange is None:
+ minrange = '*'
+ if maxrange is None:
+ maxrange = '*'
+ self('set %s [%s:%s]' % (option, minrange, maxrange,))
+
+ def set(self, **keyw):
+ """Set one or more settings at once from keyword arguments.
+ The allowed settings and their treatments are determined from
+ the optiontypes mapping."""
+
+ for (k,v) in keyw.items():
+ try:
+ type = self.optiontypes[k]
+ except KeyError:
+ raise Exception('option %s is not supported' % (k,))
+ getattr(self, 'set_%s' % type)(k, v)
+
+ def xlabel(self, s=None, offset=None, font=None):
+ """Set the plot's xlabel."""
+
+ self.set_label('xlabel', s, offset=offset, font=font)
+
+ def ylabel(self, s=None, offset=None, font=None):
+ """Set the plot's ylabel."""
+
+ self.set_label('ylabel', s, offset=offset, font=font)
+
+ def zlabel(self, s=None, offset=None, font=None):
+ """Set the plot's zlabel."""
+
+ self.set_label('zlabel', s, offset=offset, font=font)
+
+ def title(self, s=None, offset=None, font=None):
+ """Set the plot's title."""
+
+ self.set_label('title', s, offset=offset, font=font)
+
+ def hardcopy(self, filename=None, terminal='postscript', **keyw):
+ """Create a hardcopy of the current plot.
+
+ Output the current plot to the default printer (if configured)
+ or to the specified filename.
+
+ Note that gnuplot remembers the printer suboptions across
+ terminal changes (at least for postscript). Therefore if you
+ set, for example, color=1 for one hardcopy then the next
+ hardcopy will also be color unless you explicitly choose
+ color=0. Alternately you can force all of the options to
+ their defaults by setting mode='default'. I consider this to
+ be a bug in gnuplot.
+
+ Keyword arguments:
+
+ 'filename=<string>' -- if a filename is specified, save the
+ output in that file; otherwise print it immediately
+ using the 'default_lpr' configuration option.
+
+ 'terminal=<string>' -- the type of gnuplot 'terminal' to use
+ for the output (e.g., 'postscript', 'png', 'latex',
+ etc). Look in termdefs.py to see what terminal types
+ are defined, or check termdefs.terminal_opts.keys().
+
+ The rest of the keyword arguments depend on the terminal type.
+
+ Keyword arguments for 'postscript' terminal:
+
+ 'mode=<string>' -- set the postscript submode ('landscape',
+ 'portrait', 'eps', or 'default'). The default is
+ to leave this option unspecified.
+
+ 'eps=<bool>' -- shorthand for 'mode="eps"'; asks gnuplot to
+ generate encapsulated postscript.
+
+ 'enhanced=<bool>' -- if set (the default), then generate
+ enhanced postscript, which allows extra features like
+ font-switching, superscripts, and subscripts in axis
+ labels. (Some old gnuplot versions do not support
+ enhanced postscript; if this is the case set
+ gp.GnuplotOpts.prefer_enhanced_postscript=None.)
+
+ 'color=<bool>' -- if set, create a plot with color. Default
+ is to leave this option unchanged.
+
+ 'solid=<bool>' -- if set, force lines to be solid (i.e., not
+ dashed).
+
+ 'duplexing=<string>' -- set duplexing option ('defaultplex',
+ 'simplex', or 'duplex'). Only request double-sided
+ printing if your printer can handle it. Actually this
+ option is probably meaningless since hardcopy() can only
+ print a single plot at a time.
+
+ 'fontname=<string>' -- set the default font to <string>,
+ which must be a valid postscript font. The default is
+ to leave this option unspecified.
+
+ 'fontsize=<double>' -- set the default font size, in
+ postscript points.
+
+ Note that this command will return immediately even though it
+ might take gnuplot a while to actually finish working. Be
+ sure to pause briefly before issuing another command that
+ might cause the temporary files to be deleted.
+
+ """
+
+ if filename is None:
+ if gp.GnuplotOpts.default_lpr is None:
+ raise Errors.OptionError(
+ 'default_lpr is not set, so you can only print to a file.')
+ filename = gp.GnuplotOpts.default_lpr
+
+ # Be careful processing the options. If the user didn't
+ # request an option explicitly, do not specify it on the 'set
+ # terminal' line (don't even specify the default value for the
+ # option). This is to avoid confusing older versions of
+ # gnuplot that do not support all of these options. The
+ # exception is postscript's 'enhanced' option, which is just
+ # too useful to have to specify each time!
+
+ # Build up the 'set terminal' command here:
+ setterm = ['set', 'terminal', terminal]
+ try:
+ opts = termdefs.terminal_opts[terminal]
+ except KeyError:
+ raise Errors.OptionError(
+ 'Terminal "%s" is not configured in Gnuplot.py.' % (terminal,))
+
+ for opt in opts:
+ cmd = opt(keyw)
+ if cmd is not None:
+ setterm.extend(cmd)
+ if keyw:
+ # Not all options were consumed.
+ raise Errors.OptionError(
+ 'The following options are unrecognized: %s'
+ % (", ".join(keyw.keys()),)
+ )
+
+ self.set_string('output', filename)
+ self(" ".join(setterm))
+ # replot the current figure (to the printer):
+ self.refresh()
+ # reset the terminal to its `default' setting:
+ self('set terminal %s' % gp.GnuplotOpts.default_term)
+ self.set_string('output')
+
+
--- /dev/null
+#! /usr/bin/env python
+# Id: __init__.py 306 2008-05-02 01:09:02Z alford
+
+# Copyright (C) 1998-2003 Michael Haggerty <mhagger@alum.mit.edu>
+#
+# This file is licensed under the GNU Lesser General Public License
+# (LGPL). See LICENSE.txt for details.
+
+"""Gnuplot -- A pipe-based interface to the gnuplot plotting program.
+
+This is the main module of the Gnuplot package.
+
+Written by "Michael Haggerty", mailto:mhagger@alum.mit.edu. Inspired
+by and partly derived from an earlier version by "Konrad Hinsen",
+mailto:hinsen@ibs.ibs.fr. If you find a problem or have a suggestion,
+please "let me know", mailto:mhagger@alum.mit.edu. Other feedback
+would also be appreciated.
+
+The Gnuplot.py home page is at
+
+"Gnuplot.py", http://gnuplot-py.sourceforge.net
+
+
+For information about how to use this module:
+
+1. Check the README file.
+
+2. Look at the example code in demo.py and try running it by typing
+ 'python demo.py' or 'python __init__.py'.
+
+3. For more details see the extensive documentation strings
+ throughout the python source files, especially this file,
+ _Gnuplot.py, PlotItems.py, and gp_unix.py.
+
+4. The docstrings have also been turned into html which can be read
+ "here", http://gnuplot-py.sourceforge.net/doc. However, the
+ formatting is not perfect; when in doubt, double-check the
+ docstrings.
+
+You should import this file with 'import Gnuplot', not with 'from
+Gnuplot import *', because the module and the main class have the same
+name, `Gnuplot'.
+
+To obtain the gnuplot plotting program itself, see "the gnuplot FAQ",
+ftp://ftp.gnuplot.vt.edu/pub/gnuplot/faq/index.html. Obviously you
+need to have gnuplot installed if you want to use Gnuplot.py.
+
+The old command-based interface to gnuplot (previously supported as
+'oldplot.py') has been removed from the package.
+
+Features:
+
+ o Allows the creation of two or three dimensional plots from
+ python.
+
+ o A gnuplot session is an instance of class 'Gnuplot'. Multiple
+ sessions can be open at once. For example::
+
+ g1 = Gnuplot.Gnuplot()
+ g2 = Gnuplot.Gnuplot()
+
+ Note that due to limitations on those platforms, opening multiple
+ simultaneous sessions on Windows or Macintosh may not work
+ correctly. (Feedback?)
+
+ o The implicitly-generated gnuplot commands can be stored to a file
+ instead of executed immediately::
+
+ g = Gnuplot.Gnuplot('commands.txt')
+
+ The 'commands.txt' file can then be run later with gnuplot's
+ 'load' command. Beware, however: the plot commands may depend on
+ the existence of temporary files, which will probably be deleted
+ before you use the command file.
+
+ o Can pass arbitrary commands to the gnuplot command interpreter::
+
+ g('set pointsize 2')
+
+ (If this is all you want to do, you might consider using the
+ lightweight GnuplotProcess class defined in gp.py.)
+
+ o A Gnuplot object knows how to plot objects of type 'PlotItem'.
+ Any PlotItem can have optional 'title' and/or 'with' suboptions.
+ Builtin PlotItem types:
+
+ * 'Data(array1)' -- data from a Python list or NumPy array
+ (permits additional option 'cols' )
+
+ * 'File('filename')' -- data from an existing data file (permits
+ additional option 'using' )
+
+ * 'Func('exp(4.0 * sin(x))')' -- functions (passed as a string,
+ evaluated by gnuplot)
+
+ * 'GridData(m, x, y)' -- data tabulated on a grid of (x,y) values
+ (usually to be plotted in 3-D)
+
+ See the documentation strings for those classes for more details.
+
+ o PlotItems are implemented as objects that can be assigned to
+ variables and plotted repeatedly. Most of their plot options can
+ also be changed with the new 'set_option()' member functions then
+ they can be replotted with their new options.
+
+ o Communication of commands to gnuplot is via a one-way pipe.
+ Communication of data from python to gnuplot is via inline data
+ (through the command pipe) or via temporary files. Temp files are
+ deleted automatically when their associated 'PlotItem' is deleted.
+ The PlotItems in use by a Gnuplot object at any given time are
+ stored in an internal list so that they won't be deleted
+ prematurely.
+
+ o Can use 'replot' method to add datasets to an existing plot.
+
+ o Can make persistent gnuplot windows by using the constructor option
+ 'persist=1'. Such windows stay around even after the gnuplot
+ program is exited. Note that only newer version of gnuplot support
+ this option.
+
+ o Can plot either directly to a postscript printer or to a
+ postscript file via the 'hardcopy' method.
+
+ o Grid data for the splot command can be sent to gnuplot in binary
+ format, saving time and disk space.
+
+ o Should work under Unix, Macintosh, and Windows.
+
+Restrictions:
+
+ - Relies on the numpy Python extension. This can be obtained from
+ the Scipy group at <http://www.scipy.org/Download>. If you're
+ interested in gnuplot, you would probably also want numpy anyway.
+
+ - Only a small fraction of gnuplot functionality is implemented as
+ explicit method functions. However, you can give arbitrary
+ commands to gnuplot manually::
+
+ g = Gnuplot.Gnuplot()
+ g('set style data linespoints')
+ g('set pointsize 5')
+
+ - There is no provision for missing data points in array data (which
+ gnuplot allows via the 'set missing' command).
+
+Bugs:
+
+ - No attempt is made to check for errors reported by gnuplot. On
+ unix any gnuplot error messages simply appear on stderr. (I don't
+ know what happens under Windows.)
+
+ - All of these classes perform their resource deallocation when
+ '__del__' is called. Normally this works fine, but there are
+ well-known cases when Python's automatic resource deallocation
+ fails, which can leave temporary files around.
+
+"""
+import os, sys
+sys.path.append(os.path.dirname(__file__))
+
+__version__ = '1.8.10'
+
+# Other modules that should be loaded for 'from Gnuplot import *':
+__all__ = ['utils', 'funcutils', ]
+
+from gp import GnuplotOpts, GnuplotProcess, test_persist
+from Errors import Error, OptionError, DataError
+from PlotItems import PlotItem, Func, File, Data, GridData
+from _Gnuplot import Gnuplot
+
+
+if __name__ == '__main__':
+ import demo
+ demo.demo()
+
+
--- /dev/null
+#! /usr/bin/env python
+# Id: demo.py 299 2007-03-30 12:52:17Z mhagger
+
+# Copyright (C) 1999-2003 Michael Haggerty <mhagger@alum.mit.edu>
+#
+# This file is licensed under the GNU Lesser General Public License
+# (LGPL). See LICENSE.txt for details.
+
+"""demo.py -- Demonstrate the Gnuplot python module.
+
+Run this demo by typing 'python demo.py'. For a more complete test of
+the Gnuplot package, see test.py.
+
+"""
+
+from numpy import *
+
+# If the package has been installed correctly, this should work:
+import Gnuplot, Gnuplot.funcutils
+
+
+def demo():
+ """Demonstrate the Gnuplot package."""
+
+ # A straightforward use of gnuplot. The `debug=1' switch is used
+ # in these examples so that the commands that are sent to gnuplot
+ # are also output on stderr.
+ g = Gnuplot.Gnuplot(debug=1)
+ g.title('A simple example') # (optional)
+ g('set style data linespoints') # give gnuplot an arbitrary command
+ # Plot a list of (x, y) pairs (tuples or a numpy array would
+ # also be OK):
+ g.plot([[0,1.1], [1,5.8], [2,3.3], [3,4.2]])
+ input('Please press return to continue...\n')
+
+ g.reset()
+ # Plot one dataset from an array and one via a gnuplot function;
+ # also demonstrate the use of item-specific options:
+ x = arange(10, dtype='float_')
+ y1 = x**2
+ # Notice how this plotitem is created here but used later? This
+ # is convenient if the same dataset has to be plotted multiple
+ # times. It is also more efficient because the data need only be
+ # written to a temporary file once.
+ d = Gnuplot.Data(x, y1,
+ title='calculated by python',
+ with_='points 3 3')
+ g.title('Data can be computed by python or gnuplot')
+ g.xlabel('x')
+ g.ylabel('x squared')
+ # Plot a function alongside the Data PlotItem defined above:
+ g.plot(Gnuplot.Func('x**2', title='calculated by gnuplot'), d)
+ input('Please press return to continue...\n')
+
+ # Save what we just plotted as a color postscript file.
+
+ # With the enhanced postscript option, it is possible to show `x
+ # squared' with a superscript (plus much, much more; see `help set
+ # term postscript' in the gnuplot docs). If your gnuplot doesn't
+ # support enhanced mode, set `enhanced=0' below.
+ g.ylabel('x^2') # take advantage of enhanced postscript mode
+ g.hardcopy('gp_test.ps', enhanced=1, color=1)
+ print ('\n******** Saved plot to postscript file "gp_test.ps" ********\n')
+ input('Please press return to continue...\n')
+
+ g.reset()
+ # Demonstrate a 3-d plot:
+ # set up x and y values at which the function will be tabulated:
+ x = arange(35)/2.0
+ y = arange(30)/10.0 - 1.5
+ # Make a 2-d array containing a function of x and y. First create
+ # xm and ym which contain the x and y values in a matrix form that
+ # can be `broadcast' into a matrix of the appropriate shape:
+ xm = x[:,newaxis]
+ ym = y[newaxis,:]
+ m = (sin(xm) + 0.1*xm) - ym**2
+ g('set parametric')
+ g('set style data lines')
+ g('set hidden')
+ g('set contour base')
+ g.title('An example of a surface plot')
+ g.xlabel('x')
+ g.ylabel('y')
+ # The `binary=1' option would cause communication with gnuplot to
+ # be in binary format, which is considerably faster and uses less
+ # disk space. (This only works with the splot command due to
+ # limitations of gnuplot.) `binary=1' is the default, but here we
+ # disable binary because older versions of gnuplot don't allow
+ # binary data. Change this to `binary=1' (or omit the binary
+ # option) to get the advantage of binary format.
+ g.splot(Gnuplot.GridData(m,x,y, binary=0))
+ input('Please press return to continue...\n')
+
+ # plot another function, but letting GridFunc tabulate its values
+ # automatically. f could also be a lambda or a global function:
+ def f(x,y):
+ return 1.0 / (1 + 0.01 * x**2 + 0.5 * y**2)
+
+ g.splot(Gnuplot.funcutils.compute_GridData(x,y, f, binary=0))
+ input('Please press return to continue...\n')
+
+ # Explicit delete shouldn't be necessary, but if you are having
+ # trouble with temporary files being left behind, try uncommenting
+ # the following:
+ #del g, d
+
+
+# when executed, just run demo():
+if __name__ == '__main__':
+ demo()
+
--- /dev/null
+#! /usr/bin/env python
+
+# Id: funcutils.py 297 2007-03-30 11:25:28Z mhagger
+
+# Copyright (C) 1998-2003 Michael Haggerty <mhagger@alum.mit.edu>
+#
+# This file is licensed under the GNU Lesser General Public License
+# (LGPL). See LICENSE.txt for details.
+
+"""funcutils.py -- Subroutines that tabulate a function's values.
+
+Convenience functions that evaluate a python function on a grid of
+points and tabulate the output to be used with Gnuplot.
+
+"""
+
+import numpy
+
+import Gnuplot
+import Gnuplot.utils as utils
+
+
+def tabulate_function(f, xvals, yvals=None, dtype=None, ufunc=0):
+ """Evaluate and tabulate a function on a 1- or 2-D grid of points.
+
+ f should be a function taking one or two floating-point
+ parameters.
+
+ If f takes one parameter, then xvals should be a 1-D array and
+ yvals should be None. The return value is a numpy array
+ '[f(x[0]), f(x[1]), ..., f(x[-1])]'.
+
+ If f takes two parameters, then 'xvals' and 'yvals' should each be
+ 1-D arrays listing the values of x and y at which 'f' should be
+ tabulated. The return value is a matrix M where 'M[i,j] =
+ f(xvals[i],yvals[j])', which can for example be used in the
+ 'GridData' constructor.
+
+ If 'ufunc=0', then 'f' is evaluated at each point using a Python
+ loop. This can be slow if the number of points is large. If
+ speed is an issue, you should write 'f' in terms of numpy ufuncs
+ and use the 'ufunc=1' feature described next.
+
+ If called with 'ufunc=1', then 'f' should be a function that is
+ composed entirely of ufuncs (i.e., a function that can operate
+ element-by-element on whole matrices). It will be passed the
+ xvals and yvals as rectangular matrices.
+
+ """
+
+ if yvals is None:
+ # f is a function of only one variable:
+ xvals = numpy.asarray(xvals, dtype)
+
+ if ufunc:
+ return f(xvals)
+ else:
+ if dtype is None:
+ dtype = xvals.dtype.char
+
+ m = numpy.zeros((len(xvals),), dtype)
+ for xi in range(len(xvals)):
+ x = xvals[xi]
+ m[xi] = f(x)
+ return m
+ else:
+ # f is a function of two variables:
+ xvals = numpy.asarray(xvals, dtype)
+ yvals = numpy.asarray(yvals, dtype)
+
+ if ufunc:
+ return f(xvals[:,numpy.newaxis], yvals[numpy.newaxis,:])
+ else:
+ if dtype is None:
+ # choose a result dtype based on what '+' would return
+ # (yecch!):
+ dtype = (numpy.zeros((1,), xvals.dtype.char) +
+ numpy.zeros((1,), yvals.dtype.char)).dtype.char
+
+ m = numpy.zeros((len(xvals), len(yvals)), dtype)
+ for xi in range(len(xvals)):
+ x = xvals[xi]
+ for yi in range(len(yvals)):
+ y = yvals[yi]
+ m[xi,yi] = f(x,y)
+ return m
+
+
+# For backwards compatibility:
+grid_function = tabulate_function
+
+
+def compute_Data(xvals, f, ufunc=0, **keyw):
+ """Evaluate a function of 1 variable and store the results in a Data.
+
+ Computes a function f of one variable on a set of specified points
+ using 'tabulate_function', then store the results into a 'Data' so
+ that it can be plotted. After calculation, the data are written
+ to a file; no copy is kept in memory. Note that this is quite
+ different than 'Func' (which tells gnuplot to evaluate the
+ function).
+
+ Arguments:
+
+ 'xvals' -- a 1-d array with dimension 'numx'
+
+ 'f' -- the function to plot--a callable object for which
+ f(x) returns a number.
+
+ 'ufunc=<bool>' -- evaluate 'f' as a ufunc?
+
+ Other keyword arguments are passed through to the Data
+ constructor.
+
+ 'f' should be a callable object taking one argument. 'f(x)' will
+ be computed at all values in xvals.
+
+ If called with 'ufunc=1', then 'f' should be a function that is
+ composed entirely of ufuncs, and it will be passed the 'xvals' and
+ 'yvals' as rectangular matrices.
+
+ Thus if you have a function 'f', a vector 'xvals', and a Gnuplot
+ instance called 'g', you can plot the function by typing
+ 'g.splot(compute_Data(xvals, f))'.
+
+ """
+
+ xvals = utils.float_array(xvals)
+
+ # evaluate function:
+ data = tabulate_function(f, xvals, ufunc=ufunc)
+
+ return Gnuplot.Data(xvals, data, **keyw)
+
+
+def compute_GridData(xvals, yvals, f, ufunc=0, **keyw):
+ """Evaluate a function of 2 variables and store the results in a GridData.
+
+ Computes a function 'f' of two variables on a rectangular grid
+ using 'tabulate_function', then store the results into a
+ 'GridData' so that it can be plotted. After calculation the data
+ are written to a file; no copy is kept in memory. Note that this
+ is quite different than 'Func' (which tells gnuplot to evaluate
+ the function).
+
+ Arguments:
+
+ 'xvals' -- a 1-d array with dimension 'numx'
+
+ 'yvals' -- a 1-d array with dimension 'numy'
+
+ 'f' -- the function to plot--a callable object for which
+ 'f(x,y)' returns a number.
+
+ 'ufunc=<bool>' -- evaluate 'f' as a ufunc?
+
+ Other keyword arguments are passed to the 'GridData' constructor.
+
+ 'f' should be a callable object taking two arguments.
+ 'f(x,y)' will be computed at all grid points obtained by
+ combining elements from 'xvals' and 'yvals'.
+
+ If called with 'ufunc=1', then 'f' should be a function that is
+ composed entirely of ufuncs, and it will be passed the 'xvals' and
+ 'yvals' as rectangular matrices.
+
+ Thus if you have a function 'f' and two vectors 'xvals' and
+ 'yvals' and a Gnuplot instance called 'g', you can plot the
+ function by typing 'g.splot(compute_GridData(f, xvals, yvals))'.
+
+ """
+
+ xvals = utils.float_array(xvals)
+ yvals = utils.float_array(yvals)
+
+ # evaluate function:
+ data = tabulate_function(f, xvals, yvals, ufunc=ufunc)
+
+ return Gnuplot.GridData(data, xvals, yvals, **keyw)
+
+
+# For backwards compatibility:
+def GridFunc(f, xvals, yvals, **keyw):
+ return compute_GridData(xvals, yvals, f, **keyw)
+
+
--- /dev/null
+# Id: gnuplot_Suites.py 292 2006-03-03 09:49:04Z mhagger
+
+# This file is provided as part of the Gnuplot.py package for the
+# convenience of Mac users. It was generated primarily using gensuitemodule
+# with Mac gnuplot 3.7.1a. Thanks to Anthony M. Ingraldi and Noboru Yamamoto
+# for helping with this.
+
+# file contains
+#
+# class gnuplot_Suite
+# class odds_and_ends
+# class Standard_Suite
+# class Miscellaneous_Events
+#
+"""Suite gnuplot Suite: Events supplied by gnuplot
+Level 1, version 1
+
+Generated from Alpha:Desktop Folder:gnuplot.1:gnuplot 3.7.1a
+AETE/AEUT resource version 1/0, language 0, script 0
+"""
+
+import aetools
+import MacOS
+
+_code = 'GPSE'
+
+class gnuplot_Suite:
+
+ def gnuexec(self, _object=None, _attributes={}, **_arguments):
+ """exec: execute a gnuplot command
+ Required argument: gnuplot command
+ Keyword argument _attributes: AppleEvent attribute dictionary
+ """
+ _code = 'GPSE'
+ _subcode = 'exec'
+
+ if _arguments:
+ raise TypeError('No optional args expected')
+ _arguments['----'] = _object
+
+
+ _reply, _arguments, _attributes = self.send(_code, _subcode,
+ _arguments, _attributes)
+ if _arguments.has_key('errn'):
+ raise aetools.Error(aetools.decodeerror(_arguments))
+ # XXXX Optionally decode result
+ if _arguments.has_key('----'):
+ return _arguments['----']
+
+ def plot(self, _object=None, _attributes={}, **_arguments):
+ """plot: create a 2-D plot
+
+
+ Required argument: data to be plotted
+ Keyword argument _attributes: AppleEvent attribute dictionary
+ """
+ _code = 'GPLT'
+ _subcode = 'plot'
+
+ if _arguments:
+ raise TypeError('No optional args expected')
+ _arguments['----'] = _object
+
+
+ _reply, _arguments, _attributes = self.send(_code, _subcode,
+ _arguments, _attributes)
+ if _arguments.has_key('errn'):
+ raise aetools.Error(aetools.decodeerror(_arguments))
+ # XXXX Optionally decode result
+ if _arguments.has_key('----'):
+ return _arguments['----']
+
+ def splot(self, _object=None, _attributes={}, **_arguments):
+ """splot: create a 3-D plot
+ Required argument: data to be plotted
+ Keyword argument _attributes: AppleEvent attribute dictionary
+ """
+ _code = 'GPLT'
+ _subcode = 'splt'
+
+ if _arguments:
+ raise TypeError('No optional args expected')
+ _arguments['----'] = _object
+
+
+ _reply, _arguments, _attributes = self.send(_code, _subcode,
+ _arguments, _attributes)
+ if _arguments.has_key('errn'):
+ raise aetools.Error(aetools.decodeerror(_arguments))
+ # XXXX Optionally decode result
+ if _arguments.has_key('----'):
+ return _arguments['----']
+
+
+class graph(aetools.ComponentItem):
+ """graph - graph - a subclass of window"""
+ want = 'cGRF'
+class picture(aetools.NProperty):
+ """picture - gnuplot graph in "PICT" format"""
+ which = 'PICT'
+ want = 'PICT'
+graph._propdict = {
+ 'picture' : picture,
+}
+graph._elemdict = {
+}
+_Enum_lyty = {
+ 'line' : 'typ1', # line
+ 'points' : 'typ2', # points
+ 'impulses' : 'typ3', # impulses
+ 'linespoints' : 'typ4', # linespoints
+ 'dots' : 'typ5', # dots
+ 'steps' : 'typ6', # steps
+ 'fsteps' : 'typ7', # fsteps
+ 'errorbars' : 'typ8', # errorbars
+ 'xerrorbars' : 'typ9', # xerrorbars
+ 'yerrorbars' : 'ty10', # yerrorbars
+ 'xyerrorbars' : 'ty11', # xyerrorbars
+ 'boxes' : 'ty12', # boxes
+ 'boxerrorbars' : 'ty13', # boxerrorbars
+ 'boxxyerrorbars' : 'ty14', # boxxyerrorbars
+ 'vector' : 'ty19', # vector
+}
+
+
+#
+# Indices of types declared in this module
+#
+_classdeclarations = {
+ 'cGRF' : graph,
+}
+
+_propdeclarations = {
+ 'PICT' : picture,
+}
+
+_compdeclarations = {
+}
+
+_enumdeclarations = {
+ 'lyty' : _Enum_lyty,
+}
+
+
+"""Suite odds and ends: Things that should be in some standard suite, but arenÕt
+Level 1, version 1
+
+Generated from Alpha:Desktop Folder:gnuplot.1:gnuplot 3.7.1a
+AETE/AEUT resource version 1/0, language 0, script 0
+"""
+
+import aetools
+import MacOS
+
+_code = 'Odds'
+
+class odds_and_ends:
+
+ def select(self, _object=None, _attributes={}, **_arguments):
+ """select: Select the specified object
+ Required argument: the object to select
+ Keyword argument _attributes: AppleEvent attribute dictionary
+ """
+ _code = 'misc'
+ _subcode = 'slct'
+
+ if _arguments:
+ raise TypeError('No optional args expected')
+ _arguments['----'] = _object
+
+
+ _reply, _arguments, _attributes = self.send(_code, _subcode,
+ _arguments, _attributes)
+ if _arguments.has_key('errn'):
+ raise aetools.Error(aetools.decodeerror(_arguments))
+ # XXXX Optionally decode result
+ if _arguments.has_key('----'):
+ return _arguments['----']
+
+
+#
+# Indices of types declared in this module
+#
+_classdeclarations = {
+}
+
+_propdeclarations = {
+}
+
+_compdeclarations = {
+}
+
+_enumdeclarations = {
+}
+
+"""Suite Standard Suite: Common terms for most applications
+Level 1, version 1
+
+Generated from Alpha:Desktop Folder:gnuplot.1:gnuplot 3.7.1a
+AETE/AEUT resource version 1/0, language 0, script 0
+"""
+
+import aetools
+import MacOS
+
+_code = 'CoRe'
+
+class Standard_Suite:
+
+ _argmap_close = {
+ 'saving' : 'savo',
+ '_in' : 'kfil',
+ }
+
+ def close(self, _object, _attributes={}, **_arguments):
+ """close: Close an object
+ Required argument: the objects to close
+ Keyword argument saving: specifies whether or not changes should be saved before closing
+ Keyword argument _in: the file in which to save the object
+ Keyword argument _attributes: AppleEvent attribute dictionary
+ """
+ _code = 'core'
+ _subcode = 'clos'
+
+ aetools.keysubst(_arguments, self._argmap_close)
+ _arguments['----'] = _object
+
+ aetools.enumsubst(_arguments, 'savo', _Enum_savo)
+
+ _reply, _arguments, _attributes = self.send(_code, _subcode,
+ _arguments, _attributes)
+ if _arguments.has_key('errn'):
+ raise aetools.Error(aetools.decodeerror(_arguments))
+ # XXXX Optionally decode result
+ if _arguments.has_key('----'):
+ return _arguments['----']
+
+ def data_size(self, _object, _attributes={}, **_arguments):
+ """data size: Return the size in bytes of an object
+ Required argument: the object whose data size is to be returned
+ Keyword argument _attributes: AppleEvent attribute dictionary
+ Returns: the size of the object in bytes
+ """
+ _code = 'core'
+ _subcode = 'dsiz'
+
+ if _arguments:
+ raise TypeError('No optional args expected')
+ _arguments['----'] = _object
+
+
+ _reply, _arguments, _attributes = self.send(_code, _subcode,
+ _arguments, _attributes)
+ if _arguments.has_key('errn'):
+ raise aetools.Error(aetools.decodeerror(_arguments))
+ # XXXX Optionally decode result
+ if _arguments.has_key('----'):
+ return _arguments['----']
+
+ def get(self, _object, _attributes={}, **_arguments):
+ """get: Get the data for an object
+ Required argument: the object whose data is to be returned
+ Keyword argument _attributes: AppleEvent attribute dictionary
+ Returns: The data from the object
+ """
+ _code = 'core'
+ _subcode = 'getd'
+
+ if _arguments:
+ raise TypeError('No optional args expected')
+ _arguments['----'] = _object
+
+
+ _reply, _arguments, _attributes = self.send(_code, _subcode,
+ _arguments, _attributes)
+ if _arguments.has_key('errn'):
+ raise aetools.Error(aetools.decodeerror(_arguments))
+ # XXXX Optionally decode result
+ if _arguments.has_key('----'):
+ return _arguments['----']
+
+ _argmap_make = {
+ 'new' : 'kocl',
+ 'at' : 'insh',
+ 'with_data' : 'data',
+ 'with_properties' : 'prdt',
+ }
+
+ def make(self, _no_object=None, _attributes={}, **_arguments):
+ """make: Make a new element
+ Keyword argument new: the class of the new element
+ Keyword argument at: the location at which to insert the element
+ Keyword argument with_data: the initial data for the element
+ Keyword argument with_properties: the initial values for the properties of the element
+ Keyword argument _attributes: AppleEvent attribute dictionary
+ Returns: Object specifier for the new element
+ """
+ _code = 'core'
+ _subcode = 'crel'
+
+ aetools.keysubst(_arguments, self._argmap_make)
+ if _no_object != None:
+ raise TypeError('No direct arg expected')
+
+
+ _reply, _arguments, _attributes = self.send(_code, _subcode,
+ _arguments, _attributes)
+ if _arguments.has_key('errn'):
+ raise aetools.Error(aetools.decodeerror(_arguments))
+ # XXXX Optionally decode result
+ if _arguments.has_key('----'):
+ return _arguments['----']
+
+ def open(self, _object, _attributes={}, **_arguments):
+ """open: Open the specified object(s)
+ Required argument: Objects to open. Can be a list of files or an object specifier.
+ Keyword argument _attributes: AppleEvent attribute dictionary
+ """
+ _code = 'aevt'
+ _subcode = 'odoc'
+
+ if _arguments:
+ raise TypeError('No optional args expected')
+ _arguments['----'] = _object
+
+
+ _reply, _arguments, _attributes = self.send(_code, _subcode,
+ _arguments, _attributes)
+ if _arguments.has_key('errn'):
+ raise aetools.Error(aetools.decodeerror(_arguments))
+ # XXXX Optionally decode result
+ if _arguments.has_key('----'):
+ return _arguments['----']
+
+ def _print(self, _object, _attributes={}, **_arguments):
+ """print: Print the specified object(s)
+ Required argument: Objects to print. Can be a list of files or an object specifier.
+ Keyword argument _attributes: AppleEvent attribute dictionary
+ """
+ _code = 'aevt'
+ _subcode = 'pdoc'
+
+ if _arguments:
+ raise TypeError('No optional args expected')
+ _arguments['----'] = _object
+
+
+ _reply, _arguments, _attributes = self.send(_code, _subcode,
+ _arguments, _attributes)
+ if _arguments.has_key('errn'):
+ raise aetools.Error(aetools.decodeerror(_arguments))
+ # XXXX Optionally decode result
+ if _arguments.has_key('----'):
+ return _arguments['----']
+
+ _argmap_save = {
+ '_in' : 'kfil',
+ 'as' : 'fltp',
+ }
+
+ def save(self, _object, _attributes={}, **_arguments):
+ """save: save a set of objects
+ Required argument: Objects to save.
+ Keyword argument _in: the file in which to save the object(s)
+ Keyword argument as: the file type of the document in which to save the data
+ Keyword argument _attributes: AppleEvent attribute dictionary
+ """
+ _code = 'core'
+ _subcode = 'save'
+
+ aetools.keysubst(_arguments, self._argmap_save)
+ _arguments['----'] = _object
+
+
+ _reply, _arguments, _attributes = self.send(_code, _subcode,
+ _arguments, _attributes)
+ if _arguments.has_key('errn'):
+ raise aetools.Error(aetools.decodeerror(_arguments))
+ # XXXX Optionally decode result
+ if _arguments.has_key('----'):
+ return _arguments['----']
+
+ _argmap_set = {
+ 'to' : 'data',
+ }
+
+ def set(self, _object, _attributes={}, **_arguments):
+ """set: Set an objectÕs data
+ Required argument: the object to change
+ Keyword argument to: the new value
+ Keyword argument _attributes: AppleEvent attribute dictionary
+ """
+ _code = 'core'
+ _subcode = 'setd'
+
+ aetools.keysubst(_arguments, self._argmap_set)
+ _arguments['----'] = _object
+
+
+ _reply, _arguments, _attributes = self.send(_code, _subcode,
+ _arguments, _attributes)
+ if _arguments.has_key('errn'):
+ raise aetools.Error(aetools.decodeerror(_arguments))
+ # XXXX Optionally decode result
+ if _arguments.has_key('----'):
+ return _arguments['----']
+
+
+class application(aetools.ComponentItem):
+ """application - An application program"""
+ want = 'capp'
+# element 'cwin' as ['indx', 'name', 'rele']
+# element 'docu' as ['name']
+
+class window(aetools.ComponentItem):
+ """window - A Window"""
+ want = 'cwin'
+class bounds(aetools.NProperty):
+ """bounds - the boundary rectangle for the window"""
+ which = 'pbnd'
+ want = 'qdrt'
+class closeable(aetools.NProperty):
+ """closeable - Does the window have a close box?"""
+ which = 'hclb'
+ want = 'bool'
+class titled(aetools.NProperty):
+ """titled - Does the window have a title bar?"""
+ which = 'ptit'
+ want = 'bool'
+class index(aetools.NProperty):
+ """index - the number of the window"""
+ which = 'pidx'
+ want = 'long'
+class floating(aetools.NProperty):
+ """floating - Does the window float?"""
+ which = 'isfl'
+ want = 'bool'
+class modal(aetools.NProperty):
+ """modal - Is the window modal?"""
+ which = 'pmod'
+ want = 'bool'
+class resizable(aetools.NProperty):
+ """resizable - Is the window resizable?"""
+ which = 'prsz'
+ want = 'bool'
+class zoomable(aetools.NProperty):
+ """zoomable - Is the window zoomable?"""
+ which = 'iszm'
+ want = 'bool'
+class zoomed(aetools.NProperty):
+ """zoomed - Is the window zoomed?"""
+ which = 'pzum'
+ want = 'bool'
+class name(aetools.NProperty):
+ """name - the title of the window"""
+ which = 'pnam'
+ want = 'itxt'
+class visible(aetools.NProperty):
+ """visible - is the window visible?"""
+ which = 'pvis'
+ want = 'bool'
+class position(aetools.NProperty):
+ """position - upper left coordinates of window"""
+ which = 'ppos'
+ want = 'QDpt'
+
+class document(aetools.ComponentItem):
+ """document - A Document"""
+ want = 'docu'
+# repeated property name the title of the document
+class modified(aetools.NProperty):
+ """modified - Has the document been modified since the last save?"""
+ which = 'imod'
+ want = 'bool'
+application._propdict = {
+}
+application._elemdict = {
+ 'window' : window,
+ 'document' : document,
+}
+window._propdict = {
+ 'bounds' : bounds,
+ 'closeable' : closeable,
+ 'titled' : titled,
+ 'index' : index,
+ 'floating' : floating,
+ 'modal' : modal,
+ 'resizable' : resizable,
+ 'zoomable' : zoomable,
+ 'zoomed' : zoomed,
+ 'name' : name,
+ 'visible' : visible,
+ 'position' : position,
+}
+window._elemdict = {
+}
+document._propdict = {
+ 'name' : name,
+ 'modified' : modified,
+}
+document._elemdict = {
+}
+_Enum_savo = {
+ 'yes' : 'yes ', # Save objects now
+ 'no' : 'no ', # Do not save objects
+ 'ask' : 'ask ', # Ask the user whether to save
+}
+
+
+#
+# Indices of types declared in this module
+#
+_classdeclarations = {
+ 'cwin' : window,
+ 'docu' : document,
+ 'capp' : application,
+}
+
+_propdeclarations = {
+ 'ptit' : titled,
+ 'pidx' : index,
+ 'ppos' : position,
+ 'pnam' : name,
+ 'pbnd' : bounds,
+ 'imod' : modified,
+ 'isfl' : floating,
+ 'hclb' : closeable,
+ 'iszm' : zoomable,
+ 'pmod' : modal,
+ 'pzum' : zoomed,
+ 'pvis' : visible,
+ 'prsz' : resizable,
+}
+
+_compdeclarations = {
+}
+
+_enumdeclarations = {
+ 'savo' : _Enum_savo,
+}
+
+"""Suite Miscellaneous Events: Useful events that arenÕt in any other suite
+Level 1, version 1
+
+Generated from Alpha:Desktop Folder:gnuplot.1:gnuplot 3.7.1a
+AETE/AEUT resource version 1/0, language 0, script 0
+"""
+
+import aetools
+import MacOS
+
+_code = 'misc'
+
+class Miscellaneous_Events:
+
+ def revert(self, _object, _attributes={}, **_arguments):
+ """revert: Revert an object to the most recently saved version
+ Required argument: object to revert
+ Keyword argument _attributes: AppleEvent attribute dictionary
+ """
+ _code = 'misc'
+ _subcode = 'rvrt'
+
+ if _arguments:
+ raise TypeError('No optional args expected')
+ _arguments['----'] = _object
+
+
+ _reply, _arguments, _attributes = self.send(_code, _subcode,
+ _arguments, _attributes)
+ if _arguments.has_key('errn'):
+ raise aetools.Error(aetools.decodeerror(_arguments))
+ # XXXX Optionally decode result
+ if _arguments.has_key('----'):
+ return _arguments['----']
+
+ def do_script(self, _object=None, _attributes={}, **_arguments):
+ """do script: execute a gnuplot script
+ Required argument: a gnuplot script
+ Keyword argument _attributes: AppleEvent attribute dictionary
+ """
+ _code = 'misc'
+ _subcode = 'dosc'
+
+ if _arguments:
+ raise TypeError('No optional args expected')
+ _arguments['----'] = _object
+
+
+ _reply, _arguments, _attributes = self.send(_code, _subcode,
+ _arguments, _attributes)
+ if _arguments.has_key('errn'):
+ raise aetools.Error(aetools.decodeerror(_arguments))
+ # XXXX Optionally decode result
+ if _arguments.has_key('----'):
+ return _arguments['----']
+
+
+#
+# Indices of types declared in this module
+#
+_classdeclarations = {
+}
+
+_propdeclarations = {
+}
+
+_compdeclarations = {
+}
+
+_enumdeclarations = {
+}
--- /dev/null
+# Id: gp.py 292 2006-03-03 09:49:04Z mhagger
+
+# Copyright (C) 1998-2003 Michael Haggerty <mhagger@alum.mit.edu>
+#
+# This file is licensed under the GNU Lesser General Public License
+# (LGPL). See LICENSE.txt for details.
+
+"""gp -- a platform-independent interface to a gnuplot process.
+
+This file imports a low-level, platform-independent interface to the
+gnuplot program. Which interface is imported depends on the platform.
+There are variations of this file for Unix, the Macintosh, and for
+Windows called gp_unix.py, gp_mac.py, and gp_win32.py, respectively.
+Note that the end-user should use the more capable interface from
+__init__.py (i.e., 'import Gnuplot') rather than the low-level
+interface imported by this file.
+
+See gp_unix.py for most documentation about the facilities of the
+gp_*.py modules.
+
+"""
+
+import sys, string
+
+# Low-level communication with gnuplot is platform-dependent. Import
+# the appropriate implementation of GnuplotProcess based on the
+# platform:
+if sys.platform == 'mac':
+ from gp_mac import GnuplotOpts, GnuplotProcess, test_persist
+elif sys.platform == 'win32':
+ from gp_win32 import GnuplotOpts, GnuplotProcess, test_persist
+elif sys.platform == 'darwin':
+ from gp_macosx import GnuplotOpts, GnuplotProcess, test_persist
+elif sys.platform[:4] == 'java':
+ from gp_java import GnuplotOpts, GnuplotProcess, test_persist
+elif sys.platform == 'cygwin':
+ from gp_cygwin import GnuplotOpts, GnuplotProcess, test_persist
+else:
+ from gp_unix import GnuplotOpts, GnuplotProcess, test_persist
+
+
+def double_quote_string(s):
+ """Return string s quoted and surrounded by double-quotes for gnuplot."""
+
+ for c in ['\\', '\"']:
+ s = str.replace(s, c, '\\' + c)
+
+ return '"%s"' % (s,)
+
+
--- /dev/null
+# Id: gp_cygwin.py 292 2006-03-03 09:49:04Z mhagger
+
+# Copyright (C) 1999-2003 Michael Haggerty <mhagger@alum.mit.edu>
+#
+# This file is licensed under the GNU Lesser General Public License
+# (LGPL). See LICENSE.txt for details.
+
+"""gp_cygwin -- an interface to gnuplot for cygwin under Windows.
+
+This is identical to gp_win32.py except that prefer_inline_data is
+set.
+
+"""
+
+import Errors
+
+# ############ Configuration variables: ################################
+
+class GnuplotOpts:
+ """The configuration options for gnuplot under windows.
+
+ See gp_unix.py for details about the meaning of these options.
+ Please let me know if you know better choices for these settings.
+
+ """
+
+ # Command to start up the gnuplot program. Note that on windows
+ # the main gnuplot program cannot be used directly because it can
+ # not read commands from standard input. See README for more
+ # information.
+ #
+ # If pgnuplot is in a subdirectory with spaces in its name, extra
+ # quoting is required for windows for it to launch gnuplot.
+ # Moreover, any backslashes in the filename have to be escaped by
+ # writing them as "\\". Example:
+ #
+ # gnuplot_command = '"C:\\Program Files\\gp371w32\\pgnuplot.exe"'
+ gnuplot_command = 'pgnuplot.exe'
+
+ # The '-persist' option is not supported on windows:
+ recognizes_persist = 0
+
+ # As far as I know, gnuplot under windows can use binary data:
+ recognizes_binary_splot = 1
+
+ # Apparently gnuplot on windows can use inline data, but we use
+ # non-inline data (i.e., temporary files) by default for no
+ # special reason:
+ prefer_inline_data = 1
+
+ # os.mkfifo is apparently not supported under Windows.
+ support_fifo = 0
+ prefer_fifo_data = 0
+
+ # The default choice for the 'set term' command (to display on
+ # screen):
+ default_term = 'windows'
+
+ # According to the gnuplot help manual, the following can be used
+ # to print directly to a printer under windows. (Of course it
+ # won't help if your printer can't handle postscript!)
+ default_lpr = 'PRN'
+
+ # Used the 'enhanced' option of postscript by default? Set to
+ # None (*not* 0!) if your version of gnuplot doesn't support
+ # enhanced postscript.
+ prefer_enhanced_postscript = 1
+
+# ############ End of configuration options ############################
+
+
+try:
+ from sys import hexversion
+except ImportError:
+ hexversion = 0
+
+if hexversion >= 0x02000000:
+ # Apparently at least as of Python 2.0b1, popen support for
+ # windows is adequate. Give that a try:
+ from os import popen
+else:
+ # For earlier versions, you have to have the win32 extensions
+ # installed and we use the popen that it provides.
+ from win32pipe import popen
+
+
+# Mac doesn't recognize persist.
+def test_persist():
+ return 0
+
+
+class GnuplotProcess:
+ """Unsophisticated interface to a running gnuplot program.
+
+ See gp_unix.py for usage information.
+
+ """
+
+ def __init__(self, persist=0):
+ """Start a gnuplot process.
+
+ Create a 'GnuplotProcess' object. This starts a gnuplot
+ program and prepares to write commands to it.
+
+ Keyword arguments:
+
+ 'persist' -- the '-persist' option is not supported under
+ Windows so this argument must be zero.
+
+ """
+
+ if persist:
+ raise Errors.OptionError(
+ '-persist is not supported under Windows!')
+
+ self.gnuplot = popen(GnuplotOpts.gnuplot_command, 'w')
+
+ # forward write and flush methods:
+ self.write = self.gnuplot.write
+ self.flush = self.gnuplot.flush
+
+ def close(self):
+ if self.gnuplot is not None:
+ self.gnuplot.close()
+ self.gnuplot = None
+
+ def __del__(self):
+ self.close()
+
+ def __call__(self, s):
+ """Send a command string to gnuplot, followed by newline."""
+
+ self.write(s + '\n')
+ self.flush()
+
+
--- /dev/null
+# Id: gp_java.py 291 2006-03-03 08:58:48Z mhagger
+
+# Copyright (C) 2002-2003 Michael Haggerty <mhagger@alum.mit.edu>
+#
+# This file is licensed under the GNU Lesser General Public License
+# (LGPL). See LICENSE.txt for details.
+
+"""gp_java -- an interface to gnuplot used under Jython/Java.
+
+This file implements a low-level interface to a gnuplot program run
+via Jython/Java. This file should be imported through gp.py, which in
+turn should be imported via 'import Gnuplot' rather than these
+low-level interfaces.
+
+"""
+
+# ############ Configuration variables: ################################
+
+class GnuplotOpts:
+ """The configuration options for gnuplot on generic platforms.
+
+ Store the options in a class to make them easy to import and
+ modify en masse. If you want to modify the options from the
+ command line or within a running program, do something like the
+ following::
+
+ import Gnuplot
+ Gnuplot.GnuplotOpts.gnuplot_command = '/bin/mygnuplot'
+
+ """
+
+ gnuplot_command = 'gnuplot'
+ recognizes_persist = 1
+ prefer_persist = 0
+ recognizes_binary_splot = 1
+ prefer_inline_data = 0
+ support_fifo = 0
+ prefer_fifo_data = 0
+ default_term = 'x11'
+ default_lpr = '| lpr'
+ prefer_enhanced_postscript = 1
+
+# ############ End of configuration options ############################
+
+import sys
+
+from java.lang import Thread
+from java.lang import Runtime
+
+
+def test_persist():
+ """Determine whether gnuplot recognizes the option '-persist'.
+
+ """
+
+ return GnuplotOpts.recognizes_persist
+
+
+class OutputProcessor(Thread):
+ """In a separate thread, read from one InputStream and output to a file.
+
+ """
+
+ def __init__(self, name, input, output):
+ self.input = input
+ self.output = output
+
+ Thread.__init__(self, name)
+ self.setDaemon(1)
+
+ def run(self):
+ while 1:
+ self.output.write(chr(self.input.read()))
+
+
+class GnuplotProcess:
+ """Unsophisticated interface to a running gnuplot program.
+
+ This represents a running gnuplot program and the means to
+ communicate with it at a primitive level (i.e., pass it commands
+ or data). When the object is destroyed, the gnuplot program exits
+ (unless the 'persist' option was set). The communication is
+ one-way; gnuplot's text output just goes to stdout with no attempt
+ to check it for error messages.
+
+ Members:
+
+
+ Methods:
+
+ '__init__' -- start up the program.
+
+ '__call__' -- pass an arbitrary string to the gnuplot program,
+ followed by a newline.
+
+ 'write' -- pass an arbitrary string to the gnuplot program.
+
+ 'flush' -- cause pending output to be written immediately.
+
+ """
+
+ def __init__(self, persist=None):
+ """Start a gnuplot process.
+
+ Create a 'GnuplotProcess' object. This starts a gnuplot
+ program and prepares to write commands to it.
+
+ Keyword arguments:
+
+ 'persist=1' -- start gnuplot with the '-persist' option,
+ (which leaves the plot window on the screen even after
+ the gnuplot program ends, and creates a new plot window
+ each time the terminal type is set to 'x11'). This
+ option is not available on older versions of gnuplot.
+
+ """
+
+ if persist is None:
+ persist = GnuplotOpts.prefer_persist
+ command = [GnuplotOpts.gnuplot_command]
+ if persist:
+ if not test_persist():
+ raise Exception('-persist does not seem to be supported '
+ 'by your version of gnuplot!')
+ command.append('-persist')
+
+ # This is a kludge: distutils wants to import everything it
+ # sees when making a distribution, and if we just call exec()
+ # normally that causes a SyntaxError in CPython because "exec"
+ # is a keyword. Therefore, we call the exec() method
+ # indirectly.
+ #self.process = Runtime.getRuntime().exec(command)
+ exec_method = getattr(Runtime.getRuntime(), 'exec')
+ self.process = exec_method(command)
+
+ self.outprocessor = OutputProcessor(
+ 'gnuplot standard output processor',
+ self.process.getInputStream(), sys.stdout
+ )
+ self.outprocessor.start()
+ self.errprocessor = OutputProcessor(
+ 'gnuplot standard error processor',
+ self.process.getErrorStream(), sys.stderr
+ )
+ self.errprocessor.start()
+
+ self.gnuplot = self.process.getOutputStream()
+
+ def close(self):
+ # ### Does this close the gnuplot process under Java?
+ if self.gnuplot is not None:
+ self.gnuplot.close()
+ self.gnuplot = None
+
+ def __del__(self):
+ self.close()
+
+ def write(self, s):
+ self.gnuplot.write(s)
+
+ def flush(self):
+ self.gnuplot.flush()
+
+ def __call__(self, s):
+ """Send a command string to gnuplot, followed by newline."""
+
+ self.write(s + '\n')
+ self.flush()
+
+
--- /dev/null
+# Id: gp_mac.py 292 2006-03-03 09:49:04Z mhagger
+
+# Copyright (C) 1999-2003 Michael Haggerty <mhagger@alum.mit.edu>
+# Thanks to Tony Ingraldi and Noboru Yamamoto for their contributions.
+#
+# This file is licensed under the GNU Lesser General Public License
+# (LGPL). See LICENSE.txt for details.
+
+"""gp_mac -- an interface to gnuplot for the Macintosh.
+
+"""
+
+import os, string
+
+import Errors
+
+
+# ############ Configuration variables: ################################
+
+class GnuplotOpts:
+ """The configuration options for gnuplot on the Macintosh.
+
+ See gp.py for details about the meaning of these options. Please
+ let me know if you know better choices for these settings."""
+
+ # The '-persist' option is not supported on the Mac:
+ recognizes_persist = 0
+
+ # Apparently the Mac can use binary data:
+ recognizes_binary_splot = 1
+
+ # Apparently the Mac can not use inline data:
+ prefer_inline_data = 0
+
+ # os.mkfifo is not supported on the Mac.
+ support_fifo = 0
+ prefer_fifo_data = 0
+
+ # The default choice for the 'set term' command (to display on screen).
+ # Terminal types are different in Gnuplot 3.7.1c.
+ # For earlier versions, this was default_term = 'macintosh'
+ default_term = 'pict'
+
+ # I don't know how to print directly to a printer on the Mac:
+ default_lpr = '| lpr'
+
+ # Used the 'enhanced' option of postscript by default? Set to
+ # None (*not* 0!) if your version of gnuplot doesn't support
+ # enhanced postscript.
+ prefer_enhanced_postscript = 1
+
+# ############ End of configuration options ############################
+
+
+# The Macintosh doesn't support pipes so communication is via
+# AppleEvents.
+
+import gnuplot_Suites
+import Required_Suite
+import aetools
+
+
+# Mac doesn't recognize persist.
+def test_persist():
+ return 0
+
+
+class _GNUPLOT(aetools.TalkTo,
+ Required_Suite.Required_Suite,
+ gnuplot_Suites.gnuplot_Suite,
+ gnuplot_Suites.odds_and_ends,
+ gnuplot_Suites.Standard_Suite,
+ gnuplot_Suites.Miscellaneous_Events):
+ """Start a gnuplot program and emulate a pipe to it."""
+
+ def __init__(self):
+ aetools.TalkTo.__init__(self, '{GP}', start=1)
+
+
+class GnuplotProcess:
+ """Unsophisticated interface to a running gnuplot program.
+
+ See gp_unix.GnuplotProcess for usage information.
+
+ """
+
+ def __init__(self, persist=0):
+ """Start a gnuplot process.
+
+ Create a 'GnuplotProcess' object. This starts a gnuplot
+ program and prepares to write commands to it.
+
+ Keyword arguments:
+
+ 'persist' -- the '-persist' option is not supported on the
+ Macintosh so this argument must be zero.
+
+ """
+
+ if persist:
+ raise Errors.OptionError(
+ '-persist is not supported on the Macintosh!')
+
+ self.gnuplot = _GNUPLOT()
+
+ def close(self):
+ if self.gnuplot is not None:
+ self.gnuplot.quit()
+ self.gnuplot = None
+
+ def __del__(self):
+ self.close()
+
+ def write(self, s):
+ """Mac gnuplot apparently requires '\r' to end statements."""
+
+ self.gnuplot.gnuexec(string.replace(s, '\n', os.linesep))
+
+ def flush(self):
+ pass
+
+ def __call__(self, s):
+ """Send a command string to gnuplot, for immediate execution."""
+
+ # Apple Script doesn't seem to need the trailing '\n'.
+ self.write(s)
+ self.flush()
+
+
--- /dev/null
+# Id: gp_macosx.py 291 2006-03-03 08:58:48Z mhagger
+
+# Copyright (C) 1998-2003 Michael Haggerty <mhagger@alum.mit.edu>
+#
+# This file is licensed under the GNU Lesser General Public License
+# (LGPL). See LICENSE.txt for details.
+
+"""gp_macosx -- an interface to the command line version of gnuplot
+used under Mac OS X.
+
+The only difference between this interface and gp_unix is that
+default_term is 'aqua'.
+
+This file implements a low-level interface to gnuplot. This file
+should be imported through gp.py, which in turn should be imported via
+'import Gnuplot' rather than using these low-level interfaces
+directly.
+
+"""
+
+# ############ Configuration variables: ################################
+
+class GnuplotOpts:
+ """The configuration options for gnuplot on Mac OS X.
+
+ See the gp_unix.py for documentation on all of the parameters.
+
+ """
+
+ gnuplot_command = 'gnuplot'
+ recognizes_persist = None # test automatically on first use
+ prefer_persist = 0
+ recognizes_binary_splot = 1
+ prefer_inline_data = 0
+
+ # os.mkfifo should be supported on Mac OS X. Let me know if I'm
+ # wrong.
+ support_fifo = 1
+ prefer_fifo_data = 1
+
+ default_term = 'aqua'
+ default_lpr = '| lpr'
+ prefer_enhanced_postscript = 1
+
+# ############ End of configuration options ############################
+
+from os import popen
+
+
+def test_persist():
+ """Determine whether gnuplot recognizes the option '-persist'.
+
+ If the configuration variable 'recognizes_persist' is set (i.e.,
+ to something other than 'None'), return that value. Otherwise,
+ try to determine whether the installed version of gnuplot
+ recognizes the -persist option. (If it doesn't, it should emit an
+ error message with '-persist' in the first line.) Then set
+ 'recognizes_persist' accordingly for future reference.
+
+ """
+
+ if GnuplotOpts.recognizes_persist is None:
+ import string
+ g = popen('echo | %s -persist 2>&1' % GnuplotOpts.gnuplot_command, 'r')
+ response = g.readlines()
+ g.close()
+ GnuplotOpts.recognizes_persist = (
+ (not response) or (string.find(response[0], '-persist') == -1))
+ return GnuplotOpts.recognizes_persist
+
+
+class GnuplotProcess:
+ """Unsophisticated interface to a running gnuplot program.
+
+ This represents a running gnuplot program and the means to
+ communicate with it at a primitive level (i.e., pass it commands
+ or data). When the object is destroyed, the gnuplot program exits
+ (unless the 'persist' option was set). The communication is
+ one-way; gnuplot's text output just goes to stdout with no attempt
+ to check it for error messages.
+
+ Members:
+
+ 'gnuplot' -- the pipe to the gnuplot command.
+
+ Methods:
+
+ '__init__' -- start up the program.
+
+ '__call__' -- pass an arbitrary string to the gnuplot program,
+ followed by a newline.
+
+ 'write' -- pass an arbitrary string to the gnuplot program.
+
+ 'flush' -- cause pending output to be written immediately.
+
+ 'close' -- close the connection to gnuplot.
+
+ """
+
+ def __init__(self, persist=None):
+ """Start a gnuplot process.
+
+ Create a 'GnuplotProcess' object. This starts a gnuplot
+ program and prepares to write commands to it.
+
+ Keyword arguments:
+
+ 'persist=1' -- start gnuplot with the '-persist' option,
+ (which leaves the plot window on the screen even after
+ the gnuplot program ends, and creates a new plot window
+ each time the terminal type is set to 'x11'). This
+ option is not available on older versions of gnuplot.
+
+ """
+
+ if persist is None:
+ persist = GnuplotOpts.prefer_persist
+ if persist:
+ if not test_persist():
+ raise Exception('-persist does not seem to be supported '
+ 'by your version of gnuplot!')
+ self.gnuplot = popen('%s -persist' % GnuplotOpts.gnuplot_command,
+ 'w')
+ else:
+ self.gnuplot = popen(GnuplotOpts.gnuplot_command, 'w')
+
+ # forward write and flush methods:
+ self.write = self.gnuplot.write
+ self.flush = self.gnuplot.flush
+
+ def close(self):
+ if self.gnuplot is not None:
+ self.gnuplot.close()
+ self.gnuplot = None
+
+ def __del__(self):
+ self.close()
+
+ def __call__(self, s):
+ """Send a command string to gnuplot, followed by newline."""
+
+ self.write(s + '\n')
+ self.flush()
+
+
--- /dev/null
+# Id: gp_unix.py 292 2006-03-03 09:49:04Z mhagger
+
+# Copyright (C) 1998-2003 Michael Haggerty <mhagger@alum.mit.edu>
+#
+# This file is licensed under the GNU Lesser General Public License
+# (LGPL). See LICENSE.txt for details.
+
+"""gp_unix -- an interface to gnuplot used for unix platforms.
+
+This file implements a low-level interface to a gnuplot program for a
+unix platform (actually it is used for any non-Windows, non-Mac
+system). This file should be imported through gp.py, which in turn
+should be imported via 'import Gnuplot' rather than these low-level
+interfaces.
+
+"""
+
+# ############ Configuration variables: ################################
+
+class GnuplotOpts:
+ """The configuration options for gnuplot on generic platforms.
+
+ Store the options in a class to make them easy to import and
+ modify en masse. If you want to modify the options from the
+ command line or within a running program, do something like the
+ following::
+
+ import Gnuplot
+ Gnuplot.GnuplotOpts.gnuplot_command = '/bin/mygnuplot'
+
+ """
+
+ # Command to start up the gnuplot program. If your version of
+ # gnuplot is run otherwise, specify the correct command here. You
+ # could also specify a full path or append command-line options
+ # here if you wish.
+ gnuplot_command = 'gnuplot'
+
+ # Recent versions of gnuplot (at least for Xwindows) allow a
+ # `-persist' command-line option when starting up gnuplot. When
+ # this option is specified, graph windows remain on the screen
+ # even after you quit gnuplot (type `q' in the window to close
+ # it). This can be handy but unfortunately it is not supported by
+ # older versions of gnuplot. The following configuration variable
+ # specifies whether the user's version of gnuplot recognizes this
+ # option or not. You can set this variable to 1 (supports
+ # -persist) or 0 (doesn't support) yourself; if you leave it with
+ # the value None then the first time you create a Gnuplot object
+ # it will try to detect automatically whether your version accepts
+ # this option.
+ recognizes_persist = None # test automatically on first use
+
+ # What should be the default if the persist option is not
+ # specified explicitly?
+ prefer_persist = 0
+
+ # Recent versions of gnuplot allow you to specify a `binary'
+ # option to the splot command for grid data, which means that the
+ # data file is to be read in binary format. This option saves
+ # substantial time writing and reading the file, and can also save
+ # substantial disk space and therefore it is the default for that
+ # type of plot. But if you have an older version of gnuplot (or
+ # you prefer text format) you can disable the binary option in
+ # either of two ways: (a) set the following variable to 0; or (b)
+ # pass `binary=0' to the GridData constructor. (Note that the
+ # demo uses binary=0 to maximize portability.)
+ recognizes_binary_splot = 1
+
+ # Data can be passed to gnuplot through a temporary file or as
+ # inline data (i.e., the filename is set to '-' and the data is
+ # entered into the gnuplot interpreter followed by 'e'). If
+ # prefer_inline_data is true, then use the inline method as
+ # default whenever it is supported. This should be fast but will
+ # use more memory since currently the inline data is put into a
+ # big string when the PlotItem is created.
+ prefer_inline_data = 0
+
+ # Does Python implement the threading module and os.mkfifo on this
+ # operating system? If so, the _FIFOFileItem class will be
+ # defined in PlotItem.py.
+ support_fifo = 1
+
+ # Should FIFOs be used to send data to gnuplot by default?
+ prefer_fifo_data = 1
+
+ # After a hardcopy is produced, we have to set the terminal type
+ # back to `on screen' using gnuplot's `set terminal' command. The
+ # following is the usual setting for Xwindows. If it is wrong,
+ # change the following line to select the terminal type you prefer
+ # to use for on-screen work.
+ default_term = 'x11'
+
+ # Gnuplot can plot to a printer by using "set output '| ...'"
+ # where ... is the name of a program that sends its stdin to a
+ # printer, or by "set output 'printer_device', where
+ # 'printer_device is the name of a file-like interface to the
+ # printer. On my machine the appropriate program is `lpr', as set
+ # below. On your computer it may be something different (like
+ # `lp'); you can set that by changing the variable below. You can
+ # also add options to the print command if needed.
+ default_lpr = '| lpr'
+
+ # Enhanced postscript is an option to the postscript terminal
+ # driver that requests enhanced treatment of strings (for example,
+ # font changes, superscripts, and subscripts). Set to 1 to enable
+ # or 0 to disable. If you have a version of gnuplot earlier than
+ # 3.7, you should set this to None (*not* 0!) so that the option
+ # is not used at all.
+ prefer_enhanced_postscript = 1
+
+# ############ End of configuration options ############################
+
+from os import popen
+
+
+def test_persist():
+ """Determine whether gnuplot recognizes the option '-persist'.
+
+ If the configuration variable 'recognizes_persist' is set (i.e.,
+ to something other than 'None'), return that value. Otherwise,
+ try to determine whether the installed version of gnuplot
+ recognizes the -persist option. (If it doesn't, it should emit an
+ error message with '-persist' in the first line.) Then set
+ 'recognizes_persist' accordingly for future reference.
+
+ """
+
+ if GnuplotOpts.recognizes_persist is None:
+ import string
+ g = popen('echo | %s -persist 2>&1' % GnuplotOpts.gnuplot_command, 'r')
+ response = g.readlines()
+ g.close()
+ GnuplotOpts.recognizes_persist = (
+ (not response) or (string.find(response[0], '-persist') == -1))
+ return GnuplotOpts.recognizes_persist
+
+
+class GnuplotProcess:
+ """Unsophisticated interface to a running gnuplot program.
+
+ This represents a running gnuplot program and the means to
+ communicate with it at a primitive level (i.e., pass it commands
+ or data). When the object is destroyed, the gnuplot program exits
+ (unless the 'persist' option was set). The communication is
+ one-way; gnuplot's text output just goes to stdout with no attempt
+ to check it for error messages.
+
+ Members:
+
+ 'gnuplot' -- the pipe to the gnuplot command.
+
+ Methods:
+
+ '__init__' -- start up the program.
+
+ '__call__' -- pass an arbitrary string to the gnuplot program,
+ followed by a newline.
+
+ 'write' -- pass an arbitrary string to the gnuplot program.
+
+ 'flush' -- cause pending output to be written immediately.
+
+ 'close' -- close the connection to gnuplot.
+
+ """
+
+ def __init__(self, persist=None):
+ """Start a gnuplot process.
+
+ Create a 'GnuplotProcess' object. This starts a gnuplot
+ program and prepares to write commands to it.
+
+ Keyword arguments:
+
+ 'persist=1' -- start gnuplot with the '-persist' option,
+ (which leaves the plot window on the screen even after
+ the gnuplot program ends, and creates a new plot window
+ each time the terminal type is set to 'x11'). This
+ option is not available on older versions of gnuplot.
+
+ """
+
+ if persist is None:
+ persist = GnuplotOpts.prefer_persist
+ if persist:
+ if not test_persist():
+ raise Exception('-persist does not seem to be supported '
+ 'by your version of gnuplot!')
+ self.gnuplot = popen('%s -persist' % GnuplotOpts.gnuplot_command,
+ 'w')
+ else:
+ self.gnuplot = popen(GnuplotOpts.gnuplot_command, 'w')
+
+ # forward write and flush methods:
+ self.write = self.gnuplot.write
+ self.flush = self.gnuplot.flush
+
+ def close(self):
+ if self.gnuplot is not None:
+ self.gnuplot.close()
+ self.gnuplot = None
+
+ def __del__(self):
+ self.close()
+
+ def __call__(self, s):
+ """Send a command string to gnuplot, followed by newline."""
+
+ self.write(s + '\n')
+ self.flush()
+
+
--- /dev/null
+# Id: gp_win32.py 292 2006-03-03 09:49:04Z mhagger
+
+# Copyright (C) 1999-2003 Michael Haggerty <mhagger@alum.mit.edu>
+#
+# This file is licensed under the GNU Lesser General Public License
+# (LGPL). See LICENSE.txt for details.
+
+"""gp_win32 -- an interface to gnuplot for Windows.
+
+"""
+
+import Errors
+
+# ############ Configuration variables: ################################
+
+class GnuplotOpts:
+ """The configuration options for gnuplot under windows.
+
+ See gp_unix.py for details about the meaning of these options.
+ Please let me know if you know better choices for these settings.
+
+ """
+
+ # Command to start up the gnuplot program. Note that on windows
+ # the main gnuplot program cannot be used directly because it can
+ # not read commands from standard input. See README for more
+ # information.
+ #
+ # If pgnuplot is in a subdirectory with spaces in its name, extra
+ # quoting is required for windows for it to launch gnuplot.
+ # Moreover, it is suggested to use a raw string to avoid having to
+ # quote backslashes in the filename. Example:
+ #
+ # gnuplot_command = r'"C:\Program Files\gp371w32\pgnuplot.exe"'
+ gnuplot_command = r'pgnuplot.exe'
+
+ # The '-persist' option is not supported on windows:
+ recognizes_persist = 0
+
+ # As far as I know, gnuplot under windows can use binary data:
+ recognizes_binary_splot = 1
+
+ # Apparently gnuplot on windows can use inline data, but we use
+ # non-inline data (i.e., temporary files) by default for no
+ # special reason:
+ prefer_inline_data = 0
+
+ # os.mkfifo is apparently not supported under Windows.
+ support_fifo = 0
+ prefer_fifo_data = 0
+
+ # The default choice for the 'set term' command (to display on
+ # screen):
+ default_term = 'windows'
+
+ # According to the gnuplot help manual, the following can be used
+ # to print directly to a printer under windows. (Of course it
+ # won't help if your printer can't handle postscript!)
+ default_lpr = 'PRN'
+
+ # Used the 'enhanced' option of postscript by default? Set to
+ # None (*not* 0!) if your version of gnuplot doesn't support
+ # enhanced postscript.
+ prefer_enhanced_postscript = 1
+
+# ############ End of configuration options ############################
+
+
+try:
+ from sys import hexversion
+except ImportError:
+ hexversion = 0
+
+if hexversion >= 0x02000000:
+ # Apparently at least as of Python 2.0b1, popen support for
+ # windows is adequate. Give that a try:
+ from os import popen
+else:
+ # For earlier versions, you have to have the win32 extensions
+ # installed and we use the popen that it provides.
+ from win32pipe import popen
+
+
+# Mac doesn't recognize persist.
+def test_persist():
+ return 0
+
+
+class GnuplotProcess:
+ """Unsophisticated interface to a running gnuplot program.
+
+ See gp_unix.py for usage information.
+
+ """
+
+ def __init__(self, persist=0):
+ """Start a gnuplot process.
+
+ Create a 'GnuplotProcess' object. This starts a gnuplot
+ program and prepares to write commands to it.
+
+ Keyword arguments:
+
+ 'persist' -- the '-persist' option is not supported under
+ Windows so this argument must be zero.
+
+ """
+
+ if persist:
+ raise Errors.OptionError(
+ '-persist is not supported under Windows!')
+
+ self.gnuplot = popen(GnuplotOpts.gnuplot_command, 'w')
+
+ # forward write and flush methods:
+ self.write = self.gnuplot.write
+ self.flush = self.gnuplot.flush
+
+ def close(self):
+ if self.gnuplot is not None:
+ self.gnuplot.close()
+ self.gnuplot = None
+
+ def __del__(self):
+ self.close()
+
+ def __call__(self, s):
+ """Send a command string to gnuplot, followed by newline."""
+
+ self.write(s + '\n')
+ self.flush()
+
+
--- /dev/null
+# Id: termdefs.py 302 2008-01-14 22:15:19Z bmcage
+
+# Copyright (C) 2001-2003 Michael Haggerty <mhagger@alum.mit.edu>
+#
+# This file is licensed under the GNU Lesser General Public License
+# (LGPL). See LICENSE.txt for details.
+
+"""Terminal definition file.
+
+This module describes the options available to gnuplot's various
+terminals. For the moment, it only supports a few terminals, but the
+infrastructure is here to add others as they are needed.
+
+Part of the trick is that the 'set terminal' command takes myriad
+suboptions with various argument types, and order is sometimes
+significant. The other part of the trick is that there are over 50
+terminal types, and each terminal has its own set of options.
+
+The strategy here is to define a general mechanism for turning Python
+keyword parameters into fragments of gnuplot command strings. There
+are a number of classes derived from Arg that do this. Some take
+string args, some boolean, etc. Then the list of options that each
+terminal accepts is stored in the terminal_opts dictionary.
+Gnuplot.hardcopy(), in turn, uses this dictionary to interpret its
+keyword arguments and build the 'set terminal' command.
+
+"""
+
+
+import types
+
+import gp, Errors
+
+
+class Arg:
+ """Process terminal subargs and return a command fragment.
+
+ Pull one or more arguments from keyw and output a list of strings
+ that will be appended to the 'set terminal' (separated by spaces).
+ Delete any used args from keyw. If no relevant options are found,
+ return None.
+
+ This is a base class for the actual argument-processing classes.
+ Derived classes must define a __call__(self, keyw) method
+ returning a list of strings or None.
+
+ """
+
+ pass
+
+
+class ArgOneParam(Arg):
+ """Arg abstract base class specialized for exactly one parameter.
+
+ Members:
+
+ 'argname' -- The name of the keyword argument used to pass
+ this argument to Python.
+
+ 'default' -- The default value of the argument, used if no
+ keyword parameter is found. If this is None, then no
+ default is assumed.
+
+ """
+
+ def __init__(self, argname, default):
+ self.argname = argname
+ self.default = default
+
+ def get_option(self, keyw):
+ """Get the keyword argument corresponding to this Arg.
+
+ Look in keyw for the keyword argument needed by this Arg. If
+ it is found, delete it from keyw and return it. If it is not
+ found, return self.default.
+
+ """
+
+ try:
+ k = keyw[self.argname]
+ except KeyError:
+ return self.default
+ else:
+ del keyw[self.argname]
+ return k
+
+
+class KeywordArg(ArgOneParam):
+ """Represent an argument that must be passed as a keyword to gnuplot.
+
+ Some gnuplot options take the form of single unquoted keywords
+ (possibly preceded by a fixed keyword). We allow those to be
+ passed as strings 'option="keyword"'. Check that the option
+ supplied is in the list of allowed options.
+
+ Members:
+
+ 'fixedword' -- the fixed keyword that must precede the
+ variable keyword in the gnuplot command, or None if none
+ is required.
+
+ 'options' -- a list of strings containing the legal
+ alternatives for this argument.
+
+ """
+
+ def __init__(self, argname, options, fixedword=None, default=None):
+ ArgOneParam.__init__(self, argname, default)
+ self.fixedword = fixedword
+ self.options = options
+
+ def __call__(self, keyw):
+ k = self.get_option(keyw)
+
+ if k is None:
+ return None
+ elif k in self.options:
+ if self.fixedword is None:
+ return [k]
+ else:
+ return [self.fixedword, k]
+ else:
+ raise Errors.OptionError(
+ 'Illegal option %s="%s"' % (self.argname, k,))
+
+
+class StringArg(ArgOneParam):
+ """An option taking a quoted string argument."""
+
+ def __init__(self, argname, fixedword=None, default=None):
+ ArgOneParam.__init__(self, argname, default)
+ self.fixedword = fixedword
+
+ def __call__(self, keyw):
+ k = self.get_option(keyw)
+
+ if k is None:
+ return None
+ elif type(k) is not str:
+ raise Errors.OptionError(
+ 'Option %s must be a string' % (self.argname,))
+ else:
+ retval = []
+ if self.fixedword is not None:
+ retval.append(self.fixedword)
+ retval.append('"%s"' % k)
+ return retval
+
+
+class BareStringArg(ArgOneParam):
+ """An arbitrary argument output without quotes.
+
+ The argument can be a string or anything with a str()
+ representation, or a tuple of such things. Thus this can be used
+ for strings (which will be output without quotation marks),
+ integers, floating point arguments, or multiple arguments of the
+ above types (which will be output separated by spaces). No
+ checking is done that the argument is sensible.
+
+ """
+
+ def __init__(self, argname, fixedword=None, default=None):
+ ArgOneParam.__init__(self, argname, default)
+ self.fixedword = fixedword
+
+ def __call__(self, keyw):
+ k = self.get_option(keyw)
+
+ if k is None:
+ return None
+ else:
+ retval = []
+ if self.fixedword is not None:
+ retval.append(self.fixedword)
+ if type(k) in (tuple, list):
+ for i in k:
+ retval.append(str(i))
+ else:
+ retval.append(str(k))
+ return retval
+
+
+class BooleanArg(ArgOneParam):
+ """An argument that takes a true/false value.
+
+ The argument should be 0 or 1. The option is output to gnuplot as
+ 'trueval' if the argument is true or 'falseval' if the argument is
+ false. Either one can be 'None', in which case nothing is output.
+ 'default' should also be 0 or 1.
+
+ """
+
+ def __init__(self, argname, trueval, falseval,
+ fixedword=None, default=None):
+ ArgOneParam.__init__(self, argname, default)
+ self.trueval = trueval
+ self.falseval = falseval
+ self.fixedword = fixedword
+
+ def __call__(self, keyw):
+ k = self.get_option(keyw)
+ if k is None:
+ return None
+ else:
+ retval = []
+ if self.fixedword is not None:
+ retval.append(self.fixedword)
+ if k:
+ val = self.trueval
+ else:
+ val = self.falseval
+ if val is not None:
+ retval.append(val)
+ return retval
+
+
+class MutuallyExclusiveArgs(Arg):
+ """A group of args, of which either zero or one may be set, but not more.
+
+ Members:
+
+ subargs -- a list [('argname', arg), ...] of Arg instances.
+ 'argname' is used to identify the corresponding arg in
+ error messages. (The name of the corresponding keyword
+ args is determined internally by each arg.)
+
+ """
+
+ def __init__(self, *subargs):
+ self.subargs = list(subargs)
+
+ def __call__(self, keyw):
+ foundargname = None
+ retval = None
+ for (argname, arg,) in self.subargs:
+ cmd = arg(keyw)
+ if cmd is not None:
+ if foundargname is not None:
+ raise Errors.OptionError(
+ 'Arguments %s and %s cannot both be specified'
+ % (foundargname, argname,)
+ )
+ else:
+ foundargname = argname
+ retval = cmd
+ return retval # might be None
+
+
+class KeywordOrBooleanArg(Arg):
+ """Allow a keyword arg to be specified either as a keyword or a boolean.
+
+ This arg type is the most flexible way to allow keyword parameters
+ to be specified. Say there is an option like 'fontsize' that can
+ take the values 'small' or 'large'. This could be represented as
+
+ 'KeywordOrBooleanArg(options=["small", "large"], argname="fontsize")'
+
+ In that case, the fontsize could be specified in any of the
+ following ways:
+
+ 'g.hardcopy(..., fontsize="small", ...)'
+ 'g.hardcopy(..., fontsize="large", ...)'
+ 'g.hardcopy(..., small=1, ...)'
+ 'g.hardcopy(..., large=1, ...)'
+
+ If 'argname' is set to be 'None', then the first two possibilities
+ are omitted.
+
+ In the special case that there are exactly two alternatives, one
+ can also use:
+
+ 'g.hardcopy(..., small=0, ...) # implies fontsize="large"'
+ 'g.hardcopy(..., large=0, ...) # implies fontsize="small"'
+
+ Obviously care must be taken to ensure that none of the implied
+ keyword parameter names conflict with one another or with any of
+ the other Args allowed by a function.
+
+ Members:
+
+ 'options' -- a list of strings representing allowed keyword
+ values. These options can be used as boolean values in
+ the style 'option=1'.
+
+ 'argname' -- the name of the argname for the 'arg=value' style
+ of setting the argument. If 'None', then this style is
+ not allowed.
+
+ 'fixedword' -- a fixed keyword that must precede the option,
+ or 'None'.
+
+ 'default' -- the default option to set if nothing is set
+ explicitly, or None to leave nothing set in that case.
+
+ """
+
+ def __init__(self, options, argname=None, fixedword=None, default=None):
+ self.options = options
+ self.argname = argname
+ self.fixedword = fixedword
+ self.default = default
+ assert self.default is None or self.default in self.options, \
+ 'default must be a valid option'
+
+ def __call__(self, keyw):
+ if self.argname is not None and self.argname in keyw:
+ k = keyw[self.argname]
+ del keyw[self.argname]
+ if k is None:
+ pass
+ elif k in self.options:
+ # Make sure it isn't contradicted by the corresponding boolean:
+ if k in keyw and not keyw[k]:
+ raise Errors.OptionError(
+ 'Arguments %s and %s are contradictory'
+ % (self.argname, k,)
+ )
+ else:
+ # Store the option into the boolean to be processed below:
+ keyw[k] = 1
+ else:
+ raise Errors.OptionError(
+ 'Illegal option %s=%s' % (self.argname, k,))
+
+ # Now scan the booleans and make sure that at most one is set:
+ option = None
+ for i in range(len(self.options)):
+ k = self.options[i]
+ if k in keyw:
+ newval = keyw[k]
+ del keyw[k]
+ if newval:
+ if option is not None:
+ raise Errors.OptionError(
+ 'Arguments %s and %s cannot both be specified'
+ % (option, k,)
+ )
+ else:
+ option = k
+ else:
+ # newval was false. This is only legal if this
+ # option only has two possible values:
+ if len(self.options) == 2:
+ option = self.options[1 - i]
+ else:
+ pass
+
+ if option is None:
+ if self.default is None:
+ return None
+ else:
+ option = self.default
+ retval = []
+ if self.fixedword is not None:
+ retval.append(self.fixedword)
+ retval.append(option)
+ return retval
+
+
+# Now we define the allowed options for a few terminal types. This
+# table is used by Gnuplot.hardcopy() to construct the necessary 'set
+# terminal' command.
+
+terminal_opts = {}
+
+terminal_opts['postscript'] = [
+ KeywordOrBooleanArg(
+ options=['landscape', 'portrait', 'eps', 'default'],
+ argname='mode',
+ ),
+ KeywordOrBooleanArg(
+ options=['enhanced', 'noenhanced'],
+ # This default should probably be computed from the *current*
+ # value of GnuplotOpts, not at import time. ###
+ default=(gp.GnuplotOpts.prefer_enhanced_postscript
+ and 'enhanced'
+ or 'noenhanced'),
+ ),
+ KeywordOrBooleanArg(options=['color', 'monochrome']),
+ KeywordOrBooleanArg(options=['solid', 'dashed']),
+ KeywordOrBooleanArg(
+ options=['defaultplex', 'simplex', 'duplex'],
+ argname='duplexing',
+ ),
+ StringArg(argname='fontname'),
+ BareStringArg(argname='fontsize'),
+ ]
+
+terminal_opts['pdf'] = [
+ KeywordOrBooleanArg(
+ options=['landscape', 'portrait', 'eps', 'default'],
+ argname='mode',
+ ),
+ KeywordOrBooleanArg(options=['color', 'monochrome']),
+ KeywordOrBooleanArg(options=['solid', 'dashed']),
+ KeywordOrBooleanArg(
+ options=['defaultplex', 'simplex', 'duplex'],
+ argname='duplexing',
+ ),
+ StringArg(argname='fontname'),
+ BareStringArg(argname='fontsize'),
+ ]
+
+terminal_opts['png'] = [
+ KeywordOrBooleanArg(
+ options=['small', 'medium', 'large'],
+ argname='fontsize',
+ ),
+ KeywordOrBooleanArg(options=['monochrome', 'gray', 'color']),
+ ]
+
+terminal_opts['fig'] = [
+ KeywordOrBooleanArg(options=['monochrome', 'color']),
+ KeywordOrBooleanArg(options=['small', 'big']),
+ BareStringArg(argname='pointsmax', fixedword='pointsmax'),
+ KeywordOrBooleanArg(options=['landscape', 'portrait']),
+ KeywordOrBooleanArg(options=['metric', 'inches']),
+ BareStringArg(argname='fontsize'),
+ BareStringArg(argname='size'), # needs a tuple of two doubles
+ BareStringArg(argname='thickness'),
+ BareStringArg(argname='depth'),
+ ]
+
+terminal_opts['cgm'] = [
+ KeywordOrBooleanArg(
+ options=['landscape', 'portrait', 'default'],
+ argname='mode',
+ ),
+ KeywordOrBooleanArg(options=['color', 'monochrome']),
+ KeywordOrBooleanArg(options=['rotate', 'norotate']),
+ BareStringArg(argname='width', fixedword='width'),
+ BareStringArg(argname='linewidth', fixedword='linewidth'),
+ StringArg(argname='font'),
+ BareStringArg(argname='fontsize'),
+ ]
+
+terminal_opts['pict'] = [
+ KeywordOrBooleanArg(
+ options=['landscape', 'portrait', 'default'],
+ argname='mode',
+ ),
+ KeywordOrBooleanArg(options=['color', 'monochrome']),
+ KeywordOrBooleanArg(options=['dashes', 'nodashes']),
+
+ # default font, which must be a valid pict font:
+ StringArg(argname='fontname'),
+
+ # default font size, in points:
+ BareStringArg(argname='fontsize'),
+
+ # width of plot in pixels:
+ BareStringArg(argname='width'),
+
+ # height of plot in pixels:
+ BareStringArg(argname='height'),
+
+ ]
+
+terminal_opts['mp'] = [
+ KeywordOrBooleanArg(options=['color', 'colour', 'monochrome']),
+ KeywordOrBooleanArg(options=['solid', 'dashed']),
+ KeywordOrBooleanArg(options=['notex', 'tex', 'latex']),
+ BareStringArg(argname='magnification'),
+ KeywordOrBooleanArg(options=['psnfss', 'psnfss-version7', 'nopsnfss']),
+ BareStringArg(argname='prologues'),
+ KeywordOrBooleanArg(options=['a4paper']),
+ KeywordOrBooleanArg(options=['amstex']),
+ StringArg(argname='fontname'),
+ BareStringArg(argname='fontsize'),
+ ]
+
+terminal_opts['svg'] = [
+ BareStringArg(argname='size', fixedword='size'), # tuple of two doubles
+ KeywordOrBooleanArg(options=['fixed', 'dynamic']),
+ StringArg(argname='fname', fixedword='fname'),
+ BareStringArg(argname='fsize', fixedword='fsize'),
+ KeywordOrBooleanArg(options=['enhanced', 'noenhanced']),
+ StringArg(argname='fontfile', fixedword='fontfile'),
+ ]
--- /dev/null
+#! /usr/bin/env python
+
+# Id: test.py 302 2008-01-14 22:15:19Z bmcage
+
+# Copyright (C) 1999-2003 Michael Haggerty <mhagger@alum.mit.edu>
+#
+# This file is licensed under the GNU Lesser General Public License
+# (LGPL). See LICENSE.txt for details.
+
+"""test.py -- Exercise the Gnuplot.py module.
+
+This module is not meant to be a flashy demonstration; rather it is a
+thorough test of many combinations of Gnuplot.py features.
+
+"""
+
+import os, time, math, tempfile
+import numpy
+
+try:
+ import Gnuplot, Gnuplot.PlotItems, Gnuplot.funcutils
+except ImportError:
+ # kludge in case Gnuplot hasn't been installed as a module yet:
+ import __init__
+ Gnuplot = __init__
+ import PlotItems
+ Gnuplot.PlotItems = PlotItems
+ import funcutils
+ Gnuplot.funcutils = funcutils
+
+
+def wait(str=None, prompt='Press return to show results...\n'):
+ if str is not None:
+ print(str)
+ input(prompt)
+
+
+def main():
+ """Exercise the Gnuplot module."""
+
+ print (
+ 'This program exercises many of the features of Gnuplot.py. The\n'
+ 'commands that are actually sent to gnuplot are printed for your\n'
+ 'enjoyment.'
+ )
+
+ wait('Popping up a blank gnuplot window on your screen.')
+ g = Gnuplot.Gnuplot(debug=1)
+ g.clear()
+
+ # Make two temporary files:
+ if hasattr(tempfile, 'mkstemp'):
+ (fd, filename1,) = tempfile.mkstemp(text=1)
+ f = os.fdopen(fd, 'w')
+ (fd, filename2,) = tempfile.mkstemp(text=1)
+ else:
+ filename1 = tempfile.mktemp()
+ f = open(filename1, 'w')
+ filename2 = tempfile.mktemp()
+ try:
+ for x in numpy.arange(100.)/5. - 10.:
+ f.write('%s %s %s\n' % (x, math.cos(x), math.sin(x)))
+ f.close()
+
+ print('############### test Func ###################################')
+ wait('Plot a gnuplot-generated function')
+ g.plot(Gnuplot.Func('sin(x)'))
+
+ wait('Set title and axis labels and try replot()')
+ g.title('Title')
+ g.xlabel('x')
+ g.ylabel('y')
+ g.replot()
+
+ wait('Style linespoints')
+ g.plot(Gnuplot.Func('sin(x)', with_='linespoints'))
+ wait('title=None')
+ g.plot(Gnuplot.Func('sin(x)', title=None))
+ wait('title="Sine of x"')
+ g.plot(Gnuplot.Func('sin(x)', title='Sine of x'))
+ wait('axes=x2y2')
+ g.plot(Gnuplot.Func('sin(x)', axes='x2y2', title='Sine of x'))
+
+ print('Change Func attributes after construction:')
+ f = Gnuplot.Func('sin(x)')
+ wait('Original')
+ g.plot(f)
+ wait('Style linespoints')
+ f.set_option(with_='linespoints')
+ g.plot(f)
+ wait('title=None')
+ f.set_option(title=None)
+ g.plot(f)
+ wait('title="Sine of x"')
+ f.set_option(title='Sine of x')
+ g.plot(f)
+ wait('axes=x2y2')
+ f.set_option(axes='x2y2')
+ g.plot(f)
+
+ print('############### test File ###################################')
+ wait('Generate a File from a filename')
+ g.plot(Gnuplot.File(filename1))
+
+ wait('Style lines')
+ g.plot(Gnuplot.File(filename1, with_='lines'))
+
+ wait('using=1, using=(1,)')
+ g.plot(Gnuplot.File(filename1, using=1, with_='lines'),
+ Gnuplot.File(filename1, using=(1,), with_='points'))
+ wait('using=(1,2), using="1:3"')
+ g.plot(Gnuplot.File(filename1, using=(1,2)),
+ Gnuplot.File(filename1, using='1:3'))
+
+ wait('every=5, every=(5,)')
+ g.plot(Gnuplot.File(filename1, every=5, with_='lines'),
+ Gnuplot.File(filename1, every=(5,), with_='points'))
+ wait('every=(10,None,0), every="10::5"')
+ g.plot(Gnuplot.File(filename1, with_='lines'),
+ Gnuplot.File(filename1, every=(10,None,0)),
+ Gnuplot.File(filename1, every='10::5'))
+
+ wait('title=None')
+ g.plot(Gnuplot.File(filename1, title=None))
+ wait('title="title"')
+ g.plot(Gnuplot.File(filename1, title='title'))
+
+ print('Change File attributes after construction:')
+ f = Gnuplot.File(filename1)
+ wait('Original')
+ g.plot(f)
+ wait('Style linespoints')
+ f.set_option(with_='linespoints')
+ g.plot(f)
+ wait('using=(1,3)')
+ f.set_option(using=(1,3))
+ g.plot(f)
+ wait('title=None')
+ f.set_option(title=None)
+ g.plot(f)
+
+ print('############### test Data ###################################')
+ x = numpy.arange(100)/5. - 10.
+ y1 = numpy.cos(x)
+ y2 = numpy.sin(x)
+ d = numpy.transpose((x,y1,y2))
+
+ wait('Plot Data against its index')
+ g.plot(Gnuplot.Data(y2, inline=0))
+
+ wait('Plot Data, specified column-by-column')
+ g.plot(Gnuplot.Data(x,y2, inline=0))
+ wait('Same thing, saved to a file')
+ Gnuplot.Data(x,y2, inline=0, filename=filename1)
+ g.plot(Gnuplot.File(filename1))
+ wait('Same thing, inline data')
+ g.plot(Gnuplot.Data(x,y2, inline=1))
+
+ wait('Plot Data, specified by an array')
+ g.plot(Gnuplot.Data(d, inline=0))
+ wait('Same thing, saved to a file')
+ Gnuplot.Data(d, inline=0, filename=filename1)
+ g.plot(Gnuplot.File(filename1))
+ wait('Same thing, inline data')
+ g.plot(Gnuplot.Data(d, inline=1))
+ wait('with_="lp 4 4"')
+ g.plot(Gnuplot.Data(d, with_='lp 4 4'))
+ wait('cols=0')
+ g.plot(Gnuplot.Data(d, cols=0))
+ wait('cols=(0,1), cols=(0,2)')
+ g.plot(Gnuplot.Data(d, cols=(0,1), inline=0),
+ Gnuplot.Data(d, cols=(0,2), inline=0))
+ wait('Same thing, saved to files')
+ Gnuplot.Data(d, cols=(0,1), inline=0, filename=filename1)
+ Gnuplot.Data(d, cols=(0,2), inline=0, filename=filename2)
+ g.plot(Gnuplot.File(filename1), Gnuplot.File(filename2))
+ wait('Same thing, inline data')
+ g.plot(Gnuplot.Data(d, cols=(0,1), inline=1),
+ Gnuplot.Data(d, cols=(0,2), inline=1))
+ wait('Change title and replot()')
+ g.title('New title')
+ g.replot()
+ wait('title=None')
+ g.plot(Gnuplot.Data(d, title=None))
+ wait('title="Cosine of x"')
+ g.plot(Gnuplot.Data(d, title='Cosine of x'))
+
+ print('############### test compute_Data ###########################')
+ x = numpy.arange(100)/5. - 10.
+
+ wait('Plot Data, computed by Gnuplot.py')
+ g.plot(
+ Gnuplot.funcutils.compute_Data(x, lambda x: math.cos(x), inline=0)
+ )
+ wait('Same thing, saved to a file')
+ Gnuplot.funcutils.compute_Data(
+ x, lambda x: math.cos(x), inline=0, filename=filename1
+ )
+ g.plot(Gnuplot.File(filename1))
+ wait('Same thing, inline data')
+ g.plot(Gnuplot.funcutils.compute_Data(x, math.cos, inline=1))
+ wait('with_="lp 4 4"')
+ g.plot(Gnuplot.funcutils.compute_Data(x, math.cos, with_='lp 4 4'))
+
+ print('############### test hardcopy ###############################')
+ print('******** Generating postscript file "gp_test.ps" ********')
+ wait()
+ g.plot(Gnuplot.Func('cos(0.5*x*x)', with_='linespoints 2 2',
+ title='cos(0.5*x^2)'))
+ g.hardcopy('gp_test.ps')
+
+ wait('Testing hardcopy options: mode="eps"')
+ g.hardcopy('gp_test.ps', mode='eps')
+ wait('Testing hardcopy options: mode="landscape"')
+ g.hardcopy('gp_test.ps', mode='landscape')
+ wait('Testing hardcopy options: mode="portrait"')
+ g.hardcopy('gp_test.ps', mode='portrait')
+ wait('Testing hardcopy options: eps=1')
+ g.hardcopy('gp_test.ps', eps=1)
+ wait('Testing hardcopy options: mode="default"')
+ g.hardcopy('gp_test.ps', mode='default')
+ wait('Testing hardcopy options: enhanced=1')
+ g.hardcopy('gp_test.ps', enhanced=1)
+ wait('Testing hardcopy options: enhanced=0')
+ g.hardcopy('gp_test.ps', enhanced=0)
+ wait('Testing hardcopy options: color=1')
+ g.hardcopy('gp_test.ps', color=1)
+ # For some reason,
+ # g.hardcopy('gp_test.ps', color=0, solid=1)
+ # doesn't work here (it doesn't activate the solid option), even
+ # though the command sent to gnuplot looks correct. I'll
+ # tentatively conclude that it is a gnuplot bug. ###
+ wait('Testing hardcopy options: color=0')
+ g.hardcopy('gp_test.ps', color=0)
+ wait('Testing hardcopy options: solid=1')
+ g.hardcopy('gp_test.ps', solid=1)
+ wait('Testing hardcopy options: duplexing="duplex"')
+ g.hardcopy('gp_test.ps', solid=0, duplexing='duplex')
+ wait('Testing hardcopy options: duplexing="defaultplex"')
+ g.hardcopy('gp_test.ps', duplexing='defaultplex')
+ wait('Testing hardcopy options: fontname="Times-Italic"')
+ g.hardcopy('gp_test.ps', fontname='Times-Italic')
+ wait('Testing hardcopy options: fontsize=20')
+ g.hardcopy('gp_test.ps', fontsize=20)
+
+ print('******** Generating svg file "gp_test.svg" ********')
+ wait()
+ g.plot(Gnuplot.Func('cos(0.5*x*x)', with_='linespoints 2 2',
+ title='cos(0.5*x^2)'))
+ g.hardcopy('gp_test.svg', terminal='svg')
+
+ wait('Testing hardcopy svg options: enhanced')
+ g.hardcopy('gp_test.ps', terminal='svg', enhanced='1')
+
+ print('############### test shortcuts ##############################')
+ wait('plot Func and Data using shortcuts')
+ g.plot('sin(x)', d)
+
+ print('############### test splot ##################################')
+ wait('a 3-d curve')
+ g.splot(Gnuplot.Data(d, with_='linesp', inline=0))
+ wait('Same thing, saved to a file')
+ Gnuplot.Data(d, inline=0, filename=filename1)
+ g.splot(Gnuplot.File(filename1, with_='linesp'))
+ wait('Same thing, inline data')
+ g.splot(Gnuplot.Data(d, with_='linesp', inline=1))
+
+ print('############### test GridData and compute_GridData ##########')
+ # set up x and y values at which the function will be tabulated:
+ x = numpy.arange(35)/2.0
+ y = numpy.arange(30)/10.0 - 1.5
+ # Make a 2-d array containing a function of x and y. First create
+ # xm and ym which contain the x and y values in a matrix form that
+ # can be `broadcast' into a matrix of the appropriate shape:
+ xm = x[:,numpy.newaxis]
+ ym = y[numpy.newaxis,:]
+ m = (numpy.sin(xm) + 0.1*xm) - ym**2
+ wait('a function of two variables from a GridData file')
+ g('set parametric')
+ g('set style data lines')
+ g('set hidden')
+ g('set contour base')
+ g.xlabel('x')
+ g.ylabel('y')
+ g.splot(Gnuplot.GridData(m,x,y, binary=0, inline=0))
+ wait('Same thing, saved to a file')
+ Gnuplot.GridData(m,x,y, binary=0, inline=0, filename=filename1)
+ g.splot(Gnuplot.File(filename1, binary=0))
+ wait('Same thing, inline data')
+ g.splot(Gnuplot.GridData(m,x,y, binary=0, inline=1))
+
+ wait('The same thing using binary mode')
+ g.splot(Gnuplot.GridData(m,x,y, binary=1))
+ wait('Same thing, using binary mode and an intermediate file')
+ Gnuplot.GridData(m,x,y, binary=1, filename=filename1)
+ g.splot(Gnuplot.File(filename1, binary=1))
+
+ wait('The same thing using compute_GridData to tabulate function')
+ g.splot(Gnuplot.funcutils.compute_GridData(
+ x,y, lambda x,y: math.sin(x) + 0.1*x - y**2,
+ ))
+ wait('Same thing, with an intermediate file')
+ Gnuplot.funcutils.compute_GridData(
+ x,y, lambda x,y: math.sin(x) + 0.1*x - y**2,
+ filename=filename1)
+ g.splot(Gnuplot.File(filename1, binary=1))
+
+ wait('Use compute_GridData in ufunc and binary mode')
+ g.splot(Gnuplot.funcutils.compute_GridData(
+ x,y, lambda x,y: numpy.sin(x) + 0.1*x - y**2,
+ ufunc=1, binary=1,
+ ))
+ wait('Same thing, with an intermediate file')
+ Gnuplot.funcutils.compute_GridData(
+ x,y, lambda x,y: numpy.sin(x) + 0.1*x - y**2,
+ ufunc=1, binary=1,
+ filename=filename1)
+ g.splot(Gnuplot.File(filename1, binary=1))
+
+ wait('And now rotate it a bit')
+ for view in range(35,70,5):
+ g('set view 60, %d' % view)
+ g.replot()
+ time.sleep(1.0)
+
+ wait(prompt='Press return to end the test.\n')
+ finally:
+ os.unlink(filename1)
+ os.unlink(filename2)
+
+
+# when executed, just run main():
+if __name__ == '__main__':
+ main()
+
--- /dev/null
+#! /usr/bin/env python
+
+# Id: utils.py 297 2007-03-30 11:25:28Z mhagger
+
+# Copyright (C) 1998-2003 Michael Haggerty <mhagger@alum.mit.edu>
+#
+# This file is licensed under the GNU Lesser General Public License
+# (LGPL). See LICENSE.txt for details.
+
+"""utils.py -- Utility functions used by Gnuplot.
+
+This module contains utility functions used by Gnuplot.py which aren't
+particularly gnuplot-related.
+
+"""
+
+import string
+import numpy
+
+def float_array(m):
+ """Return the argument as a numpy array of type at least 'Float32'.
+
+ Leave 'Float64' unchanged, but upcast all other types to
+ 'Float32'. Allow also for the possibility that the argument is a
+ python native type that can be converted to a numpy array using
+ 'numpy.asarray()', but in that case don't worry about
+ downcasting to single-precision float.
+
+ """
+
+ try:
+ # Try Float32 (this will refuse to downcast)
+ return numpy.asarray(m, numpy.float32)
+ except TypeError:
+ # That failure might have been because the input array was
+ # of a wider data type than float32; try to convert to the
+ # largest floating-point type available:
+ # NOTE TBD: I'm not sure float_ is the best data-type for this...
+ try:
+ return numpy.asarray(m, numpy.float_)
+ except TypeError:
+ # TBD: Need better handling of this error!
+ print("Fatal: array dimensions not equal!")
+ return None
+
+def write_array(f, set,
+ item_sep=' ',
+ nest_prefix='', nest_suffix='\n', nest_sep=''):
+ """Write an array of arbitrary dimension to a file.
+
+ A general recursive array writer. The last four parameters allow
+ a great deal of freedom in choosing the output format of the
+ array. The defaults for those parameters give output that is
+ gnuplot-readable. But using '(",", "{", "}", ",\n")' would output
+ an array in a format that Mathematica could read. 'item_sep'
+ should not contain '%' (or if it does, it should be escaped to
+ '%%') since it is put into a format string.
+
+ The default 2-d file organization::
+
+ set[0,0] set[0,1] ...
+ set[1,0] set[1,1] ...
+
+ The 3-d format::
+
+ set[0,0,0] set[0,0,1] ...
+ set[0,1,0] set[0,1,1] ...
+
+ set[1,0,0] set[1,0,1] ...
+ set[1,1,0] set[1,1,1] ...
+
+ """
+
+ if len(set.shape) == 1:
+ (columns,) = set.shape
+ assert columns > 0
+ fmt = item_sep.join(["%s"] * columns)
+ f.write(nest_prefix)
+ f.write(fmt % tuple(set.tolist()))
+ f.write(nest_suffix)
+ elif len(set.shape) == 2:
+ # This case could be done with recursion, but `unroll' for
+ # efficiency.
+ (points, columns) = set.shape
+ assert points > 0 and columns > 0
+ fmt = item_sep.join(["%s"] * columns)
+ f.write(nest_prefix + nest_prefix)
+ f.write(fmt % tuple(set[0].tolist()))
+ f.write(nest_suffix)
+ for point in set[1:]:
+ f.write(nest_sep + nest_prefix)
+ f.write(fmt % tuple(point.tolist()))
+ f.write(nest_suffix)
+ f.write(nest_suffix)
+ else:
+ # Use recursion for three or more dimensions:
+ assert set.shape[0] > 0
+ f.write(nest_prefix)
+ write_array(f, set[0],
+ item_sep, nest_prefix, nest_suffix, nest_sep)
+ for subset in set[1:]:
+ f.write(nest_sep)
+ write_array(f, subset,
+ item_sep, nest_prefix, nest_suffix, nest_sep)
+ f.write(nest_suffix)
+
+