pygrace-0.4p2.orig/0000755000175000017500000000000011154024750014405 5ustar georgeskgeorgeskpygrace-0.4p2.orig/tests/0000755000175000017500000000000011225132264015546 5ustar georgeskgeorgeskpygrace-0.4p2.orig/tests/gracetest.py0000644000175000017500000003377511225132264020120 0ustar georgeskgeorgesk#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # gracetest.py # # 4/7/2005 version 0.0.1a # mmckerns@caltech.edu # (C) 2005 All Rights Reserved # # # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # from pygrace import grace from numpy import * import unittest import time class PyGrace_PyGrace_TestCase(unittest.TestCase): def setUp(self): '''grace: instantiate a grace session''' time.sleep(1) self.session = grace() self.int = 1 self.list = [1,2] self.array = array(self.list) self.dict = {} self.matrix = [[1,2,3],[4,5,6]] self.none = None self.str = 'foo' self.bytearray = array(self.str) self.strlist = ["hello", "world"] return #FIXME: do I want a new session for each test? def tearDown(self): '''grace: destroy a grace session''' self.session.exit() self.session = None return #FIXME: do I want a new session for each test? # def test_gracedependancy(self): # '''grace: check package dependancies''' # self.assert_(exec 'import numpy' == None,"failure to import numpy") # return def test_grace__getattr__(self): '''grace: call grace method if gracePlot method is implicit''' self.assert_(self.session.redraw() == None,"implicit method not found ") #self.assertRaises(AttributeError,self.session.foo,'x') return def test_grace_validate(self): '''grace: fail upon invalid name''' self.assert_(self.session._validate("foo") == None, "failure to validate a valid variable") self.assert_(self.session._validate("f_o1o") == None, "failure to validate a valid variable") self.assertRaises(NameError,self.session._validate,'1foo') self.assertRaises(NameError,self.session._validate,'$foo') self.assertRaises(NameError,self.session._validate,'f.oo') self.assertRaises(NameError,self.session._validate,'foo!') self.assertRaises(NameError,self.session._validate,'for') return def test_grace_putlocal(self): '''grace: add variable to local store''' Z = 666 self.assert_(self.session._putlocal("a",self.int) == None, "failure to add scalar to local store") self.assert_(self.session._putlocal("b",self.list) == None, "failure to add list to local store") self.assert_(self.session._putlocal("c",self.array) == None, "failure to add array to local store") self.assert_(self.session._putlocal("n",self.none) == None, "failure to add None to local store") self.assert_(self.session._putlocal("s",self.str) == None, "failure to add string to local store") self.assert_(self.session._putlocal("z",Z) == None, "failure to add to named local store") self.assertEqual(self.int, self.session.whos['a']) self.assertEqual(self.list, self.session.whos['b']) self.assertEqual(self.array.tolist(), self.session.whos['c'].tolist()) self.assertEqual(self.none, self.session.whos['n']) self.assertEqual(self.str, self.session.whos['s']) self.assertEqual(Z, self.session.whos['z']) self.assertRaises(NameError,self.session._putlocal,'foo!',69) return def test_grace_getlocal(self): '''grace: return variable value from local store''' Z = 666 self.session.whos['a'] = self.int self.session.whos['b'] = self.list self.session.whos['c'] = self.array self.session.whos['n'] = self.none self.session.whos['s'] = self.str self.session.whos['z'] = Z self.assertEqual(self.int, self.session._getlocal('a')) self.assertEqual(self.list, self.session._getlocal('b')) self.assertEqual(self.array.tolist(),\ self.session._getlocal('c').tolist()) self.assertEqual(self.none, self.session._getlocal('n')) self.assertEqual(self.str, self.session._getlocal('s')) self.assertEqual(Z, self.session._getlocal('z')) self.assertEqual(None, self.session._getlocal('x')) #KeyError not raised self.assertEqual(self.int, self.session._getlocal('a',skip=False)) self.assertRaises(NameError, self.session._getlocal,'x',skip=False) return def test_grace_poplocal(self): '''grace: delete variable from local store''' Z = 666 self.session.whos['a'] = self.int self.session.whos['b'] = self.list self.session.whos['c'] = self.array self.session.whos['n'] = self.none self.session.whos['s'] = self.str self.session.whos['z'] = Z self.assertEqual(self.int, self.session._poplocal('a')) self.assertEqual(self.list, self.session._poplocal('b')) self.assertEqual(self.array.tolist(),\ self.session._poplocal('c').tolist()) self.assertEqual(self.none, self.session._poplocal('n')) self.assertEqual(self.str, self.session._poplocal('s')) self.assertEqual(Z, self.session._poplocal('z')) self.assertEqual(None, self.session._poplocal('x')) #KeyError not raised self.assertEqual({},self.session.whos) return def test_grace_wholist(self): '''grace: check list of string names for all grace variables''' self.session.eval("a = 1") self.session.eval("b = [1,2]") self.session.eval("s = 'foo'") self.session.put("n",None) wholist = ['a', 's', 'b', 'n'] self.assertEqual(wholist, self.session._wholist()) return def test_grace_exists(self): '''grace: check if grace variable exists''' self.session.eval("a = 1") self.assertEqual(True, self.session._exists('a')) self.assertEqual(False, self.session._exists('b')) return def test_gracerestart(self): '''grace: restart a grace window''' self.session.eval('a = 1') whos = {'a': 1} self.assert_(self.session.restart() == None, "failure to restart grace window") self.assertEqual(whos, self.session.who()) self.assert_(self.session.redraw() == None, "failure to reinitialize grace session") return def test_graceput(self): '''grace: pass a variable into grace''' self.assert_(self.session.put("a",self.int) == None, "failure to pass an int to grace") self.assert_(self.session.put("b",self.list) == None, "failure to pass a list to grace") self.assert_(self.session.put("c",self.array) == None, "failure to pass an array to grace") self.assert_(self.session.put("s",self.str) == None, "failure to pass a string to IDL") whos = {'a': self.int, 'c': self.array, 'b': self.list, 's': self.str} self.assertEqual(whos, self.session.who()) self.assertEqual(self.int, self.session.get('a')) self.assertEqual(self.list, self.session.get('b')) self.assertEqual(self.array.tolist(), self.session.get('c').tolist()) self.assertEqual(self.str, self.session.get('s')) self.assertRaises(NameError,self.session.put,'x[0]',1) self.assertRaises(NameError,self.session.put,'a+a',2) self.assertRaises(TypeError,self.session.put,'a[1:3]',0) self.assertRaises(IndexError,self.session.put,'b[100]',0) self.assertRaises(SyntaxError,self.session.put,'b[]',0) self.assertEqual(whos, self.session.who()) return def test_graceget(self): '''grace: extract a variable from grace''' self.session.put("a",self.int) self.session.put("b",self.list) self.session.put("c",self.array) self.session.put("s",self.str) whos = {'a': self.int, 'c': self.array, 'b': self.list, 's': self.str} self.assert_(self.session.get('a') == whos['a'], "failure to extract an int from grace") self.assert_(self.session.get('b') == whos['b'], "failure to extract a list from grace") self.assert_(self.session.get('c') == whos['c'], "failure to extract an array from grace") self.assert_(self.session.get('s') == whos['s'], "failure to extract a string from grace") self.assertRaises(NameError,self.session.get,'x') self.assertRaises(NameError,self.session.get,'sin(x)') self.assertEqual(whos,self.session.who()) self.assertEqual(self.list[0],self.session.get('b[0]')) self.assertEqual(self.list[0]+self.int,self.session.get('b[0]+a')) self.assertRaises(SyntaxError,self.session.get,'x[]') return def test_gracewho(self): '''grace: inquire who are the grace variables''' self.session.put('a',self.int) self.session.put('b',self.list) self.session.put('c',self.array) self.session.put('s',self.str) whos = {'a':self.int, 'b':self.list, 's':self.str, 'c':self.array} self.assertEqual(self.int,self.session.who('a')) self.assertEqual(self.list,self.session.who('b')) self.assertEqual(self.array.tolist(),self.session.who('c').tolist()) self.assertEqual(self.str,self.session.who('s')) self.assertEqual(whos,self.session.who()) whos['n'] = self.none self.session.put('n',None) self.assertEqual(self.none,self.session.who('n')) self.assertEqual(whos,self.session.who()) self.assertRaises(NameError,self.session.who,'x') self.assertRaises(NameError,self.session.who,'a, b') #XXX: allow this? self.assertEqual(whos,self.session.who()) return def test_gracedelete(self): '''grace: delete grace variables''' self.session.put("a",1) self.session.put("b",2) self.session.put("c",3) self.assert_(self.session.delete("c") == None, "failure to delete a grace variable") whos = {'a': 1, 'b': 2} self.assertEqual(whos, self.session.who()) self.assert_(self.session.delete("a, b") == None, "failure to delete a grace variable tuple") whos = {} self.assertEqual(whos, self.session.who()) self.assert_(self.session.delete("z") == None, "failure to skip delete for unknown variable") whos = {} self.assertEqual(whos, self.session.who()) self.assert_(self.session.delete("[0,1]") == None, "failure to skip delete for bad syntax") whos = {} self.assertEqual(whos, self.session.who()) return # def test_graceeval(self): # '''grace: eval TESTS NOT IMPLEMENTED''' # pass def test_graceevalpython(self): '''grace: evaluate a python expression''' self.assert_(self.session.eval("a = 1") == None, "failure to eval an int") self.assert_(self.session.eval("b = [1,2]") == None, "failure to eval a list") self.assert_(self.session.eval("c = array([[1,2,3,4]])") == None, "failure to eval a 2D array") self.assert_(self.session.eval("import os") == None, "failure to eval a python builtin") whos = {'a': 1, 'c': array([[1, 2, 3, 4]]), 'b': [1, 2]} self.assertEqual(whos, self.session.who()) return def test_graceevalgrace(self): '''grace: evaluate a gracePlot expression''' self.assert_(self.session.eval("redraw()") == None, "failure to evaluate a gracePlot expression") self.assert_(self.session.eval("s0 line color 2") == None, "failure to evaluate a grace expression") return def test_graceevalexit(self): '''grace: do nothing upon 'exit' command''' self.session.eval('a = 1') whos = {'a': 1} self.assert_(self.session.eval("exit") == None, "failure to skip 'exit' command") self.assertEqual(whos, self.session.who()) return def test_graceevalbigexit(self): '''grace: exit a grace window upon 'exit()' command''' self.session.eval('a = 1') whos = {'a': 1} self.assert_(self.session.eval("exit()") == None, "failure to exit grace window") self.assertEqual(whos, self.session.who()) self.assertRaises(ValueError,self.session.plot,[1,2],[3,4]) return def test_graceevaldel(self): '''grace: delete a grace variable upon 'del' command''' self.session.eval("a = 1") self.session.eval("b = 2") self.session.eval("c = 3") self.assert_(self.session.eval("del b, c") == None, "failure to perform 'del' command") whos = {'a': 1} self.assertEqual(whos, self.session.who()) return def test_graceevalundefined(self): '''grace: let grace catch all command errors internally''' self.assert_(self.session.eval("foo()") == None, "failure of grace to catch command error internally") self.assert_(self.session.eval("s = t") == None, "failure of grace to catch command error internally") whos = {} self.assertEqual(whos, self.session.who()) # '''grace: fail when expression is undefined''' # self.assertRaises('CommandError',self.session.eval,"foo()") # self.assertRaises('CommandError',self.session.eval,"s = t") return #FIXME: is this the desired behavior? # def test_graceprompt(self): # '''grace: prompt TESTS NOT IMPLEMENTED''' # pass if __name__ == "__main__": suite0 = unittest.makeSuite(PyGrace_PyGrace_TestCase) alltests = unittest.TestSuite((suite0,)) unittest.TextTestRunner(verbosity=2).run(alltests) # version __id__ = "$Id: gracetest.py,v 1.5 2005/06/20 20:28:06 mmckerns Exp $" # End of file pygrace-0.4p2.orig/README.txt0000644000175000017500000000561211153301013016074 0ustar georgeskgeorgeskpygrace # Python bindings for grace, based on Nathan Gray's gracePlot # Requires grace and Numpy # Download pygrace source tarfile # Installation unzup and unpack the gzipped tar archive $ tar -xvzf pygrace-0.4.tgz install the package $ python setup.py build $ python setup.py install # Documentation import the grace class >>> from pygrace import grace instantiate the grace class >>> pg = grace() get help >>> pg.doc() Methods: prompt() --> start interactive session eval(command) --> execute a grace command put(name,val) --> put variable into interactive session get(name) --> get variable from interactive session who([name]) --> return the existing grace variables delete(name) --> destroy selected pylab variables restart() --> restart a grace window Notes: grace and Numpy must be installed, grace also relies on (open)motif Copyright (c) 2009 California Institute of Technology. All rights reserved. If you use this software to do productive scientific research that leads to publication, we ask that you acknowledge use of the software by citing the following paper in your publication: "pygrace: python bindings to the Grace plotting package", Michael McKerns, unpublished; http://www.its.caltech.edu/~mmckerns/software.html use grace methods directly from the python interpreter >>> from Numpy import * >>> x = [] >>> for i in range(21): x.append(i*pi/10) ... >>> pg.plot(x,sin(x)) push python variables into grace and interact with grace scripting language >>> pg.put('x',x) >>> pg.put('y',cos(x)) >>> pg.eval('s0 line color 2') >>> pg.eval('plot(x,y)') use the interactive grace prompt >>> pg.prompt() grace interface: vars= y x grace> histoPlot(y) grace> s0 fill color 3 grace> redraw() grace> exit check variables in grace session >>> pg.who().keys() ['y', 'x'] >>> pg.who('x') [0.0, 0.31415926535897931, 0.62831853071795862, 0.94247779607693793, 1.2566370614359172, 1.5707963267948966, 1.8849555921538759, 2.1991148575128552, 2.5132741228718345, 2.8274333882308138, 3.1415926535897931, 3.455751918948772, 3.7699111843077517, 4.0840704496667311, 4.3982297150257104, 4.7123889803846897, 5.026548245743669, 5.3407075111026483, 5.6548667764616276, 5.9690260418206069, 6.2831853071795862] get variables back into python from grace >>> cosx = pg.get('y') use shortcuts for put, eval, and get >>> pg.z = 0.5 >>> pg('print z') 0.5 >>> pg.z + 1 1.5 delete variables from grace >>> pg.delete('x') >>> pg.delete('y') # Versions 0.4: 03/02/09 migrated Numeric dependency to Numpy added license text installs with setuptools, if available more gentle install & dependency failure 0.3: 05/23/06 added examples directory shortcuts for put, get, & eval 0.2: 06/20/05 put() & get() now handle sequence elements, slices, etc. 0.1: 06/17/05 initial; python bindings for grace interactive grace prompt embed python into grace 'plot' for 2-D line plots 'histoPlot' for 2-D histograms pygrace-0.4p2.orig/grace_np.py0000644000175000017500000002740011153115103016530 0ustar georgeskgeorgesk#! /usr/bin/env python # $Id: grace_np.py,v 1.1 2004/09/18 22:37:38 mmckerns Exp $ """A python replacement for grace_np.c, a pipe-based interface to xmgrace. Copyright (C) 1999 Michael Haggerty Written by Michael Haggerty . Based on grace_np.c distributed with grace, which was written by Henrik Seidel and the Grace Development Team. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details; it is available at , or by writing to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Grace (xmgrace) is a very nice X program for doing 2-D graphics. It is very flexible, produces beautiful output, and has a graphical user interface. It is available from . Grace is the successor to ACE/gr and xmgr. This module implements a pipe-based interface to grace similar to the one provided by the grace_np library included with grace. I haven't used it very much so it is likely that it still has bugs. I am releasing it in the hope that it might be of use to the community. If you find a problem or have a suggestion, please let me know at . Other feedback is also welcome. For a demonstration, run this file by typing `python grace_np.py'. See the bottom of the file to see how the demonstration is programmed. About the module: At first I tried just to translate grace_np from C to python, but then I realized that it is possible to do a much nicer job using classes. The main class here is GraceProcess, which creates a running copy of the grace program, and creates a pipe connection to it. Through an instance of this class you can send commands to grace. Note that grace interprets command streams differently depending on their source. The pipe represented by this class is connected in such a way that grace expects `parameter-file'-style commands (without the @ or & or whatever). [Details: this class communicates to grace through a -dpipe which specified an open file descriptor from which it is to read commands. This is the same method used by the grace_np that comes with grace. I thought that the -pipe option might be more convenient--just pipe commands to standard input. However, grace interprets commands differently when it receives them from these two sources: -dpipe expects parameter-file information, whereas -pipe expects datafile information. Also -pipe doesn't seem to respond to the `close' command (but maybe the same effect could be had by just closing the pipe).] """ __version__ = '1.0' __cvs_version__ = 'CVS version $Revision: 1.1 $' import sys, os, signal, errno # global variables: OPEN_MAX = 64 # copied from C header file sys/syslimits.h ### class Error(Exception): """All exceptions thrown by this class are descended from Error.""" pass class Disconnected(Error): """Thrown when xmgrace unexpectedly disconnects from the pipe. This exception is thrown on an EPIPE error, which indicates that xmgrace has stopped reading the pipe that is used to communicate with it. This could be because it has been closed (e.g., by clicking on the exit button), crashed, or sent an exit command.""" pass # Three possible states for a GraceProcess, shown with their desired # indicators: # # 1. Healthy (pipe and pid both set) # 2. Disconnected but alive (pipe.closed is set, pid still set) # 3. Disconnected and dead (pipe.closed is set and pid is None) # # The error handling is such as to try to keep the above indicators # set correctly. class GraceProcess: """Represents a running xmgrace program.""" def __init__(self, bufsize=-1, debug=0, fixedsize=None, ask=None): """Start xmgrace, reading from a pipe that we control. Parameters: bufsize -- choose the size of the buffer used in the communication. grace won't act on commands that haven't been flushed from the buffer, but speed should supposedly be better with some buffering. The default is -1, which means use the default (full) buffering. 0 would mean use no buffering. debug -- when set, each command that is passed to xmgrace is also echoed to stderr. fixedsize -- if set to None, the grace window is freely resizable (`-free'). Otherwise set to a tuple, which will set the fixed size of the grace canvas. (I don't know what units are used.###) ask -- if set, xmgrace will ask before doing `dangerous' things, like overwriting a file or even clearing the display. Default is not to ask. """ self.debug = debug self.fixedsize = fixedsize self.ask = ask cmd = ('xmgrace',) if self.fixedsize is None: cmd = cmd + ('-free',) else: cmd = cmd + ('-fixed', `self.fixedsize[0]`, `self.fixedsize[1]`) if self.ask is None: cmd = cmd + ('-noask',) # Python, by default, ignores SIGPIPE signals anyway #signal.signal(signal.SIGPIPE, signal.SIG_IGN) # Don't exit when our child "grace" exits (which it could if # the user clicks on `exit'): signal.signal(signal.SIGCHLD, signal.SIG_IGN) # Make the pipe that will be used for communication: (fd_r, fd_w) = os.pipe() cmd = cmd + ('-dpipe', `fd_r`) # Fork the subprocess that will start grace: self.pid = os.fork() # If we are the child, replace ourselves with grace if self.pid == 0: try: # This whole thing is within a try block to make sure # the child can't escape. for i in range(OPEN_MAX): # close everything except stdin, stdout, stderr # and the read part of the pipe if i not in (fd_r,0,1,2): try: os.close(i) except OSError: pass try: os.execvp('xmgrace', cmd) except: # we have to be careful in the child process. We # don't want to throw an exception because that would # allow two threads to continue running. sys.stderr.write('GraceProcess: Could not start xmgrace\n') os._exit(1) # exit this forked process but not the parent except: sys.stderr.write('Unexpected exception in child!\n') os._exit(2) # exit child but not parent # We are the parent -> keep only the writeable side of the pipe os.close(fd_r) # turn the writeable side into a buffered file object: self.pipe = os.fdopen(fd_w, 'w', bufsize) def command(self, cmd): """Issue a command to grace followed by a newline. Unless the constructor was called with bufsize=0, this interface is buffered, and command execution may be delayed. To flush the buffer, either call self.flush() or send the command via self(cmd).""" if self.debug: sys.stderr.write('Grace command: "%s"\n' % cmd) try: self.pipe.write(cmd + '\n') except IOError, err: if err.errno == errno.EPIPE: self.pipe.close() raise Disconnected() else: raise def flush(self): """Flush any pending commands to grace.""" try: self.pipe.flush() except IOError, err: if err.errno == errno.EPIPE: # grace is no longer reading from the pipe: self.pipe.close() raise Disconnected() else: raise def __call__(self, cmd): """Send the command to grace, then flush the write queue.""" self.command(cmd) self.flush() # was `GraceClosePipe': def __del__(self): """Disconnect from xmgrace process but leave it running. If a GraceProcess is destroyed without calling exit(), it disconnects from the xmgrace program but does not kill it, under the assumption that the user may want to continue manipulating the graph through the X interface. If you want to force xmgrace to terminate, call self.exit().""" if self.is_open(): try: # Ask grace to close its end of the pipe (this also # flushes pending commands): self('close') except Disconnected: # Looks like grace has already disconnected. pass else: # Close our end of the pipe (actually, it should be closed # automatically when it's deleted, but...): self.pipe.close() def is_open(self): """Return 1 iff the pipe is not known to have been closed.""" # we could potentially send a kind of null-command to grace # here to see if it is really still alive... return not self.pipe.closed def exit(self): """Cause xmgrace to exit. Ask xmgrace to exit (i.e., for the program to shut down). If it isn't listening, try to kill the process with a SIGTERM.""" # First try--ask politely for xmgrace to exit: if not self.pipe.closed: try: self('exit') # this also flushes the queue except Disconnected: # self.pipe will have been closed by whomever # generated the exception. pass # drop through kill code below else: os.waitpid(self.pid, 0) self.pipe.close() self.pid = None return # Second try--kill it via a SIGTERM if self.pid is not None: try: os.kill(self.pid, signal.SIGTERM) except OSError, err: if err.errno == errno.ESRCH: # No such process; it must already be dead self.pid = None return else: raise os.waitpid(self.pid, 0) self.pid = None if __name__ == '__main__': # Test import time g = GraceProcess() # Send some initialization commands to Grace: g('world xmax 100') g('world ymax 10000') g('xaxis tick major 20') g('xaxis tick minor 10') g('yaxis tick major 2000') g('yaxis tick minor 1000') g('s0 on') g('s0 symbol 1') g('s0 symbol size 0.3') g('s0 symbol fill pattern 1') g('s1 on') g('s1 symbol 1') g('s1 symbol size 0.3') g('s1 symbol fill pattern 1') # Display sample data for i in range(1,101): g('g0.s0 point %d, %d' % (i, i)) g('g0.s1 point %d, %d' % (i, i * i)) # Update the Grace display after every ten steps if i % 10 == 0: g('redraw') # Wait a second, just to simulate some time needed for # calculations. Your real application shouldn't wait. time.sleep(1) # Tell Grace to save the data: g('saveall "sample.agr"') # Close Grace: g.exit() pygrace-0.4p2.orig/__init__.py0000644000175000017500000000071511153272645016530 0ustar georgeskgeorgesk#!/usr/bin/env python # # Michael McKerns # mmckerns@caltech.edu from pygrace import __doc__ as gracedoc __doc__ = gracedoc def grace(): '''get usage: gr = grace(); gr.doc()''' from pygrace import grace as graceFactory return graceFactory() def copyright(): from pygrace import __license__ return __license__ #return "pygrace module: Copyright (c) 2005-2009 Michael McKerns" #built with: Grace-5.1.14, grace_np-2.7, gracePlot-0.5.1 pygrace-0.4p2.orig/setup.py0000644000175000017500000000257011153542657016135 0ustar georgeskgeorgesk#!/usr/bin/env python # # Michael McKerns # mmckerns@caltech.edu try: # see if easy_install is available from setuptools import setup has_setuptools = True except ImportError: from distutils.core import setup has_setuptools = False # build the 'setup' call setup_code = """ setup(name='pygrace', version='0.4', description='Python bindings for grace', author = 'Mike McKerns', author_email = 'mmckerns@caltech.edu', url = 'http://www.its.caltech.edu/~mmckerns/software/', packages=['pygrace'], package_dir={'pygrace':''}, """ # add dependencies grace_version = '>=5.1.14' numpy_version = '>=1.0' if has_setuptools: setup_code += """ install_requires=("numpy%s"), """ % numpy_version # close 'setup' call, and exec the code setup_code += """ ) """ exec setup_code # if dependencies are missing, print a warning try: import numpy from os import system xmgrace_missing = system("xmgrace -v") #grep "Grace-" | sed -e "s/Grace-//" if xmgrace_missing: raise ImportError except ImportError: print "\n***********************************************************" print "WARNING: One of the following dependencies is unresolved:" print " Numpy %s" % numpy_version print " Grace %s" % grace_version print "***********************************************************\n" # end of file pygrace-0.4p2.orig/pygrace.py0000644000175000017500000003120311153274015016410 0ustar georgeskgeorgesk#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # 3/2/2009 version 0.4 # mmckerns@caltech.edu # (C) 2005-2009 All Rights Reserved # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # __license__ = """ This software is part of the open-source DANSE project at the California Institute of Technology, and is available subject to the conditions and terms laid out below. By downloading and using this software you are agreeing to the following conditions. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistribution of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistribution in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentations and/or other materials provided with the distribution. * Neither the name of the California Institute of Technology nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (c) 2009 California Institute of Technology. All rights reserved. If you use this software to do productive scientific research that leads to publication, we ask that you acknowledge use of the software by citing the following paper in your publication: "pygrace: python bindings to the Grace plotting package", Michael McKerns, unpublished; http://www.its.caltech.edu/~mmckerns/software.html """ __author__='Mike McKerns' __doc__ = '''Instructions for pygrace: Import the grace class >>> from pygrace import grace Instantiate the grace class >>> pg = grace() Get help >>> pg.doc() ''' from numpy import * try: from numarray import array as numarr hasnumarray = True except ImportError: hasnumarray = False try: from Numeric import array as oldarr hasnumeric = True except ImportError: hasnumeric = False class grace: #Nathan Gray's gracePlot with interactive prompt added '''Python-grace bindings Methods: prompt() --> start interactive session eval(command) --> execute a grace command put(name,val) --> put variable into interactive session get(name) --> get variable from interactive session who([name]) --> return the existing grace variables delete(name) --> destroy selected grace variables restart() --> restart a grace window Notes: grace and numpy must be installed, grace also relies on (open)motif ''' _privdoc='''Private methods: _validate(name) --> raise NameError if is invalid python name _putlocal(name,value) --> add a variable to local store _getlocal(name) --> return variable value from local store _poplocal(name) --> delete variable from local store, return value _wholist() --> get list of strings containing grace variables _exists(name) --> True if is a variable in grace ''' def __init__(self): from gracePlot import gracePlot as grace_plot self.session = grace_plot() self.whos = {} self.reserved = ['and','assert','break','class','continue','def','del', 'elif','else','except','exec','finally','for','from', 'global','if','import','in','is','lambda','not','or', 'pass','print','raise','return','try','while','yield', 'as','None'] return def __getattr__(self,name): try: exec 'attr = self.session.'+name except: exec 'attr = self.get("'+name+'")' return attr def __setattr__(self,name,value): if name in ['session','whos','reserved']: self.__dict__[name] = value return self.put(name,value) return def __call__(self,*args): for arg in args: self.eval(arg) return def _validate(self,name): '''_validate(name) --> raise NameError if is invalid python name''' #a valid python name begins with a letter or underscore, #and can include only alphanumeric symbols and the underscore. #python also does not allow redefinition of reserved words. if not name: raise NameError, "invalid name" import re if re.compile('[_a-zA-Z]').sub('',name[0]): raise NameError, "invalid first character '%s'" % name[0] badc = re.compile('[_a-zA-Z0-9]').sub('',name) if badc: raise NameError, "invalid name '%s'; remove '%s'" % (name,badc) if name.lower() in self.reserved: raise NameError, "invalid name '%s'; is a reserved word" % name return def _putlocal(self,name,value): '''_putlocal(name,value) --> add a variable to local store''' self._validate(name) self.whos[name] = value return def _getlocal(self,name,skip=True): '''_getlocal(name) --> return variable value from local store''' if self.whos.has_key(name): return self.whos[name] if skip: return #name not found in local store raise NameError,"'%s' is not defined locally" % str(name) def _poplocal(self,name): '''_poplocal(name) --> delete variable from local store, return value''' return self.whos.pop(name,None) def _wholist(self): '''_wholist() --> get list of strings containing grace variables''' return self.whos.keys() def _exists(self,name): '''_exists(name) --> True if is a variable in grace''' exists = self._wholist().count(name) if exists: return True return False def doc(self): print self.__doc__ print __license__[-416:] # print copyright and reference return def restart(self): '''restart() --> restart a grace window''' vars = self.who() self.exit() self.session = None self.__init__() self.session.whos = vars return def put(self,name,val): '''put(name,val) --> add variable to grace session''' if name.count('[') or name.count('.') or name.count('('): varlist = self._wholist() for var in varlist: #put whos into locals() exec var+" = self._getlocal('"+var+"')" if (type(val) is type(array([]))) or \ (hasnumarray and (type(val) is type(numarr([])))) or \ (hasnumeric and (type(val) is type(oldarr([])))): val = val.tolist() exec name+' = array('+str(val)+')' else: exec name+' = '+str(val) #put new var value into locals() for var in varlist: #use varlist to update state variables exec 'self._putlocal("'+var+'",locals()["'+var+'"])' return return self._putlocal(name,val) def get(self,name): '''get(name) --> value; get value from grace session''' #if name.count('+') or ... #if name.count('[') or name.count('.') or name.count('('): varlist = self._wholist() for var in varlist: #put whos into locals() exec var+" = self._getlocal('"+var+"')" exec '___ = '+name #get from locals() as temp variable return ___ #return self._getlocal(name) def who(self,name=None): '''who([name]) --> return the existing grace variables''' if name: return self._getlocal(name,skip=False) return self.whos def delete(self,name): '''delete(name) --> destroy selected grace variables''' if not name.count(','): self._poplocal(name) return vars = name.split(',') for var in vars: self.delete(var.strip()) return def eval(self,com): '''eval(command) --> execute a grace command''' outlist = [] if self.whos: #add to outlist for name,val in self.whos.items(): # if numerix: if (type(val) is type(array([]))) or \ (hasnumarray and (type(val) is type(numarr([])))) or \ (hasnumeric and (type(val) is type(oldarr([])))): val = val.tolist() exec name+' = array('+str(val)+')' else: exec name+' = '+str(val) exec 'outlist.append("'+name+'")' if com == 'exit': return try: #if intended for python exec com if com.startswith('del '): names = com.split('del ')[1].strip() self.delete(names) return if com.count('='): name = com.split('=')[0].strip() if not name.count('['): outlist.append(name) except: try: #if intended for gracePlot exec 'self.session.'+com except: try: #if intended for grace self.session._send(com) except: #is unknown command raise "CommandError", com for name in outlist: #use outlist to update state variables if name in locals().keys(): exec 'self._putlocal("'+name+'",locals()["'+name+'"])' return def prompt(self): '''an interactive grace session''' outlist = [] print "grace interface:" if self.whos: #print 'put' variables, add to outlist print "vars=" for name,val in self.whos.items(): # if numerix: if (type(val) is type(array([]))) or \ (hasnumarray and (type(val) is type(numarr([])))) or \ (hasnumeric and (type(val) is type(oldarr([])))): val = val.tolist() exec name+' = array('+str(val)+')' else: exec name+' = '+str(val) exec 'print " ","'+name+'"' exec 'outlist.append("'+name+'")' while 1: com = raw_input('grace> ') ## print com if com == 'exit': break elif com == 'exit()': self.session.exit() break else: try: #if intended for python exec com if com.startswith('del '): names = com.split('del ')[1].strip() vars = names.split(',') for var in vars: self.delete(var.strip()) outlist.remove(var.strip()) if com.count('='): name = com.split('=')[0].strip() if not name.count('['): outlist.append(name) except: try: #if intended for gracePlot exec 'self.session.'+com except: try: #if intended for grace self.session._send(com) except: #is unknown command print "CommandError: %s" % com for name in outlist: #use outlist to update state variables if name in locals().keys(): exec 'self._putlocal("'+name+'",locals()["'+name+'"])' return # elif com.startswith('python('): # pcom = com[7:-1] # try: # exec pcom # except: # print "PythonError: %s" % pcom # elif com.startswith('*'): # pcom = com[1:] # try: # exec 'self.session.'+pcom # except: # print "GraceError: %s" % pcom # else: # self.session._send(com) if __name__ == "__main__": x = range(1,15) y = [] for i in x: y.append(i*i) g = grace() g.plot(x,y) g.put('x',x) g.put('y',y) g.prompt() print g.who() g.exit() pygrace-0.4p2.orig/examples/0000755000175000017500000000000011225132256016223 5ustar georgeskgeorgeskpygrace-0.4p2.orig/examples/grace_prompt.py0000644000175000017500000000125311225132255021257 0ustar georgeskgeorgesk#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # 2/11/2005 version 0.0.1a # mmckerns@caltech.edu # (C) 2005 All Rights Reserved # # # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # __author__ = 'Mike McKerns' x = [1,2,3,4,5] y = [1,4,9,16,25] print 'x: %s' % x print 'y: %s' % y raw_input('Please press return to continue...\n') ##### grace ##### from pygrace import grace pg = grace() #pg.doc() pg.plot(x,y) print '''EXAMPLE SCRIPT: grace> z = [2,8,18,32,50] grace> histoPlot(z) grace> s0 fill color 3 grace> redraw() grace> exit ''' pg.prompt() pygrace-0.4p2.orig/examples/grace.py0000644000175000017500000000356011225132251017655 0ustar georgeskgeorgeskprint "build python list" print '''>>> from numpy import * >>> from numpy import newaxis as NewAxis >>> x = pi*arange(21)/10. >>> y = cos(x)''' from numpy import * from numpy import newaxis as NewAxis x = pi*arange(21)/10. y = cos(x) print '''build a numpy matrix''' print '''>>> xm = x[:,NewAxis] >>> ym = y[NewAxis,:] >>> m = (sin(xm) + 0.1*xm) - ym**2''' xm = x[:,NewAxis] ym = y[NewAxis,:] m = (sin(xm) + 0.1*xm) - ym**2 print '''instantiate the grace class''' print '''>>> from pygrace import grace >>> gr = grace()''' from pygrace import grace gr = grace() #get help #>>> gr.doc() #create a colormap directly from python #GRACE (5.1.18) CANNOT CREATE COLORMAP #create a surface plot from within grace #GRACE (5.1.18) CANNOT CREATE SURFACE PLOT print '''delete a variable within grace''' print '''>>> gr.m = m >>> gr.delete('m')''' gr.m = m gr.delete('m') print '''create a lineplot directly from python''' print '''>>> gr.plot(x,sin(x))''' gr.plot(x,sin(x)) raw_input("Press 'Return' to continue...") print '''create a formatted lineplot from within grace''' print '''>>> gr.x = x >>> gr.y = cos(x) >>> gr('plot(x,y)') >>> gr('s0 line color "green"') >>> gr('s0 symbol 1') >>> gr('s0 symbol fill pattern 1') >>> gr('redraw()')''' gr.x = x gr.y = cos(x) gr('plot(x,y)') gr('s0 line color "green"') gr('s0 symbol 1') gr('s0 symbol fill pattern 1') gr('redraw()') raw_input("Press 'Return' to continue...") print '''create a histogram using the grace session interface''' print '''# TYPE THE FOLLOWING IN THE PROMPT: # grace> title "foobar" # grace> histoPlot(y) # grace> exit''' print '''>>> gr.prompt()''' gr.prompt() print '''inspect variables within grace''' print '''>>> gr.who().keys()''' print gr.who().keys() print '''>>> gr.who('x')''' print gr.who('x') print '''get variables from grace into python''' print '''>>> gr.y''' print gr.y print '''>>> gr.y[0]''' print gr.y[0] pygrace-0.4p2.orig/gracePlot.py0000644000175000017500000005035611153115061016703 0ustar georgeskgeorgesk""" gracePlot.py -- A high-level Python interface to the Grace plotting package The intended purpose of gracePlot is to allow easy programmatic and interactive command line plotting with convenience functions for the most common commands. The Grace UI (or the grace_np module) can be used if more advanced functionality needs to be accessed. The data model in Grace, (mirrored in gracePlot) goes like this: Each grace session is like virtual sheet of paper called a Plot. Each Plot can have multiple Graphs, which are sets of axes (use gracePlot.multi() to get multiple axes in gracePlot). Each Graph has multiple data Sets. Data Sets are added to graphs with the plot and histoPlot functions in gracePlot. The main python functions are plot() and histoPlot(). See their docstrings for usage information. They can be called with any mix of Numpy arrays, lists, tuples, or other sequences. In general, data is considered to be stored in columns, so a matrix with three vectors x1, x2 and x3 would be: [ [ x1[0], x2[0], x3[0] ], [ x1[1], x2[1], x3[1] ], [ x1[2], x2[2], x3[2] ], [ x1[3], x2[3], x3[3] ] ] Here's a simple example of a gracePlot session: >>> import gracePlot >>> p = gracePlot.gracePlot() # A grace session begins >>> # Sequence arguments to plot() are X, Y, dy >>> p.plot( [1,2,3,4,5], [10, 4, 2, 4, 10], [0.1, 0.4, 0.2, 0.4, 0.1], ... symbols=1 ) # A plot with errorbars If you're doing a lot of histograms then you should get Konrad Hinsen's Scientific Python package: http://starship.python.net/crew/hinsen/scientific.html histoPlot() knows how to automatically plot Histogram instances from the Scientific.Statistics.Histogram module, so histogramming ends up being pretty simple: >>> from Scientific.Statistics.Histogram import Histogram >>> joe = Histogram( some_data, 40 ) # 40 = number of bins >>> p.histoPlot( joe ) # A histogram plot with correct axis limits An important thing to realize about gracePlot is that it only has a one-way communications channel with the Grace session. This means that if you make changes to your plot interactively (such as changing the number/layout of graphs) then gracePlot will have NO KNOWLEDGE of the changes. This should not often be an issue, since the only state that gracePlot saves is the number and layout of graphs, the number of Sets that each graph has, and the hold state for each graph. """ # --UPDATES-- # 03/02/09: ported to Numpy by Mike McKerns (mmckerns@caltech.edu) __version__ = "0.5.2" __author__ = "Nathaniel Gray " __date__ = "September 16, 2001" import grace_np import numpy, string N = numpy del numpy try: from Scientific.Statistics.Histogram import Histogram haveHisto = 1 except ImportError: haveHisto = 0 class gracePlot: def __init__(self): self.grace = grace_np.GraceProcess() self.g = [ graceGraph(self.grace, 0) ] self.curr_graph = self.g[0] self.rows = 1 self.cols = 1 self.focus(0,0) def _send(self, cmd): #print cmd self.grace.command(cmd) def _flush(self): #print 'flush()' self.grace.flush() def __del__(self): """Destroy the pipe but leave the grace window open for interaction. This is the best action for the destructor so that unexpected crashes don't needlessly destroy plots.""" self.grace = None def exit(self): """Nuke the grace session. (more final than gracePlot.__del__())""" self.grace.exit() def redraw(self): """Refresh the plot""" #print 'redraw' self.grace('redraw') def multi(self, rows, cols, offset=0.1, hgap=0.1, vgap=0.15): """Create a grid of graphs with the given number of and """ self._send( 'ARRANGE( %s, %s, %s, %s, %s )' % ( rows, cols, offset, hgap, vgap ) ) self.rows = rows self.cols = cols if rows*cols > len(self.g): nPlots = len(self.g) for i in range( nPlots, (rows*cols - nPlots)+1 ): self.g.append( graceGraph(self.grace, i) ) # Should we trim the last graphs if we now have *fewer* than before? # I say yes. elif rows*cols < len(self.g): del self.g[rows*cols:] self._flush() self.redraw() def save(self, filename, format='agr'): """Save the current plot Default format is Grace '.agr' file, but other possible formats are: x11, postscript, eps, pdf, mif, svg, pnm, jpeg, png, metafile Note: Not all drivers are created equal. See the Grace documentation for caveats that apply to some of these formats.""" devs = {'agr':'.agr', 'eps':'.eps', 'jpeg':'.jpeg', 'metafile':'', 'mif':'', 'pdf':'.pdf', 'png':'.png', 'pnm':'', 'postscript':'.ps', 'svg':'', 'x11':''} try: ext = devs[string.lower(format)] except KeyError: print 'Unknown format. Known formats are\n%s' % devs.keys() return if filename[-len(ext):] != ext: filename = filename + ext if ext == '.agr': self._send('saveall "%s"' % filename) else: self._send('hardcopy device "%s"' % string.lower(format) ) self._send('print to "%s"' % filename) self._send('print') self._flush() def focus( self, row, col ): """Set the currently active graph""" self.curr_graph = self.g[row*self.cols + col] self._send('focus g%s' % self.curr_graph.gID) self._send('with g%s' % self.curr_graph.gID) self._flush() self.redraw() for i in ['plot', 'histoPlot', 'title', 'subtitle', 'xlabel', 'ylabel', 'kill', 'clear', 'legend', 'hold', 'xlimit', 'ylimit', 'redraw']: setattr( self, i, getattr(self.curr_graph, i) ) return self.curr_graph def resize( self, xdim, ydim, rescale=1 ): """Change the page dimensions (in pp). If rescale==1, then also rescale the current plot accordingly. Don't ask me what a pp is--I don't know.""" if rescale: self._send('page resize %s %s' % (xdim, ydim)) else: self._send('page size %s %s' % (xdim, ydim)) def __getitem__( self, item ): """Access a specific graph. Can use either p[num] or p[row, col].""" if type(item) == type(1): return self.g[item] elif type(item) == type( () ) and len(item) <= 2: if item[0] >= self.rows or item[1] >= self.cols: raise IndexError, 'graph index out of range' return self.g[item[0]*self.cols + item[1]] else: raise TypeError, 'graph index must be integer or two integers' class graceGraph: def __init__(self, grace, gID): self._hold = 0 # Set _hold=1 to add datasets to a graph self.grace = grace self.nSets = 0 self.gID = gID def _send(self, cmd): #print cmd #raise NameError, "duh" self.grace.command(cmd) def _flush(self): #print 'flush()' self.grace.flush() def _send_2(self, var, X, Y): send = self.grace.command for i in xrange(len(X)): send( 'g%s.s%s point %s, %s' % (self.gID, var, X[i], Y[i]) ) if i%50 == 0: self._flush() self._flush() def _send_3(self, var, X, Y, Z): self._send_2(var, X, Y) send = self.grace.command for i in range(len(Z)): send( 'g%s.s%s.y1[%s] = %s' % (self.gID, var, i, Z[i]) ) if i%50 == 0: self._flush() self._flush() def hold(self, onoff=None): """Turn on/off overplotting for this graph. Call as hold() to toggle, hold(1) to turn on, or hold(0) to turn off. Returns the previous hold setting. """ lastVal = self._hold if onoff is None: self._hold = not self._hold return lastVal if onoff not in [0, 1]: raise RuntimeError, "Valid arguments to hold() are 0 or 1." self._hold = onoff return lastVal def title(self, titlestr): """Change the title of the plot""" self._send('with g%s' % self.gID) self._send('title "' + str(titlestr) + '"') self.redraw() def subtitle(self, titlestr): """Change the subtitle of the plot""" self._send('with g%s' % self.gID) self._send('subtitle "' + str(titlestr) + '"') self.redraw() def redraw(self): """Refresh the plot""" self.grace('redraw') def xlabel(self, label): """Change the x-axis label""" self._send('with g%s' % self.gID) self._send('xaxis label "' + str(label) + '"') self.redraw() def ylabel(self, label): """Change the y-axis label""" self._send('with g%s' % self.gID) self._send('yaxis label "' + str(label) + '"') self.redraw() def xlimit(self, lower=None, upper=None): """Set the lower and/or upper bounds of the x-axis.""" self._limHelper( 'x', lower, upper) def ylimit(self, lower=None, upper=None): """Set the lower and/or upper bounds of the y-axis.""" self._limHelper( 'y', lower, upper) def _limHelper(self, ax, lower, upper): send = self._send if lower is not None: send('with g%s; world %smin %s' % (self.gID, ax, lower)) if upper is not None: send('with g%s; world %smax %s' % (self.gID, ax, upper)) self.redraw() def kill(self): """Kill the plot""" self._send('kill g%s' % self.gID) self._send('g%s on' % self.gID) self.redraw() self.nSets = 0 self._hold = 0 def clear(self): """Erase all lines from the plot and set hold to 0""" for i in range(self.nSets): self._send('kill g%s.s%s' % (self.gID, i)) self.redraw() self.nSets=0 self._hold=0 def legend(self, labels): """Set the legend labels for the plot Takes a list of strings, one string per dataset on the graph. Note: -L allows you to reposition legends in Grace using the mouse. """ if len(labels) != self.nSets: raise RuntimeError, 'Wrong number of legends (%s) for number' \ ' of lines in plot (%s).' % (len(labels), self.nSets) for i in range(len(labels)): self._send( ('g%s.s%s legend "' % (self.gID, i)) + labels[i] + '"' ) self._send('with g%s; legend on' % self.gID) self.redraw() def histoPlot(self, y, x_min=0, x_max=None, dy=None, edges=0, fillcolor=2, edgecolor=1, labeled=0): """Plot a histogram y contains a vector of bin counts By default bin counts are plotted against bin numbers unless x_min and/or x_max are specified if edges == 0: # This is the default x_min and x_max specify the lower and upper edges of the first and last bins, respectively else: x_min and x_max specify the centers of the first and last bins If dy is specified symmetric errorbars are plotted. fillcolor and edgecolor are color numbers (0-15) If labeled is set to 1 then labels are placed at each bin to show the bin count Note that this function can create *two* datasets in grace if you specify error bars.""" if haveHisto and isinstance(y, Histogram): self.histoPlot( y.array[:,1], x_min=y.min, x_max=y.max, edges=1, dy=dy, fillcolor=fillcolor, edgecolor=edgecolor, labeled=labeled ) return # this is going to be ugly y = N.array(y) if x_max is None: x_max = len(y)-1 + x_min edges = 0 if x_max <= x_min: raise RuntimeError, "x_max must be > x_min" if dy is not None: if len(dy) != len(y): raise RuntimeError, 'len(dy) != len(y)' dy = N.array(dy) if not self._hold: self.clear() if edges: # x_min and x_max are the outside edges of the first/last bins binwidth = (x_max-x_min)/float(len(y)) edge_x = N.arange(len(y)+1 , dtype='d')*binwidth + x_min cent_x = (edge_x + 0.5*binwidth)[0:-1] else: # x_min and x_max are the centers of the first/last bins binwidth = (x_max-x_min)/float(len(y)-1) cent_x = N.arange(len(y), dtype='d')*binwidth + x_min edge_x = cent_x - 0.5*binwidth edge_x = N.resize(edge_x, (len(cent_x)+1,)) edge_x[-1] = edge_x[-2] + binwidth edge_y = y.copy() #N.zeros(len(y)+1) edge_y = N.resize(edge_y, (len(y)+1,)) edge_y[-1] = 0 # Draw the edges: me = 'g%s.s%s ' % (self.gID, self.nSets) self._send( me + 'type xy' ) self._send( me + 'dropline on' ) self._send( me + 'line type 3' ) # step to right self._send( me + 'line color ' + str(edgecolor) ) if fillcolor is not None: self._send( me + 'fill type 2' ) #Solid self._send( me + 'fill color ' + str(fillcolor) ) if labeled: self._send( me + 'avalue on' ) self._flush() self._send_2( self.nSets, edge_x, edge_y ) self.nSets = self.nSets + 1 # Draw the errorbars (if given) if dy is not None: me = 'g%s.s%s ' % (self.gID, self.nSets) self._send( me + 'type xydy' ) self._send( me + 'line linestyle 0' ) #No connecting lines self._send( me + 'errorbar color ' + str(edgecolor) ) self._flush() self._send_3( self.nSets, cent_x, y, dy ) self.nSets = self.nSets + 1 #self._errPlot( cent_x, y, dy ) self._send('with g%s' % self.gID) self._send('world ymin 0.0') # Make sure the y-axis starts at 0 self._send('autoscale') self._send('redraw') self._flush() def _errPlot(self, X, Y, dy=None, symbols=None, styles=None, pType = 'xydy' ): """Line plot with error bars -- for internal use only Do not use this! Use plot() with dy=something instead.""" if dy is None: dy = Y Y = X X = N.arange(X.shape[0]) # Guarantee rank-2 matrices if len(X.shape) == 1: X.shape = (X.shape[0], 1) if len(Y.shape) == 1: Y.shape = (Y.shape[0], 1) if len(dy.shape) == 1: dy.shape = (dy.shape[0], 1) if not ( Y.shape == dy.shape and X.shape[0] == Y.shape[0] and ( X.shape[1] == Y.shape[1] or X.shape[1] == 1 ) ): raise RuntimeError, 'X, Y, and dy have mismatched shapes' if not self._hold: self.clear() for i in xrange(self.nSets, Y.shape[1] + self.nSets): me = 'g%s.s%s ' % (self.gID, i) self._send( me + 'on') self._send( me + 'type ' + pType) mycolor = (i%15)+1 self._send( '%s line color %s' % (me, mycolor) ) self._send( '%s errorbar color %s' % (me, mycolor) ) if symbols is not None: self._send( me + 'symbol %s' % ((i%10) + 1) ) # From 1 to 10 self._send( '%s symbol color %s' % (me, mycolor) ) if styles is not None: self._send( me + 'line linestyle %s' %((i%8) + 1) ) # 1 to 8 self._flush() if X.shape[1] == 1: for i in range(Y.shape[1]): self._send_3( i+self.nSets, X[:,0], Y[:,i], dy[:,i] ) # Send an upper and lower line too so that autoscaling works self._send_2( i+self.nSets+Y.shape[1], X[:,0], Y[:,i]+dy[:,i] ) self._send_2( i+self.nSets+2*Y.shape[1], X[:,0], Y[:,i]-dy[:,i] ) else: for i in range(Y.shape[1]): self._send_3( i+self.nSets, X[:,i], Y[:,i], dy[:,i] ) self._send_2( i+self.nSets+Y.shape[1], X[:,i], Y[:,i]+dy[:,i] ) self._send_2( i+self.nSets+2*Y.shape[1], X[:,i], Y[:,i]-dy[:,i] ) self._send('with g%s' % self.gID) self._send('autoscale') #self._send('redraw') self.nSets = self.nSets + Y.shape[1] # Kill off the extra lines above/below for i in range(self.nSets, self.nSets+2*Y.shape[1]): self._send( 'KILL G%s.S%s' % (self.gID, i) ) self._send('redraw') self._flush() def plot(self, X, Y=None, dy=None, symbols=None, styles=None): """2-D line plot, with or without error bars The arguments should be Numpy arrays of equal length. X, Y, and dy can be rank-1 or rank-2 arrays (vectors or matrices). In rank-2 arrays each column is treated as a dataset. X can be rank-1 even if Y and DY are rank-2, so long as len(X) == len( Y[:,0] ) If dy is not None then it must be the same shape as Y, and symmetric error bars will be plotted with total height 2*dy. Setting symbols=1 will give each dataset a unique symbol. Setting styles=1 will give each dataset a unique linestyle """ X = N.array(X) # if there's no Y, then just use X if Y is None: Y = X X = N.arange(X.shape[0]) else: Y = N.array(Y) if dy is not None: dy = N.array(dy) self._errPlot(X, Y, dy, symbols=symbols, styles=styles) return # Guarantee rank-2 matrices if len(X.shape) == 1: X.shape = (X.shape[0], 1) if len(Y.shape) == 1: Y.shape = (Y.shape[0], 1) if X.shape[0] != Y.shape[0] or ( # Different number of points per line X.shape[1] != X.shape[1] and # Different number of lines X.shape[1] != 1): # But if X is just 1 line it's ok. raise RuntimeError, 'X and Y have mismatched shapes' ############# Grace commands start here ########### if not self._hold: self.clear() pType = 'xy' # At some point this might become an option for i in range(self.nSets, Y.shape[1] + self.nSets): me = 'g%s.s%s ' % (self.gID, i) self._send( me + 'on') self._send( me + 'type ' + pType) self._send( '%s line color %s' % (me, (i%15)+1) ) if symbols is not None: self._send( me + 'symbol %s' % ((i%15) + 1) ) # From 1 to 15 self._send( '%s symbol color %s' % (me, (i%15)+1) ) if styles is not None: self._send( me + 'line linestyle %s' %((i%8) + 1) ) # 1 to 8 self._flush() if X.shape[1] == 1: for i in range(Y.shape[1]): self._send_2( i+self.nSets, X[:,0], Y[:,i] ) else: for i in range(Y.shape[1]): self._send_2( i+self.nSets, X[:,i], Y[:,i] ) self._send('with g%s' % self.gID) self._send('autoscale') self._send('redraw') self._flush() self.nSets = self.nSets + Y.shape[1] def _test(): from time import sleep p = gracePlot() joe = N.arange(5,50) p.plot(joe, joe**2, symbols=1) p.title('Parabola') sleep(2) p.multi(2,2) p.focus(1,1) p.plot(joe, joe, styles=1) p.hold(1) p.plot(joe, N.log(joe), styles=1) p.legend(['Linear', 'Logarithmic']) p.xlabel('Abscissa') p.ylabel('Ordinate') sleep(2) p.focus(1,0) p.histoPlot(N.sin(joe*3.14/49.0), 5./49.*3.14, 3.14) sleep(2) p.exit() if __name__=="__main__": _test()