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
data/lib/carray/stack.rb CHANGED
@@ -60,7 +60,7 @@ class CArray
60
60
  def self.stack (list, axis: 0, data_type: nil)
61
61
  raise ArgumentError, "stack: list must not be empty" if list.empty?
62
62
  axis = 0 if axis.nil?
63
- list = CArray.promote_list(list, data_type: data_type)
63
+ list = promote_list_for("stack", list, data_type: data_type)
64
64
  axis = CArray.normalize_axis(axis, list[0].ndim + 1, "stack")
65
65
  CAStack.new(list, axis: axis) # CAStack.new does Face lift internally
66
66
  end
@@ -101,16 +101,19 @@ class CArray
101
101
  raise ArgumentError, "meld: entries must be CArray (got #{first.class})"
102
102
  end
103
103
  axis_norm = CArray.normalize_axis(axis, first.ndim, "meld")
104
- arrays = CArray.promote_list(arrays, data_type: data_type)
104
+ arrays = promote_list_for("meld", arrays, data_type: data_type)
105
105
  # Flatten nested CAMeld inputs that share our meld axis: they already
106
106
  # describe a segment sequence, so absorbing their parents keeps chain
107
107
  # depth at 1 (avoids 2-level xfer_all / reduce chains through the
108
108
  # intermediate CAMeld). A CAMeld with a different meld_axis is left
109
- # intact — its segment structure is orthogonal.
110
- if arrays.any? { |a| a.is_a?(CAMeld) && a.meld_axis == axis_norm }
111
- arrays = arrays.flat_map { |a|
112
- a.is_a?(CAMeld) && a.meld_axis == axis_norm ? a.parents : [a]
113
- }
109
+ # intact — its segment structure is orthogonal. So is a read-only one
110
+ # (frozen or flagged): writes through it are refused, and absorbing it
111
+ # would drop that. The mask of a meld is a CAMeld with no parents of
112
+ # its own; it is passed on, to be refused as a part.
113
+ absorbed = ->(a) { a.is_a?(CAMeld) && a.meld_axis == axis_norm &&
114
+ !a.read_only? && !a.mask_array? }
115
+ if arrays.any?(&absorbed)
116
+ arrays = arrays.flat_map { |a| absorbed.(a) ? a.parents : [a] }
114
117
  end
115
118
  CAMeld.new(arrays, axis: axis_norm)
116
119
  end
@@ -180,7 +183,7 @@ class CArray
180
183
  "montage: tdim product (#{expected}) must equal list size (#{list.size})"
181
184
  end
182
185
 
183
- list = CArray.promote_list(list, data_type: data_type)
186
+ list = promote_list_for("montage", list, data_type: data_type)
184
187
  parent_shape = list[0].shape
185
188
  ntile = tdim.size
186
189
  nparent = parent_shape.size
@@ -291,10 +294,19 @@ class CAStack
291
294
  # preserving `self.k_axis`. Distinct from `CArray#stack`, which
292
295
  # always treats `self` as a single parent of a new K-stack.
293
296
  # @param others [Array<CArray>] extra parents to append.
297
+ # A read-only stack hands on read-only views of its parents, so
298
+ # writes into its cells stay refused.
294
299
  # @return [CAStack]
295
300
  # @raise [ArgumentError] when no `others` are given.
296
301
  def append (*others)
297
302
  raise ArgumentError, "append: at least one parent required" if others.empty?
298
- CArray.stack(self.parents + others, axis: self.k_axis)
303
+ if mask_array?
304
+ raise ArgumentError, "append: a mask array can have no mask and can not be a part"
305
+ end
306
+ mine = self.parents
307
+ if read_only?
308
+ mine = mine.map { |p| p[].tap(&:set_read_only_flag) }
309
+ end
310
+ CArray.stack(mine + others, axis: self.k_axis)
299
311
  end
300
312
  end
data/lib/carray/string.rb CHANGED
@@ -115,22 +115,22 @@ class CAString
115
115
  def mod (other) ; as_text(super) ; end
116
116
  # The later String of each cell and `other`, cell by cell.
117
117
  # @return [CAString]
118
- def pmax (other) ; as_text(super) ; end
118
+ def pmax (other) ; refuse_unordered_operands("pmax", other) ; as_text(super) ; end
119
119
  # The earlier String of each cell and `other`, cell by cell.
120
120
  # @return [CAString]
121
- def pmin (other) ; as_text(super) ; end
121
+ def pmin (other) ; refuse_unordered_operands("pmin", other) ; as_text(super) ; end
122
122
  # Another name of {#pmax} (a String has no NaN to let win).
123
123
  # @return [CAString]
124
- def maximum (other) ; as_text(super) ; end
124
+ def maximum (other) ; refuse_unordered_operands("maximum", other) ; as_text(super) ; end
125
125
  # Another name of {#pmin}.
126
126
  # @return [CAString]
127
- def minimum (other) ; as_text(super) ; end
127
+ def minimum (other) ; refuse_unordered_operands("minimum", other) ; as_text(super) ; end
128
128
  # Another name of {#pmax}.
129
129
  # @return [CAString]
130
- def fmax (other) ; as_text(super) ; end
130
+ def fmax (other) ; refuse_unordered_operands("fmax", other) ; as_text(super) ; end
131
131
  # Another name of {#pmin}.
132
132
  # @return [CAString]
133
- def fmin (other) ; as_text(super) ; end
133
+ def fmin (other) ; refuse_unordered_operands("fmin", other) ; as_text(super) ; end
134
134
 
135
135
  # The String a blank cell holds: the cell a fresh {#template} gives and
136
136
  # the one {#shift} fills by default. Frozen, because every blank cell
@@ -44,6 +44,25 @@ class CArray
44
44
  end
45
45
  private :string_map
46
46
 
47
+ # An ordering (pmax and its kin, clip) with a value that is not a String
48
+ # is refused as String#< refuses it. nil (no bound, for clip), UNDEF,
49
+ # an Array and a CArray are left to the operation.
50
+ def refuse_unordered_operands (verb, *operands)
51
+ operands.each do |v|
52
+ next if v.nil? || v.is_a?(String) || v.is_a?(Array) || v.is_a?(CArray) || UNDEF.equal?(v)
53
+ name = v.is_a?(Symbol) ? v.inspect : v.class
54
+ raise ArgumentError, "#{verb}: comparison of String with #{name} failed"
55
+ end
56
+ end
57
+ private :refuse_unordered_operands
58
+
59
+ # Clips the strings in byte order (see {CArray#clip}); a bound that is
60
+ # not a String is refused.
61
+ def clip (min, max = nil, *rest, **kw)
62
+ refuse_unordered_operands("clip", min, max)
63
+ super
64
+ end
65
+
47
66
  # ---- transforms (String result -> CAString) --------------------------
48
67
 
49
68
  # Per-cell `String#upcase`.
@@ -93,7 +112,7 @@ class CArray
93
112
  def encode (*a) ; string_map { |s| s.encode(*a) } ; end
94
113
  # Per-cell `String#force_encoding`.
95
114
  # @return [CAString] shape and mask of `self` preserved.
96
- def force_encoding (e) ; string_map { |s| s.force_encoding(e) } ; end
115
+ def force_encoding (e) ; string_map { |s| s.dup.force_encoding(e) } ; end
97
116
  # Per-cell `String#scrub`.
98
117
  # @return [CAString] shape and mask of `self` preserved.
99
118
  def scrub () ; string_map { |s| s.scrub } ; end
@@ -221,14 +240,16 @@ class CArray
221
240
  end
222
241
  entity = CArray.new(CA_FIXLEN, shape, :bytes => width)
223
242
  values.each_with_index { |s, i| entity[i] = s.nil? ? UNDEF : s }
224
- CAFixlenString.wrap(entity)
243
+ text = respond_to?(:encoding) ? encoding : CAFixlenString.__send__(:encoding_of_strings, values)
244
+ CAFixlenString.wrap(entity, encoding: text)
225
245
  end
226
246
 
227
247
  # Self (zero-copy) when already a {CAConstString} of the same encoding;
228
248
  # otherwise materialises a compact column.
229
- # @param encoding [Encoding] column encoding.
249
+ # @param encoding [Encoding] column encoding; defaults to the encoding
250
+ # the array carries, and to UTF-8 for one that carries none.
230
251
  # @return [CAConstString]
231
- def to_const_string (encoding: Encoding::UTF_8)
252
+ def to_const_string (encoding: respond_to?(:encoding) ? self.encoding : Encoding::UTF_8)
232
253
  if is_a?(CAConstString) && encoding == self.encoding
233
254
  return self
234
255
  end
@@ -699,7 +699,10 @@ class CAStruct::Builder # :nodoc:
699
699
  # Declares a bitfield member. Bits accumulate within the
700
700
  # current byte; when a byte member follows, the cursor rounds
701
701
  # up to the next byte boundary. Only supported in `:struct`
702
- # (not `:union`) and always requires a name.
702
+ # (not `:union`) and always requires a name. A member of more
703
+ # than one bit keeps the low `bits` bits of an Integer written to
704
+ # it (300 into 3 bits is 4), through an element or the member's
705
+ # column alike; a one-bit member is boolean.
703
706
  # @param name [Symbol, String] member name.
704
707
  # @param bits [Integer] bit width in `1..64`.
705
708
  # @return [void]
data/lib/carray/time.rb CHANGED
@@ -623,8 +623,57 @@ module CATimeOperandValues
623
623
  in_common_unit_with(lifted)
624
624
  end
625
625
 
626
+ # @overload pmax(other)
627
+ # The later time, or the longer duration, of each cell and `other`, cell
628
+ # by cell: `other` is an array of the same kind and shape, or one value
629
+ # (for a time a {CATime::Element}, a `Time`, a `Date`, `"2024-01-02"`; for
630
+ # a duration a {CATimedelta::Element}, `"3 days"`) for every cell. The
631
+ # two meet as a comparison does, so the result is in `self`'s unit when
632
+ # `other` sits on its grid and in the finer unit the two share otherwise.
633
+ # A masked cell on either side gives a masked cell.
634
+ # @param other [CATime, CATimedelta, CATime::Element, CATimedelta::Element, Time, Date, String]
635
+ # @return [CATime, CATimedelta]
636
+ # @raise [TypeError] when `other` is not of this kind.
637
+ def pmax (other)
638
+ pick_by_order(other) { |a, b| a < b }
639
+ end
640
+
641
+ # @overload pmin(other)
642
+ # The earlier time, or the shorter duration; see {#pmax}.
643
+ # @param other [CATime, CATimedelta, CATime::Element, CATimedelta::Element, Time, Date, String]
644
+ # @return [CATime, CATimedelta]
645
+ # @raise [TypeError] when `other` is not of this kind.
646
+ def pmin (other)
647
+ pick_by_order(other) { |a, b| a > b }
648
+ end
649
+
650
+ # A time or a duration has no NaN, so maximum / minimum (which let a NaN
651
+ # win) are pmax / pmin, and fmax / fmin are their other names.
652
+ alias_method :maximum, :pmax
653
+ alias_method :minimum, :pmin
654
+ alias_method :fmax, :pmax
655
+ alias_method :fmin, :pmin
656
+
626
657
  private
627
658
 
659
+ # `other` where the block says self's cell loses to it, else self's cell.
660
+ def pick_by_order (other)
661
+ return copy.tap { |out| out[] = UNDEF } if UNDEF.equal?(other)
662
+ a, b = comparable_pair(other)
663
+ b = b[0] unless other.is_a?(CArray) || other.is_a?(Array)
664
+ yield(a, b).then_else(b, a)
665
+ end
666
+
667
+ # Both branches of a selection in the unit a comparison meets them in, so
668
+ # the finer unit wins whichever branch it is.
669
+ def branches_in_common (x, y)
670
+ other, base = y.is_a?(CArray) && !y.scalar? ? [x, y] : [y, x]
671
+ return [x, y] if other.nil? || UNDEF.equal?(other)
672
+ a, b = base.comparable_pair(other)
673
+ b = b[0] unless other.is_a?(CArray) && !other.scalar?
674
+ base.equal?(y) ? [b, a] : [a, b]
675
+ end
676
+
628
677
  # The operand as an array of this kind in its own unit: one value read as
629
678
  # it is written, an Array or an array of another kind read value by value
630
679
  # in the unit they share, an UNDEF or a masked cell kept masked.
@@ -739,13 +788,19 @@ class CATime
739
788
  # @return [String]
740
789
  def to_s
741
790
  case unit.base
742
- when :Y then to_date.strftime("%Y")
743
- when :M then to_date.strftime("%Y-%m")
744
- when :W, :D then to_date.strftime("%Y-%m-%d")
745
- else to_time.iso8601(fractional_second_digits) # :h .. :as (time shown)
791
+ when :Y then signed_past_four_digits(to_date.strftime("%Y"))
792
+ when :M then signed_past_four_digits(to_date.strftime("%Y-%m"))
793
+ when :W, :D then signed_past_four_digits(to_date.strftime("%Y-%m-%d"))
794
+ else signed_past_four_digits(to_time.iso8601(fractional_second_digits)) # :h .. :as (time shown)
746
795
  end
747
796
  end
748
797
 
798
+ # A year past four digits carries its sign, which is what tells it from a
799
+ # date written without separators when the text is read back.
800
+ private def signed_past_four_digits (text)
801
+ text.start_with?("-") || to_date.year < 10000 ? text : "+#{text}"
802
+ end
803
+
749
804
  # @return [String] the instant plus its storage unit.
750
805
  def inspect
751
806
  tag = unit.count == 1 ? "#{value}#{unit.base}" : "#{value} @ #{unit}"
@@ -810,7 +865,7 @@ class CATime
810
865
  # @raise [TypeError, ArgumentError] on a non-timedelta operand, or a
811
866
  # pair that has no answer on self's grid.
812
867
  def +(td)
813
- shifted_by_duration(td, 1)
868
+ shifted_by_duration(one_step_of(td), 1)
814
869
  end
815
870
 
816
871
  # @overload -(other)
@@ -831,6 +886,10 @@ class CATime
831
886
  shifted_by_duration(other, -1)
832
887
  when CATime
833
888
  -(other - self)
889
+ when String, Time, Date
890
+ step = other.is_a?(String) ? one_step_of(other) : other
891
+ return shifted_by_duration(step, -1) unless step.equal?(other)
892
+ (CATime.wrap(CA_INT64([value]), unit: unit) - other)[0]
834
893
  else
835
894
  raise TypeError, "CATime::Element - #{other.class} is not allowed"
836
895
  end
@@ -851,6 +910,18 @@ class CATime
851
910
  # the duration is converted into it (truncated toward zero when finer; a
852
911
  # month or year duration on a fixed grid moves the date by months).
853
912
  # Mirrors the array CATime +/-.
913
+ # A String naming a duration ("3 days") as one step of it; anything else
914
+ # as it is.
915
+ def one_step_of(x)
916
+ return x unless x.is_a?(String)
917
+ res = begin
918
+ CATime::Resolution.parse(x)
919
+ rescue ArgumentError
920
+ return x
921
+ end
922
+ CATimedelta::Element.new(1, res)
923
+ end
924
+
854
925
  def shifted_by_duration(td, sign)
855
926
  # An array of durations gives an array of instants, anchored here.
856
927
  return sign > 0 ? td + self : (-td) + self if td.is_a?(CATimedelta)
@@ -1005,6 +1076,20 @@ class CATimedelta
1005
1076
  # @return [CATimedelta::Element]
1006
1077
  def -(other) = combined_with_duration(other, -1)
1007
1078
 
1079
+ # @return [CATimedelta::Element] this duration with its sign reversed.
1080
+ def -@ = Element.new(-value, unit)
1081
+
1082
+ # @return [CATimedelta::Element] the magnitude of this duration.
1083
+ def abs = Element.new(value.abs, unit)
1084
+
1085
+ # @overload coerce(number)
1086
+ # Lets a duration stand on the right of a number, so `2 * d` is `d * 2`.
1087
+ # @param number [Numeric]
1088
+ # @return [Array]
1089
+ def coerce (number)
1090
+ [LeftFactor.new(number), self]
1091
+ end
1092
+
1008
1093
  # @overload *(n)
1009
1094
  # Returns this duration scaled by an Integer.
1010
1095
  # @param n [Integer]
@@ -1122,6 +1207,9 @@ class CATime
1122
1207
  # @raise [RangeError] when the widened ticks overflow int64.
1123
1208
  def to_unit(unit)
1124
1209
  to = CATime::Resolution.parse(unit)
1210
+ # The conversion hands back the storage itself when the unit does not
1211
+ # change; the result is a new array whichever unit is asked for.
1212
+ return face_storage.copy.time(unit: to) if to == self.unit
1125
1213
  CATimeUnitAlgebra.convert_instant_floor(face_storage, self.unit, to).time(unit: to)
1126
1214
  end
1127
1215
 
@@ -1200,6 +1288,13 @@ class CATime
1200
1288
  end
1201
1289
  end
1202
1290
 
1291
+ # The word form of {#+}.
1292
+ # @return [CATime]
1293
+ alias_method :add, :+
1294
+ # The word form of {#-}.
1295
+ # @return [CATime, CATimedelta]
1296
+ alias_method :sub, :-
1297
+
1203
1298
  # Whether a duration moves this time by calendar months: a month or year
1204
1299
  # duration on a time whose grid is fixed-length. A time on a month or year
1205
1300
  # grid adds it as months already, and a fixed duration on a calendar grid
@@ -1217,44 +1312,6 @@ class CATime
1217
1312
  CATimeUnitAlgebra.shift_months(face_storage, unit, months).time(unit: unit)
1218
1313
  end
1219
1314
 
1220
- # @overload pmax(other)
1221
- # The later of each cell and `other`, cell by cell: `other` is a time
1222
- # array of the same shape, or one time (a {CATime::Element}, a `Time`, a
1223
- # `Date`, `"2024-01-02"`) for every cell. The two meet as a comparison
1224
- # does, so the result is in `self`'s unit when `other` sits on its grid
1225
- # and in the finer unit the two share otherwise. A masked cell on either
1226
- # side gives a masked cell.
1227
- # @param other [CATime, CATime::Element, Time, Date, String]
1228
- # @return [CATime]
1229
- # @raise [TypeError] when `other` is not a time.
1230
- def pmax (other)
1231
- pick_by_order(other) { |a, b| a < b }
1232
- end
1233
-
1234
- # @overload pmin(other)
1235
- # The earlier of each cell and `other`; see {#pmax}.
1236
- # @param other [CATime, CATime::Element, Time, Date, String]
1237
- # @return [CATime]
1238
- # @raise [TypeError] when `other` is not a time.
1239
- def pmin (other)
1240
- pick_by_order(other) { |a, b| a > b }
1241
- end
1242
-
1243
- # A time has no NaN, so maximum / minimum (which let a NaN win) are pmax /
1244
- # pmin, and fmax / fmin are their other names.
1245
- alias_method :maximum, :pmax
1246
- alias_method :minimum, :pmin
1247
- alias_method :fmax, :pmax
1248
- alias_method :fmin, :pmin
1249
-
1250
- # `other` where the block says self's cell loses to it, else self's cell.
1251
- private def pick_by_order (other)
1252
- return copy.tap { |out| out[] = UNDEF } if UNDEF.equal?(other)
1253
- a, b = comparable_pair(other)
1254
- b = b[0] unless other.is_a?(CArray) || other.is_a?(Array)
1255
- yield(a, b).then_else(b, a)
1256
- end
1257
-
1258
1315
  # Element-wise comparison (< <= > >= <=>) rides the core comparison Face
1259
1316
  # gate (ca_face_reconcile_comparison in ext/ca_obj_face.c): the inherited
1260
1317
  # CArray operators descend to storage and reconcile a CATime RHS in a
@@ -1830,6 +1887,8 @@ class CATimedelta
1830
1887
  # @raise [RangeError] when the widened ticks overflow int64.
1831
1888
  def to_unit(unit)
1832
1889
  to = CATime::Resolution.parse(unit)
1890
+ # As CATime#to_unit: a new array even when the unit does not change.
1891
+ return face_storage.copy.timedelta(unit: to) if to == self.unit
1833
1892
  CATimeUnitAlgebra.convert_scale_trunc(face_storage, self.unit, to).timedelta(unit: to)
1834
1893
  end
1835
1894
 
@@ -1923,6 +1982,7 @@ class CATimedelta
1923
1982
  # @raise [TypeError] on incompatible operands.
1924
1983
  def /(other)
1925
1984
  given, other = other, CATimeUnitAlgebra.operand(other)
1985
+ other = CATimeUnitAlgebra.scalar_operand(other, unit) || other
1926
1986
  case other
1927
1987
  when Integer
1928
1988
  CATimeUnitAlgebra.trunc_divide(face_storage, other).timedelta(unit: unit)
@@ -1937,6 +1997,68 @@ class CATimedelta
1937
1997
  end
1938
1998
  end
1939
1999
 
2000
+ # A number on the left of a duration: only `n * duration` has an answer.
2001
+ class LeftFactor
2002
+ def initialize (factor)
2003
+ @factor = factor
2004
+ end
2005
+
2006
+ def * (duration) = duration * @factor
2007
+
2008
+ def method_missing (op, duration, *)
2009
+ raise TypeError, "#{@factor.class} #{op} #{duration.class} is not allowed"
2010
+ end
2011
+
2012
+ def respond_to_missing? (*) = true
2013
+ end
2014
+ private_constant :LeftFactor
2015
+
2016
+ # @overload coerce(number)
2017
+ # Lets a duration stand on the right of a number, so `2 * td` is `td * 2`.
2018
+ # @param number [Numeric]
2019
+ # @return [Array]
2020
+ def coerce (number)
2021
+ number.is_a?(Numeric) ? [LeftFactor.new(number), self] : super
2022
+ end
2023
+
2024
+ # @overload to_seconds
2025
+ # Each duration in seconds, exactly, as {Element#to_seconds} answers.
2026
+ # @return [CArray] an object array of Rational.
2027
+ # @raise [ArgumentError] for a :Y / :M unit, which has no exact seconds.
2028
+ def to_seconds
2029
+ unless CATimeUnitAlgebra::FIXED.key?(unit.base)
2030
+ raise ArgumentError,
2031
+ "CATimedelta #{unit} has no exact seconds (a :#{unit.base} is " \
2032
+ "calendar-variable); use to_seconds_approx for an estimate"
2033
+ end
2034
+ ratio = unit.tick_ratio
2035
+ face_storage.convert(:object) { |v| Rational(v) * ratio }
2036
+ end
2037
+
2038
+ # @overload to_seconds_approx
2039
+ # Each duration in seconds by nominal lengths, as
2040
+ # {Element#to_seconds_approx} answers.
2041
+ # @return [CArray] float64.
2042
+ def to_seconds_approx
2043
+ face_storage.to_type(:float64) * (unit.count * (Element::UNIT_TO_SECONDS[unit.base] || 1))
2044
+ end
2045
+
2046
+ # The word form of {#+}.
2047
+ # @return [CATimedelta, CATime]
2048
+ alias_method :add, :+
2049
+ # The word form of {#-}.
2050
+ # @return [CATimedelta]
2051
+ alias_method :sub, :-
2052
+ # The word form of {#*}.
2053
+ # @return [CATimedelta]
2054
+ alias_method :mul, :*
2055
+ # The word form of {#/}.
2056
+ # @return [CATimedelta, CArray]
2057
+ alias_method :div, :/
2058
+ # The word form of {#-@}.
2059
+ # @return [CATimedelta]
2060
+ alias_method :neg, :-@
2061
+
1940
2062
  # Element-wise comparison (< <= > >= <=>) rides the core comparison Face
1941
2063
  # gate (ca_face_reconcile_comparison): the inherited CArray operators
1942
2064
  # descend to storage and reconcile a CATimedelta RHS in a different unit
@@ -2133,8 +2255,12 @@ class CATimedelta
2133
2255
 
2134
2256
  # One duration as a length-1 duration array in its own unit, or nil.
2135
2257
  private def lift_value (operand)
2136
- if operand.is_a?(CATimedelta::Element)
2258
+ case operand
2259
+ when CATimedelta::Element
2137
2260
  CATimedelta.wrap(CA_INT64([operand.value]), unit: operand.unit)
2261
+ when String
2262
+ res = CATime::Resolution.parse(operand)
2263
+ CATimedelta.wrap(CA_INT64([res.count]), unit: res.base)
2138
2264
  end
2139
2265
  end
2140
2266
 
@@ -2147,6 +2273,8 @@ class CATimedelta
2147
2273
  when CATimedelta::Element
2148
2274
  lifted = CATimedelta.wrap(CA_INT64([operand.value]), unit: operand.unit)
2149
2275
  to_comparable(lifted)
2276
+ when String
2277
+ to_comparable(lift_value(operand))
2150
2278
  when Array, CArray
2151
2279
  # Durations written one by one, or an array that is not a duration
2152
2280
  # array (an object column of elements), read value by value.
@@ -2164,7 +2292,8 @@ class CATimedelta
2164
2292
  # scalar store round-trips with a fetch. A {Element} is reconciled to
2165
2293
  # self's unit via {#to_comparable} (lossless discipline; a `Time` /
2166
2294
  # `DateTime` is an absolute instant, not a duration, so it raises there).
2167
- # A bare Integer (the `.parent` raw-storage escape) and a String pass
2295
+ # A String that names a duration (`"3 days"`) is read as one. A bare
2296
+ # Integer (the `.parent` raw-storage escape) and any other String pass
2168
2297
  # through unchanged.
2169
2298
  # @param surface [Element, Integer, String]
2170
2299
  # @return [Integer, Object] the storage-domain value, or `surface`
@@ -2172,8 +2301,15 @@ class CATimedelta
2172
2301
  # @raise [TypeError, ArgumentError] on an unreconcilable surface / unit.
2173
2302
  def element_to_storage (surface)
2174
2303
  case surface
2175
- when Integer, String
2304
+ when Integer
2176
2305
  surface
2306
+ when String
2307
+ begin
2308
+ to_comparable(surface).parent[0]
2309
+ rescue ArgumentError => e
2310
+ raise unless e.message.start_with?("invalid unit spec")
2311
+ surface
2312
+ end
2177
2313
  else
2178
2314
  to_comparable(surface).parent[0]
2179
2315
  end
@@ -2261,11 +2397,24 @@ module CATimeLiteral
2261
2397
  sec: t.sec, sec_fraction: frac.zero? ? nil : Rational(frac), leftover: h[:leftover] }.compact
2262
2398
  end
2263
2399
 
2400
+ # Date._parse drops the sign of a year on its own or before a month, a day
2401
+ # of the year or a week, and reads a year below 100 as this century's, so
2402
+ # those are read here.
2403
+ def year_first_fields(spec)
2404
+ case spec
2405
+ when /\A([-+]\d{4,})\z/ then { year: $1.to_i }
2406
+ when /\A([-+]\d{4,})-(\d{1,2})\z/ then { year: $1.to_i, mon: $2.to_i }
2407
+ when /\A([-+]?\d{4,})-(\d{3})\z/ then { year: $1.to_i, yday: $2.to_i }
2408
+ when /\A([-+]?\d{4,})-W(\d{2})-(\d)\z/ then { cwyear: $1.to_i, cweek: $2.to_i, cwday: $3.to_i }
2409
+ end
2410
+ end
2411
+
2264
2412
  def parse_date_fields(spec, format)
2265
2413
  h =
2266
2414
  if format then epoch_fields(Date._strptime(spec, format))
2267
2415
  elsif spec =~ /\A(\d{4})-(\d{1,2})\z/ then { year: $1.to_i, mon: $2.to_i }
2268
2416
  elsif spec =~ /\A(\d{4})\z/ then { year: $1.to_i }
2417
+ elsif (year_first = year_first_fields(spec)) then year_first
2269
2418
  elsif (hour = hour_only_fields(spec)) then hour
2270
2419
  else Date._parse(spec)
2271
2420
  end