Python xarray.open_dataarray() Examples

The following are 8 code examples of xarray.open_dataarray(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module xarray , or try the search function .
Example #1
Source File: test_surface.py    From pygmt with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_surface_with_outfile_param():
    """
    Run surface with the -Goutputfile.nc parameter
    """
    ship_data = load_sample_bathymetry()
    data = ship_data.values  # convert pandas.DataFrame to numpy.ndarray
    try:
        output = surface(
            data=data, spacing="5m", region=[245, 255, 20, 30], outfile=TEMP_GRID
        )
        assert output is None  # check that output is None since outfile is set
        assert os.path.exists(path=TEMP_GRID)  # check that outfile exists at path
        with xr.open_dataarray(TEMP_GRID) as grid:
            assert isinstance(grid, xr.DataArray)  # ensure netcdf grid loads ok
    finally:
        os.remove(path=TEMP_GRID)
    return output 
Example #2
Source File: test_surface.py    From pygmt with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_surface_short_aliases():
    """
    Run surface using short aliases -I for spacing, -R for region, -G for
    outfile
    """
    ship_data = load_sample_bathymetry()
    data = ship_data.values  # convert pandas.DataFrame to numpy.ndarray
    try:
        output = surface(data=data, I="5m", R=[245, 255, 20, 30], G=TEMP_GRID)
        assert output is None  # check that output is None since outfile is set
        assert os.path.exists(path=TEMP_GRID)  # check that outfile exists at path
        with xr.open_dataarray(TEMP_GRID) as grid:
            assert isinstance(grid, xr.DataArray)  # ensure netcdf grid loads ok
    finally:
        os.remove(path=TEMP_GRID)
    return output 
Example #3
Source File: expression_matrix.py    From starfish with MIT License 6 votes vote down vote up
def load(cls, filename: str) -> "ExpressionMatrix":  # type: ignore
        """load an ExpressionMatrix from Netcdf

        Parameters
        ----------
        filename : str
            File to load

        Returns
        -------
        ExpressionMatrix

        """
        loaded = xr.open_dataarray(filename)
        expression_matrix = cls(
            loaded.data,
            loaded.coords,
            loaded.dims
        )
        return expression_matrix 
Example #4
Source File: run_xarray.py    From recipy with Apache License 2.0 5 votes vote down vote up
def open_dataarray(self):
        """
        Use xarray.open_dataarray to read a netcdf file.
        """
        file_name = os.path.join(self.data_dir, "data_array.nc")
        xarray.open_dataarray(file_name) 
Example #5
Source File: label_image.py    From starfish with MIT License 5 votes vote down vote up
def open_netcdf(cls, path: Union[str, Path]) -> "LabelImage":
        """Load a label image saved as a netcdf file from disk.

        Parameters
        ----------
        path : Union[str, Path]
            Path of the label image to instantiate from.

        Returns
        -------
        label_image : LabelImage
            Label image from the path.
        """
        label_image = xr.open_dataarray(path)
        if (
                AttrKeys.DOCTYPE not in label_image.attrs
                or label_image.attrs[AttrKeys.DOCTYPE] != DOCTYPE_STRING
                or AttrKeys.VERSION not in label_image.attrs
        ):
            raise ValueError(f"{path} does not appear to be a starfish label image")
        if not (
                MIN_SUPPORTED_VERSION
                <= Version(label_image.attrs[AttrKeys.VERSION])
                <= MAX_SUPPORTED_VERSION):
            raise ValueError(
                f"{path} contains a label image, but the version "
                f"{label_image.attrs[AttrKeys.VERSION]} is not supported")

        return cls(label_image) 
Example #6
Source File: intensity_table.py    From starfish with MIT License 5 votes vote down vote up
def open_netcdf(cls, filename: str) -> "IntensityTable":
        """
        Load an IntensityTable from Netcdf.

        Parameters
        ----------
        filename : str
            File to load.

        Returns
        -------
        IntensityTable

        """
        loaded = xr.open_dataarray(filename)
        intensity_table = cls(
            loaded.data,
            loaded.coords,
            loaded.dims,
            attrs=loaded.attrs,
        )
        return intensity_table 
Example #7
Source File: rinex_reader.py    From georinex with MIT License 4 votes vote down vote up
def rinexobs(fn, ofn=None):
    """
    Program overviw:
    1) scan the whole file for the header and other information using scan(lines)
    2) each epoch is read and the information is put in a 4-D xarray.DataArray
    3)  rinexobs can also be sped up with if an h5 file is provided,
        also rinexobs can save the rinex file as an h5. The header will
        be returned only if specified.

    rinexobs() returns the data in a 4-D xarray.DataArray, [Parameter,Sat #,time,data/loss of lock/signal strength]
    """
    # open file, get header info, possibly speed up reading data with a premade h5 file
    fn = Path(fn).expanduser()
    with fn.open('r') as f:
        tic = time()
        lines = f.read().splitlines(True)
        header, version, headlines, headlength, obstimes, sats, svset = scan(lines)
        print(fn, 'is a RINEX', version, 'file.', fn.stat().st_size//1000, 'kB.')
        if fn.suffix == '.nc':
            data = xarray.open_dataarray(str(fn), group='OBS')
        elif fn.suffix == '.h5':
            logging.warning('HDF5 is deprecated in this program, please use NetCDF format')
            import pandas
            data = pandas.read_hdf(fn, key='OBS')
        else:
            data = processBlocks(lines, header, obstimes, svset, headlines, headlength, sats)

        print("finished in {:.2f} seconds".format(time()-tic))

    # write an h5 file if specified
    if ofn:
        ofn = Path(ofn).expanduser()
        print('saving OBS data to', ofn)
        if ofn.is_file():
            wmode = 'a'
        else:
            wmode = 'w'
        data.to_netcdf(ofn, group='OBS', mode=wmode)

    return data, header


# this will scan the document for the header info and for the line on
# which each block starts 
Example #8
Source File: earth_relief.py    From pygmt with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def load_earth_relief(resolution="01d"):
    """
    Load Earth relief grids (topography and bathymetry) in various resolutions.

    The grids are downloaded to a user data directory (usually ``~/.gmt/``) the
    first time you invoke this function. Afterwards, it will load the data from
    the cache. So you'll need an internet connection the first time around.

    These grids can also be accessed by passing in the file name
    ``'@earth_relief_XXm'`` or ``'@earth_relief_XXs'`` to any grid
    plotting/processing function.

    Parameters
    ----------
    resolution : str
        The grid resolution. The suffix ``d``, ``m`` and ``s`` stand for
        arc-degree, arc-minute and arc-second. It can be ``'01d'``, ``'30m'``,
        ``'20m'``, ``'15m'``, ``'10m'``, ``'06m'``, ``'05m'``, ``'04m'``,
        ``'03m'``, ``'02m'``, ``'01m'``, ``'30s'`` or ``'15s'``.

    Returns
    -------
    grid : xarray.DataArray
        The Earth relief grid. Coordinates are latitude and longitude in
        degrees. Relief is in meters.

    """
    _is_valid_resolution(resolution)
    fname = which("@earth_relief_{}".format(resolution), download="u")
    grid = xr.open_dataarray(fname)
    # Add some metadata to the grid
    grid.name = "elevation"
    grid.attrs["long_name"] = "elevation relative to the geoid"
    grid.attrs["units"] = "meters"
    grid.attrs["vertical_datum"] = "EMG96"
    grid.attrs["horizontal_datum"] = "WGS84"
    # Remove the actual range because it gets outdated when indexing the grid,
    # which causes problems when exporting it to netCDF for usage on the
    # command-line.
    grid.attrs.pop("actual_range")
    for coord in grid.coords:
        grid[coord].attrs.pop("actual_range")
    return grid