| 19 | |
| 20 | |
| 21 | class BasicVectorStore: |
| 22 | def __init__(self, *, vectors: npt.NDArray, **kwargs: Any) -> None: |
| 23 | """ |
| 24 | A basic vector store that just stores vectors. |
| 25 | |
| 26 | Note that we use kwargs in order to use this class as a mixin. |
| 27 | |
| 28 | :param vectors: The vectors to store. |
| 29 | :param **kwargs: Additional arguments. These are passed on to the super class. |
| 30 | """ |
| 31 | super().__init__(**kwargs) |
| 32 | self._vectors = vectors |
| 33 | |
| 34 | def _update_precomputed_data(self) -> None: |
| 35 | """Update precomputed data based on the metric.""" |
| 36 | # NOTE: this is a no-op in the base implementation. |
| 37 | return |
| 38 | |
| 39 | def get_by_index(self, indices: list[int]) -> npt.NDArray: |
| 40 | """Get vectors by index.""" |
| 41 | return self._vectors[indices] |
| 42 | |
| 43 | def insert(self, vectors: npt.NDArray) -> None: |
| 44 | """Insert vectors into the vector space.""" |
| 45 | self._vectors = np.vstack([self._vectors, vectors]) |
| 46 | self._update_precomputed_data() |
| 47 | |
| 48 | def delete(self, indices: list[int]) -> None: |
| 49 | """Deletes specific indices from the vector space.""" |
| 50 | self._vectors = np.delete(self._vectors, indices, axis=0) |
| 51 | self._update_precomputed_data() |
| 52 | |
| 53 | def save(self, path: Path) -> None: |
| 54 | """Save the vectors to a path.""" |
| 55 | path = path / "vectors.npy" |
| 56 | with open(path, "wb") as f: |
| 57 | np.save(f, self._vectors) |
| 58 | |
| 59 | @staticmethod |
| 60 | def _load_vectors(path: Path) -> npt.NDArray: |
| 61 | """Load the vectors from a path.""" |
| 62 | path = path / "vectors.npy" |
| 63 | with open(path, "rb") as f: |
| 64 | vectors = np.load(f) |
| 65 | |
| 66 | return vectors |
| 67 | |
| 68 | @classmethod |
| 69 | def load(cls, path: Path) -> BasicVectorStore: |
| 70 | """Load the vectors from a path.""" |
| 71 | vectors = cls._load_vectors(path) |
| 72 | return cls(vectors=vectors) |
| 73 | |
| 74 | @property |
| 75 | def dim(self) -> int: |
| 76 | """The size of the space.""" |
| 77 | return self.vectors.shape[1] |
| 78 |
no outgoing calls
no test coverage detected
searching dependent graphs…