-
Notifications
You must be signed in to change notification settings - Fork 224
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add pygmt.read to read a dataset/grid/image into pandas.DataFrame/xarray.DataArray #3673
Open
seisman
wants to merge
25
commits into
main
Choose a base branch
from
feature/read
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 19 commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
d913c86
Add pygmt.read to read a dataset/grid/image into pandas.DataFrame/xar…
seisman f456bf8
Set GMT accessor
seisman c3cbb6e
Need to set 'source' encoding to make GMT accessor work
seisman f2a4ce4
Merge branch 'main' into feature/read
seisman 1dd97c6
Fix the source encoding
seisman 7790ea3
No need to set the source encoding in load_remote_dataset.py
seisman e588008
Revert changes in pygmt/datasets/load_remote_dataset.py
seisman 40d12ee
Improve docstring in pygmt/helpers/testing.py
seisman fa1021d
Improve docstrinbgs
seisman c378225
Get rid of decorators
seisman 7b749e0
Improve comment
seisman 8befa58
Get rid of the fmt_docstring alias
seisman a758752
Fix type hints issue with overload
seisman 9d66cf4
Remove the type ignore flag
seisman a05383a
region defaults to None
seisman 6ca4ef2
Merge branch 'main' into feature/read
seisman 7851ced
Improve type hints and add tests
seisman 084b87a
Improve the checking of return value of which
seisman b21997c
Use the read funciton in pygmt/tests/test_datatypes_dataset.py
seisman a812317
Use the read function instead of the load_dataarray method
seisman 1f0f158
Add one test to make sure that read and load_dataarray returns the sa…
seisman 957c7eb
Simplify pygmt/tests/test_clib_read_data.py with read
seisman 6aef3ca
Fix a typo
seisman 72afbfe
Replace xr.open_dataarray with read
seisman 03de9b7
Fix a typo
seisman File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -172,6 +172,7 @@ Input/output | |
:toctree: generated | ||
|
||
load_dataarray | ||
read | ||
|
||
GMT Defaults | ||
------------ | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -54,6 +54,7 @@ | |
makecpt, | ||
nearneighbor, | ||
project, | ||
read, | ||
select, | ||
sph2grd, | ||
sphdistance, | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,118 @@ | ||||||
""" | ||||||
Read a file into an appropriate object. | ||||||
""" | ||||||
|
||||||
from collections.abc import Mapping, Sequence | ||||||
from pathlib import PurePath | ||||||
from typing import Any, Literal | ||||||
|
||||||
import pandas as pd | ||||||
import xarray as xr | ||||||
from pygmt.clib import Session | ||||||
from pygmt.helpers import build_arg_list, is_nonstr_iter | ||||||
from pygmt.src.which import which | ||||||
|
||||||
|
||||||
def read( | ||||||
file: str | PurePath, | ||||||
kind: Literal["dataset", "grid", "image"], | ||||||
region: Sequence[float] | str | None = None, | ||||||
header: int | None = None, | ||||||
column_names: pd.Index | None = None, | ||||||
dtype: type | Mapping[Any, type] | None = None, | ||||||
index_col: str | int | None = None, | ||||||
) -> pd.DataFrame | xr.DataArray: | ||||||
""" | ||||||
Read a dataset, grid, or image from a file and return the appropriate object. | ||||||
|
||||||
The returned object is a :class:`pandas.DataFrame` for datasets, and | ||||||
:class:`xarray.DataArray` for grids and images. | ||||||
|
||||||
For datasets, keyword arguments ``column_names``, ``header``, ``dtype``, and | ||||||
``index_col`` are supported. | ||||||
|
||||||
Parameters | ||||||
---------- | ||||||
file | ||||||
The file name to read. | ||||||
kind | ||||||
The kind of data to read. Valid values are ``"dataset"``, ``"grid"``, and | ||||||
``"image"``. | ||||||
region | ||||||
The region of interest. Only data within this region will be read. | ||||||
column_names | ||||||
A list of column names. | ||||||
header | ||||||
Row number containing column names. ``header=None`` means not to parse the | ||||||
column names from table header. Ignored if the row number is larger than the | ||||||
number of headers in the table. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
dtype | ||||||
Data type. Can be a single type for all columns or a dictionary mapping | ||||||
column names to types. | ||||||
index_col | ||||||
Column to set as index. | ||||||
|
||||||
Returns | ||||||
------- | ||||||
data | ||||||
Return type depends on the ``kind`` argument: | ||||||
|
||||||
- ``"dataset"``: :class:`pandas.DataFrame` | ||||||
- ``"grid"`` or ``"image"``: :class:`xarray.DataArray` | ||||||
|
||||||
|
||||||
Examples | ||||||
-------- | ||||||
Read a dataset into a :class:`pandas.DataFrame` object: | ||||||
|
||||||
>>> from pygmt import read | ||||||
>>> df = read("@hotspots.txt", kind="dataset") | ||||||
>>> type(df) | ||||||
<class 'pandas.core.frame.DataFrame'> | ||||||
|
||||||
Read a grid into an :class:`xarray.DataArray` object: | ||||||
|
||||||
>>> dataarray = read("@earth_relief_01d", kind="grid") | ||||||
>>> type(dataarray) | ||||||
<class 'xarray.core.dataarray.DataArray'> | ||||||
""" | ||||||
if kind not in {"dataset", "grid", "image"}: | ||||||
msg = f"Invalid kind {kind}: must be one of 'dataset', 'grid', or 'image'." | ||||||
raise ValueError(msg) | ||||||
|
||||||
if kind != "dataset" and any( | ||||||
v is not None for v in [column_names, header, dtype, index_col] | ||||||
): | ||||||
msg = ( | ||||||
"Only the 'dataset' kind supports the 'column_names', 'header', " | ||||||
"'dtype', and 'index_col' arguments." | ||||||
) | ||||||
raise ValueError(msg) | ||||||
|
||||||
kwdict = { | ||||||
"R": "/".join(f"{v}" for v in region) if is_nonstr_iter(region) else region, # type: ignore[union-attr] | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This line is used here to avoid using the
|
||||||
"T": {"dataset": "d", "grid": "g", "image": "i"}[kind], | ||||||
} | ||||||
|
||||||
with Session() as lib: | ||||||
with lib.virtualfile_out(kind=kind) as voutfile: | ||||||
lib.call_module("read", args=[file, voutfile, *build_arg_list(kwdict)]) | ||||||
|
||||||
match kind: | ||||||
case "dataset": | ||||||
return lib.virtualfile_to_dataset( | ||||||
vfname=voutfile, | ||||||
column_names=column_names, | ||||||
header=header, | ||||||
dtype=dtype, | ||||||
index_col=index_col, | ||||||
) | ||||||
case "grid" | "image": | ||||||
raster = lib.virtualfile_to_raster(vfname=voutfile, kind=kind) | ||||||
# Add "source" encoding | ||||||
source = which(fname=file) | ||||||
raster.encoding["source"] = ( | ||||||
source[0] if isinstance(source, list) else source | ||||||
) | ||||||
_ = raster.gmt # Load GMTDataArray accessor information | ||||||
return raster |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
""" | ||
Test the read function. | ||
""" | ||
|
||
import pytest | ||
from pygmt import read | ||
|
||
|
||
def test_read_invalid_kind(): | ||
""" | ||
Test that an invalid kind raises a ValueError. | ||
""" | ||
with pytest.raises(ValueError, match="Invalid kind"): | ||
read("file.cpt", kind="cpt") | ||
|
||
|
||
def test_read_invalid_arguments(): | ||
""" | ||
Test that invalid arguments raise a ValueError for non-'dataset' kind. | ||
""" | ||
with pytest.raises(ValueError, match="Only the 'dataset' kind supports"): | ||
read("file.nc", kind="grid", column_names="foo") | ||
|
||
with pytest.raises(ValueError, match="Only the 'dataset' kind supports"): | ||
read("file.nc", kind="grid", header=1) | ||
|
||
with pytest.raises(ValueError, match="Only the 'dataset' kind supports"): | ||
read("file.nc", kind="grid", dtype="float") |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.