使用xarray和open_mfdataset从URL打开多个文件

问题描述

我正尝试从2015-2050年下载多个CMIP6数据文件,以获取高分辨率的阵风。 来自here的数据集中总共有432个文件(有关缩小搜索范围的搜索字词,请参见屏幕截图)。

其中有432个文件,我可以通过右键单击OpenDAP下载按钮(在屏幕截图上以红色突出显示)并将URL粘贴到open_mfdataset函数中来单独打开它们,如下所示:

ds = xarray.open_mfdataset(('http://esgf-data3.ceda.ac.uk/thredds/dodsC/esg_cmip6/CMIP6/HighResMIP/CMCC/CMCC-CM2-VHR4/highres-future/r1i1p1f1/6hrPlevPt/sfcWind/gn/v20190509/sfcWind_6hrPlevPt_CMCC-CM2-VHR4_highres-future_r1i1p1f1_gn_201501010000-201501311800.nc','http://esgf-data3.ceda.ac.uk/thredds/dodsC/esg_cmip6/CMIP6/HighResMIP/CMCC/CMCC-CM2-VHR4/highres-future/r1i1p1f1/6hrPlevPt/sfcWind/gn/v20190509/sfcWind_6hrPlevPt_CMCC-CM2-VHR4_highres-future_r1i1p1f1_gn_201502010000-201502281800.nc'))

这可以正常工作,但是有432个文件,并且要花很长时间-我尝试了其他方法,但是觉得我有一种方法可以使用xarray有效地执行此操作,而我丢失了-我非常感谢您的帮助。谢谢。

编辑: 我使用下面的屏幕快照中的“ THREDDS目录”链接和以下代码来使它工作:

df = pd.read_html('http://esg.lasg.ac.cn/thredds/catalog/esgcet/180/CMIP6.HighResMIP.CAS.FGOALS-f3-H.highressst-future.r1i1p1f1.6hrPlevPt.psl.gr.v20200521.html#CMIP6.HighResMIP.CAS.FGOALS-f3-H.highressst-future.r1i1p1f1.6hrPlevPt.psl.gr.v20200521',skiprows = 1)

df = df[0]

#get all relevant (432 files)
df = df[:432]

#add the url to each datafile to create a downloadable link for each
df['url'] = 'http://esg.lasg.ac.cn/thredds/dodsC/esg_daTaroot/CMIP6/HighResMIP/CAS/FGOALS-f3-H/highressst-future/r1i1p1f1/6hrPlevPt/psl/gr/v20200521/' + df['CMIP6.HighResMIP.CAS.FGOALS-f3-H.highressst-future.r1i1p1f1.6hrPlevPt.psl.gr'].astype(str)

filelist = df['url'].tolist()

#do the first 10 to see if it works (change the number)
test = filelist[:10]

#do the first 10 into a dataset
ds = xarray.open_mfdataset(test)

解决方法

据我们了解,我们不能使用通配符运算符来从openDAP服务器访问数据。但是我们可以利用CMIP模型输出文件的常规结构并手动构建文件名:

import calendar
import pandas as pd
import xarray as xr

# base url
base_url = 'http://esgf-data3.ceda.ac.uk/thredds/dodsC/esg_cmip6/CMIP6/HighResMIP/CMCC/CMCC-CM2-VHR4/highres-future/r1i1p1f1/6hrPlevPt/sfcWind/gn/v20190509/sfcWind_6hrPlevPt_CMCC-CM2-VHR4_highres-future_r1i1p1f1_gn_'

# period of interest
pr = pd.period_range(start='2015-01',end='2050-12',freq='M')

file_list=[]
for dt in pr:
    # get recent year and month
    year = dt.strftime('%Y')
    month = dt.strftime('%m')

    # get last day of month (no leap years in CMIP)
    last_day_of_month = str(calendar.monthrange(dt.year,dt.month)[1])
    if last_day_of_month == '29':
        last_day_of_month = '28'
        
    # build complete file name
    single_file=(base_url+year+month+'010000-'+year+month+last_day_of_month+'1800.nc')
    file_list.append(single_file)
    
ds=xr.open_mfdataset(file_list)