#!/usr/bin/env ruby
=begin
= mkfig.rb -- make figure for energy balance

$BFnKL%(%M%k%.!<M"Aw4XO"?^(B. $B0J2<$NJ*M}NL$N7PEY1tD>@QJ,CM$r%W%m%C%H(B.

* $B4%Ag@EE*%(%M%k%.!<(B
  * CpvT + vh
* $B@xG.M"Aw(B
  * LQv

=end

require "getopts"        # for option_parse
require "numru/netcdf_miss"
require "numru/ggraph"
require "colorbar"
require "libgphys-n"
include NumRu
include Misc::EMath

## enable to the option min, max 

  def GGraph::line(gphys, newframe=true, options=nil)
    if newframe!=true && newframe!=false
      raise ArgumentError, "2nd arg (newframe) must be true or false"
    end
    if ! defined?(@@line_options)
      @@line_options = Misc::KeywordOptAutoHelp.new(
						    ['title', nil, 'Title of the figure(if nil, internally determined)'],
						    ['annotate', true, 'if false, do not put texts on the right margin even when newframe==true'],
						    ['exchange', false, 'whether to exchange x and y axes'],
						    ['index', 1, 'line/mark index'],
						    ['type', 1, 'line type'],
						    ['label', nil, 'if a String is given, it is shown as the label'],
						    ['max', nil, 'maximam value for draw line'],
						    ['min', nil, 'minimam value for draw line']
						    )
    end
    opts = @@line_options.interpret(options)
    gp = gphys.first1D
    if !opts['exchange']
      x = gp.coord(0)
      y = gp.data
      xax = x
      if opts['min']
	ymin = opts['min'].to_f
      else
	ymin = gp.data.val.min
      end
      if opts['max']
	ymax = opts['max'].to_f
      else
	ymax = gp.data.val.max
      end
      yax = VArray.new(NArray[ymin, ymax], gp.data, gp.data.name)      
    else
      y = gp.coord(0)
      x = gp.data
      yax = y
      if opts['min']
	xmin = opts['min'] 
      else
	xmin = gp.data.val.min
      end
      if opts['max']
	xmax = opts['max'] if opts['max']
      else
	xmax = gp.data.val.max
      end
      xax = VArray.new(NArray[xmin, xmax], gp.data, gp.data.name)
    end
    if newframe
      fig(xax, yax)
      axes(xax, yax)
      title( (opts['title'] || gp.data.get_att('long_name')) )
      annotate(gp.lost_axes) if opts['annotate']
    end
    if opts['label']
      lcharbk = DCL.sgpget('lchar')
      DCL.sgpset('lchar',true)
      DCL.sgsplc(opts['label'])
      end
    DCL.uulinz(x.val, y.val, opts['type'], opts['index'])
    DCL.sgpset('lchar',lcharbk) if opts['label']
    nil
  end


##-----------------------
#  $B%i%$%s%a%=%C%I:FDj5A(B?

def plot_line_main(gphys_array, line_opts={})
  
  line_index_ary = Array.new; name_ary = Array.new

  default_index = 12
  
  line_hash = { "index"=> default_index }.update(line_opts)
  line_index_ary.push(default_index)
  name_ary.push(gphys_array[0].data.get_att("long_name"))
  
  GGraph.line( gphys_array[0], true, line_hash )
  gphys_array.size.times{ |num|
      unless num == 0
	line_hash = { "index"=> (num*10 + default_index)}
	line_index_ary.push(num*10 +default_index)
	name_ary.push(gphys_array[num].data.get_att("long_name"))
	GGraph.line( gphys_array[num], false, line_hash ) 
      end
  }
  
  return name_ary, line_index_ary
  
end



##-----------------------
#  $B%i%$%s%$%s%G%C%/%9$N<oN`$rI=<((B

def __show_line_index(str_ary,line_index_ary) 
    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 = 0.15
    vy = 0.12 - 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 == 4
	vx = 0.30
	vy = 0.12 - charsize/2
      end
  }
    nil
  end


def make_mean_gphys(var, phys, src, season, year)
  ary = []
  y1 = year[0]; y2 = year[1]
  path = "../../#{phys}.#{src}/"
  season.each do |m|
    y1.upto(y2) do |y|
      fn = path + "#{phys}.#{y}.#{src}/#{phys}_#{y}-#{m}_#{src}.nc"
      ary << fn
    end
  end
  gp     = mean_gphys(ary, var)
  return gp
end

######################################################

Rad = UNumeric.new(6.37E6, 'm')
G =   UNumeric.new(9.81  , 'm.s-2')

year = [1979, 2003]
# year = [1980, 1980]

winter = ["12", "01", "02"];  spring = ["03", "04", "05"]
summer = ["06", "07", "08"];  fall = ["09", "10", "11"]
annual = winter + spring + summer + fall
djf = []; mam = []; jja = []; son = []; ann_se = []
ann_le = []

## $B4%Ag@EE*%(%M%k%.!<%U%i%C%/%9(B 
#temp  = make_mean_gphys('T',    'NCEP', annual, year)#.cut('level'=>300..1000)
#hgt   = make_mean_gphys('HGT',  'NCEP', annual, year)#.cut('level'=>300..1000)
#vwnd  = make_mean_gphys('VWND', 'NCEP', annual, year)#.cut('level'=>300..1000)

## $B4%Ag@EE*%(%M%k%.!<%U%i%C%/%9(B 
lhefl  =      make_mean_gphys('lhefl',     'LHEFL', 'NCEP', annual, year)#.cut('level'=>300..1000)
lhefl_bar   = make_mean_gphys('lhefl_bar', 'LHEFL', 'NCEP', annual, year)#.cut('level'=>300..1000)
lhefl_dash  = make_mean_gphys('lhefl_dash','LHEFL', 'NCEP', annual, year)#.cut('level'=>300..1000)
lhefl.data.set_att('units', 'W')
lhefl_bar.data.set_att('units', 'W')
lhefl_dash.data.set_att('units', 'W')


# get cos
lat     = lhefl.coord('lat')
grid    = Grid.new(lhefl.axis('lat'))
cos_lat = GPhys.new(grid, cos(lat*2*PI/360.0))


# dsefl = ( vt + vh ).mean('lon').integrate('level') /G * Rad * cos_lat * 2 * PI * 100



ann_se << lhefl.integrate('level') /G * Rad * cos_lat * 2 * PI * 100
ann_se << lhefl.integrate('level') /G * Rad * cos_lat * 2 * PI * 100
ann_se << lhefl.integrate('level') /G * Rad * cos_lat * 2 * PI * 100
ann_le << lhefl.integrate('level') /G * Rad * cos_lat * 2 * PI * 100
ann_le << lhefl_bar.integrate('level') /G * Rad * cos_lat * 2 * PI * 100
ann_le << lhefl_dash.integrate('level') /G * Rad * cos_lat * 2 * PI * 100


###################################################################

# set User Path for dcldatabase
DCL.glcset('DUPATH','/home/daktu32/.dcldir/')     


## four in one(itr 2)
itr = 1
min =  8e15
max = -8e15


## annual mean

DCL.swpset('lsep',  true)    # $B%Z!<%8KhJL!9$N%U%!%$%k$KMn$9(B
DCL.gropn(2)
DCL.sgpset('lcntl', false)   # 
DCL.sgpset('lfull',true)     # $B%U%k%9%/%j!<%s(B
DCL.uzfact(0.55)             # 
DCL.sgpset('lcorner',false)  # $B%3!<%J!<$r<h$CJ'$&(B 
DCL.sgpset('lfprop',true)    # 
DCL.udpset('lmsg',false)     # 
DCL.uscset('cyspos', 'B' )   # y $B<4$NC10L$N0LCV$r2<J}$X(B 

# $B%S%e!<%]!<%H@_Dj(B
vpt = NArray[0.15,0.85,0.23,0.58]

# dcl $B$K7gB;CM>pJs$r65$($k(B
before = DCLExt.gl_set_params('lmiss'=>true,'rmiss'=>ann_le[0].data.get_att("missing_value")[0])

# annual mean
GGraph.set_fig('viewport'=>vpt, 'itr'=>itr)
GGraph.set_axes('ytitle'=>'')
names, idxs = plot_line_main(ann_se, 'annot'=>false, 'titl'=>'', 'min'=>min, 'max'=>max)

__show_line_index(names,idxs)

## -- extra information --
DCL::sgtxzv(0.5,vpt[3]+0.028,"25 years annual mean Dry Static Energy Transport (1979-2003)",
	        1.15*DCL.uzpget('rsizec2'),0,0,3)
DCL::sgtxzv(0.78,vpt[3]+0.01,"(units:#{ann_se[0].data.units.to_s})",
	        0.8*DCL.uzpget('rsizec2'),0,0,3)


#####################################################

# annual mean
GGraph.set_fig('viewport'=>vpt, 'itr'=>itr, 'new_frame'=>true)
GGraph.set_axes('ytitle'=>'')
names, idxs = plot_line_main(ann_le, 'annot'=>false, 'titl'=>'', 'min'=>min, 'max'=>max)

__show_line_index(names,idxs)

## -- extra information --
DCL::sgtxzv(0.5,vpt[3]+0.028,"25 years annual mean Latent Heat Energy Transport (1979-2003)",
	        1.15*DCL.uzpget('rsizec2'),0,0,3)
DCL::sgtxzv(0.78,vpt[3]+0.01,"(units:#{ann_le[0].data.units.to_s})",
	        0.8*DCL.uzpget('rsizec2'),0,0,3)

DCL.grcls
#-------------------------------------------------------------------
##################################################
# $B2hA|%U%!%$%kL>$rJQ99(B
File.rename('dcl_001.ps', 'ENERGY_TRANSPORT_1973-2003-ANNUAL_SE_NCEP.ps')
File.rename('dcl_002.ps', 'ENERGY_TRANSPORT_1973-2003-ANNUAL_LE_NCEP.ps')
