#!/usr/bin/env ruby
=begin
= 比湿鉛直平均値  気候値からの偏差 時系列作図スクリプト(赤道, 中緯度)

=end

require "getopts"        # for option_parse
require "numru/ggraph"
include NumRu
include Misc::EMath

## 描画メソッドメイン

def plot_line_main(gphys_array)
  
  line_index_ary = Array.new; name_ary = Array.new

  default_index = 12
  
  line_hash = { "index"=> default_index }
  line_index_ary.push(default_index)
  name_ary.push(gphys_array[0].data.get_att("long_name"))
  
  x = gphys_array[0].coord(0).val
  y = gphys_array[0].data.val
  DCL.uulinz(x, y, 1, default_index)
  gphys_array.size.times{ |num|
      unless num == 0
	line_index = (num*10 + default_index)
	line_index_ary.push(num*10 +default_index)
	name_ary.push(gphys_array[num].data.get_att("long_name"))
	x = gphys_array[num].coord(0).val
	y = gphys_array[num].data.val
	DCL.uulinz(x, y, 1, line_index)
      end
  }
  
  return name_ary, line_index_ary
  
end



##-----------------------
#  ラインインデックスの種類を表示

def __show_line_index(str_ary,line_index_ary, x=0.15, y=0.12) 
  charsize = 1.0 * DCL.uzpget('rsizec1')
  dvx = 0.01
  dvy = charsize*1.5
  raise TypeError,"Array expected" if ! str_ary.is_a?(Array)
  vxmin,vxmax,vymin,vymax = DCL.sgqvpt
  vx = x
  vy = y + charsize/2
  str_ary.size.times{|num|
    DCL::sgtxzv(vx,vy,"--- #{str_ary[num]}", 
		  charsize, 0, -1, line_index_ary[num])
      vy -= dvy
      if num == 5
	vx = 0.30
	vy = 0.12 - charsize/2
      end
  }
    nil
  end



################################################################
#                        make gphys 
################################################################
year = [1979, 2003]
month = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]   # 初期値 

shum_tropical_long_name =  "Vertical mean specific humidity (S30 - N30)"
shum_nh_midlat_long_name = "Vertical mean specific humidity (N30 - N60)"
shum_sh_midlat_long_name = "Vertical mean specific humidity (S30 - S60)"

## make compisit-GPhys object 
# make array which set the gphys objects.

### climatlogy value
shum_path = "../../25MEANS.NCEP/25MEANS.1979-2003.NCEP/300hPa_PHYS_1979-2003_ANNUAL_NCEP.nc"
gp_shum_climat  = GPhys::IO.open(shum_path, "shum").average('level')

axmonth = []
i = 0

shum_name = ""
shum_unit = ""

shum_law =    []
shum_nh_mid = []
shum_sh_mid = []

year[0].upto(year[1]) do |y|
  month.each do |m|
    path = "../../../SHUM.NCEP/SHUM.#{y}.NCEP/SHUM_#{y}-#{m}_NCEP.nc" # specific humidity

    gp_shum = GPhys::NetCDF_IO.open(path, 'shum').average('level').mean('lon')
    cos_lat = cos( gp_shum.coord('lat')*2*PI/360 )
    shum_law    << ( ( ( ( gp_shum - gp_shum_climat ) * cos_lat ).cut( 'lat'=> 30..-30 ) ).average('lat').val )
    shum_nh_mid << ( ( ( ( gp_shum - gp_shum_climat ) * cos_lat ).cut( 'lat'=> 60.. 30 ) ).average('lat').val )
    shum_sh_mid << ( ( ( ( gp_shum - gp_shum_climat ) * cos_lat ).cut( 'lat'=>-30..-60 ) ).average('lat').val )

    shum_name =      gp_shum.data.name
    shum_unit =      gp_shum.data.get_att("units")

    axmonth << DCL::dateg3(year[0],1,1,y.to_i,m.to_i,1)
    i += 1
    p y if i%12 == 0
  end
end


### for intensity

  # 日付軸作成
  namonth = NArray.to_na(axmonth)                 # 日付軸の NArray
  vamonth = VArray.new(namonth).rename!("month")  # VArray 化. 名前は "month"
  vamonth.set_att('long_name','month')            # 属性設定. long_name と
  vamonth.set_att('units','month since 1979 JAN') #           units     を設定.
  grid = Grid.new( Axis.new(true).set_cell_guess_bounds(vamonth).set_pos_to_center )
                                                  # Axis 化して, セル位置を適当に決めて Grid 化
  # 温度差時系列を GPhys 化
  gp_shum_law    = GPhys.new(grid, VArray.new(NArray.to_na(shum_law)).rename!(shum_name))
  gp_shum_nh_mid = GPhys.new(grid, VArray.new(NArray.to_na(shum_nh_mid)).rename!(shum_name))
  gp_shum_sh_mid = GPhys.new(grid, VArray.new(NArray.to_na(shum_sh_mid)).rename!(shum_name))

  ## データの属性設定
  gp_shum_law.data.set_att('long_name', shum_tropical_long_name)
  gp_shum_nh_mid.data.set_att('long_name', shum_nh_midlat_long_name)
  gp_shum_sh_mid.data.set_att('long_name', shum_sh_midlat_long_name)
  gp_shum_law.data.set_att('units', shum_unit)
  gp_shum_nh_mid.data.set_att('units', shum_unit)
  gp_shum_sh_mid.data.set_att('units', shum_unit)

################################################################
#                        描画ルーチン
################################################################

##
# 事前準備

DCL.uscset('cyspos', 'B' )              # y 軸の単位の位置を下方へ 
rsizel2 = DCL.uzrget('rsizel2')         # 現在のラベルサイズを取得
DCL.uzrset('rsizel2', rsizel2*0.42 )    # ラベルサイズをデフォルトの 0.5 倍に

##
# お絵描きメイン

# 縦軸の最大描画範囲(Kg/Kg)
max = +0.001
min = -0.001

# ビューポート設定
vpt = NArray[0.15,0.85,0.23,0.58]

p idate = (year[0].to_s+"0101").to_i      # 日付 0 日. 19790101
ndate = (year[-1].to_s+"1201").to_i       # 日付 最後の日. 20031231
p nd = DCL.dateg1(idate,ndate)            # 日日数
#GGraph.set_axes("date?"=>["x", idate, nd])        
                                          # 日付軸を有効にする


DCL.swpset('lsep',  true)    # ページ毎別々のファイルに落す
DCL.gropn(2)
DCL.sgpset('lcntl', false)   # 
DCL.sgpset('lfull',true)     # フルスクリーン
DCL.uzfact(0.55)             # 
DCL.sgpset('lcorner',false)  # コーナーを取っ払う 
DCL.sgpset('lfprop',true)    # 
DCL.udpset('lmsg',false)     # 
DCL.uscset('cyspos', 'B' )   # y 軸の単位の位置を下方へ 


### 時系列

DCL::grfrm                   # ページ確定 

DCL::grswnd(0.0, nd, min, max)
DCL::grsvpt(*vpt)
DCL::grstrn(1)
DCL::grstrf

DCL::ucxacl('B', idate, nd)
DCL::ucxacl('T', idate, nd)

DCL::uyaxdv('L', max/10, max/5)
DCL::uyaxdv('R', max/10, max/5)

DCL::uxmttl('T', 'Deviation of vertical mean specific humidity (1979-2003)', 0.0)
DCL::uysttl('L', "specific humidity(#{shum_unit.to_s})", 0.0)
DCL::uxsttl('B', 'YEAR', 0.0)
# DCL::uscset('cyunit', shum_unit.to_s ) # y 軸の単位

names, idxs = plot_line_main([ gp_shum_law, gp_shum_nh_mid, gp_shum_sh_mid ])

__show_line_index(names,idxs)


DCL.grcls

##################################################
# 画像ファイル名を変更
File.rename('dcl_001.ps', 'SHUM_1979-2003_TIME-SERIES_NCEP_DEVIATION.ps')
