class CArray
– CArray
class –
carray/broadcast.rb This file is part of Ruby/CArray extension library. Copyright (C) 2005-2020 Hiroki Motoyoshi
carray/composition.rb This file is part of Ruby/CArray extension library. Copyright (C) 2005-2020 Hiroki Motoyoshi
carray/constructor.rb This file is part of Ruby/CArray extension library. Copyright (C) 2005-2020 Hiroki Motoyoshi
carray/mask.rb This file is part of Ruby/CArray extension library. Copyright (C) 2005-2020 Hiroki Motoyoshi
carray/math.rb This file is part of Ruby/CArray extension library. Copyright (C) 2005-2020 Hiroki Motoyoshi
carray/ordering.rb This file is part of Ruby/CArray extension library. Copyright (C) 2005-2020 Hiroki Motoyoshi
carray/struct.rb This file is part of Ruby/CArray extension library. Copyright (C) 2005-2020 Hiroki Motoyoshi
The data class for fixed length carray are required to satisfy only five conditions.
* constant data_class::DATA_SIZE -> integer * constant data_class::MEMBER_TABLE -> hash * constant data_class::MEMBERS -> array (MEMBER_TABLE.keys as usual) * method data_class.decode(data) -> new data_class object * method data_class#encode() -> string
The implementation of other properties (cf. initialization, instance, methods …) are left free.
CAStruct and CAUnion
are examples of such data class.
option = {
:pack => 1, # nil for alignment, int for pack(n) :size => 1024 # user defined size (with padding)
}
CA.struct(option)
{ |s|
# numeric types int8 :a, :b, :c float32 :f1, :f2 float :f5, :f6 float64 :d1, :d2 double :d5, :d6 # fixed length or string fixlen :str1, :str2, :bytes => 3 char_p :str3, :str4, :bytes => 3 # array type array :ary1, :ary2, :type => CArray.int(3) # struct type struct(:st1, :st2) { uint8 :a, :b, :c } struct :st3, :st4, :type => CA.struct { uint8 :a, :b, :c } # union type union(:un1, :un2) { uint8 :a; int16 :b; float32 :c } union :un3, :un4, :type => CA.union { uint8 :a, :b, :c } # anonymous int8_t nil, nil, nil fixlen nil, :bytes=>3 ### padding # low level definition member CA_INT8, :x0 member :int8, :mem0, :mem1 member "int8", :mem0, :mem1 member :uint8, nil ### anonymous member CArray.int(3), :ary3 member struct{ int8 :a, :b, :c }, :st5, :st6 member union{ int8 :a; int16 :b; float :c }, :st5, :st6
}
carray/test.rb This file is part of Ruby/CArray extension library. Copyright (C) 2005-2020 Hiroki Motoyoshi
carray/composition.rb This file is part of Ruby/CArray extension library. Copyright (C) 2005-2020 Hiroki Motoyoshi
Constants
- DComplex
- DFloat
- DataType
- HAVE_COMPLEX
@private
- RObject
- SComplex
- SFloat
- TypeSymbol
- VERSION
@private
- VERSION_CODE
@private
- VERSION_DATE
@private
- VERSION_MAJOR
@private
- VERSION_MINOR
@private
- VERSION_TEENY
@private
Public Class Methods
# File lib/carray/compose.rb, line 189 def self.bind (data_type, list, at = 0, bytes: nil) return CArray.combine(data_type, [list.size], list, at, bytes: bytes) end
# File lib/carray/broadcast.rb, line 72 def CArray.broadcast (*argv, expand_scalar: false, &block) sel = argv.select { |arg| arg.is_a?(CArray) } return argv if sel.empty? dim = [] ndim = sel.map(&:ndim).max ndim.times do |k| dim[k] = sel.map { |arg| arg.dim[k] || 1 }.max end if not expand_scalar list = argv.map { |arg| case arg when CScalar arg when CArray arg.broadcast_to(*dim) else arg end } else list = argv.map { |arg| arg.is_a?(CArray) ? arg.broadcast_to(*dim) : arg } end return block.call(*list) if block return list end
# File lib/carray/compose.rb, line 117 def self.combine (data_type, tdim, list, at = 0, bytes: nil) if CArray.data_class?(data_type) data_class = data_type data_type = :fixlen bytes = data_class::DATA_SIZE else data_class = nil end has_fill_value = false if block_given? fill_value = yield has_fill_value = true end if not tdim.is_a?(Array) or tdim.size == 0 raise "invalid binding dimension" end if not list.is_a?(Array) or list.size == 0 raise "invalid list" end list = list.map{|x| CArray.wrap_readonly(x, data_type) } ref = list.detect{|x| x.is_a?(CArray) or not x.scalar? } unless ref raise "at least one element in list should be a carray" end dim = ref.dim ndim = ref.ndim tndim = tdim.size if at < 0 at += ndim - tndim + 1 end unless at.between?(0, ndim - tndim) raise "concatnating position out of range" end list.map! do |x| if x.scalar? rdim = dim.clone rdim[at] = :% x = x[*rdim] # convert CScalar to CARepeat end x end block = CArray.object(*tdim){ list } edim = tdim.clone idx = Array.new(tdim) offset = Array.new(tdim.size) { [] } tdim.each_with_index do |td, i| edim[i] = 0 idx.map!{0} idx[i] = nil block[*idx].each do |e| offset[i] << edim[i] edim[i] += e.dim[at+i] # extended dimension size end end newdim = dim.clone newdim[at,tndim] = edim # extended dimension size if has_fill_value obj = CArray.new(data_type, newdim) { fill_value } else obj = CArray.new(data_type, newdim) end out.data_class = data_class if data_class idx = newdim.map{0} block.each_with_index do |item, tidx| (at...at+tndim).each_with_index do |d,i| idx[d] = offset[i][tidx[i]] end obj.paste(idx, item) end obj end
# File lib/carray/compose.rb, line 193 def self.composite (data_type, tdim, list, at = 0, bytes: nil) if CArray.data_class?(data_type) data_class = data_type data_type = :fixlen bytes = data_class::DATA_SIZE else data_class = nil end if not tdim.is_a?(Array) or tdim.size == 0 raise "invalid tiling dimension" end if not list.is_a?(Array) or list.size == 0 raise "invalid carray list" end list = list.map{|x| CArray.wrap_readonly(x, data_type) } ref = list.detect{|x| x.is_a?(CArray) or not x.scalar? } unless ref raise "at least one element in list should be a carray" end dim = ref.dim ndim = ref.ndim if at < 0 at += ndim + 1 # "+ 1" is needed here end unless at.between?(0,ndim) raise "tiling position is out of range" end tndim = tdim.size list.map! do |x| if x.scalar? rdim = dim.clone rdim[at] = :% x = x[*rdim] # convert CScalar to CARepeat end x end newdim = dim.clone newdim[at,0] = tdim obj = CArray.new(data_type, newdim, bytes: bytes) out.data_class = data_class if data_class idx = Array.new(ndim+tndim) { nil } CArray.each_index(*tdim) do |*tidx| idx[at,tndim] = tidx obj[*idx] = list.shift end obj end
# File lib/carray/serialize.rb, line 221 def self.dump (ca, **opt) io = StringIO.new("") Serializer.new(io).save(ca, **opt) return io.string end
# File lib/carray/convert.rb, line 104 def self.from_bit_string (bstr, nb, data_type=CA_INT32, dim=nil) if dim obj = CArray.new(data_type, dim) else dim0 = ((bstr.length*8)/nb.to_f).floor obj = CArray.new(data_type, [dim0]) end obj.from_bit_string(bstr, nb) return obj end
Guard methods for handling variables that can be UNDEF values. Provide different processing depending on whether the given value is UNDEF or not.
@param value [Object] target object @param fill_value [Object] alternative value if the given value is UNDEF
@return fill_value if the given value is UNDEF, block return value if block
is given, or value itself
# File lib/carray/mask.rb, line 23 def self.guard_undef (*values, fill_value: UNDEF, &block) return fill_value if values.any?{|v| v == UNDEF } return block.(*values) end
# File lib/carray/compose.rb, line 245 def self.join (*argv) # get options case argv.first when Class if CArray.data_class?(argv.first) data_class = argv.shift data_type = "fixlen" bytes = data_class::DATA_SIZE else raise "#{argv.first} can not to be a data_class for CArray" end when Integer, Symbol, String type, = *CArray.guess_type_and_bytes(argv.shift, 0) else type = argv.flatten.first.data_type end # process conc = argv.map do |list| case list when CArray if list.ndim == 1 list[:%,1] else list end when Array x0 = list.first if list.size == 1 and x0.is_a?(CArray) and x0.ndim == 1 list = [x0[:%,1]] else list = list.map { |x| case x when CArray if x.ndim == 1 x[:%,1] else x end when Array y = x.first if x.size == 1 and y.is_a?(CArray) and y.ndim == 1 y[1,:%] else CArray.join(*x) end else x end } end if block_given? CArray.bind(type, list, 1, &block) else CArray.bind(type, list, 1) end else list end end if conc.size > 1 return CArray.bind(type, conc) else return conc.first end end
# File lib/carray/serialize.rb, line 205 def self.load (input, **opt) case input when String if input.length >= 256 and input =~ /\A_CARRAY_.{8}_(LE|BE)_/ io = StringIO.new(input) return Serializer.new(io).load(**opt) else open(input, "rb:ASCII-8BIT") { |io| return Serializer.new(io).load(**opt) } end else return Serializer.new(input).load(**opt) end end
# File lib/carray/io/imagemagick.rb, line 46 def self.load_by_magick (filename, imap = "rgb", data_type = nil) if not File.exist?(filename) raise "can't find image file '#{filename}'" end identify_command = [ "identify", "-format " + "'" + [ "---", "height: %h", "width: %w", "depth: %z", ].join("\n") + "'", filename, "2>/dev/null" ].join(" ") ident = YAML.load(`#{identify_command}`) if ident.empty? raise "ImageMagick's identify command failed to read image file '#{filename}'" end height, width, depth = ident.values_at('height', 'width', 'depth') unless data_type case depth when 8 data_type = CA_UINT8 when 16 data_type = CA_UINT16 when 32 data_type = CA_UINT32 end end storage_type = case data_type when CA_UINT8, CA_INT8 "char" when CA_UINT16, CA_INT16 "short" when CA_UINT32, CA_INT32 "integer" when CA_FLOAT32 "float" when CA_FLOAT64 "double" else raise "invalid data_type" end tempfile = "CA_Magick_#{$$}_#{@@magick_tempfile_count}.dat" @@magick_tempfile_count += 1 stream_command = [ "stream", "-storage-type #{storage_type}", "-map #{imap}", filename, tempfile, "2>/dev/null" ].join(" ") begin system stream_command return open(tempfile) { |io| if imap.size == 1 CArray.new(data_type, [height, width]).load_binary(io) else CArray.new(data_type, [height, width, imap.size]).load_binary(io) end } rescue raise "ImageMagick's stream command failed to read image file '#{filename}'" ensure if File.exist?(tempfile) File.unlink(tempfile) end end end
# File lib/carray/compose.rb, line 241 def self.merge (data_type, list, at = -1, bytes: nil) return CArray.composite(data_type, [list.size], list, at, bytes: bytes) end
# File lib/carray/construct.rb, line 449 def self.meshgrid (*axes, indexing: "xy", copy: true, sparse: false, &block) case indexing when "xy" ### no operation when "ij" axes = axes.map{|axis| axis.seq } else raise ArgumentError, %{indexing option should be one of "xy" and "ij"} end shape = axes.map(&:size).reverse if sparse ### => CAUnboundRepeat list = axes.map.with_index do |axis, k| extended_shape = (shape.size-1).downto(0).map { |i| ( i == k ) ? nil : :* } if copy axis[*extended_shape].to_ca else axis[*extended_shape] end end else ### => CARepeat naxes = shape.size list = axes.map.with_index do |axis, k| extended_shape = shape.dup extended_shape[naxes - k - 1] = :% if copy axis[*extended_shape].to_ca else axis[*extended_shape] end end end return block.call(*list) if block return list end
# File lib/carray/object/ca_obj_pack.rb, line 96 def self.pack (*argv) return CAPack.new(argv) end
ref = CA_INT([,[1,2,0],]) a = CArray.int(3,3).seq(1) b = CArray.int(3,3).seq(11) c = CArray.int(3,3).seq(21)
CArray.pickup
(CA_OBJECT, ref, [a,b,c])
> <CArray.object(3,3): elem=9 mem=72b¶ ↑
[ [ 1, 12, 23 ],
[ 14, 25, 6 ], [ 27, 8, 19 ] ]>
CArray.pickup
(CA_OBJECT, ref, [“a”,“b”,“c”])
> <CArray.object(3,3): elem=9 mem=36b¶ ↑
[ [ “a”, “b”, “c” ],
[ "b", "c", "a" ], [ "c", "a", "b" ] ]>
# File lib/carray/convert.rb, line 47 def self.pickup (data_type, ref, args) out = ref.template(data_type) args.each_with_index do |v, i| s = ref.eq(i) case v when CArray out[s] = v[s] else out[s] = v end end return out end
# File lib/carray/serialize.rb, line 194 def self.save(ca, output, **opt) case output when String open(output, "wb:ASCII-8BIT") { |io| return Serializer.new(io).save(ca, **opt) } else return Serializer.new(output).save(ca, **opt) end end
CArray.span
(data_type, range[, step]) CArray.span
(range[, step]) -> data_type guessed by range.first type
# File lib/carray/construct.rb, line 18 def self.span (*argv) if argv.first.is_a?(Range) type = nil else type, = *CArray.guess_type_and_bytes(argv.shift, nil) end range, step = argv[0], argv[1] start, stop = range.begin, range.end if step == 0 raise "step should not be 0" end if not type case start when Integer type = CA_INT32 when Float type = CA_FLOAT64 else type = CA_OBJECT end end if type == CA_OBJECT and not step return CA_OBJECT(range.to_a) else step ||= 1 if range.exclude_end? n = ((stop - start).abs/step).floor else n = ((stop - start).abs/step).floor + 1 end if start <= stop return CArray.new(type, [n]).seq(start, step) else return CArray.new(type, [n]).seq(start, -step.abs) end end end
# File lib/carray/obsolete.rb, line 48 def self.summation (*dim) warn "CArray.summation will be obsolete" out = nil first = true CArray.each_index(*dim) { |*idx| if first out = yield(*idx) first = false else out += yield(*idx) end } return out end
Public Instance Methods
comparison operators
# File lib/carray/math.rb, line 81 def <=> (other) lower = self < other upper = self > other out = CArray.new(CA_INT8, lower.dim) out[lower] = -1 out[upper] = 1 return out end
index / indices / axes
# File lib/carray/basic.rb, line 113 def address () return CArray.int32(*dim).seq! end
# File lib/carray/math.rb, line 225 def anomaly (*argv) opt = argv.last.is_a?(Hash) ? argv.pop : {} idxs = Array.new(self.ndim) { |i| argv.include?(i) ? :* : nil } if mn = opt[:mean] return self - mn[*idxs] else return self - self.mean(*argv)[*idxs] end end
# File lib/carray/obsolete.rb, line 114 def asign (*idx) warn "CArray#asign will be obsolete" self[*idx] = yield return self end
# File lib/carray/basic.rb, line 80 def attribute @attribute ||= {} return @attribute end
# File lib/carray/basic.rb, line 73 def attribute= (obj) unless obj.is_a?(Hash) raise "attribute should be a hash object" end @attribute = obj end
# File lib/carray/testing.rb, line 25 def between (a, b) return (self >= a) & (self <= b) end
# File lib/carray/math/histogram.rb, line 118 def bin (val, include_upper, include_lowest, offset=0) scales = CArray.wrap_readonly(self, CA_DOUBLE) x = scales.section(val) # x.inherit_mask(val) unless x.is_a?(CArray) x = CA_DOUBLE(x) end if include_upper if include_lowest x[:eq, 0] = 0.5 end xi = x.ceil.int32 - 1 else xi = x.floor.int32 end case offset when 0 xi[:gt, elements-1] = elements - 1 xi[:lt, 0] = UNDEF when 1 xi.add!(1) xi[:gt, elements] = elements xi[:lt, 1] = 0 else raise "invalid offset value" end return xi end
# File lib/carray/broadcast.rb, line 13 def broadcast_to (*newdim) if newdim.size < ndim raise "(Broadcasting) can't broadcast to #{newdim.inspect} because too small rank is specified" end # # Try to build unbound repeat index (includes :*) # with broadcasting rule in Numpy. # repdim = [] shape = [] srcdim = dim.dup dstdim = newdim.dup sd = srcdim.pop dd = dstdim.pop while dd if sd == dd repdim.unshift nil shape.unshift(dd) sd = srcdim.pop elsif dd == 1 repdim.unshift :* elsif sd == 1 repdim.unshift :* sd = srcdim.pop else raise "(Broadcasting) can't broadcast to #{newdim.inspect} " end dd = dstdim.pop end # # Call Unbound repeat's bind # return self.reshape(*shape)[*repdim].bind(*newdim) if repdim.include?(:*) self end
# File lib/carray/obsolete.rb, line 63 def by (other) warn "CArray#by will be obsolete" case other when CArray return (self[nil][nil,:*]*other[nil][:*,nil]).reshape(*(dim+other.dim)) else return self * other end end
# File lib/carray/iterator.rb, line 305 def classes (classifier=nil, &block) return CAClassIterator.new(self, classifier).__build__(&block) end
# File lib/carray/inspect.rb, line 236 def code text = [ desc, " { ", self.to_a.pretty_inspect.split("\n").map{|s| " " * (desc.length+3) + s }.join("\n").lstrip, " }" ].join return text end
Returns the array which ndim is reduced by eliminating the dimensions which size == 1
# File lib/carray/transform.rb, line 72 def compact if ndim == 1 return self.to_ca else newdim = dim.reject{|x| x == 1 } return ( ndim != newdim.size ) ? reshape(*newdim).to_ca : self.to_ca end end
Reutrns the reference which ndim is reduced by eliminating the dimensions which size == 1
# File lib/carray/transform.rb, line 61 def compacted if ndim == 1 return self[] else newdim = dim.reject{|x| x == 1 } return ( ndim != newdim.size ) ? reshape(*newdim) : self[] end end
# File lib/carray/testing.rb, line 17 def contains (*list) result = self.false() list.each do |item| result = result | self.eq(item) end return result end
# File lib/carray/math.rb, line 348 def correlation (y, min_count = nil, fill_value = nil) x = self.double y = y.double if x.has_mask? or y.has_mask? x.inherit_mask(y) y.inherit_mask(x) xm = x.mean(:min_count=>min_count) ym = y.mean(:min_count=>min_count) if ( xm == UNDEF or ym == UNDEF ) return fill_value || UNDEF else xd, yd = x-xm, y-ym return xd.wsum(yd)/(xd.wsum(xd)*yd.wsum(yd)).sqrt end else xd, yd = x-x.mean, y-y.mean return xd.wsum(yd)/(xd.wsum(xd)*yd.wsum(yd)).sqrt end end
mask
Returns the number of masked elements.
# File lib/carray/mask.rb, line 32 def count_masked (*axis) if has_mask? return mask.int64.accumulate(*axis) else if axis.empty? return 0 else spec = shape.map{:i} axis.each do |k| spec[k] = nil end return self[*spec].ca.template(:int64) { 0 } end end end
Returns the number of not-masked elements.
# File lib/carray/mask.rb, line 51 def count_not_masked (*axis) if has_mask? return mask.not.int64.accumulate(*axis) else if axis.empty? return elements else spec = shape.map {:i} axis.each do |k| spec[k] = nil end it = self[*spec].ca count = self.elements/it.elements return it.template(:int64) { count } end end end
# File lib/carray/math.rb, line 329 def covariance (y, min_count = nil, fill_value = nil) x = self.double y = y.double if x.has_mask? or y.has_mask? x.inherit_mask(y) y.inherit_mask(x) count = x.count_not_masked xm = x.mean(:min_count=>min_count) ym = y.mean(:min_count=>min_count) if ( xm == UNDEF or ym == UNDEF ) return fill_value || UNDEF else return (x-xm).wsum(y-ym)/(count-1) end else return (x-x.mean).wsum(y-y.mean)/(elements-1) end end
# File lib/carray/math.rb, line 310 def covariancep (y, min_count = nil, fill_value = nil) x = self.double y = y.double if x.has_mask? or y.has_mask? x.inherit_mask(y) y.inherit_mask(x) count = x.count_not_masked xm = x.mean(:min_count => min_count) ym = y.mean(:min_count => min_count) if ( xm == UNDEF or ym == UNDEF ) return fill_value || UNDEF else return (x-xm).wsum(y-ym)/count end else return (x-x.mean).wsum(y-y.mean)/elements end end
# File lib/carray/compose.rb, line 75 def delete_block (offset, bsize) if offset.size != ndim or bsize.size != ndim raise "ndim mismatch" end newdim = dim grids = [] ndim.times do |i| if offset[i] < 0 offset[i] += dim[i] end if bsize[i] >= 0 if offset[i] < 0 or offset[i] >= dim[i] raise "invalid offset or size" end newdim[i] -= bsize[i] else if offset[i] + bsize[i] + 1 < 0 or offset[i] + bsize[i] > dim[i] raise "invalid offset or size" end newdim[i] += bsize[i] end grids[i] = CArray.int32(newdim[i]) if bsize[i] >= 0 if offset[i] > 0 grids[i][0...offset[i]].seq! end if offset[i] + bsize[i] < dim[i] grids[i][offset[i]..-1].seq!(offset[i]+bsize[i]) end else if offset[i]+bsize[i] > 0 grids[i][0..offset[i]+bsize[i]].seq! end if offset[i]+bsize[i]+1 < dim[i]-1 grids[i][offset[i]+bsize[i]+1..-1].seq!(offset[i]+1) end end end return self[*grids].to_ca end
# File lib/carray/io/imagemagick.rb, line 200 def display_by_magick (image_type = nil, options = "") unless image_type image_type = magick_guess_image_type() end unless image_type raise "please specify image_type" end quantum_format = self.float? ? "-define quantum:format=floating-point" : "" depth = fixlen? ? "-depth 8" : "-depth #{8*bytes}" display_command = [ "display", depth, "-size " + [dim1, dim0].join("x"), quantum_format, options, "#{image_type}:-", ].join(" ") begin IO.popen(display_command, "w") { |io| if bytes > 1 and CArray.endian == CA_LITTLE_ENDIAN swap_bytes.dump_binary(io) else self.dump_binary(io) end } rescue raise "ImageMagick's display command failed to display image" end end
Returns the array eliminated all the duplicated elements.
# File lib/carray/obsolete.rb, line 27 def duplicated_values warn "CArray#duplicated_values will be obsolete" if uniq.size == size return [] else hash = {} list = [] each_with_addr do |v, addr| if v == UNDEF next elsif hash[v] list << [v, addr, hash[v]] hash[v] += 1 else hash[v] = 0 end end return list end end
obsolete methods
# File lib/carray/obsolete.rb, line 19 def extend_as_table (column_names) warn "CArray#extend_as_table will be obsolete" self.extend CArray::TableMethods self.column_names = column_names self end
Returns the 8-bit integer CArray
object filled with 0 which dimension size is same as self
. The resulted array represents the logical array which has false
for its all elements.
# File lib/carray/convert.rb, line 11 def false () return template(:boolean) end
# File lib/carray/basic.rb, line 85 def first ( self.elements == 0 ) ? nil : self[0] end
# File lib/carray/transform.rb, line 46 def flatten return reshape(elements).to_ca end
flatten
# File lib/carray/transform.rb, line 42 def flattened return reshape(elements) end
# File lib/carray/convert.rb, line 96 def from_bit_string (bstr, nb) hex = CArray.uint8(bstr.length).load_binary(bstr) hex.bits[] = hex.bits[nil,[-1..0]] bits = hex.bits.flatten self.bits[false,[(nb-1)..0]][nil].paste([0], bits) return self end
# File lib/carray/basic.rb, line 65 def has_attribute? if ( not @attribute ) or @attribute.empty? return false else return true end end
Return the imaginary part of self
. If self
is a complex array, the resulted array is CAMember object refers the appropriate part of self
. In this case, you change the resulted array, the original array is also changed.
Otherwise, the resulted array is a dummy CArray
object filled with 0. In this case, the change in the resulted array does not affect the original array. For this purpose, you should explicitly convert the array to complex array.
# File lib/carray/math.rb, line 53 def imag if not @__imag__ if complex? @__imag__ = case data_type when CA_CMPLX64 field(4, CA_FLOAT32) when CA_CMPLX128 field(8, CA_FLOAT64) when CA_CMPLX128 field(16, CA_FLOAT128) end else @__imag__ = self.template { 0 } end end return @__imag__ end
# File lib/carray/math.rb, line 71 def imag= (val) if complex? imag[] = val else raise "not a complex array" end end
# File lib/carray/basic.rb, line 117 def index (n = 0) unless n.is_a?(Integer) raise ArgumentError, "argument should be an integer" end if n.between?(0, ndim-1) return CArray.int32(dim[n]).seq! else raise ArgumentError, "invalid dimension specifier #{n} (0..#{self.ndim-1})" end end
# File lib/carray/basic.rb, line 133 def indices list = Array.new(ndim) {|i| rpt = self.dim rpt[i] = :% index(i)[*rpt] } if block_given? return yield(*list) else return list end end
insert
# File lib/carray/compose.rb, line 44 def insert_block (offset, bsize, &block) if offset.size != ndim or bsize.size != ndim raise "ndim mismatch" end newdim = dim grids = dim.map{|d| CArray.int32(d) } ndim.times do |i| if offset[i] < 0 offset[i] += dim[i] end if offset[i] < 0 or offset[i] >= dim[i] or bsize[i] < 0 raise "invalid offset or size" end if bsize[i] > 0 newdim[i] += bsize[i] end grids[i][0...offset[i]].seq! grids[i][offset[i]..-1].seq!(offset[i]+bsize[i]) end out = CArray.new(data_type, newdim) out.data_class = data_class if has_data_class? if block_given? sel = out.true sel[*grids] = 0 out[sel] = block.call end out[*grids] = self return out end
# File lib/carray/inspect.rb, line 215 def inspect return CArray::Inspector.new(self).inspect_string end
# File lib/carray/math.rb, line 98 def is_close (other, atol) return ((self - other).abs <= atol) end
# File lib/carray/math.rb, line 102 def is_divisible (n) unless integer? raise "data type of reciever of CArray#divisible? should be integer." end return (self % n).eq(0) end
# File lib/carray/math.rb, line 92 def is_equiv (other, rtol) exact_eq = self.eq(other) relative_eq = ((self - other).abs/CAMath.max(self.abs, other.abs) <= rtol) return (exact_eq).or(relative_eq) end
# File lib/carray/math.rb, line 109 def is_not_divisible (n) unless integer? raise "data type of reciever of CArray#divisible? should be integer." end return (self % n).ne(0) end
# File lib/carray/math.rb, line 126 def is_real if complex? imag.eq(0) elsif numeric? self.true else nil end end
Array#join like method
> a = CArray.object(3,3).seq(“a”,:succ)
> <CArray.object(3,3): elem=9 mem=72b¶ ↑
[ [ “a”, “b”, “c” ],
[ "d", "e", "f" ], [ "g", "h", "i" ] ]>
> a.join(“n”,“,”)
> “a,b,cnd,e,fng,h,i”¶ ↑
# File lib/carray/convert.rb, line 73 def join (*argv) case argv.size when 0 return to_a.join() when 1 sep = argv.shift return to_a.join(sep) else sep = argv.shift return self[:i, false].map { |s| s[0, false].join(*argv) }.join(sep) end end
# File lib/carray/basic.rb, line 89 def last ( self.elements == 0 ) ? nil :self[-1] end
Returns map
# File lib/carray/convert.rb, line 25 def map (&block) return self.convert(CA_OBJECT, &block).to_a end
for Marshal
# File lib/carray/serialize.rb, line 229 def marshal_dump () if self.class != CArray and self.class != CScalar return CArray.dump(self.to_ca) # raise TypeError, "can't dump a virtual or wrapped array." end return CArray.dump(self) end
# File lib/carray/serialize.rb, line 237 def marshal_load (data) io = StringIO.new(data) ca = CArray.load(io) initialize_copy(ca) end
# File lib/carray/mask.rb, line 85 def maskout (*argv) obj = self.to_ca case argv.size when 1 val = argv.first case val when CArray, Symbol obj[val] = UNDEF else obj[:eq, val] = UNDEF end else obj[*argv] = UNDEF end return obj end
# File lib/carray/mask.rb, line 69 def maskout! (*argv) case argv.size when 1 val = argv.first case val when CArray, Symbol self[val] = UNDEF else self[:eq, val] = UNDEF end else self[*argv] = UNDEF end return self end
matchup
# File lib/carray/basic.rb, line 95 def matchup (ref) ri = ref.sort_addr rs = ref[ri].to_ca si = rs.bsearch(self) return ri.project(si) end
# File lib/carray/basic.rb, line 102 def matchup_nearest (ref, direction: "round") ri = ref.sort_addr rs = ref[ri].to_ca si = rs.section(self).send(direction.intern).int64 si.trim!(0,si.size) return ri[si].to_ca end
# File lib/carray/ordering.rb, line 71 def max_by (&block) if empty? return UNDEF else addr = convert(:object, &block).max_addr return self[addr] end end
# File lib/carray/ordering.rb, line 80 def max_with (*others) if empty? return ([self] + others).map { |x| UNDEF } else addr = max_addr return ([self] + others).map { |x| x[addr] } end end
# File lib/carray/math.rb, line 237 def median (*argv) opt = argv.last.is_a?(Hash) ? argv.pop : {} min_count = opt[:mask_limit] if min_count and min_count < 0 min_count += elements end fill_value = opt[:fill_value] if argv.empty? if has_mask? if min_count and count_masked() > min_count return fill_value || UNDEF end c = self[:is_not_masked].sort n = self.count_not_masked else c = self.sort n = c.elements end if n == 0 return fill_value || UNDEF else return (c[(n-1)/2] + c[n/2])/2.0 end else raise "CArray#median is not implemented for multiple ndims" end end
# File lib/carray/ordering.rb, line 89 def min_by (&block) if empty? return UNDEF else addr = convert(:object, &block).min_addr return self[addr] end end
# File lib/carray/ordering.rb, line 98 def min_with (*others) if empty? return ([self] + others).map { |x| UNDEF } else addr = min_addr return ([self] + others).map { |x| x[addr] } end end
# File lib/carray/ordering.rb, line 111 def nlargest (n) obj = self.to_ca list = [] n.times do |i| k = obj.max_addr list << obj[k] obj[k] = UNDEF end list.to_ca.to_type(data_type) end
# File lib/carray/ordering.rb, line 122 def nlargest_addr (n) obj = self.to_ca list = [] n.times do |i| k = obj.max_addr list << k obj[k] = UNDEF end CA_INT64(list) end
# File lib/carray/ordering.rb, line 133 def nsmallest (n) obj = self.to_ca list = [] n.times do |i| k = obj.min_addr list << obj[k] obj[k] = UNDEF end list.to_ca.to_type(data_type) end
# File lib/carray/ordering.rb, line 144 def nsmallest_addr (n) obj = self.to_ca list = [] n.times do |i| k = obj.min_addr list << k obj[k] = UNDEF end CA_INT64(list) end
# File lib/carray/ordering.rb, line 155 def order (dir = 1) if dir >= 0 ### ascending order if has_mask? obj = template(:int32) { UNDEF } sel = is_not_masked obj[sel][self[sel].sort_addr].seq! return obj else obj = template(:int32) obj[sort_addr].seq! return obj end else ### descending order if has_mask? obj = template(:int32) { UNDEF} sel = is_not_masked obj[sel][self[sel].sort_addr.reversed].seq! return obj else obj = template(:int32) obj[sort_addr.reversed].seq! return obj end end end
# File lib/carray/math.rb, line 266 def percentile (*argv) opt = argv.last.is_a?(Hash) ? argv.pop : {} pers = argv min_count = opt[:mask_limit] if min_count and min_count < 0 min_count += elements end fill_value = opt[:fill_value] if has_mask? if min_count and count_masked() > min_count return argv.map { fill_value || UNDEF } end ca = self[:is_not_masked].sort n = self.count_not_masked else ca = self.sort n = ca.elements end out = [] begin pers.each do |per| if per == 100 out << ca[n-1] elsif per >= 0 and per < 100 if n > 1 f = (n-1)*per/100.0 k = f.floor r = f - k out << (1-r)*ca[k] + r*ca[k+1] else out << ca[0] end else out << CA_NAN end end end return out end
# File lib/carray/transform.rb, line 104 def pull (*args) idx = args.map{|s| s.nil? ? :% : s} return self[*idx].to_ca end
pulled
# File lib/carray/transform.rb, line 99 def pulled (*args) idx = args.map{|s| s.nil? ? :% : s} return self[*idx] end
# File lib/carray/math.rb, line 306 def quantile return percentile(0, 25, 50, 75, 100) end
# File lib/carray/math.rb, line 146 def quo (other) case when integer? return object.quo_i(other) when object? return quo_i(other) else return self/other end end
statistics
# File lib/carray/math.rb, line 198 def random (*argv) return template.random!(*argv) end
# File lib/carray/math.rb, line 221 def randomn return template.randomn! end
# File lib/carray/math.rb, line 202 def randomn! if elements == 1 self[0] = CArray.new(data_type,[2]).randomn![0] return self end x1 = CArray.new(data_type, [elements/2]) x2 = CArray.new(data_type, [elements/2]) fac = x1.random!.log!.mul!(-2.0).sqrt! ### fac = sqrt(-2*log(rnd())) x2.random!.mul!(2.0*Math::PI) ### x2 = 2*PI*rnd() x3 = x2.to_ca self2 = reshape(2,elements/2) self2[0,nil] = x2.cos!.mul!(fac) ### self[even] = fac*cos(x2) self2[1,nil] = x3.sin!.mul!(fac) ### self[odd] = fac*sin(x2) if elements % 2 == 1 self[[-1]].randomn! end return self end
# File lib/carray/ordering.rb, line 107 def range return (self.min)..(self.max) end
Return the real part of self
. If self
is a complex array, the resulted array is CAMember object refers the appropriate part of self
. Otherwise, the resulted array is CARefer
object refers self
. If you change the resulted array, the original array is also changed.
# File lib/carray/math.rb, line 21 def real if not @__real__ if complex? @__real__ = case data_type when CA_CMPLX64 field(0, CA_FLOAT32) when CA_CMPLX128 field(0, CA_FLOAT64) when CA_CMPLX128 field(0, CA_FLOAT128) end else @__real__ = self[] end end @__real__ end
# File lib/carray/math.rb, line 39 def real= (val) real[] = val end
# File lib/carray/math.rb, line 116 def real? if complex? imag.all_equal?(0) elsif numeric? true else nil end end
# File lib/carray/math/recurrence.rb, line 71 def recurrence (*argv, &block) return self.template.recurrence!(*argv, &block) end
# File lib/carray/math/recurrence.rb, line 65 def recurrence! (init = {}, &block) lazy = CARecurrence.new(self, init, &block) CArray.attach(lazy) {} return self end
# File lib/carray/obsolete.rb, line 108 def replace_value (from, to) warn "CArray#replace_value will be obsolete" self[:eq, from] = to return self end
reshape
# File lib/carray/transform.rb, line 15 def reshape (*newdim) ifalse = nil i = 0 0.upto(newdim.size-1) do |i| if newdim[i].nil? newdim[i] = dim[i] elsif newdim[i] == false ifalse = i break end end k = 0 (newdim.size-1).downto(i+1) do |j| if newdim[j].nil? newdim[j] = dim[ndim-1-k] end k += 1 end if ifalse newdim[ifalse] = elements/newdim.select{|x| x!=false}.inject(1){|s,x| s*x} end return refer(data_type, newdim, :bytes=>bytes) end
Returns the array resized to the dimension given as `newdim`. The new area is filled by the value returned by the block.
# File lib/carray/compose.rb, line 15 def resize (*newdim, &block) if newdim.size != ndim raise "ndim mismatch" end offset = Array.new(ndim){0} ndim.times do |i| d = newdim[i] case d when nil newdim[i] = dim[i] when Integer if d < 0 newdim[i] *= -1 offset[i] = newdim[i] - dim[i] end else raise "invalid dimension size" end end out = CArray.new(data_type, newdim, &block) out.data_class = data_class if has_data_class? if out.has_mask? out.mask.paste(offset, self.false) end out.paste(offset, self) return out end
reversed
# File lib/carray/ordering.rb, line 14 def reversed return self[*([-1..0]*ndim)] end
# File lib/carray/ordering.rb, line 39 def roll (*argv) return self.rolled(*argv).to_ca end
# File lib/carray/ordering.rb, line 34 def roll! (*argv) self[] = self.rolled(*argv) return self end
# File lib/carray/ordering.rb, line 29 def rolled (*argv) argv.push({:roll => Array.new(ndim){1} }) return shifted(*argv) end
# File lib/carray/io/imagemagick.rb, line 151 def save_by_magick (filename, image_type = nil, options = "") unless image_type image_type = magick_guess_image_type() end unless image_type raise "please specify image_type" end quantum_format = self.float? ? "-define quantum:format=floating-point" : "" case self.data_type when CA_INT8, CA_UINT8 depth = "-depth 8" when CA_INT16, CA_UINT16 depth = "-depth 16" when CA_FLOAT32 depth = "-depth 32" when CA_FLOAT64 depth = "-depth 64" when CA_FIXLEN depth = "-depth #{8*bytes}" else depth = "-depth 8" end convert_command = [ "convert", depth, "-size " + [dim1, dim0].join("x"), quantum_format, options, "#{image_type}:-", filename ].join(" ") begin IO.popen(convert_command, "w") { |io| if data_type != CA_FIXLEN and data_type != CA_OBJECT if bytes > 1 and CArray.endian == CA_LITTLE_ENDIAN self.dump_binary(io) # swap_bytes.dump_binary(io) else self.dump_binary(io) end else self.dump_binary(io) end } rescue raise "ImageMagick's convert command failed to write image file '#{filename}'" end end
# File lib/carray/construct.rb, line 94 def scale (xa, xb) template.scale!(xa, xb) end
# File lib/carray/construct.rb, line 88 def scale! (xa, xb) xa = xa.to_f xb = xb.to_f seq!(xa, (xb-xa)/(elements-1)) end
# File lib/carray/ordering.rb, line 25 def shift (*argv, &block) return self.shifted(*argv, &block).to_ca end
roll / shift
# File lib/carray/ordering.rb, line 20 def shift! (*argv, &block) self[] = self.shifted(*argv, &block) return self end
# File lib/carray/math.rb, line 136 def sign out = self.zero out[self.lt(0)] = -1 out[self.gt(0)] = 1 if float? out[self.is_nan] = 0.0/0.0 end return out end
Returns the array which elements are sorted by the comparison method given as block
# File lib/carray/ordering.rb, line 54 def sort_by (type=nil, opt={}, &block) type, bytes = CArray.guess_type_and_bytes(type||data_type, opt[:bytes]||bytes) cmpary = convert(type, :bytes=>bytes, &block) return self[cmpary.sort_addr].to_ca end
# File lib/carray/ordering.rb, line 66 def sort_with (*others) addr = sort_addr ([self] + others).map { |x| x[addr].to_ca } end
Returns the reference which elements are sorted by the comparison method given as block
# File lib/carray/ordering.rb, line 45 def sorted_by (type=nil, opt={}, &block) type, bytes = CArray.guess_type_and_bytes(type||data_type, opt[:bytes]||bytes) cmpary = convert(type, :bytes=>bytes, &block) return self[cmpary.sort_addr] end
# File lib/carray/ordering.rb, line 61 def sorted_with (*others) addr = sort_addr ([self] + others).map { |x| x[addr] } end
# File lib/carray/construct.rb, line 80 def span (range) return template.span!(range) end
# File lib/carray/construct.rb, line 56 def span! (range) first = range.begin.to_r last = range.end.to_r if integer? if range.exclude_end? step = ((last-1)-first+1)/elements else step = (last-first+1)/elements end else if range.exclude_end? step = (last-first)/elements else step = (last-first)/(elements-1) end end if integer? && step.denominator != 1 self[] = (first + seq * step).floor else seq!(first, step) end return self end
Returns object carray has elements of splitted carray at dimensions
which is given by arguments a = CA_INT([[1,2,3], [4,5,6], [7,8,9]]) a.split(0) [1,2,3], [4,5,6], [7,8,9] a.split(1) [1,4,7], [2,5,8], [3,6,9]
# File lib/carray/basic.rb, line 164 def split (*argv) odim = dim.values_at(*argv) out = CArray.object(*odim) idx = [nil] * ndim attach { out.map_with_index! do |o, v| argv.each_with_index do |r, i| idx[r] = v[i] end self[*idx].to_ca end } return out end
# File lib/carray/struct.rb, line 77 def st unless has_data_class? raise "should have data_class" end unless @struct struct_class = Struct.new(nil, *data_class::MEMBERS) members = data_class::MEMBERS.map{|name| self[name]} @struct = struct_class.new(*members) end return @struct end
# File lib/carray/string.rb, line 23 def str_bytesize () return convert(:int, &:bytesize) end
# File lib/carray/string.rb, line 85 def str_capitalize () return convert(&:capitalize) end
# File lib/carray/string.rb, line 129 def str_center (*args) return convert() {|s| s.center(*args) } end
# File lib/carray/string.rb, line 93 def str_chomp (*args) return convert() {|s| s.chomp(*args) } end
# File lib/carray/string.rb, line 97 def str_chop () return convert(&:chop) end
# File lib/carray/string.rb, line 101 def str_chr () return convert(&:chr) end
# File lib/carray/string.rb, line 105 def str_clear () return convert(&:clear) end
# File lib/carray/string.rb, line 109 def str_count (*args) return convert(:int) {|s| s.count(*args) } end
# File lib/carray/string.rb, line 113 def str_delete (*args) return convert() {|s| s.delete(*args) } end
# File lib/carray/string.rb, line 117 def str_delete_prefix (prefix) return convert() {|s| s.delete_prefix(prefix) } end
# File lib/carray/string.rb, line 121 def str_delete_suffix (suffix) return convert() {|s| s.delete_suffix(suffix) } end
# File lib/carray/string.rb, line 77 def str_downcase () return convert(&:downcase) end
# File lib/carray/string.rb, line 125 def str_dump () return convert(&:dump) end
# File lib/carray/string.rb, line 35 def str_encode (*args) return convert() {|s| s.encode(*args) } end
# File lib/carray/string.rb, line 43 def str_encoding () return convert(&:encoding) end
# File lib/carray/string.rb, line 183 def str_extract (regexp, replace = '\0') return convert {|s| regexp.match(s) {|m| m[0].sub(regexp, replace) } || "" } end
# File lib/carray/string.rb, line 39 def str_force_encoding (encoding) return convert() {|s| s.force_encoding(encoding) } end
# File lib/carray/string.rb, line 27 def str_gsub (*args, &block) return convert() {|s| s.gsub(*args, &block) } end
# File lib/carray/string.rb, line 55 def str_includes (substr) return test {|s| s.include?(substr) } end
# File lib/carray/string.rb, line 61 def str_index (*args) return convert(:int) {|s| s.index(*args) } end
# File lib/carray/string.rb, line 69 def str_intern () return convert(&:intern) end
# File lib/carray/string.rb, line 165 def str_is_empty () return test(&:empty?) end
# File lib/carray/string.rb, line 47 def str_is_end_with (*args) return test {|s| s.end_with?(*args) } end
# File lib/carray/string.rb, line 51 def str_is_start_with (*args) return test {|s| s.start_with?(*args) } end
# File lib/carray/string.rb, line 15 def str_len () return convert(:int, &:length) end
# File lib/carray/string.rb, line 133 def str_ljust (*args) return convert() {|s| s.ljust(*args) } end
# File lib/carray/string.rb, line 161 def str_lstrip () return convert(&:lstrip) end
# File lib/carray/string.rb, line 169 def str_matches (*args) if args.size == 1 && args.first.is_a?(Regexp) regexp = args.first return test {|v| v =~ regexp } else mask = template(:boolean) { false } args.each do |str| addr = search(str) mask[addr] = true if addr end return mask end end
# File lib/carray/string.rb, line 65 def str_rindex (*args) return convert(:int) {|s| s.rindex(*args) } end
# File lib/carray/string.rb, line 137 def str_rjust (*args) return convert() {|s| s.rjust(*args) } end
# File lib/carray/string.rb, line 157 def str_rstrip () return convert(&:rstrip) end
# File lib/carray/string.rb, line 73 def str_scrub () return convert(&:scrub) end
# File lib/carray/string.rb, line 19 def str_size () return convert(:int, &:size) end
# File lib/carray/string.rb, line 153 def str_strip () return convert(&:strip) end
# File lib/carray/string.rb, line 31 def str_sub (*args, &block) return convert() {|s| s.sub(*args, &block) } end
# File lib/carray/string.rb, line 89 def str_swapcase () return convert(&:swapcase) end
# File lib/carray/time.rb, line 15 def str_to_datetime (template = nil) if template return convert() {|v| DateTime.strptime(v, template) } else return convert() {|v| DateTime.parse(v) } end end
# File lib/carray/string.rb, line 145 def str_to_f () return convert(&:to_f) end
# File lib/carray/string.rb, line 141 def str_to_i () return convert(&:to_i) end
# File lib/carray/string.rb, line 149 def str_to_r () return convert(&:to_r) end
# File lib/carray/time.rb, line 23 def str_to_time (template = nil) if template return str_strptime(template) else return convert() {|v| Time.parse(v) } end end
# File lib/carray/string.rb, line 81 def str_upcase () return convert(&:upcase) end
# File lib/carray/testing.rb, line 13 def test (&block) return convert(:boolean) {|v| yield(v) ? true : false } end
# File lib/carray/time.rb, line 67 def time_ajd return convert(:double, &:ajd) end
# File lib/carray/time.rb, line 47 def time_day return convert(:int, &:day) end
# File lib/carray/time.rb, line 31 def time_format (template = nil) if template return str_strftime(template) else return convert(&:to_s) end end
# File lib/carray/time.rb, line 51 def time_hour return convert(:int, &:hour) end
# File lib/carray/time.rb, line 71 def time_is_leap return test(&:leap?) end
# File lib/carray/time.rb, line 63 def time_jd return convert(:int, &:jd) end
# File lib/carray/time.rb, line 55 def time_minute return convert(:int, &:minute) end
# File lib/carray/time.rb, line 43 def time_month return convert(:int, &:month) end
# File lib/carray/time.rb, line 59 def time_second return convert(:double) {|d| d.second + d.second_fraction } end
# File lib/carray/time.rb, line 39 def time_year return convert(:int, &:year) end
# File lib/carray/convert.rb, line 89 def to_bit_string (nb) hex = CArray.uint8(((nb*elements)/8.0).ceil) hex.bits[nil].paste([0], self.bits[false,[(nb-1)..0]].flatten) hex.bits[] = hex.bits[nil,[-1..0]] return hex.to_s end
Returns (n,1) array from 1-dimensional array
# File lib/carray/transform.rb, line 90 def to_column if ndim != 1 raise "ndim should be 1" end return self[:%,1] end
Returns (1,n) array from 1-dimensional array
# File lib/carray/transform.rb, line 82 def to_row if ndim != 1 raise "ndim should be 1" end return self[1,:%] end
# File lib/carray/transform.rb, line 55 def transpose (*argv) return self.transposed(*argv).to_ca end
# File lib/carray/transform.rb, line 50 def transpose! (*argv) self[] = self.transposed(*argv) return self end
Returns the 8-bit integer CArray
object filled with 1 which dimension size is same as self
. The resulted array represents the logical array which has true
for its all elements.
# File lib/carray/convert.rb, line 20 def true () return template(:boolean) { 1 } end
Returns the array eliminated all the duplicated elements.
# File lib/carray/testing.rb, line 41 def uniq ary = flatten.to_a.uniq if has_mask? ary.delete(UNDEF) end out = CArray.new(data_type, [ary.length], :bytes=>bytes) { ary } out.data_class = data_class if has_data_class? return out end
# File lib/carray/testing.rb, line 29 def where_range w = where x = (w - w.shifted(1){-2}).sub!(1).where y = (w - w.shifted(-1){-2}).add!(1).where list = [] x.each_addr do |i| list.push(w[x[i]]..w[y[i]]) end return list end
# File lib/carray/iterator.rb, line 296 def windows (*args, &block) return CAWindowIterator.new(self.window(*args, &block)) end
Private Instance Methods
# File lib/carray/inspect.rb, line 221 def desc output = "" case data_type when CA_FIXLEN output << sprintf("CArray.%s(%s, :bytes=>%i)", data_type_name, dim.inspect[1..-2], bytes) else output << sprintf("CArray.%s(%s)", data_type_name, dim.inspect[1..-2]) end return output end
# File lib/carray/io/imagemagick.rb, line 120 def magick_guess_image_type image_type = nil case ndim when 2 if fixlen? case bytes when 1 image_type = "gray" when 3 image_type = "rgb" when 4 image_type = "rgba" end else image_type = "gray" end when 3 case dim2 when 1 image_type = "gray" when 3 image_type = "rgb" when 4 image_type = "rgba" end end return image_type end