Class: NumRu::Axis

Inherits:
Object
  • Object
show all
Defined in:
lib/numru/gphys/axis.rb,
lib/numru/gphys/gphys_dim_op.rb

Constant Summary collapse

@@humane_message =
true
@@strftime_fmt =
nil
@@operations =
["integrate","average"]

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cell = false, bare_index = false, name = nil) ⇒ Axis

Returns a new instance of Axis.



358
359
360
361
362
363
364
365
366
367
368
# File 'lib/numru/gphys/axis.rb', line 358

def initialize(cell=false,bare_index=false,name=nil)
	 @init_fin = false         # true/false (true if initializatn finished)
	 @name = name              # String
	 @pos = nil                # VArray (to set it can be deferred if
                             # @cell to support mother axes)
	 @cell = cell              # true/false
	 @cell_center = nil        # VArray (defined if @cell)
   @cell_bounds = nil        # VArray (defined if @cell)
   @bare_index = bare_index  # true/false(if true @cell is meaningless)
   @aux = nil                # Hash of VArray (auxiliary quantities)
end

Class Method Details

.defined_operationsObject



937
938
939
# File 'lib/numru/gphys/axis.rb', line 937

def Axis.defined_operations
	 @@operations
end

.humane_message=(t_or_f) ⇒ Object

if true, [] returns a humane message when the axis is lost. if false, it returns a naive one



345
346
347
# File 'lib/numru/gphys/axis.rb', line 345

def self.humane_message=(t_or_f)
	@@humane_message = t_or_f
end

.join(ary) ⇒ Object

Join multiple axis objects

  • ary : Array (or 1D NArray) of Axis objects



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
476
# File 'lib/numru/gphys/axis.rb', line 435

def Axis.join(ary)
  ax = ary[0]
  #raise(ArgumentError,"not an Axis") if !ax.is_a?(Axis)
  lens = ary.collect{|ax| ax.length}
  na = ary.length

  axpool = Hash.new
  cell = ax.cell?
  if cell
    axpool[:celctrs] = ary.collect{|ax| ax.cell_center}
    axpool[:celbnds] = ary.collect{|ax| ax.cell_bounds}
  else
    axpool[:pos] = ary.collect{|ax| ax.pos}
  end
  ax.aux_names.each do |nm|
    axpool[nm] = ary.collect{|ax| ax.get_aux(nm)}
  end
  axpool.each do |nm,vas|
    for i in 1...na
      if ( vas[i-1].length == lens[i-1]+1 and vas[i].length == lens[i]+1 \
           and vas[i-1][-1].val == vas[i][0].val )
        vas[i] = vas[i][1..-1]   # exclude overwrap (such as cell_bounds)
      end
      vas = NArray.to_na(vas) if vas.is_a?(Array)
      axpool[nm] = VArrayComposite.new( vas )
    end
  end

  bidx = ax.bare_index?
  name = ax.name
  jax = Axis.new(cell, bidx, name)   # prepare outout (jax: joined axis)
  if cell
    jax.set_cell(axpool.delete(:celctrs), axpool.delete(:celbnds))
    ax.cell_center? ? jax.set_pos_to_center : jax.set_pos_to_bounds
  else
    jax.set_pos(axpool.delete(:pos))
  end
  axpool.each do |nm,va|
    jax.set_aux(nm, va)
  end
  jax
end

.strftime_fmtObject



354
355
356
# File 'lib/numru/gphys/axis.rb', line 354

def self.strftime_fmt
  @@strftime_fmt
end

.strftime_fmt=(fmt) ⇒ Object

nil, or String to explicitly specify the format for strftime used in []



351
352
353
# File 'lib/numru/gphys/axis.rb', line 351

def self.strftime_fmt=(fmt)
  @@strftime_fmt = fmt
end

Instance Method Details

#[](slicer) ⇒ Object



627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
# File 'lib/numru/gphys/axis.rb', line 627

def [] (slicer)
	 if ! @pos
	    raise "pos has not been set. Forgot set_pos_to_(center|bounds)?"
	 end

	 case slicer
	 when Fixnum
	    pos=@pos[slicer]
	    cval = ( pos.val.is_a?(Numeric) ? pos.val : pos.val[0] )
	    units = pos.get_att('units')
	    info_lost = false
	    if @@humane_message
 if units && /(.*) *since *(.*)/ =~ units  
          calendar = self.pos.get_att('calendar')
          datetime = UNumeric[cval, units].to_datetime(0.1,calendar)
          if datetime
            if Units[units] =~ Units['days since 1-1-1'] # s,hour,day,..
              info_lost = datetime.strftime(@@strftime_fmt || '%Y-%m-%d %H:%M:%S%z')
            elsif Units[units] =~ Units['months since 1-1-1'] # year,month,pentad,..
              if /mon/ =~ units.to_s || /year/ =~ units.to_s
                info_lost = datetime.strftime(@@strftime_fmt || '%Y-%m')
              else  # maybe pentad
                info_lost = datetime.strftime(@@strftime_fmt || '%Y-%m-%d')
              end
            end
          end
		info_lost_set = true
 end
	    end
	    if !info_lost_set
 sval = sprintf("%g",cval)
 info_lost = "#{self.name}=#{sval}"
 if (units)   # substitution
		info_lost += " "+units
 end
	    end
	    return info_lost
	 when Range, true
	    # re-organize the range to support slicing of variables
	    # with a 1 larger / smaller length.
	    if true===slicer
  range=0..-1
	    else
  range = slicer
	    end
	    first = range.first
	    last = range.exclude_end? ? range.last-1 : range.last
	    if first < 0
  first += self.length  # first will be counted from the beginning
	    end
	    if last >= 0
  last -= self.length   # last will be counted from the end
	    end
	    slicer = first..last
	    newax=Axis.new(@cell,@bare_index)
	 when Hash
	    range = slicer.keys[0]
	    step = slicer[range]
	    range = 0..-1 if range==true
	    first = range.first
	    last = range.exclude_end? ? range.last-1 : range.last
	    if first < 0
  first += self.length  # first will be counted from the beginning
	    end
	    if last >= 0
  last -= self.length   # last will be counted from the end
	    end
	    slicer = { (first..last) => step }
	    newax=Axis.new(false,@bare_index)  # always not a cell axis
   when NArray, Array
	    newax=Axis.new(false,@bare_index)  # always not a cell axis
	 else
	    raise ArgumentError, "Axis slicing with #{slicer.inspect} is not available"
	 end

	 if newax.bare_index? || !newax.cell?
	    pos=@pos[slicer]
	    newax.set_pos( pos )
	 elsif newax.cell?
	    center=@cell_center[slicer]
	    bounds=@cell_bounds[slicer]
	    newax.set_cell( center, bounds )
	    if self.cell_center?
  newax.set_pos_to_center
	    elsif self.cell_bounds?
  newax.set_pos_to_bounds
	    end
	 end
	 if @aux
	    @aux.each{ |name, vary|
#	       if (aux=vary[slicer]).rank != 0
		  newax.set_aux(name, vary[slicer])
#	       else
#		  print "WARNING #{__FILE__}:#{__LINE__} auxiliary VArray #{name} is eliminated\n"
#	       end
	    }
	 end
	 newax
end

#add(z) ⇒ Object



988
989
990
# File 'lib/numru/gphys/axis.rb', line 988

def add(z)
  self.copy.add!(z)
end

#add!(z) ⇒ Object

  • z : usually a scalar, but can be an array-like object (which may be used in cyclic operations)



994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
# File 'lib/numru/gphys/axis.rb', line 994

def add!(z)
  @pos += z

  if @cell
    if cell_bounds?
      if z.respond_to?(:length)
        @cell_center += z[0..-2]
      else
        @cell_center += z
      end
    elsif cell_center?
      if z.respond_to?(:length)  # array-like
        @cell_bounds[0..-2] += z
        @cell_bounds[-1..-1] += z[-1..-1]   # simply use the last one
      else
        @cell_bounds += z
      end
    end
  end

  self
end

#aux_namesObject



605
606
607
# File 'lib/numru/gphys/axis.rb', line 605

def aux_names
	 @aux ? @aux.keys : []
end

#average(ary, dim) ⇒ Object



955
956
957
958
959
960
961
962
# File 'lib/numru/gphys/axis.rb', line 955

def average(ary,dim)
	 if !@avg_weight; _set_default_avg_weight; end
	 sh = (0...ary.rank).collect{|i| (i==dim) ? @avg_weight.length : 1 }
	 mn = sprintf("%g", ( UNumeric===(a=@pos.min) ? a.val : a) )
   mx = sprintf("%g", ( UNumeric===(a=@pos.max) ? a.val : a) )
	 return [ ( ary * @avg_weight.reshape(*sh) ).sum(dim), 
     "averaged  "+@name+":#{mn}..#{mx}" ]
end

#average_weightObject



964
# File 'lib/numru/gphys/axis.rb', line 964

def average_weight; @avg_weight; end

#average_weight=(wgt) ⇒ Object



965
# File 'lib/numru/gphys/axis.rb', line 965

def average_weight=(wgt); @avg_weight=wgt; end

#bare_index?Boolean

Returns:

  • (Boolean)


390
391
392
# File 'lib/numru/gphys/axis.rb', line 390

def bare_index?
	 @bare_index
end

#binning(len) ⇒ Object



213
214
215
216
217
218
219
220
221
222
223
# File 'lib/numru/gphys/gphys_dim_op.rb', line 213

def binning(len)
  if cell? && cell_center?
    c = cell_center.bin_mean(0,len)
    b = cell_bounds[ {0..-1=>len} ]
    newax = Axis.new(true).set_cell(c,b)
    newax = axcel.dup.set_pos_to_center
  else
    newax = Axis.new().set_pos( pos.bin_mean(0,len) )
  end
  newax  
end

#cell?Boolean

Returns:

  • (Boolean)


381
382
383
# File 'lib/numru/gphys/axis.rb', line 381

def cell?
	 @cell
end

#cell_boundsObject



534
535
536
# File 'lib/numru/gphys/axis.rb', line 534

def cell_bounds
	 @cell_bounds
end

#cell_bounds?Boolean

Returns:

  • (Boolean)


387
388
389
# File 'lib/numru/gphys/axis.rb', line 387

def cell_bounds?
	 @cell && @pos.length == @cell_bounds.length
end

#cell_centerObject



531
532
533
# File 'lib/numru/gphys/axis.rb', line 531

def cell_center
	 @cell_center
end

#cell_center?Boolean

Returns:

  • (Boolean)


384
385
386
# File 'lib/numru/gphys/axis.rb', line 384

def cell_center?
	 @cell && @pos.length == @cell_center.length
end

#collectObject



478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
# File 'lib/numru/gphys/axis.rb', line 478

def collect
	 # This method is like ((<copy>)), but it is the 'collect' 
   # iterator for each VArray in self (block required).
	 out = Axis.new(cell?, bare_index?, name)
	 if cell?
	    out.set_cell( yield(@cell_center), yield(@cell_bounds) )
	    if cell_center?
  out.set_pos_to_center
	    elsif cell_bounds?
  out.set_pos_to_bounds
	    end
	 else
	    out.set_pos( yield(@pos) )
	 end
	 if @aux
	    @aux.each{|k,v|
  out.set_aux(k, yield(v))
	    }
	 end
	 out
end

#copyObject



412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
# File 'lib/numru/gphys/axis.rb', line 412

def copy
	 # deep clone onto memory
	 out = Axis.new(cell?, bare_index?, name)
	 if cell?
	    out.set_cell( @cell_center.copy, @cell_bounds.copy )
	    if cell_center?
  out.set_pos_to_center
	    elsif cell_bounds?
  out.set_pos_to_bounds
	    end
	 else
	    out.set_pos( @pos.copy )
	 end
	 if @aux
	    @aux.each{|k,v|
  out.set_aux(k, v.copy)
	    }
	 end
	 out
end

#cut(coord_cutter) ⇒ Object



727
728
729
730
731
732
733
# File 'lib/numru/gphys/axis.rb', line 727

def cut(coord_cutter)
  if cyclic_extendible?
    _cut_cyclic(false, coord_cutter)
  else
    _cut_(false, coord_cutter)
  end
end

#cut_rank_conserving(coord_cutter) ⇒ Object



734
735
736
737
738
739
740
# File 'lib/numru/gphys/axis.rb', line 734

def cut_rank_conserving(coord_cutter)
  if cyclic_extendible?
    _cut_cyclic(true, coord_cutter)
  else
    _cut_(true, coord_cutter)
  end
end

#cyclic?Boolean

Returns:

  • (Boolean)


976
977
978
# File 'lib/numru/gphys/axis.rb', line 976

def cyclic?
	@pos.axis_cyclic?
end

#cyclic_extendible?Boolean

Returns:

  • (Boolean)


984
985
986
# File 'lib/numru/gphys/axis.rb', line 984

def cyclic_extendible?
	@pos.axis_cyclic_extendible?
end

#draw_positiveObject



967
968
969
970
971
972
973
974
# File 'lib/numru/gphys/axis.rb', line 967

def draw_positive
	# Returns the direction to plot the axis
	# * true: axis should be drawn in the increasing order(to right/upward)
	# * false: axis should be drawn in the decreasing order
	# * nil: not specified (VArray's default if not overridden in 
  #   subclasses)
	@pos.axis_draw_positive
end

#each_varrayObject



408
409
410
# File 'lib/numru/gphys/axis.rb', line 408

def each_varray
	self.flatten.each{|x| yield x}
end

#flattenObject



394
395
396
397
398
399
400
401
402
403
404
405
406
# File 'lib/numru/gphys/axis.rb', line 394

def flatten
	 # return VArrays contained in a flat array
	 out = Array.new
	 out.push(@pos) if @pos
	 out.push(@cell_center) if @cell_center && !cell_center?
	 out.push(@cell_bounds) if @cell_bounds && !cell_bounds?
	 if @aux
	    @aux.each{|k,v|
  out.push(v)
	    }
	 end
	 out
end

#get_aux(name) ⇒ Object



602
603
604
# File 'lib/numru/gphys/axis.rb', line 602

def get_aux(name)
	 @aux[name]
end

#inspectObject



370
371
372
# File 'lib/numru/gphys/axis.rb', line 370

def inspect
	 "<axis pos=#{@pos.inspect}>"
end

#integ_weightObject



952
# File 'lib/numru/gphys/axis.rb', line 952

def integ_weight; @integ_weight; end

#integ_weight=(wgt) ⇒ Object



953
# File 'lib/numru/gphys/axis.rb', line 953

def integ_weight=(wgt); @integ_weight=wgt; end

#integrate(ary, dim) ⇒ Object



943
944
945
946
947
948
949
950
# File 'lib/numru/gphys/axis.rb', line 943

def integrate(ary,dim)
	 if !@integ_weight; _set_default_integ_weight; end
	 sh = (0...ary.rank).collect{|i| (i==dim) ? @integ_weight.length : 1 }
	 mn = sprintf("%g", ( UNumeric===(a=@pos.min) ? a.val : a) )
   mx = sprintf("%g", ( UNumeric===(a=@pos.max) ? a.val : a) )
	 return [ ( ary * @integ_weight.reshape(*sh) ).sum(dim), 
     "integrated  "+@name+":#{mn}..#{mx}" ]
end

#lengthObject



538
539
540
541
542
543
544
# File 'lib/numru/gphys/axis.rb', line 538

def length
	 if @pos
	    @pos.length
	 else
	    raise "length is not determined until pos is set"
	 end
end

#moduloObject



980
981
982
# File 'lib/numru/gphys/axis.rb', line 980

def modulo
	@pos.axis_modulo
end

#nameObject



377
378
379
# File 'lib/numru/gphys/axis.rb', line 377

def name
	 @name || "noname"
end

#name=(nm) ⇒ Object



374
375
376
# File 'lib/numru/gphys/axis.rb', line 374

def name=(nm)
	 @name=nm
end

#posObject



527
528
529
530
# File 'lib/numru/gphys/axis.rb', line 527

def pos
	 raise "pos has not been set" if !@pos
	 @pos
end

#pos=(pos) ⇒ Object



500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
# File 'lib/numru/gphys/axis.rb', line 500

def pos=(pos)
	 if !@cell
	    if ! pos.is_a?(VArray)
  raise ArgumentError,"arg not a VArray: #{pos.class}"  
	    end
	    if pos.rank != 1
 raise ArgumentError,"rank of #{pos.name} (#{pos.rank}) is not 1" 
	    end

	    @pos=pos
	    @init_fin = true
	    if ! @name
  @name = pos.name
	    end
	 else
	    raise "This method is not available for a cell axis. "+
     "Use set_pos_to_center or set_pos_to_bounds instead."
	 end
	 pos
end

#set_aux(name, vary) ⇒ Object



585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
# File 'lib/numru/gphys/axis.rb', line 585

def set_aux(name,vary)
	 if !name.is_a?(String) 
	    raise ArgumentError,"1nd arg: not a String"
	 end

	 if ! vary.is_a?(VArray)
	    raise ArgumentError,"2nd arg not a VArray: #{vary.class}"  
	 end
	 if vary.rank != 1
	    raise ArgumentError,"rank of #{vary.name} (#{vary.rank}) is not 1" 
	 end

	 if !@aux; @aux = Hash.new; end

	 @aux[name] = vary
	 self
end

#set_cell(center, bounds, name = nil) ⇒ Object



546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
# File 'lib/numru/gphys/axis.rb', line 546

def set_cell(center, bounds, name=nil)
	 # it is the user's obligation to ensure that center and bounds
   # have the same units etc.

	 # < error check >

	 if ! @cell; raise "method not available for a non-cell axis"; end

	 if ! center.is_a?(VArray)
	    raise ArgumentError,"1st arg not a VArray: #{center.class}"  
	 end
	 if center.rank != 1
	    raise ArgumentError,"center: rank of #{center.name} (#{center.rank}) is not 1" 
	 end

	 if ! bounds.is_a?(VArray)
	    raise ArgumentError,"2nd arg not a VArray: #{bounds.class}"  
	 end
	 if bounds.rank != 1
	    raise ArgumentError,"bounds: rank of #{bounds.name} (#{bounds.rank}) is not 1" 
	 end

	 if( center.length != bounds.length-1 )
	    raise "center.length != bounds.length-1"
	 end

	 # < do the job >

	 @cell_center = center
	 @cell_bounds = bounds
	 if name
	    @name=name
	 end
	 @init_fin = true       # To set @pos is deferred at this moment.
                          # use set_pos_to_(bounds|center) to make 
                          # the object fully available
   self
end

#set_cell_guess_bounds(center, name = nil) ⇒ Object



903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
# File 'lib/numru/gphys/axis.rb', line 903

def set_cell_guess_bounds(center, name=nil)
	 # derive bounds with a naive assumption (should be OK for
	 # an equally separated axis).
	 if ! center.is_a?(VArray) || center.rank != 1
	    raise ArgumentError, "1st arg: not a VArray, or its rank != 1" 
	 end
	 vc = center.val
	 vb = NArray.float( vc.length + 1 )
	 vb[0] = vc[0] - (vc[1]-vc[0])/2   # Assume this!!
	 for i in 1...vb.length
	    vb[i] = 2*vc[i-1] - vb[i-1]    # from vc[i-1] = (vb[i-1]+vb[i])/2
	 end
	 bounds = VArray.new(vb, center)  # borrow attributes from center
	 set_cell(center, bounds, name)
end

#set_pos(pos) ⇒ Object



521
522
523
524
525
# File 'lib/numru/gphys/axis.rb', line 521

def set_pos(pos)
	 self.pos= pos
	 @name = pos.name
	 self
end

#set_pos_to_boundsObject



928
929
930
931
932
933
934
935
# File 'lib/numru/gphys/axis.rb', line 928

def set_pos_to_bounds
	 raise "The method is not available for a non-cell axis" if ! @cell
	 @pos = @cell_bounds
	 if !@name
	    @name = @cell_bounds.name
	 end
	 self
end

#set_pos_to_centerObject



919
920
921
922
923
924
925
926
# File 'lib/numru/gphys/axis.rb', line 919

def set_pos_to_center
	 raise "The method is not available for a non-cell axis" if ! @cell
	 @pos = @cell_center
	 if !@name
	    @name = @cell_center.name
	 end
	 self
end

#to_gphys(datavary1d = nil) ⇒ Object



609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
# File 'lib/numru/gphys/axis.rb', line 609

def to_gphys(datavary1d=nil)
	# To form a 1-dimensional GPhys
	# (Dependent on GPhys&Grid, unlike other methods Axis,
  # so the test program is in gphys.rb)
	# Arguments
	#   * datavary1d (nil or VArray): 1D VArray with the same
  #     size as the axis. If omitted, @pos (coordinate variable
  #     of the variable) is used.
	if !datavary1d
	  datavary1d = @pos.copy
	else
	  if datavary1d.rank != 1 || datavary1d.length != length
 raise ArgumentError, "Must be 1D and same size"
	  end
	end
	GPhys.new( Grid.new(self), datavary1d )
end