Skip to content

Commit

Permalink
Use classmethod decorator for more methods
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Jun 4, 2024
1 parent 3a4118c commit fb8edf9
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 12 deletions.
10 changes: 6 additions & 4 deletions pgvector/utils/bit.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,15 @@ def to_text(self):
def to_binary(self):
return pack('>i', len(self._value)) + np.packbits(self._value).tobytes()

def from_text(value):
return Bit(np.asarray([v != '0' for v in value], dtype=bool))
@classmethod
def from_text(cls, value):
return cls(np.asarray([v != '0' for v in value], dtype=bool))

def from_binary(value):
@classmethod
def from_binary(cls, value):
count = unpack_from('>i', value)[0]
buf = np.frombuffer(value, dtype=np.uint8, offset=4)
return Bit(np.unpackbits(buf, count=count).astype(bool))
return cls(np.unpackbits(buf, count=count).astype(bool))

@classmethod
def _to_db(cls, value):
Expand Down
10 changes: 6 additions & 4 deletions pgvector/utils/sparsevec.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,21 +40,23 @@ def to_binary(self):
nnz = len(self._indices)
return pack(f'>iii{nnz}i{nnz}f', self._dim, nnz, 0, *self._indices, *self._values)

def from_text(value):
@classmethod
def from_text(cls, value):
elements, dim = value.split('/')
indices = []
values = []
for e in elements[1:-1].split(','):
i, v = e.split(':')
indices.append(int(i) - 1)
values.append(float(v))
return SparseVector(int(dim), indices, values)
return cls(int(dim), indices, values)

def from_binary(value):
@classmethod
def from_binary(cls, value):
dim, nnz, unused = unpack_from('>iii', value)
indices = unpack_from(f'>{nnz}i', value, 12)
values = unpack_from(f'>{nnz}f', value, 12 + nnz * 4)
return SparseVector(int(dim), indices, values)
return cls(int(dim), indices, values)

@classmethod
def _to_db(cls, value, dim=None):
Expand Down
10 changes: 6 additions & 4 deletions pgvector/utils/vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,14 @@ def to_text(self):
def to_binary(self):
return pack('>HH', self.dim(), 0) + self._value.tobytes()

def from_text(value):
return Vector([float(v) for v in value[1:-1].split(',')])
@classmethod
def from_text(cls, value):
return cls([float(v) for v in value[1:-1].split(',')])

def from_binary(value):
@classmethod
def from_binary(cls, value):
dim, unused = unpack_from('>HH', value)
return Vector(np.frombuffer(value, dtype='>f4', count=dim, offset=4))
return cls(np.frombuffer(value, dtype='>f4', count=dim, offset=4))

@classmethod
def _to_db(cls, value, dim=None):
Expand Down

0 comments on commit fb8edf9

Please sign in to comment.