写在前面

在我看来,学习一种编程语言最快的方法,就是将每一行的代码理解他的意思,明白运行这行代码运行之后会产生什么结果。这样下次你要进行数据处理时你或许就知道应该使用哪些函数了。

最近我刚好在学习使用ncl处理数据,下面是一个计算daily资料气候态平均的ncl代码。

我来理解的方法是打印出每一个环节的结果,这样我就知道他是用来干嘛了。这对于刚刚入门NCL的我来说非常有用。

NCL | cal daily climatology

下面来分解代码,尝试理解每一段代码块的意思

读取数据中的time变量

f    = addfile("/DatadiskExt/xpji/data_interp/tas_interp/tas_day_EC-Earth3_data_1997-2014_regrid_2x2.nc","r")
time = f->time ;-- get time values
print("----------------------------")
print("Time variable information:")
printVarSummary(time)

这里在python我通常直接

import xarray as xr
time = xr.open_dataset(path).time

输出得到:


(0)     ----------------------------
(0)     Time variable information:

Variable: time
Type: double
Total Size: 52592 bytes
            6574 values
Number of Dimensions: 1
Dimensions and sizes:   [time | 6574]
Coordinates:
            time: [53691.5..60264.5]
Number Of Attributes: 5
  standard_name :       time
  long_name :   time
  units :       days since 1850-01-01
  calendar :    proleptic_gregorian
  axis :        T

定义起始 | 终止时间 , 并将时间转换为年

ymdStrt = 20060101 ;-- start yyyymmdd
ymdLast = 20061231 ;-- last
yrStrt  = ymdStrt/10000
yrLast  = ymdLast/10000
print("----------------------------")
print("Start year: " + yrStrt)
print("End year: " + yrLast)

这里在python可以通过切片的方式来实现时间的截取

import xarray as xr
time = xr.open_dataset(path).sel(time=slice('start','end'))

输出得到:

(0)     ----------------------------
(0)     Start year: 2006
(0)     End year: 2006

使用 cd_calendar 函数将时间变量转换为 yyyymmdd 格式。

  ymd = cd_calendar(time, -2)   ;-- yyyymmdd
  print("----------------------------")
  print("ymd variable information:")
  printVarSummary(ymd)

这里在python可以通过datetime来实现,这里确实没有ncl方便

from datetime import datetime

# 假设你有一个时间字符串
date_string = "2024-05-29 14:30:00"

# 将字符串转换为 datetime 对象
date_object = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")

输出得到:


(0)     ymd variable information:

Variable: ymd
Type: integer
Total Size: 26296 bytes
            6574 values
Number of Dimensions: 1
Dimensions and sizes:   [6574]
Coordinates:
Number Of Attributes: 1
  calendar :    proleptic_gregorian

找到起始日期和结束日期在 ymd 数组中的索引 (iStrt 和 iLast)。

  iStrt = ind(ymd .eq. ymdStrt) ;-- index start
  iLast = ind(ymd .eq. ymdLast) ;-- index last
  print("----------------------------")
  print("Start index: " + iStrt)
  print("End index: " + iLast)

输出得到:


(0)     ----------------------------
(0)     Start index: 3287
(0)     End index: 3651

在python里面没必要通过找index的方式来截取数据,倒是在matlab里面习惯这样

删除原始的 time 和 ymd 变量以释放内存 | 重新读取指定时间范围内的时间变量 time。

  delete([/time,ymd/])

  time = f->time(iStrt:iLast)   ;-- time:units = "hours since"
  print("----------------------------")
  print("Selected time variable information:")
  printVarSummary(time)

输出得到:


(0)     ----------------------------
(0)     Selected time variable information:

Variable: time
Type: double
Total Size: 2920 bytes
            365 values
Number of Dimensions: 1
Dimensions and sizes:   [time | 365]
Coordinates:
            time: [56978.5..57342.5]
Number Of Attributes: 5
  standard_name :       time
  long_name :   time
  units :       days since 1850-01-01
  calendar :    proleptic_gregorian
  axis :        T

搞半天就为了截取数据,,,

将时间变量 time 转换为 cd_calendar 函数的 float 类型

  TIME = cd_calendar(time, 0)   ;-- type float
  print("----------------------------")
  print("TIME variable information:")
  printVarSummary(TIME)

输出得到:


(0)     ----------------------------
(0)     TIME variable information:

Variable: TIME
Type: float
Total Size: 8760 bytes
            2190 values
Number of Dimensions: 2
Dimensions and sizes:   [365] x [6]
Coordinates:
Number Of Attributes: 1
  calendar :    proleptic_gregorian

将 TIME 数组的列转换为 year、month 和 day。

  year = toint(TIME(:,0))
  month = toint(TIME(:,1))
  day = toint(TIME(:,2))
  print("----------------------------")
  print("Year variable information:")
  printVarSummary(year)
  print("Month variable information:")
  printVarSummary(month)
  print("Day variable information:")
  printVarSummary(day)

输出得到:


(0)     ----------------------------
(0)     Year variable information:

Variable: year
Type: integer
Total Size: 1460 bytes
            365 values
Number of Dimensions: 1
Dimensions and sizes:   [365]
Coordinates:
(0)     Month variable information:

Variable: month
Type: integer
Total Size: 1460 bytes
            365 values
Number of Dimensions: 1
Dimensions and sizes:   [365]
Coordinates:
(0)     Day variable information:

Variable: day
Type: integer
Total Size: 1460 bytes
            365 values
Number of Dimensions: 1
Dimensions and sizes:   [365]
Coordinates:

计算每年的天数 (ddd)。

  ddd = day_of_year(year, month, day)
  print("----------------------------")
  print("Day of year variable information:")
  printVarSummary(ddd)

输出得到:


(0)     ----------------------------
(0)     Day of year variable information:

Variable: ddd
Type: integer
Total Size: 1460 bytes
            365 values
Number of Dimensions: 1
Dimensions and sizes:   [365]
Coordinates:

生成 yyyyddd 格式的日期,以年和天数的组合表示

  yyyyddd = year*1000 + ddd  ;-- needed for input
  print("----------------------------")
  print("yyyyddd variable information:")
  printVarSummary(yyyyddd)

输出得到:

(0)     ----------------------------
(0)     yyyyddd variable information:

Variable: yyyyddd
Type: integer
Total Size: 1460 bytes
            365 values
Number of Dimensions: 1
Dimensions and sizes:   [365]
Coordinates:

在指定时间范围内读取温度数据变量 tas

  tas = f->tas(iStrt:iLast,:,:)  ;-- read variable within time range
  print("----------------------------")
  print("tas variable information:")
  printVarSummary(tas)

输出得到:

(0)     ----------------------------
(0)     tas variable information:

Variable: tas
Type: float
Total Size: 23652000 bytes
            5913000 values
Number of Dimensions: 3
Dimensions and sizes:   [time | 365] x [lat | 90] x [lon | 180]
Coordinates:
            time: [56978.5..57342.5]
            lat: [ -89..  89]
            lon: [   0.. 358]
Number Of Attributes: 2
  _FillValue :  nan
  missing_value :       nan

计算每日气候学平均值 tasClmDay | 对每日气候学平均值进行平滑处理,得到 tasClmDay_sm

  ;-- compute daily climatology
  tasClmDay = clmDayTLL(tas, yyyyddd)        ;-- daily climatology at each grid point
  print("----------------------------")
  print("Daily climatology variable information:")
  printVarSummary(tasClmDay)

  tasClmDay_sm = smthClmDayTLL(tasClmDay,4)  ;-- daily climatology - smoothed
  print("----------------------------")
  print("Smoothed daily climatology variable information:")
  printVarSummary(tasClmDay_sm)

这里,在python中可以通过xarray.groupby()来实现数据的分类以及求平均等可能需要好几个步骤(当然也可以几步写为函数);这里体现了NCL的方便,一行代码直接实现;

下面是一个去除季节趋势的python代码


  
def remove_seasonal_trend():
    
    precip_clim = (
    pre
    .groupby("time.month")
    .mean(dim="time"))
    
    precip_clim
    
    precip_anom = pre.groupby("time.month") - precip_clim
    precip_anom
    
    return precip_anom
    
    
pre_anom =    remove_seasonal_trend() 

输出得到:

(0)     ----------------------------
(0)     Daily climatology variable information:

Variable: tasClmDay
Type: float
Total Size: 23716800 bytes
            5929200 values
Number of Dimensions: 3
Dimensions and sizes:   [year_day | 366] x [lat | 90] x [lon | 180]
Coordinates:
            year_day: [1..366]
            lat: [ -89..  89]
            lon: [   0.. 358]
Number Of Attributes: 3
  long_name :   Daily Climatology
  information : Raw daily averages across all years
  smoothing :   None
(0)     ----------------------------
(0)     Smoothed daily climatology variable information:

Variable: tasClmDay_sm
Type: float
Total Size: 23716800 bytes
            5929200 values
Number of Dimensions: 3
Dimensions and sizes:   [year_day | 366] x [lat | 90] x [lon | 180]
Coordinates:
            year_day: [1..366]
            lat: [ -89..  89]
            lon: [   0.. 358]
Number Of Attributes: 3
  smoothing :   FFT: 4 harmonics were retained.
  information : Smoothed daily climatological averages
  long_name :   Daily Climatology

创建包含原始和平滑气候学平均值的数组 data

  ;-- set lat/lon where to compute the climatology
  lat = 60
  lon = 270
  ;-- create data array containing both climatologies
  data = new ( (/2,366/), typeof(tasClmDay), getFillValue(tasClmDay))
  data(0,:) = tasClmDay(:,{lat},{lon})
  data(1,:) = tasClmDay_sm(:,{lat},{lon})
  print("----------------------------")
  print("Data array variable information:")
  printVarSummary(data)

ncl这里创建数组的方式我觉得挺离谱的,看不习惯

输出得到:

(0)     ----------------------------
(0)     Data array variable information:

Variable: data
Type: float
Total Size: 2928 bytes
            732 values
Number of Dimensions: 2
Dimensions and sizes:   [2] x [year_day | 366]
Coordinates:
            year_day: [1..366]
Number Of Attributes: 3
  long_name :   Daily Climatology
  information : Smoothed daily climatological averages
  smoothing :   FFT: 4 harmonics were retained.

创建x轴的值 x,表示一年中的天数

  ;-- create x-axis values
  x = ispan(0,365,1)
  x@units = "days"
  print("----------------------------")
  print("X-axis variable information:")
  printVarSummary(x)

输出得到:


(0)     ----------------------------
(0)     X-axis variable information:

Variable: x
Type: integer
Total Size: 1464 bytes
            366 values
Number of Dimensions: 1
Dimensions and sizes:   [366]
Coordinates:
Number Of Attributes: 1
  units :       days

将混合的Julian/Gregorian日期转换为UTC日期 utc_date | 提取年、月、日,并组合成字符串 date_str。

  ;-- convert a mixed Julian/Gregorian date to a UT-referenced date
  utc_date = cd_calendar(time, 0)
  year = toint(utc_date(:,0))
  month = toint(utc_date(:,1))
  day = toint(utc_date(:,2))
  date_str = sprinti("%0.4i-",year)+sprinti("%0.2i-",month)+sprinti("%0.2i",day)
  print("----------------------------")
  print("UTC date variable information:")
  printVarSummary(utc_date)
  print("Date strings variable information:")
  printVarSummary(date_str)

这里看着挺新奇的,虽然只是字符串拼接;但是在python中基本没怎么处理过时间的格式,基本上用的再分析资料的时间都是挺规整的

输出得到:

(0)     ----------------------------
(0)     UTC date variable information:

Variable: utc_date
Type: float
Total Size: 8760 bytes
            2190 values
Number of Dimensions: 2
Dimensions and sizes:   [365] x [6]
Coordinates:
Number Of Attributes: 1
  calendar :    proleptic_gregorian
(0)     Date strings variable information:

Variable: date_str
Type: string
Total Size: 2920 bytes
            365 values
Number of Dimensions: 1
Dimensions and sizes:   [365]
Coordinates:

绘图代码

绘图部分没啥好说的,适当了解一下,毕竟绘图我还是更习惯使用python

plot_daily_climatology

打开一个绘图工作站用于生成图形 | 类似于python 里面创建一个figure

;-- open workstation
wks_type = "png"
wks_type@wkWidth = 1200
wks_type@wkHeight = 1200
wks = gsn_open_wks(wks_type,"plot_daily_climatology")  ;-- open a workstation

解释:

打开一个绘图工作站用于生成图形。
wks_type 设置为 "png" 表示输出格式为PNG图片。
wks_type@wkWidth 和 wks_type@wkHeight 设置图形的宽度和高度为1200像素。
gsn_open_wks 函数打开一个工作站,并将其命名为 "plot_daily_climatology"。

设置图片的高宽,位置 | 类似于python中的figsize ,aspect ,axes

;-- set resources
res = True
res@vpHeightF = 0.5    ;-- viewport height
res@vpWidthF = 0.8     ;-- viewport width
res@vpXF = 0.12        ;-- viewport x-position

解释:

​创建一个资源对象 res 并启用它。
res@vpHeightF 设置视口的高度为0.5。
res@vpWidthF 设置视口的宽度为0.8。
res@vpXF 设置视口的x位置为0.12。

设置图形的x轴和y轴的最小值和最大值 | 类似于python中的xlim 、 ylim

res@trXMinF = min(x)   ;-- x-axis min value
res@trXMaxF = max(x)   ;-- x-axis max value
res@trYMinF = 240.0    ;-- y-axis min value
res@trYMaxF = 290.0    ;-- y-axis max value

解释:


res@trXMinF 和 res@trXMaxF 分别设置x轴的最小值和最大值为 x 数组的最小值和最大值。
res@trYMinF 和 res@trYMaxF 分别设置y轴的最小值为240.0和最大值为290.0。

设置x轴刻度和标签的相关属性。 | 类似于python中的xticks 、 yticks、xaxis.set_major_locator()

res@tmXBMode = "Manual"               ;-- don't use default settings for tick marks
res@tmXBTickSpacingF = 30             ;-- x major tick mark spacing
res@tmXBMinorPerMajor = 2             ;-- set number of minor tick marks
res@tmXBLabelDeltaF = 0.15            ;-- move x-axis labels down
res@tmXBLabelFontHeightF = 0.012      ;-- decrease x-axis label font size

解释:

res@tmXBMode 设置为 "Manual",表示不使用默认的刻度设置。
res@tmXBTickSpacingF 设置x轴主要刻度的间隔为30。
res@tmXBMinorPerMajor 设置每个主要刻度间的次要刻度数量为2。
res@tmXBLabelDeltaF 设置x轴标签向下移动0.15。
res@tmXBLabelFontHeightF 设置x轴标签字体大小为0.012。

设置图形的标题和轴的标签 | 类似于python中的xticklabels

res@tiMainString = "DKRZ NCL Example: Daily Climatology" ;-- title string
res@tiXAxisString = x@units           ;-- x-axis string
res@tiXAxisFontHeightF = 0.012        ;-- x-axis label font size
res@tiYAxisFontHeightF = 0.012        ;-- y-axis label font size

解释:


res@tiMainString 设置图形的主标题为 "DKRZ NCL Example: Daily Climatology"。
res@tiXAxisString 设置x轴标签为 x 变量的单位属性值。
res@tiXAxisFontHeightF 和 res@tiYAxisFontHeightF 分别设置x轴和y轴标签字体大小为0.012。

设置线条的相关属性 | 类似于python中的plt.plot(color=’b’)

res@xyLineThicknesses = (/1.0, 2.0/)  ;-- make 2nd lines thicker
res@xyLineColors = (/"blue","red"/)   ;-- change line color
res@xyMonoDashPattern = True          ;-- all solid
res@xyMarkLineModes = "Lines"         ;-- line mode

解释:


res@xyLineThicknesses 设置两条线的粗细,第2条线的粗细为2.0,较第1条线更粗。
res@xyLineColors 设置两条线的颜色,分别为蓝色和红色。
res@xyMonoDashPattern 设置为 True,表示所有线条为实线。
res@xyMarkLineModes 设置为 "Lines",表示线条模式。

使用 gsn_csm_y 函数创建图形 |

;-- create the plot
plot = gsn_csm_y(wks,data,res)

解释:

wks 为前面打开的工作站。
data 为要绘制的数据数组。
res 为设置的资源对象。
plot 为创建的图形对象。

以下是全部的代码


;--------------------------------------------------------------------
; NCL example: compute_daily_climatology_and_draw_timeseries.ncl
;
; Description:  compute the daily climatology; raw and smooth
;--------------------------------------------------------------------

begin

  f    = addfile("/DatadiskExt/data_interp/tas_interp/tas_day_EC-Earth3_regrid_2x2.nc","r")
  time = f->time ;-- get time values
  print("----------------------------")
  print("Time variable information:")
  printVarSummary(time)

  ymdStrt = 20060101 ;-- start yyyymmdd
  ymdLast = 20061231 ;-- last
  yrStrt  = ymdStrt/10000
  yrLast  = ymdLast/10000
  print("----------------------------")
  print("Start year: " + yrStrt)
  print("End year: " + yrLast)

  ymd = cd_calendar(time, -2)   ;-- yyyymmdd
  print("----------------------------")
  print("ymd variable information:")
  printVarSummary(ymd)

  iStrt = ind(ymd .eq. ymdStrt) ;-- index start
  iLast = ind(ymd .eq. ymdLast) ;-- index last
  print("----------------------------")
  print("Start index: " + iStrt)
  print("End index: " + iLast)

  delete([/time,ymd/])

  time = f->time(iStrt:iLast)   ;-- time:units = "hours since"
  print("----------------------------")
  print("Selected time variable information:")
  printVarSummary(time)

  TIME = cd_calendar(time, 0)   ;-- type float
  print("----------------------------")
  print("TIME variable information:")
  printVarSummary(TIME)

  year = toint(TIME(:,0))
  month = toint(TIME(:,1))
  day = toint(TIME(:,2))
  print("----------------------------")
  print("Year variable information:")
  printVarSummary(year)
  print("Month variable information:")
  printVarSummary(month)
  print("Day variable information:")
  printVarSummary(day)

  ddd = day_of_year(year, month, day)
  print("----------------------------")
  print("Day of year variable information:")
  printVarSummary(ddd)

  yyyyddd = year*1000 + ddd  ;-- needed for input
  print("----------------------------")
  print("yyyyddd variable information:")
  printVarSummary(yyyyddd)

  tas = f->tas(iStrt:iLast,:,:)  ;-- read variable within time range
  print("----------------------------")
  print("tas variable information:")
  printVarSummary(tas)

  ;-- compute daily climatology
  tasClmDay = clmDayTLL(tas, yyyyddd)        ;-- daily climatology at each grid point
  print("----------------------------")
  print("Daily climatology variable information:")
  printVarSummary(tasClmDay)

  tasClmDay_sm = smthClmDayTLL(tasClmDay,4)  ;-- daily climatology - smoothed
  print("----------------------------")
  print("Smoothed daily climatology variable information:")
  printVarSummary(tasClmDay_sm)

  ;-- set lat/lon where to compute the climatology
  lat = 60
  lon = 270

  ;-- create data array containing both climatologies
  data = new ( (/2,366/), typeof(tasClmDay), getFillValue(tasClmDay))
  data(0,:) = tasClmDay(:,{lat},{lon})
  data(1,:) = tasClmDay_sm(:,{lat},{lon})
  print("----------------------------")
  print("Data array variable information:")
  printVarSummary(data)

  ;-- create x-axis values
  x = ispan(0,365,1)
  x@units = "days"
  print("----------------------------")
  print("X-axis variable information:")
  printVarSummary(x)

  ;-- convert a mixed Julian/Gregorian date to a UT-referenced date
  utc_date = cd_calendar(time, 0)
  year = toint(utc_date(:,0))
  month = toint(utc_date(:,1))
  day = toint(utc_date(:,2))
  date_str = sprinti("%0.4i-",year)+sprinti("%0.2i-",month)+sprinti("%0.2i",day)
  print("----------------------------")
  print("UTC date variable information:")
  printVarSummary(utc_date)
  print("Date strings variable information:")
  printVarSummary(date_str)
  ;-- open workstation
   wks_type = "png"
   wks_type@wkWidth = 1200
   wks_type@wkHeight = 1200
   wks = gsn_open_wks(wks_type,"plot_daily_climatology")  ;-- open a workstation

  ;-- set resources
   res = True
   res@vpHeightF = 0.5    ;-- viewport height
   res@vpWidthF = 0.8     ;-- viewport width
   res@vpXF = 0.12        ;-- viewport x-position

   res@trXMinF = min(x)   ;-- x-axis min value
   res@trXMaxF = max(x)   ;-- x-axis max value
   res@trYMinF = 240.0    ;-- y-axis min value
   res@trYMaxF = 290.0    ;-- y-axis max value

   res@tmXBMode = "Manual"               ;-- don't use default settings for tick marks
   res@tmXBTickSpacingF = 30             ;-- x major tick mark spacing
   res@tmXBMinorPerMajor = 2             ;-- set number of minor tick marks
   res@tmXBLabelDeltaF = 0.15            ;-- move x-axis labels down
   res@tmXBLabelFontHeightF = 0.012      ;-- decrease x-axis label font size

   res@tiMainString = "Daily Climatology of tas" ;-- title string
   res@tiXAxisString = x@units           ;-- x-axis string
   res@tiXAxisFontHeightF = 0.012        ;-- x-axis label font size
   res@tiYAxisFontHeightF = 0.012        ;-- y-axis label font size

   res@xyLineThicknesses = (/1.0, 2.0/)  ;-- make 2nd lines thicker
   res@xyLineColors = (/"blue","red"/)   ;-- change line color
   res@xyMonoDashPattern = True          ;-- all solid
   res@xyMarkLineModes = "Lines"         ;-- line mode

  ;-- create the plot
   plot = gsn_csm_y(wks,data,res)
end


总的来说,这种方法其实挺傻的;但是对刚开始学编程或者新上手一种语言时,确实挺有效果,多写写代码自然就记得住了。

同时,这样也方便去debug找错误,一般这样去了解几个代码就能很快熟悉函数的功能了,下面就是不断积累的过程了;再后面就是遇到什么新的需求,再去学习其他的函数或者功能;慢慢处理的多了,就感觉慢慢上手了;anyway,只是简单分享一下比较基础的ncl代码,记录一下最近学习的过程~

https://www.ncl.ucar.edu/Applications/climo.shtml

https://docs.dkrz.de/doc/visualization/sw/ncl/examples/source_code/dkrz-ncl-daily-climatology.html