daru_lite 0.4.0 → 0.5.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 (46) hide show
  1. checksums.yaml +4 -4
  2. data/History.md +30 -0
  3. data/README.md +1 -1
  4. data/lib/daru_lite/data_frame/convertible.rb +0 -33
  5. data/lib/daru_lite/data_frame/fetchable.rb +1 -1
  6. data/lib/daru_lite/data_frame/i_o_able.rb +0 -102
  7. data/lib/daru_lite/data_frame/indexable.rb +24 -0
  8. data/lib/daru_lite/data_frame/relabelable.rb +125 -0
  9. data/lib/daru_lite/data_frame/sortable.rb +27 -1
  10. data/lib/daru_lite/dataframe.rb +3 -4
  11. data/lib/daru_lite/index/categorical_index.rb +8 -0
  12. data/lib/daru_lite/index/index.rb +0 -1
  13. data/lib/daru_lite/index/multi_index.rb +8 -5
  14. data/lib/daru_lite/io/io.rb +0 -195
  15. data/lib/daru_lite/maths/arithmetic/vector.rb +31 -0
  16. data/lib/daru_lite/maths/statistics/vector/descriptive.rb +134 -0
  17. data/lib/daru_lite/maths/statistics/vector/dispersion.rb +120 -0
  18. data/lib/daru_lite/maths/statistics/vector/extrema.rb +217 -0
  19. data/lib/daru_lite/maths/statistics/vector/normalization.rb +86 -0
  20. data/lib/daru_lite/maths/statistics/vector/percentile.rb +64 -0
  21. data/lib/daru_lite/maths/statistics/vector/sampling.rb +56 -0
  22. data/lib/daru_lite/maths/statistics/vector/time_series.rb +350 -0
  23. data/lib/daru_lite/maths/statistics/vector.rb +16 -994
  24. data/lib/daru_lite/vector/convertible.rb +0 -32
  25. data/lib/daru_lite/vector.rb +0 -9
  26. data/lib/daru_lite/version.rb +1 -1
  27. data/lib/daru_lite.rb +0 -30
  28. metadata +9 -75
  29. data/lib/daru_lite/date_time/index.rb +0 -570
  30. data/lib/daru_lite/date_time/offsets.rb +0 -397
  31. data/lib/daru_lite/extensions/which_dsl.rb +0 -53
  32. data/lib/daru_lite/io/sql_data_source.rb +0 -80
  33. data/lib/daru_lite/iruby/helpers.rb +0 -38
  34. data/lib/daru_lite/iruby/templates/dataframe.html.erb +0 -5
  35. data/lib/daru_lite/iruby/templates/dataframe_mi.html.erb +0 -5
  36. data/lib/daru_lite/iruby/templates/dataframe_mi_tbody.html.erb +0 -35
  37. data/lib/daru_lite/iruby/templates/dataframe_mi_thead.html.erb +0 -21
  38. data/lib/daru_lite/iruby/templates/dataframe_tbody.html.erb +0 -28
  39. data/lib/daru_lite/iruby/templates/dataframe_thead.html.erb +0 -21
  40. data/lib/daru_lite/iruby/templates/multi_index.html.erb +0 -12
  41. data/lib/daru_lite/iruby/templates/vector.html.erb +0 -5
  42. data/lib/daru_lite/iruby/templates/vector_mi.html.erb +0 -5
  43. data/lib/daru_lite/iruby/templates/vector_mi_tbody.html.erb +0 -26
  44. data/lib/daru_lite/iruby/templates/vector_mi_thead.html.erb +0 -8
  45. data/lib/daru_lite/iruby/templates/vector_tbody.html.erb +0 -17
  46. data/lib/daru_lite/iruby/templates/vector_thead.html.erb +0 -8
@@ -1,1009 +1,31 @@
1
+ require 'daru_lite/maths/statistics/vector/descriptive'
2
+ require 'daru_lite/maths/statistics/vector/extrema'
3
+ require 'daru_lite/maths/statistics/vector/dispersion'
4
+ require 'daru_lite/maths/statistics/vector/percentile'
5
+ require 'daru_lite/maths/statistics/vector/normalization'
6
+ require 'daru_lite/maths/statistics/vector/sampling'
7
+ require 'daru_lite/maths/statistics/vector/time_series'
8
+
1
9
  module DaruLite
2
10
  module Maths
3
11
  # Encapsulates statistics methods for vectors. Most basic stuff like mean, etc.
4
12
  # is done inside the wrapper, so that native methods can be used for most of
5
13
  # the computationally intensive tasks.
6
14
  module Statistics
7
- module Vector # rubocop:disable Metrics/ModuleLength
8
- def mean
9
- @data.mean
10
- end
11
-
12
- def sum
13
- @data.sum
14
- end
15
-
16
- def product
17
- @data.product
18
- end
19
-
20
- def range
21
- max - min
22
- end
23
-
24
- def median
25
- @data.respond_to?(:median) ? @data.median : percentile(50)
26
- end
27
-
28
- def mode
29
- mode = frequencies.to_h.select { |_, v| v == frequencies.max }.keys
30
- mode.size > 1 ? DaruLite::Vector.new(mode) : mode.first
31
- end
32
-
33
- # Create a summary of count, mean, standard deviation, min and max of
34
- # the vector in one shot.
35
- #
36
- # == Arguments
37
- #
38
- # +methods+ - An array with aggregation methods specified as symbols to
39
- # be applied to vectors. Default is [:count, :mean, :std, :max,
40
- # :min]. Methods will be applied in the specified order.
41
- def describe(methods = nil)
42
- methods ||= %i[count mean std min max]
43
- description = methods.map { |m| send(m) }
44
- DaruLite::Vector.new(description, index: methods, name: :statistics)
45
- end
46
-
47
- def median_absolute_deviation
48
- m = median
49
- recode { |val| (val - m).abs }.median
50
- end
51
-
52
- alias mad median_absolute_deviation
53
-
54
- def standard_error
55
- standard_deviation_sample / Math.sqrt(size - count_values(*DaruLite::MISSING_VALUES))
56
- end
57
-
58
- def sum_of_squared_deviation
59
- (
60
- @data.inject(0) { |a, x| (x**2) + a } -
61
- (sum**2).quo(size - count_values(*DaruLite::MISSING_VALUES)).to_f
62
- ).to_f
63
- end
64
-
65
- # Retrieve unique values of non-nil data
66
- def factors
67
- reject_values(*DaruLite::MISSING_VALUES).uniq.reset_index!
68
- end
69
-
70
- if RUBY_VERSION >= '2.2'
71
- # Returns the maximum value(s) present in the vector, with an optional comparator block.
72
- #
73
- # @param size [Integer] Number of maximum values to return. Defaults to nil.
74
- #
75
- # @example
76
- #
77
- # dv = DaruLite::Vector.new (["Tyrion", "Daenerys", "Jon Starkgaryen"]),
78
- # index: DaruLite::Index.new([:t, :d, :j])
79
- # #=>
80
- # # #<DaruLite::Vector(3)>
81
- # # t Tyrion
82
- # # d Daenerys
83
- # # j Jon Starkgaryen
84
- #
85
- # dv.max
86
- # #=> "Tyrion"
87
- #
88
- # dv.max(2) { |a,b| a.size <=> b.size }
89
- # #=> ["Jon Starkgaryen","Daenerys"]
90
- def max(size = nil, &)
91
- reject_values(*DaruLite::MISSING_VALUES).to_a.max(size, &)
92
- end
93
-
94
- # Returns the maximum value(s) present in the vector, with a compulsory object block.
95
- #
96
- # @param size [Integer] Number of maximum values to return. Defaults to nil.
97
- #
98
- # @example
99
- #
100
- # dv = DaruLite::Vector.new (["Tyrion", "Daenerys", "Jon Starkgaryen"]),
101
- # index: DaruLite::Index.new([:t, :d, :j])
102
- # #=>
103
- # # #<DaruLite::Vector(3)>
104
- # # t Tyrion
105
- # # d Daenerys
106
- # # j Jon Starkgaryen
107
- #
108
- # dv.max_by(2) { |i| i.size }
109
- # #=> ["Jon Starkgaryen","Daenerys"]
110
- def max_by(size = nil, &block)
111
- raise ArgumentError, 'Expected compulsory object block in max_by method' unless block
112
-
113
- reject_values(*DaruLite::MISSING_VALUES).to_a.max_by(size, &block)
114
- end
115
-
116
- # Returns the minimum value(s) present in the vector, with an optional comparator block.
117
- #
118
- # @param size [Integer] Number of minimum values to return. Defaults to nil.
119
- #
120
- # @example
121
- #
122
- # dv = DaruLite::Vector.new (["Tyrion", "Daenerys", "Jon Starkgaryen"]),
123
- # index: DaruLite::Index.new([:t, :d, :j])
124
- # #=>
125
- # # #<DaruLite::Vector(3)>
126
- # # t Tyrion
127
- # # d Daenerys
128
- # # j Jon Starkgaryen
129
- #
130
- # dv.min
131
- # #=> "Daenerys"
132
- #
133
- # dv.min(2) { |a,b| a.size <=> b.size }
134
- # #=> ["Tyrion","Daenerys"]
135
- def min(size = nil, &)
136
- reject_values(*DaruLite::MISSING_VALUES).to_a.min(size, &)
137
- end
138
-
139
- # Returns the minimum value(s) present in the vector, with a compulsory object block.
140
- #
141
- # @param size [Integer] Number of minimum values to return. Defaults to nil.
142
- #
143
- # @example
144
- #
145
- # dv = DaruLite::Vector.new (["Tyrion", "Daenerys", "Jon Starkgaryen"]),
146
- # index: DaruLite::Index.new([:t, :d, :j])
147
- # #=>
148
- # # #<DaruLite::Vector(3)>
149
- # # t Tyrion
150
- # # d Daenerys
151
- # # j Jon Starkgaryen
152
- #
153
- # dv.min_by(2) { |i| i.size }
154
- # #=> ["Tyrion","Daenerys"]
155
- def min_by(size = nil, &block)
156
- raise ArgumentError, 'Expected compulsory object block in min_by method' unless block
157
-
158
- reject_values(*DaruLite::MISSING_VALUES).to_a.min_by(size, &block)
159
- end
160
- else
161
- # Returns the maximum value(s) present in the vector, with an optional comparator block.
162
- #
163
- # @param size [Integer] Number of maximum values to return. Defaults to nil.
164
- #
165
- # @example
166
- #
167
- # dv = DaruLite::Vector.new (["Tyrion", "Daenerys", "Jon Starkgaryen"]),
168
- # index: DaruLite::Index.new([:t, :d, :j])
169
- # #=>
170
- # # #<DaruLite::Vector(3)>
171
- # # t Tyrion
172
- # # d Daenerys
173
- # # j Jon Starkgaryen
174
- #
175
- # dv.max
176
- # #=> "Tyrion"
177
- #
178
- # dv.max(2) { |a,b| a.size <=> b.size }
179
- # #=> ["Jon Starkgaryen","Daenerys"]
180
- def max(size = nil, &)
181
- range = size.nil? ? 0 : (0..(size - 1))
182
- reject_values(*DaruLite::MISSING_VALUES).to_a.sort(&).reverse[range]
183
- end
184
-
185
- # Returns the maximum value(s) present in the vector, with a compulsory object block.
186
- #
187
- # @param size [Integer] Number of maximum values to return. Defaults to nil.
188
- #
189
- # @example
190
- #
191
- # dv = DaruLite::Vector.new (["Tyrion", "Daenerys", "Jon Starkgaryen"]),
192
- # index: DaruLite::Index.new([:t, :d, :j])
193
- # #=>
194
- # # #<DaruLite::Vector(3)>
195
- # # t Tyrion
196
- # # d Daenerys
197
- # # j Jon Starkgaryen
198
- #
199
- # dv.max_by(2) { |i| i.size }
200
- # #=> ["Jon Starkgaryen","Daenerys"]
201
- def max_by(size = nil, &block)
202
- raise ArgumentError, 'Expected compulsory object block in max_by method' unless block
203
-
204
- reject_values(*DaruLite::MISSING_VALUES).to_a.sort_by(&block).reverse[size.nil? ? 0 : (0..(size - 1))]
205
- end
206
-
207
- # Returns the minimum value(s) present in the vector, with an optional comparator block.
208
- #
209
- # @param size [Integer] Number of minimum values to return. Defaults to nil.
210
- #
211
- # @example
212
- #
213
- # dv = DaruLite::Vector.new (["Tyrion", "Daenerys", "Jon Starkgaryen"]),
214
- # index: DaruLite::Index.new([:t, :d, :j])
215
- # #=>
216
- # # #<DaruLite::Vector(3)>
217
- # # t Tyrion
218
- # # d Daenerys
219
- # # j Jon Starkgaryen
220
- #
221
- # dv.min
222
- # #=> "Daenerys"
223
- #
224
- # dv.min(2) { |a,b| a.size <=> b.size }
225
- # #=> ["Tyrion","Daenerys"]
226
- def min(size = nil, &)
227
- range = size.nil? ? 0 : (0..(size - 1))
228
- reject_values(*DaruLite::MISSING_VALUES).to_a.sort(&)[range]
229
- end
230
-
231
- # Returns the minimum value(s) present in the vector, with a compulsory object block.
232
- #
233
- # @param size [Integer] Number of minimum values to return. Defaults to nil.
234
- #
235
- # @example
236
- #
237
- # dv = DaruLite::Vector.new (["Tyrion", "Daenerys", "Jon Starkgaryen"]),
238
- # index: DaruLite::Index.new([:t, :d, :j])
239
- # #=>
240
- # # #<DaruLite::Vector(3)>
241
- # # t Tyrion
242
- # # d Daenerys
243
- # # j Jon Starkgaryen
244
- #
245
- # dv.min_by
246
- # #=> "Daenerys"
247
- #
248
- # dv.min_by(2) { |i| i.size }
249
- # #=> ["Tyrion","Daenerys"]
250
- def min_by(size = nil, &block)
251
- raise ArgumentError, 'Expected compulsory object block in min_by method' unless block
252
-
253
- reject_values(*DaruLite::MISSING_VALUES).to_a.sort_by(&block)[size.nil? ? 0 : (0..(size - 1))]
254
- end
255
- end
256
-
257
- # Returns the index of the maximum value(s) present in the vector, with an optional
258
- # comparator block.
259
- #
260
- # @param size [Integer] Number of maximum indices to return. Defaults to nil.
261
- #
262
- # @example
263
- #
264
- # dv = DaruLite::Vector.new (["Tyrion", "Daenerys", "Jon Starkgaryen"]),
265
- # index: DaruLite::Index.new([:t, :d, :j])
266
- # #=>
267
- # # #<DaruLite::Vector(3)>
268
- # # t Tyrion
269
- # # d Daenerys
270
- # # j Jon Starkgaryen
271
- #
272
- # dv.index_of_max
273
- # #=> :t
274
- #
275
- # dv.index_of_max(2) { |a,b| a.size <=> b.size }
276
- # #=> [:j, :d]
277
- def index_of_max(size = nil, &)
278
- vals = max(size, &)
279
- dv = reject_values(*DaruLite::MISSING_VALUES)
280
- vals.is_a?(Array) ? vals.map { |x| dv.index_of(x) } : dv.index_of(vals)
281
- end
282
-
283
- # Returns the index of the maximum value(s) present in the vector, with a compulsory
284
- # object block.
285
- #
286
- # @param size [Integer] Number of maximum indices to return. Defaults to nil.
287
- #
288
- # @example
289
- #
290
- # dv = DaruLite::Vector.new (["Tyrion", "Daenerys", "Jon Starkgaryen"]),
291
- # index: DaruLite::Index.new([:t, :d, :j])
292
- # #=>
293
- # # #<DaruLite::Vector(3)>
294
- # # t Tyrion
295
- # # d Daenerys
296
- # # j Jon Starkgaryen
297
- #
298
- # dv.index_of_max_by(2) { |i| i.size }
299
- # #=> [:j, :d]
300
- def index_of_max_by(size = nil, &)
301
- vals = max_by(size, &)
302
- dv = reject_values(*DaruLite::MISSING_VALUES)
303
- vals.is_a?(Array) ? vals.map { |x| dv.index_of(x) } : dv.index_of(vals)
304
- end
305
-
306
- # Returns the index of the minimum value(s) present in the vector, with an optional
307
- # comparator block.
308
- #
309
- # @param size [Integer] Number of minimum indices to return. Defaults to nil.
310
- #
311
- # @example
312
- #
313
- # dv = DaruLite::Vector.new (["Tyrion", "Daenerys", "Jon Starkgaryen"]),
314
- # index: DaruLite::Index.new([:t, :d, :j])
315
- # #=>
316
- # # #<DaruLite::Vector(3)>
317
- # # t Tyrion
318
- # # d Daenerys
319
- # # j Jon Starkgaryen
320
- #
321
- # dv.index_of_min
322
- # #=> :d
323
- #
324
- # dv.index_of_min(2) { |a,b| a.size <=> b.size }
325
- # #=> [:t, :d]
326
- def index_of_min(size = nil, &)
327
- vals = min(size, &)
328
- dv = reject_values(*DaruLite::MISSING_VALUES)
329
- vals.is_a?(Array) ? vals.map { |x| dv.index_of(x) } : dv.index_of(vals)
330
- end
331
-
332
- # Returns the index of the minimum value(s) present in the vector, with a compulsory
333
- # object block.
334
- #
335
- # @param size [Integer] Number of minimum indices to return. Defaults to nil.
336
- #
337
- # @example
338
- #
339
- # dv = DaruLite::Vector.new (["Tyrion", "Daenerys", "Jon Starkgaryen"]),
340
- # index: DaruLite::Index.new([:t, :d, :j])
341
- # #=>
342
- # # #<DaruLite::Vector(3)>
343
- # # t Tyrion
344
- # # d Daenerys
345
- # # j Jon Starkgaryen
346
- #
347
- # dv.index_of_min(2) { |i| i.size }
348
- # #=> [:t, :d]
349
- def index_of_min_by(size = nil, &)
350
- vals = min_by(size, &)
351
- dv = reject_values(*DaruLite::MISSING_VALUES)
352
- vals.is_a?(Array) ? vals.map { |x| dv.index_of(x) } : dv.index_of(vals)
353
- end
354
-
355
- # Return the maximum element present in the Vector, as a Vector.
356
- # @return [DaruLite::Vector]
357
- def max_index
358
- max_value = @data.max
359
- DaruLite::Vector.new({ index_of(max_value) => max_value }, name: @name, dtype: @dtype)
360
- end
361
-
362
- def frequencies
363
- DaruLite::Vector.new(
364
- @data.each_with_object(Hash.new(0)) do |element, hash|
365
- hash[element] += 1 unless element.nil?
366
- end
367
- )
368
- end
369
-
370
- def proportions
371
- len = size - count_values(*DaruLite::MISSING_VALUES)
372
- frequencies.to_h.transform_values do |count|
373
- count / len.to_f
374
- end
375
- end
376
-
377
- def ranked
378
- sum = 0
379
- r = frequencies.to_h.sort.each_with_object({}) do |(el, count), memo|
380
- memo[el] = ((sum + 1) + (sum + count)).quo(2)
381
- sum += count
382
- end
383
-
384
- recode { |e| r[e] }
385
- end
386
-
387
- def coefficient_of_variation
388
- standard_deviation_sample / mean
389
- end
390
-
391
- # Retrieves number of cases which comply condition. If block given,
392
- # retrieves number of instances where block returns true. If other
393
- # values given, retrieves the frequency for this value. If no value
394
- # given, counts the number of non-nil elements in the Vector.
395
- def count(value = false, &block)
396
- if block
397
- @data.count(&block)
398
- elsif value
399
- count { |val| val == value }
400
- else
401
- size - indexes(*DaruLite::MISSING_VALUES).size
402
- end
403
- end
404
-
405
- # Count number of occurrences of each value in the Vector
406
- def value_counts
407
- DaruLite::Vector.new(@data.tally)
408
- end
409
-
410
- def proportion(value = 1)
411
- frequencies[value].quo(size - count_values(*DaruLite::MISSING_VALUES)).to_f
412
- end
413
-
414
- # Sample variance with denominator (N-1)
415
- def variance_sample(m = nil)
416
- m ||= mean
417
- if @data.respond_to? :variance_sample
418
- @data.variance_sample m
419
- else
420
- sum_of_squares(m).quo(size - count_values(*DaruLite::MISSING_VALUES) - 1)
421
- end
422
- end
423
-
424
- # Population variance with denominator (N)
425
- def variance_population(m = nil)
426
- m ||= mean
427
- if @data.respond_to? :variance_population
428
- @data.variance_population m
429
- else
430
- sum_of_squares(m).quo(size - count_values(*DaruLite::MISSING_VALUES)).to_f
431
- end
432
- end
433
-
434
- # Sample covariance with denominator (N-1)
435
- def covariance_sample(other)
436
- size == other.size or raise ArgumentError, 'size of both the vectors must be equal'
437
- covariance_sum(other) / (size - count_values(*DaruLite::MISSING_VALUES) - 1)
438
- end
439
-
440
- # Population covariance with denominator (N)
441
- def covariance_population(other)
442
- size == other.size or raise ArgumentError, 'size of both the vectors must be equal'
443
- covariance_sum(other) / (size - count_values(*DaruLite::MISSING_VALUES))
444
- end
445
-
446
- def sum_of_squares(m = nil)
447
- m ||= mean
448
- reject_values(*DaruLite::MISSING_VALUES).data.inject(0) do |memo, val|
449
- memo + ((val - m)**2)
450
- end
451
- end
452
-
453
- def standard_deviation_population(m = nil)
454
- m ||= mean
455
- if @data.respond_to? :standard_deviation_population
456
- @data.standard_deviation_population(m)
457
- else
458
- Math.sqrt(variance_population(m))
459
- end
460
- end
461
-
462
- def standard_deviation_sample(m = nil)
463
- m ||= mean
464
- if @data.respond_to? :standard_deviation_sample
465
- @data.standard_deviation_sample m
466
- else
467
- Math.sqrt(variance_sample(m))
468
- end
469
- end
470
-
471
- # Calculate skewness using (sigma(xi - mean)^3)/((N)*std_dev_sample^3)
472
- def skew(m = nil)
473
- if @data.respond_to? :skew
474
- @data.skew
475
- else
476
- m ||= mean
477
- th = @data.inject(0) { |memo, val| memo + ((val - m)**3) }
478
- th.quo((size - indexes(*DaruLite::MISSING_VALUES).size) * (standard_deviation_sample(m)**3))
479
- end
480
- end
481
-
482
- def kurtosis(m = nil)
483
- if @data.respond_to? :kurtosis
484
- @data.kurtosis
485
- else
486
- m ||= mean
487
- fo = @data.inject(0) { |a, x| a + ((x - m)**4) }
488
- fo.quo((size - indexes(*DaruLite::MISSING_VALUES).size) * (standard_deviation_sample(m)**4)) - 3
489
- end
490
- end
491
-
492
- def average_deviation_population(m = nil)
493
- must_be_numeric!
494
- m ||= mean
495
- reject_values(*DaruLite::MISSING_VALUES).data.inject(0) do |memo, val|
496
- (val - m).abs + memo
497
- end.quo(size - count_values(*DaruLite::MISSING_VALUES))
498
- end
499
-
500
- # Returns the value of the percentile q
501
- #
502
- # Accepts an optional second argument specifying the strategy to interpolate
503
- # when the requested percentile lies between two data points a and b
504
- # Valid strategies are:
505
- # * :midpoint (Default): (a + b) / 2
506
- # * :linear : a + (b - a) * d where d is the decimal part of the index between a and b.
507
- # == References
508
- #
509
- # This is the NIST recommended method (http://en.wikipedia.org/wiki/Percentile#NIST_method)
510
- def percentile(q, strategy = :midpoint)
511
- case strategy
512
- when :midpoint
513
- midpoint_percentile(q)
514
- when :linear
515
- linear_percentile(q)
516
- else
517
- raise ArgumentError, "Unknown strategy #{strategy}"
518
- end
519
- end
520
-
521
- # Dichotomize the vector with 0 and 1, based on lowest value.
522
- # If parameter is defined, this value and lower will be 0
523
- # and higher, 1.
524
- def dichotomize(low = nil)
525
- low ||= factors.min
526
-
527
- recode do |x|
528
- if x.nil?
529
- nil
530
- elsif x > low
531
- 1
532
- else
533
- 0
534
- end
535
- end
536
- end
537
-
538
- # Center data by subtracting the mean from each non-nil value.
539
- def center
540
- self - mean
541
- end
542
-
543
- # Standardize data.
544
- #
545
- # == Arguments
546
- #
547
- # * use_population - Pass as *true* if you want to use population
548
- # standard deviation instead of sample standard deviation.
549
- def standardize(use_population = false)
550
- m ||= mean
551
- sd = use_population ? sdp : sds
552
- return DaruLite::Vector.new([nil] * size) if m.nil? || sd.nil? || sd.zero?
553
-
554
- vector_standardized_compute m, sd
555
- end
556
-
557
- # simplecov:disable
558
- def box_cox_transformation(lambda) # :nodoc:
559
- must_be_numeric!
560
-
561
- recode do |x|
562
- unless x.nil?
563
- if lambda.zero?
564
- Math.log(x)
565
- else
566
- ((x**lambda) - 1).quo(lambda)
567
- end
568
- end
569
- end
570
- end
571
- # simplecov:enable
572
-
573
- # Replace each non-nil value in the vector with its percentile.
574
- def vector_percentile
575
- c = size - indexes(*DaruLite::MISSING_VALUES).size
576
- ranked.recode! { |i| i.nil? ? nil : (i.quo(c) * 100).to_f }
577
- end
578
-
579
- def vector_standardized_compute(m, sd)
580
- if @data.respond_to? :vector_standardized_compute
581
- @data.vector_standardized_compute(m, sd)
582
- else
583
- DaruLite::Vector.new @data.collect { |x| x.nil? ? nil : (x.to_f - m).quo(sd) },
584
- index: index, name: name, dtype: dtype
585
- end
586
- end
587
-
588
- def vector_centered_compute(m)
589
- if @data.respond_to? :vector_centered_compute
590
- @data.vector_centered_compute(m)
591
- else
592
- DaruLite::Vector.new @data.collect { |x| x.nil? ? nil : x.to_f - m },
593
- index: index, name: name, dtype: dtype
594
- end
595
- end
596
-
597
- # Returns an random sample of size n, with replacement,
598
- # only with non-nil data.
599
- #
600
- # In all the trails, every item have the same probability
601
- # of been selected.
602
- def sample_with_replacement(sample = 1)
603
- if @data.respond_to? :sample_with_replacement
604
- @data.sample_with_replacement sample
605
- else
606
- valid = indexes(*DaruLite::MISSING_VALUES).empty? ? self : reject_values(*DaruLite::MISSING_VALUES)
607
- vds = valid.size
608
- (0...sample).collect { valid[rand(vds)] }
609
- end
610
- end
611
-
612
- # Returns an random sample of size n, without replacement,
613
- # only with valid data.
614
- #
615
- # Every element could only be selected once.
616
- #
617
- # A sample of the same size of the vector is the vector itself.
618
- def sample_without_replacement(sample = 1)
619
- if @data.respond_to? :sample_without_replacement
620
- @data.sample_without_replacement sample
621
- else
622
- raw_sample_without_replacement(sample)
623
- end
624
- end
625
-
626
- # The percent_change method computes the percent change over
627
- # the given number of periods.
628
- #
629
- # @param [Integer] periods (1) number of nils to insert at the beginning.
630
- #
631
- # @example
632
- #
633
- # vector = DaruLite::Vector.new([4,6,6,8,10],index: ['a','f','t','i','k'])
634
- # vector.percent_change
635
- # #=>
636
- # # <DaruLite::Vector:28713060 @name = nil size: 5 >
637
- # # nil
638
- # # a
639
- # # f 0.5
640
- # # t 0.0
641
- # # i 0.3333333333333333
642
- # # k 0.25
643
- def percent_change(periods = 1)
644
- must_be_numeric!
645
-
646
- prev = nil
647
- arr = @data.each_with_index.map do |cur, i|
648
- if i < periods ||
649
- include_with_nan?(DaruLite::MISSING_VALUES, cur) ||
650
- include_with_nan?(DaruLite::MISSING_VALUES, prev)
651
- nil
652
- else
653
- (cur - prev) / prev.to_f
654
- end.tap { prev = cur if cur }
655
- end
656
-
657
- DaruLite::Vector.new(arr, index: @index, name: @name)
658
- end
659
-
660
- # Performs the difference of the series.
661
- # Note: The first difference of series is X(t) - X(t-1)
662
- # But, second difference of series is NOT X(t) - X(t-2)
663
- # It is the first difference of the first difference
664
- # => (X(t) - X(t-1)) - (X(t-1) - X(t-2))
665
- #
666
- # == Arguments
667
- #
668
- # * *max_lags*: integer, (default: 1), number of differences reqd.
669
- #
670
- # @example Using #diff
671
- #
672
- # ts = DaruLite::Vector.new((1..10).map { rand })
673
- # # => [0.69, 0.23, 0.44, 0.71, ...]
674
- #
675
- # ts.diff # => [nil, -0.46, 0.21, 0.27, ...]
676
- #
677
- # @return [DaruLite::Vector]
678
- def diff(max_lags = 1)
679
- ts = self
680
- difference = []
681
- max_lags.times do
682
- difference = ts - ts.lag
683
- ts = difference
684
- end
685
- difference
686
- end
687
-
688
- # Calculate the rolling function for a loopback value.
689
- #
690
- # @param [Symbol] function The rolling function to be applied. Can be
691
- # any function applicatble to DaruLite::Vector (:mean, :median, :count,
692
- # :min, :max, etc.)
693
- # @param [Integer] n (10) A non-negative value which serves as the loopback length.
694
- # @return [DaruLite::Vector] Vector containin rolling calculations.
695
- # @example Using #rolling
696
- # ts = DaruLite::Vector.new((1..100).map { rand })
697
- # # => [0.69, 0.23, 0.44, 0.71, ...]
698
- # # first 9 observations are nil
699
- # ts.rolling(:mean) # => [ ... nil, 0.484... , 0.445... , 0.513 ... , ... ]
700
- def rolling(function, n = 10)
701
- DaruLite::Vector.new(
702
- ([nil] * (n - 1)) +
703
- (0..(size - n)).map do |i|
704
- DaruLite::Vector.new(@data[i...(i + n)]).send(function)
705
- end, index: @index
706
- )
707
- end
708
-
709
- # @!method rolling_mean
710
- # Calculate rolling average
711
- # @yieldparam [Integer] n (10) Loopback length
712
- # @!method rolling_median
713
- # Calculate rolling median
714
- # @yieldparam [Integer] n (10) Loopback length
715
- # @!method rolling_count
716
- # Calculate rolling non-missing count
717
- # @yieldparam [Integer] n (10) Loopback length
718
- # @!method rolling_max
719
- # Calculate rolling max value
720
- # @yieldparam [Integer] n (10) Loopback length
721
- # @!method rolling_min
722
- # Calculate rolling min value
723
- # @yieldparam [Integer] n (10) Loopback length
724
- # @!method rolling_sum
725
- # Calculate rolling sum
726
- # @yieldparam [Integer] n (10) Loopback length
727
- # @!method rolling_std
728
- # Calculate rolling standard deviation
729
- # @yieldparam [Integer] n (10) Loopback length
730
- # @!method rolling_variance
731
- # Calculate rolling variance
732
- # @yieldparam [Integer] n (10) Loopback length
733
- %i[count mean median max min sum std variance].each do |meth|
734
- define_method(:"rolling_#{meth}") do |n = 10|
735
- rolling(meth, n)
736
- end
737
- end
738
-
739
- # Exponential Moving Average.
740
- # Calculates an exponential moving average of the series using a
741
- # specified parameter. If wilder is false (the default) then the EMA
742
- # uses a smoothing value of 2 / (n + 1), if it is true then it uses the
743
- # Welles Wilder smoother of 1 / n.
744
- #
745
- # Warning for EMA usage: EMAs are unstable for small series, as they
746
- # use a lot more than n observations to calculate. The series is stable
747
- # if the size of the series is >= 3.45 * (n + 1)
748
- #
749
- # @param [Integer] n (10) Loopback length.
750
- # @param [TrueClass, FalseClass] wilder (false) If true, 1/n value is
751
- # used for smoothing; if false, uses 2/(n+1) value
752
- #
753
- # @example Using ema
754
- #
755
- # ts = DaruLite::Vector.new((1..100).map { rand })
756
- # # => [0.577..., 0.123..., 0.173..., 0.233..., ...]
757
- #
758
- # # first 9 observations are nil
759
- # ts.ema # => [ ... nil, 0.455... , 0.395..., 0.323..., ... ]
760
- #
761
- # @return [DaruLite::Vector] Contains EMA
762
- def ema(n = 10, wilder = false)
763
- smoother = wilder ? 1.0 / n : 2.0 / (n + 1)
764
- # need to start everything from the first non-nil observation
765
- start = @data.index { |i| !i.nil? }
766
- # first n - 1 observations are nil
767
- base = [nil] * (start + n - 1)
768
- # nth observation is just a moving average
769
- base << (@data[start...(start + n)].inject(0.0) { |s, a| a.nil? ? s : s + a } / n)
770
- (start + n).upto size - 1 do |i|
771
- base << ((self[i] * smoother) + ((1 - smoother) * base.last))
772
- end
773
-
774
- DaruLite::Vector.new(base, index: @index, name: @name)
775
- end
776
-
777
- # Exponential Moving Variance.
778
- # Calculates an exponential moving variance of the series using a
779
- # specified parameter. If wilder is false (the default) then the EMV
780
- # uses a smoothing value of 2 / (n + 1), if it is true then it uses the
781
- # Welles Wilder smoother of 1 / n.
782
- #
783
- # @param [Integer] n (10) Loopback length.
784
- # @param [TrueClass, FalseClass] wilder (false) If true, 1/n value is
785
- # used for smoothing; if false, uses 2/(n+1) value
786
- #
787
- # @example Using emv
788
- #
789
- # ts = DaruLite::Vector.new((1..100).map { rand })
790
- # # => [0.047..., 0.23..., 0.836..., 0.845..., ...]
791
- #
792
- # # first 9 observations are nil
793
- # ts.emv # => [ ... nil, 0.073... , 0.082..., 0.080..., ...]
794
- #
795
- # @return [DaruLite::Vector] contains EMV
796
- def emv(n = 10, wilder = false) # rubocop:disable Metrics/AbcSize
797
- smoother = wilder ? 1.0 / n : 2.0 / (n + 1)
798
- # need to start everything from the first non-nil observation
799
- start = @data.index { |i| !i.nil? }
800
- # first n - 1 observations are nil
801
- var_base = [nil] * (start + n - 1)
802
- mean_base = [nil] * (start + n - 1)
803
- mean_base << (@data[start...(start + n)].inject(0.0) { |s, a| a.nil? ? s : s + a } / n)
804
- # nth observation is just a moving variance_population
805
- var_base << (@data[start...(start + n)].inject(0.0) { |s, x| x.nil? ? s : s + ((x - mean_base.last)**2) } / n)
806
- (start + n).upto size - 1 do |i|
807
- last = mean_base.last
808
- mean_base << ((self[i] * smoother) + ((1 - smoother) * last))
809
- var_base << (((1 - smoother) * var_base.last) + (smoother * (self[i] - last) * (self[i] - mean_base.last)))
810
- end
811
- DaruLite::Vector.new(var_base, index: @index, name: @name)
812
- end
813
-
814
- # Exponential Moving Standard Deviation.
815
- # Calculates an exponential moving standard deviation of the series using a
816
- # specified parameter. If wilder is false (the default) then the EMSD
817
- # uses a smoothing value of 2 / (n + 1), if it is true then it uses the
818
- # Welles Wilder smoother of 1 / n.
819
- #
820
- # @param [Integer] n (10) Loopback length.
821
- # @param [TrueClass, FalseClass] wilder (false) If true, 1/n value is
822
- # used for smoothing; if false, uses 2/(n+1) value
823
- #
824
- # @example Using emsd
825
- #
826
- # ts = DaruLite::Vector.new((1..100).map { rand })
827
- # # => [0.400..., 0.727..., 0.862..., 0.013..., ...]
828
- #
829
- # # first 9 observations are nil
830
- # ts.emsd # => [ ... nil, 0.285... , 0.258..., 0.243..., ...]
831
- #
832
- # @return [DaruLite::Vector] contains EMSD
833
- def emsd(n = 10, wilder = false)
834
- result = []
835
- emv_return = emv(n, wilder)
836
- emv_return.each do |d| # rubocop:disable Style/MapIntoArray
837
- result << (d.nil? ? nil : Math.sqrt(d))
838
- end
839
- DaruLite::Vector.new(result, index: @index, name: @name)
840
- end
841
-
842
- # Moving Average Convergence-Divergence.
843
- # Calculates the MACD (moving average convergence-divergence) of the time
844
- # series.
845
- # @see https://en.wikipedia.org/wiki/MACD
846
- #
847
- # @param fast [Integer] fast period of MACD (default 12)
848
- # @param slow [Integer] slow period of MACD (default 26)
849
- # @param signal [Integer] signal period of MACD (default 9)
850
- #
851
- # @example Create a series and calculate MACD values
852
- # ts = DaruLite::Vector.new((1..100).map { rand })
853
- # # => [0.69, 0.23, 0.44, 0.71, ...]
854
- # macdseries, macdsignal, macdhist = ts.macd
855
- # macdseries, macdsignal, macdhist = ts.macd(13)
856
- # macdseries, macdsignal, macdhist = ts.macd(signal=5)
857
- #
858
- # @return [Array<DaruLite::Vector>] macdseries, macdsignal and macdhist are
859
- # returned as an array of three DaruLite::Vectors
860
- #
861
- def macd(fast = 12, slow = 26, signal = 9)
862
- macdseries = ema(fast) - ema(slow)
863
- macdsignal = macdseries.ema(signal)
864
- macdhist = macdseries - macdsignal
865
- [macdseries, macdsignal, macdhist]
866
- end
867
-
868
- # Calculates the autocorrelation coefficients of the series.
869
- #
870
- # The first element is always 1, since that is the correlation
871
- # of the series with itself.
872
- #
873
- # @example
874
- # ts = DaruLite::Vector.new((1..100).map { rand })
875
- #
876
- # ts.acf # => array with first 21 autocorrelations
877
- # ts.acf 3 # => array with first 3 autocorrelations
878
- def acf(max_lags = nil)
879
- max_lags ||= (10 * Math.log10(size)).to_i
880
-
881
- (0..max_lags).map do |i|
882
- if i.zero?
883
- 1.0
884
- else
885
- m = mean
886
- # can't use Pearson coefficient since the mean for the lagged series should
887
- # be the same as the regular series
888
- ((self - m) * (lag(i) - m)).sum / variance_sample / (size - 1)
889
- end
890
- end
891
- end
892
-
893
- # Provides autocovariance.
894
- #
895
- # == Options
896
- #
897
- # * *:demean* = true; optional. Supply false if series is not to be demeaned
898
- # * *:unbiased* = true; optional. true/false for unbiased/biased form of autocovariance
899
- #
900
- # == Returns
901
- #
902
- # Autocovariance value
903
- def acvf(demean = true, unbiased = true)
904
- demeaned_series = demean ? self - mean : self
905
-
906
- n = (10 * Math.log10(size)).to_i + 1
907
- m = mean
908
- d = if unbiased
909
- Array.new(size, size)
910
- else
911
- (1..size).to_a.reverse[0..n]
912
- end
913
-
914
- 0.upto(n - 1).map do |i|
915
- (demeaned_series * (lag(i) - m)).sum / d[i]
916
- end
917
- end
918
-
919
- # Calculate cumulative sum of Vector
920
- def cumsum
921
- result = []
922
- acc = 0
923
- @data.each do |d|
924
- if include_with_nan? DaruLite::MISSING_VALUES, d
925
- result << nil
926
- else
927
- acc += d
928
- result << acc
929
- end
930
- end
931
-
932
- DaruLite::Vector.new(result, index: @index)
933
- end
934
-
935
- alias sdp standard_deviation_population
936
- alias sds standard_deviation_sample
937
- alias std sds
938
- alias adp average_deviation_population
939
- alias cov coefficient_of_variation
940
- alias variance variance_sample
941
- alias covariance covariance_sample
942
- alias sd standard_deviation_sample
943
- alias ss sum_of_squares
944
- alias percentil percentile
945
- alias se standard_error
15
+ module Vector
16
+ include Descriptive
17
+ include Extrema
18
+ include Dispersion
19
+ include Percentile
20
+ include Normalization
21
+ include Sampling
22
+ include TimeSeries
946
23
 
947
24
  private
948
25
 
949
26
  def must_be_numeric!
950
27
  numeric? or raise TypeError, 'Vector must be numeric'
951
28
  end
952
-
953
- def covariance_sum(other)
954
- self_mean = mean
955
- other_mean = other.mean
956
- @data
957
- .zip(other.data).inject(0) do |res, (d, o)|
958
- res + if !d || !o
959
- 0
960
- else
961
- (d - self_mean) * (o - other_mean)
962
- end
963
- end
964
- end
965
-
966
- def midpoint_percentile(q)
967
- sorted = reject_values(*DaruLite::MISSING_VALUES).to_a.sort
968
-
969
- v = ((size - count_values(*DaruLite::MISSING_VALUES)) * q).quo(100)
970
- if v.to_i == v
971
- (sorted[(v - 0.5).to_i].to_f + sorted[(v + 0.5).to_i]).quo(2)
972
- else
973
- sorted[v.to_i]
974
- end
975
- end
976
-
977
- def linear_percentile(q)
978
- sorted = reject_values(*DaruLite::MISSING_VALUES).to_a.sort
979
- index = (q / 100.0) * ((size - count_values(*DaruLite::MISSING_VALUES)) + 1)
980
-
981
- k = index.truncate
982
- d = index % 1
983
-
984
- if k.zero?
985
- sorted[0]
986
- elsif k >= sorted.size
987
- sorted[-1]
988
- else
989
- sorted[k - 1] + (d * (sorted[k] - sorted[k - 1]))
990
- end
991
- end
992
-
993
- def raw_sample_without_replacement(sample)
994
- valid = indexes(*DaruLite::MISSING_VALUES).empty? ? self : reject_values(*DaruLite::MISSING_VALUES)
995
- raise ArgumentError, "Sample size couldn't be greater than n" if
996
- sample > valid.size
997
-
998
- out = []
999
- size = valid.size
1000
- while out.size < sample
1001
- value = rand(size)
1002
- out.push(value) unless out.include?(value)
1003
- end
1004
-
1005
- out.collect { |i| valid[i] }
1006
- end
1007
29
  end
1008
30
  end
1009
31
  end