#! /usr/bin/ruby
# -*- coding: utf-8 -*-
#
# 2015/02/19 石渡正樹 allocate memory error が出ないように改変.
#                     ファイルを出力してしまっているが, 
#                     ファイルを出力せずに図を描くようにしたい.
# 2014/10/03 石渡正樹
#
# = fig_globalinteg.rb
# * 全球積分値を求める.
#
# == USAGE
#   % fig_globalinteg.rb --var=H2OLiq --time_start=731 --time_end=1095 --wsn=2
# == Calculation Method
#  \int q d \sigma = \int q d dp/ps
#                  = 1/ps \int q \rho g (dz)  
#                  = g/ps \int \rho q (dz) 
# よって, 求めたいのは
# \int \rho q (dz)  = ps/g \int q d \sigma


require "/GFD_Dennou_Work3/momoko/SyncRotEarthRad/script/dcpam.rb"

require 'getoptlong'
require "numru/ggraph"
include NumRu

ITR=1

## 定数設定
Grav = 9.8

RPlanet = 6.371e6

Pi = 3.1415926535897932

## オプション解析
parser = GetoptLong.new
parser.set_options(
                   ###    global option   ###
                   ['--var',                      GetoptLong::REQUIRED_ARGUMENT],
                   ['--time_start',                      GetoptLong::REQUIRED_ARGUMENT],
                   ['--time_end',                      GetoptLong::REQUIRED_ARGUMENT],
                   ['--area',                      GetoptLong::REQUIRED_ARGUMENT],
                   ['--wsn',                      GetoptLong::REQUIRED_ARGUMENT]
                   )
parser.each_option do |name, arg|
  eval "$OPT_#{name.sub(/^--/, '').gsub(/-/, '_')} = '#{arg}'"  # strage option value to $OPT_val
end

if $OPT_var == nil then
  p '--var must be specified.'
  exit
end
variable = $OPT_var
ncfile = $OPT_var + '.nc'
outncfile = 'VerticalIntegrated' + $OPT_var + '.nc'

wsn = ($OPT_wsn||4)

time_start = ($OPT_time_start||1).to_f
time_end = ($OPT_time_end||9999).to_f

area = ($OPT_area||'all')


# ここから

dir = "./"

gqv = gpopen dir + "H2OLiq.nc"
gps = gpopen dir + "Ps.nc"
sigm = gpopen dir + "H2OLiq.nc","sigm"

sig = gpopen dir + "H2OLiq.nc","sig"
lat = gpopen dir + "H2OLiq.nc","lat"
lon = gpopen dir + "H2OLiq.nc","lon"

sig_weight = gpopen dir + "H2OLiq.nc","sig_weight"
lat_weight = gpopen dir + "H2OLiq.nc","lat_weight"

return if gqv.nil? || gps.nil?

na_sig = sig.val
na_lon = lon.val
na_lat = lat.val

na_sig_weight = sig_weight.val
na_lat_weight = lat_weight.val

nsig = na_sig.size
nlat = na_lat.size

data_name = 'GlblIntH2OLiq' 
ofile = NetCDF.create(dir + data_name + '.nc')

# 時間ループ
GPhys::NetCDF_IO.each_along_dims_write([gqv,gps], ofile, 'time') { 
  |h2oliq,ps|  
        
  time = h2oliq.axis("time")    
        
  qc = ps.copy
  qc.units = 'kg.m-2'
  qc.long_name = 'cloud water'
  qc.name = data_name
  qc[false] = 0
        
  alph = h2oliq * ps / Grav 

  # 鉛直積算の計算
  qc = alph *  na_sig_weight.reshape(1, 1 ,nsig, 1)/na_sig_weight.sum
  qc = qc.sum('sig')

  # 水平積分の計算
  global_integrated_data = qc*na_lat_weight.reshape(1, nlat)/na_lat_weight.sum
  if (area == 'all') then
    data = global_integrated_data.mean('lon').sum('lat')
    data = data * 4.0 * Pi * RPlanet * RPlanet
  elsif (area == 'east') then
    data = global_integrated_data.cut('lon'=>180.0..360.0).mean('lon').sum('lat')
    data = data * 2.0 * Pi * RPlanet * RPlanet
  elsif (area == 'west') then
    data = global_integrated_data.cut('lon'=>0.0..180.0).mean('lon').sum('lat')
    data = data * 2.0 * Pi * RPlanet * RPlanet
  else
    p 'area is not set properly: area=', area
    exit
  end

  [data]
}
ofile.close

infile = "./GlblIntH2OLiq.nc"

varvar = GPhys::IO.open('GlblIntH2OLiq.nc', 'H2OLiq')

DCL.gropn(wsn)

# 描画準備
vx0,vx1,vy0,vy1 = 0.15,0.85,0.2,0.55
GGraph.set_fig 'itr'=>ITR, 'viewport'=>[vx0,vx1,vy0,vy1]

DCL.ugpset('LUMSG', false)   # no message

#  DCL.sgpset('lfull', true)     # 全画面表示
#  DCL.sgpset('lcntl', true)

  # オプションのデフォルト値の設定
  opt = {
    'legend'=>false, 'annotate'=>false,
    'title'=>'cloud water'
  }

#   GGraph.line( $data, true, opt )
   GGraph.line( varvar, true, opt )

DCL.grcls

ofile.close

