使用 Python 获取 NetCDF 变量 min/max 的最快方法?

Joh*_*rer 5 python numpy scipy netcdf

min/max从 NetCDF 文件中提取变量数据值的常用方法与scipy.io.netcdf.

我正在处理相对较大的海洋模型输出文件(来自 ROMS),在给定的地图区域(夏威夷)上具有多个深度级别。当这些在 NetCDF-3 中时,我使用了scipy.io.netcdf.

现在这些文件在 NetCDF-4(“经典”)中,我不能再使用scipy.io.netcdf,而是切换到使用 netCDF4 Python 模块。但是,缓慢是一个问题,我想知道是否有更有效的方法来提取变量的数据范围(最小和最大数据值)?

这是我使用 scipy 的 NetCDF-3 方法:

import scipy.io.netcdf
netcdf = scipy.io.netcdf.netcdf_file(file)
var = netcdf.variables['sea_water_potential_temperature']
min = var.data.min()
max = var.data.max()
Run Code Online (Sandbox Code Playgroud)

这是我使用 netCDF4 的 NetCDF-4 方法:

import netCDF4
netcdf = netCDF4.Dataset(file)
var = netcdf.variables['sea_water_potential_temperature']
var_array = var.data.flatten()
min = var_array.data.min()
max = var_array.data.max()
Run Code Online (Sandbox Code Playgroud)

显着的区别是我必须首先展平 netCDF4 中的数据数组,而这个操作显然会减慢速度。

有没有更好/更快的方法?

rya*_*lon 2

这里的每个建议是一个使用调用命令hpaulj的函数。使用 OPeNDAP 地址时它会严重挂起,而且我手头没有任何文件可以在本地测试它。nconcwasubprocess

您可以查看它是否适合您以及速度差异有多大。

这假设您已经nco安装了该库。

def ncwa(path, fnames, var, op_type, times=None, lons=None, lats=None):
    '''Perform arithmetic operations on netCDF file or OPeNDAP data

    Args
    ----
    path: str
        prefix
    fnames: str or iterable
        Names of file(s) to perform operation on
    op_type: str
        ncwa arithmetic operation to perform. Available operations are:
        avg,mabs,mebs,mibs,min,max,ttl,sqravg,avgsqr,sqrt,rms,rmssdn
    times: tuple
        Minimum and maximum timestamps within which to perform the operation
    lons: tuple
        Minimum and maximum longitudes within which to perform the operation
    lats: tuple
        Minimum and maximum latitudes within which to perform the operation

    Returns
    -------
    result: float
        Result of the operation on the selected data

    Note
    ----
    Adapted from the OPeNDAP examples in the NCO documentation:
    http://nco.sourceforge.net/nco.html#OPeNDAP
    '''
    import os
    import netCDF4
    import numpy
    import subprocess

    output = 'tmp_output.nc'

    # Concatenate subprocess command
    cmd = ['ncwa']
    cmd.extend(['-y', '{}'.format(op_type)])
    if times:
        cmd.extend(['-d', 'time,{},{}'.format(times[0], times[1])])
    if lons:
        cmd.extend(['-d', 'lon,{},{}'.format(lons[0], lons[1])])
    if lats:
        cmd.extend(['-d', 'lat,{},{}'.format(lats[0], lats[1])])
    cmd.extend(['-p', path])
    cmd.extend(numpy.atleast_1d(fnames).tolist())
    cmd.append(output)

    # Run cmd and check for errors
    subprocess.run(cmd, stdout=subprocess.PIPE, check=True)

    # Load, read, close data and delete temp .nc file
    data = netCDF4.Dataset(output)
    result = float(data[var][:])
    data.close()
    os.remove(output)

    return result

path = 'https://ecowatch.ncddc.noaa.gov/thredds/dodsC/hycom/hycom_reg6_agg/'
fname = 'HYCOM_Region_6_Aggregation_best.ncd'

times = (0.0, 48.0)
lons = (201.5, 205.5)
lats = (18.5, 22.5)

smax = ncwa(path, fname, 'salinity', 'max', times, lons, lats)
Run Code Online (Sandbox Code Playgroud)