carray 3.0.3 → 3.0.4

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 (212) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +264 -0
  3. data/README.md +3 -2
  4. data/carray.gemspec +1 -1
  5. data/ext/ca_axis_descriptor.h +27 -24
  6. data/ext/ca_axis_dispatch.c +1 -6
  7. data/ext/ca_axis_group.c +27 -27
  8. data/ext/ca_binop_dispatch.c +1 -29
  9. data/ext/ca_binop_dispatch.h +0 -1
  10. data/ext/ca_categorical_iterator.c +205 -134
  11. data/ext/ca_compare.c +7 -18
  12. data/ext/ca_group_iter.c +16 -17
  13. data/ext/ca_kernel_iterator.c +1234 -1994
  14. data/ext/ca_kernel_iterator.h +391 -437
  15. data/ext/ca_monop_dispatch.c +82 -59
  16. data/ext/ca_monop_dispatch.h +1 -0
  17. data/ext/ca_obj_array.c +96 -39
  18. data/ext/ca_obj_bincmp.c +24 -21
  19. data/ext/ca_obj_binop.c +15 -26
  20. data/ext/ca_obj_bitarray.c +3 -2
  21. data/ext/ca_obj_bitfield.c +5 -6
  22. data/ext/ca_obj_block.c +18 -9
  23. data/ext/ca_obj_byte_swap.c +5 -6
  24. data/ext/ca_obj_const_string.c +173 -19
  25. data/ext/ca_obj_face.c +238 -57
  26. data/ext/ca_obj_face.h +19 -0
  27. data/ext/ca_obj_fake.c +15 -29
  28. data/ext/ca_obj_farray.c +6 -3
  29. data/ext/ca_obj_field.c +17 -5
  30. data/ext/ca_obj_fixlen_string.c +2 -3
  31. data/ext/ca_obj_grid.c +406 -132
  32. data/ext/ca_obj_meld.c +172 -34
  33. data/ext/ca_obj_moncmp.c +23 -8
  34. data/ext/ca_obj_monop.c +67 -57
  35. data/ext/ca_obj_object.c +157 -51
  36. data/ext/ca_obj_record.c +12 -7
  37. data/ext/ca_obj_reduce.c +13 -8
  38. data/ext/ca_obj_refer.c +25 -27
  39. data/ext/ca_obj_remap.c +30 -9
  40. data/ext/ca_obj_repeat.c +9 -10
  41. data/ext/ca_obj_roll.c +6 -5
  42. data/ext/ca_obj_select.c +14 -9
  43. data/ext/ca_obj_select_axis.c +15 -47
  44. data/ext/ca_obj_shift.c +11 -1
  45. data/ext/ca_obj_stack.c +179 -34
  46. data/ext/ca_obj_stride.c +162 -115
  47. data/ext/ca_obj_string.c +71 -4
  48. data/ext/ca_obj_tile.c +6 -5
  49. data/ext/ca_obj_time.c +22 -6
  50. data/ext/ca_obj_timedelta.c +22 -6
  51. data/ext/ca_obj_transpose.c +5 -3
  52. data/ext/ca_obj_triop.c +23 -32
  53. data/ext/ca_obj_window.c +190 -26
  54. data/ext/ca_sweep_engine.c +2 -2
  55. data/ext/caframe_csv_reader.c +80 -1
  56. data/ext/carray.h +181 -75
  57. data/ext/carray_access.c +184 -96
  58. data/ext/carray_address_basis.c +343 -87
  59. data/ext/carray_attribute.c +89 -6
  60. data/ext/carray_bincount.c +10 -8
  61. data/ext/carray_broadcast.c +13 -8
  62. data/ext/carray_build_flags.h +3 -0
  63. data/ext/carray_call_cfunc.c +108 -0
  64. data/ext/carray_cast.c +142 -24
  65. data/ext/carray_cast_func.rb +46 -6
  66. data/ext/carray_class.c +4 -3
  67. data/ext/carray_config.h +28 -0
  68. data/ext/carray_conversion.c +16 -7
  69. data/ext/carray_copy.c +51 -14
  70. data/ext/carray_core.c +147 -55
  71. data/ext/carray_count.c +50 -20
  72. data/ext/carray_element.c +76 -33
  73. data/ext/carray_factorize.c +118 -64
  74. data/ext/carray_generate.c +191 -50
  75. data/ext/carray_histogram.c +62 -17
  76. data/ext/carray_hold.c +12 -15
  77. data/ext/carray_index_classifier.c +388 -176
  78. data/ext/carray_internal.h +336 -29
  79. data/ext/carray_kernels_bincmp.c +4453 -0
  80. data/ext/carray_kernels_binop.c +11368 -0
  81. data/ext/carray_kernels_init.c +1734 -0
  82. data/ext/carray_kernels_moncmp.c +2104 -0
  83. data/ext/carray_kernels_monop.c +18369 -0
  84. data/ext/carray_kernels_reduce_aggregate.c +23818 -0
  85. data/ext/carray_kernels_reduce_boolean.c +406 -0
  86. data/ext/carray_kernels_reduce_cumulative.c +10086 -0
  87. data/ext/carray_kernels_reduce_extreme.c +17634 -0
  88. data/ext/carray_kernels_reduce_variance.c +3849 -0
  89. data/ext/carray_kernels_scan.c +4302 -0
  90. data/ext/carray_kernels_search.c +33829 -0
  91. data/ext/carray_kernels_sort.c +10906 -0
  92. data/ext/carray_kernels_triop.c +1864 -0
  93. data/ext/carray_key_windows.c +216 -0
  94. data/ext/carray_lazy.c +170 -111
  95. data/ext/carray_mask.c +292 -72
  96. data/ext/carray_median_percentile.c +82 -28
  97. data/ext/carray_memory_view.c +669 -561
  98. data/ext/carray_operator.c +124 -47
  99. data/ext/carray_order.c +384 -76
  100. data/ext/carray_partition.c +28 -27
  101. data/ext/carray_random.c +67 -13
  102. data/ext/carray_round.c +273 -0
  103. data/ext/carray_scatter.c +63 -38
  104. data/ext/carray_segment.c +3 -3
  105. data/ext/carray_slab.c +91 -28
  106. data/ext/carray_sort.c +35 -35
  107. data/ext/carray_struct.c +19 -18
  108. data/ext/carray_test.c +26 -5
  109. data/ext/carray_undef.c +4 -0
  110. data/ext/carray_utils.c +246 -45
  111. data/ext/mk_call_cfunc.rb +19 -2
  112. data/ext/mkkernel.rb +198 -240
  113. data/ext/ruby_carray.c +10 -4
  114. data/ext/version.h +4 -4
  115. data/lib/carray/attribute.rb +126 -22
  116. data/lib/carray/autoload_carray.rb +8 -31
  117. data/lib/carray/autoload_method_extension.rb +14 -5
  118. data/lib/carray/axis_group.rb +255 -106
  119. data/lib/carray/basics.rb +78 -10
  120. data/lib/carray/bincount_nd.rb +12 -2
  121. data/lib/carray/block_iterator.rb +126 -23
  122. data/lib/carray/boolean_reduce.rb +17 -17
  123. data/lib/carray/categorical.rb +165 -43
  124. data/lib/carray/categorical_iterator.rb +130 -27
  125. data/lib/carray/complex.rb +5 -5
  126. data/lib/carray/conditional.rb +67 -18
  127. data/lib/carray/const_string.rb +14 -5
  128. data/lib/carray/construct.rb +15 -11
  129. data/lib/carray/data_type_extension.rb +1 -0
  130. data/lib/carray/distance_limit.rb +77 -0
  131. data/lib/carray/fixlen_string.rb +7 -1
  132. data/lib/carray/frame/column_verbs.rb +70 -0
  133. data/lib/carray/frame/convert.rb +69 -0
  134. data/lib/carray/frame/csv_parser.rb +111 -17
  135. data/lib/carray/frame/describe.rb +3 -2
  136. data/lib/carray/frame/frame.rb +246 -21
  137. data/lib/carray/frame/group.rb +510 -95
  138. data/lib/carray/frame/io.rb +115 -28
  139. data/lib/carray/frame/join.rb +312 -51
  140. data/lib/carray/frame/records.rb +83 -7
  141. data/lib/carray/frame/reshape.rb +42 -35
  142. data/lib/carray/frame/sort.rb +7 -19
  143. data/lib/carray/frame/verbs.rb +188 -48
  144. data/lib/carray/frame/windows.rb +117 -0
  145. data/lib/carray/frame.rb +2 -0
  146. data/lib/carray/fuse_source.rb +11 -4
  147. data/lib/carray/fusion.rb +40 -16
  148. data/lib/carray/histogram.rb +6 -1
  149. data/lib/carray/inspect.rb +31 -8
  150. data/lib/carray/iterator.rb +85 -7
  151. data/lib/carray/key_windows.rb +620 -0
  152. data/lib/carray/lazy.rb +182 -183
  153. data/lib/carray/mask_gap_fill.rb +63 -57
  154. data/lib/carray/meld_reduce.rb +12 -14
  155. data/lib/carray/methods/bin.rb +26 -18
  156. data/lib/carray/methods/bincount.rb +16 -0
  157. data/lib/carray/methods/bit_string.rb +1 -1
  158. data/lib/carray/methods/choose.rb +16 -3
  159. data/lib/carray/methods/composition.rb +3 -1
  160. data/lib/carray/methods/gather_nd.rb +14 -5
  161. data/lib/carray/methods/insert_block.rb +2 -2
  162. data/lib/carray/methods/is_between.rb +59 -0
  163. data/lib/carray/methods/is_in.rb +53 -36
  164. data/lib/carray/methods/join.rb +1 -6
  165. data/lib/carray/methods/lag.rb +49 -0
  166. data/lib/carray/methods/locate_addr.rb +47 -51
  167. data/lib/carray/methods/mode.rb +1 -1
  168. data/lib/carray/methods/nunique.rb +11 -6
  169. data/lib/carray/methods/resize.rb +3 -3
  170. data/lib/carray/methods/value_counts.rb +4 -11
  171. data/lib/carray/record_order.rb +3 -3
  172. data/lib/carray/rng.rb +3 -0
  173. data/lib/carray/runtime.rb +53 -8
  174. data/lib/carray/segment_iterator.rb +313 -82
  175. data/lib/carray/serialize.rb +24 -10
  176. data/lib/carray/slab_iterator.rb +50 -0
  177. data/lib/carray/string.rb +105 -5
  178. data/lib/carray/string_operation_extension.rb +8 -1
  179. data/lib/carray/struct.rb +9 -21
  180. data/lib/carray/struct_builder.rb +19 -8
  181. data/lib/carray/time.rb +726 -104
  182. data/lib/carray/window_iterator.rb +122 -16
  183. data/lib/carray.rb +7 -0
  184. data/yard-stubs/ca_obj_bitfield.rb +1 -1
  185. data/yard-stubs/ca_obj_field.rb +4 -0
  186. data/yard-stubs/ca_obj_grid.rb +21 -10
  187. data/yard-stubs/ca_obj_refer.rb +2 -1
  188. data/yard-stubs/ca_obj_roll.rb +2 -2
  189. data/yard-stubs/ca_obj_shift.rb +5 -1
  190. data/yard-stubs/ca_obj_tile.rb +1 -1
  191. data/yard-stubs/ca_obj_window.rb +8 -3
  192. data/yard-stubs/carray_access.rb +6 -1
  193. data/yard-stubs/carray_attribute.rb +0 -5
  194. data/yard-stubs/carray_cast.rb +10 -0
  195. data/yard-stubs/carray_conversion.rb +2 -1
  196. data/yard-stubs/carray_copy.rb +4 -2
  197. data/yard-stubs/carray_count.rb +4 -4
  198. data/yard-stubs/carray_element.rb +10 -4
  199. data/yard-stubs/carray_generate.rb +21 -1
  200. data/yard-stubs/carray_mask.rb +26 -2
  201. data/yard-stubs/carray_math.rb +27 -1
  202. data/yard-stubs/carray_median_percentile.rb +5 -2
  203. data/yard-stubs/carray_memory_view.rb +40 -23
  204. data/yard-stubs/carray_order.rb +29 -18
  205. data/yard-stubs/carray_random.rb +13 -4
  206. data/yard-stubs/carray_scatter.rb +14 -9
  207. data/yard-stubs/carray_slab.rb +9 -2
  208. data/yard-stubs/carray_sort.rb +6 -5
  209. data/yard-stubs/carray_test.rb +5 -3
  210. metadata +25 -3
  211. data/lib/carray/arrow_tensor.rb +0 -401
  212. data/lib/carray/table.rb +0 -108
@@ -9,12 +9,72 @@
9
9
  class CAFrame
10
10
  # Group rows by one or more keys. Each key is a column name (String) or an
11
11
  # external length-N CArray. Returns a GroupedFrame.
12
+ #
13
+ # With one key, a summary's index is the key's value of each group. With
14
+ # several, each key is a column of a summary, holding its part of each
15
+ # group's key, and the summary has no index; a CArray key among several
16
+ # names its column by its position, "key0", "key1", ....
12
17
  def group_by(*keys)
13
18
  raise ArgumentError, "group_by needs at least one key" if keys.empty?
19
+ CAFrame.__send__(:refuse_repeated_names, keys.grep(String), "group_by")
14
20
  cat = grouping_categorical(keys)
15
- axis = keys.size == 1 && keys.first.is_a?(String) ? keys.first : "group"
16
- key = keys.size == 1 ? key_column(keys.first) : nil
17
- GroupedFrame.new(self, cat, axis, keys.grep(String), key: key)
21
+ if keys.size == 1
22
+ axis = keys.first.is_a?(String) ? keys.first : "group"
23
+ return GroupedFrame.new(self, cat, axis, keys.grep(String), key: key_column(keys.first))
24
+ end
25
+ names = keys.each_with_index.map { |k, i| k.is_a?(String) ? k : "key#{i}" }
26
+ CAFrame.__send__(:refuse_repeated_names, names, "group_by")
27
+ GroupedFrame.new(self, cat, "group", keys.grep(String),
28
+ key_columns: names.zip(keys.map { |k| key_column(k) }).to_h)
29
+ end
30
+
31
+ # Whether each row repeats another row: a boolean column, true for the rows
32
+ # whose values in the named columns (every column when none are named)
33
+ # appear on more than one row, except the one +except:+ leaves out --
34
+ #
35
+ # except: :first every occurrence but the first (the default)
36
+ # except: :last every occurrence but the last
37
+ # except: :none every occurrence
38
+ #
39
+ # so +df[df.is_duplicate.not]+ keeps one row of each, and
40
+ # +is_duplicate(except: :none).not+ is the rows that appear only once.
41
+ # Values compare as group_by compares keys (NaN is one value, -0.0 is 0.0),
42
+ # and a row with a masked cell in those columns is never a duplicate, as a
43
+ # masked key is in no group. The index is compared only when named
44
+ # (by the row axis name, as group_by takes it).
45
+ #
46
+ # df[df.is_duplicate.not] # the rows without repeats
47
+ # df.is_duplicate("station", "time") # repeats of the pair
48
+ # df.is_duplicate(except: :none).not # the rows that appear once
49
+ #
50
+ # @param names [Array<String>] the columns to compare; default every column.
51
+ # @param except [Symbol] the occurrence left unmarked: :first, :last or :none.
52
+ # @return [CArray] boolean, one value per row.
53
+ # @raise [KeyError] for a name that is no column.
54
+ # @raise [ArgumentError] when a compared column is N-D, there is no column
55
+ # to compare, or +except:+ is not one of the three.
56
+ def is_duplicate(*names, except: :first)
57
+ unless %i[first last none].include?(except)
58
+ raise ArgumentError,
59
+ "is_duplicate: except: must be :first, :last or :none (got #{except.inspect})"
60
+ end
61
+ names = column_keys(names, "is_duplicate")
62
+ names = column_names if names.empty?
63
+ raise ArgumentError, "is_duplicate: the frame has no column to compare" if names.empty?
64
+ cols = names.map { |n| key_column(n, "is_duplicate") }
65
+ cat = CACategorical.send(:from_keys, cols)
66
+ codes = cat.codes
67
+ out =
68
+ case except
69
+ when :first then codes.mask_duplicates.is_masked
70
+ when :last then codes.flip(0).mask_duplicates.is_masked.flip(0).copy
71
+ when :none
72
+ index = codes.value.int64
73
+ index[codes.is_masked] = 0 if codes.has_mask?
74
+ sizes = cat.category_sizes
75
+ sizes.elements > 0 ? sizes[index].gt(1) : CArray.boolean(nrow) { false }
76
+ end
77
+ codes.has_mask? ? out & codes.is_not_masked : out
18
78
  end
19
79
 
20
80
  # Group rows into time bins of length +unit+ along the time column (or the
@@ -38,17 +98,28 @@ class CAFrame
38
98
  # as an empty reduction does: UNDEF for +mean+, 0 for +count+ and +sum+.
39
99
  # A row whose time is masked belongs to no bin.
40
100
  #
101
+ # +by:+ (a column name or an Array of them) bins each group of rows on its
102
+ # own: a group is the rows sharing the +by:+ values and a bin. The result
103
+ # then has no index: the +by:+ columns and the bin times (named +name+)
104
+ # are its first columns, the groups in the order their +by:+ values first
105
+ # appear and the bins of each in time order. With +fill: true+ every group
106
+ # has every bin from the first to the last of the whole frame. A row whose
107
+ # +by:+ value is masked belongs to no group.
108
+ #
109
+ # df.resample("date", "1 week", by: "shop").sum
110
+ #
41
111
  # @param name [String] the time column, or the index's axis name.
42
112
  # @param unit [String, Symbol, CATime::Resolution] the bin length.
43
113
  # @param origin [nil, Time, String, CATime::Element] where bins start.
44
114
  # @param label [:left, :right] which end of a bin names it and is closed.
45
115
  # @param fill [Boolean] whether bins with no rows are rows of the result.
116
+ # @param by [nil, String, Array<String>] columns whose groups are binned apart.
46
117
  # @return [GroupedFrame]
47
118
  # @raise [ArgumentError] when the column is not a CATime, or +label:+ is
48
- # neither :left nor :right.
49
- def resample(name, unit, origin: nil, label: :left, fill: false)
50
- name = name.to_s
51
- time = column_or_index(name)
119
+ # neither :left nor :right, or +by:+ names the time column.
120
+ def resample(name, unit, origin: nil, label: :left, fill: false, by: nil)
121
+ name = column_key(name, "resample")
122
+ time = key_column(name, "resample")
52
123
  unless time.is_a?(CATime)
53
124
  raise ArgumentError, "resample: #{name.inspect} is not a time column (got #{time.class})"
54
125
  end
@@ -59,18 +130,62 @@ class CAFrame
59
130
  else
60
131
  raise ArgumentError, "resample: label: must be :left or :right (got #{label.inspect})"
61
132
  end
133
+ # key-labels: the bins are the index, given the column's attributes below.
62
134
  grid = fill && bins.count_not_masked > 0 ? resample_grid(bins, unit) : bins.unique(sort: true)
135
+ return resample_by(name, time, bins, grid, by, fill) unless by.nil?
63
136
  cat = CACategorical.from_codes(bins.locate_addr(grid), grid.to_a)
64
- GroupedFrame.new(self, cat, name, @columns.key?(name) ? [name] : [], index: grid)
137
+ GroupedFrame.new(self, cat, name, @columns.key?(name) ? [name] : [],
138
+ index: CAFrame.__send__(:key_labels, time, grid))
65
139
  end
66
140
 
67
- # Every bin from the first occupied one to the last. A fixed-length bin
68
- # steps from the first bin, so an origin's phase is kept; a month or a year
69
- # cannot be stepped on a finer grid and is laid on its own unit, where
70
- # bins start on the calendar boundary anyway.
141
+ # resample with by:. A group is a (by values, bin) pair, coded as
142
+ # group * bins + bin, so the codes run through the groups in the order their
143
+ # by values first appear and through each group's bins in time order.
144
+ private def resample_by(name, time, bins, grid, by, fill)
145
+ by_names = column_keys(Array(by), "resample")
146
+ raise ArgumentError, "resample: by: names no column" if by_names.empty?
147
+ if by_names.include?(name)
148
+ raise ArgumentError, "resample: by: names the time column #{name.inspect}"
149
+ end
150
+ by_cols = by_names.map { |n| key_column(n, "resample") }
151
+ gcat = CACategorical.send(:from_keys, by_cols)
152
+ ng = gcat.labels.size
153
+ nb = grid.elements
154
+ comb = gcat.codes.int64 * nb + bins.locate_addr(grid).int64
155
+ # key-labels: the used (group, bin) codes, not labels; those go through key_labels below
156
+ occupied = fill ? CArray.int64(ng * nb).seq! : comb.unique(sort: true)
157
+ codes = fill ? comb : comb.locate_addr(occupied)
158
+ g_of = nb > 0 ? occupied / nb : occupied
159
+ b_of = nb > 0 ? occupied % nb : occupied
160
+ # Each group's by values, from its first row.
161
+ order = gcat.sort_addr
162
+ first = order[CArray.segment_offsets(lengths: gcat.category_sizes)[0...ng]]
163
+ columns = {}
164
+ by_names.zip(by_cols).each do |n, col|
165
+ columns[n] = CAFrame.__send__(:key_labels, col, col.project(first))[g_of].copy
166
+ end
167
+ columns[name] = CAFrame.__send__(:key_labels, time, grid[b_of].copy)
168
+ glabels = gcat.labels
169
+ blabels = grid.to_a
170
+ labels = occupied.to_a.map do |c|
171
+ g, b = c.divmod(nb)
172
+ parts = by_names.size == 1 ? [glabels[g]] : glabels[g]
173
+ parts + [blabels[b]]
174
+ end
175
+ cat = CACategorical.from_codes(codes, labels)
176
+ key_names = by_names + (@columns.key?(name) ? [name] : [])
177
+ GroupedFrame.new(self, cat, "group", key_names, label_columns: columns)
178
+ end
179
+
180
+ # Every bin from the first occupied one to the last, stepped from the
181
+ # first bin so an origin's phase (or label: :right) is kept. A month or a
182
+ # year cannot be stepped on a finer grid, so it is stepped on the one-month
183
+ # or one-year grid and then given the bins' unit, as the labels without
184
+ # fill: are.
71
185
  private def resample_grid(bins, unit)
72
- if %i[Y M].include?(CATime::Resolution.parse(unit).base)
73
- CArray.time_range(bins.min, bins.max, unit: unit)
186
+ base = CATime::Resolution.parse(unit).base
187
+ if %i[Y M].include?(base)
188
+ CArray.time_range(bins.min, bins.max, unit: base, step: unit).to_unit(bins.unit)
74
189
  else
75
190
  CArray.time_range(bins.min, bins.max, unit: bins.unit, step: unit)
76
191
  end
@@ -80,50 +195,32 @@ class CAFrame
80
195
  # and elsewhere; already provided by the core (attr_reader :nrow).
81
196
 
82
197
  private def grouping_categorical(keys)
83
- cols = keys.map { |k| key_column(k) }
84
- if cols.size == 1
85
- cols.first.categorize
86
- else
87
- composite_categorical(cols)
88
- end
198
+ CACategorical.send(:from_keys, keys.map { |k| key_column(k) })
89
199
  end
90
200
 
91
- # A composite key. Each column is categorized on its own, so a component
92
- # compares exactly as a single key does (NaN is one value, -0.0 is 0.0, a
93
- # masked cell matches nothing); a row's group is then the tuple of its
94
- # component codes, and a group's label the tuple of the component labels.
95
- # One masked component leaves the row in no group, as a masked single key.
96
- private def composite_categorical(cols)
97
- cats = cols.map(&:categorize)
98
- sizes = cats.map { |c| c.labels.size }
99
- tuple = if sizes.inject(1, :*) <= 2**62
100
- cats.drop(1).inject(cats[0].codes.int64) { |acc, c| acc * c.labels.size + c.codes.int64 }
101
- else
102
- codes = cats.map(&:codes)
103
- t = CArray.object(nrow) { |i| codes.map { |c| c[i] } }
104
- nrow.times { |i| t[i] = UNDEF if t[i].any? { |x| UNDEF.equal?(x) } }
105
- t
106
- end
107
- rows = tuple.categorize
108
- labels = rows.labels.map do |code|
109
- parts = code.is_a?(Array) ? code : sizes.reverse.map { |n| code, d = code.divmod(n); d }.reverse
110
- parts.each_with_index.map { |d, j| cats[j].labels[d] }
111
- end
112
- CACategorical.from_codes(rows.codes, labels)
113
- end
114
-
115
- # The column a group key names, checked: +verb+ is the method the caller
116
- # called, for the messages.
201
+ # The column a key names, checked -- the one reading of a key every verb
202
+ # that takes one goes through (group_by, is_duplicate, sort_by_key, join,
203
+ # join_asof, align, pivot, resample, windows): a column of that name, or
204
+ # the index by the row axis name; or a CArray of one value per row. It
205
+ # gives each row one value. +verb+ is the method the caller called, for
206
+ # the messages.
117
207
  private def key_column(key, verb = "group_by")
118
208
  col = case key
119
209
  when String
120
- @columns.fetch(key) { raise KeyError, "#{verb}: no column #{key.inspect}" }
210
+ # The index names the rows, so it is a key as a column is, by the
211
+ # row axis name, as resample and pivot take it.
212
+ @columns.fetch(key) do
213
+ next @index if @index && @axis_name == key
214
+ raise KeyError, "#{verb}: no column #{key.inspect}"
215
+ end
121
216
  when CArray
122
217
  unless key.shape[0] == nrow
123
218
  raise ArgumentError,
124
219
  "#{verb}: the key has #{key.shape[0]} values for #{nrow} rows"
125
220
  end
126
221
  key
222
+ when Symbol
223
+ column_key(key, verb)
127
224
  else
128
225
  raise ArgumentError, "#{verb}: a group key is a column name or a CArray (got #{key.class})"
129
226
  end
@@ -133,7 +230,7 @@ class CAFrame
133
230
  name = key.is_a?(String) ? "#{key.inspect} " : ""
134
231
  raise ArgumentError,
135
232
  "#{verb}: the key #{name}has shape #{col.shape.inspect}, not one value per row; " \
136
- "group by one of its components (e.g. df[name][nil, 0])"
233
+ "use one of its components (e.g. df[name][nil, 0])"
137
234
  end
138
235
  col
139
236
  end
@@ -147,6 +244,7 @@ end
147
244
  # aggregate -> declarative per-column reductions into a new frame
148
245
  # table { |g| }-> cross-column Ruby escape, g is a per-group view-frame
149
246
  class GroupedFrame
247
+ include CAFrame::ColumnVerbs
150
248
  # +key_names+ are the frame columns the grouping was keyed on. They become
151
249
  # the result's index, so the reduction shortcuts must not also return them as
152
250
  # reduced columns; an external CArray key contributes no name.
@@ -154,17 +252,27 @@ class GroupedFrame
154
252
  # The result's index is +index:+ when given (one entry per group, in code
155
253
  # order); otherwise, for a single +key:+, the key's value at each group's
156
254
  # first row, so it keeps the key's data type and Face; otherwise an object
157
- # array of the labels (a composite key's tuples).
255
+ # array of the labels.
256
+ #
257
+ # With several keys the result has no index: +key_columns:+ (name => the
258
+ # key, one value per row) become its first columns, each holding the key's
259
+ # value at each group's first row; +label_columns:+ (name => one value per
260
+ # group, in code order) give them directly, for groups that may have no
261
+ # rows (resample with fill: true).
158
262
  #
159
263
  # The grouping and the index are taken here, so a later change to the key
160
264
  # does not rename the groups; the values are read when a reduction is.
161
- def initialize(frame, cat, axis_name, key_names = [], index: nil, key: nil)
265
+ def initialize(frame, cat, axis_name, key_names = [], index: nil, key: nil,
266
+ key_columns: nil, label_columns: nil)
162
267
  @frame = frame
163
268
  @cat = cat
164
269
  @axis_name = axis_name
165
270
  @key_names = key_names
166
271
  @labels = cat.labels # group values, in code order
167
- @index = index || (key && key.project(group_perm[group_bounds[0...ngroup]]))
272
+ @index = index ||
273
+ (key && CAFrame.__send__(:key_labels, key, key.project(first_rows)))
274
+ @label_columns = label_columns ||
275
+ key_columns&.transform_values { |col| CAFrame.__send__(:key_labels, col, col.project(first_rows)) }
168
276
  end
169
277
 
170
278
  # Number of groups.
@@ -179,6 +287,7 @@ class GroupedFrame
179
287
 
180
288
  # Raw exposure: the CArray group iterator for one column (memo §11.6).
181
289
  def [](name)
290
+ refuse_changed_rows("[]")
182
291
  @frame[name].group_by_category(@cat)
183
292
  end
184
293
 
@@ -188,10 +297,20 @@ class GroupedFrame
188
297
  # with the group's column slice). A Symbol reduction takes its arguments
189
298
  # after it, as in a call: +["temp", :percentile, 90.0]+, and its keywords
190
299
  # last: +["temp", :mean, min_count: 6]+.
191
- def aggregate(spec)
300
+ #
301
+ # With +keep_rows: true+ the rows are not collapsed: each row of the frame
302
+ # gets the result of its own group, so the result has the frame's rows and
303
+ # index, and a row whose key is masked (in no group) is UNDEF. The same
304
+ # keyword works for +table+ and the reductions below.
305
+ #
306
+ # df.group_by("station").aggregate("temp_mean" => ["temp", :mean], keep_rows: true)
307
+ def aggregate(spec = nil, keep_rows: false, **named)
308
+ refuse_changed_rows("aggregate")
309
+ spec = (spec || {}).merge(named)
192
310
  cols = {}
193
311
  spec.each do |out_name, (in_name, reduction, *args)|
194
- out = out_name.to_s
312
+ out = @frame.__send__(:column_name_arg, out_name, "aggregate")
313
+ @frame.__send__(:column_key, in_name, "aggregate")
195
314
  options = args.last.is_a?(Hash) ? args.pop : {}
196
315
  cols[out] =
197
316
  case reduction
@@ -207,29 +326,34 @@ class GroupedFrame
207
326
  "reduction must be a Symbol or Proc (got #{reduction.class})"
208
327
  end
209
328
  end
210
- CAFrame.new(cols, axis_name: @axis_name, index: label_index)
329
+ result_frame(cols, keep_rows)
211
330
  end
212
331
 
213
332
  # Cross-column Ruby escape (memo §11.6). The block receives a per-group
214
333
  # view-frame and returns a Hash of output-name => value; the values are
215
- # collected column-wise across groups into a new frame.
216
- def table
217
- collected = {}
218
- order = nil
334
+ # collected column-wise across groups into a new frame. +keep_rows: true+
335
+ # gives each row its group's values, as for +aggregate+.
336
+ #
337
+ # The columns are the names any group's Hash has, in the order they
338
+ # first appear; a group whose Hash lacks a name is UNDEF there, as
339
+ # +from_records+ reads a record that lacks a key.
340
+ def table(keep_rows: false)
341
+ refuse_changed_rows("table")
342
+ outs = []
219
343
  each_group_frame do |g|
220
344
  out = yield(g)
221
345
  unless out.is_a?(Hash)
222
346
  raise ArgumentError, "table block must return a Hash (got #{out.class})"
223
347
  end
224
- order ||= out.keys.map(&:to_s)
225
- out.each { |k, v| (collected[k.to_s] ||= []) << v }
348
+ out.each_key { |k| @frame.__send__(:column_name_arg, k, "table") }
349
+ outs << out
226
350
  end
351
+ names = CAFrame.__send__(:record_key_union, outs)
227
352
  cols = {}
228
- (order || []).each do |name|
229
- vals = collected[name]
230
- cols[name] = CArray.object(vals.size) { |i| vals[i] }
353
+ names.each do |name|
354
+ cols[name] = column_of_values(outs.map { |out| out.fetch(name, nil) })
231
355
  end
232
- CAFrame.new(cols, axis_name: @axis_name, index: label_index)
356
+ result_frame(cols, keep_rows)
233
357
  end
234
358
 
235
359
  # Convenience reductions over every column that defines the reduction. A
@@ -240,28 +364,247 @@ class GroupedFrame
240
364
  # its trailing shape: a (N, L) column gives (groups, L). Each
241
365
  # takes +min_count:+ and +fill_value:+ as a core reduction does: a group
242
366
  # with fewer than min_count present values is UNDEF, and fill_value fills
243
- # the UNDEF cells.
367
+ # the UNDEF cells. +keep_rows: true+ gives each row its group's value
368
+ # instead of one row per group, as for +aggregate+.
369
+ #
370
+ # Given column names, they reduce those columns only and return them as
371
+ # +df[...]+ does: one name gives the CArray, several an Array of them.
244
372
  #
245
- # @!method sum(min_count: nil, fill_value: nil)
373
+ # grp.mean # a frame, one row per group
374
+ # grp.mean("temp") # CArray, one value per group
375
+ # df["temp"] - grp.mean("temp", keep_rows: true) # anomaly from the group mean
376
+ #
377
+ # @!method sum(*names, min_count: nil, fill_value: nil, keep_rows: false)
246
378
  # Returns a frame of the per-group sum of every column whose type has a
247
379
  # sum, an N-D one per group along the rows. Other columns are left out.
248
- # @return [CAFrame] one row per group, indexed by the group labels.
249
- # @!method mean(min_count: nil, fill_value: nil)
380
+ # @return [CAFrame, CArray, Array<CArray>] a frame with one row per
381
+ # group, indexed by the group labels, or with keep_rows: true the
382
+ # frame's rows and index; given names, the CArray (one) or the Array of
383
+ # them (several).
384
+ # @!method mean(*names, min_count: nil, fill_value: nil, keep_rows: false)
250
385
  # Returns a frame of the per-group mean of every column whose type has
251
386
  # a mean, as {#sum} does.
252
387
  # @return [CAFrame] one row per group.
253
- # @!method min(min_count: nil, fill_value: nil)
388
+ # @!method min(*names, min_count: nil, fill_value: nil, keep_rows: false)
254
389
  # Returns a frame of the per-group minimum of every column whose type has
255
390
  # a minimum, as {#sum} does.
256
391
  # @return [CAFrame] one row per group.
257
- # @!method max(min_count: nil, fill_value: nil)
392
+ # @!method max(*names, min_count: nil, fill_value: nil, keep_rows: false)
258
393
  # Returns a frame of the per-group maximum of every column whose type has
259
394
  # a maximum, as {#sum} does.
260
395
  # @return [CAFrame] one row per group.
261
- [:sum, :mean, :min, :max].each do |red|
262
- define_method(red) do |min_count: nil, fill_value: nil|
263
- reduce_columns(red, min_count: min_count, fill_value: fill_value)
396
+ # @!method prod(*names, min_count: nil, fill_value: nil, keep_rows: false)
397
+ # Returns the per-group product, as {#sum} does.
398
+ # @return [CAFrame] one row per group.
399
+ # @!method accumulate(*names, min_count: nil, fill_value: nil, keep_rows: false)
400
+ # Returns the per-group sum kept in each column's own data type, as
401
+ # +CArray#accumulate+, as {#sum} does.
402
+ # @return [CAFrame] one row per group.
403
+ # @!method median(*names, min_count: nil, fill_value: nil, keep_rows: false)
404
+ # Returns the per-group median, as {#sum} does.
405
+ # @return [CAFrame] one row per group.
406
+ # @!method variance(*names, min_count: nil, fill_value: nil, keep_rows: false)
407
+ # Returns the per-group sample variance (divisor n - 1), as {#sum} does.
408
+ # @return [CAFrame] one row per group.
409
+ # @!method stddev(*names, min_count: nil, fill_value: nil, keep_rows: false)
410
+ # Returns the per-group sample standard deviation, as {#sum} does.
411
+ # @return [CAFrame] one row per group.
412
+ # @!method variancep(*names, min_count: nil, fill_value: nil, keep_rows: false)
413
+ # Returns the per-group population variance (divisor n), as {#sum} does.
414
+ # @return [CAFrame] one row per group.
415
+ # @!method stddevp(*names, min_count: nil, fill_value: nil, keep_rows: false)
416
+ # Returns the per-group population standard deviation, as {#sum} does.
417
+ # @return [CAFrame] one row per group.
418
+ CArray.send(:define_named_methods, self,
419
+ [:sum, :mean, :min, :max, :prod, :accumulate, :median,
420
+ :variance, :stddev, :variancep, :stddevp], :group_reduction)
421
+
422
+ private def group_reduction (red, *names, min_count: nil, fill_value: nil, keep_rows: false)
423
+ refuse_changed_rows(red)
424
+ reduce_columns(red, names, keep_rows, min_count: min_count, fill_value: fill_value)
425
+ end
426
+
427
+ # The same convenience for the reductions that take no min_count: or
428
+ # fill_value:, as the core ones take none: a value of the group (first,
429
+ # last), a count (nunique, count) or a boolean fold (all, any).
430
+ #
431
+ # @!method first(*names, keep_rows: false)
432
+ # Returns each group's first present value in row order, UNDEF for a
433
+ # group with none, as {#sum} returns its sums.
434
+ # @return [CAFrame] one row per group.
435
+ # @!method last(*names, keep_rows: false)
436
+ # Returns each group's last present value in row order.
437
+ # @return [CAFrame] one row per group.
438
+ # @!method nunique(*names, keep_rows: false)
439
+ # Returns each group's number of distinct present values (int64).
440
+ # @return [CAFrame] one row per group.
441
+ # @!method count(*names, keep_rows: false)
442
+ # Returns each group's number of present values (int64), a masked cell
443
+ # left out.
444
+ # @return [CAFrame] one row per group.
445
+ # @!method all(*names, keep_rows: false)
446
+ # Returns whether every present value of the group is true, for the
447
+ # boolean columns.
448
+ # @return [CAFrame] one row per group.
449
+ # @!method any(*names, keep_rows: false)
450
+ # Returns whether any present value of the group is true, for the
451
+ # boolean columns.
452
+ # @return [CAFrame] one row per group.
453
+ CArray.send(:define_named_methods, self,
454
+ [:first, :last, :nunique, :count, :all, :any], :group_value)
455
+
456
+ private def group_value (red, *names, keep_rows: false)
457
+ refuse_changed_rows(red)
458
+ reduce_columns(red, names, keep_rows)
459
+ end
460
+
461
+ # Values computed within each group and kept on the frame's rows, in row
462
+ # order: the value some rows back in the same group, a rank among the
463
+ # group's rows, a running statistic. A row in no group is UNDEF. Without
464
+ # names they give a frame of every column whose type has the operation
465
+ # (the key columns left out), on the frame's rows and index; given names,
466
+ # the CArray (one) or the Array of them (several), as +df[...]+ returns
467
+ # columns. An N-D column runs along the rows.
468
+ #
469
+ # df["dtemp"] = df["temp"] - grp.lag("temp") # change since the station's previous row
470
+ # grp.order("temp", descending: true) # rank within the station
471
+ # grp.cumsum("rain") # running total per station
472
+ #
473
+ # "Previous" is the previous row of the frame: sort the frame first
474
+ # (+sort_by_key("time")+) when its rows are not in time order.
475
+ #
476
+ # @!method lag(*names, n: 1)
477
+ # Returns each row's value +n+ rows back in its own group, UNDEF where
478
+ # the group has none, as +CArray#lag+; a negative +n+ looks ahead.
479
+ # @return [CAFrame, CArray, Array<CArray>]
480
+ # @!method order(*names, descending: false, method: :ordinal, kind: :quick)
481
+ # Returns each row's rank among its group's rows (int64, 0 the
482
+ # smallest), as +CArray#order+ ranks them.
483
+ # @return [CAFrame, CArray, Array<CArray>]
484
+ # @!method cumsum(*names)
485
+ # Returns the running sum within each group, as +CArray#cumsum+.
486
+ # @return [CAFrame, CArray, Array<CArray>]
487
+ # @!method cumprod(*names)
488
+ # Returns the running product within each group.
489
+ # @return [CAFrame, CArray, Array<CArray>]
490
+ # @!method cummax(*names)
491
+ # Returns the running maximum within each group.
492
+ # @return [CAFrame, CArray, Array<CArray>]
493
+ # @!method cummin(*names)
494
+ # Returns the running minimum within each group.
495
+ # @return [CAFrame, CArray, Array<CArray>]
496
+ # @!method cumcount(*names)
497
+ # Returns the running count of present values within each group (int64).
498
+ # @return [CAFrame, CArray, Array<CArray>]
499
+ def lag (*names, n: 1)
500
+ transform_columns(:lag, names, [n], {})
501
+ end
502
+
503
+ def order (*names, descending: false, method: :ordinal, kind: :quick)
504
+ transform_columns(:order, names, [], { descending: descending, method: method, kind: kind })
505
+ end
506
+
507
+ CArray.send(:define_named_methods, self,
508
+ [:cumsum, :cumprod, :cummax, :cummin, :cumcount], :group_scan)
509
+
510
+ private def group_scan (op, *names)
511
+ transform_columns(op, names, [], {})
512
+ end
513
+
514
+ # Fill the masked cells of a column from the rows of the same group, in
515
+ # place, as +CAFrame#fill+ does for the whole column: +:ffill+ carries the
516
+ # group's last present value forward in row order, +:bfill+ its next one
517
+ # back. A fill never reaches across into another group, so a cell with
518
+ # nothing to carry in its group stays masked, and a row whose key is
519
+ # masked (in no group) is left as it is. A constant fills every masked
520
+ # cell, as +CAFrame#fill+ does. Returns self.
521
+ #
522
+ # df.group_by("station").fill("temp", :ffill)
523
+ #
524
+ # Sort the frame first (+sort_by_key("time")+) when its rows are not in
525
+ # time order.
526
+ #
527
+ # @param name [String] the column.
528
+ # @param method_or_value [Symbol, Object] +:ffill+, +:bfill+, or a constant.
529
+ # @return [GroupedFrame] self
530
+ # @raise [ArgumentError] for +:linear+, which within groups is not
531
+ # provided, or another Symbol.
532
+ def fill (name, method_or_value)
533
+ refuse_changed_rows("fill")
534
+ case method_or_value
535
+ when :ffill, :bfill
536
+ @frame.__send__(:refuse_if_frozen)
537
+ key = @frame.__send__(:column_key, name, "fill")
538
+ col = @frame[key]
539
+ # A row in no group is UNDEF in the fill, so writing it changes nothing.
540
+ held = group_transform(col, :strip_mask, [], { method: method_or_value })
541
+ target = col.is_masked
542
+ col[target] = held[target] if target.any
543
+ when :linear
544
+ raise ArgumentError,
545
+ "fill(#{name.inspect}, :linear): an interpolation within each group " \
546
+ "is not provided; use :ffill or :bfill, or interpolate one group at a " \
547
+ "time with CAFrame#fill"
548
+ when Symbol
549
+ raise ArgumentError,
550
+ "fill: unknown method #{method_or_value.inspect} " \
551
+ "(:ffill | :bfill, or a constant fill value)"
552
+ else
553
+ @frame.fill(name, method_or_value)
264
554
  end
555
+ self
556
+ end
557
+
558
+ # Keep the rows of the groups the block chooses. The block receives the
559
+ # grouped frame and returns a boolean CArray with one value per group,
560
+ # built from the group reductions, as +CAFrame#filter+'s block returns one
561
+ # per row:
562
+ #
563
+ # grp.filter { |g| g["temp"].count_not_masked >= 20 } # stations with 20 readings
564
+ # grp.filter { |g| g.mean("temp") > 15.0 }
565
+ #
566
+ # The rows of a chosen group are kept in the frame's order, as a sub-frame
567
+ # sharing the frame's columns. A group whose value is UNDEF is
568
+ # undetermined, as is a row whose key is masked (it belongs to no group):
569
+ # such rows are dropped, or with +keep_masked: true+ carried with their
570
+ # cells masked, as +CAFrame#filter+ does.
571
+ #
572
+ # @param keep_masked [Boolean] carry the undetermined rows forward masked.
573
+ # @yieldparam grouped [GroupedFrame] self.
574
+ # @yieldreturn [CArray] boolean, one value per group.
575
+ # @return [CAFrame]
576
+ # @raise [ArgumentError] when the block does not return a boolean CArray of
577
+ # shape [ngroup].
578
+ def filter (keep_masked: false)
579
+ refuse_changed_rows("filter")
580
+ chosen = yield(self)
581
+ unless chosen.is_a?(CArray) && chosen.data_type == :boolean
582
+ raise ArgumentError,
583
+ "filter block must return a boolean CArray (got #{chosen.is_a?(CArray) ? "a #{CArray::Inspector.type_label(chosen)} CArray" : chosen.class})"
584
+ end
585
+ unless chosen.shape == [ngroup]
586
+ raise ArgumentError,
587
+ "filter mask has shape #{chosen.shape.inspect}, " \
588
+ "expected [#{ngroup}] (one value per group)"
589
+ end
590
+ rows = spread_to_rows(chosen)
591
+ @frame.filter(keep_masked: keep_masked) { rows }
592
+ end
593
+
594
+ # Returns the grouped rows as a frame: the frame the grouping was made
595
+ # from, its rows, columns and index, as a new frame sharing its columns.
596
+ # Nothing is copied, so a write to a cell reaches the grouped frame's
597
+ # rows; adding or dropping a column changes the new frame only.
598
+ #
599
+ # def warm_stations (grp)
600
+ # grp.filter { |g| g.mean("temp") > 15.0 } # the rows of some groups
601
+ # end
602
+ # grp.to_frame # all of its rows
603
+ #
604
+ # @return [CAFrame]
605
+ def to_frame
606
+ refuse_changed_rows("to_frame")
607
+ @frame.__send__(:rebuild, @frame.column_names.to_h { |name| [name, @frame[name]] })
265
608
  end
266
609
 
267
610
  # @return [String]
@@ -269,22 +612,71 @@ class GroupedFrame
269
612
  "#<GroupedFrame ngroup=#{ngroup} by=#{@axis_name.inspect}>"
270
613
  end
271
614
 
615
+ # A within-group transform of the named columns, or of every column whose
616
+ # type has it. The arguments are checked by the core first: below, a
617
+ # refusal reads as "this type has no such operation", and a wrong keyword
618
+ # would otherwise leave every column out without a word.
619
+ private def transform_columns(op, names, args, keywords)
620
+ refuse_changed_rows(op)
621
+ CArray.float64(1).public_send(op, *args, **keywords)
622
+ out = over_named_columns(op, names, @key_names, args, keywords) do |col|
623
+ group_transform(col, op, args, keywords)
624
+ end
625
+ return out unless names.empty?
626
+ CAFrame.new(out, axis_name: @frame.axis_name, index: @frame.index)
627
+ end
628
+
629
+ # A column's within-group transform: an N-D column runs along the rows.
630
+ private def group_transform(col, op, args, keywords)
631
+ it = col.group_by_category(@cat)
632
+ keywords = keywords.merge(axis: 0) if col.ndim > 1
633
+ it.public_send(op, *args, **keywords)
634
+ end
635
+
272
636
  # Each result gets its own index.
273
637
  private def label_index
274
638
  return @index.copy if @index
275
639
  CArray.object(@labels.size) { |i| @labels[i] }
276
640
  end
277
641
 
278
- private def reduce_columns(reduction, **keywords)
279
- cols = {}
280
- @frame.column_names.each do |name|
281
- # A key column is the index here, not a result column.
282
- next if @key_names.include?(name)
283
- col = @frame[name]
284
- next unless answers?(col, reduction)
285
- cols[name] = group_reduce(col, reduction, **keywords)
642
+ # A key column is the index here, not a result column. Named columns
643
+ # come back as df[...] returns them, each on the frame's rows with
644
+ # +keep_rows+.
645
+ private def reduce_columns(reduction, names, keep_rows, **keywords)
646
+ keywords = keywords.compact
647
+ out = over_named_columns(reduction, names, @key_names) do |col|
648
+ col = group_reduce(col, reduction, **keywords)
649
+ keep_rows && !names.empty? ? spread_to_rows(col) : col
286
650
  end
287
- CAFrame.new(cols, axis_name: @axis_name, index: label_index)
651
+ return out unless names.empty?
652
+ result_frame(out, keep_rows)
653
+ end
654
+
655
+ # One row per group, indexed by the labels; or, with +keep_rows+, the
656
+ # frame's rows, each holding its group's result.
657
+ private def result_frame(cols, keep_rows)
658
+ unless keep_rows
659
+ return CAFrame.new(cols, axis_name: @axis_name, index: label_index) unless @label_columns
660
+ clash = cols.keys & @label_columns.keys
661
+ unless clash.empty?
662
+ raise ArgumentError,
663
+ "a result column has the name of a key column: #{clash.map(&:inspect).join(', ')}"
664
+ end
665
+ return CAFrame.new(@label_columns.transform_values(&:copy).merge(cols))
666
+ end
667
+ CAFrame.new(cols.transform_values { |col| spread_to_rows(col) },
668
+ axis_name: @frame.axis_name, index: @frame.index)
669
+ end
670
+
671
+ # A per-group result (one entry per group along axis 0) laid back over the
672
+ # frame's rows through the group codes. A row in no group is UNDEF.
673
+ private def spread_to_rows(result)
674
+ # A row in no group has a masked index cell, which x[i] answers as a
675
+ # hole: so even with no group at all, the result keeps its type.
676
+ codes = group_codes
677
+ index = codes.value.int64
678
+ index[codes.is_masked] = UNDEF
679
+ result[index, *[nil] * (result.ndim - 1)].copy
288
680
  end
289
681
 
290
682
  # A column's group reduction. An N-D column is reduced along the rows, so
@@ -298,22 +690,28 @@ class GroupedFrame
298
690
  end
299
691
  end
300
692
 
301
- # Whether the column's type defines the reduction, asked of the core on one
302
- # cell of it so that the answer is about the type and not the data: a
303
- # refusal there is the core saying the reduction does not apply, while an
304
- # error in the grouped reduction itself is left to raise. A column with no
305
- # rows is asked as it is: the refusal does not depend on the cells.
306
- private def answers?(col, reduction)
307
- (col.elements > 0 ? col[0..0] : col).public_send(reduction)
308
- true
309
- rescue CArray::DataTypeError, TypeError, ArgumentError
310
- false
311
- end
312
-
313
693
  private def per_group_column(in_name, proc)
314
694
  results = []
315
695
  each_group_slice(in_name) { |slice| results << proc.call(slice) }
316
- CArray.object(results.size) { |i| results[i] }
696
+ column_of_values(results)
697
+ end
698
+
699
+ # The grouping holds one code per row of the frame as it was when grouped.
700
+ # A frame whose row count changed since (a splice, a deletion) has rows
701
+ # the grouping does not know, so every verb refuses it.
702
+ private def refuse_changed_rows(verb)
703
+ return if @frame.nrow == @cat.elements
704
+ raise ArgumentError,
705
+ "#{verb}: the frame has #{@frame.nrow} rows, #{@cat.elements} when it " \
706
+ "was grouped; group it again"
707
+ end
708
+
709
+ # A column of the Ruby values the groups gave, typed as from_records types
710
+ # a record's values: Integers int64, numbers float64, Strings text, time
711
+ # elements a time column, arrays of one shape an N-D column, anything else
712
+ # object. UNDEF and nil are missing.
713
+ private def column_of_values(values)
714
+ CAFrame.__send__(:build_record_column, values, values.size)
317
715
  end
318
716
 
319
717
  private def each_group_slice(in_name)
@@ -327,6 +725,23 @@ class GroupedFrame
327
725
  ngroup.times { |k| yield @frame[group_address(k)] }
328
726
  end
329
727
 
728
+ # The first row of each group, in code order.
729
+ # With few groups each row's number is folded into its group's slot by the
730
+ # smallest, which needs no sort of the rows (a numeric column then reduces
731
+ # without one too); a row in no group (masked code) is in no slot, and a
732
+ # group without rows keeps no row (UNDEF). With more groups the columns
733
+ # are gathered through the sort anyway, so the first rows are read off it.
734
+ private def first_rows
735
+ if ngroup > CACategoricalIterator::SCATTER_CATEGORIES_MAX
736
+ return group_perm[group_bounds[0...ngroup]]
737
+ end
738
+ n = @cat.elements
739
+ first = CArray.int64(ngroup).fill(n)
740
+ first.scatter_min!(@cat.codes, CArray.int64(n).seq!)
741
+ first[first.eq(n)] = UNDEF if ngroup > 0
742
+ first
743
+ end
744
+
330
745
  private def group_address(k)
331
746
  group_perm[group_bounds[k]...group_bounds[k + 1]]
332
747
  end