Help, problem with gnumeric/python


I try to write a plugin to use xmgrace with gnumeric. My procedure works, but in the moment when I try to change data in spreadsheet I can do it but only (max) two times. Data from spreadsheet are plotted correctly first time (just after loading xmgrace_tmp.gnumeric), then one more time when I change data (in this moment xmgrace plot is updated) and when I try to do it one more time gnumeric crash (I can't send any extra data because I do not have any information from gnumeric).
I'm not sure but problem is with this procedure
def range_ref_to_tuples(range_ref):
This is standard procedure that I copy from Internet but I don't know where is the problem.
As a attachment I send (plugin) (standard xmgrace library - from internet) (-"-)
xmgrace_tmp.gnumeric (demo file - try to change data in the spreadsheet gnumeric shoud crash if not please send me e-mail)

I test it on 1.2.13 and 1.2.12 version of gnumeric and I have still the same problem.
Can somebody help me?

Best regards
Andrzej Grzegorczyk

#!/usr/local/bin/python -t
# $Id:,v 2.6 1999/09/26 03:16:19 mhagger Exp $

"""A python replacement for grace_np.c, a pipe-based interface to xmgrace.

Copyright (C) 1999 Michael Haggerty

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.  This program is distributed in the
hope that it will be useful, but WITHOUT ANY WARRANTY; without even
PURPOSE.  See the GNU 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.

Written by Michael Haggerty <mhagger blizzard harvard edu>.  Based on
the grace_np library distributed with grace, which was written by
Henrik Seidel and the Grace Development Team.

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
<mhagger blizzard harvard edu>.  Other feedback is also welcome.

For a demonstration, run this file by typing `python'.
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


__version__ = '1.0'
__cvs_version__ = 'CVS version $Revision: 2.6 $'

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."""

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."""

# 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.

          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
          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',)
            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: = os.fork()

        # If we are the child, replace ourselves with grace
        if == 0:
                # 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):
                        except OSError:
                    os.execvp('xmgrace', cmd)
                    # 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
                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

        # 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)

            self.pipe.write(cmd + '\n')
        except IOError, err:
            if err.errno == errno.EPIPE:
                raise Disconnected()

    def flush(self):
        """Flush any pending commands to grace."""

        except IOError, err:
            if err.errno == errno.EPIPE:
                # grace is no longer reading from the pipe:
                raise Disconnected()

    def __call__(self, cmd):
        """Send the command to grace, then flush the write queue."""


    # 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():
                # Ask grace to close its end of the pipe (this also
                # flushes pending commands):
            except Disconnected:
                # Looks like grace has already disconnected.
                # Close our end of the pipe (actually, it should be closed
                # automatically when it's deleted, but...):

    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:
                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
                os.waitpid(, 0)
       = None

        # Second try--kill it via a SIGTERM
        if is not None:
                os.kill(, signal.SIGTERM)
            except OSError, err:
                if err.errno == errno.ESRCH:
                    # No such process; it must already be dead
           = None
            os.waitpid(, 0)
   = 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:
            # Wait a second, just to simulate some time needed for
            # calculations. Your real application shouldn't wait.

    # Tell Grace to save the data:
    g('saveall "sample.agr"')

    # Close Grace:

""" -- 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 Numeric 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:

histoPlot() knows how to automatically plot Histogram instances from the 
Scientific.Statistics.Histogram module, so histogramming ends up being pretty 
    >>> 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.

__version__ = "0.5.1"
__author__ = "Nathaniel Gray <n8gray caltech edu>"
__date__ = "September 16, 2001"

import grace_np
import Numeric, string
N = Numeric
del Numeric

    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
    def _send(self, cmd): 
        #print cmd
    def _flush(self):
        #print '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__())"""

    def redraw(self):
        """Refresh the plot"""
        #print '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 <rows> and <cols>
        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:]
    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':''}
            ext = devs[string.lower(format)]
        except KeyError:
            print 'Unknown format.  Known formats are\n%s' % devs.keys()
        if filename[-len(ext):] != ext:
            filename = filename + ext
        if ext == '.agr':
            self._send('saveall "%s"' % filename)
            self._send('hardcopy device "%s"' % string.lower(format) )
            self._send('print to "%s"' % filename)
    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)
        for i in ['plot', 'histoPlot', 'title', 'subtitle', 'xlabel', 'ylabel',
                  'kill', 'clear', 'legend', 'hold', 'xlimit', 'ylimit',
            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))
            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]]
            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"
    def _flush(self):
        #print '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:

    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:

    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) + '"')
    def subtitle(self, titlestr):
        """Change the subtitle of the plot"""
        self._send('with g%s' % self.gID)
        self._send('subtitle "' + str(titlestr) + '"')
    def redraw(self):
        """Refresh the plot"""
    def xlabel(self, label):
        """Change the x-axis label"""
        self._send('with g%s' % self.gID)
        self._send('xaxis label "' + str(label) + '"')
    def ylabel(self, label):
        """Change the y-axis label"""
        self._send('with g%s' % self.gID)
        self._send('yaxis label "' + str(label) + '"')
    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))
    def kill(self):
        """Kill the plot"""
        self._send('kill g%s' % self.gID)
        self._send('g%s on' % self.gID)
        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))
    def legend(self, labels):
        """Set the legend labels for the plot
        Takes a list of strings, one string per dataset on the graph.
        Note:  <ctrl>-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)
    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
            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 )
        # 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 , typecode='d')*binwidth + x_min
            cent_x = (edge_x + 0.5*binwidth)[0:-1]
            # 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), typecode='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._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._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
    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

        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] )
            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.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) )

    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 Numeric 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])
            Y = N.array(Y)
        if dy is not None:
            dy = N.array(dy)
            self._errPlot(X, Y, dy, symbols=symbols, styles=styles)

        # 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

        if X.shape[1] == 1:
            for i in range(Y.shape[1]):
                self._send_2( i+self.nSets, X[:,0], Y[:,i] )
            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.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.plot(joe, joe, styles=1)
    p.plot(joe, N.log(joe), styles=1)
    p.legend(['Linear', 'Logarithmic'])
    p.histoPlot(N.sin(joe*3.14/49.0), 5./49.*3.14, 3.14)
if __name__=="__main__":
<?xml version="1.0"?>
<plugin id="Gnumeric_MyFuncPlugin">
        <name>Takie tam</name>
        <description>A few extra python functions demonstrating the API.</description>
  <loader type="Gnumeric_PythonLoader:python">
        <attribute name="module_name" value="xmgrace"/>
        <service type="function_group" id="example">
          <category>Local Python</category>
                <function name="xmgrace"/>

# 'version 0.1'
# ^^^^^^^
# File name must match value of module_name in plugin.xml.
# Sample python plug-ins for gnumeric, written for the HOWTO
#   starting-with-python.html
# To define a new function, you must do five things (three sir!):
#   1. Write the new function: def func_newfunc(....):
#   2. Include it in the example_functions list at the end.
#   3. Include it in ./plugin.xml, at the end.
# Then restart Gnumeric and it should be there!

from Gnumeric import GnumericError, GnumericErrorVALUE
import Gnumeric
import string
from gracePlot import gracePlot
p = gracePlot()
def xmgrace(gRange, gRange1):
        '@SYNTAX=XMGRACE(gRange, gRange1)\n'\
        '@DESCRIPTION=Adds two numbers together.\n\n'\
        '@EXAMPLES=To add two constants, just type them in: XMGRACE(A1:A5,B1:B5)\n'\
        'To add two cells, use the cell addresses: xmgrace(A1,A2)\n'\
        [r_begin, r_end] = range_ref_to_tuples(gRange)
        [r_begin1, r_end1] = range_ref_to_tuples(gRange1)
        for row in range(r_begin[1], r_end[1]):
                cell = s[r_begin[0], row]
                cell1 = s[r_begin1[0], row]
                print x,',',y

        return 1

def range_ref_to_tuples(range_ref):
        '''I need a function to find the bounds of a RangeRef. This one
        extracts them from the Gnumeric "column" and "row" commands, and
        returns them as a pair of tuples. Surely there is a better way?
        For example, return a list of cells??'''

        col  = Gnumeric.functions['column']   
        row  = Gnumeric.functions['row']

        # "column" and "row" take references and return an array of col or row
        # nums for each cell in the reference. For example, [[1, 1, 1], [2, 2, 2]]
        # for columns and [[2, 3, 4], [2, 3, 4]] for rows.

                columns = col(range_ref)
                rows    = row(range_ref)

                begin_col = columns[0][0] - 1  
                begin_row = rows[0][0] - 1     

                end_col = columns[-1][-1]
                end_row = rows[-1][-1]

                # We subtracted 1 from the begin values because in the API,
                # indexing begins at 0, while "column" and "row" begin at 1.
                # We did NOT subtract 1 from the end values, in order to make
                # them suitable for Python's range(begin, end) paradigm.
        except TypeError:
                raise GnumericError,GnumericErrorVALUE
        except NameError:                     # right name?
                raise GnumericError,Gnumeric.GnumericErrorNAME
        except RefError:                     # right name?
                raise GnumericError,Gnumeric.GnumericErrorREF
        except NumError:                     # right name?
                raise GnumericError,Gnumeric.GnumericErrorNUM

        return [ (begin_col, begin_row), (end_col, end_row) ]

# To register your functions with gnumeric, include them in a
# dictionary list. This list must have the name <id>_functions
# where <id> is the value of function_group in plugin.xml.
# The format for functions taking an arbitrary number of arguments is:
#    'gnumeric-name': python-name
# The format for functions taking a known set of parameters is:
#    'gnumeric-name': ('params type string', 'params-names', python-name)
# For more information, read doc/developer/writing-functions.sgml.
# After including them here, also declare them in the list at the
# end of plugin.xml.
# Types I know are available (float, string):
#     f, s
# Other possible types (boolean, range, array, arrayOrRange, cell, any):
#     b, r, a, A, c, ?

example_functions = {
        'xmgrace': ('rr','range1,range2',xmgrace),

Attachment: xmgrace_tmp.gnumeric
Description: Binary data

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]