carray 3.0.5 → 3.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +343 -0
  3. data/README.md +25 -4
  4. data/carray.gemspec +3 -2
  5. data/ext/ca_axis_dispatch.c +6 -0
  6. data/ext/ca_axis_group.c +7 -7
  7. data/ext/ca_binop_dispatch.c +8 -0
  8. data/ext/ca_binop_dispatch.h +1 -0
  9. data/ext/ca_categorical_iterator.c +14 -14
  10. data/ext/ca_kernel_iterator.c +116 -231
  11. data/ext/ca_kernel_iterator.h +416 -258
  12. data/ext/ca_obj_array.c +4 -4
  13. data/ext/ca_obj_bincmp.c +28 -4
  14. data/ext/ca_obj_binop.c +46 -12
  15. data/ext/ca_obj_bitarray.c +2 -4
  16. data/ext/ca_obj_bitfield.c +88 -4
  17. data/ext/ca_obj_byte_swap.c +4 -4
  18. data/ext/ca_obj_const_string.c +422 -257
  19. data/ext/ca_obj_face.c +73 -33
  20. data/ext/ca_obj_fake.c +114 -13
  21. data/ext/ca_obj_farray.c +7 -1
  22. data/ext/ca_obj_fixlen_string.c +51 -17
  23. data/ext/ca_obj_grid.c +179 -19
  24. data/ext/ca_obj_meld.c +74 -118
  25. data/ext/ca_obj_moncmp.c +9 -1
  26. data/ext/ca_obj_monop.c +100 -36
  27. data/ext/ca_obj_object.c +63 -29
  28. data/ext/ca_obj_reduce.c +17 -5
  29. data/ext/ca_obj_refer.c +162 -23
  30. data/ext/ca_obj_remap.c +69 -10
  31. data/ext/ca_obj_repeat.c +1 -1
  32. data/ext/ca_obj_roll.c +3 -4
  33. data/ext/ca_obj_select.c +12 -7
  34. data/ext/ca_obj_select_axis.c +9 -6
  35. data/ext/ca_obj_shift.c +1 -0
  36. data/ext/ca_obj_stack.c +315 -116
  37. data/ext/ca_obj_stride.c +177 -53
  38. data/ext/ca_obj_string.c +20 -4
  39. data/ext/ca_obj_tile.c +3 -4
  40. data/ext/ca_obj_triop.c +24 -13
  41. data/ext/ca_obj_window.c +23 -15
  42. data/ext/ca_op_ipower.c +71 -23
  43. data/ext/ca_op_powi.h +6 -29
  44. data/ext/ca_sort_kernels.h +3 -0
  45. data/ext/ca_sweep_engine.c +90 -23
  46. data/ext/ca_sweep_engine.h +5 -6
  47. data/ext/caframe_csv_reader.c +2 -2
  48. data/ext/carray.h +5 -2
  49. data/ext/carray_access.c +125 -103
  50. data/ext/carray_address_basis.c +209 -1
  51. data/ext/carray_attribute.c +8 -0
  52. data/ext/carray_broadcast.c +5 -6
  53. data/ext/carray_build_flags.h +1 -1
  54. data/ext/carray_call_cfunc.c +5 -8
  55. data/ext/carray_cast.c +319 -48
  56. data/ext/carray_cast_func.rb +37 -5
  57. data/ext/carray_conversion.c +65 -7
  58. data/ext/carray_copy.c +24 -0
  59. data/ext/carray_core.c +874 -72
  60. data/ext/carray_count.c +28 -9
  61. data/ext/carray_element.c +22 -12
  62. data/ext/carray_factorize.c +11 -11
  63. data/ext/carray_histogram.c +27 -5
  64. data/ext/carray_index_classifier.c +7 -5
  65. data/ext/carray_internal.h +241 -12
  66. data/ext/carray_kernels_bincmp.c +2007 -3
  67. data/ext/carray_kernels_binop.c +25502 -5336
  68. data/ext/carray_kernels_init.c +22 -22
  69. data/ext/carray_kernels_monop.c +10739 -3771
  70. data/ext/carray_kernels_reduce_aggregate.c +4429 -702
  71. data/ext/carray_kernels_reduce_boolean.c +1533 -15
  72. data/ext/carray_kernels_reduce_cumulative.c +1808 -248
  73. data/ext/carray_kernels_reduce_extreme.c +4508 -511
  74. data/ext/carray_kernels_reduce_variance.c +2284 -152
  75. data/ext/carray_kernels_scan.c +240 -240
  76. data/ext/carray_kernels_search.c +4211 -264
  77. data/ext/carray_kernels_sort.c +367 -450
  78. data/ext/carray_lazy.c +63 -1
  79. data/ext/carray_loop.c +10 -3
  80. data/ext/carray_mask.c +247 -149
  81. data/ext/carray_median_percentile.c +17 -12
  82. data/ext/carray_memory_view.c +54 -29
  83. data/ext/carray_operator.c +219 -55
  84. data/ext/carray_order.c +55 -11
  85. data/ext/carray_partition.c +1 -1
  86. data/ext/carray_random.c +5 -2
  87. data/ext/carray_round.c +24 -1
  88. data/ext/carray_scatter.c +4 -0
  89. data/ext/carray_segment.c +1 -1
  90. data/ext/carray_slab.c +110 -25
  91. data/ext/carray_sort.c +7 -4
  92. data/ext/carray_sort_kernel.c +24 -0
  93. data/ext/carray_struct.c +21 -6
  94. data/ext/carray_test.c +154 -53
  95. data/ext/carray_time_text.c +8 -2
  96. data/ext/carray_utils.c +124 -54
  97. data/ext/extconf.rb +11 -0
  98. data/ext/mk_call_cfunc.rb +6 -11
  99. data/ext/mkkernel.rb +383 -121
  100. data/ext/ruby_carray.c +4 -1
  101. data/ext/version.h +4 -4
  102. data/lib/carray/attribute.rb +25 -1
  103. data/lib/carray/autoload_carray.rb +3 -3
  104. data/lib/carray/autoload_method_extension.rb +5 -3
  105. data/lib/carray/axis_group.rb +22 -13
  106. data/lib/carray/basics.rb +27 -9
  107. data/lib/carray/bincount_nd.rb +8 -2
  108. data/lib/carray/block_iterator.rb +65 -24
  109. data/lib/carray/categorical.rb +27 -16
  110. data/lib/carray/categorical_iterator.rb +4 -3
  111. data/lib/carray/complex.rb +2 -2
  112. data/lib/carray/conditional.rb +55 -6
  113. data/lib/carray/const_string.rb +74 -0
  114. data/lib/carray/construct.rb +2 -2
  115. data/lib/carray/core_extensions.rb +19 -68
  116. data/lib/carray/data_type_extension.rb +1 -0
  117. data/lib/carray/fixlen_string.rb +83 -1
  118. data/lib/carray/frame/column_verbs.rb +102 -16
  119. data/lib/carray/frame/concat.rb +50 -6
  120. data/lib/carray/frame/convert.rb +19 -0
  121. data/lib/carray/frame/csv_parser.rb +45 -36
  122. data/lib/carray/frame/describe.rb +4 -2
  123. data/lib/carray/frame/frame.rb +436 -83
  124. data/lib/carray/frame/group.rb +731 -78
  125. data/lib/carray/frame/io.rb +216 -73
  126. data/lib/carray/frame/join.rb +166 -43
  127. data/lib/carray/frame/records.rb +9 -7
  128. data/lib/carray/frame/reshape.rb +109 -11
  129. data/lib/carray/frame/sort.rb +57 -9
  130. data/lib/carray/frame/verbs.rb +448 -60
  131. data/lib/carray/frame/windows.rb +71 -9
  132. data/lib/carray/fuse_source.rb +4 -2
  133. data/lib/carray/inspect.rb +7 -2
  134. data/lib/carray/iterator.rb +40 -0
  135. data/lib/carray/key_windows.rb +10 -4
  136. data/lib/carray/lazy.rb +28 -24
  137. data/lib/carray/mask_gap_fill.rb +37 -17
  138. data/lib/carray/meld_reduce.rb +1 -1
  139. data/lib/carray/methods/bin.rb +3 -0
  140. data/lib/carray/methods/choose.rb +3 -2
  141. data/lib/carray/methods/composition.rb +1 -1
  142. data/lib/carray/methods/factorize.rb +2 -0
  143. data/lib/carray/methods/gather_nd.rb +4 -1
  144. data/lib/carray/methods/is_in.rb +23 -3
  145. data/lib/carray/methods/locate_addr.rb +63 -12
  146. data/lib/carray/methods/meshgrid.rb +3 -1
  147. data/lib/carray/methods/repeat.rb +11 -1
  148. data/lib/carray/record_order.rb +35 -6
  149. data/lib/carray/runtime.rb +57 -8
  150. data/lib/carray/segment_iterator.rb +42 -24
  151. data/lib/carray/serialize.rb +56 -17
  152. data/lib/carray/slab_iterator.rb +1 -1
  153. data/lib/carray/stack.rb +21 -9
  154. data/lib/carray/string.rb +6 -6
  155. data/lib/carray/string_operation_extension.rb +25 -4
  156. data/lib/carray/struct_builder.rb +4 -1
  157. data/lib/carray/time.rb +195 -46
  158. data/lib/carray/window_iterator.rb +64 -16
  159. data/yard-stubs/ca_obj_array.rb +26 -1
  160. data/yard-stubs/ca_obj_bitfield.rb +4 -1
  161. data/yard-stubs/ca_obj_refer.rb +3 -0
  162. data/yard-stubs/ca_obj_window.rb +2 -1
  163. data/yard-stubs/carray_access.rb +4 -2
  164. data/yard-stubs/carray_cast.rb +14 -5
  165. data/yard-stubs/carray_conversion.rb +8 -2
  166. data/yard-stubs/carray_count.rb +6 -3
  167. data/yard-stubs/carray_mask.rb +20 -1
  168. data/yard-stubs/carray_math.rb +36 -16
  169. data/yard-stubs/carray_memory_view.rb +7 -0
  170. data/yard-stubs/carray_order.rb +6 -0
  171. data/yard-stubs/carray_scatter.rb +2 -1
  172. data/yard-stubs/carray_test.rb +23 -7
  173. metadata +17 -3
data/ext/ruby_carray.c CHANGED
@@ -14,6 +14,7 @@
14
14
  ---------------------------------------------------------------------------- */
15
15
 
16
16
  #include "carray.h"
17
+ #include "carray_internal.h"
17
18
  #include "carray_build_flags.h"
18
19
  #include "version.h"
19
20
 
@@ -313,7 +314,7 @@ Init_carray_ext (void)
313
314
  Init_carray_sort(); /* sort / sort_copy / sort_addr / axis2addr */
314
315
  Init_carray_count();
315
316
  Init_carray_kernels(); /* mkkernel-generated: reductions + maps */
316
- Init_carray_round(); /* round(ndigits); after the generated round */
317
+ Init_carray_round(); /* round(ndigits) / round!(ndigits) */
317
318
 
318
319
  Init_carray_utils();
319
320
 
@@ -394,5 +395,7 @@ Init_carray_ext (void)
394
395
  Init_carray_slab();
395
396
 
396
397
  Init_carray_address_basis();
398
+
399
+ ca_obj_num_builtin = ca_obj_num;
397
400
  }
398
401
 
data/ext/version.h CHANGED
@@ -1,6 +1,6 @@
1
- #define CA_VERSION "3.0.5"
2
- #define CA_VERSION_CODE 30005
1
+ #define CA_VERSION "3.0.7"
2
+ #define CA_VERSION_CODE 30007
3
3
  #define CA_VERSION_MAJOR 3
4
4
  #define CA_VERSION_MINOR 0
5
- #define CA_VERSION_TEENY 5
6
- #define CA_VERSION_DATE "2026/10/20"
5
+ #define CA_VERSION_TEENY 7
6
+ #define CA_VERSION_DATE "2026/11/03"
@@ -6,6 +6,7 @@
6
6
  # ca.set_attr(:unit, "m/s") # => setter; writes to self's @attr
7
7
  # ca.set_attrs(other.attrs) # => sets every key of a Hash at once
8
8
  # ca.attrs # => frozen shallow clone of the full Hash
9
+ # ca.attrs_symkey # => the same, with Symbol keys (nested too)
9
10
  # ca.has_attr? # => any attribute present?
10
11
  # ca.has_attr?(:unit) # => specific key present?
11
12
  #
@@ -162,6 +163,15 @@ class CArray
162
163
  (merged || {}).freeze
163
164
  end
164
165
 
166
+ # @overload attrs_symkey
167
+ # Returns {#attrs} with its keys as Symbols, frozen. The keys of
168
+ # Hashes nested in the values, inside Arrays too, become Symbols
169
+ # as well.
170
+ # @return [Hash{Symbol => Object}]
171
+ def attrs_symkey
172
+ return CArray.__send__(:attr_symbolize_keys, self.attrs)
173
+ end
174
+
165
175
  # @overload has_attr?
166
176
  # Returns whether `self` (or any parent view) has any attribute
167
177
  # set.
@@ -317,6 +327,20 @@ class CArray
317
327
  v
318
328
  end
319
329
  end
320
- private_class_method :attr_normalize_key, :attr_validate_value, :attr_coerce_value
330
+ # A stored value with the keys of every Hash in it as Symbols, frozen
331
+ # as the stored value is.
332
+ def self.attr_symbolize_keys (v)
333
+ case v
334
+ when Array then v.map { |e| attr_symbolize_keys(e) }.freeze
335
+ when Hash
336
+ v.each_with_object({}) do |(k, vv), h|
337
+ h[k.to_sym] = attr_symbolize_keys(vv)
338
+ end.freeze
339
+ else
340
+ v
341
+ end
342
+ end
343
+ private_class_method :attr_normalize_key, :attr_validate_value, :attr_coerce_value,
344
+ :attr_symbolize_keys
321
345
 
322
346
  end
@@ -32,12 +32,12 @@ class CArray
32
32
  autoload_method "marshal_load", serialize_rb
33
33
  end
34
34
 
35
- # A view, a wrap and a scalar are marshalled through _dump / self._load,
35
+ # A view, a mask, a wrap and a scalar are marshalled through _dump / self._load,
36
36
  # which return a new array: with marshal_dump Marshal records the class and
37
37
  # loads into an empty instance of it, which the plain array the payload
38
38
  # holds cannot become. A record array keeps marshal_dump, under which it
39
39
  # already round-trips with its class.
40
- [CAView, CAWrap, CScalar].each do |klass|
40
+ [CAView, CAWrap, CScalar, CArrayMask, CAObjectMask].each do |klass|
41
41
  klass.class_eval do
42
42
  undef_method :marshal_dump
43
43
  autoload_method "_dump", "carray/serialize"
@@ -137,7 +137,7 @@ autoload :CAUnion, "carray/struct"
137
137
  # ---- CAFrame (DataFrame over CArray columns) -------------------------------
138
138
  #
139
139
  # The frame is only reached through the CAFrame constant (CAFrame.new /
140
- # .from_csv / subclassing) or GroupedFrame (obtained from CAFrame#group_by,
140
+ # .read_csv / subclassing) or GroupedFrame (obtained from CAFrame#group_by,
141
141
  # by which point CAFrame is already loaded). Both constants live in the same
142
142
  # require bundle (carray/frame.rb), so autoloading either loads the whole
143
143
  # frame. Nothing in the eager core references them, so it loads on first use.
@@ -31,9 +31,11 @@ module AutoloadMethodExtension
31
31
 
32
32
  private
33
33
 
34
- def autoload_define (target, name, library, original_spec)
35
- library = Ractor.make_shareable(library.to_s.dup)
36
- original_spec = Ractor.make_shareable(original_spec.to_s.dup)
34
+ def autoload_define (target, name, library_given, spec_given)
35
+ # The stub reads these two, so they are never assigned again: Ruby 4.0
36
+ # refuses to make a Proc shareable when a variable it reads may be.
37
+ library = Ractor.make_shareable(library_given.to_s.dup)
38
+ original_spec = Ractor.make_shareable(spec_given.to_s.dup)
37
39
  # Shareable, so the stub answers in any Ractor. Only the main Ractor
38
40
  # loads the library: Ractors that require at the same time can deadlock
39
41
  # (Ruby 3.4), so another Ractor is told what to load there instead.
@@ -409,7 +409,7 @@ class CAGroupIterator
409
409
  # except for a band folded into the count, which has no route but the
410
410
  # engine.
411
411
  def core_counts? (kw)
412
- return false if CArray.__fast_paths_enabled__
412
+ return false if CArray.__fast_paths_enabled__(:axis_group_count_kernel)
413
413
  has_group, fused = AxisGroup.parse_axis(kw[:axis])
414
414
  has_group && fused.empty?
415
415
  end
@@ -494,8 +494,8 @@ class CAGroupIterator
494
494
  # Weighted mean = Sum(v*w) / Sum(w), both over the combined present-set. The
495
495
  # `value*0 + weights` denominator carries the same value|weight mask, so its
496
496
  # group-sum is Sum(w) over exactly the cells value*weight used. An empty group
497
- # (no present pair) is UNDEF (matching CArray#wmean); a present group whose
498
- # weights sum to zero yields NaN/Inf (core's 0/0).
497
+ # (no present pair) and a group whose weights sum to zero are UNDEF, as
498
+ # CArray#wmean leaves both.
499
499
  def wmean (weights, **kw)
500
500
  has_group, = AxisGroup.parse_axis(kw[:axis])
501
501
  return value.wmean(weights, **kw) unless has_group
@@ -508,7 +508,7 @@ class CAGroupIterator
508
508
  # No present pair is UNDEF (an empty group), set on the denominator so
509
509
  # the division never meets an empty group's 0 / 0.
510
510
  den = den.copy
511
- den[cnt.eq(0)] = UNDEF
511
+ den[cnt.eq(0).or(den.eq(0))] = UNDEF
512
512
  # min_count: counts the present pairs, as the core wmean does.
513
513
  pairs = regroup(prod, spec)
514
514
  pairs.finish_reduction(:wmean, kw, num / den)
@@ -846,16 +846,19 @@ class CAGroupIterator
846
846
  place = Array.new(gslots.size, 1) # place value per slot
847
847
  (gslots.size - 2).downto(0) { |i| place[i] = place[i + 1] * gslots[i + 1][:k] }
848
848
  comp = nil
849
+ groups = kdims.inject(1, :*)
849
850
  gslots.each_with_index do |m, i|
850
851
  target = Array.new(gb_rank, 1)
851
852
  m[:axes].each { |a| target[gaxes.index(a)] = shape[a] }
852
853
  term = m[:codes].reshape(*target)
854
+ # The composite code has to reach the last group in the codes' type.
855
+ term = term.int64 if groups > CACategorical::MAX_LABELS[term.data_type]
853
856
  term = term * place[i] if place[i] != 1
854
857
  comp = comp.nil? ? term : comp + term
855
858
  end
856
859
  gb_size = gaxes.map { |a| shape[a] }.inject(1, :*)
857
860
  ccat = CACategorical.from_codes(comp.reshape(gb_size),
858
- CArray.int32(kdims.inject(1, :*)).seq!)
861
+ CArray.int32(groups).seq!)
859
862
  [ccat, kdims, gslots, bslots, gaxes]
860
863
  end
861
864
 
@@ -863,7 +866,7 @@ class CAGroupIterator
863
866
  # pass. With the fast paths off it goes through the band loop instead,
864
867
  # which then has one position.
865
868
  def whole_block? (bslots)
866
- bslots.empty? && CArray.__fast_paths_enabled__
869
+ bslots.empty? && CArray.__fast_paths_enabled__(:axis_group_whole_block)
867
870
  end
868
871
 
869
872
  # Iterate the band positions of a band-preserving grouping. For each band
@@ -923,9 +926,15 @@ class CAGroupIterator
923
926
  # paths off (a development build run with CARRAY_GENERAL_PATH set) each
924
927
  # group is reduced by the core instead -- except a band folded into the
925
928
  # statistic (+fused+), which has no route but the kernel.
929
+ #
930
+ # With no band axis the core groups the whole value in one pass, which is
931
+ # faster than the kernel for every group size (1M cells on an M2 Max: 7.5
932
+ # to 12.5 ms against 15 ms), so the kernel is taken only with a band.
926
933
  def kernel_reads_value? (fused = [])
927
934
  return false if value.face? || ! (value.integer? || value.float?)
928
- CArray.__fast_paths_enabled__ || ! fused.empty?
935
+ return true unless fused.empty?
936
+ return false if spec.slot_meta.none? { |m| m[:kind] == :band }
937
+ CArray.__fast_paths_enabled__(:axis_group_reduce_kernel)
929
938
  end
930
939
 
931
940
  # Whether the scan kernel gives the core's answer: it reads an integer,
@@ -933,8 +942,8 @@ class CAGroupIterator
933
942
  # float64 (an object in object), cummax / cummin in the payload's data type
934
943
  # and cumcount in int64 -- not the core's answer for a boolean's running sum.
935
944
  def kernel_scans? (op)
936
- return false unless CArray.__fast_paths_enabled__
937
- return false if value.face? || value.complex?
945
+ return false unless CArray.__fast_paths_enabled__(:axis_group_scan_kernel)
946
+ return false if value.face? || value.complex? || value.data_type == CA_FIXLEN
938
947
  return true if value.object? || op == :cumcount
939
948
  core = CAIterator.core_probe(value).public_send(op).data_type
940
949
  kernel = [:cumsum, :cumprod].include?(op) ? CA_FLOAT64 : value.data_type
@@ -971,10 +980,10 @@ class CAGroupIterator
971
980
  end
972
981
 
973
982
  # An array of +shape+ of the same kind as +model+ -- its data type, or its
974
- # Face -- with every cell UNDEF. A read-only Face cannot be written cell by
975
- # cell, so its values are held in an object array.
983
+ # Face -- with every cell UNDEF. A Face that holds no new value cannot be
984
+ # written cell by cell, so its values are held in an object array.
976
985
  def blank_of (model, shape)
977
- out = if model.face? && model.read_only?
986
+ out = if model.face? && !model.__send__(:holds_new_values?)
978
987
  CArray.new(CA_OBJECT, shape)
979
988
  else
980
989
  model.__send__(:blank_like, shape)
@@ -1052,7 +1061,7 @@ class CAGroupIterator
1052
1061
  gb_rank = gaxes.size
1053
1062
  gb_shape = gaxes.map { |a| shape[a] }
1054
1063
  gb_size = gb_shape.inject(1, :*)
1055
- nvalid = ccat.category_sizes.int64.sum
1064
+ nvalid = ccat.category_sizes.int64.sum.to_i
1056
1065
  nband = bslots.map { |m| m[:len] }.inject(1, :*)
1057
1066
  out = CArray.int64(nband * nvalid)
1058
1067
  cursor = 0
data/lib/carray/basics.rb CHANGED
@@ -122,7 +122,7 @@ class CArray
122
122
  # @return [CArray] view with reduced `ndim`.
123
123
  def drop_axis
124
124
  if ndim == 1
125
- return self[]
125
+ return scalar? ? self : self[]
126
126
  else
127
127
  newdim = shape.reject{|x| x == 1 }
128
128
  newdim = [1] if newdim.empty? # every axis has size 1: keep one
@@ -162,6 +162,10 @@ class CArray
162
162
  lfill = fill_value if lfill.nil?
163
163
  ufill = fill_value if ufill.nil?
164
164
  out = copy
165
+ # Whatever is written must fit: a finer time, a wider fixed string.
166
+ [min, max, lfill, ufill].each { |v|
167
+ out, = branches_in_common(out, v) unless v.nil? || UNDEF.equal?(v)
168
+ }
165
169
  out[self < min] = lfill.nil? ? min : lfill unless min.nil?
166
170
  out[self > max] = ufill.nil? ? max : ufill unless max.nil?
167
171
  out
@@ -170,6 +174,12 @@ class CArray
170
174
  # An array of +shape+ of the same kind as self: its data type and cell
171
175
  # width, or its Face over a zero storage. Nothing is written into it, so
172
176
  # it can be built for a read-only Face too.
177
+ # Whether a cell can be given a value it has not seen. Not a CAConstString,
178
+ # whose strings share a buffer, or a CACategorical, whose codes index a
179
+ # vocabulary. A view that is read-only can still hold them: it is only
180
+ # that view that cannot be written.
181
+ private def holds_new_values? = true
182
+
173
183
  private def blank_like (shape)
174
184
  storage = face_storage
175
185
  out = CArray.new(storage.data_type, shape, bytes: storage.bytes)
@@ -334,7 +344,8 @@ class CArray
334
344
  # masked: a missing bound is not read as either, so fill it first.
335
345
  #
336
346
  # Boundary is strict `[min, max]`: values equal to a bound
337
- # remain unchanged in both the clamped and filled variants.
347
+ # remain unchanged in both the clamped and filled variants. A NaN
348
+ # is in neither range and stays NaN.
338
349
  #
339
350
  # @param min [Numeric, nil] lower bound; `nil` for one-sided
340
351
  # clip above.
@@ -597,14 +608,14 @@ class CArray
597
608
  # reductions do: each block value is written into a blank of the Face
598
609
  # (which reads a CATime::Element, a string, a Face array ...) and handed
599
610
  # to the slab engine as the storage it became; the result is lifted back
600
- # at the end. A read-only Face has no blank to write into, so its values
601
- # are collected as the surface objects they are. A `data_type:` from the
602
- # caller is the caller's, and passes through.
611
+ # at the end. A Face that holds no new value has no blank to write into,
612
+ # so its values are collected as the surface objects they are. A
613
+ # `data_type:` from the caller is the caller's, and passes through.
603
614
  module FaceSlabResult
604
615
  def map_slab (**kw, &block)
605
616
  return super unless face? && kw[:data_type].nil? && block
606
- return super(**kw, data_type: :object, &block) if read_only?
607
- out = super(**kw, data_type: face_storage.data_type) { |slab|
617
+ return super(**kw, data_type: :object, &block) unless holds_new_values?
618
+ out = super(**kw, **face_slab_type) { |slab|
608
619
  face_slab_storage(block.call(slab), slab.shape)
609
620
  }
610
621
  out.face_lift(self)
@@ -612,10 +623,10 @@ class CArray
612
623
 
613
624
  def reduce_slab (**kw, &block)
614
625
  return super unless face? && kw[:data_type].nil? && block
615
- return super(**kw, data_type: :object, &block) if read_only?
626
+ return super(**kw, data_type: :object, &block) unless holds_new_values?
616
627
  fiber = kw.key?(:init)
617
628
  init = kw.delete(:init)
618
- out = super(**kw, data_type: face_storage.data_type) { |slab|
629
+ out = super(**kw, **face_slab_type) { |slab|
619
630
  value = if fiber
620
631
  slab.to_a.flatten.inject(init) { |acc, e| block.call(acc, e) }
621
632
  else
@@ -628,6 +639,13 @@ class CArray
628
639
 
629
640
  private
630
641
 
642
+ # The engine's output type. Fixlen storage is named by leaving it out: the
643
+ # name alone has no width, and the source's is the one wanted.
644
+ def face_slab_type
645
+ storage = face_storage
646
+ storage.data_type == CA_FIXLEN ? {} : { data_type: storage.data_type }
647
+ end
648
+
631
649
  def face_slab_storage (value, shape)
632
650
  cell = blank_like(shape)
633
651
  cell[] = value
@@ -238,7 +238,10 @@ class CArray
238
238
  ext_sizes = @lengths.map { |l| l + 1 } # +1: upper overflow cell
239
239
  strides_ext = ext_sizes.each_with_index.map { |_, k| ext_sizes[(k + 1)..].inject(1, :*) }
240
240
  total_ext = ext_sizes.inject(:*)
241
- widen = total_ext > 0x7fffffff # int64 flat for big joint tables
241
+ # The flat index is worked out in the labels' own type, so it must reach
242
+ # the last cell of the table in that type.
243
+ label_bits = 8 * chunk.bytes - (chunk.data_type_name.start_with?("u") ? 0 : 1)
244
+ widen = total_ext - 1 >= 2 ** label_bits
242
245
 
243
246
  # canonical [fiber..., sample, channel] view (channel last); weights to
244
247
  # [fiber..., sample]. Skip the transpose when the layout is already
@@ -270,7 +273,10 @@ class CArray
270
273
  ravel = nil
271
274
  (0...@m).each do |k|
272
275
  b = tchunk[nil, k]
273
- b = b.clip(0, @lengths[k]) if b.max > @lengths[k] - 1
276
+ top = b.max
277
+ # No present cell in a channel: every sample is dropped.
278
+ return self if top == UNDEF
279
+ b = b.clip(0, @lengths[k]) if top > @lengths[k] - 1
274
280
  b = b.int64 if widen
275
281
  term = strides_ext[k] == 1 ? b : b * strides_ext[k]
276
282
  ravel = ravel.nil? ? term : ravel + term
@@ -74,16 +74,29 @@ class CABlockIterator < CAIterator
74
74
  "blocks: expected #{source.ndim} tile sizes (one per axis), " \
75
75
  "got #{blocks.size}"
76
76
  end
77
+ # Each tile is read through a view with one axis per tile position and
78
+ # one per cell in the tile, twice the source's rank.
79
+ if 2 * source.ndim > CA_RANK_MAX
80
+ raise ArgumentError,
81
+ "blocks: a rank #{source.ndim} array would need #{2 * source.ndim} " \
82
+ "axes for its tiles, beyond the limit of #{CA_RANK_MAX}; " \
83
+ "blocks works up to rank #{CA_RANK_MAX / 2}"
84
+ end
77
85
 
78
86
  @sndim = source.ndim
79
87
  offsets = Array.new(@sndim, 0)
80
88
  @sizes = Array.new(@sndim)
81
89
  blocks.each_with_index do |b, i|
82
90
  if b.is_a?(Range)
91
+ unless b.begin.is_a?(Integer) && b.end.is_a?(Integer)
92
+ raise TypeError, "blocks: axis #{i} takes a Range of Integer positions, got #{b.inspect}"
93
+ end
83
94
  offsets[i] = b.begin
84
95
  @sizes[i] = b.end - b.begin + (b.exclude_end? ? 0 : 1)
96
+ elsif b.is_a?(Integer)
97
+ @sizes[i] = b
85
98
  else
86
- @sizes[i] = Integer(b)
99
+ raise TypeError, "blocks: a tile size must be an Integer (got #{b.class})"
87
100
  end
88
101
  if @sizes[i] < 1
89
102
  raise ArgumentError, "blocks: tile size on axis #{i} must be >= 1"
@@ -93,7 +106,9 @@ class CABlockIterator < CAIterator
93
106
  # Absorb a leading offset with a zero-copy pre-slice, so the tile geometry
94
107
  # below always starts at index 0.
95
108
  @source =
96
- if offsets.all?(&:zero?)
109
+ if source.scalar?
110
+ source.flatten # a CScalar takes no index; its one-cell view does
111
+ elsif offsets.all?(&:zero?)
97
112
  source
98
113
  else
99
114
  source[*offsets.map { |o| o..-1 }]
@@ -355,16 +370,9 @@ class CABlockIterator < CAIterator
355
370
  def count (*args, **kw)
356
371
  return count_not_masked(**kw) if args.empty?
357
372
  kw = CAIterator.reduce_keywords(:count, kw)
358
- out = nil
359
- each_region do |strip_ranges, tiles, out_ranges|
360
- view = @source[*strip_ranges].block_view(*tiles)
361
- # block_view is a CAStride, so #count is not shadowed; dispatch
362
- # CArray#count explicitly anyway, matching the family regularity.
363
- red = CArray.instance_method(:count).bind_call(view, *args, axis: @tile_axes, **kw)
364
- out ||= CArray.new(red.data_type, @shape, bytes: red.bytes)
365
- out[*out_ranges] = red
366
- end
367
- out
373
+ # block_view is a CAStride, so #count is not shadowed; dispatch
374
+ # CArray#count explicitly anyway, matching the family regularity.
375
+ assemble { |view, _| count_cells(view, *args, axis: @tile_axes, **kw) }
368
376
  end
369
377
 
370
378
  # @overload count_not_masked
@@ -467,6 +475,12 @@ class CABlockIterator < CAIterator
467
475
  return src[addr.strip_mask(hole[0])].copy
468
476
  end
469
477
  out = src[addr.strip_mask(0)].copy
478
+ unless out.__send__(:holds_new_values?)
479
+ # A const string's cells are written as Strings and packed again.
480
+ text = out.to_string
481
+ text[empty] = fill_value.nil? ? UNDEF : fill_value
482
+ return text.to_const_string
483
+ end
470
484
  out[empty] = fill_value.nil? ? UNDEF : fill_value
471
485
  out
472
486
  end
@@ -517,7 +531,7 @@ class CABlockIterator < CAIterator
517
531
  sview = saddr[*strip_ranges].block_view(*tiles)
518
532
  grid = (0...@sndim).map { |i| vview.shape[i] }
519
533
  cells = tiles.inject(1) { |p, t| p * t }
520
- order = vview.copy.reshape(*(grid + [cells])).sort_addr(axis: @sndim)
534
+ order = vview.copy.reshape(*(grid + [cells])).sort_index(axis: @sndim)
521
535
  src_sorted = sview.reshape(*(grid + [cells])).take_along_axis(order, axis: @sndim)
522
536
  out[*strip_ranges].block_view(*tiles)[] = src_sorted.reshape(*(grid + tiles))
523
537
  end
@@ -671,15 +685,24 @@ class CABlockIterator < CAIterator
671
685
  # into a source-shaped CArray (the out-of-bounds cells of a partial edge
672
686
  # tile are dropped). Well-defined because tiles do not overlap; the source
673
687
  # is not modified (a new array is returned). Without a block, an Enumerator.
688
+ # The result has the source's data type; a Face source gives a result of
689
+ # the same Face, and a read-only Face (a categorical, a const string) an
690
+ # object array of its surface values.
674
691
  # @yieldparam tile [CArray]
675
692
  # @return [CArray, Enumerator] source-shaped
676
693
  def map
677
694
  return to_enum(:map) unless block_given?
678
- pout = CArray.new(padded_source.data_type, padded_source.shape, bytes: padded_source.bytes)
695
+ src = padded_source
696
+ surface = src.face? && !src.__send__(:holds_new_values?)
697
+ pout = surface ? CArray.new(CA_OBJECT, src.shape) : src.__send__(:blank_like, src.shape)
679
698
  pgv = pout.block_view(*@sizes)
680
699
  tgv = tile_grid_view
681
700
  nils = Array.new(@sndim, nil)
682
- CArray.each_index(*@shape) { |*g| pgv[*g, *nils] = yield(tgv[*g, *nils]) }
701
+ CArray.each_index(*@shape) { |*g|
702
+ tile = yield(tgv[*g, *nils])
703
+ tile = tile.to_a if surface && tile.is_a?(CArray) && tile.face?
704
+ pgv[*g, *nils] = tile
705
+ }
683
706
  pout[*@sndim.times.map { |i| 0...@source.shape[i] }].copy
684
707
  end
685
708
 
@@ -787,20 +810,23 @@ class CABlockIterator < CAIterator
787
810
  tile = tgv[*g, *nils]
788
811
  scanned = tile.copy.reshape(tile.elements).public_send(op, *args).reshape(*@sizes)
789
812
  unless pout
790
- pout = CArray.new(scanned.data_type, padded_source.shape, bytes: scanned.bytes)
813
+ pout = scanned.face? ? scanned.__send__(:blank_like, padded_source.shape) :
814
+ CArray.new(scanned.data_type, padded_source.shape, bytes: scanned.bytes)
791
815
  pout[] = UNDEF
792
816
  pgv = pout.block_view(*@sizes)
793
817
  end
794
818
  pgv[*g, *nils] = scanned
795
819
  end
820
+ # a source with no cells has no tile; its own scan gives the type
821
+ return @source.copy.reshape(@source.elements).public_send(op, *args).reshape(*@source.shape) unless pout
796
822
  pout[*@sndim.times.map { |i| 0...@source.shape[i] }].copy
797
823
  end
798
824
 
799
825
  # A source-shaped array that can hold what #tile_wise gives: of its kind,
800
- # or an object array for a read-only Face, which cannot be written cell by
801
- # cell.
826
+ # or an object array for a Face that holds no new value, which cannot be
827
+ # written cell by cell.
802
828
  def tile_output (lagged)
803
- if lagged.face? && lagged.read_only?
829
+ if lagged.face? && !lagged.__send__(:holds_new_values?)
804
830
  CArray.object(*@source.shape)
805
831
  else
806
832
  lagged.__send__(:blank_like, @source.shape)
@@ -817,17 +843,28 @@ class CABlockIterator < CAIterator
817
843
  # A padded entity whose interior holds the source and whose partial-edge
818
844
  # margin is masked (UNDEF), sized to exactly cover the ceil tile grid. When
819
845
  # the source already divides evenly this is the source itself (no copy), so
820
- # the tiles alias it. Memoised; feeds the iterate escape hatches.
846
+ # the tiles alias it. Kept for one call; feeds the iterate escape hatches.
821
847
  def padded_source
822
848
  @padded_source ||= begin
823
849
  pshape = @sndim.times.map { |i| @shape[i] * @sizes[i] }
824
850
  if pshape == @source.shape.to_a
825
851
  @source
826
852
  else
827
- pad = @source.__send__(:blank_like, pshape) # a Face stays one
828
- pad[] = UNDEF
829
- pad[*@sndim.times.map { |i| 0...@source.shape[i] }] = @source
830
- pad
853
+ interior = @sndim.times.map { |i| 0...@source.shape[i] }
854
+ if @source.face? && !@source.__send__(:holds_new_values?)
855
+ # A Face that holds no new value cannot be written: its storage is
856
+ # padded and the Face put back on.
857
+ storage = @source.__send__(:face_storage)
858
+ pad = CArray.new(storage.data_type, pshape, bytes: storage.bytes)
859
+ pad[] = UNDEF
860
+ pad[*interior] = storage
861
+ pad.face_lift(@source)
862
+ else
863
+ pad = @source.__send__(:blank_like, pshape) # a Face stays one
864
+ pad[] = UNDEF
865
+ pad[*interior] = @source
866
+ pad
867
+ end
831
868
  end
832
869
  end
833
870
  end
@@ -845,6 +882,8 @@ class CABlockIterator < CAIterator
845
882
  def lag (*args, **keywords) = @source.__send__(:carry_attrs, super)
846
883
  def strip_mask (**keywords) = @source.__send__(:carry_attrs, super)
847
884
  end)
885
+
886
+ read_source_per_call :@padded_source, :@tile_grid_view
848
887
  end
849
888
 
850
889
 
@@ -857,6 +896,8 @@ class CArray
857
896
  # first for "valid" tiling.
858
897
  # @param blocks [Array<Integer, Range>] per-axis tile sizes (or ranges).
859
898
  # @return [CABlockIterator]
899
+ # @raise [ArgumentError] when `self` has a rank above `CA_RANK_MAX / 2`
900
+ # (8): the tiles are read through a view of twice the rank.
860
901
  def blocks (*blocks)
861
902
  CABlockIterator.new(self, *blocks)
862
903
  end
@@ -59,6 +59,8 @@ require "carray/methods/is_in" # refuse_range_set, for the set-valued verbs
59
59
  # kernels are gated off (`cat + 1` raises; arithmetic on category codes is
60
60
  # not meaningful).
61
61
  class CACategorical < CAObject
62
+ private def holds_new_values? = false
63
+
62
64
 
63
65
  # raw-byte unpack format per storage (codes) data_type, native endian.
64
66
  # The FIXLEN surface delivers a per-cell fetch as an N-byte String; this
@@ -373,12 +375,13 @@ class CACategorical < CAObject
373
375
  # Returns a boolean CArray marking cells whose category equals
374
376
  # `label`. A CArray is compared cell by cell, by label: another
375
377
  # categorical is matched whatever order its labels are in, and a
376
- # masked cell on either side gives UNDEF. Anything else, a Ruby Array
377
- # included, is one label, as for {CArray#eq}. An unknown label matches
378
- # nothing.
378
+ # masked cell on either side gives UNDEF. `UNDEF` asks the mask, as for
379
+ # {CArray#eq}: true where a cell is in no category. Anything else, a Ruby
380
+ # Array included, is one label. An unknown label matches nothing.
379
381
  # @param label [Object, CArray] category to match, or one per cell.
380
382
  # @return [CArray]
381
383
  def eq(label)
384
+ return is_masked if label.equal?(UNDEF)
382
385
  codes.eq(codes_of(label))
383
386
  end
384
387
 
@@ -388,24 +391,31 @@ class CACategorical < CAObject
388
391
  # cell.
389
392
  # @return [CArray]
390
393
  def ne(label)
394
+ return is_not_masked if label.equal?(UNDEF)
391
395
  codes.ne(codes_of(label))
392
396
  end
393
397
 
394
398
  # @overload count(label)
395
399
  # Returns the number of cells whose category equals `label`
396
- # (0 for an unknown label).
400
+ # (0 for an unknown label). `UNDEF` counts the cells in no category,
401
+ # as {#count_masked}. The keywords of {CArray#count} (`axis:`,
402
+ # `keep_axis:`, `min_count:`, `fill_value:`) are taken in both forms.
397
403
  # @param label [Object] category to count.
398
404
  # @return [Integer]
399
405
  # @overload count
400
406
  # Returns the number of cells in some category (not masked), as
401
407
  # {CArray#count} with no value does.
402
408
  # @return [Integer]
403
- def count(*args)
404
- return count_not_masked if args.empty?
409
+ def count(*args, **kw)
410
+ return count_not_masked(**kw) if args.empty?
405
411
  raise ArgumentError, "count: wrong number of arguments (given #{args.size}, expected 0..1)" if args.size > 1
406
412
  label = args[0]
413
+ return count_masked(**kw) if label.equal?(UNDEF)
407
414
  code = @labels.index(label)
408
- code ? codes.count(code) : 0
415
+ return codes.count(code, **kw) if code
416
+ # an unknown label matches no cell; counted over the same mask so the
417
+ # keywords (axis:, min_count:, fill_value:) answer as for a known label
418
+ kw.empty? ? 0 : codes.ne(codes).count(true, **kw)
409
419
  end
410
420
 
411
421
  # Per-category counts as a length-k array aligned to #labels. Trailing empty
@@ -415,8 +425,8 @@ class CACategorical < CAObject
415
425
  # Memoised: the codes are read-only (immutable storage), so the counts are a
416
426
  # pure function of the categorical and stay valid for its lifetime. The same
417
427
  # cached array backs {#reduceat_index} and {#group_addr}, so a wide aggregate
418
- # over the same categorical pays the count once. (Do not mutate the returned
419
- # array — it is shared; take `.copy` for a scratch buffer.) A derived-view /
428
+ # over the same categorical pays the count once. The returned array is shared,
429
+ # so it is frozen; take `.copy` for a scratch buffer. A derived-view /
420
430
  # composite categorical caches too: read-only rides from the codes as a flag,
421
431
  # not a Ruby freeze, so the object stays non-frozen and the memo ivar sticks.
422
432
  # @overload category_sizes
@@ -429,8 +439,7 @@ class CACategorical < CAObject
429
439
  bc = codes.bincount
430
440
  out = CArray.new(bc.data_type, [@labels.size], bytes: bc.bytes) # new zero-fills
431
441
  out[0...bc.elements] = bc if bc.elements > 0
432
- @category_sizes = out
433
- out
442
+ @category_sizes = out.freeze
434
443
  end
435
444
 
436
445
  # Back-compatible alias; {#category_sizes} is the canonical name (a histogram
@@ -495,7 +504,10 @@ class CACategorical < CAObject
495
504
  # @return [CArray]
496
505
  def is_in (values)
497
506
  refuse_range_set(values, "is_in")
498
- wanted = label_list(values).filter_map { |l| @labels.index(l) }
507
+ wanted = label_list(values).filter_map do |l|
508
+ # nan-order: looks a label up and orders nothing; == does not find a NaN.
509
+ l.is_a?(Float) && l.nan? ? @labels.index { |x| x.is_a?(Float) && x.nan? } : @labels.index(l)
510
+ end
499
511
  codes.is_in(CArray.int64(wanted.size) { |i| wanted[i] })
500
512
  end
501
513
 
@@ -635,7 +647,7 @@ class CACategorical < CAObject
635
647
  # Memoised (see the grouping-plan note above): the counting sort is the
636
648
  # dominant grouping cost, so it is computed once and shared by every payload
637
649
  # column and by CACategoricalIterator, and kept for the categorical's
638
- # lifetime (an int64 per cell). Do not mutate the returned array.
650
+ # lifetime (an int64 per cell). The returned array is shared, so it is frozen.
639
651
  # @overload group_addr
640
652
  # Returns a length-{#elements} integer CArray of flat storage
641
653
  # addresses that order the cells by category (excluded cells last).
@@ -645,8 +657,7 @@ class CACategorical < CAObject
645
657
  out = codes.reshape(elements).__send__(:addresses_by_category,
646
658
  reduceat_index.copy, @labels.size,
647
659
  category_sizes.sum)
648
- @group_addr = out
649
- out
660
+ @group_addr = out.freeze
650
661
  end
651
662
 
652
663
  # Segment start offsets into the category-contiguous layout produced by
@@ -663,7 +674,7 @@ class CACategorical < CAObject
663
674
  return @reduceat_index if @reduceat_index
664
675
  # Every boundary but the last; the copy makes it an entity the
665
676
  # reduceat kernels can read directly.
666
- @reduceat_index = CArray.segment_offsets(lengths: category_sizes)[0...-1].copy
677
+ @reduceat_index = CArray.segment_offsets(lengths: category_sizes)[0...-1].copy.freeze
667
678
  end
668
679
 
669
680
  # @overload categorize(labels: nil, sort_labels: false)