python - 从文件对象或 netCDF4 数据集创建 Iris Cube

标签 python python-iris

有没有办法使用文件对象(二进制流)或从 netCDF4 数据集对象创建(打开/加载)鸢尾花立方体?

具体来说,我有一个通过 URL 提供的文件,但不是由 OpenDAP 服务器提供的; iris.load_cube() & friends 失败了。

我意识到 Iris 更喜欢延迟加载,因此使用 URI 而不是内存中的数据,但这并不总是可行的。

对于普通的 netCDF4 Dataset 对象,我可以执行以下操作:

from urllib.request import urlopen
import netCDF4 as nc

url = 'https://crudata.uea.ac.uk/cru/data/temperature/HadCRUT.4.6.0.0.median.nc'
with urlopen(url) as stream:
    ds = nc.Dataset('HadCRUT', memory=stream.read())

所以我想为 Iris Cube 做一些类似的事情,或者将 netCDF4 数据集读入一个立方体,而不是通过磁盘上的临时文件。我曾希望 Iris 功能中存在一些东西,但我(还)没能在引用文档中找到它。

最佳答案

要读取 .nc 文件,Iris 在内部使用 same netcdf4-python你提到的图书馆。

这意味着理论上您可以:

  1. 子类 CFReader覆盖它的 __init__ 方法,唯一的变化是 self._dataset = netCDF4.Dataset(self._filename, mode='r')

  2. 要么编写您自己的 load_cube 函数 ( based on this code ),它将使用您的自定义 CFReader,或者您可以使用您自定义的 CFReader monkeypatch iris

猴子补丁的总体思路:

from urllib.request import urlopen

import iris.fileformats.cf
import netCDF4 as nc


def __patch_CFReader():
    if getattr(iris.fileformats.cf.CFReader, '_HACKY_PATCHED'):
        return

    from iris.fileformats.cf import CFReader

    class CustomCFReader(CFReader):
        _HACKY_PATCHED = True

        def __init__(self, uri, *args, **kwargs):
            # ... other code copied
            with urlopen(url) as stream:
                self._dataset = nc.Dataset('HadCRUT', memory=stream.read())
            # ... other code copied

    iris.fileformats.cf.CFReader = CustomCFReader


__patch_CFReader()

import iris
cube = iris.load_cube('https://crudata.uea.ac.uk/cru/data/temperature/HadCRUT.4.6.0.0.median.nc')

警告!根据项目中导入的方式,monkey patching 可能 并不总是像你最初想的那样工作。所以也许你应该更喜欢使用一些库 专为猴子修补而设计,例如 gorilla :

https://gorilla.readthedocs.io/en/latest/tutorial.html

# my_patches.py:
from urllib.request import urlopen

import gorilla
import iris.fileformats.cf
import netCDF4 as nc

settings = gorilla.Settings(allow_hit=True)

@gorilla.patch(iris.fileformats.cf.CFReader, settings=settings)
def __init__(self, uri, *args, **kwargs):
    # ... other code copied
    with urlopen(url) as stream:
        self._dataset = nc.Dataset('HadCRUT', memory=stream.read())
    # ... other code copied

# earliest_imported_module.py:
import gorilla
import my_patches

for patch in gorilla.find_patches([my_patches]):
    gorilla.apply(patch)

关于python - 从文件对象或 netCDF4 数据集创建 Iris Cube,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56039266/

相关文章:

python -/iris/is 中的未捕获异常(也是 [Errno 101] 网络无法访问)

python - 有没有办法在 "pure"Keras 中将图像从灰度转换为 RGB

python - 在 Heroku 应用程序之间共享 Python 代码

python - 在 Pandas DataFrame 中选择包含至少一个 True 值的列的最佳解决方案

python - DataFrame 创建 - 重新索引

Python:使用多边形在给定的二维网格上创建蒙版

python - 将 Iris 约束与 OR 结合起来?

python - 按索引删除 pandas 中的行 - 必须添加到索引吗?

python - "unfair" Pandas 分类.from_codes

python - 无法使用 pip 安装 scitools-iris : ImportError No module named target_pkg (in pyke)