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
data/lib/carray/basics.rb CHANGED
@@ -13,10 +13,36 @@
13
13
 
14
14
  class CArray
15
15
 
16
+ # A Ruby Array has no data type of its own, so it does not stand in for a
17
+ # CArray: each reading of it (an object array by to_ca, the receiver's
18
+ # type, the type of its values) disagrees with another rule. The caller
19
+ # makes it a CArray of the type it means. The example names types to
20
+ # write rather than the receiver's, which would cut a Float down.
21
+ def self.refuse_ruby_array(name, role, dt = nil)
22
+ example = dt == CA_BOOLEAN ? "CA_BOOLEAN(ary)" : "CA_INT64(ary) or CA_FLOAT64(ary)"
23
+ raise TypeError,
24
+ "#{name}: a Ruby Array is not #{role}; make it a CArray of the " \
25
+ "type you mean first, e.g. #{example}"
26
+ end
27
+ private_class_method :refuse_ruby_array
28
+
29
+ # One number given as the weights of an iterator, which takes one weight
30
+ # per cell (of the value, of a window or of a tile). CArray#wsum reads a
31
+ # number as the weight of every cell; for that, the iterator's own sum and
32
+ # mean already answer.
33
+ def self.refuse_scalar_weights(name, per)
34
+ raise TypeError,
35
+ "#{name}: the weights are a CArray with one weight per cell of " \
36
+ "#{per}, not a number; with one weight w on every cell, wsum is " \
37
+ "w times sum and wmean is mean"
38
+ end
39
+ private_class_method :refuse_scalar_weights
40
+
41
+
16
42
  # The order sort puts two object values in (ca_obj_order_cmp in C): a
17
43
  # Float NaN after every other value, NaN ties NaN, other pairs by `<=>`.
18
44
  # nil when `<=>` cannot order the pair; the caller says what refused.
19
- private_class_method def self.object_order_cmp (a, b)
45
+ private_class_method def self.object_order_cmp(a, b)
20
46
  a_nan = a.is_a?(Float) && a.nan?
21
47
  b_nan = b.is_a?(Float) && b.nan?
22
48
  return (a_nan ? 1 : 0) - (b_nan ? 1 : 0) if a_nan || b_nan
@@ -60,7 +86,7 @@ class CArray
60
86
  # a.insert_axis(0) # shape (1, 3, 4)
61
87
  # a.insert_axis(1, repeat: 5) # shape (3, 5, 4)
62
88
  # a.insert_axis(0, 1, repeat: [1, 3]) # size-1 then bound
63
- def insert_axis (*positions, repeat: nil)
89
+ def insert_axis(*positions, repeat: nil)
64
90
  flat = positions.flatten
65
91
  if flat.empty?
66
92
  raise ArgumentError, "insert_axis: at least one position is required"
@@ -131,18 +157,18 @@ class CArray
131
157
  end
132
158
 
133
159
  # @overload address
134
- # Returns an int32 CArray of the same shape as `self` where each
160
+ # Returns an int64 CArray of the same shape as `self` where each
135
161
  # cell holds its row-major flat address.
136
162
  # @return [CArray]
137
163
  def address
138
- return CArray.int32(*shape).seq!
164
+ return CArray.int64(*shape).seq!
139
165
  end
140
166
 
141
167
  # @overload false
142
168
  # Returns a boolean CArray of the same shape as `self` filled
143
169
  # with `false`.
144
170
  # @return [CArray]
145
- def false ()
171
+ def false()
146
172
  return template(:boolean)
147
173
  end
148
174
 
@@ -150,7 +176,7 @@ class CArray
150
176
  # Returns a boolean CArray of the same shape as `self` filled
151
177
  # with `true`.
152
178
  # @return [CArray]
153
- def true ()
179
+ def true()
154
180
  return template(:boolean) { 1 }
155
181
  end
156
182
 
@@ -158,7 +184,7 @@ class CArray
158
184
  # out of range (a time array reads its bounds as times, a record array
159
185
  # orders by its declared members, a Face that cannot be ordered refuses),
160
186
  # and its store writes the bound or the fill value into them.
161
- private def face_clip (min, max, fill_value, lfill, ufill)
187
+ private def face_clip(min, max, fill_value, lfill, ufill)
162
188
  lfill = fill_value if lfill.nil?
163
189
  ufill = fill_value if ufill.nil?
164
190
  out = copy
@@ -180,10 +206,17 @@ class CArray
180
206
  # that view that cannot be written.
181
207
  private def holds_new_values? = true
182
208
 
183
- private def blank_like (shape)
209
+ # The `sort:` of unique and the set operations is true or false (nil reads
210
+ # as false). A Symbol such as value_counts's `:count` would otherwise be
211
+ # taken as true and give the values in their own order.
212
+ private def sort_flag(sort, verb)
213
+ CArray.send(:bool_arg, sort, "sort", verb)
214
+ end
215
+
216
+ private def blank_like(shape)
184
217
  storage = face_storage
185
218
  out = CArray.new(storage.data_type, shape, bytes: storage.bytes)
186
- face? ? out.face_lift(self) : out
219
+ face? ? out.send(:face_lift, self) : out
187
220
  end
188
221
 
189
222
  # Sub-region copy (paste / crop), the old C `ca_paste` / `ca_clip` pair.
@@ -202,7 +235,8 @@ class CArray
202
235
  # @return [self]
203
236
  # @raise [ArgumentError] when `offset.length != self.ndim`.
204
237
  # @raise [FrozenError] when `self` is frozen.
205
- def paste (offset, src)
238
+ def paste(offset, src)
239
+ CArray.send(:refuse_ruby_array, "paste", "an array to paste") if src.is_a?(Array)
206
240
  # The write goes through a window view, which is not frozen itself:
207
241
  # refuse a frozen self here, as a write into it directly is refused.
208
242
  if frozen?
@@ -227,7 +261,7 @@ class CArray
227
261
  # @param dst [CArray] destination array; mutated in place.
228
262
  # @return [CArray] `dst`.
229
263
  # @raise [ArgumentError] when `offset.length != self.ndim`.
230
- def crop (offset, dst)
264
+ def crop(offset, dst)
231
265
  raise ArgumentError, "offset length must equal ndim" if offset.length != ndim
232
266
  src_ranges = []
233
267
  dst_ranges = []
@@ -242,36 +276,72 @@ class CArray
242
276
  dst
243
277
  end
244
278
 
245
- # @overload lookup(table, fill_value = nil, lfill: nil, ufill: nil)
279
+ # @overload lookup(table, fill_value: nil, lfill: nil, ufill: nil)
246
280
  # Returns values gathered from `table` at the indices given by
247
- # `self`. Equivalent to `table.project(self, lfill, ufill)` with
248
- # the receiver / first argument swapped so the index reads as
249
- # the subject. `fill_value` is sugar for symmetric dual-fill;
250
- # `lfill` / `ufill` override per side (`UNDEF` or `nil` masks
251
- # that end), following the `project` vocabulary.
281
+ # `self`. Equivalent to `table.project(self, fill_value:, lfill:,
282
+ # ufill:)` with the receiver / first argument swapped so the index
283
+ # reads as the subject. `fill_value` fills both ends; `lfill` /
284
+ # `ufill` override per side (`UNDEF` or `nil` masks that end).
252
285
  # @param table [CArray] value table indexed by `self`.
253
286
  # @param fill_value [Object, nil] symmetric fill for below- and
254
287
  # above-range indices.
255
288
  # @param lfill [Object, nil] override for below-range fill.
256
289
  # @param ufill [Object, nil] override for above-range fill.
257
290
  # @return [CArray] gathered values with the shape of `self`.
258
- def lookup(table, fill_value=nil, lfill: nil, ufill: nil)
259
- lfill = fill_value if lfill.nil?
260
- ufill = fill_value if ufill.nil?
261
- table.project(self, lfill, ufill)
291
+ def lookup(table, fill_value: nil, lfill: nil, ufill: nil)
292
+ table.project(self, fill_value: fill_value, lfill: lfill, ufill: ufill)
262
293
  end
263
294
 
264
295
  # @overload <=>(other)
265
296
  # Returns an element-wise 3-way comparison: `+1` where
266
297
  # `self > other`, `-1` where `self < other`, `0` where equal.
267
- # Output `data_type` is `CA_INT8`.
298
+ # Output `data_type` is `CA_INT8`. A number on the left (`2 <=> a`)
299
+ # answers element-wise too, except a Rational: its `<` `<=` `>` `>=`
300
+ # read `<=>` as one value, so `Rational(1, 3) <=> a` and
301
+ # `Rational(1, 3) < a` raise TypeError. Put the array on the left:
302
+ # `a > Rational(1, 3)`.
268
303
  # @param other [CArray, Numeric] operand to compare against.
269
304
  # @return [CArray]
270
- def <=> (other)
305
+ def <=>(other)
271
306
  (self > other).as_int8 - (self < other).as_int8
272
307
  end
273
308
 
274
- alias cmp <=>
309
+ # Marks the scalar made from a Rational, whose comparison operators come
310
+ # from Comparable and reach the array through this scalar's <=>.
311
+ module MarkScalarFromRational
312
+ def coerce(other)
313
+ pair = super
314
+ if other.is_a?(Rational) && pair[0].is_a?(CScalar)
315
+ pair[0].instance_variable_set(:@coerced_from_rational, true)
316
+ end
317
+ pair
318
+ end
319
+ end
320
+ private_constant :MarkScalarFromRational
321
+ prepend MarkScalarFromRational
322
+
323
+ end
324
+
325
+ class CScalar
326
+
327
+ # Refuses a 3-way comparison with an array for a scalar made from a
328
+ # Rational. Comparable reads the answer of `<=>` as one value, so
329
+ # `Rational(1,3) > a` would read the element-wise answer as a single truth
330
+ # value and be `true` for any `a`. Other scalars (`2 <=> a`) answer
331
+ # element-wise as before.
332
+ def <=>(other)
333
+ if instance_variable_defined?(:@coerced_from_rational) &&
334
+ other.is_a?(CArray) && !other.is_a?(CScalar)
335
+ raise TypeError,
336
+ "<=>: a Rational does not compare with an array as one value; " \
337
+ "put the array on the left (a > x, not x < a)"
338
+ end
339
+ super
340
+ end
341
+
342
+ end
343
+
344
+ class CArray
275
345
 
276
346
  # @!group Elementwise math
277
347
 
@@ -288,7 +358,7 @@ class CArray
288
358
  # floor toward.
289
359
  # @example
290
360
  # CA_INT32([-7]).divmod(3) # => [-3, 2]
291
- # CA_DOUBLE([-7.0]).divmod(3.0) # => [-3.0, 2.0]
361
+ # CA_FLOAT64([-7.0]).divmod(3.0) # => [-3.0, 2.0]
292
362
  def divmod(other)
293
363
  if complex?
294
364
  raise ArgumentError, "divmod is not defined for complex arrays"
@@ -300,32 +370,140 @@ class CArray
300
370
 
301
371
  # @!endgroup
302
372
 
373
+ UNSIGNED = [CA_UINT8, CA_UINT16, CA_UINT32, CA_UINT64].freeze
374
+
303
375
  # An Integer shift count on an integer array means what it means to
304
376
  # Integer#<< and #>>: negative shifts the other way, and a count past the
305
377
  # width shifts every bit out. The kernels do that for a count of the
306
378
  # array's own type; this brings a count the type cannot hold -- -1 for a
307
379
  # uint8 array, 300 for an int8 one -- to one it can.
308
380
  module IntegerShiftCount
309
- UNSIGNED = [CA_UINT8, CA_UINT16, CA_UINT32, CA_UINT64].freeze
310
-
311
- def << (other)
381
+ def <<(other)
312
382
  return super unless other.is_a?(Integer) && integer? && ! face?
313
383
  w = bytes * 8
314
384
  return self >> -other if other < 0 && UNSIGNED.include?(data_type)
315
385
  super(other.clamp(-w, w))
316
386
  end
317
387
 
318
- def >> (other)
388
+ def >>(other)
319
389
  return super unless other.is_a?(Integer) && integer? && ! face?
320
390
  w = bytes * 8
321
391
  return self << -other if other < 0 && UNSIGNED.include?(data_type)
322
392
  super(other.clamp(-w, w))
323
393
  end
394
+
395
+ def bit_lshift!(other)
396
+ return super unless other.is_a?(Integer) && integer? && ! face?
397
+ w = bytes * 8
398
+ return bit_rshift!(-other) if other < 0 && UNSIGNED.include?(data_type)
399
+ super(other.clamp(-w, w))
400
+ end
401
+
402
+ def bit_rshift!(other)
403
+ return super unless other.is_a?(Integer) && integer? && ! face?
404
+ w = bytes * 8
405
+ return bit_lshift!(-other) if other < 0 && UNSIGNED.include?(data_type)
406
+ super(other.clamp(-w, w))
407
+ end
324
408
  end
409
+
410
+ # An Integer exponent on an integer array is a count, not a value of the
411
+ # array's type: `a ** 1000` multiplies 1000 times and keeps the answer
412
+ # modulo 2 ** bits, as the kernels do for an exponent of the array's own
413
+ # type. An exponent the type can not hold is brought to one it can that
414
+ # gives the same answer: x ** p modulo 2 ** n repeats with period
415
+ # 2 ** (n - 2) once p is at least n (an even x is then 0), and a
416
+ # negative power is decided by x and the parity of p alone. An integer
417
+ # CScalar exponent is read as its Integer.
418
+ module IntegerPowerCount
419
+ def **(other)
420
+ if unfit_scalar_base_of?(other)
421
+ return other.send(:power_with_unfit_base, self[0])
422
+ end
423
+ count = integer_power_count(other)
424
+ return unsigned_reciprocal_power if unsigned_negative_count?(count)
425
+ return super(count)
426
+ end
427
+
428
+ def pow!(other)
429
+ count = integer_power_count(other)
430
+ if unsigned_negative_count?(count)
431
+ self[] = unsigned_reciprocal_power
432
+ return self
433
+ end
434
+ return super(count)
435
+ end
436
+
437
+ private
438
+
439
+ def integer_power_count(other)
440
+ return other unless integer? && ! face?
441
+ if other.is_a?(CScalar) && other.integer? && ! other.face? && ! other.any_masked?
442
+ other = other[0]
443
+ end
444
+ return other unless other.is_a?(Integer)
445
+ bits = bytes * 8
446
+ if UNSIGNED.include?(data_type)
447
+ return other if other < 0 # unsigned_reciprocal_power
448
+ lo, hi = 0, 2**63 - 1 # the kernels read the count as int64
449
+ else
450
+ lo, hi = -2**(bits - 1), 2**(bits - 1) - 1
451
+ end
452
+ return other if other.between?(lo, hi)
453
+ return ( other.even? ? -2 : -1 ) if other < 0
454
+ return bits + (other - bits) % 2**(bits - 2)
455
+ end
456
+
457
+ # An integer CScalar on the left whose value the array's type can not
458
+ # hold is taken at its value, as an Integer is.
459
+ def unfit_scalar_base_of?(other)
460
+ return false unless is_a?(CScalar) && integer? && ! face? && ! any_masked?
461
+ return false unless other.is_a?(CArray) && ! other.is_a?(CScalar) &&
462
+ other.integer? && ! other.face?
463
+ bits = other.bytes * 8
464
+ lo, hi = UNSIGNED.include?(other.data_type) ?
465
+ [0, 2**bits - 1] : [-2**(bits - 1), 2**(bits - 1) - 1]
466
+ return ! self[0].between?(lo, hi)
467
+ end
468
+
469
+ # base ** self for an Integer base this array's type can not hold. A
470
+ # cell with an exponent of 0 or more gets the base cut to the type
471
+ # (modulo 2 ** bits): b and b' equal modulo 2 ** n give b ** p and
472
+ # b' ** p equal modulo 2 ** n. A negative exponent is 1 / base ** -p
473
+ # in integer division, which the base decides itself and the cut base
474
+ # would not (256 is 0 as uint8, 257 is 1): the base is at least 2 in
475
+ # size, so the cell is 0.
476
+ def power_with_unfit_base(base)
477
+ bits = bytes * 8
478
+ cut = base % 2**bits
479
+ if UNSIGNED.include?(data_type)
480
+ return cut ** self
481
+ end
482
+ cut -= 2**bits if cut >= 2**(bits - 1)
483
+ negative = self.lt(0)
484
+ power = cut ** negative.then_else(0, self)
485
+ return negative.then_else(0, power)
486
+ end
487
+
488
+ def unsigned_negative_count?(count)
489
+ return count.is_a?(Integer) && count < 0 &&
490
+ UNSIGNED.include?(data_type) && ! face?
491
+ end
492
+
493
+ # x ** -p is 1 / x ** p in integer division, which x decides alone, as
494
+ # on a signed array: 0 has no reciprocal, 1 stays 1, anything larger
495
+ # is 0. The kernels of an unsigned array take no negative exponent.
496
+ def unsigned_reciprocal_power
497
+ raise ZeroDivisionError, "divided by 0" if self.eq(0).any
498
+ # coerce: x ** p keeps the type of x, as the kernels give it
499
+ return self.eq(1).to_type(data_type)
500
+ end
501
+ end
502
+
325
503
  # Prepended by carray/lazy, after it has wrapped << and >>: prepended
326
504
  # here, the method lazy aliases as the eager form would be this one.
327
505
 
328
- # @overload clip(min, max = nil, fill_value = nil, lfill: nil, ufill: nil)
506
+ # @overload clip(min, max = nil, fill_value: nil, lfill: nil, ufill: nil)
329
507
  # Returns `self` with every element clamped to `[min, max]`.
330
508
  #
331
509
  # Either bound may be `nil` for a one-sided clip. When
@@ -343,6 +521,12 @@ class CArray
343
521
  # as `nil` does for the whole side. A bound is never UNDEF or
344
522
  # masked: a missing bound is not read as either, so fill it first.
345
523
  #
524
+ # On an integer array an Integer bound the type can not hold is taken
525
+ # by value: a lower bound below the type or an upper bound above it
526
+ # bounds nothing (`CA_UINT8([1, 200]).clip(0, 1000)` is `[1, 200]`);
527
+ # a lower bound above the type or an upper bound below it would put
528
+ # every cell out of the type, and raises `RangeError`.
529
+ #
346
530
  # Boundary is strict `[min, max]`: values equal to a bound
347
531
  # remain unchanged in both the clamped and filled variants. A NaN
348
532
  # is in neither range and stays NaN.
@@ -359,11 +543,13 @@ class CArray
359
543
  # @raise [ArgumentError] when both `min` and `max` are `nil`,
360
544
  # when either is `UNDEF` or has a masked cell, or when `min`
361
545
  # exceeds `max`.
546
+ # @raise [TypeError] on a numeric array, when a bound is a Ruby value
547
+ # that is not a real number (true, a String, a Complex).
362
548
  # @example
363
549
  # a.clip(0, 10) # strict clamp
364
- # a.clip(0, 10, -1) # both ends -> -1
550
+ # a.clip(0, 10, fill_value: -1) # both ends -> -1
365
551
  # a.clip(0, 10, lfill: UNDEF, ufill: 99) # below masks
366
- def clip(min, max=nil, fill_value=nil, lfill: nil, ufill: nil)
552
+ def clip(min, max=nil, fill_value: nil, lfill: nil, ufill: nil)
367
553
  if min.nil? && max.nil?
368
554
  raise ArgumentError, "clip: at least one of (min, max) must be given"
369
555
  end
@@ -377,9 +563,20 @@ class CArray
377
563
  "unbounded, and UNDEF as the fill masks the cells out of range)"
378
564
  end
379
565
  return face_clip(min, max, fill_value, lfill, ufill) if face?
566
+ if numeric?
567
+ [min, max].each do |bound|
568
+ next if bound.nil? || bound.is_a?(CArray) || bound.is_a?(Array)
569
+ next if bound.is_a?(Numeric) && bound.real?
570
+ raise TypeError, "clip: #{bound.inspect} (#{bound.class}) is not a bound; " \
571
+ "a bound is a real number or a CArray"
572
+ end
573
+ end
380
574
  if !min.nil? && !max.nil?
575
+ # A Ruby Array bound is refused by the clamp below (the operand rule
576
+ # of pmax / pmin), so it is not compared here.
381
577
  reversed = if min.is_a?(CArray) then min.gt(max).any
382
578
  elsif max.is_a?(CArray) then max.lt(min).any
579
+ elsif min.is_a?(Array) || max.is_a?(Array) then false
383
580
  else min > max
384
581
  end
385
582
  if reversed
@@ -409,11 +606,11 @@ class CArray
409
606
  # A one-sided clip of a float array passes a NaN cell through, as the
410
607
  # two-sided one does: the open side is a NaN bound, which leaves it
411
608
  # unbounded. pmax / pmin would answer the bound for a NaN cell.
412
- protected def clamp_below (min)
609
+ protected def clamp_below(min)
413
610
  float? ? clamp_between(min, Float::NAN) : pmax(min)
414
611
  end
415
612
 
416
- protected def clamp_above (max)
613
+ protected def clamp_above(max)
417
614
  float? ? clamp_between(Float::NAN, max) : pmin(max)
418
615
  end
419
616
 
@@ -438,7 +635,8 @@ class CArray
438
635
  # endpoint. Concretely:
439
636
  #
440
637
  # - inclusive range `a..b`: `self[0] == a`, `self[-1] == b`,
441
- # intermediate values are evenly spaced.
638
+ # intermediate values are evenly spaced. A one-element array holds
639
+ # `a`.
442
640
  # - exclusive range `a...b`: `self[0] == a`, `self[-1] == a + (N-1)
443
641
  # * (b-a)/N` (endpoint `b` is not reached).
444
642
  #
@@ -459,7 +657,7 @@ class CArray
459
657
  # @param range [Range<Numeric>] value range to span.
460
658
  # @return [self]
461
659
  # @raise [ArgumentError] when `self` is not a float array.
462
- def span! (range)
660
+ def span!(range)
463
661
  unless float?
464
662
  raise ArgumentError,
465
663
  "span!: integer arrays are ambiguous — 'N evenly-spaced " \
@@ -470,9 +668,15 @@ class CArray
470
668
  " (B) N labels distributed uniformly over range values:\n" \
471
669
  " CArray.int32(N).seq * (b - a + 1) / N + a"
472
670
  end
671
+ CArray.send(:refuse_non_real_bounds, "span!", range.begin, range.end)
473
672
  first = range.begin.to_r
474
673
  last = range.end.to_r
475
- step = range.exclude_end? ? (last-first)/elements : (last-first)/(elements-1)
674
+ return self if elements == 0
675
+ # One element over an inclusive range holds the start.
676
+ step = if range.exclude_end? then (last-first)/elements
677
+ elsif elements == 1 then 0
678
+ else (last-first)/(elements-1)
679
+ end
476
680
  seq!(first, step)
477
681
  return self
478
682
  end
@@ -483,21 +687,35 @@ class CArray
483
687
  # @param range [Range<Numeric>] value range to span.
484
688
  # @return [CArray]
485
689
  # @raise [ArgumentError] when `self` is not a float array.
486
- def span (range)
690
+ def span(range)
691
+ CArray.send(:refuse_non_real_bounds, "span", range.begin, range.end)
487
692
  return template.span!(range)
488
693
  end
489
694
 
490
695
  # @overload scale!(xa, xb)
491
696
  # Sets `self` to `elements` evenly spaced float64 values from
492
- # `xa` to `xb` inclusive.
697
+ # `xa` to `xb` inclusive. A one-element array holds `xa`.
493
698
  # @param xa [Numeric] first value.
494
699
  # @param xb [Numeric] last value.
495
700
  # @return [self]
496
- def scale! (xa, xb)
701
+ def scale!(xa, xb)
702
+ CArray.send(:refuse_non_real_bounds, "scale!", xa, xb)
497
703
  xa = xa.to_f
498
704
  xb = xb.to_f
499
- seq!(xa, (xb-xa)/(elements-1))
705
+ seq!(xa, elements > 1 ? (xb-xa)/(elements-1) : 0.0)
706
+ end
707
+
708
+ # The ends of an evenly spaced range (linspace, span!, scale!) are read as
709
+ # real numbers. Anything else that answers to_f (nil, a String, a Time)
710
+ # would be read as a number it is not, so it is refused.
711
+ def self.refuse_non_real_bounds(name, *values)
712
+ values.each do |v|
713
+ next if v.is_a?(Numeric) && v.real?
714
+ hint = v.is_a?(Time) ? "; for times use CArray.time_range" : ""
715
+ raise TypeError, "#{name}: a bound must be a real number (got #{v.inspect})#{hint}"
716
+ end
500
717
  end
718
+ private_class_method :refuse_non_real_bounds
501
719
 
502
720
  # @overload scale(xa, xb)
503
721
  # Returns a fresh CArray shaped like `self` holding `elements`
@@ -505,7 +723,8 @@ class CArray
505
723
  # @param xa [Numeric] first value.
506
724
  # @param xb [Numeric] last value.
507
725
  # @return [CArray]
508
- def scale (xa, xb)
726
+ def scale(xa, xb)
727
+ CArray.send(:refuse_non_real_bounds, "scale", xa, xb)
509
728
  template.scale!(xa, xb)
510
729
  end
511
730
 
@@ -527,6 +746,7 @@ class Array
527
746
  # @return [CArray]
528
747
  # @raise [RuntimeError] when `writable: true` is given.
529
748
  def to_ca(writable: false)
749
+ writable = CArray.send(:bool_arg, writable, "writable", "to_ca")
530
750
  if writable
531
751
  raise "#{self.class}#to_ca builds a new array; " \
532
752
  "it can't satisfy `writable: true'"
@@ -556,6 +776,7 @@ class Range
556
776
  # @return [CArray]
557
777
  # @raise [RuntimeError] when `writable: true` is given.
558
778
  def to_ca(writable: false)
779
+ writable = CArray.send(:bool_arg, writable, "writable", "to_ca")
559
780
  if writable
560
781
  raise "#{self.class}#to_ca builds a new array; " \
561
782
  "it can't satisfy `writable: true'"
@@ -588,6 +809,7 @@ class Enumerator::ArithmeticSequence
588
809
  # @raise [RangeError] when the sequence has no end.
589
810
  # @raise [RuntimeError] when `writable: true` is given.
590
811
  def to_ca(writable: false)
812
+ writable = CArray.send(:bool_arg, writable, "writable", "to_ca")
591
813
  if writable
592
814
  raise "#{self.class}#to_ca builds a new array; " \
593
815
  "it can't satisfy `writable: true'"
@@ -612,29 +834,29 @@ class CArray
612
834
  # so its values are collected as the surface objects they are. A
613
835
  # `data_type:` from the caller is the caller's, and passes through.
614
836
  module FaceSlabResult
615
- def map_slab (**kw, &block)
837
+ def map_slab(**kw, &block)
616
838
  return super unless face? && kw[:data_type].nil? && block
617
839
  return super(**kw, data_type: :object, &block) unless holds_new_values?
618
840
  out = super(**kw, **face_slab_type) { |slab|
619
841
  face_slab_storage(block.call(slab), slab.shape)
620
842
  }
621
- out.face_lift(self)
843
+ out.send(:face_lift, self)
622
844
  end
623
845
 
624
- def reduce_slab (**kw, &block)
846
+ def reduce_slab(**kw, &block)
625
847
  return super unless face? && kw[:data_type].nil? && block
626
848
  return super(**kw, data_type: :object, &block) unless holds_new_values?
627
849
  fiber = kw.key?(:init)
628
850
  init = kw.delete(:init)
629
851
  out = super(**kw, **face_slab_type) { |slab|
630
852
  value = if fiber
631
- slab.to_a.flatten.inject(init) { |acc, e| block.call(acc, e) }
853
+ slab.to_a.flatten.reject { |e| UNDEF.equal?(e) }.inject(init.dup) { |acc, e| block.call(acc, e) }
632
854
  else
633
855
  block.call(slab)
634
856
  end
635
857
  face_slab_storage(value, [1])[0]
636
858
  }
637
- out.face_lift(self)
859
+ out.send(:face_lift, self)
638
860
  end
639
861
 
640
862
  private
@@ -646,7 +868,7 @@ class CArray
646
868
  storage.data_type == CA_FIXLEN ? {} : { data_type: storage.data_type }
647
869
  end
648
870
 
649
- def face_slab_storage (value, shape)
871
+ def face_slab_storage(value, shape)
650
872
  cell = blank_like(shape)
651
873
  cell[] = value
652
874
  cell.__send__(:face_storage)
@@ -654,4 +876,6 @@ class CArray
654
876
  end
655
877
 
656
878
  prepend FaceSlabResult
879
+ private_constant :FaceSlabResult, :IntegerPowerCount, :IntegerShiftCount,
880
+ :UNSIGNED
657
881
  end