【问题标题】:Calculate variables mean in a selective area , in gridded netCDF file在网格化的 netCDF 文件中计算选定区域中的变量均值
【发布时间】:2014-04-21 02:22:53
【问题描述】:

假设我们有 TRMM 降水数据,每个文件代表每个月的数据。例如文件夹中的文件有:

     3B42.1998.01.01.7A.nc,
     3B42.1998.02.01.7A.nc, 
     3B42.1998.03.01.7A.nc, 
     3B42.1998.04.01.7A.nc, 
     3B42.1998.05.01.7A.nc, 
     ......
     ......
     3B42.2010.11.01.7A.nc,         
     3B42.2010.12.01.7A.nc.

这些文件的尺寸如下:Xsize=1440, Ysize=400, Zsize=1,Tsize=1。经度设置为 0 到 360,纬度设置为 -50 到 50。 我想计算某个地区的降水量,比如说在lon=98.5, lon=100 and lat=4, lat=6.5 之间。这意味着,仅读取该区域中的变量-:

-------------------- |lon:98.5 lat:6.5| | | |lat:4 lon:100 | ---------------------

我曾经在 GrADS(网格分析和显示系统)中执行此操作。在 GrADS 中,可以这样做:(简化版)

      yy=1998
      while yr < 2011
        'sdfopen f:\data\trmm\3B42.'yy'.12.01.7A.nc'
        'd aave(pcp,lon=98.5,lon=100.0,lat=4.0,lat=6.5)'
         res=subwrd(result,4)
         rec=write('d:\precip.sp.TRMM3B42.1.'yy'.csv',res,append)   
         yy = yy+1
      endwhile

我尝试在 Python 中做同样的事情,但是出了点问题。 经过一些建议,我现在在这里:

     import csv
     import netCDF4 as nc 
     import numpy as np

     #calculating december only
     f = nc.MFDataset('d:/data/trmm/3B43.????.12.01.7A.nc')#maybe I shouldn't do MFDataset?
     pcpt = f.variables['pcp']
     lon = f.variables['longitude']
     lat = f.variables['latitude']
     # Determine which longitudes
     latidx1 = (lat >=4.0 ) & (lat <=6.5 ) 
     lonidx1 = (lon >=98.5 ) & (lon <=100.0 ) 

     rainf1 = pcpt[:]
     rainf1 = rainf1[:, latidx1][..., lonidx1]
     rainf_1 = rainf1

     with open('d:/trmmtest.csv', 'wb') as fp:
          a = csv.writer(fp)
          for i in rainf_1:
              a.writerow([i])

此脚本在 CSV 文件中生成(在我的情况下)15 个值的列表。 但是当我尝试获取另一个区域的值并调整我认为必要的值时,可以说:

     latidx2 = (lat >=1.0 ) & (lat <=1.5 ) 
     lonidx2 = (lon >=102.75 ) & (lon <=103.25 ) 

     rainf2 = pcpt[:]
     rainf2 = rainf2[:, latidx2][..., lonidx2]
     rainf_2 = rainf2

我得到与第一个相同的值。

firstarea=[0.511935,1.0771,0.613548,1.48839,0.445161,1.39161,1.03548,0.452903, 3.07725,2.84613 0.701613,2.10581,2.47839,3.84097,2.41065,1.38387]

secondarea=[0.511935,1.0771,0.613548,1.48839,0.445161,1.39161,1.03548,0.452903, 3.07725,2.84613,0.701613,2.10581,2.47839,3.84097,2.41065,1.38387]

我对单独的脚本进行了测试,它仍然给我相同的值。我确实检查了地图(之前构建的),这两个区域的值不同(12 月的平均值)。

知道为什么吗?有没有其他优雅的方式来写这个? 谢谢。

【问题讨论】:

  • 在哪里可以找到这些数据集?我找到了 TRMM 数据,但没有找到月度文件。你解决了这个问题吗?如果是这样,您可以回答自己的问题,这将对社区有所帮助。
  • 数据来自这里:link ...我还没有得到解决方案。在回到这个问题之前,我正在做其他事情。希望我能在此过程中有所收获。

标签: python average netcdf area cdo-climate


【解决方案1】:

我相信使用easymore包可以轻松完成。

第一步是创建一个 shapefile。这可以是任何形状(例如点、盆地或矩形)。在您的情况下,它将是一个矩形 shapefile,其中一个形状定义了边界。这可以在 QGIS、ArcGIS 或 python 中完成:

Creating a shape file from a bounding box coordinates list

接下来是调用easymore python包并将变量重新映射到感兴趣的shapefile,如下所示:

# loading EASYMORE
from easymore.easymore import easymore

# initializing EASYMORE object
esmr = easymore()

# specifying EASYMORE objects
# name of the case
esmr.case_name                = 'TRMM_3B43'              
# temporary path that the EASYMORE generated GIS files and remapped file will be saved
esmr.temp_dir                 = 'path/temporary/'
# name of target shapefile that the source netcdf files should be remapped to;
# it was created in the first step
esmr.target_shp               = 'path/target_shapefiles/box.shp'
# name of netCDF file(s); multiple files can be specified with *
esmr.source_nc                = ' d:/data/trmm/3B43*.nc'
# name of variables from source netCDF file(s) to be remapped
esmr.var_names                = ['pcp']
# name of variable longitude in source netCDF files
esmr.var_lon                  = 'longitude'
# name of variable latitude in source netCDF files
esmr.var_lat                  = 'latitude'
# name of variable time in source netCDF file; should be always time
esmr.var_time                 = 'time'
# location where the remapped netCDF, csv file will be saved
esmr.output_dir               = 'path/output/'
# if required that the remapped values to be saved as csv as well
esmr.save_csv                 = True

# execute EASYMORE nc remapper
esmr.nc_remapper()

此代码将为每个原始 nc 文件在输出目录中生成重新映射的 nc 文件及其 csv 版本。重新映射的文件将是原始时间分辨率(例如天)下感兴趣形状的降水面积平均值。然后,您可以轻松地将它们升级到每月的时间步长并进行比较。

优点:

1- 使用此软件包,您可以提供具有多个形状(感兴趣区域)的 shapefile,并且它可以一次性完成重新映射。例如,您可以改为提供世界各国的 shapefile。

2- 如果您的框小于网格(多边形)或点,则返回值将是小框或点所在的网格。

3- 重映射和加权在等面积内完成,以计算 WGS84 中更高纬度的不同等面积网格。

4- 代码足够智能,因此您无需担心 0 到 360 lon 格式和 -180 到 180 lon 格式的目标 shapefile。例如,如果盒子是 NA,负 lon 值,shapefile 可以以负 lon 格式给出 -180 到 180,而 nc 文件具有非负 lon 值(0 到 360)。

包含更多示例的 GitHub 页面:

https://github.com/ShervanGharari/EASYMORE

【讨论】:

    【解决方案2】:

    我只想指出 Fir Nor 的解决方案是不正确的,因为在处理常规纬度/经度网格上的空间数据时,不能像这里那样简单地使用算术平均值 (np.mean)因为随着您向两极移动,网格单元的大小会发生变化!

    Here is a discussion on the python xarray pages that demonstrates the differences that occur if you do not apply a weighted mean.

    我还制作了一个未装箱的youtube video on this topic 来解释为什么未加权平均值不正确以及如何使用 CDO 来计算空间统计数据。

    1. CDO 解决方案:

    最好不要担心这个并使用 CDO 进行操作:

    cdo fldmean -sellonlatbox,98.5,100,4.5,6 3B42.1998.05.01.7A.nc boxav.nc
    

    2。 Python解决方案

    如果你想用 python 来做这个,你需要为你的子区域生成权重,可以根据你的解决方案(或使用 xarray.where)提取权重。

    如果您的纬度是 1D,您可以使用 numpy.meshgrid 将其转换为 2D 数组

    然后在二维数组上生成权重,并计算weighted average:

     weights = np.cos(np.deg2rad(lat2d))
     meanrain = numpy.average(pcpt, weights=weights)
    

    Another example of the weights calculation using xarray and a diagnostic of the error is found my my answer here:

    【讨论】:

      【解决方案3】:

      如果您在 Linux 上工作,可以使用 nctoolkit (nctoolkit.readthedocs.io/en/latest/) 解决此问题。以下应该做所有事情:

      import nctoolkit as nc
      ff = '~/data/TRMM3H/3B42.19980101.12.7A.nc'
      data = nc.open_data(ff)
      data.clip(lon = [98.5, 100], lat = [4, 6.5])
      data.spatial_mean()
      

      注意:这里使用 CDO 作为后端,spatial_mean 将计算每个网格单元面积加权的平均值。

      【讨论】:

        【解决方案4】:

        过了一会儿,我又重新审视了这个问题,显然上面的方法几乎是正确的。经过几次调整,在单个数据文件上进行测试,并与 GrADS 解决方案进行交叉检查,我得到了这样的结果:

            f = nc.Dataset('~/data/TRMM3H/3B42.19980101.12.7A.nc')
            pcpt = f.variables['pcp'][:]
            lon = f.variables['longitude'][:]
            lat = f.variables['latitude'][:]
        
            #select two regions
            latidx1 = (lat >=4. ) & (lat <=6.5 ) 
            lonidx1 = (lon >=100.5 ) & (lon <=101.5 ) 
            latidx2 = (lat >=2.5 ) & (lat <=5.0 ) 
            lonidx2 = (lon >=101. ) & (lon <=102. ) 
        
            rainf = pcpt[:]
            #these basically listing the values in an array (2 in this case)
            rainf1 = rainf[:, latidx1][..., lonidx1]
            rainf2 = rainf[:, latidx2][..., lonidx2]
            rainf_1 = rainf1
            rainf_2 = rainf2
        
            #time to get the mean values
            print np.mean(rainf_1)
            print "............."
            print np.mean(rainf_2)
            print "............."
        

        这给了我这些结果:

            >>> execfile('find_percentile.py')
            0.7830327034
            .............
            1.56235361099
            .............
        

        用GrADS计算的结果是一样的。

        建议后编辑:

            f = nc.Dataset('~/data/TRMM3H/3B42.19980101.12.7A.nc')
            pcpt = f.variables['pcp'][:]
            lon = f.variables['longitude'][:]
            lat = f.variables['latitude'][:]
        
            #select two regions
            latidx1 = (lat >=4. ) & (lat <=6.5 ) 
            lonidx1 = (lon >=100.5 ) & (lon <=101.5 ) 
            latidx2 = (lat >=2.5 ) & (lat <=5.0 ) 
            lonidx2 = (lon >=101. ) & (lon <=102. ) 
        
            #these basically listing the values in an array (2 in this case)
            rainf1 = pcpt[:, latidx1][..., lonidx1]
            rainf2 = pcpt[:, latidx2][..., lonidx2]
            rainf_1 = rainf1
            rainf_2 = rainf2
        
            #time to get the mean values
            print np.mean(rainf_1)
            print "............."
            print np.mean(rainf_2)
            print "............."
        

        回到最初的问题,在多个文件中执行此操作并将其打印到 txt/csv 文件中仍在构建(和测试)中。

        【讨论】:

        • 小心所有这些变量的重新分配。它们不是必需的,并且会阻塞代码。只需读入变量名,在本例中为 pcpt 并对其执行算术运算。无需重命名为rainf。
        • 另请注意,此答案不正确,您必须使用纬度的余弦在常规纬度网格上使用空间平均值来缩放框大小。对于您的特定情况,该误差非常小,因为您仅在非常小的区域 4-6.5N 上进行平均,并且它也在热带地区。但更一般地说,这是不正确的,并且此代码会给更大的区域带来非常严重的错误,例如整个北半球,特别是对于具有强烈纬度梯度的领域。
        猜你喜欢
        • 1970-01-01
        • 2018-01-29
        • 2019-02-04
        • 1970-01-01
        • 2020-04-03
        • 2013-12-04
        • 1970-01-01
        • 2015-02-23
        • 1970-01-01
        相关资源
        最近更新 更多