|
| 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