Module: NumRu::GPhys::HE5_IO

Defined in:
lib/numru/gphys/gphys_hdfeos5_io.rb

Constant Summary collapse

PredefCoordNames =
["Time","Longitude","Latitude","Colatitude"]
@@predef_gdcoords =

^ In the order of precedence

[/^altitude$/i, /^altitude/i, /^pressure$/i, /^wavelength$/i, /^wavelength/i,/^wavenumber$/i, /^wavenumber/i, /^time$/i,/time$/i]
@@predef_zacoords =

^ In the order of precedence

[/^latitude$/i, /^latitude/i, /^altitude$/i, /^altitude/i, /^pressure$/i, /^wavelength$/i, /^wavelength/i,/^wavenumber$/i, /^wavenumber/i, /^time$/i, /time$/i, /^solarzenithangle$/i, /^solarzenithangle/i]

Class Method Summary collapse

Class Method Details

.__convertTime(axisname) ⇒ Object



228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/numru/gphys/gphys_hdfeos5_io.rb', line 228

def __convertTime( axisname )
  # Convert Geo Location Field "Time" or "LocalTime"
#	if axisname.name == "Time" ||  axisname.name == "LocalTime"
#          axisname.val.each{|ax|
#            stun = axisname.units.to_s
#            since = DateTime.parse("1993-01-01 00:00:00+00:00")
#            tun = Units[stun]
#            sec = tun.convert( ax, Units['seconds'] ).round + 1e-1
#            datetime = since + (sec/86400.0)
#            ax =datetime.strftime("%Y-%m-%d %H:%M:%S")
#          }
#p axisname[0].val
#        end
end

.__files2varray(files, varname, dim = nil, gd_flag = nil, ntype = nil) ⇒ Object



243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# File 'lib/numru/gphys/gphys_hdfeos5_io.rb', line 243

def __files2varray( files, varname, dim=nil, gd_flag=nil, ntype=nil )
	if files.is_a?(HE5Sw)
	  # Single file. Returns a VArrayHE5SwField. dim is ignored.
	  file = files
	  var = file.var(varname)
	  raise "variable '#{varname}' not found in #{file}" if !var
	  if ntype != nil && gd_flag == 1
      VArrayHE5SwField.new2( var , varname, ntype,  dim)
	  elsif ntype != nil && gd_flag == 0
      VArrayHE5SwField.new3( file, varname, ntype,  dim)
	  else
      VArrayHE5SwField.new( var )
    end
  elsif files.is_a?(HE5Gd)
	  # Single file. Returns a VArrayHE5GdField. dim is ignored. 
	  file = files
	  var = file.var(varname)
	  raise "variable '#{varname}' not found in #{file}" if !var
	  if ntype != nil && gd_flag == 1
      VArrayHE5GdField.new2( var , varname, ntype,  dim)
	  else
      VArrayHE5GdField.new( var )
    end
  elsif files.is_a?(HE5Za)
	  # Single file. Returns a VArrayHE5ZaField. dim is ignored. 
	  file = files
	  var = file.var(varname)
	  raise "variable '#{varname}' not found in #{file}" if !var
	  if ntype != nil && gd_flag == 1
      VArrayHE5ZaField.new2( var , varname, ntype,  dim)
	  else
      VArrayHE5ZaField.new( var )
    end
	elsif files.is_a?(NArray)
	  # Suppose that files is a NArray of HDF-EOS5. Returns a VArrayCompsite.
	  if dim.is_a?(Integer) && dim>=0 && dim<files.rank
	    files = files[ *([0]*dim+[true]+[0]*(files.rank-dim-1)) ]
	  end
	  varys = NArray.object( *files.shape )
	  for i in 0...files.length
	    var = files[i].var( varname )
      ntype = var.ntype
      ntype = var.dim
	    raise "variable '#{varname}' not found in #{files[i].path}" if !var
  if ntype != nil && gd_flag == 1     # For Data Field
        varys[i] = VArrayHE5SwField.new2( var , varname, ntype,  dim)
	    elsif ntype != nil && gd_flag == 0  # For Geo Location Field
        varys[i] = VArrayHE5SwField.new3( file, varname, ntype,  dim)
	    else
        varys[i] = VArrayHE5SwField.new( var )
      end
	  end
	  if files.length != 1
	    VArrayComposite.new( varys )
	  else
	    varys[0]
	  end
	else
	  raise TypeError, "not a HDF-EOS5 or NArray"
	end
end

.__interpret_files(files, varname) ⇒ Object



305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# File 'lib/numru/gphys/gphys_hdfeos5_io.rb', line 305

def __interpret_files( files, varname )
  gridtype = nil  # --> "swath", "grid", "za", ....
	case files
	when HE5, String
    files   = HE5.open(files) if files.is_a?(String)
    dirname, varname, = varname.split(/\//)

    if files.has_swath?
      swath = files.swath(dirname) or raise("Can't find a swath named #{dirname}")
      he5var0 = swath.var( varname )
      gridtype = 'swath'
    elsif files.has_grid?
      grid = files.grid(dirname) or raise("Can't find a grid named #{dirname}")
      he5var0 = grid.var( varname )
      gridtype = 'grid'
    elsif files.has_za?
      za = files.zonal(dirname) or raise("Can't find a zonal average named #{dirname}")
      he5var0 = za.var( varname )
      gridtype = 'za'
    else
      raise "Sorry. Currenly, only the Swath type is supported"
    end
	when HE5Sw
	  he5var0 = files.var( varname )
    gridtype = 'swath'
	when HE5Gd
	  he5var0 = files.var( varname )
    gridtype = 'grid'
  # when Regexp 
	else
	  raise TypeError, "argument files: not a HDF-EOS5, String, NArray, or Array"
	end
	[files, he5var0, varname, gridtype]
end

.__make_field_one_dimension(aHE5GdField, dim_index) ⇒ Object

dim_index に関して実質1次元の変数ならば VArray を返す。そうでなければ nil を返す。



479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
# File 'lib/numru/gphys/gphys_hdfeos5_io.rb', line 479

def __make_field_one_dimension(aHE5GdField, dim_index)
  rank = aHE5GdField.rank
  indexes = Array.new
  seps = (2**(-23).to_f) * 10
  deps = Float::EPSILON * 10 # (2**(-52).to_f) * 10
  permissible_diff = case aHE5GdField.simple_get.typecode
                     when NArray::SFLOAT, NArray::SCOMPLEX then seps
                     when NArray::DFLOAT, NArray::DCOMPLEX then deps
                     else 0
                     end

  for i in 0...rank do
    indexes.push(i) unless i == dim_index
  end
  mn = aHE5GdField.simple_get.min(*indexes)
  mx = aHE5GdField.simple_get.max(*indexes)
  maxdiff = (mx - mn).max
  maxval = ((mx1=mx.max)>(mx2=-mn.min)) ? mx1 : mx2        

  is_zero = (maxdiff/maxval <= permissible_diff)

  unless is_zero
    return nil 
  else
    ary = Array.new
    for j in 0...rank do
      if j == dim_index
        ary.push(true)
      else
        ary.push(0)
      end
    end
    return VArrayHE5GdField.new(aHE5GdField).[](*ary)
  end
end

.__make_gd_axes(var0, grid, data) ⇒ Object



340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'lib/numru/gphys/gphys_hdfeos5_io.rb', line 340

def __make_gd_axes(var0, grid, data)
  dim_names = var0.dim_names # 次元の名前
  unlocated_dim_names = var0.dim_names # まだ軸の決まっていない次元の名前
  unused_var_names = grid.var_names
  axes = Array.new

  # (#1) HDF-EOS5 standard rule.
  ["Longitude", "Latitude"].each do |provided_varname|
    unlocated_dim_names.each do |dim_nm|
      if (vary = __make_field_one_dimension(grid.var(provided_varname), dim_names.index(dim_nm)))
        axes.push(Axis.new().set_pos(vary))
        unlocated_dim_names.delete(dim_nm)
        unused_var_names.delete(provided_varname)
        break
      end
    end
  end
  if unused_var_names.include?("Longitude") || unused_var_names.include?("Latitude")
    raise("Sorry. Truely multidimensional longitudes/latitudes are yet to be supported. (2-dimensional lon/lat data that are actually one dimensional are supported.)")
  end

  # (#2) Empirical rule (from EOS-AURA, MLS, etc)
  # (#2-1) 軸が未確定の次元に対し、次元名と一致する名前を持つ1次元変数を座標変数として採用する
  unlocated_dim_names.each do |dim_nm|
    if unused_var_names.include?(dim_nm)
      vary = __files2varray( grid, dim_nm)
      if vary.rank == 1
        axes.push(Axis.new().set_pos(vary))
        unlocated_dim_names.delete(dim_nm)
        unused_var_names.delete(dim_nm)
      end
    end
  end

  # (#2-2) 軸が未確定の次元に対し、その次元を使って定義されている1次元変数を座標変数として採用する
  # (a) select variables match to Regexp. 
  @@predef_gdcoords.each do |reg_exp|
    unlocated_dim_names.each do |dim_nm|
      # get candidates
      candidate_var_names = Array.new
      unused_var_names.each do |var_nm|
        var = grid.var(var_nm)
        if reg_exp =~ var_nm && var.dim_names.include?(dim_nm)
          candidate_var_names.push(var_nm)
        end
      end
      
      # permute the candidates in order of length.
      candidate_var_names = candidate_var_names.sort {|a, b| a.length <=> b.length}
      candidate_var_names.each do |candidate|
        vary = __files2varray(grid, candidate)
        if vary.rank == 1
          axes.push(Axis.new().set_pos(vary))
          unlocated_dim_names.delete(dim_nm)
          unused_var_names.delete(candidate)
        end
        break if unlocated_dim_names.length == 0
      end
    end
  end

  # (#2-3) 座標変数はファイル中にないものとみなし,
  # ダミーとして 0,1,2,... が割り当てられるようにする.
  unlocated_dim_names.each do |dim_nm|
    nary_length = data.shape_current[dim_names.index(dim_nm)]
    nary = NArray[0...nary_length]
    vary = VArray.new(nary).rename(dim_nm + "_dummy")
    axis = Axis.new(false, true)
    axis.set_pos(vary)
    axes.push(axis)
  end

  return axes
end

.__make_za_axes(var0, za, data) ⇒ Object



416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
# File 'lib/numru/gphys/gphys_hdfeos5_io.rb', line 416

def __make_za_axes(var0, za, data)
  dim_names = var0.dim_names # 次元の名前
  unlocated_dim_names = var0.dim_names # まだ軸の決まっていない次元の名前
  unused_var_names = za.var_names
  axes = Array.new

  # (#1) HDF-EOS5 standard rule is none.
  # (#2) Empirical rule (from EOS-AURA, MLS, etc)
  # (#2-1) 次元名と一致する名前を持つ1次元変数を座標変数として採用する
  unlocated_dim_names.each do |dim_nm|
    if unused_var_names.include?(dim_nm)
      vary = __files2varray( za, dim_nm)
      if vary.rank == 1
        axes.push(Axis.new().set_pos(vary))
        unlocated_dim_names.delete(dim_nm)
        unused_var_names.delete(dim_nm)
      end
    end
  end

  # (#2-2) 軸が未確定の次元に対し、その次元を使って定義されている1次元変数を座標変数として採用する
  # (a) select variables match to Regexp. 
  @@predef_zacoords.each do |reg_exp|
    unlocated_dim_names.each do |dim_nm|
      # get candidates
      candidate_var_names = Array.new
      unused_var_names.each do |var_nm|
        var = za.var(var_nm)
        if reg_exp =~ var_nm && var.dim_names.include?(dim_nm)
          candidate_var_names.push(var_nm)
        end
      end
      
      # permute the candidates in order of length.
      candidate_var_names = candidate_var_names.sort {|a, b| a.length <=> b.length}
      candidate_var_names.each do |candidate|
        vary = __files2varray(za, candidate)
        if vary.rank == 1
          axes.push(Axis.new().set_pos(vary))
          unlocated_dim_names.delete(dim_nm)
          unused_var_names.delete(candidate)
        end
        break if unlocated_dim_names.length == 0
      end
    end
  end

  # (#2-3) 座標変数はファイル中にないものとみなし,
  # ダミーとして 0,1,2,... が割り当てられるようにする.
  unlocated_dim_names.each do |dim_nm|
    nary_length = data.shape_current[dim_names.index(dim_nm)]
    nary = NArray[0...nary_length]
    vary = VArray.new(nary).rename(dim_nm + "_dummy")
    axis = Axis.new(false, true)
    axis.set_pos(vary)
    axes.push(axis)
  end

  return axes
end

._gd_open(var0, varname) ⇒ Object



146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/numru/gphys/gphys_hdfeos5_io.rb', line 146

def _gd_open(var0, varname)
  #< make axes >
  grid = var0.grid
  data = __files2varray( grid, varname )
  axes = __make_gd_axes(var0, grid, data)

  #< make grid >
  new_grid = Grid.new( *axes )

  #< make gphys >
  GPhys.new(new_grid,data)
end

._sw_open(var0, varname) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/numru/gphys/gphys_hdfeos5_io.rb', line 65

def _sw_open(var0, varname)
  swath = var0.swath
  	data = __files2varray( swath, varname )
	rank = data.rank
  dim_names = var0.dim_names

  #< coordiante varables >

  geo_names = swath.geo_names  # geolocation varables
  coords = Array.new(rank)
  assoccoords = Array.new

  proc = Proc.new{|nm|
    vdns = swath.var(nm).dim_names
    if vdns.length==1 && (dim=dim_names.index(vdns[0])) && !coords[dim]
      coords[dim] = __files2varray( swath, nm)
    elsif ( (vdns - dim_names).length==0 )  # all dims are covered
      dimids = vdns.collect{|s| dim_names.index(s)}
      assoccoords.push( [dimids, __files2varray( swath, nm)] )
    end
  }

  # (first precedence) Predefined coordinate variable names
  PredefCoordNames.each do |nm|
    proc.call(nm) if geo_names.delete(nm)  # if included, delete and call
  end

  # (second precedence) Variables having the same name as a dimension
  dim_names.each do |nm|
    proc.call(nm) if geo_names.delete(nm)  # if included, delete and call
  end

  # (else)
  geo_names.each do |nm|
    proc.call(nm) if  swath.geo(nm).ntype != "char"
  end

=begin
  # if no geolocation variable was found for a dim, search variables too
  if coords.include?(nil)
    swath.var_names.each do |nm|
      vdns = swath.var(nm).dim_names
      if vdns.length==1 && (dim=dim_names.index(vdns[0])) && !coords[dim]
        coords[dim] = __files2varray( swath, nm)
      end
      break if !coords.include?(nil)
    end
  end
=end

  #< make axes >
  axes = Array.new
  coords.each_with_index do |crd, dim|
    if crd
      axis = Axis.new
      axis.set_pos( crd )
    else
      axis = Axis.new(false, true)
      dimnm = dim_names[dim]
      len = data.shape_current[dim]
      axis.set_pos( VArray.new(NArray.float(len).indgen!).rename(dimnm) )
    end
    axes.push( axis )
  end

  #< make grid >
  grid = Grid.new( *axes )

  if assoccoords.length > 0
    assoccoords.collect! do |dimids, vary|
      acgrid = Grid.new( *(dimids.collect{|dim| axes[dim]}) )
      gphys = GPhys.new(acgrid, vary)
    end
    grid.set_assoc_coords( assoccoords )
  end

  #< make gphys >
  GPhys.new(grid,data)
end

._za_open(var0, varname) ⇒ Object



160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/numru/gphys/gphys_hdfeos5_io.rb', line 160

def _za_open(var0, varname)
  #< make axes >
  za = var0.za

  data = __files2varray( za, varname )
  axes = __make_za_axes(var0, za, data)

  #< make grid >
  new_za = Grid.new( *axes )

  #< make gphys >
  GPhys.new(new_za,data)
end

.add_predef_gdcoords(regexp) ⇒ Object

^ In the order of precedence

Raises:

  • (ArgumentError)


22
23
24
25
# File 'lib/numru/gphys/gphys_hdfeos5_io.rb', line 22

def self.add_predef_gdcoords(regexp)
  raise ArgumentError, "arg must be a regexp" unless regexp.is_a?(Regexp)
  @@predef_gdcoords.push(regexp)
end

.add_predef_zacoords(regexp) ⇒ Object

Raises:

  • (ArgumentError)


31
32
33
34
# File 'lib/numru/gphys/gphys_hdfeos5_io.rb', line 31

def self.add_predef_zacoords(regexp)
  raise ArgumentError, "arg must be a regexp" unless regexp.is_a?(Regexp)
  @@predef_gdcoords.push(regexp)
end

.is_a_HE5?(filename) ⇒ Boolean

Returns:

  • (Boolean)


40
41
42
43
44
45
46
47
48
49
# File 'lib/numru/gphys/gphys_hdfeos5_io.rb', line 40

def is_a_HE5?(filename)
  file = nil
  begin
    file = File.open(filename,"rb")
    str = file.read(4)
  ensure
    file.close if file
  end
  return str=="\211HDF"
end

.open(files, varname) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/numru/gphys/gphys_hdfeos5_io.rb', line 51

def open(files, varname)
	files, var0, varname, gridtype = __interpret_files( files, varname )
  case gridtype
  when "swath"
    _sw_open(var0, varname)
  when "grid"
    _gd_open(var0, varname)
  when "za"
    _za_open(var0, varname)
  else
    raise "Sorry. Currently, only the Swath type is supported"
  end
end

.predef_gdcoordsObject



27
28
29
# File 'lib/numru/gphys/gphys_hdfeos5_io.rb', line 27

def self.predef_gdcoords
  @@predef_gdcoords
end

.predef_zacoordsObject



36
37
38
# File 'lib/numru/gphys/gphys_hdfeos5_io.rb', line 36

def self.predef_zacoords
  @@predef_gdcoords
end

.var_names(files) ⇒ Object



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/numru/gphys/gphys_hdfeos5_io.rb', line 195

def var_names(files)
  case files
  when HE5
    file = files
    opened = true
  when String
    file = HE5.open(files)
    opened = false
  else
    raise ArgumentError, "arg must be a HDF-EOS5 or a file name"
  end
  raise "file must be a HDF-EOS5 swath filed" if !file.has_swath?()
  swathlist=file.swath_names()
  varnames=[]
  for i in 0..swathlist.size-1
    sfile=file.swath(swathlist[i])
    sfile.var_names.each{|name|
      f, var, varname, gridtype = __interpret_files( sfile, name )
      if var.rank>1 || var.name!=var.dim_names[0]
        varnames.push(swathlist[i]+"/"+name)
      end
    }
    sfile.closed           # close Swath field
  end
  file.close unless opened # close Swath field & close HDF-EOS5 file
  return varnames
end

.var_names_except_coordinates(files) ⇒ Object



223
224
225
# File 'lib/numru/gphys/gphys_hdfeos5_io.rb', line 223

def var_names_except_coordinates(files)
  var_names(files)
end

.write(file, gphys, name = nil) ⇒ Object



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/numru/gphys/gphys_hdfeos5_io.rb', line 175

def write(file, gphys, name=nil)
  name = gphys.name if name.nil?
  dims = Array.new
  gphys.rank.times{|n|
    dims[n] = gphys.coord(n)
  }

  case file
  when HE5Sw
    VArrayHE5SwField.write(file,gphys.data,name,dims)
  when HE5Gd
    VArrayHE5GdField.write(file,gphys.data,name,dims)
  when HE5Za
  else
    raise ArgumentError, "arg must be a HE5Sw, a HE5Gd or a HE5Za"
  end

  nil
end