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
@@ -3,40 +3,10 @@ module DaruLite
3
3
 
4
4
  module IOHelpers
5
5
  class << self
6
- INT_PATTERN = /^[-+]?\d+$/
7
- FLOAT_PATTERN = /^[-+]?\d+[,.]?\d*(e-?\d+)?$/
8
-
9
- def process_row(row, empty)
10
- row.to_a.map do |c|
11
- if empty.include?(c)
12
- # FIXME: As far as I can guess, it will never work.
13
- # It is called only inside `from_plaintext`, and there
14
- # data is splitted by `\s+` -- there is no chance that
15
- # "empty" (currently just '') will be between data?..
16
- nil
17
- else
18
- try_string_to_number(c)
19
- end
20
- end
21
- end
22
-
23
6
  def open_local_or_remote_file(path)
24
7
  uri = URI.parse(path)
25
8
  uri.is_a?(URI::HTTP) || uri.is_a?(URI::HTTPS) ? uri.open : File.open(uri.path)
26
9
  end
27
-
28
- private
29
-
30
- def try_string_to_number(s)
31
- case s
32
- when INT_PATTERN
33
- s.to_i
34
- when FLOAT_PATTERN
35
- s.tr(',', '.').to_f
36
- else
37
- s
38
- end
39
- end
40
10
  end
41
11
  end
42
12
 
@@ -44,53 +14,6 @@ module DaruLite
44
14
  class << self
45
15
  DARU_OPT_KEYS = %i[clone order index name].freeze
46
16
 
47
- # Functions for loading/writing Excel files.
48
-
49
- def from_excel(path, opts = {})
50
- opts = {
51
- worksheet_id: 0,
52
- row_id: 0
53
- }.merge opts
54
-
55
- worksheet, headers = read_from_excel(path, opts)
56
- df = DaruLite::DataFrame.new({})
57
- headers.each_with_index do |h, i|
58
- col = worksheet.column(i).to_a
59
- col.delete_at 0
60
- df[h] = col
61
- end
62
-
63
- df
64
- end
65
-
66
- def read_from_excel(path, opts)
67
- optional_gem 'spreadsheet', '~>1.3.0'
68
-
69
- worksheet_id = opts[:worksheet_id]
70
- row_id = opts[:row_id]
71
- book = Spreadsheet.open path
72
- worksheet = book.worksheet worksheet_id
73
- headers = ArrayHelper.recode_repeated(worksheet.row(row_id)).map(&:to_sym)
74
-
75
- [worksheet, headers]
76
- end
77
-
78
- def dataframe_write_excel(dataframe, path, _opts = {})
79
- book = Spreadsheet::Workbook.new
80
- sheet = book.create_worksheet
81
- format = Spreadsheet::Format.new color: :blue, weight: :bold
82
-
83
- sheet.row(0).concat(dataframe.vectors.to_a.map(&:to_s)) # Unfreeze strings
84
- sheet.row(0).default_format = format
85
- i = 1
86
- dataframe.each_row do |row|
87
- sheet.row(i).concat(row.to_a)
88
- i += 1
89
- end
90
-
91
- book.write(path)
92
- end
93
-
94
17
  # Functions for loading/writing CSV files
95
18
  def from_csv(path, opts = {})
96
19
  daru_options, opts = from_csv_prepare_opts opts
@@ -125,78 +48,8 @@ module DaruLite
125
48
  writer.close
126
49
  end
127
50
 
128
- # Execute a query and create a data frame from the result
129
- #
130
- # @param db [ActiveRecord::ConnectionAdapters::AbstractAdapter, String] An ActiveRecord connection
131
- # OR Path to a SQlite3 database.
132
- # @param query [String] The query to be executed
133
- #
134
- # @return A dataframe containing the data resulting from the query
135
- def from_sql(db, query)
136
- require 'daru_lite/io/sql_data_source'
137
- SqlDataSource.make_dataframe(db, query)
138
- end
139
-
140
- def dataframe_write_sql(ds, dbh, table)
141
- query = "INSERT INTO #{table} (#{ds.vectors.to_a.join(',')}) VALUES (#{(['?'] * ds.vectors.size).join(',')})"
142
- sth = dbh.prepare(query)
143
- ds.each_row { |c| sth.execute(*c.to_a) }
144
- end
145
-
146
- # Load dataframe from AR::Relation
147
- #
148
- # @param relation [ActiveRecord::Relation] A relation to be used to load the contents of dataframe
149
- #
150
- # @return A dataframe containing the data in the given relation
151
- def from_activerecord(relation, *fields)
152
- fields = relation.klass.column_names if fields.empty?
153
- fields = fields.map(&:to_sym)
154
-
155
- result = relation.pluck(*fields).transpose
156
- DaruLite::DataFrame.new(result, order: fields).tap(&:update)
157
- end
158
-
159
- # Loading data from plain text files
160
-
161
- def from_plaintext(filename, fields)
162
- ds = DaruLite::DataFrame.new({}, order: fields)
163
- File.open(filename, 'r') do |fp|
164
- fp.each_line do |line|
165
- row = DaruLite::IOHelpers.process_row(line.strip.split(/\s+/), [''])
166
- next if row == ["\x1A"]
167
-
168
- ds.add_row(row)
169
- end
170
- end
171
- ds.update
172
- fields.each { |f| ds[f].rename f }
173
- ds
174
- end
175
-
176
- # Loading and writing Marshalled DataFrame/Vector
177
- def save(klass, filename)
178
- File.open(filename, 'w') { Marshal.dump(klass, it) }
179
- end
180
-
181
- def load(filename)
182
- if File.exist? filename
183
- o = false
184
- File.open(filename, 'r') { |fp| o = Marshal.load(fp) }
185
- o
186
- else
187
- false
188
- end
189
- end
190
-
191
51
  private
192
52
 
193
- def optional_gem(name, version)
194
- gem name, version
195
- require name
196
- rescue LoadError
197
- DaruLite.error "\nInstall the #{name} gem version #{version} for using #{name} functions."
198
- end
199
-
200
53
  def from_csv_prepare_opts(opts)
201
54
  opts[:col_sep] ||= ','
202
55
  opts[:skip_blanks] ||= true
@@ -240,54 +93,6 @@ module DaruLite
240
93
  csv_as_arrays = csv_as_arrays.transpose
241
94
  headers.each_with_index.to_h { |h, i| [h, csv_as_arrays[i]] }
242
95
  end
243
-
244
- def html_parse_table(table)
245
- headers, headers_size = html_scrape_tag(table, 'th')
246
- data, size = html_scrape_tag(table, 'td')
247
- data.keep_if { |x| x.count == size }
248
- order, indice = html_parse_hash(headers, size, headers_size) if headers_size >= size
249
- return unless (indice.nil? || indice.count == data.count) && !order.nil? && order.any?
250
-
251
- { data: data.compact, index: indice, order: order }
252
- end
253
-
254
- def html_scrape_tag(table, tag)
255
- arr = table.search('tr').map { |row| row.search(tag).map { |val| val.text.strip } }
256
- size = arr.map(&:count).max
257
- [arr, size]
258
- end
259
-
260
- # Splits headers (all th tags) into order and index. Wherein,
261
- # Order : All <th> tags on first proper row of HTML table
262
- # index : All <th> tags on first proper column of HTML table
263
- def html_parse_hash(headers, size, headers_size)
264
- headers_index = headers.find_index { |x| x.count == headers_size }
265
- order = headers[headers_index]
266
- order_index = order.count - size
267
- order = order[order_index..]
268
- indice = headers[(headers_index + 1)..].flatten
269
- indice = nil if indice.to_a.empty?
270
- [order, indice]
271
- end
272
-
273
- def html_search(table, match = nil)
274
- match.nil? || (table.to_s.include? match)
275
- end
276
-
277
- # Allows user to override the scraped order / index / data
278
- def html_decide_values(scraped_val = {}, user_val = {})
279
- %I[data index name order].each do |key|
280
- user_val[key] ||= scraped_val[key]
281
- end
282
- user_val
283
- end
284
-
285
- def html_table_to_dataframe(table)
286
- DaruLite::DataFrame.rows table[:data],
287
- index: table[:index],
288
- order: table[:order],
289
- name: table[:name]
290
- end
291
96
  end
292
97
  end
293
98
  end
@@ -18,6 +18,33 @@ module DaruLite
18
18
  binary_op :/, other
19
19
  end
20
20
 
21
+ # Divides by +divisor+, or returns 0.0 (a Float, whatever the values)
22
+ # for every number when +divisor+ is zero, NaN or nil, where #/ would
23
+ # raise or return Infinity or NaN. Missing values (nil and NaN) stay as
24
+ # they are in both cases; with such a divisor, so does anything that
25
+ # is not a number.
26
+ #
27
+ # The division itself is #/: an Integer vector divided by an Integer
28
+ # rounds down (floor division). Pass a Float divisor to get ratios.
29
+ #
30
+ # @param divisor [Numeric, nil] a scalar: unlike #/, a Vector is not accepted
31
+ # @raise [ArgumentError] when +divisor+ is neither Numeric nor nil
32
+ # @return [DaruLite::Vector]
33
+ # @example
34
+ # vector = DaruLite::Vector.new([1, nil, 3])
35
+ # vector.divide_or_zero(2).to_a #=> [0, nil, 1]
36
+ # vector.divide_or_zero(2.0).to_a #=> [0.5, nil, 1.5]
37
+ # vector.divide_or_zero(0).to_a #=> [0.0, nil, 0.0]
38
+ def divide_or_zero(divisor)
39
+ unless divisor.nil? || divisor.is_a?(Numeric)
40
+ raise ArgumentError, "divisor must be Numeric or nil, not #{divisor.class}"
41
+ end
42
+ return self / divisor unless divisor.nil? || divisor.zero? || not_a_number?(divisor)
43
+
44
+ zeroed = map { |value| value.is_a?(Numeric) && !not_a_number?(value) ? 0.0 : value }
45
+ DaruLite::Vector.new(zeroed, name: @name, index: @index)
46
+ end
47
+
21
48
  def %(other)
22
49
  binary_op :%, other
23
50
  end
@@ -72,6 +99,10 @@ module DaruLite
72
99
 
73
100
  private
74
101
 
102
+ def not_a_number?(value)
103
+ value.respond_to?(:nan?) && value.nan?
104
+ end
105
+
75
106
  def math_unary_op(operation)
76
107
  recode { |e| Math.send(operation, e) unless e.nil? }
77
108
  end
@@ -0,0 +1,134 @@
1
+ module DaruLite
2
+ module Maths
3
+ module Statistics
4
+ module Vector
5
+ # Central tendency, counts and frequencies.
6
+ module Descriptive
7
+ def mean
8
+ @data.mean
9
+ end
10
+
11
+ def sum
12
+ @data.sum
13
+ end
14
+
15
+ def product
16
+ @data.product
17
+ end
18
+
19
+ def range
20
+ max - min
21
+ end
22
+
23
+ def median
24
+ @data.respond_to?(:median) ? @data.median : percentile(50)
25
+ end
26
+
27
+ def mode
28
+ mode = frequencies.to_h.select { |_, v| v == frequencies.max }.keys
29
+ mode.size > 1 ? DaruLite::Vector.new(mode) : mode.first
30
+ end
31
+
32
+ # Create a summary of count, mean, standard deviation, min and max of
33
+ # the vector in one shot.
34
+ #
35
+ # == Arguments
36
+ #
37
+ # +methods+ - An array with aggregation methods specified as symbols to
38
+ # be applied to vectors. Default is [:count, :mean, :std, :max,
39
+ # :min]. Methods will be applied in the specified order.
40
+ def describe(methods = nil)
41
+ methods ||= %i[count mean std min max]
42
+ description = methods.map { |m| send(m) }
43
+ DaruLite::Vector.new(description, index: methods, name: :statistics)
44
+ end
45
+
46
+ def median_absolute_deviation
47
+ m = median
48
+ recode { |val| (val - m).abs }.median
49
+ end
50
+
51
+ alias mad median_absolute_deviation
52
+
53
+ def standard_error
54
+ standard_deviation_sample / Math.sqrt(size - count_values(*DaruLite::MISSING_VALUES))
55
+ end
56
+
57
+ def sum_of_squared_deviation
58
+ (
59
+ reject_values(*DaruLite::MISSING_VALUES).data.inject(0) { |a, x| (x**2) + a } -
60
+ (sum**2).quo(size - count_values(*DaruLite::MISSING_VALUES)).to_f
61
+ ).to_f
62
+ end
63
+
64
+ # Retrieve unique values of non-nil data
65
+ def factors
66
+ reject_values(*DaruLite::MISSING_VALUES).uniq.reset_index!
67
+ end
68
+
69
+ def frequencies
70
+ DaruLite::Vector.new(
71
+ @data.each_with_object(Hash.new(0)) do |element, hash|
72
+ hash[element] += 1 unless element.nil?
73
+ end
74
+ )
75
+ end
76
+
77
+ def proportions
78
+ len = size - count_values(*DaruLite::MISSING_VALUES)
79
+ frequencies.to_h.transform_values do |count|
80
+ count / len.to_f
81
+ end
82
+ end
83
+
84
+ def ranked
85
+ sum = 0
86
+ r = frequencies.to_h.sort.each_with_object({}) do |(el, count), memo|
87
+ memo[el] = ((sum + 1) + (sum + count)).quo(2)
88
+ sum += count
89
+ end
90
+
91
+ recode { |e| r[e] }
92
+ end
93
+
94
+ def coefficient_of_variation
95
+ standard_deviation_sample / mean
96
+ end
97
+
98
+ # Retrieves number of cases which comply condition. If block given,
99
+ # retrieves number of instances where block returns true. If other
100
+ # values given, retrieves the frequency for this value. If no value
101
+ # given, counts the number of non-nil elements in the Vector.
102
+ def count(value = false, &block)
103
+ if block
104
+ @data.count(&block)
105
+ elsif value
106
+ count { |val| val == value }
107
+ else
108
+ size - indexes(*DaruLite::MISSING_VALUES).size
109
+ end
110
+ end
111
+
112
+ # Count number of occurrences of each value in the Vector
113
+ def value_counts
114
+ DaruLite::Vector.new(@data.tally)
115
+ end
116
+
117
+ def proportion(value = 1)
118
+ if include_with_nan?(DaruLite::MISSING_VALUES, value)
119
+ raise ArgumentError, 'Cannot calculate the proportion of a missing value'
120
+ end
121
+
122
+ present = size - count_values(*DaruLite::MISSING_VALUES)
123
+ raise ArgumentError, 'Cannot calculate a proportion without any non-missing value' if present.zero?
124
+
125
+ count { |element| element == value }.quo(present).to_f
126
+ end
127
+
128
+ alias cov coefficient_of_variation
129
+ alias se standard_error
130
+ end
131
+ end
132
+ end
133
+ end
134
+ end
@@ -0,0 +1,120 @@
1
+ module DaruLite
2
+ module Maths
3
+ module Statistics
4
+ module Vector
5
+ # Variance, covariance, standard deviation and shape of the distribution.
6
+ module Dispersion
7
+ # Sample variance with denominator (N-1)
8
+ def variance_sample(m = nil)
9
+ m ||= mean
10
+ if @data.respond_to? :variance_sample
11
+ @data.variance_sample m
12
+ else
13
+ sum_of_squares(m).quo(size - count_values(*DaruLite::MISSING_VALUES) - 1)
14
+ end
15
+ end
16
+
17
+ # Population variance with denominator (N)
18
+ def variance_population(m = nil)
19
+ m ||= mean
20
+ if @data.respond_to? :variance_population
21
+ @data.variance_population m
22
+ else
23
+ sum_of_squares(m).quo(size - count_values(*DaruLite::MISSING_VALUES)).to_f
24
+ end
25
+ end
26
+
27
+ # Sample covariance with denominator (N-1)
28
+ def covariance_sample(other)
29
+ size == other.size or raise ArgumentError, 'size of both the vectors must be equal'
30
+ covariance_sum(other) / (size - count_values(*DaruLite::MISSING_VALUES) - 1)
31
+ end
32
+
33
+ # Population covariance with denominator (N)
34
+ def covariance_population(other)
35
+ size == other.size or raise ArgumentError, 'size of both the vectors must be equal'
36
+ covariance_sum(other) / (size - count_values(*DaruLite::MISSING_VALUES))
37
+ end
38
+
39
+ def sum_of_squares(m = nil)
40
+ m ||= mean
41
+ reject_values(*DaruLite::MISSING_VALUES).data.inject(0) do |memo, val|
42
+ memo + ((val - m)**2)
43
+ end
44
+ end
45
+
46
+ def standard_deviation_population(m = nil)
47
+ m ||= mean
48
+ if @data.respond_to? :standard_deviation_population
49
+ @data.standard_deviation_population(m)
50
+ else
51
+ Math.sqrt(variance_population(m))
52
+ end
53
+ end
54
+
55
+ def standard_deviation_sample(m = nil)
56
+ m ||= mean
57
+ if @data.respond_to? :standard_deviation_sample
58
+ @data.standard_deviation_sample m
59
+ else
60
+ Math.sqrt(variance_sample(m))
61
+ end
62
+ end
63
+
64
+ # Calculate skewness using (sigma(xi - mean)^3)/((N)*std_dev_sample^3)
65
+ def skew(m = nil)
66
+ if @data.respond_to? :skew
67
+ @data.skew
68
+ else
69
+ m ||= mean
70
+ th = reject_values(*DaruLite::MISSING_VALUES).data.inject(0) { |memo, val| memo + ((val - m)**3) }
71
+ th.quo((size - indexes(*DaruLite::MISSING_VALUES).size) * (standard_deviation_sample(m)**3))
72
+ end
73
+ end
74
+
75
+ def kurtosis(m = nil)
76
+ if @data.respond_to? :kurtosis
77
+ @data.kurtosis
78
+ else
79
+ m ||= mean
80
+ fo = reject_values(*DaruLite::MISSING_VALUES).data.inject(0) { |a, x| a + ((x - m)**4) }
81
+ fo.quo((size - indexes(*DaruLite::MISSING_VALUES).size) * (standard_deviation_sample(m)**4)) - 3
82
+ end
83
+ end
84
+
85
+ def average_deviation_population(m = nil)
86
+ must_be_numeric!
87
+ m ||= mean
88
+ reject_values(*DaruLite::MISSING_VALUES).data.inject(0) do |memo, val|
89
+ (val - m).abs + memo
90
+ end.quo(size - count_values(*DaruLite::MISSING_VALUES))
91
+ end
92
+
93
+ alias sdp standard_deviation_population
94
+ alias sds standard_deviation_sample
95
+ alias std sds
96
+ alias adp average_deviation_population
97
+ alias variance variance_sample
98
+ alias covariance covariance_sample
99
+ alias sd standard_deviation_sample
100
+ alias ss sum_of_squares
101
+
102
+ private
103
+
104
+ def covariance_sum(other)
105
+ self_mean = mean
106
+ other_mean = other.mean
107
+ @data
108
+ .zip(other.data).inject(0) do |res, (d, o)|
109
+ res + if !d || !o
110
+ 0
111
+ else
112
+ (d - self_mean) * (o - other_mean)
113
+ end
114
+ end
115
+ end
116
+ end
117
+ end
118
+ end
119
+ end
120
+ end