Class: NumRu::GPhys

Inherits:
Object
  • Object
show all
Includes:
Misc::MD_Iterators
Defined in:
lib/numru/ganalysis/fitting.rb,
lib/numru/gphys/grib.rb,
lib/numru/gphys/gphys.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/derivative.rb,
lib/numru/gphys/interpolate.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,
lib/numru/gphys/gphys_hdfeos5_io.rb,
ext/numru/gphys/dim_op.c,
ext/numru/gphys/interpo.c,
ext/numru/gphys/quad_mesh_sample.c

Overview

GPhys extension with GAnalysis::Fitting

Defined Under Namespace

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

Constant Summary collapse

VERSION =

Add subsubminor version while under development; remove it and advance version to release

"1.5.6"
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
@@interpo_previous_cutter =
nil
@@interpo_previous_modifier =
nil
@@interpo_missval =

NC_FILL_DOUBLE/FLOAT ~15*2^119

9.9692099683868690e+36
@@interpo_extrapolation =
false
@@default_missval =

NC_FILL_DOUBLE/FLOAT ~15*2^119

9.9692099683868690e+36

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(grid, data) ⇒ GPhys

Returns a new instance of GPhys.



584
585
586
587
588
589
590
591
592
593
# File 'lib/numru/gphys/gphys.rb', line 584

def initialize(grid, data)
	 #raise ArgumentError,"1st arg not a Grid" if ! grid.is_a?(Grid)
	 #raise ArgumentError,"2nd arg not a VArray" if ! data.is_a?(VArray)
	 if ( grid.shape_current != data.shape_current )
	    raise ArgumentError, "Shapes of grid and data do not agree. " +
  "#{grid.shape_current.inspect} vs #{data.shape_current.inspect}"
	 end
	 @grid = grid
	 @data = data
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



595
596
597
# File 'lib/numru/gphys/gphys.rb', line 595

def data
  @data
end

#gridObject (readonly)

Returns the value of attribute grid.



595
596
597
# File 'lib/numru/gphys/gphys.rb', line 595

def grid
  @grid
end

Class Method Details

.c_bin_mean(*args) ⇒ Object



853
854
855
856
857
# File 'ext/numru/gphys/dim_op.c', line 853

static VALUE
bin_mean(int argc, VALUE *argv, VALUE self)
{
    bin_mean_sum(argc, argv, self, 1);
}

.c_bin_sum(*args) ⇒ Object



859
860
861
862
863
# File 'ext/numru/gphys/dim_op.c', line 859

static VALUE
bin_sum(int argc, VALUE *argv, VALUE self)
{
    bin_mean_sum(argc, argv, self, 0);
}

.c_cap_by_boundaryObject

cap_by_boundary : Cap (insert) a NArray with boundary values

Restriction; data alignment is restricted so that the beginning of the out data is always valid (within the domain). To ensure it, it should be either zcrd is increasing and upper==true or zcrd is decreasing and upper==false.

RETURN VALUES

fe: f capped by the boundary values. The dimension zdim is

extended by 1; i.e., f[:,nz,:] --> fe[:,nz+1,:], where ":" respresent
arbitrary number of dimensions. The elements of fe are equal to
those of f where inside the domain (simple copies), and they are equal
to the elements of fs at the bondary (simple copies if fs is given;
if not, guessed by interpolation or naive extension).

ze: grid points of fe along zdim. It is a mixture of zcrd and zs;

it is zcrd inside the domain (where f is copied), and it is zs
at the boundary (where fs is copied).
Same shape as fe.

nze: The number of valid data along zdim of fe. Shaped as ze,

according to the notation above. For example, when fe is 4D and
zdim==2, fe[i,j,k,l] is valid for k = 0,1,...,nze[i,j,l]-1,
where the boundary is at nze[i,j,l]-1. Thus, nze is always
smaller than or equal to the length of zdim of fe (which is nz+1)


1235
1236
1237
# File 'ext/numru/gphys/dim_op.c', line 1235

static VALUE
cap_by_boundary(obj, f, zdim, zcrd, upper, zb, fb)
VALUE obj;

.c_cell_integ_irregObject

cell_integ_irreg: trapezoidal numerical integration over coordinate cells, supporting irregular grid

Description

Suppose a multi-dimensional NArray f, where colon represents any number of dimensions, and k is the “z” dimension along which integration is made. We write its real space representation as f(z; x), where x symbolically represents all of the independent variables other than z, and for simplicity, we further write it as f(z).

z is sampled at z_k, k=0,1,…,nzbound-1. This method allows z_k to be defined for each z column, so it requires a multi-D NArray argument z (having the same shape as f). Optionally, nzbound can also vary as nzbound. If, instead, nil is given to nzbound, the entire z grid is used; nzbound is set to f.shape(zdim).

We define the integration of f as

           {    \int_za^zb f(z) dz,  when za<=zb,
I(za,zb) = {
           {   -\int_za^zb f(z) dz,  otherwise.

In other words, our integration is always made from the smaller end to the greater end.

In the normal use case (when w is given nil), we define the cell integration as,

I(-\infty, zc_0), I(zc_0, zc_1), I(zc_1, zc_2),...,

The cell boundaries zc_m (m=0,1,..) are specified by the 1D NArray argument “ccell”; ccell must be aligned in the increasing order.

This method allows coordinate transformation by specifying another coordinate variable w (having the same shape as f). In this case, the ccell argument specifies a coordinate with respect to w: wc_m (m=0,1,…; wc_m must be in the increasing order). The integration is still taken with respect to z, so the cell integration is expressed as

I(-\infty, z(wc_0)), I(z(wc_0), z(wc_1)), I(z(wc_1), z(wc_2)),...,

The grid values z and w do not have to be monotonic; the numerical integration properly treats the contribution from multiple ranges along k. Mathematically, the coordinate-transferred integration over the w bin (-infty, wc] is expressed as

\int_-\infty^+\infty H(wc-w(z)) f(z) dz,

where H is the Heaviside function. The normal use case (without w) is simply when w is z itself, which is exploited in implementation.



1002
1003
1004
# File 'ext/numru/gphys/dim_op.c', line 1002

static VALUE
cell_integ_irreg(obj, f, z, zdim, nzbound, ccell, w)
VALUE obj;

.c_cum_integ_irregObject

cum_integ_irreg : similar to cell_integ_irreg but it sums up along the axis. – This method acutually uses cell_integ_irreg and make sumation.



1191
1192
1193
# File 'ext/numru/gphys/dim_op.c', line 1191

static VALUE
cum_integ_irreg(obj, f, z, zdim, nzbound, ccell, w)
VALUE obj;

.c_running_mean(*args) ⇒ Object



320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
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
414
# File 'ext/numru/gphys/dim_op.c', line 320

static VALUE
running_mean(int argc, VALUE *argv, VALUE self)
{
    VALUE vi;    // mandatory 1st arg; input NArray
    VALUE dim;   // mandatory 2nd arg; Integer 
    VALUE wgt;   // mandatory 3rd arg; weight 1D NArray
    VALUE bc;    // mandatory 4th arg; boundary condition (Integer class const)
    VALUE missv=Qnil; // optional 5th arg; if present(Float) vi may have missing
    int nminvalid=1;     // optional 6th arg; miminum count of non-missing vales
    int with_miss;
    struct NARRAY *na;
    na_shape_t *shi, wlen;
    na_shape_t n0, n1, n2;
    double *zi, *w, zmiss;
    int d, i, rank, ibc;
    VALUE vo;
    na_shape_t *sho, n1o;
    double *zo;

    // < process arguments >

    if ( argc<4 || argc>6 ) { rb_raise(rb_eArgError,"Need 4 to 6 arguments"); }
    vi  = argv[0];
    dim = argv[1];
    wgt = argv[2];
    bc  = argv[3];
    with_miss = (argc > 4) && (!NIL_P(argv[4]));
    if ( with_miss ) { missv = argv[4]; }
    if ( argc == 6) {
	nminvalid = NUM2INT( argv[5] );
    }

    //   1st arg
    if (!IsNArray(vi)) { rb_raise(rb_eArgError,"1st arg must be a NArray"); }
    vi = na_cast_object(vi, NA_DFLOAT);
    rank = NA_RANK(vi);
    zi = NA_PTR_TYPE(vi, double *);
    GetNArray(vi, na);
    shi = na->shape;

    //   2nd arg
    d = NUM2INT( dim );

    //   3rd arg
    if (!IsNArray(wgt)) {rb_raise(rb_eArgError,"3rd arg must be a 1D NArray");}
    if (NA_RANK(wgt)!=1) {rb_raise(rb_eArgError,"3rd arg must be a 1D NArray");}
    wgt = na_cast_object(wgt, NA_DFLOAT);
    wlen = NA_TOTAL(wgt);
    w = NA_PTR_TYPE(wgt, double *);

    //   4th arg
    ibc = NUM2INT( bc );

    //   5th arg
    if ( with_miss ) { zmiss = NUM2DBL(missv); }

    //   6th arg
    if (nminvalid > wlen) {rb_raise(rb_eArgError,"nminvalid > filtering length");}

    // < shape as 3D >

    n1 = shi[d];   // length of the dim to filter
    if (wlen >= n1) {rb_raise(rb_eArgError,"filter len >= len of the dim");}

    n0 = n2 = 1;
    for (i=0; i<d; i++) {
	n0 *= shi[i];   // total lengths of dims before d
    }
    for (i=d+1; i<rank; i++) {
	n2 *= shi[i];   // total lengths of dims after d
    }

    // < initialize the NArray to ruturn >

    n1o = convol_result_length(n1, wlen, ibc);

    sho = ALLOCA_N(int, rank);
    for(i=0; i<rank; i++){
	sho[i] = ( i!=d ? shi[i] : n1o );
    }

    vo = na_make_object(NA_DFLOAT, rank, sho, cNArray);
    GetNArray(vo, na);
    na_clear_data(na);
    zo = NA_PTR_TYPE(vo, double *);

    // < do the job >
    if ( with_miss ) {
	running_mean_miss(zi,n0,n1,n2, w,wlen, ibc, zmiss, nminvalid, zo);
    } else {
	running_mean_nomiss(zi,n0,n1,n2, w,wlen, ibc, zo);
    }

    return vo;
}

.c_running_mean_2DObject



518
519
520
521
# File 'ext/numru/gphys/dim_op.c', line 518

static VALUE
running_mean_2D(obj, vi, dim1, len_or_wgt1, bc1, dim2, len_or_wgt2, bc2,
            missv, nminvalid)
VALUE obj;

.concat(gpary, axis_or_ary, name = nil, attr = nil) ⇒ Object



1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
# File 'lib/numru/gphys/gphys.rb', line 1342

def GPhys.concat(gpary, axis_or_ary, name=nil, attr=nil)
  #< interpret gpary (1st arg) >
  gpary = NArray.to_na(gpary) if gpary.is_a?(Array)
  if !gpary.is_a?(NArray) || gpary.rank != 1
    raise(ArgumentError,"1st arg must be a 1D NArray or Array of GPhys")
  end
  len = gpary.length

  #< interpret axis_or_ary (2nd arg) and make an Axis if not >
  case axis_or_ary
  when Axis
    ax = axis_or_ary
    if ax.length != len
      raise(ArgumentError,"length mismatch #{len} vs #{ax.length}")
    end
  else
    ary = axis_or_ary   # must be an NArray or Array
    ary = NArray.to_na(ary).to_f if ary.is_a?(Array)
    if !ary.is_a?(NArray) || ary.rank != 1
      raise(ArgumentError,
        "If not an Axis, 2nd arg must be 1D NArray or Array of float")
    end
    if ary.length != len
      raise(ArgumentError,"length mismatch #{len} vs #{ary.length}")
    end
    if name.nil?
      raise(ArgumentError,
         "3rd arg (name) is needed if the 2nd arg is not an Axis") 
    end
    va = VArray.new(ary, attr, name)
    ax = Axis.new().set_pos(va)
  end

  #< new grid >
  grid = gpary[0].grid.insert_axis(-1,ax)  # insert_axis: non-destructive

  #< join VArrays >
  ds = gpary.collect{|gp| gp.data}
  gpary[0].rank.times{ds.newdim!(0)}   # for VArrayComposite.new
  data = VArrayComposite.new(ds)

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

.each_along_dims(gphyses, loopdims) ⇒ Object



1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
# File 'lib/numru/gphys/gphys.rb', line 1045

def self.each_along_dims(gphyses, loopdims)
	if !gphyses.is_a?(Array)
	  gphyses = [gphyses]     # put in an Array (if a single GPhys)
	end
	gp = gphyses[0]

	if !loopdims.is_a?(Array)
	  loopdims = [loopdims]  # put in an Array (if a single Integer/String)
	end
	if loopdims.length == 0
	  #raise ArgumentError, "No loop dimension is specified "+
	  #  " -- In that case, you don't need this iterator."

	  return yield(*gphyses)  # trivial case supported just for generality
	end

	#if loopdims.min<0 || loopdims.max>=gp.rank
	#  raise ArguemntError,"Invalid dims #{loopdims.inspect} for #{gp.rank}D array"
	#end

	loopdimids = Array.new
	loopdimnames = Array.new
	loopdims.each{|d|
	  case d
	  when Integer
	    if d < 0
 d += gp.rank
	    end
	    loopdimids.push( d )
	    loopdimnames.push( gp.axis(d).name )
	  when String
	    loopdimids.push( gp.dim_index(d) )
	    loopdimnames.push( d )
	  else
	    raise ArgumentError,"loopdims must consist of Integer and/or String"
	  end
	}

	sh = Array.new
	len = 1
	loopdimids.each{|i|
	  sh.push(gp.shape[i])
	  len *= gp.shape[i]
	}

	gphyses.each do |g|
	  for i in 1...gphyses.length
	    loopdimnames.each_with_index do |nm,i|
 if !g.axnames.include?( nm )
		raise ArgumentError,"#{i+1}-th GPhys do not have dim '#{nm}'"
 end
 if g.coord(nm).length != sh[i]
		raise ArgumentError,"loop dimensions must have the same lengths(#{nm}; #{sh[i]} vs #{g.coord(nm).length})"
 end
	    end
	  end
	end

	to_return = nil

	cs = [1]
	(1...sh.length).each{|i| cs[i] = sh[i-1]*cs[i-1]}
	idx_hash = Hash.new
	for i in 0...len do
	  loopdimnames.each_with_index{|d,j| 
	    idx_hash[d] = ((i/cs[j])%sh[j])..((i/cs[j])%sh[j]) # rank preserved
	  }
	  subs = gphyses.collect{|g| g[idx_hash] }
	  results = yield(*subs)
	  if results.is_a?(Array)  # then it must consist of GPhys objects
	    if i == 0
 to_return = results_whole = Array.new
 for j in 0...results.length
		rs = results[j]
		grid = rs.grid_copy
		loopdimnames.each{|nm|
		  # replaces with original axes (full length)
		  if !grid.axnames.include?( nm )
raise "Dimension '#{nm}' has been eliminated. "+
                    "You must keep all loop dimensions." 
		  end
		  grid.set_axis(nm,gphyses[0].axis(nm))
		}
		if ( (vtst=rs.data[0..0,false].val).respond_to?(:set_mask) )
             # DEVELOPPER'S NOTE (2006/08/15 horinout). 
             # Here, [0..0,false] is to take the minimum subset,
             # and respond_to?(:set_mask) is used to check whether
             # the data array is compatible to NArrayMiss
		  vary = VArray.new(NArrayMiss.new(vtst.typecode, *grid.shape), 
  rs.data)
		else
		  vary = VArray.new(NArray.new(vtst.typecode, *grid.shape), rs.data)
		end
		results_whole.push( self.new( grid, vary ) )
 end
	    end
	    for j in 0...results.length
 rs = results[j]
 results_whole[j][idx_hash] = rs.data
	    end
	  else
	    to_return = nil
	  end
	end
	return to_return

end

.extrapolation=(extrapo) ⇒ Object

Change the behavior of the interpolation methods to extrapolate outside the grid coverage.

ARGUMENTS

  • extrapo : true or false — the default behaviour is false (not to extrapolate), so use this method if you want to set it to true.



28
29
30
# File 'lib/numru/gphys/interpolate.rb', line 28

def self.extrapolation=(extrapo)
  @@interpo_extrapolation = extrapo
end

.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

.interpo_find_loc_1DObject

to make “find loc” methods available outside GPhys as class methods



311
312
313
# File 'ext/numru/gphys/interpo.c', line 311

static VALUE
interpo_find_loc_1D(obj, X, x, missval, extrapo)
VALUE obj;

.interpo_find_loc_1D_MDObject

To apply interpo_find_loc_1D multi-dimensionally



372
373
374
# File 'ext/numru/gphys/interpo.c', line 372

static VALUE
interpo_find_loc_1D_MD(obj, X, x, dimc, missval, extrapo)
VALUE obj;

.join(gpary, ignore_overlap = false, no_sort = false) ⇒ Object

Join multiple GPhys objects (not need for any pre-ordering).

ARGUMENT

  • gpnarray [Array (or 1D NArray) of GPhys]



1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
# File 'lib/numru/gphys/gphys.rb', line 1298

def GPhys.join(gpary, ignore_overlap=false, no_sort=false)

  #< initialization with the first GPhys object >

  gp = gpary[0]
  rank = gp.rank
  gpstore = MDStorage.new(rank)
  gpstore[ *Array.new(rank, 0) ] = gp     # first element
  x0s = (0...rank).collect{|d| 
    pos = gp.axis(d).pos
    x0 = UNumeric[ pos.val[0], pos.units ]
    [ x0 ]   # first values of each coordinate
  }

  #< scan the coordiantes of the remaining GPhys objects >
  for k in 1...gpary.length
    gp = gpary[k]
    idx = Array.new
    for d in 0...rank
      pos = gp.axis(d).pos
      x0 = UNumeric[ pos.val[0], pos.units ]
      i = x0s[d].index(x0)  
      if i.nil?
        x0s[d].push(x0)
        i = x0s[d].length-1
      end
      idx.push(i)
    end
    gpstore[*idx] = gp
  end

  if !ignore_overlap && gpstore.count_non_nil != gpary.length
    raise(ArgumentError,"Cannot uniquely locate one or more objects; some overlap in the grids?")
  end

  gpnary = gpstore.to_na

  #< Sort along dimensions to join >
  gpnary = __sort_gpnary(gpnary) unless no_sort

  #< Join! >
  self.join_md_nocheck(gpnary)
end

.join_md(gpnary, no_sort = false) ⇒ Object



1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
# File 'lib/numru/gphys/gphys.rb', line 1226

def GPhys.join_md(gpnary, no_sort=false)
  #< Check >

  if !gpnary.is_a?(NArray)
    raise(ArgumentError,"Input must be an NArray of GPhys") 
  end
  arank = gpnary.rank      # rank of the input NArray
  ashape = gpnary.shape
  rank = gpnary[0].rank    

  #< Reshape and transpose gpnary if needed >

  #  / find dimmensions to join /
  dimmap = Array.new
  for i in 0...arank
    if ashape[i] > 1   # join needed
      sel = Array.new(arank, 0)   # [0,0,...,0]
      gp0 = gpnary[ *sel ]
      sel[i] = 1
      gp1 = gpnary[ *sel ]   # [0,..,0,1,0,...,0]
      for d in 0...rank
        c0 = gp0.coord(d)[0]
        c1 = gp1.coord(d)[0]
        if c0.val != c1.convert_units(c0.units).val
          dimmap[i] = d   # dimension to join (found)
          break
        end
        raise("Corresponding dim is not found for #{i}") if d==rank-1
      end
    else
      dimmap[i] = nil   # no need to join this dimension
    end
  end
  if (x=dimmap-[nil]).length != x.uniq.length
    raise "Dimensions to join cannot be determined uniquely"
  end

  #  / "solo" dimensions (dimensions no need to join) /
  sdims = (0...rank).collect{|d| d} - dimmap
  for i in 0...arank
    if dimmap[i].nil?
      dimmap[i] = sdims.shift    # assign dimensions orderly to 
                                 # minimize the need to transpose
    end
  end
  sdims.each do |d|
    dimmap.insert(d,d)           # assign dimensions orderly to 
    gpnary = gpnary.newdim(d)    # minimize the need to transpose
  end
  #   now, gpnary.rank == rank

  #  / transpose gpnary if needed /
  if dimmap != (0...rank).collect{|d| d}
    imap = Array.new
    dimmap.each_with_index do |d,j|
      imap[j] = d
    end
    gpnary = gpnary.transpose(*imap)
  end

  #< Sort along dimensions to join >
  gpnary = __sort_gpnary(gpnary) unless no_sort

  #< Join! >
  self.join_md_nocheck(gpnary)
end

.join_md_nocheck(gpnary) ⇒ Object

join multiple GPhys objects #######



1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
# File 'lib/numru/gphys/gphys.rb', line 1187

def GPhys.join_md_nocheck(gpnary)
  #< check >
  if !gpnary.is_a?(NArray)
    raise(ArgumentError,"Input must be an NArray of GPhys") 
  end
  rank = gpnary.rank

  #< axes >
  gp0 = gpnary[0]

  axes = Array.new
  for d in 0...rank
    if gpnary.shape[d] > 1  # --> join axes
      sel = [0]*d + [true] + [0]*(rank-d-1)   # [0,..0,true,0,...0]
      axs = gpnary[*sel].collect{|gp| gp.axis(d)}   # axes along d-th dim
      ax = Axis.join(axs)
    else
      ax = gp0.axis(d)
    end
    axes.push(ax)
  end

  #< grid >
  grid = Grid.new(*axes)
  if gp0.assoc_coords
    assoc_coords = gp0.assoccoordnames.collect do |aname|
      GPhys.join( gpnary.collect{|gp| gp.assoc_coord_gphys(aname)}, true,
                  true )
    end
    grid.set_assoc_coords(assoc_coords)
  end

  #< data >
  data = VArrayComposite.new( gpnary.collect{|gp| gp.data} )

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

.quad_mesh_sample(z_na, si_na, ri_na, p_na, q_na, misval_f) ⇒ Object



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
# File 'ext/numru/gphys/quad_mesh_sample.c', line 357

VALUE rb_quad_mesh_sample(VALUE obj, VALUE z_na, VALUE si_na, VALUE ri_na,
                       VALUE p_na, VALUE q_na, VALUE misval_f)
{
  VALUE zg_na;
  int ns, nr, nx, ny;
  int *si, *ri; 
  double *p, *q, misval, *z, *zg;
  struct NARRAY *na;
  na_shape_t sh[2];

  GetNArray( na_cast_object(z_na, NA_DFLOAT), na);
  ns = na->shape[0];  
  nr = na->shape[1];  
  z = (double *) NA_PTR(na, 0);

  GetNArray( na_cast_object(si_na, NA_DFLOAT), na);
  nx = na->shape[0];
  ny = na->shape[1];
  si = NA_PTR_TYPE(si_na, int *);
  ri = NA_PTR_TYPE(ri_na, int *);
  p = NA_PTR_TYPE(p_na, double *);
  q = NA_PTR_TYPE(q_na, double *);
  misval = NUM2DBL( misval_f ); 

  sh[0] = (na_shape_t) nx;
  sh[1] = (na_shape_t) ny;
  zg_na = na_make_object(NA_DFLOAT, 2, sh, cNArray);
  zg = NA_PTR_TYPE(zg_na, double *);

  quad_mesh_sample(ns, nr, z, nx, ny, si, ri, p, q, misval, zg);

  return zg_na;
}

.quad_mesh_sample_initObject

(in)



292
293
294
295
296
297
298
299
300
301
302
303
304
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'ext/numru/gphys/quad_mesh_sample.c', line 292

VALUE rb_quad_mesh_sample_init(VALUE obj, VALUE x_na, VALUE y_na, // (in)
                        VALUE nx_i, VALUE x0_f, VALUE dx_f,     // (in)
                        VALUE ny_i, VALUE y0_f, VALUE dy_f,     // (in)
                        VALUE misval_f )     // (in)
{
  VALUE si_na, ri_na, p_na, q_na;  // (out)
  int ns, nr, nx, ny, rank;
  double *x, *y;
  double x0, dx, y0, dy, misval;
  int handle_miss;
  int *si, *ri;
  double *p, *q;
  struct NARRAY *na;
  na_shape_t sh[2];

  if (!IsNArray(x_na)) rb_raise(rb_eTypeError, "1st arg (x) must be an NArray");
  if (!IsNArray(y_na)) rb_raise(rb_eTypeError, "2nd arg (y) must be an NArray");

  rank = NA_RANK(x_na);
  if (rank != 2) rb_raise(rb_eArgError, "rank of x is not 2");
  rank = NA_RANK(y_na);
  if (rank != 2) rb_raise(rb_eArgError, "rank of x is not 2");

  GetNArray( na_cast_object(x_na, NA_DFLOAT), na);
  ns = na->shape[0];  
  nr = na->shape[1];  
  x = (double *) NA_PTR(na, 0);

  GetNArray( na_cast_object(y_na, NA_DFLOAT), na);
  if ( ns != na->shape[0] || nr != na->shape[1])
    rb_raise(rb_eArgError, "shapes of x and y do not agree");
  y = (double *) NA_PTR(na, 0);

  nx = NUM2INT( nx_i ); 
  ny = NUM2INT( ny_i ); 
  x0 = NUM2DBL( x0_f ); 
  dx = NUM2DBL( dx_f ); 
  y0 = NUM2DBL( y0_f ); 
  dy = NUM2DBL( dy_f ); 

  handle_miss = misval_f != Qnil;
  if (handle_miss) {
    misval = NUM2DBL( misval_f ); 
  } else {
    misval_f = 0.0; // just to avoid non-nitialization
  } 

  sh[0] = (na_shape_t) nx;
  sh[1] = (na_shape_t) ny;
  si_na = na_make_object(NA_LINT, 2, sh, cNArray);
  si = NA_PTR_TYPE(si_na, int *);
  ri_na = na_make_object(NA_LINT, 2, sh, cNArray);
  ri = NA_PTR_TYPE(ri_na, int *);
  p_na = na_make_object(NA_DFLOAT, 2, sh, cNArray);
  p = NA_PTR_TYPE(p_na, double *);
  q_na = na_make_object(NA_DFLOAT, 2, sh, cNArray);
  q = NA_PTR_TYPE(q_na, double *);

  quad_mesh_sample_init(ns, nr, x, y, nx, x0, dx, ny, y0, dy, // (in)
                     handle_miss, misval, // (in)
                     si, ri, p, q);

  return rb_ary_new3(4, si_na, ri_na, p_na, q_na);
}

Instance Method Details

#[](*slicer) ⇒ Object



678
679
680
681
682
683
684
685
686
# File 'lib/numru/gphys/gphys.rb', line 678

def [](*slicer)
	 if slicer.length==1 && slicer[0].is_a?(Hash) && 
	    slicer[0].keys[0].is_a?(String)
	   slicer = __process_hash_slicer(slicer[0])
	 else
	   slicer = __rubber_expansion( slicer )
	 end
	 self.class.new( @grid[*slicer], @data[*slicer] )
end

#[]=(*args) ⇒ Object



688
689
690
691
692
693
694
695
696
697
698
699
# File 'lib/numru/gphys/gphys.rb', line 688

def []=(*args)
	 val = args.pop
	 slicer = args
	 if slicer.length==1 && slicer[0].is_a?(Hash) && 
	    slicer[0].keys[0].is_a?(String)
	   slicer = __process_hash_slicer(slicer[0])
	 else
	   slicer = __rubber_expansion( slicer )
	 end
	 val = val.data if val.respond_to?(:grid) #.is_a?(GPhys)
	 @data[*slicer] = val
end

#add_lost_axes(lost) ⇒ Object



770
771
772
773
# File 'lib/numru/gphys/gphys.rb', line 770

def add_lost_axes( lost )
  @grid.add_lost_axes( lost )
  self
end

#assoc_coord_gphys(name) ⇒ Object



759
760
761
# File 'lib/numru/gphys/gphys.rb', line 759

def assoc_coord_gphys(name)
	@grid.assoc_coord_gphys(name)
end

#assoc_coordsObject



798
799
800
# File 'lib/numru/gphys/gphys.rb', line 798

def assoc_coords
  @grid.assoc_coords
end

#assoc_coords=(assoc_coords) ⇒ Object



795
796
797
# File 'lib/numru/gphys/gphys.rb', line 795

def assoc_coords=(assoc_coords)
  @grid.assoc_coords=assoc_coords
end

#assoccoordnamesObject



789
790
791
# File 'lib/numru/gphys/gphys.rb', line 789

def assoccoordnames
  @grid.assoccoordnames
end

#att_namesObject



635
636
637
# File 'lib/numru/gphys/gphys.rb', line 635

def att_names
	@data.att_names
end

#axis(i) ⇒ Object



753
754
755
# File 'lib/numru/gphys/gphys.rb', line 753

def axis(i)
	@grid.axis(i)
end

#axnamesObject



744
745
746
# File 'lib/numru/gphys/gphys.rb', line 744

def axnames
	 @grid.axnames
end

#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



194
195
196
197
# File 'lib/numru/gphys/gphys_dim_op.rb', line 194

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



212
213
214
215
# File 'lib/numru/gphys/gphys_dim_op.rb', line 212

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

#cderiv(*args) ⇒ Object



91
92
93
# File 'lib/numru/gphys/derivative.rb', line 91

def cderiv(*args)
  Derivative::cderiv(self,*args)
end

#coerce(other) ⇒ Object

<– For graphics



848
849
850
851
852
853
854
855
856
# File 'lib/numru/gphys/gphys.rb', line 848

def coerce(other)
	case other
  when Numeric, Array, NArrayMiss
    c_other = UNumeric::Num2Coerce.new( other )
  else
    raise "Cannot coerse #{other.class}"
  end
	[c_other, self]
end

#convert_units(to) ⇒ Object



662
663
664
665
666
667
668
669
# File 'lib/numru/gphys/gphys.rb', line 662

def convert_units(to)
	# ==NOTE: 
	#    * VArray#convert_units does not copy data if to == @data.units
	#    * @grid is shared with self (no duplication)
  #    Thus, use GPhys#copy to separate all sub-objects (deep clone).
	data = @data.convert_units(to)  
	self.class.new(@grid, data)
end

#coord(i) ⇒ Object Also known as: coordinate



756
757
758
# File 'lib/numru/gphys/gphys.rb', line 756

def coord(i)
	@grid.coord(i)
end

#coord_data_reverse(axname, pos) ⇒ Object

Reverse the main data (i.e., the dependent variable) and one of the coordinates (an independent variable) through interpolation.

Returns a GPhys in which the main data is the specfied coordinate (argument: axname) sampled at specified locations (argument: pos) in terms of the main data of self. The main data of self is expected to be quai-monotonic with respect to the specfied coordinate.

ARGUMENTS

  • axname [String] : one of the names of the axes (i.e. main coordinates. Auxiliary coordinates are not supported as the target.)

  • pos [NArray] : grid locations. For example, if the current data is potential temperature theta, pos consists of the theta levels to make sampling.

RETURN VALUE

  • a GPhys



231
232
233
234
235
236
237
238
239
240
# File 'lib/numru/gphys/interpolate.rb', line 231

def coord_data_reverse(axname,pos)
  gp = self.axis(axname).to_gphys
  gp = self.shape_coerce_full(gp)[0]   # conform the shape to that of self
  gp = GPhys.new( gp.grid.copy, gp.data )  # copy grid to avoid side effect
                                           # on the grid of self
  gp.set_assoc_coords([self])
  pos = NArray[*pos].to_type(NArray::FLOAT) if pos.is_a?(Array)
  newcrd = VArray.new(pos,self.data,self.name)  # succeeds the attributes
  gp.interpolate(axname=>newcrd)
end

#coordnamesObject



777
778
779
# File 'lib/numru/gphys/gphys.rb', line 777

def coordnames
  @grid.coordnames
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

#copyObject



603
604
605
606
# File 'lib/numru/gphys/gphys.rb', line 603

def copy
	 # deep clone onto memory
	 self.class.new( @grid.copy, @data.copy )
end

#correlation(other, *dims) ⇒ Object



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

def correlation(other, *dims)
  GAnalysis.correlation(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

#cut(*args) ⇒ Object



712
713
714
715
716
717
718
719
720
721
722
723
724
# File 'lib/numru/gphys/gphys.rb', line 712

def cut( *args )
  if has_assoccoord? && args.length==1 && ((spec=args[0]).is_a?(Hash)) &&
      ( acnms = (spec.keys & assoccoordnames ) ).length > 0
    acspec = Hash.new
    acnms.each{|nm| acspec[nm] = spec.delete(nm)}
    grid, sl = @grid.cut_assoccoord(acspec)
    gphys = self.class.new( grid, self.data[*sl] )
  else
    gphys = self
  end
	newgrid, slicer = gphys.grid.cut( *args )
	self.class.new( newgrid, gphys.data[ *slicer ] )
end

#cut_rank_conserving(*args) ⇒ Object



726
727
728
729
# File 'lib/numru/gphys/gphys.rb', line 726

def cut_rank_conserving( *args )
	newgrid, slicer = @grid.cut_rank_conserving( *args )
	self.class.new( newgrid, @data[ *slicer ] )
end

#cyclic_ext(dim_or_dimname) ⇒ Object



1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
# File 'lib/numru/gphys/gphys.rb', line 1024

def cyclic_ext(dim_or_dimname)
  # Cyclic extention to push the first element after the last element
  # if appropriate. (by using the cut method)

  ax = axis(dim_or_dimname)
  if ax.cyclic_extendible? 
    modulo = ax.modulo
    v = ax.pos.val
    v0 = v[0]
    eps = 1e-2/ax.length
    if v0 < v[-1]  # increasing
      v1 = v0 + modulo*(1+eps)
    else
      v1 = v0 - modulo*(1+eps)
    end
    return self.cut(ax.name=>v0..v1)
  else
    return self 
  end
end

#cyclic_ext_with_modulo(dim_or_dimname, modulo) ⇒ Object

Old version of cyclic_ext



998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
# File 'lib/numru/gphys/gphys.rb', line 998

def cyclic_ext_with_modulo(dim_or_dimname, modulo)
	# Cyclic extention to push the first element after the last element
  # if appropriate.

	vx = coord(dim_or_dimname)
	return self if vx.length <= 1

	vvx = vx.val
	width = (vvx[-1] - vvx[0]).abs
	dx = width / (vx.length-1)
	eps = 1e-4
	modulo = modulo.abs
	extendible = ( ((width+dx) - modulo).abs < eps*modulo )

	if extendible
	  dim = @grid.dim_index(dim_or_dimname)
	  newgp = self.copy[false, [0...vx.length, 0], *([true]*(rank-1-dim))]
	  vx = newgp.coord(dim).copy
	  vx[-1] = vx[-1].val + modulo
	  newgp.axis(dim).set_pos(vx)
	  return newgp
	else
	  return self
	end
end

#dcl_fig_cut(dimx, dimy, ux, uy) ⇒ Object

Interpolation on the DCL window (automatic iso-interval interpolation along a poly line that can be drawn in the current viewport of the DCL window). Used in mouse_cut.

ARGUMENTS

  • dimx [Integer or String] : specifies the dimension corresponding to the UX coordinate. (Here, the UX coordinate is the X coordinate of the DCL’s USER coordinate. For exapmle, longitude if map projection.)

  • dimy [Integer or String] : specifies the dimension corresponding to the UY coordinate. (Here, the UY coordinate is the Y coordinate of the DCL’s USER coordinate. For exapmle, latitude if map projection.)

  • ux [Array] : x values in terms of the UX coordinate

  • uy [Array] : y values in terms of the UY coordinate Lengths of ux and uy must be the same and greter or equal to 2.



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
162
163
164
165
166
# File 'lib/numru/gphys/interpolate.rb', line 89

def dcl_fig_cut(dimx,dimy,ux,uy)
  len = ux.length
  raise("ux and uy must be arrays with the (same) length >= 2") if len<=1
  raise("ux's len (#{len}) != uy's len (#{uy.length})") if uy.length != len
  vx=Array.new; vy=Array.new
  for i in 0...len
    vx[i],vy[i] = NumRu::DCL.stftrf(ux[i],uy[i]) 
  end
  kx = Array.new
  ky = Array.new
  cut = [true]*rank
  for i in 0...len
    cut[dimx] = ux[i]
    cut[dimy] = uy[i]
    dummy, sl = grid.cut(*cut)
    kx[i] = sl[dimx]
    ky[i] = sl[dimy]
  end
  ndiv = Array.new
  ndsum = [0]
  for i in 0...len-1
    ndiv[i] = Math.sqrt( (kx[i+1]-kx[i])**2 + (ky[i+1]-ky[i])**2).to_i
    ndiv[i] += 1 if i==len-2
    ndsum.push ndsum[-1] + ndiv[i]   # 0, ndiv[0], ndiv[0]+ndiv[1], ...
  end
  ndtot = ndsum[-1]
  vxdiv = NArray.float(ndtot)
  vydiv = NArray.float(ndtot)
  for i in 0...len-1
    if i!=len-2
      a = NArray.float(ndiv[i]).indgen / ndiv[i]
    else
      a = NArray.float(ndiv[i]).indgen / (ndiv[i]-1)
    end
    vxdiv[ndsum[i]...ndsum[i+1]] = (1.0-a)*vx[i] + a*vx[i+1]
    vydiv[ndsum[i]...ndsum[i+1]] = (1.0-a)*vy[i] + a*vy[i+1]
  end
  uxdiv = NArray.float(ndtot)
  uydiv = NArray.float(ndtot)
  for i in 0...ndtot
    uxdiv[i], uydiv[i] = DCL.stitrf(vxdiv[i], vydiv[i])
  end
  cx = coord(dimx)
  xcrd = VArray.new(uxdiv, cx, cx.name)
  cy = coord(dimy)
  ycrd = VArray.new(uydiv, cy, cy.name)
  if (vxdiv[-1]-vxdiv[0]).abs > (vydiv[-1]-vydiv[0]).abs
    cutter = [xcrd,ycrd]  # x will be the main coord var if not map proj
    crd = xcrd
  else
    cutter = [ycrd,xcrd]  # x will be the main coord var if not map proj
    crd = ycrd
  end
  axnm = crd.name
  itr = DCL.sgqtrn
  if itr>=10 and itr<=40
    newcrd = __sp_dist(xcrd,ycrd)
    modifier = Proc.new{|gp|
      newax = Axis.new.set_pos(newcrd)
      gp.grid.set_axis(axnm,newax)
      g = Grid.new( newax )
      gxcrd = GPhys.new(g,xcrd)
      gycrd = GPhys.new(g,ycrd)
      gp.set_assoc_coords([gxcrd, gycrd])
      gp
    }
  else
    modifier = nil
  end
  @@interpo_previous_cutter = cutter
  @@interpo_previous_modifier = modifier

  # < do the job >

  gpnew = interpolate(cutter)
  gpnew = modifier[gpnew] if modifier
  gpnew
end

#del_att(name) ⇒ Object



645
646
647
648
# File 'lib/numru/gphys/gphys.rb', line 645

def del_att(name)
	@data.del_att(name)
	self
end

#deriv2nd(*args) ⇒ Object



97
98
99
# File 'lib/numru/gphys/derivative.rb', line 97

def deriv2nd(*args)
  Derivative::deriv2nd(self,*args)
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

#dim_index(dimname) ⇒ Object



774
775
776
# File 'lib/numru/gphys/gphys.rb', line 774

def dim_index( dimname )
	 @grid.dim_index( dimname )
end

#eddy(*dim) ⇒ Object

Basic numerical operations that are not defined on the VArray level



804
805
806
# File 'lib/numru/gphys/gphys.rb', line 804

def eddy(*dim)
  self - self.mean(*dim)
end

#eof(*args) ⇒ Object



235
236
237
# File 'lib/numru/ganalysis/eof.rb', line 235

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.to_f   # 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!.to_f
	  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

#first1DObject



817
818
819
820
# File 'lib/numru/gphys/gphys.rb', line 817

def first1D
	raise "rank less than 1" if rank < 1
	self[true,*([0]*(rank-1))]
end

#first1DreallyObject



843
844
845
# File 'lib/numru/gphys/gphys.rb', line 843

def first1Dreally
  firstNDreally(1)
end

#first2DObject



813
814
815
816
# File 'lib/numru/gphys/gphys.rb', line 813

def first2D
	raise "rank less than 2" if rank < 2
	self[true,true,*([0]*(rank-2))]
end

#first2DreallyObject



840
841
842
# File 'lib/numru/gphys/gphys.rb', line 840

def first2Dreally
  firstNDreally(2)
end

#first3DObject

For graphics –>



809
810
811
812
# File 'lib/numru/gphys/gphys.rb', line 809

def first3D
	raise "rank less than 3" if rank < 3
	self[true,true,true,*([0]*(rank-3))]
end

#first3DreallyObject



837
838
839
# File 'lib/numru/gphys/gphys.rb', line 837

def first3Dreally
  firstNDreally(3)
end

#firstNDreally(nd) ⇒ Object



821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
# File 'lib/numru/gphys/gphys.rb', line 821

def firstNDreally(nd)
  sh = shape_current
  n = 0
  sel = sh.map do |len|
    if len > 1 && n < nd
      n += 1
      true
    else
      0
    end
  end
  if n<nd
    raise "Invalid shape #{sh} (not really #{nd}D or greater): # of dims with len>1 is fewer than #{nd}"
  end
  self[*sel]
end

#get_att(name) ⇒ Object



638
639
640
# File 'lib/numru/gphys/gphys.rb', line 638

def get_att(name)
	@data.get_att(name)
end

#grid_copyObject

protected :grid # protection is lifted



598
599
600
601
# File 'lib/numru/gphys/gphys.rb', line 598

def grid_copy
	# deep clone of the grid
	@grid.copy
end

#has_assoccoord?(*arg) ⇒ Boolean

Returns:

  • (Boolean)


783
784
785
# File 'lib/numru/gphys/gphys.rb', line 783

def has_assoccoord?(*arg)
  @grid.has_assoccoord?(*arg)
end

#has_axis?(name) ⇒ Boolean

Returns:

  • (Boolean)


780
781
782
# File 'lib/numru/gphys/gphys.rb', line 780

def has_axis?(name)
  @grid.has_axis?(name)
end

#has_coord?(name) ⇒ Boolean

Returns:

  • (Boolean)


786
787
788
# File 'lib/numru/gphys/gphys.rb', line 786

def has_coord?(name)
  @grid.has_coord?(name)
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

#inspectObject



608
609
610
# File 'lib/numru/gphys/gphys.rb', line 608

def inspect
  "<#{self.class} grid=#{@grid.inspect}\n   data=#{@data.inspect}>"
end

#interpolate(*coords) ⇒ Object

Wide-purpose multi-dimensional linear interpolation

This method supports interpolation regarding combinations of 1D and 2D coordinate variables. For instance, suppose self is 4D with coordinates named [“x”, “y”, “z”, “t”] and associated coordinates “sigma” (“sigma” is 1D and its axis is “z”), “p”, “q” (“p” and “q” are 2D having the coordinates “x” and “y”). You can make interpolation by specifying 1D VArrays whose names are among “x”, “y”, “z”, “t”, “sigma”, “p”, “q”. You can also use a Hash like => 1.0 to specify a single point along the “x” coordinate.

If the units of the target coordinate and the current coordinate are different, a converstion was made so that slicing is made correctly, as long as the two units are comvertible; if the units are not convertible, it is just warned.

If you specify only “x”, “y”, and “t” coordinates for interpolation, the remaining coordinates “z” is simply retained. So the result will be 4 dimensional with coordinates named [“x”, “y”, “z”, “t”], but the lengths of “x”, “y”, and “t” dimensions are changed according to the specification. Note that the result could be 3-or-smaller dimensional – see below.

Suppose you have two 1D VArrays, xnew and ynew, having names “x” and “y”, respectively, and the lengths of xnew and the ynew are the same. Then, you can give an array of the two, [xnew, ynew], for coord0 as

gp_int = gp_org.interpolate( [xnew, ynew] )

(Here, gp_org represents a GPhys object, and the return value pointed by gp_int is also a GPhys.) In this case, the 1st dimension of the result (gp_int) will be sampled at the points [xnew,ynew], [xnew,ynew], [xnew,ynew], …, while the 2nd and the third dimensions are “z” and “t” (no interpolation). This way, the rank of the result will be reduced from that of self.

If you instead give xnew to coord0 and ynew to coord1 as

gp_int = gp_org.interpolate( xnew, ynew )

The result will be 4-dimensional with the first coordinate sampled at xnew, xnew, xnew,… and the second coordinate sampled at ynew, ynew, ynew,…

You can also cut regarding 2D coordinate variable as

gp_int = gp_org.interpolate( pnew, qnew )
gp_int = gp_org.interpolate( xnew, qnew )
gp_int = gp_org.interpolate( [pnew, qnew] )
gp_int = gp_org.interpolate( [xnew, qnew] )

In any case, the desitination VArrays such as xnew ynew pnew qnew must be one-dimensional.

Note that

gp_int = gp_org.interpolate( qnew )

fails (exception raised), since it is ambiguous. If you tempted to do so, perhaps what you want is covered by the following special form:

As a special form, you can specify a particular dimension like this:

gp_int = gp_org.interpolate( "x"=>pnew )

Here, interpolation along “x” is made, while other axes are retained. This is useful if pnew corresponds to a multi-D coordinate variable where there are two or more corresponding axes (otherwise, this special form is not needed.)

See the test part at the end of this file for more examples.

LIMITATION

Currently associated coordinates expressed by 3D or greater dimensional arrays are not supported.

Computational efficiency of pure two-dimensional coordinate support should be improved by letting C extensions cover deeper and improving the search algorithm for grid (which is usually ordered quasi-regularly).

COVERAGE

Extrapolation is covered for 1D coordinates, but only interpolation is covered for 2D coordinates (which is limited by gt2dlib in DCL – exception will be raised if you specify a grid point outside the original 2D grid points.).

MATHEMATICAL SPECIFICATION

The multi-dimensional linear interpolation is done by supposing a (hyper-) “rectangular” grid, where each dimension is independently sampled one-dimensionally. In case of interpolation along two dimensional coordinates such as “p” and “q” in the example above, a mapping from a rectangular grid is assumed, and the corresponding points in the rectangular grid is solved inversely (currently by using gt2dlib in DCL).

For 1D and 2D cases, linear interpolations may be expressed as

1D:  zi = (1-a)*z0 + a*z1
2D:  zi = (1-a)*(1-b)*z00 + a*(1-b)*z10 + (1-a)*b*z01 + a*b*z11

This method is extended to arbitrary number of dimensions. Thus, if the number of dimensions to interpolate is S, then 2**S grid points are used for each interpolation (8 points for 3D, 16 points for 4D,…). Thus, the linearity of this interpolation is only along each dimension, not over the whole dimensionality.

USAGE

interpolate(coord0, coord1, ...)

ARGUMENTS

  • coord0, coord1,… [ 1D VArray, or Array of 1D VArray, or a 1-element Hash as => slice_loc_value(Numeric) ] : locations to which interpolation is made. Names of all the VArray’s in the arguments must exist among the names of the coordinates of self (including associated coordinates), since the dimension finding is made in terms of coordinate names. If an argument is an Array of VArray’s, the first VArray will become the main coordinate variable, and the rest will be associated coordinates.

  • SPECIAL CASE

    You can specfify a one-element Hash as the only argument such as

    gphys.interpolate("x"=>varray)
    

    where varray is a coordinate onto which interpolation is made. This is espcially useful if varray is multi-D. If varray’s name “p” (name of a 2D coordnate var), for example, you can interpolate only regarding “x” by retaining other axes. If varray is 1-diemnsional, the same thing can be done simply by

    gphys.interpolate(varray)
    

    since the corresponding 1D coordinate is found aotomatically.

RETURN VALUE

  • a GPhys



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
415
416
417
418
419
420
421
422
423
424
425
# File 'lib/numru/gphys/interpolate.rb', line 389

def interpolate(*coords)
  coords, org_coords, org_dims, newgrid = _interpo_match_coords(coords)
  crdmap = _interpo_reorder_2crdmap(coords, org_coords, org_dims)
  idxmap = _interpo_find_position(crdmap)

  z = val
  if z.is_a?(NArrayMiss)
    missval = ( (a=get_att('_FillValue')) ? a[0] : nil ) || 
              ( (a=get_att('missing_value')) ? a[0] : nil ) || 
              @@interpo_missval
    z = z.to_na(missval)
    input_nomiss = false
  else
    input_nomiss = true
    if @@interpo_extrapolation
      missval = nil
    else
      missval = @@interpo_missval
    end
  end

  na = c_interpo_do(newgrid.shape, idxmap, z, missval,
                    @@interpo_extrapolation)   # [C-extension]

  if !input_nomiss || !@@interpo_extrapolation
    mask = na.ne(missval)
    if !input_nomiss || mask.min == 0
      na = NArrayMiss.to_nam_no_dup(na,mask)
    end
  end

  va = VArray.new(na, data, name)

  ret = GPhys.new(newgrid, va)
  ret.grid.set_lost_axes(self.lost_axes)
  ret
end

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



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
504
505
506
507
508
509
510
511
512
513
514
515
516
# File 'lib/numru/ganalysis/fitting.rb', line 476

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

#long_nameObject



671
672
673
# File 'lib/numru/gphys/gphys.rb', line 671

def long_name
	@data.long_name
end

#long_name=(long_name) ⇒ Object



674
675
676
# File 'lib/numru/gphys/gphys.rb', line 674

def long_name=(long_name)
	@data.long_name= long_name
end

#lost_axesObject



763
764
765
# File 'lib/numru/gphys/gphys.rb', line 763

def lost_axes
	 @grid.lost_axes
end

#marshal_dumpObject



1176
1177
1178
# File 'lib/numru/gphys/gphys.rb', line 1176

def marshal_dump
  [@data.copy, @grid.copy]
end

#marshal_load(ary) ⇒ Object



1180
1181
1182
1183
# File 'lib/numru/gphys/gphys.rb', line 1180

def marshal_load(ary)
  @data = ary[0]
  @grid = ary[1]
end

#mask(mask) ⇒ Object



1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
# File 'lib/numru/gphys/gphys.rb', line 1164

def mask(mask)
  mask = mask.to_na(0) if mask.is_a?(NArrayMiss)
  v = self.val
  if v.is_a?(NArrayMiss)
    v.set_mask( v.get_mask & mask )
  else
    v = NArrayMiss.to_nam(v,mask)
  end        
  self.copy.replace_val(v)
end

#mask!(mask) ⇒ Object



1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
# File 'lib/numru/gphys/gphys.rb', line 1153

def mask!(mask)
  mask = mask.to_na(0) if mask.is_a?(NArrayMiss)
  v = self.val
  if v.is_a?(NArrayMiss)
    v.set_mask( v.get_mask & mask )
  else
    v = NArrayMiss.to_nam(v,mask)
  end        
  self.replace_val(v)
end

#mouse_cut(dimx, dimy, num = 2, line_type = 1, line_index = 1) ⇒ Object

Makes a subset interactively by specifying a (poly-)line on the DCL viewport

ARGUMENTS

  • dimx {String] : name of number (0,1,..) of the dimension corresponding to the X coordinate in the current window of DCL

  • dimy {String] : name of number (0,1,..) of the dimension corresponding to the Y coordinate in the current window of DCL

  • num {Integer] : the number of points along the (poly-)line (2 or greater – if 2, a single line segment; if 3 or more, a poly-line)

RETURN VALUE

  • a GPhys



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

def mouse_cut(dimx, dimy, num=2, line_type=1, line_index=1)

  # < preparation >

  dimx = dim_index(dimx)
  dimy = dim_index(dimy)

  rundef = DCL.glpget("rundef")
  line = nil
  while(true)
    puts "\n*** Waiting for mouse click. Click #{num} points in the current viewport."
    line = DCLMouseLine.new(num)
    if line.ux.include?(rundef)
      puts "** The points specified include one(s) outside the U window. Do it again."
    else
      break
    end
  end
  line.draw(line_type, line_index)
  vx = line.vx
  vy = line.vy
  ux = line.ux
  uy = line.uy
  gpnew = dcl_fig_cut(dimx,dimy,ux,uy)
  [gpnew, line]
end

#mouse_cut_repeatObject

Interpolation onto grid points specified by the previous call of GPhys#mouse_cut



169
170
171
172
173
174
175
176
# File 'lib/numru/gphys/interpolate.rb', line 169

def mouse_cut_repeat
  if @@interpo_previous_cutter.nil?
    raise("You must first use GPhys#mouse_cut. This method repeats it") 
  end
  gpnew = interpolate(@@interpo_previous_cutter)
  gpnew = @@interpo_previous_modifier[gpnew] if @@interpo_previous_modifier
  gpnew
end

#nameObject



612
613
614
# File 'lib/numru/gphys/gphys.rb', line 612

def name
	 data.name
end

#name=(nm) ⇒ Object



615
616
617
# File 'lib/numru/gphys/gphys.rb', line 615

def name=(nm)
	 data.name=nm
end

#ntypeObject



651
652
653
# File 'lib/numru/gphys/gphys.rb', line 651

def ntype
	@data.ntype
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

#rankObject



747
748
749
# File 'lib/numru/gphys/gphys.rb', line 747

def rank
	@grid.rank
end

#rank_len_ne_1Object



750
751
752
# File 'lib/numru/gphys/gphys.rb', line 750

def rank_len_ne_1
	(shape_current - [1]).length
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.to_f
	end
  }
  self * factor
end

#regrid(to) ⇒ Object

Interpolate to conform the grid to a target GPhys object

ARGUMENTS

  • to [GPhys] : the target gphys

RETURN VALUE

  • a GPhys



208
209
210
211
# File 'lib/numru/gphys/interpolate.rb', line 208

def regrid(to)
  coords = to.axnames.collect{|nm| to.coord(nm)}
  interpolate(*coords)
end

#rename(nm) ⇒ Object



618
619
620
621
# File 'lib/numru/gphys/gphys.rb', line 618

def rename(nm)
	data.name=nm
	self
end

#replace_val(v) ⇒ Object

Raises:

  • (ArgumentError)


629
630
631
632
633
# File 'lib/numru/gphys/gphys.rb', line 629

def replace_val(v)
	 raise(ArgumentError,"Shape miss-match") if @grid.shape != v.shape
	 @data.replace_val(v)
	 self
end

#running_mean(dim, len_or_wgt = nil, bc = nil, 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) : Specify one of the following:

    • nil (default) : choose BC_SIMPLE or BC_CYCLIC automatically

    • GPhys::BC_SIMPLE : Averaging is truncated 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; default=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 averaging, so:

  • This method does not support complex numbers.



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

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

  #< process arguments >

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

  if bc.nil?
    if axis(dim).cyclic_extendible?
      bc=BC_CYCLIC
    else
      bc=BC_SIMPLE
    end
  end

  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

#running_mean_2D(dim1, dim2, len_or_wgt1, len_or_wgt2, bc1 = nil, bc2 = nil, nminvalid = 1) ⇒ Object

Running mean along two dimensions (with optional weight specification).

This method would be needed for data with missing. If the data has no missing, you should apply running_mean consecutively along the two dimensions you want, which will be faster and efficient.

However, if the data have missing, the results are not the same. That’s why this method is needed.

ARGUMENTS

  • dim1 (Integer or String) : a dimension to apply the running mean

  • dim2 (Integer or String) : another dimension to apply the running mean (dim1 must be smaller than dim2)

  • len_or_wgt1 : If Integer, specifies the length of running mean for dim1. If 1D NArray, it specifies the weight (e.g., NArray[1.0, 2.0, 1.0] for the 1-2-1 smoothing)

  • len_or_wgt2 : as len_or_wgt1 but for dim2.

  • bc1 (Integer or nil; optional) : Specify one of the following for dim1:

    • nil : choose BC_SIMPLE or BC_CYCLIC automatically

    • GPhys::BC_SIMPLE : Averaging is truncated 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.

  • bc2 : as bc1 but for dim2.

  • nminvalid (Integer; optional; default=1): Minimum number of grid points needed to define the running mean (it is the number of valid data in the 2-dimensional tile).



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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/numru/gphys/gphys_dim_op.rb', line 135

def running_mean_2D(dim1, dim2, len_or_wgt1, len_or_wgt2,
                    bc1=nil, bc2=nil,
                    nminvalid=1)

  dim1 = dim_index(dim1)  # to handle String or negative specification
  dim2 = dim_index(dim2)  # to handle String or negative specification

  if bc1.nil?
    if axis(dim1).cyclic_extendible?
      bc1=BC_CYCLIC
    else
      bc1=BC_SIMPLE
    end
  end
  if bc2.nil?
    if axis(dim2).cyclic_extendible?
      bc2=BC_CYCLIC
    else
      bc2=BC_SIMPLE
    end
  end

  vi = self.val
  if vi.is_a?(NArray)
    # Just for convenience.
    self.running_mean(dim1, len_or_wgt1, bc1, nminvalid).running_mean(dim2, len_or_wgt2, bc2, nminvalid)
  end
  
  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_2D(vi, dim1,len_or_wgt1,bc1, dim2,len_or_wgt2,bc2,
            missval, nminvalid)
    vo = NArrayMiss.to_nam(vo, vo.ne(missval) )
  else
    raise("This method accepts only data with missing. If not, you should apply running_mean twice for dim1 & dim2, respectively")
  end

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

#set_assoc_coords(assoc_crds) ⇒ Object



792
793
794
# File 'lib/numru/gphys/gphys.rb', line 792

def set_assoc_coords(assoc_crds)
  @grid.set_assoc_coords(assoc_crds)
end

#set_att(name, val) ⇒ Object Also known as: put_att



641
642
643
644
# File 'lib/numru/gphys/gphys.rb', line 641

def set_att(name, val)
	@data.set_att(name, val)
	self
end

#set_lost_axes(lost) ⇒ Object



766
767
768
769
# File 'lib/numru/gphys/gphys.rb', line 766

def set_lost_axes( lost )
  @grid.set_lost_axes( lost )
  self
end

#shape_coerce(other) ⇒ Object



858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
# File 'lib/numru/gphys/gphys.rb', line 858

def shape_coerce(other)
	 #
	 # for binary operations
	 #
	 if self.rank == other.rank
	    # nothing to do
	    [other, self]
	 else
	    if self.rank < other.rank
  shorter = self
  longer = other
  i_am_the_shorter = true
	    else
  shorter = other
  longer = self 
  i_am_the_shorter = false
	    end
	    reshape_args = 
  __shape_matching( shorter.shape_current, longer.shape_current, 
				shorter.axnames, longer.axnames )
	    shorter = shorter.data.copy.reshape!(*reshape_args)
	    ##def shorter.data; self; end  # singular method!
	    if i_am_the_shorter
  [longer, shorter]
	    else
  [shorter, longer]
	    end
	 end
end

#shape_coerce_full(other) ⇒ Object



888
889
890
891
892
893
894
895
896
# File 'lib/numru/gphys/gphys.rb', line 888

def shape_coerce_full(other)
  o, s = shape_coerce(other)
  if o.length < s.length
    o = self.class.new( s.grid, o + NArray.new(o.typecode,*s.shape) )
  elsif o.length > s.length
    s = self.class.new( o.grid, s + NArray.new(s.typecode,*o.shape) )
  end
  [o, s]
end

#shape_currentObject Also known as: shape



992
993
994
# File 'lib/numru/gphys/gphys.rb', line 992

def shape_current
	 @data.shape_current
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

#threepoint_O2nd_deriv(*args) ⇒ Object



94
95
96
# File 'lib/numru/gphys/derivative.rb', line 94

def threepoint_O2nd_deriv(*args)
  Derivative::threepoint_O2nd_deriv(self,*args)
end

#transpose(*dims) ⇒ Object



898
899
900
901
902
# File 'lib/numru/gphys/gphys.rb', line 898

def transpose(*dims)
	grid = @grid.transpose(*dims)
	data = @data.transpose(*dims)
	self.class.new( grid, data )
end

#unitsObject



655
656
657
# File 'lib/numru/gphys/gphys.rb', line 655

def units
	@data.units
end

#units=(units) ⇒ Object



658
659
660
# File 'lib/numru/gphys/gphys.rb', line 658

def units=(units)
	@data.units= units
end

#valObject



623
624
625
# File 'lib/numru/gphys/gphys.rb', line 623

def val
	 @data.val
end

#val=(v) ⇒ Object



626
627
628
# File 'lib/numru/gphys/gphys.rb', line 626

def val=(v)
	 @data.val= v
end