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
@@ -3,40 +3,78 @@
3
3
  class CAFrame
4
4
 
5
5
  # The one rule of a frame-wide verb over the frame's columns -- the group
6
- # reductions and transforms, the windowed reductions -- kept in one place
7
- # so that every verb answers in the same shape:
6
+ # reductions and transforms, the windowed reductions, and the frame's own
7
+ # reductions and running values -- kept in one place: which columns a verb
8
+ # computes, and what a named column without the operation does.
8
9
  #
9
- # - given names, the CArray (one) or the Array of them (several), as
10
- # +df[...]+ returns columns; a named column whose type has no such
11
- # operation is refused with CArray::DataTypeError, as the core refuses
12
- # it, since it was asked for;
10
+ # - given names, those columns, as the CArray (one) or a Hash of name to
11
+ # result (several); a named column whose type has no such operation is
12
+ # refused with CArray::DataTypeError, as the core refuses it, since it
13
+ # was asked for;
13
14
  # - given none, every column whose type has it, the key columns left out,
14
- # as a Hash of name to result that the caller makes a frame of.
15
+ # as a Hash of name to result.
16
+ #
17
+ # The caller decides the shape of the answer from these: a verb whose
18
+ # answers lie on the frame's rows (a transform, a window at the rows,
19
+ # +keep_rows:+) hands one named column back as it is, as +df[name]+
20
+ # returns it, and several as a frame on the frame's rows, while a verb
21
+ # with one row per group, per point or for the whole frame makes a frame
22
+ # of them, labelled by its rows.
15
23
  #
16
24
  # Whether a type has the operation is asked of the core on two copies of
17
25
  # the column's first row (two blank cells of its kind when it has no
18
26
  # rows), so the answer is about the type and not the data: a refusal
19
27
  # there means the operation does not apply, while an error in the verb
20
- # itself is left to raise. An N-D column (each row a profile) is asked,
21
- # and computed, along the rows.
28
+ # itself is left to raise. An object column is the exception: its type
29
+ # says nothing of what it holds, so one with no present value, or whose
30
+ # cells do not answer, is left out of a verb run over every column. An N-D column (each row a profile) is
31
+ # asked, and computed, along the rows.
22
32
  module ColumnVerbs
23
33
 
24
34
  private
25
35
 
36
+ # The row of each cell, UNDEF where the cell is masked: a first or last
37
+ # taken of it picks the row, and the row picks the value of a Face that
38
+ # cannot hold new values, as lag picks it.
39
+ def present_rows (col)
40
+ rows = CArray.int64(col.elements).seq
41
+ rows[col.is_masked] = UNDEF if col.has_mask?
42
+ rows
43
+ end
44
+
45
+ # A verb whose answers lie on the frame's rows, with no column to compute:
46
+ # a frame of no column would also have no row.
47
+ def refuse_no_column_on_rows (verb, out, nrow)
48
+ return unless out.is_a?(Hash) && out.empty? && nrow > 0
49
+ raise ArgumentError, "#{verb}: no column to compute (every column is a key or has no #{verb})"
50
+ end
51
+
52
+ def refuse_unknown_fill_columns (verb, fills)
53
+ return unless fills.is_a?(Hash)
54
+ unknown = fills.keys - @frame.column_names
55
+ return if unknown.empty?
56
+ raise ArgumentError, "#{verb}: fill_value names no column #{unknown.map(&:inspect).join(', ')}"
57
+ end
58
+
26
59
  def over_named_columns (verb, names, key_names, args = [], keywords = {})
27
60
  if names.empty?
28
61
  cols = {}
29
62
  @frame.column_names.each do |name|
30
63
  next if key_names.include?(name)
31
64
  col = @frame[name]
65
+ next if valueless_object_column?(col, verb, args)
32
66
  next unless column_has?(col, verb, args, keywords)
33
- cols[name] = yield(col, name)
67
+ cols[name] = answer_of_every_column(col, name) { |c, n| yield(c, n) }
68
+ cols.delete(name) if cols[name].equal?(NO_ANSWER)
34
69
  end
35
70
  return cols
36
71
  end
37
- results = names.map do |name|
38
- key = @frame.__send__(:column_key, name, verb)
39
- col = @frame[key]
72
+ # A column named twice would be one result column twice over.
73
+ keys = CAFrame.__send__(:refuse_repeated_names,
74
+ names.map { |name| @frame.__send__(:column_key, name, verb) }, verb)
75
+ results = keys.map do |key|
76
+ name = key
77
+ col = @frame.__send__(:named_column, key, verb)
40
78
  unless column_has?(col, verb, args, keywords)
41
79
  raise CArray::DataTypeError,
42
80
  "#{verb}: column #{name.inspect} " \
@@ -44,7 +82,48 @@ class CAFrame
44
82
  end
45
83
  yield(col, key)
46
84
  end
47
- results.size == 1 ? results.first : results
85
+ results.size == 1 ? results.first : keys.zip(results).to_h
86
+ end
87
+
88
+ NO_ANSWER = Object.new.freeze
89
+ private_constant :NO_ANSWER
90
+
91
+ # What an object column holds shows only in the verb itself: one whose
92
+ # cells do not answer is left out of a verb run over every column, as a
93
+ # column of a type without the operation is, wherever those cells sit.
94
+ # refuse_wrong_reduction_arguments has refused what no column would take.
95
+ def answer_of_every_column (col, name)
96
+ return yield(col, name) if col.face? || col.data_type != CA_OBJECT
97
+ begin
98
+ yield(col, name)
99
+ rescue TypeError, ArgumentError, NoMethodError, RangeError
100
+ NO_ANSWER
101
+ end
102
+ end
103
+
104
+ # The arguments of a reduction, asked of the core on a number before any
105
+ # column, so a wrong one is not taken for a column that does not answer.
106
+ # fill_value: is of each column's type, and stays out of this.
107
+ def refuse_wrong_reduction_arguments (verb, args, keywords)
108
+ return if verb == :count
109
+ CArray.float64(1).public_send(verb, *args, **keywords.reject { |k, _| k == :fill_value })
110
+ rescue CArray::DataTypeError, NoMethodError
111
+ nil
112
+ end
113
+
114
+ # An object column with no present cell says nothing of what it holds,
115
+ # so a verb run over every column leaves it out, as select leaves it out
116
+ # of every kind; counting the present cells applies to any column. A
117
+ # Face kept in object cells (a CAString) with rows, every one masked, is
118
+ # the same: the type would be asked of masked cells only, which answer
119
+ # with the identity whatever the type. With no rows the type is asked of
120
+ # blank cells of its kind.
121
+ def valueless_object_column? (col, verb, args)
122
+ return false if col.data_type != CA_OBJECT
123
+ return false if col.face? && col.elements == 0
124
+ return false if %i[count_not_masked count_masked].include?(verb)
125
+ return false if verb == :count && args.empty?
126
+ col.count_not_masked == 0
48
127
  end
49
128
 
50
129
  # count with no value counts the present cells, which every type has;
@@ -54,10 +133,17 @@ class CAFrame
54
133
  verb = :count_not_masked if verb == :count && args.empty?
55
134
  # Two cells: one cell does not reach what combines two (a String's
56
135
  # median interpolates, its sum adds), and an empty column answers
57
- # with the identity without asking the type at all.
136
+ # with the identity without asking the type at all. The row is the
137
+ # first that holds a present cell, so a masked first row does not
138
+ # answer with the identity for a column whose values have none.
58
139
  tail = [nil] * (col.ndim - 1)
140
+ row = 0
141
+ if col.has_mask? && col.elements > 0
142
+ present = col.is_not_masked.flatten.where
143
+ row = present[0] / (col.elements / col.shape[0]) if present.elements > 0
144
+ end
59
145
  probe = if col.shape[0] > 0
60
- col[CA_INT64([0, 0]), *tail]
146
+ col[CA_INT64([row, row]), *tail]
61
147
  else
62
148
  col.resize(2, *col.shape[1..])
63
149
  end
@@ -52,10 +52,13 @@ class CAFrame
52
52
  index_pieces(frames, verb: "meld")
53
53
  check_trailing_shapes(frames, names, verb: "meld")
54
54
  frames = frames_with_rows(frames)
55
+ if first.index
56
+ check_same_column_type(frames.map(&:index), first.axis_name, verb: "meld")
57
+ end
55
58
  cols = {}
56
59
  names.each do |name|
57
60
  check_same_column_type(frames.map { |f| f[name] }, name, verb: "meld")
58
- cols[name] = CArray.meld(frames.map { |f| f[name] }, axis: 0)
61
+ cols[name] = welding_column(name, "meld") { CArray.meld(frames.map { |f| f[name] }, axis: 0) }
59
62
  end
60
63
  new(cols, axis_name: first.axis_name, index: meld_index(frames))
61
64
  end
@@ -85,7 +88,9 @@ class CAFrame
85
88
  frames = frames_with_rows(frames)
86
89
  cols = {}
87
90
  names.each do |name|
88
- cols[name] = CArray.concatenate(frames.map { |f| f[name] })
91
+ pieces = face_pieces_in_one_state(frames.map { |f| f[name] })
92
+ refuse_rounded_pieces(pieces, "concatenate", "column #{name.inspect}")
93
+ cols[name] = welding_column(name, "concatenate") { CArray.concatenate(pieces) }
89
94
  end
90
95
  new(cols, axis_name: first.axis_name, index: concatenate_index(frames))
91
96
  end
@@ -135,7 +140,8 @@ class CAFrame
135
140
  "stack: axis #{axis} out of range for column #{name.inspect} " \
136
141
  "(a #{parts.first.ndim}-D column takes 1 to #{parts.first.ndim})"
137
142
  end
138
- cols[name] = CArray.stack(parts, axis: axis)
143
+ refuse_rounded_pieces(parts, "stack", "column #{name.inspect}")
144
+ cols[name] = welding_column(name, "stack") { CArray.stack(parts, axis: axis) }
139
145
  end
140
146
  new(cols, axis_name: first.axis_name, index: first.index)
141
147
  end
@@ -194,6 +200,43 @@ class CAFrame
194
200
 
195
201
  # ---- shared validators -------------------------------------------------
196
202
 
203
+ # Pieces of one Face in different states brought to one, as an outer join
204
+ # brings its two keys: times and durations to a common unit, categoricals
205
+ # to the labels of all, the first piece's first.
206
+ def self.face_pieces_in_one_state(pieces)
207
+ first = pieces.first
208
+ return pieces unless first.face? && pieces.all? { |p| p.class == first.class }
209
+ # names-check: units, not names
210
+ if first.respond_to?(:in_common_unit_with) && pieces.map(&:unit).uniq.size > 1
211
+ common = pieces.drop(1).reduce(first) { |acc, p| acc.in_common_unit_with(p).first }
212
+ return pieces.map { |p| p.unit == common.unit ? p : p.to_unit(common.unit) }
213
+ end
214
+ # names-check: label lists, not names
215
+ if first.is_a?(CACategorical) && pieces.map(&:labels).uniq.size > 1
216
+ labels = pieces.map(&:labels).reduce(:|)
217
+ return pieces.map { |p| CArray.object(*p.shape) { p.to_a }.categorize(labels: labels) }
218
+ end
219
+ pieces
220
+ end
221
+ private_class_method :face_pieces_in_one_state
222
+
223
+ # Pieces brought to a float: a value it rounds would be another value.
224
+ def self.refuse_rounded_pieces(pieces, verb, what)
225
+ return if pieces.size < 2 || pieces.any?(&:face?) || pieces.any? { |c| c.data_type == CA_FIXLEN }
226
+ refuse_rounded_integers(pieces, CArray.result_type(*pieces), verb, what)
227
+ end
228
+ private_class_method :refuse_rounded_pieces
229
+
230
+ # A refusal of the pieces reads as the verb the frames were given to, with
231
+ # the column it came from.
232
+ def self.welding_column(name, verb)
233
+ yield
234
+ rescue ArgumentError, CArray::DataTypeError => e
235
+ raise unless e.message.start_with?("#{verb}: ", "can't promote", "CAStack parents")
236
+ raise e.class, "#{verb}: column #{name.inspect}: #{e.message.delete_prefix("#{verb}: ")}"
237
+ end
238
+ private_class_method :welding_column
239
+
197
240
  def self.check_concat_inputs(frames, verb:)
198
241
  raise ArgumentError, "#{verb} requires at least one frame" if frames.empty?
199
242
  unless frames.all? { |f| f.is_a?(CAFrame) }
@@ -267,8 +310,7 @@ class CAFrame
267
310
  def self.meld_index(frames)
268
311
  indexes, axis = index_pieces(frames, verb: "meld")
269
312
  return nil unless indexes
270
- axis # unused; kept for symmetry
271
- CArray.meld(indexes, axis: 0)
313
+ welding_column(axis, "meld") { CArray.meld(indexes, axis: 0) }
272
314
  end
273
315
  private_class_method :meld_index
274
316
 
@@ -276,7 +318,9 @@ class CAFrame
276
318
  def self.concatenate_index(frames)
277
319
  indexes, _axis = index_pieces(frames, verb: "concatenate")
278
320
  return nil unless indexes
279
- CArray.concatenate(indexes)
321
+ indexes = face_pieces_in_one_state(indexes)
322
+ refuse_rounded_pieces(indexes, "concatenate", "the index")
323
+ welding_column(frames.first.axis_name, "concatenate") { CArray.concatenate(indexes) }
280
324
  end
281
325
  private_class_method :concatenate_index
282
326
 
@@ -26,6 +26,25 @@ class CAFrame
26
26
  each_row.map { |row| row.transform_values { |v| record_value(v) } }
27
27
  end
28
28
 
29
+ # The rows as an Array of Arrays, one value per column in column order --
30
+ # the table as plain Ruby data, for a library that takes rows (anything
31
+ # that calls +to_a+ on what it is given). A cell is what the column's own
32
+ # +to_a+ gives: a masked cell is +UNDEF+, a time column's cell its element,
33
+ # and an N-D column's cell an Array. The index is a row label, not a value,
34
+ # and is left out; +reset_index+ first to have it as the first column.
35
+ #
36
+ # Masked cells are not turned into anything: decide what they should be
37
+ # before handing the rows over, with +strip_mask+ or +drop_masked+.
38
+ #
39
+ # df.drop_masked.to_a
40
+ # df.strip_mask("temp" => Float::NAN).to_a
41
+ #
42
+ # @return [Array<Array>]
43
+ def to_a
44
+ return Array.new(@nrow) { [] } if @columns.empty?
45
+ return @columns.values.map(&:to_a).transpose
46
+ end
47
+
29
48
  # Hand the frame over as a CArray with the minimum work (memo §11.9): a
30
49
  # 2-D **view** of shape (nrow, ncol), one per column in column
31
50
  # order (§12-C). Nothing is materialised — the result is a +CAStack+ over
@@ -1,4 +1,4 @@
1
- # A small, self-contained CSV tokenizer for CAFrame.from_csv.
1
+ # A small, self-contained CSV tokenizer for CAFrame.read_csv.
2
2
  #
3
3
  # It produces raw String cells and does no type inference — casting is a
4
4
  # separate step. The tokenizer is tuned for the
@@ -22,14 +22,14 @@
22
22
  # Two entry points share the Tokenizer:
23
23
  # * CSVParser.parse / parse_file -- whole-file parse into [headers, rows].
24
24
  # * CSVReader -- the block reading-control DSL used by
25
- # CAFrame.from_csv (header / skip / body /
25
+ # CAFrame.read_csv (header / skip / body /
26
26
  # column_names).
27
27
 
28
28
  require "strscan"
29
29
  require "stringio"
30
30
 
31
31
  class CAFrame
32
- # CSV tokenizer behind `CAFrame.from_csv`. It produces raw String cells
32
+ # CSV tokenizer behind `CAFrame.read_csv`. It produces raw String cells
33
33
  # and does no type inference — casting is a separate step.
34
34
  #
35
35
  # Records with no quote character take a `String#split` fast path; only
@@ -79,7 +79,7 @@ class CAFrame
79
79
 
80
80
  # Parse an IO (or anything answering +gets+). The first record supplies the
81
81
  # headers; the rest are data rows. Blank lines are skipped, including in a
82
- # one-column file (from_csv reads them there as missing cells).
82
+ # one-column file (read_csv reads them there as missing cells).
83
83
  def parse(io, sep: ",", quote: '"', strip: false)
84
84
  tok = Tokenizer.new(sep, quote, strip)
85
85
  headers = nil
@@ -99,16 +99,24 @@ class CAFrame
99
99
  class Tokenizer
100
100
  attr_reader :sep, :quote, :strip
101
101
 
102
- def initialize(sep, quote, strip)
102
+ # What a separator and a quote have to be, for reading and for writing.
103
+ def self.check_delimiters(sep, quote)
103
104
  unless sep.is_a?(String) && !sep.empty?
104
105
  raise ArgumentError, "sep: must be a non-empty String (got #{sep.inspect})"
105
106
  end
107
+ if sep.match?(/[\r\n]/)
108
+ raise ArgumentError, "sep: cannot hold a line end (got #{sep.inspect})"
109
+ end
106
110
  unless quote.is_a?(String) && quote.size == 1
107
111
  raise ArgumentError, "quote: must be one character (got #{quote.inspect})"
108
112
  end
109
113
  if sep.include?(quote)
110
114
  raise ArgumentError, "sep: #{sep.inspect} cannot contain the quote character"
111
115
  end
116
+ end
117
+
118
+ def initialize(sep, quote, strip)
119
+ Tokenizer.check_delimiters(sep, quote)
112
120
  @sep = sep
113
121
  @quote = quote
114
122
  @strip = strip
@@ -239,7 +247,7 @@ class CAFrame
239
247
  part = part + @sep + parts[i]
240
248
  end
241
249
  inner = part[1...-1]
242
- fields << (inner.include?(@quote) ? inner.gsub(@qq, @quote) : inner)
250
+ fields << (inner.include?(@quote) ? inner.gsub(@qq) { @quote } : inner)
243
251
  elsif part.include?(@quote)
244
252
  return nil
245
253
  else
@@ -315,24 +323,24 @@ class CAFrame
315
323
  end
316
324
  end
317
325
 
318
- # The reading-control block for CAFrame.from_csv. A file often has
326
+ # The reading-control block for CAFrame.read_csv. A file often has
319
327
  # preamble lines, a units row, or no header at all; the block is given the
320
328
  # reader and says, in order, how to consume the stream:
321
329
  #
322
- # CAFrame.from_csv(path) do |r|
330
+ # CAFrame.read_csv(path) do |r|
323
331
  # r.skip 3 # drop 3 preamble lines
324
332
  # r.header # next record supplies the column names
325
333
  # r.skip 1 # drop a units row
326
334
  # r.data # the rest are data rows
327
335
  # end
328
336
  #
329
- # CAFrame.from_csv(path) { it.column_names "date", "temp", "rh"; it.data }
337
+ # CAFrame.read_csv(path) { it.column_names "date", "temp", "rh"; it.data }
330
338
  #
331
339
  # The verbs are +skip+ / +header+ / +column_names+ / +columns+ / +data+;
332
340
  # each returns a value useful inline (header returns its fields) and the ordering is the
333
341
  # script. The reader is a parameter, not self, so a local variable named
334
342
  # +data+ or +header+ cannot stand in for the verb. Without a block,
335
- # from_csv reads by its header: / data: / column_names: (see +layout+).
343
+ # read_csv reads by its header: / data: / column_names: (see +layout+).
336
344
  class CSVReader
337
345
  def initialize(io, sep: ",", quote: '"', strip: false, read_text_as_const_string: false)
338
346
  @read_text_as_const_string = read_text_as_const_string
@@ -388,7 +396,7 @@ class CAFrame
388
396
  key = name.to_s
389
397
  @named_headers ||= {}
390
398
  if @named_headers.key?(key)
391
- raise ArgumentError, "from_csv: header(#{name.inspect}) is read twice"
399
+ raise ArgumentError, "read_csv: header(#{name.inspect}) is read twice"
392
400
  end
393
401
  @named_headers[key] = [fields, @tok.record_line, name]
394
402
  end
@@ -403,7 +411,7 @@ class CAFrame
403
411
  def column_names(*names)
404
412
  names = names.flatten.map(&:to_s)
405
413
  if names.include?("")
406
- raise ArgumentError, "from_csv: column_names: a column name can not be empty"
414
+ raise ArgumentError, "read_csv: column_names: a column name can not be empty"
407
415
  end
408
416
  if @header_line
409
417
  check_column_names(names, @names.size, @header_line)
@@ -431,15 +439,15 @@ class CAFrame
431
439
  end
432
440
  selection = selection.flatten
433
441
  if selection.empty?
434
- raise ArgumentError, "from_csv: columns: names no column"
442
+ raise ArgumentError, "read_csv: columns: names no column"
435
443
  end
436
444
  selection.each do |c|
437
445
  next if c.is_a?(String)
438
- CAFrame.__send__(:column_key, c, "from_csv", "columns: a column name") if c.is_a?(Symbol)
446
+ CAFrame.__send__(:column_key, c, "read_csv", "columns: a column name") if c.is_a?(Symbol)
439
447
  next if c.is_a?(Integer) && c >= 0
440
448
  next if c.is_a?(Range) && (c.begin.nil? || (c.begin.is_a?(Integer) && c.begin >= 0)) &&
441
- (c.end.nil? || c.end.is_a?(Integer))
442
- raise ArgumentError, "from_csv: columns: takes column names, or indexes from 0 " \
449
+ (c.end.nil? || (c.end.is_a?(Integer) && c.end >= 0))
450
+ raise ArgumentError, "read_csv: columns: takes column names, or indexes from 0 " \
443
451
  "and Ranges of them (got #{c.inspect})"
444
452
  end
445
453
  @selection = selection
@@ -450,17 +458,17 @@ class CAFrame
450
458
  private def column_renames(map)
451
459
  map.each do |key, name|
452
460
  if key.is_a?(Range)
453
- raise ArgumentError, "from_csv: columns: a Hash selects one column per key, " \
461
+ raise ArgumentError, "read_csv: columns: a Hash selects one column per key, " \
454
462
  "not a Range (got #{key.inspect})"
455
463
  end
456
- CAFrame.__send__(:column_key, name, "from_csv", "columns: a column name",
464
+ CAFrame.__send__(:column_key, name, "read_csv", "columns: a column name",
457
465
  hint: "given for #{key.inspect}")
458
466
  if name.empty?
459
- raise ArgumentError, "from_csv: columns: a column name can not be empty " \
467
+ raise ArgumentError, "read_csv: columns: a column name can not be empty " \
460
468
  "(given for #{key.inspect})"
461
469
  end
462
470
  end
463
- CAFrame.__send__(:refuse_repeated_names, map.values, "from_csv", "columns: names")
471
+ CAFrame.__send__(:refuse_repeated_names, map.values, "read_csv", "columns: names")
464
472
  map.values
465
473
  end
466
474
 
@@ -474,7 +482,7 @@ class CAFrame
474
482
  # Without a header the columns are named c0, c1, ... by position.
475
483
  j = names ? names.index(c) : c[/\Ac(0|[1-9]\d*)\z/, 1]&.to_i
476
484
  if j.nil?
477
- raise KeyError, "from_csv: columns: names no column #{c.inspect}" +
485
+ raise KeyError, "read_csv: columns: names no column #{c.inspect}" +
478
486
  (names ? "" : " (with no header the columns are c0, c1, ...)")
479
487
  end
480
488
  j
@@ -485,12 +493,13 @@ class CAFrame
485
493
  return nil if last.nil? && ncol.nil?
486
494
  last = ncol - 1 if last.nil?
487
495
  last -= 1 if c.end && c.exclude_end?
496
+ raise ArgumentError, "read_csv: columns: #{c.inspect} selects no column" if last < first
488
497
  (first..last).to_a
489
498
  end
490
499
  end
491
- CAFrame.__send__(:refuse_repeated_names, indexes, "from_csv", "columns: selects column")
500
+ CAFrame.__send__(:refuse_repeated_names, indexes, "read_csv", "columns: selects column")
492
501
  if ncol && (bad = indexes.find { |j| j >= ncol })
493
- raise ArgumentError, "from_csv: columns: #{bad} is past the #{ncol} columns of the file"
502
+ raise ArgumentError, "read_csv: columns: #{bad} is past the #{ncol} columns of the file"
494
503
  end
495
504
  indexes
496
505
  end
@@ -503,7 +512,7 @@ class CAFrame
503
512
 
504
513
  private def check_column_names(names, ncol, line)
505
514
  return if names.size == ncol
506
- raise ArgumentError, "from_csv: column_names: gives #{names.size} " \
515
+ raise ArgumentError, "read_csv: column_names: gives #{names.size} " \
507
516
  "name#{names.size == 1 ? '' : 's'} for the #{ncol} columns of line #{line}"
508
517
  end
509
518
 
@@ -525,7 +534,7 @@ class CAFrame
525
534
  read_data(nil)
526
535
  end
527
536
 
528
- # The header: / data: / column_names: of from_csv, as the verbs above.
537
+ # The header: / data: / column_names: of read_csv, as the verbs above.
529
538
  # They index the lines of the file from 0, as File.readlines does (an
530
539
  # error names a line from 1, as an editor does). header: defaults to 0,
531
540
  # or to none (false) when column_names: is given; data: is the first line
@@ -534,12 +543,12 @@ class CAFrame
534
543
  def layout(header: nil, data: nil, column_names: nil, columns: nil, attrs: nil)
535
544
  header = column_names ? false : 0 if header.nil?
536
545
  unless header == false || (header.is_a?(Integer) && header >= 0)
537
- raise ArgumentError, "from_csv: header: takes the index of a line, from 0, " \
546
+ raise ArgumentError, "read_csv: header: takes the index of a line, from 0, " \
538
547
  "or false (got #{header.inspect})"
539
548
  end
540
- attr_keys = attrs.nil? ? [] : CAFrame.send(:csv_attr_keys, attrs, "from_csv")
549
+ attr_keys = attrs.nil? ? [] : CAFrame.send(:csv_attr_keys, attrs, "read_csv")
541
550
  if !header && !attr_keys.empty?
542
- raise ArgumentError, "from_csv: attrs: reads the lines below the header, " \
551
+ raise ArgumentError, "read_csv: attrs: reads the lines below the header, " \
543
552
  "so it needs a header line"
544
553
  end
545
554
  first, last = CSVReader.data_lines(data)
@@ -552,7 +561,7 @@ class CAFrame
552
561
  self.columns(*(columns.is_a?(Array) ? columns : [columns])) if columns
553
562
  first ||= @tok.lineno
554
563
  if first < @tok.lineno
555
- raise ArgumentError, "from_csv: data: #{first} does not come after header: #{header}" +
564
+ raise ArgumentError, "read_csv: data: #{first} does not come after header: #{header}" +
556
565
  (attr_keys.empty? ? "" : " and the #{attr_keys.size} attrs: lines")
557
566
  end
558
567
  skip(first - @tok.lineno)
@@ -570,15 +579,15 @@ class CAFrame
570
579
  e -= 1 if e.is_a?(Integer) && spec.exclude_end?
571
580
  [spec.begin, e]
572
581
  else
573
- raise ArgumentError, "from_csv: data: takes the index of a line or a Range of " \
582
+ raise ArgumentError, "read_csv: data: takes the index of a line or a Range of " \
574
583
  "them, from 0 (got #{spec.inspect})"
575
584
  end
576
585
  [first, last].each do |n|
577
586
  next if n.nil? || (n.is_a?(Integer) && n >= 0)
578
- raise ArgumentError, "from_csv: data: lines are indexed from 0 (got #{spec.inspect})"
587
+ raise ArgumentError, "read_csv: data: lines are indexed from 0 (got #{spec.inspect})"
579
588
  end
580
589
  if first && last && last < first
581
- raise ArgumentError, "from_csv: data: #{spec.inspect} ends before it starts"
590
+ raise ArgumentError, "read_csv: data: #{spec.inspect} ends before it starts"
582
591
  end
583
592
  [first, last]
584
593
  end
@@ -648,12 +657,12 @@ class CAFrame
648
657
  end
649
658
 
650
659
  # The columns read_body_into_const_string_columns made, as +result+
651
- # hands them to CAFrame.from_csv.
660
+ # hands them to CAFrame.read_csv.
652
661
  ConstStringColumns = Struct.new(:columns)
653
662
 
654
663
  private def body_in_c(last = nil, chunk_bytes = CHUNK_BYTES)
655
664
  return read_body_into_const_string_columns if last.nil? && @read_text_as_const_string
656
- chunked = last.nil? && @names && @io.respond_to?(:external_encoding) &&
665
+ chunked = last.nil? && @names && @io.respond_to?(:internal_encoding) &&
657
666
  @io.internal_encoding.nil?
658
667
  # Names that have to agree with the first record leave its column
659
668
  # count to C, to be checked against them.
@@ -767,7 +776,7 @@ class CAFrame
767
776
  attrs = indexes.map { {} }
768
777
  @named_headers.each do |key, (fields, line, name)|
769
778
  if fields.size > ncol
770
- raise ArgumentError, "from_csv: header(#{name.inspect}) on line #{line} " \
779
+ raise ArgumentError, "read_csv: header(#{name.inspect}) on line #{line} " \
771
780
  "has #{fields.size} fields for the #{ncol} columns"
772
781
  end
773
782
  indexes.each_with_index do |j, k|
@@ -784,7 +793,7 @@ class CAFrame
784
793
  @names ? @names.size : ((@rows || []).map(&:size).max || 0)
785
794
  end
786
795
 
787
- # [names_or_nil, rows] for CAFrame.from_csv to build from. names is nil when
796
+ # [names_or_nil, rows] for CAFrame.read_csv to build from. names is nil when
788
797
  # neither header nor column_names ran (positional names are generated).
789
798
  def result
790
799
  return table_result if @table
@@ -30,10 +30,12 @@ class CAFrame
30
30
  # column with no present cell has UNDEF statistics. The index is not a
31
31
  # column and is not summarized.
32
32
  #
33
- # @param names [Array<String>] the columns to summarize; default all.
33
+ # @param names [Array<String, Range, Regexp, Symbol>] the columns to
34
+ # summarize, picked as +select+ picks them (a Symbol is a kind of column,
35
+ # such as :numeric); default all.
34
36
  # @return [CAFrame] a new frame with one row per column.
35
37
  def describe(*names)
36
- names = names.empty? ? column_names : column_keys(names, "describe")
38
+ names = names.empty? ? column_names : names_selected(names, "describe")
37
39
  rows = names.map { |name| describe_column(self[name]) }
38
40
  stats = %w[type count masked unique min max mean stddev]
39
41
  cols = stats.to_h do |stat|