Class: Numo::NArray

Inherits:
Object
  • Object
show all
Defined in:
ext/numo/narray/narray.c,
lib/numo/narray.rb,
lib/numo/narray/extra.rb,
ext/numo/narray/narray.c

Overview

Numo::NArray is the abstract super class for Numerical N-dimensional Array in the Ruby/Numo module. Use Typed Subclasses of NArray (Numo::DFloat, Int32, etc) to create data array instances.

Defined Under Namespace

Classes: CastError, DimensionError, OperationError, ShapeError, ValueError

Constant Summary collapse

ALTERNATIVE =

Constant to indicate whether it is numo-narray-alt.

true
VERSION =

:NArray Alternative.

The version of Numo
@@warn_slow_dot =
false

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(shape) ⇒ Object #initialize(size0, size1, ...) ⇒ Numo::NArray

Constructs an instance of NArray class using the given and shape or sizes. Note that NArray itself is an abstract super class and not suitable to create instances. Use Typed Subclasses of NArray (DFloat, Int32, etc) to create instances. This method does not allocate memory for array data. Memory is allocated on write method such as #fill, #store, #seq, etc.

Examples:

i = Numo::Int64.new([2,4,3])
# => Numo::Int64#shape=[2,4,3](empty)

f = Numo::DFloat.new(3,4)
# => Numo::DFloat#shape=[3,4](empty)

f.fill(2)
# => Numo::DFloat#shape=[3,4]
# [[2, 2, 2, 2],
#  [2, 2, 2, 2],
#  [2, 2, 2, 2]]

x = Numo::NArray.new(5)
# => in `new': allocator undefined for Numo::NArray (TypeError)
#   	from t.rb:9:in `<main>'

Overloads:

  • #initialize(size0, size1, ...) ⇒ Numo::NArray

    Returns unallocated narray.

    Parameters:

    • shape (Array)

      (array of sizes along each dimension)

    • sizeN (Integer)

      (size along Nth-dimension)



359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
# File 'ext/numo/narray/narray.c', line 359

static VALUE na_initialize(VALUE self, VALUE args) {
  VALUE v;
  size_t* shape = NULL;
  int ndim;

  if (RARRAY_LEN(args) == 1) {
    v = RARRAY_AREF(args, 0);
    if (TYPE(v) != T_ARRAY) {
      v = args;
    }
  } else {
    v = args;
  }
  ndim = (int)RARRAY_LEN(v);
  if (ndim > NA_MAX_DIMENSION) {
    rb_raise(rb_eArgError, "ndim=%d exceeds maximum dimension", ndim);
  }
  shape = ALLOCA_N(size_t, ndim);
  // setup size_t shape[] from VALUE shape argument
  na_array_to_internal_shape(self, v, shape);
  na_setup(self, ndim, shape);

  return self;
}

Class Method Details

.[](elements) ⇒ NArray

Generate NArray object. NArray datatype is automatically selected.

Parameters:

  • elements (Numeric, Array)

Returns:



444
445
446
447
448
449
450
451
452
453
# File 'ext/numo/narray/array.c', line 444

static VALUE nary_s_bracket(VALUE klass, VALUE ary) {
  VALUE dtype = Qnil;

  if (TYPE(ary) != T_ARRAY) {
    rb_bug("Argument is not array");
  }
  dtype = na_ary_composition_dtype(ary);
  check_subclass_of_narray(dtype);
  return rb_funcall(dtype, id_cast, 1, ary);
}

.alternative?Boolean

Returns true if this is numo-narray-alt.

Returns:

  • (Boolean)


15
16
17
# File 'lib/numo/narray.rb', line 15

def self.alternative?
  ALTERNATIVE
end

.array_type(ary) ⇒ Class

return type of NArray which would be created from given Array.

Examples:

Numo::NArray.array_type([1, 2, 3])
# => Numo::Int32
Numo::NArray.array_type([0, 1, 2i])
# => Numo::DComplex
Numo::NArray.array_type(Numo::DFloat[1, 2, 3])
# => Numo::DFloat

Returns NArray class.

Parameters:

  • ary (Array)

Returns:

  • (Class)

    NArray class



434
435
436
# File 'ext/numo/narray/array.c', line 434

static VALUE na_s_array_type(VALUE mod, VALUE ary) {
  return na_ary_composition_dtype(ary);
}

.asarray(a) ⇒ Object

Convert the argument to an narray.



118
119
120
121
122
123
124
125
126
127
# File 'lib/numo/narray/extra.rb', line 118

def self.asarray(a)
  case a
  when NArray
    a.ndim == 0 ? a[:new] : a
  when Numeric, Range
    self[a]
  else
    cast(a)
  end
end

.byte_sizeNumeric

Returns byte size of one element of NArray.

Returns:

  • (Numeric)

    byte size.



1231
1232
1233
# File 'ext/numo/narray/narray.c', line 1231

static VALUE nary_s_byte_size(VALUE type) {
  return rb_const_get(type, id_element_byte_size);
}

.cast(a) ⇒ Object

Convert the argument to an narray if not an narray.



103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/numo/narray/extra.rb', line 103

def self.cast(a)
  case a
  when NArray
    a
  when Array, Numeric
    NArray.array_type(a).cast(a)
  else
    raise TypeError, 'invalid type for NArray' unless a.respond_to?(:to_a)

    a = a.to_a
    NArray.array_type(a).cast(a)
  end
end

.column_stack(arrays) ⇒ Object

Stack 1-d arrays into columns of a 2-d array.

Examples:

x = Numo::Int32[1,2,3]
y = Numo::Int32[2,3,4]
Numo::NArray.column_stack([x,y])
# => Numo::Int32#shape=[3,2]
# [[1, 2],
#  [2, 3],
#  [3, 4]]


552
553
554
555
556
557
558
559
560
561
562
# File 'lib/numo/narray/extra.rb', line 552

def column_stack(arrays)
  arys = arrays.map do |a|
    a = cast(a)
    case a.ndim
    when 0 then a[:new, :new]
    when 1 then a[true, :new]
    else; a
    end
  end
  concatenate(arys, axis: 1)
end

.concatenate(arrays, axis: 0) ⇒ Object

Examples:

a = Numo::DFloat[[1, 2], [3, 4]]
# => Numo::DFloat#shape=[2,2]
# [[1, 2],
#  [3, 4]]

b = Numo::DFloat[[5, 6]]
# => Numo::DFloat#shape=[1,2]
# [[5, 6]]

Numo::NArray.concatenate([a,b],axis:0)
# => Numo::DFloat#shape=[3,2]
# [[1, 2],
#  [3, 4],
#  [5, 6]]

Numo::NArray.concatenate([a,b.transpose], axis:1)
# => Numo::DFloat#shape=[2,3]
# [[1, 2, 5],
#  [3, 4, 6]]

Raises:

  • (ArgumentError)


415
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
# File 'lib/numo/narray/extra.rb', line 415

def concatenate(arrays, axis: 0)
  klass = self == NArray ? NArray.array_type(arrays) : self
  nd = 0
  arrays = arrays.map do |a|
    case a
    when NArray
      # ok
    when Numeric
      a = klass[a]
    when Array
      a = klass.cast(a)
    else
      raise TypeError, "not Numo::NArray: #{a.inspect[0..48]}"
    end
    nd = a.ndim if a.ndim > nd
    a
  end
  axis += nd if axis < 0
  raise ArgumentError, 'axis is out of range' if axis < 0 || axis >= nd

  new_shape = nil
  sum_size = 0
  arrays.each do |a|
    a_shape = a.shape
    a_shape = ([1] * (nd - a_shape.size)) + a_shape if nd != a_shape.size # rubocop:disable Performance/CollectionLiteralInLoop
    sum_size += a_shape.delete_at(axis)
    if new_shape
      raise ShapeError, 'shape mismatch' if new_shape != a_shape
    else
      new_shape = a_shape
    end
  end
  new_shape.insert(axis, sum_size)
  result = klass.zeros(*new_shape)
  lst = 0
  refs = [true] * nd
  arrays.each do |a|
    fst = lst
    lst = fst + (a.shape[axis - nd] || 1)
    if lst > fst
      refs[axis] = fst...lst
      result[*refs] = a
    end
  end
  result
end

.debug=(flag) ⇒ Object



1716
1717
1718
1719
# File 'ext/numo/narray/narray.c', line 1716

static VALUE na_debug_set(VALUE mod, VALUE flag) {
  na_debug_flag = RTEST(flag);
  return Qnil;
}

.diag_indices(m, n, k = 0) ⇒ Object

Return the k-th diagonal indices.



1033
1034
1035
1036
1037
# File 'lib/numo/narray/extra.rb', line 1033

def self.diag_indices(m, n, k = 0)
  x = Numo::Int64.new(m, 1).seq + k
  y = Numo::Int64.new(1, n).seq
  (x.eq y).where
end

.dstack(arrays) ⇒ Object

Stack arrays in depth wise (along third axis).

Examples:

a = Numo::Int32[1,2,3]
b = Numo::Int32[2,3,4]
Numo::NArray.dstack([a,b])
# => Numo::Int32#shape=[1,3,2]
# [[[1, 2],
#   [2, 3],
#   [3, 4]]]

a = Numo::Int32[[1],[2],[3]]
b = Numo::Int32[[2],[3],[4]]
Numo::NArray.dstack([a,b])
# => Numo::Int32#shape=[3,1,2]
# [[[1, 2]],
#  [[2, 3]],
#  [[3, 4]]]


535
536
537
538
539
540
# File 'lib/numo/narray/extra.rb', line 535

def dstack(arrays)
  arys = arrays.map do |a|
    _atleast_3d(cast(a))
  end
  concatenate(arys, axis: 2)
end

.eye(n) ⇒ Numo::NArray

Returns a NArray with shape=(n,n) whose diagonal elements are 1, otherwise 0.

Examples:

a = Numo::DFloat.eye(3)
# => Numo::DFloat#shape=[3,3]
# [[1, 0, 0],
#  [0, 1, 0],
#  [0, 0, 1]]

Returns created NArray.

Parameters:

  • n (Integer)

    Size of NArray. Creates 2-D NArray with shape=(n,n)

Returns:



552
553
554
555
556
557
558
559
560
561
562
563
564
565
# File 'ext/numo/narray/narray.c', line 552

static VALUE na_s_eye(int argc, VALUE* argv, VALUE klass) {
  VALUE obj;
  VALUE tmp[2];

  if (argc == 0) {
    rb_raise(rb_eArgError, "No argument");
  } else if (argc == 1) {
    tmp[0] = tmp[1] = argv[0];
    argv = tmp;
    argc = 2;
  }
  obj = rb_class_new_instance(argc, argv, klass);
  return rb_funcall(obj, id_eye, 0);
}

.from_binary(string, [shape]) ⇒ Numo::NArray

Returns a new 1-D array initialized from binary raw data in a string.

Returns NArray containing binary data.

Parameters:

  • string (String)

    Binary raw data.

  • shape (Array)

    array of integers representing array shape.

Returns:



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
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
# File 'ext/numo/narray/narray.c', line 1242

static VALUE nary_s_from_binary(int argc, VALUE* argv, VALUE type) {
  size_t len, str_len, byte_size;
  size_t* shape;
  int i, nd, narg;
  VALUE vstr, vshape, vna;
  VALUE velmsz;

  narg = rb_scan_args(argc, argv, "11", &vstr, &vshape);
  Check_Type(vstr, T_STRING);
  str_len = RSTRING_LEN(vstr);
  velmsz = rb_const_get(type, id_element_byte_size);
  if (narg == 2) {
    switch (TYPE(vshape)) {
    case T_FIXNUM:
      nd = 1;
      len = NUM2SIZET(vshape);
      shape = &len;
      break;
    case T_ARRAY:
      nd = (int)RARRAY_LEN(vshape);
      if (nd > NA_MAX_DIMENSION) {
        rb_raise(nary_eDimensionError, "shape exceeds max dimension");
      }
      shape = ALLOCA_N(size_t, nd);
      len = 1;
      for (i = 0; i < nd; ++i) {
        len *= shape[i] = NUM2SIZET(RARRAY_AREF(vshape, i));
      }
      break;
    default:
      rb_raise(rb_eArgError, "second argument must be size or shape");
    }
    if (FIXNUM_P(velmsz)) {
      byte_size = len * NUM2SIZET(velmsz);
    } else {
      byte_size = ceil(len * NUM2DBL(velmsz));
    }
    if (byte_size > str_len) {
      rb_raise(rb_eArgError, "specified size is too large");
    }
  } else {
    nd = 1;
    if (FIXNUM_P(velmsz)) {
      len = str_len / NUM2SIZET(velmsz);
      byte_size = len * NUM2SIZET(velmsz);
    } else {
      len = floor(str_len / NUM2DBL(velmsz));
      byte_size = str_len;
    }
    if (len == 0) {
      rb_raise(rb_eArgError, "string is empty or too short");
    }
    shape = ALLOCA_N(size_t, nd);
    shape[0] = len;
  }

  vna = nary_new(type, nd, shape);
  if (OBJ_FROZEN(vstr)) {
    na_set_pointer(vna, RSTRING_PTR(vstr), byte_size);
    rb_ivar_set(vna, id_source, vstr);
  } else {
    void* ptr = na_get_pointer_for_write(vna);
    memcpy(ptr, RSTRING_PTR(vstr), byte_size);
  }

  return vna;
}

.hstack(arrays) ⇒ Object

Stack arrays horizontally (column wise).

Examples:

a = Numo::Int32[1,2,3]
b = Numo::Int32[2,3,4]
Numo::NArray.hstack([a,b])
# => Numo::Int32#shape=[6]
# [1, 2, 3, 2, 3, 4]

a = Numo::Int32[[1],[2],[3]]
b = Numo::Int32[[2],[3],[4]]
Numo::NArray.hstack([a,b])
# => Numo::Int32#shape=[3,2]
# [[1, 2],
#  [2, 3],
#  [3, 4]]


505
506
507
508
509
510
511
512
513
514
515
# File 'lib/numo/narray/extra.rb', line 505

def hstack(arrays)
  klass = self == NArray ? NArray.array_type(arrays) : self
  nd = 0
  arys = arrays.map do |a|
    a = klass.cast(a)
    nd = a.ndim if a.ndim > nd
    a
  end
  dim = nd >= 2 ? 1 : 0
  concatenate(arys, axis: dim)
end

.inspect_colsInteger or nil

Returns the number of cols used for NArray#inspect

Returns the number of cols.

Returns:

  • (Integer or nil)

    the number of cols.



1765
1766
1767
1768
1769
1770
1771
# File 'ext/numo/narray/narray.c', line 1765

static VALUE na_inspect_cols(VALUE mod) {
  if (numo_na_inspect_cols > 0) {
    return INT2NUM(numo_na_inspect_cols);
  } else {
    return Qnil;
  }
}

.inspect_cols=(cols) ⇒ nil

Set the number of cols used for NArray#inspect

Parameters:

  • cols (Integer or nil)

    the number of cols

Returns:

  • (nil)


1779
1780
1781
1782
1783
1784
1785
1786
# File 'ext/numo/narray/narray.c', line 1779

static VALUE na_inspect_cols_set(VALUE mod, VALUE num) {
  if (RTEST(num)) {
    numo_na_inspect_cols = NUM2INT(num);
  } else {
    numo_na_inspect_cols = 0;
  }
  return Qnil;
}

.inspect_rowsInteger or nil

Returns the number of rows used for NArray#inspect

Returns the number of rows.

Returns:

  • (Integer or nil)

    the number of rows.



1737
1738
1739
1740
1741
1742
1743
# File 'ext/numo/narray/narray.c', line 1737

static VALUE na_inspect_rows(VALUE mod) {
  if (numo_na_inspect_rows > 0) {
    return INT2NUM(numo_na_inspect_rows);
  } else {
    return Qnil;
  }
}

.inspect_rows=(rows) ⇒ nil

Set the number of rows used for NArray#inspect

Parameters:

  • rows (Integer or nil)

    the number of rows

Returns:

  • (nil)


1751
1752
1753
1754
1755
1756
1757
1758
# File 'ext/numo/narray/narray.c', line 1751

static VALUE na_inspect_rows_set(VALUE mod, VALUE num) {
  if (RTEST(num)) {
    numo_na_inspect_rows = NUM2INT(num);
  } else {
    numo_na_inspect_rows = 0;
  }
  return Qnil;
}

.linspace(x1, x2, [n]) ⇒ Numo::NArray

Returns an array of N linearly spaced points between x1 and x2. This singleton method is valid not for NArray class itself but for typed NArray subclasses, e.g., DFloat, Int64.

Examples:

a = Numo::DFloat.linspace(-5,5,7)
# => Numo::DFloat#shape=[7]
# [-5, -3.33333, -1.66667, 0, 1.66667, 3.33333, 5]

Returns result array.

Parameters:

  • x1 (Numeric)

    The start value

  • x2 (Numeric)

    The end value

  • n (Integer)

    The number of elements. (default is 100).

Returns:



477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
# File 'ext/numo/narray/narray.c', line 477

static VALUE na_s_linspace(int argc, VALUE* argv, VALUE klass) {
  VALUE obj, vx1, vx2, vstep, vsize;
  double n;
  int narg;

  narg = rb_scan_args(argc, argv, "21", &vx1, &vx2, &vsize);
  if (narg == 3) {
    n = NUM2DBL(vsize);
  } else {
    n = 100;
    vsize = INT2FIX(100);
  }

  obj = rb_funcall(vx2, '-', 1, vx1);
  vstep = rb_funcall(obj, '/', 1, DBL2NUM(n - 1));

  obj = rb_class_new_instance(1, &vsize, klass);
  return rb_funcall(obj, id_seq, 2, vx1, vstep);
}

.logspace(a, b, [n, base]) ⇒ Numo::NArray

Returns an array of N logarithmically spaced points between 10^a and 10^b. This singleton method is valid not for NArray having logseq method, i.e., DFloat, SFloat, DComplex, and SComplex.

Examples:

Numo::DFloat.logspace(4,0,5,2)
# => Numo::DFloat#shape=[5]
# [16, 8, 4, 2, 1]

Numo::DComplex.logspace(0,1i*Math::PI,5,Math::E)
# => Numo::DComplex#shape=[5]
# [1+4.44659e-323i, 0.707107+0.707107i, 6.12323e-17+1i, -0.707107+0.707107i, ...]

Returns result array.

Parameters:

  • a (Numeric)

    The start value

  • b (Numeric)

    The end value

  • n (Integer)

    The number of elements. (default is 50)

  • base (Numeric)

    The base of log space. (default is 10)

Returns:



518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
# File 'ext/numo/narray/narray.c', line 518

static VALUE na_s_logspace(int argc, VALUE* argv, VALUE klass) {
  VALUE obj, vx1, vx2, vstep, vsize, vbase;
  double n;

  rb_scan_args(argc, argv, "22", &vx1, &vx2, &vsize, &vbase);
  if (vsize == Qnil) {
    vsize = INT2FIX(50);
    n = 50;
  } else {
    n = NUM2DBL(vsize);
  }
  if (vbase == Qnil) {
    vbase = DBL2NUM(10);
  }

  obj = rb_funcall(vx2, '-', 1, vx1);
  vstep = rb_funcall(obj, '/', 1, DBL2NUM(n - 1));

  obj = rb_class_new_instance(1, &vsize, klass);
  return rb_funcall(obj, id_logseq, 3, vx1, vstep, vbase);
}

.new_like(obj) ⇒ Numo::NArray

Generate new unallocated NArray instance with shape and type defined from obj. Numo::NArray.new_like(obj) returns instance whose type is defined from obj. Numo::DFloat.new_like(obj) returns DFloat instance.

Examples:

Numo::NArray.new_like([[1,2,3],[4,5,6]])
# => Numo::Int32#shape=[2,3](empty)

Numo::DFloat.new_like([[1,2],[3,4]])
# => Numo::DFloat#shape=[2,2](empty)

Numo::NArray.new_like([1,2i,3])
# => Numo::DComplex#shape=[3](empty)

Parameters:

Returns:



418
419
420
421
422
423
424
# File 'ext/numo/narray/array.c', line 418

VALUE
na_s_new_like(VALUE type, VALUE obj) {
  VALUE newary;

  na_composition3(obj, &type, 0, &newary);
  return newary;
}

.ones(shape) ⇒ Object .ones(size1, size2, ...) ⇒ Object

Returns a one-filled narray with shape. This singleton method is valid not for NArray class itself but for typed NArray subclasses, e.g., DFloat, Int64.

Examples:

a = Numo::DFloat.ones(3,5)
# => Numo::DFloat#shape=[3,5]
# [[1, 1, 1, 1, 1],
#  [1, 1, 1, 1, 1],
#  [1, 1, 1, 1, 1]]


455
456
457
458
459
# File 'ext/numo/narray/narray.c', line 455

static VALUE na_s_ones(int argc, VALUE* argv, VALUE klass) {
  VALUE obj;
  obj = rb_class_new_instance(argc, argv, klass);
  return rb_funcall(obj, id_fill, 1, INT2FIX(1));
}

.parse(str, split1d: /\s+/, split2d: /;?$|;/, split3d: /\s*\n(\s*\n)+/m) ⇒ Object

parse matrix like matlab, octave

Examples:

a = Numo::DFloat.parse %[
 2 -3 5
 4 9 7
 2 -1 6
]
# => Numo::DFloat#shape=[3,3]
# [[2, -3, 5],
#  [4, 9, 7],
#  [2, -1, 6]]


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
# File 'lib/numo/narray/extra.rb', line 141

def self.parse(str, split1d: /\s+/, split2d: /;?$|;/,
               split3d: /\s*\n(\s*\n)+/m)
  a = []
  str.split(split3d).each do |block|
    b = []
    # print "b"; p block
    block.split(split2d).each do |line|
      # p line
      line.strip!
      next if line.empty?

      c = []
      line.split(split1d).each do |item|
        c << eval(item.strip) unless item.empty? # rubocop:disable Security/Eval
      end
      b << c unless c.empty?
    end
    a << b unless b.empty?
  end
  if a.size == 1
    cast(a[0])
  else
    cast(a)
  end
end

.profileObject



1723
1724
1725
# File 'ext/numo/narray/narray.c', line 1723

static VALUE na_profile(VALUE mod) {
  return rb_float_new(na_profile_value);
}

.profile=(val) ⇒ Object



1727
1728
1729
1730
# File 'ext/numo/narray/narray.c', line 1727

static VALUE na_profile_set(VALUE mod, VALUE val) {
  na_profile_value = NUM2DBL(val);
  return val;
}

.tril_indices(m, n, k = 0) ⇒ Object

Return the indices for the lower-triangle on and below the k-th diagonal.



1018
1019
1020
1021
1022
# File 'lib/numo/narray/extra.rb', line 1018

def self.tril_indices(m, n, k = 0)
  x = Numo::Int64.new(m, 1).seq + k
  y = Numo::Int64.new(1, n).seq
  (x >= y).where
end

.triu_indices(m, n, k = 0) ⇒ Object

Return the indices for the upper-triangle on and above the k-th diagonal.



981
982
983
984
985
# File 'lib/numo/narray/extra.rb', line 981

def self.triu_indices(m, n, k = 0)
  x = Numo::Int64.new(m, 1).seq + k
  y = Numo::Int64.new(1, n).seq
  (x <= y).where
end

.upcast(type2) ⇒ Object




1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
# File 'ext/numo/narray/narray.c', line 1173

VALUE
numo_na_upcast(VALUE type1, VALUE type2) {
  VALUE upcast_hash;
  VALUE result_type;

  if (type1 == type2) {
    return type1;
  }
  upcast_hash = rb_const_get(type1, id_UPCAST);
  result_type = rb_hash_aref(upcast_hash, type2);
  if (NIL_P(result_type)) {
    if (TYPE(type2) == T_CLASS) {
      if (RTEST(rb_class_inherited_p(type2, cNArray))) {
        upcast_hash = rb_const_get(type2, id_UPCAST);
        result_type = rb_hash_aref(upcast_hash, type1);
      }
    }
  }
  return result_type;
}

.vstack(arrays) ⇒ Object

Stack arrays vertically (row wise).

Examples:

a = Numo::Int32[1,2,3]
b = Numo::Int32[2,3,4]
Numo::NArray.vstack([a,b])
# => Numo::Int32#shape=[2,3]
# [[1, 2, 3],
#  [2, 3, 4]]

a = Numo::Int32[[1],[2],[3]]
b = Numo::Int32[[2],[3],[4]]
Numo::NArray.vstack([a,b])
# => Numo::Int32#shape=[6,1]
# [[1],
#  [2],
#  [3],
#  [2],
#  [3],
#  [4]]


482
483
484
485
486
487
# File 'lib/numo/narray/extra.rb', line 482

def vstack(arrays)
  arys = arrays.map do |a|
    _atleast_2d(cast(a))
  end
  concatenate(arys, axis: 0)
end

.zeros(shape) ⇒ Object .zeros(size1, size2, ...) ⇒ Object

Returns a zero-filled narray with shape. This singleton method is valid not for NArray class itself but for typed NArray subclasses, e.g., DFloat, Int64.

Examples:

a = Numo::DFloat.zeros(3,5)
# => Numo::DFloat#shape=[3,5]
# [[0, 0, 0, 0, 0],
#  [0, 0, 0, 0, 0],
#  [0, 0, 0, 0, 0]]


434
435
436
437
438
# File 'ext/numo/narray/narray.c', line 434

static VALUE na_s_zeros(int argc, VALUE* argv, VALUE klass) {
  VALUE obj;
  obj = rb_class_new_instance(argc, argv, klass);
  return rb_funcall(obj, id_fill, 1, INT2FIX(0));
}

Instance Method Details

#==(other) ⇒ Boolean

Equality of self and other in view of numerical array. i.e., both arrays have same shape and corresponding elements are equal.

Returns true if self and other is equal.

Parameters:

  • other (Object)

Returns:

  • (Boolean)

    true if self and other is equal.



1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
# File 'ext/numo/narray/narray.c', line 1795

static VALUE na_equal(VALUE self, volatile VALUE other) {
  volatile VALUE vbool;
  narray_t *na1, *na2;
  int i;

  GetNArray(self, na1);

  if (!rb_obj_is_kind_of(other, cNArray)) {
    other = rb_funcall(rb_obj_class(self), id_cast, 1, other);
  }

  GetNArray(other, na2);
  if (na1->ndim != na2->ndim) {
    return Qfalse;
  }
  for (i = 0; i < na1->ndim; i++) {
    if (na1->shape[i] != na2->shape[i]) {
      return Qfalse;
    }
  }
  if (na1->size == 0) {
    return Qtrue;
  }
  vbool = rb_funcall(self, id_eq, 1, other);
  return (rb_funcall(vbool, id_count_false, 0) == INT2FIX(0)) ? Qtrue : Qfalse;
}

#[]Object

#[]=Object

#append(other, axis: nil) ⇒ Object

Append values to the end of an narray.

Examples:

a = Numo::DFloat[1, 2, 3]
a.append([[4, 5, 6], [7, 8, 9]])
# => Numo::DFloat#shape=[9]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

a = Numo::DFloat[[1, 2, 3]]
a.append([[4, 5, 6], [7, 8, 9]],axis:0)
# => Numo::DFloat#shape=[3,3]
# [[1, 2, 3],
#  [4, 5, 6],
#  [7, 8, 9]]

a = Numo::DFloat[[1, 2, 3], [4, 5, 6]]
a.append([7, 8, 9], axis:0)
# in `append': dimension mismatch (Numo::NArray::DimensionError)


230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/numo/narray/extra.rb', line 230

def append(other, axis: nil)
  other = self.class.cast(other)
  if axis
    raise DimensionError, 'dimension mismatch' if ndim != other.ndim

    concatenate(other, axis: axis)
  else
    a = self.class.zeros(size + other.size)
    a[0...size] = self[true]
    a[size..-1] = other[true]
    a
  end
end

#argsort(axis: -1) ⇒ Numo::Int32

Returns an index array of sort result.

Examples:

require 'numo/narray'

a = Numo::DFloat[[0.1, 0.7],
                 [0.4, 0.2],
                 [0.2, 0.5]]
pp a.argsort
# =>
# Numo::Int32#shape=[3,2]
# [[0, 1],
#  [1, 0],
#  [0, 1]]
pp a.argsort(axis: 0)
# =>
# Numo::Int32#shape=[3,2]
# [[0, 1],
#  [2, 2],
#  [1, 0]]
pp a.argsort(axis: 1)
# =>
# Numo::Int32#shape=[3,2]
# [[0, 1],
#  [1, 0],
#  [0, 1]]
pp a.argsort(axis: nil)
# =>
# Numo::Int32#shape=[6]
# [0, 3, 4, 2, 5, 1]

Returns An array of indices that would sort the array.

Parameters:

  • axis (Integer, nil) (defaults to: -1)

    Axis along which to sort. Default is -1 (the last axis). If ‘nil` is given, the array is flattened before sorting.

Returns:

  • (Numo::Int32)

    An array of indices that would sort the array.

Raises:

  • (NotImplementedError)


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
# File 'lib/numo/narray/extra.rb', line 1083

def argsort(axis_ = 'none', axis: -1)
  raise NotImplementedError, "argsort is not implemented for #{self.class}" unless respond_to?(:sort_index)

  axis = axis_ unless axis_ == 'none'

  return flatten.sort_index if axis.nil?

  axis = ndim + axis if axis.negative?
  raise Numo::NArray::DimensionError, 'dimension is out of range' if axis.negative? || axis >= ndim

  case ndim
  when 1
    sort_index
  when 2
    case axis
    when 0
      indices = transpose.sort_index(1)
      indices.transpose - indices.min(1)
    when 1
      indices = sort_index(1)
      indices - indices.min(1).expand_dims(1)
    end
  else
    res = Numo::Int32.zeros(*shape)
    slicer = Array.new(ndim)
    slicer[axis] = true
    other_axes = Array.new(ndim) { |i| i } - [axis]
    axis_ids = other_axes.map do |d|
      Array.new(shape[d]) { |i| i }
    end
    axis_ids.inject(:product).each do |indices|
      indices = indices.flatten
      other_axes.each_with_index do |d, i|
        slicer[d] = indices[i]
      end
      sorted_indices = self[*slicer].sort_index
      res[*slicer] = sorted_indices - sorted_indices.min
    end
    res
  end
end

#at(dim0, ..., dimL) ⇒ Numo::NArray

Multi-dimensional array indexing. Similar to numpy’s tuple indexing, i.e., ‘a[,[3,4,..]]` Same as Numo::NArray#[] for one-dimensional NArray.

Examples:

x = Numo::DFloat.new(3,3,3).seq
# => Numo::DFloat#shape=[3,3,3]
#  [[[0, 1, 2],
#    [3, 4, 5],
#    [6, 7, 8]],
#   [[9, 10, 11],
#    [12, 13, 14],
#    [15, 16, 17]],
#   [[18, 19, 20],
#    [21, 22, 23],
#    [24, 25, 26]]]

x.at([0,1,2],[0,1,2],[-1,-2,-3])
# => Numo::DFloat(view)#shape=[3]
#  [2, 13, 24]

Returns one-dimensional NArray view.

Parameters:

Returns:

See Also:



1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
# File 'ext/numo/narray/index.c', line 1041

static VALUE na_at(int argc, VALUE* argv, VALUE self) {
  int i;
  size_t n;
  ssize_t stride = 1;
  narray_t* na;
  VALUE idx = Qnil;

  na_index_arg_to_internal_order(argc, argv, self);

  GetNArray(self, na);
  if (NA_NDIM(na) != argc) {
    rb_raise(rb_eArgError, "the number of argument must be same as dimension");
  }
  for (i = argc; i > 0;) {
    i--;
    n = NA_SHAPE(na)[i];
    na_at_parse_each(argv[i], n, i, &idx, stride);
    stride *= n;
  }
  return na_aref_main(1, &idx, self, 1, 1);
}

#byte_sizeInteger

Returns total byte size of NArray.

Returns:

  • (Integer)

    byte size.



1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
# File 'ext/numo/narray/narray.c', line 1215

static VALUE nary_byte_size(VALUE self) {
  VALUE velmsz;
  narray_t* na;

  GetNArray(self, na);
  velmsz = rb_const_get(rb_obj_class(self), id_element_byte_size);
  if (FIXNUM_P(velmsz)) {
    return SIZET2NUM(NUM2SIZET(velmsz) * na->size);
  }
  return SIZET2NUM(ceil(NUM2DBL(velmsz) * na->size));
}

#byte_swapped?Boolean Also known as: network_order?

Return true if byte swapped.

Returns:

  • (Boolean)


1662
1663
1664
1665
# File 'ext/numo/narray/narray.c', line 1662

static VALUE na_byte_swapped_p(VALUE self) {
  if (TEST_BYTE_SWAPPED(self)) return Qtrue;
  return Qfalse;
}

#cast_to(datatype) ⇒ Numo::NArray

Cast self to another NArray datatype.

Parameters:

  • datatype (Class)

    NArray datatype.

Returns:



1475
1476
1477
# File 'ext/numo/narray/narray.c', line 1475

static VALUE nary_cast_to(VALUE obj, VALUE type) {
  return rb_funcall(type, id_cast, 1, obj);
}

#coerce(other) ⇒ Array

Returns an array containing other and self, both are converted to upcasted type of NArray. Note that NArray has distinct UPCAST mechanism. Coerce is used for operation between non-NArray and NArray.

Returns NArray-casted [other,self].

Parameters:

  • other (Object)

    numeric object.

Returns:

  • (Array)

    NArray-casted [other,self]



1203
1204
1205
1206
1207
1208
1209
# File 'ext/numo/narray/narray.c', line 1203

static VALUE nary_coerce(VALUE x, VALUE y) {
  VALUE type;

  type = numo_na_upcast(rb_obj_class(x), rb_obj_class(y));
  y = rb_funcall(type, id_cast, 1, y);
  return rb_assoc_new(y, x);
}

#column_major?Boolean

Return true if column major.

Returns:

  • (Boolean)


1642
1643
1644
1645
1646
1647
# File 'ext/numo/narray/narray.c', line 1642

static VALUE na_column_major_p(VALUE self) {
  if (TEST_COLUMN_MAJOR(self))
    return Qtrue;
  else
    return Qfalse;
}

#concatenate(*arrays, axis: 0) ⇒ Object

Examples:

a = Numo::DFloat[[1, 2], [3, 4]]
# => Numo::DFloat#shape=[2,2]
# [[1, 2],
#  [3, 4]]

b = Numo::DFloat[[5, 6]]
# => Numo::DFloat#shape=[1,2]
# [[5, 6]]

a.concatenate(b,axis:0)
# => Numo::DFloat#shape=[3,2]
# [[1, 2],
#  [3, 4],
#  [5, 6]]

a.concatenate(b.transpose, axis:1)
# => Numo::DFloat#shape=[2,3]
# [[1, 2, 5],
#  [3, 4, 6]]


607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
# File 'lib/numo/narray/extra.rb', line 607

def concatenate(*arrays, axis: 0)
  axis = check_axis(axis)
  self_shape = shape
  self_shape.delete_at(axis)
  sum_size = shape[axis]
  arrays.map! do |a|
    case a
    when NArray
      # ok
    when Numeric
      a = self.class.new(1).store(a)
    when Array
      a = self.class.cast(a)
    else
      raise TypeError, "not Numo::NArray: #{a.inspect[0..48]}"
    end
    raise ShapeError, 'dimension mismatch' if a.ndim > ndim

    a_shape = a.shape
    sum_size += a_shape.delete_at(axis - ndim) || 1
    raise ShapeError, 'shape mismatch' if self_shape != a_shape

    a
  end
  self_shape.insert(axis, sum_size)
  result = self.class.zeros(*self_shape)
  lst = shape[axis]
  refs = [true] * ndim
  if lst > 0
    refs[axis] = 0...lst
    result[*refs] = self
  end
  arrays.each do |a|
    fst = lst
    lst = fst + (a.shape[axis - ndim] || 1)
    if lst > fst
      refs[axis] = fst...lst
      result[*refs] = a
    end
  end
  result
end

#contiguous?Boolean

Returns:

  • (Boolean)


909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
# File 'ext/numo/narray/narray.c', line 909

VALUE
na_check_contiguous(VALUE self) {
  ssize_t elmsz;
  narray_t* na;
  GetNArray(self, na);

  switch (na->type) {
  case NARRAY_DATA_T:
  case NARRAY_FILEMAP_T:
    return Qtrue;
  case NARRAY_VIEW_T:
    if (NA_VIEW_STRIDX(na) == 0) {
      return Qtrue;
    }
    if (na_check_ladder(self, 0) == Qtrue) {
      elmsz = nary_element_stride(self);
      if (elmsz == NA_STRIDE_AT(na, NA_NDIM(na) - 1)) {
        return Qtrue;
      }
    }
  }
  return Qfalse;
}

#cov(y = nil, ddof: 1, fweights: nil, aweights: nil) ⇒ Numo::NArray

Compute a covariance matrix.

Examples:

x = Numo::DFloat[4, 5, 6]
x.cov
# => 1.0

x = Numo::DFloat[[4, 5, 6], [3, 2, 1]]
x.cov
# => Numo::DFloat#shape=[2,2]
# [[1, -1],
#  [-1, 1]]

y = Numo::DFloat[7, 9, 8]
x.cov(y)
# => Numo::DFloat#shape=[3,3]
# [[1, -1, 0.5],
#  [-1, 1, -0.5],
#  [0.5, -0.5, 1]]

Parameters:

  • y (Numo::NArray) (defaults to: nil)

    (optional) If not nil, the covariance matrix of ‘self` and `y` is computed.

  • ddof (Integer) (defaults to: 1)

    (optional) Delta degrees of freedom. The divisor used in calculations is ‘N - ddof`, where `N` represents the number of observations.

  • fweights (Numo::NArray) (defaults to: nil)

    (optional) 1-D array of integer frequency weights.

  • aweights (Numo::NArray) (defaults to: nil)

    (optional) 1-D array of observation vector weights.

Returns:

Raises:



1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
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
# File 'lib/numo/narray/extra.rb', line 1318

def cov(y = nil, ddof: 1, fweights: nil, aweights: nil) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
  raise Numo::NArray::ShapeError, 'ndim must be <= 2' if ndim > 2
  raise Numo::NArray::ShapeError, 'y.ndim must be <= 2' if !y.nil? && (y.ndim > 2)
  raise ArgumentError, 'ddof must be 0 or 1' unless [0, 1].include?(ddof)

  m = if y
        NArray.vstack([self, y])
      else
        self
      end
  w = nil
  if fweights
    fweights = Numo::NArray.cast(fweights) unless fweights.is_a?(Numo::NArray)
    raise ArgumentError, 'fweights must be 1-D array' unless fweights.ndim == 1
    raise ArgumentError, 'fweights size is wrong' unless fweights.size == m.shape[1]
    raise ArgumentError, 'fweights must be non-negative' if (fweights < 0).any?
    raise ArgumentError, 'fweights must be integer' unless fweights == fweights.floor

    w = fweights
  end
  if aweights
    aweights = Numo::NArray.cast(aweights) unless aweights.is_a?(Numo::NArray)
    raise ArgumentError, 'aweights must be 1-D array' unless aweights.ndim == 1
    raise ArgumentError, 'aweights size is wrong' unless aweights.size == m.shape[1]
    raise ArgumentError, 'aweights must be non-negative' if (aweights < 0).any?

    if w.nil?
      w = aweights
    else
      w *= aweights
    end
  end
  fact = if w.nil?
           m.shape[-1] - ddof
         elsif ddof == 0
           w.sum
         elsif aweights.nil?
           w.sum - ddof
         else
           w_sum = w.sum
           w_sum - (ddof * (w * aweights).sum / w_sum)
         end
  if fact <= 0
    warn('Degrees of freedom <= 0 for slice')
    fact = 0.0
  end
  if w.nil?
    m -= m.mean(axis: -1, keepdims: true)
    mw = m
  else
    m -= (m * w).sum(axis: -1, keepdims: true) / w.sum
    mw = m * w
  end
  m.dot(mw.transpose.conj) / fact
end

#debug_infoObject



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
# File 'ext/numo/narray/narray.c', line 136

VALUE
nary_debug_info(VALUE self) {
  int i;
  narray_t* na;
  GetNArray(self, na);

  printf("%s:\n", rb_class2name(rb_obj_class(self)));
  printf("  id     = 0x%" PRI_VALUE_PREFIX "x\n", self);
  printf("  type   = %d\n", na->type);
  printf("  flag   = [%d,%d]\n", na->flag[0], na->flag[1]);
  printf("  size   = %" SZF "d\n", na->size);
  printf("  ndim   = %d\n", na->ndim);
  printf("  shape  = 0x%" SZF "x\n", (size_t)na->shape);
  if (na->shape) {
    printf("  shape  = [");
    for (i = 0; i < na->ndim; i++) printf(" %" SZF "d", na->shape[i]);
    printf(" ]\n");
  }

  switch (na->type) {
  case NARRAY_DATA_T:
  case NARRAY_FILEMAP_T:
    nary_debug_info_nadata(self);
    break;
  case NARRAY_VIEW_T:
    nary_debug_info_naview(self);
    break;
  }
  return Qnil;
}

#deg2radObject

Convert angles from degrees to radians.



31
32
33
# File 'lib/numo/narray/extra.rb', line 31

def deg2rad
  self * (Math::PI / 180)
end

#delete(indice, axis = nil) ⇒ Object

Examples:

a = Numo::DFloat[[1,2,3,4], [5,6,7,8], [9,10,11,12]]
a.delete(1,0)
# => Numo::DFloat(view)#shape=[2,4]
# [[1, 2, 3, 4],
#  [9, 10, 11, 12]]

a.delete((0..-1).step(2),1)
# => Numo::DFloat(view)#shape=[3,2]
# [[2, 4],
#  [6, 8],
#  [10, 12]]

a.delete([1,3,5])
# => Numo::DFloat(view)#shape=[9]
# [1, 3, 5, 7, 8, 9, 10, 11, 12]


264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/numo/narray/extra.rb', line 264

def delete(indice, axis = nil)
  if axis
    bit = Bit.ones(shape[axis])
    bit[indice] = 0
    idx = [true] * ndim
    idx[axis] = bit.where
    self[*idx].copy
  else
    bit = Bit.ones(size)
    bit[indice] = 0
    self[bit.where].copy
  end
end

#diag(k = 0) ⇒ Object

Return a matrix whose diagonal is constructed by self along the last axis.



1040
1041
1042
1043
1044
1045
1046
# File 'lib/numo/narray/extra.rb', line 1040

def diag(k = 0)
  *shp, n = shape
  n += k.abs
  a = self.class.zeros(*shp, n, n)
  a.diagonal(k).store(self)
  a
end

#diag_indices(k = 0) ⇒ Object

Return the k-th diagonal indices.

Raises:



1025
1026
1027
1028
1029
1030
# File 'lib/numo/narray/extra.rb', line 1025

def diag_indices(k = 0)
  raise NArray::ShapeError, 'must be >= 2-dimensional array' if ndim < 2

  m, n = shape[-2..]
  NArray.diag_indices(m, n, k)
end

#diagonal([offset,axes]) ⇒ Numo::NArray

Returns a diagonal view of NArray

Examples:

a = Numo::DFloat.new(4,5).seq
# => Numo::DFloat#shape=[4,5]
# [[0, 1, 2, 3, 4],
#  [5, 6, 7, 8, 9],
#  [10, 11, 12, 13, 14],
#  [15, 16, 17, 18, 19]]
b = a.diagonal(1)
# => Numo::DFloat(view)#shape=[4]
# [1, 7, 13, 19]

b.store(0)
a
# => Numo::DFloat#shape=[4,5]
# [[0, 0, 2, 3, 4],
#  [5, 6, 0, 8, 9],
#  [10, 11, 12, 0, 14],
#  [15, 16, 17, 18, 0]]

b.store([1,2,3,4])
a
# => Numo::DFloat#shape=[4,5]
# [[0, 1, 2, 3, 4],
#  [5, 6, 2, 8, 9],
#  [10, 11, 12, 3, 14],
#  [15, 16, 17, 18, 4]]

Returns diagonal view of NArray.

Parameters:

  • offset (Integer)

    Diagonal offset from the main diagonal. The default is 0. k>0 for diagonals above the main diagonal, and k<0 for diagonals below the main diagonal.

  • axes (Array)

    Array of axes to be used as the 2-d sub-arrays from which the diagonals should be taken. Defaults to last-two axes ([-2,-1]).

Returns:



580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
# File 'ext/numo/narray/data.c', line 580

static VALUE na_diagonal(int argc, VALUE* argv, VALUE self) {
  int i, k, nd;
  size_t j;
  size_t *idx0, *idx1, *diag_idx;
  size_t* shape;
  size_t diag_size;
  ssize_t stride, stride0, stride1;
  narray_t* na;
  narray_view_t *na1, *na2;
  VALUE view;
  VALUE vofs = 0, vaxes = 0;
  ssize_t kofs;
  size_t k0, k1;
  int ax[2];

  // check arguments
  if (argc > 2) {
    rb_raise(rb_eArgError, "too many arguments (%d for 0..2)", argc);
  }

  for (i = 0; i < argc; i++) {
    switch (TYPE(argv[i])) {
    case T_FIXNUM:
      if (vofs) {
        rb_raise(rb_eArgError, "offset is given twice");
      }
      vofs = argv[i];
      break;
    case T_ARRAY:
      if (vaxes) {
        rb_raise(rb_eArgError, "axes-array is given twice");
      }
      vaxes = argv[i];
      break;
    }
  }

  if (vofs) {
    kofs = NUM2SSIZET(vofs);
  } else {
    kofs = 0;
  }

  GetNArray(self, na);
  nd = na->ndim;
  if (nd < 2) {
    rb_raise(nary_eDimensionError, "less than 2-d array");
  }

  if (vaxes) {
    if (RARRAY_LEN(vaxes) != 2) {
      rb_raise(rb_eArgError, "axes must be 2-element array");
    }
    ax[0] = NUM2INT(RARRAY_AREF(vaxes, 0));
    ax[1] = NUM2INT(RARRAY_AREF(vaxes, 1));
    if (ax[0] < -nd || ax[0] >= nd || ax[1] < -nd || ax[1] >= nd) {
      rb_raise(rb_eArgError, "axis out of range:[%d,%d]", ax[0], ax[1]);
    }
    if (ax[0] < 0) {
      ax[0] += nd;
    }
    if (ax[1] < 0) {
      ax[1] += nd;
    }
    if (ax[0] == ax[1]) {
      rb_raise(rb_eArgError, "same axes:[%d,%d]", ax[0], ax[1]);
    }
  } else {
    ax[0] = nd - 2;
    ax[1] = nd - 1;
  }

  // Diagonal offset from the main diagonal.
  if (kofs >= 0) {
    k0 = 0;
    k1 = kofs;
    if (k1 >= na->shape[ax[1]]) {
      rb_raise(
        rb_eArgError,
        "invalid diagonal offset(%" SZF "d) for "
        "last dimension size(%" SZF "d)",
        kofs, na->shape[ax[1]]
      );
    }
  } else {
    k0 = -kofs;
    k1 = 0;
    if (k0 >= na->shape[ax[0]]) {
      rb_raise(
        rb_eArgError,
        "invalid diagonal offset(=%" SZF "d) for "
        "last-1 dimension size(%" SZF "d)",
        kofs, na->shape[ax[0]]
      );
    }
  }

  diag_size = MIN(na->shape[ax[0]] - k0, na->shape[ax[1]] - k1);

  // new shape
  shape = ALLOCA_N(size_t, nd - 1);
  for (i = k = 0; i < nd; i++) {
    if (i != ax[0] && i != ax[1]) {
      shape[k++] = na->shape[i];
    }
  }
  shape[k] = diag_size;

  // new object
  view = na_s_allocate_view(rb_obj_class(self));
  na_copy_flags(self, view);
  GetNArrayView(view, na2);

  // new stride
  na_setup_shape((narray_t*)na2, nd - 1, shape);
  na2->stridx = ALLOC_N(stridx_t, nd - 1);

  switch (na->type) {
  case NARRAY_DATA_T:
  case NARRAY_FILEMAP_T:
    na2->offset = 0;
    na2->data = self;
    stride = stride0 = stride1 = nary_element_stride(self);
    for (i = nd, k = nd - 2; i--;) {
      if (i == ax[1]) {
        stride1 = stride;
        if (kofs > 0) {
          na2->offset = kofs * stride;
        }
      } else if (i == ax[0]) {
        stride0 = stride;
        if (kofs < 0) {
          na2->offset = (-kofs) * stride;
        }
      } else {
        SDX_SET_STRIDE(na2->stridx[--k], stride);
      }
      stride *= na->shape[i];
    }
    SDX_SET_STRIDE(na2->stridx[nd - 2], stride0 + stride1);
    break;

  case NARRAY_VIEW_T:
    GetNArrayView(self, na1);
    na2->data = na1->data;
    na2->offset = na1->offset;
    for (i = k = 0; i < nd; i++) {
      if (i != ax[0] && i != ax[1]) {
        if (SDX_IS_INDEX(na1->stridx[i])) {
          idx0 = SDX_GET_INDEX(na1->stridx[i]);
          idx1 = ALLOC_N(size_t, na->shape[i]);
          for (j = 0; j < na->shape[i]; j++) {
            idx1[j] = idx0[j];
          }
          SDX_SET_INDEX(na2->stridx[k], idx1);
        } else {
          na2->stridx[k] = na1->stridx[i];
        }
        k++;
      }
    }
    if (SDX_IS_INDEX(na1->stridx[ax[0]])) {
      idx0 = SDX_GET_INDEX(na1->stridx[ax[0]]);
      diag_idx = ALLOC_N(size_t, diag_size);
      if (SDX_IS_INDEX(na1->stridx[ax[1]])) {
        idx1 = SDX_GET_INDEX(na1->stridx[ax[1]]);
        for (j = 0; j < diag_size; j++) {
          diag_idx[j] = idx0[j + k0] + idx1[j + k1];
        }
      } else {
        stride1 = SDX_GET_STRIDE(na1->stridx[ax[1]]);
        for (j = 0; j < diag_size; j++) {
          diag_idx[j] = idx0[j + k0] + stride1 * (j + k1);
        }
      }
      SDX_SET_INDEX(na2->stridx[nd - 2], diag_idx);
    } else {
      stride0 = SDX_GET_STRIDE(na1->stridx[ax[0]]);
      if (SDX_IS_INDEX(na1->stridx[ax[1]])) {
        idx1 = SDX_GET_INDEX(na1->stridx[ax[1]]);
        diag_idx = ALLOC_N(size_t, diag_size);
        for (j = 0; j < diag_size; j++) {
          diag_idx[j] = stride0 * (j + k0) + idx1[j + k1];
        }
        SDX_SET_INDEX(na2->stridx[nd - 2], diag_idx);
      } else {
        stride1 = SDX_GET_STRIDE(na1->stridx[ax[1]]);
        na2->offset += stride0 * k0 + stride1 * k1;
        SDX_SET_STRIDE(na2->stridx[nd - 2], stride0 + stride1);
      }
    }
    break;
  }
  return view;
}

#diff(n = 1, axis: -1)) ⇒ Object

Calculate the n-th discrete difference along given axis.

Examples:

x = Numo::DFloat[1, 2, 4, 7, 0]
# => Numo::DFloat#shape=[5]
# [1, 2, 4, 7, 0]

x.diff
# => Numo::DFloat#shape=[4]
# [1, 2, 3, -7]

x.diff(2)
# => Numo::DFloat#shape=[3]
# [1, 1, -10]

x = Numo::DFloat[[1, 3, 6, 10], [0, 5, 6, 8]]
# => Numo::DFloat#shape=[2,4]
# [[1, 3, 6, 10],
#  [0, 5, 6, 8]]

x.diff
# => Numo::DFloat#shape=[2,3]
# [[2, 3, 4],
#  [5, 1, 2]]

x.diff(axis:0)
# => Numo::DFloat#shape=[1,4]
# [[-1, 2, 0, -2]]

Raises:



925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
# File 'lib/numo/narray/extra.rb', line 925

def diff(n = 1, axis: -1)
  axis = check_axis(axis)
  raise ShapeError, "n=#{n} is invalid for shape[#{axis}]=#{shape[axis]}" if n < 0 || n >= shape[axis]

  # calculate polynomial coefficient
  c = self.class[-1, 1]
  2.upto(n) do |i|
    x = self.class.zeros(i + 1)
    x[0..-2] = c
    y = self.class.zeros(i + 1)
    y[1..-1] = c
    c = y - x
  end
  s = [true] * ndim
  s[axis] = n..-1
  result = self[*s].dup
  sum = result.inplace
  (n - 1).downto(0) do |i|
    s = [true] * ndim
    s[axis] = i..(-n - 1 + i)
    sum + (self[*s] * c[i]) # inplace addition
  end
  result
end

#dot(b) ⇒ Numo::NArray

Dot product of two arrays.

Parameters:

Returns:



1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
# File 'lib/numo/narray/extra.rb', line 1145

def dot(b)
  t = self.class::UPCAST[b.class]
  if defined?(Linalg) && [SFloat, DFloat, SComplex, DComplex].include?(t)
    Linalg.dot(self, b)
  else
    b = self.class.asarray(b)
    case b.ndim
    when 1
      mulsum(b, axis: -1)
    else
      case ndim
      when 0
        b.mulsum(self, axis: -2)
      when 1
        self[true, :new].mulsum(b, axis: -2)
      else
        unless @@warn_slow_dot
          nx = 200
          ns = 200_000
          am, an = shape[-2..]
          bm, bn = b.shape[-2..]
          if am > nx && an > nx && bm > nx && bn > nx &&
             size > ns && b.size > ns
            @@warn_slow_dot = true
            warn "\nwarning: Built-in matrix dot is slow. Consider installing numo-linalg-alt gem.\n\n"
          end
        end
        self[false, :new].mulsum(b[false, :new, true, true], axis: -2)
      end
    end
  end
end

#dsplit(indices_or_sections) ⇒ Object

Split an array into multiple sub-arrays along the depth



757
758
759
# File 'lib/numo/narray/extra.rb', line 757

def dsplit(indices_or_sections)
  split(indices_or_sections, axis: 2)
end

#each_over_axis(axis = 0) ⇒ Object

Iterate over an axis

Examples:

> a = Numo::DFloat.new(2,2,2).seq
> p a
Numo::DFloat#shape=[2,2,2]
[[[0, 1],
  [2, 3]],
 [[4, 5],
  [6, 7]]]

> a.each_over_axis{|i| p i}
Numo::DFloat(view)#shape=[2,2]
[[0, 1],
 [2, 3]]
Numo::DFloat(view)#shape=[2,2]
[[4, 5],
 [6, 7]]

> a.each_over_axis(1){|i| p i}
Numo::DFloat(view)#shape=[2,2]
[[0, 1],
 [4, 5]]
Numo::DFloat(view)#shape=[2,2]
[[2, 3],
 [6, 7]]


193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/numo/narray/extra.rb', line 193

def each_over_axis(axis = 0)
  return to_enum(:each_over_axis, axis) unless block_given?

  if ndim == 0
    raise ArgumentError, "axis=#{axis} is invalid" if axis != 0

    niter = 1
  else
    axis = check_axis(axis)
    niter = shape[axis]
  end
  idx = [true] * ndim
  niter.times do |i|
    idx[axis] = i
    yield(self[*idx])
  end
  self
end

#empty?Boolean

Returns true if self.size == 0.

Returns:

  • (Boolean)


749
750
751
752
753
754
755
756
# File 'ext/numo/narray/narray.c', line 749

static VALUE na_empty_p(VALUE self) {
  narray_t* na;
  GetNArray(self, na);
  if (NA_SIZE(na) == 0) {
    return Qtrue;
  }
  return Qfalse;
}

#expand_dims(dim) ⇒ Numo::NArray #expand_dims(dim) ⇒ Object

Expand the shape of an array. Insert a new axis with size=1 at a given dimension.

Overloads:

  • #expand_dims(dim) ⇒ Numo::NArray

    Returns result narray view.

    Parameters:

    • dim (Integer)

      dimension at which new axis is inserted.

    Returns:



1036
1037
1038
1039
1040
1041
1042
1043
1044
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
# File 'ext/numo/narray/narray.c', line 1036

static VALUE na_expand_dims(VALUE self, VALUE vdim) {
  int i, j, nd, dim;
  size_t *shape, *na_shape;
  stridx_t *stridx, *na_stridx;
  narray_t* na;
  narray_view_t* na2;
  VALUE view;

  GetNArray(self, na);
  nd = na->ndim;

  dim = NUM2INT(vdim);
  if (dim < -nd - 1 || dim > nd) {
    rb_raise(nary_eDimensionError, "invalid axis (%d for %dD NArray)", dim, nd);
  }
  if (dim < 0) {
    dim += nd + 1;
  }

  view = na_make_view(self);
  GetNArrayView(view, na2);

  shape = ALLOC_N(size_t, nd + 1);
  stridx = ALLOC_N(stridx_t, nd + 1);
  na_shape = na2->base.shape;
  na_stridx = na2->stridx;

  for (i = j = 0; i <= nd; i++) {
    if (i == dim) {
      shape[i] = 1;
      SDX_SET_STRIDE(stridx[i], 0);
    } else {
      shape[i] = na_shape[j];
      stridx[i] = na_stridx[j];
      j++;
    }
  }

  na2->stridx = stridx;
  xfree(na_stridx);
  na2->base.shape = shape;
  if (na_shape != &(na2->base.size)) {
    xfree(na_shape);
  }
  na2->base.ndim++;
  return view;
}

#flattenObject

deprecated



534
535
536
537
# File 'ext/numo/narray/data.c', line 534

VALUE
na_flatten(VALUE self) {
  return na_flatten_dim(self, 0);
}

#fliplrObject

Flip each row in the left/right direction. Same as ‘a[true, (-1..0).step(-1), …]`.



37
38
39
# File 'lib/numo/narray/extra.rb', line 37

def fliplr
  reverse(1)
end

#flipudObject

Flip each column in the up/down direction. Same as ‘a[(-1..0).step(-1), …]`.



43
44
45
# File 'lib/numo/narray/extra.rb', line 43

def flipud
  reverse(0)
end

#fortran_contiguous?Boolean

Returns:

  • (Boolean)


933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
# File 'ext/numo/narray/narray.c', line 933

VALUE
na_check_fortran_contiguous(VALUE self) {
  int i;
  ssize_t st0;
  narray_t* na;

  switch (RNARRAY_TYPE(self)) {
  case NARRAY_DATA_T:
  case NARRAY_FILEMAP_T:
    return Qfalse;
  case NARRAY_VIEW_T:
    GetNArray(self, na);

    // not contiguous if it has index
    for (i = 0; i < NA_NDIM(na); i++) {
      if (NA_IS_INDEX_AT(na, i)) return Qfalse;
    }

    // check f-contiguous
    st0 = nary_element_stride(self); // elmsz
    for (i = 0; i < NA_NDIM(na); i++) {
      if (NA_SHAPE(na)[i] == 1) continue;
      if (NA_STRIDE_AT(na, i) != st0) return Qfalse;
      st0 *= NA_SHAPE(na)[i];
    }
  }
  return Qtrue;
}

#freeObject

Release memory for array data. Ignored for NArray-view. This method is useful to free memory of referenced (i.e., GC does not work) but unused NArray object.



764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
# File 'ext/numo/narray/narray.c', line 764

static VALUE na_free(VALUE self) {
  narray_t* na;
  char* ptr;

  GetNArray(self, na);

  switch (NA_TYPE(na)) {
  case NARRAY_DATA_T:
    ptr = NA_DATA_PTR(na);
    if (ptr != NULL) {
      NA_DATA_PTR(na) = NULL;
      xfree(ptr);
    }
    break;
  case NARRAY_VIEW_T:
    break;
  case NARRAY_FILEMAP_T:
  default:
    rb_bug("invalid narray type : %d", NA_TYPE(na));
  }
  return self;
}

#host_order?Boolean Also known as: little_endian?, vacs_order?

Return true if not byte swapped.

Returns:

  • (Boolean)


1670
1671
1672
1673
# File 'ext/numo/narray/narray.c', line 1670

static VALUE na_host_order_p(VALUE self) {
  if (TEST_BYTE_SWAPPED(self)) return Qfalse;
  return Qtrue;
}

#hsplit(indices_or_sections) ⇒ Object

Split an array into multiple sub-arrays horizontally

Examples:

x = Numo::DFloat.new(4,4).seq
# => Numo::DFloat#shape=[4,4]
# [[0, 1, 2, 3],
#  [4, 5, 6, 7],
#  [8, 9, 10, 11],
#  [12, 13, 14, 15]]

x.hsplit(2)
# => [Numo::DFloat(view)#shape=[4,2]
# [[0, 1],
#  [4, 5],
#  [8, 9],
#  [12, 13]],
#  Numo::DFloat(view)#shape=[4,2]
# [[2, 3],
#  [6, 7],
#  [10, 11],
#  [14, 15]]]

x.hsplit([3, 6])
# => [Numo::DFloat(view)#shape=[4,3]
# [[0, 1, 2],
#  [4, 5, 6],
#  [8, 9, 10],
#  [12, 13, 14]],
#  Numo::DFloat(view)#shape=[4,1]
# [[3],
#  [7],
#  [11],
#  [15]],
#  Numo::DFloat(view)#shape=[4,0][]]


752
753
754
# File 'lib/numo/narray/extra.rb', line 752

def hsplit(indices_or_sections)
  split(indices_or_sections, axis: 1)
end

#initialize_copy(other) ⇒ Numo::NArray

Replaces the contents of self with the contents of other narray. Used in dup and clone method.

Returns self.

Parameters:

Returns:



409
410
411
412
413
414
415
416
417
# File 'ext/numo/narray/narray.c', line 409

static VALUE na_initialize_copy(VALUE self, VALUE orig) {
  narray_t* na;
  GetNArray(orig, na);

  na_setup(self, NA_NDIM(na), NA_SHAPE(na));
  na_store(self, orig);
  na_copy_flags(orig, self);
  return self;
}

#inner(b, axis: -1)) ⇒ Numo::NArray

Inner product of two arrays. Same as ‘(a*b).sum(axis:-1)`.

Parameters:

  • b (Numo::NArray)
  • axis (Integer) (defaults to: -1))

    applied axis

Returns:



1184
1185
1186
# File 'lib/numo/narray/extra.rb', line 1184

def inner(b, axis: -1)
  mulsum(b, axis: axis)
end

#inplaceNumo::NArray

Returns view of narray with inplace flagged.

Returns:



1679
1680
1681
1682
1683
1684
# File 'ext/numo/narray/narray.c', line 1679

static VALUE na_inplace(VALUE self) {
  VALUE view = self;
  view = na_make_view(self);
  SET_INPLACE(view);
  return view;
}

#inplace!Numo::NArray

Set inplace flag to self.

Returns:



1690
1691
1692
1693
# File 'ext/numo/narray/narray.c', line 1690

static VALUE na_inplace_bang(VALUE self) {
  SET_INPLACE(self);
  return self;
}

#inplace?Boolean

Return true if inplace flagged.

Returns:

  • (Boolean)


1698
1699
1700
1701
1702
1703
# File 'ext/numo/narray/narray.c', line 1698

static VALUE na_inplace_p(VALUE self) {
  if (TEST_INPLACE(self))
    return Qtrue;
  else
    return Qfalse;
}

#insert(indice, values, axis: nil) ⇒ Object

Insert values along the axis before the indices.

Examples:

a = Numo::DFloat[[1, 2], [3, 4]]
a = Numo::Int32[[1, 1], [2, 2], [3, 3]]

a.insert(1,5)
# => Numo::Int32#shape=[7]
# [1, 5, 1, 2, 2, 3, 3]

a.insert(1, 5, axis:1)
# => Numo::Int32#shape=[3,3]
# [[1, 5, 1],
#  [2, 5, 2],
#  [3, 5, 3]]

a.insert([1], [[11],[12],[13]], axis:1)
# => Numo::Int32#shape=[3,3]
# [[1, 11, 1],
#  [2, 12, 2],
#  [3, 13, 3]]

a.insert(1, [11, 12, 13], axis:1)
# => Numo::Int32#shape=[3,3]
# [[1, 11, 1],
#  [2, 12, 2],
#  [3, 13, 3]]

a.insert([1], [11, 12, 13], axis:1)
# => Numo::Int32#shape=[3,5]
# [[1, 11, 12, 13, 1],
#  [2, 11, 12, 13, 2],
#  [3, 11, 12, 13, 3]]

b = a.flatten
# => Numo::Int32(view)#shape=[6]
# [1, 1, 2, 2, 3, 3]

b.insert(2,[15,16])
# => Numo::Int32#shape=[8]
# [1, 1, 15, 16, 2, 2, 3, 3]

b.insert([2,2],[15,16])
# => Numo::Int32#shape=[8]
# [1, 1, 15, 16, 2, 2, 3, 3]

b.insert([2,1],[15,16])
# => Numo::Int32#shape=[8]
# [1, 16, 1, 15, 2, 2, 3, 3]

b.insert([2,0,1],[15,16,17])
# => Numo::Int32#shape=[9]
# [16, 1, 17, 1, 15, 2, 2, 3, 3]

b.insert(2..3, [15, 16])
# => Numo::Int32#shape=[8]
# [1, 1, 15, 2, 16, 2, 3, 3]

b.insert(2, [7.13, 0.5])
# => Numo::Int32#shape=[8]
# [1, 1, 7, 0, 2, 2, 3, 3]

x = Numo::DFloat.new(2,4).seq
# => Numo::DFloat#shape=[2,4]
# [[0, 1, 2, 3],
#  [4, 5, 6, 7]]

x.insert([1,3],999,axis:1)
# => Numo::DFloat#shape=[2,6]
# [[0, 999, 1, 2, 999, 3],
#  [4, 999, 5, 6, 999, 7]]


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
# File 'lib/numo/narray/extra.rb', line 349

def insert(indice, values, axis: nil)
  if axis
    values = self.class.asarray(values)
    nd = values.ndim
    midx = ([:new] * (ndim - nd)) + ([true] * nd)
    case indice
    when Numeric
      midx[-nd - 1] = true
      midx[axis] = :new
    end
    values = values[*midx]
  else
    values = self.class.asarray(values).flatten
  end
  idx = Int64.asarray(indice)
  nidx = idx.size
  if nidx == 1
    nidx = values.shape[axis || 0]
    idx += Int64.new(nidx).seq
  else
    sidx = idx.sort_index
    idx[sidx] += Int64.new(nidx).seq
  end
  if axis
    bit = Bit.ones(shape[axis] + nidx)
    bit[idx] = 0
    new_shape = shape
    new_shape[axis] += nidx
    a = self.class.zeros(new_shape)
    mdidx = [true] * ndim
    mdidx[axis] = bit.where
    a[*mdidx] = self
    mdidx[axis] = idx
    a[*mdidx] = values
  else
    bit = Bit.ones(size + nidx)
    bit[idx] = 0
    a = self.class.zeros(size + nidx)
    a[bit.where] = flatten
    a[idx] = values
  end
  a
end

#kron(b) ⇒ Numo::NArray

Kronecker product of two arrays.

kron(a,b)[k_0, k_1, ...] = a[i_0, i_1, ...] * b[j_0, j_1, ...]
   where:  k_n = i_n * b.shape[n] + j_n

Examples:

Numo::DFloat[1,10,100].kron([5,6,7])
# => Numo::DFloat#shape=[9]
# [5, 6, 7, 50, 60, 70, 500, 600, 700]

Numo::DFloat[5,6,7].kron([1,10,100])
# => Numo::DFloat#shape=[9]
# [5, 50, 500, 6, 60, 600, 7, 70, 700]

Numo::DFloat.eye(2).kron(Numo::DFloat.ones(2,2))
# => Numo::DFloat#shape=[4,4]
# [[1, 1, 0, 0],
#  [1, 1, 0, 0],
#  [0, 0, 1, 1],
#  [0, 0, 1, 1]]

Parameters:

Returns:



1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
# File 'lib/numo/narray/extra.rb', line 1280

def kron(b)
  b = NArray.cast(b)
  nda = ndim
  ndb = b.ndim
  shpa = shape
  shpb = b.shape
  adim = ([:new] * (2 * [ndb - nda, 0].max)) + ([true, :new] * nda)
  bdim = ([:new] * (2 * [nda - ndb, 0].max)) + ([:new, true] * ndb)
  shpr = (-[nda, ndb].max..-1).map { |i| (shpa[i] || 1) * (shpb[i] || 1) }
  (self[*adim] * b[*bdim]).reshape(*shpr)
end

#marshal_dumpArray

Dump marshal data.

Returns Array containing marshal data.

Returns:

  • (Array)

    Array containing marshal data.



1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
# File 'ext/numo/narray/narray.c', line 1390

static VALUE nary_marshal_dump(VALUE self) {
  VALUE a;

  a = rb_ary_new();
  rb_ary_push(a, INT2FIX(1)); // version
  rb_ary_push(a, na_shape(self));
  rb_ary_push(a, INT2FIX(NA_FLAG0(self)));
  if (rb_obj_class(self) == numo_cRObject) {
    narray_t* na;
    VALUE* ptr;
    size_t offset = 0;
    GetNArray(self, na);
    if (na->type == NARRAY_VIEW_T) {
      if (na_check_contiguous(self) == Qtrue) {
        offset = NA_VIEW_OFFSET(na);
      } else {
        self = rb_funcall(self, id_dup, 0);
      }
    }
    ptr = (VALUE*)na_get_pointer_for_read(self);
    rb_ary_push(a, rb_ary_new4(NA_SIZE(na), ptr + offset));
  } else {
    rb_ary_push(a, nary_to_binary(self));
  }
  RB_GC_GUARD(self);
  return a;
}

#marshal_load(data) ⇒ nil

Load marshal data.

Parameters:

  • Array (Array)

    containing marshal data.

Returns:

  • (nil)


1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
# File 'ext/numo/narray/narray.c', line 1425

static VALUE nary_marshal_load(VALUE self, VALUE a) {
  VALUE v;

  if (TYPE(a) != T_ARRAY) {
    rb_raise(rb_eArgError, "marshal argument should be array");
  }
  if (RARRAY_LEN(a) != 4) {
    rb_raise(rb_eArgError, "marshal array size should be 4");
  }
  if (RARRAY_AREF(a, 0) != INT2FIX(1)) {
    rb_raise(
      rb_eArgError,
      "NArray marshal version %d is not supported "
      "(only version 1)",
      NUM2INT(RARRAY_AREF(a, 0))
    );
  }
  na_initialize(self, RARRAY_AREF(a, 1));
  NA_FL0_SET(self, FIX2INT(RARRAY_AREF(a, 2)));
  v = RARRAY_AREF(a, 3);
  if (rb_obj_class(self) == numo_cRObject) {
    narray_t* na;
    char* ptr;
    if (TYPE(v) != T_ARRAY) {
      rb_raise(rb_eArgError, "RObject content should be array");
    }
    GetNArray(self, na);
    if (RARRAY_LEN(v) != (long)NA_SIZE(na)) {
      rb_raise(rb_eArgError, "RObject content size mismatch");
    }
    ptr = na_get_pointer_for_write(self);
    memcpy(ptr, RARRAY_PTR(v), NA_SIZE(na) * sizeof(VALUE));
  } else {
    rb_str_freeze(v);
    nary_store_binary(1, &v, self);
    if (TEST_BYTE_SWAPPED(self)) {
      rb_funcall(na_inplace(self), id_to_host, 0);
      REVERSE_ENDIAN(self); // correct behavior??
    }
  }
  RB_GC_GUARD(a);
  return self;
}

#ndimObject Also known as: rank

method: size() – returns the total number of typeents



739
740
741
742
743
# File 'ext/numo/narray/narray.c', line 739

static VALUE na_ndim(VALUE self) {
  narray_t* na;
  GetNArray(self, na);
  return INT2NUM(na->ndim);
}

#new_fill(value) ⇒ Object

Return an array filled with value with the same shape and type as self.



21
22
23
# File 'lib/numo/narray/extra.rb', line 21

def new_fill(value)
  self.class.new(*shape).fill(value)
end

#new_narrayObject

Return an unallocated array with the same shape and type as self.



6
7
8
# File 'lib/numo/narray/extra.rb', line 6

def new_narray
  self.class.new(*shape)
end

#new_onesObject

Return an array of ones with the same shape and type as self.



16
17
18
# File 'lib/numo/narray/extra.rb', line 16

def new_ones
  self.class.ones(*shape)
end

#new_zerosObject

Return an array of zeros with the same shape and type as self.



11
12
13
# File 'lib/numo/narray/extra.rb', line 11

def new_zeros
  self.class.zeros(*shape)
end

#out_of_place!Numo::NArray Also known as: not_inplace!

Unset inplace flag to self.

Returns:



1709
1710
1711
1712
# File 'ext/numo/narray/narray.c', line 1709

static VALUE na_out_of_place_bang(VALUE self) {
  UNSET_INPLACE(self);
  return self;
}

#outer(b, axis: nil) ⇒ Numo::NArray

Outer product of two arrays. Same as ‘self * b`.

Examples:

a = Numo::DFloat.ones(5)
# => Numo::DFloat#shape=[5]
# [1, 1, 1, 1, 1]

b = Numo::DFloat.linspace(-2,2,5)
# => Numo::DFloat#shape=[5]
# [-2, -1, 0, 1, 2]

a.outer(b)
# => Numo::DFloat#shape=[5,5]
# [[-2, -1, 0, 1, 2],
#  [-2, -1, 0, 1, 2],
#  [-2, -1, 0, 1, 2],
#  [-2, -1, 0, 1, 2],
#  [-2, -1, 0, 1, 2]]

Parameters:

  • b (Numo::NArray)
  • axis (Integer) (defaults to: nil)

    applied axis (default=-1)

Returns:



1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
# File 'lib/numo/narray/extra.rb', line 1211

def outer(b, axis: nil)
  b = NArray.cast(b)
  if axis.nil?
    self[false, :new] * (b.ndim == 0 ? b : b[false, :new, true])
  else
    md, nd = [ndim, b.ndim].minmax
    axis = check_axis(axis) - nd
    raise ArgumentError, "axis=#{axis} is out of range" if axis < -md

    adim = [true] * ndim
    adim[axis + ndim + 1, 0] = :new
    bdim = [true] * b.ndim
    bdim[axis + b.ndim, 0] = :new
    self[*adim] * b[*bdim]
  end
end

#percentile(q, axis: nil) ⇒ Numo::NArray

Percentile

Parameters:

  • q (Numo::NArray)
  • axis (Integer) (defaults to: nil)

    applied axis

Returns:

Raises:

  • (ArgumentError)


1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
# File 'lib/numo/narray/extra.rb', line 1233

def percentile(q, axis: nil)
  raise ArgumentError, 'q is out of range' if q < 0 || q > 100

  x = self
  unless axis
    axis = 0
    x = x.flatten
  end

  sorted = x.sort(axis: axis)
  x = q / 100.0 * (sorted.shape[axis] - 1)
  r = x % 1
  i = x.floor
  refs = [true] * sorted.ndim
  refs[axis] = i
  if i == sorted.shape[axis] - 1
    sorted[*refs]
  else
    refs_upper = refs.dup
    refs_upper[axis] = i + 1
    sorted[*refs] + (r * (sorted[*refs_upper] - sorted[*refs]))
  end
end

#rad2degObject

Convert angles from radians to degrees.



26
27
28
# File 'lib/numo/narray/extra.rb', line 26

def rad2deg
  self * (180 / Math::PI)
end

#repeat(arg, axis: nil) ⇒ Object

Examples:

Numo::NArray[3].repeat(4)
# => Numo::Int32#shape=[4]
# [3, 3, 3, 3]

x = Numo::NArray[[1,2],[3,4]]
# => Numo::Int32#shape=[2,2]
# [[1, 2],
#  [3, 4]]

x.repeat(2)
# => Numo::Int32#shape=[8]
# [1, 1, 2, 2, 3, 3, 4, 4]

x.repeat(3,axis:1)
# => Numo::Int32#shape=[2,6]
# [[1, 1, 1, 2, 2, 2],
#  [3, 3, 3, 4, 4, 4]]

x.repeat([1,2],axis:0)
# => Numo::Int32#shape=[3,2]
# [[1, 2],
#  [3, 4],
#  [3, 4]]


867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
# File 'lib/numo/narray/extra.rb', line 867

def repeat(arg, axis: nil)
  case axis
  when Integer
    axis = check_axis(axis)
    c = self
  when NilClass
    c = flatten
    axis = 0
  else
    raise ArgumentError, 'invalid axis'
  end
  case arg
  when Integer
    raise ArgumentError, 'argument should be positive integer' if !arg.is_a?(Integer) || arg < 1

    idx = Array.new(c.shape[axis]) { |i| [i] * arg }.flatten
  else
    arg = arg.to_a
    raise ArgumentError, 'repeat size shoud be equal to size along axis' if arg.size != c.shape[axis]

    arg.each do |i|
      raise ArgumentError, 'argument should be non-negative integer' if !i.is_a?(Integer) || i < 0
    end
    idx = arg.each_with_index.map { |a, i| [i] * a }.flatten
  end
  ref = [true] * c.ndim
  ref[axis] = idx
  c[*ref].copy
end

#reshape(size0, size1, ...) ⇒ Numo::NArray

Copy and change the shape of NArray. Returns a copied NArray.

Return self.

Parameters:

  • sizeN (Integer)

    new shape

Returns:



405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'ext/numo/narray/data.c', line 405

static VALUE na_reshape(int argc, VALUE* argv, VALUE self) {
  size_t* shape;
  narray_t* na;
  VALUE copy;

  shape = ALLOCA_N(size_t, argc);
  na_check_reshape(argc, argv, self, shape);

  copy = rb_funcall(self, rb_intern("dup"), 0);
  GetNArray(copy, na);
  na_setup_shape(na, argc, shape);
  return copy;
}

#reshape!(size0, size1, ...) ⇒ Numo::NArray

Change the shape of self NArray without coping. Raise exception if self is non-contiguous.

Return self.

Parameters:

  • sizeN (Integer)

    new shape

Returns:



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
# File 'ext/numo/narray/data.c', line 361

static VALUE na_reshape_bang(int argc, VALUE* argv, VALUE self) {
  size_t* shape;
  narray_t* na;
  narray_view_t* na2;
  ssize_t stride;
  stridx_t* stridx;
  int i;

  if (na_check_contiguous(self) == Qfalse) {
    rb_raise(rb_eStandardError, "cannot change shape of non-contiguous NArray");
  }
  shape = ALLOCA_N(size_t, argc);
  na_check_reshape(argc, argv, self, shape);

  GetNArray(self, na);
  if (na->type == NARRAY_VIEW_T) {
    GetNArrayView(self, na2);
    if (na->ndim < argc) {
      stridx = ALLOC_N(stridx_t, argc);
    } else {
      stridx = na2->stridx;
    }
    stride = SDX_GET_STRIDE(na2->stridx[na->ndim - 1]);
    for (i = argc; i--;) {
      SDX_SET_STRIDE(stridx[i], stride);
      stride *= shape[i];
    }
    if (stridx != na2->stridx) {
      xfree(na2->stridx);
      na2->stridx = stridx;
    }
  }
  na_setup_shape(na, argc, shape);
  return self;
}

#reverse([dim0,dim1,..]) ⇒ Object

Return reversed view along specified dimeinsion



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
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
# File 'ext/numo/narray/narray.c', line 1092

static VALUE nary_reverse(int argc, VALUE* argv, VALUE self) {
  int i, nd;
  size_t j, n;
  size_t offset;
  size_t *idx1, *idx2;
  ssize_t stride;
  ssize_t sign;
  narray_t* na;
  narray_view_t *na1, *na2;
  VALUE view;
  VALUE reduce;

  reduce = na_reduce_dimension(argc, argv, 1, &self, 0, 0);

  GetNArray(self, na);
  nd = na->ndim;

  view = na_s_allocate_view(rb_obj_class(self));

  na_copy_flags(self, view);
  GetNArrayView(view, na2);

  na_setup_shape((narray_t*)na2, nd, na->shape);
  na2->stridx = ALLOC_N(stridx_t, nd);

  switch (na->type) {
  case NARRAY_DATA_T:
  case NARRAY_FILEMAP_T:
    stride = nary_element_stride(self);
    offset = 0;
    for (i = nd; i--;) {
      if (na_test_reduce(reduce, i)) {
        offset += (na->shape[i] - 1) * stride;
        sign = -1;
      } else {
        sign = 1;
      }
      SDX_SET_STRIDE(na2->stridx[i], stride * sign);
      stride *= na->shape[i];
    }
    na2->offset = offset;
    na2->data = self;
    break;
  case NARRAY_VIEW_T:
    GetNArrayView(self, na1);
    offset = na1->offset;
    for (i = 0; i < nd; i++) {
      n = na1->base.shape[i];
      if (SDX_IS_INDEX(na1->stridx[i])) {
        idx1 = SDX_GET_INDEX(na1->stridx[i]);
        idx2 = ALLOC_N(size_t, n);
        if (na_test_reduce(reduce, i)) {
          for (j = 0; j < n; j++) {
            idx2[n - 1 - j] = idx1[j];
          }
        } else {
          for (j = 0; j < n; j++) {
            idx2[j] = idx1[j];
          }
        }
        SDX_SET_INDEX(na2->stridx[i], idx2);
      } else {
        stride = SDX_GET_STRIDE(na1->stridx[i]);
        if (na_test_reduce(reduce, i)) {
          offset += (n - 1) * stride;
          SDX_SET_STRIDE(na2->stridx[i], -stride);
        } else {
          na2->stridx[i] = na1->stridx[i];
        }
      }
    }
    na2->offset = offset;
    na2->data = na1->data;
    break;
  }

  return view;
}

#rot90(k = 1, axes = [0, 1]) ⇒ Object

Rotate in the plane specified by axes.

Examples:

a = Numo::Int32.new(2,2).seq
# => Numo::Int32#shape=[2,2]
# [[0, 1],
#  [2, 3]]

a.rot90
# => Numo::Int32(view)#shape=[2,2]
# [[1, 3],
#  [0, 2]]

a.rot90(2)
# => Numo::Int32(view)#shape=[2,2]
# [[3, 2],
#  [1, 0]]

a.rot90(3)
# => Numo::Int32(view)#shape=[2,2]
# [[2, 0],
#  [3, 1]]


68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/numo/narray/extra.rb', line 68

def rot90(k = 1, axes = [0, 1])
  case k % 4
  when 0
    view
  when 1
    swapaxes(*axes).reverse(axes[0])
  when 2
    reverse(*axes)
  when 3
    swapaxes(*axes).reverse(axes[1])
  end
end

#row_major?Boolean

Return true if row major.

Returns:

  • (Boolean)


1652
1653
1654
1655
1656
1657
# File 'ext/numo/narray/narray.c', line 1652

static VALUE na_row_major_p(VALUE self) {
  if (TEST_ROW_MAJOR(self))
    return Qtrue;
  else
    return Qfalse;
}

#shapeObject

method: shape() – returns shape, array of the size of dimensions



788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
# File 'ext/numo/narray/narray.c', line 788

static VALUE na_shape(VALUE self) {
  volatile VALUE v;
  narray_t* na;
  size_t i, n, c, s;

  GetNArray(self, na);
  n = NA_NDIM(na);
  if (TEST_COLUMN_MAJOR(self)) {
    c = n - 1;
    s = -1;
  } else {
    c = 0;
    s = 1;
  }
  v = rb_ary_new2(n);
  for (i = 0; i < n; i++) {
    rb_ary_push(v, SIZET2NUM(na->shape[c]));
    c += s;
  }
  return v;
}

#sizeObject Also known as: length, total

method: size() – returns the total number of typeents



732
733
734
735
736
# File 'ext/numo/narray/narray.c', line 732

static VALUE na_size(VALUE self) {
  narray_t* na;
  GetNArray(self, na);
  return SIZET2NUM(na->size);
}

#split(indices_or_sections, axis: 0) ⇒ Object

Examples:

x = Numo::DFloat.new(9).seq
# => Numo::DFloat#shape=[9]
# [0, 1, 2, 3, 4, 5, 6, 7, 8]

x.split(3)
# => [Numo::DFloat(view)#shape=[3]
# [0, 1, 2],
#  Numo::DFloat(view)#shape=[3]
# [3, 4, 5],
#  Numo::DFloat(view)#shape=[3]
# [6, 7, 8]]

x = Numo::DFloat.new(8).seq
# => Numo::DFloat#shape=[8]
# [0, 1, 2, 3, 4, 5, 6, 7]

x.split([3, 5, 6, 10])
# => [Numo::DFloat(view)#shape=[3]
# [0, 1, 2],
#  Numo::DFloat(view)#shape=[2]
# [3, 4],
#  Numo::DFloat(view)#shape=[1]
# [5],
#  Numo::DFloat(view)#shape=[2]
# [6, 7],
#  Numo::DFloat(view)#shape=[0][]]


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
# File 'lib/numo/narray/extra.rb', line 678

def split(indices_or_sections, axis: 0)
  axis = check_axis(axis)
  size_axis = shape[axis]
  case indices_or_sections
  when Integer
    div_axis, mod_axis = size_axis.divmod(indices_or_sections)
    refs = [true] * ndim
    beg_idx = 0
    Array.new(mod_axis) do |_i|
      end_idx = beg_idx + div_axis + 1
      refs[axis] = beg_idx...end_idx
      beg_idx = end_idx
      self[*refs]
    end +
      Array.new(indices_or_sections - mod_axis) do |_i|
        end_idx = beg_idx + div_axis
        refs[axis] = beg_idx...end_idx
        beg_idx = end_idx
        self[*refs]
      end
  when NArray
    split(indices_or_sections.to_a, axis: axis)
  when Array
    refs = [true] * ndim
    fst = 0
    (indices_or_sections + [size_axis]).map do |lst|
      lst = size_axis if lst > size_axis
      refs[axis] = fst < size_axis ? fst...lst : -1...-1
      fst = lst
      self[*refs]
    end
  else
    raise TypeError, 'argument must be Integer or Array'
  end
end

#store_binary(string, [offset]) ⇒ Integer

Returns a new 1-D array initialized from binary raw data in a string.

Returns stored length.

Parameters:

  • string (String)

    Binary raw data.

  • (optional) (Integer)

    offset Byte offset in string.

Returns:

  • (Integer)

    stored length.



1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
# File 'ext/numo/narray/narray.c', line 1317

static VALUE nary_store_binary(int argc, VALUE* argv, VALUE self) {
  size_t size, str_len, byte_size, offset;
  int narg;
  VALUE vstr, voffset;
  VALUE velmsz;
  narray_t* na;

  narg = rb_scan_args(argc, argv, "11", &vstr, &voffset);
  str_len = RSTRING_LEN(vstr);
  if (narg == 2) {
    offset = NUM2SIZET(voffset);
    if (str_len < offset) {
      rb_raise(rb_eArgError, "offset is larger than string length");
    }
    str_len -= offset;
  } else {
    offset = 0;
  }

  GetNArray(self, na);
  size = NA_SIZE(na);
  velmsz = rb_const_get(rb_obj_class(self), id_element_byte_size);
  if (FIXNUM_P(velmsz)) {
    byte_size = size * NUM2SIZET(velmsz);
  } else {
    byte_size = ceil(size * NUM2DBL(velmsz));
  }
  if (byte_size > str_len) {
    rb_raise(rb_eArgError, "string is too short to store");
  }

  if (OBJ_FROZEN(vstr)) {
    na_set_pointer(self, RSTRING_PTR(vstr) + offset, byte_size);
    rb_ivar_set(self, id_source, vstr);
  } else {
    void* ptr = na_get_pointer_for_write(self);
    memcpy(ptr, RSTRING_PTR(vstr) + offset, byte_size);
  }

  return SIZET2NUM(byte_size);
}

#swap_byteObject Also known as: hton



102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'ext/numo/narray/data.c', line 102

static VALUE nary_swap_byte(VALUE self) {
  VALUE v;
  ndfunc_arg_in_t ain[1] = { { Qnil, 0 } };
  ndfunc_arg_out_t aout[1] = { { INT2FIX(0), 0 } };
  ndfunc_t ndf = { iter_swap_byte, FULL_LOOP | NDF_ACCEPT_BYTESWAP, 1, 1, ain, aout };

  v = na_ndloop(&ndf, 1, self);
  if (self != v) {
    na_copy_flags(self, v);
  }
  REVERSE_ENDIAN(v);
  return v;
}

#swapaxes(axis1, axis2) ⇒ Numo::NArray

Interchange two axes.

Examples:

x = Numo::Int32[[1,2,3]]

x.swapaxes(0,1)
# => Numo::Int32(view)#shape=[3,1]
# [[1],
#  [2],
#  [3]]

x = Numo::Int32[[[0,1],[2,3]],[[4,5],[6,7]]]
# => Numo::Int32#shape=[2,2,2]
# [[[0, 1],
#   [2, 3]],
#  [[4, 5],
#   [6, 7]]]

x.swapaxes(0,2)
# => Numo::Int32(view)#shape=[2,2,2]
# [[[0, 4],
#   [2, 6]],
#  [[1, 5],
#   [3, 7]]]

Returns view of NArray.

Parameters:

  • axis1 (Integer)
  • axis2 (Integer)

Returns:



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'ext/numo/narray/data.c', line 185

static VALUE na_swapaxes(VALUE self, VALUE a1, VALUE a2) {
  int i, j, ndim;
  size_t tmp_shape;
  stridx_t tmp_stridx;
  narray_view_t* na;
  volatile VALUE view;

  view = na_make_view(self);
  GetNArrayView(view, na);

  ndim = na->base.ndim;
  i = check_axis(NUM2INT(a1), ndim);
  j = check_axis(NUM2INT(a2), ndim);

  tmp_shape = na->base.shape[i];
  tmp_stridx = na->stridx[i];
  na->base.shape[i] = na->base.shape[j];
  na->stridx[i] = na->stridx[j];
  na->base.shape[j] = tmp_shape;
  na->stridx[j] = tmp_stridx;

  return view;
}

#tile(*arg) ⇒ Object

Examples:

a = Numo::NArray[0,1,2]
# => Numo::Int32#shape=[3]
# [0, 1, 2]

a.tile(2)
# => Numo::Int32#shape=[6]
# [0, 1, 2, 0, 1, 2]

a.tile(2,2)
# => Numo::Int32#shape=[2,6]
# [[0, 1, 2, 0, 1, 2],
#  [0, 1, 2, 0, 1, 2]]

a.tile(2,1,2)
# => Numo::Int32#shape=[2,1,6]
# [[[0, 1, 2, 0, 1, 2]],
#  [[0, 1, 2, 0, 1, 2]]]

b = Numo::NArray[[1, 2], [3, 4]]
# => Numo::Int32#shape=[2,2]
# [[1, 2],
#  [3, 4]]

b.tile(2)
# => Numo::Int32#shape=[2,4]
# [[1, 2, 1, 2],
#  [3, 4, 3, 4]]

b.tile(2,1)
# => Numo::Int32#shape=[4,2]
# [[1, 2],
#  [3, 4],
#  [1, 2],
#  [3, 4]]

c = Numo::NArray[1,2,3,4]
# => Numo::Int32#shape=[4]
# [1, 2, 3, 4]

c.tile(4,1)
# => Numo::Int32#shape=[4,4]
# [[1, 2, 3, 4],
#  [1, 2, 3, 4],
#  [1, 2, 3, 4],
#  [1, 2, 3, 4]]


808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
# File 'lib/numo/narray/extra.rb', line 808

def tile(*arg)
  arg.each do |i|
    raise ArgumentError, 'argument should be positive integer' if !i.is_a?(Integer) || i < 1
  end
  ns = arg.size
  nd = ndim
  shp = shape
  new_shp = []
  src_shp = []
  res_shp = []
  (nd - ns).times do
    new_shp << 1
    new_shp << (n = shp.shift)
    src_shp << :new
    src_shp << true
    res_shp << n
  end
  (ns - nd).times do
    new_shp << (m = arg.shift)
    new_shp << 1
    src_shp << :new
    src_shp << :new
    res_shp << m
  end
  [nd, ns].min.times do
    new_shp << (m = arg.shift)
    new_shp << (n = shp.shift)
    src_shp << :new
    src_shp << true
    res_shp << (n * m)
  end
  self.class.new(*new_shp).store(self[*src_shp]).reshape(*res_shp)
end

#to_binaryString Also known as: to_string

Returns string containing the raw data bytes in NArray.

Returns String object containing binary raw data.

Returns:

  • (String)

    String object containing binary raw data.



1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
# File 'ext/numo/narray/narray.c', line 1364

static VALUE nary_to_binary(VALUE self) {
  size_t len, offset = 0;
  char* ptr;
  VALUE str;
  narray_t* na;

  GetNArray(self, na);
  if (na->type == NARRAY_VIEW_T) {
    if (na_check_contiguous(self) == Qtrue) {
      offset = NA_VIEW_OFFSET(na);
    } else {
      self = rb_funcall(self, id_dup, 0);
    }
  }
  len = NUM2SIZET(nary_byte_size(self));
  ptr = na_get_pointer_for_read(self);
  str = rb_usascii_str_new(ptr + offset, len);
  RB_GC_GUARD(self);
  return str;
}

#to_cObject

Raises:

  • (TypeError)


95
96
97
98
99
100
# File 'lib/numo/narray/extra.rb', line 95

def to_c
  # convert to DComplex?
  raise TypeError, "can't convert #{self.class} into Complex" unless size == 1

  Complex(self[0])
end

#to_fObject

Raises:

  • (TypeError)


88
89
90
91
92
93
# File 'lib/numo/narray/extra.rb', line 88

def to_f
  # convert to DFloat?
  raise TypeError, "can't convert #{self.class} into Float" unless size == 1

  self[0].to_f
end

#to_hostObject



130
131
132
133
134
135
# File 'ext/numo/narray/data.c', line 130

static VALUE nary_to_host(VALUE self) {
  if (TEST_HOST_ORDER(self)) {
    return self;
  }
  return rb_funcall(self, id_swap_byte, 0);
}

#to_iObject

Raises:

  • (TypeError)


81
82
83
84
85
86
# File 'lib/numo/narray/extra.rb', line 81

def to_i
  # convert to Int?
  raise TypeError, "can't convert #{self.class} into Integer" unless size == 1

  self[0].to_i
end

#to_networkObject



116
117
118
119
120
121
# File 'ext/numo/narray/data.c', line 116

static VALUE nary_to_network(VALUE self) {
  if (TEST_BIG_ENDIAN(self)) {
    return self;
  }
  return rb_funcall(self, id_swap_byte, 0);
}

#to_swappedObject



137
138
139
140
141
142
# File 'ext/numo/narray/data.c', line 137

static VALUE nary_to_swapped(VALUE self) {
  if (TEST_BYTE_SWAPPED(self)) {
    return self;
  }
  return rb_funcall(self, id_swap_byte, 0);
}

#to_vacsObject



123
124
125
126
127
128
# File 'ext/numo/narray/data.c', line 123

static VALUE nary_to_vacs(VALUE self) {
  if (TEST_LITTLE_ENDIAN(self)) {
    return self;
  }
  return rb_funcall(self, id_swap_byte, 0);
}

#trace(offset = nil, axis = nil, nan: false) ⇒ Object

Return the sum along diagonals of the array.

If 2-D array, computes the summation along its diagonal with the given offset, i.e., sum of ‘a`. If more than 2-D array, the diagonal is determined from the axes specified by axis argument. The default is axis=.

Parameters:

  • offset (Integer) (defaults to: nil)

    (optional, default=0) diagonal offset

  • axis (Array) (defaults to: nil)

    (optional, default=) diagonal axis

  • nan (Bool) (defaults to: false)

    (optional, default=false) nan-aware algorithm, i.e., if true then it ignores nan.



1135
1136
1137
# File 'lib/numo/narray/extra.rb', line 1135

def trace(offset = nil, axis = nil, nan: false)
  diagonal(offset, axis).sum(nan: nan, axis: -1)
end

#transpose(*args) ⇒ Object



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

static VALUE na_transpose(int argc, VALUE* argv, VALUE self) {
  int ndim, *map, *permute;
  int i, d;
  bool is_positive, is_negative;
  narray_t* na1;

  GetNArray(self, na1);
  ndim = na1->ndim;
  if (ndim < 2) {
    if (argc > 0) {
      rb_raise(rb_eArgError, "unnecessary argument for 1-d array");
    }
    return na_make_view(self);
  }
  map = ALLOCA_N(int, ndim);
  if (argc == 0) {
    for (i = 0; i < ndim; i++) {
      map[i] = ndim - 1 - i;
    }
    return na_transpose_map(self, map);
  }
  // with argument
  if (argc > ndim) {
    rb_raise(rb_eArgError, "more arguments than ndim");
  }
  for (i = 0; i < ndim; i++) {
    map[i] = i;
  }
  permute = ALLOCA_N(int, argc);
  for (i = 0; i < argc; i++) {
    permute[i] = 0;
  }
  is_positive = is_negative = 0;
  for (i = 0; i < argc; i++) {
    if (TYPE(argv[i]) != T_FIXNUM) {
      rb_raise(rb_eArgError, "invalid argument");
    }
    d = FIX2INT(argv[i]);
    if (d >= 0) {
      if (d >= argc) {
        rb_raise(rb_eArgError, "out of dimension range");
      }
      if (is_negative) {
        rb_raise(rb_eArgError, "dimension must be non-negative only or negative only");
      }
      if (permute[d]) {
        rb_raise(rb_eArgError, "not permutation");
      }
      map[i] = d;
      permute[d] = 1;
      is_positive = 1;
    } else {
      if (d < -argc) {
        rb_raise(rb_eArgError, "out of dimension range");
      }
      if (is_positive) {
        rb_raise(rb_eArgError, "dimension must be non-negative only or negative only");
      }
      if (permute[argc + d]) {
        rb_raise(rb_eArgError, "not permutation");
      }
      map[ndim - argc + i] = ndim + d;
      permute[argc + d] = 1;
      is_negative = 1;
    }
  }
  return na_transpose_map(self, map);
}

#tril(k = 0) ⇒ Object

Lower triangular matrix. Return a copy with the elements above the k-th diagonal filled with zero.



989
990
991
# File 'lib/numo/narray/extra.rb', line 989

def tril(k = 0)
  dup.tril!(k)
end

#tril!(k = 0) ⇒ Object

Lower triangular matrix. Fill the self elements above the k-th diagonal with zero.

Raises:



995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
# File 'lib/numo/narray/extra.rb', line 995

def tril!(k = 0)
  raise NArray::ShapeError, 'must be >= 2-dimensional array' if ndim < 2

  if contiguous?
    idx = triu_indices(k + 1)
    *shp, m, n = shape
    reshape!(*shp, m * n)
    self[false, idx] = 0
    reshape!(*shp, m, n)
  else
    store(tril(k))
  end
end

#tril_indices(k = 0) ⇒ Object

Return the indices for the lower-triangle on and below the k-th diagonal.

Raises:



1010
1011
1012
1013
1014
1015
# File 'lib/numo/narray/extra.rb', line 1010

def tril_indices(k = 0)
  raise NArray::ShapeError, 'must be >= 2-dimensional array' if ndim < 2

  m, n = shape[-2..]
  NArray.tril_indices(m, n, k)
end

#triu(k = 0) ⇒ Object

Upper triangular matrix. Return a copy with the elements below the k-th diagonal filled with zero.



952
953
954
# File 'lib/numo/narray/extra.rb', line 952

def triu(k = 0)
  dup.triu!(k)
end

#triu!(k = 0) ⇒ Object

Upper triangular matrix. Fill the self elements below the k-th diagonal with zero.

Raises:



958
959
960
961
962
963
964
965
966
967
968
969
970
# File 'lib/numo/narray/extra.rb', line 958

def triu!(k = 0)
  raise NArray::ShapeError, 'must be >= 2-dimensional array' if ndim < 2

  if contiguous?
    *shp, m, n = shape
    idx = tril_indices(k - 1)
    reshape!(*shp, m * n)
    self[false, idx] = 0
    reshape!(*shp, m, n)
  else
    store(triu(k))
  end
end

#triu_indices(k = 0) ⇒ Object

Return the indices for the upper-triangle on and above the k-th diagonal.

Raises:



973
974
975
976
977
978
# File 'lib/numo/narray/extra.rb', line 973

def triu_indices(k = 0)
  raise NArray::ShapeError, 'must be >= 2-dimensional array' if ndim < 2

  m, n = shape[-2..]
  NArray.triu_indices(m, n, k)
end

#viewObject

Return view of NArray



970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
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 'ext/numo/narray/narray.c', line 970

VALUE
na_make_view(VALUE self) {
  int i, nd;
  size_t j;
  size_t *idx1, *idx2;
  ssize_t stride;
  narray_t* na;
  narray_view_t *na1, *na2;
  volatile VALUE view;

  GetNArray(self, na);
  nd = na->ndim;

  view = na_s_allocate_view(rb_obj_class(self));

  na_copy_flags(self, view);
  GetNArrayView(view, na2);

  na_setup_shape((narray_t*)na2, nd, na->shape);
  na2->stridx = ALLOC_N(stridx_t, nd);

  switch (na->type) {
  case NARRAY_DATA_T:
  case NARRAY_FILEMAP_T:
    stride = nary_element_stride(self);
    for (i = nd; i--;) {
      SDX_SET_STRIDE(na2->stridx[i], stride);
      stride *= na->shape[i];
    }
    na2->offset = 0;
    na2->data = self;
    break;
  case NARRAY_VIEW_T:
    GetNArrayView(self, na1);
    for (i = 0; i < nd; i++) {
      if (SDX_IS_INDEX(na1->stridx[i])) {
        idx1 = SDX_GET_INDEX(na1->stridx[i]);
        idx2 = ALLOC_N(size_t, na1->base.shape[i]);
        for (j = 0; j < na1->base.shape[i]; j++) {
          idx2[j] = idx1[j];
        }
        SDX_SET_INDEX(na2->stridx[i], idx2);
      } else {
        na2->stridx[i] = na1->stridx[i];
      }
    }
    na2->offset = na1->offset;
    na2->data = na1->data;
    break;
  }

  return view;
}

#vsplit(indices_or_sections) ⇒ Object

Split an array into multiple sub-arrays vertically



715
716
717
# File 'lib/numo/narray/extra.rb', line 715

def vsplit(indices_or_sections)
  split(indices_or_sections, axis: 0)
end