\chapter{Graphs}
\label{graph}

\section{Introduction} % {{{
\PyX{} can be used for data and function plotting. At present
x-y-graphs and x-y-z-graphs are supported only. However, the component
architecture of the graph system described in section
\ref{graph:components} allows for additional graph geometries while
reusing most of the existing components.

Creating a graph splits into two basic steps. First you have to create
a graph instance. The most simple form would look like:
\begin{verbatim}
from pyx import *
g = graph.graphxy(width=8)
\end{verbatim}
The graph instance \code{g} created in this example can then be used
to actually plot something into the graph. Suppose you have some data
in a file \file{graph.dat} you want to plot. The content of the file
could look like:
\verbatiminput{graph.dat}
To plot these data into the graph \code{g} you must perform:
\begin{verbatim}
g.plot(graph.data.file("graph.dat", x=1, y=2))
\end{verbatim}
The method \method{plot()} takes the data to be plotted and optionally
a list of graph styles to be used to plot the data. When no styles are
provided, a default style defined by the data instance is used. For
data read from a file by an instance of \class{graph.data.file}, the
default are symbols. When instantiating \class{graph.data.file}, you
not only specify the file name, but also a mapping from columns to
axis names and other information the styles might make use of
(\emph{e.g.} data for error bars to be used by the errorbar style).

While the graph is already created by that, we still need to perform a
write of the result into a file. Since the graph instance is a canvas,
we can just call its \method{writeEPSfile()} method.
\begin{verbatim}
g.writeEPSfile("graph")
\end{verbatim}
The result \file{graph.eps} is shown in figure~\ref{fig:graph}.

\begin{figure}[ht]
\centerline{\includegraphics{graph}}
\caption{A minimalistic plot for the data from file \file{graph.dat}.}
\label{fig:graph}
\end{figure}

Instead of plotting data from a file, other data source are available
as well. For example function data is created and placed into
\method{plot()} by the following line:
\begin{verbatim}
g.plot(graph.data.function("y(x)=x**2"))
\end{verbatim}
You can plot different data in a single graph by calling
\method{plot()} several times before \method{writeEPSfile()} or
\method{writePDFfile()}. Note that a calling \method{plot()} will fail
once a graph was forced to ``finish'' itself. This happens
automatically, when the graph is written to a file. Thus it is not an
option to call \method{plot()} after \method{writeEPSfile()} or
\method{writePDFfile()}. The topic of the finalization of a graph is
addressed in more detail in section~\ref{graph:graph}. As you can see
in figure~\ref{fig:graph2}, a function is plotted as a line by
default.

\begin{figure}[ht]
\centerline{\includegraphics{graph2}}
\caption{Plotting data from a file together with a function.}
\label{fig:graph2}
\end{figure}

While the axes ranges got adjusted automatically in the previous
example, they might be fixed by keyword options in axes constructors.
Plotting only a function will need such a setting at least in the
variable coordinate. The following code also shows how to set a
logathmic axis in y-direction:

\verbatiminput{graph3.py}

The result is shown in figure~\ref{fig:graph3}.

\begin{figure}[ht]
\centerline{\includegraphics{graph3}}
\caption{Plotting a function for a given axis range and use a
logarithmic y-axis.}
\label{fig:graph3}
\end{figure} % }}}

\section{Component architecture} % {{{
\label{graph:components}

Creating a graph involves a variety of tasks, which thus can be
separated into components without significant additional costs.
This structure manifests itself also in the \PyX{} source, where there
are different modules for the different tasks. They interact by some
well-defined interfaces. They certainly have to be completed and
stabilized in their details, but the basic structure came up in the
continuous development quite clearly. The basic parts of a graph are:

\begin{definitions}
\term{graph}
  Defines the geometry of the graph by means of graph coordinates with
  range [0:1]. Keeps lists of plotted data, axes \emph{etc.}
\term{data}
  Produces or prepares data to be plotted in graphs.
\term{style}
  Performs the plotting of the data into the graph. It gets data,
  converts them via the axes into graph coordinates and uses the graph
  to finally plot the data with respect to the graph geometry methods.
\term{key}
  Responsible for the graph keys.
\term{axis}
  Creates axes for the graph, which take care of the mapping from data
  values to graph coordinates. Because axes are also responsible for
  creating ticks and labels, showing up in the graph themselves and
  other things, this task is splitted into several independent
  subtasks. Axes are discussed separately in chapter~\ref{axis}.
\end{definitions} % }}}

\section{Module \module{graph.graph}: Graphs} % {{{
\label{graph:graph}

\declaremodule{}{graph.graph}
\modulesynopsis{Graph geometry}

The classes \class{graphxy} and \class{graphxyz} are part of the
module \module{graph.graph}. However, there are shortcuts to access
the classes via \code{graph.graphxy} and \code{graph.graphxyz},
respectively.

\begin{classdesc}{graphxy}{xpos=0, ypos=0, width=None, height=None,
ratio=goldenmean, key=None, backgroundattrs=None,
axesdist=0.8*unit.v\_cm, xaxisat=None, yaxisat=None, **axes}
  This class provides an x-y-graph. A graph instance is also a fully
  functional canvas.

  The position of the graph on its own canvas is specified by
  \var{xpos} and \var{ypos}. The size of the graph is specified by
  \var{width}, \var{height}, and \var{ratio}. These parameters define
  the size of the graph area not taking into account the additional
  space needed for the axes. Note that you have to specify at least
  \var{width} or \var{height}. \var{ratio} will be used as the ratio
  between \var{width} and \var{height} when only one of these is
  provided.

  \var{key} can be set to a \class{graph.key.key} instance to create
  an automatic graph key. \code{None} omits the graph key.

  \var{backgroundattrs} is a list of attributes for drawing the
  background of the graph. Allowed are decorators, strokestyles, and
  fillstyles. \code{None} disables background drawing.

  \var{axisdist} is the distance between axes drawn at the same side
  of a graph.

  \var{xaxisat} and \var{yaxisat} specify a value at the y and x axis,
  where the corresponding axis should be moved to. It's a shortcut for
  corresonding calls of \method{axisatv()} described below. Moving an
  axis by \var{xaxisat} or \var{yaxisat} disables the automatic
  creation of a linked axis at the opposite side of the graph.

  \var{**axes} receives axes instances. Allowed keywords (axes names)
  are \code{x}, \code{x2}, \code{x3}, \emph{etc.} and \code{y},
  \code{y2}, \code{y3}, \emph{etc.} When not providing an \code{x} or
  \code{y} axis, linear axes instances will be used automatically.
  When not providing a \code{x2} or \code{y2} axis, linked axes to the
  \code{x} and \code{y} axes are created automatically and \emph{vice
  versa}. As an exception, a linked axis is not created automatically
  when the axis is placed at a specific position by \var{xaxisat} or
  \var{yaxisat}. You can disable the automatic creation of axes by
  setting the linked axes to \code{None}. The even numbered axes are
  plotted at the top (\code{x} axes) and right (\code{y} axes) while
  the others are plotted at the bottom (\code{x} axes) and left
  (\code{y} axes) in ascending order each.
\end{classdesc}

Some instance attributes might be useful for outside read-access.
Those are:

\begin{memberdesc}{axes}
  A dictionary mapping axes names to the \class{anchoredaxis} instances.
\end{memberdesc}

To actually plot something into the graph, the following instance
method \method{plot()} is provided:

\begin{methoddesc}{plot}{data, styles=None}
  Adds \var{data} to the list of data to be plotted. Sets \var{styles}
  to be used for plotting the data. When \var{styles} is \code{None},
  the default styles for the data as provided by \var{data} is used.

  \var{data} should be an instance of any of the data described in
  section~\ref{graph:data}.

  When the same combination of styles (\emph{i.e.} the same
  references) are used several times within the same graph instance,
  the styles are kindly asked by the graph to iterate their
  appearance. Its up to the styles how this is performed.

  Instead of calling the plot method several times with different
  \var{data} but the same style, you can use a list (or something
  iterateable) for \var{data}.
\end{methoddesc}

While a graph instance only collects data initially, at a certain
point it must create the whole plot. Once this is done, further calls
of \method{plot()} will fail. Usually you do not need to take care
about the finalization of the graph, because it happens automatically
once you write the plot into a file. However, sometimes position
methods (described below) are nice to be accessible. For that, at
least the layout of the graph must have been finished. By calling the
\method{do}-methods yourself you can also alter the order in which the
graph components are plotted. Multiple calls to any of the
\method{do}-methods have no effect (only the first call counts). The
orginal order in which the \method{do}-methods are called is:

\begin{methoddesc}{dolayout}{}
  Fixes the layout of the graph. As part of this work, the ranges of
  the axes are fitted to the data when the axes ranges are allowed to
  adjust themselves to the data ranges. The other \method{do}-methods
  ensure, that this method is always called first.
\end{methoddesc}

\begin{methoddesc}{dobackground}{}
  Draws the background.
\end{methoddesc}

\begin{methoddesc}{doaxes}{}
  Inserts the axes.
\end{methoddesc}

\begin{methoddesc}{doplot}{plotitem}
  Plots the plotitem as returned by the graphs plot method.
\end{methoddesc}

\begin{methoddesc}{dodata}{}
  Plots the data.
\end{methoddesc}

\begin{methoddesc}{dokey}{}
  Inserts the graph key.
\end{methoddesc}

\begin{methoddesc}{finish}{}
  Finishes the graph by calling all pending \method{do}-methods. This
  is done automatically, when the output is created.
\end{methoddesc}

The graph provides some methods to access its geometry:

\begin{methoddesc}{pos}{x, y, xaxis=None, yaxis=None}
  Returns the given point at \var{x} and \var{y} as a tuple
  \code{(xpos, ypos)} at the graph canvas. \var{x} and \var{y} are
  anchoredaxis instances for the two axes \var{xaxis} and \var{yaxis}.
  When \var{xaxis} or \var{yaxis} are \code{None}, the axes with names
  \code{x} and \code{y} are used. This method fails if called before
  \method{dolayout()}.
\end{methoddesc}

\begin{methoddesc}{vpos}{vx, vy}
  Returns the given point at \var{vx} and \var{vy} as a tuple
  \code{(xpos, ypos)} at the graph canvas. \var{vx} and \var{vy} are
  graph coordinates with range [0:1].
\end{methoddesc}

\begin{methoddesc}{vgeodesic}{vx1, vy1, vx2, vy2}
  Returns the geodesic between points \var{vx1}, \var{vy1} and
  \var{vx2}, \var{vy2} as a path. All parameters are in graph
  coordinates with range [0:1]. For \class{graphxy} this is a straight
  line.
\end{methoddesc}

\begin{methoddesc}{vgeodesic\_el}{vx1, vy1, vx2, vy2}
  Like \method{vgeodesic()} but this method returns the path element to
  connect the two points.
\end{methoddesc}

% dirty hack to add a whole list of methods to the index:
\index{xbasepath()@\texttt{xbasepath()} (graphxy method)}
\index{xvbasepath()@\texttt{xvbasepath()} (graphxy method)}
\index{xgridpath()@\texttt{xgridpath()} (graphxy method)}
\index{xvgridpath()@\texttt{xvgridpath()} (graphxy method)}
\index{xtickpoint()@\texttt{xtickpoint()} (graphxy method)}
\index{xvtickpoint()@\texttt{xvtickpoint()} (graphxy method)}
\index{xtickdirection()@\texttt{xtickdirection()} (graphxy method)}
\index{xvtickdirection()@\texttt{xvtickdirection()} (graphxy method)}
\index{ybasepath()@\texttt{ybasepath()} (graphxy method)}
\index{yvbasepath()@\texttt{yvbasepath()} (graphxy method)}
\index{ygridpath()@\texttt{ygridpath()} (graphxy method)}
\index{yvgridpath()@\texttt{yvgridpath()} (graphxy method)}
\index{ytickpoint()@\texttt{ytickpoint()} (graphxy method)}
\index{yvtickpoint()@\texttt{yvtickpoint()} (graphxy method)}
\index{ytickdirection()@\texttt{ytickdirection()} (graphxy method)}
\index{yvtickdirection()@\texttt{yvtickdirection()} (graphxy method)}

Further geometry information is available by the \member{axes}
instance variable, with is a dictionary mapping axis names to
\class{anchoredaxis} instances. Shortcuts to the anchoredaxis
positioner methods for the \code{x}- and \code{y}-axis become
available after \method{dolayout()} as \class{graphxy} methods
\code{Xbasepath}, \code{Xvbasepath}, \code{Xgridpath},
\code{Xvgridpath}, \code{Xtickpoint}, \code{Xvtickpoint},
\code{Xtickdirection}, and \code{Xvtickdirection} where the prefix
\code{X} stands for \code{x} and \code{y}.

\begin{methoddesc}{axistrafo}{axis, t}
  This method can be used to apply a transformation \var{t} to an
  \class{anchoredaxis} instance \var{axis} to modify the axis position
  and the like. This method fails when called on a not yet finished
  axis, i.e. it should be used after \method{dolayout()}.
\end{methoddesc}

\begin{methoddesc}{axisatv}{axis, v}
  This method calls \method{axistrafo()} with a transformation to move
  the axis \var{axis} to a graph position \var{v} (in graph
  coordinates).
\end{methoddesc}

The class \class{graphxyz} is very similar to the \class{graphxy}
class, except for its additional dimension. In the following
documentation only the differences to the \class{graphxy} class are
described.

\begin{classdesc}{graphxyz}{xpos=0, ypos=0, size=None,
                            xscale=1, yscale=1, zscale=1/goldenmean,
                            projector=central(10, -30, 30), key=None,
                            **axes}
  This class provides an x-y-z-graph.

  The position of the graph on its own canvas is specified by
  \var{xpos} and \var{ypos}. The size of the graph is specified by
  \var{size} and the length factors \var{xscale}, \var{yscale}, and
  \var{zscale}. The final size of the graph depends on the projector
  \var{projector}, which is called with \code{x}, \code{y}, and
  \code{z} values up to \var{xscale}, \var{yscale}, and  \var{zscale}
  respectively and scaling the result by \var{size}. For a parallel
  projector changing \var{size} is thus identical to changing
  \var{xscale}, \var{yscale}, and \var{zscale} by the same factor. For
  the central projector the projectors internal distance would also
  need to be changed by this factor. Thus \var{size} changes the size
  of the whole graph without changing the projection.

  \var{projector} defines the conversion of 3d coordinates to 2d
  coordinates. It can be an instance of \class{central} or
  \class{parallel} described below.

  \var{**axes} receives axes instances as for \class{graphxyz}. The
  graphxyz allows for 4 axes per graph dimension \code{x}, \code{x2},
  \code{x3}, \code{x4}, \code{y}, \code{y2}, \code{y3}, \code{y4},
  \code{z}, \code{z2}, \code{z3}, and \code{z4}. The x-y-plane is the
  horizontal plane at the bottom and the \code{x}, \code{x2},
  \code{y}, and \code{y2} axes are placed at the boundary of this
  plane with \code{x} and \code{y} always being in front. \code{x3},
  \code{x4}, \code{y3}, and \code{y4} are handled similar, but for the
  top plane of the graph. The \code{z} axis is placed at the origin of
  the \code{x} and \code{y} dimension, whereas \code{z2} is placed at
  the final point of the \code{x} dimension, \code{z3} at the final
  point of the \code{y} dimension and \code{z4} at the final point of
  the \code{x} and \code{y} dimension together.
\end{classdesc}

\begin{memberdesc}{central}
  The central attribute of the graphxyz is the \class{central} class.
  See the class description below.
\end{memberdesc}

\begin{memberdesc}{parallel}
  The parallel attribute of the graphxyz is the \class{parallel} class.
  See the class description below.
\end{memberdesc}

Regarding the 3d to 2d transformation the methods \method{pos},
\method{vpos}, \method{vgeodesic}, and \method{vgeodesic\_el} are
available as for class \class{graphxy} and just take an additional
argument for the dimension. Note that a similar transformation method
(3d to 2d) is available as part of the projector as well already, but
only the graph acknowledges its size, the scaling and the internal
tranformation of the graph coordinates to the scaled coordinates. As
the projector also implements a \method{zindex} and a \method{angle}
method, those are also available at the graph level in the graph
coordinate variant (i.e. having an additional v in its name and using
values from 0 to 1 per dimension).

\begin{methoddesc}{vzindex}{vx, vy, vz}
  The depths of the point defined by \var{vx}, \var{vy}, and \var{vz}
  scaled to a range [-1:1] where 1 in closed to the viewer. All
  arguments passed to the method are in graph coordinates with range
  [0:1].
\end{methoddesc}

\begin{methoddesc}{vangle}{vx1, vy1, vz1, vx2, vy2, vz2, vx3, vy3, vz3}
  The cosine of the angle of the view ray thru point \code{(vx1, vy1,
  vz1)} and the plane defined by the points \code{(vx1, vy1, vz1)},
  \code{(vx2, vy2, vz2)}, and \code{(vx3, vy3, vz3)}. All arguments
  passed to the method are in graph coordinates with range [0:1].
\end{methoddesc}

There are two projector classes \class{central} and \class{parallel}:

\begin{classdesc}{central}{distance, phi, theta, anglefactor=math.pi/180}
  Instances of this class implement a central projection for the given
  parameters.

  \var{distance} is the distance of the viewer from the origin. Note
  that the \class{graphxyz} class uses the range \code{-xscale} to
  \code{xscale}, \code{-yscale} to \code{yscale}, and \code{-zscale}
  to \code{zscale} for the coordinates \code{x}, \code{y}, and
  \code{z}. As those scales are of the order of one (by default), the
  distance should be of the order of 10 to give nice results. Smaller
  distances increase the central projection character while for huge
  distances the central projection becomes identical to the parallel
  projection.

  \code{phi} is the angle of the viewer in the x-y-plane and
  \code{theta} is the angle of the viewer to the x-y-plane. The
  standard notation for spheric coordinates are used. The angles are
  multiplied by \var{anglefactor} which is initialized to do a degree
  in radiant transformation such that you can specify \code{phi} and
  \code{theta} in degree while the internal computation is always done
  in radiants.
\end{classdesc}

\begin{classdesc}{parallel}{phi, theta, anglefactor=math.pi/180}
  Instances of this class implement a parallel projection for the
  given parameters. There is no distance for that transformation
  (compared to the central projection). All other parameters are
  identical to the \class{central} class.
\end{classdesc} % }}}

\section{Module \module{graph.data}: Data} % {{{
\label{graph:data}

\declaremodule{}{graph.data}
\modulesynopsis{Graph data}

The following classes provide data for the \method{plot()} method of a
graph. The classes are implemented in \module{graph.data}.

\begin{classdesc}{file}{filename, % {{{
                        commentpattern=defaultcommentpattern,
                        columnpattern=defaultcolumnpattern,
                        stringpattern=defaultstringpattern,
                        skiphead=0, skiptail=0, every=1, title=notitle,
                        context=\{\}, copy=1,
                        replacedollar=1, columncallback="\_\_column\_\_",
                        **columns}
  This class reads data from a file and makes them available to the
  graph system. \var{filename} is the name of the file to be read.
  The data should be organized in columns.

  The arguments \var{commentpattern}, \var{columnpattern}, and
  \var{stringpattern} are responsible for identifying the data in each
  line of the file. Lines matching \var{commentpattern} are ignored
  except for the column name search of the last non-empty comment line
  before the data. By default a line starting with one of the
  characters \character{\#}, \character{\%}, or \character{!} as well
  as an empty line is treated as a comment.

  A non-comment line is analysed by repeatedly matching
  \var{stringpattern} and, whenever the stringpattern does not match,
  by \var{columnpattern}. When the \var{stringpattern} matches, the
  result is taken as the value for the next column without further
  transformations. When \var{columnpattern} matches, it is tried to
  convert the result to a float. When this fails the result is taken
  as a string as well. By default, you can write strings with spaces
  surrounded by \character{\textquotedbl} immediately surrounded by
  spaces or begin/end of line in the data file. Otherwise
  \character{\textquotedbl} is not taken to be special.

  \var{skiphead} and \var{skiptail} are numbers of data lines to be
  ignored at the beginning and end of the file while \var{every}
  selects only every \var{every} line from the data.

  \var{title} is the title of the data to be used in the graph key. A
  default title is constructed out of \var{filename} and
  \var{**columns}. You may set \var{title} to \code{None} to disable
  the title.

  Finally, \var{columns} define columns out of the existing columns
  from the file by a column number or a mathematical expression (see
  below). When \var{copy} is set the names of the columns in the file
  (file column names) and the freshly created columns having the names
  of the dictionary key (data column names) are passed as data to the
  graph styles. The data columns may hide file columns when names are
  equal. For unset \var{copy} the file columns are not available to
  the graph styles.

  File column names occur when the data file contains a comment line
  immediately in front of the data (except for empty or empty comment
  lines). This line will be parsed skipping the matched comment
  identifier as if the line would be regular data, but it will not be
  converted to floats even if it would be possible to convert the
  items. The result is taken as file column names, \emph{i.e.} a
  string representation for the columns in the file.

  The values of \var{**columns} can refer to column numbers in the
  file starting at \code{1}. The column \code{0} is also available
  and contains the line number starting from \code{1} not counting
  comment lines, but lines skipped by \var{skiphead}, \var{skiptail},
  and \var{every}. Furthermore values of \var{**columns} can be
  strings: file column names or complex mathematical expressions. To
  refer to columns within mathematical expressions you can also use
  file column names when they are valid variable identifiers. Equal
  named items in context will then be hidden. Alternatively columns
  can be access by the syntax \code{\$\textless number\textgreater}
  when \var{replacedollar} is set. They will be translated into
  function calls to \var{columncallback}, which is a function to
  access column data by index or name.

  \var{context} allows for accessing external variables and functions
  when evaluating mathematical expressions for columns. Additionally
  to the identifiers in \var{context}, the file column names, the
  \var{columncallback} function and the functions shown in the table
  ``builtins in math expressions'' at the end of the section are
  available.

  Example:
  \begin{verbatim}
graph.data.file("test.dat", a=1, b="B", c="2*B+$3")
  \end{verbatim}
  with \file{test.dat} looking like:
  \begin{verbatim}
# A   B C
1.234 1 2
5.678 3 4
  \end{verbatim}
  The columns with name \code{"a"}, \code{"b"}, \code{"c"} will become
  \code{"[1.234, 5.678]"}, \code{"[1.0, 3.0]"}, and \code{"[4.0,
  10.0]"}, respectively. The columns \code{"A"}, \code{"B"},
  \code{"C"} will be available as well, since \var{copy} is enabled by
  default.

  When creating several data instances accessing the same file,
  the file is read only once. There is an inherent caching of the
  file contents.
\end{classdesc}

For the sake of completeness we list the default patterns:

\begin{memberdesc}{defaultcommentpattern}
  \code{re.compile(r\textquotedbl (\#+|!+|\%+)\e s*\textquotedbl)}
\end{memberdesc}

\begin{memberdesc}{defaultcolumnpattern}
  \code{re.compile(r\textquotedbl\e \textquotedbl(.*?)\e \textquotedbl(\e s+|\$)\textquotedbl)}
\end{memberdesc}

\begin{memberdesc}{defaultstringpattern}
  \code{re.compile(r\textquotedbl(.*?)(\e s+|\$)\textquotedbl)}
\end{memberdesc} % }}}

\begin{classdesc}{function}{expression, title=notitle, % {{{
                            min=None, max=None, points=100,
                            context=\{\}}
  This class creates graph data from a function. \var{expression} is
  the mathematical expression of the function. It must also contain
  the result variable name including the variable the function depends
  on by assignment. A typical example looks like \code{"y(x)=sin(x)"}.

  \var{title} is the title of the data to be used in the graph key. By
  default \var{expression} is used. You may set \var{title} to
  \code{None} to disable the title.

  \var{min} and \var{max} give the range of the variable. If not set,
  the range spans the whole axis range. The axis range might be set
  explicitly or implicitly by ranges of other data. \var{points} is
  the number of points for which the function is calculated. The
  points are choosen linearly in terms of graph coordinates.

  \var{context} allows for accessing external variables and functions.
  Additionally to the identifiers in \var{context}, the variable name
  and the functions shown in the table ``builtins in math
  expressions'' at the end of the section are available.
\end{classdesc} % }}}

\begin{classdesc}{paramfunction}{varname, min, max, expression, % {{{
                                 title=notitle, points=100,
                                 context=\{\}}
  This class creates graph data from a parametric function.
  \var{varname} is the parameter of the function. \var{min} and
  \var{max} give the range for that variable. \var{points} is the
  number of points for which the function is calculated. The points
  are choosen lineary in terms of the parameter.

  \var{expression} is the mathematical expression for the parametric
  function. It contains an assignment of a tuple of functions to a
  tuple of variables. A typical example looks like
  \code{"x, y = cos(k), sin(k)"}.

  \var{title} is the title of the data to be used in the graph key. By
  default \var{expression} is used. You may set \var{title} to
  \code{None} to disable the title.

  \var{context} allows for accessing external variables and functions.
  Additionally to the identifiers in \var{context}, \var{varname} and
  the functions shown in the table ``builtins in math expressions'' at
  the end of the section are available.
\end{classdesc} % }}}

\begin{classdesc}{values}{title="user provided values", % {{{
                          **columns}
  This class creates graph data from externally provided data.
  Each column is a list of values to be used for that column.

  \var{title} is the title of the data to be used in the graph key.
\end{classdesc} % }}}

\begin{classdesc}{points}{data, title="user provided points", % {{{
                          addlinenumbers=1, **columns}
  This class creates graph data from externally provided data.
  \var{data} is a list of lines, where each line is a list of data
  values for the columns.

  \var{title} is the title of the data to be used in the graph key.

  The keywords of \var{**columns} become the data column names. The
  values are the column numbers starting from one, when
  \var{addlinenumbers} is turned on (the zeroth column is added to
  contain a line number in that case), while the column numbers starts
  from zero, when \var{addlinenumbers} is switched off.
\end{classdesc} % }}}

\begin{classdesc}{data}{data, title=notitle, context={}, copy=1, % {{{
                        replacedollar=1, columncallback="\_\_column\_\_", **columns}
  This class provides graph data out of other graph data. \var{data}
  is the source of the data. All other parameters work like the equally
  called parameters in \class{graph.data.file}. Indeed, the latter is
  built on top of this class by reading the file and caching its
  contents in a \class{graph.data.list} instance.
\end{classdesc} % }}}

\begin{classdesc}{conffile}{filename, title=notitle, context={}, copy=1, % {{{
                            replacedollar=1, columncallback="\_\_column\_\_", **columns}
  This class reads data from a config file with the file name
  \var{filename}. The format of a config file is described within the
  documentation of the \module{ConfigParser} module of the Python
  Standard Library.

  Each section of the config file becomes a data line. The options in
  a section are the columns. The name of the options will be used as
  file column names. All other parameters work as in
  \var{graph.data.file} and \var{graph.data.data} since they all use
  the same code.
\end{classdesc} % }}}

\begin{classdesc}{cbdfile}{filename, minrank=None, maxrank=None, % {{{
                           title=notitle, context={}, copy=1,
                           replacedollar=1, columncallback="\_\_column\_\_", **columns}
  This is an experimental class to read map data from cbd-files. See
  \url{http://sepwww.stanford.edu/ftp/World_Map/} for some world-map
  data.
\end{classdesc} % }}}

The builtins in math expressions are listed in the following table:
\begin{tableii}{l|l}{textrm}{name}{value}
\code{neg}&\code{lambda x: -x}\\
\code{abs}&\code{lambda x: x < 0 and -x or x}\\
\code{sgn}&\code{lambda x: x < 0 and -1 or 1}\\
\code{sqrt}&\code{math.sqrt}\\
\code{exp}&\code{math.exp}\\
\code{log}&\code{math.log}\\
\code{sin}&\code{math.sin}\\
\code{cos}&\code{math.cos}\\
\code{tan}&\code{math.tan}\\
\code{asin}&\code{math.asin}\\
\code{acos}&\code{math.acos}\\
\code{atan}&\code{math.atan}\\
\code{sind}&\code{lambda x: math.sin(math.pi/180*x)}\\
\code{cosd}&\code{lambda x: math.cos(math.pi/180*x)}\\
\code{tand}&\code{lambda x: math.tan(math.pi/180*x)}\\
\code{asind}&\code{lambda x: 180/math.pi*math.asin(x)}\\
\code{acosd}&\code{lambda x: 180/math.pi*math.acos(x)}\\
\code{atand}&\code{lambda x: 180/math.pi*math.atan(x)}\\
\code{norm}&\code{lambda x, y: math.hypot(x, y)}\\
\code{splitatvalue}&see the \code{splitatvalue} description below\\
\code{pi}&\code{math.pi}\\
\code{e}&\code{math.e}
\end{tableii}
\code{math} refers to Pythons \module{math} module. The
\code{splitatvalue} function is defined as:

\begin{funcdesc}{splitatvalue}{value, *splitpoints}
  This method returns a tuple \code{(section, \var{value})}.
  The section is calculated by comparing \var{value} with the values
  of {splitpoints}. If \var{splitpoints} contains only a single item,
  \code{section} is \code{0} when value is lower or equal this item
  and \code{1} else. For multiple splitpoints, \code{section} is
  \code{0} when its lower or equal the first item, \code{None} when
  its bigger than the first item but lower or equal the second item,
  \code{1} when its even bigger the second item, but lower or equal
  the third item. It continues to alter between \code{None} and
  \code{2}, \code{3}, etc.
\end{funcdesc}

% }}}

\section{Module \module{graph.style}: Styles} % {{{
\label{graph:style}

\declaremodule{}{graph.style}
\modulesynopsis{Graph style}

Please note that we are talking about graph styles here. Those are
responsible for plotting symbols, lines, bars and whatever else into a
graph. Do not mix it up with path styles like the line width, the line
style (solid, dashed, dotted \emph{etc.}) and others.

The following classes provide styles to be used at the \method{plot()}
method of a graph. The plot method accepts a list of styles. By that
you can combine several styles at the very same time.

Some of the styles below are hidden styles. Those do not create any
output, but they perform internal data handling and thus help on
modularization of the styles. Usually, a visible style will depend on
data provided by one or more hidden styles but most of the time it is
not necessary to specify the hidden styles manually. The hidden styles
register themself to be the default for providing certain internal
data.

\begin{classdesc}{pos}{epsilon=1e-10} % {{{
  This class is a hidden style providing a position in the graph. It
  needs a data column for each graph dimension. For that the column
  names need to be equal to an axis name. Data points are considered
  to be out of graph when their position in graph coordinates exceeds
  the range [0:1] by more than \var{epsilon}.
\end{classdesc} % }}}

\begin{classdesc}{range}{usenames={}, epsilon=1e-10} % {{{
  This class is a hidden style providing an errorbar range. It needs
  data column names constructed out of a axis name \code{X} for each
  dimension errorbar data should be provided as follows:
  \begin{tableii}{l|l}{}{data name}{description}
    \lineii{\code{Xmin}}{minimal value}
    \lineii{\code{Xmax}}{maximal value}
    \lineii{\code{dX}}{minimal and maximal delta}
    \lineii{\code{dXmin}}{minimal delta}
    \lineii{\code{dXmax}}{maximal delta}
  \end{tableii}
  When delta data are provided the style will also read column data
  for the axis name \code{X} itself. \var{usenames} allows to insert a
  translation dictionary from axis names to the identifiers \code{X}.

  \var{epsilon} is a comparison precision when checking for invalid
  errorbar ranges.
\end{classdesc} % }}}

\begin{classdesc}{symbol}{symbol=changecross, size=0.2*unit.v\_cm, % {{{
                          symbolattrs=[]}
  This class is a style for plotting symbols in a graph.
  \var{symbol} refers to a (changeable) symbol function with the
  prototype \code{symbol(c, x\_pt, y\_pt, size\_pt, attrs)} and draws
  the symbol into the canvas \code{c} at the position \code{(x\_pt,
  y\_pt)} with size \code{size\_pt} and attributes \code{attrs}. Some
  predefined symbols are available in member variables listed below.
  The symbol is drawn at size \var{size} using \var{symbolattrs}.
  \var{symbolattrs} is merged with \code{defaultsymbolattrs} which is
  a list containing the decorator \class{deco.stroked}. An instance of
  \class{symbol} is the default style for all graph data classes
  described in section~\ref{graph:data} except for \class{function}
  and \class{paramfunction}.
\end{classdesc}

The class \class{symbol} provides some symbol functions as member
variables, namely:

\begin{memberdesc}{cross}
  A cross. Should be used for stroking only.
\end{memberdesc}

\begin{memberdesc}{plus}
  A plus. Should be used for stroking only.
\end{memberdesc}

\begin{memberdesc}{square}
  A square. Might be stroked or filled or both.
\end{memberdesc}

\begin{memberdesc}{triangle}
  A triangle. Might be stroked or filled or both.
\end{memberdesc}

\begin{memberdesc}{circle}
  A circle. Might be stroked or filled or both.
\end{memberdesc}

\begin{memberdesc}{diamond}
  A diamond. Might be stroked or filled or both.
\end{memberdesc}

\class{symbol} provides some changeable symbol functions as member
variables, namely:

\begin{memberdesc}{changecross}
  attr.changelist([cross, plus, square, triangle, circle, diamond])
\end{memberdesc}

\begin{memberdesc}{changeplus}
  attr.changelist([plus, square, triangle, circle, diamond, cross])
\end{memberdesc}

\begin{memberdesc}{changesquare}
  attr.changelist([square, triangle, circle, diamond, cross, plus])
\end{memberdesc}

\begin{memberdesc}{changetriangle}
  attr.changelist([triangle, circle, diamond, cross, plus, square])
\end{memberdesc}

\begin{memberdesc}{changecircle}
  attr.changelist([circle, diamond, cross, plus, square, triangle])
\end{memberdesc}

\begin{memberdesc}{changediamond}
  attr.changelist([diamond, cross, plus, square, triangle, circle])
\end{memberdesc}

\begin{memberdesc}{changesquaretwice}
  attr.changelist([square, square, triangle, triangle, circle, circle, diamond, diamond])
\end{memberdesc}

\begin{memberdesc}{changetriangletwice}
  attr.changelist([triangle, triangle, circle, circle, diamond, diamond, square, square])
\end{memberdesc}

\begin{memberdesc}{changecircletwice}
  attr.changelist([circle, circle, diamond, diamond, square, square, triangle, triangle])
\end{memberdesc}

\begin{memberdesc}{changediamondtwice}
  attr.changelist([diamond, diamond, square, square, triangle, triangle, circle, circle])
\end{memberdesc}

The class \class{symbol} provides two changeable decorators for
alternated filling and stroking. Those are especially useful in
combination with the \method{change}-\method{twice}-symbol methods
above. They are:

\begin{memberdesc}{changestrokedfilled}
  attr.changelist([deco.stroked, deco.filled])
\end{memberdesc}

\begin{memberdesc}{changefilledstroked}
  attr.changelist([deco.filled, deco.stroked])
\end{memberdesc} % }}}

\begin{classdesc}{line}{lineattrs=[]} % {{{
  This class is a style to stroke lines in a graph.
  \var{lineattrs} is merged with \code{defaultlineattrs} which is
  a list containing the member variable \code{changelinestyle} as
  described below. An instance of \class{line} is the default style
  of the graph data classes \class{function} and \class{paramfunction}
  described in section~\ref{graph:data}.
\end{classdesc}

The class \class{line} provides a changeable line style. Its
definition is:

\begin{memberdesc}{changelinestyle}
  attr.changelist([style.linestyle.solid, style.linestyle.dashed, style.linestyle.dotted, style.linestyle.dashdotted])
\end{memberdesc} % }}}

\begin{classdesc}{impulses}{lineattrs=[], fromvalue=0, % {{{
                             frompathattrs=[], valueaxisindex=1}
  This class is a style to plot impulses. \var{lineattrs} is merged
  with \code{defaultlineattrs} which is a list containing the member
  variable \code{changelinestyle} of the \class{line} class.
  \var{fromvalue} is the baseline value of the impulses. When set to
  \code{None}, the impulses will start at the baseline. When fromvalue
  is set, \var{frompathattrs} are the stroke attributes used to show
  the impulses baseline path.
\end{classdesc} % }}}

\begin{classdesc}{errorbar}{size=0.1*unit.v\_cm, errorbarattrs=[], % {{{
                            epsilon=1e-10}
  This class is a style to stroke errorbars in a graph. \var{size} is
  the size of the caps of the errorbars and \var{errorbarattrs} are
  the stroke attributes. Errorbars and error caps are considered to be
  out of the graph when their position in graph coordinates exceeds
  the range [0:1] by more that \var{epsilon}. Out of graph caps are
  omitted and the errorbars are cut to the valid graph range.
\end{classdesc} % }}}

\begin{classdesc}{text}{textname="text", dxname=None, dyname=None, % {{{
                        dxunit=0.3*unit.v\_cm, dyunit=0.3*unit.v\_cm,
                        textdx=0*unit.v\_cm, textdy=0.3*unit.v\_cm,
                        textattrs=[]}
  This class is a style to stroke text in a graph. The
  text to be written has to be provided in the data column named
  \code{textname}. \var{textdx} and \var{textdy} are the position of the
  text with respect to the position in the graph. Alternatively you can
  specify a \code{dxname} and a \code{dyname} and provide appropriate
  data in those columns to be taken in units of \var{dxunit} and
  \var{dyunit} to specify the position of the text for each point
  separately. \var{textattrs} are text attributes for the output of
  the text. Those attributes are merged with the default attributes
  \code{textmodule.halign.center} and \code{textmodule.vshift.mathaxis}.
\end{classdesc} % }}}

\begin{classdesc}{arrow}{linelength=0.25*unit.v\_cm, % {{{
                         arrowsize=0.15*unit.v\_cm,
                         lineattrs=[], arrowattrs=[], arrowpos=0.5,
                         epsilon=1e-10}
  This class is a style to plot short lines with arrows into a
  two-dimensional graph to a given graph position. The arrow
  parameters are defined by two additional data columns named
  \code{size} and \code{angle} define the size and angle for each
  arrow. \code{size} is taken as a factor to \var{arrowsize} and
  \var{linelength}, the size of the arrow and the length of the line
  the arrow is plotted at. \code{angle} is the angle the arrow points
  to with respect to a horizontal line. The \code{angle} is taken in
  degrees and used in mathematically positive sense. \var{lineattrs}
  and \var{arrowattrs} are styles for the arrow line and arrow head,
  respectively. \var{arrowpos} defines the position of the arrow line
  with respect to the position at the graph. The default \code{0.5}
  means centered at the graph position, whereas \code{0} and \code{1}
  creates the arrows to start or end at the graph position,
  respectively. \var{epsilon} is used as a cutoff for short arrows in
  order to prevent numerical instabilities.
\end{classdesc} % }}}

\begin{classdesc}{rect}{gradient=color.gradient.Grey} % {{{
  This class is a style to plot colored rectangles into a
  two-dimensional graph. The size of the rectangles is taken from
  the data provided by the \class{range} style. The additional
  data column named \code{color} specifies the color of the rectangle
  defined by \var{gradient}. The valid color range is [0:1].

  \begin{note}
    Although this style can be used for plotting colored surfaces, it
    will lead to a huge memory footprint of \PyX{} together with a
    long running time and large outputs. Improved support for colored
    surfaces is planned for the future.
  \end{note}
\end{classdesc} % }}}

\begin{classdesc}{histogram}{lineattrs=[], steps=0, fromvalue=0, % {{{
                             frompathattrs=[], fillable=0, rectkey=0,
                             autohistogramaxisindex=0,
                             autohistogrampointpos=0.5, epsilon=1e-10}
  This class is a style to plot histograms. \var{lineattrs} is merged
  with \code{defaultlineattrs} which is \code{[deco.stroked]}. When
  \var{steps} is set, the histrogram is plotted as steps instead of
  the default being a boxed histogram. \var{fromvalue} is the baseline
  value of the histogram. When set to \code{None}, the histogram will
  start at the baseline. When fromvalue is set, \var{frompathattrs}
  are the stroke attributes used to show the histogram baseline path.

  The \var{fillable} flag changes the stoke line of the histogram to
  make it fillable properly. This is important on non-steped
  histograms or on histograms, which hit the graph boundary.
  \var{rectkey} can be set to generate a rectanglar area instead of a
  line in the graph key.

  Usually, a histogram wants a range specification (like for an
  errorbar) in one graph dimension and a value for the other graph
  dimension. By that, the widths of the histogram boxes might be
  variable. But a typical use case is, that you just provide graph
  positions for both graph dimensions. Then
  \var{autohistogramaxisindex} defines the graph dimension where the
  histogram should be plotted on top of it. (\code{0} thus means a
  histogram at the x axes and \code{1} for the y axes.) The style will
  then demand equal spaced values on this axis. The histogram boxes
  are usually centered on those values for \var{autohistogrampointpos}
  equals \code{0.5}, but they can also be aligned at the right side or
  left side of this value for \var{autohistogrampointpos} being
  \code{0} or \code{1}.

  Positions of the histograms are considered to be out of graph when
  they exceed the graph coordinate range [0:1] by more than
  \var{epsilon}.
\end{classdesc} % }}}

\begin{classdesc}{barpos}{fromvalue=None, frompathattrs=[], epsilon=1e-10} % {{{
  This class is a hidden style providing position information in a bar
  graph. Those graphs need to contain a specialized axis, namely a bar
  axis. The data column for this bar axis is named \code{Xname} where
  \code{X} is an axis name. In the other graph dimension the data
  column name must be equal to an axis name. To plot several bars in a
  single graph side by side, you need to have a nested bar axis and
  provide a tuple as data for nested bar axis.

  The bars start at \var{fromvalue} when provided. The \var{fromvalue}
  is marked by a gridline stroked using \var{frompathattrs}. Thus this
  hidden style might actually create some output. The value of a bar
  axis is considered to be out of graph when its position in graph
  coordinates exceeds the range [0:1] by more than \var{epsilon}.
\end{classdesc} % }}}

\begin{classdesc}{stackedbarpos}{stackname, addontop=0, epsilon=1e-10} % {{{
  This class is a hidden style providing position information in a bar
  graph by stacking a new bar on top of another bar. The value of the
  new bar is taken from the data column named \var{stackname}. When
  \var{addontop} is set, the values is taken relative to the previous
  top of the bar.
\end{classdesc} % }}}

\begin{classdesc}{bar}{barattrs=[]} % {{{
  This class draws bars in a bar graph. The bars are filled using
  \var{barattrs}. \var{barattrs} is merged with \code{defaultbarattrs}
  which is a list containing \code{[color.gradient.Rainbow,
  deco.stroked([color.grey.black])]}.
\end{classdesc} % }}}

\begin{classdesc}{changebar}{barattrs=[]} % {{{
  This style works like the \class{bar} style, but instead of the
  \var{barattrs} to be changed on subsequent data instances the
  \var{barattrs} are changed for each value within a single data
  instance. In the result the style can't be applied to several data
  instances. The style raises an error instead.
\end{classdesc} % }}}

\begin{classdesc}{gridpos}{index1=0, index2=1, % {{{
                        gridlines1=1, gridlines2=1, gridattrs=[],
                        epsilon=1e-10}
  This class is a hidden style providing rectangular grid information
  out of graph positions for graph dimensions \var{index1} and
  \var{index2}. Data points are considered to be out of graph when
  their position in graph coordinates exceeds the range [0:1] by more
  than \var{epsilon}. Data points are merged to a single graph
  coordinate value when their difference in graph coordinates is below
  \var{epsilon}.
\end{classdesc} % }}}

\begin{classdesc}{grid}{gridlines1=1, gridlines2=1, gridattrs=[]} % {{{
  Strokes a rectangular grid in the first grid direction, when
  \var{gridlines1} is set and in the second grid direction, when
  \var{gridlines2} is set. \var{gridattrs} is merged with
  \code{defaultgridattrs} which is a list containing the member
  variable \code{changelinestyle} of the \class{line} class.
\end{classdesc} % }}}

\begin{classdesc}{surface}{colorname="color", % {{{
                           gradient=color.gradient.Grey,
                           mincolor=None, maxcolor=None,
                           gridlines1=0.05, gridlines2=0.05,
                           gridcolor=None,
                           backcolor=color.gray.black}
  Draws a surface of a rectangular grid. Each rectangle is divided
  into 4 triangles.

  The grid can be colored using values provided by the data column
  named \var{columnname}. The values are rescaled to the range [0:1]
  using mincolor and maxcolor (which are taken from the minimal and
  maximal values, but larger bounds could be set).

  If no \var{columnname} column exists, the surface style falls back
  to a lightning coloring taking into account the angle between the
  view ray and the triangle and the distance between viewer and
  triangle. The precise conversion is defined in the
  \method{lightning} method.

  If a \var{gridcolor} is set, the rectangular grid is marked by small
  stripes of the relative (compared to each rectangle) size of
  \var{gridlines1} and \var{gridlines2} for the first and second grid
  direction, respectively.

  \var{backcolor} is used to fill triangles shown from the back. If
  \var{backcolor} is set to \code{None}, back sides are not drawn
  differently from the front sides.

  The surface is encoded using a single mesh. While this is quite
  space efficient, it has the following implications:
  \begin{itemize}
    \item All colors must use the same color space.
    \item HSB colors are not allowed, whereas Gray, RGB, and CMYK are
    allowed. You can convert HSB colors into a different color space
    before passing them to the surface.
    \item The grid itself is also constructed out of triangles. The
    grid is transformed along with the triangles thus looking quite
    different from a stroked grid (as done by the grid style).
    \item Occlusion is handled by proper painting order.
    \item Color changes are continuous (in the selected color
    space) for each triangle.
  \end{itemize}
\end{classdesc} % }}}

% }}}

\section{Module \module{graph.key}: Keys} % {{{
\label{graph:key}

\declaremodule{}{graph.key}
\modulesynopsis{Graph keys}

The following class provides a key, whose instances can be passed to
the constructor keyword argument \code{key} of a graph. The class is
implemented in \module{graph.key}.

\begin{classdesc}{key}{dist=0.2*unit.v\_cm,
                       pos="tr", hpos=None, vpos=None,
                       hinside=1, vinside=1,
                       hdist=0.6*unit.v\_cm,
                       vdist=0.4*unit.v\_cm,
                       symbolwidth=0.5*unit.v\_cm,
                       symbolheight=0.25*unit.v\_cm,
                       symbolspace=0.2*unit.v\_cm,
                       textattrs=[],
                       columns=1, columndist=0.5*unit.v\_cm,
                       border=0.3*unit.v\_cm, keyattrs=None}
  This class writes the title of the data in a plot together with a
  small illustration of the style. The style is responsible for its
  illustration.

  \var{dist} is a visual length and a distance between the key
  entries. \var{pos} is the position of the key with respect to the
  graph. Allowed values are combinations of \code{"t"} (top),
  \code{"m"} (middle) and \code{"b"} (bottom) with \code{"l"} (left),
  \code{"c"} (center) and \code{"r"} (right). Alternatively, you may
  use \var{hpos} and \var{vpos} to specify the relative position
  using the range [0:1]. \var{hdist} and \var{vdist} are the distances
  from the specified corner of the graph. \var{hinside} and
  \var{vinside} are numbers to be set to 0 or 1 to define whether the
  key should be placed horizontally and vertically inside of the graph
  or not.

  \var{symbolwidth} and \var{symbolheight} are passed to the style to
  control the size of the style illustration. \var{symbolspace} is the
  space between the illustration and the text. \var{textattrs} are
  attributes for the text creation. They are merged with
  \code{[text.vshift.mathaxis]}.

  \var{columns} is a number of columns of the graph key and
  \var{columndist} is the distance between those columns.

  When \var{keyattrs} is set to contain some draw attributes, the
  graph key is enlarged by \var{border} and the key area is drawn
  using \var{keyattrs}.
\end{classdesc} % }}} % }}}

% vim:fdm=marker
