爱气象,爱气象家园! 

气象家园

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博登陆

只需一步, 快速开始

搜索
查看: 3654|回复: 16

MeteoInfo脚本示例:GrADS to netCDF

[复制链接]

新浪微博达人勋

发表于 2015-4-16 17:36:12 | 显示全部楼层 |阅读模式

登录后查看更多精彩内容~

您需要 登录 才可以下载或查看,没有帐号?立即注册 新浪微博登陆

x
这里给出一个将GrADS数据文件转为netCDF数据文件的脚本示例程序,其它格式数据转netCDF可以参考:
  1. #-----------------------------------------------------
  2. # Author: Yaqiang Wang
  3. # Date: 2015-3-12
  4. # Purpose: Convert CUACE grads data to netCDF (CUACE/Dust)
  5. # Note: Sample
  6. #-----------------------------------------------------
  7. print 'Loading classes...'
  8. from org.meteoinfo.data import GridData
  9. from org.meteoinfo.data import DataMath
  10. from org.meteoinfo.data.meteodata import MeteoDataInfo
  11. from org.meteoinfo.geoprocess.analysis import ResampleMethods
  12. from org.meteoinfo.data.meteodata.netcdf import NetCDFDataInfo
  13. from org.meteoinfo.projection import ProjectionInfo
  14. from org.meteoinfo.projection import ProjectionNames
  15. from org.meteoinfo.projection import KnownCoordinateSystems
  16. from ucar.nc2 import NetcdfFileWriter
  17. from ucar.nc2 import Attribute
  18. from ucar.ma2 import DataType
  19. from ucar.ma2 import Array
  20. import os.path
  21. import jarray
  22. import datetime
  23. from java.util import Date
  24. from java.text import SimpleDateFormat

  25. #Set date
  26. year = 2014
  27. month = 4
  28. day = 23
  29. hour = 0
  30. sdate = datetime.datetime(year, month, day, hour)
  31. print sdate
  32. #Set directory
  33. dataDir = 'U:/data/cuace_dust/dust_example/2014_case'
  34. outDir = dataDir
  35. infn = os.path.join(dataDir, 'dust_post_'+ sdate.strftime('%Y%m%d%H') + '.ctl')
  36. outfn = os.path.join(dataDir, 'WMO_SDS-WAS_Asian_Center_Model_Forecasting_CUACE-Dust_CMA_' \
  37.     + sdate.strftime('%Y-%m-%d') + '.nc')
  38. #Set output X/Y coordinates and projection
  39. toProjInfo = KnownCoordinateSystems.geographic.world.WGS1984
  40. sx = 70.0
  41. xnum = 161
  42. sy = 20
  43. ynum = 71
  44. delta = 0.5
  45. xlist = []
  46. ylist = []
  47. for i in range(0, xnum):
  48.     xlist.append(sx + delta * i)
  49. for i in range(0, ynum):
  50.     ylist.append(sy + delta * i)
  51. X = jarray.array(xlist, 'd')
  52. Y = jarray.array(ylist, 'd')

  53. #Read GrADS data file
  54. print 'Open GrADS data file...'
  55. mdi = MeteoDataInfo()
  56. mdi.openGrADSData(infn)
  57. dataInfo = mdi.getDataInfo()
  58. dataInfo.setBigEndian(True)
  59. fromProjInfo = mdi.getProjectionInfo()
  60. tnum = dataInfo.getTimeNum()
  61. mvalue = dataInfo.getMissingValue()

  62. #Set output nc data file
  63. print 'Create output NC file: ' + outfn
  64. ncfile = NetcdfFileWriter.createNew(NetcdfFileWriter.Version.netcdf3, outfn)
  65. #Add dimensions
  66. print 'Add dimensions...'
  67. xDim = ncfile.addDimension(None, 'lon', xnum)
  68. yDim = ncfile.addDimension(None, 'lat', ynum)
  69. tDim = ncfile.addDimension(None, 'time', tnum)

  70. #Add global attributes
  71. print 'Add global attributes...'
  72. ncfile.addGroupAttribute(None, Attribute('Conventions', 'CF-1.6'))
  73. ncfile.addGroupAttribute(None, Attribute('Title', 'Sand and dust storm forecasting'))
  74. ncfile.addGroupAttribute(None, Attribute('Model', 'CUACE/Dust'))
  75. ncfile.addGroupAttribute(None, Attribute('Center', 'WMO SDS-WAS Asian Center'))
  76. ncfile.addGroupAttribute(None, Attribute('Agency', 'China Meteorological Administration'))

  77. #Add variables
  78. xvar = ncfile.addVariable(None, 'lon', DataType.FLOAT, [xDim])
  79. xvar.addAttribute(Attribute('units', 'degrees_east'))
  80. xvar.addAttribute(Attribute('long_name', 'Longitude'))
  81. xvar.addAttribute(Attribute('standard_name', 'longitude'))
  82. xvar.addAttribute(Attribute('axis', 'X'))
  83. yvar = ncfile.addVariable(None, 'lat', DataType.FLOAT, [yDim])
  84. yvar.addAttribute(Attribute('units', 'degrees_north'))
  85. yvar.addAttribute(Attribute('long_name', 'Latitude'))
  86. yvar.addAttribute(Attribute('standard_name', 'latitude'))
  87. yvar.addAttribute(Attribute('axis', 'Y'))
  88. tvar = ncfile.addVariable(None, 'time', DataType.INT, [tDim])
  89. tvar.addAttribute(Attribute('units', 'hours since 1900-01-01 00:00:0.0'))
  90. tvar.addAttribute(Attribute('long_name', 'Time'))
  91. tvar.addAttribute(Attribute('standart_name', 'time'))
  92. tvar.addAttribute(Attribute('axis', 'T'))
  93. #Data variables
  94. vnames = ['load','con','dry','wet','aod']
  95. varlist = []
  96. var = ncfile.addVariable(None, 'LOAD_DUST', DataType.FLOAT, [tDim, yDim, xDim])
  97. var.addAttribute(Attribute('long_name', 'Dust load'))
  98. var.addAttribute(Attribute('units', 'kg/m2'))
  99. var.addAttribute(Attribute('missing_value', -9999.0))
  100. varlist.append(var)
  101. var = ncfile.addVariable(None, 'SCONC_DUST', DataType.FLOAT, [tDim, yDim, xDim])
  102. var.addAttribute(Attribute('long_name', 'Surface dust concentration'))
  103. var.addAttribute(Attribute('units', 'ug/m3'))
  104. var.addAttribute(Attribute('missing_value', -9999.0))
  105. varlist.append(var)
  106. var = ncfile.addVariable(None, 'DDEPO_DUST', DataType.FLOAT, [tDim, yDim, xDim])
  107. var.addAttribute(Attribute('long_name', '3-hour accumulated dry deposition'))
  108. var.addAttribute(Attribute('units', 'kg/m2'))
  109. var.addAttribute(Attribute('missing_value', -9999.0))
  110. varlist.append(var)
  111. var = ncfile.addVariable(None, 'WDEPO_DUST', DataType.FLOAT, [tDim, yDim, xDim])
  112. var.addAttribute(Attribute('long_name', '3-hour accumulated wet deposition'))
  113. var.addAttribute(Attribute('units', 'kg/m2'))
  114. var.addAttribute(Attribute('missing_value', -9999.0))
  115. varlist.append(var)
  116. var = ncfile.addVariable(None, 'AOD550_DUST', DataType.FLOAT, [tDim, yDim, xDim])
  117. var.addAttribute(Attribute('long_name', 'Dust optical depth at 550nm'))
  118. var.addAttribute(Attribute('units', '-'))
  119. var.addAttribute(Attribute('missing_value', -9999.0))
  120. varlist.append(var)

  121. #Write nc file
  122. ncfile.create()
  123. #Write x,y,z,t variables
  124. print 'Write x variable...'
  125. shape = jarray.array([xnum], 'i')
  126. data = Array.factory(DataType.FLOAT, shape)
  127. for i in range(0,xnum):
  128.     data.set(i, X)
  129. ncfile.write(xvar, data)

  130. print 'Write y variable...'
  131. shape = jarray.array([ynum], 'i')
  132. data = Array.factory(DataType.FLOAT, shape)
  133. for i in range(0,ynum):
  134.     data.set(i, Y)
  135. ncfile.write(yvar, data)

  136. print 'Write time variable...'
  137. format = SimpleDateFormat('yyyy-MM-dd')
  138. sdate = format.parse('1900-01-01')
  139. tvalues = dataInfo.getTimeValues(sdate, 'hours')
  140. shape = jarray.array([tnum], 'i')
  141. data = Array.factory(DataType.INT, shape)
  142. for i in range(0,tnum):
  143.     data.set(i, tvalues)
  144. ncfile.write(tvar, data)

  145. #Write data variables
  146. print 'Write data variable...'
  147. for vname, var in zip(vnames, varlist):
  148.     for t in range(0, tnum):
  149.         print 'Time: ' + str(t + 1)
  150.         mdi.setTimeIndex(t)
  151.         gData = mdi.getGridData(vname)
  152.         ngData = gData.project(fromProjInfo, toProjInfo, X, Y, ResampleMethods.Bilinear)
  153.         origin = jarray.array([t, 0, 0], 'i')
  154.         ncfile.write(var, origin, NetCDFDataInfo.gridToArray3D(ngData))

  155. #Close nc file
  156. ncfile.flush()
  157. ncfile.close()

  158. print 'Finished'


V_SCONC_DUST_CUACE-Dust_CMA_20140423--loop-.gif
密码修改失败请联系微信:mofangbao

新浪微博达人勋

 楼主| 发表于 2015-4-16 17:39:59 | 显示全部楼层
上面转换的netCDF文件绘制模式结果和地面天气现象观测叠加动画图的示例脚本:
  1. # coding=utf-8
  2. #-----------------------------------------------------
  3. # Author: Yaqiang Wang
  4. # Date: 2015-3-13
  5. # Purpose: Read CUACE/Dust netCDF data and MICAPS observation data to plot figures
  6. # Note: Sample
  7. #-----------------------------------------------------
  8. print 'Loading classes...'
  9. from org.meteoinfo.layout import MapLayout
  10. from org.meteoinfo.data import GridData
  11. from org.meteoinfo.data.meteodata import MeteoDataInfo, DrawMeteoData
  12. from org.meteoinfo.legend import LegendScheme
  13. from org.meteoinfo.shape import ShapeTypes
  14. from org.meteoinfo.global.image import AnimatedGifEncoder
  15. import os.path
  16. import jarray
  17. import datetime
  18. import sys
  19. from java.util import Date, Calendar, Locale
  20. from java.text import SimpleDateFormat
  21. from java.awt import Color

  22. #Set date
  23. year = 2013
  24. month = 3
  25. day = 1
  26. hour = 0
  27. sdate = datetime.datetime(year, month, day, hour)

  28. #sdate = datetime.date.today()
  29. #if len(sys.argv) >= 2:
  30. #    sdate = sdate - datetime.timedelta(days=int(sys.argv[1]))
  31. #    sdate = sdate + datetime.timedelta(days=1)
  32. print sdate
  33. dformat = SimpleDateFormat('HH dd MMM yyy', Locale.ENGLISH)
  34. dformat1 = SimpleDateFormat('yyMMddHH')
  35. cal = Calendar.getInstance()

  36. #Set model
  37. #model = 'CUACE-DUST_CMA'
  38. model = 'ADAM2_KMA'

  39. #Set directory
  40. dataDir = 'D:/Working/2015/International/SDS_Asian_Region_Center/Model_Verification'
  41. obsDir = 'U:/data/micaps/2014/plot'
  42. obsDir = 'E:/MetData/micaps'
  43. runDir = dataDir
  44. outDir = os.path.join(dataDir, 'figure')
  45. if not os.path.exists(outDir):
  46.     os.mkdir(outDir)
  47. #Set input/output file names
  48. infn = os.path.join(dataDir, 'WMO_SDS-WAS_Asian_Center_Model_Forecasting_' + model + '_' \
  49.     + sdate.strftime('%Y-%m-%d') + '.nc')
  50. projfn = os.path.join(runDir, 'sds_asian.mip')

  51. #Plot data
  52. print 'Plot data...'
  53. mapLayout = MapLayout()
  54. mapLayout.loadProjectFile(projfn)
  55. mf = mapLayout.getActiveMapFrame()
  56. title = mapLayout.getTexts().get(2)
  57. legend = mapLayout.getLegends()[0]

  58. #---- Set weather list - sand and dust storm
  59. weathers = [6, 7, 8, 9, 30, 31, 32, 33, 34, 35]
  60. #---- Set weather list - sand and dust storm and haze
  61. #weathers = [5, 6, 7, 8, 9, 30, 31, 32, 33, 34, 35]

  62. #---- Create MeteoDataInfo object
  63. mdi = MeteoDataInfo()
  64. omdi = MeteoDataInfo()

  65. #---- Plot loop
  66. mdi.openNetCDFData(infn)
  67. lsfn = os.path.join(runDir,'dust_conc.lgs')
  68. print 'Read data file: ' + infn
  69. aLS = LegendScheme(ShapeTypes.Polygon)
  70. aLS.importFromXMLFile(lsfn)
  71. tnum = mdi.getDataInfo().getTimeNum()
  72. #tnum = 3
  73. s = 'SCONC_DUST'
  74. giffn = os.path.join(outDir, 'V_' + s + '_' + model + '_' + sdate.strftime('%Y%m%d') + '--loop-.gif')
  75. print giffn
  76. encoder = AnimatedGifEncoder()
  77. encoder.setRepeat(0)
  78. encoder.setDelay(1000)
  79. encoder.start(giffn)
  80. sTime = mdi.getDataInfo().getTimes().get(0)
  81. for t in range(1, tnum):
  82.     mdi.setTimeIndex(t)
  83.     aTime = mdi.getDataInfo().getTimes().get(t)
  84.     cal.setTime(aTime)
  85.     cal.add(Calendar.HOUR, 8)
  86.     bjTime = cal.getTime()
  87.     #---- Open observation weather data   
  88.     obsfn = os.path.join(obsDir, dformat1.format(bjTime) + '.000')
  89.     print obsfn
  90.     if not os.path.exists(obsfn):
  91.         continue
  92.     omdi.openMICAPSData(obsfn)
  93.     wData = omdi.getStationData('WeatherNow')
  94.     weatherLayer = DrawMeteoData.createWeatherSymbolLayer(wData, weathers, 'Weather')
  95.     #for lb in weatherLayer.getLegendScheme().getLegendBreaks():
  96.     #    lb.setColor(Color.red)
  97.     weatherLayer.setAvoidCollision(False)
  98.     mf.removeMeteoLayers()
  99.     mf.addLayer(weatherLayer)
  100.     #---- Get grid data and create a shaded layer
  101.     gData = mdi.getGridData(s)  
  102.     aLayer = DrawMeteoData.createShadedLayer(gData, aLS, 'Forecasting_' + s, 'Data', True)
  103.     aLayer.setProjInfo(mdi.getProjectionInfo())   
  104.     mf.addLayer(aLayer)
  105.     mf.moveLayer(aLayer, 0)
  106.     #---- Set title
  107.     title.setLabelText('Run: ' + dformat.format(sTime) + '    Valid: ' + dformat.format(aTime) \
  108.         + '(H+' + str(t * 3) + ')')
  109.     #---- Set legend
  110.     legend.setLegendLayer(aLayer)
  111.     mapLayout.paintGraphics()
  112.     encoder.addFrame(mapLayout.getViewImage())
  113.     figurefn = os.path.join(outDir, 'V_' + model + '_' + s + '_' + dformat1.format(aTime) + '.png')
  114.     print 'Output figure: ' + figurefn
  115.     mapLayout.exportToPicture(figurefn)

  116. encoder.finish()
  117. print 'Finished'


密码修改失败请联系微信:mofangbao
回复 支持 1 反对 0

使用道具 举报

新浪微博达人勋

发表于 2015-4-17 12:35:48 | 显示全部楼层
谢谢LZ,我研究下。
密码修改失败请联系微信:mofangbao

新浪微博达人勋

发表于 2015-4-19 16:38:10 | 显示全部楼层
这个帖子怎么收藏???
密码修改失败请联系微信:mofangbao

新浪微博达人勋

发表于 2015-4-23 23:57:45 | 显示全部楼层
知道了。。。
密码修改失败请联系微信:mofangbao
回复

使用道具 举报

新浪微博达人勋

发表于 2015-4-29 00:23:41 | 显示全部楼层
本帖最后由 MeteoInfo 于 2015-4-29 08:28 编辑


密码修改失败请联系微信:mofangbao

新浪微博达人勋

发表于 2015-5-1 00:01:23 | 显示全部楼层
怎么修改用户名?
密码修改失败请联系微信:mofangbao

新浪微博达人勋

发表于 2015-5-1 07:49:34 | 显示全部楼层
大大的点个赞
密码修改失败请联系微信:mofangbao

新浪微博达人勋

发表于 2015-5-3 12:25:52 | 显示全部楼层
MeteoInfo 发表于 2015-4-16 17:39
上面转换的netCDF文件绘制模式结果和地面天气现象观测叠加动画图的示例脚本:

王老师,这个meteoinfo能用地图文件裁剪nc数据得到底图的区域吗
密码修改失败请联系微信:mofangbao

新浪微博达人勋

 楼主| 发表于 2015-5-3 15:36:13 | 显示全部楼层
人生路 发表于 2015-5-3 12:25
王老师,这个meteoinfo能用地图文件裁剪nc数据得到底图的区域吗

可以
密码修改失败请联系微信:mofangbao
您需要登录后才可以回帖 登录 | 立即注册 新浪微博登陆

本版积分规则

Copyright ©2011-2014 bbs.06climate.com All Rights Reserved.  Powered by Discuz! (京ICP-10201084)

本站信息均由会员发表,不代表气象家园立场,禁止在本站发表与国家法律相抵触言论

快速回复 返回顶部 返回列表