spark-connect 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.
@@ -0,0 +1,211 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SparkConnect
4
+ module ML
5
+ # Encodes Ruby values as `Expression.Literal` protos (ML params, fetch
6
+ # arguments) and decodes the literal results of `MlCommandResult`, the same
7
+ # way PySpark's `pyspark.ml.connect.serialize` does.
8
+ module Serialize
9
+ Proto = SparkConnect::Proto
10
+
11
+ INT32_MIN = -(2**31)
12
+ INT32_MAX = (2**31) - 1
13
+
14
+ module_function
15
+
16
+ # @return [Proto::DataType] a `udt` data type for the given JVM class.
17
+ def udt_type(jvm_class)
18
+ Proto::DataType.new(udt: Proto::DataType::UDT.new(type: "udt", jvm_class: jvm_class))
19
+ end
20
+
21
+ # @return [Proto::Expression::Literal] a typed null.
22
+ def null_literal
23
+ Proto::Expression::Literal.new(null: Proto::DataType.new(null: Proto::DataType::NULL.new))
24
+ end
25
+
26
+ # @return [Proto::Expression::Literal] an int array (specialized array).
27
+ def int_list(values)
28
+ Proto::Expression::Literal.new(
29
+ specialized_array: Proto::Expression::Literal::SpecializedArray.new(
30
+ ints: Proto::Ints.new(values: values.map(&:to_i))
31
+ )
32
+ )
33
+ end
34
+
35
+ # @return [Proto::Expression::Literal] a double array (specialized array).
36
+ def double_list(values)
37
+ Proto::Expression::Literal.new(
38
+ specialized_array: Proto::Expression::Literal::SpecializedArray.new(
39
+ doubles: Proto::Doubles.new(values: values.map(&:to_f))
40
+ )
41
+ )
42
+ end
43
+
44
+ # @param value [Linalg::Vector, Linalg::Matrix, Object]
45
+ # @return [Proto::Expression::Literal]
46
+ def literal(value)
47
+ case value
48
+ when Linalg::Vector then vector_literal(value)
49
+ when Linalg::Matrix then matrix_literal(value)
50
+ when nil then null_literal
51
+ when true, false then Proto::Expression::Literal.new(boolean: value)
52
+ when Integer then integer_literal(value)
53
+ when Float then Proto::Expression::Literal.new(double: value)
54
+ when String, Symbol then Proto::Expression::Literal.new(string: value.to_s)
55
+ when Array then array_literal(value)
56
+ else raise IllegalArgumentError, "cannot send #{value.inspect} as an ML parameter"
57
+ end
58
+ end
59
+
60
+ # @api private
61
+ def integer_literal(value)
62
+ if value.between?(INT32_MIN, INT32_MAX)
63
+ Proto::Expression::Literal.new(integer: value)
64
+ else
65
+ Proto::Expression::Literal.new(long: value)
66
+ end
67
+ end
68
+
69
+ # Arrays of numbers and strings are typed `array` literals, which is the
70
+ # form the server reads for ML params. (Specialized arrays are used only
71
+ # inside vector and matrix structs, where the server expects them.)
72
+ # @api private
73
+ def array_literal(values)
74
+ if !values.empty? && values.all?(Numeric)
75
+ element_type = values.all?(Integer) ? Proto::DataType.new(integer: Proto::DataType::Integer.new) : Proto::DataType.new(double: Proto::DataType::Double.new)
76
+ elements = values.map { |v| element_type.integer ? Proto::Expression::Literal.new(integer: v) : Proto::Expression::Literal.new(double: v.to_f) }
77
+ return Proto::Expression::Literal.new(array: Proto::Expression::Literal::Array.new(element_type: element_type,
78
+ elements: elements))
79
+ end
80
+
81
+ element_type, elements = typed_elements(values)
82
+ Proto::Expression::Literal.new(
83
+ array: Proto::Expression::Literal::Array.new(element_type: element_type, elements: elements)
84
+ )
85
+ end
86
+
87
+ # @api private
88
+ def typed_elements(values)
89
+ if values.all?(String) || values.empty?
90
+ [Proto::DataType.new(string: Proto::DataType::String.new(collation: "UTF8_BINARY")),
91
+ values.map { |v| Proto::Expression::Literal.new(string: v) },]
92
+ elsif values.all?(Array)
93
+ inner_type, = typed_elements(values.first)
94
+ [Proto::DataType.new(array: Proto::DataType::Array.new(element_type: inner_type, contains_null: true)),
95
+ values.map { |v| array_literal(v) },]
96
+ else
97
+ raise IllegalArgumentError, "unsupported ML array elements #{values.inspect}"
98
+ end
99
+ end
100
+
101
+ # @api private
102
+ def vector_literal(vector)
103
+ builder = Proto::Expression::Literal::Struct.new(struct_type: udt_type(Linalg::VECTOR_UDT))
104
+ if vector.is_a?(Linalg::SparseVector)
105
+ builder.elements.push(
106
+ Proto::Expression::Literal.new(byte: 0),
107
+ Proto::Expression::Literal.new(integer: vector.size),
108
+ int_list(vector.indices),
109
+ double_list(vector.values)
110
+ )
111
+ else
112
+ builder.elements.push(
113
+ Proto::Expression::Literal.new(byte: 1),
114
+ null_literal,
115
+ null_literal,
116
+ double_list(vector.values)
117
+ )
118
+ end
119
+ Proto::Expression::Literal.new(struct: builder)
120
+ end
121
+
122
+ # @api private
123
+ def matrix_literal(matrix)
124
+ builder = Proto::Expression::Literal::Struct.new(struct_type: udt_type(Linalg::MATRIX_UDT))
125
+ if matrix.is_a?(Linalg::SparseMatrix)
126
+ builder.elements.push(
127
+ Proto::Expression::Literal.new(byte: 0),
128
+ Proto::Expression::Literal.new(integer: matrix.num_rows),
129
+ Proto::Expression::Literal.new(integer: matrix.num_cols),
130
+ int_list(matrix.col_ptrs),
131
+ int_list(matrix.row_indices),
132
+ double_list(matrix.values),
133
+ Proto::Expression::Literal.new(boolean: matrix.is_transposed)
134
+ )
135
+ else
136
+ builder.elements.push(
137
+ Proto::Expression::Literal.new(byte: 1),
138
+ Proto::Expression::Literal.new(integer: matrix.num_rows),
139
+ Proto::Expression::Literal.new(integer: matrix.num_cols),
140
+ null_literal,
141
+ null_literal,
142
+ double_list(matrix.values),
143
+ Proto::Expression::Literal.new(boolean: matrix.is_transposed)
144
+ )
145
+ end
146
+ Proto::Expression::Literal.new(struct: builder)
147
+ end
148
+
149
+ # Build the `MlParams` message for a param map (keys are {Param}s).
150
+ #
151
+ # @param values [Hash{Param => Object}]
152
+ # @return [Proto::MlParams]
153
+ def ml_params(values)
154
+ Proto::MlParams.new(params: values.to_h { |param, value| [param.spark_name, literal(value)] })
155
+ end
156
+
157
+ # Decode a literal returned by the server.
158
+ #
159
+ # @param literal [Proto::Expression::Literal]
160
+ # @return [Object]
161
+ def decode(literal)
162
+ case literal.literal_type
163
+ when :struct then decode_struct(literal.struct)
164
+ when :specialized_array then decode_specialized(literal.specialized_array)
165
+ when :array then literal.array.elements.map { |e| decode(e) }
166
+ when :null, nil then nil
167
+ else literal.public_send(literal.literal_type)
168
+ end
169
+ end
170
+
171
+ # @api private
172
+ def decode_struct(struct)
173
+ jvm_class = struct.struct_type.udt.jvm_class
174
+ case jvm_class
175
+ when Linalg::VECTOR_UDT then vector_from_elements(struct.elements)
176
+ when Linalg::MATRIX_UDT then matrix_from_elements(struct.elements)
177
+ else raise IllegalArgumentError, "unsupported struct #{jvm_class} in ML result"
178
+ end
179
+ end
180
+
181
+ # @api private
182
+ def vector_from_elements(elements)
183
+ if elements[0].byte.zero?
184
+ Linalg::SparseVector.new(elements[1].integer, decode(elements[2]), decode(elements[3]))
185
+ else
186
+ Linalg::DenseVector.new(decode(elements[3]))
187
+ end
188
+ end
189
+
190
+ # @api private
191
+ def matrix_from_elements(elements)
192
+ if elements[0].byte.zero?
193
+ Linalg::SparseMatrix.new(elements[1].integer, elements[2].integer, decode(elements[3]), decode(elements[4]),
194
+ decode(elements[5]), is_transposed: elements[6].boolean)
195
+ else
196
+ Linalg::DenseMatrix.new(elements[1].integer, elements[2].integer, decode(elements[5]),
197
+ is_transposed: elements[6].boolean)
198
+ end
199
+ end
200
+
201
+ # @api private
202
+ def decode_specialized(array)
203
+ %i[ints longs floats doubles bools strings].each do |field|
204
+ values = array.public_send(field)&.values.to_a
205
+ return values unless values.empty?
206
+ end
207
+ []
208
+ end
209
+ end
210
+ end
211
+ end
@@ -0,0 +1,127 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SparkConnect
4
+ module ML
5
+ # The `pyspark.ml.stat` statistics over Connect.
6
+ #
7
+ # Correlation, ChiSquareTest and KolmogorovSmirnovTest run on the server's
8
+ # ML helper (the same calls PySpark's connect client makes), and return
9
+ # lazy DataFrames. Summarizer builds an aggregate `Column` through Spark's
10
+ # internal `aggregate_metrics` function.
11
+ module Stat
12
+ # Helper-object calls return DataFrames: build one from a helper method chain.
13
+ # @api private
14
+ def self.helper_relation(session, method, args)
15
+ methods = [AttributeSupport.method_proto(method, args)]
16
+ ml_rel = Proto::MlRelation.new(fetch: Proto::Fetch.new(
17
+ obj_ref: Proto::ObjectRef.new(id: Rpc::HELPER_ID), methods: methods
18
+ ))
19
+ DataFrame.new(session, PlanBuilder.relation(session, ml_relation: ml_rel))
20
+ end
21
+
22
+ # Pearson or Spearman correlation matrix of a vector column.
23
+ class Correlation
24
+ class << self
25
+ # @param dataset [DataFrame]
26
+ # @param column [String] the vector column.
27
+ # @param method [String] "pearson" or "spearman".
28
+ # @return [DataFrame] a single row holding the correlation matrix.
29
+ def corr(dataset, column, method = "pearson")
30
+ Stat.helper_relation(dataset.session, "correlation", [dataset, column.to_s, method.to_s])
31
+ end
32
+ end
33
+ end
34
+
35
+ # Pearson's chi-squared independence test between a features column and a label column.
36
+ class ChiSquareTest
37
+ class << self
38
+ # @param dataset [DataFrame]
39
+ # @param features_col [String]
40
+ # @param label_col [String]
41
+ # @param flatten [Boolean] one row per statistic rather than one row in total.
42
+ # @return [DataFrame] columns `pValues`, `degreesOfFreedom`, `statistics`.
43
+ def test(dataset, features_col, label_col, flatten: false)
44
+ Stat.helper_relation(dataset.session, "chiSquareTest", [dataset, features_col.to_s, label_col.to_s, flatten])
45
+ end
46
+ end
47
+ end
48
+
49
+ # One-sample two-sided Kolmogorov-Smirnov test.
50
+ class KolmogorovSmirnovTest
51
+ class << self
52
+ # @param dataset [DataFrame]
53
+ # @param sample_col [String]
54
+ # @param dist_name [String] the reference distribution, e.g. "norm".
55
+ # @param params [Array<Numeric>] the distribution parameters.
56
+ # @return [DataFrame]
57
+ def test(dataset, sample_col, dist_name, *params)
58
+ Stat.helper_relation(dataset.session, "kolmogorovSmirnovTest",
59
+ [dataset, sample_col.to_s, dist_name.to_s, params.map(&:to_f)])
60
+ end
61
+ end
62
+ end
63
+
64
+ # Column-level summary statistics (`Summarizer.mean(col)` and friends).
65
+ class Summarizer
66
+ METRICS = %w[mean sum variance std count numNonZeros max min normL1 normL2].freeze
67
+ # Ruby names for the metrics: `Summarizer.num_non_zeros(col)` and so on.
68
+ RUBY_NAMES = METRICS.to_h do |m|
69
+ [m, m.gsub(/([a-z])([A-Z])/) do
70
+ "#{Regexp.last_match(1)}_#{Regexp.last_match(2).downcase}"
71
+ end.downcase,]
72
+ end
73
+
74
+ class << self
75
+ # A builder that computes the named metrics of a vector column.
76
+ # @param names [Array<String>] see {METRICS}.
77
+ # @return [SummaryBuilder]
78
+ def metrics(*names)
79
+ unknown = names.map(&:to_s) - METRICS
80
+ raise IllegalArgumentError, "unknown metrics #{unknown.join(', ')}" unless unknown.empty?
81
+
82
+ SummaryBuilder.new(names.map(&:to_s))
83
+ end
84
+
85
+ # The value of one metric, as a Column.
86
+ # @param name [String]
87
+ # @param col [Column, String] the vector column.
88
+ # @param weight [Column, nil]
89
+ # @return [Column]
90
+ def metric(name, col, weight = nil)
91
+ metrics(name).summary(col, weight).get_field(name.to_s)
92
+ end
93
+
94
+ RUBY_NAMES.each do |metric_name, ruby_name|
95
+ define_method(ruby_name) { |col, weight = nil| metric(metric_name, col, weight) }
96
+ end
97
+ end
98
+ end
99
+
100
+ # The metrics requested from a {Summarizer}.
101
+ class SummaryBuilder
102
+ # @return [Array<String>]
103
+ attr_reader :metric_names
104
+
105
+ # @param names [Array<String>]
106
+ def initialize(names)
107
+ @metric_names = names
108
+ end
109
+
110
+ # The struct column holding every requested metric, keyed by name.
111
+ # @param features_col [Column, String]
112
+ # @param weight_col [Column, nil]
113
+ # @return [Column]
114
+ def summary(features_col, weight_col = nil)
115
+ names = Column.new(Proto::Expression.new(
116
+ unresolved_function: Proto::Expression::UnresolvedFunction.new(
117
+ function_name: "array",
118
+ arguments: metric_names.map { |m| Column.to_col(m).to_expr }
119
+ )
120
+ ))
121
+ Functions.internal_call("aggregate_metrics", names, Functions.column_of(features_col),
122
+ weight_col ? Functions.column_of(weight_col) : Column.to_col(1.0))
123
+ end
124
+ end
125
+ end
126
+ end
127
+ end