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
@@ -135,7 +135,9 @@ class CArray
135
135
  # `self`; cells with no match in the direction and beyond-tolerance
136
136
  # cells are masked.
137
137
  # @raise [ArgumentError] when `direction` is not one of the accepted
138
- # symbols, or `tolerance` is not a duration for a time key.
138
+ # symbols, `tolerance` is not a duration for a time key, or `:round` /
139
+ # `tolerance` is asked of an object key whose values have no `-` (a
140
+ # String is ordered but has no distance).
139
141
  def locate_nearest_addr (ref, direction: :round, tolerance: nil)
140
142
  unless [:round, :floor, :ceil].include?(direction)
141
143
  raise ArgumentError,
@@ -150,8 +152,8 @@ class CArray
150
152
  # one has no place among the others either; it sorts after them.
151
153
  ri = ref.sort_addr
152
154
  ri = ri[0...ref.count_not_masked] if ref.has_mask?
153
- if ref.float? && ri.elements > 0
154
- ri = ri[0...(ri.elements - ref[ri].is_nan.count(true))]
155
+ if ri.elements > 0 && (nan = nearest_nan_cells(ref[ri]))
156
+ ri = ri[0...(ri.elements - nan.count(true))]
155
157
  end
156
158
  if ri.elements == 0
157
159
  out = CArray.int64(*shape)
@@ -160,6 +162,7 @@ class CArray
160
162
  end
161
163
  rs = ref[ri]
162
164
  n = rs.elements
165
+ nearest_refuse_distanceless(rs, direction, limit)
163
166
  rk, qk = nearest_keys(rs, self)
164
167
  # The position of each cell among the sorted references is counted, not
165
168
  # interpolated: :floor takes the last reference at or below it, :ceil the
@@ -172,17 +175,69 @@ class CArray
172
175
  when :round then nearest_round(rk, qk, nearest_count_below(rk, qk, false))
173
176
  end
174
177
  si[si.lt(0) | si.ge(n)] = UNDEF
175
- si[qk.is_nan.strip_mask(false)] = UNDEF if qk.float?
178
+ nan = nearest_nan_cells(qk)
179
+ si[nan.strip_mask(false)] = UNDEF if nan
176
180
  si = si.reshape(*shape)
177
181
  si[is_masked] = UNDEF if has_mask?
178
182
  idx = ri.project(si)
179
183
  if limit
180
- dist = (ref.project(idx) - self).abs
181
- idx[dist > limit] = UNDEF
184
+ idx[nearest_beyond(ref.project(idx), self, limit)] = UNDEF
182
185
  end
183
186
  idx
184
187
  end
185
188
 
189
+ # The NaN cells of a key, nil for a key that has none. A NaN in an object
190
+ # key is the cell that differs from itself.
191
+ private def nearest_nan_cells(key)
192
+ return key.is_nan if key.float?
193
+ return key.ne(key) if key.data_type == CA_OBJECT && !key.face?
194
+ nil
195
+ end
196
+
197
+ # :round and tolerance: measure how far a key is from its neighbours. An
198
+ # object key whose values have no subtraction (a String) is ordered but
199
+ # has no distance: only :floor and :ceil apply to it.
200
+ private def nearest_refuse_distanceless(key, direction, limit, subject = "locate_nearest_addr")
201
+ return unless key.data_type == CA_OBJECT && !key.face?
202
+ return unless direction == :round || limit
203
+ value = key.to_a.find { |v| !v.equal?(UNDEF) && v == v }
204
+ return if value.nil? || value.respond_to?(:-)
205
+ asked = (direction == :round) ? "direction: :round" : "tolerance:"
206
+ raise ArgumentError,
207
+ "#{subject}: #{asked} measures a distance, and a key of #{value.class} values " \
208
+ "has none (#{value.class} has no -); use direction: :floor or :ceil without tolerance:"
209
+ end
210
+
211
+ # Whether each pair of keys lies farther apart than +limit+. A time key is
212
+ # measured in ticks of the unit both keys meet in, as an integer key is:
213
+ # two instants an int64 holds can lie farther apart than an int64 holds (a
214
+ # nanosecond key spanning more than 292 years).
215
+ private def nearest_beyond(a, b, limit)
216
+ time_key = (a.is_a?(CATime) || a.is_a?(CATimedelta)) && a.class == b.class
217
+ r = time_key && CATimeUnitAlgebra.ratio(limit.unit, CATimeUnitAlgebra.diff_unit(a.unit, b.unit))
218
+ return nearest_distance(a, b) > limit unless r
219
+ a, b = a.in_common_unit_with(b)
220
+ threshold = (limit.value * r).floor
221
+ out = nearest_distance(a.ticks, b.ticks) > [threshold, 2**64 - 1].min
222
+ out[] = false if threshold >= 2**64 - 1
223
+ out
224
+ end
225
+
226
+ # How far apart two keys are. Integer keys are measured from the smaller to
227
+ # the larger, which fits an unsigned integer however far apart they are:
228
+ # the difference in their own type would wrap.
229
+ private def nearest_distance(a, b)
230
+ return (a - b).abs if a.face? || b.face?
231
+ t = a.send(:query_match_type, b)
232
+ return (a - b).abs if t == CA_OBJECT
233
+ a, b = a.to_type(t), b.to_type(t)
234
+ return (a - b).abs unless a.integer?
235
+ unless t == CA_UINT64
236
+ a, b = a.to_type(CA_INT64), b.to_type(CA_INT64)
237
+ end
238
+ (a.pmax(b) - a.pmin(b)).to_type(CA_UINT64)
239
+ end
240
+
186
241
  # A key held as fixed-length bytes (raw fixlen, or a fixlen string) has
187
242
  # no nearest: the search counts keys as numbers. A Face whose storage is
188
243
  # a number (a time) is searched by that number.
@@ -207,11 +262,7 @@ class CArray
207
262
  # that holds both.
208
263
  private def nearest_keys(rs, q)
209
264
  if rs.face? || q.face?
210
- if rs.respond_to?(:to_unit) && q.class == rs.class && q.unit != rs.unit
211
- u = CATimeUnitAlgebra.finer(rs.unit, q.unit)
212
- rs = rs.to_unit(u)
213
- q = q.to_unit(u)
214
- end
265
+ rs, q = rs.in_common_unit_with(q) if rs.respond_to?(:to_unit) && q.class == rs.class && q.unit != rs.unit
215
266
  q = rs.__send__(:reconcile_operand, q, "locate_nearest_addr")
216
267
  rs = rs.__send__(:face_storage)
217
268
  end
@@ -248,7 +299,7 @@ class CArray
248
299
  private def nearest_round(rk, qk, lt)
249
300
  lo = rk.project(lt - 1)
250
301
  hi = rk.project(lt)
251
- upper = (hi - qk).le(qk - lo).strip_mask(false)
302
+ upper = nearest_distance(hi, qk).le(nearest_distance(qk, lo)).strip_mask(false)
252
303
  upper[lo.is_masked] = true if lo.has_mask?
253
304
  upper[hi.is_masked] = false if hi.has_mask?
254
305
  upper[hi.eq(qk).strip_mask(false)] = true
@@ -58,7 +58,9 @@ class CArray
58
58
  raise ArgumentError,
59
59
  "coordinate vector #{k} should be 1-D (got #{a.ndim}-D)"
60
60
  end
61
- a
61
+ # A CScalar takes no index, so a scalar axis is read as the
62
+ # one-cell array it stands for.
63
+ a.is_a?(CScalar) ? a.reshape(1) : a
62
64
  end
63
65
 
64
66
  ndim = axes.size
@@ -59,7 +59,17 @@ class CArray
59
59
  end
60
60
  CArray.int64(width).fill(count)
61
61
  else
62
- given = count.to_ca.int64
62
+ unless count.respond_to?(:to_ca)
63
+ raise TypeError, "repeat: count must be an Integer or a list of them (got #{count.class})"
64
+ end
65
+ given = count.to_ca
66
+ # A list arrives as an object array; a Float in it is no count, as a
67
+ # float array is not.
68
+ unless given.integer? || (given.data_type == CA_OBJECT &&
69
+ given.to_a.flatten.all? { |c| c.is_a?(Integer) || c.equal?(UNDEF) })
70
+ raise TypeError, "repeat: counts must be Integers"
71
+ end
72
+ given = given.int64
63
73
  unless given.elements == width
64
74
  raise ArgumentError,
65
75
  "repeat: #{given.elements} counts for #{width} " \
@@ -52,20 +52,20 @@ class CARecord
52
52
  define_method(op, &Ractor.make_shareable(proc { |*args, **kw| record_rank.public_send(op, *args, **kw) }))
53
53
  end
54
54
 
55
- # @overload min(axis: nil, keep_axis: false)
55
+ # @overload min(axis: nil, keep_axis: false, min_count: nil, fill_value: nil)
56
56
  # Returns the smallest record by the declared order, skipping masked
57
57
  # records; UNDEF when every record is masked. With `axis:` a
58
58
  # {CARecord} of the smallest along that axis.
59
59
  # @return [CAStruct, CARecord]
60
- def min (axis: nil, keep_axis: false)
61
- record_extreme(:min_index, axis, keep_axis)
60
+ def min (axis: nil, keep_axis: false, min_count: nil, fill_value: nil)
61
+ record_extreme_kept(:min_index, axis, keep_axis, min_count, fill_value)
62
62
  end
63
63
 
64
- # @overload max(axis: nil, keep_axis: false)
64
+ # @overload max(axis: nil, keep_axis: false, min_count: nil, fill_value: nil)
65
65
  # The largest record; see {#min}.
66
66
  # @return [CAStruct, CARecord]
67
- def max (axis: nil, keep_axis: false)
68
- record_extreme(:max_index, axis, keep_axis)
67
+ def max (axis: nil, keep_axis: false, min_count: nil, fill_value: nil)
68
+ record_extreme_kept(:max_index, axis, keep_axis, min_count, fill_value)
69
69
  end
70
70
 
71
71
  # @overload minmax(axis: nil, keep_axis: false)
@@ -162,6 +162,28 @@ class CARecord
162
162
  end
163
163
 
164
164
  # The record at each min_index / max_index, gathered from self.
165
+ # An extreme under the reduction keywords every extreme takes: UNDEF where
166
+ # fewer than `min_count` cells are present, then `fill_value` for UNDEF.
167
+ def record_extreme_kept (index_op, axis, keep_axis, min_count, fill_value)
168
+ out = record_extreme(index_op, axis, keep_axis)
169
+ name = index_op.to_s.sub("_index", "").to_sym
170
+ need = CArray.__present_cells_needed_per_result_cell__(name, min_count, 0)
171
+ if need > 0
172
+ if axis.nil?
173
+ out = UNDEF if count_not_masked < need
174
+ else
175
+ counts = count_not_masked(axis: axis, keep_axis: keep_axis)
176
+ if counts.is_a?(CArray)
177
+ few = counts.lt(need)
178
+ out[few] = UNDEF if few.any
179
+ elsif counts < need
180
+ out = UNDEF
181
+ end
182
+ end
183
+ end
184
+ CArray.__fill_undefined_result_cells__(out, fill_value)
185
+ end
186
+
165
187
  def record_extreme (index_op, axis, keep_axis)
166
188
  rank = record_rank
167
189
  if axis.nil?
@@ -175,6 +197,13 @@ class CARecord
175
197
  return record_extreme_over(index_op, axes, keep_axis)
176
198
  end
177
199
  axis = normalize_axis(axis, name)
200
+ if ndim == 1
201
+ r = record_extreme(index_op, nil, false)
202
+ return r unless keep_axis
203
+ out = flatten[0..0].copy
204
+ out[0] = r
205
+ return out
206
+ end
178
207
  idx = rank.public_send(index_op, axis: axis)
179
208
  empty = idx.is_masked
180
209
  picked_shape = shape.dup
@@ -7,10 +7,11 @@ class CArray
7
7
 
8
8
  # A fast path answers by a different algorithm what a general path also
9
9
  # answers. A development build defines this in C, false when run with
10
- # CARRAY_GENERAL_PATH=1 so the test suite takes the general paths (see
10
+ # CARRAY_GENERAL_PATH=1 so the test suite takes the general paths, and
11
+ # false for a name listed in CARRAY_SHORTCUTS_OFF (see
11
12
  # ext/carray_internal.h); a release build has no switch.
12
13
  unless respond_to?(:__fast_paths_enabled__)
13
- def self.__fast_paths_enabled__ # :nodoc:
14
+ def self.__fast_paths_enabled__ (name = nil) # :nodoc:
14
15
  true
15
16
  end
16
17
  end
@@ -57,13 +58,14 @@ class CArray
57
58
  # is more naturally (and exactly, for Rational / BigDecimal weights) a
58
59
  # +(self * weights).sum+ composition than a dedicated :object kernel branch.
59
60
  #
60
- # +weights+ is a Ruby Numeric scalar (W-A1) or a same-shape CArray; the 1-D
61
- # axis-broadcast form (W-A2) is not supported for object weights (pass a
62
- # scalar or a full-shape weight), matching CArray's explicit-broadcast rule.
63
- # +opts+ is the trailing options Hash (axis:/keep_axis:/min_count:/
64
- # fill_value:) forwarded verbatim by the C escape; it goes straight to +sum+.
61
+ # +weights+ takes the forms the numeric kernel takes: a scalar (or a
62
+ # one-element CArray), an array of the shape of the reduced axes (taken in
63
+ # ascending axis order), or an array of self.shape. +opts+ is the trailing
64
+ # options Hash (axis:/keep_axis:/min_count:/fill_value:) forwarded verbatim
65
+ # by the C escape; it goes straight to +sum+.
65
66
  def wsum_object (weights, opts = {}) # :nodoc:
66
- (self * weights).sum(**opts)
67
+ weights = weights_over_self_shape(weights, opts[:axis], "wsum")
68
+ return (self * weights).sum(**opts)
67
69
  end
68
70
  private :wsum_object
69
71
 
@@ -76,6 +78,7 @@ class CArray
76
78
  def wmean_object (weights, opts = {}) # :nodoc:
77
79
  axis = opts[:axis]
78
80
  keep_axis = opts[:keep_axis]
81
+ weights = weights_over_self_shape(weights, axis, "wmean")
79
82
  prod = self * weights
80
83
  wv = (weights.is_a?(CArray) ? weights : self * 0 + weights).copy
81
84
  wv[prod.is_masked] = UNDEF if prod.has_mask?
@@ -97,6 +100,42 @@ class CArray
97
100
  end
98
101
  private :wmean_object
99
102
 
103
+ # The weights of wsum / wmean as a scalar or an array of self.shape. A
104
+ # CScalar is a scalar; any other array, one with a single element included,
105
+ # is held to the shapes. An array of the shape of the reduced axes (in ascending axis order) is
106
+ # repeated along the kept axes; any other shape is refused, with the same
107
+ # message as the numeric kernel.
108
+ def weights_over_self_shape (weights, axis, name) # :nodoc:
109
+ unless weights.is_a?(CArray)
110
+ return weights
111
+ end
112
+ if weights.scalar?
113
+ w = weights[0]
114
+ # A boolean cell reads as true / false; as a weight it is 1 / 0.
115
+ w = (w ? 1 : 0) if weights.data_type == CA_BOOLEAN && !UNDEF.equal?(w)
116
+ return w
117
+ end
118
+ if weights.shape == self.shape
119
+ return weights
120
+ end
121
+ axes = case axis
122
+ when nil then (0...self.ndim).to_a
123
+ when Integer then [axis]
124
+ else axis
125
+ end
126
+ axes = axes.map { |a| ( a < 0 ) ? a + self.ndim : a }.sort
127
+ reduced_shape = axes.map { |a| self.shape[a] }
128
+ unless weights.shape == reduced_shape
129
+ raise ArgumentError,
130
+ "#{name}: weights of shape #{weights.shape.inspect} not accepted " \
131
+ "(expected a scalar, the shape of the reduced axes " \
132
+ "#{reduced_shape.inspect}, or self.shape #{self.shape.inspect})"
133
+ end
134
+ spread = self.shape.each_index.map { |i| axes.include?(i) ? self.shape[i] : 1 }
135
+ return weights.reshape(*spread).broadcast_to(*self.shape)
136
+ end
137
+ private :weights_over_self_shape
138
+
100
139
  # Define on +mod+ one method per name in +names+, each a `def` that passes
101
140
  # its own name and its arguments to the private method +to+:
102
141
  #
@@ -133,5 +172,15 @@ class CArray
133
172
  end
134
173
  private_class_method :define_named_methods
135
174
 
175
+ # CArray.promote_list, its refusal named after the verb that gave it the
176
+ # list (stack, meld, concatenate, ...), not after promote_list.
177
+ def self.promote_list_for (verb, list, data_type: nil)
178
+ CArray.promote_list(list, data_type: data_type)
179
+ rescue ArgumentError, CArray::DataTypeError => e
180
+ raise unless e.message.start_with?("promote_list: ")
181
+ raise e.class, "#{verb}: #{e.message.delete_prefix("promote_list: ")}"
182
+ end
183
+ private_class_method :promote_list_for
184
+
136
185
  end
137
186
 
@@ -125,8 +125,7 @@ class CASegmentIterator < CAIterator
125
125
  # CABlock, whose own #count is the block geometry accessor, so dispatch
126
126
  # CArray#count explicitly. (Not fused: a value-equality reduceat would have
127
127
  # to reproduce core's cross-type / out-of-range equality exactly.)
128
- cnt = CArray.instance_method(:count)
129
- per_segment(CA_INT64) { |s| cnt.bind_call(s, *args) }
128
+ per_segment(CA_INT64) { |s| count_cells(s, *args) }
130
129
  end
131
130
 
132
131
  # @overload count_masked
@@ -233,8 +232,10 @@ class CASegmentIterator < CAIterator
233
232
  # as five length-k float64 CArrays (matching `CArray#quantile`): the
234
233
  # percentiles at 0 / 25 / 50 / 75 / 100. Empty / all-masked segments are
235
234
  # MASKED. For a single fraction q in 0..1 use `percentile(q * 100)`.
235
+ # @param axis [Integer, nil] as for {#percentile}.
236
236
  # @return [Array<CArray>]
237
- def quantile
237
+ def quantile (axis: nil)
238
+ return CArray.__name_errors_after_method__(:quantile) { [0, 25, 50, 75, 100].map { |p| percentile(p, axis: axis) } } if axis
238
239
  unless kernel_reads?
239
240
  return CArray.__name_errors_after_method__(:quantile) { [0, 25, 50, 75, 100].map { |p| percentile(p) } }
240
241
  end
@@ -297,7 +298,8 @@ class CASegmentIterator < CAIterator
297
298
  # iff every present value is truthy (empty segment -> true, vacuously).
298
299
  # The value data type must be boolean, as for `CArray#all`.
299
300
  # @return [CArray]
300
- def all
301
+ def all (axis: nil)
302
+ return axis_by_core(axis, :all) if axis
301
303
  aa = all_any
302
304
  aa ? aa[:all] : per_segment(CA_BOOLEAN) { |s| s.all }
303
305
  end
@@ -307,7 +309,8 @@ class CASegmentIterator < CAIterator
307
309
  # iff some present value is truthy (empty segment -> false). The value
308
310
  # data type must be boolean, as for `CArray#any`.
309
311
  # @return [CArray]
310
- def any
312
+ def any (axis: nil)
313
+ return axis_by_core(axis, :any) if axis
311
314
  aa = all_any
312
315
  aa ? aa[:any] : per_segment(CA_BOOLEAN) { |s| s.any }
313
316
  end
@@ -337,9 +340,17 @@ class CASegmentIterator < CAIterator
337
340
  # with the distinctness of `CArray#nunique` (every NaN is one value,
338
341
  # -0.0 is 0.0). A segment with no present value counts 0.
339
342
  # @return [CArray]
343
+ # Coding every cell costs the same for every cell, and the segment-by-
344
+ # segment way the same for every segment, so long segments are faster one
345
+ # by one: from an average of about 100 cells (1M cells on an M2 Max).
346
+ NUNIQUE_KERNEL_MAX_LENGTH = 100
347
+
340
348
  def nunique (axis: nil)
341
349
  return axis_by_core(axis, :nunique) if axis
342
- return per_segment(CA_INT64) { |s| s.nunique } unless CArray.__fast_paths_enabled__
350
+ if ! CArray.__fast_paths_enabled__(:segment_nunique) ||
351
+ grouped.elements >= NUNIQUE_KERNEL_MAX_LENGTH * @k
352
+ return per_segment(CA_INT64) { |s| s.nunique }
353
+ end
343
354
  out = CArray.int64(@k)
344
355
  return out if grouped.elements.zero?
345
356
  # Each cell's value becomes a code, so a distinct (segment, value) pair is
@@ -476,9 +487,8 @@ class CASegmentIterator < CAIterator
476
487
  end
477
488
 
478
489
  # @overload wmean(weights)
479
- # Per-segment weighted mean as float64, matching `CArray#wmean`. Empty
480
- # segment -> MASKED; a present segment whose weights sum to zero -> NaN
481
- # (core's 0/0 contract).
490
+ # Per-segment weighted mean as float64, matching `CArray#wmean`. An empty
491
+ # segment, and one whose weights sum to zero, is masked.
482
492
  # @param weights [CArray]
483
493
  # @return [CArray]
484
494
  def wmean (weights, axis: nil)
@@ -724,7 +734,9 @@ class CASegmentIterator < CAIterator
724
734
 
725
735
  def scan_answered (op)
726
736
  # An empty Face has no cell to ask the core about, and nothing to scan.
727
- return blank_output(@src_shape) if @value.face? && @value.elements.zero?
737
+ if @value.face? && @value.elements.zero?
738
+ return op == :cumcount ? CArray.int64(*@src_shape) : blank_output(@src_shape)
739
+ end
728
740
  answer = core_scan_answer(op)
729
741
  unless kernel_scans?(op, answer)
730
742
  return scatter_segments(->(shape) { blank_like(answer, shape) }) { |s| s.public_send(op) }
@@ -749,8 +761,8 @@ class CASegmentIterator < CAIterator
749
761
  # cumcount in int64 -- which is not the core's answer for every data type
750
762
  # (the core counts a boolean's running sum in uint64).
751
763
  def kernel_scans? (op, answer)
752
- return false unless CArray.__fast_paths_enabled__
753
- return false if @value.face? || answer.face? || @value.complex?
764
+ return false unless CArray.__fast_paths_enabled__(:segment_scan_kernel)
765
+ return false if @value.face? || answer.face? || @value.complex? || @value.data_type == CA_FIXLEN
754
766
  kernel_type =
755
767
  case op
756
768
  when :cumcount then CA_INT64
@@ -791,10 +803,10 @@ class CASegmentIterator < CAIterator
791
803
  end
792
804
 
793
805
  # A blank array of +shape+ of the same kind as +model+: its data type, or its
794
- # Face. A read-only Face cannot be written cell by cell, so its values are
795
- # held as the surface objects they are.
806
+ # Face. A Face that holds no new value cannot be written cell by cell, so its
807
+ # values are held as the surface objects they are.
796
808
  def blank_like (model, shape)
797
- if model.face? && model.read_only?
809
+ if model.face? && !model.__send__(:holds_new_values?)
798
810
  CArray.new(CA_OBJECT, shape)
799
811
  else
800
812
  model.__send__(:blank_like, shape)
@@ -906,9 +918,17 @@ class CASegmentIterator < CAIterator
906
918
  # segment's first or last slot and kept when it falls inside the segment.
907
919
  # A read-only Face cannot take UNDEF cell by cell, so its answers are
908
920
  # collected segment by segment, as its other reductions are.
921
+ #
922
+ # The running minimum or maximum costs the same for every cell, and the
923
+ # segment-by-segment way the same for every segment, so long segments
924
+ # are faster one by one: from an average of about 300 cells for :first
925
+ # and 2000 for :last (1M cells on an M2 Max).
926
+ EDGE_KERNEL_MAX_LENGTH = { first: 300, last: 2000 }.freeze
927
+
909
928
  def edge_values (op)
910
929
  n = grouped.elements
911
- if n.zero? || (@value.face? && ! face_output?) || ! CArray.__fast_paths_enabled__
930
+ if n.zero? || (@value.face? && ! face_output?) || ! CArray.__fast_paths_enabled__(:segment_edge_kernel) ||
931
+ n >= EDGE_KERNEL_MAX_LENGTH.fetch(op) * @k
912
932
  return per_segment(core_reduce_kind(op)) { |s| s.public_send(op) }
913
933
  end
914
934
  slot = CArray.int64(n).seq!
@@ -955,7 +975,7 @@ class CASegmentIterator < CAIterator
955
975
  # CARRAY_GENERAL_PATH set reduces every group by the core instead, which
956
976
  # is how the two are compared.
957
977
  def kernel_reads? (data_type = grouped.data_type)
958
- MONOID_TYPES.include?(data_type) && CArray.__fast_paths_enabled__
978
+ MONOID_TYPES.include?(data_type) && CArray.__fast_paths_enabled__(:segment_reduce_kernel)
959
979
  end
960
980
 
961
981
  def moments
@@ -991,7 +1011,7 @@ class CASegmentIterator < CAIterator
991
1011
  def all_any
992
1012
  return @all_any if defined?(@all_any)
993
1013
  @all_any =
994
- if grouped.data_type == CA_BOOLEAN && CArray.__fast_paths_enabled__
1014
+ if grouped.data_type == CA_BOOLEAN && CArray.__fast_paths_enabled__(:segment_all_any_kernel)
995
1015
  a = CArray.boolean(@k)
996
1016
  o = CArray.boolean(@k)
997
1017
  grouped.send(:__reduceat_all_any__, @offsets, a, o)
@@ -1027,10 +1047,10 @@ class CASegmentIterator < CAIterator
1027
1047
 
1028
1048
  # Whether an output can be built by lifting one. A Face is filled by writing
1029
1049
  # surface values into storage, so this needs a Face that can be written
1030
- # into; a read-only one -- a const string's records index a shared pool, a
1050
+ # into; another -- a const string's records index a shared pool, a
1031
1051
  # categorical's codes index a vocabulary -- has no blank form to fill.
1032
1052
  def face_output?
1033
- @value.face? && ! @value.read_only?
1053
+ @value.face? && @value.__send__(:holds_new_values?)
1034
1054
  end
1035
1055
 
1036
1056
  # Build a length-k typed output by folding each segment's members with the
@@ -1041,8 +1061,6 @@ class CASegmentIterator < CAIterator
1041
1061
  # for free (an all-masked segment reduces like an empty one; identity-bearing
1042
1062
  # reductions return their identity, ratios return UNDEF).
1043
1063
  def per_segment (kind)
1044
- # a data type the values' own Face answers in names that Face
1045
- kind = @value if ! kind.is_a?(CArray) && @value.face? && kind == @value.data_type
1046
1064
  data_type = kind.is_a?(CArray) ? kind.data_type : kind
1047
1065
  out = if kind.nil?
1048
1066
  CArray.new(CA_OBJECT, [@k])
@@ -1051,13 +1069,13 @@ class CASegmentIterator < CAIterator
1051
1069
  elsif data_type == @value.data_type then @value.bytes
1052
1070
  else 0 end
1053
1071
  CArray.new(data_type, [@k], bytes: bytes)
1054
- elsif ! kind.read_only?
1072
+ elsif kind.__send__(:holds_new_values?)
1055
1073
  # the core answered in a Face, so the output is one too:
1056
1074
  # CATime#min hands back a CATime::Element, which only a CATime
1057
1075
  # has anywhere to put
1058
1076
  kind.__send__(:blank_like, [@k])
1059
1077
  else
1060
- # a read-only Face cannot be filled, so its answers are collected
1078
+ # a Face that holds no new value cannot be filled, so its answers are collected
1061
1079
  # as the surface objects they already are
1062
1080
  CArray.new(CA_OBJECT, [@k])
1063
1081
  end
@@ -662,6 +662,12 @@ class CArray
662
662
  case tag
663
663
  when "object"
664
664
  shape, values, mask, attrs = rest
665
+ # The shape is only a claim until the cells are seen to fill it, and
666
+ # a damaged one can ask for more memory than the machine has.
667
+ unless marshal_cells_fill_shape?(values, shape) &&
668
+ (mask.nil? || marshal_cells_fill_shape?(mask, shape))
669
+ raise ArgumentError, "corrupt CArray Marshal payload (the cells do not fill shape #{shape.inspect})"
670
+ end
665
671
  ca = CArray.object(*shape)
666
672
  ca[] = values
667
673
  if mask
@@ -683,13 +689,29 @@ class CArray
683
689
  end
684
690
  private_class_method :array_from_marshal_payload
685
691
 
692
+ # Whether `cells`, nested as #to_a nests them, has the extent of every axis
693
+ # of `shape`. A cell may itself hold an Array, so only shape.size levels
694
+ # are counted.
695
+ def self.marshal_cells_fill_shape? (cells, shape)
696
+ return false unless shape.is_a?(Array) && !shape.empty? &&
697
+ shape.all? { |extent| extent.is_a?(Integer) && extent >= 0 }
698
+ level = [cells]
699
+ shape.each do |extent|
700
+ return false unless level.all? { |row| row.is_a?(Array) && row.size == extent }
701
+ level = level.flat_map { |row| row }
702
+ return true if level.empty?
703
+ end
704
+ true
705
+ end
706
+ private_class_method :marshal_cells_fill_shape?
707
+
686
708
  end
687
709
 
688
- # Marshal of a view and a scalar: the {CArray#marshal_dump} payload, loaded
689
- # back by the class method rather than into an empty instance. A view comes
690
- # back as a plain array (a copy owns its memory, as #copy gives); a scalar
691
- # comes back a scalar. A wrap is refused below.
692
- [CAView, CAWrap, CScalar].each do |klass|
710
+ # Marshal of a view, a mask and a scalar: the {CArray#marshal_dump} payload,
711
+ # loaded back by the class method rather than into an empty instance. A
712
+ # view, a wrap and a mask come back as a plain array (a copy owns its
713
+ # memory, as #copy gives); a scalar comes back a scalar.
714
+ [CAView, CAWrap, CScalar, CArrayMask, CAObjectMask].each do |klass|
693
715
  klass.class_eval do
694
716
  # A Face other than a record is refused: the payload would carry its
695
717
  # storage without what makes it the Face (a unit, labels), and load
@@ -703,28 +725,45 @@ end
703
725
  "dump its values with to_type(:object)" +
704
726
  (storage ? ", or its storage, which ##{storage} gives" : "")
705
727
  end
728
+ return dump_payload unless data_type == CA_OBJECT
729
+ # An object view dumps its cells by a nested Marshal.dump, which does
730
+ # not know the objects the outer dump has written. A cell holding the
731
+ # view again (directly or through other views) would dump it without
732
+ # end, so dumping the same view from inside its own dump is refused,
733
+ # as reading such a cell is.
734
+ refuse_reentry("Marshal.dump") { dump_payload }
735
+ end
736
+
737
+ private
738
+
739
+ # Marshal writes the instance variables of an object that has _dump
740
+ # after the String it returns, unless the String has instance
741
+ # variables of its own. A view keeps its parent in one, so a view of
742
+ # a large array would carry the whole parent, and a parent holding the
743
+ # view in a cell would be an object cycle. The String is given one of
744
+ # its own, which _load ignores.
745
+ def dump_payload
706
746
  Marshal.dump(CArray.instance_method(:marshal_dump).bind_call(self))
747
+ .tap { |s| s.instance_variable_set(:@carray_payload, true) }
707
748
  end
708
749
  end
709
750
  end
710
751
 
711
- class CAView
752
+ [CAView, CArrayMask, CAObjectMask].each do |klass|
712
753
  # @return [CArray] the plain array a {#_dump} string describes.
713
- def self._load (str)
714
- CArray.send(:array_from_marshal_payload, Marshal.load(str))
754
+ # Defined with def, not define_singleton_method: a block's method keeps
755
+ # the block's self and cannot be called from another Ractor.
756
+ klass.singleton_class.class_eval do
757
+ def _load (str)
758
+ CArray.send(:array_from_marshal_payload, Marshal.load(str))
759
+ end
715
760
  end
716
761
  end
717
762
 
718
763
  class CAWrap
719
- # A wrap borrows memory, which Marshal cannot carry to another process;
720
- # Ruby would also try to write the objects that keep the borrowed memory
721
- # alive. Its copy owns its memory and marshals.
722
- def _dump (_level)
723
- raise TypeError,
724
- "Marshal cannot carry a #{self.class}: it borrows its memory; " \
725
- "dump .copy instead"
726
- end
727
-
764
+ # A wrap borrows its memory, which Marshal cannot carry to another
765
+ # process: {#_dump} above writes its values, and the load gives a plain
766
+ # array that owns a copy of them, as it does for a view of the wrap.
728
767
  def self._load (str)
729
768
  CArray.send(:array_from_marshal_payload, Marshal.load(str))
730
769
  end
@@ -204,7 +204,7 @@ class CASlabIterator < CAIterator
204
204
  return count_not_masked(**kw) if args.empty?
205
205
  # CABlock / CAWindow shadow #count with a geometry accessor, and @reference
206
206
  # may be such a view, so dispatch CArray#count explicitly for count(v).
207
- CArray.instance_method(:count).bind_call(@reference, *args, axis: @slab_axes,
207
+ count_cells(@reference, *args, axis: @slab_axes,
208
208
  **CAIterator.reduce_keywords(:count, kw))
209
209
  end
210
210