carray 3.0.5 → 3.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +343 -0
  3. data/README.md +25 -4
  4. data/carray.gemspec +3 -2
  5. data/ext/ca_axis_dispatch.c +6 -0
  6. data/ext/ca_axis_group.c +7 -7
  7. data/ext/ca_binop_dispatch.c +8 -0
  8. data/ext/ca_binop_dispatch.h +1 -0
  9. data/ext/ca_categorical_iterator.c +14 -14
  10. data/ext/ca_kernel_iterator.c +116 -231
  11. data/ext/ca_kernel_iterator.h +416 -258
  12. data/ext/ca_obj_array.c +4 -4
  13. data/ext/ca_obj_bincmp.c +28 -4
  14. data/ext/ca_obj_binop.c +46 -12
  15. data/ext/ca_obj_bitarray.c +2 -4
  16. data/ext/ca_obj_bitfield.c +88 -4
  17. data/ext/ca_obj_byte_swap.c +4 -4
  18. data/ext/ca_obj_const_string.c +422 -257
  19. data/ext/ca_obj_face.c +73 -33
  20. data/ext/ca_obj_fake.c +114 -13
  21. data/ext/ca_obj_farray.c +7 -1
  22. data/ext/ca_obj_fixlen_string.c +51 -17
  23. data/ext/ca_obj_grid.c +179 -19
  24. data/ext/ca_obj_meld.c +74 -118
  25. data/ext/ca_obj_moncmp.c +9 -1
  26. data/ext/ca_obj_monop.c +100 -36
  27. data/ext/ca_obj_object.c +63 -29
  28. data/ext/ca_obj_reduce.c +17 -5
  29. data/ext/ca_obj_refer.c +162 -23
  30. data/ext/ca_obj_remap.c +69 -10
  31. data/ext/ca_obj_repeat.c +1 -1
  32. data/ext/ca_obj_roll.c +3 -4
  33. data/ext/ca_obj_select.c +12 -7
  34. data/ext/ca_obj_select_axis.c +9 -6
  35. data/ext/ca_obj_shift.c +1 -0
  36. data/ext/ca_obj_stack.c +315 -116
  37. data/ext/ca_obj_stride.c +177 -53
  38. data/ext/ca_obj_string.c +20 -4
  39. data/ext/ca_obj_tile.c +3 -4
  40. data/ext/ca_obj_triop.c +24 -13
  41. data/ext/ca_obj_window.c +23 -15
  42. data/ext/ca_op_ipower.c +71 -23
  43. data/ext/ca_op_powi.h +6 -29
  44. data/ext/ca_sort_kernels.h +3 -0
  45. data/ext/ca_sweep_engine.c +90 -23
  46. data/ext/ca_sweep_engine.h +5 -6
  47. data/ext/caframe_csv_reader.c +2 -2
  48. data/ext/carray.h +5 -2
  49. data/ext/carray_access.c +125 -103
  50. data/ext/carray_address_basis.c +209 -1
  51. data/ext/carray_attribute.c +8 -0
  52. data/ext/carray_broadcast.c +5 -6
  53. data/ext/carray_build_flags.h +1 -1
  54. data/ext/carray_call_cfunc.c +5 -8
  55. data/ext/carray_cast.c +319 -48
  56. data/ext/carray_cast_func.rb +37 -5
  57. data/ext/carray_conversion.c +65 -7
  58. data/ext/carray_copy.c +24 -0
  59. data/ext/carray_core.c +874 -72
  60. data/ext/carray_count.c +28 -9
  61. data/ext/carray_element.c +22 -12
  62. data/ext/carray_factorize.c +11 -11
  63. data/ext/carray_histogram.c +27 -5
  64. data/ext/carray_index_classifier.c +7 -5
  65. data/ext/carray_internal.h +241 -12
  66. data/ext/carray_kernels_bincmp.c +2007 -3
  67. data/ext/carray_kernels_binop.c +25502 -5336
  68. data/ext/carray_kernels_init.c +22 -22
  69. data/ext/carray_kernels_monop.c +10739 -3771
  70. data/ext/carray_kernels_reduce_aggregate.c +4429 -702
  71. data/ext/carray_kernels_reduce_boolean.c +1533 -15
  72. data/ext/carray_kernels_reduce_cumulative.c +1808 -248
  73. data/ext/carray_kernels_reduce_extreme.c +4508 -511
  74. data/ext/carray_kernels_reduce_variance.c +2284 -152
  75. data/ext/carray_kernels_scan.c +240 -240
  76. data/ext/carray_kernels_search.c +4211 -264
  77. data/ext/carray_kernels_sort.c +367 -450
  78. data/ext/carray_lazy.c +63 -1
  79. data/ext/carray_loop.c +10 -3
  80. data/ext/carray_mask.c +247 -149
  81. data/ext/carray_median_percentile.c +17 -12
  82. data/ext/carray_memory_view.c +54 -29
  83. data/ext/carray_operator.c +219 -55
  84. data/ext/carray_order.c +55 -11
  85. data/ext/carray_partition.c +1 -1
  86. data/ext/carray_random.c +5 -2
  87. data/ext/carray_round.c +24 -1
  88. data/ext/carray_scatter.c +4 -0
  89. data/ext/carray_segment.c +1 -1
  90. data/ext/carray_slab.c +110 -25
  91. data/ext/carray_sort.c +7 -4
  92. data/ext/carray_sort_kernel.c +24 -0
  93. data/ext/carray_struct.c +21 -6
  94. data/ext/carray_test.c +154 -53
  95. data/ext/carray_time_text.c +8 -2
  96. data/ext/carray_utils.c +124 -54
  97. data/ext/extconf.rb +11 -0
  98. data/ext/mk_call_cfunc.rb +6 -11
  99. data/ext/mkkernel.rb +383 -121
  100. data/ext/ruby_carray.c +4 -1
  101. data/ext/version.h +4 -4
  102. data/lib/carray/attribute.rb +25 -1
  103. data/lib/carray/autoload_carray.rb +3 -3
  104. data/lib/carray/autoload_method_extension.rb +5 -3
  105. data/lib/carray/axis_group.rb +22 -13
  106. data/lib/carray/basics.rb +27 -9
  107. data/lib/carray/bincount_nd.rb +8 -2
  108. data/lib/carray/block_iterator.rb +65 -24
  109. data/lib/carray/categorical.rb +27 -16
  110. data/lib/carray/categorical_iterator.rb +4 -3
  111. data/lib/carray/complex.rb +2 -2
  112. data/lib/carray/conditional.rb +55 -6
  113. data/lib/carray/const_string.rb +74 -0
  114. data/lib/carray/construct.rb +2 -2
  115. data/lib/carray/core_extensions.rb +19 -68
  116. data/lib/carray/data_type_extension.rb +1 -0
  117. data/lib/carray/fixlen_string.rb +83 -1
  118. data/lib/carray/frame/column_verbs.rb +102 -16
  119. data/lib/carray/frame/concat.rb +50 -6
  120. data/lib/carray/frame/convert.rb +19 -0
  121. data/lib/carray/frame/csv_parser.rb +45 -36
  122. data/lib/carray/frame/describe.rb +4 -2
  123. data/lib/carray/frame/frame.rb +436 -83
  124. data/lib/carray/frame/group.rb +731 -78
  125. data/lib/carray/frame/io.rb +216 -73
  126. data/lib/carray/frame/join.rb +166 -43
  127. data/lib/carray/frame/records.rb +9 -7
  128. data/lib/carray/frame/reshape.rb +109 -11
  129. data/lib/carray/frame/sort.rb +57 -9
  130. data/lib/carray/frame/verbs.rb +448 -60
  131. data/lib/carray/frame/windows.rb +71 -9
  132. data/lib/carray/fuse_source.rb +4 -2
  133. data/lib/carray/inspect.rb +7 -2
  134. data/lib/carray/iterator.rb +40 -0
  135. data/lib/carray/key_windows.rb +10 -4
  136. data/lib/carray/lazy.rb +28 -24
  137. data/lib/carray/mask_gap_fill.rb +37 -17
  138. data/lib/carray/meld_reduce.rb +1 -1
  139. data/lib/carray/methods/bin.rb +3 -0
  140. data/lib/carray/methods/choose.rb +3 -2
  141. data/lib/carray/methods/composition.rb +1 -1
  142. data/lib/carray/methods/factorize.rb +2 -0
  143. data/lib/carray/methods/gather_nd.rb +4 -1
  144. data/lib/carray/methods/is_in.rb +23 -3
  145. data/lib/carray/methods/locate_addr.rb +63 -12
  146. data/lib/carray/methods/meshgrid.rb +3 -1
  147. data/lib/carray/methods/repeat.rb +11 -1
  148. data/lib/carray/record_order.rb +35 -6
  149. data/lib/carray/runtime.rb +57 -8
  150. data/lib/carray/segment_iterator.rb +42 -24
  151. data/lib/carray/serialize.rb +56 -17
  152. data/lib/carray/slab_iterator.rb +1 -1
  153. data/lib/carray/stack.rb +21 -9
  154. data/lib/carray/string.rb +6 -6
  155. data/lib/carray/string_operation_extension.rb +25 -4
  156. data/lib/carray/struct_builder.rb +4 -1
  157. data/lib/carray/time.rb +195 -46
  158. data/lib/carray/window_iterator.rb +64 -16
  159. data/yard-stubs/ca_obj_array.rb +26 -1
  160. data/yard-stubs/ca_obj_bitfield.rb +4 -1
  161. data/yard-stubs/ca_obj_refer.rb +3 -0
  162. data/yard-stubs/ca_obj_window.rb +2 -1
  163. data/yard-stubs/carray_access.rb +4 -2
  164. data/yard-stubs/carray_cast.rb +14 -5
  165. data/yard-stubs/carray_conversion.rb +8 -2
  166. data/yard-stubs/carray_count.rb +6 -3
  167. data/yard-stubs/carray_mask.rb +20 -1
  168. data/yard-stubs/carray_math.rb +36 -16
  169. data/yard-stubs/carray_memory_view.rb +7 -0
  170. data/yard-stubs/carray_order.rb +6 -0
  171. data/yard-stubs/carray_scatter.rb +2 -1
  172. data/yard-stubs/carray_test.rb +23 -7
  173. metadata +17 -3
@@ -295,7 +295,7 @@ class CACategoricalIterator < CASegmentIterator
295
295
  # @overload wmean(weights, axis:)
296
296
  # Per-fiber per-category weighted mean along `axis`. Same weights-shape
297
297
  # contract as {#wsum} (weights.shape == source.shape). Empty cell → MASKED;
298
- # a present cell whose weights sum to zero → NaN (0/0 core contract).
298
+ # a present cell whose weights sum to zero → UNDEF, as CArray#wmean.
299
299
  # @param weights [CArray]
300
300
  # @param axis [Integer]
301
301
  # @return [CArray]
@@ -492,6 +492,7 @@ class CACategoricalIterator < CASegmentIterator
492
492
  # each c) — bounded by K, typically small. A fused per-fiber variance
493
493
  # kernel is a natural follow-on if bench demands it.
494
494
  def axis_by_masked_copy (axis, op, out_data_type = core_reduce_type(op))
495
+ return axis_by_core(axis, op) if @value.face?
495
496
  h = @value
496
497
  axis = checked_axis(axis, op)
497
498
  full_c = resolve_axis_codes(@cat.codes, h.shape, axis)
@@ -534,7 +535,7 @@ class CACategoricalIterator < CASegmentIterator
534
535
  flat ? g.__send__(op, *args, axis: axis, keep_axis: true)
535
536
  : g.__send__(op, *args, axis: axis)
536
537
  end
537
- if answers.first.face? && answers.first.read_only?
538
+ if answers.first.face? && !answers.first.__send__(:holds_new_values?)
538
539
  answers = answers.map { |a| CArray.object(*a.shape) { a.to_a } }
539
540
  end
540
541
  out = flat ? CArray.concatenate(answers) : CArray.stack(answers, axis: 0).copy
@@ -551,7 +552,7 @@ class CACategoricalIterator < CASegmentIterator
551
552
  codes = @cat.codes
552
553
  # Classified along the axis, a group is taken by index; the general way,
553
554
  # masking the rest of a copy, gives the same cells.
554
- if codes.shape == [h.shape[axis]] && CArray.__fast_paths_enabled__
555
+ if codes.shape == [h.shape[axis]] && CArray.__fast_paths_enabled__(:categorical_group_by_index)
555
556
  sel = none ? CArray.boolean(codes.elements) { false } : codes.eq(c)
556
557
  sel = sel.strip_mask(false) if sel.has_mask?
557
558
  idx = [nil] * h.ndim
@@ -74,7 +74,7 @@ class CArray
74
74
  when CA_CMPLX128 then field(0, CA_FLOAT64)
75
75
  end
76
76
  else
77
- self[]
77
+ scalar? ? self : self[]
78
78
  end
79
79
  frozen? ? view : (@__real__ = view)
80
80
  end
@@ -100,7 +100,7 @@ class CArray
100
100
  end
101
101
  if not complex?
102
102
  zero = template { 0 }
103
- zero[is_masked] = UNDEF if has_mask?
103
+ zero.inherit_mask(self) if has_mask?
104
104
  return zero
105
105
  end
106
106
  return @__imag__ if part_of_self?(@__imag__)
@@ -130,6 +130,13 @@ class CArray
130
130
  CATriOp.__build__(self, branch.(x), branch.(y), CATriOp::OP_SELECT)
131
131
  end
132
132
 
133
+ # The two branches of a selection, in a form that holds the cells of both.
134
+ # A Face whose cells differ by more than their values (a time's unit, a
135
+ # fixed string's width) brings them to one here, whichever branch is which.
136
+ private def branches_in_common (x, y)
137
+ [x, y]
138
+ end
139
+
133
140
  private def face_then_else (x, y, face)
134
141
  # A Face branch decides the result: the other branch is written into a
135
142
  # copy of it through the Face's own store, so an instant stays an instant.
@@ -141,10 +148,11 @@ class CArray
141
148
  sy = y.is_a?(CAConstString) ? y.to_string : y
142
149
  return CArray.const_string(then_else(sx, sy), encoding: face.encoding)
143
150
  end
151
+ x, y = face.__send__(:branches_in_common, x, y)
144
152
  x_full = x.is_a?(CArray) && !x.scalar?
145
153
  y_full = y.is_a?(CArray) && !y.scalar?
146
154
  base = y_full ? y : x
147
- if base.read_only?
155
+ unless base.__send__(:holds_new_values?)
148
156
  # No store to write through (a CACategorical's codes): select among
149
157
  # the values themselves.
150
158
  result = CArray.object(*shape)
@@ -180,7 +188,8 @@ class CArray
180
188
  "replace_where: cond must be a boolean CArray (data_type == CA_BOOLEAN)"
181
189
  end
182
190
  result = self.copy
183
- result[cond] = b.is_a?(CArray) ? b[cond] : b
191
+ # A CScalar takes no index: like a number, it is the value for every cell.
192
+ result[cond] = b.is_a?(CArray) && !b.scalar? ? b[cond] : b
184
193
  result
185
194
  end
186
195
 
@@ -219,8 +228,9 @@ class CArray
219
228
  "conditional: cond must be a boolean CArray with same shape as self"
220
229
  end
221
230
 
222
- x_then = self[cond]
223
- x_else = self[cond.not]
231
+ src = scalar? ? flatten : self # a CScalar takes no index
232
+ x_then = src[cond]
233
+ x_else = src[cond.not]
224
234
  y_then = then_fn.call(x_then)
225
235
  y_else = else_fn.call(x_else)
226
236
  text = !data_type && CArray.send(:selection_text?, [y_then, y_else])
@@ -264,6 +274,8 @@ class CArray
264
274
  # @param condlist [Array<CArray>] boolean selectors.
265
275
  # @param choicelist [Array<CArray, Numeric, Object>] values, one
266
276
  # per condition (same length as `condlist`).
277
+ # When a choice is a Face the result is that Face (the choices meet as
278
+ # in {#then_else}), and `default` is UNDEF unless it is given.
267
279
  # @param default [CArray, Numeric, Object] value written where no
268
280
  # condition holds.
269
281
  # @param data_type [Symbol, Integer, nil] override for the result
@@ -277,7 +289,7 @@ class CArray
277
289
  # [-x, x * 10],
278
290
  # default: 999)
279
291
  # # => [5.0, 3.0, -10.0, 0.0, 10.0, 999.0]
280
- def self.select (condlist, choicelist, default: 0, data_type: nil)
292
+ def self.select (condlist, choicelist, default: (no_default = true; 0), data_type: nil)
281
293
  unless condlist.is_a?(Array) && choicelist.is_a?(Array)
282
294
  raise ArgumentError, "select: condlist and choicelist must be Arrays"
283
295
  end
@@ -295,6 +307,14 @@ class CArray
295
307
  end
296
308
  shape = first.shape
297
309
 
310
+ if data_type.nil?
311
+ face = choicelist.find { |v| v.is_a?(CArray) && !v.scalar? && v.face? }
312
+ if face
313
+ fallback = no_default ? UNDEF : default
314
+ return select_among_faces(condlist, choicelist, fallback, face, shape)
315
+ end
316
+ end
317
+
298
318
  dt = data_type || selection_type(choicelist + [default])
299
319
  # `default` can be either a same-shape CArray (per-cell fallback) or a
300
320
  # scalar (broadcast to every cell).
@@ -316,7 +336,7 @@ class CArray
316
336
  "select: condlist[#{k}] must be a same-shape boolean CArray"
317
337
  end
318
338
  v = choicelist[k]
319
- out[c] = v.is_a?(CArray) ? v[c] : v
339
+ out[c] = v.is_a?(CArray) && !v.scalar? ? v[c] : v
320
340
  end
321
341
  if !data_type && selection_text?(choicelist + [default])
322
342
  out = CAString.wrap(out)
@@ -330,6 +350,35 @@ class CArray
330
350
  # some type, so it leaves the type to the others. A String or Symbol is a
331
351
  # value, which CArray.result_type would read as the name of a data type
332
352
  # ("int32"), so it makes the result object.
353
+ # select over Face choices. Each condition is a then_else on the choices
354
+ # below it, so the Faces meet as they do there; a Face that cannot be
355
+ # written selects among its values.
356
+ def self.select_among_faces (condlist, choicelist, fallback, face, shape)
357
+ if face.is_a?(CAConstString)
358
+ choices = choicelist.map { |v| v.is_a?(CAConstString) ? v.to_string : v }
359
+ text = select(condlist, choices, default: fallback)
360
+ return CArray.const_string(text, encoding: face.encoding)
361
+ end
362
+ unless face.__send__(:holds_new_values?)
363
+ choices = choicelist.map { |v| v.is_a?(CArray) && v.face? ? v.to_type(CA_OBJECT) : v }
364
+ return select(condlist, choices, default: fallback)
365
+ end
366
+ unless face.shape == shape
367
+ raise ArgumentError, "select: choicelist shape #{face.shape} differs from condlist shape #{shape}"
368
+ end
369
+ out = CArray.boolean(*shape).zero.then_else(face, fallback)
370
+ (condlist.size - 1).downto(0) do |k|
371
+ c = condlist[k]
372
+ unless c.is_a?(CArray) && c.boolean? && c.shape == shape
373
+ raise ArgumentError,
374
+ "select: condlist[#{k}] must be a same-shape boolean CArray"
375
+ end
376
+ out = c.then_else(choicelist[k], out)
377
+ end
378
+ out
379
+ end
380
+ private_class_method :select_among_faces
381
+
333
382
  def self.selection_type (values)
334
383
  typed = values.reject { |v| v.equal?(UNDEF) }
335
384
  if typed.empty? || typed.any? { |v| v.is_a?(String) || v.is_a?(Symbol) }
@@ -86,6 +86,7 @@ end
86
86
  # (categorical labels) prefer {CACategorical}, which stores each distinct
87
87
  # value once.
88
88
  class CAConstString
89
+ private def holds_new_values? = false
89
90
 
90
91
  # Read-only String Face: L1 string operations only (no in-place Mutable).
91
92
  # Its C-native byte predicates / search / comparison (ext/ca_obj_const_string.c)
@@ -205,6 +206,17 @@ class CAConstString
205
206
  const_string_lift(to_string.clip(*args, **kw))
206
207
  end
207
208
 
209
+ # A String has no distance, so there is no nearest one; refused in the
210
+ # words CAString uses.
211
+ def search_nearest (*args, **kw)
212
+ to_string.search_nearest(*args, **kw)
213
+ end
214
+
215
+ # @see #search_nearest
216
+ def search_nearest_addr (*args, **kw)
217
+ to_string.search_nearest_addr(*args, **kw)
218
+ end
219
+
208
220
  # @overload min_index(axis: nil)
209
221
  # @return [Integer, CArray] where the byte-smallest string sits.
210
222
  def min_index (*args, **kw)
@@ -217,6 +229,68 @@ class CAConstString
217
229
  to_string.max_index(*args, **kw)
218
230
  end
219
231
 
232
+ # @overload min_addr(axis: nil)
233
+ # @return [Integer, CArray] the flat address of the byte-smallest string.
234
+ def min_addr (*args, **kw)
235
+ to_string.min_addr(*args, **kw)
236
+ end
237
+
238
+ # @overload max_addr(axis: nil)
239
+ # @return [Integer, CArray] the flat address of the byte-largest string.
240
+ def max_addr (*args, **kw)
241
+ to_string.max_addr(*args, **kw)
242
+ end
243
+
244
+ # @overload bsearch(value)
245
+ # @return [Integer, nil] where a sorted column holds `value`.
246
+ def bsearch (*args, **kw)
247
+ to_string.bsearch(*args, **kw)
248
+ end
249
+
250
+ # @overload bsearch_addr(value)
251
+ # @return [Integer, nil] the flat address of `value` in a sorted column.
252
+ def bsearch_addr (*args, **kw)
253
+ to_string.bsearch_addr(*args, **kw)
254
+ end
255
+
256
+ # @overload search_addr(value)
257
+ # @return [Integer, nil] the flat address of the first cell equal to `value`.
258
+ def search_addr (*args, **kw)
259
+ to_string.search_addr(*args, **kw)
260
+ end
261
+
262
+ # @overload match(pattern)
263
+ # @return [CArray] boolean, as {CAString} answers.
264
+ def match (*args)
265
+ to_string.match(*args)
266
+ end
267
+
268
+ # @!method pmax(other)
269
+ # The later String in byte order of each cell and `other`.
270
+ # @return [CAConstString]
271
+ # @!method pmin(other)
272
+ # The earlier String in byte order of each cell and `other`.
273
+ # @return [CAConstString]
274
+ # @!method maximum(other)
275
+ # Another name of {#pmax}.
276
+ # @return [CAConstString]
277
+ # @!method minimum(other)
278
+ # Another name of {#pmin}.
279
+ # @return [CAConstString]
280
+ # @!method fmax(other)
281
+ # Another name of {#pmax}.
282
+ # @return [CAConstString]
283
+ # @!method fmin(other)
284
+ # Another name of {#pmin}.
285
+ # @return [CAConstString]
286
+ CArray.send(:define_named_methods, self,
287
+ [:pmax, :pmin, :maximum, :minimum, :fmax, :fmin], :pick_among_strings)
288
+
289
+ private def pick_among_strings (op, other)
290
+ refuse_unordered_operands(op, other)
291
+ const_string_lift(to_string.public_send(op, string_operand(other)))
292
+ end
293
+
220
294
  # @overload partition_copy(kth, axis: nil)
221
295
  # @return [CAConstString] partitioned about the `kth` string in order.
222
296
  def partition_copy (*args, **kw)
@@ -191,7 +191,7 @@ class CArray
191
191
  extend DataTypeNewConstructor
192
192
  extend DataTypeExtension
193
193
  # @!visibility private
194
- TypeSymbol = :complex64
194
+ TypeSymbol = :cmplx64
195
195
  # @!visibility private
196
196
  DataType = CA_CMPLX64
197
197
  end
@@ -208,7 +208,7 @@ class CArray
208
208
  extend DataTypeNewConstructor
209
209
  extend DataTypeExtension
210
210
  # @!visibility private
211
- TypeSymbol = :complex128
211
+ TypeSymbol = :cmplx128
212
212
  # @!visibility private
213
213
  DataType = CA_CMPLX128
214
214
  end
@@ -9,7 +9,8 @@
9
9
  # Provides:
10
10
  # - Postfix math on Float/Integer/Rational (sqrt, exp, log, sin, ...)
11
11
  # enabling scalar/CArray polymorphism: the same expression
12
- # `(0.0415*(t-218.8)).tanh` works whether t is a Float or a CArray.
12
+ # `(0.0415*(t-218.8)).tanh` works whether t is a Float or a CArray,
13
+ # and answers as the array does (`(-1.0).sqrt` is NaN, not an exception).
13
14
  # - The same postfix math on Complex, so an expression written for a
14
15
  # complex CArray still reads for a single cell taken out of it.
15
16
  # - Angle normalisation on Numeric (deg_360 / deg_180 / rad_2pi / rad_pi).
@@ -43,11 +44,18 @@ class CArray
43
44
  # lexically scoped: nothing changes for code that does not opt in.
44
45
  module CoreExtensions
45
46
 
47
+ # What a real scalar answers through the float64 kernel of the array form.
48
+ # The refinement exists so that one expression reads for a scalar and for
49
+ # an array, so it answers as the array does: NaN outside a function's
50
+ # domain where Ruby's Math raises, the sign of a zero, and the accuracy of
51
+ # expm1 and log1p near zero. The cost is one CScalar per call.
52
+ #
46
53
  # @!visibility private
47
54
  MATH_METHODS = %i[
48
55
  sqrt exp log log10
49
56
  sin cos tan sinh cosh tanh
50
57
  asin acos atan asinh acosh atanh
58
+ expm1 log1p rsqrt signbit
51
59
  ].freeze
52
60
 
53
61
  [Float, Integer, Rational].each do |klass|
@@ -55,7 +63,7 @@ class CArray
55
63
  MATH_METHODS.each do |m|
56
64
  module_eval <<~RUBY, __FILE__, __LINE__ + 1
57
65
  def #{m}
58
- Math.#{m}(self)
66
+ CA_FLOAT64(self).#{m}[0]
59
67
  end
60
68
  RUBY
61
69
  end
@@ -68,26 +76,12 @@ class CArray
68
76
  def distance(other)
69
77
  (self.to_f - other.to_f).abs
70
78
  end
71
- # M.1 (PyTorch alignment) scalar polymorphism additions.
72
79
  # `trunc` is left to Ruby's built-in semantics (Float#truncate
73
80
  # returns Integer when arg=0) — its CArray counterpart preserves
74
81
  # data type, so scalar-side use should call .to_f.trunc explicitly.
75
- # Math.expm1 / Math.log1p don't exist in stdlib; hand-roll.
76
- def expm1
77
- Math.exp(self) - 1.0
78
- end
79
- def log1p
80
- Math.log(1.0 + self)
81
- end
82
- def rsqrt
83
- 1.0 / Math.sqrt(self)
84
- end
85
82
  def square
86
83
  self * self
87
84
  end
88
- def signbit
89
- self.negative?
90
- end
91
85
  end
92
86
  end
93
87
 
@@ -109,14 +103,9 @@ class CArray
109
103
  square rsqrt
110
104
  ].freeze
111
105
 
112
- # Complex is not handled the way Float / Integer / Rational are.
113
- # Math.tanh(Complex(1,2)) raises RangeError -- of the stdlib Math
114
- # methods only Math.sqrt accepts a Complex -- so the complex forms
115
- # need their own implementation.
116
- #
117
- # Each one runs the value through a one-element cmplx128 CScalar, so
118
- # the answer comes from the very kernel the array form would have
119
- # used. That is the point: the branch cuts of csqrt / clog / casin /
106
+ # Complex goes the same way, through a one-element cmplx128 CScalar, so
107
+ # the answer comes from the very kernel the array form would have used.
108
+ # That is the point: the branch cuts of csqrt / clog / casin /
120
109
  # cacosh / catanh, and the sign of a zero on either side of them, are
121
110
  # whatever the platform's C99 complex.h says they are, and they are
122
111
  # not the same everywhere. On this machine, for instance,
@@ -143,50 +132,12 @@ class CArray
143
132
  end
144
133
 
145
134
  refine Numeric do
146
- def deg_360
147
- a = self.to_f
148
- fa = a / 360.0
149
- if a >= 0
150
- (fa - fa.floor) * 360.0
151
- else
152
- (fa - fa.ceil + 1) * 360.0
153
- end
154
- end
155
-
156
- def deg_180
157
- a = self.to_f
158
- fa = (a + 180.0) / 360.0
159
- b = if a >= 0
160
- (fa - fa.floor) * 360.0 - 180.0
161
- else
162
- (fa - fa.ceil) * 360.0 - 180.0
163
- end
164
- b += 360.0 if b <= -180.0
165
- b
166
- end
167
-
168
- def rad_2pi
169
- a = self.to_f
170
- two_pi = 2 * Math::PI
171
- fa = a / two_pi
172
- if a >= 0
173
- (fa - fa.floor) * two_pi
174
- else
175
- (fa - fa.ceil + 1) * two_pi
176
- end
177
- end
178
-
179
- def rad_pi
180
- a = self.to_f
181
- two_pi = 2 * Math::PI
182
- fa = (a + Math::PI) / two_pi
183
- b = if a >= 0
184
- (fa - fa.floor) * two_pi - Math::PI
185
- else
186
- (fa - fa.ceil) * two_pi - Math::PI
187
- end
188
- b += two_pi if b <= -Math::PI
189
- b
135
+ %i[deg_360 deg_180 rad_2pi rad_pi].each do |m|
136
+ module_eval <<~RUBY, __FILE__, __LINE__ + 1
137
+ def #{m}
138
+ CA_FLOAT64(self.to_f).#{m}[0]
139
+ end
140
+ RUBY
190
141
  end
191
142
 
192
143
  def eq(other)
@@ -151,6 +151,7 @@ class CArray
151
151
  # @param n [Integer] number of samples.
152
152
  # @return [CArray]
153
153
  def linspace (x1, x2, n = 100)
154
+ raise TypeError, "linspace: n must be an Integer (got #{n.class})" unless n.is_a?(Integer)
154
155
  data_type = self::DataType
155
156
  unless data_type
156
157
  guess = guess_data_type_from_values(x1, x2)
@@ -87,7 +87,7 @@ class CArray
87
87
  values.each_with_index do |s, i|
88
88
  entity[i] = s.nil? ? UNDEF : s.to_s
89
89
  end
90
- CAFixlenString.wrap(entity)
90
+ CAFixlenString.wrap(entity, encoding: CAFixlenString.__send__(:encoding_of_strings, values))
91
91
  end
92
92
 
93
93
  end
@@ -95,6 +95,88 @@ end
95
95
  # Mutable fixed-width String Face: L1 ops + in-place variants. In-place
96
96
  # transforms re-store through the native fixlen path (silent truncate).
97
97
  class CAFixlenString
98
+
99
+ # The greater String of each cell and `other`, cell by cell: `other` is a
100
+ # CAFixlenString of the same shape or one String. The result is as wide as
101
+ # the wider of the two.
102
+ # @return [CAFixlenString]
103
+ def pmax (other)
104
+ refuse_unordered_operands(__callee__, other)
105
+ pick_by_order(other) { |a, b| a.lt(b) }
106
+ end
107
+
108
+ # The lesser String of each cell and `other`; see {#pmax}.
109
+ # @return [CAFixlenString]
110
+ def pmin (other)
111
+ refuse_unordered_operands(__callee__, other)
112
+ pick_by_order(other) { |a, b| a.gt(b) }
113
+ end
114
+
115
+ # A String has no NaN to let win, so these are other names of pmax / pmin.
116
+ alias_method :maximum, :pmax
117
+ alias_method :minimum, :pmin
118
+ alias_method :fmax, :pmax
119
+ alias_method :fmin, :pmin
120
+
121
+ # @overload min_addr(axis: nil)
122
+ # @return [Integer, CArray] the flat address of the smallest String.
123
+ def min_addr (*args, **kw)
124
+ to_string.min_addr(*args, **kw)
125
+ end
126
+
127
+ # @overload max_addr(axis: nil)
128
+ # @return [Integer, CArray] the flat address of the largest String.
129
+ def max_addr (*args, **kw)
130
+ to_string.max_addr(*args, **kw)
131
+ end
132
+
133
+ # A value that is no String is in no cell, and the kernels below take only
134
+ # bytes: these ask the Strings, which answer it as any other value.
135
+ CArray.send(:define_named_methods, self,
136
+ [:eq, :ne, :count, :search, :search_addr, :is_in, :union, :difference, :intersection],
137
+ :through_strings_unless_text, super_block: true)
138
+
139
+ private def through_strings_unless_text (op, args, kw)
140
+ v = args[0]
141
+ return yield(*args, **kw) if args.empty? || v.is_a?(String) || v.is_a?(CArray) ||
142
+ v.is_a?(Array) || UNDEF.equal?(v)
143
+ to_string.public_send(op, *args, **kw)
144
+ end
145
+
146
+ # `other` where the block says self's cell loses to it, else self's cell.
147
+ # Another array of Strings (a CAString, a CAConstString, an object array)
148
+ # is taken as fixed-length strings, so the result is one.
149
+ private def pick_by_order (other)
150
+ return copy.tap { |out| out[] = UNDEF } if UNDEF.equal?(other)
151
+ if other.is_a?(CArray) && !other.is_a?(CAFixlenString)
152
+ other = CArray.string(other) if other.data_type == CA_OBJECT && !other.face?
153
+ other = other.to_fixlen_string if other.respond_to?(:to_fixlen_string)
154
+ end
155
+ yield(self, other).then_else(other, self)
156
+ end
157
+
158
+ # Both branches of a selection at the width of the wider one.
159
+ private def branches_in_common (x, y)
160
+ width = [x, y].map { |v|
161
+ case v
162
+ when CArray then v.bytes
163
+ when String then v.bytesize
164
+ else 1
165
+ end
166
+ }.max
167
+ [x, y].map { |v|
168
+ v.is_a?(CAFixlenString) && !v.scalar? ? v.to_fixlen_string(bytes: width) : v
169
+ }
170
+ end
171
+
172
+ # The encoding a column of these strings holds its text in: that of the
173
+ # strings beyond ASCII, UTF-8 if none is, and BINARY if they disagree,
174
+ # since the column cannot read them all back.
175
+ private_class_method def self.encoding_of_strings (values)
176
+ text = values.compact.map(&:to_s).reject(&:ascii_only?).map(&:encoding).uniq
177
+ text.size > 1 ? Encoding::BINARY : (text.first || Encoding::UTF_8)
178
+ end
179
+
98
180
  # inspect's name for the array: the class and the cell width, which is the
99
181
  # longest string a cell holds.
100
182
  private def inspect_label