Class: NumRu::GPhys

Inherits:
Object
  • Object
show all
Defined in:
lib/numru/ganalysis/fitting.rb,
lib/numru/gphys/grib.rb,
lib/numru/ganalysis/eof.rb,
lib/numru/ganalysis/met.rb,
lib/numru/gphys/ep_flux.rb,
lib/numru/gphys/version.rb,
lib/numru/gphys/gphys_io.rb,
lib/numru/ganalysis/log_p.rb,
lib/numru/gphys/gphys_fft.rb,
lib/numru/gphys/gphys_dim_op.rb,
lib/numru/ganalysis/histogram.rb,
lib/numru/gphys/gphys_grib_io.rb,
lib/numru/ganalysis/covariance.rb,
lib/numru/gphys/coordtransform.rb,
lib/numru/gphys/gphys_grads_io.rb,
lib/numru/gphys/gphys_gtool3_io.rb,
lib/numru/gphys/gphys_io_common.rb,
lib/numru/gphys/gphys_netcdf_io.rb,
lib/numru/gphys/gphys_nusdas_io.rb

Overview

GPhys extension with GAnalysis::Fitting

Defined Under Namespace

Modules: EP_Flux, GrADS_IO, GribUtils, Grib_IO, Gtool3_IO, IO, IO_Common, NetCDF_IO, NuSDaS_IO Classes: Grib, GribDim, GribVar

Constant Summary collapse

VERSION =
"1.4.3.2"
COS_TAPER_SP_FACTOR =
1.0 / 0.875
BC_SIMPLE =

enum in convol_filter.c

10
BC_CYCLIC =

enum in convol_filter.c

11
BC_TRIM =

enum in convol_filter.c

12
@@fft_forward =
-1
@@fft_backward =
1
@@fft_ignore_missing =
false
@@fft_missing_replace_val =
nil
@@default_missval =

NC_FILL_DOUBLE/FLOAT ~15*2^119

9.9692099683868690e+36

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.fft_ignore_missing(ignore = true, replace_val = nil) ⇒ Object



331
332
333
334
# File 'lib/numru/gphys/gphys_fft.rb', line 331

def self.fft_ignore_missing( ignore=true, replace_val=nil )
  @@fft_ignore_missing = ignore 
  @@fft_missing_replace_val = replace_val
end

Instance Method Details

#bin_mean(dim, len, nminvalid = 1) ⇒ Object

Binning along a dimension (mean)

The values are averaged every “len” grids; unlike running_mean the number of grids is reduced to 1/len. Currently, the only available boundary condition is BC_TRIM.

ARGUMENTS

  • dim (Integer or String) : the dimension

  • len (Integer): length of the bin

  • nminvalid (Integer; optional; defualt=1): Effective only for data with missing. Minimum number of grid points needed for averaging (1 to len).

RETURN VALUE

  • a GPhys



113
114
115
116
# File 'lib/numru/gphys/gphys_dim_op.rb', line 113

def bin_mean(dim, len, nminvalid=1)
  dim = dim_index(dim)  # to handle String or negative specification
  GPhys.new( grid.binning(dim, len), data.bin_mean(dim, len, nminvalid) )
end

#bin_sum(dim, len, nminvalid = 1) ⇒ Object

Binning along a dimension (summation)

Similar to bin_mean, but the values are simply summed without averaging

ARGUMENTS

  • dim (Integer or String) : the dimension

  • len (Integer): length of the bin

  • nminvalid (Integer; optional; defualt=1): Effective only for data with missing. Minimum number of grid points needed for averaging (1 to len).

RETURN VALUE

  • a GPhys



131
132
133
134
# File 'lib/numru/gphys/gphys_dim_op.rb', line 131

def bin_sum(dim, len, nminvalid=1)
  dim = dim_index(dim)  # to handle String or negative specification
  GPhys.new( grid.binning(dim, len), data.bin_sum(dim, len, nminvalid) ) 
end

#coordtransform(coordmapping, axes_to, *dims) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/numru/gphys/coordtransform.rb', line 41

def coordtransform( coordmapping, axes_to, *dims )

  rankmp = coordmapping.rank

  #< check arguments >
  if axes_to.length != rankmp
    raise ArgumentError,
      "length of axes_to must be equal to the rank of coordmapping"
  end
  if self.rank == rankmp
    dims = (0...rankmp).collect{|i| i}
  elsif self.rank < rankmp
    raise ArgumentError,"rank of coordmapping is greater than self.rank"
  elsif dims.length != rankmp
    raise ArguemntError,
      "# of dimensions speficied is not equal to the rank of coordmapping"
  elsif dims != dims.sort
    raise ArguementErroor,"dims must be in the increasing order"
  end

  #< get grid points >
  vt = coordmapping.map_grid( *dims.collect{|d| axes_to[d].pos.val} )
  x = dims.collect{|d| self.grid.axis(d).pos.val}
  #< prepare the output object >
  axes = (0...self.rank).collect{|i| grid.axis(i)}
  dims.each_with_index{|d,j| axes[d]=axes_to[j]}
  grid_to = Grid.new( *axes )
  vnew = VArray.new( NArray.new( self.data.ntype, *grid_to.shape ),
                    self.data, self.name )

  #< do interpolation (so far only 2D is supported) >
  case dims.length
  when 2
    if !HAVE_NUMRU_SSL2

      p "interpolation without SSL2"
#         raise "Sorry, so far I need SSL2 (ruby-ssl2)"
      self.each_subary_at_dims_with_index( *dims ){ |fxy,idx|

        wgts = Array.new
        idxs = Array.new

        for d in 0..dims.length-1
          wgt = vt[d].dup.fill!(-1.0)
          idx0 = vt[d].dup.to_i.fill!(-1)
          idx1 = idx0.dup.fill!(x[d].length)

          xsort = x[d].sort
          xsortindex = x[d].sort_index
          for i in 0..x[d].length-1
            idx0[ xsort[i] <= vt[d] ] = xsortindex[i]
            idx1[ xsort[-1-i] >= vt[d] ] = xsortindex[-1-i]
          end

          # where idx0=idx1
          wgt[ idx0.eq(idx1) ] = 1.0

          # where vt[d] < x[d].min
          wgt[ idx0 <= -1 ] = 1.0
          idx0[ idx0 <= -1 ] = 0

          # where vt[d] > x[d].max
          wgt[ idx1 >= x[d].length ] = 0.0
          idx1[ idx1 >= x[d].length ] = x[d].length-1

          # normal points
          mask = wgt.eq(-1.0)
          wgt[mask] = (vt[d][mask]-x[d][idx0[mask]])/(x[d][idx1[mask]]-x[d][idx0[mask]])

          wgts.push(wgt)
          idxs[d*2] = idx0
          idxs[d*2+1] = idx1

        end

        case dims.length
#            when 1
#              f =   fxy.data.val[idxs[0]]*(1-wgts[0]) + 
#                    fxy.data.val[idxs[1]]*wgts[0]
#              f = f.to_na if( f.class.to_s == "NArrayMiss" )
        when 2
          lx = fxy.shape[0]
          f =   ( fxy.data.val[idxs[0]+idxs[2]*lx]*(1-wgts[0]) + 
                  fxy.data.val[idxs[1]+idxs[2]*lx]*wgts[0]
                ) * (1-wgts[1]) + 
                ( fxy.data.val[idxs[0]+idxs[3]*lx]*(1-wgts[0]) + 
                  fxy.data.val[idxs[1]+idxs[3]*lx]*wgts[0] 
                ) * wgts[1]
          f = f.to_na if( f.class.to_s == "NArrayMiss" )
        else
          raise "Sorry, #{v.length}D interpolation is yet to be supported"
        end

        if(idx==false)
          vnew[] = f
        else
          vnew[*idx] = f
        end
      }

    else
      ix=iy=0
      m=3
      self.each_subary_at_dims_with_index( *dims ){ |fxy,idx|
        c,xt = SSL2.bicd3(x[0],x[1],fxy.val,m)
        begin
          ix,iy,f = SSL2.bifd3(x[0],x[1],m,c,xt,0,vt[0],ix,0,vt[1],iy)
        rescue
          $stderr.print "Interpolation into", vt[0].inspect, vt[1].inspect
          raise $!
        end
        vnew[*idx] = f
      }
    end
  else
    raise "Sorry, #{v.length}D interpolation is yet to be supported"
  end

  #< finish >
  GPhys.new( grid_to, vnew )
end

#corelation(other, *dims) ⇒ Object Also known as: correlation



93
94
95
# File 'lib/numru/ganalysis/covariance.rb', line 93

def corelation(other, *dims)
  GAnalysis.corelation(self, other, *dims)
end

#cos_taper(*dims) ⇒ Object

Spectral factor for the cosine taper. Specta should be multiplied by this.



339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
# File 'lib/numru/gphys/gphys_fft.rb', line 339

def cos_taper(*dims)
  if dims.length < 1
	raise ArgumentError,'You have to specify one or more dimensions'
  end
  dims.sort!.uniq!
  val = self.data.val
  dims.each{|dim|
	dim = dim_index(dim) if dim.is_a?(String)
	dim += rank if dim < 0
	raise ArgumentError,"dim #{dim} does not exist" if dim<0 || dim>rank
    nx = shape[dim]
	wgt = NArray.float(nx).fill!(1)
    x = 10.0 / nx * (NArray.float(nx).indgen!+0.5) 
	wskl = x.lt(1).where
	wskr = x.gt(9).where
	wgt[wskl] = 0.5*( 1.0 - NMath::cos(Math::PI*x[wskl]) )
	wgt[wskr] = 0.5*( 1.0 - NMath::cos(Math::PI*x[wskr]) )
	wgt.reshape!( *([1]*dim + [nx] + [1]*(rank-dim-1)) )
	val = val*wgt
  }
  to_ret = self.copy
  to_ret.data.val = val
  to_ret
end

#covariance(other, *dims) ⇒ Object



89
90
91
# File 'lib/numru/ganalysis/covariance.rb', line 89

def covariance(other, *dims)
  GAnalysis.covariance(self, other, *dims)
end

#detrend(*dims) ⇒ Object



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
414
# File 'lib/numru/gphys/gphys_fft.rb', line 364

def detrend(*dims)
  if dims.length < 1
	raise ArgumentError,'You have to specify one or more dimensions'
  end
  dims.sort!.uniq!
  val = self.data.val
  dims.each{|dim|
	dim = dim_index(dim) if dim.is_a?(String)
	dim += rank if dim < 0
	raise ArgumentError,"dim #{dim} does not exist" if dim<0 || dim>rank
	if val.is_a?(NArray)
	  x = self.coord(dim).val
	  x.reshape!( *([1]*dim + [x.length] + [1]*(rank-dim-1)) )
	  vmean = val.mean(dim)
	  vxmean = (val*x).mean(dim)
	  xmean = x.mean(dim)
	  x2mean = (x*x).mean(dim)
	  denom = x2mean-xmean**2
	  if denom != 0
 a = (vxmean - vmean*xmean)/denom
 b = (vmean*x2mean - vxmean*xmean)/denom
	  else
 a = 0
 b = vmean
	  end
	elsif val.is_a?(NArrayMiss)
	  x = self.coord(dim).val
	  x.reshape!( *([1]*dim + [x.length] + [1]*(rank-dim-1)) )
	  x = NArrayMiss.to_nam( NArray.new(x.typecode, *val.shape) + x,
 val.get_mask ) 
	  vmean = val.mean(dim)
	  vxmean = (val*x).mean(dim)
	  xmean = x.mean(dim)
	  x2mean = (x*x).mean(dim)
	  denom = x2mean-xmean**2
	  meq0 = denom.eq(0).to_na(0)    # ==0 and not masked
	  mne0 = denom.ne(0).to_na(0)    # !=0 and not masked
      denom.set_mask(mne0)    # only nonzero part will be used to divide:
	  a = (vxmean - vmean*xmean)/denom
	  b = (vmean*x2mean - vxmean*xmean)/denom
	  a[meq0] = 0
	  b[meq0] = vmean[meq0]
	end
	a.newdim!(dim) if !a.is_a?(Numeric)
	b.newdim!(dim) if !b.is_a?(Numeric)
	val = val - a*x-b
  }
  to_ret = self.copy
  to_ret.data.val = val
  to_ret
end

#eof(*args) ⇒ Object



229
230
231
# File 'lib/numru/ganalysis/eof.rb', line 229

def eof(*args)
  GAnalysis.eof(self, *args)
end

#fft(backward = false, *dims) ⇒ 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
476
477
478
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
# File 'lib/numru/gphys/gphys_fft.rb', line 416

def fft(backward=false, *dims)
  fftw3 = false
  if defined?(FFTW3)
	fftw3 = true
  elsif !defined?(FFTW)
	raise "Both FFTW3 and FFTW are not installed."
  end
  if backward==true
	dir = @@fft_backward
  elsif !backward
	dir = @@fft_forward
  else
	raise ArgumentError,"1st arg must be true or false (or, equivalenty, nil)"
  end

  # <FFT>

  gfc = self.copy  # make a deep clone
  if fftw3
	val = gfc.data.val
	if @@fft_ignore_missing and val.is_a?(NArrayMiss)
	  if @@fft_missing_replace_val
 val = val.to_na(@@fft_missing_replace_val)
	  else
 val = val.to_na 
	  end
    elsif val.is_a?(NArrayMiss) && val.count_invalid == 0
      val = val.to_na 
	end
	fcoef = FFTW3.fft( val, dir, *dims )
  else
	# --> always FFT for all dimensions
	if dims.length == 0
	  raise ArgumentError,
 "dimension specification is available only if FFTW3 is installed"
	end
	val = gfc.data.val
	if @@fft_ignore_missing and val.is_a?(NArrayMiss)
	  if @@fft_missing_replace_val
 val = val.to_na(@@fft_missing_replace_val)
	  else
 val = val.to_na 
	  end
    elsif val.is_a?(NArrayMiss) && val.count_invalid == 0
      val = val.to_na 
	end
	fcoef = FFTW.fftw( val, dir )
  end
  if dir == @@fft_forward
	if dims.length == 0
	  fcoef = fcoef / fcoef.length       # normalized if forward FT
	else
	  sh = fcoef.shape
	  len = 1
	  dims.each{|d|
 raise ArgumentError, "dimension out of range" if sh[d] == nil
 len *= sh[d]
      }
	  fcoef = fcoef / len
    end
  end
  gfc.data.replace_val( fcoef )

  # <coordinate variables>
  for i in 0...gfc.rank
	if dims.length == 0 || dims.include?(i) || dims.include?(i+rank)
	  __predefined_coord_units_conversion(gfc.coord(i))
	  cv = gfc.coord(i).val
	  n = cv.length
	  clen = (cv.max - cv.min) * n / (n-1)
	  wn = (2*Math::PI/clen) * NArray.new(cv.typecode,cv.length).indgen!
	  if (!backward)
 gfc.coord(i).set_att('origin_in_real_space',cv[0..0])
	  else 
 if ( org = gfc.coord(i).get_att('origin_in_real_space') )
   wn += org[0]
   ###gfc.coord(i).del_att('origin_in_real_space')
 end
	  end
	  gfc.coord(i).replace_val(wn)
	  gfc.coord(i).units = gfc.coord(i).units**(-1)
	  __coord_name_conversion(gfc.coord(i), backward)
	end
  end

  # <fini>
  gfc
end

#fft_deriv(dim) ⇒ Object



505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
# File 'lib/numru/gphys/gphys_fft.rb', line 505

def fft_deriv(dim)
  tp = self.data.typecode
  fc = self.fft(false,dim)
  wn = fc.coord(dim)
  k = wn.val.to_type(NArray::Complex)
  n = k.length
  n2a = (n-1)/2
  n2b = [n/2 + 1, n-1].min  # min to avoid error if n=2 (though meaningless)
  kmx = k[-1]+k[1]
  ik = NArray.complex(n)
  ik[0..n2a] = k[0..n2a]*Complex::I
  ik[n2b..-1] = (k[n2b..-1]-kmx) * Complex::I
  dim.times{ik.newdim!(0)}
  (self.rank-dim-1).times{ik.newdim!(-1)}
  fc.replace_val(fc.val*ik)
  deriv = fc.fft(true,dim)
  deriv.units = deriv.units * wn.units
  if tp >= NArray::SCOMPLEX
    deriv
  else
    deriv.real
  end
end

#histogram(opts = Hash.new) ⇒ Object Also known as: histogram1D



155
156
157
# File 'lib/numru/ganalysis/histogram.rb', line 155

def histogram(opts=Hash.new)
  GAnalysis.histogram(self, opts)
end

#least_square_fit(functions, ensemble_dims = nil, indep_dims = nil) ⇒ Object



460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
# File 'lib/numru/ganalysis/fitting.rb', line 460

def least_square_fit(functions, ensemble_dims=nil, indep_dims=nil)

  #< preparation >

  no_fitting_dims = Array.new
  if ensemble_dims
    ensemble_dims = ensemble_dims.collect{|d| @grid.dim_index(d)}
    no_fitting_dims += ensemble_dims
  end
  if indep_dims
    indep_dims = indep_dims.collect{|d| @grid.dim_index(d)}
    no_fitting_dims += indep_dims
  end
  fitting_dims = (0...rank).collect{|i| i} - no_fitting_dims
  grid_locs = fitting_dims.collect{|d| coord(d).val}
  data = self.val

  #< fitting >
  c, bf, diff = GAnalysis::Fitting.least_square_fit(data, grid_locs, 
                                      functions, ensemble_dims, indep_dims)

  #< make a GPhys of the best fit >

  if !ensemble_dims
    grid = self.grid
  else
    axes = Array.new
    (0...rank).each{|d| 
      axes.push(self.axis(d)) unless ensemble_dims.include?(d)
    }
    grid = Grid.new(*axes)
    shape = bf.shape
    ensemble_dims.sort.reverse_each{|d| shape.delete_at(d)}
    bf = bf.reshape(*shape)
  end

  va = VArray.new(bf, self.data, self.name)
  bf = GPhys.new(grid, va)

  [c, bf, diff]
end

#logp_coord_p2z(pdim = nil) ⇒ Object

Convert the pressure coordinate in self to log-pressure height (after duplicating self)

Return value: a GPhys



84
85
86
87
88
89
90
91
92
93
# File 'lib/numru/ganalysis/log_p.rb', line 84

def logp_coord_p2z(pdim=nil)
  pdim = GAnalysis::Met.find_prs_d(self) if !pdim
  p = self.coord(pdim)
  z = GAnalysis::LogP.p2z(p)
  ax = self.axis(pdim).copy
  ax.set_pos(z)
  ax.name = z.name
  grid = self.grid.copy.set_axis(pdim, ax)
  GPhys.new(grid,self.data)
end

#phase_velocity(kdim, fdim, kconv, fconv, kf0_is_c0 = true, no_kfreorder = false) ⇒ Object



757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
# File 'lib/numru/gphys/gphys_fft.rb', line 757

def phase_velocity(kdim,fdim,kconv,fconv,kf0_is_c0=true,no_kfreorder=false)
  kax = self.axis(kdim)
  fax = self.axis(fdim)
  kax.pos = kax.pos*kconv if kconv
  fax.pos = fax.pos*fconv if fconv
  cunits = fax.pos.units / kax.pos.units

  f = fax.pos.val
  k = kax.pos.val
  nk = k.length
  nf = f.length
  if no_kfreorder
    k[nk/2+1..-1] = -k[nk/2+1..-1][-1..0]+k[nk/2]
    f[nf/2+1..-1] = -f[nf/2+1..-1][-1..0]+f[nf/2]
  end
  f = -f
  cp = f.newdim(0) / k.newdim(1) #cp[kdim,fdim]
  jf0 = f.eq(0).where[0]  # where f==0
  jk0 = k.eq(0).where[0]  # where k==0
  if kf0_is_c0
    cp[jk0,jf0] = 0.0       # treat k=f=0 as stationary (c=0)
  else
    cp[jk0,jf0] = 1.0/0.0   # not to count k=f=0 component at all (c=infty)
  end

  [cp, cunits]
end

#phase_velocity_binning(kdim, fdim, cbins, kconv = nil, fconv = nil) ⇒ Object



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
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
# File 'lib/numru/gphys/gphys_fft.rb', line 673

def phase_velocity_binning(kdim, fdim, cbins, kconv=nil, fconv=nil)

  # < process arguments >

  case cbins
  when Hash 
    min = cbins["min"] ||raise(ArgumentError,"a Hash cbins must have 'min'")
    max = cbins["max"] ||raise(ArgumentError,"a Hash cbins must have 'max'")
    int = cbins["int"] ||raise(ArgumentError,"a Hash cbins must have 'int'")
    cbins = Array.new
    eps = int.abs*1e-6   # epsilon to deal with float steps
    (min.to_f..(max.to_f+eps)).step(int){|c| cbins.push(c)}
    cbins = NArray.to_na(cbins)
  when Array
    cbins = NArray.to_na(cbins)
  when NArray
  else
    raise ArgumentError, "cbins must be a Hash or Array or NArray"
  end

  kdim = dim_index(kdim) if kdim.is_a?(String)
  kdim += rank if kdim < 0
  fdim = dim_index(fdim) if fdim.is_a?(String)
  fdim += rank if fdim < 0

  # < sort along wavenumber/freuqency axis >

  pw = self.spect_zero_centering(kdim).spect_one_sided(fdim)

  # < process axes >

  cp, cunits = pw.phase_velocity(kdim,fdim,kconv,fconv,false)

  vcbins = VArray.new(cbins, {"units"=>cunits.to_s, 
                "long_name"=>"phase velocity bounds"}, "cbounds")
  vccent = VArray.new( (cbins[0..-2] + cbins[1..-1])/2, 
                {"units"=>cunits.to_s, "long_name"=>"phase velocity"}, "c")
  axc = Axis.new(true).set_cell(vccent, vcbins).set_pos_to_center
  axes = [axc]   # the first dimension will be "c"
  gr = pw.grid
  (0...pw.rank).each do |d|
    if d!=kdim && d!=fdim
      axes.push(gr.axis(d))
    end
  end
  newgrid = Grid.new(*axes)

  nk = pw.shape[kdim]
  nf = pw.shape[fdim]
  cp.reshape!(nk*nf)

  # < reorder input data >

  dimorder = (0...pw.rank).collect{|i| i}
  dimorder.delete(fdim)
  dimorder.unshift(fdim)
  dimorder.delete(kdim)
  dimorder.unshift(kdim)   # --> [kdim, fdim, the other dims...]
  sh = pw.shape
  reshape = [nk*nf]
  (0...rank).each{|i| reshape.push(sh[i]) if i!=fdim && i!=kdim}
  pwv = pw.val.transpose(*dimorder).reshape(*reshape)  
                           # --> [ combined k&fdim, the other dims...]

  # < binning >

  shc = newgrid.shape
  pwc = NArray.new(pwv.typecode, *shc)    # will have no missing data
  nc = axc.length
  for jc in 0...nc
    w = (cp.gt(cbins[jc]) & cp.lt(cbins[jc+1])).where
    pwc[jc,false] += pwv[w,false].sum(0) if w.length>0
    w = (cp.eq(cbins[jc])).where
    pwc[jc,false] += pwv[w,false].sum(0)/2 if w.length>0  # half from bdry
    w = (cp.eq(cbins[jc+1])).where
    pwc[jc,false] += pwv[w,false].sum(0)/2 if w.length>0  # half from bdry
  end

  vpwc = VArray.new(pwc,pw.data,pw.name)
  gpwc = GPhys.new(newgrid,vpwc)

  gpwc
end

#phase_velocity_binning_iso_norml(kdim, fdim, cmin, cmax, cint, kconv = nil, fconv = nil) ⇒ Object



665
666
667
668
669
670
671
# File 'lib/numru/gphys/gphys_fft.rb', line 665

def phase_velocity_binning_iso_norml(kdim, fdim, cmin, cmax, cint, 
                               kconv=nil, fconv=nil)
  cbins = {"min"=>cmin,"max"=>cmax,"int"=>cint}
  pwc = phase_velocity_binning(kdim, fdim, cbins, kconv, fconv)
  fact = UNumeric[int, pwc.coord(0).units]
  pwc/fact
end

#phase_velocity_filter(xdim, tdim, cmin = nil, cmax = nil, xconv = nil, tconv = nil, remove_xtmean = false) ⇒ Object

Raises:

  • (ArgumentError)


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
# File 'lib/numru/gphys/gphys_fft.rb', line 628

def phase_velocity_filter(xdim, tdim, cmin=nil, cmax=nil, xconv=nil, tconv=nil, remove_xtmean=false)
  raise(ArgumentError,"need at least cmin or cmax") if !(cmin || cmax)


  xdim = dim_index(xdim) if xdim.is_a?(String)
  xdim += rank if xdim < 0
  tdim = dim_index(tdim) if tdim.is_a?(String)
  tdim += rank if tdim < 0
  fc = self.fft(nil,xdim,tdim)
  
  kdim = xdim
  fdim = tdim
  kconv = ( xconv ? 1.0/xconv : nil )
  fconv = ( tconv ? 1.0/tconv : nil )
  cp, = fc.phase_velocity(kdim,fdim,kconv,fconv,!remove_xtmean,true)

  fcv = fc.val
  nk = fc.shape[kdim]
  nf = fc.shape[fdim]
  sel = [true]*fc.rank
  for jf in 0...nf
    for jk in 0...nk
      c = cp[jk,jf]
      if ( cmin && c<cmin or cmax && c>cmax)
        sel[kdim]=jk
        sel[fdim]=jf
        fcv[*sel] = 0.0
      end
    end
  end
  fc.replace_val(fcv)
  gp = fc.fft(true,xdim,tdim)
  gp = gp.real if (self.typecode <= NArray::FLOAT)
  GPhys.new(self.grid_copy, gp.data)
            #^ use the original grid, since units may have changed
end

#rawspect2powerspect(*dims) ⇒ Object



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

def rawspect2powerspect(*dims)
  # developpers memo: Needs Units conversion.
  factor = nil
  dims.each{|dim|
	ax = self.coord(dim)
	dwn = UNumeric.new( ((ax[-1].val - ax[0].val)/(ax.length - 1)).abs,
   ax.units )
    if !factor
	  factor = dwn**(-1)
	else
	  factor = factor / dwn
	end
  }
  self * factor
end

#running_mean(dim, len_or_wgt = nil, bc = BC_SIMPLE, nminvalid = 1) ⇒ Object

Running mean along a dimension (with optional weight specification).

ARGUMENTS

  • dim (Integer or String) : the dimension

  • len_or_wgt : If Integer, specifies the length; if 1D NArray, specifies the weight (e.g., NArray[1.0, 2.0, 1.0] for the 1-2-1 smooting)

  • bc (Integer; optional) : Speficy one of the folloing:

    • GPhys::BC_SIMPLE (default) : Averaging is trucated at the boundaries (the number of grid points used is reduced near the boundaries). The shape of the object is conserved.

    • GPhys::BC_CYCLIC : Cyclic boundary condition. Shape conserved.

    • GPhys::BC_TRIM : Grids near the boundaries are trimmed to secure the number of grid points to average. Shape not conserved; length along the dim is reduced by (len-1).

  • nminvalid (Integer; optional; defualt=1): This parameter is used only when the data have missing. Minimum number of grid points needed for averaging. Must be from 1 to len.

RETURN VALUE

  • a GPhys

REMARK AND LIMITATION

  • If the length of the running mean is even number, fewer grid points are used from the “left” side; e.g., If len is 6, result is a mean over self..self.

  • Regardless the na_type of self, double is used for avaraging, so:

  • This method does not support complex numbers.



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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
# File 'lib/numru/gphys/gphys_dim_op.rb', line 46

def running_mean(dim, len_or_wgt=nil, bc=BC_SIMPLE, nminvalid=1)

  #< process arguments >

  dim = dim_index(dim)  # to handle String or negative specification

  case len_or_wgt
  when nil
    raise ArgumentError, "You need to specify the length (Integer) or the weight (1D NArray) as the 2nd argument"
  when Integer
    # len_or_wgt is a length
    len = len_or_wgt  
    wgt = NArray.float(len).fill!(1.0)
  else
    # len_or_wgt is a weight
    wgt = len_or_wgt
    if (!wgt.respond_to?(:rank) || wgt.rank != 1)
      raise ArgumentError, "wgt: expect a 1D NArray(-like obj)"
    end
    len = wgt.length
  end

  #< calc running mean >

  vi = self.val
  if (vi.typecode > NArray::DFLOAT)
    raise("This method supports only real or integer data")
  end 
  if vi.is_a?(NArrayMiss)
    vi, missval = nam2na_missval(vi)
    vo = c_running_mean(vi,dim,wgt,bc,missval,nminvalid)
    vo = NArrayMiss.to_nam(vo, vo.ne(missval) )
  else
    vo = c_running_mean(vi,dim,wgt,bc)
  end

  #< grid >

  if (bc ==  BC_TRIM)
    fst = (len-1)/2    # if odd len/2, if even len/2-1
    lst = -(len/2) - 1 
    grid = self.grid[ *([true]*dim + [fst..lst, false]) ]
  else
    grid = self.grid
  end

  #< result >
  vvo = VArray.new( vo, self.data, self.name )  # Inherit name & attrs
  GPhys.new( grid, vvo )

end

#spect_one_sided(dim) ⇒ Object



601
602
603
604
605
606
607
608
609
610
# File 'lib/numru/gphys/gphys_fft.rb', line 601

def spect_one_sided(dim)
  dim = dim + self.rank if dim<0
  len = self.shape[dim]
  b = self[ *([true]*dim + [0..len/2,false]) ] * 2
  b[*([true]*dim + [0,false])] = b[*([true]*dim + [0,false])] / 2
  if (self.shape[dim] % 2) == 0  # --> even number
    b[*([true]*dim + [-1,false])] = b[*([true]*dim + [-1,false])] / 2
  end
  b
end

#spect_zero_centering(dim) ⇒ Object



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

def spect_zero_centering(dim)
  dim = dim + self.rank if dim<0
  len = self.shape[dim]
  b = self[ *( [true]*dim + [[(len+1)/2..len-1,0..len/2],false] ) ].copy
  s1 = [true]*dim + [0, false]
  s2 = [true]*dim + [-1, false]
  if (len % 2) == 0   #--> even number
    b[*s1] = b[*s1]/2      # the ends are duplicated --> halved
    b[*s2] = b[*s1]
  end
  b.coord(dim)[0..len/2-1] = -b.coord(dim)[len/2+1..-1].val[-1..0]
  b
end