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
@@ -186,9 +186,10 @@ class CAFrame
186
186
  # Read CSV text already in hand into a frame -- the String is the CSV, not
187
187
  # a path. The options and the reading block are +read_csv+'s; +encoding:+
188
188
  # has nothing to open and is refused, the text being in its String's
189
- # encoding. A BOM at the start of UTF-8 or binary text (as File.binread
190
- # and many HTTP bodies give) is skipped, as +read_csv+ skips one at the
191
- # start of a file.
189
+ # encoding. Binary text (bytes with no encoding, as File.binread and many
190
+ # HTTP bodies give) is read as UTF-8, and refused when it is not UTF-8.
191
+ # A BOM at the start of the text is skipped, as +read_csv+ skips one at
192
+ # the start of a file.
192
193
  #
193
194
  # CAFrame.from_csv("date,temp\n2026-01-01,1.5\n")
194
195
  # CAFrame.from_csv(response.body, types: :string)
@@ -202,10 +203,15 @@ class CAFrame
202
203
  raise ArgumentError, "from_csv: encoding: is the open mode of a path; " \
203
204
  "text in hand is read in its String's encoding"
204
205
  end
206
+ if text.encoding == Encoding::BINARY
207
+ text = text.dup.force_encoding(Encoding::UTF_8)
208
+ unless text.valid_encoding?
209
+ raise ArgumentError, "from_csv: the text is bytes with no encoding (ASCII-8BIT) " \
210
+ "and is not UTF-8; give it its encoding with force_encoding"
211
+ end
212
+ end
205
213
  if text.encoding == Encoding::UTF_8
206
214
  text = text.delete_prefix("\uFEFF")
207
- elsif text.encoding == Encoding::BINARY && text.start_with?("\xEF\xBB\xBF".b)
208
- text = text.byteslice(3..) # bytes read from a file or the network
209
215
  end
210
216
  read_csv(StringIO.new(text), **opts, &block)
211
217
  end
@@ -231,7 +237,7 @@ class CAFrame
231
237
  map = types == :infer ? { default: :infer } : types
232
238
  return types unless map.is_a?(Hash)
233
239
  frame.column_names.each do |name|
234
- given = [name, name.to_sym].find { |k| map.key?(k) }
240
+ given = map.keys.find { |k| k == name || k == name.to_sym || (k.is_a?(Array) && k.include?(name)) }
235
241
  next unless (given ? map[given] : map[:default]) == :infer
236
242
  map = map.merge(name => :string) if blank_value_in?(frame[name])
237
243
  end
@@ -247,7 +253,7 @@ class CAFrame
247
253
  # whitespace, and only those are read as Strings.
248
254
  def self.blank_value_in?(col)
249
255
  if col.is_a?(CAConstString)
250
- lead = col.byte_length.eq(0)
256
+ lead = col.bytesize.eq(0)
251
257
  BLANK_LEADS.each { |c| lead = lead.or(col.start_with?(c)) }
252
258
  addrs = lead.strip_mask(false).where
253
259
  return addrs.to_a.any? { |i| col[i].strip.empty? }
@@ -344,7 +350,9 @@ class CAFrame
344
350
  # Drive the reading-control DSL over one open IO and hand back
345
351
  # [names, rows, column_attrs]. Shared by the path and the IO source, so the
346
352
  # two cannot come to read a file differently.
347
- def self.parse_csv_io (io, sep:, quote:, strip:, layout:, read_text_as_const_string: false, &block)
353
+ def self.parse_csv_io(io, sep:, quote:, strip:, layout:, read_text_as_const_string: false, &block)
354
+ strip = CArray.send(:bool_arg, strip, "strip", "from_csv")
355
+ read_text_as_const_string = CArray.send(:bool_arg, read_text_as_const_string, "read_text_as_const_string", "from_csv")
348
356
  reader = CSVReader.new(io, sep: sep, quote: quote, strip: strip,
349
357
  read_text_as_const_string: read_text_as_const_string)
350
358
  reader.reporting do
@@ -451,9 +459,12 @@ class CAFrame
451
459
  # csv = df.to_csv(sep: "\t", index: false)
452
460
  def to_csv(sep: ",", quote: '"', header: true, index: true,
453
461
  encoding: nil, missing: nil, attrs: [], precision: nil)
462
+ header = CArray.send(:bool_arg, header, "header", "to_csv")
463
+ index = CArray.send(:bool_arg, index, "index", "to_csv")
454
464
  unless precision.nil? || (precision.is_a?(Integer) && precision >= 0)
455
465
  raise ArgumentError, "to_csv: precision: is a number of decimal places, 0 or more (got #{precision.inspect})"
456
466
  end
467
+ CSVParser::Tokenizer.check_delimiters(sep, quote)
457
468
  default, per_column = CAFrame.send(:split_missing, missing, "to_csv")
458
469
  [default, *per_column.values].each do |text|
459
470
  next if text.nil? || text.is_a?(String)
@@ -510,7 +521,11 @@ class CAFrame
510
521
  formatted.each_with_index do |fcol, j|
511
522
  token = per_column.fetch(names[j], default)
512
523
  next if token.nil? || token.empty? # the empty field, as without missing:
513
- i = fcol.index(token)
524
+ # A cell in another encoding is the token too once transcoded.
525
+ i = fcol.index(token) || fcol.index do |text|
526
+ text && text.encoding != token.encoding &&
527
+ text.encode(token.encoding, invalid: :replace, undef: :replace) == token
528
+ end
514
529
  if i
515
530
  raise ArgumentError,
516
531
  "to_csv: row #{i} of #{names[j].inspect} is written as " \
@@ -574,7 +589,16 @@ class CAFrame
574
589
  # Long frames are truncated in the middle: +rows+ caps how many rows are
575
590
  # printed (default 20, split evenly around an ellipsis row), and
576
591
  # +rows: nil+ prints every row. +index: false+ drops the index column.
592
+ # +precision:+ and +rows:+ are an Integer, 0 or more, or nil; another
593
+ # value raises ArgumentError.
577
594
  def to_table(rows: 20, index: true, precision: 6)
595
+ index = CArray.send(:bool_arg, index, "index", "to_table")
596
+ unless precision.nil? || (precision.is_a?(Integer) && precision >= 0)
597
+ raise ArgumentError, "to_table: precision: is a number of decimal places, 0 or more (got #{precision.inspect})"
598
+ end
599
+ unless rows.nil? || (rows.is_a?(Integer) && rows >= 0)
600
+ raise ArgumentError, "to_table: rows: is a number of rows, 0 or more (got #{rows.inspect})"
601
+ end
578
602
  head = rows && (rows + 1) / 2
579
603
  render_table(head: head, tail: rows && rows - head,
580
604
  index: index, precision: precision, footer: true)
@@ -757,8 +781,8 @@ class CAFrame
757
781
  # Still a float, so precision: 0 writes 3.0 and the column reads
758
782
  # back as floats.
759
783
  csv_rounded(e, precision).to_s
760
- elsif precision && e.is_a?(Complex) && e.real.is_a?(Float)
761
- Complex(*[e.real, e.imaginary].map { |x| csv_rounded(x, precision) }).to_s
784
+ elsif precision && e.is_a?(Complex) && (e.real.is_a?(Float) || e.imaginary.is_a?(Float))
785
+ Complex(*[e.real, e.imaginary].map { |x| x.is_a?(Float) ? csv_rounded(x, precision) : x }).to_s
762
786
  else
763
787
  e.to_s
764
788
  end
@@ -866,7 +890,7 @@ class CAFrame
866
890
  if text.empty? || text.include?(sep) || text.include?(quote) ||
867
891
  text.include?("\n") || text.include?("\r") || text.each_byte.all? { |b| b == 0x20 || b == 0x09 } ||
868
892
  (sep.size > 1 && (text + sep).index(sep) != text.size)
869
- quote + text.gsub(quote, quote * 2) + quote
893
+ quote + text.gsub(quote) { quote * 2 } + quote
870
894
  else
871
895
  text
872
896
  end
@@ -103,7 +103,7 @@ class CAFrame
103
103
  # locate_nearest_addr (the per-row, row-preserving counterpart of
104
104
  # align_nearest_addr); +direction:+ follows CArray (:floor = most recent
105
105
  # at-or-before, :ceil = next, :round = nearest), and rows with no match
106
- # in that direction or beyond +tolerance:+ come back UNDEF. +tolerance:+
106
+ # in that direction or beyond +tol:+ come back UNDEF. +tol:+
107
107
  # is a number for a numeric key and a duration for a time key
108
108
  # ("10 minutes", or a CATimedelta value). Same wiring as the left join,
109
109
  # only the address primitive differs; +view: :full+ makes +other+'s
@@ -115,8 +115,8 @@ class CAFrame
115
115
  # +on:+ and +by:+ take a Hash of this frame's name to +other+'s for a key
116
116
  # named differently on the two sides, as +join+'s +on:+ does.
117
117
  #
118
- # obs.join_asof(radar, on: "time", by: "station", tolerance: "10 minutes")
119
- def join_asof(other, on:, by: nil, direction: :floor, tolerance: nil, suffixes: DEFAULT_JOIN_SUFFIXES, view: nil)
118
+ # obs.join_asof(radar, on: "time", by: "station", tol: "10 minutes")
119
+ def join_asof(other, on:, by: nil, direction: :floor, tol: nil, suffixes: DEFAULT_JOIN_SUFFIXES, view: nil)
120
120
  refuse_unknown_view(view, "join_asof")
121
121
  ons, ron = join_key_pairs(on, "join_asof", "on:")
122
122
  if ons.size != 1
@@ -135,14 +135,18 @@ class CAFrame
135
135
  key.__send__(:nearest_refuse_bytes, key, "join_asof: the on: key #{on.inspect}",
136
136
  "join on it exactly with join")
137
137
  end
138
+ refuse_rounded_keys(lkey, rkey, "join_asof")
139
+ if [:round, :floor, :ceil].include?(direction)
140
+ rkey.__send__(:nearest_refuse_distanceless, rkey, direction, tol, "join_asof")
141
+ end
138
142
  addr = if exact.empty?
139
- lkey.locate_nearest_addr(rkey, direction: direction, tolerance: tolerance)
143
+ lkey.locate_nearest_addr(rkey, direction: direction, tol: tol)
140
144
  else
141
145
  lexact = exact.map { |name| key_column(name, "join_asof") }
142
146
  rexact = rexact_names.map { |name| other.__send__(:key_column, name, "join_asof") }
143
147
  join_check_key_widths(exact, lexact, rexact, "join_asof")
144
- _, lcode, rcode, k = join_codes(lexact, rexact)
145
- join_asof_by(lkey, rkey, lcode, rcode, k, direction, tolerance)
148
+ _, lcode, rcode, k = join_codes(lexact, rexact, "join_asof")
149
+ join_asof_by(lkey, rkey, lcode, rcode, k, direction, tol)
146
150
  end
147
151
  join_by_addr(other, [on, *exact], [ron, *rexact_names], addr, plan, view)
148
152
  end
@@ -164,7 +168,8 @@ class CAFrame
164
168
  # +key+ may be a column name or the index axis name. +reference+ is a CArray
165
169
  # or an Array; its keys are matched against the source key by value. An
166
170
  # Array is read as values of the key's kind, as +is_in+ reads one: numbers
167
- # against a numeric key, Time / Date / String instants against a time key.
171
+ # against a numeric key, Time / Date / String instants against a time key,
172
+ # and Strings against a text or categorical key, which the result keeps.
168
173
  def align(key, reference)
169
174
  key = column_key(key, "align")
170
175
  on_index = !@columns.key?(key) && @axis_name == key && @index
@@ -172,11 +177,17 @@ class CAFrame
172
177
  # An Array reference is read as values of the key's kind, as is_in reads
173
178
  # one: 1 and 2.5 against a float key are numbers, and Time or String
174
179
  # values against a time key are instants.
175
- ref = reference.is_a?(CArray) ? reference : keys.send(:promote_value_set, reference)[1]
180
+ ref = if reference.is_a?(CArray)
181
+ reference
182
+ else
183
+ (reference.is_a?(Array) && values_of_key_kind(keys, reference)) ||
184
+ keys.send(:promote_value_set, reference)[1]
185
+ end
176
186
  unless ref.ndim == 1
177
187
  raise ArgumentError,
178
188
  "align: the reference has shape #{ref.shape.inspect}; give one key value per row of the result"
179
189
  end
190
+ refuse_rounded_keys(keys, ref, "align")
180
191
  addr = ref.locate_addr(keys)
181
192
  # The result's keys are the reference's values, taken as they are now
182
193
  # and shown with the key's attributes; the caller's array is left as
@@ -195,6 +206,25 @@ class CAFrame
195
206
  end
196
207
  end
197
208
 
209
+ # An Array of values for a text or categorical key, built as an array of
210
+ # the key's own kind, or nil for any other key. promote_value_set builds
211
+ # it in the key's storage type (object or fixlen), so the result's key
212
+ # would lose its kind, and against a CAConstString key nothing would match.
213
+ # A categorical key keeps its labels and gains the values it lacks.
214
+ private def values_of_key_kind(keys, values)
215
+ case keys
216
+ when CACategorical
217
+ present = values.reject { |v| v.nil? || v.equal?(UNDEF) }
218
+ CArray.object(values.size).tap { |o| o[] = values }
219
+ .categorize(labels: keys.labels | present.uniq)
220
+ when CAConstString then CArray.const_string(values)
221
+ when CAFixlenString then CArray.fixlen_string(values)
222
+ when CAString then CArray.string(values)
223
+ end
224
+ rescue TypeError => e
225
+ raise TypeError, "align: #{e.message}"
226
+ end
227
+
198
228
  # Paste +other+'s columns beside this frame's, matched by **row position**
199
229
  # (memo §12-C) — a keyless column merge (the column-direction counterpart of
200
230
  # the row-stacking +concat+, and the positional counterpart of the key-aligned
@@ -320,8 +350,9 @@ class CAFrame
320
350
  # so the number stays below the row count. Returns [parts, lcode, rcode,
321
351
  # k], parts holding each column's [distinct values, left codes, right
322
352
  # codes].
323
- private def join_codes(lkeys, rkeys)
353
+ private def join_codes(lkeys, rkeys, verb = "join")
324
354
  parts = lkeys.zip(rkeys).map do |lkey, rkey|
355
+ refuse_rounded_keys(lkey, rkey, verb)
325
356
  common = CArray.align_addr(lkey, rkey, join: :outer)[0]
326
357
  [common, lkey.locate_addr(common), rkey.locate_addr(common)]
327
358
  end
@@ -338,6 +369,14 @@ class CAFrame
338
369
  [parts, lcode, rcode, k]
339
370
  end
340
371
 
372
+ # The two sides of a key meet at one type; a value that type rounds would
373
+ # match another value.
374
+ private def refuse_rounded_keys(lkey, rkey, verb)
375
+ return if lkey.face? || rkey.face?
376
+ CAFrame.__send__(:refuse_rounded_integers, [lkey, rkey],
377
+ lkey.send(:query_match_type, rkey), verb, "a key")
378
+ end
379
+
341
380
  # The rows of a :semi or :anti join: whether each row's key code occurs
342
381
  # among the other side's codes. A row without a code (a masked key cell)
343
382
  # has no match.
@@ -359,11 +398,11 @@ class CAFrame
359
398
  # key, row); sorting the left keys in among them by (code, key) counts,
360
399
  # for each left row, the right rows of its group below it, and the
361
400
  # nearest is one of the two right rows on either side of that count.
362
- private def join_asof_by(lkey, rkey, lcode, rcode, k, direction, tolerance)
363
- # direction: and tolerance: are checked here, on no rows, whether or
401
+ private def join_asof_by(lkey, rkey, lcode, rcode, k, direction, tol)
402
+ # direction: and tol: are checked here, on no rows, whether or
364
403
  # not any group is in both frames.
365
- lkey[0...0].locate_nearest_addr(rkey[0...0], direction: direction, tolerance: tolerance)
366
- limit = tolerance && CArray::DistanceLimit.read(tolerance, lkey, "tolerance:")
404
+ lkey[0...0].locate_nearest_addr(rkey[0...0], direction: direction, tol: tol)
405
+ limit = tol && CArray::DistanceLimit.read(tol, lkey, "tol:")
367
406
  addr = CArray.int64(lkey.elements).fill(UNDEF)
368
407
 
369
408
  # The right rows that can be found: a code, and a key that is present
@@ -412,7 +451,7 @@ class CAFrame
412
451
  hi = rk.project((start + lt).tap { |a| a[has_hi.not] = UNDEF })
413
452
  # an exact match takes its first reference; otherwise the nearer
414
453
  # neighbour, the upper one on a tie
415
- upper = (hi - qk).le(qk - lo).strip_mask(false)
454
+ upper = lkey.__send__(:nearest_distance, hi, qk).le(lkey.__send__(:nearest_distance, qk, lo)).strip_mask(false)
416
455
  upper[has_lo.not] = true
417
456
  upper[has_hi.not] = false
418
457
  upper[hi.eq(qk).strip_mask(false)] = true
@@ -421,8 +460,7 @@ class CAFrame
421
460
  local[local.lt(0) | local.ge(size)] = UNDEF
422
461
  found = rrows.project(gstart.project(qc) + local)
423
462
  if limit
424
- dist = (rkey.project(found) - lkey.project(lrows)).abs
425
- found[dist > limit] = UNDEF
463
+ found[lkey.__send__(:nearest_beyond, rkey.project(found), lkey.project(lrows), limit)] = UNDEF
426
464
  end
427
465
  addr[lrows] = found
428
466
  addr
@@ -433,7 +471,8 @@ class CAFrame
433
471
  private def asof_searchable(key, code)
434
472
  ok = code.is_not_masked.strip_mask(false)
435
473
  ok &= key.is_not_masked.strip_mask(false) if key.has_mask?
436
- ok &= key.is_nan.strip_mask(false).not if key.float?
474
+ nan = key.__send__(:nearest_nan_cells, key)
475
+ ok &= nan.strip_mask(false).not if nan
437
476
  ok
438
477
  end
439
478
 
@@ -96,7 +96,7 @@ class CAFrame
96
96
  # second) stay an object column of the elements.
97
97
  def self.build_duration_column(values, present, n)
98
98
  unit = begin
99
- present.map(&:unit).reduce { |a, b| CATimeUnitAlgebra.finer(a, b) }
99
+ present.map(&:unit).reduce { |a, b| CATime::UnitAlgebra.finer(a, b) }
100
100
  rescue ArgumentError
101
101
  return mask_missing(CArray.object(n) { values })
102
102
  end
@@ -181,7 +181,8 @@ class CAFrame
181
181
  # :cmplx128 when Complex values join them, otherwise nil (keep object).
182
182
  # Other Numerics (Rational, BigDecimal) stay object: a float column would
183
183
  # round them, and a Complex one has room for them only as floats too. So
184
- # does an Integer an int64 cannot hold: it is kept as it is, not refused.
184
+ # does an Integer an int64 cannot hold, and one past 2**53 beside a Float:
185
+ # it is kept as it is, not refused.
185
186
  INT64_RANGE = (-2**63..2**63 - 1)
186
187
  private_constant :INT64_RANGE
187
188
 
@@ -198,9 +199,10 @@ class CAFrame
198
199
 
199
200
  def self.numeric_leaf_type(values)
200
201
  return nil if values.any? { |v| v.is_a?(Integer) && !INT64_RANGE.cover?(v) }
201
- if values.all? { |v| v.is_a?(Integer) }
202
- :int64
203
- elsif values.all? { |v| v.is_a?(Integer) || v.is_a?(Float) }
202
+ return :int64 if values.all? { |v| v.is_a?(Integer) }
203
+ # Beside a float an integer is read as one, which rounds past 2**53.
204
+ return nil if values.any? { |v| v.is_a?(Integer) && v.abs > 2**53 }
205
+ if values.all? { |v| v.is_a?(Integer) || v.is_a?(Float) }
204
206
  :float64
205
207
  elsif values.all? { |v| v.is_a?(Integer) || v.is_a?(Float) || v.is_a?(Complex) }
206
208
  :cmplx128
@@ -210,11 +210,29 @@ class CAFrame
210
210
  Ractor.make_shareable(SIGNIFICAND_BITS)
211
211
  private_constant :INTEGER_BITS, :SIGNIFICAND_BITS
212
212
 
213
+ # Integers past what +type+'s significand holds would meet as one value
214
+ # once read in it, so they are refused; the verb reads every other integer
215
+ # exactly. +type+ is the float the columns meet at, or anything else, which
216
+ # rounds nothing.
217
+ def self.refuse_rounded_integers(cols, type, verb, what)
218
+ digits = SIGNIFICAND_BITS[CArray.data_type_name(type)]
219
+ return if digits.nil?
220
+ cols.each do |col|
221
+ next if col.face? || !col.integer? || col.count_not_masked == 0
222
+ big = [col.min.abs, col.max.abs].max
223
+ next if big <= 2**digits
224
+ raise ArgumentError,
225
+ "#{verb}: #{what} holds #{big}, past 2**#{digits}, beyond which " \
226
+ "#{CArray.data_type_name(type)} does not hold every integer; cast them to one type first"
227
+ end
228
+ end
229
+ private_class_method :refuse_rounded_integers
230
+
213
231
  # Whether every value of data type +from+ is exactly a value of +to+, for
214
232
  # numbers and booleans: a boolean in any number, an integer in a wide
215
233
  # enough integer (a signed one never in an unsigned) or in a float whose
216
234
  # significand holds it, a float in a wider float or complex.
217
- def self.holds_every_value (from, to)
235
+ def self.holds_every_value(from, to)
218
236
  f = CArray.data_type_name(from)
219
237
  t = CArray.data_type_name(to)
220
238
  return true if f == t || f == "boolean"
@@ -244,7 +262,7 @@ class CAFrame
244
262
  # type, else the narrowest that does; nil when no type does. Decided by
245
263
  # the types alone, so a value written to a column later is one the common
246
264
  # type holds too.
247
- def self.melt_common_type (pieces)
265
+ def self.melt_common_type(pieces)
248
266
  types = pieces.map(&:data_type)
249
267
  holds = ->(to) { types.all? { |t| holds_every_value(t, to) } }
250
268
  first = CArray.result_type(*pieces)
@@ -269,9 +287,11 @@ class CAFrame
269
287
  # melted columns and each id column is +CArray.meld+ of itself, so a write
270
288
  # to the result lands in +self+. Number columns of different types meet
271
289
  # at a type that holds every value of each column's type (int8 and uint8
272
- # at int16, int32 and float64 at float64), so a value written later reads
273
- # back unchanged; a mixture no type holds (int64 and float64) raises, and
274
- # so do other mixtures of types. The value columns share one trailing
290
+ # at int16, int32 and float64 at float64), so a value written to one of
291
+ # the columns later reads back unchanged. A value written to the result
292
+ # lands in the column's own type, as an array stored into it does: outside
293
+ # that type it wraps. A mixture no type holds (int64 and float64) raises,
294
+ # and so do other mixtures of types. The value columns share one trailing
275
295
  # shape; cast first when they do not.
276
296
  #
277
297
  # @param id [String, Array<String>] columns repeated alongside each value.
@@ -332,11 +352,11 @@ class CAFrame
332
352
  begin
333
353
  out[value_name] = CArray.meld(pieces)
334
354
  rescue ArgumentError => e
335
- raise unless e.message.start_with?("promote_list:")
355
+ raise unless e.message.start_with?("meld:", "CAMeld parents")
336
356
  labels = vars.zip(pieces.map { |c| CArray::Inspector.type_label(c) }).to_h
337
357
  raise ArgumentError,
338
358
  "melt: value columns #{labels} do not meet as one column " \
339
- "(#{e.message.delete_prefix("promote_list: ")}); cast them to one type first"
359
+ "(#{e.message.delete_prefix("meld: ")}); cast them to one type first"
340
360
  end
341
361
  CAFrame.new(out)
342
362
  end
@@ -1,4 +1,4 @@
1
- # CAFrame row sort (memo §5, spine = addressing + gather).
1
+ # CAFrame row sort (memo §5; the core is addressing + gather).
2
2
  #
3
3
  # Two entry points, both delegating to the multi-key CArray.sort_addr -- the
4
4
  # class-method lexicographic sort that returns flat row addresses (distinct from
@@ -12,7 +12,7 @@
12
12
  # math.
13
13
  #
14
14
  # sort_addr is ascending, so a descending key is expressed by replacing it with
15
- # its dense descending rank (CArray#order(descending: true, method: :dense)):
15
+ # its dense descending rank (CArray#rank_index(descending: true, method: :dense)):
16
16
  # this works for every data type (unlike negation, which cannot reverse a string and
17
17
  # silently wraps an unsigned integer), and the *dense* rank keeps equal values
18
18
  # on one rank so ties fall through to later keys in a multi-key sort.
@@ -27,7 +27,7 @@ class CAFrame
27
27
  # Each key is a **column name** (or the index axis name), or a
28
28
  # **`[name, :asc | :desc]`** pair for a per-key direction. +descending: true+
29
29
  # sorts the bare-name keys from largest to smallest (default ascending), as
30
- # +CArray#order+ takes it. +masked_position:+
30
+ # +CArray#rank_index+ takes it. +masked_position:+
31
31
  # sends masked key rows to the +:last+ (default) or +:first+ end.
32
32
  #
33
33
  # df.sort_by_key("temp") # one column, ascending
@@ -37,6 +37,7 @@ class CAFrame
37
37
  # df.sort_by_key("temp", masked_position: :first) # masked rows first
38
38
  # df.sort_by_key("time") # by the index
39
39
  def sort_by_key(*specs, descending: false, masked_position: :last)
40
+ descending = CArray.send(:bool_arg, descending, "descending", "sort_by_key")
40
41
  raise ArgumentError, "sort_by_key requires at least one key" if specs.empty?
41
42
  order = descending ? :desc : :asc
42
43
  named = specs.map do |spec|
@@ -45,7 +46,7 @@ class CAFrame
45
46
  end
46
47
  CAFrame.__send__(:refuse_repeated_names, named.map(&:first), "sort_by_key")
47
48
  keys = named.map do |name, col, dir|
48
- dir == :desc ? col.order(descending: true, method: :dense) : col
49
+ dir == :desc ? col.rank_index(descending: true, method: :dense) : col
49
50
  end
50
51
  select_rows(CArray.sort_addr(*keys, masked_position: masked_position))
51
52
  rescue ArgumentError, CArray::DataTypeError => e
@@ -89,7 +90,7 @@ class CAFrame
89
90
  # @param keys [Array<String>] the key columns (or the index axis name).
90
91
  # @return [CAFrame]
91
92
  # @raise [ArgumentError] when +n+ is negative or no key is given.
92
- def nlargest (n, *keys)
93
+ def nlargest(n, *keys)
93
94
  return largest_or_smallest("nlargest", n, keys, true)
94
95
  end
95
96
 
@@ -100,11 +101,11 @@ class CAFrame
100
101
  # @param keys [Array<String>] the key columns (or the index axis name).
101
102
  # @return [CAFrame]
102
103
  # @raise [ArgumentError] when +n+ is negative or no key is given.
103
- def nsmallest (n, *keys)
104
+ def nsmallest(n, *keys)
104
105
  return largest_or_smallest("nsmallest", n, keys, false)
105
106
  end
106
107
 
107
- private def largest_or_smallest (verb, n, keys, descending)
108
+ private def largest_or_smallest(verb, n, keys, descending)
108
109
  unless n.is_a?(Integer)
109
110
  raise TypeError, "#{verb}: the count is an Integer (got #{n.inspect})"
110
111
  end
@@ -133,6 +134,7 @@ class CAFrame
133
134
  # df.sort_by { |f| (f["temp"] - target).abs } # nearest-to-target first
134
135
  # df.sort_by(descending: true) { |f| f["name"].length }
135
136
  def sort_by(descending: false, masked_position: :last)
137
+ descending = CArray.send(:bool_arg, descending, "descending", "sort_by")
136
138
  raise ArgumentError, "sort_by requires a block" unless block_given?
137
139
  keys = yield(self)
138
140
  keys = [keys] unless keys.is_a?(Array)
@@ -146,7 +148,7 @@ class CAFrame
146
148
  "sort_by key #{i} must be a 1-D column of length #{nrow} (got shape #{k.shape.inspect})"
147
149
  end
148
150
  end
149
- keys = keys.map { |k| k.order(descending: true, method: :dense) } if descending
151
+ keys = keys.map { |k| k.rank_index(descending: true, method: :dense) } if descending
150
152
  select_rows(CArray.sort_addr(*keys, masked_position: masked_position))
151
153
  end
152
154