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
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,10 +184,14 @@ 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
191
+ # Whatever is written must fit: a finer time, a wider fixed string.
192
+ [min, max, lfill, ufill].each { |v|
193
+ out, = branches_in_common(out, v) unless v.nil? || UNDEF.equal?(v)
194
+ }
165
195
  out[self < min] = lfill.nil? ? min : lfill unless min.nil?
166
196
  out[self > max] = ufill.nil? ? max : ufill unless max.nil?
167
197
  out
@@ -170,10 +200,23 @@ class CArray
170
200
  # An array of +shape+ of the same kind as self: its data type and cell
171
201
  # width, or its Face over a zero storage. Nothing is written into it, so
172
202
  # it can be built for a read-only Face too.
173
- private def blank_like (shape)
203
+ # Whether a cell can be given a value it has not seen. Not a CAConstString,
204
+ # whose strings share a buffer, or a CACategorical, whose codes index a
205
+ # vocabulary. A view that is read-only can still hold them: it is only
206
+ # that view that cannot be written.
207
+ private def holds_new_values? = true
208
+
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)
174
217
  storage = face_storage
175
218
  out = CArray.new(storage.data_type, shape, bytes: storage.bytes)
176
- face? ? out.face_lift(self) : out
219
+ face? ? out.send(:face_lift, self) : out
177
220
  end
178
221
 
179
222
  # Sub-region copy (paste / crop), the old C `ca_paste` / `ca_clip` pair.
@@ -192,7 +235,8 @@ class CArray
192
235
  # @return [self]
193
236
  # @raise [ArgumentError] when `offset.length != self.ndim`.
194
237
  # @raise [FrozenError] when `self` is frozen.
195
- 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)
196
240
  # The write goes through a window view, which is not frozen itself:
197
241
  # refuse a frozen self here, as a write into it directly is refused.
198
242
  if frozen?
@@ -217,7 +261,7 @@ class CArray
217
261
  # @param dst [CArray] destination array; mutated in place.
218
262
  # @return [CArray] `dst`.
219
263
  # @raise [ArgumentError] when `offset.length != self.ndim`.
220
- def crop (offset, dst)
264
+ def crop(offset, dst)
221
265
  raise ArgumentError, "offset length must equal ndim" if offset.length != ndim
222
266
  src_ranges = []
223
267
  dst_ranges = []
@@ -232,36 +276,72 @@ class CArray
232
276
  dst
233
277
  end
234
278
 
235
- # @overload lookup(table, fill_value = nil, lfill: nil, ufill: nil)
279
+ # @overload lookup(table, fill_value: nil, lfill: nil, ufill: nil)
236
280
  # Returns values gathered from `table` at the indices given by
237
- # `self`. Equivalent to `table.project(self, lfill, ufill)` with
238
- # the receiver / first argument swapped so the index reads as
239
- # the subject. `fill_value` is sugar for symmetric dual-fill;
240
- # `lfill` / `ufill` override per side (`UNDEF` or `nil` masks
241
- # 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).
242
285
  # @param table [CArray] value table indexed by `self`.
243
286
  # @param fill_value [Object, nil] symmetric fill for below- and
244
287
  # above-range indices.
245
288
  # @param lfill [Object, nil] override for below-range fill.
246
289
  # @param ufill [Object, nil] override for above-range fill.
247
290
  # @return [CArray] gathered values with the shape of `self`.
248
- def lookup(table, fill_value=nil, lfill: nil, ufill: nil)
249
- lfill = fill_value if lfill.nil?
250
- ufill = fill_value if ufill.nil?
251
- 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)
252
293
  end
253
294
 
254
295
  # @overload <=>(other)
255
296
  # Returns an element-wise 3-way comparison: `+1` where
256
297
  # `self > other`, `-1` where `self < other`, `0` where equal.
257
- # 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)`.
258
303
  # @param other [CArray, Numeric] operand to compare against.
259
304
  # @return [CArray]
260
- def <=> (other)
305
+ def <=>(other)
261
306
  (self > other).as_int8 - (self < other).as_int8
262
307
  end
263
308
 
264
- 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
265
345
 
266
346
  # @!group Elementwise math
267
347
 
@@ -278,7 +358,7 @@ class CArray
278
358
  # floor toward.
279
359
  # @example
280
360
  # CA_INT32([-7]).divmod(3) # => [-3, 2]
281
- # CA_DOUBLE([-7.0]).divmod(3.0) # => [-3.0, 2.0]
361
+ # CA_FLOAT64([-7.0]).divmod(3.0) # => [-3.0, 2.0]
282
362
  def divmod(other)
283
363
  if complex?
284
364
  raise ArgumentError, "divmod is not defined for complex arrays"
@@ -290,32 +370,140 @@ class CArray
290
370
 
291
371
  # @!endgroup
292
372
 
373
+ UNSIGNED = [CA_UINT8, CA_UINT16, CA_UINT32, CA_UINT64].freeze
374
+
293
375
  # An Integer shift count on an integer array means what it means to
294
376
  # Integer#<< and #>>: negative shifts the other way, and a count past the
295
377
  # width shifts every bit out. The kernels do that for a count of the
296
378
  # array's own type; this brings a count the type cannot hold -- -1 for a
297
379
  # uint8 array, 300 for an int8 one -- to one it can.
298
380
  module IntegerShiftCount
299
- UNSIGNED = [CA_UINT8, CA_UINT16, CA_UINT32, CA_UINT64].freeze
300
-
301
- def << (other)
381
+ def <<(other)
302
382
  return super unless other.is_a?(Integer) && integer? && ! face?
303
383
  w = bytes * 8
304
384
  return self >> -other if other < 0 && UNSIGNED.include?(data_type)
305
385
  super(other.clamp(-w, w))
306
386
  end
307
387
 
308
- def >> (other)
388
+ def >>(other)
309
389
  return super unless other.is_a?(Integer) && integer? && ! face?
310
390
  w = bytes * 8
311
391
  return self << -other if other < 0 && UNSIGNED.include?(data_type)
312
392
  super(other.clamp(-w, w))
313
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
314
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
+
315
503
  # Prepended by carray/lazy, after it has wrapped << and >>: prepended
316
504
  # here, the method lazy aliases as the eager form would be this one.
317
505
 
318
- # @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)
319
507
  # Returns `self` with every element clamped to `[min, max]`.
320
508
  #
321
509
  # Either bound may be `nil` for a one-sided clip. When
@@ -333,8 +521,15 @@ class CArray
333
521
  # as `nil` does for the whole side. A bound is never UNDEF or
334
522
  # masked: a missing bound is not read as either, so fill it first.
335
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
+ #
336
530
  # Boundary is strict `[min, max]`: values equal to a bound
337
- # remain unchanged in both the clamped and filled variants.
531
+ # remain unchanged in both the clamped and filled variants. A NaN
532
+ # is in neither range and stays NaN.
338
533
  #
339
534
  # @param min [Numeric, nil] lower bound; `nil` for one-sided
340
535
  # clip above.
@@ -348,11 +543,13 @@ class CArray
348
543
  # @raise [ArgumentError] when both `min` and `max` are `nil`,
349
544
  # when either is `UNDEF` or has a masked cell, or when `min`
350
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).
351
548
  # @example
352
549
  # a.clip(0, 10) # strict clamp
353
- # a.clip(0, 10, -1) # both ends -> -1
550
+ # a.clip(0, 10, fill_value: -1) # both ends -> -1
354
551
  # a.clip(0, 10, lfill: UNDEF, ufill: 99) # below masks
355
- 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)
356
553
  if min.nil? && max.nil?
357
554
  raise ArgumentError, "clip: at least one of (min, max) must be given"
358
555
  end
@@ -366,9 +563,20 @@ class CArray
366
563
  "unbounded, and UNDEF as the fill masks the cells out of range)"
367
564
  end
368
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
369
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.
370
577
  reversed = if min.is_a?(CArray) then min.gt(max).any
371
578
  elsif max.is_a?(CArray) then max.lt(min).any
579
+ elsif min.is_a?(Array) || max.is_a?(Array) then false
372
580
  else min > max
373
581
  end
374
582
  if reversed
@@ -398,11 +606,11 @@ class CArray
398
606
  # A one-sided clip of a float array passes a NaN cell through, as the
399
607
  # two-sided one does: the open side is a NaN bound, which leaves it
400
608
  # unbounded. pmax / pmin would answer the bound for a NaN cell.
401
- protected def clamp_below (min)
609
+ protected def clamp_below(min)
402
610
  float? ? clamp_between(min, Float::NAN) : pmax(min)
403
611
  end
404
612
 
405
- protected def clamp_above (max)
613
+ protected def clamp_above(max)
406
614
  float? ? clamp_between(Float::NAN, max) : pmin(max)
407
615
  end
408
616
 
@@ -427,7 +635,8 @@ class CArray
427
635
  # endpoint. Concretely:
428
636
  #
429
637
  # - inclusive range `a..b`: `self[0] == a`, `self[-1] == b`,
430
- # intermediate values are evenly spaced.
638
+ # intermediate values are evenly spaced. A one-element array holds
639
+ # `a`.
431
640
  # - exclusive range `a...b`: `self[0] == a`, `self[-1] == a + (N-1)
432
641
  # * (b-a)/N` (endpoint `b` is not reached).
433
642
  #
@@ -448,7 +657,7 @@ class CArray
448
657
  # @param range [Range<Numeric>] value range to span.
449
658
  # @return [self]
450
659
  # @raise [ArgumentError] when `self` is not a float array.
451
- def span! (range)
660
+ def span!(range)
452
661
  unless float?
453
662
  raise ArgumentError,
454
663
  "span!: integer arrays are ambiguous — 'N evenly-spaced " \
@@ -459,9 +668,15 @@ class CArray
459
668
  " (B) N labels distributed uniformly over range values:\n" \
460
669
  " CArray.int32(N).seq * (b - a + 1) / N + a"
461
670
  end
671
+ CArray.send(:refuse_non_real_bounds, "span!", range.begin, range.end)
462
672
  first = range.begin.to_r
463
673
  last = range.end.to_r
464
- 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
465
680
  seq!(first, step)
466
681
  return self
467
682
  end
@@ -472,21 +687,35 @@ class CArray
472
687
  # @param range [Range<Numeric>] value range to span.
473
688
  # @return [CArray]
474
689
  # @raise [ArgumentError] when `self` is not a float array.
475
- def span (range)
690
+ def span(range)
691
+ CArray.send(:refuse_non_real_bounds, "span", range.begin, range.end)
476
692
  return template.span!(range)
477
693
  end
478
694
 
479
695
  # @overload scale!(xa, xb)
480
696
  # Sets `self` to `elements` evenly spaced float64 values from
481
- # `xa` to `xb` inclusive.
697
+ # `xa` to `xb` inclusive. A one-element array holds `xa`.
482
698
  # @param xa [Numeric] first value.
483
699
  # @param xb [Numeric] last value.
484
700
  # @return [self]
485
- def scale! (xa, xb)
701
+ def scale!(xa, xb)
702
+ CArray.send(:refuse_non_real_bounds, "scale!", xa, xb)
486
703
  xa = xa.to_f
487
704
  xb = xb.to_f
488
- 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
489
717
  end
718
+ private_class_method :refuse_non_real_bounds
490
719
 
491
720
  # @overload scale(xa, xb)
492
721
  # Returns a fresh CArray shaped like `self` holding `elements`
@@ -494,7 +723,8 @@ class CArray
494
723
  # @param xa [Numeric] first value.
495
724
  # @param xb [Numeric] last value.
496
725
  # @return [CArray]
497
- def scale (xa, xb)
726
+ def scale(xa, xb)
727
+ CArray.send(:refuse_non_real_bounds, "scale", xa, xb)
498
728
  template.scale!(xa, xb)
499
729
  end
500
730
 
@@ -516,6 +746,7 @@ class Array
516
746
  # @return [CArray]
517
747
  # @raise [RuntimeError] when `writable: true` is given.
518
748
  def to_ca(writable: false)
749
+ writable = CArray.send(:bool_arg, writable, "writable", "to_ca")
519
750
  if writable
520
751
  raise "#{self.class}#to_ca builds a new array; " \
521
752
  "it can't satisfy `writable: true'"
@@ -545,6 +776,7 @@ class Range
545
776
  # @return [CArray]
546
777
  # @raise [RuntimeError] when `writable: true` is given.
547
778
  def to_ca(writable: false)
779
+ writable = CArray.send(:bool_arg, writable, "writable", "to_ca")
548
780
  if writable
549
781
  raise "#{self.class}#to_ca builds a new array; " \
550
782
  "it can't satisfy `writable: true'"
@@ -577,6 +809,7 @@ class Enumerator::ArithmeticSequence
577
809
  # @raise [RangeError] when the sequence has no end.
578
810
  # @raise [RuntimeError] when `writable: true` is given.
579
811
  def to_ca(writable: false)
812
+ writable = CArray.send(:bool_arg, writable, "writable", "to_ca")
580
813
  if writable
581
814
  raise "#{self.class}#to_ca builds a new array; " \
582
815
  "it can't satisfy `writable: true'"
@@ -597,38 +830,45 @@ class CArray
597
830
  # reductions do: each block value is written into a blank of the Face
598
831
  # (which reads a CATime::Element, a string, a Face array ...) and handed
599
832
  # to the slab engine as the storage it became; the result is lifted back
600
- # at the end. A read-only Face has no blank to write into, so its values
601
- # are collected as the surface objects they are. A `data_type:` from the
602
- # caller is the caller's, and passes through.
833
+ # at the end. A Face that holds no new value has no blank to write into,
834
+ # so its values are collected as the surface objects they are. A
835
+ # `data_type:` from the caller is the caller's, and passes through.
603
836
  module FaceSlabResult
604
- def map_slab (**kw, &block)
837
+ def map_slab(**kw, &block)
605
838
  return super unless face? && kw[:data_type].nil? && block
606
- return super(**kw, data_type: :object, &block) if read_only?
607
- out = super(**kw, data_type: face_storage.data_type) { |slab|
839
+ return super(**kw, data_type: :object, &block) unless holds_new_values?
840
+ out = super(**kw, **face_slab_type) { |slab|
608
841
  face_slab_storage(block.call(slab), slab.shape)
609
842
  }
610
- out.face_lift(self)
843
+ out.send(:face_lift, self)
611
844
  end
612
845
 
613
- def reduce_slab (**kw, &block)
846
+ def reduce_slab(**kw, &block)
614
847
  return super unless face? && kw[:data_type].nil? && block
615
- return super(**kw, data_type: :object, &block) if read_only?
848
+ return super(**kw, data_type: :object, &block) unless holds_new_values?
616
849
  fiber = kw.key?(:init)
617
850
  init = kw.delete(:init)
618
- out = super(**kw, data_type: face_storage.data_type) { |slab|
851
+ out = super(**kw, **face_slab_type) { |slab|
619
852
  value = if fiber
620
- 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) }
621
854
  else
622
855
  block.call(slab)
623
856
  end
624
857
  face_slab_storage(value, [1])[0]
625
858
  }
626
- out.face_lift(self)
859
+ out.send(:face_lift, self)
627
860
  end
628
861
 
629
862
  private
630
863
 
631
- def face_slab_storage (value, shape)
864
+ # The engine's output type. Fixlen storage is named by leaving it out: the
865
+ # name alone has no width, and the source's is the one wanted.
866
+ def face_slab_type
867
+ storage = face_storage
868
+ storage.data_type == CA_FIXLEN ? {} : { data_type: storage.data_type }
869
+ end
870
+
871
+ def face_slab_storage(value, shape)
632
872
  cell = blank_like(shape)
633
873
  cell[] = value
634
874
  cell.__send__(:face_storage)
@@ -636,4 +876,6 @@ class CArray
636
876
  end
637
877
 
638
878
  prepend FaceSlabResult
879
+ private_constant :FaceSlabResult, :IntegerPowerCount, :IntegerShiftCount,
880
+ :UNSIGNED
639
881
  end