carray 3.0.6 → 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 (277) hide show
  1. checksums.yaml +4 -4
  2. data/.yardopts +1 -1
  3. data/CHANGELOG.md +7 -1830
  4. data/README.md +62 -35
  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 +12 -15
  11. data/ext/ca_bincmp_dispatch.h +16 -38
  12. data/ext/ca_binop_dispatch.c +35 -0
  13. data/ext/ca_binop_dispatch.h +22 -46
  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 -1504
  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 +92 -165
  28. data/ext/ca_obj_bincmp.c +65 -48
  29. data/ext/ca_obj_binop.c +74 -49
  30. data/ext/ca_obj_bitarray.c +7 -21
  31. data/ext/ca_obj_bitfield.c +93 -26
  32. data/ext/ca_obj_block.c +11 -12
  33. data/ext/ca_obj_byte_swap.c +34 -34
  34. data/ext/ca_obj_const_string.c +464 -304
  35. data/ext/ca_obj_face.c +167 -121
  36. data/ext/ca_obj_face.h +32 -170
  37. data/ext/ca_obj_fake.c +127 -34
  38. data/ext/ca_obj_farray.c +13 -9
  39. data/ext/ca_obj_field.c +17 -13
  40. data/ext/ca_obj_fixlen_string.c +57 -34
  41. data/ext/ca_obj_grid.c +149 -113
  42. data/ext/ca_obj_meld.c +28 -26
  43. data/ext/ca_obj_moncmp.c +10 -21
  44. data/ext/ca_obj_monop.c +88 -73
  45. data/ext/ca_obj_object.c +60 -46
  46. data/ext/ca_obj_record.c +74 -22
  47. data/ext/ca_obj_reduce.c +10 -14
  48. data/ext/ca_obj_refer.c +146 -39
  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 +20 -28
  52. data/ext/ca_obj_select.c +17 -27
  53. data/ext/ca_obj_select_axis.c +35 -42
  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 +33 -29
  57. data/ext/ca_obj_stride.c +99 -62
  58. data/ext/ca_obj_string.c +8 -20
  59. data/ext/ca_obj_tile.c +14 -16
  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 +48 -49
  64. data/ext/ca_obj_window.c +87 -99
  65. data/ext/ca_op_cmplx64.h +4 -0
  66. data/ext/ca_op_ipower.c +97 -27
  67. data/ext/ca_op_powi.h +9 -28
  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 +23 -26
  72. data/ext/ca_sweep_engine.c +92 -26
  73. data/ext/ca_sweep_engine.h +22 -15
  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 +12 -12
  77. data/ext/carray.h +300 -1009
  78. data/ext/carray_access.c +320 -207
  79. data/ext/carray_address_basis.c +128 -59
  80. data/ext/carray_attribute.c +81 -104
  81. data/ext/carray_bincount.c +12 -14
  82. data/ext/carray_broadcast.c +31 -27
  83. data/ext/carray_call_cfunc.c +174 -285
  84. data/ext/carray_call_cfunc.h +36 -28
  85. data/ext/carray_cast.c +1191 -351
  86. data/ext/carray_cast_func.rb +68 -8
  87. data/ext/carray_class.c +6 -11
  88. data/ext/carray_conversion.c +98 -39
  89. data/ext/carray_copy.c +52 -26
  90. data/ext/carray_core.c +286 -132
  91. data/ext/carray_count.c +53 -22
  92. data/ext/carray_element.c +49 -28
  93. data/ext/carray_factorize.c +64 -63
  94. data/ext/carray_generate.c +26 -19
  95. data/ext/carray_histogram.c +9 -11
  96. data/ext/carray_hold.c +7 -9
  97. data/ext/carray_index_classifier.c +127 -230
  98. data/ext/carray_index_classifier.h +11 -10
  99. data/ext/carray_integer_total.c +523 -0
  100. data/ext/carray_internal.h +1364 -156
  101. data/ext/carray_key_windows.c +3 -3
  102. data/ext/carray_lazy.c +37 -37
  103. data/ext/carray_loop.c +27 -23
  104. data/ext/carray_mask.c +235 -150
  105. data/ext/carray_math_kernel.h +23 -47
  106. data/ext/carray_mathfunc.c +10 -3
  107. data/ext/carray_median_percentile.c +106 -100
  108. data/ext/carray_memory_view.c +83 -69
  109. data/ext/carray_operator.c +490 -128
  110. data/ext/carray_order.c +163 -84
  111. data/ext/carray_partition.c +14 -16
  112. data/ext/carray_random.c +48 -42
  113. data/ext/carray_round.c +33 -5
  114. data/ext/carray_scatter.c +57 -39
  115. data/ext/carray_segment.c +42 -46
  116. data/ext/carray_slab.c +77 -51
  117. data/ext/carray_slab.h +44 -33
  118. data/ext/carray_sort.c +37 -31
  119. data/ext/carray_sort_kernel.c +36 -10
  120. data/ext/carray_struct.c +44 -34
  121. data/ext/carray_test.c +131 -81
  122. data/ext/carray_time_text.c +30 -31
  123. data/ext/carray_undef.c +50 -7
  124. data/ext/carray_utils.c +373 -139
  125. data/ext/extconf.rb +24 -17
  126. data/ext/mk_call_cfunc.rb +25 -31
  127. data/ext/mk_pow5_table.rb +2 -1
  128. data/ext/mkkernel.rb +819 -488
  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 +272 -185
  135. data/lib/carray/basics.rb +298 -56
  136. data/lib/carray/bincount_nd.rb +41 -18
  137. data/lib/carray/block_iterator.rb +167 -119
  138. data/lib/carray/boolean_reduce.rb +7 -4
  139. data/lib/carray/categorical.rb +84 -59
  140. data/lib/carray/categorical_iterator.rb +90 -67
  141. data/lib/carray/complex.rb +61 -41
  142. data/lib/carray/conditional.rb +98 -23
  143. data/lib/carray/const_string.rb +112 -46
  144. data/lib/carray/core_extensions.rb +20 -69
  145. data/lib/carray/distance_limit.rb +7 -5
  146. data/lib/carray/factories.rb +269 -0
  147. data/lib/carray/fixlen_string.rb +95 -12
  148. data/lib/carray/frame/column_verbs.rb +76 -9
  149. data/lib/carray/frame/concat.rb +51 -7
  150. data/lib/carray/frame/convert.rb +2 -1
  151. data/lib/carray/frame/csv_parser.rb +20 -5
  152. data/lib/carray/frame/frame.rb +73 -31
  153. data/lib/carray/frame/group.rb +247 -187
  154. data/lib/carray/frame/io.rb +36 -12
  155. data/lib/carray/frame/join.rb +56 -17
  156. data/lib/carray/frame/records.rb +7 -5
  157. data/lib/carray/frame/reshape.rb +27 -7
  158. data/lib/carray/frame/sort.rb +10 -8
  159. data/lib/carray/frame/verbs.rb +217 -134
  160. data/lib/carray/frame/windows.rb +254 -19
  161. data/lib/carray/frame.rb +1 -2
  162. data/lib/carray/fuse_source.rb +28 -23
  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 +104 -23
  167. data/lib/carray/key_windows.rb +93 -61
  168. data/lib/carray/lazy.rb +208 -111
  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 +8 -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 +73 -72
  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/factorize.rb +2 -0
  183. data/lib/carray/methods/gather_nd.rb +106 -103
  184. data/lib/carray/methods/insert_block.rb +2 -2
  185. data/lib/carray/methods/is_between.rb +6 -4
  186. data/lib/carray/methods/is_in.rb +183 -143
  187. data/lib/carray/methods/join.rb +2 -1
  188. data/lib/carray/methods/lag.rb +6 -2
  189. data/lib/carray/methods/locate_addr.rb +157 -94
  190. data/lib/carray/methods/mask_duplicates.rb +1 -1
  191. data/lib/carray/methods/meshgrid.rb +28 -16
  192. data/lib/carray/methods/mode.rb +67 -67
  193. data/lib/carray/methods/nunique.rb +9 -7
  194. data/lib/carray/methods/repeat.rb +23 -13
  195. data/lib/carray/methods/resize.rb +1 -1
  196. data/lib/carray/methods/snap.rb +24 -20
  197. data/lib/carray/methods/string_format.rb +2 -2
  198. data/lib/carray/methods/unique.rb +4 -2
  199. data/lib/carray/methods/value_counts.rb +1 -1
  200. data/lib/carray/mkmf.rb +25 -28
  201. data/lib/carray/percentile_arguments.rb +82 -0
  202. data/lib/carray/record_order.rb +50 -20
  203. data/lib/carray/rng.rb +1 -0
  204. data/lib/carray/runtime.rb +195 -17
  205. data/lib/carray/segment_iterator.rb +262 -137
  206. data/lib/carray/serialize.rb +635 -566
  207. data/lib/carray/slab_iterator.rb +114 -114
  208. data/lib/carray/stack.rb +14 -15
  209. data/lib/carray/string.rb +16 -22
  210. data/lib/carray/string_operation_extension.rb +97 -52
  211. data/lib/carray/struct.rb +122 -164
  212. data/lib/carray/struct_builder.rb +247 -73
  213. data/lib/carray/time.rb +663 -365
  214. data/lib/carray/window_iterator.rb +232 -155
  215. data/lib/carray.rb +6 -11
  216. data/yard-stubs/ca_obj_array.rb +20 -135
  217. data/yard-stubs/ca_obj_bitarray.rb +1 -8
  218. data/yard-stubs/ca_obj_bitfield.rb +6 -2
  219. data/yard-stubs/ca_obj_byte_swap.rb +21 -7
  220. data/yard-stubs/ca_obj_fake.rb +3 -1
  221. data/yard-stubs/ca_obj_farray.rb +1 -1
  222. data/yard-stubs/ca_obj_field.rb +8 -6
  223. data/yard-stubs/ca_obj_refer.rb +10 -5
  224. data/yard-stubs/ca_obj_roll.rb +7 -6
  225. data/yard-stubs/ca_obj_shift.rb +2 -3
  226. data/yard-stubs/ca_obj_stride.rb +5 -7
  227. data/yard-stubs/ca_obj_tile.rb +1 -1
  228. data/yard-stubs/ca_obj_time.rb +43 -0
  229. data/yard-stubs/ca_obj_transpose.rb +1 -1
  230. data/yard-stubs/ca_obj_window.rb +28 -16
  231. data/yard-stubs/carray_access.rb +55 -6
  232. data/yard-stubs/carray_attribute.rb +26 -38
  233. data/yard-stubs/carray_cast.rb +121 -162
  234. data/yard-stubs/carray_class.rb +3 -4
  235. data/yard-stubs/carray_conversion.rb +6 -7
  236. data/yard-stubs/carray_copy.rb +2 -1
  237. data/yard-stubs/carray_count.rb +10 -5
  238. data/yard-stubs/carray_element.rb +4 -3
  239. data/yard-stubs/carray_limits.rb +100 -0
  240. data/yard-stubs/carray_loop.rb +0 -20
  241. data/yard-stubs/carray_mask.rb +59 -41
  242. data/yard-stubs/carray_math.rb +162 -100
  243. data/yard-stubs/carray_mathfunc.rb +415 -3
  244. data/yard-stubs/carray_median_percentile.rb +29 -11
  245. data/yard-stubs/carray_memory_view.rb +2 -2
  246. data/yard-stubs/carray_order.rb +72 -33
  247. data/yard-stubs/carray_random.rb +6 -6
  248. data/yard-stubs/carray_reduce.rb +353 -0
  249. data/yard-stubs/carray_rng.rb +92 -0
  250. data/yard-stubs/carray_scatter.rb +12 -3
  251. data/yard-stubs/carray_slab.rb +7 -4
  252. data/yard-stubs/carray_sort.rb +7 -6
  253. data/yard-stubs/carray_test.rb +18 -5
  254. data/yard-stubs/carray_undef.rb +44 -5
  255. data/yard-stubs/ruby_carray.rb +75 -40
  256. metadata +63 -25
  257. data/CHANGELOG.v1.md +0 -126
  258. data/ext/carray_build_flags.h +0 -3
  259. data/ext/carray_config.h +0 -28
  260. data/ext/carray_data_type.c +0 -90
  261. data/ext/carray_kernels_bincmp.c +0 -6457
  262. data/ext/carray_kernels_binop.c +0 -31534
  263. data/ext/carray_kernels_init.c +0 -1734
  264. data/ext/carray_kernels_moncmp.c +0 -2104
  265. data/ext/carray_kernels_monop.c +0 -25387
  266. data/ext/carray_kernels_reduce_aggregate.c +0 -27545
  267. data/ext/carray_kernels_reduce_boolean.c +0 -1924
  268. data/ext/carray_kernels_reduce_cumulative.c +0 -11646
  269. data/ext/carray_kernels_reduce_extreme.c +0 -21631
  270. data/ext/carray_kernels_reduce_variance.c +0 -5981
  271. data/ext/carray_kernels_scan.c +0 -4302
  272. data/ext/carray_kernels_search.c +0 -37776
  273. data/ext/carray_kernels_sort.c +0 -10814
  274. data/ext/carray_kernels_triop.c +0 -1864
  275. data/lib/carray/construct.rb +0 -360
  276. data/lib/carray/data_type_extension.rb +0 -261
  277. data/lib/carray/data_type_limits.rb +0 -91
@@ -39,7 +39,7 @@
39
39
  # `fill_value:` (replace an UNDEF result) — both passed straight through to
40
40
  # the core reduction — express the full spectrum from "fold whatever is
41
41
  # present" to "full windows only, edges filled". There is no window-specific
42
- # strictness knob.
42
+ # strictness option.
43
43
  #
44
44
  # The class name is kept from 2.0 (the concept — a window — is stable);
45
45
  # this is the Ruby family member that supersedes the C engine. Loaded
@@ -68,37 +68,44 @@ class CAWindowIterator < CAIterator
68
68
  # Each `ranges[i]` is a `lo..hi` giving the window's offset span around
69
69
  # an anchor (`a.windows(-1..1)` is a centred width-3 window; `0..2` is
70
70
  # forward-looking). `bounds:` selects the margin policy (`:skip` /
71
- # `:nearest` / `:truncate`). `fill_value:` is a constant margin value
72
- # (an escape for `:constant` padding); when given it overrides `:skip`.
71
+ # `:nearest` / `:fill` / `:truncate`). `fill_value:` is the value of the
72
+ # `:fill` margin; given without `bounds:`, it makes the margin `:fill`.
73
+ # `:fill` without `fill_value:` raises, and so does `fill_value:` with
74
+ # `:skip`, `:nearest` or `:truncate`, which take no fill value.
75
+ # Over a categorical or a const string, which hold no new value, it has
76
+ # to be a value some cell already holds.
73
77
  #
74
- # For backward compatibility `initialize(window_view)` with no ranges
75
- # accepts a CAWindow view (the old `CAWindowIterator.new(a.window(...))`
76
- # form): the geometry (offset ranges, bounds, fill value) is read back
77
- # from the view. Given ranges, a CAWindow view is rolled over like any
78
- # other array.
78
+ # A CAWindow view is rolled over like any other array.
79
79
  #
80
- # @param source [CArray, CAWindow] the array to roll over, or a CAWindow
81
- # view to read the geometry from.
80
+ # @param source [CArray] the array to roll over.
82
81
  # @param ranges [Array<Range>] per-axis offset ranges.
83
- # @param bounds [Symbol] `:skip` / `:nearest` / `:truncate`.
84
- # @param fill_value [Object, nil] constant margin value, overriding :skip.
85
- def initialize (source, *ranges, bounds: :skip, fill_value: nil)
86
- if ranges.empty? && source.is_a?(CArray) && source.obj_type == CA_OBJ_WINDOW
87
- # Backward-compat: read geometry from a CAWindow view built by #window.
88
- # start[i] = lo, shape[i] (window width) = w, so hi = lo + w - 1.
89
- win = source
90
- @source = win.parent
91
- widths = win.shape
92
- @ranges = win.start.each_with_index.map { |lo, i| lo..(lo + widths[i] - 1) }
93
- # The legacy #window default is FILL (constant), whose value is the
94
- # view's fill_value; map that to a :constant margin.
95
- @bounds = :constant
96
- @fill_value = win.fill_value
97
- else
98
- @source = source
99
- @ranges = ranges.flatten(0)
100
- @bounds = bounds
101
- @fill_value = fill_value
82
+ # @param bounds [Symbol] `:skip` / `:nearest` / `:fill` / `:truncate`.
83
+ # @param fill_value [Object, nil] the `:fill` margin value.
84
+ # @raise [ArgumentError] when `fill_value:` is given with a `bounds:`
85
+ # other than `:fill`.
86
+ # @raise [ArgumentError] when a categorical or const string source holds
87
+ # no cell with `fill_value` (raised when the windows are first read).
88
+ # The boundary policies a window takes.
89
+ BOUNDS = [:skip, :nearest, :fill, :truncate].freeze
90
+
91
+ def initialize(source, *ranges, bounds: nil, fill_value: nil)
92
+ @source = source
93
+ @ranges = ranges.flatten(0)
94
+ # fill_value: without bounds: is bounds: :fill; with any other bounds:
95
+ # it would have nothing to fill, and is refused as window refuses it.
96
+ @bounds = bounds || (fill_value.nil? ? :skip : :fill)
97
+ @fill_value = fill_value
98
+
99
+ unless BOUNDS.include?(@bounds)
100
+ raise ArgumentError,
101
+ "windows: unknown bounds: #{@bounds.inspect} " \
102
+ "(use :skip, :nearest, :fill or :truncate)"
103
+ end
104
+ if @bounds == :fill && @fill_value.nil?
105
+ raise ArgumentError, "windows: bounds: :fill needs fill_value: (the value the cells outside take)"
106
+ end
107
+ if @bounds != :fill && ! @fill_value.nil?
108
+ raise ArgumentError, "windows: fill_value: is for bounds: :fill, not #{@bounds.inspect}"
102
109
  end
103
110
 
104
111
  unless @ranges.size == @source.ndim
@@ -108,11 +115,11 @@ class CAWindowIterator < CAIterator
108
115
  end
109
116
  # Each window is read through a view with one axis per anchor and one
110
117
  # per cell in the window, twice the source's rank.
111
- if 2 * @source.ndim > CA_RANK_MAX
118
+ if 2 * @source.ndim > CArray::RANK_MAX
112
119
  raise ArgumentError,
113
120
  "windows: a rank #{@source.ndim} array would need #{2 * @source.ndim} " \
114
- "axes for its windows, beyond the limit of #{CA_RANK_MAX}; " \
115
- "windows works up to rank #{CA_RANK_MAX / 2}"
121
+ "axes for its windows, beyond the limit of #{CArray::RANK_MAX}; " \
122
+ "windows works up to rank #{CArray::RANK_MAX / 2}"
116
123
  end
117
124
  @ranges = @ranges.each_with_index.map { |r, k| window_offsets(r, k) }
118
125
 
@@ -121,9 +128,6 @@ class CAWindowIterator < CAIterator
121
128
  @lefts = @ranges.map { |r| [0, -r.begin].max } # left margin per axis
122
129
  @rights = @ranges.map { |r| [0, r.end ].max } # right margin per axis
123
130
 
124
- # A constant fill_value: overrides :skip (constant margin escape hatch).
125
- @bounds = :constant if @fill_value != nil && @bounds == :skip
126
-
127
131
  # Trailing window axes of the sliding_windows view: [ndim .. 2*ndim-1].
128
132
  @window_axes = (@sndim...(2 * @sndim)).to_a
129
133
 
@@ -147,11 +151,6 @@ class CAWindowIterator < CAIterator
147
151
  self
148
152
  end
149
153
 
150
- # @overload source
151
- # Returns the array being rolled over.
152
- # @return [CArray]
153
- attr_reader :source
154
-
155
154
  # @overload bounds
156
155
  # Returns the boundary policy symbol.
157
156
  # @return [Symbol]
@@ -159,15 +158,24 @@ class CAWindowIterator < CAIterator
159
158
 
160
159
  # ---- padded entity + sliding_windows view -----------------------------
161
160
  #
162
- # The engine: pad the source (:skip -> UNDEF, :nearest -> edge, :constant
161
+ # The engine: pad the source (:skip -> UNDEF, :nearest -> edge, :fill
163
162
  # -> value; :truncate does not pad), then take a sliding_windows view. Both
164
163
  # are kept for one call, so the helpers a reduction runs share one pad and
165
164
  # one view, and the next call pads the source as it is then.
166
165
 
167
166
  # @overload sliding_view
168
- # Returns the sliding_windows view feeding the reductions. For :truncate
169
- # this is the source's own view (zero-copy); otherwise it is the view over
170
- # a padded copy made from the source as it is at this call.
167
+ # Returns every window as one array: the anchor axes first ({#shape}),
168
+ # then one axis per window axis, so `sliding_view[i, nil]` is the window
169
+ # at anchor `i` of a 1-D source. The reductions of this iterator are the
170
+ # core's reductions of this array over the window axes
171
+ # (`it.mean == it.sliding_view.mean(axis: [1])` for a 1-D source), so a
172
+ # computation the iterator does not offer can be written on it directly.
173
+ #
174
+ # A cell outside the source reads as `bounds:` says: UNDEF for `:skip`,
175
+ # the nearest edge for `:nearest`, `fill_value` for `:fill`. With
176
+ # `:truncate` it is a view of the source itself; otherwise it is a view of
177
+ # a padded copy made from the source as it is at this call, so a write to
178
+ # it does not reach the source.
171
179
  # @return [CArray]
172
180
  def sliding_view
173
181
  @sliding_view ||= @shape.include?(0) ? no_windows : anchored_buffer.sliding_windows(*@widths)
@@ -177,7 +185,7 @@ class CAWindowIterator < CAIterator
177
185
 
178
186
  # An axis's offsets as an inclusive Integer range, as Ruby reads the range
179
187
  # given (`-1...1` is the offsets -1 and 0).
180
- def window_offsets (r, k)
188
+ def window_offsets(r, k)
181
189
  unless r.is_a?(Range) && r.begin.is_a?(Integer) && r.end.is_a?(Integer)
182
190
  raise TypeError,
183
191
  "windows: axis #{k} takes a Range of Integer offsets, got #{r.inspect}"
@@ -199,7 +207,7 @@ class CAWindowIterator < CAIterator
199
207
  cut = @shape.each_with_index.map { |n, k| n == unit.shape[k] ? nil : 0...n }
200
208
  unit = unit[*cut, *[nil] * @sndim] unless cut.all?(&:nil?)
201
209
  view = unit.broadcast_to(*(@shape + @widths))
202
- @source.face? ? view.face_lift(@source) : view
210
+ @source.face? ? view.send(:face_lift, @source) : view
203
211
  end
204
212
 
205
213
  # The stretch of the padded buffer the windows are taken from: it begins at
@@ -228,11 +236,7 @@ class CAWindowIterator < CAIterator
228
236
  case @bounds
229
237
  when :skip then :masked
230
238
  when :nearest then :edge
231
- when :constant then :constant
232
- else
233
- raise ArgumentError,
234
- "windows: unknown bounds #{@bounds.inspect} " \
235
- "(expected :skip, :nearest, :truncate)"
239
+ when :fill then :fill
236
240
  end
237
241
  end
238
242
 
@@ -242,13 +246,13 @@ class CAWindowIterator < CAIterator
242
246
  # escape hatches yield from the padded entity, so users never call it. A
243
247
  # standalone public CArray#pad is a possible future promotion.
244
248
  #
245
- # :constant margin cells set to `value` (0 when value is nil).
249
+ # :fill margin cells set to `value` (0 when value is nil).
246
250
  # :edge margin cells replicate the nearest source edge cell.
247
251
  # :masked margin cells are UNDEF (masked); reductions skip them.
248
252
  #
249
253
  # One allocation, the source copied into the interior region, then the
250
254
  # margins filled per mode.
251
- def pad_source (src, lefts, rights, mode, value)
255
+ def pad_source(src, lefts, rights, mode, value)
252
256
  return pad_face(src, lefts, rights, mode, value) if src.face?
253
257
  nd = src.ndim
254
258
  shape = src.shape
@@ -257,7 +261,7 @@ class CAWindowIterator < CAIterator
257
261
 
258
262
  # Fill the whole buffer first, then overwrite the interior with the source.
259
263
  case mode
260
- when :constant
264
+ when :fill
261
265
  pad[] = (value.nil? ? 0 : value)
262
266
  when :masked
263
267
  pad[] = UNDEF
@@ -275,20 +279,37 @@ class CAWindowIterator < CAIterator
275
279
  end
276
280
 
277
281
  # A Face is padded on its storage and put back on at the end, so the margins
278
- # hold storage -- UNDEF, a copy of an edge cell, or a `:constant` value the
282
+ # hold storage -- UNDEF, a copy of an edge cell, or a `:fill` value the
279
283
  # Face has turned into storage -- and the reductions over the windows are
280
284
  # the Face's own. A buffer of the Face's surface type could not take the
281
285
  # margin values at all.
282
- def pad_face (src, lefts, rights, mode, value)
286
+ def pad_face(src, lefts, rights, mode, value)
283
287
  storage = src.__send__(:face_storage)
284
- if mode == :constant && !value.nil?
285
- cell = src.__send__(:blank_like, [1])
286
- cell[0] = value
287
- padded = pad_source(storage, lefts, rights, :constant, cell.parent[0])
288
+ if mode == :fill && !value.nil?
289
+ padded = pad_source(storage, lefts, rights, :fill, margin_storage(src, storage, value))
288
290
  else
289
291
  padded = pad_source(storage, lefts, rights, mode, value)
290
292
  end
291
- padded.face_lift(src)
293
+ padded.send(:face_lift, src)
294
+ end
295
+
296
+ # The storage of a `:fill` margin value. A Face that holds new values
297
+ # turns the value into storage; one that holds none (a const string's
298
+ # records index a shared pool, a categorical's codes index its labels) can
299
+ # only repeat the storage of a cell that already holds the value.
300
+ def margin_storage(src, storage, value)
301
+ if src.__send__(:holds_new_values?)
302
+ cell = src.__send__(:blank_like, [1])
303
+ cell[0] = value
304
+ return cell.parent[0]
305
+ end
306
+ hit = src.eq(value).where
307
+ if hit.elements == 0
308
+ raise ArgumentError,
309
+ "windows: fill_value #{value.inspect} is not a value of this " \
310
+ "#{src.class}, which can only repeat a value it already holds"
311
+ end
312
+ storage.flatten[hit[0]]
292
313
  end
293
314
 
294
315
  # Edge-replicate the margins of a padded buffer whose interior already holds
@@ -296,7 +317,7 @@ class CAWindowIterator < CAIterator
296
317
  # the right margin rows copy the last; done axis by axis over the whole
297
318
  # buffer (including corners, which pick up the replicated neighbours from an
298
319
  # earlier axis, matching the standard edge-pad of corners).
299
- def replicate_edges (pad, lefts, rights, shape)
320
+ def replicate_edges(pad, lefts, rights, shape)
300
321
  pad.ndim.times do |ax|
301
322
  lo = lefts[ax]
302
323
  hi = lefts[ax] + shape[ax] - 1 # last interior index on this axis
@@ -319,7 +340,7 @@ class CAWindowIterator < CAIterator
319
340
  # A window away from the edges holds all of them, so the vector is the window
320
341
  # width everywhere but the two ends, and only the ends -- at most one window
321
342
  # width of cells each -- are counted out.
322
- def axis_cell_counts (k)
343
+ def axis_cell_counts(k)
323
344
  length = @shape[k]
324
345
  first = @ranges[k].begin
325
346
  last = @ranges[k].end
@@ -338,7 +359,7 @@ class CAWindowIterator < CAIterator
338
359
 
339
360
  # An index list of length `nd` that is `nil` (full range) on every axis
340
361
  # except `ax`, which is pinned to `k`.
341
- def axis_selector (nd, ax, k)
362
+ def axis_selector(nd, ax, k)
342
363
  sel = Array.new(nd)
343
364
  sel[ax] = k
344
365
  sel
@@ -353,7 +374,7 @@ class CAWindowIterator < CAIterator
353
374
  # `sliding_view.<op>(axis: window_axes, ...)`. This inherits the core data type,
354
375
  # mask, empty / all-masked (identity vs UNDEF) and epsilon-close contracts
355
376
  # unchanged. `min_count:` / `fill_value:` pass straight to the core (the
356
- # boundary strictness + result fill knobs).
377
+ # boundary strictness + result fill options).
357
378
 
358
379
  # @!method sum(min_count: nil, fill_value: nil)
359
380
  # Rolling sum.
@@ -459,7 +480,7 @@ class CAWindowIterator < CAIterator
459
480
  [:sum, :accumulate, :prod, :mean, :min, :max, :variance, :stddev,
460
481
  :variancep, :stddevp, :minmax, :min_index, :max_index].each do |op|
461
482
  class_eval <<~RUBY, __FILE__, __LINE__ + 1
462
- def #{op} (min_count: nil, fill_value: nil)
483
+ def #{op}(min_count: nil, fill_value: nil)
463
484
  folded = @shape.include?(0) ? nil : fold_by_offset(:#{op}, min_count, fill_value)
464
485
  return folded unless folded.nil?
465
486
  kw = {}
@@ -473,12 +494,12 @@ class CAWindowIterator < CAIterator
473
494
  # all / any take no min_count: or fill_value:, as the core ones do not.
474
495
  [:all, :any].each do |op|
475
496
  class_eval <<~RUBY, __FILE__, __LINE__ + 1
476
- def #{op} (**kw)
497
+ def #{op}(**kw)
477
498
  if kw.empty?
478
499
  folded = @shape.include?(0) ? nil : fold_by_offset(:#{op}, nil)
479
500
  return folded unless folded.nil?
480
501
  end
481
- sliding_view.#{op}(axis: @window_axes, **CAIterator.reduce_keywords(:#{op}, kw))
502
+ sliding_view.#{op}(axis: @window_axes, **CAIterator.send(:reduce_keywords, :#{op}, kw))
482
503
  end
483
504
  RUBY
484
505
  end
@@ -499,8 +520,8 @@ class CAWindowIterator < CAIterator
499
520
  # These take no `min_count:` or `fill_value:`, as the core ones do not.
500
521
  [:first, :last, :nunique].each do |op|
501
522
  class_eval <<~RUBY, __FILE__, __LINE__ + 1
502
- def #{op} (**kw)
503
- sliding_view.#{op}(axis: @window_axes, **CAIterator.reduce_keywords(:#{op}, kw))
523
+ def #{op}(**kw)
524
+ sliding_view.#{op}(axis: @window_axes, **CAIterator.send(:reduce_keywords, :#{op}, kw))
504
525
  end
505
526
  RUBY
506
527
  end
@@ -511,15 +532,15 @@ class CAWindowIterator < CAIterator
511
532
  # Unlike `min_index` (the position within the window) this indexes back into
512
533
  # the original array. The winner's source cell is the anchor plus its window
513
534
  # offset; with `bounds: :nearest` a winning margin cell resolves to the edge
514
- # source cell it replicates, and with `bounds: :constant` (or `fill_value:`)
535
+ # source cell it replicates, and with `bounds: :fill` (or `fill_value:`)
515
536
  # a winning margin cell has no source address and is a masked result.
516
537
  # @return [CArray] reference-shaped (or shrunk, for :truncate)
517
- def min_addr (**kw); window_winner_addr(:min_index, kw); end
538
+ def min_addr(**kw); window_winner_addr(:min_index, kw); end
518
539
 
519
540
  # @overload max_addr
520
541
  # Rolling flat source address of the window maximum. See {#min_addr}.
521
542
  # @return [CArray] reference-shaped (or shrunk, for :truncate)
522
- def max_addr (**kw); window_winner_addr(:max_index, kw); end
543
+ def max_addr(**kw); window_winner_addr(:max_index, kw); end
523
544
 
524
545
  private
525
546
 
@@ -536,7 +557,7 @@ class CAWindowIterator < CAIterator
536
557
  # pass is a straight walk over contiguous memory. It costs one pass per
537
558
  # offset, so it only pays while the window is small; the crossover moves with
538
559
  # rank and data type, but stays above width 5 on every axis in every
539
- # combination measured (see devel/PROPOSAL_WINDOW_OFFSET_ACCUMULATION.md).
560
+ # combination measured.
540
561
  #
541
562
  # What is decided here is the order of the fold and which pad it reads; the
542
563
  # arithmetic is the core's elementwise kernel, and the result data type is
@@ -551,7 +572,7 @@ class CAWindowIterator < CAIterator
551
572
  :all => :and!, :any => :or! }.freeze
552
573
 
553
574
  # A boolean accumulates as the core's does, by parity, so its kernel is xor.
554
- def offset_fold_kernel (op)
575
+ def offset_fold_kernel(op)
555
576
  return :xor! if op == :accumulate && @source.data_type == CA_BOOLEAN
556
577
  OFFSET_FOLD.fetch(op)
557
578
  end
@@ -561,23 +582,42 @@ class CAWindowIterator < CAIterator
561
582
 
562
583
  # Runs the fold by offset, or returns nil when this window is not one it can
563
584
  # answer for -- in which case the caller delegates as before.
564
- def fold_by_offset (op, min_count, fill_value = nil)
585
+ def fold_by_offset(op, min_count, fill_value = nil)
565
586
  return nil unless CArray.__fast_paths_enabled__(:window_fold_by_offset)
566
587
  need = CArray.__present_cells_needed_per_result_cell__(op, min_count, 0)
567
588
  return nil unless op == :mean || OFFSET_FOLD.key?(op)
568
589
  # The elementwise kernels act on a Face's storage; its reductions are its own.
569
590
  return nil if @source.face?
591
+ # Fixed-length cells have no elementwise kernels and no neutral value.
592
+ return nil if @source.data_type == CA_FIXLEN
593
+ # An undefined constant margin is a masked one, which a fold must skip.
594
+ return nil if @fill_value.equal?(UNDEF)
570
595
  return nil if @widths.any? { |width| width > OFFSET_FOLD_MAX_WIDTH }
571
- return nil if neutral_value(op).nil?
572
596
  # pmin / pmax let NaN lose, so a window holding only NaN would fold to the
573
597
  # neutral value; the core answers NaN there.
574
598
  return nil if (op == :min || op == :max) && source_has_nan?
599
+ return nil if neutral_value(op).nil?
600
+ return nil if offset_fold_can_leave_the_range?(op)
575
601
 
576
602
  folded = op == :mean ? fold_mean : accumulate_offsets(op)
577
603
  folded = mask_empty_windows(folded) if EMPTY_WINDOW_IS_UNDEFINED.include?(op)
578
604
  folded = apply_min_count(folded, need)
579
605
  # A `fill_value:` on the call replaces a result that came out undefined.
580
- CArray.__fill_undefined_result_cells__(folded, fill_value)
606
+ CArray.__fill_undefined_result_cells__(folded, fill_value, op)
607
+ end
608
+
609
+ # The core answers an integer sum or product in int64 / uint64, and in
610
+ # float64 where the total is out of that range; this path accumulates in
611
+ # the answer's type and would wrap instead. A window of at most
612
+ # OFFSET_FOLD_MAX_WIDTH cells per axis can not take a sum of cells of 4
613
+ # bytes or fewer out of int64, but a sum of 8-byte cells, or a product, can.
614
+ def offset_fold_can_leave_the_range?(op)
615
+ return false unless @source.integer?
616
+ case op
617
+ when :prod then true
618
+ when :sum, :mean then @source.bytes >= 8
619
+ else false
620
+ end
581
621
  end
582
622
 
583
623
  # The mean is the sum over the same offsets, divided by the number of cells
@@ -591,11 +631,13 @@ class CAWindowIterator < CAIterator
591
631
  divisor[counts.eq(0)] = 1
592
632
  end
593
633
  # coerce: the mean's fixed compute type
594
- accumulate_offsets(:sum).to_type(offset_fold_data_type(:mean)) / divisor
634
+ sums = accumulate_offsets(:sum).to_type(offset_fold_data_type(:mean))
635
+ # An object mean divides with quo, as the core's does (exact for Integer).
636
+ sums.data_type == CA_OBJECT ? sums.send(:quo_i, divisor) : sums / divisor
595
637
  end
596
638
 
597
639
  # Walks the window offsets, accumulating each shifted plane into the result.
598
- def accumulate_offsets (op, base = nil, kernel = nil, data_type = nil)
640
+ def accumulate_offsets(op, base = nil, kernel = nil, data_type = nil)
599
641
  base ||= offset_fold_base(op)
600
642
  kernel ||= offset_fold_kernel(op)
601
643
  data_type ||= offset_fold_data_type(op)
@@ -619,7 +661,7 @@ class CAWindowIterator < CAIterator
619
661
  # listed answer with their identity, which the accumulation already holds.
620
662
  EMPTY_WINDOW_IS_UNDEFINED = [:min, :max, :mean].freeze
621
663
 
622
- def mask_empty_windows (folded)
664
+ def mask_empty_windows(folded)
623
665
  return folded unless windows_can_be_empty?
624
666
  folded[window_cell_counts.eq(0)] = UNDEF
625
667
  folded
@@ -640,12 +682,13 @@ class CAWindowIterator < CAIterator
640
682
  end
641
683
 
642
684
  def source_has_nan?
685
+ return true if @bounds == :fill && @fill_value.is_a?(Float) && @fill_value.nan?
643
686
  return false unless @source.float? || @source.data_type == CA_OBJECT
644
687
  @source.is_nan.any
645
688
  end
646
689
 
647
690
  # A result only where the window held `need` cells (CArray.__present_cells_needed_per_result_cell__).
648
- def apply_min_count (folded, need)
691
+ def apply_min_count(folded, need)
649
692
  return folded if need == 0
650
693
  counts = window_cell_counts
651
694
  if counts.is_a?(Integer)
@@ -659,10 +702,10 @@ class CAWindowIterator < CAIterator
659
702
  # What stands in for a cell the fold must not see: a margin the boundary
660
703
  # policy does not fill, or a masked cell of the source. For sum, prod, all
661
704
  # and any that is the operation's identity. For min and max it is any value
662
- # that cannot win, and the array's own extreme is one -- so no table of
663
- # per-type limits is needed. Nil means there is none to be had (a source
664
- # masked everywhere), and the caller delegates instead.
665
- def neutral_value (op)
705
+ # that cannot win, and the extreme of the array and its constant margin is
706
+ # one -- so no table of per-type limits is needed. Nil means there is none
707
+ # to be had (a source masked everywhere), and the caller delegates instead.
708
+ def neutral_value(op)
666
709
  @neutral_value ||= {}
667
710
  return @neutral_value[op] if @neutral_value.key?(op)
668
711
  @neutral_value[op] =
@@ -676,9 +719,13 @@ class CAWindowIterator < CAIterator
676
719
  end
677
720
  end
678
721
 
679
- def source_extreme (op)
722
+ def source_extreme(op)
680
723
  value = @source.send(op)
681
- value.equal?(UNDEF) ? nil : value
724
+ return nil if value.equal?(UNDEF)
725
+ return value unless @bounds == :fill
726
+ margin = @fill_value || 0
727
+ margin = margin ? 1 : 0 if @source.boolean? # the core answers 0 or 1
728
+ [value, margin].public_send(op)
682
729
  end
683
730
 
684
731
  # The buffer the offsets are read from: the source with its margins filled
@@ -689,7 +736,7 @@ class CAWindowIterator < CAIterator
689
736
  # depends on the pair, the working set and the compiler; converting once is
690
737
  # one behaviour everywhere. It costs a buffer in the wider type, which for
691
738
  # a `sum` over bytes is the one case where it does not pay.
692
- def offset_fold_base (op)
739
+ def offset_fold_base(op)
693
740
  @offset_fold_base ||= {}
694
741
  @offset_fold_base[op] ||=
695
742
  begin
@@ -697,7 +744,7 @@ class CAWindowIterator < CAIterator
697
744
  if @source.has_mask?
698
745
  pad_for(@source.strip_mask(neutral_value(op)), neutral_value(op))
699
746
  elsif @bounds == :skip
700
- pad_source(@source, @lefts, @rights, :constant, neutral_value(op))
747
+ pad_source(@source, @lefts, @rights, :fill, neutral_value(op))
701
748
  else
702
749
  padded_entity
703
750
  end
@@ -708,12 +755,12 @@ class CAWindowIterator < CAIterator
708
755
 
709
756
  # Pads `values` the way this window's boundary policy says, with `outside`
710
757
  # standing in for the margin where the policy does not fill one.
711
- def pad_for (values, outside)
758
+ def pad_for(values, outside)
712
759
  case @bounds
713
760
  when :truncate then values
714
761
  when :nearest then pad_source(values, @lefts, @rights, :edge, nil)
715
- when :constant then pad_source(values, @lefts, @rights, :constant, @fill_value)
716
- else pad_source(values, @lefts, @rights, :constant, outside)
762
+ when :fill then pad_source(values, @lefts, @rights, :fill, @fill_value)
763
+ else pad_source(values, @lefts, @rights, :fill, outside)
717
764
  end
718
765
  end
719
766
 
@@ -722,13 +769,19 @@ class CAWindowIterator < CAIterator
722
769
  # real values, so the count is the whole window and one Integer says it;
723
770
  # `:skip` counts the in-bounds offsets, which is separable -- the count on
724
771
  # one axis depends on that axis alone. A masked source has to be counted for
725
- # real, by accumulating over the same offsets.
772
+ # real, by accumulating over the same offsets; a cell of a constant margin
773
+ # counts once, whatever its value.
726
774
  def window_cell_counts
727
775
  return @window_cell_counts unless @window_cell_counts.nil?
728
776
  @window_cell_counts =
729
777
  if @source.has_mask?
730
- accumulate_offsets(:sum, pad_for(@source.is_not_masked.int64, 0),
731
- :add!, CA_INT64)
778
+ present = @source.is_not_masked.int64
779
+ present = if @bounds == :fill
780
+ pad_source(present, @lefts, @rights, :fill, 1)
781
+ else
782
+ pad_for(present, 0)
783
+ end
784
+ accumulate_offsets(:sum, present, :add!, CA_INT64)
732
785
  elsif @bounds != :skip
733
786
  @widths.inject(:*)
734
787
  else
@@ -745,10 +798,10 @@ class CAWindowIterator < CAIterator
745
798
 
746
799
  # The data type the delegating path would have produced, asked of the core
747
800
  # itself so the two paths cannot disagree.
748
- def offset_fold_data_type (op)
801
+ def offset_fold_data_type(op)
749
802
  @offset_fold_data_type ||= {}
750
803
  @offset_fold_data_type[op] ||=
751
- CAIterator.core_probe(@source).public_send(op, axis: [1]).data_type
804
+ CAIterator.send(:core_probe, @source).public_send(op, axis: [1]).data_type
752
805
  end
753
806
 
754
807
  # Every offset within the window, as a list of per-axis positions into the
@@ -765,9 +818,9 @@ class CAWindowIterator < CAIterator
765
818
  # source coordinate on each axis is anchor + offset + window-coordinate (the
766
819
  # offset is the range's begin for a padded margin, 0 for :truncate). A margin
767
820
  # winner (coordinate out of bounds) resolves per the boundary policy:
768
- # :nearest clamps to the edge source cell, :constant / :skip mask the result.
769
- def window_winner_addr (idx_op, kw = {})
770
- kw = CAIterator.reduce_keywords(idx_op, kw)
821
+ # :nearest clamps to the edge source cell, :fill / :skip mask the result.
822
+ def window_winner_addr(idx_op, kw = {})
823
+ kw = CAIterator.send(:reduce_keywords, idx_op, kw)
771
824
  mi = send(idx_op, **kw.slice(:min_count)) # window-local flat index
772
825
  n = @source.shape
773
826
  wstride = Array.new(@sndim); acc = 1
@@ -802,29 +855,29 @@ class CAWindowIterator < CAIterator
802
855
  # cells (the effective tap count, which drops near a :skip edge);
803
856
  # `count(UNDEF)` counts masked cells; `count(v)` counts cells equal to `v`.
804
857
  # @return [CArray]
805
- def count (*args, **kw)
858
+ def count(*args, **kw)
806
859
  return count_not_masked(**kw) if args.empty?
807
860
  # The sliding_windows view is a CAStride, so its #count is not shadowed;
808
861
  # dispatch CArray#count explicitly anyway, matching the family regularity.
809
- CArray.instance_method(:count).bind_call(sliding_view, *args, axis: @window_axes,
810
- **CAIterator.reduce_keywords(:count, kw))
862
+ count_cells(sliding_view, *args, axis: @window_axes,
863
+ **CAIterator.send(:reduce_keywords, :count, kw))
811
864
  end
812
865
 
813
866
  # @overload count_not_masked
814
867
  # Rolling count of present (non-masked) cells -- the denominator of a
815
868
  # renormalizing convolution.
816
869
  # @return [CArray]
817
- def count_not_masked (**kw)
870
+ def count_not_masked(**kw)
818
871
  sliding_view.count_not_masked(axis: @window_axes,
819
- **CAIterator.reduce_keywords(:count_not_masked, kw))
872
+ **CAIterator.send(:reduce_keywords, :count_not_masked, kw))
820
873
  end
821
874
 
822
875
  # @overload count_masked
823
876
  # Rolling count of masked cells.
824
877
  # @return [CArray]
825
- def count_masked (**kw)
878
+ def count_masked(**kw)
826
879
  sliding_view.count_masked(axis: @window_axes,
827
- **CAIterator.reduce_keywords(:count_masked, kw))
880
+ **CAIterator.send(:reduce_keywords, :count_masked, kw))
828
881
  end
829
882
 
830
883
  # @overload elements
@@ -847,14 +900,15 @@ class CAWindowIterator < CAIterator
847
900
  # the kernel (one line). Both are exposed under their literal names because
848
901
  # the flip convention splits by domain (signal processing flips, image / DL
849
902
  # does not). For these, the constant margin default is 0.0 (the value a tap
850
- # reaching outside the source contributes); override with a :constant fill.
903
+ # reaching outside the source contributes); override with a :fill fill.
851
904
 
852
905
  # @overload correlate(kernel, min_count: nil, fill_value: nil)
853
906
  # Rolling cross-correlation `out[i] = Σ_j a[i+j]·k[j]` (kernel not
854
907
  # flipped). `kernel` has the shape of one window (`w_1 × ... × w_n`).
855
908
  # @param kernel [CArray] weights shaped like a single window.
856
909
  # @return [CArray]
857
- def correlate (kernel, min_count: nil, fill_value: nil)
910
+ def correlate(kernel, min_count: nil, fill_value: nil)
911
+ CArray.send(:refuse_ruby_array, "correlate", "a kernel") if kernel.is_a?(Array)
858
912
  unless kernel.shape == @widths
859
913
  raise ArgumentError,
860
914
  "correlate: kernel shape #{kernel.shape.inspect} != " \
@@ -881,15 +935,16 @@ class CAWindowIterator < CAIterator
881
935
  # symmetric kernel.
882
936
  # @param kernel [CArray] weights shaped like a single window.
883
937
  # @return [CArray]
884
- def convolve (kernel, min_count: nil, fill_value: nil)
938
+ def convolve(kernel, min_count: nil, fill_value: nil)
939
+ CArray.send(:refuse_ruby_array, "convolve", "a kernel") if kernel.is_a?(Array)
885
940
  correlate(reverse_all_axes(kernel), min_count: min_count, fill_value: fill_value)
886
941
  end
887
942
 
888
943
  private
889
944
 
890
- # Reverse a kernel on every axis (`CArray#reverse` flips all axes at once).
891
- def reverse_all_axes (kernel)
892
- kernel.reverse
945
+ # Reverse a kernel on every axis (`CArray#flip` with no argument flips all axes at once).
946
+ def reverse_all_axes(kernel)
947
+ kernel.flip
893
948
  end
894
949
 
895
950
  public
@@ -904,17 +959,18 @@ class CAWindowIterator < CAIterator
904
959
  # @overload median(min_count: nil, fill_value: nil)
905
960
  # Rolling median.
906
961
  # @return [CArray]
907
- def median (**kw)
908
- kw = CAIterator.reduce_keywords(:median, kw)
962
+ def median(**kw)
963
+ kw = CAIterator.send(:reduce_keywords, :median, kw)
909
964
  order_stat { |view, axis| view.median(axis: axis, **kw) }
910
965
  end
911
966
 
912
- # @overload percentile(*pers, min_count: nil, fill_value: nil)
913
- # Rolling percentile(s). One argument returns one CArray, several return
914
- # an array of CArrays (as `CArray#percentile`).
967
+ # @overload percentile(p, min_count: nil, fill_value: nil)
968
+ # Rolling percentile(s), in the form `CArray#percentile` returns: one p
969
+ # gives one CArray, an Array of p an Array of CArrays, and several p
970
+ # (or a CArray of p) one CArray with the p axes in front.
915
971
  # @return [CArray, Array<CArray>]
916
- def percentile (*pers, **kw)
917
- kw = CAIterator.reduce_keywords(:percentile, kw)
972
+ def percentile(*pers, **kw)
973
+ kw = CAIterator.send(:reduce_keywords, :percentile, kw)
918
974
  order_stat { |view, axis| view.percentile(*pers, axis: axis, **kw) }
919
975
  end
920
976
 
@@ -922,8 +978,10 @@ class CAWindowIterator < CAIterator
922
978
  # Rolling five-number summary `[min, Q1, median, Q3, max]` (five CArrays),
923
979
  # as `CArray#quantile`.
924
980
  # @return [Array<CArray>]
925
- def quantile
926
- order_stat { |view, axis| view.quantile(axis: axis) }
981
+ def quantile(*args, **kw)
982
+ CAIterator.send(:refuse_quantile_arguments, args)
983
+ kw = CAIterator.send(:reduce_keywords, :quantile, kw)
984
+ order_stat { |view, axis| view.quantile(axis: axis, **kw) }
927
985
  end
928
986
 
929
987
  private
@@ -951,22 +1009,28 @@ class CAWindowIterator < CAIterator
951
1009
  # @overload wsum(weights)
952
1010
  # Rolling weighted sum, `weights` shaped like a single window.
953
1011
  # @return [CArray]
954
- def wsum (weights, **kw)
955
- kw = CAIterator.reduce_keywords(:wsum, kw)
1012
+ # @raise [TypeError] when `weights` is a number, not one weight per
1013
+ # cell of a window.
1014
+ def wsum(weights, **kw)
1015
+ kw = CAIterator.send(:reduce_keywords, :wsum, kw)
956
1016
  weighted(weights) { |sv, w, axis| sv.wsum(w, axis: axis, **kw) }
957
1017
  end
958
1018
 
959
1019
  # @overload wmean(weights)
960
1020
  # Rolling weighted mean, `weights` shaped like a single window.
961
1021
  # @return [CArray]
962
- def wmean (weights, **kw)
963
- kw = CAIterator.reduce_keywords(:wmean, kw)
1022
+ # @raise [TypeError] when `weights` is a number, not one weight per
1023
+ # cell of a window.
1024
+ def wmean(weights, **kw)
1025
+ kw = CAIterator.send(:reduce_keywords, :wmean, kw)
964
1026
  weighted(weights) { |sv, w, axis| sv.wmean(w, axis: axis, **kw) }
965
1027
  end
966
1028
 
967
1029
  private
968
1030
 
969
- def weighted (weights)
1031
+ def weighted(weights)
1032
+ CArray.send(:refuse_ruby_array, "wsum/wmean", "a weight array") if weights.is_a?(Array)
1033
+ CArray.send(:refuse_scalar_weights, "wsum/wmean", "a window") if weights.is_a?(Numeric)
970
1034
  unless weights.shape == @widths
971
1035
  raise ArgumentError,
972
1036
  "wsum/wmean: weights shape #{weights.shape.inspect} != " \
@@ -1013,11 +1077,15 @@ class CAWindowIterator < CAIterator
1013
1077
  # @yieldparam window [CArray]
1014
1078
  # @return [CArray] reference-shaped (or shrunk, for :truncate)
1015
1079
  # @overload reduce(init) { |acc, elem| ... }
1016
- # Per-window fiber fold: each window's cells are folded element by element
1017
- # starting from `init`.
1080
+ # Per-window fiber fold: each window's present cells are folded element
1081
+ # by element from a copy of `init` (`init.dup`). A masked cell and a cell
1082
+ # outside the array (the `:skip` margin) are not passed.
1018
1083
  # @param init [Object] initial accumulator.
1019
1084
  # @return [CArray]
1020
- def reduce (*args, data_type: nil, &blk)
1085
+ def reduce(*args, data_type: nil, &blk)
1086
+ if args.size > 1
1087
+ raise ArgumentError, "reduce: wrong number of arguments (given #{args.size}, expected 0..1)"
1088
+ end
1021
1089
  raise LocalJumpError, "no block given (yield)" unless blk
1022
1090
  dt = data_type || CA_OBJECT
1023
1091
  out = CArray.new(dt, @shape)
@@ -1028,8 +1096,8 @@ class CAWindowIterator < CAIterator
1028
1096
  else
1029
1097
  init = args[0]
1030
1098
  each_anchor_index do |idx|
1031
- acc = init
1032
- sv[*idx, *nils].each { |e| acc = blk.call(acc, e) }
1099
+ acc = init.dup
1100
+ sv[*idx, *nils].each { |e| acc = blk.call(acc, e) unless UNDEF.equal?(e) }
1033
1101
  out[*idx] = acc
1034
1102
  end
1035
1103
  end
@@ -1041,7 +1109,7 @@ class CAWindowIterator < CAIterator
1041
1109
  # an element-wise transform has no well-defined scatter-back. Raises
1042
1110
  # NotImplementedError; use {#reduce} for a custom per-window fold.
1043
1111
  # @raise [NotImplementedError]
1044
- def map (*)
1112
+ def map(*)
1045
1113
  raise NotImplementedError,
1046
1114
  "#{self.class} has no map: overlapping windows share cells, so an " \
1047
1115
  "element-wise scatter-back is ill-defined; use reduce for a custom " \
@@ -1055,7 +1123,7 @@ class CAWindowIterator < CAIterator
1055
1123
  # NotImplementedError. (min_addr / max_addr are fine: the single winning
1056
1124
  # cell of a window is a real source cell.)
1057
1125
  # @raise [NotImplementedError]
1058
- def sort_addr (*)
1126
+ def sort_addr(*)
1059
1127
  raise NotImplementedError,
1060
1128
  "#{self.class} has no sort_addr: padded boundary cells have no " \
1061
1129
  "source address and overlapping windows share cells, so a per-window " \
@@ -1119,7 +1187,7 @@ class CAWindowIterator < CAIterator
1119
1187
  # position in one piece; overlapping windows put a cell in many windows.
1120
1188
  # Use `source.lag(n, axis:)` for the lag along an axis.
1121
1189
  # @raise [NotImplementedError]
1122
- def lag (*)
1190
+ def lag(*)
1123
1191
  raise NotImplementedError,
1124
1192
  "#{self.class} has no lag: a cell belongs to many overlapping windows, " \
1125
1193
  "so it has no single position to step back from; use " \
@@ -1131,22 +1199,22 @@ class CAWindowIterator < CAIterator
1131
1199
  # windows, so it has no single value to be filled with. Use
1132
1200
  # `source.strip_mask(method:, axis:)` for a fill along an axis.
1133
1201
  # @raise [NotImplementedError]
1134
- def strip_mask (*, **)
1202
+ def strip_mask(*, **)
1135
1203
  raise NotImplementedError,
1136
1204
  "#{self.class} has no strip_mask: a cell belongs to many overlapping " \
1137
1205
  "windows, so it has no single fill; use source.strip_mask(method:, axis:) " \
1138
1206
  "for a fill along an axis."
1139
1207
  end
1140
1208
 
1141
- # @!method order
1209
+ # @!method rank_index
1142
1210
  # Not supported for a window iterator: a cell belongs to many overlapping
1143
- # windows, so it has no single rank. Use `source.order(axis:)` for the
1211
+ # windows, so it has no single rank. Use `source.rank_index(axis:)` for the
1144
1212
  # rank along an axis.
1145
1213
  # @raise [NotImplementedError]
1146
- def order (*, **)
1214
+ def rank_index(*, **)
1147
1215
  raise NotImplementedError,
1148
- "#{self.class} has no order: a cell belongs to many overlapping windows, " \
1149
- "so it has no single rank; use source.order(axis:) for the rank along " \
1216
+ "#{self.class} has no rank_index: a cell belongs to many overlapping windows, " \
1217
+ "so it has no single rank; use source.rank_index(axis:) for the rank along " \
1150
1218
  "an axis."
1151
1219
  end
1152
1220
 
@@ -1169,19 +1237,19 @@ class CArray
1169
1237
  # @overload windows(*ranges, bounds: :skip, fill_value: nil)
1170
1238
  # Returns a {CAWindowIterator} rolling a per-axis offset window over
1171
1239
  # `self`. Each `ranges[i]` is a `lo..hi` offset span (`a.windows(-1..1)`
1172
- # is a centred width-3 window); `bounds:` selects the margin policy. With
1173
- # no ranges (`a.windows(a.window(...))` passing a CAWindow view) the
1174
- # geometry is read from the view for backward compatibility.
1240
+ # is a centred width-3 window); `bounds:` selects the margin policy.
1175
1241
  # @param ranges [Array<Range>] per-axis offset ranges.
1176
- # @param bounds [Symbol] `:skip` / `:nearest` / `:truncate`.
1177
- # @param fill_value [Object, nil] constant margin value.
1242
+ # @param bounds [Symbol] `:skip` / `:nearest` / `:fill` / `:truncate`.
1243
+ # @param fill_value [Object, nil] constant margin value; alone it makes
1244
+ # the margin `:fill`, and with another `bounds:` it is refused.
1178
1245
  # @return [CAWindowIterator]
1179
1246
  # @overload windows(on:, before: nil, after: nil, exclude: :lower, by: nil, interval: nil, at: nil)
1180
1247
  # Returns a {CAKeyWindowIterator}: a window per value bounded by a width
1181
1248
  # of the key `on` (a time, a duration or a number) instead of a count of
1182
1249
  # cells. The window of a value whose key is t holds the values whose
1183
1250
  # key lies between t - before and t + after; `exclude:` leaves out the
1184
- # lower end (default), the upper end, both or neither. `by:` keeps
1251
+ # lower end (default, so a value on the boundary of two windows is in
1252
+ # one of them), the upper end, both or neither. `by:` keeps
1185
1253
  # each window within the values with the same by keys, and `interval:`
1186
1254
  # gives the key's grid step for {CAKeyWindowIterator#is_complete}. A
1187
1255
  # value whose key is masked, NaN or infinite is in no window and has no
@@ -1192,7 +1260,12 @@ class CArray
1192
1260
  # temp.windows(on: time, before: "1 hour").mean
1193
1261
  # temp.windows(on: time, at: hours, after: "3 hours", exclude: :upper).mean
1194
1262
  # @return [CAKeyWindowIterator]
1195
- def windows (*ranges, on: nil, **key_window)
1263
+ # The keywords of a window on a key (on: aside), which an offset window
1264
+ # refuses as needing on:.
1265
+ KEY_WINDOW_KEYWORDS = %i[before after exclude by interval at].freeze
1266
+ private_constant :KEY_WINDOW_KEYWORDS
1267
+
1268
+ def windows(*ranges, on: nil, **key_window)
1196
1269
  unless on.nil?
1197
1270
  unless ranges.empty?
1198
1271
  raise ArgumentError, "windows: give offset ranges or on:, not both"
@@ -1207,15 +1280,19 @@ class CArray
1207
1280
  require "carray/key_windows"
1208
1281
  return CAKeyWindowIterator.new(self, on: on, **key_window)
1209
1282
  end
1210
- bounds = key_window.delete(:bounds) { :skip }
1283
+ bounds = key_window.delete(:bounds)
1211
1284
  fill_value = key_window.delete(:fill_value)
1212
- unless key_window.empty?
1285
+ keyed = key_window.keys & KEY_WINDOW_KEYWORDS
1286
+ unknown = key_window.keys - KEY_WINDOW_KEYWORDS
1287
+ unless unknown.empty?
1213
1288
  raise ArgumentError,
1214
- "windows: #{key_window.keys.map { |k| "#{k}:" }.join(', ')} " \
1215
- "need on:, the key the widths are measured on"
1289
+ "windows: unknown keyword#{unknown.size > 1 ? 's' : ''}: " \
1290
+ "#{unknown.map(&:inspect).join(', ')}"
1216
1291
  end
1217
- if ranges.size == 1 && ranges[0].is_a?(CArray) && ranges[0].obj_type == CA_OBJ_WINDOW
1218
- return CAWindowIterator.new(ranges[0])
1292
+ unless keyed.empty?
1293
+ raise ArgumentError,
1294
+ "windows: #{keyed.map { |k| "#{k}:" }.join(', ')} " \
1295
+ "need on:, the key the widths are measured on"
1219
1296
  end
1220
1297
  CAWindowIterator.new(self, *ranges, bounds: bounds, fill_value: fill_value)
1221
1298
  end