From the Binary, create a list or 1-d numpy array of numbers, along with dtype and padding. :param return_numpy: If True, BinaryVector.data will be a one-dimensional numpy array. By default, it is a list. :return: BinaryVector .. versionadded:: 4.10
(self, return_numpy: bool = False)
| 542 | return cls(metadata + data, subtype=VECTOR_SUBTYPE) |
| 543 | |
| 544 | def as_vector(self, return_numpy: bool = False) -> BinaryVector: |
| 545 | """From the Binary, create a list or 1-d numpy array of numbers, along with dtype and padding. |
| 546 | |
| 547 | :param return_numpy: If True, BinaryVector.data will be a one-dimensional numpy array. By default, it is a list. |
| 548 | :return: BinaryVector |
| 549 | |
| 550 | .. versionadded:: 4.10 |
| 551 | """ |
| 552 | |
| 553 | if self.subtype != VECTOR_SUBTYPE: |
| 554 | raise ValueError(f"Cannot decode subtype {self.subtype} as a vector") |
| 555 | |
| 556 | dtype, padding = struct.unpack_from("<sB", self) |
| 557 | dtype = BinaryVectorDtype(dtype) |
| 558 | offset = 2 |
| 559 | n_bytes = len(self) - offset |
| 560 | |
| 561 | if padding and dtype != BinaryVectorDtype.PACKED_BIT: |
| 562 | raise ValueError( |
| 563 | f"Corrupt data. Padding ({padding}) must be 0 for all but PACKED_BIT dtypes. ({dtype=})" |
| 564 | ) |
| 565 | |
| 566 | if not return_numpy: |
| 567 | if dtype == BinaryVectorDtype.INT8: |
| 568 | dtype_format = "b" |
| 569 | format_string = f"<{n_bytes}{dtype_format}" |
| 570 | vector = list(struct.unpack_from(format_string, self, offset)) |
| 571 | return BinaryVector(vector, dtype, padding) |
| 572 | |
| 573 | elif dtype == BinaryVectorDtype.FLOAT32: |
| 574 | n_values = n_bytes // 4 |
| 575 | if n_bytes % 4: |
| 576 | raise ValueError( |
| 577 | "Corrupt data. N bytes for a float32 vector must be a multiple of 4." |
| 578 | ) |
| 579 | dtype_format = "f" |
| 580 | format_string = f"<{n_values}{dtype_format}" |
| 581 | vector = list(struct.unpack_from(format_string, self, offset)) |
| 582 | return BinaryVector(vector, dtype, padding) |
| 583 | |
| 584 | elif dtype == BinaryVectorDtype.PACKED_BIT: |
| 585 | # data packed as uint8 |
| 586 | if padding and not n_bytes: |
| 587 | raise ValueError("Corrupt data. Vector has a padding P, but no data.") |
| 588 | if padding > 7 or padding < 0: |
| 589 | raise ValueError(f"Corrupt data. Padding ({padding}) must be between 0 and 7.") |
| 590 | dtype_format = "B" |
| 591 | format_string = f"<{n_bytes}{dtype_format}" |
| 592 | unpacked_uint8s = list(struct.unpack_from(format_string, self, offset)) |
| 593 | if padding and n_bytes and unpacked_uint8s[-1] & (1 << padding) - 1 != 0: |
| 594 | warnings.warn( |
| 595 | "Vector has a padding P, but bits in the final byte lower than P are non-zero. For pymongo>=5.0, they must be zero.", |
| 596 | DeprecationWarning, |
| 597 | stacklevel=2, |
| 598 | ) |
| 599 | return BinaryVector(unpacked_uint8s, dtype, padding) |
| 600 | |
| 601 | else: |