【问题标题】:Create lazy xarray object from Future从 Future 创建惰性 xarray 对象
【发布时间】:2021-09-05 09:29:43
【问题描述】:

我有一个dask.delayed 函数,它接受xarray.Dataarray 作为参数并返回一个。

我正在创建一些延迟任务,并使用dask.distributed 将它们传递给client.compute。每次调用计算都会返回一个distributed.client.Future,表示将返回的数据数组。

我的问题是:

有没有办法从未来再次构建一个“惰性”数据数组而不从工作人员加载实际数据?我的意图是根据第一次计算的输出构建第二个任务图。

我见过client.gather,但这似乎将所有数据拉回客户端,这不是我想要的。

这是一个小例子:

import dask
from distributed import Client
import xarray as xr

# load example data
x = xr.tutorial.open_dataset("air_temperature")

# use first timestep
x_t0 = x.isel(time=0)

# delayed 'processing' function
@dask.delayed
def fun(x):
    return x*2

# init client
client = Client()

# compute on worker
future = client.compute(fun(x_t0))

# when done
print(future)
# <Future: finished, type: xarray.Dataset, key: fun-96cd56f4-4ed3-4eac-ade9-fe3f17e4b8c6>

## now how to get back to lazy xarray from future?

【问题讨论】:

    标签: python python-xarray dask-distributed dask-delayed


    【解决方案1】:

    我不知道你到底想达到什么目的。可能有比从未来创建一个新数组更好的方法来做到这一点。话虽如此,这将从您的数据创建一个新的数据数组: 你不必调用 compute 来保持它的懒惰。

    (如果您想要一个 dask 数组而不是 xarray 数组,请删除 xr.DataArray)

    import dask
    from distributed import Client
    import xarray as xr
    
    # load example data
    x = xr.tutorial.open_dataset("air_temperature")
    
    # use first timestep
    x_t0 = x.isel(time=0)
    
    # delayed 'processing' function
    @dask.delayed
    def fun(x):
        return x*2
    
    # init client
    client = Client()
    
    # Create lazy xarray object from future:
    import dask.array as da
    
    new_ds = xr.DataArray(da.from_delayed(client.persist(fun(x_t0)), shape=x_t0.air.shape, meta='f8'), coords=x.coords)
    
    

    编辑:添加了 client.persist 以将数据留在客户端

    输出:

    【讨论】:

    • 谢谢,但我想我应该更明确一点:我需要数据数组中的元数据(坐标等),所以只是简单地将一个 dask 数组包装到 xarray.Dataarray 中不是一个解决方案为了我。 +1 可行的解决方案
    • 谢谢,我希望这可行:x['new'] = ((tuple(x_t0.coords)[:2], da.from_delayed(client.persist(fun(x_t0))), shape =x_t0.air.shape, meta='f8')) ? 这将在您的数据集中在现有维度上创建一个新参数..
    • 或者你可以使用:new_ds = xr.DataArray(da.from_delayed(client.persist(fun(x_t0)), shape=x_t0.air.shape, meta='f8'));新的_ds。 assign_coords(x.coords) 用延迟的数组创建一个新的ds?
    • 您第二条评论中的示例几乎可以满足我的需求(并且我希望可以采用本地方式)。请注意,如果您使用coords=x.coords 调用xr.DataArray,则可以将所有内容放在一个电话中。如果您想将此添加到您的解决方案中,我会接受它作为答案!再次感谢!
    • 好的,我添加了。感谢您指出这一点!
    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 2015-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    相关资源
    最近更新 更多