pygmt.clib.Session.virtualfile_from_grid

Session.virtualfile_from_grid(grid)[source]

Store a grid in a virtual file.

Use the virtual file name to pass in the data in your grid to a GMT module. Grids must be xarray.DataArray instances.

Context manager (use in a with block). Yields the virtual file name that you can pass as an argument to a GMT module call. Closes the virtual file upon exit of the with block.

The virtual file will contain the grid as a GMT_MATRIX with extra metadata.

Use this instead of creating a data container and virtual file by hand with pygmt.clib.Session.create_data, pygmt.clib.Session.put_matrix, and pygmt.clib.Session.open_virtual_file

The grid data matrix must be C contiguous in memory. If it is not (e.g., it is a slice of a larger array), the array will be copied to make sure it is.

Parameters

grid (xarray.DataArray) – The grid that will be included in the virtual file.

Yields

fname (str) – The name of virtual file. Pass this as a file name argument to a GMT module.

Examples

>>> from pygmt.helpers.testing import load_static_earth_relief
>>> from pygmt.helpers import GMTTempFile
>>> data = load_static_earth_relief()
>>> print(data.shape)
(14, 8)
>>> print(data.lon.values.min(), data.lon.values.max())
-54.5 -47.5
>>> print(data.lat.values.min(), data.lat.values.max())
-23.5 -10.5
>>> print(data.values.min(), data.values.max())
190.0 981.0
>>> with Session() as ses:
...     with ses.virtualfile_from_grid(data) as fin:
...         # Send the output to a file so that we can read it
...         with GMTTempFile() as fout:
...             args = f"{fin} -L0 -Cn ->{fout.name}"
...             ses.call_module("grdinfo", args)
...             print(fout.read().strip())
...
-55 -47 -24 -10 190 981 1 1 8 14 1 1
>>> # The output is: w e s n z0 z1 dx dy n_columns n_rows reg gtype