Class: Cumo::NArray
- Inherits:
-
Object
- Object
- Cumo::NArray
- Defined in:
- ext/cumo/narray/narray.c,
lib/cumo/narray/extra.rb
Overview
Cumo::NArray is the abstract super class for Numerical N-dimensional Array in the Ruby/Cumo module. Use Typed Subclasses of NArray (Cumo::DFloat, Int32, etc) to create data array instances.
Constant Summary collapse
- @@warn_slow_dot =
false
Class Method Summary collapse
- .asarray(a) ⇒ Object
-
.cast(a) ⇒ Object
Convert the argument to an narray if not an narray.
-
.column_stack(arrays) ⇒ Object
Stack 1-d arrays into columns of a 2-d array.
- .concatenate(arrays, axis: 0) ⇒ Object
-
.diag_indices(m, n, k = 0) ⇒ Object
Return the k-th diagonal indices.
-
.dstack(arrays) ⇒ Object
Stack arrays in depth wise (along third axis).
-
.hstack(arrays) ⇒ Object
Stack arrays horizontally (column wise).
-
.parse(str, split1d: /\s+/, split2d: /;?$|;/, split3d: /\s*\n(\s*\n)+/m) ⇒ Object
parse matrix like matlab, octave.
-
.tril_indices(m, n, k = 0) ⇒ Object
Return the indices for the lower-triangle on and below the k-th diagonal.
-
.triu_indices(m, n, k = 0) ⇒ Object
Return the indices for the uppler-triangle on and above the k-th diagonal.
-
.vstack(arrays) ⇒ Object
Stack arrays vertically (row wise).
Instance Method Summary collapse
-
#append(other, axis: nil) ⇒ Object
Append values to the end of an narray.
-
#at(*indices) ⇒ Cumo::NArray
Multi-dimensional array indexing.
- #concatenate(*arrays, axis: 0) ⇒ Object
-
#cov(y = nil, ddof: 1, fweights: nil, aweights: nil) ⇒ Object
under construction.
-
#deg2rad ⇒ Object
Convert angles from degrees to radians.
- #delete(indice, axis = nil) ⇒ Object
-
#diag(k = 0) ⇒ Object
Return a matrix whose diagonal is constructed by self along the last axis.
-
#diag_indices(k = 0) ⇒ Object
Return the k-th diagonal indices.
-
#diff(n = 1, axis: -1)) ⇒ Object
Calculate the n-th discrete difference along given axis.
-
#dot(b) ⇒ Cumo::NArray
Dot product of two arrays.
- #dsplit(indices_or_sections) ⇒ Object
-
#each_over_axis(axis = 0) ⇒ Object
Iterate over an axis @ example > a = Cumo::DFloat.new(2,2,2).seq > p a Cumo::DFloat#shape= [[[0, 1], [2, 3]], [[4, 5], [6, 7]]].
-
#fliplr ⇒ Object
Flip each row in the left/right direction.
-
#flipud ⇒ Object
Flip each column in the up/down direction.
- #hsplit(indices_or_sections) ⇒ Object
-
#inner(b, axis: -1)) ⇒ Cumo::NArray
Inner product of two arrays.
-
#insert(indice, values, axis: nil) ⇒ Object
Insert values along the axis before the indices.
-
#kron(b) ⇒ Cumo::NArray
Kronecker product of two arrays.
-
#new_fill(value) ⇒ Object
Return an array filled with value with the same shape and type as self.
-
#new_narray ⇒ Object
Return an unallocated array with the same shape and type as self.
-
#new_ones ⇒ Object
Return an array of ones with the same shape and type as self.
-
#new_zeros ⇒ Object
Return an array of zeros with the same shape and type as self.
-
#outer(b, axis: nil) ⇒ Cumo::NArray
Outer product of two arrays.
-
#rad2deg ⇒ Object
Convert angles from radians to degrees.
- #repeat(arg, axis: nil) ⇒ Object
-
#rot90(k = 1, axes = [0,1]) ⇒ Object
Rotate in the plane specified by axes.
- #split(indices_or_sections, axis: 0) ⇒ Object
- #tile(*arg) ⇒ Object
- #to_c ⇒ Object
- #to_f ⇒ Object
- #to_i ⇒ Object
-
#trace(offset = nil, axis = nil, nan: false) ⇒ Object
Return the sum along diagonals of the array.
-
#tril(k = 0) ⇒ Object
Lower triangular matrix.
-
#tril!(k = 0) ⇒ Object
Lower triangular matrix.
-
#tril_indices(k = 0) ⇒ Object
Return the indices for the lower-triangle on and below the k-th diagonal.
-
#triu(k = 0) ⇒ Object
Upper triangular matrix.
-
#triu!(k = 0) ⇒ Object
Upper triangular matrix.
-
#triu_indices(k = 0) ⇒ Object
Return the indices for the uppler-triangle on and above the k-th diagonal.
- #vsplit(indices_or_sections) ⇒ Object
Class Method Details
.asarray(a) ⇒ Object
162 163 164 165 166 167 168 169 170 171 |
# File 'lib/cumo/narray/extra.rb', line 162 def self.asarray(a) case a when NArray (a.ndim == 0) ? a[:new] : a when Numeric,Range self[a] else cast(a) end end |
.cast(a) ⇒ Object
Convert the argument to an narray if not an narray.
158 159 160 |
# File 'lib/cumo/narray/extra.rb', line 158 def self.cast(a) a.kind_of?(NArray) ? a : NArray.array_type(a).cast(a) end |
.column_stack(arrays) ⇒ Object
Stack 1-d arrays into columns of a 2-d array.
608 609 610 611 612 613 614 615 616 617 618 |
# File 'lib/cumo/narray/extra.rb', line 608 def column_stack(arrays) arys = arrays.map do |a| a = cast(a) case a.ndim when 0; a[:new,:new] when 1; a[true,:new] else; a end end concatenate(arys,axis:1) end |
.concatenate(arrays, axis: 0) ⇒ Object
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 504 505 506 507 508 509 510 511 512 513 514 515 516 |
# File 'lib/cumo/narray/extra.rb', line 464 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 Cumo::NArray: #{a.inspect[0..48]}" end if a.ndim > nd nd = a.ndim end a end if axis < 0 axis += nd end if axis < 0 || axis >= nd raise ArgumentError,"axis is out of range" end new_shape = nil sum_size = 0 arrays.each do |a| a_shape = a.shape if nd != a_shape.size a_shape = [1]*(nd-a_shape.size) + a_shape end sum_size += a_shape.delete_at(axis) if new_shape if new_shape != a_shape raise ShapeError,"shape mismatch" end 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) refs[axis] = fst...lst result[*refs] = a end result end |
.diag_indices(m, n, k = 0) ⇒ Object
Return the k-th diagonal indices.
1098 1099 1100 1101 1102 |
# File 'lib/cumo/narray/extra.rb', line 1098 def self.diag_indices(m,n,k=0) x = Cumo::Int64.new(m,1).seq + k y = Cumo::Int64.new(1,n).seq (x.eq y).where end |
.dstack(arrays) ⇒ Object
Stack arrays in depth wise (along third axis).
591 592 593 594 595 596 |
# File 'lib/cumo/narray/extra.rb', line 591 def dstack(arrays) arys = arrays.map do |a| _atleast_3d(cast(a)) end concatenate(arys,axis:2) end |
.hstack(arrays) ⇒ Object
Stack arrays horizontally (column wise).
561 562 563 564 565 566 567 568 569 570 571 |
# File 'lib/cumo/narray/extra.rb', line 561 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 |
.parse(str, split1d: /\s+/, split2d: /;?$|;/, split3d: /\s*\n(\s*\n)+/m) ⇒ Object
parse matrix like matlab, octave
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 |
# File 'lib/cumo/narray/extra.rb', line 185 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! if !line.empty? c = [] line.split(split1d).each do |item| c << eval(item.strip) if !item.empty? end b << c if !c.empty? end end a << b if !b.empty? end if a.size==1 self.cast(a[0]) else self.cast(a) end end |
.tril_indices(m, n, k = 0) ⇒ Object
Return the indices for the lower-triangle on and below the k-th diagonal.
1082 1083 1084 1085 1086 |
# File 'lib/cumo/narray/extra.rb', line 1082 def self.tril_indices(m,n,k=0) x = Cumo::Int64.new(m,1).seq + k y = Cumo::Int64.new(1,n).seq (x>=y).where end |
.triu_indices(m, n, k = 0) ⇒ Object
Return the indices for the uppler-triangle on and above the k-th diagonal.
1043 1044 1045 1046 1047 |
# File 'lib/cumo/narray/extra.rb', line 1043 def self.triu_indices(m,n,k=0) x = Cumo::Int64.new(m,1).seq + k y = Cumo::Int64.new(1,n).seq (x<=y).where end |
.vstack(arrays) ⇒ Object
Stack arrays vertically (row wise).
538 539 540 541 542 543 |
# File 'lib/cumo/narray/extra.rb', line 538 def vstack(arrays) arys = arrays.map do |a| _atleast_2d(cast(a)) end concatenate(arys,axis:0) end |
Instance Method Details
#append(other, axis: nil) ⇒ Object
Append values to the end of an narray.
278 279 280 281 282 283 284 285 286 287 288 289 290 291 |
# File 'lib/cumo/narray/extra.rb', line 278 def append(other,axis:nil) other = self.class.cast(other) if axis if ndim != other.ndim raise DimensionError, "dimension mismatch" end return concatenate(other,axis:axis) else a = self.class.zeros(size+other.size) a[0...size] = self[true] a[size..-1] = other[true] return a end end |
#at(*indices) ⇒ Cumo::NArray
Multi-dimensional array indexing. Same as [] for one-dimensional NArray. Similar to numpy’s tuple indexing, i.e., ‘a[,[3,4,..]]` (This method will be rewritten in C)
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 |
# File 'lib/cumo/narray/extra.rb', line 67 def at(*indices) if indices.size != ndim raise DimensionError, "argument length does not match dimension size" end idx = nil stride = 1 (indices.size-1).downto(0) do |i| ix = Int64.cast(indices[i]) if ix.ndim != 1 raise DimensionError, "index array is not one-dimensional" end ix[ix < 0] += shape[i] if ((ix < 0) & (ix >= shape[i])).any? raise IndexError, "index array is out of range" end if idx if idx.size != ix.size raise ShapeError, "index array sizes mismatch" end idx += ix * stride stride *= shape[i] else idx = ix stride = shape[i] end end self[idx] end |
#concatenate(*arrays, axis: 0) ⇒ Object
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 |
# File 'lib/cumo/narray/extra.rb', line 663 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 Cumo::NArray: #{a.inspect[0..48]}" end if a.ndim > ndim raise ShapeError,"dimension mismatch" end a_shape = a.shape sum_size += a_shape.delete_at(axis-ndim) || 1 if self_shape != a_shape raise ShapeError,"shape mismatch" end a end self_shape.insert(axis,sum_size) result = self.class.zeros(*self_shape) lst = shape[axis] refs = [true] * ndim refs[axis] = 0...lst result[*refs] = self arrays.each do |a| fst = lst lst = fst + (a.shape[axis-ndim] || 1) refs[axis] = fst...lst result[*refs] = a end result end |
#cov(y = nil, ddof: 1, fweights: nil, aweights: nil) ⇒ Object
under construction
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 1309 1310 |
# File 'lib/cumo/narray/extra.rb', line 1270 def cov(y=nil, ddof:1, fweights:nil, aweights:nil) if y m = NArray.vstack([self,y]) else m = self end w = nil if fweights f = fweights w = f end if aweights a = aweights w = w ? w*a : a end if w w_sum = w.sum(axis:-1, keepdims:true) if ddof == 0 fact = w_sum elsif aweights.nil? fact = w_sum - ddof else wa_sum = (w*a).sum(axis:-1, keepdims:true) fact = w_sum - ddof * wa_sum / w_sum end if (fact <= 0).any? raise StandardError,"Degrees of freedom <= 0 for slice" end else fact = m.shape[-1] - ddof end if w m -= (m*w).sum(axis:-1, keepdims:true) / w_sum mw = m*w else m -= m.mean(axis:-1, keepdims:true) mw = m end mt = (m.ndim < 2) ? m : m.swapaxes(-2,-1) mw.dot(mt.conj) / fact end |
#deg2rad ⇒ Object
Convert angles from degrees to radians.
30 31 32 |
# File 'lib/cumo/narray/extra.rb', line 30 def deg2rad self * (Math::PI/180) end |
#delete(indice, axis = nil) ⇒ Object
313 314 315 316 317 318 319 320 321 322 323 324 325 |
# File 'lib/cumo/narray/extra.rb', line 313 def delete(indice,axis=nil) if axis bit = Bit.ones(shape[axis]) bit[indice] = 0 idx = [true]*ndim idx[axis] = bit.where return self[*idx].copy else bit = Bit.ones(size) bit[indice] = 0 return self[bit.where].copy end end |
#diag(k = 0) ⇒ Object
Return a matrix whose diagonal is constructed by self along the last axis.
1105 1106 1107 1108 1109 1110 1111 |
# File 'lib/cumo/narray/extra.rb', line 1105 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.
1089 1090 1091 1092 1093 1094 1095 |
# File 'lib/cumo/narray/extra.rb', line 1089 def diag_indices(k=0) if ndim < 2 raise NArray::ShapeError, "must be >= 2-dimensional array" end m,n = shape[-2..-1] NArray.diag_indices(m,n,k) end |
#diff(n = 1, axis: -1)) ⇒ Object
Calculate the n-th discrete difference along given axis.
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 |
# File 'lib/cumo/narray/extra.rb', line 983 def diff(n=1,axis:-1) axis = check_axis(axis) if n < 0 || n >= shape[axis] raise ShapeError,"n=#{n} is invalid for shape[#{axis}]=#{shape[axis]}" end # 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 return result end |
#dot(b) ⇒ Cumo::NArray
Dot product of two arrays.
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 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 |
# File 'lib/cumo/narray/extra.rb', line 1134 def dot(b) t = self.class::UPCAST[b.class] if self.ndim == 0 and b.ndim == 0 return self * b end if [SFloat, DFloat, SComplex, DComplex].include?(t) b = self.class.asarray(b) case self.ndim when 1 case b.ndim when 1 self.mulsum(b, axis:-1) else self[:new, false].gemm(b).flatten end else case b.ndim when 1 self.gemm(b[false, :new]).flatten else self.gemm(b) end end 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 = 200000 am,an = shape[-2..-1] bm,bn = b.shape[-2..-1] if am > nx && an > nx && bm > nx && bn > nx && size > ns && b.size > ns @@warn_slow_dot = true warn "\nwarning: matrix dot for #{t} is slow. Consider SFloat, DFloat, SComplex, or DComplex to use cuBLAS.\n\n" end end self[false,:new].mulsum(b[false,:new,true,true], axis:-2) end end end end |
#dsplit(indices_or_sections) ⇒ Object
809 810 811 |
# File 'lib/cumo/narray/extra.rb', line 809 def dsplit(indices_or_sections) split(indices_or_sections, axis:2) end |
#each_over_axis(axis = 0) ⇒ Object
Iterate over an axis @ example
> a = Cumo::DFloat.new(2,2,2).seq
> p a
Cumo::DFloat#shape=[2,2,2]
[[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]]
> a.each_over_axis{|i| p i}
Cumo::DFloat(view)#shape=[2,2]
[[0, 1],
[2, 3]]
Cumo::DFloat(view)#shape=[2,2]
[[4, 5],
[6, 7]]
> a.each_over_axis(1){|i| p i}
Cumo::DFloat(view)#shape=[2,2]
[[0, 1],
[4, 5]]
Cumo::DFloat(view)#shape=[2,2]
[[2, 3],
[6, 7]]
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 |
# File 'lib/cumo/narray/extra.rb', line 238 def each_over_axis(axis=0) unless block_given? return to_enum(:each_over_axis,axis) end if ndim == 0 if axis != 0 raise ArgumentError,"axis=#{axis} is invalid" end 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 |
#fliplr ⇒ Object
Flip each row in the left/right direction. Same as ‘a[true, (-1..0).step(-1), …]`.
36 37 38 |
# File 'lib/cumo/narray/extra.rb', line 36 def fliplr reverse(1) end |
#flipud ⇒ Object
Flip each column in the up/down direction. Same as ‘a[(-1..0).step(-1), …]`.
42 43 44 |
# File 'lib/cumo/narray/extra.rb', line 42 def flipud reverse(0) end |
#hsplit(indices_or_sections) ⇒ Object
805 806 807 |
# File 'lib/cumo/narray/extra.rb', line 805 def hsplit(indices_or_sections) split(indices_or_sections, axis:1) end |
#inner(b, axis: -1)) ⇒ Cumo::NArray
Inner product of two arrays. Same as ‘(a*b).sum(axis:-1)`.
1192 1193 1194 |
# File 'lib/cumo/narray/extra.rb', line 1192 def inner(b, axis:-1) mulsum(b, axis:axis) end |
#insert(indice, values, axis: nil) ⇒ Object
Insert values along the axis before the indices.
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 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 |
# File 'lib/cumo/narray/extra.rb', line 398 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 = 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] = self.flatten a[idx] = values end return a end |
#kron(b) ⇒ Cumo::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
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 |
# File 'lib/cumo/narray/extra.rb', line 1256 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 |
#new_fill(value) ⇒ Object
Return an array filled with value with the same shape and type as self.
20 21 22 |
# File 'lib/cumo/narray/extra.rb', line 20 def new_fill(value) self.class.new(*shape).fill(value) end |
#new_narray ⇒ Object
Return an unallocated array with the same shape and type as self.
5 6 7 |
# File 'lib/cumo/narray/extra.rb', line 5 def new_narray self.class.new(*shape) end |
#new_ones ⇒ Object
Return an array of ones with the same shape and type as self.
15 16 17 |
# File 'lib/cumo/narray/extra.rb', line 15 def new_ones self.class.ones(*shape) end |
#new_zeros ⇒ Object
Return an array of zeros with the same shape and type as self.
10 11 12 |
# File 'lib/cumo/narray/extra.rb', line 10 def new_zeros self.class.zeros(*shape) end |
#outer(b, axis: nil) ⇒ Cumo::NArray
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 |
# File 'lib/cumo/narray/extra.rb', line 1217 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 if axis < -md raise ArgumentError,"axis=#{axis} is out of range" end 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 |
#rad2deg ⇒ Object
Convert angles from radians to degrees.
25 26 27 |
# File 'lib/cumo/narray/extra.rb', line 25 def rad2deg self * (180/Math::PI) end |
#repeat(arg, axis: nil) ⇒ Object
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 |
# File 'lib/cumo/narray/extra.rb', line 921 def repeat(arg,axis:nil) case axis when Integer axis = check_axis(axis) c = self when NilClass c = self.flatten axis = 0 else raise ArgumentError,"invalid axis" end case arg when Integer if !arg.kind_of?(Integer) || arg<1 raise ArgumentError,"argument should be positive integer" end idx = c.shape[axis].times.map{|i| [i]*arg}.flatten else arg = arg.to_a if arg.size != c.shape[axis] raise ArgumentError,"repeat size shoud be equal to size along axis" end arg.each do |i| if !i.kind_of?(Integer) || i<0 raise ArgumentError,"argument should be non-negative integer" end end idx = arg.each_with_index.map{|a,i| [i]*a}.flatten end ref = [true] * c.ndim ref[axis] = idx c[*ref].copy end |
#rot90(k = 1, axes = [0,1]) ⇒ Object
Rotate in the plane specified by axes.
117 118 119 120 121 122 123 124 125 126 127 128 |
# File 'lib/cumo/narray/extra.rb', line 117 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 |
#split(indices_or_sections, axis: 0) ⇒ Object
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 |
# File 'lib/cumo/narray/extra.rb', line 732 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 mod_axis.times.map do |i| end_idx = beg_idx + div_axis + 1 refs[axis] = beg_idx ... end_idx beg_idx = end_idx self[*refs] end + (indices_or_sections-mod_axis).times.map 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 |
#tile(*arg) ⇒ Object
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 887 888 889 890 891 892 893 894 |
# File 'lib/cumo/narray/extra.rb', line 860 def tile(*arg) arg.each do |i| if !i.kind_of?(Integer) || i<1 raise ArgumentError,"argument should be positive integer" end end ns = arg.size nd = self.ndim shp = self.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_c ⇒ Object
148 149 150 151 152 153 154 155 |
# File 'lib/cumo/narray/extra.rb', line 148 def to_c if size==1 Complex(self.extract_cpu) else # convert to DComplex? raise TypeError, "can't convert #{self.class} into Complex" end end |
#to_f ⇒ Object
139 140 141 142 143 144 145 146 |
# File 'lib/cumo/narray/extra.rb', line 139 def to_f if size==1 self.extract_cpu.to_f else # convert to DFloat? raise TypeError, "can't convert #{self.class} into Float" end end |
#to_i ⇒ Object
130 131 132 133 134 135 136 137 |
# File 'lib/cumo/narray/extra.rb', line 130 def to_i if size==1 self.extract_cpu.to_i else # convert to Int? raise TypeError, "can't convert #{self.class} into Integer" end end |
#trace(offset = nil, axis = nil, nan: false) ⇒ Object
1123 1124 1125 |
# File 'lib/cumo/narray/extra.rb', line 1123 def trace(offset=nil,axis=nil,nan:false) diagonal(offset,axis).sum(nan:nan,axis:-1) end |
#tril(k = 0) ⇒ Object
Lower triangular matrix. Return a copy with the elements above the k-th diagonal filled with zero.
1051 1052 1053 |
# File 'lib/cumo/narray/extra.rb', line 1051 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.
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 |
# File 'lib/cumo/narray/extra.rb', line 1057 def tril!(k=0) if ndim < 2 raise NArray::ShapeError, "must be >= 2-dimensional array" end 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.
1073 1074 1075 1076 1077 1078 1079 |
# File 'lib/cumo/narray/extra.rb', line 1073 def tril_indices(k=0) if ndim < 2 raise NArray::ShapeError, "must be >= 2-dimensional array" end m,n = shape[-2..-1] 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.
1012 1013 1014 |
# File 'lib/cumo/narray/extra.rb', line 1012 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.
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 |
# File 'lib/cumo/narray/extra.rb', line 1018 def triu!(k=0) if ndim < 2 raise NArray::ShapeError, "must be >= 2-dimensional array" end 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 uppler-triangle on and above the k-th diagonal.
1034 1035 1036 1037 1038 1039 1040 |
# File 'lib/cumo/narray/extra.rb', line 1034 def triu_indices(k=0) if ndim < 2 raise NArray::ShapeError, "must be >= 2-dimensional array" end m,n = shape[-2..-1] NArray.triu_indices(m,n,k) end |
#vsplit(indices_or_sections) ⇒ Object
801 802 803 |
# File 'lib/cumo/narray/extra.rb', line 801 def vsplit(indices_or_sections) split(indices_or_sections, axis:0) end |