carray 3.0.7 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (275) hide show
  1. checksums.yaml +4 -4
  2. data/.yardopts +1 -1
  3. data/CHANGELOG.md +7 -1940
  4. data/README.md +38 -32
  5. data/carray.gemspec +16 -4
  6. data/docs/changelogs/CHANGELOG-3.0.md +2464 -0
  7. data/ext/ca_array_pool.c +4 -5
  8. data/ext/ca_axis_descriptor.h +45 -30
  9. data/ext/ca_axis_dispatch.c +7 -4
  10. data/ext/ca_axis_group.c +6 -9
  11. data/ext/ca_bincmp_dispatch.h +16 -38
  12. data/ext/ca_binop_dispatch.c +27 -0
  13. data/ext/ca_binop_dispatch.h +22 -47
  14. data/ext/ca_categorical_iterator.c +36 -34
  15. data/ext/ca_compare.c +0 -1
  16. data/ext/ca_compare.h +8 -1
  17. data/ext/ca_composite_dispatch.h +6 -0
  18. data/ext/ca_for_buffer.h +6 -1
  19. data/ext/ca_group_iter.c +17 -18
  20. data/ext/ca_iter_state_fields.h +196 -0
  21. data/ext/ca_iter_substrate.h +84 -103
  22. data/ext/ca_kernel_iterator.c +125 -89
  23. data/ext/ca_kernel_iterator.h +229 -1506
  24. data/ext/ca_kernel_iterator_internal.h +1167 -0
  25. data/ext/ca_moncmp_dispatch.h +17 -24
  26. data/ext/ca_monop_dispatch.h +25 -74
  27. data/ext/ca_obj_array.c +90 -163
  28. data/ext/ca_obj_bincmp.c +47 -46
  29. data/ext/ca_obj_binop.c +38 -38
  30. data/ext/ca_obj_bitarray.c +5 -17
  31. data/ext/ca_obj_bitfield.c +15 -30
  32. data/ext/ca_obj_block.c +11 -12
  33. data/ext/ca_obj_byte_swap.c +32 -30
  34. data/ext/ca_obj_const_string.c +57 -62
  35. data/ext/ca_obj_face.c +99 -91
  36. data/ext/ca_obj_face.h +32 -170
  37. data/ext/ca_obj_fake.c +15 -21
  38. data/ext/ca_obj_farray.c +7 -9
  39. data/ext/ca_obj_field.c +17 -13
  40. data/ext/ca_obj_fixlen_string.c +8 -19
  41. data/ext/ca_obj_grid.c +137 -106
  42. data/ext/ca_obj_meld.c +23 -21
  43. data/ext/ca_obj_moncmp.c +10 -21
  44. data/ext/ca_obj_monop.c +24 -35
  45. data/ext/ca_obj_object.c +51 -37
  46. data/ext/ca_obj_record.c +74 -22
  47. data/ext/ca_obj_reduce.c +8 -10
  48. data/ext/ca_obj_refer.c +42 -29
  49. data/ext/ca_obj_remap.c +11 -29
  50. data/ext/ca_obj_repeat.c +41 -23
  51. data/ext/ca_obj_roll.c +18 -24
  52. data/ext/ca_obj_select.c +10 -22
  53. data/ext/ca_obj_select_axis.c +27 -36
  54. data/ext/ca_obj_shift.c +22 -42
  55. data/ext/ca_obj_source.c +1 -5
  56. data/ext/ca_obj_stack.c +28 -24
  57. data/ext/ca_obj_stride.c +53 -54
  58. data/ext/ca_obj_string.c +6 -18
  59. data/ext/ca_obj_tile.c +12 -12
  60. data/ext/ca_obj_time.c +12 -23
  61. data/ext/ca_obj_timedelta.c +12 -23
  62. data/ext/ca_obj_transpose.c +8 -10
  63. data/ext/ca_obj_triop.c +35 -39
  64. data/ext/ca_obj_window.c +67 -86
  65. data/ext/ca_op_cmplx64.h +4 -0
  66. data/ext/ca_op_ipower.c +34 -12
  67. data/ext/ca_op_powi.h +4 -0
  68. data/ext/ca_pow5_table.h +2 -1
  69. data/ext/ca_rng_normal.h +4 -0
  70. data/ext/ca_rng_xoshiro256pp.h +3 -0
  71. data/ext/ca_sort_kernels.h +20 -26
  72. data/ext/ca_sweep_engine.c +2 -3
  73. data/ext/ca_sweep_engine.h +17 -9
  74. data/ext/ca_transform_common.c +3 -8
  75. data/ext/ca_triop_dispatch.h +20 -32
  76. data/ext/caframe_csv_reader.c +11 -11
  77. data/ext/carray.h +300 -1011
  78. data/ext/carray_access.c +234 -180
  79. data/ext/carray_address_basis.c +33 -38
  80. data/ext/carray_attribute.c +81 -104
  81. data/ext/carray_bincount.c +12 -14
  82. data/ext/carray_broadcast.c +30 -26
  83. data/ext/carray_call_cfunc.c +169 -277
  84. data/ext/carray_call_cfunc.h +36 -28
  85. data/ext/carray_cast.c +912 -346
  86. data/ext/carray_cast_func.rb +31 -3
  87. data/ext/carray_class.c +6 -11
  88. data/ext/carray_conversion.c +43 -38
  89. data/ext/carray_copy.c +28 -26
  90. data/ext/carray_core.c +217 -126
  91. data/ext/carray_count.c +27 -15
  92. data/ext/carray_element.c +40 -25
  93. data/ext/carray_factorize.c +53 -52
  94. data/ext/carray_generate.c +26 -19
  95. data/ext/carray_histogram.c +8 -10
  96. data/ext/carray_hold.c +7 -9
  97. data/ext/carray_index_classifier.c +123 -228
  98. data/ext/carray_index_classifier.h +11 -10
  99. data/ext/carray_integer_total.c +523 -0
  100. data/ext/carray_internal.h +1274 -160
  101. data/ext/carray_key_windows.c +3 -3
  102. data/ext/carray_lazy.c +21 -36
  103. data/ext/carray_loop.c +19 -22
  104. data/ext/carray_mask.c +123 -145
  105. data/ext/carray_math_kernel.h +23 -47
  106. data/ext/carray_mathfunc.c +10 -3
  107. data/ext/carray_median_percentile.c +95 -94
  108. data/ext/carray_memory_view.c +42 -47
  109. data/ext/carray_operator.c +423 -122
  110. data/ext/carray_order.c +121 -85
  111. data/ext/carray_partition.c +13 -15
  112. data/ext/carray_random.c +47 -41
  113. data/ext/carray_round.c +9 -4
  114. data/ext/carray_scatter.c +54 -40
  115. data/ext/carray_segment.c +41 -45
  116. data/ext/carray_slab.c +64 -47
  117. data/ext/carray_slab.h +44 -33
  118. data/ext/carray_sort.c +32 -29
  119. data/ext/carray_sort_kernel.c +12 -10
  120. data/ext/carray_struct.c +38 -43
  121. data/ext/carray_test.c +47 -43
  122. data/ext/carray_time_text.c +24 -31
  123. data/ext/carray_undef.c +50 -7
  124. data/ext/carray_utils.c +258 -94
  125. data/ext/extconf.rb +24 -17
  126. data/ext/mk_call_cfunc.rb +19 -20
  127. data/ext/mk_pow5_table.rb +2 -1
  128. data/ext/mkkernel.rb +782 -461
  129. data/ext/ruby_carray.c +47 -42
  130. data/ext/version.h +7 -5
  131. data/lib/carray/attribute.rb +19 -18
  132. data/lib/carray/autoload_carray.rb +20 -15
  133. data/lib/carray/autoload_method_extension.rb +64 -57
  134. data/lib/carray/axis_group.rb +264 -180
  135. data/lib/carray/basics.rb +272 -48
  136. data/lib/carray/bincount_nd.rb +33 -16
  137. data/lib/carray/block_iterator.rb +123 -102
  138. data/lib/carray/boolean_reduce.rb +7 -4
  139. data/lib/carray/categorical.rb +63 -51
  140. data/lib/carray/categorical_iterator.rb +89 -67
  141. data/lib/carray/complex.rb +61 -41
  142. data/lib/carray/conditional.rb +49 -22
  143. data/lib/carray/const_string.rb +54 -62
  144. data/lib/carray/core_extensions.rb +1 -1
  145. data/lib/carray/distance_limit.rb +7 -5
  146. data/lib/carray/factories.rb +269 -0
  147. data/lib/carray/fixlen_string.rb +25 -24
  148. data/lib/carray/frame/column_verbs.rb +20 -8
  149. data/lib/carray/frame/concat.rb +3 -3
  150. data/lib/carray/frame/convert.rb +2 -1
  151. data/lib/carray/frame/csv_parser.rb +7 -1
  152. data/lib/carray/frame/frame.rb +35 -25
  153. data/lib/carray/frame/group.rb +183 -150
  154. data/lib/carray/frame/io.rb +26 -7
  155. data/lib/carray/frame/join.rb +37 -12
  156. data/lib/carray/frame/records.rb +1 -1
  157. data/lib/carray/frame/reshape.rb +3 -3
  158. data/lib/carray/frame/sort.rb +10 -8
  159. data/lib/carray/frame/verbs.rb +148 -118
  160. data/lib/carray/frame/windows.rb +232 -21
  161. data/lib/carray/frame.rb +1 -2
  162. data/lib/carray/fuse_source.rb +24 -21
  163. data/lib/carray/fusion.rb +30 -30
  164. data/lib/carray/histogram.rb +35 -16
  165. data/lib/carray/inspect.rb +7 -7
  166. data/lib/carray/iterator.rb +97 -24
  167. data/lib/carray/key_windows.rb +83 -57
  168. data/lib/carray/lazy.rb +196 -94
  169. data/lib/carray/limits.rb +80 -0
  170. data/lib/carray/mask_gap_fill.rb +21 -16
  171. data/lib/carray/math.rb +87 -50
  172. data/lib/carray/meld_reduce.rb +30 -8
  173. data/lib/carray/methods/align_addr.rb +29 -17
  174. data/lib/carray/methods/bin.rb +5 -1
  175. data/lib/carray/methods/bincount.rb +4 -2
  176. data/lib/carray/methods/bit_string.rb +19 -31
  177. data/lib/carray/methods/broadcast.rb +8 -3
  178. data/lib/carray/methods/choose.rb +5 -5
  179. data/lib/carray/methods/composition.rb +72 -71
  180. data/lib/carray/methods/{index.rb → coordinate.rb} +13 -13
  181. data/lib/carray/methods/discovery_along.rb +3 -3
  182. data/lib/carray/methods/gather_nd.rb +106 -106
  183. data/lib/carray/methods/insert_block.rb +2 -2
  184. data/lib/carray/methods/is_between.rb +6 -4
  185. data/lib/carray/methods/is_in.rb +165 -145
  186. data/lib/carray/methods/join.rb +2 -1
  187. data/lib/carray/methods/lag.rb +6 -2
  188. data/lib/carray/methods/locate_addr.rb +150 -138
  189. data/lib/carray/methods/mask_duplicates.rb +1 -1
  190. data/lib/carray/methods/meshgrid.rb +28 -16
  191. data/lib/carray/methods/mode.rb +67 -67
  192. data/lib/carray/methods/nunique.rb +9 -7
  193. data/lib/carray/methods/repeat.rb +12 -12
  194. data/lib/carray/methods/resize.rb +1 -1
  195. data/lib/carray/methods/snap.rb +24 -20
  196. data/lib/carray/methods/string_format.rb +2 -2
  197. data/lib/carray/methods/unique.rb +4 -2
  198. data/lib/carray/methods/value_counts.rb +1 -1
  199. data/lib/carray/mkmf.rb +25 -28
  200. data/lib/carray/percentile_arguments.rb +82 -0
  201. data/lib/carray/record_order.rb +18 -17
  202. data/lib/carray/rng.rb +1 -0
  203. data/lib/carray/runtime.rb +190 -22
  204. data/lib/carray/segment_iterator.rb +251 -129
  205. data/lib/carray/serialize.rb +618 -571
  206. data/lib/carray/slab_iterator.rb +114 -114
  207. data/lib/carray/stack.rb +11 -12
  208. data/lib/carray/string.rb +16 -22
  209. data/lib/carray/string_operation_extension.rb +76 -52
  210. data/lib/carray/struct.rb +122 -164
  211. data/lib/carray/struct_builder.rb +243 -72
  212. data/lib/carray/time.rb +496 -342
  213. data/lib/carray/window_iterator.rb +191 -150
  214. data/lib/carray.rb +6 -11
  215. data/yard-stubs/ca_obj_array.rb +20 -135
  216. data/yard-stubs/ca_obj_bitarray.rb +1 -8
  217. data/yard-stubs/ca_obj_bitfield.rb +4 -3
  218. data/yard-stubs/ca_obj_byte_swap.rb +21 -7
  219. data/yard-stubs/ca_obj_fake.rb +3 -1
  220. data/yard-stubs/ca_obj_farray.rb +1 -1
  221. data/yard-stubs/ca_obj_field.rb +8 -6
  222. data/yard-stubs/ca_obj_refer.rb +7 -5
  223. data/yard-stubs/ca_obj_roll.rb +7 -6
  224. data/yard-stubs/ca_obj_shift.rb +2 -3
  225. data/yard-stubs/ca_obj_stride.rb +5 -7
  226. data/yard-stubs/ca_obj_tile.rb +1 -1
  227. data/yard-stubs/ca_obj_time.rb +43 -0
  228. data/yard-stubs/ca_obj_transpose.rb +1 -1
  229. data/yard-stubs/ca_obj_window.rb +26 -15
  230. data/yard-stubs/carray_access.rb +51 -4
  231. data/yard-stubs/carray_attribute.rb +26 -38
  232. data/yard-stubs/carray_cast.rb +118 -165
  233. data/yard-stubs/carray_class.rb +3 -4
  234. data/yard-stubs/carray_conversion.rb +6 -7
  235. data/yard-stubs/carray_copy.rb +2 -1
  236. data/yard-stubs/carray_count.rb +5 -3
  237. data/yard-stubs/carray_element.rb +4 -3
  238. data/yard-stubs/carray_limits.rb +100 -0
  239. data/yard-stubs/carray_loop.rb +0 -20
  240. data/yard-stubs/carray_mask.rb +59 -41
  241. data/yard-stubs/carray_math.rb +157 -100
  242. data/yard-stubs/carray_mathfunc.rb +415 -3
  243. data/yard-stubs/carray_median_percentile.rb +29 -11
  244. data/yard-stubs/carray_memory_view.rb +2 -2
  245. data/yard-stubs/carray_order.rb +67 -34
  246. data/yard-stubs/carray_random.rb +6 -6
  247. data/yard-stubs/carray_reduce.rb +353 -0
  248. data/yard-stubs/carray_rng.rb +92 -0
  249. data/yard-stubs/carray_scatter.rb +10 -2
  250. data/yard-stubs/carray_slab.rb +7 -4
  251. data/yard-stubs/carray_sort.rb +7 -6
  252. data/yard-stubs/carray_undef.rb +44 -5
  253. data/yard-stubs/ruby_carray.rb +75 -40
  254. metadata +62 -24
  255. data/CHANGELOG.v1.md +0 -126
  256. data/ext/carray_build_flags.h +0 -3
  257. data/ext/carray_config.h +0 -28
  258. data/ext/carray_data_type.c +0 -90
  259. data/ext/carray_kernels_bincmp.c +0 -6457
  260. data/ext/carray_kernels_binop.c +0 -31534
  261. data/ext/carray_kernels_init.c +0 -1734
  262. data/ext/carray_kernels_moncmp.c +0 -2104
  263. data/ext/carray_kernels_monop.c +0 -25337
  264. data/ext/carray_kernels_reduce_aggregate.c +0 -27545
  265. data/ext/carray_kernels_reduce_boolean.c +0 -1924
  266. data/ext/carray_kernels_reduce_cumulative.c +0 -11646
  267. data/ext/carray_kernels_reduce_extreme.c +0 -21631
  268. data/ext/carray_kernels_reduce_variance.c +0 -5981
  269. data/ext/carray_kernels_scan.c +0 -4302
  270. data/ext/carray_kernels_search.c +0 -37776
  271. data/ext/carray_kernels_sort.c +0 -10814
  272. data/ext/carray_kernels_triop.c +0 -1864
  273. data/lib/carray/construct.rb +0 -360
  274. data/lib/carray/data_type_extension.rb +0 -262
  275. data/lib/carray/data_type_limits.rb +0 -91
@@ -3,6 +3,128 @@ require "carray/distance_limit"
3
3
 
4
4
  class CArray
5
5
 
6
+ # The NaN cells of a key, nil for a key that has none. A NaN in an object
7
+ # key is the cell that differs from itself.
8
+ private def nearest_nan_cells(key)
9
+ return key.is_nan if key.float?
10
+ return key.ne(key) if key.data_type == CA_OBJECT && !key.face?
11
+ nil
12
+ end
13
+
14
+ # :round and tol: measure how far a key is from its neighbours. An
15
+ # object key whose values have no subtraction (a String) is ordered but
16
+ # has no distance: only :floor and :ceil apply to it.
17
+ private def nearest_refuse_distanceless(key, direction, limit, subject = "locate_nearest_addr")
18
+ return unless key.data_type == CA_OBJECT && !key.face?
19
+ return unless direction == :round || limit
20
+ value = key.to_a.find { |v| !v.equal?(UNDEF) && v == v }
21
+ return if value.nil? || value.respond_to?(:-)
22
+ asked = (direction == :round) ? "direction: :round" : "tol:"
23
+ raise ArgumentError,
24
+ "#{subject}: #{asked} measures a distance, and a key of #{value.class} values " \
25
+ "has none (#{value.class} has no -); use direction: :floor or :ceil without tol:"
26
+ end
27
+
28
+ # Whether each pair of keys lies farther apart than +limit+. A time key is
29
+ # measured in ticks of the unit both keys meet in, as an integer key is:
30
+ # two instants an int64 holds can lie farther apart than an int64 holds (a
31
+ # nanosecond key spanning more than 292 years).
32
+ private def nearest_beyond(a, b, limit)
33
+ time_key = (a.is_a?(CATime) || a.is_a?(CATimedelta)) && a.class == b.class
34
+ r = time_key && CATime::UnitAlgebra.ratio(limit.unit, CATime::UnitAlgebra.diff_unit(a.unit, b.unit))
35
+ return nearest_distance(a, b) > limit unless r
36
+ a, b = a.send(:in_common_unit_with, b)
37
+ threshold = (limit.value * r).floor
38
+ out = nearest_distance(a.ticks, b.ticks) > [threshold, 2**64 - 1].min
39
+ out[] = false if threshold >= 2**64 - 1
40
+ out
41
+ end
42
+
43
+ # How far apart two keys are. Integer keys are measured from the smaller to
44
+ # the larger, which fits an unsigned integer however far apart they are:
45
+ # the difference in their own type would wrap.
46
+ private def nearest_distance(a, b)
47
+ return (a - b).abs if a.face? || b.face?
48
+ t = a.send(:query_match_type, b)
49
+ return (a - b).abs if t == CA_OBJECT
50
+ a, b = a.to_type(t), b.to_type(t)
51
+ return (a - b).abs unless a.integer?
52
+ unless t == CA_UINT64
53
+ a, b = a.to_type(CA_INT64), b.to_type(CA_INT64)
54
+ end
55
+ (a.pmax(b) - a.pmin(b)).to_type(CA_UINT64)
56
+ end
57
+
58
+ # A key held as fixed-length bytes (raw fixlen, or a fixlen string) has
59
+ # no nearest: the search counts keys as numbers. A Face whose storage is
60
+ # a number (a time) is searched by that number.
61
+ # +subject+ and +remedy+ let a caller (CAFrame#join_asof) say it in its
62
+ # own words.
63
+ private def nearest_refuse_bytes(key, subject = nil, remedy = "match exact values with locate_addr")
64
+ # A Face whose cells encode the value (a const string, a categorical)
65
+ # is refused later by its own reconcile, which says why.
66
+ return unless key.is_a?(CArray) && key.__send__(:orderable_storage?)
67
+ storage = key.face? ? key.__send__(:face_storage) : key
68
+ return unless storage.data_type == CA_FIXLEN
69
+ subject ||= "locate_nearest_addr: a #{CArray::Inspector.type_label(key)} key"
70
+ raise CArray::DataTypeError,
71
+ "#{subject} is held as fixed-length bytes, which have no nearest; #{remedy}"
72
+ end
73
+
74
+ # The keys locate_nearest_addr orders by: the storage of the sorted
75
+ # reference and of the query, in one numeric type. A Face key is first
76
+ # brought into the reference's space (two time keys of different units
77
+ # into the finer of the two, which holds both exactly); plain keys meet at
78
+ # the type CArray.result_type gives, an integer pair of mixed sign at one
79
+ # that holds both.
80
+ private def nearest_keys(rs, q)
81
+ if rs.face? || q.face?
82
+ rs, q = rs.send(:in_common_unit_with, q) if rs.respond_to?(:to_unit) && q.class == rs.class && q.unit != rs.unit
83
+ q = rs.__send__(:reconcile_operand, q, "locate_nearest_addr")
84
+ rs = rs.__send__(:face_storage)
85
+ end
86
+ t = rs.send(:query_match_type, q)
87
+ rk = (rs.data_type == t) ? rs : rs.to_type(t)
88
+ qk = (q.data_type == t) ? q : q.to_type(t)
89
+ [rk, qk.flatten]
90
+ end
91
+
92
+ # For each query key, how many of the sorted reference keys are below it
93
+ # (inclusive: at or below). A numeric key is binary-searched in C; an
94
+ # object key is sorted together with the references, a tie putting the
95
+ # reference first when it counts, and counted against the references met
96
+ # before it.
97
+ private def nearest_count_below(rk, qk, inclusive)
98
+ return rk.send(:__count_below__, qk, inclusive) unless rk.data_type == CA_OBJECT
99
+ n, m = rk.elements, qk.elements
100
+ keys = CArray.concatenate([rk, qk])
101
+ tag = CArray.int8(n + m)
102
+ tag[0...n] = inclusive ? 0 : 1
103
+ tag[n...n+m] = inclusive ? 1 : 0
104
+ perm = CArray.sort_addr(keys, tag)
105
+ seen = perm.lt(n).cumsum.int64
106
+ query = perm.ge(n)
107
+ count = CArray.int64(m)
108
+ count[perm[query] - n] = seen[query]
109
+ count
110
+ end
111
+
112
+ # :round -- an exact match takes its first reference; otherwise the
113
+ # nearer of the two neighbours, the upper one on a tie. +lt+ counts the
114
+ # references below each key, so the upper neighbour is at lt and an exact
115
+ # match is the reference there.
116
+ private def nearest_round(rk, qk, lt)
117
+ lo = rk.project(lt - 1)
118
+ hi = rk.project(lt)
119
+ upper = nearest_distance(hi, qk).le(nearest_distance(qk, lo)).strip_mask(false)
120
+ upper[lo.is_masked] = true if lo.has_mask?
121
+ upper[hi.is_masked] = false if hi.has_mask?
122
+ upper[hi.eq(qk).strip_mask(false)] = true
123
+ si = lt - 1
124
+ si[upper] = lt[upper]
125
+ si
126
+ end
127
+
6
128
  # @!group Sorting and searching
7
129
 
8
130
  # @overload locate_addr(ref)
@@ -49,21 +171,21 @@ class CArray
49
171
  # @return [CArray] `:int64` flat addresses into `ref`, same shape as
50
172
  # `self`; unmatched cells are masked.
51
173
  # @raise [CArray::DataTypeError] when `self` and `ref` have no common data type.
52
- def locate_addr (ref)
174
+ def locate_addr(ref)
53
175
  # A time key (any Face that reconciles operands) against values that do
54
176
  # not -- Time, Date or String objects, a string column -- reads them as
55
177
  # values of its kind, whichever side they are on.
56
178
  if ref.is_a?(CArray) && ref.class == self.class &&
57
- respond_to?(:in_common_unit_with) && ref.unit != unit
179
+ respond_to?(:in_common_unit_with, true) && ref.unit != unit
58
180
  a, b = in_common_unit_with(ref)
59
181
  return a.locate_addr(b)
60
182
  end
61
183
  # They meet as a comparison does (comparable_pair).
62
- if respond_to?(:comparable_pair) && !ref.respond_to?(:comparable_pair)
63
- key, r = comparable_pair(ref)
184
+ if respond_to?(:comparable_pair, true) && !ref.respond_to?(:comparable_pair, true)
185
+ key, r = comparable_pair(ref, lookup: true)
64
186
  return key.locate_addr(r)
65
- elsif ref.respond_to?(:comparable_pair) && !respond_to?(:comparable_pair)
66
- r, key = ref.comparable_pair(self)
187
+ elsif ref.respond_to?(:comparable_pair, true) && !respond_to?(:comparable_pair, true)
188
+ r, key = ref.send(:comparable_pair, self, lookup: true)
67
189
  return key.locate_addr(r)
68
190
  end
69
191
  unless ref.is_a?(CArray) || ref.respond_to?(:to_ca)
@@ -92,7 +214,7 @@ class CArray
92
214
  q.send(:__locate_addr__, r)
93
215
  end
94
216
 
95
- # @overload locate_nearest_addr(ref, direction: :round, tolerance: nil)
217
+ # @overload locate_nearest_addr(ref, direction: :round, tol: nil)
96
218
  # Returns, for each element of `self`, the flat address into `ref` of
97
219
  # the nearest reference value. Continuous sibling of {#locate_addr}:
98
220
  # each cell is placed among the sorted reference values by comparing
@@ -105,11 +227,11 @@ class CArray
105
227
  # cell before the first value to that first value, and `:round`
106
228
  # matches either to the nearer end. The other side has no match
107
229
  # (`:floor` before the first value, `:ceil` after the last) and is
108
- # masked. Use `tolerance:` to refuse matches that are too far away.
230
+ # masked. Use `tol:` to refuse matches that are too far away.
109
231
  #
110
- # `tolerance:` (default `nil`) sets a maximum accepted absolute
232
+ # `tol:` (default `nil`) sets a maximum accepted absolute
111
233
  # distance between `self[i]` and its matched `ref` value. When
112
- # `|ref[addr] - self[i]| > tolerance`, the result cell is masked. Use
234
+ # `|ref[addr] - self[i]| > tol`, the result cell is masked. Use
113
235
  # for accuracy-controlled matching (e.g. "an observation snaps to a
114
236
  # time step only if within N seconds").
115
237
  #
@@ -126,26 +248,38 @@ class CArray
126
248
  # @param ref [CArray] 1-D reference grid to match against.
127
249
  # @param direction [Symbol] `:round`, `:floor`, or `:ceil` — rounding
128
250
  # applied to the fractional position.
129
- # @param tolerance [Numeric, String, CATimedelta::Element, nil] maximum
251
+ # @param tol [Numeric, String, CATimedelta::Element, nil] maximum
130
252
  # accepted `|self - ref|` distance; cells beyond this are masked.
131
253
  # For a time key it is a duration: a String such as `"10 minutes"` or
132
254
  # a CATimedelta value (a bare number is refused, since its length
133
255
  # would depend on the key's unit). `nil` disables the check.
134
256
  # @return [CArray] `:int64` flat addresses into `ref`, same shape as
135
- # `self`; cells with no match in the direction and beyond-tolerance
257
+ # `self`; cells with no match in the direction and beyond-`tol:`
136
258
  # cells are masked.
137
259
  # @raise [ArgumentError] when `direction` is not one of the accepted
138
- # symbols, `tolerance` is not a duration for a time key, or `:round` /
139
- # `tolerance` is asked of an object key whose values have no `-` (a
260
+ # symbols, `tol` is not a duration for a time key, or `:round` /
261
+ # `tol` is asked of an object key whose values have no `-` (a
140
262
  # String is ordered but has no distance).
141
- def locate_nearest_addr (ref, direction: :round, tolerance: nil)
263
+ def locate_nearest_addr(ref, direction: :round, tol: nil)
264
+ if ref.is_a?(Array)
265
+ CArray.send(:refuse_ruby_array, "locate_nearest_addr", "an array to search")
266
+ end
142
267
  unless [:round, :floor, :ceil].include?(direction)
143
268
  raise ArgumentError,
144
269
  "locate_nearest_addr: direction must be :round / :floor / " \
145
270
  ":ceil (got #{direction.inspect})"
146
271
  end
147
272
  [self, ref].each { |key| nearest_refuse_bytes(key) }
148
- limit = tolerance && DistanceLimit.read(tolerance, self, "tolerance:")
273
+ # The reference is sorted below, which would name sort_addr in the
274
+ # refusal of an unordered key.
275
+ [self, ref].each do |key|
276
+ next unless key.is_a?(CArray) && key.complex?
277
+ raise CArray::DataTypeError,
278
+ "locate_nearest_addr: a #{CArray::Inspector.type_label(key)} key " \
279
+ "has no order (complex numbers are not ordered); search by its " \
280
+ "real part, imaginary part or abs"
281
+ end
282
+ limit = tol && DistanceLimit.read(tol, self, "tol:")
149
283
  return CArray.int64(*shape) if elements == 0
150
284
  # A masked reference value matches nothing, as in locate_addr: sorting
151
285
  # puts the masked ones last, and only the others are searched. A NaN
@@ -186,128 +320,6 @@ class CArray
186
320
  idx
187
321
  end
188
322
 
189
- # The NaN cells of a key, nil for a key that has none. A NaN in an object
190
- # key is the cell that differs from itself.
191
- private def nearest_nan_cells(key)
192
- return key.is_nan if key.float?
193
- return key.ne(key) if key.data_type == CA_OBJECT && !key.face?
194
- nil
195
- end
196
-
197
- # :round and tolerance: measure how far a key is from its neighbours. An
198
- # object key whose values have no subtraction (a String) is ordered but
199
- # has no distance: only :floor and :ceil apply to it.
200
- private def nearest_refuse_distanceless(key, direction, limit, subject = "locate_nearest_addr")
201
- return unless key.data_type == CA_OBJECT && !key.face?
202
- return unless direction == :round || limit
203
- value = key.to_a.find { |v| !v.equal?(UNDEF) && v == v }
204
- return if value.nil? || value.respond_to?(:-)
205
- asked = (direction == :round) ? "direction: :round" : "tolerance:"
206
- raise ArgumentError,
207
- "#{subject}: #{asked} measures a distance, and a key of #{value.class} values " \
208
- "has none (#{value.class} has no -); use direction: :floor or :ceil without tolerance:"
209
- end
210
-
211
- # Whether each pair of keys lies farther apart than +limit+. A time key is
212
- # measured in ticks of the unit both keys meet in, as an integer key is:
213
- # two instants an int64 holds can lie farther apart than an int64 holds (a
214
- # nanosecond key spanning more than 292 years).
215
- private def nearest_beyond(a, b, limit)
216
- time_key = (a.is_a?(CATime) || a.is_a?(CATimedelta)) && a.class == b.class
217
- r = time_key && CATimeUnitAlgebra.ratio(limit.unit, CATimeUnitAlgebra.diff_unit(a.unit, b.unit))
218
- return nearest_distance(a, b) > limit unless r
219
- a, b = a.in_common_unit_with(b)
220
- threshold = (limit.value * r).floor
221
- out = nearest_distance(a.ticks, b.ticks) > [threshold, 2**64 - 1].min
222
- out[] = false if threshold >= 2**64 - 1
223
- out
224
- end
225
-
226
- # How far apart two keys are. Integer keys are measured from the smaller to
227
- # the larger, which fits an unsigned integer however far apart they are:
228
- # the difference in their own type would wrap.
229
- private def nearest_distance(a, b)
230
- return (a - b).abs if a.face? || b.face?
231
- t = a.send(:query_match_type, b)
232
- return (a - b).abs if t == CA_OBJECT
233
- a, b = a.to_type(t), b.to_type(t)
234
- return (a - b).abs unless a.integer?
235
- unless t == CA_UINT64
236
- a, b = a.to_type(CA_INT64), b.to_type(CA_INT64)
237
- end
238
- (a.pmax(b) - a.pmin(b)).to_type(CA_UINT64)
239
- end
240
-
241
- # A key held as fixed-length bytes (raw fixlen, or a fixlen string) has
242
- # no nearest: the search counts keys as numbers. A Face whose storage is
243
- # a number (a time) is searched by that number.
244
- # +subject+ and +remedy+ let a caller (CAFrame#join_asof) say it in its
245
- # own words.
246
- private def nearest_refuse_bytes(key, subject = nil, remedy = "match exact values with locate_addr")
247
- # A Face whose cells encode the value (a const string, a categorical)
248
- # is refused later by its own reconcile, which says why.
249
- return unless key.is_a?(CArray) && key.__send__(:orderable_storage?)
250
- storage = key.face? ? key.__send__(:face_storage) : key
251
- return unless storage.data_type == CA_FIXLEN
252
- subject ||= "locate_nearest_addr: a #{CArray::Inspector.type_label(key)} key"
253
- raise CArray::DataTypeError,
254
- "#{subject} is held as fixed-length bytes, which have no nearest; #{remedy}"
255
- end
256
-
257
- # The keys locate_nearest_addr orders by: the storage of the sorted
258
- # reference and of the query, in one numeric type. A Face key is first
259
- # brought into the reference's space (two time keys of different units
260
- # into the finer of the two, which holds both exactly); plain keys meet at
261
- # the type CArray.result_type gives, an integer pair of mixed sign at one
262
- # that holds both.
263
- private def nearest_keys(rs, q)
264
- if rs.face? || q.face?
265
- rs, q = rs.in_common_unit_with(q) if rs.respond_to?(:to_unit) && q.class == rs.class && q.unit != rs.unit
266
- q = rs.__send__(:reconcile_operand, q, "locate_nearest_addr")
267
- rs = rs.__send__(:face_storage)
268
- end
269
- t = rs.send(:query_match_type, q)
270
- rk = (rs.data_type == t) ? rs : rs.to_type(t)
271
- qk = (q.data_type == t) ? q : q.to_type(t)
272
- [rk, qk.flatten]
273
- end
274
-
275
- # For each query key, how many of the sorted reference keys are below it
276
- # (inclusive: at or below). A numeric key is binary-searched in C; an
277
- # object key is sorted together with the references, a tie putting the
278
- # reference first when it counts, and counted against the references met
279
- # before it.
280
- private def nearest_count_below(rk, qk, inclusive)
281
- return rk.send(:__count_below__, qk, inclusive) unless rk.data_type == CA_OBJECT
282
- n, m = rk.elements, qk.elements
283
- keys = CArray.concatenate([rk, qk])
284
- tag = CArray.int8(n + m)
285
- tag[0...n] = inclusive ? 0 : 1
286
- tag[n...n+m] = inclusive ? 1 : 0
287
- perm = CArray.sort_addr(keys, tag)
288
- seen = perm.lt(n).cumsum.int64
289
- query = perm.ge(n)
290
- count = CArray.int64(m)
291
- count[perm[query] - n] = seen[query]
292
- count
293
- end
294
-
295
- # :round -- an exact match takes its first reference; otherwise the
296
- # nearer of the two neighbours, the upper one on a tie. +lt+ counts the
297
- # references below each key, so the upper neighbour is at lt and an exact
298
- # match is the reference there.
299
- private def nearest_round(rk, qk, lt)
300
- lo = rk.project(lt - 1)
301
- hi = rk.project(lt)
302
- upper = nearest_distance(hi, qk).le(nearest_distance(qk, lo)).strip_mask(false)
303
- upper[lo.is_masked] = true if lo.has_mask?
304
- upper[hi.is_masked] = false if hi.has_mask?
305
- upper[hi.eq(qk).strip_mask(false)] = true
306
- si = lt - 1
307
- si[upper] = lt[upper]
308
- si
309
- end
310
-
311
323
  # @!endgroup
312
324
 
313
325
  end
@@ -44,7 +44,7 @@ class CArray
44
44
  # @param along [Integer] axis whose index enumerates the sub-arrays.
45
45
  # @return [CArray] shape-preserving copy of `self` with duplicated
46
46
  # sub-arrays masked.
47
- def mask_duplicates (axis: nil, along: nil)
47
+ def mask_duplicates(axis: nil, along: nil)
48
48
  reject_axis_with_along(axis, along, "mask_duplicates")
49
49
  if along
50
50
  keys = fibers_as_cells(along, "mask_duplicates")
@@ -1,19 +1,19 @@
1
1
  class CArray
2
2
 
3
- # @overload meshgrid(*axes, indexing: "xy", copy: true, sparse: false)
3
+ # @overload meshgrid(*axes, indexing: :xy, copy: true, sparse: false)
4
4
  # Returns coordinate matrices built from 1-D coordinate vectors.
5
5
  #
6
6
  # Given N 1-D vectors, produces N arrays each broadcasting one
7
7
  # input axis across the others. Useful for evaluating a function
8
8
  # on a grid.
9
9
  #
10
- # With `indexing: "xy"` (default) the first two axes are swapped
10
+ # With `indexing: :xy` (default) the first two axes are swapped
11
11
  # in the output shape (matrix-style convention): `meshgrid(x, y)`
12
12
  # gives outputs of shape `[y.elements, x.elements]`. With
13
- # `indexing: "ij"` input order is preserved:
14
- # `meshgrid(x, y, indexing: "ij")` gives outputs of shape
13
+ # `indexing: :ij` input order is preserved:
14
+ # `meshgrid(x, y, indexing: :ij)` gives outputs of shape
15
15
  # `[x.elements, y.elements]`. For more than two axes only the
16
- # first two are swapped under `"xy"`; the remaining axes follow
16
+ # first two are swapped under `:xy`; the remaining axes follow
17
17
  # input order in both modes.
18
18
  #
19
19
  # When `copy` is true (default) each output is a materialised
@@ -25,34 +25,46 @@ class CArray
25
25
  # arguments and returns the block's value.
26
26
  #
27
27
  # Each axis goes through {CArray.wrap_readonly}, so a coordinate
28
- # vector may be given as anything that entry point accepts (a
29
- # CArray, an Array, a Range, a Numeric, a MemoryView producer, an
30
- # object answering `ca` / `to_ca`); its own data type is kept.
28
+ # vector may be given as a CArray, a Range, a MemoryView producer or
29
+ # an object answering `to_ca`; its own data type is kept. A Ruby
30
+ # Array has no data type and is refused: make it a CArray of the type
31
+ # you mean (`CA_FLOAT64([0.5, 1.5])`).
31
32
  #
32
- # @param axes [Array<CArray, Array, Object>] 1-D coordinate vectors.
33
- # @param indexing [String] `"xy"` or `"ij"`.
33
+ # @param axes [Array<CArray, Object>] 1-D coordinate vectors.
34
+ # @param indexing [Symbol] `:xy` or `:ij`.
34
35
  # @param copy [Boolean] materialise each output when true.
35
36
  # @param sparse [Boolean] return broadcast-on-demand views when true.
36
37
  # @yieldparam grids [Array<CArray>] the resulting coordinate arrays.
37
38
  # @return [Array<CArray>] the coordinate arrays, or the block's
38
39
  # return value.
39
- # @raise [ArgumentError] when `indexing` is neither `"xy"` nor `"ij"`,
40
+ # @raise [ArgumentError] when `indexing` is neither `:xy` nor `:ij`,
40
41
  # or when a coordinate vector is not 1-D.
42
+ # @raise [TypeError] when `indexing` is not a Symbol, or a coordinate
43
+ # vector is a Ruby Array.
41
44
  # @example
42
45
  # x = CA_FLOAT64([1.0, 2.0, 3.0])
43
46
  # y = CA_FLOAT64([10.0, 20.0])
44
47
  # xx, yy = CArray.meshgrid(x, y)
45
48
  # xx.shape # => [2, 3]
46
49
  # yy.to_a # => [[10.0, 10.0, 10.0], [20.0, 20.0, 20.0]]
47
- def self.meshgrid (*axes, indexing: "xy", copy: true, sparse: false, &block)
48
- unless %w[xy ij].include?(indexing)
49
- raise ArgumentError, %{indexing option should be one of "xy" and "ij"}
50
+ def self.meshgrid(*axes, indexing: :xy, copy: true, sparse: false, &block)
51
+ copy = CArray.send(:bool_arg, copy, "copy", "meshgrid")
52
+ sparse = CArray.send(:bool_arg, sparse, "sparse", "meshgrid")
53
+ unless indexing.is_a?(Symbol)
54
+ raise TypeError, "meshgrid: indexing must be a Symbol (got #{indexing.class})"
55
+ end
56
+ unless %i[xy ij].include?(indexing)
57
+ raise ArgumentError,
58
+ "meshgrid: unknown indexing #{indexing.inspect} (expected :xy or :ij)"
50
59
  end
51
60
 
52
61
  # Each axis is negotiable, so no target type is imposed here; a
53
62
  # CArray comes back as itself and anything else is brought in with
54
63
  # its own data type.
55
64
  axes = axes.map.with_index do |axis, k|
65
+ if axis.is_a?(Array)
66
+ CArray.send(:refuse_ruby_array, "meshgrid", "a coordinate vector")
67
+ end
56
68
  a = CArray.wrap_readonly(axis)
57
69
  unless a.ndim == 1
58
70
  raise ArgumentError,
@@ -66,9 +78,9 @@ class CArray
66
78
  ndim = axes.size
67
79
 
68
80
  # dest[k] = output axis position that input axis k populates.
69
- # "xy" swaps the first two; everything else is in input order.
81
+ # :xy swaps the first two; everything else is in input order.
70
82
  dest = (0...ndim).to_a
71
- dest[0], dest[1] = 1, 0 if indexing == "xy" && ndim >= 2
83
+ dest[0], dest[1] = 1, 0 if indexing == :xy && ndim >= 2
72
84
 
73
85
  # Output shape: each output axis i takes its size from the input
74
86
  # axis that maps there.
@@ -1,5 +1,66 @@
1
1
  class CArray
2
2
 
3
+ private def mode_answered(axis)
4
+ if complex?
5
+ raise CArray::DataTypeError,
6
+ "mode: the modes are listed in ascending order, and a " \
7
+ "#{data_type_name} value has no order (complex numbers are not " \
8
+ "ordered); is_mode marks the cells that hold a mode"
9
+ end
10
+ return __mode_flat if axis.nil?
11
+ k = normalize_axis(axis, "mode")
12
+
13
+ # Numeric: the C frequency-table kernel emits the ragged Array<CArray>
14
+ # directly (reduced CArrays, self.shape with axis k dropped). A 1-D input
15
+ # reduces to length-1 CArrays, unwrapped to scalars like flat quantile.
16
+ unless data_type == CA_OBJECT || data_type == CA_FIXLEN
17
+ cols = __mode_axis__(k)
18
+ return ndim == 1 ? cols.map { |col| col[0] } : cols
19
+ end
20
+
21
+ # Object / fixlen (rare): per-fiber Ruby path, reusing the flat mode as the
22
+ # single source of what counts as a mode. Move axis k to the innermost
23
+ # position and fold the rest to one outer axis, so each row is a fiber.
24
+ perm = (0...ndim).to_a
25
+ perm.delete(k)
26
+ perm << k
27
+ a2 = (ndim == 1) ? self : transpose(*perm).copy # (outer..., L)
28
+ outer = a2.shape[0...-1]
29
+ m = outer.empty? ? 1 : outer.inject(:*)
30
+ flat2 = a2.reshape(m, a2.shape[-1])
31
+ lists = Array.new(m) { |r| flat2[r, nil].__send__(:__mode_flat).to_a }
32
+
33
+ # K = widest fiber's mode count. Emit K reduced CArrays (like quantile's
34
+ # per-axis Array<CArray>): slot j holds each fiber's j-th smallest mode,
35
+ # masked where a fiber has fewer than j+1 modes. Stack them to get the
36
+ # rectangular mask-padded form: CArray.stack(result, axis: k).
37
+ kk = lists.map(&:size).max || 0
38
+ (0...kk).map do |j|
39
+ # Take the column shape from self rather than building it from data_type:
40
+ # it carries the element width a fixlen array needs, and it keeps a Face
41
+ # (a time array), whose cells then accept the surface values in `lists`.
42
+ col = flat2[nil, 0].copy
43
+ col[] = UNDEF
44
+ m.times { |r| col[r] = lists[r][j] if j < lists[r].size }
45
+ outer.empty? ? col[0] : col.reshape(*outer)
46
+ end
47
+ end
48
+
49
+ # Flat mode: the distinct modal values ascending, 1-D CArray of self's data type.
50
+ # The single source of what counts as a mode (per-axis reuses it per fiber).
51
+ # The distinct values with the maximum count, read from the frequency table
52
+ # (value_counts, which covers numeric / object / fixlen), then sorted
53
+ # ascending. value_counts already skips masked cells.
54
+ private def __mode_flat
55
+ values, counts = value_counts
56
+ return values if values.elements == 0
57
+ modes = values[counts.eq(counts.max)]
58
+ # Records are sorted only by the members their struct declares in
59
+ # order_by:; without one the modes stay in first-appearance order.
60
+ return modes if is_a?(CARecord) && data_class.order_by.nil?
61
+ modes.sort
62
+ end
63
+
3
64
  # @overload is_mode(axis: nil)
4
65
  # Returns a shape-preserving boolean CArray, true at every cell
5
66
  # that holds a modal value — a value whose occurrence count equals
@@ -32,7 +93,7 @@ class CArray
32
93
  # @param axis [Integer, nil] axis to take the mode along; `nil` uses
33
94
  # the whole array.
34
95
  # @return [CArray] boolean CArray of `self.shape`.
35
- def is_mode (axis: nil)
96
+ def is_mode(axis: nil)
36
97
  # Per-fiber two-pass frequency table (C __is_mode__), one lane per data type
37
98
  # family (numeric widen / NaN collapse, object rb_hash + rb_eql, fixlen
38
99
  # byte-hash + memcmp). Ties are all marked; masked cells stay false.
@@ -70,74 +131,13 @@ class CArray
70
131
  #
71
132
  # @param axis [Integer, nil] axis to take the mode along; `nil` uses
72
133
  # the whole array.
73
- # @return [CArray, Array<CArray>] 1-D CArray (flat) or an Array of
74
- # reduced CArrays, one per mode rank (per-axis).
75
- def mode (axis: nil)
134
+ # @return [CArray, Array<CArray>, Array<Object>] 1-D CArray (flat) or an
135
+ # Array of reduced CArrays, one per mode rank (per-axis). Along the
136
+ # only axis of a 1-D array each reduced value is a single value, as
137
+ # any reduction of every axis gives one, so the Array holds values.
138
+ def mode(axis: nil)
76
139
  # An error from the methods mode is made of (sort, ...) names mode.
77
140
  CArray.__name_errors_after_method__(:mode) { mode_answered(axis) }
78
141
  end
79
142
 
80
- private def mode_answered (axis)
81
- if complex?
82
- raise CArray::DataTypeError,
83
- "mode: the modes are listed in ascending order, and a " \
84
- "#{data_type_name} value has no order (complex numbers are not " \
85
- "ordered); is_mode marks the cells that hold a mode"
86
- end
87
- return __mode_flat if axis.nil?
88
- k = normalize_axis(axis, "mode")
89
-
90
- # Numeric: the C frequency-table kernel emits the ragged Array<CArray>
91
- # directly (reduced CArrays, self.shape with axis k dropped). A 1-D input
92
- # reduces to length-1 CArrays, unwrapped to scalars like flat quantile.
93
- unless data_type == CA_OBJECT || data_type == CA_FIXLEN
94
- cols = __mode_axis__(k)
95
- return ndim == 1 ? cols.map { |col| col[0] } : cols
96
- end
97
-
98
- # Object / fixlen (rare): per-fiber Ruby path, reusing the flat mode as the
99
- # single source of what counts as a mode. Move axis k to the innermost
100
- # position and fold the rest to one outer axis, so each row is a fiber.
101
- perm = (0...ndim).to_a
102
- perm.delete(k)
103
- perm << k
104
- a2 = (ndim == 1) ? self : transpose(*perm).copy # (outer..., L)
105
- outer = a2.shape[0...-1]
106
- m = outer.empty? ? 1 : outer.inject(:*)
107
- flat2 = a2.reshape(m, a2.shape[-1])
108
- lists = Array.new(m) { |r| flat2[r, nil].__send__(:__mode_flat).to_a }
109
-
110
- # K = widest fiber's mode count. Emit K reduced CArrays (like quantile's
111
- # per-axis Array<CArray>): slot j holds each fiber's j-th smallest mode,
112
- # masked where a fiber has fewer than j+1 modes. Stack them to get the
113
- # rectangular mask-padded form: CArray.stack(result, axis: k).
114
- kk = lists.map(&:size).max || 0
115
- (0...kk).map do |j|
116
- # Take the column shape from self rather than building it from data_type:
117
- # it carries the element width a fixlen array needs, and it keeps a Face
118
- # (a time array), whose cells then accept the surface values in `lists`.
119
- col = flat2[nil, 0].copy
120
- col[] = UNDEF
121
- m.times { |r| col[r] = lists[r][j] if j < lists[r].size }
122
- outer.empty? ? col[0] : col.reshape(*outer)
123
- end
124
- end
125
-
126
- private
127
-
128
- # Flat mode: the distinct modal values ascending, 1-D CArray of self's data type.
129
- # The single source of what counts as a mode (per-axis reuses it per fiber).
130
- # The distinct values with the maximum count, read from the frequency table
131
- # (value_counts, which covers numeric / object / fixlen), then sorted
132
- # ascending. value_counts already skips masked cells.
133
- def __mode_flat
134
- values, counts = value_counts
135
- return values if values.elements == 0
136
- modes = values[counts.eq(counts.max)]
137
- # Records are sorted only by the members their struct declares in
138
- # order_by:; without one the modes stay in first-appearance order.
139
- return modes if is_a?(CARecord) && data_class.order_by.nil?
140
- modes.sort
141
- end
142
-
143
143
  end
@@ -9,7 +9,8 @@ class CArray
9
9
  # and {#value_counts} tabulates, `nunique` just counts.
10
10
  #
11
11
  # With `axis: nil` (default) it counts distinct values across the
12
- # whole array and returns an Integer. With `axis: k` it counts per
12
+ # whole array and returns an Integer (with `keep_axis: true`, a
13
+ # `CA_INT64` CArray with every axis of length 1, as `sum` gives it). With `axis: k` it counts per
13
14
  # fiber along axis `k`, returning a reduced `CA_INT64` CArray
14
15
  # (shape = self.shape with axis `k` removed; `keep_axis: true` keeps
15
16
  # it as a length-1 axis). An Array of axes counts over all of them
@@ -29,10 +30,10 @@ class CArray
29
30
  #
30
31
  # @param axis [Integer, Array<Integer>, nil] axis or axes to count
31
32
  # over; `nil` counts over the whole array.
32
- # @param keep_axis [Boolean] when `axis` is given, keep the reduced
33
- # axis as a length-1 axis instead of dropping it.
34
- # @return [Integer, CArray] Integer for `axis: nil` or every axis,
35
- # otherwise a reduced `CA_INT64` CArray.
33
+ # @param keep_axis [Boolean] keep the reduced axes as length-1 axes
34
+ # instead of dropping them.
35
+ # @return [Integer, CArray] Integer for `axis: nil` or every axis
36
+ # (without `keep_axis:`), otherwise a reduced `CA_INT64` CArray.
36
37
  # @overload nunique(along: k)
37
38
  # Returns how many distinct **sub-arrays** `self` holds, comparing
38
39
  # whole sub-arrays rather than cells: `along: k` names the axis
@@ -50,7 +51,7 @@ class CArray
50
51
  #
51
52
  # @param along [Integer] axis whose index enumerates the sub-arrays.
52
53
  # @return [Integer] the number of distinct sub-arrays.
53
- def nunique (axis: nil, keep_axis: false, along: nil)
54
+ def nunique(axis: nil, keep_axis: false, along: nil)
54
55
  reject_axis_with_along(axis, along, "nunique")
55
56
  return fibers_as_cells(along, "nunique").nunique if along
56
57
  # Per-fiber single-pass seen-set hash (C __nunique__), one lane per data type
@@ -60,7 +61,8 @@ class CArray
60
61
  if axis.nil?
61
62
  # Whole-array distinct count: flatten to 1-D and reduce its only axis,
62
63
  # then read the single reduced cell as an Integer.
63
- flatten.send(:__nunique__, 0, false)[0]
64
+ count = flatten.send(:__nunique__, 0, false)[0]
65
+ keep_axis ? CArray.int64(*([1] * ndim)).fill(count) : count
64
66
  else
65
67
  axes = Array(axis).map { |a| normalize_axis(a, "nunique") }
66
68
  counts = __nunique__(axes, keep_axis)