Skip to content

Commit 2081516

Browse files
lhoupertweiji14seismanmichaelgrundMeghan Jones
authored
Wrap velo (#525)
Add `velo` function for plotting velocity vectors, crosses, anisotropy bars, and wedges. Original GMT velo function can be found at https://docs.generic-mapping-tools.org/6.1/supplements/geodesy/velo.html * clarify the type of data input * raise error if alias S is not defined * Refactor velo to use virtualfile_from_data and add three more unit tests * Alias panel (c) for velo, and lightly edit some docstrings * Alias scale (H), intensity (I) and zvalue (Z) from GMT 6.2.0 Update docstring to include new options in `velo` from the upcoming GMT 6.2.0 that were added in GenericMappingTools/gmt#4970, GenericMappingTools/gmt#4901, and GenericMappingTools/gmt#4907. Removed the default vector="+p1p+e" argument, and formatted docstring to have nested lists to be nicer looking. * Fix typos and add intersphinx mappings * Update the frame, region, projection and color of velo example * Rename alias intensity for -I to shading * Rename alias facecolor for -G to color * Move docstring for projection (J) and region (R) up a bit * Rename alias to spec (S) and update baseline images for GMT 6.2.0rc1 * Mark fig.velo tests with xfail * Rename alias uncertainty_color to uncertaintycolor for parameter E * Move velo_arrow_ellipse.py under "Seismology and Geodesy" category Co-authored-by: Wei Ji <[email protected]> Co-authored-by: Dongdong Tian <[email protected]> Co-authored-by: Michael Grund <[email protected]> Co-authored-by: Meghan Jones <[email protected]>
1 parent 53caa74 commit 2081516

File tree

8 files changed

+390
-0
lines changed

8 files changed

+390
-0
lines changed

doc/api/index.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ Plotting data and laying out the map:
4343
Figure.solar
4444
Figure.subplot
4545
Figure.text
46+
Figure.velo
4647
Figure.wiggle
4748

4849
Color palette table generation:
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""
2+
Velocity arrows and confidence ellipses
3+
---------------------------------------
4+
5+
The :meth:`pygmt.Figure.velo` method can be used to plot mean velocity arrows
6+
and confidence ellipses. The example below plots red velocity arrows with
7+
light-blue confidence ellipses outlined in red with the east_velocity x
8+
north_velocity used for the station names. Note that the velocity arrows are
9+
scaled by 0.2 and the 39% confidence limit will give an ellipse which fits
10+
inside a rectangle of dimension east_sigma by north_sigma.
11+
"""
12+
13+
import pandas as pd
14+
import pygmt
15+
16+
fig = pygmt.Figure()
17+
df = pd.DataFrame(
18+
data={
19+
"x": [0, -8, 0, -5, 5, 0],
20+
"y": [-8, 5, 0, -5, 0, -5],
21+
"east_velocity": [0, 3, 4, 6, -6, 6],
22+
"north_velocity": [0, 3, 6, 4, 4, -4],
23+
"east_sigma": [4, 0, 4, 6, 6, 6],
24+
"north_sigma": [6, 0, 6, 4, 4, 4],
25+
"correlation_EN": [0.5, 0.5, 0.5, 0.5, -0.5, -0.5],
26+
"SITE": ["0x0", "3x3", "4x6", "6x4", "-6x4", "6x-4"],
27+
}
28+
)
29+
fig.velo(
30+
data=df,
31+
region=[-10, 8, -10, 6],
32+
pen="0.6p,red",
33+
uncertaintycolor="lightblue1",
34+
line=True,
35+
spec="e0.2/0.39/18",
36+
frame=["WSne", "2g2f"],
37+
projection="x0.8c",
38+
vector="0.3c+p1p+e+gred",
39+
)
40+
41+
fig.show()

pygmt/figure.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,7 @@ def _repr_html_(self):
426426
solar,
427427
subplot,
428428
text,
429+
velo,
429430
wiggle,
430431
)
431432

pygmt/src/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
from pygmt.src.subplot import set_panel, subplot
3333
from pygmt.src.surface import surface
3434
from pygmt.src.text import text_ as text # "text" is an argument within "text_"
35+
from pygmt.src.velo import velo
3536
from pygmt.src.which import which
3637
from pygmt.src.wiggle import wiggle
3738
from pygmt.src.x2sys_cross import x2sys_cross

pygmt/src/velo.py

Lines changed: 247 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,247 @@
1+
"""
2+
velo - Plot velocity vectors, crosses, anisotropy bars, and wedges.
3+
"""
4+
import numpy as np
5+
import pandas as pd
6+
from pygmt.clib import Session
7+
from pygmt.exceptions import GMTInvalidInput
8+
from pygmt.helpers import build_arg_string, fmt_docstring, kwargs_to_strings, use_alias
9+
10+
11+
@fmt_docstring
12+
@use_alias(
13+
A="vector",
14+
B="frame",
15+
C="cmap",
16+
D="rescale",
17+
E="uncertaintycolor",
18+
G="color",
19+
H="scale",
20+
I="shading",
21+
J="projection",
22+
L="line",
23+
N="no_clip",
24+
R="region",
25+
S="spec",
26+
U="timestamp",
27+
V="verbose",
28+
W="pen",
29+
X="xshift",
30+
Y="yshift",
31+
Z="zvalue",
32+
c="panel",
33+
p="perspective",
34+
t="transparency",
35+
)
36+
@kwargs_to_strings(R="sequence", c="sequence_comma", i="sequence_comma", p="sequence")
37+
def velo(self, data=None, **kwargs):
38+
r"""
39+
Plot velocity vectors, crosses, anisotropy bars, and wedges.
40+
41+
Reads data values from files, :class:`numpy.ndarray` or
42+
:class:`pandas.DataFrame` and plots the selected geodesy symbol on a map.
43+
You may choose from velocity vectors and their uncertainties, rotational
44+
wedges and their uncertainties, anisotropy bars, or strain crosses. Symbol
45+
fills or their outlines may be colored based on constant parameters or via
46+
color lookup tables.
47+
48+
Must provide ``data`` and ``spec``.
49+
50+
Full option list at :gmt-docs:`supplements/geodesy/velo.html`
51+
52+
{aliases}
53+
54+
Parameters
55+
----------
56+
data : str or numpy.ndarray or pandas.DataFrame
57+
Either a file name, a 2D :class:`numpy.ndarray` or a
58+
:class:`pandas.DataFrame` with the tabular data. Note that text columns
59+
are only supported with file or pandas DataFrame inputs.
60+
61+
spec: str
62+
Selects the meaning of the columns in the data file and the figure to
63+
be plotted. In all cases, the scales are in data units per length unit
64+
and sizes are in length units (default length unit is controlled by
65+
:gmt-term:`PROJ_LENGTH_UNIT` unless **c**, **i**, or **p** is
66+
appended).
67+
68+
- **e**\ [*velscale*/]\ *confidence*\ [**+f**\ *font*]
69+
70+
Velocity ellipses in (N,E) convention. The *velscale* sets the
71+
scaling of the velocity arrows. If *velscale* is not given then we
72+
read it from the data file as an extra column. The *confidence* sets
73+
the 2-dimensional confidence limit for the ellipse, e.g. 0.95 for 95%
74+
confidence ellipse. Use **+f** to set the font and size of the text
75+
[Default is 9p,Helvetica,black]; give **+f**\ 0 to deactivate
76+
labeling. The arrow will be drawn with the pen attributes specified
77+
by the ``pen`` option and the arrow-head can be colored via
78+
``color``. The ellipse will be filled with the color or shade
79+
specified by the ``uncertaintycolor`` option [Default is
80+
transparent], and its outline will be drawn if ``line`` is selected
81+
using the pen selected (by ``pen`` if not given by ``line``).
82+
Parameters are expected to be in the following columns:
83+
84+
- **1**,\ **2**: longitude, latitude of station
85+
- **3**,\ **4**: eastward, northward velocity
86+
- **5**,\ **6**: uncertainty of eastward, northward velocities
87+
(1-sigma)
88+
- **7**: correlation between eastward and northward components
89+
- **Trailing text**: name of station (optional)
90+
91+
- **n**\ [*barscale*]
92+
93+
Anisotropy bars. *barscale* sets the scaling of the bars. If
94+
*barscale* is not given then we read it from the data file as an
95+
extra column. Parameters are expected to be in the following columns:
96+
97+
- **1**,\ **2**: longitude, latitude of station
98+
- **3**,\ **4**: eastward, northward components of anisotropy
99+
vector
100+
101+
- **r**\ [*velscale*/]\ *confidence*\ [**+f**\ *font*]
102+
103+
Velocity ellipses in rotated convention. The *velscale* sets the
104+
scaling of the velocity arrows. If *velscale* is not given then we
105+
read it from the data file as an extra column. The *confidence* sets
106+
the 2-dimensional confidence limit for the ellipse, e.g. 0.95 for 95%
107+
confidence ellipse. Use **+f** to set the font and size of the text
108+
[Default is 9p,Helvetica,black]; give **+f**\ 0 to deactivate
109+
labeling. The arrow will be drawn with the pen attributes specified
110+
by the ``pen`` option and the arrow-head can be colored via
111+
``color``. The ellipse will be filled with the color or shade
112+
specified by the ``uncertaintycolor`` option [Default is
113+
transparent], and its outline will be drawn if ``line`` is selected
114+
using the pen selected (by ``pen`` if not given by ``line``).
115+
Parameters are expected to be in the following columns:
116+
117+
- **1**,\ **2**: longitude, latitude of station
118+
- **3**,\ **4**: eastward, northward velocity
119+
- **5**,\ **6**: semi-major, semi-minor axes
120+
- **7**: counter-clockwise angle, in degrees, from horizontal axis
121+
to major axis of ellipse.
122+
- **Trailing text**: name of station (optional)
123+
124+
- **w**\ [*wedgescale*/]\ *wedgemag*
125+
126+
Rotational wedges. The *wedgescale* sets the size of the wedges. If
127+
*wedgescale* is not given then we read it from the data file as an
128+
extra column. Rotation values are multiplied by *wedgemag* before
129+
plotting. For example, setting *wedgemag* to 1.e7 works well for
130+
rotations of the order of 100 nanoradians/yr. Use ``color`` to set
131+
the fill color or shade for the wedge, and ``uncertaintycolor`` to
132+
set the color or shade for the uncertainty. Parameters are expected
133+
to be in the following columns:
134+
135+
- **1**,\ **2**: longitude, latitude of station
136+
- **3**: rotation in radians
137+
- **4**: rotation uncertainty in radians
138+
139+
- **x**\ [*cross_scale*]
140+
141+
Strain crosses. The *cross_scale* sets the size of the cross. If
142+
*cross_scale* is not given then we read it from the data file as an
143+
extra column. Parameters are expected to be in the following columns:
144+
145+
- **1**,\ **2**: longitude, latitude of station
146+
- **3**: eps1, the most extensional eigenvalue of strain tensor,
147+
with extension taken positive.
148+
- **4**: eps2, the most compressional eigenvalue of strain tensor,
149+
with extension taken positive.
150+
- **5**: azimuth of eps2 in degrees CW from North.
151+
152+
{J}
153+
{R}
154+
vector : bool or str
155+
Modify vector parameters. For vector heads, append vector head *size*
156+
[Default is 9p]. See
157+
:gmt-docs:`supplements/geodesy/velo.html#vector-attributes` for
158+
specifying additional attributes.
159+
{B}
160+
{CPT}
161+
rescale : str
162+
can be used to rescale the uncertainties of velocities (``spec='e'``
163+
and ``spec='r'``) and rotations (``spec='w'``). Can be combined with
164+
the ``confidence`` variable.
165+
uncertaintycolor : str
166+
Sets the color or shade used for filling uncertainty wedges
167+
(``spec='w'``) or velocity error ellipses (``spec='e'`` or
168+
``spec='r'``). If ``uncertaintycolor`` is not specified, the
169+
uncertainty regions will be transparent. **Note**: Using ``cmap`` and
170+
``zvalue='+e'`` will update the uncertainty fill color based on the
171+
selected measure in ``zvalue`` [magnitude error]. More details at
172+
:gmt-docs:`cookbook/features.html#gfill-attrib`.
173+
color : str
174+
Select color or pattern for filling of symbols [Default is no fill].
175+
**Note**: Using ``cmap`` (and optionally ``zvalue``) will update the
176+
symbol fill color based on the selected measure in ``zvalue``
177+
[magnitude]. More details at
178+
:gmt-docs:`cookbook/features.html#gfill-attrib`.
179+
scale : float or bool
180+
[*scale*].
181+
Scale symbol sizes and pen widths on a per-record basis using the
182+
*scale* read from the data set, given as the first column after the
183+
(optional) *z* and *size* columns [Default is no scaling]. The symbol
184+
size is either provided by ``spec`` or via the input *size* column.
185+
Alternatively, append a constant *scale* that should be used instead of
186+
reading a scale column.
187+
shading : float or bool
188+
*intens*.
189+
Use the supplied *intens* value (nominally in the -1 to +1 range) to
190+
modulate the symbol fill color by simulating illumination [Default is
191+
none]. If *intens* is not provided we will instead read the intensity
192+
from an extra data column after the required input columns determined
193+
by ``spec``.
194+
line: str
195+
[*pen*\ [**+c**\ [**f**\|\ **l**]]].
196+
Draw lines. Ellipses and rotational wedges will have their outlines
197+
drawn using the current pen (see ``pen``). Alternatively, append a
198+
separate pen to use for the error outlines. If the modifier **+cl** is
199+
appended then the color of the pen is updated from the CPT (see
200+
``cmap``). If instead modifier **+cf** is appended then the color from
201+
the cpt file is applied to error fill only [Default]. Use just **+c**
202+
to set both pen and fill color.
203+
no_clip: bool or str
204+
Do NOT skip symbols that fall outside the frame boundary specified
205+
by ``region``. [Default plots symbols inside frame only].
206+
{U}
207+
{V}
208+
pen : str
209+
[*pen*][**+c**\ [**f**\|\ **l**]].
210+
Set pen attributes for velocity arrows, ellipse circumference and fault
211+
plane edges. [Defaults: width = default, color = black, style = solid].
212+
If the modifier **+cl** is appended then the color of the pen is
213+
updated from the CPT (see ``cmap``). If instead modifier **+cf** is
214+
appended then the color from the cpt file is applied to symbol fill
215+
only [Default]. Use just **+c** to set both pen and fill color.
216+
{XY}
217+
zvalue : str
218+
[**m**\|\ **e**\|\ **n**\|\ **u**\ ][**+e**].
219+
Select the quantity that will be used with the CPT given via ``cmap``
220+
to set the fill color. Choose from **m**\ agnitude (vector magnitude
221+
or rotation magnitude), **e**\ ast-west velocity, **n**\ orth-south
222+
velocity, or **u**\ ser-supplied data column (supplied after the
223+
required columns). To instead use the corresponding error estimates
224+
(i.e., vector or rotation uncertainty) to lookup the color and paint
225+
the error ellipse or wedge instead, append **+e**.
226+
{c}
227+
{p}
228+
{t}
229+
"""
230+
kwargs = self._preprocess(**kwargs) # pylint: disable=protected-access
231+
232+
if "S" not in kwargs or ("S" in kwargs and not isinstance(kwargs["S"], str)):
233+
raise GMTInvalidInput("Spec is a required argument and has to be a string.")
234+
235+
if isinstance(data, np.ndarray) and not pd.api.types.is_numeric_dtype(data):
236+
raise GMTInvalidInput(
237+
"Text columns are not supported with numpy.ndarray type inputs. "
238+
"They are only supported with file or pandas.DataFrame inputs."
239+
)
240+
241+
with Session() as lib:
242+
# Choose how data will be passed in to the module
243+
file_context = lib.virtualfile_from_data(check_kind="vector", data=data)
244+
245+
with file_context as fname:
246+
arg_str = " ".join([fname, build_arg_string(kwargs)])
247+
lib.call_module("velo", arg_str)
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
outs:
2+
- md5: 64e45d586112fc131090cfac2c104b63
3+
size: 45483
4+
path: test_velo_numpy_array_numeric_only.png
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
outs:
2+
- md5: 60dff1a72e6d984f095fb4973cecaec7
3+
size: 42430
4+
path: test_velo_pandas_dataframe.png

0 commit comments

Comments
 (0)