Skip to content

Commit

Permalink
Add convenience constructors for block encodings (#1243)
Browse files Browse the repository at this point in the history
* Add convenience constructors for block encodings

* Fix import of `Self`

* Add docstrings
  • Loading branch information
charlesyuan314 authored Aug 1, 2024
1 parent 5db8857 commit c3a23ad
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
6 changes: 6 additions & 0 deletions qualtran/bloqs/block_encoding/linear_combination.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import numpy as np
from attrs import evolve, field, frozen, validators
from typing_extensions import Self

from qualtran import (
bloq_example,
Expand Down Expand Up @@ -106,6 +107,11 @@ def __attrs_post_init__(self):
"If given, select oracle must have block encoding `system` register as target."
)

@classmethod
def of_terms(cls, *terms: Tuple[float, BlockEncoding], lambd_bits: SymbolicInt = 1) -> Self:
"""Construct a `LinearCombination` from pairs of (coefficient, block encoding)."""
return cls(tuple(t[1] for t in terms), tuple(t[0] for t in terms), lambd_bits)

@cached_property
def signed_block_encodings(self):
"""Appropriately negated constituent block encodings."""
Expand Down
6 changes: 6 additions & 0 deletions qualtran/bloqs/block_encoding/product.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import cirq
from attrs import evolve, field, frozen, validators
from numpy.typing import NDArray
from typing_extensions import Self

from qualtran import (
bloq_example,
Expand Down Expand Up @@ -87,6 +88,11 @@ def __attrs_post_init__(self):
if not all(u.system_bitsize == self.system_bitsize for u in self.block_encodings):
raise ValueError("All block encodings must have the same system size.")

@classmethod
def of(cls, *block_encodings: BlockEncoding) -> Self:
"""Construct a `Product` from block encodings."""
return cls(block_encodings)

@cached_property
def signature(self) -> Signature:
return Signature.build_from_dtypes(
Expand Down
6 changes: 6 additions & 0 deletions qualtran/bloqs/block_encoding/tensor_product.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from typing import Dict, Set, Tuple

from attrs import evolve, field, frozen, validators
from typing_extensions import Self

from qualtran import (
bloq_example,
Expand Down Expand Up @@ -64,6 +65,11 @@ class TensorProduct(BlockEncoding):
converter=lambda x: x if isinstance(x, tuple) else tuple(x), validator=validators.min_len(1)
)

@classmethod
def of(cls, *block_encodings: BlockEncoding) -> Self:
"""Construct a `TensorProduct` from block encodings."""
return cls(block_encodings)

@cached_property
def signature(self) -> Signature:
return Signature.build_from_dtypes(
Expand Down

0 comments on commit c3a23ad

Please sign in to comment.