carray 3.0.7 → 3.1.0

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 (275) hide show
  1. checksums.yaml +4 -4
  2. data/.yardopts +1 -1
  3. data/CHANGELOG.md +7 -1940
  4. data/README.md +38 -32
  5. data/carray.gemspec +16 -4
  6. data/docs/changelogs/CHANGELOG-3.0.md +2464 -0
  7. data/ext/ca_array_pool.c +4 -5
  8. data/ext/ca_axis_descriptor.h +45 -30
  9. data/ext/ca_axis_dispatch.c +7 -4
  10. data/ext/ca_axis_group.c +6 -9
  11. data/ext/ca_bincmp_dispatch.h +16 -38
  12. data/ext/ca_binop_dispatch.c +27 -0
  13. data/ext/ca_binop_dispatch.h +22 -47
  14. data/ext/ca_categorical_iterator.c +36 -34
  15. data/ext/ca_compare.c +0 -1
  16. data/ext/ca_compare.h +8 -1
  17. data/ext/ca_composite_dispatch.h +6 -0
  18. data/ext/ca_for_buffer.h +6 -1
  19. data/ext/ca_group_iter.c +17 -18
  20. data/ext/ca_iter_state_fields.h +196 -0
  21. data/ext/ca_iter_substrate.h +84 -103
  22. data/ext/ca_kernel_iterator.c +125 -89
  23. data/ext/ca_kernel_iterator.h +229 -1506
  24. data/ext/ca_kernel_iterator_internal.h +1167 -0
  25. data/ext/ca_moncmp_dispatch.h +17 -24
  26. data/ext/ca_monop_dispatch.h +25 -74
  27. data/ext/ca_obj_array.c +90 -163
  28. data/ext/ca_obj_bincmp.c +47 -46
  29. data/ext/ca_obj_binop.c +38 -38
  30. data/ext/ca_obj_bitarray.c +5 -17
  31. data/ext/ca_obj_bitfield.c +15 -30
  32. data/ext/ca_obj_block.c +11 -12
  33. data/ext/ca_obj_byte_swap.c +32 -30
  34. data/ext/ca_obj_const_string.c +57 -62
  35. data/ext/ca_obj_face.c +99 -91
  36. data/ext/ca_obj_face.h +32 -170
  37. data/ext/ca_obj_fake.c +15 -21
  38. data/ext/ca_obj_farray.c +7 -9
  39. data/ext/ca_obj_field.c +17 -13
  40. data/ext/ca_obj_fixlen_string.c +8 -19
  41. data/ext/ca_obj_grid.c +137 -106
  42. data/ext/ca_obj_meld.c +23 -21
  43. data/ext/ca_obj_moncmp.c +10 -21
  44. data/ext/ca_obj_monop.c +24 -35
  45. data/ext/ca_obj_object.c +51 -37
  46. data/ext/ca_obj_record.c +74 -22
  47. data/ext/ca_obj_reduce.c +8 -10
  48. data/ext/ca_obj_refer.c +42 -29
  49. data/ext/ca_obj_remap.c +11 -29
  50. data/ext/ca_obj_repeat.c +41 -23
  51. data/ext/ca_obj_roll.c +18 -24
  52. data/ext/ca_obj_select.c +10 -22
  53. data/ext/ca_obj_select_axis.c +27 -36
  54. data/ext/ca_obj_shift.c +22 -42
  55. data/ext/ca_obj_source.c +1 -5
  56. data/ext/ca_obj_stack.c +28 -24
  57. data/ext/ca_obj_stride.c +53 -54
  58. data/ext/ca_obj_string.c +6 -18
  59. data/ext/ca_obj_tile.c +12 -12
  60. data/ext/ca_obj_time.c +12 -23
  61. data/ext/ca_obj_timedelta.c +12 -23
  62. data/ext/ca_obj_transpose.c +8 -10
  63. data/ext/ca_obj_triop.c +35 -39
  64. data/ext/ca_obj_window.c +67 -86
  65. data/ext/ca_op_cmplx64.h +4 -0
  66. data/ext/ca_op_ipower.c +34 -12
  67. data/ext/ca_op_powi.h +4 -0
  68. data/ext/ca_pow5_table.h +2 -1
  69. data/ext/ca_rng_normal.h +4 -0
  70. data/ext/ca_rng_xoshiro256pp.h +3 -0
  71. data/ext/ca_sort_kernels.h +20 -26
  72. data/ext/ca_sweep_engine.c +2 -3
  73. data/ext/ca_sweep_engine.h +17 -9
  74. data/ext/ca_transform_common.c +3 -8
  75. data/ext/ca_triop_dispatch.h +20 -32
  76. data/ext/caframe_csv_reader.c +11 -11
  77. data/ext/carray.h +300 -1011
  78. data/ext/carray_access.c +234 -180
  79. data/ext/carray_address_basis.c +33 -38
  80. data/ext/carray_attribute.c +81 -104
  81. data/ext/carray_bincount.c +12 -14
  82. data/ext/carray_broadcast.c +30 -26
  83. data/ext/carray_call_cfunc.c +169 -277
  84. data/ext/carray_call_cfunc.h +36 -28
  85. data/ext/carray_cast.c +912 -346
  86. data/ext/carray_cast_func.rb +31 -3
  87. data/ext/carray_class.c +6 -11
  88. data/ext/carray_conversion.c +43 -38
  89. data/ext/carray_copy.c +28 -26
  90. data/ext/carray_core.c +217 -126
  91. data/ext/carray_count.c +27 -15
  92. data/ext/carray_element.c +40 -25
  93. data/ext/carray_factorize.c +53 -52
  94. data/ext/carray_generate.c +26 -19
  95. data/ext/carray_histogram.c +8 -10
  96. data/ext/carray_hold.c +7 -9
  97. data/ext/carray_index_classifier.c +123 -228
  98. data/ext/carray_index_classifier.h +11 -10
  99. data/ext/carray_integer_total.c +523 -0
  100. data/ext/carray_internal.h +1274 -160
  101. data/ext/carray_key_windows.c +3 -3
  102. data/ext/carray_lazy.c +21 -36
  103. data/ext/carray_loop.c +19 -22
  104. data/ext/carray_mask.c +123 -145
  105. data/ext/carray_math_kernel.h +23 -47
  106. data/ext/carray_mathfunc.c +10 -3
  107. data/ext/carray_median_percentile.c +95 -94
  108. data/ext/carray_memory_view.c +42 -47
  109. data/ext/carray_operator.c +423 -122
  110. data/ext/carray_order.c +121 -85
  111. data/ext/carray_partition.c +13 -15
  112. data/ext/carray_random.c +47 -41
  113. data/ext/carray_round.c +9 -4
  114. data/ext/carray_scatter.c +54 -40
  115. data/ext/carray_segment.c +41 -45
  116. data/ext/carray_slab.c +64 -47
  117. data/ext/carray_slab.h +44 -33
  118. data/ext/carray_sort.c +32 -29
  119. data/ext/carray_sort_kernel.c +12 -10
  120. data/ext/carray_struct.c +38 -43
  121. data/ext/carray_test.c +47 -43
  122. data/ext/carray_time_text.c +24 -31
  123. data/ext/carray_undef.c +50 -7
  124. data/ext/carray_utils.c +258 -94
  125. data/ext/extconf.rb +24 -17
  126. data/ext/mk_call_cfunc.rb +19 -20
  127. data/ext/mk_pow5_table.rb +2 -1
  128. data/ext/mkkernel.rb +782 -461
  129. data/ext/ruby_carray.c +47 -42
  130. data/ext/version.h +7 -5
  131. data/lib/carray/attribute.rb +19 -18
  132. data/lib/carray/autoload_carray.rb +20 -15
  133. data/lib/carray/autoload_method_extension.rb +64 -57
  134. data/lib/carray/axis_group.rb +264 -180
  135. data/lib/carray/basics.rb +272 -48
  136. data/lib/carray/bincount_nd.rb +33 -16
  137. data/lib/carray/block_iterator.rb +123 -102
  138. data/lib/carray/boolean_reduce.rb +7 -4
  139. data/lib/carray/categorical.rb +63 -51
  140. data/lib/carray/categorical_iterator.rb +89 -67
  141. data/lib/carray/complex.rb +61 -41
  142. data/lib/carray/conditional.rb +49 -22
  143. data/lib/carray/const_string.rb +54 -62
  144. data/lib/carray/core_extensions.rb +1 -1
  145. data/lib/carray/distance_limit.rb +7 -5
  146. data/lib/carray/factories.rb +269 -0
  147. data/lib/carray/fixlen_string.rb +25 -24
  148. data/lib/carray/frame/column_verbs.rb +20 -8
  149. data/lib/carray/frame/concat.rb +3 -3
  150. data/lib/carray/frame/convert.rb +2 -1
  151. data/lib/carray/frame/csv_parser.rb +7 -1
  152. data/lib/carray/frame/frame.rb +35 -25
  153. data/lib/carray/frame/group.rb +183 -150
  154. data/lib/carray/frame/io.rb +26 -7
  155. data/lib/carray/frame/join.rb +37 -12
  156. data/lib/carray/frame/records.rb +1 -1
  157. data/lib/carray/frame/reshape.rb +3 -3
  158. data/lib/carray/frame/sort.rb +10 -8
  159. data/lib/carray/frame/verbs.rb +148 -118
  160. data/lib/carray/frame/windows.rb +232 -21
  161. data/lib/carray/frame.rb +1 -2
  162. data/lib/carray/fuse_source.rb +24 -21
  163. data/lib/carray/fusion.rb +30 -30
  164. data/lib/carray/histogram.rb +35 -16
  165. data/lib/carray/inspect.rb +7 -7
  166. data/lib/carray/iterator.rb +97 -24
  167. data/lib/carray/key_windows.rb +83 -57
  168. data/lib/carray/lazy.rb +196 -94
  169. data/lib/carray/limits.rb +80 -0
  170. data/lib/carray/mask_gap_fill.rb +21 -16
  171. data/lib/carray/math.rb +87 -50
  172. data/lib/carray/meld_reduce.rb +30 -8
  173. data/lib/carray/methods/align_addr.rb +29 -17
  174. data/lib/carray/methods/bin.rb +5 -1
  175. data/lib/carray/methods/bincount.rb +4 -2
  176. data/lib/carray/methods/bit_string.rb +19 -31
  177. data/lib/carray/methods/broadcast.rb +8 -3
  178. data/lib/carray/methods/choose.rb +5 -5
  179. data/lib/carray/methods/composition.rb +72 -71
  180. data/lib/carray/methods/{index.rb → coordinate.rb} +13 -13
  181. data/lib/carray/methods/discovery_along.rb +3 -3
  182. data/lib/carray/methods/gather_nd.rb +106 -106
  183. data/lib/carray/methods/insert_block.rb +2 -2
  184. data/lib/carray/methods/is_between.rb +6 -4
  185. data/lib/carray/methods/is_in.rb +165 -145
  186. data/lib/carray/methods/join.rb +2 -1
  187. data/lib/carray/methods/lag.rb +6 -2
  188. data/lib/carray/methods/locate_addr.rb +150 -138
  189. data/lib/carray/methods/mask_duplicates.rb +1 -1
  190. data/lib/carray/methods/meshgrid.rb +28 -16
  191. data/lib/carray/methods/mode.rb +67 -67
  192. data/lib/carray/methods/nunique.rb +9 -7
  193. data/lib/carray/methods/repeat.rb +12 -12
  194. data/lib/carray/methods/resize.rb +1 -1
  195. data/lib/carray/methods/snap.rb +24 -20
  196. data/lib/carray/methods/string_format.rb +2 -2
  197. data/lib/carray/methods/unique.rb +4 -2
  198. data/lib/carray/methods/value_counts.rb +1 -1
  199. data/lib/carray/mkmf.rb +25 -28
  200. data/lib/carray/percentile_arguments.rb +82 -0
  201. data/lib/carray/record_order.rb +18 -17
  202. data/lib/carray/rng.rb +1 -0
  203. data/lib/carray/runtime.rb +190 -22
  204. data/lib/carray/segment_iterator.rb +251 -129
  205. data/lib/carray/serialize.rb +618 -571
  206. data/lib/carray/slab_iterator.rb +114 -114
  207. data/lib/carray/stack.rb +11 -12
  208. data/lib/carray/string.rb +16 -22
  209. data/lib/carray/string_operation_extension.rb +76 -52
  210. data/lib/carray/struct.rb +122 -164
  211. data/lib/carray/struct_builder.rb +243 -72
  212. data/lib/carray/time.rb +496 -342
  213. data/lib/carray/window_iterator.rb +191 -150
  214. data/lib/carray.rb +6 -11
  215. data/yard-stubs/ca_obj_array.rb +20 -135
  216. data/yard-stubs/ca_obj_bitarray.rb +1 -8
  217. data/yard-stubs/ca_obj_bitfield.rb +4 -3
  218. data/yard-stubs/ca_obj_byte_swap.rb +21 -7
  219. data/yard-stubs/ca_obj_fake.rb +3 -1
  220. data/yard-stubs/ca_obj_farray.rb +1 -1
  221. data/yard-stubs/ca_obj_field.rb +8 -6
  222. data/yard-stubs/ca_obj_refer.rb +7 -5
  223. data/yard-stubs/ca_obj_roll.rb +7 -6
  224. data/yard-stubs/ca_obj_shift.rb +2 -3
  225. data/yard-stubs/ca_obj_stride.rb +5 -7
  226. data/yard-stubs/ca_obj_tile.rb +1 -1
  227. data/yard-stubs/ca_obj_time.rb +43 -0
  228. data/yard-stubs/ca_obj_transpose.rb +1 -1
  229. data/yard-stubs/ca_obj_window.rb +26 -15
  230. data/yard-stubs/carray_access.rb +51 -4
  231. data/yard-stubs/carray_attribute.rb +26 -38
  232. data/yard-stubs/carray_cast.rb +118 -165
  233. data/yard-stubs/carray_class.rb +3 -4
  234. data/yard-stubs/carray_conversion.rb +6 -7
  235. data/yard-stubs/carray_copy.rb +2 -1
  236. data/yard-stubs/carray_count.rb +5 -3
  237. data/yard-stubs/carray_element.rb +4 -3
  238. data/yard-stubs/carray_limits.rb +100 -0
  239. data/yard-stubs/carray_loop.rb +0 -20
  240. data/yard-stubs/carray_mask.rb +59 -41
  241. data/yard-stubs/carray_math.rb +157 -100
  242. data/yard-stubs/carray_mathfunc.rb +415 -3
  243. data/yard-stubs/carray_median_percentile.rb +29 -11
  244. data/yard-stubs/carray_memory_view.rb +2 -2
  245. data/yard-stubs/carray_order.rb +67 -34
  246. data/yard-stubs/carray_random.rb +6 -6
  247. data/yard-stubs/carray_reduce.rb +353 -0
  248. data/yard-stubs/carray_rng.rb +92 -0
  249. data/yard-stubs/carray_scatter.rb +10 -2
  250. data/yard-stubs/carray_slab.rb +7 -4
  251. data/yard-stubs/carray_sort.rb +7 -6
  252. data/yard-stubs/carray_undef.rb +44 -5
  253. data/yard-stubs/ruby_carray.rb +75 -40
  254. metadata +62 -24
  255. data/CHANGELOG.v1.md +0 -126
  256. data/ext/carray_build_flags.h +0 -3
  257. data/ext/carray_config.h +0 -28
  258. data/ext/carray_data_type.c +0 -90
  259. data/ext/carray_kernels_bincmp.c +0 -6457
  260. data/ext/carray_kernels_binop.c +0 -31534
  261. data/ext/carray_kernels_init.c +0 -1734
  262. data/ext/carray_kernels_moncmp.c +0 -2104
  263. data/ext/carray_kernels_monop.c +0 -25337
  264. data/ext/carray_kernels_reduce_aggregate.c +0 -27545
  265. data/ext/carray_kernels_reduce_boolean.c +0 -1924
  266. data/ext/carray_kernels_reduce_cumulative.c +0 -11646
  267. data/ext/carray_kernels_reduce_extreme.c +0 -21631
  268. data/ext/carray_kernels_reduce_variance.c +0 -5981
  269. data/ext/carray_kernels_scan.c +0 -4302
  270. data/ext/carray_kernels_search.c +0 -37776
  271. data/ext/carray_kernels_sort.c +0 -10814
  272. data/ext/carray_kernels_triop.c +0 -1864
  273. data/lib/carray/construct.rb +0 -360
  274. data/lib/carray/data_type_extension.rb +0 -262
  275. data/lib/carray/data_type_limits.rb +0 -91
@@ -12,37 +12,21 @@
12
12
  #
13
13
  # Two metadata layers built here:
14
14
  #
15
- # AxisGroup -- spec built by `value.axis_group(cat_or_nil, ...)`: slot
15
+ # CAAxisGroup -- spec built by `value.axis_group(cat_or_nil, ...)`: slot
16
16
  # position = axis, a CACategorical slot is a group axis,
17
17
  # nil = band (held) axis. The value is a SHAPE TEMPLATE only
18
18
  # (rank + axis lengths), value-independent so one spec serves
19
19
  # many arrays.
20
- # GroupLabels -- lazy, factorized label view returned by g.labels.
21
-
22
- class CArray
23
-
24
- # ------------------------------------------------------------------------
25
- # CArray#axis_group(cat_or_nil, ...) -- build an AxisGroup spec.
26
- #
27
- # Slot position = source axis. A CACategorical slot consumes cat.ndim source
28
- # axes (rank-1 = one axis, rank-N = several axes collapsed into one group
29
- # axis); a nil slot is a band (held) axis. ALL axes must be given
30
- # explicitly -- the rank-sum must equal self.ndim, trailing omission / nil
31
- # fill is forbidden (explicit > implicit). The value is used as a
32
- # shape TEMPLATE only (its data is never read).
33
- def axis_group (*slots)
34
- AxisGroup.new(self, slots)
35
- end
36
- end
20
+ # CArray::GroupLabels -- lazy, factorized label view returned by g.labels.
37
21
 
38
22
  # ----------------------------------------------------------------------------
39
- # AxisGroup -- value-independent grouping spec.
23
+ # CAAxisGroup -- value-independent grouping spec.
40
24
  # ----------------------------------------------------------------------------
41
- class AxisGroup
25
+ class CAAxisGroup
42
26
 
43
27
  # Built from CArray#axis_group. `value` is the shape template; `slots` is the
44
28
  # raw slot list (CACategorical or nil per slot).
45
- def initialize (value, slots)
29
+ def initialize(value, slots)
46
30
  ndim = value.ndim
47
31
  shape = value.shape
48
32
  meta = []
@@ -89,12 +73,11 @@ class AxisGroup
89
73
  end
90
74
 
91
75
  @ndim = ndim
92
- @template_shape = shape
93
76
  @slot_meta = meta.freeze
94
77
  freeze
95
78
  end
96
79
 
97
- attr_reader :ndim, :template_shape
80
+ attr_reader :ndim
98
81
 
99
82
  # Number of output slots (= number of slots in the spec; each slot is one
100
83
  # output axis before any band reduction).
@@ -121,7 +104,7 @@ class AxisGroup
121
104
  # [*group_dims, *preserved_band_dims] to slot order.
122
105
  # squeeze : slot positions (slot order) that are length-1 (fused bands)
123
106
  # to drop after the transpose.
124
- def reduce_plan (fused)
107
+ def reduce_plan(fused)
125
108
  fused = Array(fused)
126
109
  fused.each do |s|
127
110
  m = @slot_meta[s]
@@ -175,10 +158,10 @@ class AxisGroup
175
158
  #
176
159
  # g.labels(i, j, k) -> the block's label tuple (Array); group axis =
177
160
  # its label, band axis = its integer index.
178
- # g.labels(axis: SPEC) -> a GroupLabels view in the index space of
161
+ # g.labels(axis: SPEC) -> a CArray::GroupLabels view in the index space of
179
162
  # value[g].reduce(axis: SPEC) (lockstep).
180
- # g.labels -> a GroupLabels view of the full grouped space.
181
- def labels (*idx, axis: nil)
163
+ # g.labels -> a CArray::GroupLabels view of the full grouped space.
164
+ def labels(*idx, axis: nil)
182
165
  unless idx.empty?
183
166
  if axis
184
167
  raise ArgumentError, "labels: pass either positional index or axis:"
@@ -187,24 +170,24 @@ class AxisGroup
187
170
  end
188
171
  return full_labels unless axis
189
172
 
190
- has_group, fused = AxisGroup.parse_axis(axis)
173
+ has_group, fused = CAAxisGroup.send(:parse_axis, axis)
191
174
  unless has_group
192
175
  raise ArgumentError,
193
176
  "labels(axis:) needs :group (labels track the grouped result)"
194
177
  end
195
178
  survivors = (0...@slot_meta.size).reject { |s| fused.include?(s) }
196
- GroupLabels.new(survivors.map { |s| axis_vector(s) })
179
+ CArray::GroupLabels.new(survivors.map { |s| axis_vector(s) })
197
180
  end
198
181
 
199
182
  # Full-space label view (every slot survives, slot order).
200
183
  def full_labels
201
- GroupLabels.new((0...@slot_meta.size).map { |s| axis_vector(s) })
184
+ CArray::GroupLabels.new((0...@slot_meta.size).map { |s| axis_vector(s) })
202
185
  end
203
186
 
204
- # Per-slot label vector descriptor for GroupLabels.
187
+ # Per-slot label vector descriptor for CArray::GroupLabels.
205
188
  # group slot -> [:names, labels_array]
206
189
  # band slot -> [:identity, len]
207
- def axis_vector (s)
190
+ def axis_vector(s)
208
191
  m = @slot_meta[s]
209
192
  if m[:kind] == :group
210
193
  [:names, m[:labels]]
@@ -222,7 +205,7 @@ class AxisGroup
222
205
 
223
206
  # A boolean array carrying value's mask: what a count reads, for a value
224
207
  # whose payload the group kernel cannot read. Called from C.
225
- private_class_method def self.count_stand_in (value)
208
+ private_class_method def self.count_stand_in(value)
226
209
  return value if value.boolean? || value.integer? || value.float?
227
210
  stand_in = CArray.boolean(*value.shape)
228
211
  stand_in.mask = value.mask if value.has_mask?
@@ -233,7 +216,7 @@ class AxisGroup
233
216
  MASK_COUNTS = [:count, :count_not_masked, :count_masked].freeze
234
217
 
235
218
  # Parse an axis: spec into [has_group, fused_band_slot_positions].
236
- def self.parse_axis (axis)
219
+ private_class_method def self.parse_axis(axis)
237
220
  has_group = false
238
221
  fused = []
239
222
  Array(axis).each do |a|
@@ -253,21 +236,24 @@ class AxisGroup
253
236
  # @return [String]
254
237
  def inspect
255
238
  kinds = @slot_meta.map { |m| m[:kind] == :group ? "g#{m[:k]}" : "band" }
256
- "#<AxisGroup ndim=#{@ndim} slots=[#{kinds.join(', ')}]>"
239
+ "#<CAAxisGroup ndim=#{@ndim} slots=[#{kinds.join(', ')}]>"
257
240
  end
241
+
242
+ # Parts the axis-group iterator reads; not for use outside it.
243
+ private :nslots, :slot_meta, :reduce_plan, :full_labels, :axis_vector
258
244
  end
259
245
 
260
246
  # ----------------------------------------------------------------------------
261
- # GroupLabels -- lazy, factorized label view.
247
+ # CArray::GroupLabels -- lazy, factorized label view.
262
248
  #
263
249
  # Stores one 1-D label vector per surviving output axis (group axis = its
264
250
  # categorical labels; band axis = identity 0...len). Block label tuples are
265
251
  # built on demand from the product -- the N-tuple table is NEVER materialised,
266
252
  # so storage is linear in the number of axes, not the block count.
267
253
  # ----------------------------------------------------------------------------
268
- class GroupLabels
254
+ class CArray::GroupLabels
269
255
 
270
- def initialize (vectors)
256
+ def initialize(vectors)
271
257
  @vectors = vectors # Array of [:names, array] / [:identity, len]
272
258
  @shape = vectors.map { |kind, data| kind == :names ? data.size : data }
273
259
  .freeze
@@ -282,17 +268,17 @@ class GroupLabels
282
268
  end
283
269
 
284
270
  # Block label tuple at the given index (length = ndim).
285
- def [] (*idx)
271
+ def [](*idx)
286
272
  if idx.size != @vectors.size
287
273
  raise IndexError,
288
- "GroupLabels: expected #{@vectors.size} indices, got #{idx.size}"
274
+ "CArray::GroupLabels: expected #{@vectors.size} indices, got #{idx.size}"
289
275
  end
290
276
  @vectors.each_with_index.map do |(kind, data), ax|
291
277
  i = idx[ax]
292
278
  len = (kind == :names) ? data.size : data
293
279
  i += len if i < 0
294
280
  if i < 0 || i >= len
295
- raise IndexError, "GroupLabels: index #{idx[ax]} out of range for axis #{ax}"
281
+ raise IndexError, "CArray::GroupLabels: index #{idx[ax]} out of range for axis #{ax}"
296
282
  end
297
283
  (kind == :names) ? data[i] : i
298
284
  end
@@ -300,7 +286,7 @@ class GroupLabels
300
286
 
301
287
  # The label vector for output axis k (Array): group labels or the identity
302
288
  # range of a band axis.
303
- def axis (k)
289
+ def axis(k)
304
290
  kind, data = @vectors[k]
305
291
  (kind == :names) ? data.dup : (0...data).to_a
306
292
  end
@@ -312,13 +298,13 @@ class GroupLabels
312
298
 
313
299
  # @return [String]
314
300
  def inspect
315
- "#<GroupLabels shape=#{@shape.inspect}>"
301
+ "#<CArray::GroupLabels shape=#{@shape.inspect}>"
316
302
  end
317
303
  end
318
304
 
319
305
  # Let the C [] type gate (ext/ca_group_iter.c) recognise these classes without
320
306
  # a kind_of on every index. Registered once on first load of this file, which
321
- # happens either eagerly (a `axis_group` / AxisGroup call) or lazily from the C
307
+ # happens either eagerly (a `axis_group` / CAAxisGroup call) or lazily from the C
322
308
  # gate itself the first time it meets a fixlen-surface CArray index (see
323
309
  # ca_argv_has_group). CACategorical is the classifier, so it must be defined
324
310
  # before the register call.
@@ -331,6 +317,16 @@ end
331
317
  # C, so the reopening below carries no superclass for YARD to read.
332
318
  # @!parse class CAGroupIterator < CAIterator; end
333
319
  class CAGroupIterator
320
+ # @!method labels(*index, axis: nil)
321
+ # Returns the coordinate labels of the result, in the index space of
322
+ # a reduced result, as {CAAxisGroup#labels} returns them for the
323
+ # grouping of this iterator.
324
+ # @param index [Array<Integer>] the index of one block; given, the
325
+ # answer is that block's label tuple.
326
+ # @param axis [Object, nil] the axes a reduction is to run over; given,
327
+ # the labels are those of that reduction's result.
328
+ # @return [CArray::GroupLabels, Array]
329
+
334
330
  # The shape one value per piece comes back in: a group slot contributes its
335
331
  # category count, a band slot its length, in slot order. The base declares
336
332
  # these and every other member answers them; this one inherited the readers
@@ -338,12 +334,19 @@ class CAGroupIterator
338
334
  # base's own rule calls out as the one thing a member must not do ("a clean
339
335
  # NotImplementedError, never a wrong answer").
340
336
  def shape
341
- spec.slot_meta.map { |m| m[:kind] == :group ? m[:k] : m[:len] }
337
+ spec.send(:slot_meta).map { |m| m[:kind] == :group ? m[:k] : m[:len] }
342
338
  end
343
- alias dim shape
344
339
 
345
340
  def ndim
346
- spec.nslots
341
+ spec.send(:nslots)
342
+ end
343
+
344
+ # @overload inspect
345
+ # Returns a one-line summary -- the result shape and the grouping --
346
+ # instead of the source array the iterator reads.
347
+ # @return [String]
348
+ def inspect
349
+ "#<#{self.class} shape=#{shape.inspect} #{spec.inspect}>"
347
350
  end
348
351
 
349
352
  # The C dispatcher every reduction shares takes keywords only, so the
@@ -363,7 +366,7 @@ class CAGroupIterator
363
366
  # @overload count(v)
364
367
  # Per-group count of cells equal to `v`.
365
368
  # @return [CArray]
366
- def count (*args, **kw)
369
+ def count(*args, **kw)
367
370
  if args.empty?
368
371
  return core_counts?(kw) ? reduce_by_core(:count, kw) : super(**kw)
369
372
  end
@@ -374,29 +377,37 @@ class CAGroupIterator
374
377
  return count_masked(**kw) if v.equal?(UNDEF)
375
378
  # eq leaves a masked cell UNDEF, so the sum leaves it out and its
376
379
  # min_count: counts the present cells, as the core count(v) does
377
- regroup(value.eq(v).int64, spec).sum(**kw).int64
380
+ regroup(source.eq(v).int64, spec).sum(**kw).int64
378
381
  end
379
382
 
380
- # @overload all
381
- # Per-group `all` over a boolean payload.
383
+ # @overload all(skip_masked: true)
384
+ # Per-group `all` over a boolean payload. With `skip_masked: false` the
385
+ # fold is three-valued, as `CArray#all` folds it: a group is `UNDEF`
386
+ # when a masked cell could change it.
387
+ # @param skip_masked [Boolean]
382
388
  # @return [CArray]
383
- def all (**kw)
389
+ def all(skip_masked: true, **kw)
390
+ skip_masked = CArray.send(:bool_arg, skip_masked, "skip_masked", "all")
384
391
  boolean_payload!(:all)
385
- core_counts?(kw) ? reduce_by_core(:all, kw) : super(**kw)
392
+ r = core_counts?(kw) ? reduce_by_core(:all, kw) : super(**kw)
393
+ skip_masked ? r : kleene_settle(:all, r, count_masked(**kw))
386
394
  end
387
395
 
388
- # @overload any
389
- # Per-group `any` over a boolean payload.
396
+ # @overload any(skip_masked: true)
397
+ # Per-group `any` over a boolean payload; `skip_masked:` as for {#all}.
398
+ # @param skip_masked [Boolean]
390
399
  # @return [CArray]
391
- def any (**kw)
400
+ def any(skip_masked: true, **kw)
401
+ skip_masked = CArray.send(:bool_arg, skip_masked, "skip_masked", "any")
392
402
  boolean_payload!(:any)
393
- core_counts?(kw) ? reduce_by_core(:any, kw) : super(**kw)
403
+ r = core_counts?(kw) ? reduce_by_core(:any, kw) : super(**kw)
404
+ skip_masked ? r : kleene_settle(:any, r, count_masked(**kw))
394
405
  end
395
406
 
396
407
  # @overload count_not_masked
397
408
  # Per-group count of present (non-masked) cells.
398
409
  # @return [CArray]
399
- def count_not_masked (**kw)
410
+ def count_not_masked(**kw)
400
411
  core_counts?(kw) ? reduce_by_core(:count_not_masked, kw) : super(**kw)
401
412
  end
402
413
 
@@ -408,9 +419,9 @@ class CAGroupIterator
408
419
  # development build run with CARRAY_GENERAL_PATH set) the core does --
409
420
  # except for a band folded into the count, which has no route but the
410
421
  # engine.
411
- def core_counts? (kw)
422
+ def core_counts?(kw)
412
423
  return false if CArray.__fast_paths_enabled__(:axis_group_count_kernel)
413
- has_group, fused = AxisGroup.parse_axis(kw[:axis])
424
+ has_group, fused = CAAxisGroup.send(:parse_axis, kw[:axis])
414
425
  has_group && fused.empty?
415
426
  end
416
427
  end
@@ -419,14 +430,14 @@ class CAGroupIterator
419
430
  # Per-group classified cell count (mask-independent) = count on the
420
431
  # mask-stripped value, so every classified cell is counted regardless of the
421
432
  # value mask (unlike count / count_not_masked, which count present cells).
422
- def elements (**kw)
423
- regroup(value.value, spec).count(**kw)
433
+ def elements(**kw)
434
+ regroup(source.value, spec).count(**kw)
424
435
  end
425
436
 
426
437
  # Per-group count of value-masked cells = elements - count_not_masked.
427
- def count_masked (**kw)
428
- has_group, = AxisGroup.parse_axis(kw[:axis])
429
- return value.count_masked(**kw) unless has_group
438
+ def count_masked(**kw)
439
+ has_group, = CAAxisGroup.send(:parse_axis, kw[:axis])
440
+ return source.count_masked(**kw) unless has_group
430
441
  check_reduce_keywords(:count_masked, kw)
431
442
  plain = { axis: kw[:axis] }
432
443
  finish_reduction(:count_masked, kw,
@@ -444,20 +455,52 @@ class CAGroupIterator
444
455
  :scatter_or_core, super_block: true)
445
456
 
446
457
  # The scatter kernel is the block (super).
447
- private def scatter_or_core (op, args, kw)
458
+ private def scatter_or_core(op, args, kw)
448
459
  unless args.empty?
449
460
  raise ArgumentError, "wrong number of arguments (given #{args.size}, expected 0)"
450
461
  end
451
- has_group, fused = AxisGroup.parse_axis(kw[:axis])
462
+ has_group, fused = CAAxisGroup.send(:parse_axis, kw[:axis])
452
463
  if ! has_group || kernel_reads_value?(fused)
453
- yield(**kw)
464
+ out = yield(**kw)
465
+ return out unless has_group && [:sum, :prod].include?(op) && integer_payload?
466
+ integer_total(op, out, kw, fused)
454
467
  else
455
468
  reduce_by_core(op, kw)
456
469
  end
457
470
  end
458
471
 
472
+ private def integer_payload?
473
+ source.integer? && ! source.face?
474
+ end
475
+
476
+ # An integer payload's sum or product is the core's: int64 (uint64 for an
477
+ # unsigned one), and float64 where it is out of that range. The scatter
478
+ # kernel folds in float64, which is exact while every partial total stays
479
+ # below 2**53: for a sum, the largest magnitude in a group times its count
480
+ # bounds the partial totals; for a product of integers, the partial products
481
+ # only grow in magnitude (until a factor 0 makes them 0), so the answer
482
+ # bounds them. Within the bound the answer is read back in the core's
483
+ # integer type; beyond it each group is folded by the core. With a band
484
+ # folded into the statistic, the answer is the per-group answer (axis:
485
+ # :group) folded over those bands by the core, which a sum or a product
486
+ # allows in either order.
487
+ private def integer_total(op, out, kw, fused)
488
+ limit = CASegmentIterator::EXACT_IN_FLOAT64
489
+ exact = if op == :sum
490
+ plain = { axis: kw[:axis] }
491
+ (max(**plain).float64.abs.pmax(min(**plain).float64.abs) *
492
+ count_not_masked(**plain).float64).lt(limit).all
493
+ else
494
+ out.abs.lt(limit).all
495
+ end
496
+ return out.to_type(CAIterator.send(:core_probe, source).public_send(op, axis: 1).data_type) if exact
497
+ return reduce_by_core(op, kw) if fused.empty?
498
+ per_group = public_send(op, axis: :group)
499
+ finish_reduction(op, kw, per_group.public_send(op, axis: fused))
500
+ end
501
+
459
502
  # Per-group [min, max] pair (matching CArray#minmax).
460
- def minmax (**kw)
503
+ def minmax(**kw)
461
504
  [min(**kw), max(**kw)]
462
505
  end
463
506
 
@@ -469,14 +512,14 @@ class CAGroupIterator
469
512
  # source address, which indexes back into the original array. Raises
470
513
  # NotImplementedError.
471
514
  # @raise [NotImplementedError]
472
- def min_index (*)
515
+ def min_index(*)
473
516
  raise NotImplementedError,
474
517
  "CAGroupIterator has no min_index: a group preserves source order, so " \
475
518
  "a within-group index is weak; use min_addr for the winner's flat " \
476
519
  "source address (it indexes back into the original array)."
477
520
  end
478
521
 
479
- def max_index (*)
522
+ def max_index(*)
480
523
  raise NotImplementedError,
481
524
  "CAGroupIterator has no max_index: a group preserves source order, so " \
482
525
  "a within-group index is weak; use max_addr for the winner's flat " \
@@ -485,10 +528,14 @@ class CAGroupIterator
485
528
 
486
529
  # Weighted sum: group-sum of value*weight. `weights` is a per-cell CArray in
487
530
  # the source layout (same shape as value); the product carries the combined
488
- # value|weight mask, so masked cells drop out. Empty group -> 0.0 (identity).
531
+ # value|weight mask, so masked cells drop out. Empty group -> 0 (identity).
489
532
  # No weighted kernel needed -- it is a plain group-sum of a derived array.
490
- def wsum (weights, **kw)
491
- regroup(value * weights, spec).sum(**kw)
533
+ # An integer value with integer weights multiplies in a type that holds
534
+ # every product, so the total is CArray#wsum's.
535
+ def wsum(weights, **kw)
536
+ products, unsigned = source.send(:integer_weighted_products, weights)
537
+ return regroup(source * weights, spec).sum(**kw) unless products
538
+ CArray.send(:integer_weighted_total, regroup(products, spec).sum(**kw), unsigned)
492
539
  end
493
540
 
494
541
  # Weighted mean = Sum(v*w) / Sum(w), both over the combined present-set. The
@@ -496,14 +543,16 @@ class CAGroupIterator
496
543
  # group-sum is Sum(w) over exactly the cells value*weight used. An empty group
497
544
  # (no present pair) and a group whose weights sum to zero are UNDEF, as
498
545
  # CArray#wmean leaves both.
499
- def wmean (weights, **kw)
500
- has_group, = AxisGroup.parse_axis(kw[:axis])
501
- return value.wmean(weights, **kw) unless has_group
546
+ def wmean(weights, **kw)
547
+ has_group, = CAAxisGroup.send(:parse_axis, kw[:axis])
548
+ return source.wmean(weights, **kw) unless has_group
502
549
  check_reduce_keywords(:wmean, kw)
503
550
  plain = { axis: kw[:axis] }
504
- prod = value * weights
551
+ products, unsigned = source.send(:integer_weighted_products, weights)
552
+ prod = products || source * weights
505
553
  num = regroup(prod, spec).sum(**plain)
506
- den = regroup(value * 0 + weights, spec).sum(**plain)
554
+ num = CArray.send(:integer_weighted_total, num, unsigned) if products
555
+ den = regroup(source * 0 + weights, spec).sum(**plain)
507
556
  cnt = regroup(prod, spec).count_not_masked(**plain)
508
557
  # No present pair is UNDEF (an empty group), set on the denominator so
509
558
  # the division never meets an empty group's 0 / 0.
@@ -511,7 +560,13 @@ class CAGroupIterator
511
560
  den[cnt.eq(0).or(den.eq(0))] = UNDEF
512
561
  # min_count: counts the present pairs, as the core wmean does.
513
562
  pairs = regroup(prod, spec)
514
- pairs.finish_reduction(:wmean, kw, num / den)
563
+ # An integer value's weighted mean is float64, as the core's is; an
564
+ # object one divides with quo (exact for Integer).
565
+ quotient = if num.data_type == CA_OBJECT then num.send(:quo_i, den)
566
+ elsif num.integer? then num.float64 / den
567
+ else num / den
568
+ end
569
+ pairs.finish_reduction(:wmean, kw, quotient)
515
570
  end
516
571
 
517
572
  # ---- segment scan: within-group running statistics ---------------------
@@ -531,7 +586,7 @@ class CAGroupIterator
531
586
  # Per-group inclusive running sum (float64), source-shaped. Without :group
532
587
  # delegates to the plain value cumsum.
533
588
  # @return [CArray]
534
- def cumsum (**kw)
589
+ def cumsum(**kw)
535
590
  scan_op(:cumsum, kw)
536
591
  end
537
592
 
@@ -539,7 +594,7 @@ class CAGroupIterator
539
594
  # Per-group inclusive running product (float64), source-shaped. float64 like
540
595
  # cumsum since the product grows. Without :group delegates to value cumprod.
541
596
  # @return [CArray]
542
- def cumprod (**kw)
597
+ def cumprod(**kw)
543
598
  scan_op(:cumprod, kw)
544
599
  end
545
600
 
@@ -549,7 +604,7 @@ class CAGroupIterator
549
604
  # member of a group emits its own value. Without :group delegates to value
550
605
  # cummax.
551
606
  # @return [CArray]
552
- def cummax (**kw)
607
+ def cummax(**kw)
553
608
  scan_op(:cummax, kw)
554
609
  end
555
610
 
@@ -557,7 +612,7 @@ class CAGroupIterator
557
612
  # Per-group inclusive running minimum, source-shaped, in the source data type.
558
613
  # Without :group delegates to value cummin.
559
614
  # @return [CArray]
560
- def cummin (**kw)
615
+ def cummin(**kw)
561
616
  scan_op(:cummin, kw)
562
617
  end
563
618
 
@@ -567,7 +622,7 @@ class CAGroupIterator
567
622
  # members up to and including the cell). Without :group delegates to the
568
623
  # plain value cumcount (also a 1-based cumulative count of present cells).
569
624
  # @return [CArray]
570
- def cumcount (**kw)
625
+ def cumcount(**kw)
571
626
  scan_op(:cumcount, kw)
572
627
  end
573
628
 
@@ -578,9 +633,9 @@ class CAGroupIterator
578
633
  # another group. Without :group it is the value's own `lag` along an
579
634
  # axis. A negative `n` looks ahead.
580
635
  # @return [CArray] source-shaped
581
- def lag (n = 1, axis: nil)
582
- has_group, fused = AxisGroup.parse_axis(axis)
583
- return value.lag(n, axis: axis) unless has_group
636
+ def lag(n = 1, axis: nil)
637
+ has_group, fused = CAAxisGroup.send(:parse_axis, axis)
638
+ return source.lag(n, axis: axis) unless has_group
584
639
  unless fused.empty?
585
640
  raise ArgumentError,
586
641
  "axis_group lag: folding a band into a lag (axis: [:group, k]) " \
@@ -592,14 +647,14 @@ class CAGroupIterator
592
647
  # @overload strip_mask(method:, axis: :group)
593
648
  # Per-group fill of the masked cells, counting a group's members in
594
649
  # row-major position order along the grouped axes (per band), as the
595
- # scans do: `:forward` / `:ffill` or `:backward` / `:bfill`, never across
650
+ # scans do: `:forward` or `:backward`, never across
596
651
  # into another group. Without :group it is the value's own
597
652
  # `strip_mask(method:, axis:)`.
598
653
  # @return [CArray] source-shaped
599
- def strip_mask (method:, axis: nil)
600
- has_group, fused = AxisGroup.parse_axis(axis)
601
- return value.strip_mask(method: method, axis: axis) unless has_group
602
- CAIterator.hold_backward?(method)
654
+ def strip_mask(method:, axis: nil)
655
+ has_group, fused = CAAxisGroup.send(:parse_axis, axis)
656
+ return source.strip_mask(method: method, axis: axis) unless has_group
657
+ CAIterator.send(:hold_backward?, method)
603
658
  unless fused.empty?
604
659
  raise ArgumentError,
605
660
  "axis_group strip_mask: folding a band into a fill (axis: [:group, k]) " \
@@ -608,20 +663,20 @@ class CAGroupIterator
608
663
  scan_by_core(:strip_mask, method: method)
609
664
  end
610
665
 
611
- # @overload order(axis: :group, descending: false, method: :ordinal, kind: :quick)
666
+ # @overload rank_index(axis: :group, descending: false, method: :ordinal, kind: :quick)
612
667
  # Per-group rank of each cell among its group's members (int64, `0` the
613
- # smallest; per band), as `CArray#order` ranks them; a cell in no group is
668
+ # smallest; per band), as `CArray#rank_index` ranks them; a cell in no group is
614
669
  # UNDEF. Without :group it is the value's own `order`.
615
670
  # @return [CArray] source-shaped
616
- def order (axis: nil, **kw)
617
- has_group, fused = AxisGroup.parse_axis(axis)
618
- return value.order(axis: axis, **kw) unless has_group
671
+ def rank_index(axis: nil, **kw)
672
+ has_group, fused = CAAxisGroup.send(:parse_axis, axis)
673
+ return source.rank_index(axis: axis, **kw) unless has_group
619
674
  unless fused.empty?
620
675
  raise ArgumentError,
621
- "axis_group order: folding a band into an order (axis: [:group, k]) " \
622
- "is not supported; an order preserves the source shape"
676
+ "axis_group rank_index: folding a band into a rank (axis: [:group, k]) " \
677
+ "is not supported; a rank preserves the source shape"
623
678
  end
624
- scan_by_core(:order, **kw)
679
+ scan_by_core(:rank_index, **kw)
625
680
  end
626
681
 
627
682
  # ---- materialize path: order statistics + generic iteration ------------
@@ -647,21 +702,23 @@ class CAGroupIterator
647
702
  # @overload median
648
703
  # Per-group median (float64), any grouping. See {#percentile}.
649
704
  # @return [CArray]
650
- def median (**kw)
705
+ def median(**kw)
651
706
  order_stat(:median, [], kw)
652
707
  end
653
708
 
654
709
  # @overload percentile(*pers)
655
- # Per-group percentile(s) (float64), any grouping.
710
+ # Per-group percentile(s) (float64), any grouping, with p in the forms
711
+ # `CArray#percentile` takes and the answer in the form p was written in.
656
712
  # @return [CArray, Array<CArray>]
657
- def percentile (*pers, **kw)
658
- order_stat(:percentile, pers, kw)
713
+ def percentile(*pers, **kw)
714
+ CAIterator.send(:percentile_in_form, pers) { |p| order_stat(:percentile, [p], kw.dup) }
659
715
  end
660
716
 
661
717
  # @overload quantile
662
718
  # Per-group five-number summary `[min, Q1, median, Q3, max]`, any grouping.
663
719
  # @return [Array<CArray>]
664
- def quantile (**kw)
720
+ def quantile(*args, **kw)
721
+ CAIterator.send(:refuse_quantile_arguments, args)
665
722
  order_stat(:quantile, [], kw)
666
723
  end
667
724
 
@@ -683,9 +740,9 @@ class CAGroupIterator
683
740
  # not supported, as for the order statistics.
684
741
  CArray.send(:define_named_methods, self, [:first, :last, :nunique], :group_position)
685
742
 
686
- private def group_position (op, **kw)
687
- has_group, fused = AxisGroup.parse_axis(kw[:axis])
688
- return value.public_send(op, **kw) unless has_group
743
+ private def group_position(op, **kw)
744
+ has_group, fused = CAAxisGroup.send(:parse_axis, kw[:axis])
745
+ return source.public_send(op, **kw) unless has_group
689
746
  unless fused.empty?
690
747
  raise NotImplementedError,
691
748
  "axis_group: folding a band into #{op} (axis: [:group, k]) is not " \
@@ -700,17 +757,21 @@ class CAGroupIterator
700
757
  composite_order(op, [])
701
758
  end
702
759
 
703
- # @overload sort_addr
760
+ # @overload sort_addr(axis: nil, masked_position: :last)
704
761
  # Per-group sorted flat source addresses (group-major). Any grouping (single
705
762
  # or composite group slots, rank-1 or rank-N, flat or band-preserving) is
706
- # supported; with no :group it is a plain value.sort_addr.
763
+ # supported; with no :group it is a plain value.sort_addr. The masked
764
+ # cells of a group come last, or first with `masked_position: :first`.
765
+ # @param masked_position [Symbol] `:last` (default) or `:first`.
707
766
  # @return [CArray]
708
- def sort_addr (**kw)
709
- has_group, _ = AxisGroup.parse_axis(kw[:axis])
710
- return value.sort_addr unless has_group
767
+ def sort_addr(axis: nil, masked_position: :last)
768
+ has_group, _ = CAAxisGroup.send(:parse_axis, axis)
769
+ return source.sort_addr(masked_position: masked_position) unless has_group
711
770
  ccat, _kd, gslots, bslots, gaxes = composite_layout
712
- return value.group_by_category(ccat).sort_addr if bslots.empty?
713
- composite_band_sort_addr(ccat, gslots, bslots, gaxes)
771
+ if bslots.empty?
772
+ return source.group_by_category(ccat).sort_addr(masked_position: masked_position)
773
+ end
774
+ composite_band_sort_addr(ccat, gslots, bslots, gaxes, masked_position)
714
775
  end
715
776
 
716
777
  # @overload each { |members| ... }
@@ -718,9 +779,9 @@ class CAGroupIterator
718
779
  # (composite category); a band-preserving grouping yields per (band position,
719
780
  # composite category), band-major then group order. Without a block returns
720
781
  # an Enumerator.
721
- def each (&block)
782
+ def each(&block)
722
783
  ccat, _kd, gslots, bslots, gaxes = composite_layout
723
- return value.group_by_category(ccat).each(&block) if bslots.empty?
784
+ return source.group_by_category(ccat).each(&block) if bslots.empty?
724
785
  return to_enum(:each) unless block
725
786
  each_band_block(ccat, gslots, bslots, gaxes) { |_vi, _oi, _co, gi| gi.each(&block) }
726
787
  self
@@ -731,17 +792,17 @@ class CAGroupIterator
731
792
  # cells (in no group) are UNDEF. Any grouping (single or composite, flat or
732
793
  # band-preserving).
733
794
  # @return [CArray]
734
- def map (data_type: nil, &block)
795
+ def map(data_type: nil, &block)
735
796
  raise LocalJumpError, "no block given (yield)" unless block
736
797
  ccat, _kd, gslots, bslots, gaxes = composite_layout
737
- return value.group_by_category(ccat).map(data_type: data_type, &block) if bslots.empty?
798
+ return source.group_by_category(ccat).map(data_type: data_type, &block) if bslots.empty?
738
799
  out = nil
739
800
  each_band_block(ccat, gslots, bslots, gaxes) do |val_idx, _oi, _co, gi|
740
801
  result = gi.map(data_type: data_type, &block)
741
- out ||= blank_of(result, value.shape)
802
+ out ||= blank_of(result, source.shape)
742
803
  out[*val_idx] = result
743
804
  end
744
- out || (data_type ? CArray.new(data_type, value.shape) : blank_of(value, value.shape))
805
+ out || (data_type ? CArray.new(data_type, source.shape) : blank_of(source, source.shape))
745
806
  end
746
807
 
747
808
  # @overload reduce { |members| ... }
@@ -750,15 +811,18 @@ class CAGroupIterator
750
811
  # group slot -> its k, each band slot -> its length). Any grouping (single or
751
812
  # composite, flat or band-preserving).
752
813
  # @return [CArray]
753
- def reduce (*args, data_type: nil, &block)
814
+ def reduce(*args, data_type: nil, &block)
815
+ if args.size > 1
816
+ raise ArgumentError, "reduce: wrong number of arguments (given #{args.size}, expected 0..1)"
817
+ end
754
818
  raise LocalJumpError, "no block given (yield)" unless block
755
819
  ccat, kdims, gslots, bslots, gaxes = composite_layout
756
820
  if bslots.empty?
757
- return value.group_by_category(ccat).reduce(*args, data_type: data_type, &block)
821
+ return source.group_by_category(ccat).reduce(*args, data_type: data_type, &block)
758
822
  .reshape(*kdims)
759
823
  end
760
824
  dt = data_type || CA_OBJECT
761
- out_shape = spec.slot_meta.map { |m| m[:kind] == :group ? m[:k] : m[:len] }
825
+ out_shape = spec.send(:slot_meta).map { |m| m[:kind] == :group ? m[:k] : m[:len] }
762
826
  out = CArray.new(dt, out_shape)
763
827
  each_band_block(ccat, gslots, bslots, gaxes) do |_vi, out_idx, _co, gi|
764
828
  out[*out_idx] = gi.reduce(*args, data_type: dt, &block).reshape(*kdims)
@@ -772,10 +836,10 @@ class CAGroupIterator
772
836
  # or every cell for a count of the mask); fill_value: then fills the masked
773
837
  # cells -- as a core reduction does with each. Protected: wmean finishes
774
838
  # through the iterator over its products.
775
- def finish_reduction (op, kw, result)
839
+ def finish_reduction(op, kw, result)
776
840
  need = CArray.__present_cells_needed_per_result_cell__(op, kw[:min_count], 0)
777
841
  if need > 0
778
- counts = if AxisGroup::MASK_COUNTS.include?(op.to_sym)
842
+ counts = if CAAxisGroup::MASK_COUNTS.include?(op.to_sym)
779
843
  elements(axis: kw[:axis])
780
844
  else
781
845
  count_not_masked(axis: kw[:axis])
@@ -786,14 +850,14 @@ class CAGroupIterator
786
850
  result = UNDEF
787
851
  end
788
852
  end
789
- CArray.__fill_undefined_result_cells__(result, kw[:fill_value])
853
+ CArray.__fill_undefined_result_cells__(result, kw[:fill_value], op.to_sym)
790
854
  end
791
855
 
792
856
  private
793
857
 
794
858
  # An unknown keyword is refused before the work is done.
795
- def check_reduce_keywords (op, kw)
796
- allowed = [:all, :any].include?(op.to_sym) ? AxisGroup::LOGICAL_REDUCE_KEYWORDS : AxisGroup::REDUCE_KEYWORDS
859
+ def check_reduce_keywords(op, kw)
860
+ allowed = [:all, :any].include?(op.to_sym) ? CAAxisGroup::LOGICAL_REDUCE_KEYWORDS : CAAxisGroup::REDUCE_KEYWORDS
797
861
  unknown = kw.keys - allowed
798
862
  unless unknown.empty?
799
863
  raise ArgumentError,
@@ -805,11 +869,10 @@ class CAGroupIterator
805
869
  end
806
870
 
807
871
  # The same grouping over another value.
808
- def regroup (value, spec)
872
+ def regroup(value, spec)
809
873
  self.class.send(:build_for, value, spec)
810
874
  end
811
875
 
812
-
813
876
  # Build the composite categorical over the group block (the sub-array spanning
814
877
  # every group axis). Each group slot -- rank-1 or rank-N -- contributes its
815
878
  # per-axis codes; the slot codes are broadcast into the group-block rank (size
@@ -830,17 +893,17 @@ class CAGroupIterator
830
893
  # the same float array disagreed about whether the question was even
831
894
  # askable. Asking a one-cell array of the same data type lets the core's own
832
895
  # refusal through, unworded by us.
833
- def boolean_payload! (op)
834
- probe = CAIterator.core_probe(value)
896
+ def boolean_payload!(op)
897
+ probe = CAIterator.send(:core_probe, source)
835
898
  probe.public_send(op) if probe
836
899
  nil
837
900
  end
838
901
 
839
902
  def composite_layout
840
- gslots = spec.slot_meta.select { |m| m[:kind] == :group }
841
- bslots = spec.slot_meta.select { |m| m[:kind] == :band }
903
+ gslots = spec.send(:slot_meta).select { |m| m[:kind] == :group }
904
+ bslots = spec.send(:slot_meta).select { |m| m[:kind] == :band }
842
905
  gaxes = gslots.flat_map { |m| m[:axes] }.sort
843
- shape = value.shape
906
+ shape = source.shape
844
907
  gb_rank = gaxes.size
845
908
  kdims = gslots.map { |m| m[:k] }
846
909
  place = Array.new(gslots.size, 1) # place value per slot
@@ -865,7 +928,7 @@ class CAGroupIterator
865
928
  # With no band axis the group block is the whole value, grouped in one
866
929
  # pass. With the fast paths off it goes through the band loop instead,
867
930
  # which then has one position.
868
- def whole_block? (bslots)
931
+ def whole_block?(bslots)
869
932
  bslots.empty? && CArray.__fast_paths_enabled__(:axis_group_whole_block)
870
933
  end
871
934
 
@@ -878,12 +941,12 @@ class CAGroupIterator
878
941
  # result), plus the raw band coordinates. Only one group block's grouped copy
879
942
  # is alive at a time (peak = O(group-block size); no whole-array grouped copy).
880
943
  # Band positions run row-major over the band slots (slot order).
881
- def each_band_block (ccat, gslots, bslots, gaxes)
882
- shape = value.shape
944
+ def each_band_block(ccat, gslots, bslots, gaxes)
945
+ shape = source.shape
883
946
  ndim = shape.size
884
- nslots = spec.slot_meta.size
947
+ nslots = spec.send(:slot_meta).size
885
948
  band_slot_pos = []
886
- spec.slot_meta.each_with_index { |m, s| band_slot_pos << s if m[:kind] == :band }
949
+ spec.send(:slot_meta).each_with_index { |m, s| band_slot_pos << s if m[:kind] == :band }
887
950
  blens = bslots.map { |m| m[:len] }
888
951
  blens.inject(1, :*).times do |t|
889
952
  coords = Array.new(bslots.size)
@@ -894,7 +957,7 @@ class CAGroupIterator
894
957
  bslots.each_with_index { |m, j| val_idx[m[:axis]] = coords[j] }
895
958
  out_idx = Array.new(nslots) # nil across group slots
896
959
  band_slot_pos.each_with_index { |s, j| out_idx[s] = coords[j] }
897
- yield val_idx, out_idx, coords, value[*val_idx].group_by_category(ccat)
960
+ yield val_idx, out_idx, coords, source[*val_idx].group_by_category(ccat)
898
961
  end
899
962
  end
900
963
 
@@ -903,22 +966,26 @@ class CAGroupIterator
903
966
  # statistic via the fused scan kernel. Folding a band into a scan (axis:
904
967
  # [:group, k]) would collapse an axis, so it is rejected (a scan preserves the
905
968
  # source shape).
906
- def scan_op (op, kw)
907
- has_group, fused = AxisGroup.parse_axis(kw[:axis])
969
+ def scan_op(op, kw)
970
+ has_group, fused = CAAxisGroup.send(:parse_axis, kw[:axis])
908
971
  unless has_group
909
- unless value.respond_to?(op)
972
+ unless source.respond_to?(op)
910
973
  raise NotImplementedError, "axis_group scan: value has no ##{op}"
911
974
  end
912
- return value.public_send(op)
975
+ return source.public_send(op, **kw)
913
976
  end
914
977
  unless fused.empty?
915
978
  raise ArgumentError,
916
979
  "axis_group scan: folding a band into a scan (axis: [:group, k]) " \
917
980
  "is not supported; a scan preserves the source shape"
918
981
  end
919
- return scan_by_core(op) unless kernel_scans?(op)
920
- group_axes, bundles, = spec.reduce_plan([])
921
- value.__scan_by_axis_groups__(group_axes, bundles, op)
982
+ answer = CAIterator.send(:core_probe, source).public_send(op)
983
+ integer = CArray.__fast_paths_enabled__(:axis_group_scan_kernel) &&
984
+ CAIterator.send(:integer_running?, op, source, answer)
985
+ return scan_by_core(op) unless integer || kernel_scans?(op)
986
+ group_axes, bundles, = spec.send(:reduce_plan, [])
987
+ out = source.__scan_by_axis_groups__(group_axes, bundles, op)
988
+ integer ? CAIterator.send(:integer_running, out, answer) { scan_by_core(op) } : out
922
989
  end
923
990
 
924
991
  # Whether the scatter kernels read this payload: an integer or a float,
@@ -930,10 +997,10 @@ class CAGroupIterator
930
997
  # With no band axis the core groups the whole value in one pass, which is
931
998
  # faster than the kernel for every group size (1M cells on an M2 Max: 7.5
932
999
  # to 12.5 ms against 15 ms), so the kernel is taken only with a band.
933
- def kernel_reads_value? (fused = [])
934
- return false if value.face? || ! (value.integer? || value.float?)
1000
+ def kernel_reads_value?(fused = [])
1001
+ return false if source.face? || ! (source.integer? || source.float?)
935
1002
  return true unless fused.empty?
936
- return false if spec.slot_meta.none? { |m| m[:kind] == :band }
1003
+ return false if spec.send(:slot_meta).none? { |m| m[:kind] == :band }
937
1004
  CArray.__fast_paths_enabled__(:axis_group_reduce_kernel)
938
1005
  end
939
1006
 
@@ -941,39 +1008,40 @@ class CAGroupIterator
941
1008
  # float, boolean or object payload (not a complex, not a Face), and answers cumsum / cumprod in
942
1009
  # float64 (an object in object), cummax / cummin in the payload's data type
943
1010
  # and cumcount in int64 -- not the core's answer for a boolean's running sum.
944
- def kernel_scans? (op)
1011
+ def kernel_scans?(op)
945
1012
  return false unless CArray.__fast_paths_enabled__(:axis_group_scan_kernel)
946
- return false if value.face? || value.complex? || value.data_type == CA_FIXLEN
947
- return true if value.object? || op == :cumcount
948
- core = CAIterator.core_probe(value).public_send(op).data_type
949
- kernel = [:cumsum, :cumprod].include?(op) ? CA_FLOAT64 : value.data_type
1013
+ return false if source.face? || source.complex? || source.data_type == CA_FIXLEN
1014
+ return true if source.object? || op == :cumcount
1015
+ core = CAIterator.send(:core_probe, source).public_send(op).data_type
1016
+ kernel = [:cumsum, :cumprod].include?(op) ? CA_FLOAT64 : source.data_type
950
1017
  core == kernel
951
1018
  end
952
1019
 
953
1020
  # A scan the kernel does not answer as the core does: each group block is
954
1021
  # grouped through the composite categorical, whose scans are the core's.
955
- def scan_by_core (op, *args, **kw)
1022
+ def scan_by_core(op, *args, **kw)
956
1023
  ccat, _kd, gslots, bslots, gaxes = composite_layout
957
- return value.group_by_category(ccat).public_send(op, *args, **kw) if whole_block?(bslots)
1024
+ return source.group_by_category(ccat).public_send(op, *args, **kw) if whole_block?(bslots)
958
1025
  out = nil
959
1026
  each_band_block(ccat, gslots, bslots, gaxes) do |val_idx, _oi, _co, gi|
960
1027
  result = gi.public_send(op, *args, **kw)
961
- out ||= blank_of(result, value.shape)
1028
+ out ||= blank_of(result, source.shape)
1029
+ out = CAIterator.send(:widen_for_running, out, result)
962
1030
  out[*val_idx] = result
963
1031
  end
964
- out || blank_of(value, value.shape)
1032
+ out || blank_of(source, source.shape)
965
1033
  end
966
1034
 
967
1035
  # A reduction of a payload the scatter kernel does not read, group by
968
1036
  # group through the composite categorical. Folding a band into the
969
1037
  # statistic needs the kernel.
970
- def reduce_by_core (op, kw)
971
- _, fused = AxisGroup.parse_axis(kw[:axis])
1038
+ def reduce_by_core(op, kw)
1039
+ _, fused = CAAxisGroup.send(:parse_axis, kw[:axis])
972
1040
  unless fused.empty?
973
1041
  raise ArgumentError,
974
1042
  "axis_group #{op}: folding a band into the statistic " \
975
- "(axis: [:group, k]) is not supported for a #{value.class} of " \
976
- "data type #{value.data_type_name}"
1043
+ "(axis: [:group, k]) is not supported for a #{source.class} of " \
1044
+ "data type #{source.data_type_name}"
977
1045
  end
978
1046
  check_reduce_keywords(op, kw)
979
1047
  finish_reduction(op, kw, composite_order(op, []))
@@ -982,7 +1050,7 @@ class CAGroupIterator
982
1050
  # An array of +shape+ of the same kind as +model+ -- its data type, or its
983
1051
  # Face -- with every cell UNDEF. A Face that holds no new value cannot be
984
1052
  # written cell by cell, so its values are held in an object array.
985
- def blank_of (model, shape)
1053
+ def blank_of(model, shape)
986
1054
  out = if model.face? && !model.__send__(:holds_new_values?)
987
1055
  CArray.new(CA_OBJECT, shape)
988
1056
  else
@@ -997,9 +1065,9 @@ class CAGroupIterator
997
1065
  # materialize. Folding a band into an order statistic (axis: [:group, k])
998
1066
  # gathers a group axis and a band axis into one statistic, a different
999
1067
  # operation, and remains a follow-up.
1000
- def order_stat (op, args, kw)
1001
- has_group, fused = AxisGroup.parse_axis(kw[:axis])
1002
- return value.public_send(op, *args, **kw) unless has_group
1068
+ def order_stat(op, args, kw)
1069
+ has_group, fused = CAAxisGroup.send(:parse_axis, kw[:axis])
1070
+ return source.public_send(op, *args, **kw) unless has_group
1003
1071
  unless fused.empty?
1004
1072
  raise NotImplementedError,
1005
1073
  "axis_group: folding a band into an order statistic (axis: [:group, k]) " \
@@ -1022,14 +1090,14 @@ class CAGroupIterator
1022
1090
  # band position's length-K result written into the group-slot subspace.
1023
1091
  # quantile emits five outputs. Empty / all-masked groups are UNDEF cells
1024
1092
  # (inherited from the categorical engine).
1025
- def composite_order (op, args)
1093
+ def composite_order(op, args)
1026
1094
  ccat, kdims, gslots, bslots, gaxes = composite_layout
1027
1095
  nout = (op == :quantile) ? 5 : 1
1028
1096
  if whole_block?(bslots)
1029
- res = value.group_by_category(ccat).public_send(op, *args)
1097
+ res = source.group_by_category(ccat).public_send(op, *args)
1030
1098
  return nout == 1 ? res.reshape(*kdims) : res.map { |r| r.reshape(*kdims) }
1031
1099
  end
1032
- out_shape = spec.slot_meta.map { |m| m[:kind] == :group ? m[:k] : m[:len] }
1100
+ out_shape = spec.send(:slot_meta).map { |m| m[:kind] == :group ? m[:k] : m[:len] }
1033
1101
  outs = nil
1034
1102
  each_band_block(ccat, gslots, bslots, gaxes) do |_vi, out_idx, _co, gi|
1035
1103
  results = gi.public_send(op, *args)
@@ -1038,7 +1106,7 @@ class CAGroupIterator
1038
1106
  outs ||= results.map { |r| blank_of(r, out_shape) }
1039
1107
  results.each_with_index { |r, q| outs[q][*out_idx] = r.reshape(*kdims) }
1040
1108
  end
1041
- outs ||= Array.new(nout) { blank_of(value, out_shape) }
1109
+ outs ||= Array.new(nout) { blank_of(source, out_shape) }
1042
1110
  nout == 1 ? outs[0] : outs
1043
1111
  end
1044
1112
 
@@ -1053,8 +1121,8 @@ class CAGroupIterator
1053
1121
  # contribution; the per-axis ramps are broadcast into the group-block rank.
1054
1122
  # Masked values sort to the tail of their group (as CArray#sort). Peak stays
1055
1123
  # O(group-block size) -- one block's grouped copy at a time.
1056
- def composite_band_sort_addr (ccat, gslots, bslots, gaxes)
1057
- shape = value.shape
1124
+ def composite_band_sort_addr(ccat, gslots, bslots, gaxes, masked_position)
1125
+ shape = source.shape
1058
1126
  strides = Array.new(shape.size)
1059
1127
  acc = 1
1060
1128
  (shape.size - 1).downto(0) { |a| strides[a] = acc; acc *= shape[a] }
@@ -1074,7 +1142,7 @@ class CAGroupIterator
1074
1142
  target[p] = shape[a]
1075
1143
  addr_block = addr_block + (CArray.int64(shape[a]).seq! * strides[a]).reshape(*target)
1076
1144
  end
1077
- local = gi.sort_addr # into the group block
1145
+ local = gi.sort_addr(masked_position: masked_position) # into the group block
1078
1146
  out[cursor...cursor + nvalid] = addr_block.reshape(gb_size)[local]
1079
1147
  cursor += nvalid
1080
1148
  end
@@ -1085,10 +1153,26 @@ class CAGroupIterator
1085
1153
  # place, so the result shows the source's attributes, as CArray#lag and
1086
1154
  # CArray#strip_mask(method:) do.
1087
1155
  prepend(Module.new do
1088
- def lag (*args, **keywords) = value.__send__(:carry_attrs, super)
1089
- def strip_mask (**keywords) = value.__send__(:carry_attrs, super)
1156
+ def lag(*args, **keywords) = source.__send__(:carry_attrs, super)
1157
+ def strip_mask(**keywords) = source.__send__(:carry_attrs, super)
1090
1158
  end)
1091
1159
  end
1092
1160
 
1093
1161
  require "carray/categorical"
1094
- CArray.send(:register_axis_group_classes, CACategorical, AxisGroup)
1162
+ CArray.send(:register_axis_group_classes, CACategorical, CAAxisGroup)
1163
+
1164
+ class CArray
1165
+
1166
+ # ------------------------------------------------------------------------
1167
+ # CArray#axis_group(cat_or_nil, ...) -- build an CAAxisGroup spec.
1168
+ #
1169
+ # Slot position = source axis. A CACategorical slot consumes cat.ndim source
1170
+ # axes (rank-1 = one axis, rank-N = several axes collapsed into one group
1171
+ # axis); a nil slot is a band (held) axis. ALL axes must be given
1172
+ # explicitly -- the rank-sum must equal self.ndim, trailing omission / nil
1173
+ # fill is forbidden (explicit > implicit). The value is used as a
1174
+ # shape TEMPLATE only (its data is never read).
1175
+ def axis_group(*slots)
1176
+ CAAxisGroup.new(self, slots)
1177
+ end
1178
+ end