Class: CArray

Inherits:
Object
  • Object
show all
Extended by:
DataTypeExtension
Defined in:
lib/carray.rb,
lib/carray.rb,
lib/carray/lazy.rb,
lib/carray/time.rb,
lib/carray/stack.rb,
lib/carray/stack.rb,
lib/carray/table.rb,
lib/carray/basics.rb,
lib/carray/fusion.rb,
lib/carray/string.rb,
lib/carray/struct.rb,
lib/carray/struct.rb,
lib/carray/complex.rb,
lib/carray/inspect.rb,
lib/carray/runtime.rb,
lib/carray/attribute.rb,
lib/carray/construct.rb,
lib/carray/construct.rb,
lib/carray/construct.rb,
lib/carray/histogram.rb,
lib/carray/histogram.rb,
lib/carray/serialize.rb,
lib/carray/axis_group.rb,
lib/carray/bincount_nd.rb,
lib/carray/bincount_nd.rb,
lib/carray/categorical.rb,
lib/carray/conditional.rb,
lib/carray/fuse_source.rb,
lib/carray/methods/bin.rb,
lib/carray/arrow_tensor.rb,
lib/carray/const_string.rb,
lib/carray/methods/join.rb,
lib/carray/methods/mode.rb,
lib/carray/methods/snap.rb,
lib/carray/fixlen_string.rb,
lib/carray/mask_gap_fill.rb,
lib/carray/methods/index.rb,
lib/carray/methods/is_in.rb,
lib/carray/block_iterator.rb,
lib/carray/boolean_reduce.rb,
lib/carray/methods/choose.rb,
lib/carray/methods/resize.rb,
lib/carray/methods/unique.rb,
lib/carray/autoload_carray.rb,
lib/carray/autoload_carray.rb,
lib/carray/autoload_carray.rb,
lib/carray/autoload_carray.rb,
lib/carray/autoload_carray.rb,
lib/carray/autoload_carray.rb,
lib/carray/autoload_carray.rb,
lib/carray/autoload_carray.rb,
lib/carray/autoload_carray.rb,
lib/carray/autoload_carray.rb,
lib/carray/autoload_carray.rb,
lib/carray/autoload_carray.rb,
lib/carray/core_extensions.rb,
lib/carray/methods/nunique.rb,
lib/carray/window_iterator.rb,
lib/carray/methods/bincount.rb,
lib/carray/methods/meshgrid.rb,
lib/carray/methods/broadcast.rb,
lib/carray/methods/gather_nd.rb,
lib/carray/methods/align_addr.rb,
lib/carray/methods/bit_string.rb,
lib/carray/data_type_extension.rb,
lib/carray/methods/composition.rb,
lib/carray/methods/locate_addr.rb,
lib/carray/categorical_iterator.rb,
lib/carray/methods/insert_block.rb,
lib/carray/methods/value_counts.rb,
lib/carray/methods/string_format.rb,
lib/carray/methods/mask_duplicates.rb,
lib/carray/string_operation_extension.rb,
yard-stubs/ca_obj_fake.rb,
yard-stubs/ca_obj_grid.rb,
yard-stubs/ca_obj_roll.rb,
yard-stubs/ca_obj_tile.rb,
yard-stubs/carray_cast.rb,
yard-stubs/carray_copy.rb,
yard-stubs/carray_core.rb,
yard-stubs/carray_lazy.rb,
yard-stubs/carray_loop.rb,
yard-stubs/carray_mask.rb,
yard-stubs/carray_math.rb,
yard-stubs/carray_slab.rb,
yard-stubs/carray_sort.rb,
yard-stubs/carray_test.rb,
yard-stubs/ruby_carray.rb,
yard-stubs/ca_obj_array.rb,
yard-stubs/ca_obj_field.rb,
yard-stubs/ca_obj_refer.rb,
yard-stubs/ca_obj_shift.rb,
yard-stubs/carray_class.rb,
yard-stubs/carray_count.rb,
yard-stubs/carray_order.rb,
yard-stubs/carray_utils.rb,
yard-stubs/ca_obj_farray.rb,
yard-stubs/ca_obj_stride.rb,
yard-stubs/ca_obj_window.rb,
yard-stubs/carray_access.rb,
yard-stubs/carray_random.rb,
yard-stubs/carray_element.rb,
yard-stubs/carray_scatter.rb,
yard-stubs/ca_obj_bitarray.rb,
yard-stubs/ca_obj_bitfield.rb,
yard-stubs/carray_generate.rb,
yard-stubs/ca_obj_byte_swap.rb,
yard-stubs/ca_obj_transpose.rb,
yard-stubs/carray_attribute.rb,
yard-stubs/carray_broadcast.rb,
yard-stubs/carray_conversion.rb,
yard-stubs/carray_memory_view.rb,
yard-stubs/carray_median_percentile.rb

Overview

DOCUMENTATION ONLY — DO NOT REQUIRE. Stubs for methods defined in ext/carray_median_percentile.c. See yard-stubs/README.md and yard-stubs/STYLE.md.

Direct Known Subclasses

CAView, CAWrap, CScalar

Defined Under Namespace

Modules: ArrowTensor, CoreExtensions, DataTypeExtension, DataTypeNewConstructor, FuseSource, Fusion, StringOperationMixin, TableMethods Classes: BincountND, DataTypeError, Histogram, Inspector, Serializer

Constant Summary collapse

LAZY_MONOP_OP_IDS =

op_name => CAMonOp::OP_

{
  # Preserve-data_type monop (8)
  zero:    CAMonOp::OP_ZERO,
  one:     CAMonOp::OP_ONE,
  frac:    CAMonOp::OP_FRAC,
  neg:     CAMonOp::OP_NEG,
  bit_neg: CAMonOp::OP_BIT_NEG,
  abs_i:   CAMonOp::OP_ABS_I,
  conj:    CAMonOp::OP_CONJ,
  not:     CAMonOp::OP_NOT,

  # Preserve-data_type monfunc (4)
  ceil:    CAMonOp::OP_CEIL,
  floor:   CAMonOp::OP_FLOOR,
  round:   CAMonOp::OP_ROUND,
  rcp:     CAMonOp::OP_RCP,

  # Widening monfunc (22)
  rad:     CAMonOp::OP_RAD,
  deg:     CAMonOp::OP_DEG,
  sqrt:    CAMonOp::OP_SQRT,
  exp:     CAMonOp::OP_EXP,
  exp2:    CAMonOp::OP_EXP2,
  exp10:   CAMonOp::OP_EXP10,
  log:     CAMonOp::OP_LOG,
  log10:   CAMonOp::OP_LOG10,
  log2:    CAMonOp::OP_LOG2,
  logb:    CAMonOp::OP_LOGB,
  sin:     CAMonOp::OP_SIN,
  cos:     CAMonOp::OP_COS,
  tan:     CAMonOp::OP_TAN,
  asin:    CAMonOp::OP_ASIN,
  acos:    CAMonOp::OP_ACOS,
  atan:    CAMonOp::OP_ATAN,
  sinh:    CAMonOp::OP_SINH,
  cosh:    CAMonOp::OP_COSH,
  tanh:    CAMonOp::OP_TANH,
  asinh:   CAMonOp::OP_ASINH,
  acosh:   CAMonOp::OP_ACOSH,
  atanh:   CAMonOp::OP_ATANH,

  # Additional monfunc
  expm1:   CAMonOp::OP_EXPM1,
  log1p:   CAMonOp::OP_LOG1P,
  rsqrt:   CAMonOp::OP_RSQRT,
  trunc:   CAMonOp::OP_TRUNC,
  square:  CAMonOp::OP_SQUARE,

  # Angle normalisation
  deg_360: CAMonOp::OP_DEG_360,
  deg_180: CAMonOp::OP_DEG_180,
  rad_2pi: CAMonOp::OP_RAD_2PI,
  rad_pi:  CAMonOp::OP_RAD_PI,

  # Sign function (preserves the data type).  bool/uint → 0/1, sint → -1/0/1,
  # float → -1/0/1 NaN-preserving, complex → unit vector or 0.
  sign:    CAMonOp::OP_SIGN,

  # imag_i: type-preserving primitive (0 for numeric, cimag for complex
  # in the real slot).  Primarily consumed by the `imag` special case
  # below but also directly callable via `a.lazy.imag_i`; entry here
  # so the direct call fuses instead of falling to eager.
  imag_i:  CAMonOp::OP_IMAG_I,
}.freeze
LAZY_BINOP_OP_IDS =

Binop dispatch. Operator entries are redefined so a lazy operand on either side routes into CABinOp.build. Op scope:

- 5 arithmetic: + - * / **
- 3 bitwise:    & | ^
- 2 shifts:     << >>
- 2 misc:       %, rcp_mul

{
  :+         => CABinOp::OP_ADD,
  :-         => CABinOp::OP_SUB,
  :*         => CABinOp::OP_MUL,
  :/         => CABinOp::OP_DIV,
  :**        => CABinOp::OP_POW,
  :&         => CABinOp::OP_BIT_AND,
  :|         => CABinOp::OP_BIT_OR,
  :^         => CABinOp::OP_BIT_XOR,
  :<<        => CABinOp::OP_BIT_LSHIFT,
  :>>        => CABinOp::OP_BIT_RSHIFT,
  :%         => CABinOp::OP_MOD,
  :rcp_mul   => CABinOp::OP_RCP_MUL,

  # Float-only binops registered eagerly by mkkernel; the lazy entries
  # here pick them up so `a.lazy.hypot(b)` etc. ride the substrate.
  :copysign  => CABinOp::OP_COPYSIGN,
  :logaddexp => CABinOp::OP_LOGADDEXP,
  :nextafter => CABinOp::OP_NEXTAFTER,
  :fmod      => CABinOp::OP_FMOD,
  :atan2     => CABinOp::OP_ATAN2,
  :hypot     => CABinOp::OP_HYPOT,

  # Pair-wise max / min (NaN-skip via C99 fmax/fmin on float branch).
  :pmax      => CABinOp::OP_PMAX,
  :pmin      => CABinOp::OP_PMIN,

  # Pair-wise max / min, NaN-propagate variant.
  :maximum   => CABinOp::OP_MAXIMUM,
  :minimum   => CABinOp::OP_MINIMUM,

  # Boolean word forms (bool + object; plain mask propagation, no
  # Kleene fixup — see the CA_BINOP_AND note in ca_binop_dispatch.h).
  :and       => CABinOp::OP_AND,
  :or        => CABinOp::OP_OR,
  :xor       => CABinOp::OP_XOR,

  # IEEE 754 remainder (distinct semantics from `%` / `mod`: float
  # branch uses C99 `remainder`, round-half-to-even).
}.freeze
LAZY_TRIOP_OP_IDS =

Triop dispatch (fma / fms / clip). CATriOp is the CABinOp analog for three-operand element-wise ops. Each Ruby method redefined below dispatches to CATriOp.build when any of self / op2 / op3 is a lazy view, and falls to the eager C method otherwise.

clip is the strict-clamp entry (__clip_ki__, called by the lib/carray/basics.rb clip wrapper's both-bounds-present path). The nil-bound one-sided cases route through the wrapper's pmax / pmin calls, which themselves lazy-fuse via LAZY_BINOP_OP_IDS above — so a.lazy.clip(nil, hi) and a.lazy.clip(lo, nil) fuse without a dedicated triop entry.

{
  fma:         CATriOp::OP_FMA,
  fms:         CATriOp::OP_FMS,
  __clip_ki__: CATriOp::OP_CLIP,
}.freeze
LAZY_BINCMP_OP_IDS =

coerce: when self is a lazy view and the scalar appears on the LEFT (e.g. 2 * a.lazy), Ruby's Numeric#* calls a.lazy.coerce(2). The default coerce would unwrap the lazy-ness via eager scalar promotion; here we keep it lazy by returning [scalar_as_cscalar, self], so the subsequent operator call ends up with a lazy receiver and triggers the CABinOp builder.

bincmp / moncmp dispatch.

Comparison output is always boolean8_t, so it cannot reuse the CABinOp in-place trick. CABinCmp pulls both operands into operand-data_type scratches and writes boolean to the output buffer. Integer is_nan / is_inf / is_finite use existing per-data_type kernels (which handle the integer const-false/true result and mask skip).

Scope: 7 bincmp + 3 moncmp + operator aliases (< / > / <= / >=) for canonical Ruby comparison syntax. Note: == / eql? are NOT comparison ops — eager CArray#== (rb_ca_equal) is array-level equality returning bool, not element-wise. Element-wise equality is eq / feq.

feq is arity 1 in eager (compile-time FLT_EPSILON / DBL_EPSILON); we mirror that here. Runtime eps is a future extension (struct field already reserved).

{
  # Canonical method names + operator aliases (rb_define_alias in C
  # creates separate dispatch entries, so we override both).
  :lt  => CABinCmp::OP_LT,
  :<   => CABinCmp::OP_LT,
  :gt  => CABinCmp::OP_GT,
  :>   => CABinCmp::OP_GT,
  :le  => CABinCmp::OP_LE,
  :<=  => CABinCmp::OP_LE,
  :ge  => CABinCmp::OP_GE,
  :>=  => CABinCmp::OP_GE,
  :eq  => CABinCmp::OP_EQ,
  :ne  => CABinCmp::OP_NE,
  :feq => CABinCmp::OP_FEQ,
}.freeze
LAZY_BINCMP_TOL_OP_IDS =

tolerance-bearing bincmp ops (= is_close / is_equiv) use the same CABinCmp dispatch but with a 2nd tol positional arg. Kept in a separate dict because the LAZY_BINCMP_OP_IDS define_method block above uses arity 1 (|other|); these need arity 2 (|other, tol|).

{
  :is_close => CABinCmp::OP_IS_CLOSE,
  :is_equiv => CABinCmp::OP_IS_EQUIV,
}.freeze
VERSION =

Library semantic version, e.g. "3.0.0.dev".

""
UNSPECIFIED =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

Sentinel marking "the caller did not give this argument", used by C entry points whose fill value may legitimately be nil (so nil itself cannot mark absence). Never pass it in.

nil
HAVE_COMPLEX =

true when the build links <complex.h>; false otherwise. Complex array types (:cmplx64, :cmplx128) require this to be true.

nil

Class Attribute Summary collapse

Elementwise math collapse

Attributes collapse

Views collapse

Type casting collapse

Copy and conversion collapse

Attach lifecycle collapse

Iteration collapse

Masking collapse

Sorting and searching collapse

Index and address conversion collapse

Equality and hashing collapse

Construction collapse

Construction (typed shorthands) collapse

Construction (legacy-name aliases) collapse

External memory wrapping collapse

Platform inquiries collapse

Data-type inquiries collapse

Statistics collapse

Type guessing collapse

String scanning (internal) collapse

Indexing and slicing collapse

Random collapse

Element access collapse

Scatter and generation collapse

Type inquiry collapse

State inquiry collapse

MemoryView interop collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from DataTypeExtension

arange, empty, eye, full, identity, linspace, ones, zeros

Constructor Details

#initialize(data_type, shape) ⇒ self #initialize(data_type, shape, bytes:) ⇒ self #initialize(data_type, shape) ⇒ self #initialize(data_type, shape) {|idx| ... } ⇒ self

Returns a new instance of CArray.

Overloads:

  • #initialize(data_type, shape) ⇒ self

    Allocates a CArray of the given data_type and shape, with storage left uninitialized (caller is expected to fill it).

    Parameters:

    • data_type (Symbol, Integer, Class, String) —

      element type.

    • shape (Array<Integer>) —

      one extent per axis.

  • #initialize(data_type, shape, bytes:) ⇒ self

    For data_type == :fixlen, sets the per-element byte size. Ignored for numeric types.

    Parameters:

    • data_type (Symbol)
    • shape (Array<Integer>)
    • bytes (Integer)
  • #initialize(data_type, shape) ⇒ self

    With a 0-arity block, calls the block once and broadcasts its return value into every cell of the new array (scalar-fill fast path). This is the dominant CArray.<type>(n) { value } idiom.

    Yield Returns:

    • (Object) —

      value to broadcast.

  • #initialize(data_type, shape) {|idx| ... } ⇒ self

    With an n-arity block, calls the block once per cell with the multi-dimensional index unpacked (|i| for 1-D, |i, j| for 2-D, etc.). The block's return value is stored at that cell. 3.0 breaking: CArray.new(MyStruct, ...) no longer accepts a user class as data_type. Use CARecord.new(MyStruct, *shape) or define class MyArr < CARecord; data_class MyStruct; end.

    Yield Parameters:

    • idx (Array<Integer>) —

      per-axis indices.

    Yield Returns:

    • (Object)


39
# File 'yard-stubs/ca_obj_array.rb', line 39

def initialize(*); end

Class Attribute Details

.expression_evaluator ⇒ #call?

The object asked to compute an expression, or nil. CArray can always walk one, so nothing has to be registered and nothing changes when nothing is; what a registered evaluator adds is a second way to arrive at the same answer, and it may decline.

It is called as call(plan, out) -- see Fusion for what a plan holds -- and answers by filling out and returning something true, or by returning something false having written nothing. Raising is not an answer: one that raises is dropped, with a warning, and expressions are walked from there on.

Returns:

  • (#call, nil)


860
861
862
# File 'lib/carray/lazy.rb', line 860

def expression_evaluator
  @expression_evaluator
end

Class Method Details

._scan_float(str, fill_value = nil) ⇒ Float

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parses str as a single double-precision float. Returns fill_value (or NaN if fill_value is nil) when str is nil or unparseable. Internal helper used by text-format I/O readers; end users should prefer Ruby's Float() / String#to_f.

Parameters:

  • str (String, nil)
  • fill_value (Float, nil) (defaults to: nil)

Returns:

  • (Float)


83
# File 'yard-stubs/carray_utils.rb', line 83

def _scan_float(str, fill_value = nil); end

._scan_int(str, fill_value = nil) ⇒ Integer

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parses str as a single integer. Returns fill_value (or 0 if fill_value is nil) when str is nil or unparseable. Internal helper used by text-format I/O readers.

Parameters:

  • str (String, nil)
  • fill_value (Integer, nil) (defaults to: nil)

Returns:

  • (Integer)


93
# File 'yard-stubs/carray_utils.rb', line 93

def _scan_int(str, fill_value = nil); end

.addr2index(addr, shape:) ⇒ Array<Integer>, Array<CArray>

Class-form of #addr2index that takes an explicit shape: rather than reading it from a receiver. Useful for coordinate arithmetic without allocating a template CArray.

Parameters:

  • addr (Integer, CArray) —

    a flat address or a CArray of them.

  • shape (Array<Integer>) —

    the row-major shape defining the grid.

Returns:

Raises:

  • (ArgumentError) —

    when any addr is out of range or shape: is missing.



111
# File 'yard-stubs/carray_access.rb', line 111

def self.addr2index(addr, shape:); end

.align_addr(*arrays, join: :outer) ⇒ Array<CArray>

Aligns several arrays onto one common set of coordinate values and returns, for each array, the flat addresses that gather it onto that common set. Symmetric N-ary counterpart of the instance method #locate_addr (which is the asymmetric self-against-ref lookup).

Returns [common, idx_0, idx_1, ...]:

  • common is a 1-D CArray of the common coordinate values, chosen by join: (see below), in first-appearance order.
  • idx_k is a common-shaped :int64 CArray of flat addresses into arrays[k]: idx_k[j] is where common[j] lives in arrays[k], or UNDEF when that array lacks the value. Each idx_k is exactly common.locate_addr(arrays[k]).

Reindex each array onto the common grid with project, then compare element-wise (missing coordinates come through masked):

common, idx_a, idx_b = CArray.align_addr(a_coord, b_coord, join: :outer)
a_on_grid = a_data.project(idx_a)   # common-shaped, UNDEF where a lacks it
b_on_grid = b_data.project(idx_b)

Because the addresses are returned (not the reindexed values), one alignment serves any number of arrays[k]-shaped variables — compute the idx once, project many.

join: selects the common coordinate set:

  • :outer — union of the distinct values of every array.
  • :inner — distinct values present in every array.
  • :left — the first array's distinct values.
  • :right — the last array's distinct values.

Value equality follows the value-hash discovery family (numeric == with NaN collapsed and -0.0 == +0.0; object hash / eql?; fixlen byte equality). Arrays are coerced to the first array's data type within the same family (cross-family raises). Masked cells do not enter common.

Parameters:

  • arrays (Array<CArray>) —

    two or more arrays (Array / Range coerced via to_ca). One array is allowed (degenerate: common is its distinct values).

  • join (:outer, :inner, :left, :right) (defaults to: :outer) —

    how to build common.

Returns:

Raises:

  • (ArgumentError) —

    when no array is given or join is not one of the accepted symbols.

Raises:

  • (ArgumentError)


46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/carray/methods/align_addr.rb', line 46

def self.align_addr (*arrays, join: :outer)
  raise ArgumentError, "align_addr: need at least one array" if arrays.empty?
  arrays = arrays.map { |a| a.is_a?(CArray) ? a : a.to_ca }
  # Seed the fold with the first array's distinct values so N == 1 and the
  # union/intersection folds all agree (a bare reduce over one element would
  # return it with duplicates intact).
  seed = arrays.first.unique
  common = case join
           when :outer then arrays[1..-1].reduce(seed) { |acc, a| acc.union(a) }
           when :inner then arrays[1..-1].reduce(seed) { |acc, a| acc.intersection(a) }
           when :left  then seed
           when :right then arrays.last.unique
           else
             raise ArgumentError,
                   "align_addr: join must be :outer / :inner / :left / :right " \
                   "(got #{join.inspect})"
           end
  idxs = arrays.map { |a| common.locate_addr(a) }
  [common, *idxs]
end

.align_nearest_addr(*arrays, grid: nil, direction: :round, tolerance: nil) ⇒ Array<CArray>

Aligns several arrays onto one common coordinate grid by nearest match, the ordered-lane (continuous) sibling of align_addr. Returns [common, idx_0, idx_1, ...] with the same reindex contract: idx_k is a common-shaped :int64 array of flat addresses into arrays[k] giving, for each grid point, the nearest value in that array — exactly common.locate_nearest_addr(arrays[k], direction:, tolerance:).

Unlike align_addr, the common grid is not built by a set union: continuous coordinates rarely coincide exactly, so a union would merely pile up near-duplicate points. Instead the grid is a reference axis — grid: when given, otherwise the first array verbatim (kept as-is, not deduplicated). Pass grid: arrays.last to align onto the last array's axis. (join: has no meaning here and is not accepted; clustering nearby coordinates into a synthesised grid is out of scope.)

common, ia, ib = CArray.align_nearest_addr(a_coord, b_coord, grid: ref)
a_on_grid = a_data.project(ia)   # each grid point <- nearest a value
b_on_grid = b_data.project(ib)

direction: (:round / :floor / :ceil) and tolerance: are forwarded to #locate_nearest_addr: out-of-range grid points, and points whose nearest value is farther than tolerance, come back masked.

Parameters:

  • arrays (Array<CArray>) —

    one or more arrays (Array / Range coerced via to_ca).

  • grid (CArray, Array, Range, nil) (defaults to: nil) —

    the reference coordinate grid; nil uses the first array verbatim.

  • direction (:round, :floor, :ceil) (defaults to: :round) —

    rounding rule for the nearest match.

  • tolerance (Numeric, nil) (defaults to: nil) —

    maximum accepted distance; farther grid points are masked. nil disables the check.

Returns:

Raises:

  • (ArgumentError) —

    when no array is given (or direction is invalid, raised by #locate_nearest_addr).

Raises:

  • (ArgumentError)


102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/carray/methods/align_addr.rb', line 102

def self.align_nearest_addr (*arrays, grid: nil, direction: :round, tolerance: nil)
  raise ArgumentError, "align_nearest_addr: need at least one array" if arrays.empty?
  arrays = arrays.map { |a| a.is_a?(CArray) ? a : a.to_ca }
  common = if grid.nil?
             arrays.first
           else
             grid.is_a?(CArray) ? grid : grid.to_ca
           end
  idxs = arrays.map { |a|
    common.locate_nearest_addr(a, direction: direction, tolerance: tolerance)
  }
  [common, *idxs]
end

.attach(*arrays) { ... } ⇒ Object

Attaches every CArray in arrays, yields, and detaches them in reverse order on block exit. No sync is performed.

Parameters:

Yields:

Returns:

  • (Object) —

    the block's return value.



102
# File 'yard-stubs/carray_core.rb', line 102

def attach(*arrays); end

.attach!(*arrays) { ... } ⇒ Object

Attaches every CArray in arrays, yields, then syncs and detaches each on block exit.

Parameters:

Yields:

Returns:

  • (Object) —

    the block's return value.



110
# File 'yard-stubs/carray_core.rb', line 110

def attach!(*arrays); end

.big_endian? ⇒ Boolean

Returns true if the host byte order is big-endian.

Returns:

  • (Boolean)


19
# File 'yard-stubs/carray_class.rb', line 19

def big_endian?; end

.boolean ⇒ Class .boolean(*shape) ⇒ CArray

Overloads:

  • .boolean ⇒ Class

    Returns the typed class CArray::Boolean.

    Returns:

    • (Class)
  • .boolean(*shape) ⇒ CArray

    Equivalent to CArray.new(:boolean, shape) { ... }.

    Parameters:

    Returns:



82
# File 'yard-stubs/ca_obj_array.rb', line 82

def boolean(*shape); end

.byte(*shape) ⇒ Object

Alias of uint8.



194
# File 'yard-stubs/ca_obj_array.rb', line 194

def byte(*shape); end

.cast(value) ⇒ CArray

Returns value as a CArray. A CArray is returned unchanged; a Ruby value is coerced: Integer to an :int64 CScalar, Float to :float64, true/false to :boolean, Complex to :cmplx128, Array and Range via to_ca, and anything else to an :object CScalar.

Parameters:

  • value (Object) —

    the value to coerce.

Returns:



433
# File 'yard-stubs/carray_cast.rb', line 433

def self.cast(value); end

.cmplx128 ⇒ Class .cmplx128(*shape) ⇒ CArray

Overloads:

  • .cmplx128 ⇒ Class

    Returns the typed class CArray::Cmplx128.

    Returns:

    • (Class)
  • .cmplx128(*shape) ⇒ CArray

    Equivalent to CArray.new(:cmplx128, shape) { ... }.

    Returns:



178
# File 'yard-stubs/ca_obj_array.rb', line 178

def cmplx128(*shape); end

.cmplx64 ⇒ Class .cmplx64(*shape) ⇒ CArray

Overloads:

  • .cmplx64 ⇒ Class

    Returns the typed class CArray::Cmplx64.

    Returns:

    • (Class)
  • .cmplx64(*shape) ⇒ CArray

    Equivalent to CArray.new(:cmplx64, shape) { ... }.

    Returns:



170
# File 'yard-stubs/ca_obj_array.rb', line 170

def cmplx64(*shape); end

.complex(*shape) ⇒ Object

Alias of cmplx64.



214
# File 'yard-stubs/ca_obj_array.rb', line 214

def complex(*shape); end

.concatenate(list, axis: 0, data_type: nil) ⇒ CArray

Returns list concatenated along a single existing axis. Eager (returns a fresh CArray) and accepts non-uniform pieces (varying sizes along the axis); non-tile axes must agree across pieces.

Use CArray.meld for the uniform-shape view-default counterpart.

Parameters:

  • list (Array<CArray>) —

    pieces to concatenate.

  • axis (Integer) (defaults to: 0) —

    axis to concatenate along.

  • data_type (Symbol, Integer, nil) (defaults to: nil) —

    result data_type; inferred via result_type when nil.

Returns:

  • (CArray) —

    fresh CArray with per-piece axis sizes summed.

Raises:

  • (ArgumentError) —

    when list is empty or piece shapes are inconsistent.

Raises:

  • (ArgumentError)


84
85
86
87
# File 'lib/carray/methods/composition.rb', line 84

def self.concatenate (list, axis: 0, data_type: nil)
  raise ArgumentError, "concatenate: list must not be empty" if list.empty?
  __ragged_paste(list, [list.size], axis, data_type)
end

.const_string(values, encoding: Encoding::UTF_8) ⇒ CAConstString .const_string(ca, encoding: Encoding::UTF_8) ⇒ CAConstString .const_string(n, encoding: Encoding::UTF_8) {|i| ... } ⇒ CAConstString

Build a CAConstString (read-only variable-length string column) from Ruby data.

CArray.const_string(["alpha", "", "gamma"])       # 1-D from Array
CArray.const_string(3) { |i| "item#{i}" }         # block form
CArray.const_string([a, nil, b])                   # nil → masked element

B1: "" (length 0) is a valid empty string, distinct from a masked element (nil → masked). B2: element encoding must match :encoding (strict), pure-ASCII strings pass regardless (ASCII-compatible relaxation).

Storage is one (start, end) byte-range pair per element over a pure-concatenation buffer (Arrow string layout). For a high-duplication column (categorical labels), use CACategorical (= Arrow DictionaryArray) instead — CAConstString stores every element's bytes, without dedup.

Overloads:

  • .const_string(values, encoding: Encoding::UTF_8) ⇒ CAConstString

    Returns a read-only CAConstString column packing each String's bytes into a shared buffer. values may be any Array (or Array-like) of Strings; nil entries are masked.

    Parameters:

    • values (Array<String, nil>) —

      source values.

    • encoding (Encoding) (defaults to: Encoding::UTF_8) —

      column encoding.

    Returns:

  • .const_string(ca, encoding: Encoding::UTF_8) ⇒ CAConstString

    Builds from a string-bearing CArray (String Face / CA_OBJECT / raw CA_FIXLEN, the last read as NUL-stripped strings); always materialises.

    Parameters:

    • ca (CArray) —

      source array.

    Returns:

    Raises:

  • .const_string(n, encoding: Encoding::UTF_8) {|i| ... } ⇒ CAConstString

    Returns an n-element CAConstString column filled by the block, following the arity-0 broadcast convention.

    Parameters:

    • n (Integer) —

      element count.

    Yield Parameters:

    • i (Integer) —

      cell index.

    Yield Returns:

    • (String, nil) —

      value for cell i.

    Returns:



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/carray/const_string.rb', line 53

def self.const_string (arg, encoding: Encoding::UTF_8, &block)
  if arg.is_a?(CArray)
    return string_face_of(arg).to_const_string(encoding: encoding)
  end
  if block
    n = Integer(arg)
    # B5: follow CArray.<type>(n){ ... } arity-0 broadcast quirk for
    #     consistency — arity-0 block is evaluated once and broadcast.
    if block.arity == 0
      v = block.call
      values = Array.new(n) { v }
    else
      values = Array.new(n) { |i| block.call(i) }
    end
  else
    values = arg.to_a
  end

  # Arrow-style layout, built in one C pass: pure-concatenation buffer +
  # one (start,end) int64 pair per element, mask for nil.
  CAConstString.__build__(values, encoding)
end

.data_type_code(data_type) ⇒ Integer

Returns the internal int8_t numeric code of data_type (e.g. 8 for :int64, 11 for :float64). Inverse of data_type_name.

Primarily used by Ruby-side code that needs to compute kernel op ids (e.g. CAMonOp::CAST_BASE + code in lib/carray/lazy.rb). End users normally do not need this — compare Symbols or use the CA_* constants directly.

Parameters:

  • data_type (Symbol, Integer, Class, String)

Returns:

  • (Integer)


61
# File 'yard-stubs/carray_class.rb', line 61

def data_type_code(data_type); end

.data_type_name(data_type) ⇒ String

Returns the String name of data_type (e.g. "int32", "float64", "fixlen").

Parameters:

  • data_type (Symbol, Integer, Class, String)

Returns:

  • (String)


48
# File 'yard-stubs/carray_class.rb', line 48

def data_type_name(data_type); end

.dcomplex(*shape) ⇒ Object

Alias of cmplx128.



218
# File 'yard-stubs/ca_obj_array.rb', line 218

def dcomplex(*shape); end

.double(*shape) ⇒ Object

Alias of float64.



210
# File 'yard-stubs/ca_obj_array.rb', line 210

def double(*shape); end

.dump(ca, **opt) ⇒ String

Returns ca serialized to a String in the _CARRAY3 format.

Parameters:

  • ca (CArray) —

    array to serialize.

  • opt (Hash) —

    serializer options (:endian).

Returns:

  • (String)


498
499
500
501
502
# File 'lib/carray/serialize.rb', line 498

def self.dump (ca, **opt)
  io = StringIO.new("".b)
  Serializer.new(io).save(ca, **opt)
  return io.string
end

.each_index(*shape) {|idx| ... } ⇒ Object

Yields each multi-dimensional index inside the box 0...d for each d in shape, in row-major order. Independent of any CArray instance.

Examples:

CArray.each_index(3, 2) { |i, j| print "(#{i} #{j}) " }
# (0 0) (0 1) (1 0) (1 1) (2 0) (2 1)

Parameters:

  • shape (Array<Integer>) —

    one extent per axis.

Yield Parameters:

  • idx (Array<Integer>) —

    one index per axis.

Returns:

  • (Object) —

    the block's last return value.



136
# File 'yard-stubs/carray_loop.rb', line 136

def each_index(*shape); end

.endian ⇒ Integer

Returns the host byte order as an Integer: 0 (CA_LITTLE_ENDIAN) or 1 (CA_BIG_ENDIAN). Prefer big_endian? / little_endian? for predicate use.

Returns:

  • (Integer)


14
# File 'yard-stubs/carray_class.rb', line 14

def endian; end

.fixlen ⇒ Class .fixlen(*shape, bytes:) ⇒ CArray

Overloads:

  • .fixlen ⇒ Class

    Returns the typed class CArray::Fixlen.

    Returns:

    • (Class)
  • .fixlen(*shape, bytes:) ⇒ CArray

    Equivalent to CArray.new(:fixlen, shape, bytes: bytes) { ... }. The bytes: keyword is required for :fixlen.

    Parameters:

    • shape (Array<Integer>)
    • bytes (Integer)

    Returns:



73
# File 'yard-stubs/ca_obj_array.rb', line 73

def fixlen(*shape, bytes: nil); end

.fixlen_string(values, bytes: nil, truncate: :error) ⇒ CAFixlenString .fixlen_string(ca, bytes: nil, truncate: :error) ⇒ CAFixlenString .fixlen_string(n, bytes: nil, truncate: :error) ⇒ CAFixlenString

Build a CAFixlenString (fixed-width String array over CA_FIXLEN storage).

CArray.fixlen_string(["ab", "cde"], bytes: 4)   # explicit slot width
CArray.fixlen_string(["ab", "cde"])             # width = max bytesize
CArray.fixlen_string([a, nil, b], bytes: 8)     # nil → masked element

The bounded slot width is the storage seam CAFixlenString exposes. truncate: controls what happens when a value exceeds bytes (only reachable when bytes is given explicitly; the auto width can never overflow):

:error   (default) raise ArgumentError on overflow 

The overflow policy lives at this construction surface, not at per-cell fix[i] = v (which always truncates silently via the native fixlen store). A CArray source is normalised through a String Face (string_face_of): a raw CA_FIXLEN of matching width wraps zero-copy, other string-bearing arrays materialise, numeric is rejected.

Overloads:

  • .fixlen_string(values, bytes: nil, truncate: :error) ⇒ CAFixlenString

    Parameters:

    • values (Array<String, nil>) —

      source values.

    • bytes (Integer, nil) (defaults to: nil) —

      slot width; defaults to the max bytesize.

    • truncate (Symbol) (defaults to: :error) —

      :error or :silent.

    Returns:

  • .fixlen_string(ca, bytes: nil, truncate: :error) ⇒ CAFixlenString

    Parameters:

    • ca (CArray) —

      a String Face, CA_OBJECT, or raw CA_FIXLEN array.

    Returns:

    Raises:

  • .fixlen_string(n, bytes: nil, truncate: :error) ⇒ CAFixlenString

    Parameters:

    • n (Integer) —

      element count.

    • bytes (Integer, nil) (defaults to: nil) —

      slot width; defaults to the max bytesize.

    • truncate (Symbol) (defaults to: :error) —

      :error or :silent.

    Returns:



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/carray/fixlen_string.rb', line 47

def self.fixlen_string (arg, bytes: nil, truncate: :error, &block)
  if arg.is_a?(CArray)
    return string_face_of(arg).to_fixlen_string(bytes: bytes, truncate: truncate)
  end
  unless [:error, :silent].include?(truncate)
    raise ArgumentError, "truncate: must be :error or :silent (got #{truncate.inspect})"
  end
  if block
    n = Integer(arg)
    if block.arity == 0
      v = block.call
      values = Array.new(n) { v }
    else
      values = Array.new(n) { |i| block.call(i) }
    end
  else
    values = arg.to_a
  end

  width = bytes || values.compact.map { |s| s.to_s.bytesize }.max || 1
  width = 1 if width < 1

  if truncate == :error
    values.each_with_index do |s, i|
      next if s.nil?
      b = s.to_s.bytesize
      if b > width
        raise ArgumentError,
              "CArray.fixlen_string: value at #{i} is #{b} bytes, exceeds slot width #{width} " \
              "(use truncate: :silent to keep the leading bytes)"
      end
    end
  end

  entity = CArray.new(CA_FIXLEN, [values.size], :bytes => width)
  values.each_with_index do |s, i|
    entity[i] = s.nil? ? UNDEF : s.to_s
  end
  CAFixlenString.wrap(entity)
end

.float(*shape) ⇒ Object

Alias of float32.



206
# File 'yard-stubs/ca_obj_array.rb', line 206

def float(*shape); end

.float32 ⇒ Class .float32(*shape) ⇒ CArray

Overloads:

  • .float32 ⇒ Class

    Returns the typed class CArray::Float32.

    Returns:

    • (Class)
  • .float32(*shape) ⇒ CArray

    Equivalent to CArray.new(:float32, shape) { ... }.

    Returns:



154
# File 'yard-stubs/ca_obj_array.rb', line 154

def float32(*shape); end

.float64 ⇒ Class .float64(*shape) ⇒ CArray

Overloads:

  • .float64 ⇒ Class

    Returns the typed class CArray::Float64.

    Returns:

    • (Class)
  • .float64(*shape) ⇒ CArray

    Equivalent to CArray.new(:float64, shape) { ... }.

    Returns:



162
# File 'yard-stubs/ca_obj_array.rb', line 162

def float64(*shape); end

.format(fmt, *argv) ⇒ CAString

Returns a CAString of formatted strings. Each output cell at index idx is Kernel.format(fmt, *args) where a CArray argument contributes its [*idx] cell and any non-CArray argument is broadcast as-is. The output shape is taken from the first CArray argument; every CArray argument must share that shape.

Parameters:

  • fmt (String) —

    Kernel.format template.

  • argv (Array<CArray, Object>) —

    per-cell CArrays and/or broadcast scalars.

Returns:

Raises:

  • (ArgumentError) —

    when no CArray argument is given, or CArray shapes differ.

Raises:

  • (ArgumentError)


18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/carray/methods/string_format.rb', line 18

def self.format (fmt, *argv)
  cas = argv.select { |a| a.is_a?(CArray) }
  raise ArgumentError, "CArray.format: at least one CArray argument is required" if cas.empty?
  shape = cas.first.shape
  cas.each do |a|
    next if a.shape == shape
    raise ArgumentError,
          "CArray.format: shape mismatch (#{a.shape.inspect} vs #{shape.inspect})"
  end
  out = CArray.object(*shape)
  out.map_with_index! do |_, *idx|
    args = argv.map { |a| a.is_a?(CArray) ? a[*idx] : a }
    # a masked cell in any source array masks the output (UNDEF), rather
    # than feeding UNDEF into Kernel.format.
    args.any? { |v| v.equal?(UNDEF) } ? UNDEF : Kernel.format(fmt, *args)
  end
  CAString.wrap(out)
end

.from_bit_string(bstr, nb, data_type = CA_INT32, dim = nil) ⇒ CArray

Returns a new CArray built by unpacking bstr as a packed-bit byte string with nb bits per element.

Parameters:

  • bstr (String) —

    packed byte string.

  • nb (Integer) —

    bits per element.

  • data_type (Symbol, Integer) (defaults to: CA_INT32) —

    result data_type.

  • dim (Array<Integer>, nil) (defaults to: nil) —

    result shape; when nil the length is floor(bstr.length * 8 / nb).

Returns:



41
42
43
44
45
46
47
48
49
50
# File 'lib/carray/methods/bit_string.rb', line 41

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

.from_memory_view(src, data_type: nil, mask: nil) ⇒ CArray

Returns a new CArray that owns an independent copy of src's buffer. Accepts both contiguous and strided producers; strided sources are gathered into a freshly allocated row-major buffer.

For typeless producers (format nil, e.g. byte blobs from IO#read), data_type: is required and the byte buffer is reinterpreted as that data type with ndim = 1. For typed producers data_type: is optional; when given it must match the producer's format.

mask: accepts a paired buffer-protocol source whose shape matches src and whose item size is 1 (PEP 3118 ? / B / b). The mask bytes are copied into the canonical CA_BOOLEAN mask slot with non-zero coerced to 1. The copy is independent of both buffers after the call.

Examples:

Copy from a strided source

a = CArray.int32(4, 3).seq
b = CArray.from_memory_view(a.transpose)
b.shape    # => [3, 4]
b.equal?(a)  # => false

Copy paired (data, mask) — independent of source

data = CArray.uint8(3) { |i| i }
mask = CArray.boolean(3) { |i| i.zero? ? 1 : 0 }
c = CArray.from_memory_view(data, mask: mask)
c.has_mask?   # => true
data[0] = 99  # source change does not reach c

Parameters:

  • src (Object) —

    any MemoryView producer.

  • data_type (Symbol, Integer, Class, nil) (defaults to: nil) —

    target data type. Required for typeless producers; optional (must match producer format) for typed ones.

  • mask (Object, nil) (defaults to: nil) —

    optional paired mask MemoryView source. Must match src.shape and use a 1-byte/element format.

Returns:

  • (CArray) —

    independent copy; not a CAWrap.

Raises:

  • (ArgumentError) —

    if src is not a MemoryView producer, if data_type: is missing for a typeless source, if data_type: conflicts with the producer's format, or if the supplied mask: fails shape / data type / contiguity validation.



82
# File 'yard-stubs/carray_memory_view.rb', line 82

def from_memory_view(src, data_type: nil, mask: nil); end

.fuse({ <expression> }) ⇒ Object

Builds the expression rather than evaluating it, so that it is computed in one pass with no array standing for a step along the way.

The block is not called. Its source is read, every name in it that holds a CArray is given .lazy, and the result is evaluated back in the block's own binding -- so self, instance variables, methods and constants are what they were where it was written.

out[] = CArray.fuse { (a + b) * (c - a) }
total = CArray.fuse { a * weight }.sum

What comes back is the expression, not an array: it is computed where it is used -- stored into an array, reduced, or asked for one with to_ca. A block holding anything but an expression over arrays comes back as whatever it evaluated to.

Returns:

  • (Object) —

    the expression, as a lazy view

Raises:

  • (LocalJumpError) —

    when no block is given.

  • (ArgumentError) —

    when the block's source cannot be read -- in irb, in eval, or from a file that is gone. Write .lazy on the operands there: a.lazy + b.lazy.

Raises:

  • (LocalJumpError)


894
895
896
897
898
899
900
901
902
903
# File 'lib/carray/lazy.rb', line 894

def fuse (*args, &block)
  raise LocalJumpError, "CArray.fuse requires a block" unless block
  unless args.empty?
    raise ArgumentError,
          "CArray.fuse takes no arguments: write the expression itself, " \
          "`CArray.fuse { a + b }`, and the names in it are read from " \
          "where the block was written"
  end
  CArray::FuseSource.evaluate(block)
end

.guard_undef(*values, fill_value: UNDEF) {|values| ... } ⇒ Object

Returns fill_value immediately if any element of values is UNDEF; otherwise yields all values to the block and returns the block's result.

CArray.guard_undef(a, b) { |x, y| x / y }    # UNDEF if a or b masked
CArray.guard_undef(v, fill_value: 0.0) { |x| Math.sqrt(x) }

Parameters:

  • values (Array<Object>) —

    scalar values to test.

  • fill_value (Object) (defaults to: UNDEF) —

    value returned on short-circuit. Defaults to UNDEF.

Yield Parameters:

  • values (Array<Object>) —

    the non-UNDEF values.

Yield Returns:

  • (Object) —

    computation result.

Returns:

  • (Object)


255
# File 'yard-stubs/carray_mask.rb', line 255

def guard_undef(*values, fill_value: UNDEF); end

.guess_type_and_bytes(type_spec, bytes = nil) ⇒ Array(Integer, Integer)

Resolves a user-supplied type spec into the pair [data_type_code, bytes]. data_type_code is the internal int8_t numeric code (see data_type_code); bytes is the per-element byte size (0 for non-:fixlen).

Parameters:

  • type_spec (Symbol, Integer, Class, String)
  • bytes (Integer, nil) (defaults to: nil) —

    element byte size, used only for :fixlen.

Returns:

  • (Array(Integer, Integer))


67
# File 'yard-stubs/carray_utils.rb', line 67

def guess_type_and_bytes(type_spec, bytes = nil); end

.index2addr(*index, shape:) ⇒ Integer, CArray

Class-form of #index2addr.

Parameters:

  • index (Array<Integer, CArray>) —

    one entry per axis.

  • shape (Array<Integer>) —

    the row-major shape defining the grid.

Returns:

  • (Integer, CArray) —

    the flat address(es).

Raises:

  • (ArgumentError) —

    on out-of-range index, shape mismatch, or missing shape:.



120
# File 'yard-stubs/carray_access.rb', line 120

def self.index2addr(*index, shape:); end

.int(*shape) ⇒ Object

Alias of int32.



202
# File 'yard-stubs/ca_obj_array.rb', line 202

def int(*shape); end

.int16 ⇒ Class .int16(*shape) ⇒ CArray

Overloads:

  • .int16 ⇒ Class

    Returns the typed class CArray::Int16.

    Returns:

    • (Class)
  • .int16(*shape) ⇒ CArray

    Equivalent to CArray.new(:int16, shape) { ... }.

    Returns:



106
# File 'yard-stubs/ca_obj_array.rb', line 106

def int16(*shape); end

.int32 ⇒ Class .int32(*shape) ⇒ CArray

Overloads:

  • .int32 ⇒ Class

    Returns the typed class CArray::Int32.

    Returns:

    • (Class)
  • .int32(*shape) ⇒ CArray

    Equivalent to CArray.new(:int32, shape) { ... }.

    Returns:



122
# File 'yard-stubs/ca_obj_array.rb', line 122

def int32(*shape); end

.int64 ⇒ Class .int64(*shape) ⇒ CArray

Overloads:

  • .int64 ⇒ Class

    Returns the typed class CArray::Int64.

    Returns:

    • (Class)
  • .int64(*shape) ⇒ CArray

    Equivalent to CArray.new(:int64, shape) { ... }.

    Returns:



138
# File 'yard-stubs/ca_obj_array.rb', line 138

def int64(*shape); end

.int8 ⇒ Class .int8(*shape) ⇒ CArray

Overloads:

  • .int8 ⇒ Class

    Returns the typed class CArray::Int8.

    Returns:

    • (Class)
  • .int8(*shape) ⇒ CArray

    Equivalent to CArray.new(:int8, shape) { ... }.

    Returns:



90
# File 'yard-stubs/ca_obj_array.rb', line 90

def int8(*shape); end

.jit_each({ ... }) ⇒ Object

Runs a block over the cells of arrays at once, naming each cell by the array it came from, and writing what it computes into arrays of yours: CArray.jit_each { out = a + b * c }. The block is compiled, and the compiler is the carray-jit gem.

Raises:

  • (NotImplementedError) —

    when that gem is not installed.

Raises:

  • (NotImplementedError)


920
921
922
# File 'lib/carray/lazy.rb', line 920

def jit_each (&block)
  raise NotImplementedError, no_compiler("jit_each")
end

.jit_for(*extents{ |i, j, ...| ... }) ⇒ Object

Runs a block over an index space, so that a cell may reach the ones around it -- a recurrence, a stencil. The block is compiled, and the compiler is the carray-jit gem.

Raises:

  • (NotImplementedError) —

    when that gem is not installed.

Raises:

  • (NotImplementedError)


910
911
912
# File 'lib/carray/lazy.rb', line 910

def jit_for (*extents, **options)
  raise NotImplementedError, no_compiler("jit_for")
end

.jit_map({ ... }) ⇒ Object

The same block with its value asked for: the last statement is what every cell of the result gets, and the result comes back. The block is compiled, and the compiler is the carray-jit gem.

Raises:

  • (NotImplementedError) —

    when that gem is not installed.

Raises:

  • (NotImplementedError)


929
930
931
# File 'lib/carray/lazy.rb', line 929

def jit_map (&block)
  raise NotImplementedError, no_compiler("jit_map")
end

.little_endian? ⇒ Boolean

Returns true if the host byte order is little-endian.

Returns:

  • (Boolean)


24
# File 'yard-stubs/carray_class.rb', line 24

def little_endian?; end

.load(input, **opt) ⇒ CArray

Reads a _CARRAY3 payload from input. A String starting with the CArray magic is decoded in place; other Strings are treated as file paths; anything else is used as IO.

Parameters:

  • input (String, IO) —

    source path, in-memory payload, or IO.

  • opt (Hash) —

    loader options (:data_type).

Returns:



476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
# File 'lib/carray/serialize.rb', line 476

def self.load (input, **opt)
  case input
  when String
    if input.bytesize >= Serializer::HEADER_BYTES and
       input.byteslice(0, 8) == Serializer::MAGIC
      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

.load_arrow_tensor(filename) ⇒ CArray

Reads an Arrow tensor IPC file and returns it as a new CArray.

Experimental, and the name is provisional.

Parameters:

  • filename (String) —

    path to the message.

Returns:

See Also:



385
386
387
# File 'lib/carray/arrow_tensor.rb', line 385

def self.load_arrow_tensor (filename)
  File.open(filename, "rb") { |io| ArrowTensor.read(io) }
end

.meld(*arrays, axis: 0) ⇒ Object .meld(list, axis: 0) ⇒ CAMeld

Returns a CAMeld view of the arrays welded along an existing axis. No data is copied; reads gather from parents on demand and writes flow back to them (chain composability preserved).

Pieces must agree on ndim, data_type, byte width, and every axis length except axis (the "meld axis"). Mismatched data_type raises: cast the pieces yourself (.to_type(:float64)) or use concatenate (eager, auto-casts).

"meld" = melt + weld — pieces dissolve their boundaries along the named axis and are regarded as one.

Overloads:

  • .meld(list, axis: 0) ⇒ CAMeld

    Convenience form: a single Array argument is treated as the list.

    Parameters:

    • arrays (Array<CArray>) —

      pieces to weld. A single Array argument is accepted for compatibility with older callers.

    • axis (Integer) (defaults to: 0) —

      existing axis to extend (normalises negative values against the reference ndim).

    Returns:

    • (CAMeld) —

      view over the welded pieces.

    Raises:

    • (ArgumentError) —

      when the list is empty, ndim mismatch, data_type mismatch, or non-axis dim mismatch across pieces (surfaced by CAMeld.new).

Raises:

  • (ArgumentError)


89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/carray/stack.rb', line 89

def self.meld (*arrays, axis: 0)
  if arrays.length == 1 && arrays[0].is_a?(Array)
    arrays = arrays[0]
  end
  raise ArgumentError, "meld: list must not be empty" if arrays.empty?
  first = arrays[0]
  unless first.is_a?(CArray)
    raise ArgumentError, "meld: entries must be CArray (got #{first.class})"
  end
  axis_norm = CArray.normalize_axis(axis, first.ndim, "meld")
  # Flatten nested CAMeld inputs that share our meld axis: they already
  # describe a segment sequence, so absorbing their parents keeps chain
  # depth at 1 (avoids 2-level xfer_all / reduce chains through the
  # intermediate CAMeld).  A CAMeld with a different meld_axis is left
  # intact — its segment structure is orthogonal.
  if arrays.any? { |a| a.is_a?(CAMeld) && a.meld_axis == axis_norm }
    arrays = arrays.flat_map { |a|
      a.is_a?(CAMeld) && a.meld_axis == axis_norm ? a.parents : [a]
    }
  end
  CAMeld.new(arrays, axis: axis_norm)
end

.memory_view_available?(obj) ⇒ Boolean

Returns true if obj exposes the Ruby rb_memory_view protocol and a view can be acquired from it. Lightweight probe used to gate from_memory_view / wrap_memory_view calls.

Returning true does not guarantee acquisition will succeed — a producer may still refuse a particular flag combination at acquisition time.

Examples:

CArray.memory_view_available?(CArray.int32(3))      # => true
CArray.memory_view_available?("plain string")        # => false

Parameters:

  • obj (Object) —

    any object (typically a foreign array such as Numo::NArray, Arrow::Array, a bytearray, or a CArray).

Returns:

  • (Boolean)


24
# File 'yard-stubs/carray_memory_view.rb', line 24

def memory_view_available?(obj); end

.memory_view_reject_reason(obj) ⇒ String?

Returns a String explaining why CArray's MemoryView producer refuses to export obj, or nil if no problem is detected.

Diagnostic only; useful when memory_view_available? returns false on a CArray and the generic "memory view not available" error does not say which link in the parent chain caused the reject. Consumers that need to debug an alias-chain reject (mask propagation, non-contiguous strided view, etc.) call this to print a human-readable reason.

Parameters:

  • obj (Object)

Returns:

  • (String, nil) —

    reason text, or nil when acquisition would succeed.



39
# File 'yard-stubs/carray_memory_view.rb', line 39

def memory_view_reject_reason(obj); end

.meshgrid(*axes, indexing: "xy", copy: true, sparse: false) {|grids| ... } ⇒ Array<CArray>

Returns coordinate matrices built from 1-D coordinate vectors.

Given N 1-D vectors, produces N arrays each broadcasting one input axis across the others. Useful for evaluating a function on a grid.

With indexing: "xy" (default) the first two axes are swapped in the output shape (matrix-style convention): meshgrid(x, y) gives outputs of shape [y.elements, x.elements]. With indexing: "ij" input order is preserved: meshgrid(x, y, indexing: "ij") gives outputs of shape [x.elements, y.elements]. For more than two axes only the first two are swapped under "xy"; the remaining axes follow input order in both modes.

When copy is true (default) each output is a materialised CArray; when false, a view is returned. When sparse is true each output keeps a size-1 axis wherever the full grid would repeat, and broadcasts on demand, saving memory for large grids.

If a block is given, yields the resulting arrays as splat arguments and returns the block's value.

Each axis goes through wrap_readonly, so a coordinate vector may be given as anything that entry point accepts (a CArray, an Array, a Range, a Numeric, a MemoryView producer, an object answering ca / to_ca); its own data type is kept.

Examples:

x = CA_FLOAT64([1.0, 2.0, 3.0])
y = CA_FLOAT64([10.0, 20.0])
xx, yy = CArray.meshgrid(x, y)
xx.shape        # => [2, 3]
yy.to_a         # => [[10.0, 10.0, 10.0], [20.0, 20.0, 20.0]]

Parameters:

  • axes (Array<CArray, Array, Object>) —

    1-D coordinate vectors.

  • indexing (String) (defaults to: "xy") —

    "xy" or "ij".

  • copy (Boolean) (defaults to: true) —

    materialise each output when true.

  • sparse (Boolean) (defaults to: false) —

    return broadcast-on-demand views when true.

Yield Parameters:

  • grids (Array<CArray>) —

    the resulting coordinate arrays.

Returns:

  • (Array<CArray>) —

    the coordinate arrays, or the block's return value.

Raises:

  • (ArgumentError) —

    when indexing is neither "xy" nor "ij", or when a coordinate vector is not 1-D.



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/carray/methods/meshgrid.rb', line 47

def self.meshgrid (*axes, indexing: "xy", copy: true, sparse: false, &block)
  unless %w[xy ij].include?(indexing)
    raise ArgumentError, %{indexing option should be one of "xy" and "ij"}
  end

  # Each axis is negotiable, so no target type is imposed here; a
  # CArray comes back as itself and anything else is brought in with
  # its own data type.
  axes = axes.map.with_index do |axis, k|
    a = CArray.wrap_readonly(axis)
    unless a.ndim == 1
      raise ArgumentError,
            "coordinate vector #{k} should be 1-D (got #{a.ndim}-D)"
    end
    a
  end

  ndim = axes.size

  # dest[k] = output axis position that input axis k populates.
  # "xy" swaps the first two; everything else is in input order.
  dest = (0...ndim).to_a
  dest[0], dest[1] = 1, 0 if indexing == "xy" && ndim >= 2

  # Output shape: each output axis i takes its size from the input
  # axis that maps there.
  out_shape = Array.new(ndim)
  axes.each_with_index { |a, k| out_shape[dest[k]] = a.size }

  list = axes.map.with_index do |axis, k|
    d = dest[k]
    idx = if sparse
            Array.new(ndim) { |i| i == d ? nil : :_ }
          else
            out_shape.dup.tap { |s| s[d] = :% }
          end
    view = axis[*idx]
    copy ? view.copy : view
  end

  block ? block.call(*list) : list
end

.montage(list, tdim, axis: 0, data_type: nil) ⇒ CArray

Arrange list of uniform-shape pieces in a tdim-shape grid that extends parent axes axis..axis+tdim.size-1 by the corresponding tdim[i] factor (= ImageMagick montage analog). Output ndim equals each piece's ndim; the tile axes occupy positions axis..axis+tdim.size-1. Returns a view; call .to_ca to materialise.

tdim.product must equal list.size. For non-uniform pieces along tile axes, use CArray.mosaic.

Example (parent shape (3, 4), 6-element list, tdim=[2, 3], axis: 0):

CArray.montage([a, b, c, d, e, f], [2, 3], axis: 0)
#=> shape (6, 12) -- 2 rows x 3 cols grid of (3, 4) blocks
#   +-----+-----+-----+
#   |  a  |  b  |  c  |  rows 0..2
#   +-----+-----+-----+
#   |  d  |  e  |  f  |  rows 3..5
#   +-----+-----+-----+

3.0 (post K_AXIS / promote_list / stack rename): renamed from combine (= 20-year vocabulary that didn't describe the action). Positional at replaced with axis: kwarg for consistency with bind / stack. Parameter order changed from (tdim, list, at) to (list, tdim, axis:) to align with bind / stack (list first).

Returns a view arranging uniform-shape pieces in a tdim-shape grid that extends parent axes axis..axis+tdim.size-1 by the corresponding tdim[i] factors. Output ndim equals each piece's ndim. tdim.product must equal list.size. For non-uniform pieces along tile axes, use CArray.mosaic.

Parameters:

  • list (Array<CArray>) —

    pieces to arrange.

  • tdim (Array<Integer>) —

    tile grid shape.

  • axis (Integer) (defaults to: 0) —

    first tile axis in the result.

  • data_type (Symbol, Integer, nil) (defaults to: nil) —

    result data_type.

Returns:

Raises:

  • (ArgumentError) —

    when list is empty or tdim.product != list.size.

Raises:

  • (ArgumentError)


165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/carray/stack.rb', line 165

def self.montage (list, tdim, axis: 0, data_type: nil)
  raise ArgumentError, "montage: list must not be empty" if list.empty?
  unless tdim.is_a?(Array) && tdim.size > 0
    raise ArgumentError, "montage: tdim must be a non-empty Array of Integer"
  end
  expected = tdim.inject(1) { |acc, n| acc * n }
  unless expected == list.size
    raise ArgumentError,
          "montage: tdim product (#{expected}) must equal list size (#{list.size})"
  end

  list = CArray.promote_list(list, data_type: data_type)
  parent_shape = list[0].shape
  ntile = tdim.size
  nparent = parent_shape.size
  axis = CArray.normalize_axis(axis, nparent - ntile + 1, "montage")

  s = CArray.stack(list).reshape(*tdim, *parent_shape)   # (K, *) → (*tdim, *)

  # Interleave: tile axis i (= s axis i, i ∈ [0, ntile)) is moved to
  # just before parent axis (axis + i) in s coordinates (= s axis
  # ntile + axis + i).
  perm = []
  nparent.times do |j|
    if j.between?(axis, axis + ntile - 1)
      perm << (j - axis)           # tile axis
    end
    perm << ntile + j              # parent axis
  end
  s = s.transpose(*perm)

  # Merge each (tile[i], parent[axis+i]) pair via reshape.
  new_shape = parent_shape.dup
  ntile.times { |i| new_shape[axis + i] *= tdim[i] }
  s.reshape(*new_shape)
end

.mosaic(list, tdim, axis: 0, data_type: nil) ⇒ CArray

Returns list tiled into an N-D grid layout described by tdim. Eager (returns a fresh CArray), accepts non-uniform sizes along the tile axes with block-matrix consistency (row-by-row / column-by-column agreement).

Parameters:

  • list (Array<CArray>) —

    pieces to tile; length must equal the product of tdim.

  • tdim (Array<Integer>) —

    tile grid shape.

  • axis (Integer) (defaults to: 0) —

    first tile axis in the result.

  • data_type (Symbol, Integer, nil) (defaults to: nil) —

    result data_type; inferred when nil.

Returns:

  • (CArray) —

    fresh CArray with tile axes extended by summed per-tile sizes.

Raises:

  • (ArgumentError) —

    when list is empty, tdim is ill-formed, or piece shapes violate block-matrix consistency.

Raises:

  • (ArgumentError)


121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/carray/methods/composition.rb', line 121

def self.mosaic (list, tdim, axis: 0, data_type: nil)
  raise ArgumentError, "mosaic: list must not be empty" if list.empty?
  unless tdim.is_a?(Array) && tdim.size > 0
    raise ArgumentError, "mosaic: tdim must be a non-empty Array of Integer"
  end
  expected = tdim.inject(1, :*)
  unless expected == list.size
    raise ArgumentError,
          "mosaic: tdim product (#{expected}) must equal list size (#{list.size})"
  end
  __ragged_paste(list, tdim, axis, data_type)
end

.normalize_axis(axis, ndim, name = nil) ⇒ Integer

Class-method form of #normalize_axis that operates on an explicit ndim rather than a CArray instance. Range is [0, ndim).

For an insertion position (valid range [0, old_ndim] inclusive), pass old_ndim + 1 as ndim. Used by class-level callers such as CArray.stack(list, axis:) that must normalize before any instance is available, and by composition helpers in lib/carray/compose.rb.

Parameters:

  • axis (Integer)
  • ndim (Integer)
  • name (String, nil) (defaults to: nil)

Returns:

  • (Integer)


52
# File 'yard-stubs/carray_utils.rb', line 52

def normalize_axis(axis, ndim, name = nil); end

.object ⇒ Class .object(*shape) ⇒ CArray

Overloads:

  • .object ⇒ Class

    Returns the typed class CArray::Object.

    Returns:

    • (Class)
  • .object(*shape) ⇒ CArray

    Equivalent to CArray.new(:object, shape) { ... }.

    Returns:



186
# File 'yard-stubs/ca_obj_array.rb', line 186

def object(*shape); end

.promote_list(list, data_type: nil) ⇒ Array<CArray>

Returns a copy of list in which every element is in a representation that can be uniformly handled (same Face class, or same primitive data_type). The result is suitable as direct input to multi-parent constructors such as stack.

With data_type: nil (auto-detect): a list of same-class Face elements passes through (CAStack lifts it), unless the class is not portable (CAConstString) or the elements disagree on state (CATime with different units); a list of primitives is promoted via result_type + wrap_readonly; a mix of Face and non-Face, or heterogeneous Face classes, is rejected.

With an explicit primitive data_type: all-primitive elements are wrapped read-only to the requested type; any Face element is rejected (a Face cannot be coerced to a primitive without losing identity). A Class-shaped data_type is rejected.

Parameters:

  • list (Array<CArray>) —

    elements to reconcile.

  • data_type (Symbol, nil) (defaults to: nil) —

    target element type, or nil to auto-detect.

Returns:

Raises:

  • (ArgumentError) —

    on an empty list or any of the reject cases.



486
# File 'yard-stubs/carray_cast.rb', line 486

def self.promote_list(list, data_type: nil); end

.result_type(*args) ⇒ Symbol

Returns the common data_type Symbol that all of the given operands can be promoted to under the CArray casting policy.

Each argument is classified as either a data_type representation or a value:

  • CArray instance -> its data_type
  • Symbol / String / Class -> data_type representation (name lookup)
  • Integer / Float / Complex / true / false / nil / Object -> value, data_type inferred (3 -> :int64, 3.14 -> :float64, 1+2i -> :cmplx128, ...)

Values and data_type representations promote uniformly. Integer args are interpreted as values, not as data_type codes: result_type(8) returns :int64 because the value 8 is an Integer, not because a data_type code equals 8. Use result_type(:int64) or result_type(CA_INT64) to be explicit about data_type intent.

Examples:

CArray.result_type(:int32, :float32)  #=> :float32
CArray.result_type(3, 3.14)           #=> :float64
CArray.result_type(true, 3)           #=> :int64

Parameters:

  • args (Array<CArray, Symbol, String, Class, Object>) —

    operands.

Returns:

  • (Symbol)

Raises:

  • (ArgumentError) —

    when called with no arguments.

  • (RuntimeError) —

    when two inputs are mutually incompatible (e.g. :object with :fixlen).



462
# File 'yard-stubs/carray_cast.rb', line 462

def self.result_type(*args); end

.save(ca, output, **opt) ⇒ CArray

Writes ca to output in the _CARRAY3 portable format. A String output is opened as a binary file; anything else is treated as an IO-like object.

Parameters:

  • ca (CArray) —

    array to write.

  • output (String, IO) —

    destination path or IO.

  • opt (Hash) —

    serializer options (:endian).

Returns:



458
459
460
461
462
463
464
465
466
467
# File 'lib/carray/serialize.rb', line 458

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

.select(condlist, choicelist, default: 0, data_type: nil) ⇒ CArray

Multi-way ternary select: for each cell, picks the value from the first choicelist[k] whose matching condlist[k] is true, falling back to default when no condition holds. When several conditions overlap, the earliest one in condlist wins.

All entries in condlist must be same-shape boolean CArrays. Each choicelist[k] is either a same-shape CArray or a scalar broadcast to every cell. The result data_type is the promotion of every choice plus default via CArray.result_type, or data_type when given.

Examples:

x = CArray.float64(6).span(-5.0..5.0)
CArray.select([x < 0, x < 2],
              [-x,    x * 10],
              default: 999)
# => [5.0, 3.0, -10.0, 0.0, 10.0, 999.0]

Parameters:

  • condlist (Array<CArray>) —

    boolean selectors.

  • choicelist (Array<CArray, Numeric, Object>) —

    values, one per condition (same length as condlist).

  • default (CArray, Numeric, Object) (defaults to: 0) —

    value written where no condition holds.

  • data_type (Symbol, Integer, nil) (defaults to: nil) —

    override for the result data type.

Returns:

  • (CArray) —

    new array with the shape of condlist[0].

Raises:

  • (ArgumentError) —

    on size mismatch, empty condlist, or a non-boolean / wrong-shape entry in condlist.



172
173
174
175
176
177
178
179
180
181
182
183
184
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
210
211
212
213
214
# File 'lib/carray/conditional.rb', line 172

def self.select (condlist, choicelist, default: 0, data_type: nil)
  unless condlist.is_a?(Array) && choicelist.is_a?(Array)
    raise ArgumentError, "select: condlist and choicelist must be Arrays"
  end
  if condlist.size != choicelist.size
    raise ArgumentError,
          "select: condlist (#{condlist.size}) and choicelist (#{choicelist.size}) size mismatch"
  end
  if condlist.empty?
    raise ArgumentError, "select: at least one condition required"
  end

  first = condlist.first
  unless first.is_a?(CArray) && first.boolean?
    raise ArgumentError, "select: condlist[0] must be a boolean CArray"
  end
  shape = first.shape

  dt = data_type || CArray.result_type(*choicelist, default)
  # `default` can be either a same-shape CArray (per-cell fallback) or a
  # scalar (broadcast to every cell).
  default_full = default.is_a?(CArray) && !default.scalar?
  out =
    if default_full
      default.data_type == dt ? default.copy : default.to_type(dt)
    else
      CArray.new(dt, shape).fill(default.is_a?(CArray) ? default[0] : default)
    end

  # Iterate from lowest priority to highest (reverse) so the earliest
  # entry in `condlist` ends up on top — matches `np.select`'s
  # first-match semantics.
  (condlist.size - 1).downto(0) do |k|
    c = condlist[k]
    unless c.is_a?(CArray) && c.boolean? && c.shape == shape
      raise ArgumentError,
            "select: condlist[#{k}] must be a same-shape boolean CArray"
    end
    v = choicelist[k]
    out[c] = v.is_a?(CArray) ? v[c] : v
  end
  out
end

.short(*shape) ⇒ Object

Alias of int16.



198
# File 'yard-stubs/ca_obj_array.rb', line 198

def short(*shape); end

.sizeof(data_type) ⇒ Integer

Returns the byte size of one element of data_type. Returns 0 for :fixlen (the byte size of a fixlen array is per-instance and read via CArray#bytes).

Examples:

CArray.sizeof(:int32)    # => 4
CArray.sizeof(:float64)  # => 8
CArray.sizeof(:fixlen)   # => 0

Parameters:

  • data_type (Symbol, Integer, Class, String) —

    data type in any accepted form.

Returns:

  • (Integer)


41
# File 'yard-stubs/carray_class.rb', line 41

def sizeof(data_type); end

.sort_addr(*keys, masked_position: :last) ⇒ CArray

Returns a 1-D CArray of :int64 indices that lex-sort keys in priority order (keys[0] is highest priority, keys[1] breaks ties, etc.). All keys must share the same element count.

Masked cells are an incomparable sentinel clustered at masked_position: (:last, default, or :first), applied uniformly across all keys. Ties are broken by original index (stable).

Examples:

idx = CArray.sort_addr(a, b, c)  # priority: a > b > c
a[idx]; b[idx]; c[idx]

Parameters:

  • keys (Array<CArray>) —

    one or more CArrays, all of the same element count.

  • masked_position (Symbol) (defaults to: :last) —

    :last (default) or :first.

Returns:

  • (CArray) —

    flat :int64 indices, shape [a.elements].

Raises:

  • (ArgumentError) —

    when no key is given or element counts differ.



29
# File 'yard-stubs/carray_sort.rb', line 29

def self.sort_addr(*keys, masked_position: :last); end

.stack(list, axis: 0, data_type: nil) ⇒ CArray

Stack list of CArrays along a new axis inserted at position axis: (default 0 = outermost). Returns a view (CAStack with k_axis = axis) when inputs are storage-uniform, or a Face-lifted view (= CATime, CATimedelta, ...) when inputs are homogeneous Face instances. Call .to_ca to materialise eagerly.

data_type: kwarg (optional, primitive Symbol only) forces primitive promotion; cannot be used when the list contains Face elements. Class / Module targets are rejected (= data_type: CATime is invalid; use auto-detect for Face round-trip).

3.0 (post-K_AXIS, F.S1-stack landed): replaces CArray.merge. The low-level raw constructor is CAStack.new(list, axis:); this method is the high-level surface that performs promote_list + CAStack.new + (face_lift when homogeneous Face).

Returns a view stacking uniform-shape arrays along a new K axis at position axis. Runs promote_list for a common data_type and re-wraps homogeneous Face inputs via face_lift. Output ndim is one greater than each piece.

Parameters:

  • list (Array<CArray>) —

    pieces to stack; must not be empty.

  • axis (Integer) (defaults to: 0) —

    position of the new K axis.

  • data_type (Symbol, Integer, nil) (defaults to: nil) —

    result data_type; inferred when nil.

Returns:

Raises:

  • (ArgumentError) —

    when list is empty.

Raises:

  • (ArgumentError)


59
60
61
62
63
64
# File 'lib/carray/stack.rb', line 59

def self.stack (list, axis: 0, data_type: nil)
  raise ArgumentError, "stack: list must not be empty" if list.empty?
  list = CArray.promote_list(list, data_type: data_type)
  axis = CArray.normalize_axis(axis, list[0].ndim + 1, "stack")
  CAStack.new(list, axis: axis)                # CAStack.new does Face lift internally
end

.string(values) ⇒ CAString .string(ca) ⇒ CAString .string(n) {|i| ... } ⇒ CAString

Build a CAString (mutable String array over object storage) from Ruby data.

CArray.string(["alpha", "", "gamma"])   # 1-D from Array
CArray.string(3) { |i| "item#{i}" }     # block form
CArray.string([a, nil, b])              # nil → masked element
CArray.string(other_ca)                 # from a String Face / object / raw fixlen

nil entries become masked cells; "" (empty) is a valid distinct value. A CArray source is normalised through a String Face (string_face_of): a String Face converts, CA_OBJECT storage wraps, a raw CA_FIXLEN reads as NUL-stripped strings; a numeric / boolean array is rejected (stringify with #format / format).

Overloads:

  • .string(values) ⇒ CAString

    Returns a CAString wrapping a CA_OBJECT entity of the given values.

    Parameters:

    • values (Array<String, nil>) —

      source values.

    Returns:

  • .string(ca) ⇒ CAString

    Returns a CAString of the string-bearing CArray ca.

    Parameters:

    • ca (CArray) —

      a String Face, CA_OBJECT, or raw CA_FIXLEN array.

    Returns:

    Raises:

  • .string(n) {|i| ... } ⇒ CAString

    Returns an n-element CAString filled by the block, following the arity-0 broadcast convention.

    Parameters:

    • n (Integer) —

      element count.

    Yield Parameters:

    • i (Integer) —

      cell index.

    Yield Returns:

    • (String, nil) —

      value for cell i.

    Returns:



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/carray/string.rb', line 41

def self.string (arg, &block)
  return string_face_of(arg).to_string if arg.is_a?(CArray)

  if block
    n = Integer(arg)
    if block.arity == 0
      v = block.call
      values = Array.new(n) { v }
    else
      values = Array.new(n) { |i| block.call(i) }
    end
  else
    values = arg.to_a
  end

  entity = CArray.object(values.size)
  values.each_with_index do |s, i|
    entity[i] = s.nil? ? UNDEF : s
  end
  CAString.wrap(entity)
end

.struct(opt = {}) { ... } ⇒ Class

Returns a new CAStruct subclass defined by the block via CAStruct::Builder. Options control alignment, packing, and endianness.

Parameters:

  • opt (Hash) (defaults to: {})

Yields:

Returns:

  • (Class) —

    anonymous CAStruct subclass.



533
534
535
# File 'lib/carray/struct.rb', line 533

def self.struct (opt={}, &block)
  return CAStruct::Builder.new(:struct, opt).define(&block)
end

.tabulate(columns, data_type: nil) ⇒ CArray

Returns a 2-D table assembled from a list of column blocks, coerced to a common data_type. Eager (returns a fresh, owned CArray) -- the point is to materialise a typed table, not a view.

Each entry is a 1-D array (one column, length L) or a 2-D array (a block of L x k columns). All entries must share the same length L; tabulate does not pad ragged lengths. Column counts may differ: entries are concatenated along the column axis, so a 1-column, a 3-column and a 2-column block produce a 6-column table. The result data_type is inferred (result_type of the entries) unless data_type is given.

For block-matrix assembly use mosaic; to stack 2-D tables vertically use concatenate(axis: 0).

Examples:

c1 = CA_INT([1, 2, 3])
c2 = CA_DOUBLE([4.5, 5.5, 6.5])
CArray.tabulate([c1, c2])                      # float64 (3, 2)
CArray.tabulate([c1, c2], data_type: :int32)   # int32 (3, 2)

Parameters:

  • columns (Array<CArray>) —

    1-D columns and/or 2-D column blocks, all of equal length L.

  • data_type (Symbol, Integer, nil) (defaults to: nil) —

    result data_type; inferred when nil.

Returns:

  • (CArray) —

    2-D CArray of shape (L, total column count).

Raises:

  • (ArgumentError) —

    when columns is empty, entries are not 1-D or 2-D CArrays, or row counts disagree.

Raises:

  • (ArgumentError)


254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# File 'lib/carray/methods/composition.rb', line 254

def self.tabulate (columns, data_type: nil)
  raise ArgumentError, "tabulate: columns must not be empty" if columns.empty?
  blocks = columns.map do |c|
    unless c.is_a?(CArray) && (c.ndim == 1 || c.ndim == 2)
      raise ArgumentError, "tabulate: each column must be a 1-D or 2-D CArray"
    end
    c.ndim == 1 ? c[nil, :_] : c          # promote a bare column to (L, 1)
  end
  len = blocks[0].shape[0]
  blocks.each_with_index do |b, i|
    unless b.shape[0] == len
      raise ArgumentError,
            "tabulate: all columns must have equal length (row count) " \
            "(column 0 has length #{len}, column #{i} has length " \
            "#{b.shape[0]}); tabulate does not pad ragged lengths"
    end
  end
  # Equal-length blocks, ragged column counts -> concatenate along the
  # column axis with a common (coerced or inferred) data_type.
  concatenate(blocks, axis: 1, data_type: data_type)
end

.time(x, unit: :s, format: nil, on_error: :raise) ⇒ CATime

Examples:

CArray.time("2024-06-15", unit: :D)                    # 1-element
CArray.time(%w[2024-01-01 2024-02-01], unit: :D)       # Ruby Array
CArray.time(CA_OBJECT(["2024-01-01", "oops"]), unit: :D, on_error: :mask)

Builds a CATime on the unit grid from time value(s). x is either a single literal (Time / ISO 8601 String / Unix-seconds Integer / DateTime) — giving a 1-element result — or a CArray of such literals — giving a same-shape result parsed per cell. Parsing is UTC and DateTime-independent.

A value that cannot be parsed raises by default (on_error: :raise); pass on_error: :mask to make it an UNDEF cell instead. A masked / nil input cell is a missing value (not a parse failure) and always becomes UNDEF, regardless of on_error.

Parameters:

  • x (Time, String, Integer, DateTime, CATime::Element, Array, CArray) —

    a literal, a Ruby Array of literals, or a CArray of literals.

  • unit (Resolution, Symbol, String) (defaults to: :s) —

    target grid resolution.

  • format (String, nil) (defaults to: nil) —

    optional strptime format for String input.

  • on_error (:raise, :mask) (defaults to: :raise) —

    parse-failure policy (default :raise).

Returns:

  • (CATime) —

    shape [1] for a literal, else x's shape.

Raises:

  • (ArgumentError) —

    on an unparseable value when on_error: :raise.



1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
# File 'lib/carray/time.rb', line 1814

def self.time(x, unit: :s, format: nil, on_error: :raise)
  res = CATime::Resolution.parse(unit)
  unless i[raise mask].include?(on_error)
    raise ArgumentError, "on_error: must be :raise or :mask (got #{on_error.inspect})"
  end
  x = CA_OBJECT(x) if x.is_a?(Array)   # Ruby Array of literals -> object CArray
  unless x.is_a?(CArray)
    return CATimeLiteral.to_time_array(x, res, format, on_error)
  end
  raw = CArray.int64(*x.shape)
  x.each_index do |*idx|
    s = x[*idx]
    if s == UNDEF || s.nil?
      raw[*idx] = UNDEF        # missing input -> missing output (no phantom epoch)
      next
    end
    begin
      raw[*idx] = CATimeLiteral.tick_index(s, res, format)
    rescue ArgumentError, TypeError
      raise if on_error == :raise
      raw[*idx] = UNDEF        # opt-in parse-mask
    end
  end
  raw.time(unit: res)
end

.time_range(start, last, unit:, step: nil, format: nil) ⇒ CATime

Returns a CATime from start to last inclusive on the unit grid, spaced step apart. unit is the resolution the result is stored on and step is the spacing, so an hourly grid sampled once a day is unit: :h, step: "1 day". With no step the spacing is one unit tick (consecutive ticks). Off-grid endpoints floor to their bucket head (toward the past); the phase is anchored at start, and last is a bound rather than a member -- the series stops at the last step at or before it.

Parameters:

  • start (Time, String, Integer, DateTime, CATime::Element) —

    first instant.

  • last (Time, String, Integer, DateTime, CATime::Element) —

    last instant (inclusive).

  • unit (Resolution, Symbol, String) —

    grid resolution (tick).

  • step (Resolution, Symbol, String, nil) (defaults to: nil) —

    spacing between elements (default: one unit tick). Must be a whole multiple of unit.

  • format (String, nil) (defaults to: nil) —

    optional strptime format for String inputs.

Returns:

Raises:

  • (ArgumentError) —

    when step is not a whole multiple of unit (including a calendar step on a fixed-length unit, e.g. a month step on an hour grid -- a month is not a fixed number of hours).



1756
1757
1758
1759
1760
1761
1762
1763
1764
# File 'lib/carray/time.rb', line 1756

def self.time_range(start, last, unit:, step: nil, format: nil)
  res    = CATime::Resolution.parse(unit)
  stride = step.nil? ? 1 :
             CATimeUnitAlgebra.multiple_factor(CATime::Resolution.parse(step), res)
  s = CATimeLiteral.tick_index(start, res, format)
  e = CATimeLiteral.tick_index(last,  res, format)
  n = e < s ? 0 : (e - s) / stride + 1
  CArray.int64(n) {|i| s + i * stride }.time(unit: res)
end

.time_series(start, count:, unit:, step: nil, format: nil) ⇒ CATime

Returns a CATime of count instants starting at start on the unit grid, spaced step apart. unit is the resolution the result is stored on and step is the spacing, so an hourly grid sampled once a day is unit: :h, step: "1 day". With no step the spacing is one unit tick (consecutive ticks, as before).

Parameters:

  • start (Time, String, Integer, DateTime, CATime::Element) —

    first instant.

  • count (Integer) —

    number of elements.

  • unit (Resolution, Symbol, String) —

    grid resolution (tick).

  • step (Resolution, Symbol, String, nil) (defaults to: nil) —

    spacing between elements (default: one unit tick). Must be a whole multiple of unit.

  • format (String, nil) (defaults to: nil) —

    optional strptime format for String inputs.

Returns:

Raises:

  • (ArgumentError) —

    when step is not a whole multiple of unit (including a calendar step on a fixed-length unit, e.g. a month step on an hour grid -- a month is not a fixed number of hours).



1783
1784
1785
1786
1787
1788
1789
# File 'lib/carray/time.rb', line 1783

def self.time_series(start, count:, unit:, step: nil, format: nil)
  res    = CATime::Resolution.parse(unit)
  stride = step.nil? ? 1 :
             CATimeUnitAlgebra.multiple_factor(CATime::Resolution.parse(step), res)
  s = CATimeLiteral.tick_index(start, res, format)
  CArray.int64(count) {|i| s + i * stride }.time(unit: res)
end

.uint16 ⇒ Class .uint16(*shape) ⇒ CArray

Overloads:

  • .uint16 ⇒ Class

    Returns the typed class CArray::UInt16.

    Returns:

    • (Class)
  • .uint16(*shape) ⇒ CArray

    Equivalent to CArray.new(:uint16, shape) { ... }.

    Returns:



114
# File 'yard-stubs/ca_obj_array.rb', line 114

def uint16(*shape); end

.uint32 ⇒ Class .uint32(*shape) ⇒ CArray

Overloads:

  • .uint32 ⇒ Class

    Returns the typed class CArray::UInt32.

    Returns:

    • (Class)
  • .uint32(*shape) ⇒ CArray

    Equivalent to CArray.new(:uint32, shape) { ... }.

    Returns:



130
# File 'yard-stubs/ca_obj_array.rb', line 130

def uint32(*shape); end

.uint64 ⇒ Class .uint64(*shape) ⇒ CArray

Overloads:

  • .uint64 ⇒ Class

    Returns the typed class CArray::UInt64.

    Returns:

    • (Class)
  • .uint64(*shape) ⇒ CArray

    Equivalent to CArray.new(:uint64, shape) { ... }.

    Returns:



146
# File 'yard-stubs/ca_obj_array.rb', line 146

def uint64(*shape); end

.uint8 ⇒ Class .uint8(*shape) ⇒ CArray

Overloads:

  • .uint8 ⇒ Class

    Returns the typed class CArray::UInt8.

    Returns:

    • (Class)
  • .uint8(*shape) ⇒ CArray

    Equivalent to CArray.new(:uint8, shape) { ... }.

    Returns:



98
# File 'yard-stubs/ca_obj_array.rb', line 98

def uint8(*shape); end

.union(opt = {}) { ... } ⇒ Class

Returns a new CAUnion subclass defined by the block. Same options and DSL as struct but every member occupies the same offset.

Parameters:

  • opt (Hash) (defaults to: {})

Yields:

Returns:

  • (Class) —

    anonymous CAUnion subclass.



544
545
546
# File 'lib/carray/struct.rb', line 544

def self.union (opt={}, &block)
  return CAStruct::Builder.new(:union, opt).define(&block)
end

.wrap(data_type, shape) ⇒ CAWrap

Wraps an external memory block as a CAWrap. The block must return a target object that defines wrap_as_carray(obj), which receives the freshly allocated CAWrap and is responsible for setting its ptr field.

Use this when bridging to a memory source that does not expose the MemoryView protocol (otherwise prefer wrap_memory_view / from_memory_view).

Parameters:

  • data_type (Symbol)
  • shape (Array<Integer>)

Yield Returns:

  • (#wrap_as_carray) —

    external buffer holder.

Returns:



237
# File 'yard-stubs/ca_obj_array.rb', line 237

def wrap(data_type, shape); end

.wrap_memory_view(src, data_type: nil, mask: nil) ⇒ CAWrap, CAStride

Returns a CAWrap (or CAStride for strided producers) that borrows src's buffer zero-copy. Writes through the wrap reach the source buffer; external changes to the source are visible through the wrap.

The borrowed view is kept alive for the lifetime of the returned object via internal ivars; the source is released when the wrap is garbage-collected.

Contiguous typed producers return a CAWrap. Strided typed producers return a CAStride layered on an inner CAWrap of the producer's first byte, preserving the full stride pattern (including negative strides where the producer offers them). Typeless producers (format nil) require data_type: and are reinterpreted with ndim = 1.

mask: accepts a paired buffer-protocol source whose shape matches src and whose item size is 1 (PEP 3118 ? / B / b). The mask buffer is borrowed; writes to either side propagate, and the mask MemoryView is released when the wrap is collected. In this release, mask: requires a row-major contiguous data source and a row-major contiguous mask buffer.

The receiver picks the class of the result. Called on CArray it builds a CAWrap; called on a subclass of CAWrap it builds that subclass, so a gem bridging a foreign buffer can name where the array came from without writing a C extension. Any other receiver raises TypeError, and a strided producer raises ArgumentError when a subclass was asked for, since the result would be a CAStride rather than the named class.

The class marks the provenance of the returned object only. A view derived from it is a CABlock or a CAStride like any other — a slice of a borrowed image is no longer that image — so do not build an API that expects the class to survive view algebra. For semantic identity that does survive it, see CAFace.

Examples:

Zero-copy write propagation

a = CArray.int32(4).seq
w = CArray.wrap_memory_view(a)
w[0] = 999
a[0]   # => 999

Paired masked wrap

data = CArray.uint8(3) { |i| i + 10 }
mask = CArray.boolean(3) { 0 }
w = CArray.wrap_memory_view(data, mask: mask)
w[1] = UNDEF      # writes the source mask buffer
mask[1]           # => 1

Naming where a borrowed buffer came from

class VipsPixels < CAWrap
  def image ; instance_variable_get(:@vips_image) ; end
end
v = VipsPixels.wrap_memory_view(bmv)
v.class            # => VipsPixels
v[0..1, nil].class # => CABlock  (the class does not descend)

Parameters:

  • src (Object) —

    any MemoryView producer.

  • data_type (Symbol, Integer, Class, nil) (defaults to: nil) —

    target data type, same rules as from_memory_view.

  • mask (Object, nil) (defaults to: nil) —

    optional paired mask MemoryView source.

Returns:

  • (CAWrap, CAStride) —

    zero-copy borrowed view of src. A CAStride is returned when src is strided (and mask: is not given); otherwise a CAWrap, or the subclass of CAWrap the method was called on.

Raises:

  • (TypeError) —

    if the receiver is neither CArray nor a subclass of CAWrap.

  • (ArgumentError) —

    if src is not a MemoryView producer, if data_type: is missing for a typeless source, if data_type: conflicts with the producer's format, or if the supplied mask: fails validation (shape / ndim / data type / item_size / contiguity). Also raises when mask: is combined with a strided data source — that combination is not supported in this release.



159
# File 'yard-stubs/carray_memory_view.rb', line 159

def wrap_memory_view(src, data_type: nil, mask: nil); end

.wrap_readonly(other, data_type = nil) ⇒ CArray

Returns other as a CArray you intend to only read, reinterpreted as data_type when given.

The name is a statement of intent, not a property of the result: you are declaring that nothing will be written back, which frees this call to convert as widely as it can — a conversion that copies is fine when nobody writes to it. So on top of everything wrap_writable takes (a CArray, nil, an object responding to #to_ca, a MemoryView producer) this also accepts an Array (via to_ca) and a Numeric / String / arbitrary object, which become a one-element CScalar. It calls to_ca with no arguments, so a copy is welcome here.

It does not make the source read-only, and does not protect it: for a CArray whose element type already matches you get back the very same object, and a type-adapting view writes through to its source. Keeping the read-only promise is the caller's part of the bargain.

Two conversions are worth knowing before you rely on them: with a numeric data_type a String is reinterpreted as raw bytes (a copy), not parsed, so "abcd" with :uint8 gives four elements; and with data_type omitted, anything that is not already CArray-shaped lands on :object rather than a guessed numeric type, so pass data_type explicitly when the value is headed for a numeric kernel. A Face answers with the same conversion #to_type performs, since nothing here promises a view: its surface values for :object, and its own #to_numeric for a numeric type. Reading its storage instead is face.parent.

Parameters:

  • other (CArray, Numeric, String, Array, nil, Object) —

    source to wrap.

  • data_type (Symbol, Integer, Class, nil) (defaults to: nil) —

    target element type; nil keeps the source type for a CArray-shaped source, and is :object otherwise.

Returns:

Raises:

  • (TypeError) —

    when other is a Face asked for a numeric type and it declares no #to_numeric.



424
# File 'yard-stubs/carray_cast.rb', line 424

def self.wrap_readonly(other, data_type = nil); end

.wrap_writable(other, data_type = nil) ⇒ CArray

Returns other as a CArray you intend to write into, reinterpreted as data_type when given.

The name is a statement of intent, not a property of the result: you are declaring that writes are coming, so only sources that can actually take a write are accepted — a writable CArray, nil (a zero-filled CScalar), an object whose #to_ca honours writable: true, or a writable MemoryView producer (wrapped zero-copy). Anything that would have to be copied to become a CArray is refused up front, because a copy would swallow the writes silently. That is the whole difference from wrap_readonly, which is free to copy and so accepts far more.

For a foreign object the refusal is the object's own to make: this calls other.to_ca(writable: true), which is the caller's half of the #to_ca contract — "give me a CArray whose writes reach you" — and a to_ca that can only produce a copy raises rather than answering. An object whose to_ca predates the keyword raises ArgumentError, which is the honest report that it does not implement writable intake.

When data_type differs from the source element type the result is a type-adapting view over the same storage, and a write reverse-casts through to the source. A Face is refused for that same reason the other way round: the writes would land on the storage its surface hides. Wrap face.parent when that is what you mean.

Parameters:

  • other (CArray, nil, Object) —

    source to wrap.

  • data_type (Symbol, Integer, Class, nil) (defaults to: nil) —

    target element type; nil keeps the source type (or :object when other is nil).

Returns:

Raises:

  • (RuntimeError) —

    when other is read-only, its MemoryView is read-only, its to_ca refuses writable: true, or it cannot be wrapped as a CArray.

  • (TypeError) —

    when other#to_ca returns something that is not a CArray.

  • (ArgumentError) —

    when other#to_ca does not accept writable:.

  • (TypeError) —

    when other is a Face and data_type differs from its surface type.



386
# File 'yard-stubs/carray_cast.rb', line 386

def self.wrap_writable(other, data_type = nil); end

Instance Method Details

#%(other) ⇒ CArray

Returns the element-wise remainder of self divided by other, carrying the sign of the divisor.

This is the floored modulo, the pair of the floored / above and the same convention as Ruby's %: -7 % 3 is 2, and 7 % -3 is -2. A float remainder of zero takes the divisor's sign, so the rule holds without exception. For the truncated form that C gives -- the sign of the dividend -- use #fmod. Complex arrays have no modulo. Masked elements stay masked.

Examples:

CA_INT32([-7, -1, 7]) % 3      # => [ 2, 2, 1 ]
CA_INT32([7]) % -3             # => [ -2 ]
CA_DOUBLE([-0.4]) % 1.0        # => [ 0.6 ]

Parameters:

  • other (CArray, Numeric) —

    divisor, broadcast to self.shape.

Returns:

  • (CArray) —

    result of the promoted data_type of the two operands.

Raises:

  • (ZeroDivisionError) —

    when an integer divisor is 0. A float divisor of 0.0 yields NaN.

  • (CArray::DataTypeError) —

    for a complex array.



62
# File 'yard-stubs/carray_math.rb', line 62

def %(other); end

#/(other) ⇒ CArray

Returns the element-wise quotient of self and other.

Integer division floors toward negative infinity, so that (a / b) * b + a % b == a holds for every combination of signs -- the same convention as Ruby's Integer#/. Float and complex division is true division, as Ruby's Float#/ is, so that identity is an integer one. Boolean arrays participate as their 0/1 storage. Masked elements stay masked, and a masked cell is never divided.

Examples:

CA_INT32([-7, -1, 7]) / 3      # => [ -3, -1, 2 ]
CA_DOUBLE([-7.0]) / 3.0        # => [ -2.3333333333333335 ]

Parameters:

  • other (CArray, Numeric) —

    divisor, broadcast to self.shape.

Returns:

  • (CArray) —

    result of the promoted data_type of the two operands.

Raises:

  • (ZeroDivisionError) —

    when an integer divisor is 0. Float division returns Infinity or NaN instead.



28
# File 'yard-stubs/carray_math.rb', line 28

def /(other); end

#<=>(other) ⇒ CArray Also known as: cmp

Returns an element-wise 3-way comparison: +1 where self > other, -1 where self < other, 0 where equal. Output data_type is CA_INT8.

Parameters:

  • other (CArray, Numeric) —

    operand to compare against.

Returns:



216
217
218
# File 'lib/carray/basics.rb', line 216

def <=> (other)
  (self > other).as_int8 - (self < other).as_int8
end

#==(other) ⇒ Boolean

Returns true if other is a CArray with the same shape, data_class, data_type, mask state, and elementwise values as self. NaN values compare unequal (IEEE semantics), so two arrays with NaN at the same position are not ==.

Parameters:

  • other (Object)

Returns:

  • (Boolean)


41
# File 'yard-stubs/carray_test.rb', line 41

def ==(other); end

#[](*index) ⇒ CArray, Object

Returns a view of self (or a single element) selected by one index per axis. Every array-returning form is a view onto the original storage — writing through it reaches the source.

Accepted per-axis index forms:

  • Integer — one position (negative counts from the end); an all-Integer index returns the single element (masked -> UNDEF).
  • nil — the whole axis.
  • Range — a contiguous (or stepped, via a stepped Range) sub-range.
  • boolean CArray — masked selection along that axis.
  • Integer CArray — fancy gather (index array); shape follows the index array.
  • :_ — newaxis: insert a size-1 axis at this position.
  • :* / :% — repeat / tiling sugar.
  • :> — slab axis: wrap the result in a CASlabIterator.
  • a member name Symbol — project a struct field (see CARecord).

A single flat Integer (fewer indices than ndim) addresses the array in row-major flat order.

Parameters:

  • index (Array<Integer, Range, nil, CArray, Symbol>) —

    one entry per axis (or a single flat address).

Returns:

  • (CArray, Object) —

    a view for a slicing form, or the element value (or UNDEF if masked) for an all-scalar index.

Raises:

  • (IndexError) —

    on an out-of-range index or an unrecognised form.

See Also:



38
# File 'yard-stubs/carray_access.rb', line 38

def [](*index); end

#[]=(*index, value) ⇒ Object

Sets the cells of self selected by index (same per-axis forms as #[]) to value. value may be a scalar (broadcast), an Array, or a CArray whose element count matches the selection; assigning UNDEF masks the selected cells.

Assignment through a slab iterator (:>) is not supported — use a block index (e.g. ca[range, nil] = val) or each_slab.

Parameters:

  • index (Array<Integer, Range, nil, CArray, Symbol>) —

    one entry per axis (or a single flat address).

  • value (Object, Array, CArray) —

    the value(s) to store, or UNDEF to mask.

Returns:

  • (Object) —

    value.

Raises:

  • (IndexError) —

    on an out-of-range index or an unsupported form.

See Also:



55
# File 'yard-stubs/carray_access.rb', line 55

def []=(*index, value); end

#addr2index(addr) ⇒ Array<Integer>, Array<CArray>

Unravels a flat row-major address into per-axis indices, sized by self.shape. With an Integer addr returns N Integers; with a CArray of addresses returns N CArrays of the same shape as addr (mask propagated per cell). In both cases the return is a Ruby Array of length self.ndim, so i, j = ca.addr2index(x) unpacks uniformly for scalar and vector inputs.

Parameters:

  • addr (Integer, CArray) —

    a flat address in 0...elements, or a CArray of such addresses (arbitrary shape).

Returns:

Raises:

  • (ArgumentError) —

    when any addr is out of range.



88
# File 'yard-stubs/carray_access.rb', line 88

def addr2index(addr); end

#address ⇒ CArray

Returns an int32 CArray of the same shape as self where each cell holds its row-major flat address.

Returns:



125
126
127
# File 'lib/carray/basics.rb', line 125

def address
  return CArray.int32(*shape).seq!
end

#all(skip_masked: true, **opts) ⇒ Boolean, CArray

Whether every cell is true.

With skip_masked: true (the default) masked cells are simply ignored and the result is always true / false. With skip_masked: false the fold is three-valued: the result is UNDEF when a masked cell could change it, matching the element-wise Kleene semantics of | / &.

Parameters:

  • skip_masked (Boolean) (defaults to: true) —

    ignore masked cells, or fold them three-valued.

  • opts (Hash) —

    forwarded to the underlying reduction (axis:, keep_axis:, ...).

Returns:

  • (Boolean, CArray) —

    a scalar, or an array when an axis is given.



54
55
56
57
# File 'lib/carray/boolean_reduce.rb', line 54

def all (skip_masked: true, **opts)
  return __all_skipna__(**opts) if skip_masked
  __kleene_fold(:all, opts)
end

#all_masked? ⇒ Boolean

Returns true if every element of self is masked.

Returns:

  • (Boolean)


22
# File 'yard-stubs/carray_mask.rb', line 22

def all_masked?; end

#ancestors ⇒ Array<CArray>

Returns the list of arrays in the view chain, ordered from root to self.

Returns:



125
# File 'yard-stubs/carray_attribute.rb', line 125

def ancestors; end

#any(skip_masked: true, **opts) ⇒ Boolean, CArray

Whether any cell is true.

With skip_masked: true (the default) masked cells are simply ignored and the result is always true / false. With skip_masked: false the fold is three-valued: the result is UNDEF when a masked cell could change it, matching the element-wise Kleene semantics of | / &.

Parameters:

  • skip_masked (Boolean) (defaults to: true) —

    ignore masked cells, or fold them three-valued.

  • opts (Hash) —

    forwarded to the underlying reduction (axis:, keep_axis:, ...).

Returns:

  • (Boolean, CArray) —

    a scalar, or an array when an axis is given.



38
39
40
41
# File 'lib/carray/boolean_reduce.rb', line 38

def any (skip_masked: true, **opts)
  return __any_skipna__(**opts) if skip_masked
  __kleene_fold(:any, opts)
end

#any_masked? ⇒ Boolean

Returns true if at least one element of self is masked.

Returns:

  • (Boolean)


17
# File 'yard-stubs/carray_mask.rb', line 17

def any_masked?; end

#as_boolean ⇒ CAFake

Returns a CAFake :boolean view of self. Short-hand of as_type(:boolean).

Returns:



207
# File 'yard-stubs/carray_cast.rb', line 207

def as_boolean; end

#as_byte ⇒ Object

Alias of #as_uint8. @return [CAFake]



284
# File 'yard-stubs/carray_cast.rb', line 284

def as_byte; end

#as_cmplx128 ⇒ CAFake

Returns a CAFake :cmplx128 view of self. Short-hand of as_type(:cmplx128).

Returns:



264
# File 'yard-stubs/carray_cast.rb', line 264

def as_cmplx128; end

#as_cmplx256 ⇒ CAFake

Returns a CAFake :cmplx256 view of self. Short-hand of as_type(:cmplx256).

Returns:



269
# File 'yard-stubs/carray_cast.rb', line 269

def as_cmplx256; end

#as_cmplx64 ⇒ CAFake

Returns a CAFake :cmplx64 view of self. Short-hand of as_type(:cmplx64).

Returns:



259
# File 'yard-stubs/carray_cast.rb', line 259

def as_cmplx64; end

#as_complex ⇒ Object

Alias of #as_cmplx64. @return [CAFake]



299
# File 'yard-stubs/carray_cast.rb', line 299

def as_complex; end

#as_dcomplex ⇒ Object

Alias of #as_cmplx128. @return [CAFake]



302
# File 'yard-stubs/carray_cast.rb', line 302

def as_dcomplex; end

#as_double ⇒ Object

Alias of #as_float64. @return [CAFake]



296
# File 'yard-stubs/carray_cast.rb', line 296

def as_double; end

#as_fixlen(bytes: nil) ⇒ CAFake

Returns a CAFake :fixlen view of self. Short-hand of as_type(:fixlen, bytes:).

Parameters:

  • bytes (Integer, nil) (defaults to: nil) —

    fixed element width in bytes.

Returns:



280
# File 'yard-stubs/carray_cast.rb', line 280

def as_fixlen(bytes: nil); end

#as_float ⇒ Object

Alias of #as_float32. @return [CAFake]



293
# File 'yard-stubs/carray_cast.rb', line 293

def as_float; end

#as_float128 ⇒ CAFake

Returns a CAFake :float128 view of self. Short-hand of as_type(:float128).

Returns:



254
# File 'yard-stubs/carray_cast.rb', line 254

def as_float128; end

#as_float32 ⇒ CAFake

Returns a CAFake :float32 view of self. Short-hand of as_type(:float32).

Returns:



244
# File 'yard-stubs/carray_cast.rb', line 244

def as_float32; end

#as_float64 ⇒ CAFake

Returns a CAFake :float64 view of self. Short-hand of as_type(:float64).

Returns:



249
# File 'yard-stubs/carray_cast.rb', line 249

def as_float64; end

#as_int ⇒ Object

Alias of #as_int32. @return [CAFake]



290
# File 'yard-stubs/carray_cast.rb', line 290

def as_int; end

#as_int16 ⇒ CAFake

Returns a CAFake :int16 view of self. Short-hand of as_type(:int16).

Returns:



219
# File 'yard-stubs/carray_cast.rb', line 219

def as_int16; end

#as_int32 ⇒ CAFake

Returns a CAFake :int32 view of self. Short-hand of as_type(:int32).

Returns:



227
# File 'yard-stubs/carray_cast.rb', line 227

def as_int32; end

#as_int64 ⇒ CAFake

Returns a CAFake :int64 view of self. Short-hand of as_type(:int64).

Returns:



235
# File 'yard-stubs/carray_cast.rb', line 235

def as_int64; end

#as_int8 ⇒ CAFake

Returns a CAFake :int8 view of self. Short-hand of as_type(:int8).

Returns:



211
# File 'yard-stubs/carray_cast.rb', line 211

def as_int8; end

#as_object ⇒ CAFake

Returns a CAFake :object view of self. Short-hand of as_type(:object).

Returns:



274
# File 'yard-stubs/carray_cast.rb', line 274

def as_object; end

#as_short ⇒ Object

Alias of #as_int16. @return [CAFake]



287
# File 'yard-stubs/carray_cast.rb', line 287

def as_short; end

#as_strided(shape:, strides:, offset: 0) ⇒ CAStride

Returns a CAStride view of self with the given byte strides and starting byte offset, inheriting the receiver's data type and element size. Memory is shared with the receiver.

This is a low-level escape hatch: the strides and offset are not bounds-checked against the receiver's memory, so a combination that addresses outside it reads or writes past the buffer. Prefer the derived constructors (#sliding_windows, #block_view, #flip, #diagonal) when one of them expresses the layout.

Parameters:

  • shape (Array<Integer>) —

    axis lengths.

  • strides (Array<Integer>) —

    byte stride per axis, same length as shape; negative values are allowed.

  • offset (Integer) (defaults to: 0) —

    byte offset from the receiver's buffer to the [0, ..., 0] element.

Returns:

Raises:

  • (ArgumentError) —

    when shape: or strides: is missing, when their lengths differ, or when the rank is 0 or above CA_RANK_MAX.



40
# File 'yard-stubs/ca_obj_stride.rb', line 40

def as_strided(shape:, strides:, offset: 0); end

#as_type(data_type, bytes: nil) ⇒ CAFake

Returns a CAFake view of self reinterpreted as data_type (with bytes: for :fixlen). Reads and writes cast on the fly through the shared parent storage; no copy is made. For an eager copy use arr.as_type(...).to_ca or #to_type.

Note: for an :object source the on-the-fly cast to a numeric type uses the lenient path and does NOT mask parse failures — a non-numeric string reads as 0.0 (float) and raises for an integer target. Use #to_type instead for parse-with-mask (an unparseable cell becomes UNDEF). The CA_<TYPE>(obj) construction shorthands take this same non-masking path. A Face refuses: reinterpreting its storage would hand back the bytes its surface exists to hide (the serial instead of the time, the descriptor instead of the string), and no view decodes a surface. Take the values with #to_type, or the storage with face.parent.as_type. A Numeric Face, whose surface is its storage, adapts as usual.

Parameters:

  • data_type (Symbol, Integer, Class, String) —

    target element type.

  • bytes (Integer, nil) (defaults to: nil) —

    element width in bytes, required for :fixlen.

Returns:

Raises:

  • (TypeError) —

    when self is a Face and the request would read its storage under another type.



201
# File 'yard-stubs/carray_cast.rb', line 201

def as_type(data_type, bytes: nil); end

#as_uint16 ⇒ CAFake

Returns a CAFake :uint16 view of self. Short-hand of as_type(:uint16).

Returns:



223
# File 'yard-stubs/carray_cast.rb', line 223

def as_uint16; end

#as_uint32 ⇒ CAFake

Returns a CAFake :uint32 view of self. Short-hand of as_type(:uint32).

Returns:



231
# File 'yard-stubs/carray_cast.rb', line 231

def as_uint32; end

#as_uint64 ⇒ CAFake

Returns a CAFake :uint64 view of self. Short-hand of as_type(:uint64).

Returns:



239
# File 'yard-stubs/carray_cast.rb', line 239

def as_uint64; end

#as_uint8 ⇒ CAFake

Returns a CAFake :uint8 view of self. Short-hand of as_type(:uint8).

Returns:



215
# File 'yard-stubs/carray_cast.rb', line 215

def as_uint8; end

#attach({ ... }) { ... } ⇒ Object

Attaches self, yields, and detaches on block exit. No sync is performed.

Yields:

Returns:

  • (Object) —

    the block's return value.



25
# File 'yard-stubs/carray_core.rb', line 25

def attach; end

#attach!({ ... }) { ... } ⇒ Object

Attaches self, yields, then syncs and detaches on block exit. Use this form when the block mutates self.ptr and you need the changes flushed back to the parent.

Yields:

Returns:

  • (Object) —

    the block's return value.



33
# File 'yard-stubs/carray_core.rb', line 33

def attach!; end

#attached? ⇒ Boolean

Returns true if self is currently attached (ptr != NULL).

Returns:

  • (Boolean)


169
# File 'yard-stubs/carray_attribute.rb', line 169

def attached?; end

#attr(key) ⇒ Object?

Returns the value of the attribute key, or nil when the key is absent. Walks the parent chain per key: the deepest view that has an entry for key wins.

Parameters:

  • key (Symbol, String) —

    attribute key.

Returns:

  • (Object, nil)


41
42
43
44
45
46
47
# File 'lib/carray/attribute.rb', line 41

def attr (key)
  k = attr_normalize_key(key)
  attr_each_chain do |h|
    return h[k] if h.key?(k)
  end
  nil
end

#attrs ⇒ Hash{String => Object}

Returns a frozen shallow Hash of all attributes visible on self, merged along the parent chain (deeper writes shadow shallower ones on a per-key basis).

Returns:

  • (Hash{String => Object})


69
70
71
72
73
74
75
76
# File 'lib/carray/attribute.rb', line 69

def attrs
  merged = nil
  attr_each_chain do |h|
    merged ||= {}
    h.each { |k, v| merged[k] = v unless merged.key?(k) }
  end
  (merged || {}).freeze
end

#axis2addr(indices, axis: 0) ⇒ CArray

Converts per-fiber axis-local indices into row-major view-flat addresses into self. For each cell at coord c = (c_0, ..., c_(n-1)) in indices:

addr[c] = sum over `j != axis` of c_j * stride_j +
        indices[c] * stride_axis

where strides are row-major over self.shape.

Canonical converter between the two axis-position representations the *_index / *_addr kernel families produce:

Sits underneath #take_along_axis: the heavy "axis-local -> view-flat" arithmetic lives here, and take_along_axis is a one-liner on top of flatten[axis2addr(...)].

Shape rule: indices.ndim == self.ndim, and indices.dim[j] == self.dim[j] for all j != axis; indices.dim[axis] is free.

indices data_type: any integer kind (zero-copy when already :int64). Negative indices: Python-style (-1 == last). Out-of-range indices raise RangeError. Negative axis: is Python-style.

Examples:

a.min_index(axis: k)  # axis-local scalar per fiber
a.min_addr(axis: k)   # view-flat address per fiber
flat = key.axis2addr(key.min_index(axis: k), axis: k)
# flat == key.min_addr(axis: k)

Parameters:

  • indices (CArray) —

    integer-typed axis-local positions.

  • axis (Integer) (defaults to: 0) —

    axis along which indices are interpreted.

Returns:

  • (CArray) —

    :int64 view-flat addresses, same shape as indices.

Raises:

  • (RangeError) —

    when an index is out of range after negative normalization.

  • (ArgumentError) —

    for shape / ndim / data_type violations.



160
# File 'yard-stubs/carray_sort.rb', line 160

def axis2addr(indices, axis: 0); end

#axis_group(*slots) ⇒ Object


CArray#axis_group(cat_or_nil, ...) -- build an AxisGroup spec.

Slot position = source axis. A CACategorical slot consumes cat.ndim source axes (rank-1 = one axis, rank-N = several axes collapsed into one group axis); a nil slot is a band (held) axis. ALL axes must be given explicitly -- the rank-sum must equal self.ndim, trailing omission / nil fill is forbidden (explicit > implicit). The value is used as a shape TEMPLATE only (its data is never read).



33
34
35
# File 'lib/carray/axis_group.rb', line 33

def axis_group (*slots)
  AxisGroup.new(self, slots)
end

#bin(vmin, vmax, step = nil, bins: nil, lfill: nil, ufill: nil, include_max: true) ⇒ CArray

Returns each element's bin index for equal-width, half-open bins over [vmin, vmax]. Bin k covers [vmin + k*w, vmin + (k+1)*w) where w = (vmax - vmin) / n. The number of bins is set either by step (positional; bin width, matching snap's step) or by bins: (kwarg; count of bins, matching histogram convention); exactly one must be given.

Because [vmin, vmax] is a user-declared inclusive range, values exactly equal to vmax land in the last bin by default (include_max: true); this differs from bin_to, where the user-supplied edges are treated as-is (half-open, default false).

Out-of-range convention follows bin_to / project: lfill for below-range, ufill for above-range; nil on either side masks that side. NaN / masked input cells are always masked in the output, independently of lfill / ufill.

Use snap(step, offset:) when the desired output is the snapped value; use bin_to(edges) when the edges are non-uniform.

Examples:

temp.bin(270, 300, 0.5)               # 60 uniform bins every 0.5 K
temp.bin(0, 1, bins: 100)             # 100 equal-width bins over [0, 1]
temp.bin(0, 9, 1, lfill: 0, ufill: 8) # clamp OOB to end bins

Parameters:

  • vmin (Numeric) —

    range lower bound.

  • vmax (Numeric) —

    range upper bound; must be >= vmin.

  • step (Numeric, nil) (defaults to: nil) —

    bin width. The number of bins is ((vmax - vmin) / step).round (silent FP rounding, standard numeric convention).

  • bins (Integer, nil) (defaults to: nil) —

    number of bins (alternative to step); must be >= 1.

  • lfill (Integer, nil) (defaults to: nil) —

    fill for below-range cells.

  • ufill (Integer, nil) (defaults to: nil) —

    fill for above-range cells.

  • include_max (Boolean) (defaults to: true) —

    fold values equal to vmax into the last bin instead of treating them as above-range.

Returns:

  • (CArray) —

    CA_INT64 bin indices in [0, n-1], same shape as self.

Raises:

  • (ArgumentError) —

    when neither / both of step and bins: are given, bins < 1, or vmin > vmax.

Raises:

  • (ArgumentError)


43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/carray/methods/bin.rb', line 43

def bin(vmin, vmax, step = nil, bins: nil, lfill: nil, ufill: nil, include_max: true)
  if step.nil? == bins.nil?
    raise ArgumentError, "bin: give exactly one of `step` or `bins:`"
  end
  raise ArgumentError, "bin: vmin > vmax" if vmin > vmax

  n = bins || ((vmax - vmin).to_f / step).round
  raise ArgumentError, "bin: n must be >= 1" if n < 1

  if vmin == vmax
    # Degenerate: zero interval → all cells fall on the single edge;
    # with include_max: true they land in bin 0.
    out = CArray.int64(*shape) { 0 }
    out.mask = self.mask.to_ca if self.has_mask?
    if self.float?
      inv = self.is_invalid
      if inv.count(true) > 0
        out.mask = out.has_mask? ? (out.mask | inv) : inv
      end
    end
    return out
  end

  # Delegate to `bin_to` with generated uniform edges — same kernel
  # (`histbin_ki`) as `histogram`, so semantics are identical.
  edges = CArray.float64(n + 1).span(vmin..vmax)
  bin_to(edges, lfill: lfill, ufill: ufill, include_max: include_max)
end

#bin_to(edges, lfill: nil, ufill: nil, include_max: false) ⇒ CArray

Returns each element's bin index against an explicit ascending edges array (non-uniform binning). Sibling of bin (uniform, range + step) and snap_to (nearest-value snap to the same shape of grid).

edges are N+1 ascending boundaries defining N bins; bin k covers the half-open interval [edges[k], edges[k+1]). Out-of-range values follow the bin / project convention: a value below edges[0] becomes lfill, a value at or above edges[-1] becomes ufill; nil on either side masks that side. When include_max is true, a value exactly equal to edges[-1] lands in the last bin N-1 instead of being treated as above-range. NaN or masked input cells are masked in the output, independently of lfill / ufill.

The inner binning kernel is shared with histogram, which counts how many values land in each bin.

Examples:

e = CA_FLOAT64([0, 1, 10, 100])
v = CA_FLOAT64([0.5, 5.0, 50.0, -1.0, 200.0])
v.bin_to(e)                  # => [0, 1, 2, UNDEF, UNDEF]
v.bin_to(e, lfill: 0, ufill: 2)
                             # => [0, 1, 2, 0, 2]

Parameters:

  • edges (CArray, Array<Numeric>) —

    1-D ascending boundaries with at least 2 values.

  • lfill (Integer, nil) (defaults to: nil) —

    fill for below-range cells; nil masks them.

  • ufill (Integer, nil) (defaults to: nil) —

    fill for above-range cells; nil masks them.

  • include_max (Boolean) (defaults to: false) —

    fold values equal to edges[-1] into the last bin instead of treating them as above-range.

Returns:

  • (CArray) —

    CA_INT64 array with the same shape as self holding bin indices in [0, N-1] (or the fill values / mask for out-of-range and masked cells).

Raises:

  • (ArgumentError) —

    when edges is not 1-D or has fewer than 2 values.

Raises:

  • (ArgumentError)


110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/carray/methods/bin.rb', line 110

def bin_to(edges, lfill: nil, ufill: nil, include_max: false)
  e = CArray.wrap_readonly(edges, :float64)
  raise ArgumentError, "bin_to: edges must be 1-D" unless e.ndim == 1
  raise ArgumentError, "bin_to: edges needs at least 2 values" if e.elements < 2
  n = e.elements - 1                                  # number of bins

  src = data_type == CA_FLOAT64 ? self : CArray.wrap_readonly(self, :float64)

  # histbin_ki returns the extended index (0 = under, 1..N = in-range bins,
  # N+1 = over; NaN / masked -> masked).  Shift to the in-range convention:
  # under -> -1, in-range -> 0..N-1, over -> N.
  out = src.send(:histbin_ki, e, include_max) - 1

  out[:eq, -1] = lfill.nil? ? UNDEF : lfill          # under
  out[:eq, n]  = ufill.nil? ? UNDEF : ufill          # over
  out
end

#bincount(weights: nil, length: 0) ⇒ CArray

Returns occurrence counts per non-negative integer label in self, or a per-label sum of weights.

Masked labels are skipped (not counted). Masked weights are skipped too (their label contributes 0).

Examples:

labels = CA_INT32([0, 1, 1, 2, 0, 1])
labels.bincount                    # => CA_UINT32([2, 3, 1])
labels.bincount(length: 5)         # => CA_UINT32([2, 3, 1, 0, 0])
weights = CA_DOUBLE([1, 2, 3, 4, 5, 6])
labels.bincount(weights: weights)  # => CA_DOUBLE([6, 11, 4])

Parameters:

  • weights (CArray, nil) (defaults to: nil) —

    when given, sums weights per label instead of counting; length must equal self.elements and the output data_type is inherited from weights. When nil (default), counts occurrences and returns CA_UINT32 (or CA_UINT64 if length >= 2^32).

  • length (Integer) (defaults to: 0) —

    minimum output length; the actual length is max(length, self.max + 1).

Returns:

  • (CArray) —

    1-D output of length max(length, self.max + 1).

Raises:

  • (CArray::DataTypeError) —

    when self is not an integer data_type.

  • (ArgumentError) —

    when a label is negative or weights length disagrees with self.elements.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/carray/methods/bincount.rb', line 32

def bincount(weights: nil, length: 0)
  unless [CA_INT8, CA_INT16, CA_INT32, CA_INT64,
          CA_UINT8, CA_UINT16, CA_UINT32, CA_UINT64].include?(data_type)
    raise CArray::DataTypeError,
          "bincount requires an integer label array (got #{data_type_name})"
  end

  if elements.zero?
    if weights
      out = CArray.new(weights.data_type, [length])
    else
      out_type = (length > 0xFFFFFFFF) ? CA_UINT64 : CA_UINT32
      out = CArray.new(out_type, [length])
    end
    out.fill(0) unless length.zero?
    return out
  end

  # Single-pass fused min+max so the prereq scan over labels costs
  # one walk instead of two.
  label_min, label_max = minmax
  if label_min.equal?(UNDEF)
    # Every cell is masked: no labels to count, same result as an empty
    # input (all-zero output of the requested minimum length).
    if weights
      out = CArray.new(weights.data_type, [length])
    else
      out_type = (length > 0xFFFFFFFF) ? CA_UINT64 : CA_UINT32
      out = CArray.new(out_type, [length])
    end
    out.fill(0) unless length.zero?
    return out
  end
  if label_min < 0
    raise ArgumentError,
          "bincount: negative label not allowed (got #{label_min})"
  end

  n = [length, label_max + 1].max

  if weights
    unless weights.is_a?(CArray)
      raise ArgumentError, "bincount: weights must be a CArray"
    end
    if weights.elements != elements
      raise ArgumentError,
            "bincount: weights length (#{weights.elements}) doesn't " \
            "match labels length (#{elements})"
    end
    __bincount_weighted__(weights, n)
  else
    __bincount_count__(n)
  end
end

#bincount_nd(lengths:, axis: [-2, -1], weights: nil) ⇒ BincountND

Returns a discrete N-D joint BincountND count of self with shape fiber_shape + (A, M). Each of the M channels is an integer label in 0..lengths[k]-1; labels >= lengths[k] fold into the upper overflow cell, negative labels raise.

Parameters:

  • lengths (Array<Integer>) —

    per-dimension extents.

  • axis (Array(Integer, Integer)) (defaults to: [-2, -1]) —

    [sample, channel] axis pair.

  • weights (CArray, nil) (defaults to: nil) —

    optional per-sample weights.

Returns:

Raises:

  • (ArgumentError)


339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/carray/bincount_nd.rb', line 339

def bincount_nd (lengths:, axis: [-2, -1], weights: nil)
  raise ArgumentError, "lengths must be an Array of per-dim extents" unless lengths.is_a?(Array)
  sample_ax  = normalize_axis(axis[0], "bincount_nd sample axis")
  channel_ax = normalize_axis(axis[1], "bincount_nd channel axis")
  fiber_shape = shape.dup
  [sample_ax, channel_ax].sort.reverse.each { |p| fiber_shape.delete_at(p) }

  # Weighted counts are float64-only (the FLAT bincount coerces weights to the
  # counts data type and the FIBER kernel requires float64 weights/counts), so
  # the type is fixed here rather than derived from the weights' own type.
  weights_data_type = (:float64 if weights)

  h = BincountND.send(:new,
                      lengths: lengths,
                      fiber_shape: fiber_shape,
                      weights_data_type: weights_data_type)
  h.add(self, axis: axis, weights: weights)
  h
end

#bitarray ⇒ CABitarray

Returns a CABitarray view of self, exposing every bit of every parent cell as an individual boolean cell. See CABitarray for the axis layout and endian handling.

Aliased as bits.

Returns:

Raises:

  • (CADataTypeError) —

    when self.data_type is a complex or object type (bit-level access is not defined for those).



30
# File 'yard-stubs/ca_obj_bitarray.rb', line 30

def bitarray; end

#bitfield(range, type = nil) ⇒ CABitfield

Returns a CABitfield view of self. Each parent cell is treated as a bag of bits; range selects a contiguous slice of those bits, and the resulting view exposes that slice as a cell of the returned array.

range may be an integer (a single bit — the resulting view has data_type :boolean) or a Range covering the bit positions. The data_type of the view is chosen from the bit width: 1 bit → :boolean, 2..8 → :uint8, 9..16 → :uint16, 17..32 → :uint32, 33..64 → :uint64.

type is accepted but currently ignored (the width-derived type is always used).

Parameters:

  • range (Integer, Range) —

    bit position (single bit) or bit range within one parent cell.

  • type (Symbol, nil) (defaults to: nil) —

    reserved, currently ignored.

Returns:

Raises:

  • (IndexError) —

    when range extends past the parent's bit width, when the range has a step != 1, or when the bit length is outside 1..64.

  • (ArgumentError) —

    when the derived bit length exceeds the resolved data type.



40
# File 'yard-stubs/ca_obj_bitfield.rb', line 40

def bitfield(range, type = nil); end

#bits ⇒ CABitarray

Alias for #bitarray.

Returns:



35
# File 'yard-stubs/ca_obj_bitarray.rb', line 35

def bits; end

#block_view(block) ⇒ Object #block_view(b0, b1, ...) ⇒ CAStride

Returns a CAStride view of non-overlapping tiles. A parent of shape [d0, ..., dN-1] becomes a view of shape [d0/b0, ..., dN-1/bN-1, b0, ..., bN-1], where bi is the tile length on axis i.

Unlike #sliding_windows each parent dimension must divide evenly by its tile size: nothing is truncated and no cell is aliased twice. Reduce over the trailing ndim axes (e.g. v.mean(-1, -2) for a 2-D parent) for per-tile statistics such as pooling or block-wise aggregation. Memory is shared with the parent.

Overloads:

  • #block_view(b0, b1, ...) ⇒ CAStride

    Returns of rank 2 * ndim.

    Parameters:

    • block (Array<Integer>, Integer) —

      tile length per axis, one per dimension, as an Array or as variadic arguments.

    Returns:

    Raises:

    • (ArgumentError) —

      when the tile count does not equal ndim, when a tile length is not positive, when an axis is not divisible by its tile length, or when 2 * ndim exceeds CA_RANK_MAX.



106
# File 'yard-stubs/ca_obj_stride.rb', line 106

def block_view(*block); end

#blocks(*blocks) ⇒ CABlockIterator

Returns a CABlockIterator tiling self with non-overlapping tiles of a per-axis size. Each argument is an Integer tile size (offset 0) or a lo..hi range (length = tile size, start = leading offset). The remainder is covered by present-only edge tiles (ceil tile grid); slice first for "valid" tiling.

Parameters:

  • blocks (Array<Integer, Range>) —

    per-axis tile sizes (or ranges).

Returns:



611
612
613
# File 'lib/carray/block_iterator.rb', line 611

def blocks (*blocks)
  CABlockIterator.new(self, *blocks)
end

#boolean ⇒ CArray

Returns a :boolean copy of self. Short-hand of to_type(:boolean).

Returns:



94
# File 'yard-stubs/carray_cast.rb', line 94

def boolean; end

#boolean? ⇒ Boolean

Returns true if self is a boolean type array.

Returns:

  • (Boolean)


215
# File 'yard-stubs/carray_attribute.rb', line 215

def boolean?; end

#broadcast_to(*shape) ⇒ CArray

Returns a read-only CARepeat view of self whose shape is shape. Axes are paired right-to-left:

  • matching extents reuse the source stride
  • target extent > 1 against source extent 1 repeats with stride 0
  • extra leading target axes require the corresponding source axis to be 1 (otherwise raises)

CScalar sources broadcast to any target shape with all strides 0.

The result is read-only because writes against a stride-0 axis would be ambiguous.

Examples:

a = CArray.float64(3) { [1.0, 2.0, 3.0] }
a.broadcast_to(2, 3).to_a
# => [[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]]

Parameters:

  • shape (Array<Integer>) —

    target shape, with length >= self.ndim.

Returns:

Raises:

  • (RuntimeError) —

    if a source axis cannot be paired with a target axis (cross-ndim expansion is intentionally strict — see broadcast for the explicit-:_ / :* axis declaration form).



34
# File 'yard-stubs/carray_broadcast.rb', line 34

def broadcast_to(*shape); end

#bsearch(val) ⇒ Integer, ... #bsearch(val, axis:) ⇒ CArray

Overloads:

  • #bsearch(val) ⇒ Integer, ...

    Returns the flat address of val in self via binary search. self must be sorted along its single (flat) axis. Returns nil if val is not present. When val is a CArray, returns a CArray of :int64 addresses (one per element of val), with UNDEF at positions where the value is not present.

    Parameters:

    Returns:

    Raises:

    • (RuntimeError) —

      if self has any masked element.

  • #bsearch(val, axis:) ⇒ CArray

    Per-fiber binary search along axis. Returns a CArray of axis-local positions, one per fiber.

    Parameters:

    • val (Numeric, CArray)
    • axis (Integer)

    Returns:



131
# File 'yard-stubs/carray_order.rb', line 131

def bsearch(val, axis: nil); end

#bsearch_addr(val) ⇒ Integer, ... #bsearch_addr(val, axis:) ⇒ CArray

Overloads:

  • #bsearch_addr(val) ⇒ Integer, ...

    Equivalent to #bsearch when axis: is omitted (the flat case already returns a flat address).

    Parameters:

    Returns:

  • #bsearch_addr(val, axis:) ⇒ CArray

    Per-fiber binary search along axis, returning flat addresses rather than axis-local positions.

    Parameters:

    • val (Numeric, CArray)
    • axis (Integer)

    Returns:



144
# File 'yard-stubs/carray_order.rb', line 144

def bsearch_addr(val, axis: nil); end

#byte ⇒ Object

Alias of #uint8. @return [CArray]



156
# File 'yard-stubs/carray_cast.rb', line 156

def byte; end

#bytes ⇒ Integer

Returns the byte size of one element. Equals CArray.sizeof(data_type) for numeric types; for fixed-length types this method is the only way to obtain the size.

Returns:

  • (Integer)


48
# File 'yard-stubs/carray_attribute.rb', line 48

def bytes; end

#cast_with(other) ⇒ Array(CArray, CArray)

Returns a two-element [self, other] array with both operands coerced to a common representation under the CArray casting policy. Non-CArray operands are promoted to a CArray (MemoryView producers are wrapped, Ruby scalars become a CScalar), then the narrower side is wrapped read-only in the common data_type. This is the coercion primitive the binary operators use.

Parameters:

  • other (CArray, Object) —

    the second operand.

Returns:

Raises:

  • (RuntimeError) —

    when the two data_types have no common type.



341
# File 'yard-stubs/carray_cast.rb', line 341

def cast_with(other); end

#categorize(labels: nil, sort_labels: false) ⇒ CACategorical

Build a CACategorical from self read as category keys (= the values whose distinct levels become the categories). Codes are dense 0-based in the order labels appear (first-appearance by default, or ascending sorted when sort_labels: true); masked keys become masked (excluded) codes.

labels: nil                        -> discover, first-appearance order
labels: nil, sort_labels: true     -> discover, then sort ascending
labels: set                        -> fixed vocabulary (must be unique);
                                    keys outside it are excluded (masked)

Returns a CACategorical built from self read as category keys. With labels: nil distinct levels are discovered in first-appearance order (or ascending sorted when sort_labels: true); with an explicit labels list the vocabulary is fixed and keys outside it become masked (excluded). sort_labels: is ignored when an explicit labels is given (the caller has already chosen the order).

Parameters:

  • labels (Array, CArray, nil) (defaults to: nil) —

    fixed vocabulary; nil enables discovery.

  • sort_labels (Boolean) (defaults to: false) —

    when discovering (labels: nil), sort the discovered vocabulary ascending after collecting it.

Returns:

Raises:

  • (ArgumentError) —

    when explicit labels contain duplicates.



515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
# File 'lib/carray/categorical.rb', line 515

def categorize(labels: nil, sort_labels: false)
  # Automatic appearance-order vocabulary: one linear pass (C
  # __factorize_appearance__) returns both codes and levels directly, over the
  # integer / float / object / fixlen / boolean lanes (boolean rides the uint8
  # lane). Distinctness is the hash-key judgement shared with the discovery
  # family: Float NaN collapses to one category and -0.0 == +0.0, while mixed
  # Integer / Float keys stay distinct (eql?, so 1 and 1.0 are separate
  # categories). The discovery path below is reserved for sort_labels (which
  # reorders the vocabulary, desyncing the appearance-order codes), an explicit
  # labels list, and the data types the factorize kernel does not take (complex).
  if labels.nil? && !sort_labels && (integer? || float? || object? || fixlen? || boolean?)
    codes, levels = __factorize_appearance__
    return CACategorical.from_codes(codes, levels.to_a)
  end

  if labels.nil?
    # Discover the levels in first-appearance order: mask_duplicates keeps the
    # first occurrence of each distinct value and masks the rest (already-
    # masked keys stay excluded), so the non-masked cells are the levels.
    # Only the final list is Ruby, since labels are Ruby objects.
    labels_arr = mask_duplicates[:is_not_masked].to_a
    labels_arr.sort! if sort_labels
  else
    labels_arr = labels.respond_to?(:to_a) ? labels.to_a : Array(labels)
    if labels_arr.uniq.size != labels_arr.size
      raise ArgumentError, "categorize: labels: must be unique (got duplicates)"
    end
  end

  # Choose a narrow unsigned code type, reserving its top value as the
  # exclusion sentinel so it never collides with a real code 0..k-1.
  k = labels_arr.size
  code_type, sentinel =
    if    k <= 0xFF   then [CA_UINT8,  0xFF]
    elsif k <= 0xFFFF then [CA_UINT16, 0xFFFF]
    else                   [CA_UINT32, 0xFFFFFFFF]
    end

  # One vectorized masked write per category. Cells matching no category
  # (out-of-vocabulary) and masked cells (eq yields UNDEF, skipped) keep the
  # sentinel; from_codes then derives the mask from it.
  codes = CArray.new(code_type, shape).fill(sentinel)
  labels_arr.each_with_index { |label, c| codes[eq(label)] = c }

  CACategorical.from_codes(codes, labels_arr)
end

#choose(choices, data_type: nil) ⇒ CArray

Returns label-based per-cell selection: self is an integer label array, and choices is a list indexed by those labels.

Where self == i, the result takes choices[i] -- a scalar fills those cells, a CArray contributes its corresponding cells. The result has the same shape as self.

Examples:

ref = CA_INT([[0, 1, 2], [1, 2, 0], [2, 0, 1]])
a = CArray.int(3, 3).seq(1)
b = CArray.int(3, 3).seq(11)
c = CArray.int(3, 3).seq(21)
ref.choose([a, b, c])       # per-cell pick from a / b / c
ref.choose(["a", "b", "c"]) # recode labels to values

Parameters:

  • choices (Array<CArray, Object>) —

    values indexed by the labels in self; each entry is either a same-shape CArray or a scalar fill.

  • data_type (Symbol, Integer, nil) (defaults to: nil) —

    result data_type. When nil it is inferred: CArray.result_type of the CArray choices, or CA_OBJECT when every choice is a scalar.

Returns:

  • (CArray) —

    new CArray with the shape of self holding the chosen values.



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/carray/methods/choose.rb', line 26

def choose (choices, data_type: nil)
  unless data_type
    ca = choices.select { |v| v.is_a?(CArray) }
    data_type = ca.empty? ? CA_OBJECT : CArray.result_type(*ca)
  end
  out = template(data_type)
  choices.each_with_index do |v, i|
    s = self.eq(i)
    out[s] = v.is_a?(CArray) ? v[s] : v
  end
  out
end

#clip(min, max = nil, fill_value = nil, lfill: nil, ufill: nil) ⇒ CArray

Returns self with every element clamped to [min, max].

Either bound may be nil for a one-sided clip; that side dispatches to the pmax / pmin binop kernels. When fill_value (or lfill / ufill) is given, out-of-range cells are replaced by the fill instead of clamped -- pass UNDEF to mask that end. fill_value is sugar for symmetric dual-fill; lfill / ufill override per side.

Boundary is strict [min, max]: values equal to a bound remain unchanged in both the clamped and filled variants.

Examples:

a.clip(0, 10)                          # strict clamp
a.clip(0, 10, -1)                      # both ends -> -1
a.clip(0, 10, lfill: UNDEF, ufill: 99) # below masks

Parameters:

  • min (Numeric, nil) —

    lower bound; nil for one-sided clip above.

  • max (Numeric, nil) (defaults to: nil) —

    upper bound; nil for one-sided clip below.

  • fill_value (Object, nil) (defaults to: nil) —

    symmetric fill for out-of-range cells.

  • lfill (Object, nil) (defaults to: nil) —

    override below-range fill.

  • ufill (Object, nil) (defaults to: nil) —

    override above-range fill.

Returns:

  • (CArray) —

    new CArray with clamped or filled values.

Raises:

  • (ArgumentError) —

    when both min and max are nil.



276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/carray/basics.rb', line 276

def clip(min, max=nil, fill_value=nil, lfill: nil, ufill: nil)
  if min.nil? && max.nil?
    raise ArgumentError, "clip: at least one of (min, max) must be given"
  end

  # `fill_value` as a single argument is sugar applied to both ends; kwargs override.
  lfill = fill_value if lfill.nil?
  ufill = fill_value if ufill.nil?

  if lfill.nil? && ufill.nil?
    return __clip_ki__(min, max) if !min.nil? && !max.nil?
    return pmax(min) if max.nil?
    return pmin(max)
  end

  out = self.copy
  out[:lt, min] = lfill unless min.nil? || lfill.nil?
  out[:gt, max] = ufill unless max.nil? || ufill.nil?
  out
end

#clip_int16 ⇒ CArray

Returns an :int16 copy clamped to -32768..32767.

Returns:



# File 'yard-stubs/carray_cast.rb', line 306


#clip_int32 ⇒ CArray

Returns an :int32 copy clamped to the :int32 range.

Returns:



# File 'yard-stubs/carray_cast.rb', line 306


#clip_int64 ⇒ CArray

Returns an :int64 copy clamped to the :int64 range.

Returns:



# File 'yard-stubs/carray_cast.rb', line 306


#clip_int8 ⇒ Object

Returns an :int8 copy of self with values clamped to the :int8 range (-128..127) before casting. @return [CArray]



# File 'yard-stubs/carray_cast.rb', line 306


#clip_uint16 ⇒ Object

Returns a :uint16 copy clamped to 0..65535. @return [CArray]



# File 'yard-stubs/carray_cast.rb', line 306


#clip_uint32 ⇒ CArray

Returns a :uint32 copy clamped to 0..4294967295.

Returns:



# File 'yard-stubs/carray_cast.rb', line 306


#clip_uint64 ⇒ CArray

Returns a :uint64 copy clamped to the :uint64 range.

Returns:



# File 'yard-stubs/carray_cast.rb', line 306


#clip_uint8 ⇒ Object

Returns a :uint8 copy clamped to 0..255. @return [CArray]



# File 'yard-stubs/carray_cast.rb', line 306


#cmplx128 ⇒ CArray

Returns a :cmplx128 copy of self. Short-hand of to_type(:cmplx128).

Returns:



142
# File 'yard-stubs/carray_cast.rb', line 142

def cmplx128; end

#cmplx64 ⇒ CArray

Returns a :cmplx64 copy of self. Short-hand of to_type(:cmplx64).

Returns:



138
# File 'yard-stubs/carray_cast.rb', line 138

def cmplx64; end

#coerce(other) ⇒ Object

[TBD]



345
# File 'yard-stubs/carray_cast.rb', line 345

def coerce(other); end

#collect! ⇒ Object

Alias of #map!.



103
# File 'yard-stubs/carray_loop.rb', line 103

def collect!; end

#collect_addr! ⇒ Object

Alias of #map_addr!.



107
# File 'yard-stubs/carray_loop.rb', line 107

def collect_addr!; end

#collect_index! ⇒ Object

Alias of #map_index!.



111
# File 'yard-stubs/carray_loop.rb', line 111

def collect_index!; end

#collect_with_addr! ⇒ Object

Alias of #map_with_addr!.



115
# File 'yard-stubs/carray_loop.rb', line 115

def collect_with_addr!; end

#collect_with_index! ⇒ Object

Alias of #map_with_index!.



119
# File 'yard-stubs/carray_loop.rb', line 119

def collect_with_index!; end

#complex ⇒ Object

Alias of #cmplx64. @return [CArray]



171
# File 'yard-stubs/carray_cast.rb', line 171

def complex; end

#complex? ⇒ Boolean

Returns true if self is a complex type array.

Returns:

  • (Boolean)


237
# File 'yard-stubs/carray_attribute.rb', line 237

def complex?; end

#concatenate(*others, axis: 0, data_type: nil) ⇒ CArray

Instance form of concatenate: returns [self, *others] concatenated along axis as a fresh CArray. Eager auto-cast counterpart of #meld (view).

Parameters:

  • others (Array<CArray>) —

    additional pieces.

  • axis (Integer) (defaults to: 0) —

    axis to concatenate along.

  • data_type (Symbol, Integer, nil) (defaults to: nil) —

    result data_type; inferred via result_type when nil.

Returns:

Raises:

  • (ArgumentError) —

    when no others are given.

Raises:

  • (ArgumentError)


100
101
102
103
# File 'lib/carray/methods/composition.rb', line 100

def concatenate (*others, axis: 0, data_type: nil)
  raise ArgumentError, "concatenate: at least one other array required" if others.empty?
  CArray.concatenate([self, *others], axis: axis, data_type: data_type)
end

#conditional(cond, then_fn, else_fn, data_type: nil) ⇒ CArray

Returns per-cell then_fn.call(self[cond]) where cond is true and else_fn.call(self[cond.not]) where it is false. The two callables are applied only to their own subset of self, so a branch that would fail on the other region (e.g. ->(v) { v.log } on negative cells) stays safe.

Scalar returns from a callable (e.g. ->(v) { 0 }) broadcast to the subset shape. The result data_type is the promotion of the two subset results via CArray.result_type, or data_type when given. Masked cells in cond propagate to UNDEF in the result.

Examples:

x = CArray.float64(6).span(-2.0..3.0)
x.conditional(x > 0,
              ->(v) { v.log },        # domain-safe: only positive cells
              ->(v) { -v })
# => [2.0, 1.0, -0.0, 0.0, 0.6931..., 1.0986...]

Parameters:

  • cond (CArray) —

    boolean selector; same shape as self.

  • then_fn (#call) —

    callable applied to self[cond].

  • else_fn (#call) —

    callable applied to self[cond.not].

  • data_type (Symbol, Integer, nil) (defaults to: nil) —

    override for the result data type.

Returns:

  • (CArray) —

    new array with the same shape as self.

Raises:

  • (ArgumentError) —

    when cond is not a same-shape boolean CArray.



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/carray/conditional.rb', line 111

def conditional (cond, then_fn, else_fn, data_type: nil)
  unless cond.is_a?(CArray) && cond.boolean? && cond.shape == self.shape
    raise ArgumentError,
          "conditional: cond must be a boolean CArray with same shape as self"
  end

  x_then = self[cond]
  x_else = self[cond.not]
  y_then = then_fn.call(x_then)
  y_else = else_fn.call(x_else)

  # A callable that returns a scalar (e.g. `->(v) { 0 }`) broadcasts
  # to the subset shape; wrap it here so the scatter step below sees a
  # same-length CArray.
  unless y_then.is_a?(CArray)
    y_then = CArray.new(data_type || CArray.result_type(y_then), x_then.shape).fill(y_then)
  end
  unless y_else.is_a?(CArray)
    y_else = CArray.new(data_type || CArray.result_type(y_else), x_else.shape).fill(y_else)
  end

  dt  = data_type || CArray.result_type(y_then, y_else)
  out = CArray.new(dt, self.shape)
  out[cond]     = y_then
  out[cond.not] = y_else
  # Propagate cond's mask (mirrors then_else's rule): UNDEF in cond ->
  # UNDEF in out.  Kleene `cond.not` also carries UNDEF at the same
  # positions, so both scatters leave the cell untouched — an explicit
  # fix-up is required.
  out[cond.is_masked] = UNDEF if cond.has_mask?
  out
end

#convert(data_type = nil, bytes: nil) {|elem| ... } ⇒ CArray

Returns a new CArray of the same shape as self, each element set to the block's return value applied to the corresponding element of self. The output array is built via #template, so data_type (and bytes: for :fixlen) selects the result type; omit them to inherit self.data_type.

Masked cells skip the block; if the block returns CArray::UNDEF, the corresponding output cell is masked.

Parameters:

  • data_type (Symbol, Integer, Class, String, nil) (defaults to: nil)
  • bytes (Integer, nil) (defaults to: nil) —

    element byte size for :fixlen.

Yield Parameters:

  • elem (Object) —

    one element of self.

Yield Returns:

  • (Object) —

    value to store in the result.

Returns:



35
# File 'yard-stubs/carray_conversion.rb', line 35

def convert(data_type = nil, bytes: nil, &block); end

#copy ⇒ CArray

Returns a fresh entity CArray with the same shape, data_type, element values, and mask state as self. Always allocates and copies, even when self is already an entity.

Use copy when you need an array you own and can mutate without affecting any source.

Examples:

A view's copy is independent of its source

a = CArray.float64(4).seq
v = a[1..2]
b = v.copy
b[0] = 99
a   # => [0.0, 1.0, 2.0, 3.0]   # untouched

Returns:

  • (CArray) —

    independent entity.



22
# File 'yard-stubs/carray_copy.rb', line 22

def copy; end

#count(axis: nil) ⇒ Integer, CArray #count(v, axis: nil, min_count: 0, fill_value: nil) ⇒ Integer, CArray

Overloads:

  • #count(axis: nil) ⇒ Integer, CArray

    With no value argument, returns the number of present (not-masked) cells — the arity-0 rung of the dispatch ladder, answering "how many are there". Forwards to #count_not_masked (which stays as an explicit, self-documenting named method).

    Parameters:

    • axis (Integer, Array<Integer>, nil) (defaults to: nil) —

      reduction axis or axes; nil reduces fully.

    Returns:

    • (Integer, CArray) —

      Integer when axis is nil, otherwise a CArray of int64 with the given axes collapsed.

  • #count(v, axis: nil, min_count: 0, fill_value: nil) ⇒ Integer, CArray

    Returns the number of cells of self that equal v, with mask-aware reduction along axis.

    count is an orthogonal arity-dispatch ladder (like Ruby's Array#count): no argument counts present cells, count(UNDEF) counts masked cells, and count(v) counts cells equal to v. Mask-cardinality and value-match are distinct concepts, so the overloading is unambiguous.

    Dispatch:

    • no argument: forwards to #count_not_masked (present-cell count).
    • v == UNDEF: forwards to #count_masked (UNDEF is mask-state vocabulary, not a value).
    • v is a CArray: broadcasts; each v[k] is counted independently and stacked into a result whose trailing axes have shape v.shape. Not supported when self.data_type is :boolean.
    • self.data_type == :boolean: v must be true / false, or the integer literal 1 (= true) / 0 (= false) — boolean stores 0/1, so count(1) == count(true). Any other value (2, 1.0, nil, …) raises TypeError.
    • self is numeric, v is scalar: v must be numeric (true / false are rejected).

    When axis is nil (default), reduces over all axes and returns an Integer. Otherwise reduces along the given axis / axes and returns a CArray.

    An empty or fully-masked reduction returns 0: a count has identity 0, so the count over no cells is 0, not UNDEF (pass min_count: to get UNDEF below a threshold instead).

    :fixlen and :object data types raise CArray::DataTypeError.

    A time array counts by its own values: CATime / CATimedelta descend to their storage and reconcile v into their unit, so v may be an element of the array, another time array (in any unit that converts exactly), or a Ruby Time / DateTime. A bare storage number is refused — use ca.parent.count(n) to count raw ticks.

    Parameters:

    • v (Object, CArray) —

      value (or array of values) to count. UNDEF is treated as a mask-state query.

    • axis (Integer, Array<Integer>, nil) (defaults to: nil) —

      reduction axis or axes; nil reduces fully.

    • min_count (Integer) (defaults to: 0) —

      minimum number of non-masked cells required per reduced slice; slices below the threshold come back masked. Accepted only by the value-argument form (count(v)); the no-argument form accepts axis: only.

    • fill_value (Object, nil) (defaults to: nil) —

      replacement for masked output cells; nil leaves them masked. Value-argument form only.

    Returns:

    Raises:

    • (TypeError) —

      when v's type does not match the dispatch rule above.

    • (CArray::DataTypeError) —

      when self.data_type is :fixlen or :object.



76
# File 'yard-stubs/carray_count.rb', line 76

def count(*args, axis: nil, min_count: 0, fill_value: nil); end

#count_masked ⇒ Integer #count_masked(axis:) ⇒ CArray

Overloads:

  • #count_masked ⇒ Integer

    Returns the total number of masked elements in self.

    Returns:

    • (Integer)
  • #count_masked(axis:) ⇒ CArray

    Returns the per-slice count of masked elements along the given axis or axes. The result is an int64 CArray with axis removed from shape.

    Parameters:

    • axis (Integer, Array<Integer>) —

      axis or axes to reduce.

    Returns:



183
# File 'yard-stubs/carray_mask.rb', line 183

def count_masked(*, **); end

#count_not_masked ⇒ Integer #count_not_masked(axis:) ⇒ CArray

Overloads:

  • #count_not_masked ⇒ Integer

    Returns the total number of not-masked elements in self.

    Returns:

    • (Integer)
  • #count_not_masked(axis:) ⇒ CArray

    Returns the per-slice count of not-masked elements along the given axis or axes. The result is an int64 CArray with axis removed from shape.

    Parameters:

    • axis (Integer, Array<Integer>) —

      axis or axes to reduce.

    Returns:



194
# File 'yard-stubs/carray_mask.rb', line 194

def count_not_masked(*, **); end

#crop(offset, dst) ⇒ CArray

Reads a dst.shape-sized region from self starting at offset into dst. Cells whose read position falls outside self leave the corresponding dst cells untouched.

Parameters:

  • offset (Array<Integer>) —

    source starting indices, length equal to self.ndim.

  • dst (CArray) —

    destination array; mutated in place.

Returns:

Raises:

  • (ArgumentError) —

    when offset.length != self.ndim.

Raises:

  • (ArgumentError)


176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/carray/basics.rb', line 176

def crop (offset, dst)
  raise ArgumentError, "offset length must equal ndim" if offset.length != ndim
  src_ranges = []
  dst_ranges = []
  ndim.times do |i|
    s_lo = [offset[i], 0].max
    s_hi = [offset[i] + dst.shape[i], shape[i]].min
    return dst if s_lo >= s_hi
    src_ranges << (s_lo...s_hi)
    dst_ranges << ((s_lo - offset[i])...(s_hi - offset[i]))
  end
  dst[*dst_ranges] = self[*src_ranges]
  dst
end

#data_class ⇒ Class?

Returns the data_class of self if it is a Face that carries one (e.g. CARecord). Returns nil for non-Face arrays.

Returns:

  • (Class, nil)


133
# File 'yard-stubs/carray_attribute.rb', line 133

def data_class; end

#data_class=(klass) ⇒ void

This method returns an undefined value.

Always raises. data_class now lives on the Face tail (CARecord); use CARecord.new(klass, *shape) or CARecord.wrap(entity, klass) instead.

Parameters:

  • klass (Class) —

    unused.

Raises:

  • (ArgumentError) —

    always.



142
# File 'yard-stubs/carray_attribute.rb', line 142

def data_class=(klass); end

#data_type ⇒ Symbol

Returns the data type of each element as a Symbol (e.g. :int32, :float64).

Returns:

  • (Symbol)


23
# File 'yard-stubs/carray_attribute.rb', line 23

def data_type; end

#data_type_name ⇒ String

Returns the String name of data_type (e.g. "int32", "fixlen").

Returns:

  • (String)


29
# File 'yard-stubs/carray_attribute.rb', line 29

def data_type_name; end

#dcomplex ⇒ Object

Alias of #cmplx128. @return [CArray]



174
# File 'yard-stubs/carray_cast.rb', line 174

def dcomplex; end

#delete_block(offset, bsize) ⇒ CArray

Returns a new CArray obtained by deleting a block of bsize cells (per axis) starting at offset, shrinking the array.

Per axis, offset accepts 0..shape[i]-1 (negative counts from the end) and bsize[i] must be non-negative with offset[i] + bsize[i] <= shape[i]. Bytes and Face identity are preserved naturally because the result is built by fancy-index copy of self. The offset array is not mutated.

Parameters:

  • offset (Array<Integer>) —

    start of the block per axis.

  • bsize (Array<Integer>) —

    block size per axis.

Returns:

Raises:

  • (ArgumentError) —

    on ndim mismatch or out-of-range offset / size.



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/carray/methods/insert_block.rb', line 76

def delete_block (offset, bsize)
  if offset.size != ndim or bsize.size != ndim
    raise ArgumentError, "ndim mismatch"
  end
  offset = offset.dup           # normalize without mutating the caller's array
  newdim = shape
  grids  = []
  ndim.times do |i|
    offset[i] += shape[i] if offset[i] < 0
    if bsize[i] < 0 or offset[i] < 0 or offset[i] >= shape[i] or
        offset[i] + bsize[i] > shape[i]
      raise ArgumentError, "invalid offset or size at axis #{i}"
    end
    newdim[i] -= bsize[i]
    grids[i] = CArray.int32(newdim[i])
    grids[i][0...offset[i]].seq! if offset[i] > 0
    if offset[i] + bsize[i] < shape[i]
      grids[i][offset[i]..-1].seq!(offset[i]+bsize[i])
    end
  end
  return self[*grids].copy
end

#diagonal(offset = 0, axis: [0, 1]) ⇒ CAStride

Returns a CAStride view of one diagonal of the parent. For a 2-D parent of shape [m, n] this is a 1-D view of length min(m, n - offset) for offset >= 0, or min(m + offset, n) for offset < 0.

For a higher-rank parent, the two axes named by axis: collapse into a single diagonal axis appended at the end of the result, and the remaining axes keep their order in front. Memory is shared with the parent.

Parameters:

  • offset (Integer) (defaults to: 0) —

    signed shift from the main diagonal; positive selects a super-diagonal, negative a sub-diagonal. An offset larger than the relevant axis yields an empty view rather than an error. May be passed positionally or as offset:, but not both.

  • axis (Array<Integer>) (defaults to: [0, 1]) —

    the two distinct axes to take the diagonal over; negative indices count from the last axis.

Returns:

Raises:

  • (ArgumentError) —

    when the parent has fewer than two dimensions, when offset is given both positionally and as a keyword, or when axis: is not two distinct in-range axes.



178
# File 'yard-stubs/ca_obj_stride.rb', line 178

def diagonal(offset = 0, axis: [0, 1]); end

#difference(other, sort: false) ⇒ CArray

Returns a 1-D CArray of the distinct values in self that are absent from other, in self's first-appearance order. See #intersection for the shared semantics and options.

Parameters:

  • other (CArray, Array, Range) —

    promoted with self.

  • sort (Boolean) (defaults to: false) —

    when true, return the values sorted ascending.

Returns:

  • (CArray) —

    1-D CArray of the self-only distinct values.



75
76
77
78
79
# File 'lib/carray/methods/is_in.rb', line 75

def difference (other, sort: false)
  a, b = promote_value_set(other)
  r = a.__send__(:__difference__, b)
  sort ? r.sort : r
end

#dim ⇒ Array<Integer>

Deprecated.

Use #shape.

Returns:



87
# File 'yard-stubs/carray_attribute.rb', line 87

def dim; end

#dim0 ⇒ Integer

Returns shape[0].

Returns:

  • (Integer)


92
# File 'yard-stubs/carray_attribute.rb', line 92

def dim0; end

#dim1 ⇒ Integer?

Returns shape[1], or nil if ndim < 2.

Returns:

  • (Integer, nil)


97
# File 'yard-stubs/carray_attribute.rb', line 97

def dim1; end

#dim2 ⇒ Integer?

Returns shape[2], or nil if ndim < 3.

Returns:

  • (Integer, nil)


102
# File 'yard-stubs/carray_attribute.rb', line 102

def dim2; end

#dim3 ⇒ Integer?

Returns shape[3], or nil if ndim < 4.

Returns:

  • (Integer, nil)


107
# File 'yard-stubs/carray_attribute.rb', line 107

def dim3; end

#dim_view(axes) ⇒ Object #dim_view(a0, a1, ...) ⇒ CATranspose

Returns a CATranspose view in which the given axes are moved to the front, in the order given, with the remaining axes following in their original order — a thin alias over transposed that names the intent "bring these axes to the front, keep the rest as the inner slice".

Examples:

a = CArray.float64(3, 4, 5).seq
a.dim_view(0, 2)    # shape [3, 5, 4]
a.dim_view(1)       # shape [4, 3, 5]
a.dim_view(-1)      # shape [5, 3, 4]

Overloads:

  • #dim_view(a0, a1, ...) ⇒ CATranspose

    Parameters:

    • axes (Array<Integer>, Integer) —

      axes to bring to the front; negative indices count from the last axis.

    Returns:

    Raises:

    • (ArgumentError) —

      when no axis is given, when more axes are given than ndim, or when an axis is out of range or repeated.



126
# File 'yard-stubs/ca_obj_stride.rb', line 126

def dim_view(*axes); end

#div(other) ⇒ CArray

Alias of #/.

Parameters:

  • other (CArray, Numeric) —

    divisor.

Returns:



34
# File 'yard-stubs/carray_math.rb', line 34

def div(other); end

#div!(other) ⇒ self

Divides self by other in place, keeping self's data_type.

Parameters:

  • other (CArray, Numeric) —

    divisor.

Returns:

  • (self)


40
# File 'yard-stubs/carray_math.rb', line 40

def div!(other); end

#divmod(other) ⇒ Array<CArray>

Returns [quotient, remainder] element-wise.

The quotient is floored toward -inf, so q * other + r == self holds for every sign combination -- the pair Ruby's Integer#divmod and Float#divmod return. For integers that is self / other unchanged; for floats / is true division, so the quotient is floored here.

Examples:

CA_INT32([-7]).divmod(3)     # => [-3, 2]
CA_DOUBLE([-7.0]).divmod(3.0) # => [-3.0, 2.0]

Parameters:

  • other (CArray, Numeric) —

    divisor.

Returns:

  • (Array<CArray>) —

    the floored quotient and the remainder.

Raises:

  • (ArgumentError) —

    for complex arrays, which have no ordering to floor toward.



238
239
240
241
242
243
244
245
# File 'lib/carray/basics.rb', line 238

def divmod(other)
  if complex?
    raise ArgumentError, "divmod is not defined for complex arrays"
  end
  q = self / other
  q = q.floor unless q.integer?
  [q, self % other]
end

#double ⇒ Object

Alias of #float64. @return [CArray]



168
# File 'yard-stubs/carray_cast.rb', line 168

def double; end

#drop_axis ⇒ CArray

Returns a view of self with every size-1 axis dropped.

Returns:

  • (CArray) —

    view with reduced ndim.



112
113
114
115
116
117
118
119
# File 'lib/carray/basics.rb', line 112

def drop_axis
  if ndim == 1
    return self[]
  else
    newdim = shape.reject{|x| x == 1 }
    return ( ndim != newdim.size ) ? reshape(*newdim) : self[]
  end
end

#dump_binary ⇒ String #dump_binary(io) ⇒ String, ...

Overloads:

  • #dump_binary ⇒ String

    Returns a new binary String containing the raw element bytes of self in row-major order.

    Returns:

    • (String)

    Raises:

  • #dump_binary(io) ⇒ String, ...

    Writes the raw element bytes of self to io and returns io. io may be a String (resized and overwritten), an IO, or any object responding to write.

    Parameters:

    • io (String, IO, #write)

    Returns:

    • (String, IO, Object) —

      the io argument.

    Raises:



55
# File 'yard-stubs/carray_conversion.rb', line 55

def dump_binary(io = nil); end

#each {|elem| ... } ⇒ self, Enumerator

Yields each element of self once in row-major (flat address) order. Returns an Enumerator when no block is given.

Yield Parameters:

  • elem (Object)

Returns:

  • (self, Enumerator)


13
# File 'yard-stubs/carray_loop.rb', line 13

def each; end

#each_addr {|addr| ... } ⇒ self, Enumerator

Yields each flat address 0...elements once. Returns an Enumerator when no block is given.

Yield Parameters:

  • addr (Integer)

Returns:

  • (self, Enumerator)


20
# File 'yard-stubs/carray_loop.rb', line 20

def each_addr; end

#each_index {|idx| ... } ⇒ self, Enumerator

Yields each multi-dimensional index of self once in row-major order. Block receives one Integer per axis (variadic, not a single Array); use |*idx| to collect them. Returns an Enumerator when no block is given.

Yield Parameters:

  • idx (Integer) —

    one Integer per axis.

Returns:

  • (self, Enumerator)


29
# File 'yard-stubs/carray_loop.rb', line 29

def each_index; end

#each_slab(axis:) ⇒ Object #each_slab(axis:) ⇒ self, Enumerator

Overloads:

  • #each_slab(axis:) ⇒ Object

    Yields each slab of self (a view along the axes NOT in axis) to the block and returns self. The slab is a live view valid only for the duration of the block — capturing it across iterations sees the last slab's data.

  • #each_slab(axis:) ⇒ self, Enumerator

    Returns an Enumerator when no block is given.

    Parameters:

    • axis (Integer, Array<Integer>, nil) —

      the slab axis or axes (nil = the whole view as a single slab).

    Returns:

    • (self, Enumerator)

    See Also:



23
# File 'yard-stubs/carray_slab.rb', line 23

def each_slab(axis:); end

#each_with_addr {|elem, addr| ... } ⇒ self, Enumerator

Yields each (element, flat-address) pair in row-major order. Returns an Enumerator when no block is given.

Yield Parameters:

  • elem (Object)
  • addr (Integer)

Returns:

  • (self, Enumerator)


37
# File 'yard-stubs/carray_loop.rb', line 37

def each_with_addr; end

#each_with_index {|elem, idx| ... } ⇒ self, Enumerator

Yields each element followed by its multi-dimensional index components in row-major order. Block signature is |elem, i, j, ...| (one Integer per axis, not a single Array); use |elem, *idx| to collect them. Returns an Enumerator when no block is given.

Yield Parameters:

  • elem (Object)
  • idx (Integer) —

    one Integer per axis.

Returns:

  • (self, Enumerator)


48
# File 'yard-stubs/carray_loop.rb', line 48

def each_with_index; end

#elem_copy(idx1, idx2) ⇒ self

Copies the value (and mask state) at idx1 into the cell at idx2. The source cell is unchanged. Mutates self.

Parameters:

  • idx1 (Integer, Array<Integer>) —

    source position.

  • idx2 (Integer, Array<Integer>) —

    destination position.

Returns:

  • (self)


29
# File 'yard-stubs/carray_element.rb', line 29

def elem_copy(idx1, idx2); end

#elem_decr(idx) ⇒ self

Decrements the value at idx by 1 in place. Mutates self. Masked cells are skipped.

Parameters:

  • idx (Integer, Array<Integer>)

Returns:

  • (self)


60
# File 'yard-stubs/carray_element.rb', line 60

def elem_decr(idx); end

#elem_fetch(idx) ⇒ Object?

Returns the value at position idx (cast back to the appropriate Ruby type). Returns UNDEF if the cell is masked. Returns nil if self.empty?.

Parameters:

  • idx (Integer, Array<Integer>)

Returns:

  • (Object, nil)


46
# File 'yard-stubs/carray_element.rb', line 46

def elem_fetch(idx); end

#elem_incr(idx) ⇒ self

Increments the value at idx by 1 in place. Mutates self. Masked cells are skipped.

Parameters:

  • idx (Integer, Array<Integer>)

Returns:

  • (self)


53
# File 'yard-stubs/carray_element.rb', line 53

def elem_incr(idx); end

#elem_mask(idx) ⇒ self

Marks the cell at idx as masked. Allocates the mask array if self does not yet have one. Mutates self.

Parameters:

  • idx (Integer, Array<Integer>)

Returns:

  • (self)


98
# File 'yard-stubs/carray_element.rb', line 98

def elem_mask(idx); end

#elem_masked?(idx) ⇒ Boolean

Returns true if the cell at idx is masked.

Parameters:

  • idx (Integer, Array<Integer>)

Returns:

  • (Boolean)


91
# File 'yard-stubs/carray_element.rb', line 91

def elem_masked?(idx); end

#elem_max(idx, v) ⇒ self

Updates the cell at idx to max(self[idx], v). Mutates self.

Masked cells are skipped. NaN follows the fmax rule.

Parameters:

  • idx (Integer, Array<Integer>)
  • v (Numeric)

Returns:

  • (self)

Raises:



81
# File 'yard-stubs/carray_element.rb', line 81

def elem_max(idx, v); end

#elem_min(idx, v) ⇒ self

Updates the cell at idx to min(self[idx], v). Mutates self.

Masked cells are skipped. NaN follows the fmin rule (NaN is treated as missing: min(NaN, v) == v, min(x, NaN) == x).

Parameters:

  • idx (Integer, Array<Integer>)
  • v (Numeric)

Returns:

  • (self)

Raises:



71
# File 'yard-stubs/carray_element.rb', line 71

def elem_min(idx, v); end

#elem_store(idx, value) ⇒ Object

Stores value (cast to self.data_type) at position idx, clearing the mask state at that cell. Passing UNDEF masks the cell.

Parameters:

  • idx (Integer, Array<Integer>)
  • value (Object)

Returns:

  • (Object) —

    value.



38
# File 'yard-stubs/carray_element.rb', line 38

def elem_store(idx, value); end

#elem_swap(idx1, idx2) ⇒ self

Exchanges the values (and mask states, if any) at positions idx1 and idx2. Mutates self.

Parameters:

  • idx1 (Integer, Array<Integer>)
  • idx2 (Integer, Array<Integer>)

Returns:

  • (self)


21
# File 'yard-stubs/carray_element.rb', line 21

def elem_swap(idx1, idx2); end

#elem_unmask(idx) ⇒ self

Clears the mask state at idx, leaving the stored data unchanged. Mutates self.

Parameters:

  • idx (Integer, Array<Integer>)

Returns:

  • (self)


105
# File 'yard-stubs/carray_element.rb', line 105

def elem_unmask(idx); end

#elements ⇒ Integer

Returns the total number of elements (product of shape).

Returns:

  • (Integer)


62
# File 'yard-stubs/carray_attribute.rb', line 62

def elements; end

#empty? ⇒ Boolean

Returns true if self has zero elements.

Returns:

  • (Boolean)


174
# File 'yard-stubs/carray_attribute.rb', line 174

def empty?; end

#endian(byte_order) ⇒ CArray

Returns a view of self in the requested byte order.

byte_order is one of:

  • :preserve / :native — identity, since CArrays are stored host-endian.
  • :big — identity on big-endian hosts, otherwise a byte-swap view.
  • :little — identity on little-endian hosts, otherwise a byte-swap view.

The keyword set matches BulkMemoryView.from(producer, endian:).

Returns self or a byte-swap view.

Parameters:

  • byte_order (Symbol) —

    one of :preserve, :native, :big, :little.

Returns:

  • (CArray) —

    self or a byte-swap view.

Raises:

  • (ArgumentError) —

    when byte_order is not one of the accepted symbols.



53
# File 'yard-stubs/ca_obj_byte_swap.rb', line 53

def endian(byte_order); end

#entity? ⇒ Boolean

Returns true if self is an entity array (not a virtual view).

Returns:

  • (Boolean)


157
# File 'yard-stubs/carray_attribute.rb', line 157

def entity?; end

#eql?(other) ⇒ Boolean

Returns true under Hash-invariant semantics: data_class, data_type, shape, and mask state must all match, and elements are compared bitwise (for numeric types) or via Object#eql? (for :object arrays). Unlike ==, NaN.eql?(NaN) holds, so two mask-free arrays with NaN at the same positions are eql?.

Guarantees a.eql?(b) ⇒ a.hash == b.hash.

Parameters:

  • other (Object)

Returns:

  • (Boolean)


53
# File 'yard-stubs/carray_test.rb', line 53

def eql?(other); end

#face? ⇒ Boolean

Returns true if self is a Face view (CA_FLAG_IS_FACE set).

Returns:

  • (Boolean)


199
# File 'yard-stubs/carray_attribute.rb', line 199

def face?; end

#fake(data_type, bytes: 0) ⇒ CAFake

Returns a CAFake view of self whose element type is data_type (and bytes: for :fixlen). Reads and writes go through the cast table, so the returned view shares storage with self but exposes it under a different data_type. A Face refuses: its cells do not mean their storage bytes, so reading them under another type hands back what the surface exists to hide. Use #to_type for the values, or face.parent.fake to reinterpret the storage on purpose. A Numeric Face, whose surface is its storage, is unaffected.

Parameters:

  • data_type (Symbol, Integer, Class, String)
  • bytes (Integer) (defaults to: 0) —

    element byte size for :fixlen.

Returns:

Raises:

  • (TypeError) —

    when self is a Face and the request would read its storage under another type.



29
# File 'yard-stubs/ca_obj_fake.rb', line 29

def fake(data_type, bytes: 0); end

#false ⇒ CArray

Returns a boolean CArray of the same shape as self filled with false.

Returns:



133
134
135
# File 'lib/carray/basics.rb', line 133

def false ()
  return template(:boolean)
end

#farray ⇒ CAFarray

Returns a CAFarray view of self that exposes the same memory in column-major (Fortran) order. The shape is self.shape reversed; element view[i_0, ..., i_{n-1}] aliases parent element self[i_{n-1}, ..., i_0].

Useful for interop with column-major consumers (LAPACK, Fortran libraries) without copying.

Returns:



29
# File 'yard-stubs/ca_obj_farray.rb', line 29

def farray; end

#field(offset, data_type, bytes: nil) ⇒ CAField #field(offset, template) ⇒ CArray #field(offset, data_class) ⇒ CArray #field(name) ⇒ CArray

Overloads:

  • #field(offset, data_type, bytes: nil) ⇒ CAField

    Returns a CAField view of one field of a fixlen-record self. The view has the same shape as self; each element is the bytes-wide slice of element type data_type at byte offset within the corresponding record. No data is copied; writes go through to self.

    Parameters:

    • offset (Integer) —

      byte offset of the field within one record.

    • data_type (Symbol, Integer) —

      element type symbol or constant. :object is not allowed.

    • bytes (Integer, nil) (defaults to: nil) —

      element size; required for :fixlen, inferred otherwise.

    Returns:

    Raises:

    • (RuntimeError) —

      when offset is negative or the offset + bytes window falls outside one parent record.

  • #field(offset, template) ⇒ CArray

    Returns a CARefer over a CAField: takes template.elements * template.bytes bytes at offset and exposes them with template's element type and trailing shape.

    Parameters:

    • offset (Integer)
    • template (CArray) —

      element type and trailing shape donor.

    Returns:

  • #field(offset, data_class) ⇒ CArray

    Returns a CARecord wrapping a CAField so the result carries data_class's encode/decode dispatch.

    Parameters:

    • offset (Integer)
    • data_class (Class) —

      e.g. a CAStruct subclass.

    Returns:

  • #field(name) ⇒ CArray

    Returns the field named name. Delegates to the parent's Face layer (rb_ca_face_field); resolution depends on the record schema attached to self.

    Parameters:

    • name (Symbol, String)

    Returns:



42
# File 'yard-stubs/ca_obj_field.rb', line 42

def field(*); end

#fields ⇒ Array<CArray>

Returns one field view per member of self.data_class, in declaration order. Each entry is a CArray sharing storage with self.

Returns:

Raises:

  • (RuntimeError) —

    if self has no data_class.



80
# File 'yard-stubs/carray_core.rb', line 80

def fields; end

#fields_at(*names) ⇒ Array<CArray>

Returns the field views for the named members of self.data_class, in the given order.

Parameters:

  • names (Array<Symbol, String, Integer>) —

    member names or positional indices.

Returns:

Raises:

  • (RuntimeError) —

    if self has no data_class.



89
# File 'yard-stubs/carray_core.rb', line 89

def fields_at(*names); end

#fill(value) ⇒ self

Sets every element of self to value and clears any mask.

Parameters:

  • value (Object) —

    the fill value.

Returns:

  • (self)


65
# File 'yard-stubs/carray_access.rb', line 65

def fill(value); end

#fill_copy(value) ⇒ CArray

Returns a copy of self with every element set to value.

Parameters:

  • value (Object) —

    the fill value.

Returns:

  • (CArray) —

    the filled copy.



71
# File 'yard-stubs/carray_access.rb', line 71

def fill_copy(value); end

#first(axis: nil, keep_axis: false) ⇒ Object, CArray

first / last are the reduction sibling of the :forward / :backward hold (see #unmask): instead of filling a whole fiber they return the one first / last valid (unmasked) value. For an unmasked array they degrade to the first / last element. Works for every data_type.

Returns the first valid (unmasked) value along axis, skipping masked cells. Identity-less: a fiber with no valid cell (all masked, or empty) yields UNDEF. To substitute a default instead, complete at the call site — a.first(axis: 0).strip_mask(v).

Parameters:

  • axis (Integer, Array<Integer>, nil) (defaults to: nil) —

    reduce axis / axes; nil reduces the whole array to a scalar.

  • keep_axis (Boolean) (defaults to: false) —

    keep the reduced axis as a size-1 axis.

Returns:

  • (Object, CArray) —

    a scalar for a full reduce (UNDEF if no valid cell), otherwise a reduced CArray.



138
# File 'yard-stubs/carray_mask.rb', line 138

def first(axis: nil, keep_axis: false); end

#fixlen(bytes: nil) ⇒ CArray

Returns a :fixlen copy of self. Short-hand of to_type(:fixlen, bytes:).

Parameters:

  • bytes (Integer, nil) (defaults to: nil) —

    fixed element width in bytes.

Returns:



152
# File 'yard-stubs/carray_cast.rb', line 152

def fixlen(bytes: nil); end

#fixlen? ⇒ Boolean

Returns true if self is a fixed-length type array.

Returns:

  • (Boolean)


210
# File 'yard-stubs/carray_attribute.rb', line 210

def fixlen?; end

#flags ⇒ Integer

Returns the raw internal flag bitset (ca->flags) as an Integer. The bits record structural facts about the array (scalar, Face, view, read-only, …). This is a low-level provenance value with no stable public meaning; it is exposed mainly so the _CARRAY3 serializer can snapshot it into a saved file's header.

Returns:

  • (Integer)


57
# File 'yard-stubs/carray_attribute.rb', line 57

def flags; end

#flatten ⇒ CArray

Returns a 1-D view of all cells in row-major order — a CAStride when the flatten reduces to pure strides over the deepest ancestor, otherwise a CARefer.

Returns the 1-D view.

Returns:



69
# File 'yard-stubs/ca_obj_refer.rb', line 69

def flatten; end

#flip ⇒ Object #flip(axis) ⇒ Object #flip(a0, a1, ...) ⇒ Object #flip([a0, a1, ...]) ⇒ CAStride

Returns a CAStride view with the listed axes reversed (a negative stride on each); with no argument every axis is reversed. Memory is shared with the parent, so writes through the view propagate.

This is the named counterpart of the indexer form ca[-1..0, nil, -1..0] — both produce a true negative-stride view with no copy. Use flip when the axis list is parametric or when the named intent reads better than the slice form. There is no flip!; the in-place idiom is ca[] = ca.flip.

reverse is an alias of flip.

Examples:

a = CArray.float64(4, 5).seq
a.flip              # every axis reversed
a.flip(0)           # row order reversed
a.flip(-1)          # same as a.flip(1)
a.flip([0, 1])      # Array form

Overloads:

  • #flip([a0, a1, ...]) ⇒ CAStride

    Parameters:

    • axis (Array<Integer>, Integer) —

      axes to reverse; negative indices count from the last axis.

    Returns:

    Raises:

    • (ArgumentError) —

      when an axis is out of range or repeated.



155
# File 'yard-stubs/ca_obj_stride.rb', line 155

def flip(*axis); end

#float ⇒ Object

Alias of #float32. @return [CArray]



165
# File 'yard-stubs/carray_cast.rb', line 165

def float; end

#float32 ⇒ CArray

Returns a :float32 copy of self. Short-hand of to_type(:float32).

Returns:



130
# File 'yard-stubs/carray_cast.rb', line 130

def float32; end

#float64 ⇒ CArray

Returns a :float64 copy of self. Short-hand of to_type(:float64).

Returns:



134
# File 'yard-stubs/carray_cast.rb', line 134

def float64; end

#float? ⇒ Boolean

Returns true if self is a floating-point type array.

Returns:

  • (Boolean)


232
# File 'yard-stubs/carray_attribute.rb', line 232

def float?; end

#fmod(other) ⇒ CArray

Returns the element-wise truncated remainder of self divided by other, carrying the sign of the dividend.

This is C's fmod and %: the quotient is truncated toward zero rather than floored, so fmod(-7, 3) is -1 where -7 % 3 is 2. Integer arrays are accepted as well as floats. Complex arrays have no remainder. An :object array delegates to each element's #remainder, so an Integer element yields an Integer. Masked elements stay masked.

Examples:

CA_INT32([-7, -1, 7]).fmod(3)  # => [ -1, -1, 1 ]
CA_DOUBLE([-0.4]).fmod(1.0)    # => [ -0.4 ]

Parameters:

  • other (CArray, Numeric) —

    divisor, broadcast to self.shape.

Returns:

  • (CArray) —

    result of the promoted data_type of the two operands.

Raises:

  • (ZeroDivisionError) —

    when an integer divisor is 0. A float divisor of 0.0 yields NaN.

  • (CArray::DataTypeError) —

    for a complex array.



96
# File 'yard-stubs/carray_math.rb', line 96

def fmod(other); end

#fmod!(other) ⇒ self

Replaces self with the truncated remainder in place, keeping self's data_type.

Parameters:

  • other (CArray, Numeric) —

    divisor.

Returns:

  • (self)


103
# File 'yard-stubs/carray_math.rb', line 103

def fmod!(other); end

#format(fmt, *argv) ⇒ CAString

Returns a CAString formatting each cell of self with fmt; self is the first Kernel.format argument, so arr.format("%03d") renders the cells and arr.format("%s=%d", other) interleaves a second array. This is the explicit stringify path for numeric (and any) arrays — the to_* string conversions are String-Face only. Equivalent to CArray.format(fmt, self, *argv).

Defining a public CArray#format shadows the private Kernel#format for CArray instances; internal CArray methods therefore use sprintf / Kernel.format explicitly (verified: no bare format(...) call runs on a CArray receiver anywhere in the library).

Parameters:

  • fmt (String) —

    Kernel.format template.

  • argv (Array<CArray, Object>) —

    additional per-cell CArrays / broadcast scalars.

Returns:

Raises:

  • (ArgumentError) —

    when a CArray argument's shape differs from self.



53
54
55
# File 'lib/carray/methods/string_format.rb', line 53

def format (fmt, *argv)
  CArray.format(fmt, self, *argv)
end

#frac ⇒ CArray

Returns a new array of the fractional part of each element: self - self.truncated_toward_zero, so the result keeps the sign of the input (1.25 -> 0.25, -1.25 -> -0.25). The result keeps self's data_type.

Integer arrays yield all zeros. For a floating-point array a NaN element is passed through as NaN, and ±0.0 keeps its sign. Masked elements stay masked. An :object array delegates to each element's #frac.

Returns:

  • (CArray) —

    same data_type as self.



129
# File 'yard-stubs/carray_math.rb', line 129

def frac; end

#freeze ⇒ self

Freezes self and marks it read-only. Subsequent mutations raise FrozenError.

Returns:

  • (self)


71
# File 'yard-stubs/carray_test.rb', line 71

def freeze; end

#from_bit_string(bstr, nb) ⇒ self

Sets self by unpacking bstr as a packed-bit byte string with nb bits per element.

Parameters:

  • bstr (String) —

    packed byte string.

  • nb (Integer) —

    bits per element.

Returns:

  • (self)


24
25
26
27
28
29
30
# File 'lib/carray/methods/bit_string.rb', line 24

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

#gather_nd(indices) ⇒ CArray

Returns elements (or sub-arrays) gathered from self at the N-D coordinates given by indices.

indices accepts two equivalent forms:

  • stacked — a single CArray whose last axis enumerates a K-dimensional coordinate tuple into the first K axes of self.
  • per-axis — an Array of K coordinate CArrays (one per consumed axis). The per-axis arrays are broadcast together (via broadcast) and stacked along a new trailing axis, so gather_nd([i, j]) == gather_nd(CArray.stack([i, j], axis: -1)). An Integer scalar is accepted for a constant axis and broadcast to the common shape. Entries must be CArray or Integer: Ruby Array literals are rejected (wrap them with CA_INT64(...) yourself), keeping this a copy-free gather path.

The remaining self.shape[K..-1] axes (called rest) are carried through:

self.shape    = (D0, ..., D_{K-1}, *rest)
indices.shape = (*outer, K)          # stacked form
result.shape  = (*outer, *rest)

In the fully-degenerate case where both outer and rest are empty (a single full coordinate via 1-D indices of shape (K,) with K == ndim), the result is a 1-element (1,) CArray, following CArray's scalar model (CScalar carries shape [1]), not a 0-dim array.

The result is a fresh materialised CArray. Negative indices on each coordinate axis follow CArray's standard wrap rule (-1 == last); out-of-range indices raise. Duplicate coordinates in indices are fine on gather: the same value is picked multiple times. See #put_nd for the duplicate-write story.

Parameters:

  • indices (CArray, Array<CArray, Integer>) —

    stacked integer CArray with ndim >= 1 and last axis size K in [1, ndim], or an Array of K per-axis coordinate CArrays (Integer scalars allowed per axis).

Returns:

  • (CArray) —

    materialised result with shape outer + rest.

Raises:

  • (ArgumentError) —

    when indices is neither a CArray nor an Array, is 0-dim, is non-integer, or has a last-axis size outside [1, ndim].

  • (IndexError) —

    when a coordinate is out of range on any axis.



63
64
65
66
67
68
69
# File 'lib/carray/methods/gather_nd.rb', line 63

def gather_nd (indices)
  flat_addr, outer, rest = gather_nd_flat_addr(indices, "gather_nd")
  out_shape = outer + rest
  # flatten + 1-D fancy indexing -> CAMapping view -> materialise via .copy.
  result = self.flatten[flat_addr].copy
  out_shape.empty? ? result : result.reshape(*out_shape)
end

#grid(*selectors) ⇒ CArray

Returns a coordinate-selected view of self: one selector per axis picks a set of parent indices along that axis, and the view is their Cartesian product. The output size along axis k is the number of indices selected for that axis.

Each selector is one of:

  • nil — the whole axis, in order.
  • an integer Range — a contiguous sub-range along the axis.
  • a CArray of integer indices — gather exactly those parent indices (arbitrary order; duplicates produce duplicated cells).
  • a boolean CArray — the indices where it is true.

A masked index CArray selects only its not-masked cells. The view is writable; scattering back to overlapping cells (from duplicate indices) is last-write-wins.

Parameters:

Returns:

Raises:

  • (ArgumentError) —

    when more selectors than ndim are given.

  • (IndexError) —

    when a selected index is out of range.

  • (RuntimeError) —

    when a selector is a plain Ruby Array (not supported; pass a CArray of indices instead).



33
# File 'yard-stubs/ca_obj_grid.rb', line 33

def grid(*selectors); end

#group_by_category(cat) ⇒ CACategoricalIterator

Returns a CACategoricalIterator that reduces self (the payload) per category of cat. Requires self.elements == cat.elements.

Parameters:

Returns:

Raises:

  • (ArgumentError) —

    when element counts differ.



1038
1039
1040
# File 'lib/carray/categorical_iterator.rb', line 1038

def group_by_category (cat)
  CACategoricalIterator.new(self, cat)
end

#group_by_run ⇒ CACategoricalIterator

Segments self into maximal runs of consecutive non-masked cells and returns a CACategoricalIterator that reduces each run as one category, ordered by position. The run boundary is the mask: a masked cell belongs to no run and breaks any run across it. State what separates runs (the "background") by masking before the call — e.g. ca.mask_where(:le, 0) makes non-positive cells background without mutating ca. A series with no present cell yields zero groups rather than raising. 1-D only.

prec = CA_DOUBLE([1,2,2,2,0,0,0,2,1,2,0,0,0,3,2,3,2,1,0,0,0])
grp  = prec.mask_where(:le, 0).group_by_run
grp.sum     # => [7.0, 5.0, 11.0]   per-run accumulation
grp.count   # => [4, 3, 5]          per-run length
grp.each { |members| ... }          # each run as a CArray

The run categories are labelled by their 0-based run index, so grp.labels is [0, 1, ...] in position order.

Returns:

Raises:

  • (RuntimeError) —

    when self is not 1-D.



1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
# File 'lib/carray/categorical_iterator.rb', line 1064

def group_by_run
  raise "group_by_run: 1-D only (got #{ndim}-D)" unless ndim == 1
  if elements == 0
    code = CArray.int64(0)
  else
    present = is_not_masked
    edge    = present & present.shift(1).not   # rising edge = run start
    # feed cumsum via a zero-copy int8 reinterpret of the 1-byte booleans
    # rather than widening to int64; cumsum promotes to float64, so the
    # running count never overflows int8.
    code    = edge.refer(:int8).cumsum.int64 - 1   # 0-based run index per cell
    code[present.not] = UNDEF                  # masked cells join no run
  end
  # categorize turns the dense run indices into the run categories: it derives
  # the label vocabulary and folds an all-masked (dry) series to zero groups
  # on its own, so no explicit run count is needed here. code is monotonic (a
  # cumsum), so categorize's first-appearance order is already run order and
  # sort_labels would be a no-op.
  group_by_category(code.categorize)
end

#has_attr? ⇒ Boolean #has_attr?(key) ⇒ Boolean

Overloads:

  • #has_attr? ⇒ Boolean

    Returns whether self (or any parent view) has any attribute set.

    Returns:

    • (Boolean)
  • #has_attr?(key) ⇒ Boolean

    Returns whether self (or any parent view) has attribute key set.

    Parameters:

    • key (Symbol, String) —

      attribute key.

    Returns:

    • (Boolean)


87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/carray/attribute.rb', line 87

def has_attr? (key = nil)
  if key.nil?
    attr_each_chain do |h|
      return true unless h.empty?
    end
    false
  else
    k = attr_normalize_key(key)
    attr_each_chain do |h|
      return true if h.key?(k)
    end
    false
  end
end

#has_data_class? ⇒ Boolean

Returns true if self carries a data_class (i.e. is a Face such as CARecord).

Returns:

  • (Boolean)


205
# File 'yard-stubs/carray_attribute.rb', line 205

def has_data_class?; end

#has_mask? ⇒ Boolean

Returns true if self has a mask array attached. Note that a present mask may still have every entry set to "not masked".

Returns:

  • (Boolean)


12
# File 'yard-stubs/carray_mask.rb', line 12

def has_mask?; end

#hash ⇒ Integer

Returns the Hash key value for self. Mixes data_type, ndim, bytes, elements, shape, scalar-ness, and mask presence; for unmasked arrays, samples the leading 64 bytes of data. Masked arrays skip the data sample.

Returns:

  • (Integer)


61
# File 'yard-stubs/carray_test.rb', line 61

def hash; end

#histogram(edges:, axis: [-2, -1], include_max: false, weights: nil) ⇒ Histogram

Returns an M-D joint Histogram built from self with shape fiber_shape + (A, M), where M == edges.size.

Parameters:

  • edges (Array<CArray, Array<Numeric>>) —

    one edges array per dimension.

  • axis (Array(Integer, Integer)) (defaults to: [-2, -1]) —

    [sample, channel] axis pair.

  • include_max (Boolean, Array<Boolean>) (defaults to: false) —

    fold-max flag, per dimension.

  • weights (CArray, nil) (defaults to: nil) —

    optional per-sample weights.

Returns:

Raises:

  • (ArgumentError) —

    when edges is not an Array.

Raises:

  • (ArgumentError)


491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
# File 'lib/carray/histogram.rb', line 491

def histogram (edges:, axis: [-2, -1], include_max: false, weights: nil)
  raise ArgumentError, "edges must be an Array of edges arrays" unless edges.is_a?(Array)
  arr = self
  sample_ax  = normalize_axis(axis[0], "histogram sample axis")
  channel_ax = normalize_axis(axis[1], "histogram channel axis")
  fiber_shape = arr.shape.dup
  [sample_ax, channel_ax].sort.reverse.each { |p| fiber_shape.delete_at(p) }

  # Weighted counts are float64-only (the fused scatter kernel requires
  # float64 weights and float64 counts), so the type is fixed here rather
  # than derived from the weights' own type.
  weights_data_type = (:float64 if weights)

  h = Histogram.send(:new,
                    edges: edges,
                    fiber_shape: fiber_shape,
                    include_max: include_max,
                    weights_data_type: weights_data_type)
  h.add(arr, axis: axis, weights: weights)
  h
end

#histogram1d(edges:, axis: -1, include_max: false, weights: nil) ⇒ Histogram

Returns a 1-D Histogram built from self with shape fiber_shape + (A,), where A is the sample axis of length picked by axis.

Parameters:

  • edges (CArray, Array<Numeric>) —

    1-D ascending bin edges.

  • axis (Integer) (defaults to: -1) —

    sample axis.

  • include_max (Boolean) (defaults to: false) —

    fold last-edge equality into the last bin.

  • weights (CArray, nil) (defaults to: nil) —

    optional per-sample weights.

Returns:



449
450
451
452
453
454
455
456
457
458
459
460
461
# File 'lib/carray/histogram.rb', line 449

def histogram1d (edges:, axis: -1, include_max: false, weights: nil)
  ax = normalize_axis(axis, "histogram1d")

  new_shape = shape + [1]
  arr_with_channel = reshape(*new_shape)
  # `include_max` passes straight through: the Histogram constructor
  # normalizes a scalar bool to per-dim, and raises on a wrong-length Array
  # (= same path as histogram2d, no M=1 special-casing here).
  arr_with_channel.histogram(edges: [edges],
                             axis: [ax, new_shape.size - 1],
                             include_max: include_max,
                             weights: weights)
end

#histogram2d(edges:, axis: [-2, -1], include_max: false, weights: nil) ⇒ Histogram

Returns a 2-D joint Histogram built from self with shape fiber_shape + (A, 2).

Parameters:

  • edges (Array<CArray, Array<Numeric>>) —

    two edges arrays.

  • axis (Array(Integer, Integer)) (defaults to: [-2, -1]) —

    [sample, channel] axis pair.

  • include_max (Boolean, Array<Boolean>) (defaults to: false) —

    fold-max flag, per dimension.

  • weights (CArray, nil) (defaults to: nil) —

    optional per-sample weights.

Returns:

Raises:

  • (ArgumentError) —

    when edges is not a length-2 Array.

Raises:

  • (ArgumentError)


474
475
476
477
# File 'lib/carray/histogram.rb', line 474

def histogram2d (edges:, axis: [-2, -1], include_max: false, weights: nil)
  raise ArgumentError, "edges must be a list of 2" unless edges.is_a?(Array) && edges.size == 2
  histogram(edges: edges, axis: axis, include_max: include_max, weights: weights)
end

#imag ⇒ CArray

Returns the imaginary part of self. For a complex array the result is a mutable CAField view of the imaginary slot; writing to it updates self in place. For a real array the result is a fresh independent CArray filled with 0.

Returns:



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/carray/complex.rb', line 91

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)
                  end
    else
      @__imag__ = self.template { 0 }
    end
  end
  return @__imag__
end

#imag=(val) ⇒ Object

Sets the imaginary-part slot to val (complex arrays only).

Parameters:

  • val (CArray, Numeric) —

    value to broadcast.

Returns:

  • (Object) —

    val.

Raises:

  • (RuntimeError) —

    when self is not a complex array.



112
113
114
115
116
117
118
# File 'lib/carray/complex.rb', line 112

def imag= (val)
  if complex?
    imag[] = val
  else
    raise "not a complex array"
  end
end

#index(axis: 0) ⇒ CArray

Returns a writable int32 CArray holding the coordinate ramp [0, 1, ..., shape[axis] - 1] along axis, in an open broadcast shape: size shape[axis] on that axis and 1 on every other axis (e.g. for (d0, d1, d2), index(axis: 1) returns (1, d1, 1)).

The result broadcasts against self in element-wise ops without materialising the full shape. For the dense full-shape grid use index(axis: k).broadcast_to(*shape) or CArray.meshgrid.

Parameters:

  • axis (Integer) (defaults to: 0) —

    axis to vary (negative counts from the end).

Returns:

  • (CArray) —

    writable int32 CArray; size 1 on every axis except axis, which has size shape[axis].



19
20
21
22
23
24
# File 'lib/carray/methods/index.rb', line 19

def index (axis: 0)
  k = normalize_axis(axis, "index")
  oshape = Array.new(ndim, 1)
  oshape[k] = shape[k]
  CArray.int32(*oshape).seq!
end

#index2addr(*index) ⇒ Integer, CArray

Folds per-axis indices into flat row-major address(es), using self.shape. With all-Integer indices returns a single Integer; when any index is a CArray, returns a CArray of addresses whose shape follows the first non-scalar input (other non-scalar inputs must match that shape). Mask propagates from the inputs.

Parameters:

  • index (Array<Integer, CArray>) —

    one entry per axis.

Returns:

  • (Integer, CArray) —

    the flat address(es).

Raises:

  • (IndexError) —

    on an out-of-range index.

  • (ArgumentError) —

    on shape mismatch between non-scalar inputs.



100
# File 'yard-stubs/carray_access.rb', line 100

def index2addr(*index); end

#indices ⇒ Array<CArray> #indices({ |*ramps| ... }) {|*ramps| ... } ⇒ Object

Overloads:

  • #indices ⇒ Array<CArray>

    Returns an Array of ndim coordinate ramps, one per axis, each in the open broadcast shape of #index.

    Returns:

    • (Array<CArray>) —

      one open coordinate ramp per axis.

  • #indices({ |*ramps| ... }) {|*ramps| ... } ⇒ Object

    Yields the ndim open coordinate ramps as splat arguments.

    Yields:

    • (*ramps) —

      the per-axis open coordinate ramps.

    Returns:

    • (Object) —

      the block's return value.



34
35
36
37
# File 'lib/carray/methods/index.rb', line 34

def indices
  list = (0...ndim).map { |k| index(axis: k) }
  block_given? ? yield(*list) : list
end

#inherit_mask(*others) ⇒ self

Sets the mask of self to the logical OR of the current mask of self and the masks of each array in others. Mutates self.

Parameters:

  • others (Array<CArray>) —

    arrays whose mask states are OR-ed into self. Non-CArray arguments are ignored.

Returns:

  • (self)


163
# File 'yard-stubs/carray_mask.rb', line 163

def inherit_mask(*others); end

#inherit_mask_replace(*others) ⇒ self

Sets the mask of self to the logical OR of the masks of the arrays in others only (the current mask of self is discarded, in contrast to #inherit_mask). Mutates self.

Parameters:

  • others (Array<CArray>) —

    arrays whose mask states form the new mask of self.

Returns:

  • (self)


172
# File 'yard-stubs/carray_mask.rb', line 172

def inherit_mask_replace(*others); end

#initialize_copy(other) ⇒ self

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Implements dup / clone semantics: copies other's data_type, shape, mask, and element data into self. Result is an independent entity.

Note that for views, dup/clone produce a new view sharing the parent (Ruby shallow-copy semantics); use #copy when an independent owned array is required.

Parameters:

Returns:

  • (self)


52
# File 'yard-stubs/ca_obj_array.rb', line 52

def initialize_copy(other); end

#insert_axis(*positions, repeat: nil) ⇒ CArray

Returns a view of self with one or more new axes inserted, optionally repeating along them.

Each entry of positions names the source axis the new axis goes before. ndim (one past the last axis) appends at the end; negative positions count from the end. Repeating the same position inserts several axes before that axis, in argument order. Positions are in the source frame, so they do not shift as other axes are inserted (e.g. insert_axis(0, 1, 2) puts one axis before each of the first three source axes).

Each inserted axis takes one of two forms, chosen by its repeat value: 1 (or nil) for a plain size-1 axis, or an Integer N > 1 for a read-only bound repeat view. repeat is either a single value applied to every inserted axis, or an Array giving one value per position.

The everyday way to add an axis is the :_ indexer when the shape is known at the call site; insert_axis is for library code that builds the axis list programmatically.

Examples:

a = CArray.int32(3, 4).seq
a.insert_axis(0)                       # shape (1, 3, 4)
a.insert_axis(1, repeat: 5)            # shape (3, 5, 4)
a.insert_axis(0, 1, repeat: [1, 3])    # size-1 then bound

Parameters:

  • positions (Array<Integer>) —

    source-frame positions of the new axes.

  • repeat (Integer, Array, nil) (defaults to: nil) —

    repeat spec applied to each inserted axis.

Returns:

  • (CArray) —

    view with the new axes inserted.



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/carray/basics.rb', line 53

def insert_axis (*positions, repeat: nil)
    flat = positions.flatten
    if flat.empty?
      raise ArgumentError, "insert_axis: at least one position is required"
    end

    # No repeat: -> plain size-1 insertion.  The source-frame C primitive
    # handles normalization, range check and multiplicity directly.
    return __insert_axis_size1__(*flat) if repeat.nil?

    # Source frame: each position names the source axis the new axis goes
    # before.  Gaps live in [0, ndim] (ndim = append at end); negatives count
    # from the end gap.  Duplicates are allowed (several axes before one
    # source axis), kept in argument order.
    gaps = flat.map { |p| CArray.normalize_axis(p, ndim + 1, "insert_axis") }

    # One repeat value per position, in argument order.
    reps =
      case repeat
      when Array
        unless repeat.length == flat.length
          raise ArgumentError,
            "insert_axis: repeat array length (#{repeat.length}) " \
            "must match number of positions (#{flat.length})"
        end
        repeat
      else
        Array.new(flat.length, repeat)
      end

  # Validate each value.  A positive Integer only; nil is not a valid
  # per-axis repeat.
  reps.each do |r|
    unless r.is_a?(Integer)
      raise ArgumentError,
        "insert_axis: repeat must be a positive Integer, got #{r.inspect}"
    end
    raise ArgumentError, "insert_axis: repeat count must be >= 1" if r < 1
  end

  # Final output layout: stable order by (gap, argument index) keeps
  # same-gap axes in argument order; the k-th inserted axis lands at output
  # position gap + k.  This output position only drives broadcast_to; the
  # insertion itself always goes through the source-frame primitive.
  order = (0...flat.length).sort_by { |i| [gaps[i], i] }
  final = {}
  order.each_with_index { |i, k| final[i] = gaps[i] + k }

  inter = __insert_axis_size1__(*order.map { |i| gaps[i] })
  return inter unless order.any? { |i| reps[i] > 1 }

  shp = inter.shape
  order.each { |i| shp[final[i]] = reps[i] if reps[i] > 1 }
  inter.broadcast_to(*shp)
end

#insert_block(offset, bsize, &block) ⇒ CArray

Returns a new CArray obtained by inserting a block of size bsize (per axis) at offset, growing the array.

Per axis, offset accepts 0..shape[i] (equal to shape[i] appends at the end) and a negative value counts from the end; bsize[i] must be non-negative. Inserted cells are filled by the block's return value, or left at the type's default when no block is given. Preserves fixlen bytes and Face identity (built on the storage layout, re-wrapped via face_lift). The offset array is not mutated.

Parameters:

  • offset (Array<Integer>) —

    insertion offset per axis.

  • bsize (Array<Integer>) —

    block size per axis.

Yield Returns:

  • (Object) —

    fill value for the inserted cells.

Returns:

Raises:

  • (ArgumentError) —

    on ndim mismatch or out-of-range offset / size.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/carray/methods/insert_block.rb', line 24

def insert_block (offset, bsize, &block)
  if offset.size != ndim or bsize.size != ndim
    raise ArgumentError, "ndim mismatch"
  end
  offset = offset.dup           # normalize without mutating the caller's array
  newdim = shape
  grids = shape.map{|d| CArray.int32(d) }
  ndim.times do |i|
    offset[i] += shape[i] if offset[i] < 0
    if offset[i] < 0 or offset[i] > shape[i] or bsize[i] < 0
      raise ArgumentError, "invalid offset or size at axis #{i}"
    end
    if bsize[i] > 0
      newdim[i] += bsize[i]
    end
    grids[i][0...offset[i]].seq! if offset[i] > 0
    # offset == dim (append) leaves nothing on the upper side to shift.
    grids[i][offset[i]..-1].seq!(offset[i]+bsize[i]) if offset[i] < shape[i]
  end
  # Build at the storage layout (preserving bytes for fixlen / Face),
  # then re-wrap as the same Face.
  face_parent = self.face? ? self : nil
  src = self
  src = src.parent while src.face?
  dt    = src.data_type
  bytes = (dt == :fixlen) ? src.bytes : nil
  out = CArray.new(dt, newdim, bytes: bytes)
  if block_given?
    sel = out.true
    sel[*grids] = 0
    out[sel] = block.call
  end
  out[*grids] = src
  out = out.face_lift(face_parent) if face_parent
  return out
end

#inspect ⇒ String

Returns a human-readable description of self including class, data_type, shape, element and memory summaries, mask count, and a truncated data preview.

Returns:

  • (String)


218
219
220
# File 'lib/carray/inspect.rb', line 218

def inspect
  return CArray::Inspector.new(self).inspect_string
end

#int ⇒ Object

Alias of #int32. @return [CArray]



162
# File 'yard-stubs/carray_cast.rb', line 162

def int; end

#int16 ⇒ CArray

Returns an :int16 copy of self. Short-hand of to_type(:int16).

Returns:



106
# File 'yard-stubs/carray_cast.rb', line 106

def int16; end

#int32 ⇒ CArray

Returns an :int32 copy of self. Short-hand of to_type(:int32).

Returns:



114
# File 'yard-stubs/carray_cast.rb', line 114

def int32; end

#int64 ⇒ CArray

Returns an :int64 copy of self. Short-hand of to_type(:int64).

Returns:



122
# File 'yard-stubs/carray_cast.rb', line 122

def int64; end

#int8 ⇒ CArray

Returns an :int8 copy of self. Short-hand of to_type(:int8).

Returns:



98
# File 'yard-stubs/carray_cast.rb', line 98

def int8; end

#integer? ⇒ Boolean

Returns true if self is an integer type array (signed or unsigned, any width).

Returns:

  • (Boolean)


227
# File 'yard-stubs/carray_attribute.rb', line 227

def integer?; end

#intersection(other, sort: false) ⇒ CArray

Returns a 1-D CArray of the distinct values appearing in both self and other, in self's first-appearance order.

Value-based, sharing the distinctness of the discovery family (see #is_in); self and other are promoted to a common data type. Masked cells of either array do not participate. The result is always flat, like #unique, because the distinct values of a fiber vary in number.

Parameters:

  • other (CArray, Array, Range) —

    promoted with self.

  • sort (Boolean) (defaults to: false) —

    when true, return the values sorted ascending instead of in first-appearance order.

Returns:

  • (CArray) —

    1-D CArray of the common distinct values.



61
62
63
64
65
# File 'lib/carray/methods/is_in.rb', line 61

def intersection (other, sort: false)
  a, b = promote_value_set(other)
  r = a.__send__(:__intersection__, b)
  sort ? r.sort : r
end

#invert_mask ⇒ self

Flips the mask state of every element of self in place (masked ↔ not masked). Mutates self.

Returns:

  • (self)


154
# File 'yard-stubs/carray_mask.rb', line 154

def invert_mask; end

#is_in(values) ⇒ CArray

Returns a boolean CArray of the same shape as self, true at each cell whose value appears in the set values.

values is treated as a set, not as an operand to broadcast: it may be any shape (or an Array / Range) and is flattened to a single seen-set, so its shape need not match self. Only one argument is accepted; to test a few immediate values pass an Array (a.is_in([0, -1])).

When self and values have different numeric data types they are promoted to a common type first (the same promotion binops use, result_type), so membership is value-correct across data types (e.g. an int cell equals a float set element of the same value, and a fractional set element never truncates onto an int cell). Genuinely incompatible data types (e.g. numeric vs fixlen) raise.

Membership is value-based and shares the distinctness of the value-hash discovery family (#unique / #value_counts): numeric follows == with all NaN collapsed to one value and -0.0 == +0.0; CA_OBJECT follows Ruby hash / eql? with Float NaN collapsed; CA_FIXLEN follows byte equality.

Masked cells of values do not enter the set. Masked cells of self stay masked in the result (membership is unknown), so is_in propagates self's mask like an element-wise comparison.

For a per-fiber "does this fiber contain any of these values" reduction, compose with #any: a.is_in(values).any(axis: k).

Between two time arrays the question is about instants, not ticks: values is reconciled into self's unit first, so a :D array and an :h array match on the instants they share. The same holds for the set operations below, whose results come back as self's own type.

Parameters:

  • values (CArray, Array, Range) —

    the set to test membership against. Promoted with self to a common data type.

Returns:

  • (CArray) —

    boolean CArray of the same shape as self.



42
43
44
45
# File 'lib/carray/methods/is_in.rb', line 42

def is_in (values)
  a, b = promote_value_set(values)
  a.__send__(:__is_in__, b)
end

#is_masked ⇒ CArray

Returns a new boolean CArray of the same shape as self, with 1 at masked positions and 0 elsewhere.

Returns:



56
# File 'yard-stubs/carray_mask.rb', line 56

def is_masked; end

#is_mode(axis: nil) ⇒ CArray

Returns a shape-preserving boolean CArray, true at every cell that holds a modal value — a value whose occurrence count equals the maximum count. This is the first-class primitive of the mode family: rather than returning the mode value (whose count is data-dependent when there are ties), it marks every occurrence of every most-frequent value, so ties are never silently broken.

CA_INT32([1, 1, 2, 2, 3]).is_mode  # => [1, 1, 1, 1, 0]  (1 and 2 tie)

With axis: nil the frequency is over the whole array; with axis: k it is per fiber along axis k, independently. The result is always the input shape, so — unlike returning the mode value — the per-axis form has no ragged-length problem. Select the modal cells with a[a.is_mode] / a[a.is_mode(axis: k)] (the #mask_duplicates idiom); reduce further with .min / .unique.

Mode is only meaningful for discrete or binned data: raw float is almost all unique, so is_mode would mark just the single lowest cell (count 1). Bin first (bin / histogram / categorize).

Masked cells do not participate and are marked false. An empty or all-masked fiber marks every cell false (mode has no identity; it never raises). Numeric distinctness follows the discovery family (all NaN collapse to one value, -0.0 == +0.0); CA_OBJECT / CA_FIXLEN follow Ruby eql? / hash.

Parameters:

  • axis (Integer, nil) (defaults to: nil) —

    axis to take the mode along; nil uses the whole array.

Returns:

  • (CArray) —

    boolean CArray of self.shape.



35
36
37
38
39
40
41
42
43
44
# File 'lib/carray/methods/mode.rb', line 35

def is_mode (axis: nil)
  # Per-fiber two-pass frequency table (C __is_mode__), one lane per data type
  # family (numeric widen / NaN collapse, object rb_hash + rb_eql, fixlen
  # byte-hash + memcmp). Ties are all marked; masked cells stay false.
  if axis.nil?
    flatten.send(:__is_mode__, 0).reshape(*shape)
  else
    __is_mode__(normalize_axis(axis, "is_mode"))
  end
end

#is_not_masked ⇒ CArray

Returns a new boolean CArray of the same shape as self, with 1 at not-masked positions and 0 elsewhere.

Returns:



62
# File 'yard-stubs/carray_mask.rb', line 62

def is_not_masked; end

#is_real ⇒ CArray?

Returns an element-wise boolean CArray marking cells whose imaginary part is zero (all-true for real numeric arrays, nil for non-numeric arrays).

Returns:



140
141
142
143
144
145
146
147
148
# File 'lib/carray/complex.rb', line 140

def is_real
  if complex?
    imag.eq(0)
  elsif numeric?
    self.true
  else
    nil
  end
end

#join(sep = nil) ⇒ Object #join(sep = "", axis:, keep_axis: false) ⇒ CArray, String

Note:

The 2.x multi-separator form a.join("\n", ",") was removed in 3.0; use the axis form and chain, e.g. a.join(",", axis: 1).join("\n").

Examples:

Flat form

a = CArray.object(3, 3).seq("a", :succ)
a.join            # => "abcdefghi"
a.join(",")       # => "a,b,c,d,e,f,g,h,i"

Per-axis form

a = CArray.int32(3, 3).seq
a.join(" ", axis: 1)               # → CArray["0 1 2", "3 4 5", "6 7 8"]
a.join(" ", axis: 1).join("\n")    # => "0 1 2\n3 4 5\n6 7 8"

Overloads:

  • #join(sep = nil) ⇒ Object

    Flat form. Stringifies and concatenates every element of self (as if to_a.flatten.join(sep)). Returns a String.

  • #join(sep = "", axis:, keep_axis: false) ⇒ CArray, String

    Per-axis form. Reduces axis into strings, one per fiber along that axis, and returns the result as a CArray with axis removed (or set to 1 when keep_axis: true). Composable — call join again on the result to collapse another axis or fold to a String.

    For a 1-D self, the axis form fully reduces and returns the String directly (matching the flat form and the reduction convention).

    Parameters:

    • sep (String) (defaults to: "") —

      separator between elements along the axis.

    • axis (Integer) —

      axis to reduce (negative allowed).

    • keep_axis (Boolean) (defaults to: false) —

      keep the reduced axis as length 1.

    Returns:

    • (CArray, String) —

      a CArray of strings, or a String when self is 1-D.



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/carray/methods/join.rb', line 36

def join (*argv, axis: nil, keep_axis: false)
  if argv.size > 1
    raise ArgumentError,
          "join accepts at most one positional separator " \
          "(the 2.x multi-separator form was removed in 3.0; " \
          "use axis: for per-axis join and chain)"
  end
  sep = argv.first  # nil or String

  if axis.nil?
    return sep.nil? ? to_a.join : to_a.join(sep)
  end

  ax = Integer(axis)
  ax += ndim if ax < 0
  if ax < 0 || ax >= ndim
    raise ArgumentError,
          "axis #{axis.inspect} out of range for ndim=#{ndim}"
  end

  sep_str = sep || ""

  # Bring `ax` to the innermost position so we can iterate fibers as
  # rows of a 2-D reshape.  transpose returns a view; reshape may
  # materialize on non-contig, which is fine for this formatting op.
  if ax == ndim - 1
    t = self
  else
    order = (0...ndim).to_a
    order << order.delete_at(ax)
    t = transpose(*order)
  end
  inner = t.shape[-1]
  outer_n = t.elements / inner  # 1 when ndim == 1
  flat = t.reshape(outer_n, inner)

  strings = Array.new(outer_n) { |i| flat[i, nil].to_a.join(sep_str) }

  if ndim == 1
    # Full reduction: return the String directly, or a length-1
    # CArray when keep_axis was requested.
    return keep_axis ? CA_OBJECT([strings.first]) : strings.first
  end

  result_shape = shape.dup
  if keep_axis
    result_shape[ax] = 1
  else
    result_shape.delete_at(ax)
  end

  CA_OBJECT(strings).reshape(*result_shape)
end

#last(axis: nil, keep_axis: false) ⇒ Object, CArray

Returns the last valid (unmasked) value along axis (the backward counterpart of #first).

Parameters:

  • axis (Integer, Array<Integer>, nil) (defaults to: nil) —

    reduce axis / axes; nil reduces the whole array to a scalar.

  • keep_axis (Boolean) (defaults to: false) —

    keep the reduced axis as a size-1 axis.

Returns:

  • (Object, CArray) —

    a scalar for a full reduce (UNDEF if no valid cell), otherwise a reduced CArray.



148
# File 'yard-stubs/carray_mask.rb', line 148

def last(axis: nil, keep_axis: false); end

#lazy ⇒ CALazyMarker

Returns a CALazyMarker view wrapping self. Subsequent element-wise ops on the marker (m.sqrt, m + 1, ...) build a lazy expression tree; call .to_ca on the result to materialise. The marker is transient — a Ruby reference can re-consume it (m = a.lazy; m.sqrt + m.sin) without side effects on self.

Returns:



21
# File 'yard-stubs/carray_lazy.rb', line 21

def lazy; end

#length ⇒ Integer

Deprecated.

Returns:

  • (Integer)


72
# File 'yard-stubs/carray_attribute.rb', line 72

def length; end

#linear_fetch(addr, axis: nil) ⇒ Float, CArray

Returns the value of self (treated as a coordinate axis) at the fractional position addr, interpolating linearly between the two bracketing samples. The inverse of #linear_section.

self is coerced to :float64 if it is not already. When axis: nil, self is flattened to 1-D first.

Out-of-range addr returns NaN.

Because this half of the pair returns a value rather than a position, a Face axis gets its Face back: CATime#linear_fetch / CATimedelta#linear_fetch return a time on the axis's own unit (rounded to that grid, UNDEF out of range) instead of raw ticks.

Parameters:

  • addr (Float, CArray) —

    fractional position(s) into self.

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

Returns:

See Also:



309
# File 'yard-stubs/carray_order.rb', line 309

def linear_fetch(addr, axis: nil); end

#linear_section(val, axis: nil, method: :binary) ⇒ Float, CArray

Returns the fractional position of val within self (treated as a coordinate axis), interpolating linearly between the two bracketing samples. The integer part of the returned address is the index of the lower bracket, the fractional part is the interpolation weight toward the next sample. Out-of-range val returns NaN.

self is coerced to :float64 if it is not already. When axis: nil, self is flattened to 1-D first.

method: selects the search backend:

  • :binary (default) — bisection. O(log N) per query. Assumes an ascending (sorted) axis; returns NaN on descending data.
  • :linear — sign-product scan. O(N) per query but handles both ascending and descending monotone axes correctly.

See #linear_fetch for the inverse operation (fractional address to interpolated value).

Parameters:

  • val (Numeric, CArray)
  • axis (Integer, nil) (defaults to: nil)
  • method (Symbol) (defaults to: :binary) —

    :binary or :linear.

Returns:

Raises:

  • (ArgumentError) —

    when method: is neither :binary nor :linear.



289
# File 'yard-stubs/carray_order.rb', line 289

def linear_section(val, axis: nil, method: :binary); end

#load_binary(io) ⇒ self

Reads ca_length(self) bytes from io and overwrites the element data of self in row-major order. io may be a String of the exact size, or any object responding to read(n, buf = nil).

Parameters:

  • io (String, IO, #read)

Returns:

  • (self)

Raises:

  • (RuntimeError) —

    on short read or size mismatch.

  • (CArray::DataTypeError) —

    if self.data_type is :object.



73
# File 'yard-stubs/carray_conversion.rb', line 73

def load_binary(io); end

#locate_addr(ref) ⇒ CArray

Returns, for each element of self, the flat address into ref where the value first occurs, or UNDEF where it is not present. Builds a value-to-first-address map from ref in one pass (an open-addressing hash, the same substrate as #unique / #value_counts), then probes each element of self; no sort, peak memory O(distinct ref values).

The return is ref's flat address (0 to ref.elements - 1), so a multi-dimensional ref still yields a self-shaped result of flat addresses; downstream reads (ref[addr], model_var[addr], ...) apply it as a flat gather.

Works on numeric, CA_OBJECT, and CA_FIXLEN values, matching the value-hash discovery family: numeric follows == with all NaN collapsed to one value and -0.0 == +0.0; object follows Ruby hash / eql? with Float NaN collapsed; fixlen follows byte equality. When ref holds duplicate values the returned address is the earliest (appearance-order) occurrence. Masked cells of ref do not enter the map but still occupy their flat address; masked cells of self are UNDEF in the result.

Typical use is time-axis lookup: compute the address once against a reference axis, then reuse it to gather from many ref-shaped variables without repeating the lookup.

Implemented in Ruby (see lib/carray/methods/locate_addr.rb) over the __locate_addr__ hash-lane kernel; self is coerced to ref's data type within the same family (cross-family raises).

Parameters:

  • ref (CArray) —

    reference values to match against; any shape (used as flat).

Returns:

  • (CArray) —

    :int64 flat addresses into ref, same shape as self; unmatched cells are masked.



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/carray/methods/locate_addr.rb', line 6

def locate_addr (ref)
  ref = ref.to_ca unless ref.is_a?(CArray)
  # Put self and ref in a common lane via the single-source promotion rule
  # (CArray.result_type), so a fractional query against an int ref is compared
  # at the promoted type instead of truncating (1.5 no longer matches 1).
  # to_type is elementwise and order-preserving, so the addresses stay valid
  # indices into ref. result_type raises for cross-family input.
  t = CArray.result_type(self, ref)
  q = (data_type     == t) ? self : to_type(t)
  r = (ref.data_type == t) ? ref  : ref.to_type(t)
  q.send(:__locate_addr__, r)
end

#locate_nearest_addr(ref, direction: :round, tolerance: nil) ⇒ CArray

Returns, for each element of self, the flat address into ref of the nearest reference value. Continuous sibling of #locate_addr; uses linear_section + rounding for non-exact matching against a sorted ref.

Out-of-range cells of self (outside ref's span) mask through the pipeline: linear_section returns NaN, mask_invalid propagates that as UNDEF, rounding and the int64 cast carry the mask, and project scatters it into the final positions. mask_invalid runs before rounding because CArray#round maps NaN to 0 and would otherwise silently match ref[0].

tolerance: (default nil) sets a maximum accepted absolute distance between self[i] and its matched ref value. When |ref[addr] - self[i]| > tolerance, the result cell is masked. Use for accuracy-controlled matching (e.g. "an observation snaps to a time step only if within N seconds").

Implemented in Ruby (see lib/carray/methods/locate_addr.rb).

Parameters:

  • ref (CArray) —

    1-D sorted reference grid to match against.

  • direction (Symbol) (defaults to: :round) —

    :round, :floor, or :ceil — rounding applied to the fractional position.

  • tolerance (Numeric, nil) (defaults to: nil) —

    maximum accepted |self - ref| distance; cells beyond this are masked. nil disables the check.

Returns:

  • (CArray) —

    :int64 flat addresses into ref, same shape as self; out-of-range and beyond-tolerance cells are masked.

Raises:

  • (ArgumentError) —

    when direction is not one of the accepted symbols.



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
# File 'yard-stubs/carray_order.rb', line 257

def locate_nearest_addr (ref, direction: :round, tolerance: nil)
  unless [:round, :floor, :ceil].include?(direction)
    raise ArgumentError,
          "locate_nearest_addr: direction must be :round / :floor / " \
          ":ceil (got #{direction.inspect})"
  end
  ri = ref.sort_addr
  rs = ref[ri]
  sec = rs.linear_section(self)
  unless sec.is_a?(CArray)
    # A single-element (scalar-like) self makes linear_section collapse to
    # its scalar-query path, which returns a bare Float (or nil when out of
    # range) instead of a CArray.  Rebuild a self-shaped float64 CArray so
    # the mask_invalid -> direction -> project pipeline stays array-valued
    # and the returned addr array matches self's shape.
    fill = CArray.float64(*shape)
    fill[] = sec.nil? ? UNDEF : sec
    sec = fill
  end
  masked = sec.mask_invalid
  si = case direction
       when :round then masked.round
       when :floor then masked.floor
       when :ceil  then masked.ceil
       end.int64
  idx = ri.project(si)
  if tolerance
    dist = (ref.project(idx) - self).abs
    idx[dist > tolerance] = UNDEF
  end
  idx
end

#lookup(table, fill_value = nil, lfill: nil, ufill: nil) ⇒ CArray

Returns values gathered from table at the indices given by self. Equivalent to table.project(self, lfill, ufill) with the receiver / first argument swapped so the index reads as the subject. fill_value is sugar for symmetric dual-fill; lfill / ufill override per side (UNDEF or nil masks that end), following the project vocabulary.

Parameters:

  • table (CArray) —

    value table indexed by self.

  • fill_value (Object, nil) (defaults to: nil) —

    symmetric fill for below- and above-range indices.

  • lfill (Object, nil) (defaults to: nil) —

    override for below-range fill.

  • ufill (Object, nil) (defaults to: nil) —

    override for above-range fill.

Returns:

  • (CArray) —

    gathered values with the shape of self.



204
205
206
207
208
# File 'lib/carray/basics.rb', line 204

def lookup(table, fill_value=nil, lfill: nil, ufill: nil)
  lfill = fill_value if lfill.nil?
  ufill = fill_value if ufill.nil?
  table.project(self, lfill, ufill)
end

#map! {|elem| ... } ⇒ self

Replaces each element of self with the block's return value. Mutates self.

Yield Parameters:

  • elem (Object)

Yield Returns:

  • (Object) —

    new value for the cell.

Returns:

  • (self)


60
# File 'yard-stubs/carray_loop.rb', line 60

def map!; end

#map_addr! {|addr| ... } ⇒ self

Replaces each element of self with the block's return value; the block receives the flat address rather than the current value. Mutates self.

Yield Parameters:

  • addr (Integer)

Yield Returns:

  • (Object)

Returns:

  • (self)


69
# File 'yard-stubs/carray_loop.rb', line 69

def map_addr!; end

#map_index! {|idx| ... } ⇒ self

Replaces each element of self with the block's return value; the block receives the multi-dimensional index components (|i, j, ...|, one Integer per axis; use |*idx| to collect them) rather than the current value. Mutates self.

Yield Parameters:

  • idx (Integer) —

    one Integer per axis.

Yield Returns:

  • (Object)

Returns:

  • (self)


79
# File 'yard-stubs/carray_loop.rb', line 79

def map_index!; end

#map_slab(axis:, data_type: nil) ⇒ CArray

Returns a new CArray built by replacing each slab of self with the block's result. The block receives the slab view and must return a value of the same shape as the slab (a CArray or scalar); the results are written into the output at the same positions.

Parameters:

  • axis (Integer, Array<Integer>, nil) —

    the slab axis or axes.

  • data_type (Symbol, Integer, Class, nil) (defaults to: nil) —

    output data type (defaults to self's data type).

Returns:

Raises:

  • (ArgumentError) —

    when the block result's shape does not match the slab.

See Also:



37
# File 'yard-stubs/carray_slab.rb', line 37

def map_slab(axis:, data_type: nil); end

#map_with_addr! {|elem, addr| ... } ⇒ self

Replaces each element of self with the block's return value; the block receives (element, flat-address). Mutates self.

Yield Parameters:

  • elem (Object)
  • addr (Integer)

Yield Returns:

  • (Object)

Returns:

  • (self)


88
# File 'yard-stubs/carray_loop.rb', line 88

def map_with_addr!; end

#map_with_index! {|elem, idx| ... } ⇒ self

Replaces each element of self with the block's return value; the block receives the element followed by its multi-dim index components (|elem, i, j, ...|; use |elem, *idx| to collect the index). Mutates self.

Yield Parameters:

  • elem (Object)
  • idx (Integer) —

    one Integer per axis.

Yield Returns:

  • (Object)

Returns:

  • (self)


99
# File 'yard-stubs/carray_loop.rb', line 99

def map_with_index!; end

#marshal_dump ⇒ Array

Returns the Marshal payload for self. Virtual / wrapped arrays are copied first so the payload always describes an owning array.

Returns:



518
519
520
521
522
523
524
525
526
527
528
# File 'lib/carray/serialize.rb', line 518

def marshal_dump ()
  target = (self.class != CArray and self.class != CScalar) ? self.copy : self
  if target.data_type == :object
    ["object",
     target.shape,
     target.value.to_a,
     (target.has_mask? ? target.mask.to_a : nil)]
  else
    ["portable", CArray.dump(target)]
  end
end

#marshal_load(data) ⇒ void

This method returns an undefined value.

Reconstitutes self from a Marshal payload produced by #marshal_dump.

Parameters:

  • data (Array) —

    Marshal payload.



535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
# File 'lib/carray/serialize.rb', line 535

def marshal_load (data)
  tag, *rest = data
  case tag
  when "object"
    shape, values, mask = rest
    ca = CArray.object(*shape)
    ca[] = values
    if mask
      ca.mask = 0
      ca.mask[] = mask
    end
    initialize_copy(ca)
  when "portable"
    ca = CArray.load(StringIO.new(rest[0]))
    initialize_copy(ca)
  else
    raise TypeError, "unrecognised CArray Marshal payload"
  end
end

#mask ⇒ CArray, Integer

Returns a new boolean view of the mask state of self. Each element is 1 where self is masked and 0 where it is not. The returned view itself cannot carry a mask.

Returns 0 (Integer) if self has no mask array attached.

Returns:



40
# File 'yard-stubs/carray_mask.rb', line 40

def mask; end

#mask=(new_mask) ⇒ Object

Sets the mask array of self to new_mask. Allocates the mask array first if self does not yet have one. Cannot be called on a value array or a mask array.

Parameters:

  • new_mask (CArray, Boolean, Integer) —

    mask values. A non-CArray value is broadcast and stored elementwise; a CArray of any type is coerced to boolean.

Returns:

  • (Object) —

    new_mask.



50
# File 'yard-stubs/carray_mask.rb', line 50

def mask=(new_mask); end

#mask_array? ⇒ Boolean

Returns true if self is itself a mask array. (Not the same as "a masked array"; for that see #has_mask?.)

Returns:

  • (Boolean)


185
# File 'yard-stubs/carray_attribute.rb', line 185

def mask_array?; end

#mask_duplicates(axis: nil) ⇒ CArray

Returns a shape-preserving copy of self with the mask set at every cell whose value duplicates an earlier-seen one; the first occurrence is kept.

With axis: nil duplicates are detected in flatten (row-major) order across the whole array. With axis: k duplicates are detected per-fiber along axis k, independently for each fiber. Marking duplicates (not compressing) is what makes the per-axis form expressible: fibers may hold different numbers of distinct values, so a compressed result would be ragged.

Distinctness matches the value-hash discovery family. Numeric: == with all NaN collapsed to one value (so the second and later NaN are duplicates) and -0.0 == +0.0. CA_OBJECT / CA_FIXLEN: Ruby eql? / hash (distinct NaN objects stay distinct). Masked input cells stay masked and do not participate in duplicate judging. Both axis: nil and axis: k work.

Parameters:

  • axis (Integer, nil) (defaults to: nil) —

    axis to detect duplicates along; nil uses flatten order.

Returns:

  • (CArray) —

    shape-preserving copy of self with duplicates masked.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/carray/methods/mask_duplicates.rb', line 26

def mask_duplicates (axis: nil)
  dup =
    if axis.nil?
      # One seen-set over the flattened array, then restore shape.
      flatten.send(:__mask_duplicates__, 0).reshape(*shape)
    else
      # Per-fiber single-pass seen-set hash (C __mask_duplicates__): one lane
      # per data type family (integer widen, float bitwise key with NaN collapse,
      # object rb_hash + rb_eql, fixlen byte-hash + memcmp, boolean via the
      # uint8 lane). O(distinct) memory, no sort/gather/scatter buffers.
      __mask_duplicates__(normalize_axis(axis, "mask_duplicates"))
    end
  mask_where(dup)
end

#mask_eq(v) ⇒ CArray

Returns a copy of self with every element equal to v masked. In-place equivalent: ca[:eq, v] = UNDEF.

Replaces the removed maskout(v) from 2.x.

Parameters:

  • v (Object) —

    value to mask. Cast to self.data_type.

Returns:



207
# File 'yard-stubs/carray_mask.rb', line 207

def mask_eq(v); end

#mask_invalid ⇒ CArray

Returns a copy of self with every NaN or Inf element masked. For integer or boolean arrays this is a plain copy (no element is invalid by is_finite.not semantics). In-place equivalent: ca[:is_invalid] = UNDEF.

Returns:



215
# File 'yard-stubs/carray_mask.rb', line 215

def mask_invalid; end

#mask_where(key, *args) ⇒ CArray

Returns a copy of self with elements matching the given indexer predicate masked. Mirrors the indexer key set:

ca.mask_where(:lt, v)      # same as: copy then ca[:lt, v] = UNDEF
ca.mask_where(:is_invalid) # same as: copy then ca[:is_invalid] = UNDEF
ca.mask_where(bool_array)  # same as: copy then ca[bool_array] = UNDEF

At least one argument is required. For in-place mutation use the indexer idiom directly: ca[key, *args] = UNDEF.

Parameters:

  • key (Symbol, CArray) —

    indexer key or boolean condition array.

  • args (Array) —

    additional arguments required by the predicate.

Returns:



232
# File 'yard-stubs/carray_mask.rb', line 232

def mask_where(*args); end

#median(axis: nil, min_count: 0, fill_value: nil, keep_axis: false) ⇒ Float, ...

Returns the median of self along axis (or over all elements when axis is nil).

Numeric arrays return a Float; CA_OBJECT arrays return the result of Ruby + / / on the stored objects. Fixlen arrays raise, since no numeric midpoint is defined.

Masked cells are excluded. Per-axis, each fiber uses only its own present values; a fully masked fiber reduces to UNDEF. If the count of not-masked cells (per fiber, or over all elements in the flat form) is below min_count, that cell is fill_value (or UNDEF when fill_value is nil).

With keep_axis: true, the reduced axis is retained with length 1 rather than dropped.

Parameters:

  • axis (Integer, nil) (defaults to: nil)
  • min_count (Integer) (defaults to: 0) —

    minimum not-masked count required.

  • fill_value (Object, nil) (defaults to: nil) —

    replacement when the not-masked count is below min_count.

  • keep_axis (Boolean) (defaults to: false)

Returns:

Raises:



32
# File 'yard-stubs/carray_median_percentile.rb', line 32

def median(*); end

#meld(*others, axis: 0) ⇒ CAMeld

Returns a CAMeld view of [self, *others] welded along axis. Instance form of meld; non-destructive, see the class method for full semantics.

Parameters:

  • others (Array<CArray>) —

    additional pieces.

  • axis (Integer) (defaults to: 0) —

    existing axis to extend.

Returns:

Raises:

  • (ArgumentError) —

    when no others are given.

Raises:

  • (ArgumentError)


123
124
125
126
# File 'lib/carray/stack.rb', line 123

def meld (*others, axis: 0)
  raise ArgumentError, "meld: at least one other array required" if others.empty?
  CArray.meld(self, *others, axis: axis)
end

#members ⇒ Array<Symbol>

Returns the ordered list of member names for self.data_class. Only valid when self carries a data_class (e.g. a CARecord).

Returns:

Raises:

  • (RuntimeError) —

    if self has no data_class.



72
# File 'yard-stubs/carray_core.rb', line 72

def members; end

#mod(other) ⇒ CArray

Alias of #%.

Parameters:

  • other (CArray, Numeric) —

    divisor.

Returns:



68
# File 'yard-stubs/carray_math.rb', line 68

def mod(other); end

#mod!(other) ⇒ self

Replaces self with the remainder in place, keeping self's data_type.

Parameters:

  • other (CArray, Numeric) —

    divisor.

Returns:

  • (self)


75
# File 'yard-stubs/carray_math.rb', line 75

def mod!(other); end

#mode(axis: nil) ⇒ CArray+

Returns the distinct modal values — the most frequent value(s), ascending. All values that tie for the highest count are returned (matching pandas Series.mode), because #is_mode does not break ties; mode is the value-form consumer of that primitive, read straight from the frequency table.

With axis: nil the result is a 1-D CArray of the distinct modal values over the whole array (empty when all-masked).

With axis: k the per-fiber mode counts are ragged, so — like per-axis quantile — the result is an Array of reduced CArrays. Element j holds each fiber's j-th smallest modal value, masked where a fiber has fewer than j + 1 modes; the Array length is the widest fiber's mode count. So mode(axis: k)[0] is the smallest mode of each fiber (a plain reduced CArray). To get the rectangular mask-padded form, stack them: CArray.stack(a.mode(axis: k), axis: k). An all-masked array yields an empty Array.

Only meaningful for discrete / binned data: raw float is almost all unique, so every value is modal and the per-axis Array grows to the fiber length. Bin first. Same NaN / mask semantics as #is_mode.

Parameters:

  • axis (Integer, nil) (defaults to: nil) —

    axis to take the mode along; nil uses the whole array.

Returns:

  • (CArray, Array<CArray>) —

    1-D CArray (flat) or an Array of reduced CArrays, one per mode rank (per-axis).



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/carray/methods/mode.rb', line 73

def mode (axis: nil)
  return __mode_flat if axis.nil?
  k = normalize_axis(axis, "mode")

  # Numeric: the C frequency-table kernel emits the ragged Array<CArray>
  # directly (reduced CArrays, self.shape with axis k dropped). A 1-D input
  # reduces to length-1 CArrays, unwrapped to scalars like flat quantile.
  unless data_type == CA_OBJECT || data_type == CA_FIXLEN
    cols = __mode_axis__(k)
    return ndim == 1 ? cols.map { |col| col[0] } : cols
  end

  # Object / fixlen (rare): per-fiber Ruby path, reusing the flat mode as the
  # single source of what counts as a mode. Move axis k to the innermost
  # position and fold the rest to one outer axis, so each row is a fiber.
  perm = (0...ndim).to_a
  perm.delete(k)
  perm << k
  a2    = (ndim == 1) ? self : transpose(*perm).copy   # (outer..., L)
  outer = a2.shape[0...-1]
  m     = outer.empty? ? 1 : outer.inject(:*)
  flat2 = a2.reshape(m, a2.shape[-1])
  lists = Array.new(m) { |r| flat2[r, nil].__send__(:__mode_flat).to_a }

  # K = widest fiber's mode count. Emit K reduced CArrays (like quantile's
  # per-axis Array<CArray>): slot j holds each fiber's j-th smallest mode,
  # masked where a fiber has fewer than j+1 modes. Stack them to get the
  # rectangular mask-padded form: CArray.stack(result, axis: k).
  kk = lists.map(&:size).max || 0
  (0...kk).map do |j|
    # Take the column shape from self rather than building it from data_type:
    # it carries the element width a fixlen array needs, and it keeps a Face
    # (a time array), whose cells then accept the surface values in `lists`.
    col = flat2[nil, 0].copy
    col[] = UNDEF
    m.times { |r| col[r] = lists[r][j] if j < lists[r].size }
    outer.empty? ? col[0] : col.reshape(*outer)
  end
end

#ndim ⇒ Integer

Returns the number of dimensions of self.

Returns:

  • (Integer)


36
# File 'yard-stubs/carray_attribute.rb', line 36

def ndim; end

#none(skip_masked: true, **opts) ⇒ Boolean, CArray

Whether no cell is true.

With skip_masked: true (the default) masked cells are simply ignored and the result is always true / false. With skip_masked: false the fold is three-valued: the result is UNDEF when a masked cell could change it, matching the element-wise Kleene semantics of | / &.

Parameters:

  • skip_masked (Boolean) (defaults to: true) —

    ignore masked cells, or fold them three-valued.

  • opts (Hash) —

    forwarded to the underlying reduction (axis:, keep_axis:, ...).

Returns:

  • (Boolean, CArray) —

    a scalar, or an array when an axis is given.



70
71
72
73
74
75
# File 'lib/carray/boolean_reduce.rb', line 70

def none (skip_masked: true, **opts)
  return __none_skipna__(**opts) if skip_masked
  # none = not any (Kleene): not(true)=false, not(false)=true, not(UNDEF)=UNDEF
  r = __kleene_fold(:any, opts)
  r.is_a?(CArray) ? r.not : (r.equal?(UNDEF) ? UNDEF : !r)
end

#normalize_axes(axes, name = nil) ⇒ Array<Integer>

Returns an Array of canonical non-negative axis indices in input order. Accepts:

  • nil ⇒ all axes [0, 1, ..., ndim-1]
  • Integer ⇒ [normalize_axis(axis)]
  • Array<Integer> ⇒ each normalized, preserving input order

Parameters:

  • axes (Integer, Array<Integer>, nil)
  • name (String, nil) (defaults to: nil) —

    argument name for error messages.

Returns:

Raises:

  • (ArgumentError) —

    on out-of-range or duplicate axes.



31
# File 'yard-stubs/carray_utils.rb', line 31

def normalize_axes(axes, name = nil); end

#normalize_axis(axis, name = nil) ⇒ Integer

Returns the canonical non-negative integer axis index in [0, ndim) for self. Accepts Python-style negative indices (-1 ⇒ ndim-1).

Parameters:

  • axis (Integer) —

    axis index, possibly negative.

  • name (String, nil) (defaults to: nil) —

    argument name to embed in error messages (e.g. "axis", "at").

Returns:

  • (Integer)

Raises:

  • (ArgumentError) —

    if axis is outside [-ndim, ndim).



17
# File 'yard-stubs/carray_utils.rb', line 17

def normalize_axis(axis, name = nil); end

#normalize_index(idx) ⇒ Array

Returns a canonical form of the index array idx classified against self's shape (scalars normalised, nil for whole axes, [start, count, step] for blocks). Used to inspect how an index resolves.

Parameters:

  • idx (Array) —

    the raw index spec.

Returns:

  • (Array) —

    the normalised per-axis index.



128
# File 'yard-stubs/carray_access.rb', line 128

def normalize_index(idx); end

#numeric? ⇒ Boolean

Returns true if self is a numeric type array (any integer, float, or complex type).

Returns:

  • (Boolean)


221
# File 'yard-stubs/carray_attribute.rb', line 221

def numeric?; end

#nunique(axis: nil, keep_axis: false) ⇒ Integer, CArray

Counts the distinct values of self. This is the scalar-reduction member of the value-hash discovery family (#unique, #mask_duplicates, #value_counts): where #unique compresses and #value_counts tabulates, nunique just counts.

With axis: nil (default) it counts distinct values across the whole array and returns an Integer. With axis: k it counts per fiber along axis k, returning a reduced CA_INT64 CArray (shape = self.shape with axis k removed; keep_axis: true keeps it as a length-1 axis). The shape rule matches other per-axis reductions such as sum(axis:).

The distinct count has identity 0: an empty array, an all-masked fiber, or a zero-length axis counts 0 (not UNDEF) — an empty set has zero distinct values. Masked cells do not participate.

Numeric distinctness follows == with the family's two float special cases: all NaN collapse to a single value and -0.0 / +0.0 are the same value. For CA_OBJECT / CA_FIXLEN distinctness follows Ruby eql? / hash (which, unlike numeric, does not collapse distinct NaN objects).

Parameters:

  • axis (Integer, nil) (defaults to: nil) —

    axis to count along; nil counts over the whole array.

  • keep_axis (Boolean) (defaults to: false) —

    when axis is given, keep the reduced axis as a length-1 axis instead of dropping it.

Returns:

  • (Integer, CArray) —

    Integer for axis: nil, otherwise a reduced CA_INT64 CArray.



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/carray/methods/nunique.rb', line 32

def nunique (axis: nil, keep_axis: false)
  # Per-fiber single-pass seen-set hash (C __nunique__), one lane per data type
  # family (numeric widen / NaN collapse, object rb_hash + rb_eql, fixlen
  # byte-hash + memcmp). Masked cells are skipped; the accumulator is a no-op
  # (the distinct count is the interned-key count).
  if axis.nil?
    # Whole-array distinct count: flatten to 1-D and reduce its only axis,
    # then read the single reduced cell as an Integer.
    flatten.send(:__nunique__, 0, false)[0]
  else
    __nunique__(normalize_axis(axis, "nunique"), keep_axis)
  end
end

#obj_type ⇒ Integer

Returns the object-type integer of self (e.g. CA_OBJ_ARRAY, CA_OBJ_BLOCK).

Rarely needed in user code; the same information is available from self.class.

Returns:

  • (Integer)


15
# File 'yard-stubs/carray_attribute.rb', line 15

def obj_type; end

#object ⇒ CArray

Returns an :object copy of self. Short-hand of to_type(:object).

Returns:



146
# File 'yard-stubs/carray_cast.rb', line 146

def object; end

#object? ⇒ Boolean

Returns true if self is an object type array (data_type == :object).

Returns:

  • (Boolean)


243
# File 'yard-stubs/carray_attribute.rb', line 243

def object?; end

#order(axis: nil, descending: false, method: :ordinal) ⇒ CArray

Returns each cell's rank among the other cells along axis (0 = smallest). When axis is omitted, self is flattened first (global rank). Sugar over rank_index (built on the same sort machinery as sort_index); the inverse relationship is self.order == self.sort_index.sort_index.

method: selects how ties are ranked:

  • :ordinal (default) — every cell gets a distinct rank; ties are broken by original position (stable). This is a total order: no two cells ever compare equal.
  • :dense — tied values share one rank (no gaps). Useful as a sort_addr priority key: an :ordinal key never ties, so a lower-priority key after it is never consulted; a :dense key preserves the tie so it is.

descending: negates the rank order ((n-1) - rank, n = fiber element count minus masked cells). This composes correctly with method: :dense: ties stay tied after the transform, and group-to-group order still reverses.

Masked cells are excluded from ranking (own cell becomes UNDEF, like rank_index); descending:/method: apply to the remaining unmasked cells.

Parameters:

  • axis (Integer, nil) (defaults to: nil)
  • descending (Boolean) (defaults to: false)
  • method (Symbol) (defaults to: :ordinal) —

    :ordinal (default) or :dense.

Returns:

  • (CArray) —

    :int64 ranks, shape == self.shape.

Raises:

  • (ArgumentError) —

    when method: is neither :ordinal nor :dense.



110
# File 'yard-stubs/carray_order.rb', line 110

def order(axis: nil, descending: false, method: :ordinal); end

#pack_bits ⇒ CArray

Packs a 1-D boolean / 0-1 uint8 CArray of length n into a uint8 CArray of ceil(n / 8) bytes, LSB-first within each byte. Exact inverse of the .bitarray view's unpack direction: for any packed uint8 array p, p.bitarray.reshape(-1)[0...p.elements * 8].pack_bits round-trips to p. Tail bits of the last byte (when n is not a multiple of 8) are zero-filled. The byte order matches the packed-bit convention used by Apache Arrow validity bitmaps and PEP 3118 ? / _Bool at the bit level.

Returns:

  • (CArray) —

    uint8 CArray of shape [ceil(n / 8)].

Raises:

  • (ArgumentError) —

    when the receiver is not 1-D or its data_type is not one of CA_BOOLEAN / CA_UINT8 / CA_INT8.

Raises:

  • (ArgumentError)


64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/carray/methods/bit_string.rb', line 64

def pack_bits
  unless data_type == CA_BOOLEAN || data_type == CA_UINT8 || data_type == CA_INT8
    raise ArgumentError,
      "pack_bits: expected CA_BOOLEAN / CA_UINT8 / CA_INT8 (got #{data_type_name})"
  end
  raise ArgumentError, "pack_bits: 1-D CArray expected (got rank #{rank})" unless rank == 1
  n = elements
  n_bytes = (n + 7) / 8
  packed = CArray.uint8(n_bytes) { 0 }
  return packed if n == 0
  packed.bitarray.reshape(-1)[0..n-1] = self
  packed
end

#parent ⇒ CArray?

Returns the parent CArray of self, or nil if self has no parent (i.e. is an entity).

Returns:



113
# File 'yard-stubs/carray_attribute.rb', line 113

def parent; end

#partition(kth, axis: 0, masked_position: :last) ⇒ CArray

Returns a CARemap view of self permuted along axis so that the element at fiber-local position kth is in its final sorted place, every element before it is <= it, and every element after it is >= it. Order within the two regions is unspecified. Average O(n) per fiber via quickselect.

Negative kth counts from the end of the fiber (-self.shape[axis] <= kth < self.shape[axis]).

Supports numeric (i8..f64), boolean (as its 0/1 value, false < true), CA_FIXLEN (memcmp lexicographic order), and CA_OBJECT (via <=> per pair).

Mask handling matches #sort: masked cells are an incomparable sentinel, excluded from the kth-selection and clustered at masked_position:. A kth landing in the masked cluster needs no selection (unspecified order, same contract as the < / > regions); a kth landing in the unmasked range selects properly among unmasked values.

Parameters:

  • kth (Integer) —

    target fiber-local position along axis.

  • axis (Integer) (defaults to: 0)
  • masked_position (Symbol) (defaults to: :last) —

    :last (default) or :first.

Returns:

  • (CArray) —

    CARemap view of self.

Raises:

  • (ArgumentError) —

    when kth is out of range.



59
# File 'yard-stubs/carray_order.rb', line 59

def partition(kth, axis: 0, masked_position: :last); end

#partition_copy(kth, axis: 0, masked_position: :last) ⇒ CArray

Returns a fresh entity CArray with the same shape as self, partitioned along axis by the same rule as #partition. Bypasses the CARemap scatter layer for cases where an entity is wanted directly. Same dispatch (numeric / boolean / CA_FIXLEN / CA_OBJECT), same kth and masked_position: semantics. Masked input delegates to #partition + copy.

Float NaN policy: NaN cells are pre-partitioned to the tail. If kth falls within the finite slice, quickselect runs over the finite cells; otherwise the kth cell is already NaN.

Parameters:

  • kth (Integer)
  • axis (Integer) (defaults to: 0)
  • masked_position (Symbol) (defaults to: :last) —

    :last (default) or :first.

Returns:

Raises:

  • (ArgumentError) —

    same conditions as #partition.



78
# File 'yard-stubs/carray_order.rb', line 78

def partition_copy(kth, axis: 0, masked_position: :last); end

#paste(offset, src) ⇒ self

Sets self at offset by copying src. Out-of-bounds cells (src extending past self's edge or before its origin) are silently dropped via CAWindow's interior-only PUT scatter.

Parameters:

  • offset (Array<Integer>) —

    starting indices, length equal to self.ndim.

  • src (CArray) —

    source array.

Returns:

  • (self)

Raises:

  • (ArgumentError) —

    when offset.length != self.ndim.

Raises:

  • (ArgumentError)


160
161
162
163
164
165
# File 'lib/carray/basics.rb', line 160

def paste (offset, src)
  raise ArgumentError, "offset length must equal ndim" if offset.length != ndim
  ranges = offset.each_with_index.map { |o, i| o...(o + src.shape[i]) }
  self.window(*ranges)[] = src
  self
end

#percentile(*p, axis: nil, min_count: 0, fill_value: nil) ⇒ Object

Returns percentile values at each p (each in [0, 100]) along axis or over all elements.

`p` may be given as individual positional arguments, a single
`Array<Numeric>`, or a single 1-D `CArray`. When the effective
`p` count (after flattening) is 1, the result is unwrapped:
flat form returns a `Float`, per-axis form returns a `CArray`.
With 2 or more `p` values the result is an `Array` whose length
matches the number of requested `p` values.

`method` picks the interpolation rule between adjacent order
statistics:

- `:linear` (default) 

method: :linear, keep_axis: false)



73
# File 'yard-stubs/carray_median_percentile.rb', line 73

def percentile(*); end

#project(idx, lval = nil, uval = nil) ⇒ CArray

Returns a new array whose elements are taken from self at the positions named by idx. idx is a CArray of flat addresses into self; the result has the shape of idx.

Out-of-range positions are filled with lval (below-range) and uval (above-range); when lval is given alone, it fills both. Without either, out-of-range positions are masked.

When self is a Face (CATime / CATimedelta / CACategorical), the result is the same Face type, carrying the unit / labels; the gather runs on the underlying storage and misses become UNDEF. Fill (lval / uval) is not supported for a Face and raises ArgumentError — omit the fill args to get UNDEF at misses.

Parameters:

  • idx (CArray) —

    flat addresses, of any shape.

  • lval (Object, nil) (defaults to: nil) —

    fill for indices < 0 (non-Face only).

  • uval (Object, nil) (defaults to: nil) —

    fill for indices >= self.elements (non-Face only).

Returns:

  • (CArray) —

    a fresh array shaped like idx; a Face of the same type when self is a Face.

Raises:

  • (ArgumentError) —

    if lval / uval is given and self is a Face.



28
# File 'yard-stubs/carray_order.rb', line 28

def project(idx, lval = nil, uval = nil); end

#put_nd(indices, values) ⇒ self

Sets self at the N-D coordinates given by indices to values. Inverse of #gather_nd.

self.shape    = (D0, ..., D_{K-1}, *rest)
indices.shape = (*outer, K)
values          broadcast to (*outer, *rest)

Duplicate coordinates in indices use last-write-wins semantics, matching put_along_axis. Accumulate semantics (+=) are not provided here; route to the scatter_*! family instead (e.g. self.flatten.scatter_add!(flat_addr, vals)).

Parameters:

  • indices (CArray, Array<CArray, Integer>) —

    stacked integer CArray shaped (*outer, K), or an Array of K per-axis coordinate arrays (same forms as #gather_nd).

  • values (CArray, Numeric) —

    values broadcastable to (*outer, *rest).

Returns:

  • (self)

Raises:

  • (ArgumentError) —

    on the same conditions as #gather_nd.

  • (IndexError) —

    when a coordinate is out of range on any axis.



92
93
94
95
96
# File 'lib/carray/methods/gather_nd.rb', line 92

def put_nd (indices, values)
  flat_addr, _outer, _rest = gather_nd_flat_addr(indices, "put_nd")
  self.flatten[flat_addr] = values
  self
end

#quantile(axis: nil, keep_axis: false) ⇒ Array<Float>, Array<CArray>

Returns the five quartile percentiles [p0, p25, p50, p75, p100] — shorthand for percentile(0, 25, 50, 75, 100, axis: axis, keep_axis: keep_axis). Accepts no positional arguments. Flat form returns Array<Float> of length 5; per-axis form returns Array<CArray> of length 5, each CArray reduced along axis.

Parameters:

  • axis (Integer, nil) (defaults to: nil)
  • keep_axis (Boolean) (defaults to: false)

Returns:

Raises:

  • (ArgumentError) —

    on any positional argument.



86
# File 'yard-stubs/carray_median_percentile.rb', line 86

def quantile(*); end

#random(rng: nil) ⇒ Object #random(high, rng: nil) ⇒ Object #random(low, high, rng: nil) ⇒ Object #random(range, rng: nil) ⇒ CArray

Overloads:

  • #random(range, rng: nil) ⇒ CArray

    Non-bang variant: returns a newly templated array filled by random!. Accepts the same argument forms.

    Returns:



48
# File 'yard-stubs/carray_random.rb', line 48

def random(*args, rng: nil); end

#random!(rng: nil) ⇒ Object #random!(high, rng: nil) ⇒ Object #random!(low, high, rng: nil) ⇒ Object #random!(range, rng: nil) ⇒ self

Overloads:

  • #random!(rng: nil) ⇒ Object

    A float array: samples [0.0, 1.0). An integer array: raises (a range is required).

  • #random!(high, rng: nil) ⇒ Object

    Samples [0, high) (Ruby rand / Numo .rand shorthand).

  • #random!(low, high, rng: nil) ⇒ Object

    Samples [low, high) (Numo positional convention).

  • #random!(range, rng: nil) ⇒ self

    Samples from a Ruby Range: a..b closed, a...b half-open. An integer array honors the endpoint distinction (dice: 1..6 yields values in 1..6 including 6; 1...6 yields 1..5). For a float array, closed and half-open are equivalent at the sampler level (endpoint probability ≈ 2^-53), matching NumPy/SciPy convention — .. is accepted for syntax but the endpoint is not enforced at the mantissa.

    Fills self with uniform random numbers in-place and returns self. Boolean arrays fill 0/1 at 50% probability, ignoring any range argument. Complex arrays sample real and imaginary parts independently from the same range.

    Parameters:

    • low (Numeric) —

      lower bound (inclusive).

    • high (Numeric) —

      upper bound (exclusive).

    • range (Range) —

      closed (a..b) or half-open (a...b).

    • rng (Random, nil) (defaults to: nil) —

      RNG instance; nil uses the per-ractor default RNG.

    Returns:

    • (self)

    Raises:

    • (CArray::DataTypeError) —

      for :object / :fixlen arrays.

    • (ArgumentError) —

      when an integer array is called with no range, when low >= high, when a Range is combined with a second positional argument, or when a Range endpoint is nil.



39
# File 'yard-stubs/carray_random.rb', line 39

def random!(*args, rng: nil); end

#randomn(rng: nil) ⇒ CArray

Non-bang variant: returns a newly templated array filled by randomn!.

Returns:



65
# File 'yard-stubs/carray_random.rb', line 65

def randomn(rng: nil); end

#randomn!(rng: nil) ⇒ self

Fills self with standard normal N(0, 1) samples via Box-Muller and returns self. Restricted to float / complex data types; complex fills real and imaginary parts as two independent normals per cell.

Parameters:

  • rng (Random, nil) (defaults to: nil) —

    RNG instance; nil uses the per-ractor default RNG.

Returns:

  • (self)

Raises:



59
# File 'yard-stubs/carray_random.rb', line 59

def randomn!(rng: nil); end

#rank ⇒ Integer

Deprecated.

Use #ndim.

Returns:

  • (Integer)


41
# File 'yard-stubs/carray_attribute.rb', line 41

def rank; end

#read_only? ⇒ Boolean

Returns true if self is read-only.

Returns:

  • (Boolean)


179
# File 'yard-stubs/carray_attribute.rb', line 179

def read_only?; end

#real ⇒ CArray

Returns the real part of self as a zero-copy view. For a complex array the view is a mutable CAField into the real-part slot; for a real numeric array it is a CARefer over self. Writing to the view updates self in place.

Returns:



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/carray/complex.rb', line 61

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)
                  end
    else
      @__real__ = self[]
    end
  end
  @__real__
end

#real=(val) ⇒ Object

Sets the real-part slot to val via #real.

Parameters:

  • val (CArray, Numeric) —

    value to broadcast.

Returns:

  • (Object) —

    val.



81
82
83
# File 'lib/carray/complex.rb', line 81

def real= (val)
  real[] = val
end

#real? ⇒ Boolean?

Returns whether every element of self is real (imaginary part is zero for complex arrays; always true for real numeric arrays; nil for non-numeric arrays).

Returns:

  • (Boolean, nil)


125
126
127
128
129
130
131
132
133
# File 'lib/carray/complex.rb', line 125

def real?
  if complex?
    imag.eq(0).all
  elsif numeric?
    true
  else
    nil
  end
end

#reduce_slab(axis:, data_type: nil) ⇒ Object #reduce_slab(axis:, init:, data_type: nil) ⇒ CArray

Overloads:

  • #reduce_slab(axis:, data_type: nil) ⇒ Object

    Per-slab form (no init:): the block receives each slab view and returns a scalar; the scalars fill an output CArray with the slab axes collapsed. Returning a CArray from the block is an error (use slab[0], slab.sum, etc. to extract a scalar).

  • #reduce_slab(axis:, init:, data_type: nil) ⇒ CArray

    Per-element form (init: given): the block receives (acc, x) for each element of the slab and returns the new accumulator; the final accumulator per slab fills the output.

    Parameters:

    • axis (Integer, Array<Integer>, nil) —

      the slab axis or axes.

    • init (Object) —

      the initial accumulator (selects the per-element form).

    • data_type (Symbol, Integer, Class, nil) (defaults to: nil) —

      output data type.

    Returns:

    • (CArray) —

      the reduced array (slab axes collapsed).

    See Also:



54
# File 'yard-stubs/carray_slab.rb', line 54

def reduce_slab(axis:, init: nil, data_type: nil); end

#refer ⇒ CARefer #refer(data_type, dim = nil, bytes: nil, offset: 0) ⇒ CARefer, CARecord

Returns a CARefer view of self — a strided reinterpretation of the parent's memory. With no arguments the view has the same data_type, shape and bytes as self; the second form accepts a different data_type (or a data_class), and optional bytes: / offset: keywords so the view exposes the parent's bytes as elements of a different width.

bytes: must divide parent.bytes (or vice versa) so element boundaries align. offset: is measured in parent elements. The total byte extent of the view must fit inside self.

When data_type is a data_class, the result is wrapped in a CARecord so field projection continues to work.

Overloads:

  • #refer ⇒ CARefer

    Returns a same-shape same-width alias of self.

    Returns:

    • (CARefer) —

      a same-shape same-width alias of self.

  • #refer(data_type, dim = nil, bytes: nil, offset: 0) ⇒ CARefer, CARecord

    Parameters:

    • data_type (Integer, Symbol, Class) —

      target data type or a data_class.

    • dim (Array<Integer>, nil) (defaults to: nil) —

      target shape; nil reuses self.shape (only valid when the byte width is unchanged).

    • bytes (Integer, nil) (defaults to: nil) —

      target byte width per element; defaults to self.bytes.

    • offset (Integer) (defaults to: 0) —

      offset in parent elements.

    Returns:

    Raises:

    • (RuntimeError) —

      when the byte widths do not divide evenly, when offset is negative, or when the requested view extends past the parent's data.

    • (RuntimeError) —

      when reinterpreting a CA_OBJECT parent with a non-object data_type.



40
# File 'yard-stubs/ca_obj_refer.rb', line 40

def refer(*argv); end

#replace_where(cond, b) ⇒ CArray

Returns a copy of self with cells where cond is true replaced by b. Functional sibling of the destructive indexer a[cond] = b; mask handling matches the indexer. Preserves self's data_type (unlike #then_else, which promotes via CArray.result_type).

Parameters:

  • cond (CArray) —

    boolean selector; same shape as self or broadcastable.

  • b (CArray, Numeric, Object) —

    replacement value(s).

Returns:

Raises:

  • (ArgumentError) —

    when cond is not a boolean CArray.



74
75
76
77
78
79
80
81
82
# File 'lib/carray/conditional.rb', line 74

def replace_where (cond, b)
  unless cond.is_a?(CArray) && cond.boolean?
    raise ArgumentError,
          "replace_where: cond must be a boolean CArray (data_type == CA_BOOLEAN)"
  end
  result = self.copy
  result[cond] = b.is_a?(CArray) ? b[cond] : b
  result
end

#reshape(*newdim) ⇒ CArray

Returns a view of self with the requested shape. Element count must match (-1 or :~ may stand in for one axis, whose size is inferred); nil copies the corresponding axis from self. When the reshape can be expressed as strides over self's deepest non-CAStride ancestor, the result is a CAStride; otherwise a CARefer.

Returns the reshape view.

Parameters:

  • newdim (Array<Integer, nil, Symbol>) —

    target shape. Integers are axis sizes; nil copies from self in position order (mirrored from the end after the placeholder); -1 or :~ marks the auto-infer placeholder (at most one).

Returns:

  • (CArray) —

    the reshape view.

Raises:

  • (ArgumentError) —

    when the number of dims exceeds CA_RANK_MAX.

  • (RuntimeError) —

    when the product does not equal self.elements (with no placeholder), when the placeholder cannot be inferred, when more than one placeholder is given, or when a nil has no matching source axis.



61
# File 'yard-stubs/ca_obj_refer.rb', line 61

def reshape(*newdim); end

#resize(*newdim, fill_value: 0) ⇒ CArray

Returns self resized to newdim. The original data is placed at offset 0 (positive size) or right-aligned (negative size); the new area outside the original region is filled with fill_value, or -- for fixlen storage -- left as zero bytes. Pass UNDEF to mask the new area.

Each entry of newdim is: nil to keep the current shape[i], a positive Integer for a new size with the original left-aligned at offset 0, or a negative Integer d for a new size |d| with the original right-aligned.

Works on Face arrays (CARecord / CATime / ...) and plain fixlen: the resize is done on the storage layout (preserving bytes) and re-wrapped as the same Face.

Parameters:

  • newdim (Array<Integer, nil>) —

    new shape spec, one entry per axis.

  • fill_value (Object) (defaults to: 0) —

    value for the extended area.

Returns:



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/carray/methods/resize.rb', line 23

def resize (*newdim, fill_value: 0)
  raise "ndim mismatch" if newdim.size != ndim
  offset = Array.new(ndim, 0)
  newdim = newdim.each_with_index.map do |d, i|
    case d
    when nil
      shape[i]
    when Integer
      size = d.abs
      offset[i] = size - shape[i] if d < 0
      size
    else
      raise "invalid dimension size"
    end
  end
  face_parent = self.face? ? self : nil
  src = self
  src = src.parent while src.face?
  dt    = src.data_type
  bytes = (dt == :fixlen) ? src.bytes : nil
  out = CArray.new(dt, newdim, bytes: bytes)
  # Fill the new area: numeric storage takes fill_value as-is; fixlen
  # storage cannot hold a numeric 0, so leave zero bytes and honor only
  # UNDEF (mask) or an explicit String fill.
  if dt != :fixlen || fill_value.equal?(UNDEF) || fill_value.is_a?(String)
    out[] = fill_value
  end
  out.mask.paste(offset, src.false) if out.has_mask?
  out.paste(offset, src)
  out = out.face_lift(face_parent) if face_parent
  out
end

#roll(*shifts) ⇒ CARoll

Returns a CARoll view of self cyclically shifted by shifts[k] along each axis k. Positive shifts move cell i of the parent to position i + shift; negative shifts move it the other way. Each shift[k] is normalised into [0, self.dim[k]) before use, so any integer is accepted.

Fewer args than ndim treats the missing axes as shift = 0. More args than ndim raises ArgumentError.

The in-place idiom is ca[] = ca.roll(...); there is no roll!. For a non-cyclic translation with a fill value use #shift.

Parameters:

  • shifts (Array<Integer>) —

    one shift per axis; may be shorter than ndim (missing axes default to 0).

Returns:

Raises:

  • (ArgumentError) —

    when more than ndim shifts are given.

  • (IndexError) —

    when any parent dimension is non-positive.



42
# File 'yard-stubs/ca_obj_roll.rb', line 42

def roll(*shifts); end

#root_array ⇒ CArray

Returns the array at the root of the view chain (the entity). Returns self if self is already an entity.

Returns:



119
# File 'yard-stubs/carray_attribute.rb', line 119

def root_array; end

#round ⇒ CArray

Returns a new array with each element rounded to the nearest integer value, half rounded away from zero (2.5 -> 3.0, -2.5 -> -3.0). The result keeps self's data_type.

Integer arrays are returned unchanged. For a :float64 / :float32 array the value stays floating-point (e.g. 1.4 -> 1.0); a NaN element is passed through as NaN, and -0.0 keeps its sign. Masked elements stay masked. An :object array delegates to each element's #round.

Returns:

  • (CArray) —

    same data_type as self.



116
# File 'yard-stubs/carray_math.rb', line 116

def round; end

#same_shape?(other) ⇒ Boolean

Returns true if other has the same shape as self.

Parameters:

Returns:

  • (Boolean)


28
# File 'yard-stubs/carray_test.rb', line 28

def same_shape?(other); end

#save_arrow_tensor(filename) ⇒ self

Writes self to filename as an Arrow tensor IPC message.

Experimental, and the name is provisional. Rejects a masked or non-numeric array; see ArrowTensor for the type policy.

Parameters:

  • filename (String) —

    path to write.

Returns:

  • (self)

See Also:



397
398
399
400
# File 'lib/carray/arrow_tensor.rb', line 397

def save_arrow_tensor (filename)
  File.open(filename, "wb") { |io| ArrowTensor.write(self, io) }
  self
end

#scalar? ⇒ Boolean

Returns true if self is a CScalar.

Returns:

  • (Boolean)


151
# File 'yard-stubs/carray_attribute.rb', line 151

def scalar?; end

#scale(xa, xb) ⇒ CArray

Returns a fresh CArray shaped like self holding elements evenly spaced values from xa to xb inclusive.

Parameters:

  • xa (Numeric) —

    first value.

  • xb (Numeric) —

    last value.

Returns:



385
386
387
# File 'lib/carray/basics.rb', line 385

def scale (xa, xb)
  template.scale!(xa, xb)
end

#scale!(xa, xb) ⇒ self

Sets self to elements evenly spaced float64 values from xa to xb inclusive.

Parameters:

  • xa (Numeric) —

    first value.

  • xb (Numeric) —

    last value.

Returns:

  • (self)


373
374
375
376
377
# File 'lib/carray/basics.rb', line 373

def scale! (xa, xb)
  xa = xa.to_f
  xb = xb.to_f
  seq!(xa, (xb-xa)/(elements-1))
end

#scatter_add!(addrs, vals) ⇒ self

For each i, applies self[addrs[i]] += vals[i] (or += vals if vals is scalar). Mutates self.

Parameters:

Returns:

  • (self)

Raises:



43
# File 'yard-stubs/carray_scatter.rb', line 43

def scatter_add!(addrs, vals); end

#scatter_max!(addrs, vals) ⇒ self

For each i, applies self[addrs[i]] = max(self[addrs[i]], vals[i]). For float data_type, NaN follows the fmax rule.

Parameters:

Returns:

  • (self)


85
# File 'yard-stubs/carray_scatter.rb', line 85

def scatter_max!(addrs, vals); end

#scatter_min!(addrs, vals) ⇒ self

For each i, applies self[addrs[i]] = min(self[addrs[i]], vals[i]).

For float data_type, NaN follows the fmin rule (NaN is treated as missing: min(NaN, v) → v, min(x, NaN) → x).

Parameters:

Returns:

  • (self)


76
# File 'yard-stubs/carray_scatter.rb', line 76

def scatter_min!(addrs, vals); end

#scatter_mul!(addrs, vals) ⇒ self

For each i, applies self[addrs[i]] *= vals[i]. Duplicate addresses multiply.

NaN/inf follow standard C arithmetic propagation (no fmin-style missing-value rule). Integer overflow wraps.

Typical uses: Bayesian likelihood patch update, scatter blend, log-domain → linear product, weight composition.

Parameters:

Returns:

  • (self)


65
# File 'yard-stubs/carray_scatter.rb', line 65

def scatter_mul!(addrs, vals); end

#scatter_replace!(addrs, vals) ⇒ self

For each i, applies self[addrs[i]] = vals[i] (or = vals if scalar). Duplicate addresses resolve to last-write-wins.

Semantically equivalent to self[addrs] = vals but bypasses the CAGrid view chain (which snapshot-copies addrs and allocates view state); useful in hot loops where a scatter result is written back many times.

Unlike the arithmetic scatter_*! family, self may be boolean (assignment does not widen), and true / false are accepted as scalar vals alongside numeric scalars.

Parameters:

Returns:

  • (self)


103
# File 'yard-stubs/carray_scatter.rb', line 103

def scatter_replace!(addrs, vals); end

#scatter_sub!(addrs, vals) ⇒ self

For each i, applies self[addrs[i]] -= vals[i]. Same contract as #scatter_add!.

Parameters:

Returns:

  • (self)


51
# File 'yard-stubs/carray_scatter.rb', line 51

def scatter_sub!(addrs, vals); end

#search(val, eps = nil) ⇒ Integer? #search(val, eps = nil, axis:) ⇒ CArray

Overloads:

  • #search(val, eps = nil) ⇒ Integer?

    Returns the flat address of the first element of self equal to val. For float types, eps (default machine epsilon) sets the tolerance. Returns nil if no match.

    self need not be sorted; this is a linear scan. For sorted data prefer #bsearch.

    Parameters:

    • val (Object)
    • eps (Float, nil) (defaults to: nil)

    Returns:

    • (Integer, nil)
  • #search(val, eps = nil, axis:) ⇒ CArray

    Per-fiber linear search along axis. Returns axis-local positions.

    Returns:



160
# File 'yard-stubs/carray_order.rb', line 160

def search(val, eps = nil, axis: nil); end

#search_addr(val, eps = nil) ⇒ Integer? #search_addr(val, eps = nil, axis:) ⇒ CArray

Overloads:

  • #search_addr(val, eps = nil) ⇒ Integer?

    Equivalent to #search when axis: is omitted.

    Returns:

    • (Integer, nil)
  • #search_addr(val, eps = nil, axis:) ⇒ CArray

    Per-fiber linear search along axis, returning flat addresses rather than axis-local positions.

    Returns:



169
# File 'yard-stubs/carray_order.rb', line 169

def search_addr(val, eps = nil, axis: nil); end

#search_nearest(val) ⇒ Integer? #search_nearest(val, axis:) ⇒ CArray

Overloads:

  • #search_nearest(val) ⇒ Integer?

    Returns the flat address of the element of self whose value is closest to val. For :object arrays, uses val.distance(other) to compare.

    Parameters:

    • val (Object)

    Returns:

    • (Integer, nil)
  • #search_nearest(val, axis:) ⇒ CArray

    Per-fiber nearest-value search along axis. Returns axis-local positions.

    Returns:



181
# File 'yard-stubs/carray_order.rb', line 181

def search_nearest(val, axis: nil); end

#search_nearest_addr(val) ⇒ Integer? #search_nearest_addr(val, axis:) ⇒ CArray

Overloads:

  • #search_nearest_addr(val) ⇒ Integer?

    Equivalent to #search_nearest when axis: is omitted.

    Returns:

    • (Integer, nil)
  • #search_nearest_addr(val, axis:) ⇒ CArray

    Per-fiber nearest-value search along axis, returning flat addresses rather than axis-local positions.

    Returns:



190
# File 'yard-stubs/carray_order.rb', line 190

def search_nearest_addr(val, axis: nil); end

#seq(init_val = 0, step = 1, axis: nil) ⇒ CArray

Equivalent to dup.seq!(init_val, step, axis: axis). Returns a fresh array of the same shape and data_type as self, filled with a sequence (flat by default, or along axis when given).

Parameters:

  • init_val (Numeric, Object) (defaults to: 0)
  • step (Numeric, Symbol) (defaults to: 1)
  • axis (Integer, nil) (defaults to: nil) —

    the axis the progression runs along, or nil for a flat row-major fill.

Returns:



63
# File 'yard-stubs/carray_generate.rb', line 63

def seq(*); end

#seq! ⇒ self #seq!(init_val) ⇒ self #seq!(init_val, step) ⇒ self #seq!(init_val = 0, step = 1, axis:) ⇒ self

Overloads:

  • #seq! ⇒ self

    Fills self in row-major order with 0, 1, 2, .... Mutates self and clears any mask.

    Returns:

    • (self)
  • #seq!(init_val) ⇒ self

    Fills self in row-major order with init_val, init_val + 1, init_val + 2, ... Mutates self.

    Parameters:

    • init_val (Numeric)

    Returns:

    • (self)
  • #seq!(init_val, step) ⇒ self

    Fills self in row-major order with init_val, init_val + step, init_val + 2*step, ...

    For :object arrays only, step may be a Symbol naming the stepping method to invoke on the previous element (e.g. :succ).

    Parameters:

    • init_val (Numeric, Object)
    • step (Numeric, Symbol)

    Returns:

    • (self)
  • #seq!(init_val = 0, step = 1, axis:) ⇒ self

    Fills self with a progression that runs along axis and repeats across the other axes: the cell value depends only on its coordinate along axis. axis must be a single integer (a negative value counts from the end); multi-axis fills are not supported.

    Parameters:

    • init_val (Numeric, Object) (defaults to: 0)
    • step (Numeric, Symbol) (defaults to: 1)
    • axis (Integer) —

      the axis the progression runs along.

    Returns:

    • (self)

    Raises:

    • (ArgumentError) —

      if axis is out of range or not a single integer.



52
# File 'yard-stubs/carray_generate.rb', line 52

def seq!(*); end

#set_attr(key, value) ⇒ Object

Sets attribute key to value on self (not on any parent). Values are validated as JSON-compatible plus non-finite Floats (String / Numeric incl. Infinity / NaN / true / false / nil / Symbol / Array / Hash); Symbol values are coerced to String on store.

Parameters:

  • key (Symbol, String) —

    attribute key.

  • value (Object) —

    JSON-compatible value.

Returns:

  • (Object) —

    the coerced stored value.

Raises:

  • (TypeError) —

    when key or value is not accepted.



59
60
61
62
# File 'lib/carray/attribute.rb', line 59

def set_attr (key, value)
  attr_validate_value(value)
  (@attr ||= {})[attr_normalize_key(key)] = attr_coerce_value(value)
end

#set_read_only_flag ⇒ self

Marks self read-only (sets CA_FLAG_READ_ONLY) without freezing the Ruby object, so subsequent mutations raise RuntimeError while frozen? stays false and views / Faces derived from self can still memoise. One-way: there is no method to clear the flag. Use #copy for a writable copy (a copy does not inherit the flag). Contrast #freeze, which also freezes the Ruby object.

Returns:

  • (self)


82
# File 'yard-stubs/carray_test.rb', line 82

def set_read_only_flag; end

#shape ⇒ Array<Integer>

Returns a freshly allocated Array containing the dimensional shape of self (e.g. [2, 3] for a 2×3 array).

This is the recommended accessor. #dim is a legacy alias.

Examples:

CArray.float64(2, 3).shape  # => [2, 3]

Returns:



82
# File 'yard-stubs/carray_attribute.rb', line 82

def shape; end

#shift(*shifts, fill_value: 0) ⇒ CAShift

Returns a CAShift view of self translated by shifts along each axis (one shift per dimension; a positive shift moves cell i of the parent to position i + shift). Out-of-range cells take fill_value (default 0); passing fill_value: UNDEF masks them instead of filling. In-range cells alias the parent, so writes through the view reach the parent.

The in-place idiom is ca[] = ca.shift(...); there is no shift!. For a cyclic (wrap-around) shift use #roll, which returns a CARoll view.

Parameters:

  • shifts (Array<Integer>) —

    one shift per axis; the count must equal self.ndim.

  • fill_value (Object) (defaults to: 0) —

    value written to out-of-range cells; UNDEF masks them instead.

Returns:

Raises:

  • (ArgumentError) —

    when the number of shifts does not equal ndim, when the removed :roll option is given, or when a block is passed (the block form was removed in 3.0).



40
# File 'yard-stubs/ca_obj_shift.rb', line 40

def shift(*shifts, fill_value: 0); end

#short ⇒ Object

Alias of #int16. @return [CArray]



159
# File 'yard-stubs/carray_cast.rb', line 159

def short; end

#shuffle(axis: nil, rng: nil) ⇒ CArray

Non-bang variant: returns a shuffled copy of self.

Returns:



86
# File 'yard-stubs/carray_random.rb', line 86

def shuffle(axis: nil, rng: nil); end

#shuffle!(axis: nil, rng: nil) ⇒ self

Fisher-Yates permutes self in-place and returns self. Without axis:, shuffles all cells as if flattened. With axis:, permutes slices along that axis (the trailing sub-slab is treated as a byte chunk and swapped whole).

Parameters:

  • axis (Integer, nil) (defaults to: nil) —

    axis to permute along; nil = flat.

  • rng (Random, nil) (defaults to: nil) —

    RNG instance; nil uses the per-ractor default RNG.

Returns:

  • (self)

Raises:

  • (ArgumentError) —

    if axis is out of range.



81
# File 'yard-stubs/carray_random.rb', line 81

def shuffle!(axis: nil, rng: nil); end

#size ⇒ Integer

Alias of #elements.

Returns:

  • (Integer)


67
# File 'yard-stubs/carray_attribute.rb', line 67

def size; end

#sliding_windows(window, step: nil) ⇒ Object #sliding_windows(w0, w1, ..., step: nil) ⇒ CAStride

Returns a CAStride view of overlapping windows over every axis. A parent of shape [d0, ..., dN-1] becomes a view of shape [(d0-w0)/s0+1, ..., (dN-1-wN-1)/sN-1+1, w0, ..., wN-1], where wi is the window length on axis i and si the step.

Truncate mode: a trailing partial window is dropped rather than padded. Memory is shared with the parent, and because windows overlap, one parent cell is visible from several positions of the view.

Reduce over the trailing ndim axes for a rolling statistic.

Overloads:

  • #sliding_windows(w0, w1, ..., step: nil) ⇒ CAStride

    Returns of rank 2 * ndim.

    Parameters:

    • window (Array<Integer>, Integer) —

      window length per axis, one per dimension, as an Array or as variadic arguments.

    • step (Array<Integer>, Integer, nil) (defaults to: nil) —

      stride between windows per axis; nil means 1 on every axis.

    Returns:

    Raises:

    • (ArgumentError) —

      when the window count does not equal ndim, when a window or step is not positive, when a window is longer than its axis, or when 2 * ndim exceeds CA_RANK_MAX.



63
# File 'yard-stubs/ca_obj_stride.rb', line 63

def sliding_windows(*window, step: nil); end

#snap(step, offset: 0.0, direction: :round) ⇒ CArray

Returns each element snapped to a point on the uniform grid ..., -step + offset, offset, step + offset, 2*step + offset, .... The rounding rule follows direction: (default :round, matching CArray#round; :floor snaps toward -inf, :ceil toward +inf).

The output has the same data type as self (integer input is coerced to float internally when step / offset are floats, following normal arithmetic promotion). NaN / Inf are preserved as a mask on the output; the rounding kernels map NaN to 0.0, which would silently land NaN cells on the grid, so NaN is detected explicitly on the scaled chain.

Use snap_to(list) when the target grid is non-uniform; use bin(vmin, vmax, step) when the desired output is a bin index.

Examples:

temp.snap(0.5)                        # nearest 0.5 K grid point
temp.snap(0.5, offset: 0.25)          # to 0.25, 0.75, 1.25, ... (bin centers)
temp.snap(0.5, direction: :floor)     # bin lower edge
temp.snap(0.5, direction: :ceil)      # bin upper edge

Parameters:

  • step (Numeric) —

    positive grid spacing.

  • offset (Numeric) (defaults to: 0.0) —

    phase / origin of the grid; the grid always passes through offset.

  • direction (:round, :floor, :ceil) (defaults to: :round) —

    rounding rule; :round picks the nearest grid point (ties half-away-from-zero), :floor picks the grid point at or below the value, :ceil picks the grid point at or above.

Returns:

  • (CArray) —

    snapped values, same shape as self.

Raises:

  • (ArgumentError) —

    when step <= 0 or direction is not one of the accepted symbols.

Raises:

  • (ArgumentError)


35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/carray/methods/snap.rb', line 35

def snap(step, offset: 0.0, direction: :round)
  raise ArgumentError, "snap: step must be > 0" unless step > 0
  unless [:round, :floor, :ceil].include?(direction)
    raise ArgumentError,
          "snap: direction must be :round / :floor / :ceil " \
          "(got #{direction.inspect})"
  end

  scaled = (self - offset) / step

  # Detect NaN / Inf before rounding (which maps NaN -> 0.0 silently).
  invalid_mask = scaled.float? ? scaled.is_invalid : nil

  snapped = case direction
            when :round then scaled.round
            when :floor then scaled.floor
            when :ceil  then scaled.ceil
            end
  out = snapped * step + offset

  if invalid_mask && invalid_mask.count(true) > 0
    out.mask = out.has_mask? ? (out.mask | invalid_mask) : invalid_mask
  end

  out
end

#snap_to(list, lfill: :clamp, ufill: :clamp, direction: :round) ⇒ CArray

Returns each element snapped to a value in list (non-uniform grid). The rounding rule follows direction: (default :round for nearest neighbour; :floor picks the list value at or below the sample, :ceil at or above), and delegates to locate_nearest_addr(direction:).

list must be a 1-D ascending numeric CArray (or convertible via CArray.wrap_readonly). Out-of-range and NaN handling follows the same pattern as bin_to, but with an additional :clamp sentinel that snaps out-of-range cells to the nearest list end.

  • :clamp (default) — below-range cells become list[0], above-range cells become list[-1].
  • nil — the side is masked in the output.
  • any other value — the side is filled with that value.

NaN / masked input cells are always masked in the output, regardless of lfill / ufill.

Use snap(step, offset:) when the target grid is uniform; use bin_to(edges) when the output is a bin index against half-open intervals rather than a nearest-value snap.

Examples:

temp.snap_to([270.0, 280.0, 290.0, 300.0])                   # clamp OOB
temp.snap_to(grid, lfill: nil, ufill: nil)                   # mask OOB
rain.snap_to([0.0, 1.0, 5.0, 20.0], direction: :floor)       # list value at or below

Parameters:

  • list (CArray, Array<Numeric>) —

    1-D ascending grid, at least one value.

  • lfill (:clamp, nil, Numeric) (defaults to: :clamp) —

    handling for below-list[0] cells.

  • ufill (:clamp, nil, Numeric) (defaults to: :clamp) —

    handling for above-list[-1] cells.

  • direction (:round, :floor, :ceil) (defaults to: :round) —

    rounding rule; forwarded to locate_nearest_addr.

Returns:

  • (CArray) —

    snapped values with list's data_type, same shape as self.

Raises:

  • (ArgumentError) —

    when list is not 1-D or is empty, or direction is not one of the accepted symbols.

Raises:

  • (ArgumentError)


102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/carray/methods/snap.rb', line 102

def snap_to(list, lfill: :clamp, ufill: :clamp, direction: :round)
  ref = list.is_a?(CArray) ? list : CArray.wrap_readonly(list, self.data_type)
  raise ArgumentError, "snap_to: list must be 1-D" unless ref.ndim == 1
  n = ref.elements
  raise ArgumentError, "snap_to: list must have at least one value" if n < 1

  if n == 1
    # Degenerate: every finite cell snaps to the only value.
    out = CArray.new(ref.data_type, shape).fill(ref[0])
    out.mask = self.mask.to_ca if self.has_mask?
    if self.float?
      inv = self.is_invalid
      if inv.count(true) > 0
        out.mask = out.has_mask? ? (out.mask | inv) : inv
      end
    end
    return out
  end

  # `locate_nearest_addr` (via `linear_section`) accepts a 1-D `val` only;
  # flatten multi-D input and reshape the result back to preserve the
  # element-wise semantic on any shape.
  if ndim > 1
    return reshape(-1).snap_to(ref, lfill: lfill, ufill: ufill,
                               direction: direction).reshape(*shape)
  end

  # locate_nearest_addr returns int64 indices; OOB (below / above / NaN)
  # cells come back masked. We split OOB into below / above with
  # explicit comparisons so the two sides can be filled independently.
  idx = self.locate_nearest_addr(ref, direction: direction)
  out = ref.project(idx)

  below = self.lt(ref[0])
  above = self.gt(ref[-1])

  case lfill
  when :clamp then out[below] = ref[0]
  when nil    then # leave masked (locate_nearest_addr already masked OOB)
  else             out[below] = lfill
  end

  case ufill
  when :clamp then out[above] = ref[-1]
  when nil    then # leave masked
  else             out[above] = ufill
  end

  # Propagate input mask (locate_nearest_addr / project do not forward
  # `self`'s mask on their own; a masked input cell must produce a
  # masked output cell regardless of the fill options above).
  if self.has_mask?
    m = self.mask.to_ca
    out.mask = out.has_mask? ? (out.mask | m) : m
  end

  out
end

#sort(axis: nil, kind: :quick, masked_position: :last) ⇒ CArray

Returns a CARemap view of self whose elements are sorted along axis. When axis is omitted, self is first flattened to 1-D and the entire array is sorted (so the result is a 1-D view regardless of self.ndim).

kind: selects the sorting algorithm. Both kinds are stable (tie-broken by fiber-local index); the choice is a performance characteristic only:

  • :quick (default) — portable textbook introsort with mergesort escape. Faster on random data.
  • :stable — portable bottom-up mergesort with insertion pre-pass. Predictable worst case.

Masked cells are an incomparable sentinel (the same role NaN plays for float data types): they are excluded from the value comparison and clustered at one end of each fiber. masked_position: picks which end (:last, default, or :first); relative order within the masked cluster is unspecified. Masked cells keep their masked-ness at the clustered position (the CARemap gather carries the mask bit through, no separate output-mask step needed).

Supports numeric (i8..f64), CA_FIXLEN (via memcmp lexicographic order), and CA_OBJECT (via <=> per pair) -- all through the same view path, masked_position: included.

Parameters:

  • axis (Integer, nil) (defaults to: nil)
  • kind (Symbol) (defaults to: :quick) —

    :quick or :stable.

  • masked_position (Symbol) (defaults to: :last) —

    :last (default) or :first.

Returns:



62
# File 'yard-stubs/carray_sort.rb', line 62

def sort(axis: nil, kind: :quick, masked_position: :last); end

#sort_addr(axis: nil, kind: :quick, masked_position: :last) ⇒ CArray

Returns view-flat addresses that index a sort.

  • With no kwarg (a.sort_addr): returns a CArray of :int64 flat addresses shaped like self (NOT flattened -- the legacy 1-key case of CArray.sort_addr's multi-key lex sort). kind: has no effect on this form.
  • With axis: (e.g. a.sort_addr(axis: 0)): returns per-fiber view-flat addresses along the given axis, output shape == self.shape.

kind: selects the sort algorithm for the axis: path:

  • :quick (default) — introsort with mergesort escape.
  • :stable — bottom-up mergesort.

Both kinds are algorithmically stable (pair sort with index tie-break); kind: chooses the performance characteristic.

masked_position: (:last default, or :first) picks which end masked cells cluster to. Effective on both forms: the axis: path forwards to the sort/sort_index kernel family; the no-axis: path forwards to CArray.sort_addr's own masked-position-aware comparator.

Companion of #axis2addr (axis-local indices to view-flat addresses) and #sort (the view counterpart).

Parameters:

  • axis (Integer, nil) (defaults to: nil)
  • kind (Symbol) (defaults to: :quick) —

    :quick or :stable.

  • masked_position (Symbol) (defaults to: :last) —

    :last (default) or :first.

Returns:

  • (CArray) —

    :int64 addresses.

Raises:

  • (ArgumentError) —

    when kind: is neither :quick nor :stable.



114
# File 'yard-stubs/carray_sort.rb', line 114

def sort_addr(axis: nil, kind: :quick, masked_position: :last); end

#sort_copy(axis: nil, kind: :quick, masked_position: :last) ⇒ CArray

Eager-copy counterpart of #sort: returns a fresh entity CArray with the same shape and data_type as self, sorted along axis. Use this when you want an independent array rather than a view.

Unmasked numeric paths use a per-fiber gather + sort + scatter, bypassing the CARemap scatter layer that sort uses. CA_FIXLEN and masked input both materialize the sort view instead (same shape, ordering, and masked_position: semantics as #sort).

Parameters:

  • axis (Integer, nil) (defaults to: nil)
  • kind (Symbol) (defaults to: :quick) —

    :quick or :stable.

  • masked_position (Symbol) (defaults to: :last) —

    :last (default) or :first.

Returns:



79
# File 'yard-stubs/carray_sort.rb', line 79

def sort_copy(axis: nil, kind: :quick, masked_position: :last); end

#source_code ⇒ String

Returns a Ruby source-like string that would reconstruct self, combining the type/shape descriptor with a pretty printed value block. Useful for embedding fixtures in scripts.

Returns:

  • (String)


244
245
246
247
248
249
250
251
252
253
254
# File 'lib/carray/inspect.rb', line 244

def source_code
  text = [
    desc,
    " { ",
    self.to_a.pretty_inspect.split("\n").map{|s|
      " " * (desc.length+3) + s
    }.join("\n").lstrip,
    " }"
  ].join
  return text
end

#span(range) ⇒ CArray

Returns a fresh CArray shaped like self filled with the linear sequence produced by #span!. Float arrays only.

Parameters:

  • range (Range<Numeric>) —

    value range to span.

Returns:

Raises:

  • (ArgumentError) —

    when self is not a float array.



363
364
365
# File 'lib/carray/basics.rb', line 363

def span (range)
  return template.span!(range)
end

#span!(range) ⇒ self

Sets self to a linear sequence over range, with the step chosen so that range.end (or range.end when the range is exclusive-end, treated as the limit not reached) determines the endpoint. Concretely:

  • inclusive range a..b: self[0] == a, self[-1] == b, intermediate values are evenly spaced.
  • exclusive range a...b: self[0] == a, `self == a + (N-1)
    • (b-a)/N(endpointb` is not reached).

Only float arrays are supported. Integer arrays raise — "N evenly-spaced integers" is not a well-defined concept; the error message shows the two idioms that cover the two distinct integer use cases:

  • (A) N points with both endpoints hitting a and b exactly (linspace-like): use the manual integer form CArray.int32(N).seq * (b - a) / (N - 1) + a, or sample as float then cast: CArray.float64(N).span(a.to_f..b.to_f).int32.
  • (B) N labels distributed uniformly over the value range so each of the (b - a + 1) values appears approximately the same number of times (bucket distribution): use CArray.int32(N).seq * (b - a + 1) / N + a.

Parameters:

  • range (Range<Numeric>) —

    value range to span.

Returns:

  • (self)

Raises:

  • (ArgumentError) —

    when self is not a float array.



339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'lib/carray/basics.rb', line 339

def span! (range)
  unless float?
    raise ArgumentError,
          "span!: integer arrays are ambiguous — 'N evenly-spaced " \
          "integers' has two distinct meanings. Pick the one you want:\n" \
          "  (A) N points hitting both endpoints exactly (linspace-like):\n" \
          "      CArray.int32(N).seq * (b - a) / (N - 1) + a\n" \
          "      or  CArray.float64(N).span(a.to_f..b.to_f).int32\n" \
          "  (B) N labels distributed uniformly over range values:\n" \
          "      CArray.int32(N).seq * (b - a + 1) / N + a"
  end
  first = range.begin.to_r
  last  = range.end.to_r
  step = range.exclude_end? ? (last-first)/elements : (last-first)/(elements-1)
  seq!(first, step)
  return self
end

#split(axis:) ⇒ Array<CArray>

Split self along a single axis into an Array of (ndim-1)-D slices, each a writable CABlock view. The exact inverse of CArray.stack -- split's slices are all the same shape, so they round-trip back through stack:

CArray.stack(a.split(axis: k), axis: k) == a

a = CA_INT([[1,2,3], [4,5,6]])
a.split(axis: 0)   #=> [ <[1,2,3]>, <[4,5,6]> ]      (row views)
a.split(axis: 1)   #=> [ <[1,4]>, <[2,5]>, <[3,6]> ] (column views)

3.0 breaking:

- returns a Ruby Array of views (was an object CArray), so it
round-trips with CArray.stack (which takes an Array)
- +axis:+ takes a single Integer (the multi-axis Array form, which
returned an N-D object grid, is no longer accepted)
- pieces are CABlock views, NOT copies; writing through a piece
mutates +self+.  Chain +.copy+ / +.to_ca+ for independent entities.

Returns an Array of (ndim-1)-D writable CABlock views obtained by splitting self along axis. Inverse of CArray.stack. Slices share storage with self; chain .copy for independent entities.

Parameters:

  • axis (Integer) —

    axis to split along.

Returns:

Raises:

  • (ArgumentError) —

    when axis is not a single Integer.



251
252
253
254
255
256
257
258
259
260
261
# File 'lib/carray/stack.rb', line 251

def split (axis:)
  if axis.is_a?(Array)
    raise ArgumentError, "split: axis must be a single Integer"
  end
  k = normalize_axis(axis, "split")
  (0...shape[k]).map do |i|
    idx = [nil] * ndim
    idx[k] = i
    self[*idx]
  end
end

#st ⇒ Struct

Returns a Ruby Struct view exposing every CAStruct member of self as a Struct attribute holding the corresponding member column. Cached per receiver.

Returns:

  • (Struct)

Raises:



166
167
168
169
170
171
172
173
174
175
176
# File 'lib/carray/struct.rb', line 166

def st
  unless has_data_class?
    raise CAStruct::Error, "carray does not have a 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

#stack(*others, axis: 0, data_type: nil) ⇒ CArray

Instance-side stack: build a new K-stack from [self] + others along the new K axis at position axis:. Always treats self as a parent (= even when self is a CAStack, the resulting stack has self as one of its parents, NOT flat-appended into self's parents).

For flat-appending into an existing CAStack (= same k_axis, parents extended), use CAStack#append.

3.0: high-level Face-aware surface, mirrors CArray.stack(list, axis:).

Returns a K-stack view built from [self] + others along a new K axis at position axis. Always treats self as one parent, even when self is a CAStack; use CAStack#append to flat-append into an existing CAStack.

Parameters:

  • others (Array<CArray>) —

    additional parents.

  • axis (Integer) (defaults to: 0) —

    position of the new K axis.

  • data_type (Symbol, Integer, nil) (defaults to: nil) —

    result data_type.

Returns:

Raises:

  • (ArgumentError) —

    when no others are given.

Raises:

  • (ArgumentError)


221
222
223
224
# File 'lib/carray/stack.rb', line 221

def stack (*others, axis: 0, data_type: nil)
  raise ArgumentError, "stack: at least one other parent required" if others.empty?
  CArray.stack([self] + others, axis: axis, data_type: data_type)
end

#strip_mask(fill_value) ⇒ CArray #strip_mask(method:, axis: nil) ⇒ CArray

strip_mask is the copy form of unmask: it returns a new array rather than mutating self, supplying values either from a constant fill_value or a scan method:. The two are mutually exclusive.

Overloads:

  • #strip_mask(fill_value) ⇒ CArray

    Returns a new array with the same shape and data_type as self, with no mask attached, and fill_value substituted at positions that were masked in self. self is not modified.

    Replaces the removed unmask_copy(fill) from 2.x.

    Parameters:

    • fill_value (Object) —

      value to substitute at masked positions. Cast to self.data_type.

    Returns:

  • #strip_mask(method:, axis: nil) ⇒ CArray

    Returns a new array with masked cells filled from neighbouring valid cells along axis (gap-fill). self is not modified. Residual (leading / trailing / out-of-range) masked cells that cannot be filled stay masked in the returned array.

    Parameters:

    • method (Symbol) —

      fill rule: :forward / :ffill, :backward / :bfill (any data_type), or :linear (numeric or a time Face). See #unmask for the full description.

    • axis (Integer, nil) (defaults to: nil) —

      scan axis (single axis). nil flattens.

    Returns:



121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'yard-stubs/carray_mask.rb', line 121

def strip_mask (fill = MASK_FILL_UNSET, method: nil, axis: nil)
  if method
    unless fill.equal?(MASK_FILL_UNSET)
      raise ArgumentError,
            "strip_mask: pass either a constant fill value or method:, not both"
    end
    return __gap_fill__(method, axis)
  end
  if fill.equal?(MASK_FILL_UNSET)
    raise ArgumentError, "strip_mask: a fill value is required (or method:)"
  end
  __strip_mask_const__(fill)
end

#swap_bytes ⇒ CArray

Returns a lazy view of self whose cells are byte-swapped versions of the parent cells. Materialises on attach. Primitive numeric parents get a CAMonOp view; CA_FIXLEN parents (with or without a data_class) get a CAByteSwap view.

For eager copy semantics use arr.swap_bytes.to_ca. The in-place idiom is ca[] = ca.swap_bytes; there is no swap_bytes!.

Returns byte-swapped view of self.

Returns:

  • (CArray) —

    byte-swapped view of self.

Raises:

  • (CADataTypeError) —

    when self.data_type is CA_OBJECT (object arrays cannot be byte-swapped).



33
# File 'yard-stubs/ca_obj_byte_swap.rb', line 33

def swap_bytes; end

#T(*imap) ⇒ Object

Alias of #transpose.



37
# File 'yard-stubs/ca_obj_transpose.rb', line 37

def T(*imap); end

#template ⇒ CArray #template(data_type, bytes: 0) ⇒ CArray #template({ value }) ⇒ CArray #template({ |*idx| ... }) {|idx| ... } ⇒ CArray

Overloads:

  • #template ⇒ CArray

    Returns a freshly allocated CArray with the same shape and data_type as self, filled with zeros. The new array is an entity and carries no mask.

    Returns:

  • #template(data_type, bytes: 0) ⇒ CArray

    Returns a freshly allocated CArray with the same shape as self but the given data_type, filled with zeros.

    Parameters:

    • data_type (Symbol) —

      target element type (e.g. :int32, :float64, :fixlen).

    • bytes (Integer) (defaults to: 0) —

      element byte size; required for :fixlen, ignored for numeric types.

    Returns:

  • #template({ value }) ⇒ CArray

    With a 0-arity block, fills every element of the result with the block's return value (broadcast). Equivalent to template.tap { |t| t[] = value }.

    Yield Returns:

    • (Object) —

      value to broadcast to every element.

    Returns:

  • #template({ |*idx| ... }) {|idx| ... } ⇒ CArray

    With a block of arity > 0, calls the block once per cell with the multi-dimensional index *idx and stores the result.

    Yield Parameters:

    • idx (Array<Integer>) —

      per-axis indices.

    Yield Returns:

    • (Object)

    Returns:



76
# File 'yard-stubs/carray_copy.rb', line 76

def template(*, **, &block); end

#then_else(x, y) ⇒ CArray

Returns a ternary selection on self (a boolean CArray), reading as "if self then x else y". The boolean 2-way case of #choose that additionally propagates self's mask (UNDEF in self produces UNDEF in the result).

Parameters:

  • x (CArray, Numeric, Object) —

    true-branch value(s).

  • y (CArray, Numeric, Object) —

    false-branch value(s).

Returns:

  • (CArray) —

    new array with the same shape as self.

Raises:

  • (ArgumentError) —

    when self is not a boolean CArray.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/carray/conditional.rb', line 32

def then_else (x, y)
  # Guard: self must be boolean.  Integer / float receiver would be
  # silently reinterpreted by the indexer setter (`result[self] = ...`)
  # as an index array, producing surprising scatter rather than the
  # intended ternary select.  Fail fast.
  unless self.boolean?
    raise ArgumentError,
          "then_else: receiver must be a boolean CArray (data_type == CA_BOOLEAN), got #{self.data_type}"
  end
  # Promote data_type from both branches via CArray.result_type
  # (a CScalar contributes its own data_type, so CA_INT32(0) keeps int32
  # where a bare Ruby Integer would widen to int64).
  dt = CArray.result_type(x, y)
  # A CScalar (scalar? CArray) is treated as a scalar value, not as a
  # self-shaped operand: full CArray -> gather/copy, scalar -> broadcast.
  y_full = y.is_a?(CArray) && !y.scalar?
  result =
    if y_full
      y.data_type == dt ? y.copy : y.to_type(dt)
    else
      CArray.new(dt, self.shape).fill(y.is_a?(CArray) ? y[0] : y)
    end
  x_full = x.is_a?(CArray) && !x.scalar?
  result[self] = x_full ? x[self] : x
  # Propagate cond's mask: UNDEF in self -> UNDEF in result.
  if self.has_mask?
    result[self.is_masked] = UNDEF
  end
  result
end

#tile(*reps) ⇒ CATile

Returns a CATile view of self tiled reps[k] times along each axis k. Accepts either positional args (a.tile(2, 3)) or a single array (a.tile([2, 3])); the number of reps must equal ndim.

Parameters:

  • reps (Array<Integer>) —

    repetition count per axis.

Returns:

Raises:

  • (ArgumentError) —

    when the number of reps does not match ndim.

  • (IndexError) —

    when any reps[k] is not positive.



27
# File 'yard-stubs/ca_obj_tile.rb', line 27

def tile(*reps); end

#time(unit: :ns, origin: nil) ⇒ CATime

Note:

An int64 receiver is wrapped zero-copy. A narrower integer type is widened to int64 first (a copy); a Float / non-integer type raises (cast it explicitly if the truncation is intended).

Returns self as a CATime on the unit grid. With origin nil, self's int64 values are taken as tick indices already anchored to the Unix epoch (zero-copy Face wrap). With origin given, self's indices are relative to origin and are rebased to the epoch (a new int64 array is built; the origin is not stored).

Parameters:

  • unit (Resolution, Symbol, String) (defaults to: :ns) —

    grid resolution.

  • origin (Time, String, Integer, DateTime, CATime::Element, nil) (defaults to: nil) —

    base instant that self's indices are counted from (default: the Unix epoch).

Returns:



1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
# File 'lib/carray/time.rb', line 1853

def time(unit: :ns, origin: nil)
  res = CATime::Resolution.parse(unit)
  src = as_int64_time_storage
  if origin.nil?
    CATime.wrap(src, unit: res)
  else
    o = CATimeLiteral.tick_index(origin, res)
    (src + o).time(unit: res)
  end
end

#timedelta(unit: :ns) ⇒ CATimedelta

Note:

An int64 receiver is wrapped zero-copy; a narrower integer type is widened to int64 first (a copy); a Float / non-integer raises.

Returns self re-wrapped as a zero-copy CATimedelta view with the given unit.

Parameters:

  • unit (Resolution, Symbol, String) (defaults to: :ns) —

    duration resolution.

Returns:



1871
1872
1873
# File 'lib/carray/time.rb', line 1871

def timedelta(unit: :ns)
  CATimedelta.wrap(as_int64_time_storage, unit: unit)
end

#to_a ⇒ Array

Returns a newly allocated Ruby Array containing the element values of self. For ndim >= 2, the result is nested: shape == [2, 3] ⇒ a 2-element Array of 3-element Arrays.

Masked cells materialise as CArray::UNDEF; the mask state itself is not preserved on the result.

Examples:

CArray.float64(2, 3) { |i, j| i + j }.to_a
# => [[0.0, 1.0, 2.0], [1.0, 2.0, 3.0]]

Returns:



19
# File 'yard-stubs/carray_conversion.rb', line 19

def to_a; end

#to_bit_string(nb) ⇒ String

Returns a packed-bit byte string built from self, using nb bits per element.

Parameters:

  • nb (Integer) —

    bits per element.

Returns:

  • (String) —

    byte string of length ceil(nb * elements / 8).



11
12
13
14
15
16
# File 'lib/carray/methods/bit_string.rb', line 11

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

#to_ca(writable: false) ⇒ CArray

Returns self as a CArray, doing the least work possible.

For a CArray (entity or data view), to_ca returns self unchanged — no copy is made. Use #copy when you need an independent owned array. Mutating the result of to_ca may therefore mutate the source.

to_ca is the universal "give me a CArray" entry point. It is also defined on Array / Range / Enumerator::ArithmeticSequence (each builds a 1-D CArray) and on lazy views (CAMonOp, CABinOp, …) where it forces evaluation into a fresh entity.

Because it converts as cheaply as it can — sharing storage where it can, copying where it must — the result alone does not tell you whether writes to it reach the source. writable: true is how a caller states that they do have to: an implementation that can only hand back a detached copy raises instead of returning one, so a write is never swallowed silently. For a CArray, self shares its storage by construction, so the only refusal here is a read-only receiver. This is the contract wrap_writable duck-types on.

Parameters:

  • writable (Boolean) (defaults to: false) —

    when true, demand a result whose writes reach the source.

Returns:

  • (CArray) —

    self (no copy).

Raises:

  • (RuntimeError) —

    when writable: true and self is read-only.



49
# File 'yard-stubs/carray_copy.rb', line 49

def to_ca(writable: false); end

#to_s ⇒ String

Equivalent to dump_binary with no arguments. Returns the raw element bytes of self as a binary String.

Returns:

  • (String)


61
# File 'yard-stubs/carray_conversion.rb', line 61

def to_s; end

#to_type(data_type, bytes: nil) ⇒ CArray

Returns a new entity holding the elements of self converted to data_type (an eager copy that owns its storage). Masked cells are carried across. When data_type is a data_class (a CAStruct subclass) the result is wrapped in CARecord.

When self is an :object array and data_type is an integer or float type, each cell is parsed with Ruby Integer() / Float() rules and a cell that cannot be parsed becomes UNDEF (masked) rather than a silent 0.0 or a raise. This is symmetric for float and int: nil, "", "xx", and (for int targets) a non-integer string such as "1.5" all map to UNDEF. Explicit nan / inf / infinity literals (optional sign, case-insensitive, matched as a whole token) are kept as NaN / ±Infinity.

Parameters:

  • data_type (Symbol, Integer, Class, String) —

    target element type.

  • bytes (Integer, nil) (defaults to: nil) —

    element width in bytes, required for :fixlen.

Returns:



89
# File 'yard-stubs/carray_cast.rb', line 89

def to_type(data_type, bytes: nil); end

#transpose ⇒ CATranspose #transpose(*imap) ⇒ CATranspose

Overloads:

  • #transpose ⇒ CATranspose

    Returns a CATranspose view of self with the dimension order reversed (view.shape[k] == self.shape[ndim-1-k]).

    Returns:

  • #transpose(*imap) ⇒ CATranspose

    Returns a CATranspose view of self permuted by imap, a permutation of 0 ... self.ndim. Element view[i_0, ..., i_{n-1}] aliases parent element with axis k sourced from i at position imap[k].

    Parameters:

    • imap (Array<Integer>) —

      permutation of 0 ... ndim.

    Returns:

    Raises:

    • (ArgumentError) —

      when imap.length != ndim.

    • (RuntimeError) —

      when an entry of imap is out of range or duplicated.



34
# File 'yard-stubs/ca_obj_transpose.rb', line 34

def transpose(*imap); end

#true ⇒ CArray

Returns a boolean CArray of the same shape as self filled with true.

Returns:



141
142
143
# File 'lib/carray/basics.rb', line 141

def true ()
  return template(:boolean) { 1 }
end

#uint16 ⇒ CArray

Returns a :uint16 copy of self. Short-hand of to_type(:uint16).

Returns:



110
# File 'yard-stubs/carray_cast.rb', line 110

def uint16; end

#uint32 ⇒ CArray

Returns a :uint32 copy of self. Short-hand of to_type(:uint32).

Returns:



118
# File 'yard-stubs/carray_cast.rb', line 118

def uint32; end

#uint64 ⇒ CArray

Returns a :uint64 copy of self. Short-hand of to_type(:uint64).

Returns:



126
# File 'yard-stubs/carray_cast.rb', line 126

def uint64; end

#uint8 ⇒ CArray

Returns a :uint8 copy of self. Short-hand of to_type(:uint8).

Returns:



102
# File 'yard-stubs/carray_cast.rb', line 102

def uint8; end

#unfold(window, step: nil) ⇒ Object #unfold(w0, w1, ..., step: nil) ⇒ CAStride

Returns a CAStride view of overlapping windows over the leading S axes, with the remaining ndim - S trailing axes riding along untouched at their original strides — #sliding_windows generalised to arrays that carry non-spatial dimensions such as channels.

The window axes are inserted before the trailing axes, so the result rank is ndim + S. With S == ndim there are no trailing axes and the result is identical to #sliding_windows. Truncate mode; memory is shared with the parent.

Overloads:

  • #unfold(w0, w1, ..., step: nil) ⇒ CAStride

    Returns of rank ndim + window.size.

    Parameters:

    • window (Array<Integer>, Integer) —

      window length for each of the leading axes; its size chooses how many axes are slid over.

    • step (Array<Integer>, Integer, nil) (defaults to: nil) —

      stride between windows; nil means 1.

    Returns:

    • (CAStride) —

      of rank ndim + window.size.

    Raises:

    • (ArgumentError) —

      when the window count is not between 1 and ndim, when a window or step is not positive, when a window is longer than its axis, or when ndim + S exceeds CA_RANK_MAX.



85
# File 'yard-stubs/ca_obj_stride.rb', line 85

def unfold(*window, step: nil); end

#union(other, sort: false) ⇒ CArray

Returns a 1-D CArray of the distinct values appearing in either self or other, in self-then-other first-appearance order. See #intersection for the shared semantics and options.

Parameters:

  • other (CArray, Array, Range) —

    promoted with self.

  • sort (Boolean) (defaults to: false) —

    when true, return the values sorted ascending (a merged, ordered set — e.g. a common time axis).

Returns:

  • (CArray) —

    1-D CArray of the combined distinct values.



90
91
92
93
94
# File 'lib/carray/methods/is_in.rb', line 90

def union (other, sort: false)
  a, b = promote_value_set(other)
  r = a.__send__(:__union__, b)
  sort ? r.sort : r
end

#unique(sort: false) ⇒ CArray

Returns a 1-D CArray of the distinct values of self, in first-appearance (row-major flatten) order. This is the compressing counterpart of #mask_duplicates (which marks without compressing): because different fibers may hold different numbers of distinct values, compression is only well-defined over the whole array, so unique is always flat.

Named unique (not uniq) because distinctness is value-based like NumPy / pandas unique: unlike Ruby Array#uniq it collapses all NaN to a single value (see below), so the name avoids promising Array#uniq semantics.

Masked cells do not participate and never appear in the result; an all-masked array yields an empty CArray.

Distinctness follows == for numeric data types, with two float special cases so the result matches value-based expectations: all NaN collapse to a single distinct value (rather than one per cell) and -0.0 / +0.0 are the same value. The value kept for each key is the first one seen, so a leading -0.0 keeps its sign. For CA_OBJECT / CA_FIXLEN distinctness follows Ruby eql? / hash; note that Ruby does not collapse distinct NaN objects, so a CA_OBJECT array of Float NaN is not collapsed (unlike the numeric path).

A time array (CATime / CATimedelta) answers with its own type on its own unit: the distinct values are values, so the array comes back as itself rather than as raw storage ticks.

Parameters:

  • sort (Boolean) (defaults to: false) —

    when true, return the distinct values sorted ascending instead of in first-appearance order.

Returns:

  • (CArray) —

    1-D CArray of the distinct values, same data type as self.



37
38
39
40
41
42
43
44
45
# File 'lib/carray/methods/unique.rb', line 37

def unique (sort: false)
  # Single-pass seen-set hash (C __unique_flat__), one lane per data type family:
  # integer widens to a 64-bit key; float uses the bitwise key with all-NaN
  # collapsed and -0.0 / +0.0 normalized; object keys on rb_hash + rb_eql and
  # fixlen on a byte-hash + memcmp, both reproducing Ruby Hash distinctness.
  # Masked cells are skipped in the kernel.
  levels = __unique_flat__
  sort ? levels.sort : levels
end

#unmask ⇒ self #unmask(fill_value) ⇒ self #unmask(method:, axis: nil) ⇒ self

unmask clears a mask by supplying values. The value source is either a constant (the positional fill_value) or a scan method: that derives values from neighbouring valid cells (mask gap-fill). The two are mutually exclusive: passing both raises ArgumentError.

Overloads:

  • #unmask ⇒ self

    Clears the mask state of every element of self, leaving the stored data values untouched. Mutates self.

    Returns:

    • (self)
  • #unmask(fill_value) ⇒ self

    Clears the mask state and overwrites the data at previously masked positions with fill_value. Mutates self.

    Parameters:

    • fill_value (Object) —

      value to store at each previously masked position. Cast to self.data_type.

    Returns:

    • (self)
  • #unmask(method:, axis: nil) ⇒ self

    Fills masked cells in place from neighbouring valid cells along axis (gap-fill), then clears the filled cells' mask. Mutates self. Leading (:forward) / trailing (:backward) runs of masked cells with no value to carry, and cells outside the valid range (:linear), stay masked — so a mask may remain.

    Parameters:

    • method (Symbol) —

      fill rule: :forward / :ffill carries the last valid value forward; :backward / :bfill carries the next valid value backward (defined for every data_type — numeric, complex, bool, object, fixlen, and Face); :linear interpolates each masked cell linearly by index from the two bracketing valid cells (numeric data_type, or a time Face — CATime / CATimedelta interpolate through their own linear_fetch, so the filled values stay on the array's unit and are rounded to it).

    • axis (Integer, nil) (defaults to: nil) —

      scan axis (single axis). nil flattens.

    Returns:

    • (self)


96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'yard-stubs/carray_mask.rb', line 96

def unmask (fill = MASK_FILL_UNSET, method: nil, axis: nil)
  if method
    unless fill.equal?(MASK_FILL_UNSET)
      raise ArgumentError,
            "unmask: pass either a constant fill value or method:, not both"
    end
    held = __gap_fill__(method, axis)
    # Copy the filled values in place.  A Face writes through its storage: a
    # bulk store into its surface would try to cast the storage values to the
    # surface type (int64 ticks to fixlen, for a time array).
    if face?
      parent.value[] = held.parent.value
    else
      value[] = held.value
    end
    if held.has_mask?
      self.mask = held.mask              # residual leading/trailing mask
    else
      __unmask_const__                   # fully filled: drop the mask
    end
    return self
  end
  fill.equal?(MASK_FILL_UNSET) ? __unmask_const__ : __unmask_const__(fill)
end

#valid_addr?(addr) ⇒ Boolean

Returns true if addr is in range 0...elements for self.

Parameters:

  • addr (Integer) —

    flat address into the contiguous element sequence.

Returns:

  • (Boolean)


22
# File 'yard-stubs/carray_test.rb', line 22

def valid_addr?(addr); end

#valid_index?(*idx) ⇒ Boolean

Returns true if the given index tuple is in range for self. The number of indices must equal ndim.

Parameters:

  • idx (Array<Integer>) —

    one index per axis.

Returns:

  • (Boolean)

Raises:

  • (ArgumentError) —

    if the number of indices does not match ndim.



15
# File 'yard-stubs/carray_test.rb', line 15

def valid_index?(*idx); end

#validity_bits ⇒ CArray?

Returns a packed uint8 CArray where bit i is 1 iff cell i of the receiver is not masked (LSB-first, length ceil(elements / 8)). Returns nil when the receiver has no mask; consumers such as Arrow treat a missing bitmap as "all valid", so nil is the correct omission-signalling value. Equivalent to is_not_masked.pack_bits when a mask is present.

Returns:

  • (CArray, nil) —

    uint8 CArray of shape [ceil(elements / 8)], or nil when no mask is set.



87
88
89
90
# File 'lib/carray/methods/bit_string.rb', line 87

def validity_bits
  return nil unless has_mask?
  is_not_masked.reshape(-1).pack_bits
end

#value ⇒ CArray

Returns a new view that exposes the underlying data of self, bypassing the mask. The returned view itself cannot carry a mask (value_array? == true).

Use this to read or write the data slot of masked elements.

Returns:



31
# File 'yard-stubs/carray_mask.rb', line 31

def value; end

#value_array? ⇒ Boolean

Returns true if self is a value array (the .value view of a masked array).

Returns:

  • (Boolean)


191
# File 'yard-stubs/carray_attribute.rb', line 191

def value_array?; end

#value_counts(sort: false) ⇒ Array(CArray, CArray)

Returns [values, counts], the distinct values of self paired with the number of times each occurs. values is a 1-D CArray of self's data type; counts is a 1-D CA_INT64 where counts[i] is the number of occurrences of values[i]. This is the frequency- table member of the value-hash discovery family (#unique, #mask_duplicates, #nunique); like #unique it always flattens, because per-fiber distinct counts would be ragged.

By default the pairs are in first-appearance (row-major flatten) order, matching #unique. sort: reorders both arrays together:

  • false (default) — first-appearance order.
  • :count — descending frequency; ties keep first-appearance order (deterministic).
  • :value — ascending value (float NaN sorts last, as in unique(sort: true)).

Masked cells do not participate and never appear; an all-masked array yields two empty CArrays.

Numeric distinctness follows == with two float special cases so the result matches value-based expectations: all NaN collapse to a single value (their counts add up) and -0.0 / +0.0 are the same value (the first-seen value is kept, so a leading -0.0 keeps its sign). For CA_OBJECT / CA_FIXLEN distinctness follows Ruby eql? / hash; Ruby does not collapse distinct NaN objects, so a CA_OBJECT array of Float NaN is not collapsed (unlike numeric).

The values keep self's type (a CATime comes back as a CATime on its own unit); the counts are always a plain :int64 CArray.

Parameters:

  • sort (false, :count, :value) (defaults to: false) —

    pair ordering.

Returns:



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/carray/methods/value_counts.rb', line 37

def value_counts (sort: false)
  unless [false, :count, :value].include?(sort)
    raise ArgumentError, "value_counts: sort must be false, :count, or :value"
  end
  # Single-pass frequency-table hash (C __value_counts_flat__), one lane per
  # data type family: integer widens to a 64-bit key; float uses the bitwise key
  # with all NaN collapsed and -0.0 / +0.0 normalized; object keys on rb_hash +
  # rb_eql and fixlen on a byte-hash + memcmp, both reproducing Ruby Hash
  # distinctness. Masked cells are skipped in the kernel.
  values, counts = __value_counts_flat__
  case sort
  when :count
    # Descending count, ties broken by first-appearance index (stable).
    c = counts.to_a
    order = (0...c.size).sort_by { |i| [-c[i], i] }
    [ values[CArray.int64(order.size) { |i| order[i] }],
      counts[CArray.int64(order.size) { |i| order[i] }] ]
  when :value
    # Ascending value; NaN (numeric) or non-comparable last. Build the
    # permutation with an explicit NaN-last key so float NaN doesn't blow up
    # the Ruby sort, then gather both arrays through it.
    v = values.to_a
    order = (0...v.size).sort_by do |i|
      x = v[i]
      nan = x.is_a?(Float) && x.nan?
      [nan ? 1 : 0, nan ? 0 : x, i]
    end
    [ values[CArray.int64(order.size) { |i| order[i] }],
      counts[CArray.int64(order.size) { |i| order[i] }] ]
  else
    [values, counts]
  end
end

#virtual? ⇒ Boolean

Returns true if self is a virtual array (a view, not an entity).

Returns:

  • (Boolean)


163
# File 'yard-stubs/carray_attribute.rb', line 163

def virtual?; end

#where ⇒ CArray

Returns a fresh 1-D CArray of flat addresses where self is non-zero (or true). Masked positions are excluded. Non-boolean arrays are first coerced to boolean.

Examples:

CArray.int32(5) { [0, 1, 0, 2, 0] }.where.to_a
# => [1, 3]

Returns:

  • (CArray) —

    1-D, :int64 (ca_size_t).



16
# File 'yard-stubs/carray_generate.rb', line 16

def where; end

#window(*ranges, fill_value: 0, bounds: "fill") ⇒ CAWindow

Returns a CAWindow view of self covering ranges — one range per axis, which may extend past either end of the parent. Cells inside the parent alias it, so writes through the view reach the parent; cells outside take fill_value (default 0), and fill_value: UNDEF masks them instead.

Only unit-step ranges are accepted, and each range must run forward, so the 0..-1 end-relative notation cannot be used here.

Parameters:

  • ranges (Array<Range, Integer>) —

    one range per axis; the count must equal self.ndim.

  • fill_value (Object) (defaults to: 0) —

    value given to out-of-range cells; UNDEF masks them instead.

  • bounds (String) (defaults to: "fill") —

    what an out-of-range index means: "fill" (default) uses fill_value, "nearest" clamps to the edge cell, "ruby" reads negative indices from the far end, "strict" raises. "mask" masks the cell but warns — pass fill_value: UNDEF instead.

Returns:

Raises:

  • (ArgumentError) —

    when the number of ranges does not equal ndim, when a range has a step other than 1 or runs backwards, when a block is passed (the block form was removed in 3.0), or when bounds is "periodic" / "reflect" (both removed in 3.0; use #roll for a cyclic shift).

  • (IndexError) —

    when a range selects zero cells.

  • (RuntimeError) —

    when bounds conflicts with fill_value: UNDEF, or when bounds is not a recognised value.



46
# File 'yard-stubs/ca_obj_window.rb', line 46

def window(*ranges, fill_value: 0, bounds: "fill"); end

#windows(*ranges, bounds: :skip, fill_value: nil) ⇒ CAWindowIterator

Returns a CAWindowIterator rolling a per-axis offset window over self. Each ranges[i] is a lo..hi offset span (a.windows(-1..1) is a centred width-3 window); bounds: selects the margin policy. With no ranges (a.windows(a.window(...)) passing a CAWindow view) the geometry is read from the view for backward compatibility.

Parameters:

  • ranges (Array<Range>) —

    per-axis offset ranges.

  • bounds (Symbol) (defaults to: :skip) —

    :skip / :nearest / :truncate.

  • fill_value (Object, nil) (defaults to: nil) —

    constant margin value.

Returns:



921
922
923
924
925
926
# File 'lib/carray/window_iterator.rb', line 921

def windows (*ranges, bounds: :skip, fill_value: nil)
  if ranges.size == 1 && ranges[0].is_a?(CArray) && ranges[0].obj_type == CA_OBJ_WINDOW
    return CAWindowIterator.new(ranges[0])
  end
  CAWindowIterator.new(self, *ranges, bounds: bounds, fill_value: fill_value)
end