有没有办法释放 xarray.Dataset 的文件锁?

cch*_*ala 5 python concurrency netcdf python-xarray

我有一个进程fn每 5 分钟使用netcdf4.Dataset(fn, mode=a). 我还有一个使用 a xarray.Dataset(我想保留它,因为它非常方便)的NetCDF 文件的散景服务器可视化。

问题是 NetCDF-update-process 在尝试添加新数据时失败,fn如果它在我的散景服务器进程中通过

ds = xarray.open_dataset(fn)
Run Code Online (Sandbox Code Playgroud)

如果我使用该选项 autoclose

ds = xarray.open_dataset(fn, autoclose=True)
Run Code Online (Sandbox Code Playgroud)

更新fn与其他过程,同时ds在背景虚化服务器应用程序的作品“开放的”,但更新的背景虚化的人物,这拉从时间片fn,得到非常laggy。

我的问题是:有没有其他方法可以在使用时释放 NetCDF 文件的锁定xarray.Dataset

我不在乎 xarray.Dataset 的形状是否只在重新加载整个散景服务器应用程序后才一致更新。

谢谢!

这是一个最小的工作示例:

把它放到一个文件中并让它运行:

import time
from datetime import datetime

import numpy as np
import netCDF4

fn = 'my_growing_file.nc'

with netCDF4.Dataset(fn, 'w') as nc_fh:
    # create dimensions
    nc_fh.createDimension('x', 90)
    nc_fh.createDimension('y', 90)
    nc_fh.createDimension('time', None)

    # create variables
    nc_fh.createVariable('x', 'f8', ('x'))
    nc_fh.createVariable('y', 'f8', ('y'))
    nc_fh.createVariable('time', 'f8', ('time'))
    nc_fh.createVariable('rainfall_amount',
                         'i2',
                         ('time', 'y', 'x'),
                         zlib=False,
                         complevel=0,
                         fill_value=-9999,
                         chunksizes=(1, 90, 90))
    nc_fh['rainfall_amount'].scale_factor = 0.1
    nc_fh['rainfall_amount'].add_offset = 0

    nc_fh.set_auto_maskandscale(True)

    # variable attributes
    nc_fh['time'].long_name = 'Time'
    nc_fh['time'].standard_name = 'time'
    nc_fh['time'].units = 'hours since 2000-01-01 00:50:00.0'
    nc_fh['time'].calendar = 'standard'

for i in range(1000):
    with netCDF4.Dataset(fn, 'a') as nc_fh:
        current_length = len(nc_fh['time'])

        print('Appending to NetCDF file {}'.format(fn))
        print(' length of time vector: {}'.format(current_length))

        if current_length > 0:
            last_time_stamp = netCDF4.num2date(
                nc_fh['time'][-1],
                units=nc_fh['time'].units,
                calendar=nc_fh['time'].calendar)
            print(' last time stamp in NetCDF: {}'.format(str(last_time_stamp)))
        else:
            last_time_stamp = '1900-01-01'
            print(' empty file, starting from scratch')

        nc_fh['time'][i] = netCDF4.date2num(
            datetime.utcnow(),
            units=nc_fh['time'].units,
            calendar=nc_fh['time'].calendar)
        nc_fh['rainfall_amount'][i, :, :] = np.random.rand(90, 90)

    print('Sleeping...\n')
    time.sleep(3)
Run Code Online (Sandbox Code Playgroud)

然后,转到例如 IPython 并通过以下方式打开不断增长的文件:

ds = xr.open_dataset('my_growing_file.nc')
Run Code Online (Sandbox Code Playgroud)

这将导致附加到 NetCDF 的进程失败,输出如下:

Appending to NetCDF file my_growing_file.nc
 length of time vector: 0
 empty file, starting from scratch
Sleeping...

Appending to NetCDF file my_growing_file.nc
 length of time vector: 1
 last time stamp in NetCDF: 2018-04-12 08:52:39.145999
Sleeping...

Appending to NetCDF file my_growing_file.nc
 length of time vector: 2
 last time stamp in NetCDF: 2018-04-12 08:52:42.159254
Sleeping...

Appending to NetCDF file my_growing_file.nc
 length of time vector: 3
 last time stamp in NetCDF: 2018-04-12 08:52:45.169516
Sleeping...

---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-17-9950ca2e53a6> in <module>()
     37 
     38 for i in range(1000):
---> 39     with netCDF4.Dataset(fn, 'a') as nc_fh:
     40         current_length = len(nc_fh['time'])
     41 

netCDF4/_netCDF4.pyx in netCDF4._netCDF4.Dataset.__init__()

netCDF4/_netCDF4.pyx in netCDF4._netCDF4._ensure_nc_success()

IOError: [Errno -101] NetCDF: HDF error: 'my_growing_file.nc'
Run Code Online (Sandbox Code Playgroud)

如果使用

ds = xr.open_dataset('my_growing_file.nc', autoclose=True)
Run Code Online (Sandbox Code Playgroud)

没有错误,但访问时间xarray当然会变慢,这正是我的问题,因为我的仪表板可视化变得非常滞后。

我能理解,这也许不是预期的用途xarray,如果需要,我会回落到所提供的较低级接口netCDF4(希望它支持并发文件访问,至少在读),但我想保持xarray对它的方便。

cch*_*ala 2

我在这里回答我自己的问题,因为我找到了一个解决方案,或者更好地说,一种解决Python中NetCDF文件锁问题的方法。

如果您想在文件中不断增长数据集,同时保持文件打开(例如实时可视化),则一个好的解决方案是使用zarr而不是 NetCDF 文件。

幸运的是,由于最近合并的 PRxarray ,现在还可以轻松地允许使用关键字参数沿着选定的维度将数据附加到现有的 zarrappend_dim文件

使用 zarr 而不是像我的问题中那样使用 NetCDF 的代码如下所示:


import dask.array as da
import xarray as xr
import pandas as pd
import datetime
import time

fn = '/tmp/my_growing_file.zarr'

# Creat a dummy dataset and write it to zarr
data = da.random.random(size=(30, 900, 1200), chunks=(10, 900, 1200))
t = pd.date_range(end=datetime.datetime.utcnow(), periods=30, freq='1s')
ds = xr.Dataset(
    data_vars={'foo': (('time', 'y', 'x'), data)},
    coords={'time': t},
)
#ds.to_zarr(fn, mode='w', encoding={'foo': {'dtype': 'int16', 'scale_factor': 0.1, '_FillValue':-9999}})
#ds.to_zarr(fn, mode='w', encoding={'time': {'_FillValue': -9999}})
ds.to_zarr(fn, mode='w')

# Append new data in smaller chunks
for i in range(100):
    print('Sleeping for 10 seconds...')
    time.sleep(10)

    data = 0.01 * i + da.random.random(size=(7, 900, 1200), chunks=(7, 900, 1200))
    t = pd.date_range(end=datetime.datetime.utcnow(), periods=7, freq='1s')
    ds = xr.Dataset(
        data_vars={'foo': (('time', 'y', 'x'), data)},
        coords={'time': t},
    )
    print(f'Appending 7 new time slices with latest time stamp {t[-1]}')
    ds.to_zarr(fn, append_dim='time')
Run Code Online (Sandbox Code Playgroud)

然后你可以打开另一个Python进程,例如IPython并执行

 ds = xr.open_zarr('/tmp/my_growing_file.zarr/')   
Run Code Online (Sandbox Code Playgroud)

一遍又一遍,而不会导致写入进程崩溃。

在本示例中,我使用了 xarray 版本 0.15.0 和 zarr 版本 2.4.0。

一些附加说明:

请注意,此示例中的代码故意附加小块,这些小块不均匀地划分 zarr 文件中的块大小,以查看这如何影响块。根据我的测试,我可以说 zarr 文件最初选择的块大小被保留,这很棒!

另请注意,代码在附加时会生成警告,因为datetime64数据被编码并存储为整数,以xarray符合 NetCDF 的 CF 约定。这也适用于 zarr 文件,但目前似乎_FillValue不会自动设置。只要您NaT的时间中没有数据,这就不重要。

免责声明:我还没有尝试过使用更大的数据集和长时间运行的文件增长过程,因此我无法评论最终的性能下降或如果 zarr 文件或其元数据从该过程中以某种方式碎片化可能发生的其他问题。