pyrocko.plot.gmtpy¶
A Python interface to GMT.
Module Attributes
Unit cm in points. |
|
Unit inch in points. |
Functions
|
Generate a string for GMT option arguments expecting a color. |
This function should be used for debugging output only - it could be insecure. |
|
|
This function should be used for debugging output only - it could be insecure. |
|
Get default GMT configuration dict for given version. |
|
Get the built-in gmtdefaults. |
|
Grid tabular XYZ data by binning. |
|
Read COARDS compliant netcdf (grd) file. |
|
Write COARDS compliant netcdf (grd) file. |
Classes
|
Ax description with autoscaling capabilities. |
|
A layout manager which centers its single child widget. |
|
A layout manager containing a center widget sorrounded by four margin widgets. |
|
A thin wrapper to GMT command execution. |
|
A layout manager which arranges its sub-widgets in a grid. |
|
Sizing policy implementing a minimal size, plus a desire to grow. |
|
Abstract base class providing template interpolation, accessible as attributes. |
|
File-like object to buffer data. |
|
2D/3D autoscaling and ax annotation facility. |
|
Utility class to turn tables into lines. |
|
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 correspondinggmtpy.graph_colors[x]
or black returned. If it is a string and the correspondinggmtpy.tango_colors[x]
exists, this is returned, or the string is passed through. Ifx
is a tuple, it is transformed into the string form which GMT expects.
- savegrd(x, y, z, filename, title=None, naming='xy')[source]¶
Write 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.
- 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.
- 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
andAutoScaler
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
isTrue
, values which are suitable to be printed on the axes are returned. This means that in the latter case, theAx.scaled_unit
andAx.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()
andget_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 thewidth()
andheight()
methods. Thebbox()
method can be used to create a PostScript bounding box from the widgets border, e.g. for use inGMT.save()
.The convention is, that all sizes are given in PostScript points. Conversion factors are provided as constants
inch
andcm
in the gmtpy module.- set_parent(parent)[source]¶
Set the parent widget.
This method should not be called directly. The
set_widget()
methods are responsible for calling this.
- 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
andoffset
, returnnew_size
andnew_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.
- 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'
.
- class CenterLayout(horizontal=None, vertical=None)[source]¶
Bases:
Widget
A layout manager which centers its single child widget.
The child widget may be oversized.
- 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()
andset_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_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.
- 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.
- class TableLiner(in_columns=None, in_rows=None, encoding='utf-8')[source]¶
Bases:
object
Utility class to turn tables into lines.
- 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. Theversion
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
andaddargs
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. Ifname
is given, returns a path ending in thatname
.
- 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 ifoversample
is set to a value higher than one. The output image size can also be controlled by settingwidth
,height
orsize
instead ofresolution
. Whensize
is given, the image is scaled so thatmax(width, height) == size
.The bounding box is set according to the values given in
bbox
.
- 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), aFrameLayout
is centered on the page, whose size is controlled by its center widget’s size plus the margins of theFrameLayout
.If PAPER_MEDIA indicates, that a custom page size is wanted by starting with
'Custom_'
, aFrameLayout
is used to fill the complete page. The center widget’s size is then controlled by the page’s size minus the margins of theFrameLayout
.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 callingWidget.get_parent()
on the returned layout.