pyrocko.plot.gmtpy

A Python interface to GMT.

Module Attributes

inch

Unit cm in points.

cm

Unit inch in points.

Functions

color([x])

Generate a string for GMT option arguments expecting a color.

escape_shell_arg(s)

This function should be used for debugging output only - it could be insecure.

escape_shell_args(args)

This function should be used for debugging output only - it could be insecure.

gmt_default_config(version)

Get default GMT configuration dict for given version.

gmtdefaults_as_text([version])

Get the built-in gmtdefaults.

griddata_auto(x, y, z[, mode])

Grid tabular XYZ data by binning.

loadgrd(filename)

Read COARDS compliant netcdf (grd) file.

savegrd(x, y, z, filename[, title, naming])

Write COARDS compliant netcdf (grd) file.

Classes

Ax([label, unit, scaled_unit_factor, ...])

Ax description with autoscaling capabilities.

CenterLayout([horizontal, vertical])

A layout manager which centers its single child widget.

FrameLayout([horizontal, vertical])

A layout manager containing a center widget sorrounded by four margin widgets.

GMT([config, kontinue, version, ...])

A thin wrapper to GMT command execution.

GridLayout([nx, ny, horizontal, vertical])

A layout manager which arranges its sub-widgets in a grid.

GumSpring([minimal, grow])

Sizing policy implementing a minimal size, plus a desire to grow.

Guru()

Abstract base class providing template interpolation, accessible as attributes.

LineStreamChopper(liner)

File-like object to buffer data.

ScaleGuru([data_tuples, axes, aspect, ...])

2D/3D autoscaling and ax annotation facility.

TableLiner([in_columns, in_rows, encoding])

Utility class to turn tables into lines.

Widget([horizontal, vertical, parent])

Base class of the gmtpy layout system.

escape_shell_arg(s)[source]

This function should be used for debugging output only - it could be insecure.

escape_shell_args(args)[source]

This function should be used for debugging output only - it could be insecure.

inch = 72.0

Unit cm in points.

cm = 28.346456692913385

Unit inch in points.

color(x=None)[source]

Generate a string for GMT option arguments expecting a color.

If x is None, a random color is returned. If it is an integer, the corresponding gmtpy.graph_colors[x] or black returned. If it is a string and the corresponding gmtpy.tango_colors[x] exists, this is returned, or the string is passed through. If x is a tuple, it is transformed into the string form which GMT expects.

gmt_default_config(version)[source]

Get default GMT configuration dict for given version.

gmtdefaults_as_text(version='newest')[source]

Get the built-in gmtdefaults.

savegrd(x, y, z, filename, title=None, naming='xy')[source]

Write COARDS compliant netcdf (grd) file.

loadgrd(filename)[source]

Read COARDS compliant netcdf (grd) file.

griddata_auto(x, y, z, mode=None)[source]

Grid tabular XYZ data by binning.

This function does some extra work to guess the size of the grid. This should work fine if the input values are already defined on an rectilinear grid, even if data points are missing or duplicated. This routine also tries to detect a random distribution of input data and in that case creates a grid of size sqrt(N) x sqrt(N).

The points do not have to be given in any particular order. Grid nodes without data are assigned the NaN value. If multiple data points map to the same grid node, their average is assigned to the grid node.

class Guru[source]

Bases: object

Abstract base class providing template interpolation, accessible as attributes.

Classes deriving from this one, have to implement a get_params() method, which is called to get a dict to do ordinary "%(key)x"-substitutions. The deriving class must also provide a dict with the templates.

get_params(ax_projection=False)[source]

To be implemented in subclasses.

class Ax(label='', unit='', scaled_unit_factor=1.0, scaled_unit='', limits=None, masking=True, **kwargs)[source]

Bases: AutoScaler

Ax description with autoscaling capabilities.

The ax is described by the AutoScaler public attributes, plus the following additional attributes (with default values given in paranthesis):

label

Ax label (without unit).

unit

Physical unit of the data attached to this ax.

scaled_unit

(see below)

scaled_unit_factor

Scaled physical unit and factor between unit and scaled_unit so that

unit = scaled_unit_factor x scaled_unit.

(E.g. if unit is ‘m’ and data is in the range of nanometers, you may want to set the scaled_unit to ‘nm’ and the scaled_unit_factor to 1e9.)

limits

If defined, fix range of ax to limits=(min,max).

masking

If true and if there is a limit on the ax, while calculating ranges, the data points are masked such that data points outside of this axes limits are not used to determine the range of another dependant ax.

label_str(exp, unit)[source]

Get label string including the unit and multiplier.

make_params(data_range, ax_projection=False, override_mode=None, override_scaled_unit_factor=None)[source]

Get minimum, maximum, increment and label string for ax display.’

Returns minimum, maximum, increment and label string including unit and multiplier for given data range.

If ax_projection is True, values suitable to be displayed on the ax are returned, e.g. min, max and inc are returned in scaled units. Otherwise the values are returned in the original units, without any scaling applied.

class ScaleGuru(data_tuples=None, axes=None, aspect=None, percent_interval=None, copy_from=None)[source]

Bases: Guru

2D/3D autoscaling and ax annotation facility.

Instances of this class provide automatic determination of plot ranges, tick increments and scaled annotations, as well as label/unit handling. It can in particular be used to automatically generate the -R and -B option arguments, which are required for most GMT commands.

It extends the functionality of the Ax and AutoScaler classes at the level, where it can not be handled anymore by looking at a single dimension of the dataset’s data, e.g.:

  • The ability to impose a fixed aspect ratio between two axes.

  • Recalculation of data range on non-limited axes, when there are limits imposed on other axes.

get_params(ax_projection=False)[source]

Get dict with output parameters.

For each data dimension, ax minimum, maximum, increment and a label string (including unit and exponential factor) are determined. E.g. in for the first dimension the output dict will contain the keys 'xmin', 'xmax', 'xinc', and 'xlabel'.

Normally, values corresponding to the scaling of the raw data are produced, but if ax_projection is True, values which are suitable to be printed on the axes are returned. This means that in the latter case, the Ax.scaled_unit and Ax.scaled_unit_factor attributes as set on the axes are respected and that a common 10^x factor is factored out and put to the label string.

class GumSpring(minimal=None, grow=None)[source]

Bases: object

Sizing policy implementing a minimal size, plus a desire to grow.

class Widget(horizontal=None, vertical=None, parent=None)[source]

Bases: Guru

Base class of the gmtpy layout system.

The Widget class provides the basic functionality for the nesting and placing of elements on the output page, and maintains the sizing policies of each element. Each of the layouts defined in gmtpy is itself a Widget.

Sizing of the widget is controlled by get_min_size() and get_grow() which should be overloaded in derived classes. The basic behaviour of a Widget instance is to have a vertical and a horizontal minimum size which default to zero, as well as a vertical and a horizontal desire to grow, represented by floats, which default to 1.0. Additionally an aspect ratio constraint may be imposed on the Widget.

After layouting, the widget provides its width, height, x-offset and y-offset in various ways. Via the Guru interface (see Guru class), templates for the -X, -Y and -J option arguments used by GMT arguments are provided. The defaults are suitable for plotting of linear (-JX) plots. Other projections can be selected by giving an appropriate ‘J’ template, or by manual construction of the -J option, e.g. by utilizing the width() and height() methods. The bbox() method can be used to create a PostScript bounding box from the widgets border, e.g. for use in GMT.save().

The convention is, that all sizes are given in PostScript points. Conversion factors are provided as constants inch and cm in the gmtpy module.

set_widget()[source]

To be implemented in subclasses.

set_parent(parent)[source]

Set the parent widget.

This method should not be called directly. The set_widget() methods are responsible for calling this.

get_parent()[source]

Get the widgets parent widget.

get_root()[source]

Get the root widget in the layout hierarchy.

set_horizontal(minimal=None, grow=None)[source]

Set the horizontal sizing policy of the Widget.

Parameters:
  • minimal – new minimal width of the widget

  • grow – new horizontal grow disire of the widget

set_vertical(minimal=None, grow=None)[source]

Set the horizontal sizing policy of the Widget.

Parameters:
  • minimal – new minimal height of the widget

  • grow – new vertical grow disire of the widget

set_aspect(aspect=None)[source]

Set aspect constraint on the widget.

The aspect is given as height divided by width.

set_policy(minimal=(None, None), grow=(None, None), aspect=None)[source]

Shortcut to set sizing and aspect constraints in a single method call.

legalize(size, offset)[source]

Get legal size for widget.

Returns: (new_size, new_offset)

Given a box as size and offset, return new_size and new_offset, such that the widget’s sizing and aspect constraints are fullfilled. The returned box is centered on the given input box.

get_min_size()[source]

Get minimum size of widget.

Used by the layout managers. Should be overloaded in derived classes.

get_grow()[source]

Get widget’s desire to grow.

Used by the layout managers. Should be overloaded in derived classes.

set_size(size, offset)[source]

Set the widget’s current size.

Should not be called directly. It is the layout manager’s responsibility to call this.

get_corners(descend=False)[source]

Get coordinates of the corners of the widget.

Returns list with coordinate tuples.

If descend is True, the returned list will contain corner coordinates of all sub-widgets.

get_sizes()[source]

Get sizes of this widget and all it’s children.

Returns a list with size tuples.

do_layout()[source]

Triggers layouting of the widget hierarchy, if needed.

get_children()[source]

Get sub-widgets contained in this widget.

Returns a list of widgets.

get_size()[source]

Get current size and position of the widget.

Triggers layouting and returns ((width, height), (xoffset, yoffset))

get_params()[source]

Get current size and position of the widget.

Triggers layouting and returns dict with keys 'xoffset', 'yoffset', 'width' and 'height'.

width()[source]

Get current width of the widget.

Triggers layouting and returns width.

height()[source]

Get current height of the widget.

Triggers layouting and return height.

bbox()[source]

Get PostScript bounding box for this widget.

Triggers layouting and returns values suitable to create PS bounding box, representing the widgets current size and position.

dirtyfy()[source]

Set dirty flag on top level widget in the hierarchy.

Called by various methods, to indicate, that the widget hierarchy needs new layouting.

class CenterLayout(horizontal=None, vertical=None)[source]

Bases: Widget

A layout manager which centers its single child widget.

The child widget may be oversized.

set_widget(widget=None)[source]

Set the child widget, which shall be centered.

class FrameLayout(horizontal=None, vertical=None)[source]

Bases: Widget

A layout manager containing a center widget sorrounded by four margin widgets.

+---------------------------+
|             top           |
+---------------------------+
|      |            |       |
| left |   center   | right |
|      |            |       |
+---------------------------+
|           bottom          |
+---------------------------+

This layout manager does a little bit of extra effort to maintain the aspect constraint of the center widget, if this is set. It does so, by allowing for a bit more flexibility in the sizing of the margins. Two shortcut methods are provided to set the margin sizes in one shot: set_fixed_margins() and set_min_margins(). The first sets the margins to fixed sizes, while the second gives them a minimal size and a (neglectably) small desire to grow. Using the latter may be useful when setting an aspect constraint on the center widget, because this way the maximum size of the center widget may be controlled without creating empty spaces between the widgets.

set_fixed_margins(left, right, top, bottom)[source]

Give margins fixed size constraints.

set_min_margins(left, right, top, bottom, grow=0.0001)[source]

Give margins a minimal size and the possibility to grow.

The desire to grow is set to a very small number.

set_widget(which='center', widget=None)[source]

Set one of the sub-widgets.

which should be one of 'left', 'right', 'top', 'bottom' or 'center'.

get_widget(which='center')[source]

Get one of the sub-widgets.

which should be one of 'left', 'right', 'top', 'bottom' or 'center'.

class GridLayout(nx=2, ny=2, horizontal=None, vertical=None)[source]

Bases: Widget

A layout manager which arranges its sub-widgets in a grid.

The grid spacing is flexible and based on the sizing policies of the contained sub-widgets. If an equidistant grid is needed, the sizing policies of the sub-widgets have to be set equally.

The height of each row and the width of each column is derived from the sizing policy of the largest sub-widget in the row or column in question. The algorithm is not very sophisticated, so conflicting sizing policies might not be resolved optimally.

set_widget(ix, iy, widget=None)[source]

Set one of the sub-widgets.

Sets the sub-widget in column ix and row iy. The indices are counted from zero.

get_widget(ix, iy)[source]

Get one of the sub-widgets.

Gets the sub-widget from column ix and row iy. The indices are counted from zero.

class TableLiner(in_columns=None, in_rows=None, encoding='utf-8')[source]

Bases: object

Utility class to turn tables into lines.

class LineStreamChopper(liner)[source]

Bases: object

File-like object to buffer data.

class GMT(config=None, kontinue=None, version='newest', config_papersize=None, eps_mode=False)[source]

Bases: object

A thin wrapper to GMT command execution.

A dict config may be given to override some of the default GMT parameters. The version argument may be used to select a specific GMT version, which should be used with this GMT instance. The selected version of GMT has to be installed on the system, must be supported by gmtpy and gmtpy must know where to find it.

Each instance of this class is used for the task of producing one PS or PDF output file.

Output of a series of GMT commands is accumulated in memory and can then be saved as PS or PDF file using the save() method.

GMT commands are accessed as method calls to instances of this class. See the __getattr__() method for details on how the method’s arguments are translated into options and arguments for the GMT command.

Associated with each instance of this class, a temporary directory is created, where temporary files may be created, and which is automatically deleted, when the object is destroyed. The tempfilename() method may be used to get a random filename in the instance’s temporary directory.

Any .gmtdefaults files are ignored. The GMT class uses a fixed set of defaults, which may be altered via an argument to the constructor. If possible, GMT is run in ‘isolation mode’, which was introduced with GMT version 4.2.2, by setting GMT_TMPDIR to the instance’s temporary directory. With earlier versions of GMT, problems may arise with parallel execution of more than one GMT instance.

Each instance of the GMT class may pick a specific version of GMT which shall be used, so that, if multiple versions of GMT are installed on the system, different versions of GMT can be used simultaneously such that backward compatibility of the scripts can be maintained.

__getattr__(command)[source]

Maps to call self._gmtcommand(command, *addargs, **kwargs).

Execute arbitrary GMT command.

Run a GMT command and by default append its postscript output to the output file maintained by the GMT instance on which this method is called.

Except for a few keyword arguments listed below, any kwargs and addargs are converted into command line options and arguments and passed to the GMT command. Numbers in keyword arguments are converted into strings. E.g. S=10 is translated into '-S10'. Tuples of numbers or strings are converted into strings where the elements of the tuples are separated by slashes ‘/’. E.g. R=(10, 10, 20, 20) is translated into '-R10/10/20/20'. Options with a boolean argument are only appended to the GMT command, if their values are True.

If no output redirection is in effect, the -K and -O options are handled by gmtpy and thus should not be specified. Use out_discard=True if you don’t want -K or -O beeing added, but are not interested in the output.

The standard input of the GMT process is fed by data selected with one of the following in_* keyword arguments:

in_stream

Data is read from an open file like object.

in_filename

Data is read from the given file.

in_string

String content is dumped to the process.

in_columns

A 2D nested iterable whose elements can be accessed as in_columns[icolumn][irow] is converted into an ascii table, which is fed to the process.

in_rows

A 2D nested iterable whos elements can be accessed as in_rows[irow][icolumn] is converted into an ascii table, which is fed to the process.

The standard output of the GMT process may be redirected by one of the following options:

out_stream

Output is fed to an open file like object.

out_filename

Output is dumped to the given file.

out_discard

If True, output is dumped to /dev/null.

Additional keyword arguments:

config

Dict with GMT defaults which override the currently active set of defaults exclusively during this call.

finish

If True, the postscript file, which is maintained by the GMT instance is finished, and no further plotting is allowed.

suppress_defaults

Suppress appending of the '+gmtdefaults' option to the command.

tempfilename(name=None)[source]

Get filename for temporary file in the private temp directory.

If no name argument is given, a random name is picked. If name is given, returns a path ending in that name.

tempfile(name=None)[source]

Create and open a file in the private temp directory.

save(filename=None, bbox=None, resolution=150, oversample=2.0, width=None, height=None, size=None, crop_eps_mode=False, psconvert=False)[source]

Finish and save figure as PDF, PS or PPM file.

If filename ends with '.pdf' a PDF file is created by piping the GMT output through gmtpy-epstopdf.

If filename ends with '.png' a PNG file is created by running gmtpy-epstopdf, pdftocairo and convert. resolution specifies the resolution in DPI for raster file formats. Rasterization is done at a higher resolution if oversample is set to a value higher than one. The output image size can also be controlled by setting width, height or size instead of resolution. When size is given, the image is scaled so that max(width, height) == size.

The bounding box is set according to the values given in bbox.

get_command_log()[source]

Get the command log.

page_size_points()[source]

Try to get paper size of output postscript file in points.

default_layout(with_palette=False)[source]

Get a default layout for the output page.

One of three different layouts is choosen, depending on the PAPER_MEDIA setting in the GMT configuration dict.

If PAPER_MEDIA ends with a '+' (EPS output is selected), a FrameLayout is centered on the page, whose size is controlled by its center widget’s size plus the margins of the FrameLayout.

If PAPER_MEDIA indicates, that a custom page size is wanted by starting with 'Custom_', a FrameLayout is used to fill the complete page. The center widget’s size is then controlled by the page’s size minus the margins of the FrameLayout.

In any other case, two FrameLayouts are nested, such that the outer layout attaches a 1 cm (printer) margin around the complete page, and the inner FrameLayout’s center widget takes up as much space as possible under the constraint, that an aspect ratio of 1/golden_ratio is preserved.

In any case, a reference to the innermost FrameLayout instance is returned. The top-level layout can be accessed by calling Widget.get_parent() on the returned layout.

draw_layout(layout)[source]

Use psxy to draw layout; for debugging