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
@@ -61,7 +61,7 @@ class WindowedFrame
61
61
  # Returns the CAKeyWindowIterator of one column.
62
62
  # @return [CAKeyWindowIterator]
63
63
  def [] (name)
64
- @plan.for_value(@frame[@frame.__send__(:column_key, name, "windows")])
64
+ @plan.for_value(@frame.__send__(:named_column, @frame.__send__(:column_key, name, "windows"), "windows"))
65
65
  end
66
66
 
67
67
  # What each window covered, one value per row: see CAKeyWindowIterator.
@@ -79,8 +79,12 @@ class WindowedFrame
79
79
 
80
80
  # The windowed reductions. Without names, a frame of every column whose
81
81
  # type has the reduction (the on: and by: columns left out), on the
82
- # frame's rows and index; given names, the CArray (one) or the Array of
83
- # them (several), as +df[...]+ returns columns.
82
+ # frame's rows and index; given names, the CArray (one), as +df[name]+
83
+ # returns a column, or a frame of those columns (several) on the frame's
84
+ # rows and index. With +at:+ the answers
85
+ # are one per point, not per row, so names or none, the result is a frame
86
+ # with the points as its index, as a group reduction's result is labelled
87
+ # by the groups.
84
88
  CArray.send(:define_named_methods, self,
85
89
  [:sum, :mean, :min, :max, :prod, :accumulate, :median,
86
90
  :variance, :stddev, :variancep, :stddevp], :window_reduction)
@@ -88,30 +92,88 @@ class WindowedFrame
88
92
  CArray.send(:define_named_methods, self,
89
93
  [:first, :last, :nunique, :count, :all, :any], :window_value)
90
94
 
95
+ # Each window's +p+-th percentile (0 to 100), as +median+ gives the 50th.
96
+ # The percentage comes first, then the names.
97
+ #
98
+ # w.percentile(90, "rain")
99
+ #
100
+ # @param p [Numeric] the percentage.
101
+ # @param names [Array<String>] the columns; default every column that has
102
+ # a percentile.
103
+ # @return [CAFrame, CArray] as the other windowed reductions return.
104
+ def percentile (p, *names, min_count: nil, fill_value: nil)
105
+ CAFrame.__send__(:check_percentage, p)
106
+ window_reduce(:percentile, names, [p], min_count: min_count, fill_value: fill_value)
107
+ end
108
+
109
+ # Each window's five quartile percentiles, as +CAFrame#quantile+ gives
110
+ # them: a column "x" gives "x_p0", "x_p25", "x_p50", "x_p75" and "x_p100",
111
+ # a frame on the frame's rows and index, or with +at:+ on the points.
112
+ #
113
+ # @param names [Array<String>] the columns; default every column that has
114
+ # a quantile.
115
+ # @return [CAFrame]
116
+ def quantile (*names, **keywords)
117
+ refuse_keywords(keywords)
118
+ named = {}
119
+ over_named_columns(:quantile, names, @key_names) do |col, name|
120
+ named[name] = @plan.for_value(col).quantile
121
+ end
122
+ cols = CAFrame.__send__(:quantile_columns, named)
123
+ return CAFrame.new(cols, axis_name: @frame.axis_name, index: @frame.index&.copy) unless @at
124
+ key = @frame.__send__(:key_column, @key_names.first, "windows")
125
+ CAFrame.new(cols, axis_name: @key_names.first, index: CAFrame.__send__(:key_labels, key, @at.copy))
126
+ end
127
+
91
128
  private
92
129
 
93
130
  def window_reduction (reduction, *names, min_count: nil, fill_value: nil)
94
131
  window_reduce(reduction, names, min_count: min_count, fill_value: fill_value)
95
132
  end
96
133
 
97
- def window_value (reduction, *names)
134
+ def window_value (reduction, *names, **keywords)
135
+ refuse_keywords(keywords)
98
136
  window_reduce(reduction, names)
99
137
  end
100
138
 
139
+ # These reductions take no keyword. Without the **keywords above, Ruby
140
+ # would hand a keyword in as a column name.
141
+ def refuse_keywords (keywords)
142
+ return if keywords.empty?
143
+ list = keywords.keys.map(&:inspect).join(", ")
144
+ raise ArgumentError, "unknown keyword#{keywords.size > 1 ? "s" : ""}: #{list}"
145
+ end
146
+
101
147
  # An N-D column (each row a profile) is reduced along the rows, each
102
148
  # window keeping the trailing shape, as a group reduces it.
103
- def window_reduce (reduction, names, **keywords)
149
+ def window_reduce (reduction, names, args = [], **keywords)
104
150
  keywords = keywords.compact
105
- out = over_named_columns(reduction, names, @key_names) do |col|
106
- @plan.for_value(col).public_send(reduction, **keywords)
151
+ if @at && names.include?(@key_names.first)
152
+ raise ArgumentError, "#{reduction}: #{@key_names.first.inspect} is the key, already the result's index"
153
+ end
154
+ fills = keywords.delete(:fill_value)
155
+ refuse_unknown_fill_columns(reduction, fills)
156
+ refuse_wrong_reduction_arguments(reduction, args, keywords)
157
+ named = {}
158
+ out = over_named_columns(reduction, names, @key_names, args) do |col, name|
159
+ fill = fills.is_a?(Hash) ? fills[name] : fills
160
+ kw = fill.nil? ? keywords : keywords.merge(fill_value: fill)
161
+ named[name] =
162
+ if %i[first last].include?(reduction) && col.ndim == 1 && args.empty? && kw.empty? &&
163
+ col.face? && !col.__send__(:holds_new_values?)
164
+ col[@plan.for_value(present_rows(col)).public_send(reduction)].copy
165
+ else
166
+ @plan.for_value(col).public_send(reduction, *args, **kw)
167
+ end
107
168
  end
108
- return out unless names.empty?
169
+ out = named if @at && !names.empty?
170
+ return out if out.is_a?(CArray) && !@at
109
171
  if @at
110
172
  # Each result has an index of its own, as a group's result has.
111
173
  key = @frame.__send__(:key_column, @key_names.first, "windows")
112
174
  CAFrame.new(out, axis_name: @key_names.first, index: CAFrame.__send__(:key_labels, key, @at.copy))
113
175
  else
114
- CAFrame.new(out, axis_name: @frame.axis_name, index: @frame.index)
176
+ CAFrame.new(out, axis_name: @frame.axis_name, index: @frame.index&.copy)
115
177
  end
116
178
  end
117
179
  end
@@ -185,7 +185,9 @@ class CArray
185
185
  # block that starts on the sequence's first line is found in the file's
186
186
  # syntax tree. Only when two start on that line is the sequence itself
187
187
  # dumped: InstructionSequence#to_a reads the instructions while another
188
- # Ractor may be running them, and that can crash the process.
188
+ # Ractor may be running them, and that can crash the process. Two Ractors
189
+ # dumping one sequence for the first time crash Ruby before 4.1, so the
190
+ # dump goes through a lock.
189
191
  def self.code_location (sequence, path)
190
192
  line = sequence.first_lineno
191
193
  found = []
@@ -206,7 +208,7 @@ class CArray
206
208
  start, whole = found.first
207
209
  [start.start_line, start.start_column, whole.end_line, whole.end_column]
208
210
  else
209
- sequence.to_a[4][:code_location]
211
+ CArray.send(:instruction_sequence_to_a, sequence)[4][:code_location]
210
212
  end
211
213
  end
212
214
 
@@ -262,7 +262,11 @@ class CArray
262
262
  # count, and a truncated data preview.
263
263
  # @return [String]
264
264
  def inspect
265
- return CArray::Inspector.new(self).inspect_string
265
+ # A cell of an object array can hold an expression over the array, whose
266
+ # inspect shows the array again: that is refused as cyclic, as reading a
267
+ # cell that holds the array is.
268
+ return CArray::Inspector.new(self).inspect_string unless object?
269
+ refuse_reentry("inspect") { CArray::Inspector.new(self).inspect_string }
266
270
  end
267
271
 
268
272
  # @overload inspect_full
@@ -290,7 +294,8 @@ class CArray
290
294
  #
291
295
  # @return [String]
292
296
  def inspect_full
293
- return CArray::Inspector.new(self).inspect_string(abbrev: false)
297
+ return CArray::Inspector.new(self).inspect_string(abbrev: false) unless object?
298
+ refuse_reentry("inspect_full") { CArray::Inspector.new(self).inspect_string(abbrev: false) }
294
299
  end
295
300
 
296
301
  private
@@ -71,6 +71,38 @@ class CAIterator
71
71
  end
72
72
  end
73
73
 
74
+ # A member that keeps what it built from its source's values or mask (a
75
+ # padded copy, the views over it, counts of the cells present) names those
76
+ # instance variables here. They are dropped when a public method of the
77
+ # member is entered from outside, so every call reads the source as it is
78
+ # then; within one call the helpers it runs share them. What follows from
79
+ # the source's shape alone is kept for good.
80
+ def self.read_source_per_call (*state)
81
+ names = public_instance_methods(false)
82
+ prepend(Module.new do
83
+ module_eval(<<~RUBY, __FILE__, __LINE__ + 1)
84
+ private def forget_source_state
85
+ #{state.inspect}.each { |v| remove_instance_variable(v) if instance_variable_defined?(v) }
86
+ end
87
+ RUBY
88
+ names.each do |name|
89
+ module_eval(<<~RUBY, __FILE__, __LINE__ + 1)
90
+ def #{name} (...)
91
+ return super if @reading_source
92
+ forget_source_state
93
+ @reading_source = true
94
+ begin
95
+ super
96
+ ensure
97
+ @reading_source = false
98
+ end
99
+ end
100
+ RUBY
101
+ end
102
+ end)
103
+ end
104
+ private_class_method :read_source_per_call
105
+
74
106
  def self.reduce_keywords (op, kw) # :nodoc:
75
107
  if kw.key?(:axis)
76
108
  raise ArgumentError, "#{op}: unknown keyword: :axis (the iterator sets the axes)"
@@ -224,6 +256,14 @@ class CAIterator
224
256
  end))
225
257
  end
226
258
 
259
+ # CArray#count over a view: CABlock / CAWindow shadow #count with a geometry
260
+ # accessor, so it is dispatched explicitly, while a Face keeps a #count of
261
+ # its own (CAConstString reads its cells as Strings).
262
+ private def count_cells (view, *args, **kw)
263
+ return view.count(*args, **kw) if view.face?
264
+ CArray.instance_method(:count).bind_call(view, *args, **kw)
265
+ end
266
+
227
267
  # Recommended (should) surface -- template methods. These are well-defined
228
268
  # for some members and structurally impossible for others, so they are not
229
269
  # required: `map` is a per-piece element-wise transform scattered back to the
@@ -76,7 +76,9 @@ class CAKeyWindowIterator < CAIterator
76
76
  raise ArgumentError, "windows: at: is a one-dimensional CArray of points"
77
77
  end
78
78
  end
79
- @key = on
79
+ # Taken as it is now, as the windows are: first_key, last_key and bounds
80
+ # read it later.
81
+ @key = on.copy
80
82
  @n = value.dim0
81
83
  # Taken as they are now, as the windows are: bounds reads them later.
82
84
  @points = at&.copy
@@ -412,9 +414,13 @@ class CAKeyWindowIterator < CAIterator
412
414
  if sample.is_a?(Array)
413
415
  return sample.each_index.map { |k| lay_out(results.map { |r| r[k] }, sample[k], trail) }
414
416
  end
415
- out = CArray.new(sample.data_type, [@nout, *trail], bytes: sample.bytes)
417
+ # A Face that holds no new value cannot be written cell by cell, so its
418
+ # values are held as the surface objects they are.
419
+ surface = sample.face? && !sample.__send__(:holds_new_values?)
420
+ shape = [@nout, *trail]
421
+ out = surface ? CArray.new(CA_OBJECT, shape) : sample.__send__(:blank_like, shape)
416
422
  flat = out.reshape(@nout, results.size)
417
- results.each_with_index { |r, j| flat[nil, j] = r }
423
+ results.each_with_index { |r, j| flat[nil, j] = surface ? r.to_a : r }
418
424
  out
419
425
  end
420
426
 
@@ -548,7 +554,7 @@ class CAKeyWindowIterator < CAIterator
548
554
 
549
555
  def window_bound (width, op)
550
556
  key = @points || @key
551
- return key if width.nil?
557
+ return key.copy if width.nil?
552
558
  if key.is_a?(CATime) || key.is_a?(CATimedelta)
553
559
  key = key.to_unit(CATimeUnitAlgebra.finer(key.unit, width.unit))
554
560
  end
data/lib/carray/lazy.rb CHANGED
@@ -384,12 +384,6 @@ class CArray
384
384
  alias_method word, op
385
385
  end
386
386
 
387
- # `pow` is the canonical C method (defined by rb_define_method in
388
- # ext/ca_op_ipower.c) that `**` is rb_define_alias'd to. The `**`
389
- # dispatch in this file does not reach `pow` through the C alias, so
390
- # `a.lazy.pow(2)` would fall to eager; `pow` is aliased again here.
391
- alias_method :pow, :**
392
-
393
387
  # `fmax` / `fmin` are rb_define_alias'd to `pmax` / `pmin` at Init
394
388
  # time (the same C alias); they are aliased again beside them, in
395
389
  # LazyDispatch.
@@ -436,26 +430,20 @@ class CArray
436
430
  private :clamp_between
437
431
  LazyDispatch.send(:private, :clamp_between)
438
432
 
439
- # `**` integer-exponent lazy fast path.
440
- #
441
- # The default OP_POW path above goes through the `power` binop kernel,
442
- # which uses `pow(x, p)` / `cpow(x, p)` (transcendental, ~20-50 ns/cell)
443
- # for float / complex parents. When `other` is an Integer, the eager
444
- # `rb_ca_pow` dispatches to `rb_ca_ipower` (= binary exponentiation via
445
- # `op_powi_<type>`, ~1-3 mul/cell, 3-5x faster than the transcendental
446
- # form). Mirror that dispatch here so `a.lazy ** 2` rides the same
447
- # fast path.
433
+ # `**` with an Integer exponent.
448
434
  #
449
- # Routing rule (matches eager `rb_ca_pow`):
435
+ # The eager `rb_ca_pow` sends a Float / Complex array to an Integer power
436
+ # through `rb_ca_ipower` (ext/ca_op_ipower.c), which keeps the exponent
437
+ # an int64 and computes each cell with pow / powf / cpow, the answer the
438
+ # `power` kernel gives for the same exponent held in an array. The lazy
439
+ # form builds the matching CABinOp(OP_IPOWER) node:
450
440
  # - lazy parent + Integer exponent + Float/Complex parent data_type
451
441
  # -> wrap exponent as CScalar.int64 + CABinOp(OP_IPOWER)
452
- # - lazy parent (other cases) -> CABinOp(OP_POW) [existing]
453
- # - else -> eager (which itself dispatches to ipower internally)
442
+ # - lazy parent (other cases) -> CABinOp(OP_POW)
443
+ # - else -> eager
454
444
  #
455
- # Integer parents intentionally stay on OP_POW: the mkkernel-generated
456
- # `power` binop kernel already uses `op_powi_<type>` for integer data_types
457
- # via the `int:` expr in MkKernel.binop :power, so OP_POW + int parent
458
- # is already fast. The lazy-substrate gap was Float/Complex only.
445
+ # Integer parents stay on OP_POW: the `power` kernel's `int:` expr is
446
+ # `op_powi_<type>`, binary exponentiation in the integer type.
459
447
  module LazyDispatch
460
448
  def **(other)
461
449
  if ( lazy_view? || (other.is_a?(CArray) && other.lazy_view?) ) &&
@@ -474,6 +462,14 @@ class CArray
474
462
  end
475
463
  end
476
464
 
465
+ # `pow` is the canonical C method (defined by rb_define_method in
466
+ # ext/ca_op_ipower.c) that `**` is rb_define_alias'd to. The `**`
467
+ # dispatch in this file does not reach `pow` through the C alias, so
468
+ # `a.lazy.pow(2)` would fall to eager; `pow` is aliased again here.
469
+ # An alias copies the method as it is at that moment, so this follows
470
+ # the integer-exponent `**` above, not the template one.
471
+ alias_method :pow, :**
472
+
477
473
  # coerce: when self is a lazy view and the scalar appears on the LEFT
478
474
  # (e.g. `2 * a.lazy`), Ruby's Numeric#* calls a.lazy.coerce(2). The
479
475
  # default coerce would unwrap the lazy-ness via eager scalar promotion;
@@ -495,6 +491,10 @@ class CArray
495
491
  # equality returning bool, not element-wise. Element-wise equality is
496
492
  # `eq` / `feq`.
497
493
  #
494
+ # A comparison with UNDEF goes to the eager method, which answers `eq` /
495
+ # `ne` from the mask and refuses the others, and so does one with nil on
496
+ # an array that can not hold it.
497
+ #
498
498
  # `feq` is arity 1 in eager (compile-time FLT_EPSILON / DBL_EPSILON);
499
499
  # we mirror that here. Runtime eps is a future extension (struct field
500
500
  # already reserved).
@@ -518,7 +518,9 @@ class CArray
518
518
 
519
519
  CArray.send(:define_named_methods, LazyDispatch, LAZY_BINCMP_OP_IDS, template: <<~'RUBY')
520
520
  def __NAME__(other)
521
- if lazy_view? || (other.is_a?(CArray) && other.lazy_view?)
521
+ if UNDEF.equal?(other)
522
+ super(other)
523
+ elsif lazy_view? || (other.is_a?(CArray) && other.lazy_view?)
522
524
  if face_among_operands?(self, other)
523
525
  return computed_operand(self).__send__(__method__, computed_operand(other))
524
526
  end
@@ -540,7 +542,9 @@ class CArray
540
542
 
541
543
  CArray.send(:define_named_methods, LazyDispatch, LAZY_BINCMP_TOL_OP_IDS, template: <<~'RUBY')
542
544
  def __NAME__(other, tol)
543
- if lazy_view? || (other.is_a?(CArray) && other.lazy_view?)
545
+ if UNDEF.equal?(other)
546
+ super(other, tol)
547
+ elsif lazy_view? || (other.is_a?(CArray) && other.lazy_view?)
544
548
  if face_among_operands?(self, other)
545
549
  return computed_operand(self).__send__(__method__, computed_operand(other), tol)
546
550
  end
@@ -45,14 +45,14 @@ class CArray
45
45
  "unmask: pass either a constant fill value or method:, not both"
46
46
  end
47
47
  held = gap_fill(method, axis, "unmask")
48
- # Copy the filled values in place (a Face takes a Face of its own kind
49
- # as it is).
50
- value[] = held.value
51
- if held.has_mask?
52
- self.mask = held.mask # residual leading/trailing mask
53
- else
54
- super() # fully filled: drop the mask
55
- end
48
+ # Write only the cells the fill gave a value (a Face takes a Face of
49
+ # its own kind as it is). Writing every cell would let a view that
50
+ # reaches one cell twice send that cell's unfilled copy back last,
51
+ # masking it again.
52
+ return self unless has_mask?
53
+ filled = is_masked
54
+ filled = filled.and(held.is_not_masked) if held.has_mask?
55
+ self[filled] = held[filled] if filled.any
56
56
  return self
57
57
  end
58
58
  fill.equal?(MASK_FILL_UNSET) ? super() : super(fill)
@@ -161,7 +161,12 @@ class CArray
161
161
  end
162
162
 
163
163
  # Fill the masked cells of this 1-D array by linear interpolation against
164
- # the coordinate `x` (same length, ascending over the present cells).
164
+ # the coordinate `x` (same length). `x` need not be in order: the present
165
+ # cells are read as one series in the order of their `x`, so a frame whose
166
+ # index restarts for each station interpolates across the stations by
167
+ # time (interpolate one station at a time to keep them apart). Present
168
+ # cells sharing an `x` keep their row order. A cell whose `x` is masked,
169
+ # NaN or infinite has no place on the line: it is not used and not filled.
165
170
  # The one rule both the core (x = cell position) and CAFrame (x = index)
166
171
  # use: present cells come back exactly as they are, in this array's own
167
172
  # type; a masked cell inside the span of the present ones takes the
@@ -170,17 +175,34 @@ class CArray
170
175
  # NaN or Inf stored in a present cell is left alone. A Face goes through
171
176
  # its own linear_fetch, which keeps its unit and rounds to its grid.
172
177
  def linear_fill_along (x)
173
- present = is_not_masked
178
+ # A cell whose coordinate is masked, NaN or infinite has no place on the
179
+ # line: it is no point to interpolate between, and is not filled.
180
+ placed = x.is_not_masked
181
+ placed &= x.is_finite if !x.face? && x.float?
182
+ placed = placed.strip_mask(false)
183
+ present = is_not_masked & placed
174
184
  # Fewer than two valid points -> nothing to interpolate between; leave
175
185
  # every masked cell masked.
176
186
  return copy if present.count(true) < 2
177
- addr = x[present].linear_section(x) # valid positions -> monotonic grid
187
+ grid = x[present]
188
+ order = nil
189
+ if ( grid[1..-1] < grid[0..-2] ).any
190
+ order = grid.sort_addr # stable: ties keep their row order
191
+ grid = grid[order]
192
+ end
193
+ addr = grid.linear_section(x) # valid positions -> monotonic grid
194
+ fill = (is_masked & placed & addr.is_finite).strip_mask(false)
178
195
  if face?
179
- # The Face's linear_fetch already masks the exterior (out of range) and
180
- # lands on its own grid.
181
- return self[present].linear_fetch(addr)
196
+ # The Face's linear_fetch lands on its own grid; only the cells to fill
197
+ # take it, so a present cell comes back as it is.
198
+ known = self[present]
199
+ known = known[order] if order
200
+ out = copy
201
+ out[fill] = known.linear_fetch(addr)[fill] if fill.any
202
+ return out
182
203
  end
183
204
  v = value[present]
205
+ v = v[order] if order
184
206
  # A complex value interpolates its real and imaginary parts.
185
207
  interp = v.complex? ? v.linear_fetch(addr) : v.float64.linear_fetch(addr)
186
208
  # An integer array takes the nearest integer, half away from zero (as a
@@ -189,9 +211,7 @@ class CArray
189
211
  interp = interp.round if integer?
190
212
  # Built from the values alone, so a fully filled result carries no mask.
191
213
  out = value.copy
192
- masked = is_masked
193
- fill = masked & addr.is_finite
194
- exterior = masked & fill.not
214
+ exterior = is_masked & fill.not
195
215
  out[fill] = interp[fill] if fill.any
196
216
  out[exterior] = UNDEF if exterior.any
197
217
  out
@@ -171,7 +171,7 @@ class CAMeld
171
171
  # more elaborate (min_count / fill_value / keep_axis / multi-axis /
172
172
  # mask propagation) punts to super.
173
173
  def meld_reduce_fast_path_ok?(kw)
174
- return false unless CArray.__fast_paths_enabled__
174
+ return false unless CArray.__fast_paths_enabled__(:meld_reduce)
175
175
  # The mask of a meld is a meld built in C, with no parents list.
176
176
  return false unless parents
177
177
  return false unless (kw.keys - [:axis]).empty?
@@ -105,6 +105,9 @@ class CArray
105
105
  # @raise [ArgumentError] when `edges` is not 1-D, has fewer than 2
106
106
  # values, has a masked value or NaN, or decreases anywhere. Equal
107
107
  # edges (a bin of zero width) and infinite ones are accepted.
108
+ # Values and edges are compared as float64, so int64 values beyond
109
+ # 2**53 are compared at that precision.
110
+ #
108
111
  # @example
109
112
  # e = CA_FLOAT64([0, 1, 10, 100])
110
113
  # v = CA_FLOAT64([0.5, 5.0, 50.0, -1.0, 200.0])
@@ -41,11 +41,12 @@ class CArray
41
41
  data_type = ca.empty? ? CA_OBJECT : CArray.result_type(*ca)
42
42
  end
43
43
  out = template(data_type)
44
+ dst = out.scalar? ? out.flatten : out # a CScalar takes no index
44
45
  choices.each_with_index do |v, i|
45
46
  s = self.eq(i)
46
- out[s] = v.is_a?(CArray) ? v[s] : v
47
+ dst[s] = !v.is_a?(CArray) ? v : v.scalar? ? v.flatten[s] : v[s]
47
48
  end
48
- out[self.is_masked] = UNDEF if has_mask?
49
+ dst[self.is_masked] = UNDEF if has_mask?
49
50
  text ? CAString.wrap(out) : out
50
51
  end
51
52
 
@@ -140,7 +140,7 @@ class CArray
140
140
  # consistency required across rows / columns).
141
141
  def self.__ragged_paste (list, tdim, axis, data_type, name)
142
142
  shared_attrs = attrs_shared_by(list)
143
- list = CArray.promote_list(list, data_type: data_type)
143
+ list = promote_list_for(name, list, data_type: data_type)
144
144
  # promote_list has already enforced homogeneity (= common data_type, and
145
145
  # for Face elements: same Face class + portable + state-compatible). So,
146
146
  # mirroring CArray.stack, paste at the storage level and re-wrap the
@@ -44,6 +44,8 @@ class CArray
44
44
  if excluded.count(true) > 0
45
45
  codes.mask = codes.has_mask? ? (codes.mask | excluded) : excluded
46
46
  end
47
+ # A const string's discovery reads its bytes and gives Ruby Strings.
48
+ levels = CArray.const_string(levels, encoding: encoding) if is_a?(CAConstString)
47
49
  [codes, levels]
48
50
  end
49
51
 
@@ -94,7 +94,10 @@ class CArray
94
94
  # The write goes through a flattened view, which carries a frozen
95
95
  # array's read-only flag but not its frozenness; say what the array is.
96
96
  raise FrozenError.new("can't modify frozen #{self.class}", receiver: self) if frozen?
97
- flat_addr, _outer, _rest = gather_nd_flat_addr(indices, "put_nd")
97
+ flat_addr, outer, rest = gather_nd_flat_addr(indices, "put_nd")
98
+ # The values lie as gather_nd gives them back.
99
+ out_shape = outer + rest
100
+ flat_addr = flat_addr.reshape(*out_shape) unless out_shape.empty?
98
101
  if flat_addr.has_mask?
99
102
  # A masked coordinate writes nothing. The values are laid out over
100
103
  # the coordinates by the store itself, so they mean what they mean
@@ -40,8 +40,9 @@ class CArray
40
40
  # `Array#include?` does, so they are equal there. To match by value
41
41
  # across Integer and Float, convert the array to a numeric type first.
42
42
  #
43
- # Masked cells of `values` do not enter the set. Masked cells of
44
- # `self` stay masked in the result (membership is unknown), so
43
+ # Masked cells of `values` do not enter the set, and neither does `nil`
44
+ # unless `self` is an `:object` array, which can hold it. Masked cells
45
+ # of `self` stay masked in the result (membership is unknown), so
45
46
  # `is_in` propagates `self`'s mask like an element-wise comparison.
46
47
  #
47
48
  # For a per-fiber "does this fiber contain any of these values"
@@ -59,7 +60,7 @@ class CArray
59
60
  # @return [CArray] boolean CArray of the same shape as `self`.
60
61
  def is_in (values)
61
62
  refuse_range_set(values, "is_in")
62
- a, b = promote_value_set(values)
63
+ a, b = promote_value_set(values_of_set(values))
63
64
  a.__send__(:__is_in__, b)
64
65
  end
65
66
 
@@ -132,6 +133,25 @@ class CArray
132
133
  "((#{values.inspect}).to_a), or test an interval with is_between(#{values.inspect})"
133
134
  end
134
135
 
136
+ # The set as the array reads it. nil is no value of an array that can not
137
+ # hold it, so it enters no set, and true and false are the numbers 1 and 0
138
+ # to an integer, float or complex array, as they are to eq.
139
+ def values_of_set (values)
140
+ return values if data_type == CA_OBJECT
141
+ numeric = !face? && (integer? || float? || complex?)
142
+ case values
143
+ when Array
144
+ values = values.compact
145
+ numeric ? values.map { |v| (v == true) ? 1 : (v == false) ? 0 : v } : values
146
+ when CArray
147
+ ( values.data_type == CA_OBJECT ) ? values.mask_eq(nil) : values
148
+ when true, false
149
+ numeric ? (values ? 1 : 0) : values
150
+ else
151
+ values
152
+ end
153
+ end
154
+
135
155
  # Reconcile a set-valued argument with self to a common data_type via
136
156
  # CArray.result_type (the single-source promotion rule the eager binop and
137
157
  # lazy CABinOp share), returning [self', set']. Only data types are reconciled,