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
@@ -29,9 +29,27 @@ class CAFrame
29
29
  # right row.
30
30
  #
31
31
  # Rows come in left-row order (right-row order for :right), the pairs of
32
- # one row in the other side's order. The left columns are views of this
33
- # frame's, picked by row, wherever every row comes from the left (:left,
34
- # :inner); the right columns are gathered into new arrays.
32
+ # one row in the other side's order. A side whose row every result row
33
+ # has gives views of its columns, picked by row: this frame's for :left
34
+ # and :inner, +other+'s for :inner and :right (for :right, the key column
35
+ # too). A
36
+ # write to the result then reaches that frame, and reading the result
37
+ # gathers through the views each time; call +copy+ on the result for
38
+ # columns of its own, when it will be written or read many times. The
39
+ # side that gets UNDEF for an unmatched row is gathered into new arrays.
40
+ #
41
+ # The views are for cleaning data through the join, on frames read in as
42
+ # working copies just before an analysis: a condition built from both
43
+ # frames' columns masks or corrects the cells it marks, and the write
44
+ # lands in the frame they came from. +view: :full+ (experimental)
45
+ # makes the other side views too, so a write reaches either frame, with a
46
+ # hole where a row has no match: the hole reads UNDEF and a write to it is
47
+ # dropped. Every result column then reaches its frame, at a cost on each
48
+ # read (a column with holes is gathered whole: a reduction is about
49
+ # three times slower than on a column of its own, a +copy+ five to ten). The key of an outer join welds the two key
50
+ # columns (+CArray.meld+), so it needs keys of one kind on both sides, the
51
+ # same type and, for a Face, the same state (time unit, labels); a key of
52
+ # +CAConstString+ cannot be welded.
35
53
  #
36
54
  # A non-key column present on both sides collides. The key column (+on+) is
37
55
  # kept once, never suffixed. By default the collision is resolved by suffixing
@@ -41,8 +59,12 @@ class CAFrame
41
59
  #
42
60
  # +on:+ may name several columns, as an Array: rows then match when every
43
61
  # key column matches, and a row with any key cell masked matches nothing.
62
+ # When the key has different names on the two sides, give a Hash of this
63
+ # frame's name to +other+'s; the key column keeps this frame's name, and
64
+ # +other+'s key column is not added.
44
65
  #
45
66
  # obs.join(fcst, on: ["station", "date"])
67
+ # obs.join(stations, on: { "station" => "code" })
46
68
  #
47
69
  # Two modes filter this frame's rows by +other+ instead of pairing them:
48
70
  #
@@ -55,21 +77,25 @@ class CAFrame
55
77
  # The result shares this frame's columns and index, as +filter+'s does.
56
78
  #
57
79
  # obs.join(stations, on: "station", how: :anti) # stations not listed
58
- def join(other, on:, how: :left, suffixes: DEFAULT_JOIN_SUFFIXES)
80
+ def join(other, on:, how: :left, suffixes: DEFAULT_JOIN_SUFFIXES, view: nil)
59
81
  unless %i[left inner outer right semi anti].include?(how)
60
82
  raise ArgumentError, "unknown join mode #{how.inspect}"
61
83
  end
84
+ refuse_unknown_view(view, "join")
85
+ if (how == :semi || how == :anti) && view
86
+ raise ArgumentError, "join: how: #{how.inspect} adds no column of the other frame, so view: does not apply"
87
+ end
62
88
  if (how == :semi || how == :anti) && !suffixes.equal?(DEFAULT_JOIN_SUFFIXES)
63
89
  raise ArgumentError, "join: how: #{how.inspect} adds no column of the other frame, so suffixes: does not apply"
64
90
  end
65
- names = join_key_names(on, "join", "on:")
91
+ names, rnames = join_key_pairs(on, "join", "on:")
66
92
  lkeys = names.map { |name| key_column(name, "join") }
67
- rkeys = names.map { |name| other.__send__(:key_column, name, "join") }
93
+ rkeys = rnames.map { |name| other.__send__(:key_column, name, "join") }
68
94
  join_check_key_widths(names, lkeys, rkeys, "join")
69
95
  return join_filter(lkeys, rkeys, how) if how == :semi || how == :anti
70
96
 
71
- plan = join_name_plan(other, names, suffixes)
72
- join_pairs(other, names, lkeys, rkeys, how, plan)
97
+ plan = join_name_plan(other, names, rnames, suffixes)
98
+ join_pairs(other, names, rnames, lkeys, rkeys, how, plan, view)
73
99
  end
74
100
 
75
101
  # As-of (nearest-key) left join for irregular series (memo §11.7). Each
@@ -80,36 +106,49 @@ class CAFrame
80
106
  # in that direction or beyond +tolerance:+ come back UNDEF. +tolerance:+
81
107
  # is a number for a numeric key and a duration for a time key
82
108
  # ("10 minutes", or a CATimedelta value). Same wiring as the left join,
83
- # only the address primitive differs.
109
+ # only the address primitive differs; +view: :full+ makes +other+'s
110
+ # columns views with holes, as +join+'s does.
84
111
  #
85
112
  # +by:+ names columns that must match exactly, one name or an Array: each
86
113
  # left row is matched to the nearest row among the rows of +other+ with
87
114
  # the same +by+ values. A row with a masked +by+ cell matches nothing.
115
+ # +on:+ and +by:+ take a Hash of this frame's name to +other+'s for a key
116
+ # named differently on the two sides, as +join+'s +on:+ does.
88
117
  #
89
118
  # obs.join_asof(radar, on: "time", by: "station", tolerance: "10 minutes")
90
- def join_asof(other, on:, by: nil, direction: :floor, tolerance: nil, suffixes: DEFAULT_JOIN_SUFFIXES)
91
- on = column_key(on, "join_asof")
92
- exact = by.nil? ? [] : join_key_names(by, "join_asof", "by:")
93
- if exact.include?(on)
94
- raise ArgumentError, "join_asof: #{on.inspect} is the on: key; by: names the others"
119
+ def join_asof(other, on:, by: nil, direction: :floor, tolerance: nil, suffixes: DEFAULT_JOIN_SUFFIXES, view: nil)
120
+ refuse_unknown_view(view, "join_asof")
121
+ ons, ron = join_key_pairs(on, "join_asof", "on:")
122
+ if ons.size != 1
123
+ raise ArgumentError, "join_asof: on: names one key column (got #{ons.size}); by: names the others"
124
+ end
125
+ on, ron = ons.first, ron.first
126
+ exact, rexact_names = by.nil? ? [[], []] : join_key_pairs(by, "join_asof", "by:")
127
+ if exact.include?(on) || rexact_names.include?(ron)
128
+ name = exact.include?(on) ? on : ron
129
+ raise ArgumentError, "join_asof: #{name.inspect} is the on: key; by: names the others"
95
130
  end
96
- plan = join_name_plan(other, [on, *exact], suffixes)
131
+ plan = join_name_plan(other, [on, *exact], [ron, *rexact_names], suffixes)
97
132
  lkey = key_column(on, "join_asof")
98
- rkey = other.__send__(:key_column, on, "join_asof")
133
+ rkey = other.__send__(:key_column, ron, "join_asof")
99
134
  [lkey, rkey].each do |key|
100
135
  key.__send__(:nearest_refuse_bytes, key, "join_asof: the on: key #{on.inspect}",
101
136
  "join on it exactly with join")
102
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, tolerance, "join_asof")
141
+ end
103
142
  addr = if exact.empty?
104
143
  lkey.locate_nearest_addr(rkey, direction: direction, tolerance: tolerance)
105
144
  else
106
145
  lexact = exact.map { |name| key_column(name, "join_asof") }
107
- rexact = exact.map { |name| other.__send__(:key_column, name, "join_asof") }
146
+ rexact = rexact_names.map { |name| other.__send__(:key_column, name, "join_asof") }
108
147
  join_check_key_widths(exact, lexact, rexact, "join_asof")
109
- _, lcode, rcode, k = join_codes(lexact, rexact)
148
+ _, lcode, rcode, k = join_codes(lexact, rexact, "join_asof")
110
149
  join_asof_by(lkey, rkey, lcode, rcode, k, direction, tolerance)
111
150
  end
112
- join_by_addr(other, [on, *exact], addr, plan)
151
+ join_by_addr(other, [on, *exact], [ron, *rexact_names], addr, plan, view)
113
152
  end
114
153
 
115
154
  # Conform every column to an externally supplied reference key set (the
@@ -142,6 +181,7 @@ class CAFrame
142
181
  raise ArgumentError,
143
182
  "align: the reference has shape #{ref.shape.inspect}; give one key value per row of the result"
144
183
  end
184
+ refuse_rounded_keys(keys, ref, "align")
145
185
  addr = ref.locate_addr(keys)
146
186
  # The result's keys are the reference's values, taken as they are now
147
187
  # and shown with the key's attributes; the caller's array is left as
@@ -259,12 +299,21 @@ class CAFrame
259
299
  end
260
300
  end
261
301
 
262
- # The key column names of a join: one name, or an Array of names.
263
- private def join_key_names(on, verb, option)
264
- names = on.is_a?(Array) ? on : [on]
265
- raise ArgumentError, "#{verb}: #{option} names no key column" if names.empty?
266
- CAFrame.__send__(:refuse_repeated_names, names.map { |name| column_key(name, verb) },
267
- verb, "#{option} names")
302
+ # The key column names of a join, this frame's and the other's: one name
303
+ # or an Array of names (the same on both sides), or a Hash of this frame's
304
+ # name to the other's.
305
+ private def join_key_pairs(on, verb, option)
306
+ pairs = case on
307
+ when Hash then on.to_a
308
+ when Array then on.map { |name| [name, name] }
309
+ else [[on, on]]
310
+ end
311
+ raise ArgumentError, "#{verb}: #{option} names no key column" if pairs.empty?
312
+ lnames = pairs.map { |name, _| column_key(name, verb) }
313
+ rnames = pairs.map { |_, name| column_key(name, verb) }
314
+ CAFrame.__send__(:refuse_repeated_names, lnames, verb, "#{option} names")
315
+ CAFrame.__send__(:refuse_repeated_names, rnames, verb, "#{option} names")
316
+ return [lnames, rnames]
268
317
  end
269
318
 
270
319
  # Codes for the rows of both sides of a join on +lkeys+ / +rkeys+ (one
@@ -276,8 +325,9 @@ class CAFrame
276
325
  # so the number stays below the row count. Returns [parts, lcode, rcode,
277
326
  # k], parts holding each column's [distinct values, left codes, right
278
327
  # codes].
279
- private def join_codes(lkeys, rkeys)
328
+ private def join_codes(lkeys, rkeys, verb = "join")
280
329
  parts = lkeys.zip(rkeys).map do |lkey, rkey|
330
+ refuse_rounded_keys(lkey, rkey, verb)
281
331
  common = CArray.align_addr(lkey, rkey, join: :outer)[0]
282
332
  [common, lkey.locate_addr(common), rkey.locate_addr(common)]
283
333
  end
@@ -294,6 +344,14 @@ class CAFrame
294
344
  [parts, lcode, rcode, k]
295
345
  end
296
346
 
347
+ # The two sides of a key meet at one type; a value that type rounds would
348
+ # match another value.
349
+ private def refuse_rounded_keys(lkey, rkey, verb)
350
+ return if lkey.face? || rkey.face?
351
+ CAFrame.__send__(:refuse_rounded_integers, [lkey, rkey],
352
+ lkey.send(:query_match_type, rkey), verb, "a key")
353
+ end
354
+
297
355
  # The rows of a :semi or :anti join: whether each row's key code occurs
298
356
  # among the other side's codes. A row without a code (a masked key cell)
299
357
  # has no match.
@@ -368,7 +426,7 @@ class CAFrame
368
426
  hi = rk.project((start + lt).tap { |a| a[has_hi.not] = UNDEF })
369
427
  # an exact match takes its first reference; otherwise the nearer
370
428
  # neighbour, the upper one on a tie
371
- upper = (hi - qk).le(qk - lo).strip_mask(false)
429
+ upper = lkey.__send__(:nearest_distance, hi, qk).le(lkey.__send__(:nearest_distance, qk, lo)).strip_mask(false)
372
430
  upper[has_lo.not] = true
373
431
  upper[has_hi.not] = false
374
432
  upper[hi.eq(qk).strip_mask(false)] = true
@@ -377,8 +435,7 @@ class CAFrame
377
435
  local[local.lt(0) | local.ge(size)] = UNDEF
378
436
  found = rrows.project(gstart.project(qc) + local)
379
437
  if limit
380
- dist = (rkey.project(found) - lkey.project(lrows)).abs
381
- found[dist > limit] = UNDEF
438
+ found[lkey.__send__(:nearest_beyond, rkey.project(found), lkey.project(lrows), limit)] = UNDEF
382
439
  end
383
440
  addr[lrows] = found
384
441
  addr
@@ -389,16 +446,19 @@ class CAFrame
389
446
  private def asof_searchable(key, code)
390
447
  ok = code.is_not_masked.strip_mask(false)
391
448
  ok &= key.is_not_masked.strip_mask(false) if key.has_mask?
392
- ok &= key.is_nan.strip_mask(false).not if key.float?
449
+ nan = key.__send__(:nearest_nan_cells, key)
450
+ ok &= nan.strip_mask(false).not if nan
393
451
  ok
394
452
  end
395
453
 
396
454
  # The left index keeps its name as the result's row axis, so a right
397
455
  # column of that name collides with it as with a left column: it takes
398
456
  # the right suffix, and there is no left column to take the left one.
399
- private def join_name_plan(other, names, suffixes)
457
+ # The names of +other+'s columns that the join adds (its key columns
458
+ # +rnames+ are not added) and that this frame already has collide.
459
+ private def join_name_plan(other, names, rnames, suffixes)
400
460
  taken = @index ? column_names | [@axis_name] : column_names
401
- collisions = (taken & other.column_names) - names
461
+ collisions = taken & (other.column_names - rnames)
402
462
  return { collisions: [], lsuf: nil, rsuf: nil } if collisions.empty?
403
463
 
404
464
  if suffixes == false
@@ -427,19 +487,24 @@ class CAFrame
427
487
  cols[name] = col
428
488
  end
429
489
 
430
- private def join_by_addr(other, names, addr, plan)
490
+ # The left key columns keep their names, as in join_pairs; a right column
491
+ # of the same name takes the right suffix.
492
+ private def join_by_addr(other, names, rnames, addr, plan, view)
431
493
  cols = {}
432
- column_names.each { |name| put_join_column(cols, join_name(name, plan[:lsuf], plan), self[name]) }
494
+ column_names.each do |name|
495
+ name_out = names.include?(name) ? name : join_name(name, plan[:lsuf], plan)
496
+ put_join_column(cols, name_out, self[name])
497
+ end
433
498
  other.column_names.each do |name|
434
- next if names.include?(name)
435
- put_join_column(cols, join_name(name, plan[:rsuf], plan), project_rows(other[name], addr))
499
+ next if rnames.include?(name)
500
+ put_join_column(cols, join_name(name, plan[:rsuf], plan), join_rows(other[name], addr, view))
436
501
  end
437
502
  CAFrame.new(cols, axis_name: @axis_name, index: @index)
438
503
  end
439
504
 
440
505
  # The rows of a key join: li / ri are the left / right row of each result
441
506
  # row, UNDEF on the side a row has no match on.
442
- private def join_pairs(other, names, lkeys, rkeys, how, plan)
507
+ private def join_pairs(other, names, rnames, lkeys, rkeys, how, plan, view)
443
508
  parts, lcode, rcode, k = join_codes(lkeys, rkeys)
444
509
  extra = nil
445
510
  if how == :right
@@ -463,21 +528,33 @@ class CAFrame
463
528
  every_left = how == :left || how == :inner
464
529
  identity = every_left && li.elements == nrow &&
465
530
  (nrow == 0 || li.eq(CArray.int64(nrow).seq).all)
466
- rows = { li: li, ri: ri, extra: extra, how: how, every_left: every_left, identity: identity }
531
+ # Every result row of an inner or right join has a row of the other
532
+ # frame, so its columns are views of those rows, as the left's are in
533
+ # an inner or left join.
534
+ every_right = how == :right || how == :inner
535
+ right_identity = every_right && ri.elements == other.nrow &&
536
+ (other.nrow == 0 || ri.eq(CArray.int64(other.nrow).seq).all)
537
+ rows = { li: li, ri: ri, extra: extra, how: how, every_left: every_left, identity: identity,
538
+ view: view }
467
539
  cols = {}
468
540
  column_names.each do |name|
469
541
  j = names.index(name)
470
542
  col = if j then joined_key(j, parts, lkeys, rkeys, rows)
471
543
  elsif identity then self[name]
472
544
  elsif every_left then self[name][li, *([nil] * (self[name].ndim - 1))]
473
- else project_rows(self[name], li)
545
+ else join_rows(self[name], li, view)
474
546
  end
475
547
  name = join_name(name, plan[:lsuf], plan) unless j
476
548
  put_join_column(cols, name, col)
477
549
  end
478
550
  other.column_names.each do |name|
479
- next if names.include?(name)
480
- put_join_column(cols, join_name(name, plan[:rsuf], plan), project_rows(other[name], ri))
551
+ next if rnames.include?(name)
552
+ col = other[name]
553
+ col = if right_identity then col
554
+ elsif every_right then col[ri, *([nil] * (col.ndim - 1))]
555
+ else join_rows(col, ri, view)
556
+ end
557
+ put_join_column(cols, join_name(name, plan[:rsuf], plan), col)
481
558
  end
482
559
  # A key that is the left index is the result's index, as a key column
483
560
  # is a column of it.
@@ -486,7 +563,7 @@ class CAFrame
486
563
  elsif ij then joined_key(ij, parts, lkeys, rkeys, rows)
487
564
  elsif identity then @index
488
565
  elsif every_left then @index[li]
489
- else project_rows(@index, li)
566
+ else join_rows(@index, li, view)
490
567
  end
491
568
  CAFrame.new(cols, axis_name: @axis_name, index: new_index)
492
569
  end
@@ -498,7 +575,8 @@ class CAFrame
498
575
  li, ri = rows[:li], rows[:ri]
499
576
  return lkeys[j] if rows[:identity]
500
577
  return lkeys[j][li] if rows[:every_left]
501
- return project_rows(rkeys[j], ri) if rows[:how] == :right
578
+ return rkeys[j][ri] if rows[:how] == :right
579
+ return joined_key_view(lkeys[j], rkeys[j], li, rows[:extra]) if rows[:view]
502
580
  common, lc, rc = parts[j]
503
581
  extra = rows[:extra]
504
582
  code = if extra
@@ -586,6 +664,51 @@ class CAFrame
586
664
  end
587
665
  end
588
666
 
667
+ # The key of an outer join as a view: the two key columns welded
668
+ # (+CArray.meld+), picked at the left rows and then at the right rows no
669
+ # left row matched. Welding the whole columns, whatever rows the join
670
+ # gives, makes the call raise or pass the same way with any data, and
671
+ # makes the key show the attributes both keys have alike, as the default
672
+ # key does.
673
+ private def joined_key_view(lkey, rkey, li, extra)
674
+ # A Face's class, not the view class a filtered key has.
675
+ lface = lkey.class if lkey.face?
676
+ rface = rkey.class if rkey.face?
677
+ reason = if lface != rface || lkey.data_type != rkey.data_type
678
+ "#{CArray::Inspector.type_label(lkey)} and #{CArray::Inspector.type_label(rkey)}"
679
+ end
680
+ unless reason
681
+ begin
682
+ both = CArray.meld([lkey, rkey], axis: 0)
683
+ rescue ArgumentError => e # a Face's state, such as a time unit
684
+ reason = e.message
685
+ end
686
+ end
687
+ if reason
688
+ raise ArgumentError,
689
+ "join: view: :full welds the two key columns of an outer join, which needs " \
690
+ "one kind of key (#{reason}); cast one side first, or leave view: out"
691
+ end
692
+ return both[li] unless extra
693
+ nleft = li.elements - extra.elements
694
+ both[CArray.concatenate([li[0...nleft], extra + lkey.elements])]
695
+ end
696
+
697
+ # view: is nil (views where every row has a row of the side, new columns
698
+ # where some do not) or :full (views throughout, UNDEF for a row with no
699
+ # row of the side).
700
+ private def refuse_unknown_view(view, verb)
701
+ return if view.nil? || view == :full
702
+ raise ArgumentError, "#{verb}: view: takes :full (got #{view.inspect})"
703
+ end
704
+
705
+ # The rows +addr+ picks from +col+, UNDEF where +addr+ is masked: a view
706
+ # with view: :full, else a new column.
707
+ private def join_rows(col, addr, view)
708
+ return project_rows(col, addr) unless view == :full
709
+ col[addr, *([nil] * (col.ndim - 1))]
710
+ end
711
+
589
712
  private def project_rows(col, addr)
590
713
  return col.project(addr) if col.ndim == 1
591
714
  trailing = col.shape[1..]
@@ -1,7 +1,7 @@
1
1
  # CAFrame record (row-oriented) input (memo §11.2, §11.5).
2
2
  #
3
3
  # from_records takes an Array of row Hashes -- the shape JSON.parse yields for
4
- # a JSON array of objects -- and arranges it into columns. Unlike from_csv,
4
+ # a JSON array of objects -- and arranges it into columns. Unlike read_csv,
5
5
  # the cell values are already typed Ruby objects (Float / Integer / DateTime /
6
6
  # String), so a homogeneous column is built at its native leaf type rather than
7
7
  # left as strings ("arrange by the value's own type", not string inference --
@@ -41,7 +41,7 @@ class CAFrame
41
41
  end
42
42
 
43
43
  frame = new(cols)
44
- frame.cast(types, on_error: on_error, option_name: :types) unless types.nil?
44
+ frame.__send__(:cast_in_place, types, on_error: on_error, option_name: :types) unless types.nil?
45
45
  frame
46
46
  end
47
47
 
@@ -67,7 +67,7 @@ class CAFrame
67
67
  # them (CAFrame.new and df[name]= given an Array, from_records, the values
68
68
  # a group's block or Proc gives). All-Array cells of equal length -> N-D
69
69
  # native column; numeric scalars -> native scalar column (missing ->
70
- # UNDEF); Strings -> a text column (CAString), as from_csv reads text;
70
+ # UNDEF); Strings -> a text column (CAString), as read_csv reads text;
71
71
  # time and duration elements -> a CATime / CATimedelta column in the finest
72
72
  # resolution among them; anything else -> object column.
73
73
  def self.build_record_column(values, n)
@@ -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
@@ -165,8 +165,8 @@ class CAFrame
165
165
  # names-check: two rows for one cell of the grid
166
166
  first = cell.to_a.tally.find { |_, count| count > 1 }.first
167
167
  raise ArgumentError,
168
- "pivot: more than one row for #{index}=#{rlab[first / nc].inspect}, " \
169
- "#{columns}=#{clab[first % nc].inspect}; pass aggregate: to combine them"
168
+ "pivot: more than one row for #{index}=#{CAFrame.__send__(:key_text, rlab[first / nc])}, " \
169
+ "#{columns}=#{CAFrame.__send__(:key_text, clab[first % nc])}; pass aggregate: to combine them"
170
170
  end
171
171
  source[cell] = CArray.int64(nrow).seq[placed]
172
172
  end
@@ -199,6 +199,79 @@ class CAFrame
199
199
  groups.public_send(plan[:aggregate])
200
200
  end
201
201
 
202
+ # The bits of each integer type and whether it is signed; the significand
203
+ # bits of each floating type (a complex type by its parts).
204
+ INTEGER_BITS = {
205
+ "int8" => [8, true], "int16" => [16, true], "int32" => [32, true], "int64" => [64, true],
206
+ "uint8" => [8, false], "uint16" => [16, false], "uint32" => [32, false], "uint64" => [64, false],
207
+ }.freeze
208
+ SIGNIFICAND_BITS = { "float32" => 24, "float64" => 53, "cmplx64" => 24, "cmplx128" => 53 }.freeze
209
+ Ractor.make_shareable(INTEGER_BITS)
210
+ Ractor.make_shareable(SIGNIFICAND_BITS)
211
+ private_constant :INTEGER_BITS, :SIGNIFICAND_BITS
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
+
231
+ # Whether every value of data type +from+ is exactly a value of +to+, for
232
+ # numbers and booleans: a boolean in any number, an integer in a wide
233
+ # enough integer (a signed one never in an unsigned) or in a float whose
234
+ # significand holds it, a float in a wider float or complex.
235
+ def self.holds_every_value (from, to)
236
+ f = CArray.data_type_name(from)
237
+ t = CArray.data_type_name(to)
238
+ return true if f == t || f == "boolean"
239
+ if (fbits, fsigned = INTEGER_BITS[f])
240
+ if (tbits, tsigned = INTEGER_BITS[t])
241
+ return fsigned ? (tsigned && tbits >= fbits) : (tsigned ? tbits > fbits : tbits >= fbits)
242
+ end
243
+ significand = SIGNIFICAND_BITS[t]
244
+ return !significand.nil? && (fsigned ? fbits - 1 : fbits) <= significand
245
+ end
246
+ fs = SIGNIFICAND_BITS[f]
247
+ ts = SIGNIFICAND_BITS[t]
248
+ return false if fs.nil? || ts.nil? || ts < fs
249
+ return !(f.start_with?("cmplx") && t.start_with?("float"))
250
+ end
251
+ private_class_method :holds_every_value
252
+
253
+ # The types melt may bring number columns to, narrowest first within each
254
+ # kind, so the first that holds every column's type is the common one.
255
+ MELT_TYPES = %w[int8 uint8 int16 uint16 int32 uint32 int64 uint64
256
+ float32 float64 cmplx64 cmplx128].freeze
257
+ Ractor.make_shareable(MELT_TYPES)
258
+ private_constant :MELT_TYPES
259
+
260
+ # The common type of number (and boolean) columns of different types: the
261
+ # one CArray.result_type picks when it holds every value of every column's
262
+ # type, else the narrowest that does; nil when no type does. Decided by
263
+ # the types alone, so a value written to a column later is one the common
264
+ # type holds too.
265
+ def self.melt_common_type (pieces)
266
+ types = pieces.map(&:data_type)
267
+ holds = ->(to) { types.all? { |t| holds_every_value(t, to) } }
268
+ first = CArray.result_type(*pieces)
269
+ return first if holds.(first)
270
+ name = MELT_TYPES.find { |t| holds.(t) }
271
+ name&.to_sym
272
+ end
273
+ private_class_method :melt_common_type
274
+
202
275
  # Gather a wide frame into a long one. The +value_columns+ are stacked one
203
276
  # after another into a single +value_name+ column, a +var_name+ column says
204
277
  # which of them each row came from (a text column), and every +id+ column
@@ -212,8 +285,14 @@ class CAFrame
212
285
  #
213
286
  # The result is a view frame: the value column is +CArray.meld+ of the
214
287
  # melted columns and each id column is +CArray.meld+ of itself, so a write
215
- # to the result lands in +self+. The value columns must therefore share
216
- # one data type and one trailing shape; cast first when they do not.
288
+ # to the result lands in +self+. Number columns of different types meet
289
+ # at a type that holds every value of each column's type (int8 and uint8
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
295
+ # shape; cast first when they do not.
217
296
  #
218
297
  # @param id [String, Array<String>] columns repeated alongside each value.
219
298
  # @param value_columns [Array<String>, nil] columns to stack; default all
@@ -222,7 +301,7 @@ class CAFrame
222
301
  # @param value_name [String] name of the stacked value column.
223
302
  # @return [CAFrame] a view frame of +nrow * value_columns.size+ rows.
224
303
  # @raise [ArgumentError] when there is nothing to melt, or the value
225
- # columns differ in data type.
304
+ # columns differ in data type and no type holds every value of each.
226
305
  def melt(id: [], value_columns: nil, var_name: "variable", value_name: "value")
227
306
  ids = column_keys(Array(id), "melt")
228
307
  ids.each { |name| self[name] }
@@ -235,9 +314,20 @@ class CAFrame
235
314
  pieces = vars.map { |name| self[name] }
236
315
  types = pieces.map(&:data_type).uniq
237
316
  unless types.size == 1
238
- raise ArgumentError,
239
- "melt: value columns differ in data type (#{vars.zip(pieces.map(&:data_type)).to_h}); " \
240
- "cast them to one type first"
317
+ # Numbers of different types meet at a type that holds every value of
318
+ # every column's type, each through a view of its own column (as_type),
319
+ # so the value column still reads and writes the columns it was made
320
+ # from, whatever is written to them later.
321
+ common = nil
322
+ if pieces.all? { |c| !c.face? && (c.numeric? || c.data_type == :boolean) }
323
+ common = CAFrame.__send__(:melt_common_type, pieces)
324
+ end
325
+ if common.nil?
326
+ raise ArgumentError,
327
+ "melt: value columns differ in data type (#{vars.zip(pieces.map(&:data_type)).to_h}) " \
328
+ "and no type holds every value of each; cast them to one type first"
329
+ end
330
+ pieces = pieces.map { |c| c.data_type == common ? c : c.as_type(common) }
241
331
  end
242
332
  shapes = pieces.map { |c| c.shape.drop(1) }.uniq
243
333
  unless shapes.size == 1
@@ -259,7 +349,15 @@ class CAFrame
259
349
  end
260
350
  n = nrow
261
351
  out[var_name] = CArray.string(Array.new(n * k) { |i| vars[i / n] })
262
- out[value_name] = CArray.meld(pieces)
352
+ begin
353
+ out[value_name] = CArray.meld(pieces)
354
+ rescue ArgumentError => e
355
+ raise unless e.message.start_with?("meld:", "CAMeld parents")
356
+ labels = vars.zip(pieces.map { |c| CArray::Inspector.type_label(c) }).to_h
357
+ raise ArgumentError,
358
+ "melt: value columns #{labels} do not meet as one column " \
359
+ "(#{e.message.delete_prefix("meld: ")}); cast them to one type first"
360
+ end
263
361
  CAFrame.new(out)
264
362
  end
265
363
 
@@ -323,7 +421,7 @@ class CAFrame
323
421
  end
324
422
  if on
325
423
  on = column_name_arg(on, "stack_rows")
326
- raise KeyError, "stack_rows: no column #{on.inspect}" unless frame.column_names.include?(on)
424
+ frame.__send__(:refuse_missing_column, on, "stack_rows") unless frame.column_names.include?(on)
327
425
  return stack_rows_on(frame, keys, on)
328
426
  end
329
427
  grouped = frame.group_by(*keys)
@@ -362,7 +460,7 @@ class CAFrame
362
460
  # given as a CArray has no name and is written "key").
363
461
  private def group_key_desc(keys, label)
364
462
  values = keys.size == 1 ? [label] : label
365
- keys.zip(values).map { |k, v| "#{k.is_a?(String) ? k : "key"}=#{v.inspect}" }.join(", ")
463
+ keys.zip(values).map { |k, v| "#{k.is_a?(String) ? k : "key"}=#{CAFrame.__send__(:key_text, v)}" }.join(", ")
366
464
  end
367
465
 
368
466
  private def stack_rows_on(frame, keys, on)