#! /usr/bin/ruby
# -*- coding: utf-8 -*-

# 潜熱エネルギー, 顕熱エネルギーの計算

# (2014-11-11 石渡)
# 潜熱エネルギーと顕熱エネルギーは
# trnsprt_lq.rb と trnsprt_s.rb でも計算されている.

# trnsprt_lq.rb では
# (U, V), QVap を読み込み.

# trnsprt_s.rb では
# (U, V), Phi, Temp を読み込み.

# Phi は geopotential_time.rb で計算される.

# 潜熱エネルギー, 位置エネルギー, 顕熱エネルギーは
# 3 次元時系列データを作ることにしよう.

require "numru/ggraph"
include NumRu
require "pp"

time_start = 700
#time_start = 731
time_end = 1095

Latent = 2500000

dir='.'

var = 'QVap'
file = File.join(dir, var+'.nc')
gp_latenergy = GPhys::IO.open(file, var).cut('time'=>time_start..time_end)*Latent

OUTFN_LATENERGY = "LE.nc"

# axis etc.
lon        = GPhys::IO.open(file, "lon").data.val
lat        = GPhys::IO.open(file, "lat").data.val
gp_lat_weight = GPhys::IO.open(file, "lat_weight")
lat_weight = gp_lat_weight.data.val * 0.5   # 和を 1 に規格化
sig        = GPhys::IO.open(file, "sig").data.val
gp_sig_weight = GPhys::IO.open(file, "sig_weight")
sig_weight = gp_sig_weight.data.val
sigm       = GPhys::IO.open(file, "sigm").data.val
time       = GPhys::IO.open(file, "time").cut('time'=>time_start..time_end).data.val

#data = VArray.new( phi,
#                   {"long_name"=>"Geopotential", "units"=>"J kg-1"},
#                   "Phi" )
#gphys = GPhys.new( Grid.new(ax_lon,ax_lat,ax_sig,ax_time), data )

gp_latenergy.name=('LE')
gp_latenergy.units=('J')
gp_latenergy.long_name=('latent energy')


# netCDF ファイルを出力
outfile = NetCDF.create(OUTFN_LATENERGY)
GPhys::NetCDF_IO.write( outfile, gp_lat_weight )
GPhys::NetCDF_IO.write( outfile, gp_sig_weight )
GPhys::NetCDF_IO.write( outfile, gp_latenergy )
outfile.close


exit

var = 'Temp'
path = File.join(dir, var+'.nc')
gp_h = GPhys::IO.open(path, var).cut('time'=>time_start..time_end)*cp
gp_h = gp_h.convert_units('J kg-1')
