Skip to content

Commit cac7d74

Browse files
committed
Add pygmt.read to read a dataset/grid/image into pandas.DataFrame/xarray.DataArray
1 parent a92d9d0 commit cac7d74

File tree

5 files changed

+84
-6
lines changed

5 files changed

+84
-6
lines changed

doc/api/index.rst

+1
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,7 @@ Input/output
172172
:toctree: generated
173173

174174
load_dataarray
175+
read
175176

176177
GMT Defaults
177178
------------

pygmt/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@
5454
makecpt,
5555
nearneighbor,
5656
project,
57+
read,
5758
select,
5859
sph2grd,
5960
sphdistance,

pygmt/helpers/testing.py

+5-6
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@
77
import string
88
from pathlib import Path
99

10+
import xarray as xr
1011
from pygmt.exceptions import GMTImageComparisonFailure
11-
from pygmt.io import load_dataarray
12-
from pygmt.src import which
12+
from pygmt.src import read
1313

1414

1515
def check_figures_equal(*, extensions=("png",), tol=0.0, result_dir="result_images"):
@@ -144,17 +144,16 @@ def wrapper(*args, ext="png", request=None, **kwargs):
144144
return decorator
145145

146146

147-
def load_static_earth_relief():
147+
def load_static_earth_relief() -> xr.DataArray:
148148
"""
149149
Load the static_earth_relief file for internal testing.
150150
151151
Returns
152152
-------
153-
data : xarray.DataArray
153+
data
154154
A grid of Earth relief for internal tests.
155155
"""
156-
fname = which("@static_earth_relief.nc", download="c")
157-
return load_dataarray(fname)
156+
return read("@static_earth_relief.nc", kind="grid") # type: ignore[return-value]
158157

159158

160159
def skip_if_no(package):

pygmt/src/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
from pygmt.src.plot3d import plot3d
4242
from pygmt.src.project import project
4343
from pygmt.src.psconvert import psconvert
44+
from pygmt.src.read import read
4445
from pygmt.src.rose import rose
4546
from pygmt.src.select import select
4647
from pygmt.src.shift_origin import shift_origin

pygmt/src/read.py

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
"""
2+
Read data from files
3+
"""
4+
5+
from typing import Literal
6+
7+
import pandas as pd
8+
import xarray as xr
9+
from pygmt.clib import Session
10+
11+
12+
def read(
13+
file, kind: Literal["dataset", "grid", "image"], **kwargs
14+
) -> pd.DataFrame | xr.DataArray:
15+
"""
16+
Read a dataset, grid, or image from a file and return the appropriate object.
17+
18+
For datasets, it returns a :class:`pandas.DataFrame`. For grids and images,
19+
it returns a :class:`xarray.DataArray`.
20+
21+
Parameters
22+
----------
23+
file
24+
The file name to read.
25+
kind
26+
The kind of data to read. Valid values are ``"dataset"``, ``"grid"``,
27+
and ``"image"``.
28+
29+
For datasets, the following keyword arguments are supported:
30+
31+
column_names
32+
A list of column names.
33+
header
34+
Row number containing column names. ``header=None`` means not to parse the
35+
column names from table header. Ignored if the row number is larger than the
36+
number of headers in the table.
37+
dtype
38+
Data type. Can be a single type for all columns or a dictionary mapping
39+
column names to types.
40+
index_col
41+
Column to set as index.
42+
43+
Returns
44+
-------
45+
Return type depends on the ``kind`` argument:
46+
47+
- ``"dataset"``: :class:`pandas.DataFrame`
48+
- ``"grid"`` or ``"image"``: :class:`xarray.DataArray`
49+
50+
51+
Examples
52+
--------
53+
54+
Read a dataset into a :class:`pandas.DataFrame` object:
55+
56+
>>> from pygmt import read
57+
>>> df = read("@hotspots.txt", kind="dataset")
58+
>>> type(df)
59+
<class 'pandas.core.frame.DataFrame'>
60+
61+
Read a grid into an :class:`xarray.DataArray` object:
62+
>>> dataarray = read("@earth_relief_01d", kind="grid")
63+
>>> type(dataarray)
64+
<class 'xarray.core.dataarray.DataArray'>
65+
"""
66+
code = {"dataset": "d", "grid": "g", "image": "i"}[kind]
67+
68+
with Session() as lib:
69+
with lib.virtualfile_out(kind=kind) as voutfile:
70+
lib.call_module("read", args=[file, voutfile, f"-T{code}"])
71+
72+
match kind:
73+
case "dataset":
74+
return lib.virtualfile_to_dataset(vfname=voutfile, **kwargs)
75+
case "grid" | "image":
76+
return lib.virtualfile_to_raster(vfname=voutfile, kind=kind)

0 commit comments

Comments
 (0)