require 'test/unit'
require 'numru/netcdf'
include NumRu

class TestFactorOffset < Test::Unit::TestCase
  def setup
    @s = 'tmp.nc'
    f = NetCDF.create(@s)
    nx = 10
    d = f.def_dim('x',nx)
    v1 = f.def_var('v1','sint',[d])
    v2 = f.def_var('v2','sint',[d])
    v3 = f.def_var('v3','int',[d])
    v1.put_att('scale_factor',0.1,'sfloat')
    v1.put_att('add_offset',100.0,'sfloat')
    v2.put_att('scale_factor',0.1,'sfloat')
    v2.put_att('add_offset',100.0,'sfloat')
    v3.put_att('scale_factor',0.1,'sfloat')
    v3.put_att('add_offset',100.0,'sfloat')
    f.enddef
    v1.put( NArray.sint(nx).indgen!+100 )
    v2.scaled_put( NArray.float(nx).indgen!+100 )
    v3.scaled_put( NArray.float(nx).indgen!+100 )
    f.close
  end

  def teardown
    if File.exist?(@s)
      begin
        File.delete(@s)
      rescue
        p $!
      end
    end
  end
  def test_originally_uscaled
    f = NetCDF.open(@s)
    v1 = f.var('v1')
    v11 = v1.get
    assert_equal v11,
                 NArray[ 100, 101, 102, 103, 104, 105, 106, 107, 108, 109 ].to_i
    v12 = v1.scaled_get
    assert_equal v12,
                 NArray[ 110.0, 110.1, 110.2, 110.3, 110.4, 110.5, 110.6, 110.7, 110.8, 110.9 ].to_type(NArray::SFLOAT)
    f.close
  end

  def test_originally_scaled
    f = NetCDF.open(@s)
    v2 = f.var('v2')
    v21 = v2.get
    assert_equal v21,
                 NArray[ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90 ].to_i
    v22 = v2.scaled_get
    assert_equal v22,
                 NArray[ 100.0, 101.0, 102.0, 103.0, 104.0, 105.0, 106.0, 107.0, 108.0, 109.0 ].to_type(NArray::SFLOAT)
    f.close
  end

  def test_originally_scaled_int_to_double
    f = NetCDF.open(@s)
    v3 = f.var('v3')
    v31 = v3.get
    assert_equal v31,
                 NArray[ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90 ].to_i
    v32 = v3.scaled_get
    assert_equal v32,
                 NArray[ 100.0, 101.0, 102.0, 103.0, 104.0, 105.0, 106.0, 107.0, 108.0, 109.0 ].to_type(NArray::SFLOAT)
    f.close
  end

  def test_unpack_type_fixed_to_sfloat
    f = NetCDF.open(@s)
    v3 = f.var('v3')
    NetCDFVar.unpack_type = NArray::SFLOAT
    v33 = v3.scaled_get
    assert_equal v33,
                 NArray[ 100.0, 101.0, 102.0, 103.0, 104.0, 105.0, 106.0, 107.0, 108.0, 109.0 ].to_type(NArray::SFLOAT)
    NetCDFVar.unpack_type = NArray::INT
    v33 = v3.scaled_get
    assert_equal v33,
                 NArray[ 100, 101, 102, 103, 104, 105, 106, 107, 108, 109 ].to_i
  end
end
