Class: Pgvector::Vector

Inherits:
Object
  • Object
show all
Defined in:
lib/pgvector/vector.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ Vector

Returns a new instance of Vector.



3
4
5
6
7
8
9
10
11
# File 'lib/pgvector/vector.rb', line 3

def initialize(data)
  # keep as NArray when possible for performance
  @data =
    if numo?(data)
      data.cast_to(Numo::SFloat)
    else
      data.to_a.map(&:to_f)
    end
end

Class Method Details

.from_binary(string) ⇒ Object



17
18
19
20
21
# File 'lib/pgvector/vector.rb', line 17

def self.from_binary(string)
  dim, unused = string[0, 4].unpack("nn")
  raise "expected unused to be 0" if unused != 0
  Vector.new(string[4..-1].unpack("g#{dim}"))
end

.from_text(string) ⇒ Object



13
14
15
# File 'lib/pgvector/vector.rb', line 13

def self.from_text(string)
  Vector.new(string[1..-2].split(",").map(&:to_f))
end

Instance Method Details

#to_aObject



27
28
29
# File 'lib/pgvector/vector.rb', line 27

def to_a
  @data.to_a
end

#to_binaryObject



31
32
33
34
35
36
37
38
39
# File 'lib/pgvector/vector.rb', line 31

def to_binary
  if numo?(@data)
    [@data.shape[0], 0].pack("s>s>") + @data.to_network.to_binary
  else
    buffer = [@data.size, 0].pack("s>s>")
    @data.pack("g*", buffer: buffer)
    buffer
  end
end

#to_sObject



23
24
25
# File 'lib/pgvector/vector.rb', line 23

def to_s
  "[#{@data.to_a.map(&:to_f).join(",")}]"
end