pygrace.interactive module documentation
process module
a pipe-based interface to xmgrace, similar to grace_np.c
The primary class is Process, which creates a running process of the xmgrace program, and creates a pipe connected to it. The Process class instance is used to send commands to grace.
- exception Disconnected
Bases:
Error
Error resulting from xmgrace unexpectedly connecting from the pipe.
Thrown on an EPIPE error, which indicates that xmgrace has been disconnected from reading the pipe that is used to send commands. The pipe could be closed because xmgrace has crashed, has sent an exit command, or the user has clicked on the exit button.
- class Process(bufsize=-1, debug=0, fixedsize=None, ask=None, safe=None, batch=None, project=None)
Bases:
object
Interface to an instance of a running xmgrace program
Start xmgrace and read from the pipe controlled by pygrace.
- Input:
- bufsize – int, size of the buffer used. xmgrace won’t
respond to sent commands that haven’t been flushed from the buffer, however the speed should improve with buffering. Default is -1, which provdes full buffering. bufsize=0 signifies no buffering.
- debug – bool, if True, each command passed to xmgrace is
also sent to stderr. Default is to not debug.
- fixedsize – tuple, used to set the fixed size of the
grace canvas. Default is None, which causes the grace window to be freely resizable.
- ask – bool, if True, xmgrace will ask before overwriting
a file, clearing the display, etc. Default is to not ask.
- safe – bool, if True, xmgrace will ignore commands like `saveall’,
which write to files. Default is not to be overly safe.
- batch – str, path to command batch_file to be executed on startup
of xmgrace. Default is to not use a batch file.
- project – str, path to xmgrace project file (.agr) to be executed
on startup. Default is to use the xmgrace default project.
- __call__(com)
send a command to xmgrace, then flush the write queue
- __del__()
disconnect from a xmgrace process, but leave xmgrace running
If a Process instance is deleted without calling exit(), it disconnects from xmgrace without killing xmgrace. This assumes that the user may want to continue manipulating the graph through the xmgrace GUI interface. To force xmgrace to terminate, use self.exit()
- command(com)
send a command to xmgrace
- Input:
com – str, command to send to xmgrace
A newline will be added to the command. Unless the instance of the Process class was created using bufsize=0, the interface will be buffered, and thus the execution of the command may be delayed. To flush the buffer, use self.flush(), or alternately, send commands that are automatically flushed, using self(com).
- exit()
cause xmgrace to exit
nicely ask xmgrace to exit (i.e. terminate), however, if xmgrace doesn’t respond then try to kill the process with a SIGTERM.
- flush()
flush any pending commands for xmgrace
- is_open()
True, if the pipe has not been closed
project module
a high-level interface to a xmgrace project session
The intended purpose of Project is to allow easy programmatic and interactive command line plotting with convenience functions for the most common commands. The Grace UI (or pygrace.interactive.process) can be used if more advanced low-level functionality needs to be accessed.
The data model in Grace, (mirrored in Project) goes like this: Each grace session is like virtual sheet of paper called a Project. Each Project can have multiple Graphs, which are sets of axes (use Project.multi() to get multiple axes in Project). Each Graph has multiple data Sets. Data Sets are added to graphs with the plot and histoPlot functions in Project.
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 Project session:
>>> from pygrace.interactive import project
>>> p = project.Project() # A interactive grace project 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 using a lot of histograms then consider using Scientific Python:
histoPlot() knows how to automatically plot Histogram instances from the Scientific.Statistics.Histogram module, so histogramming ends up being 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 Project is that it only has a one-way communications channel with the Grace session. This means that if you make changes to your plot in the GUI (e.g. by changing number/layout of graphs) then Project will have NO KNOWLEDGE of the changes. This should not often be an issue, since the only state that Project saves is the number and layout of graphs, the number of Sets that each graph has, and the hold state for each graph.
- class Graph(grace, gID)
Bases:
object
- _errPlot(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.
- _flush()
- _limHelper(ax, lower, upper)
- _send(cmd)
- _send_2(var, X, Y)
- _send_3(var, X, Y, Z)
- clear()
Erase all lines from the plot and set hold to 0
- histoPlot(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. By default, edges == 0, where x_min and x_max specify the lower and upper edges of the first and last bins, respectively. Otherwise, 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.
- hold(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.
- kill()
Kill the plot
- legend(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 using the mouse.
- pexec(cmd)
- plot(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, as 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
- redraw()
Refresh the plot
- subtitle(titlestr)
Change the subtitle of the plot
- title(titlestr)
Change the title of the plot
- xlabel(label)
Change the x-axis label
- xlimit(lower=None, upper=None)
Set the lower and/or upper bounds of the x-axis.
- ylabel(label)
Change the y-axis label
- ylimit(lower=None, upper=None)
Set the lower and/or upper bounds of the y-axis.
- class Project(*args, **kwds)
Bases:
object
Start xmgrace and read from the pipe controlled by pygrace.
- Input:
- bufsize – int, size of the buffer used. xmgrace won’t
respond to sent commands that haven’t been flushed from the buffer, however the speed should improve with buffering. Default is -1, which provdes full buffering. bufsize=0 signifies no buffering.
- debug – bool, if True, each command passed to xmgrace is
also sent to stderr. Default is to not debug.
- fixedsize – tuple, used to set the fixed size of the
grace canvas. Default is None, which causes the grace window to be freely resizable.
- ask – bool, if True, xmgrace will ask before overwriting
a file, clearing the display, etc. Default is to not ask.
- safe – bool, if True, xmgrace will ignore commands like `saveall’,
which write to files. Default is not to be overly safe.
- batch – str, path to command batch_file to be executed on startup
of xmgrace. Default is to not use a batch file.
- project – str, path to xmgrace project file (.agr) to be executed
on startup. Default is to use the xmgrace default project.
- __del__()
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.
- __getitem__(item)
Access a specific graph. Can use either p[num] or p[row, col].
- _flush()
- _send(cmd)
- exit()
Nuke the grace session. (more final than Project.__del__())
- focus(row, col)
Set the currently active graph
- multi(rows, cols, offset=0.1, hgap=0.1, vgap=0.15)
Create a grid of graphs with the given number of <rows> and <cols>
- pexec(cmd)
- redraw()
Refresh the plot
- resize(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.
- saveall(filename='xmgrace.agr', format=None)
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 or caveats that apply to some of these formats.
session module
Instructions for pygrace: Import the grace class >>> from pygrace import grace Instantiate the grace class >>> pg = grace() Get help >>> pg.doc()
- class grace(*args, **kwds)
Bases:
object
Python interface to a xmgrace Project, with an interactive grace prompt .. method:: 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 xmgrace window
Notes
xmgrace and numpy must be installed, xmgrace also relies on (open)motif
- __call__(*args)
Call self as a function.
- __getattr__(name)
- __setattr__(name, value)
Implement setattr(self, name, value).
- _exists(name)
_exists(name) –> True if is a variable in grace
- _getlocal(name, skip=True)
_getlocal(name) –> return variable value from local store
- _poplocal(name)
_poplocal(name) –> delete variable from local store, return value
- _privdoc = 'Private methods:\n _validate(name) --> raise NameError if is invalid python name\n _putlocal(name,value) --> add a variable to local store\n _getlocal(name) --> return variable value from local store\n _poplocal(name) --> delete variable from local store, return value\n _wholist() --> get list of strings containing grace variables \n _exists(name) --> True if is a variable in grace\n'
- _putlocal(name, value)
_putlocal(name,value) –> add a variable to local store
- _validate(name)
_validate(name) –> raise NameError if is invalid python name
- _wholist()
_wholist() –> get list of strings containing grace variables
- delete(name)
delete(name) –> destroy selected grace variables
- doc()
- eval(com)
eval(command) –> execute a grace command
- get(name)
get(name) –> value; get value from grace session
- prompt()
an interactive grace session
- put(name, val)
put(name,val) –> add variable to grace session
- restart()
restart() –> restart a xmgrace window
- who(name=None)
who([name]) –> return the existing grace variables