爱气象,爱气象家园! 

气象家园

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博登陆

只需一步, 快速开始

搜索
查看: 91321|回复: 85

[经验总结] 一点总结:Ubuntu+anaconda+Python+basemap(+WRF)

  [复制链接]

新浪微博达人勋

发表于 2016-11-29 19:10:30 | 显示全部楼层 |阅读模式

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

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

x
本帖最后由 8828 于 2017-7-14 16:55 编辑

看到我们的Python板块有了关于气象应用的帖子,我也想来分享一些东西。这是将我周末弄得一些东西,系统整理一下。(从零开始,有很多不足,刚开始接触Python的气象应用)
outline:
1、Python科学计算环境的搭建
2、Python气象库的应用例子
3、WRF-Python处理

一、Python科学计算环境的搭建
#推荐两种环境:①canopy
                         ②anaconda
#这里主要应用anaconda
#个人使用平台: Ubuntu16.04(个人科研学习拒绝Windows)

#声明:所有的下载渠道配置到清华镜像上(除个别库外优先选择该channel)

1.下载客户端 :客户端传送门
2.开始搭建:
#我开始安装的是miniconda,详细问题百度
  1. $bash *.sh # *.sh为下载的文件
复制代码
  1. $conda #检测是否安装成功

  2. $conda create -n basemap python=2 #创建虚拟环境

  3. ###配置清华镜像
  4. $conda config --add channels 'https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/'
  5. $conda config --set show_channel_urls yes
  6. ###云大镜像正在编写程序中,欢迎到云大开源中心访问

  7. ###气象所需库:basemap  (属于matplotlib)
  8. $conda install basemap
  9. ###自动配置相关所需库,使用镜像快的飞起。环境算基本搭建完毕,详细内容百度,如遇错误,最好的办法是研究报错信息

  10. ###下面介绍basemap的例子,涉及到WRF的内容在第三部分

复制代码
二、应用举例
###由于图片放入代码模式里,代码中只显示图片代码,效果图在最后
  1. #来自相关网站,个人修改,相关网址最后总结
  2. from mpl_toolkits.basemap import Basemap
  3. import matplotlib.pyplot as plt
  4. import numpy as np
  5. import pdb
  6. # set up orthographic map projection with
  7. # perspective of satellite looking down at 50N, 100W.
  8. # use low resolution coastlines.
  9. # don't plot features that are smaller than 1000 square km.
  10. map = Basemap(projection='ortho', lat_0 = 35, lon_0 = 135,
  11.               resolution = 'l', area_thresh = 1000.)

  12. # draw coastlines, country boundaries, fill continents.
  13. """map.drawcoastlines()
  14. map.drawcountries()
  15. map.fillcontinents(color = 'coral')"""

  16. #NASA instead of baove, conda install PIL
  17. map.bluemarble()

  18. # draw the edge of the map projection region (the projection limb)
  19. map.drawmapboundary()
  20. # draw lat/lon grid lines every 30 degrees.
  21. map.drawmeridians(np.arange(0, 360, 30))
  22. map.drawparallels(np.arange(-90, 90, 30))

  23. # lat/lon coordinates of five cities.
  24. """lats = [40.02, 32.73, 38.55, 48.25, 17.29]
  25. lons = [-105.16, -117.16, -77.00, -114.21, -88.10]
  26. cities=['Boulder, CO','San Diego, CA',
  27.         'Washington, DC','Whitefish, MT','Belize City, Belize']"""

  28. #cities
  29. lats   = [25.05,  39.91]
  30. lons   = [102.73,  116.41]
  31. cities = ['Kunming',  'Tangshan']      
  32. # compute the native map projection coordinates for cities.
  33. x,y = map(lons,lats)
  34. # plot filled circles at the locations of the cities.
  35. map.plot(x,y,'bo')
  36. # plot the names of those five cities.
  37. for name,xpt,ypt in zip(cities,x,y):
  38.     plt.text(xpt+50000,ypt+50000,name)

  39. # make up some data on a regular lat/lon grid.
  40. nlats = 73; nlons = 145; delta = 2.*np.pi/(nlons-1)
  41. lats = (0.5*np.pi-delta*np.indices((nlats,nlons))[0,:,:])
  42. lons = (delta*np.indices((nlats,nlons))[1,:,:])
  43. wave = 0.75*(np.sin(2.*lats)**8*np.cos(4.*lons))
  44. mean = 0.5*np.cos(2.*lats)*((np.sin(2.*lats))**2 + 2.)
  45. # compute native map projection coordinates of lat/lon grid.
  46. x, y = map(lons*180./np.pi, lats*180./np.pi)
  47. # contour data over the map.
  48. CS = map.contour(x,y,wave+mean,15,linewidths=1.5)

  49. #save figure
  50. plt.savefig('city.png', bbox_inches='tight')
  51. plt.show()

  52. <img src="http://bbs.06climate.com/forum.php?mod=image&aid=59639&size=300x300&key=b5af3a6ca1216f08&nocache=yes&type=fixnone" aid="attachimg_59639" alt="" width="433" border="0" height="388">

复制代码
###Python与NASA数据的结合

  1. ###当时保存的图片是前几天的,利用Python的datetime模块可获得此刻时间
  2. import numpy as np
  3. from mpl_toolkits.basemap import Basemap
  4. import matplotlib.pyplot as plt
  5. from datetime import datetime
  6. # miller projection
  7. map = Basemap(projection='mill',lon_0=180)
  8. # plot coastlines, draw label meridians and parallels.
  9. map.drawcoastlines()
  10. map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0])
  11. map.drawmeridians(np.arange(map.lonmin,map.lonmax+30,60),labels=[0,0,0,1])
  12. # fill continents 'coral' (with zorder=0), color wet areas 'aqua'
  13. map.drawmapboundary(fill_color='aqua')
  14. map.fillcontinents(color='coral',lake_color='aqua')
  15. # shade the night areas, with alpha transparency so the
  16. # map shows through. Use current time in UTC.
  17. date = datetime.utcnow()
  18. CS=map.nightshade(date)
  19. plt.title('Day/Night Map for %s (UTC)' % date.strftime("%d %b %Y %H:%M:%S"))
  20. plt.savefig('day_night' , bbox_inches='tight')
  21. plt.show()

  22. <img src="http://bbs.06climate.com/forum.php?mod=image&aid=59640&size=300x300&key=7c7d93cc3e23dbab&nocache=yes&type=fixnone" aid="attachimg_59640" alt="" width="416" border="0" height="314">
复制代码
#####Python库很强大##########

  1. #Python的模块可以在网上抓取数据,进而直接提取数据
  2. from mpl_toolkits.basemap import Basemap
  3. from netCDF4 import Dataset, date2index
  4. import numpy as np
  5. import matplotlib.pyplot as plt
  6. from datetime import datetime
  7. date = datetime(2007,01,01,0) # date to plot.
  8. # open dataset.
  9. dataset = \
  10. Dataset('http://www.ncdc.noaa.gov/thredds/dodsC/OISST-V2-AVHRR_agg')
  11. timevar = dataset.variables['time']
  12. timeindex = date2index(date,timevar) # find time index for desired date.
  13. # read sst.  Will automatically create a masked array using
  14. # missing_value variable attribute. 'squeeze out' singleton dimensions.
  15. sst = dataset.variables['sst'][timeindex,:].squeeze()
  16. # read ice.
  17. ice = dataset.variables['ice'][timeindex,:].squeeze()
  18. # read lats and lons (representing centers of grid boxes).
  19. lats = dataset.variables['lat'][:]
  20. lons = dataset.variables['lon'][:]
  21. lons, lats = np.meshgrid(lons,lats)
  22. # create figure, axes instances.
  23. fig = plt.figure()
  24. ax = fig.add_axes([0.05,0.05,0.9,0.9])
  25. # create Basemap instance.
  26. # coastlines not used, so resolution set to None to skip
  27. # continent processing (this speeds things up a bit)
  28. m = Basemap(projection='kav7',lon_0=0,resolution=None)
  29. # draw line around map projection limb.
  30. # color background of map projection region.
  31. # missing values over land will show up this color.
  32. m.drawmapboundary(fill_color='0.3')
  33. # plot sst, then ice with pcolor
  34. im1 = m.pcolormesh(lons,lats,sst,shading='flat',cmap=plt.cm.jet,latlon=True)
  35. im2 = m.pcolormesh(lons,lats,ice,shading='flat',cmap=plt.cm.gist_gray,latlon=True)
  36. # draw parallels and meridians, but don't bother labelling them.
  37. m.drawparallels(np.arange(-90.,99.,30.))
  38. m.drawmeridians(np.arange(-180.,180.,60.))
  39. # add colorbar
  40. cb = m.colorbar(im1,"bottom", size="5%", pad="2%")
  41. # add a title.
  42. ax.set_title('SST and ICE analysis for %s'%date)
  43. # save figure
  44. plt.savefig('sst1.png', bbox_inches='tight')
  45. plt.show()
  46. <img src="http://bbs.06climate.com/forum.php?mod=image&aid=59641&size=300x300&key=eab0e1429a062936&nocache=yes&type=fixnone" aid="attachimg_59641" alt="" border="0">
复制代码


############展示一些其他例子,原脚本来自官网,做个人修改##########
SLP and Wind_.png SLP and Wind.png
figure_1-1.png

#########一些介绍############
basemap是matplotlib的一个库,matplotlib是科学计算中的重要库之一,关于matplotlib请百度,
basemap tutorial 在github上均有,请利用好网络资源,百度即可,不再提供网址
##########################

三、WRF-Python
###这里要说明,Python作图是NCL官网提供的,官方手册也有介绍,在最后的几部分####
###WRF应用时需要的库是pynio,用来读取wrfout数据,请Google
  1. >>>import Nio    #用于读取variables、global variables等
复制代码
#########################我遇到的问题:############################################
#ncar提供pynio这个库,但版本上与basemap1.0.7冲突,即geoslib3.3.2,与geoslib3.4.2冲突。可以选择其他channel,速度很慢,
#不能保证冲突问题可以解决,也许降低basemap版本可以消除冲突
  1. $conda install -c ncar pynio  #如遇问题请百度和参考报错信息
  2. $anaconda search -t conda package #在anaconda客户端搜索package和提供package的channe(可以利用conda安装anaconda client)
复制代码

#########################处理办法################################################
###利用Python的netCDF4模块读取wrfout的变量。目前只读到了variables,global variables还没有读取到,以后会认真找办法
  1. #原脚本来自NCL官网,个人修改。处理basemap与Nio矛盾的问题在脚本中体现出来
  2. #----------------------------------------------------------------------
  3. # This script calculates "TK" from data read off a WRF-ARW output,
  4. # and creates a matplotlib plot over a lambert conformal map. It
  5. # checks first that the WRF data is on a Lambert Conformal projection.
  6. #
  7. # See wrf_plot_TK_shapefiles_mpl.py for an example of adding
  8. # shapefile outlines.
  9. #
  10. # You have to provide this script with a WRF output file:
  11. #
  12. # python wrf_plot_TK_mpl.py -f ../Data/wrfout_d03_2012-04-22_23_00_00
  13. #
  14. #----------------------------------------------------------------------
  15. import os, sys, argparse
  16. import numpy as np
  17. from netCDF4 import Dataset as NetCDFFile  <u><b><i><font color="Red">#import Nio</font></i></b></u>
  18. import matplotlib.pyplot as plt
  19. import matplotlib.cm as cm
  20. from mpl_toolkits.basemap import Basemap

  21. def wrf_tk(pressure,theta):
  22.   """
  23. Calculates temperature in [K] from ARW WRF model output.

  24. If variable is more than two dimensions, then only the first element
  25. of the leftmost dimensions are plotted.

  26. tk = wrf_tk(pressure,theta)

  27. pressure - full pressure (perturbation + base state pressure) in Pa
  28. theta    - potential temperature (perturbation + reference temperature) in K
  29.   """

  30.   p1000mb = 100000.
  31.   r_d     = 287.
  32.   cp      = 7.*r_d/2.
  33.   pi      = (pressure/p1000mb)**(r_d/cp)
  34.   tk      = pi*theta

  35.   return(tk)

  36. filename = "wrfout_d02_2016-01-01_00_00_00"
  37. if os.path.exists(filename):
  38.   ncfile = NetCDFFile('wrfout_d02_2016-01-01_00_00_00') #Nio.open_file(filename + ".nc")
  39. else:
  40.     raise RuntimeError("'%s' not found" % filename)

  41. # Get the dimensions
  42. nx = 100 #ncfile.dimensions["west_east"]
  43. ny = 100 #ncfile.dimensions["south_north"]
  44. nz = 30  #ncfile.dimensions["bottom_top"]

  45. # Get the map projection information
  46. map_proj = 1       <font color="Red"><font color="Red"><u><i><b>#ncfile.attributes["MAP_PROJ"]</b></i></u></font></font>
  47. cen_lon  = 103.49 <font color="Red"><font color="Red"><u><i><b>#ncfile.attributes["STAND_LON"]</b></i></u></font></font>
  48. cen_lat  = 36.03    <font color="Red"><font color="Red"><u><i><b>#ncfile.attributes["MOAD_CEN_LAT"]</b></i></u></font></font>
  49. truelat1 = 30        <font color="Red"><font color="Red"><u><i><b>#ncfile.attributes["TRUELAT1"]</b></i></u></font></font>
  50. truelat2 = 60        <font color="Red"><font color="Red"><u><i><b>#ncfile.attributes["TRUELAT2"]</b></i></u></font></font>
  51. dx       = 10000          <font color="Red"><font color="Red"><u><i><b>#ncfile.attributes["DX"]</b></i></u></font></font>
  52. dy       = 10000          <font color="Red"><font color="Red"><u><i><b>#ncfile.attributes["DY"]</b></i></u></font></font>
  53. if map_proj != 1:
  54.   print("Error: the data on %s do not appear to be on a lambert conformal projection." % f)
  55.   sys.exit(1)

  56. # Get the latitude and longitude values
  57. xlon = ncfile.variables["XLONG"][0, :, :]
  58. xlat = ncfile.variables["XLAT"][0, :, :]
  59.    
  60. # Get the lat/lon corner points
  61. lat_ll = xlat[0,0]
  62. lat_ur = xlat[-1,-1]
  63. lon_ll = xlon[0,0]
  64. lon_ur = xlon[-1,-1]
  65.    
  66. # Create the basemap object
  67. bm = Basemap(projection="lcc",
  68.                        lon_0=cen_lon,
  69.                        lat_0=cen_lat,
  70.                        lat_1=truelat1,
  71.                        lat_2=truelat2,
  72.                        llcrnrlat=lat_ll,
  73.                        urcrnrlat=lat_ur,
  74.                        llcrnrlon=lon_ll,
  75.                        urcrnrlon=lon_ur,
  76.                        resolution='l')

  77. # Transform lon/lat points to x/y points in projected coordinates
  78. x, y = bm(xlon, xlat)
  79.    
  80. # Get the data for plotting
  81. T  = ncfile.variables["T"]
  82. P  = ncfile.variables["P"]
  83. PB = ncfile.variables["PB"]
  84. T  = T[0] + 300
  85. P  = P[0] + PB[0]
  86. TK = wrf_tk(P, T)
  87. rank = len(TK.shape)

  88. vname = "TK"

  89. if(rank == 2):
  90.   var = TK[:]
  91. elif(rank == 3):
  92.   var = TK[0,:,:]
  93. elif(rank == 4):
  94.   var = TK[0,0,:,:]
  95. else:
  96.   raise RuntimeError("Only 2, 3, and 4 dimensions are supported")

  97. # Create the figure and add axes
  98. fig = plt.figure(figsize=(8,8))
  99. ax = fig.add_axes([0.1,0.1,0.8,0.8])

  100. # Set contour levels
  101. min_lev = np.amin(var)
  102. max_lev = np.amax(var)
  103.    
  104. # Make only 10 levels
  105. lev_spacing = (max_lev - min_lev) / 10.0
  106. clevs = np.arange(min_lev, max_lev, lev_spacing)
  107.    
  108. # Make the contour plot
  109. cplot = bm.contourf(x, y, var, clevs, cmap=cm.jet, extend="both")

  110. # Define and plot the meridians and parallels
  111. min_lat = np.amin(xlat)
  112. max_lat = np.amax(xlat)
  113. min_lon = np.amin(xlon)
  114. max_lon = np.amax(xlon)
  115.    
  116. # Make only 5 parallels and meridians
  117. parallel_spacing = (max_lat - min_lat) / 5.0
  118. merid_spacing = (max_lon - min_lon) / 5.0
  119. parallels = np.arange(min_lat, max_lat, parallel_spacing)
  120. meridians = np.arange(min_lon, max_lon, merid_spacing)
  121.    
  122. bm.drawcoastlines(linewidth=1.5)
  123. bm.drawparallels(parallels,labels=[1,0,0,0],fontsize=10)
  124. bm.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10)

  125. # Create the colorbar
  126. cb = bm.colorbar(cplot,"bottom", size="5%", pad="5%")
  127. cb.set_label(vname)
  128.    
  129. # Set the plot title
  130. ax.set_title(vname)
  131.    
  132. #save figure
  133. plt.savefig('TK.png', bbox_inches='tight')

  134. # Show the figure (remove this line if only wanting to produce PNG file)
  135. plt.show()

  136. <img src="http://bbs.06climate.com/forum.php?mod=image&aid=59680&size=300x300&key=d9bd9cdee1b7e754&nocache=yes&type=fixnone" aid="attachimg_59680" alt="" width="288" border="0" height="305">

复制代码

############################说明:#######################################
#我在两个虚拟环境里分别安装了basemap和PYnio(来自NCAR),大家可以尝试换用不同channel提供的PYnio
#
  1. #我对basemap中的参数理解,在非WRF气象数据作图中应用
  2. lon_0=cen_lon,      #lon_0 中心经度
  3. lat_0=cen_lat,        #lat_0 中心纬度
  4. lat_1=truelat1,       #真实纬度1
  5. lat_2=truelat2,       #真实纬度2
  6. llcrnrlat=lat_ll,         #起始纬度
  7. urcrnrlat=lat_ur,     #终止纬度
  8. llcrnrlon=lon_ll,        #起始经度
  9. urcrnrlon=lon_ur,    #终止经度
复制代码
#
###2016.12.06
  1. |      ================ ====================================================
  2. |      Variable Name                       Description
  3. |      ================ ====================================================
  4. |      projection                          map projection. Print the module variable
  5. |                                                ``supported_projections`` to see a list of allowed
  6. |                                                values.
  7. |      epsg                                   EPSG code defining projection (see
  8. |                                                http://spatialreference.org for a list of
  9. |                                                EPSG codes and their definitions).
  10. |      aspect                                map aspect ratio
  11. |                                               (size of y dimension / size of x dimension).
  12. |      llcrnrlon                              longitude of lower left hand corner of the
  13. |                                                selected map domain.
  14. |      llcrnrlat                               latitude of lower left hand corner of the
  15. |                                                selected map domain.
  16. |      urcrnrlon                            longitude of upper right hand corner of the
  17. |                                                selected map domain.
  18. |      urcrnrlat                             latitude of upper right hand corner of the
  19. |                                                selected map domain.
  20. |      llcrnrx                                x value of lower left hand corner of the
  21. |                                                selected map domain in map projection coordinates.
  22. |      llcrnry                                y value of lower left hand corner of the
  23. |                                               selected map domain in map projection coordinates.
  24. |      urcrnrx                               x value of upper right hand corner of the
  25. |                                                selected map domain in map projection coordinates.
  26. |      urcrnry                               y value of upper right hand corner of the
  27. |                                                selected map domain in map projection coordinates.
  28. |      rmajor                               equatorial radius of ellipsoid used (in meters).
  29. |      rminor                                polar radius of ellipsoid used (in meters).
  30. |      resolution                           resolution of boundary dataset being used (``c``
  31. |                                                 for crude, ``l`` for low, etc.).
  32. |                                                If None, no boundary dataset is associated with the
  33. |                                                Basemap instance.
  34. |      proj4string                         the string describing the map projection that is
  35. |                                                used by PROJ.4.
  36. |      ================ ====================================================
复制代码
###

############netCDF4暂时代替Nio的办法###################################
#手动添加相应数值(脚本中注释部分,问题主要集中于global variables的读取),在namelist已经设定 #
################################################################

################################################################
canopy提供basemap模块,大家可以尝试一下,我没有用canopy处理以上内容

################################################
先写这么多吧,很多网站没有给出,直接百度即可,fork到github上仔细学习
user guide(其它可直接在github搜索basemap)
#################################################
uvcdat的效果也很棒,已有前辈写出,大二的新人就不乱说话了.
为云南大学开源中心做个广告,云大gitlab
#################################################

2016.11.29
Thanks&Regards


#######################2016.12.08 FOR WRF##############################
#受到Python全自动:下载数据—分析绘图—上传图到邮箱—关机(by 平流层的萝卜)的启发,这两天写了
#一个下载ERA-interim数据并作图,以及做出wrfout相应物理量的图像并发送至某一邮箱的脚本。                 
#参考资料: 飘逸的python - 发送带各种类型附件的邮件
#                   详细讲解用Python发送SMTP邮件的教程
#                   Brief request syntax(ecmwf)
#                   ECMWF官网
#                   python 官网
#                   NCL官网                                                                                                                                    #
##########################################################################
  1. # -*- coding:utf-8 -*-
  2. #weiyiwang@mail.ynu.edu.cn
  3. #由于一些内存问题,具有科学意义的程序代码被我改了一下,大家可参考官网资料改回来
  4. #Ubuntu16.04-----conda------python
  5. """
  6. First, we need to download NC data from ECMWF,
  7. Second, we need to plot data,
  8. Third, we need to plot wrfout data,
  9. At last, we need to transport pictures with e-mail
  10. """

  11. #################################################
  12. ##########
  13. #get data#
  14. ##########

  15. from ecmwfapi import ECMWFDataServer

  16. server = ECMWFDataServer()

  17. server.retrieve({
  18.      'stream'   : "oper",
  19.      'levtype'  : "sfc",
  20.      'param'    : "165.128/166.128",
  21.      'repres'   : "sh",
  22.      'step'     : "0",
  23.      'time'     : "0000",
  24.      'date'     : "2016-01-01/to/2016-01-01",
  25.      'dataset'  : "interim",
  26.      'type'     : "an",
  27.      'class'    : "ei",
  28.      'grid'     : "0.75/0.75",
  29.      'area'     : "39/96/30/107.25",
  30.      'format'   : "netcdf",
  31.      'target'   : "uv.nc"
  32.      })
  33. #########################################################################
  34. ##############################
  35. #plot uv with data downloaded#
  36. ##############################

  37. import numpy as np
  38. from netCDF4 import Dataset as NetCDFFile
  39. import matplotlib.pyplot as plt
  40. import matplotlib.cm as cm
  41. from mpl_toolkits.basemap import Basemap

  42. #load data
  43. data = NetCDFFile('uv.nc')

  44. #extra longitude, latitude, u, v then calculate speed
  45. lon = data.variables['longitude']
  46. lat = data.variables['latitude']
  47. u   = data.variables['u10'][0, :, :]
  48. v   = data.variables['v10'][0, :, :]
  49. spd = np.sqrt(u**2+v**2)
  50.    
  51. #draw a map backgroud
  52. m = Basemap(projection='cyl',llcrnrlat=min(lat)-1,urcrnrlat=max(lat)+1,\
  53. resolution='l',llcrnrlon=min(lon)-1,urcrnrlon=max(lon)+1)

  54. #set figure attributes
  55. fig = plt.figure(figsize=(8,10))
  56. ax  = fig.add_axes([0.1,0.1,0.8,0.8])

  57. #add lon, lat, u, v as quiver
  58. uproj,vproj,xx,yy = m.rotate_vector(u,v,lon,lat,returnxy=True)
  59. Q = m.quiver(xx,yy,uproj,vproj,spd,cmap=cm.jet,headlength=7)

  60. #draw coastlines, state and country boundaries, edge of map
  61. m.drawcoastlines()

  62. #create and draw meridians and parallels grid lines
  63. m.drawparallels(np.arange( -90., 90.,10.),labels=[1,0,0,0],fontsize=10)
  64. m.drawmeridians(np.arange(-180.,180.,10.),labels=[0,0,0,1],fontsize=10)

  65. #save
  66. plt.savefig('uv_ecmwf.pdf')

  67. #close
  68. plt.close(fig)

  69. ###############################################################################
  70. ##########################
  71. #plot uv with wrfout data#
  72. ##########################

  73. def wrf_unstagger(x,dim):
  74.   rank = len(x.shape)
  75.   if(rank == 4 and dim == "u"):
  76.     xu = 0.5*(x[:,:,:,:-1] + x[:,:,:,1:])
  77.   elif(rank == 4 and dim == "v"):
  78.     xu = 0.5*(x[:,:,:-1,:] + x[:,:,1:,:])
  79.   if(rank == 3 and dim == "u"):
  80.     xu = 0.5*(x[:,:,:-1] + x[:,:,1:])
  81.   elif(rank == 3 and dim == "v"):
  82.     xu = 0.5*(x[:,:-1,:] + x[:,1:,:])
  83.   elif(rank == 2 and dim == "u"):
  84.     xu = 0.5*(x[:,:-1] + x[:,1:])
  85.   elif(rank == 2 and dim == "v"):
  86.     xu = 0.5*(x[:-1,:] + x[1:,:])
  87.   return xu


  88. #Read data
  89. a     = NetCDFFile('/media/wwy/DATA/wrfoutNoah/wrfout_d02_2016-01-01_00_00_00')
  90. u     = a.variables["U"]
  91. v     = a.variables["V"]
  92. xlatu = a.variables["XLAT_U"]
  93. xlonu = a.variables["XLONG_U"]

  94. # U, V, XLATU, XLONU are on different grids. Unstagger them to the same grid.

  95. xlat = wrf_unstagger(xlatu,"u")
  96. xlon = wrf_unstagger(xlonu,"u")

  97. ua = u
  98. va = v


  99. #First timestep, lowest (bottommost) level, every 5th lat/lon
  100. nl    = 0
  101. nt    = 0
  102. nstep = 2

  103. u10 = ua[nt,nl,::nstep,::nstep]
  104. v10 = va[nt,nl,::nstep,::nstep]
  105. spd = np.sqrt(u10**2+v10**2)               
  106. lat = xlat[nt,::nstep,::nstep]
  107. lon = xlon[nt,::nstep,::nstep]

  108. #draw map background
  109. m = Basemap(projection='cyl',llcrnrlat=lat.min()-1,urcrnrlat=lat.max()+1,\
  110.             resolution='l',  llcrnrlon=lon.min()-1,urcrnrlon=lon.max()+1)

  111. #create figure, add axes
  112. fig = plt.figure(figsize=(8,10))
  113. ax  = fig.add_axes([0.1,0.1,0.8,0.8])

  114. # rotate vectors to projection grid.
  115. uproj,vproj,xx,yy = m.rotate_vector(u10,v10,lon,lat,returnxy=True)
  116. Q = m.quiver(xx,yy,uproj,vproj,spd,cmap=cm.jet,headlength=7)     

  117. #draw coastlines, state and country boundaries, edge of map
  118. m.drawcoastlines()

  119. #create and draw meridians and parallels grid lines
  120. m.drawparallels(np.arange( -90., 90.,10.),labels=[1,0,0,0],fontsize=10)
  121. m.drawmeridians(np.arange(-180.,180.,10.),labels=[0,0,0,1],fontsize=10)

  122. #save figure
  123. plt.savefig("wrf_UV.pdf")

  124. #close figure
  125. plt.close(fig)

  126. #####################################################################################
  127. ###############
  128. #mail the pdfs#
  129. ###############

  130. #e-mail with SMTP
  131. import smtplib
  132. from email import encoders
  133. from email.mime.text import MIMEText
  134. from email.mime.multipart import MIMEMultipart
  135. from email.mime.application import MIMEApplication
  136. from email.header import Header
  137. from email.utils import parseaddr, formataddr

  138. #definite function
  139. def format_addr(s):
  140.         name, addr = parseaddr(s)
  141.         return formataddr((Header(name, 'utf-8').encode(), addr.encode('utf-8') if isinstance(addr, unicode) else addr))

  142. #info
  143. user     = raw_input("user's e-mail: ")
  144. pwd      = raw_input("user's password: ")
  145. customer = raw_input("customer's e-mail: ")
  146. sever    = raw_input("SMTP sever: ")

  147. #instance
  148. lis1 = user.split('@')
  149. na1  = lis1[0]
  150. lis2 = customer.split('@')
  151. na2  = lis2[0]
  152. msg  = MIMEMultipart()
  153. msg["Subject"] = Header("test 附件", "utf-8").encode()
  154. msg["From"]    = format_addr(u"%s <%s>" %(na1, user))
  155. msg["To"]      = format_addr(u"%s <%s>" %(na2, customer))

  156. #text
  157. txt = MIMEText("附件", 'plain', 'utf-8')
  158. msg.attach(txt)

  159. #pdfs as attachment
  160. atta = MIMEApplication(open('uv_ecmwf.pdf', 'rb').read())
  161. atta.add_header('Content-Disposition', 'attachment', filename='uv_ecmwf.pdf')
  162. msg.attach(atta)  

  163. atta = MIMEApplication(open('wrf_UV.pdf', 'rb').read())
  164. atta.add_header('Content-Disposition', 'attachment', filename='wrf_UV.pdf')
  165. msg.attach(atta)  

  166. #transport
  167. ser = smtplib.SMTP(sever, 25)
  168. ser.set_debuglevel(1)
  169. ser.login(user, pwd)
  170. ser.sendmail(user, [customer], msg.as_string())
  171. ser.quit()

  172. #####################################################################################

  173. #
  174. #关于底图shape文件的使用,以中国为例(*代表CHN_adm1)
  175. #下载shape文件得到:*.shp, *.shx, *.dbf, *.prj, *.cpg
  176. #可以在上面的代码中加入 m.readshapefile('CHN_adm1', 'CHN_adm1')
  177. #
复制代码

               
  1. ##################2016.12.23####for Ubuntu Desktop#########################
  2. ##说点娱乐性质的,实时地球照片作为ubuntu桌面                                                                                    
  3. #########################################################################

  4. #移植
  5. git clone https://github.com/ujnzxw/oh-my-earth.git
  6. # Configure
  7. cd oh-my-earth/
  8. vi config.py

  9. #####################配置问题#############################################
  10. auto_offset = True

  11. hour_offset = 0

  12. # Path to the output file
  13. output_file = os.path.join(appdirs.user_cache_dir(appname="earth",
  14.                                               appauthor="yangqd"),
  15.                        "latest.png")

  16. # Xfce4 displays to change the background of
  17. xfce_displays = ["/backdrop/screen0/monitor0/image-path",
  18.              "/backdrop/screen0/monitor0/workspace0/last-image"]
  19. #修改appauthor=用户名
  20. #(我这台ubuntu名字不是wwy,原因不告诉你)
  21. ##################################################################
  22. # Install
  23. sudo bash install.sh

  24. # Test whether it's working,终端输入,(需要装python的几个库 PIL,pytz...)
  25. oh-my-earth

  26. # Set oh-my-earth to be called periodically,终端输入,选择默认项

  27. crontab -e

  28. #Add the line:(写你自己目录下的)(我的设定是每分钟执行一次)
  29. * * * * * python /home/yangqd/oh-my-earth/run.py

  30. ##基本搞定
复制代码
2016-12-23 07-15-43屏幕截图.png
2016-12-23 13-07-16屏幕截图.png
2016-12-24 00-13-34屏幕截图.png

###############2017.01.17##############
basemaptutorial.pdf (7.73 MB, 下载次数: 112)
QQ图片20161129001420.jpg
day_night.png
sst.png
TK.png

drawbounds=False

drawbounds=False

drawbounds=True

drawbounds=True

drawbounds=True

drawbounds=True

点评

赞赞赞  发表于 2016-12-4 16:19

评分

参与人数 4金钱 +90 贡献 +34 收起 理由
尽头的尽头 + 20 + 8 很给力!
风往北吹 + 30 + 6 赞一个!
mofangbao + 20 + 20
风子 + 20 小小年纪,前途无量

查看全部评分

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

新浪微博达人勋

发表于 2017-3-6 10:08:33 | 显示全部楼层
{:eb502:}{:eb502:}
怎么才能咋在win10上实现呢?
密码修改失败请联系微信:mofangbao
回复 支持 1 反对 0

使用道具 举报

新浪微博达人勋

发表于 2016-11-29 19:49:29 | 显示全部楼层
一直想学但总是没时间。。还是多谢楼主分享了{:5_214:}
密码修改失败请联系微信:mofangbao

新浪微博达人勋

 楼主| 发表于 2016-11-29 20:43:59 | 显示全部楼层
贫道敬孔 发表于 2016-11-29 19:49
一直想学但总是没时间。。还是多谢楼主分享了

看来大家都很忙啊,感觉时间被掏空
密码修改失败请联系微信:mofangbao

新浪微博达人勋

发表于 2016-11-29 21:55:52 | 显示全部楼层
真心不错,感谢楼主分享,现在正在学python
密码修改失败请联系微信:mofangbao

新浪微博达人勋

0
早起挑战累计收入
发表于 2016-11-29 23:09:29 | 显示全部楼层
非常感谢,楼主继续~
密码修改失败请联系微信:mofangbao

新浪微博达人勋

 楼主| 发表于 2016-11-29 23:36:17 | 显示全部楼层
放逐流年 发表于 2016-11-29 21:55
真心不错,感谢楼主分享,现在正在学python

嗯,一起学习,共同进步,github是好东西
密码修改失败请联系微信:mofangbao

新浪微博达人勋

 楼主| 发表于 2016-11-29 23:38:27 | 显示全部楼层
mofangbao 发表于 2016-11-29 23:09
非常感谢,楼主继续~

还是要向前辈们学习啦,所以要感谢家园这个平台喽
密码修改失败请联系微信:mofangbao

新浪微博达人勋

发表于 2016-11-30 00:24:28 | 显示全部楼层
小伙继续加油~
密码修改失败请联系微信:mofangbao

新浪微博达人勋

 楼主| 发表于 2016-11-30 08:37:29 | 显示全部楼层

多谢前辈的帖子了,学到很多东西哦
密码修改失败请联系微信:mofangbao

新浪微博达人勋

发表于 2016-11-30 08:46:49 | 显示全部楼层
楼主赞,给力~
密码修改失败请联系微信:mofangbao
您需要登录后才可以回帖 登录 | 立即注册 新浪微博登陆

本版积分规则

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

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

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