Module: Neighbor::Utils
- Defined in:
- lib/neighbor/utils.rb
Class Method Summary collapse
- .array?(value) ⇒ Boolean
- .normalize(value, column_info:) ⇒ Object
- .validate(value, dimensions:, column_info:) ⇒ Object
- .validate_dimensions(value, type, expected) ⇒ Object
- .validate_finite(value, type) ⇒ Object
Class Method Details
.array?(value) ⇒ Boolean
42 43 44 |
# File 'lib/neighbor/utils.rb', line 42 def self.array?(value) !value.nil? && value.respond_to?(:to_a) end |
.normalize(value, column_info:) ⇒ Object
31 32 33 34 35 36 37 38 39 40 |
# File 'lib/neighbor/utils.rb', line 31 def self.normalize(value, column_info:) raise Error, "Normalize not supported for type" unless [:cube, :vector, :halfvec].include?(column_info&.type) norm = Math.sqrt(value.sum { |v| v * v }) # store zero vector as all zeros # since NaN makes the distance always 0 # could also throw error norm > 0 ? value.map { |v| v / norm } : value end |
.validate(value, dimensions:, column_info:) ⇒ Object
21 22 23 24 25 26 27 28 29 |
# File 'lib/neighbor/utils.rb', line 21 def self.validate(value, dimensions:, column_info:) if ( = validate_dimensions(value, column_info&.type, dimensions || column_info&.limit)) raise Error, end if !validate_finite(value, column_info&.type) raise Error, "Values must be finite" end end |
.validate_dimensions(value, type, expected) ⇒ Object
3 4 5 6 7 8 |
# File 'lib/neighbor/utils.rb', line 3 def self.validate_dimensions(value, type, expected) dimensions = type == :sparsevec ? value.dimensions : value.size if expected && dimensions != expected "Expected #{expected} dimensions, not #{dimensions}" end end |
.validate_finite(value, type) ⇒ Object
10 11 12 13 14 15 16 17 18 19 |
# File 'lib/neighbor/utils.rb', line 10 def self.validate_finite(value, type) case type when :bit true when :sparsevec value.values.all?(&:finite?) else value.all?(&:finite?) end end |