Skip to content

Commit

Permalink
[autodoc] More arithmetic examples and sundry (#792)
Browse files Browse the repository at this point in the history
* Import qdatatype in autogenerated notebooks

* simplify call graph in autogenerated notebooks

* default import line for bloqs

* Autodoc arithmetic bloqs

* Autodoc arithmetic bloqs

* Autogenerate arithmetic notebooks

* Re-generate the rest of the notebooks
  • Loading branch information
mpharrigan authored Mar 18, 2024
1 parent 0db37a9 commit 7f4ee65
Show file tree
Hide file tree
Showing 35 changed files with 918 additions and 184 deletions.
8 changes: 8 additions & 0 deletions dev_tools/autogenerate-bloqs-notebooks-v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,7 @@
bloq_specs=[
qualtran.bloqs.arithmetic.addition._ADD_DOC,
qualtran.bloqs.arithmetic.addition._ADD_OOP_DOC,
qualtran.bloqs.arithmetic.addition._SIMPLE_ADD_K_DOC,
qualtran.bloqs.arithmetic.addition._ADD_K_DOC,
],
),
Expand Down Expand Up @@ -294,9 +295,13 @@
title='Comparison',
module=qualtran.bloqs.arithmetic.comparison,
bloq_specs=[
qualtran.bloqs.arithmetic.comparison._LT_K_DOC,
qualtran.bloqs.arithmetic.comparison._GREATER_THAN_DOC,
qualtran.bloqs.arithmetic.comparison._GREATER_THAN_K_DOC,
qualtran.bloqs.arithmetic.comparison._EQUALS_K_DOC,
qualtran.bloqs.arithmetic.comparison._BI_QUBITS_MIXER_DOC,
qualtran.bloqs.arithmetic.comparison._SQ_CMP_DOC,
qualtran.bloqs.arithmetic.comparison._LEQ_DOC,
],
),
NotebookSpecV2(
Expand All @@ -307,6 +312,9 @@
qualtran.bloqs.arithmetic.conversions._TO_CONTG_INDX,
],
),
# --------------------------------------------------------------------------
# ----- Rotations -----------------------------------------------------
# --------------------------------------------------------------------------
NotebookSpecV2(
title='Quantum Variable Rotation',
module=qualtran.bloqs.rotations.quantum_variable_rotation,
Expand Down
1 change: 1 addition & 0 deletions dev_tools/qualtran_dev_tools/jupyter_autogen.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ def _get_lines_for_constructing_an_object(func: Callable):

_IMPORTS = """\
from qualtran import Bloq, CompositeBloq, BloqBuilder, Signature, Register
from qualtran import QBit, QInt, QUInt, QAny
from qualtran.drawing import show_bloq, show_call_graph, show_counts_sigma
from typing import *
import numpy as np
Expand Down
3 changes: 2 additions & 1 deletion dev_tools/qualtran_dev_tools/jupyter_autogen_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,8 @@ def get_call_graph_cells(bloqdoc: BloqDocSpec, cid_prefix: str) -> List[_Cell]:
sigmavar = f'{ex.name}_sigma'

code = [
f'{graphvar}, {sigmavar} = {ex.name}.call_graph()',
'from qualtran.resource_counting.generalizers import ignore_split_join',
f'{graphvar}, {sigmavar} = {ex.name}.call_graph(max_depth=1, generalizer=ignore_split_join)',
f'show_call_graph({graphvar})',
f'show_counts_sigma({sigmavar})',
]
Expand Down
10 changes: 8 additions & 2 deletions qualtran/_infra/bloq_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ def _t(x: Iterable[T]) -> Tuple[T, ...]:
return _t


@frozen
@frozen(kw_only=True)
class BloqDocSpec:
"""A collection of bloq examples and specifications for documenting a bloq class.
Expand All @@ -141,10 +141,16 @@ class BloqDocSpec:
"""

bloq_cls: Type[Bloq]
import_line: str
examples: Sequence[BloqExample] = field(converter=_to_tuple(BloqExample), factory=tuple)
import_line: str = field()
call_graph_example: Union[BloqExample, None] = field()

@import_line.default
def _import_line_default(self) -> str:
pkg = '.'.join(self.bloq_cls.__module__.split('.')[:-1])
line = f'from {pkg} import {self.bloq_cls.__name__}'
return line

@call_graph_example.default
def _call_graph_example_default(self) -> Union[BloqExample, None]:
if not self.examples:
Expand Down
8 changes: 7 additions & 1 deletion qualtran/bloqs/arithmetic/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from qualtran.bloqs.arithmetic.addition import Add, AddConstantMod, OutOfPlaceAdder
from qualtran.bloqs.arithmetic.addition import (
Add,
AddConstantMod,
OutOfPlaceAdder,
SimpleAddConstant,
)
from qualtran.bloqs.arithmetic.comparison import (
BiQubitsMixer,
EqualsAConstant,
Expand All @@ -33,3 +38,4 @@
SquareRealNumber,
SumOfSquares,
)
from qualtran.bloqs.arithmetic.sorting import BitonicSort, Comparator
156 changes: 148 additions & 8 deletions qualtran/bloqs/arithmetic/addition.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"outputs": [],
"source": [
"from qualtran import Bloq, CompositeBloq, BloqBuilder, Signature, Register\n",
"from qualtran import QBit, QInt, QUInt, QAny\n",
"from qualtran.drawing import show_bloq, show_call_graph, show_counts_sigma\n",
"from typing import *\n",
"import numpy as np\n",
Expand Down Expand Up @@ -59,8 +60,7 @@
},
"outputs": [],
"source": [
"from qualtran import QInt, QUInt\n",
"from qualtran.bloqs.arithmetic.addition import Add"
"from qualtran.bloqs.arithmetic import Add"
]
},
{
Expand Down Expand Up @@ -153,7 +153,8 @@
},
"outputs": [],
"source": [
"add_symb_g, add_symb_sigma = add_symb.call_graph()\n",
"from qualtran.resource_counting.generalizers import ignore_split_join\n",
"add_symb_g, add_symb_sigma = add_symb.call_graph(max_depth=1, generalizer=ignore_split_join)\n",
"show_call_graph(add_symb_g)\n",
"show_counts_sigma(add_symb_sigma)"
]
Expand Down Expand Up @@ -192,7 +193,7 @@
},
"outputs": [],
"source": [
"from qualtran.bloqs.arithmetic.addition import OutOfPlaceAdder"
"from qualtran.bloqs.arithmetic import OutOfPlaceAdder"
]
},
{
Expand Down Expand Up @@ -285,7 +286,8 @@
},
"outputs": [],
"source": [
"add_oop_symb_g, add_oop_symb_sigma = add_oop_symb.call_graph()\n",
"from qualtran.resource_counting.generalizers import ignore_split_join\n",
"add_oop_symb_g, add_oop_symb_sigma = add_oop_symb.call_graph(max_depth=1, generalizer=ignore_split_join)\n",
"show_call_graph(add_oop_symb_g)\n",
"show_counts_sigma(add_oop_symb_sigma)"
]
Expand Down Expand Up @@ -321,7 +323,7 @@
},
"outputs": [],
"source": [
"from qualtran.bloqs.arithmetic.addition import AddConstantMod"
"from qualtran.bloqs.arithmetic import AddConstantMod"
]
},
{
Expand Down Expand Up @@ -414,10 +416,148 @@
},
"outputs": [],
"source": [
"add_k_symb_g, add_k_symb_sigma = add_k_symb.call_graph()\n",
"from qualtran.resource_counting.generalizers import ignore_split_join\n",
"add_k_symb_g, add_k_symb_sigma = add_k_symb.call_graph(max_depth=1, generalizer=ignore_split_join)\n",
"show_call_graph(add_k_symb_g)\n",
"show_counts_sigma(add_k_symb_sigma)"
]
},
{
"cell_type": "markdown",
"id": "9449e4e9",
"metadata": {
"cq.autogen": "SimpleAddConstant.bloq_doc.md"
},
"source": [
"## `SimpleAddConstant`\n",
"Takes |x> to |x + k> for a classical integer `k`.\n",
"\n",
"Applies addition to input register `|x>` given classical integer 'k'.\n",
"\n",
"This is the simple version of constant addition because it involves simply converting the\n",
"classical integer into a quantum parameter and using quantum-quantum addition as opposed to\n",
"designing a bespoke circuit for constant addition based on the classical parameter.\n",
"\n",
"#### Parameters\n",
" - `bitsize`: Number of bits used to represent each integer.\n",
" - `k`: The classical integer value to be added to x.\n",
" - `cvs`: A tuple of control values. Each entry specifies whether that control line is a \"positive\" control (`cv[i]=1`) or a \"negative\" control (`cv[i]=0`).\n",
" - `signed`: A boolean condition which controls whether the x register holds a value represented in 2's Complement or Unsigned. This affects the ability to add a negative constant. \n",
"\n",
"#### Registers\n",
" - `x`: A bitsize-sized input register (register x above). \n",
"\n",
"#### References\n",
"[Improved quantum circuits for elliptic curve discrete logarithms](https://arxiv.org/abs/2001.09580) Fig 2a\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cd255bf9",
"metadata": {
"cq.autogen": "SimpleAddConstant.bloq_doc.py"
},
"outputs": [],
"source": [
"from qualtran.bloqs.arithmetic import SimpleAddConstant"
]
},
{
"cell_type": "markdown",
"id": "7538f9a5",
"metadata": {
"cq.autogen": "SimpleAddConstant.example_instances.md"
},
"source": [
"### Example Instances"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4305289f",
"metadata": {
"cq.autogen": "SimpleAddConstant.simple_add_k_symb"
},
"outputs": [],
"source": [
"n, k = sympy.symbols('n k')\n",
"simple_add_k_symb = SimpleAddConstant(bitsize=n, k=k)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f6048819",
"metadata": {
"cq.autogen": "SimpleAddConstant.simple_add_k_small"
},
"outputs": [],
"source": [
"simple_add_k_small = SimpleAddConstant(bitsize=4, k=2, signed=False)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b67fd469",
"metadata": {
"cq.autogen": "SimpleAddConstant.simple_add_k_large"
},
"outputs": [],
"source": [
"simple_add_k_large = SimpleAddConstant(bitsize=64, k=-23, signed=True)"
]
},
{
"cell_type": "markdown",
"id": "b8b04228",
"metadata": {
"cq.autogen": "SimpleAddConstant.graphical_signature.md"
},
"source": [
"#### Graphical Signature"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e93e7f2e",
"metadata": {
"cq.autogen": "SimpleAddConstant.graphical_signature.py"
},
"outputs": [],
"source": [
"from qualtran.drawing import show_bloqs\n",
"show_bloqs([simple_add_k_small, simple_add_k_large],\n",
" ['`simple_add_k_small`', '`simple_add_k_large`'])"
]
},
{
"cell_type": "markdown",
"id": "13552795",
"metadata": {
"cq.autogen": "SimpleAddConstant.call_graph.md"
},
"source": [
"### Call Graph"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d8d6584e",
"metadata": {
"cq.autogen": "SimpleAddConstant.call_graph.py"
},
"outputs": [],
"source": [
"from qualtran.resource_counting.generalizers import ignore_split_join\n",
"simple_add_k_small_g, simple_add_k_small_sigma = simple_add_k_small.call_graph(max_depth=1, generalizer=ignore_split_join)\n",
"show_call_graph(simple_add_k_small_g)\n",
"show_counts_sigma(simple_add_k_small_sigma)"
]
}
],
"metadata": {
Expand All @@ -436,7 +576,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.9"
"version": "3.11.7"
}
},
"nbformat": 4,
Expand Down
37 changes: 24 additions & 13 deletions qualtran/bloqs/arithmetic/addition.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,11 +210,7 @@ def _add_large() -> Add:
return add_large


_ADD_DOC = BloqDocSpec(
bloq_cls=Add,
import_line='from qualtran import QInt, QUInt\nfrom qualtran.bloqs.arithmetic.addition import Add',
examples=(_add_symb, _add_small, _add_large),
)
_ADD_DOC = BloqDocSpec(bloq_cls=Add, examples=[_add_symb, _add_small, _add_large])


@frozen
Expand Down Expand Up @@ -322,9 +318,7 @@ def _add_oop_large() -> OutOfPlaceAdder:


_ADD_OOP_DOC = BloqDocSpec(
bloq_cls=OutOfPlaceAdder,
import_line='from qualtran.bloqs.arithmetic.addition import OutOfPlaceAdder',
examples=(_add_oop_symb, _add_oop_small, _add_oop_large),
bloq_cls=OutOfPlaceAdder, examples=[_add_oop_symb, _add_oop_small, _add_oop_large]
)


Expand Down Expand Up @@ -355,8 +349,10 @@ class SimpleAddConstant(Bloq):

bitsize: int
k: int
cvs: Tuple[int, ...] = field(converter=lambda v: (v,) if isinstance(v, int) else tuple(v))
signed: bool
cvs: Tuple[int, ...] = field(
converter=lambda v: (v,) if isinstance(v, int) else tuple(v), default=()
)
signed: bool = False

@cached_property
def signature(self) -> 'Signature':
Expand Down Expand Up @@ -443,6 +439,23 @@ def short_name(self) -> str:
return f'x += {self.k}'


@bloq_example
def _simple_add_k_small() -> SimpleAddConstant:
simple_add_k_small = SimpleAddConstant(bitsize=4, k=2, signed=False)
return simple_add_k_small


@bloq_example
def _simple_add_k_large() -> SimpleAddConstant:
simple_add_k_large = SimpleAddConstant(bitsize=64, k=-23, signed=True)
return simple_add_k_large


_SIMPLE_ADD_K_DOC = BloqDocSpec(
bloq_cls=SimpleAddConstant, examples=[_simple_add_k_small, _simple_add_k_large]
)


@frozen(auto_attribs=True)
class AddConstantMod(GateWithRegisters, cirq.ArithmeticGate):
"""Applies U(add, M)|x> = |(x + add) % M> if x < M else |x>.
Expand Down Expand Up @@ -552,7 +565,5 @@ def _add_k_large() -> AddConstantMod:


_ADD_K_DOC = BloqDocSpec(
bloq_cls=AddConstantMod,
import_line='from qualtran.bloqs.arithmetic.addition import AddConstantMod',
examples=(_add_k_symb, _add_k_small, _add_k_large),
bloq_cls=AddConstantMod, examples=[_add_k_symb, _add_k_small, _add_k_large]
)
Loading

0 comments on commit 7f4ee65

Please sign in to comment.