Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/algorithms/hhl.md
Original file line number Diff line number Diff line change
Expand Up @@ -328,3 +328,7 @@ The details of the interface are in the [API reference](../api/algorithms.md). I
change only one parameter while you experiment, change `n_eigenvalue_qubits`: it
controls the resolution of the phase estimation. The papers are listed in
[References](references.md#hhl-linear-systems).

To decide whether HHL is worth using on your problem, use the
[checklist of its conditions](https://eigenorbit.com/library/algorithms/hhl-harrow-hassidim-lloyd/)
in the EigenOrbit Library, which comes with resource estimates.
5 changes: 5 additions & 0 deletions docs/algorithms/hqnn.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,8 @@ modules. Other HQNN examples focus on one dataset each:
[circles](../examples/circles-hqnc.md), and
[concrete strength](../examples/cement-hqnr.md). The papers are listed in
[References](references.md#hqnn-hybrid-quantum-neural-networks).

The EigenOrbit Library explains
[what a quantum neural network and a hybrid one are](https://eigenorbit.com/library/concepts/quantum-neural-networks/),
and tests whether the quantum layer helps by
[comparing an HQNN with a classical network of the same size](https://eigenorbit.com/library/comparisons/hqnn-vs-classical-neural-network/).
3 changes: 2 additions & 1 deletion docs/algorithms/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ These pages explain how each algorithm in eigenkit works: what happens between t
data that you put in and the result that it gives back. For the interface itself
(the arguments of the constructors, the return types, saving a model), see the
[Estimators guide](../user-guide/estimators.md) and the API Reference, which is
generated from the code.
generated from the code. For when a method is worth using, and how its results compare
with a classical baseline, see the [EigenOrbit Library](https://eigenorbit.com/library/).

| Page | What it computes | What it gives back |
|---|---|---|
Expand Down
5 changes: 5 additions & 0 deletions docs/algorithms/iqae.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,8 @@ and issues a warning. `epsilon` must be in \((0, \pi/8)\).
The details of the interface are in the [API reference](../api/algorithms.md). The
same idea also appears in `PortfolioRiskEstimator`, where the ancilla marks a tail
loss. The papers are listed in [References](references.md#iqae-amplitude-estimation).

The EigenOrbit Library measures
[amplitude estimation against Monte Carlo](https://eigenorbit.com/library/comparisons/qae-vs-monte-carlo/)
to show when the quadratic speed-up is real, and repeats the comparison for
[Value at Risk and Conditional Value at Risk](https://eigenorbit.com/library/finance/var-cvar-risk-estimation-iqae/).
5 changes: 5 additions & 0 deletions docs/algorithms/qaoa.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,8 @@ small. The current mixer is the standard transverse field \(\sum_i X_i\).
The interface of the solver is in the [QAOA reference](../api/optimization/qaoa.md).
QAOA also appears in the [architecture notes](../architecture-diagrams.md). The papers
are listed in [References](references.md#qaoa-combinatorial-optimisation).

The EigenOrbit Library shows
[QAOA on a real problem](https://eigenorbit.com/library/algorithms/qaoa-quantum-approximate-optimization-algorithm/):
how to write the problem for it, which classical baseline to compare it with, and how
to read the results.
4 changes: 4 additions & 0 deletions docs/algorithms/qsvc-qsvr.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,7 @@ and the [Quantum Kernels guide](../user-guide/kernels.md) to inspect the kernel
matrix. The Iris example of hyperparameter optimisation uses `QSVC` inside
[GridSearchCV](../examples/hpo-qsvc-iris.md). The papers are listed in
[References](references.md#qsvc-qsvr-quantum-kernels).

The EigenOrbit Library
[benchmarks quantum kernels against tuned classical SVMs](https://eigenorbit.com/library/comparisons/qsvm-vs-classical-svm/),
and shows how to run such a comparison fairly.
4 changes: 4 additions & 0 deletions docs/algorithms/reservoir.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,7 @@ and the parts in
[memory-capacity example](../examples/reservoir-memory.md) is where the results
above come from. The papers are listed in
[References](references.md#quantum-reservoir-computing).

The EigenOrbit Library
[tests a quantum reservoir on volatility forecasting](https://eigenorbit.com/library/finance/market-volatility-forecasting-qrc/)
against a classical baseline, and shows how to test one on your own series.
8 changes: 7 additions & 1 deletion docs/algorithms/vqe.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,9 @@ and the parities in a balanced tree instead, which shortens these strings to
### Step 3: choose an ansatz

The ansatz is the trial circuit whose angles the optimiser tunes. The library
provides two, which balance physical accuracy against the depth of the circuit.
provides two, which balance physical accuracy against the depth of the circuit. For
the concept itself, see the [ansatz explainer](https://eigenorbit.com/library/concepts/ansatz/)
in the EigenOrbit Library.

**Hardware-efficient.** This is the default. It has layers of rotations and
entangling gates, chosen because a device can run them, not because chemistry
Expand Down Expand Up @@ -135,3 +137,7 @@ The interface of the solver is in the [chemistry reference](../api/chemistry/vqe
and the [Chemistry guide](../user-guide/chemistry.md) covers the whole pipeline with
working code. The papers are listed in
[References](references.md#vqe-the-variational-quantum-eigensolver).

The EigenOrbit Library uses VQE to
[find the bond lengths of two molecules](https://eigenorbit.com/library/chemistry-materials/molecular-optimization-vqe/),
and checks the results against exact classical chemistry.
106 changes: 106 additions & 0 deletions docs/gen_ref_pages.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
"""Generate API reference pages at build time via mkdocs-gen-files."""

import ast
import json
import re
from pathlib import Path

import mkdocs_gen_files
Expand Down Expand Up @@ -168,6 +171,102 @@ def write_member_directive(fd, module_id: str, member: str) -> None:
fd.write("\n")


# What a search result shows for a page: its <title> and its meta description.
# Both are taken from the module docstring and written as front matter.
# `html_title` is read by `overrides/main.html`. Front matter `title` is not used:
# it would also replace the short module name in the header and in the site search.
TITLE_MAX = 70
TITLE_SUFFIX = " | eigenkit API"
DESCRIPTION_MAX = 160


def main_member_docstring(tree: ast.Module, stem: str) -> str:
"""The docstring of the member that a module with no docstring is named after."""
members = [
node
for node in tree.body
if isinstance(node, (ast.ClassDef, ast.FunctionDef))
and not node.name.startswith("_")
]
# `hqnc.py` is described by `HQNC`. Failing a member of the module's own name,
# the first one that is not a result container (`HHLResult` before `HHL`).
members.sort(
key=lambda node: (
node.name.lower() != stem.replace("_", ""),
node.name.endswith("Result"),
)
)
return (ast.get_docstring(members[0]) or "") if members else ""


def summary_sentences(py_file: Path) -> list[str]:
"""The opening sentences of the module docstring, as plain text."""
tree = ast.parse(py_file.read_text(encoding="utf-8"))
docstring = ast.get_docstring(tree) or main_member_docstring(tree, py_file.stem)
prose = []
for paragraph in docstring.split("\n\n"):
# A list, a code fence or an `Example:` section ends the opening prose.
if not re.match(r"[A-Za-z]|`[^`]", paragraph) or re.match(r"\w+:\n", paragraph):
break
prose.append(paragraph)
# A link keeps its text.
text = re.sub(r"\[([^\]]*)\](\[[^\]]*\]|\([^)]*\))", r"\1", " ".join(prose))
sentences = []
for sentence in re.split(
r"(?<=[.!?])(?<![ei]\.[ge]\.)\s+(?=[A-Z`*])", " ".join(text.split())
):
# A formula has no plain-text form, and a paragraph that ends on a colon
# only introduces the list or the code block after it.
if "\\(" in sentence or not sentence.endswith((".", "!", "?")):
break
# Code spans and emphasis lose their marks; an asterisk inside a code
# span is code and stays.
sentences.append(
re.sub(r"(`+)(.+?)\1|\*+", lambda match: match.group(2) or "", sentence)
)
return sentences


def opening_clause(sentence: str, limit: int) -> str:
"""`sentence` if it fits in `limit` characters, else its opening clause."""
# Up to the first comma, colon, semicolon or dash and, if that is still too
# long, up to the first parenthesis. One word ("VQE", "Blocks") says too
# little, so such a clause runs on to the next mark. A clause that is still too
# long stays whole: cut inside a clause, a title reads as broken, and search
# engines shorten a long title themselves.
# A comma inside a list of names ("Harrow, Hassidim and Lloyd") is not a clause.
for marks in (r"(?:,(?! \w+ and )|[:;]) | [—–] ", r" \("):
cuts = [
match.start()
for match in re.finditer(marks, sentence)
if " " in sentence[: match.start()]
]
if len(sentence) > limit and cuts:
sentence = sentence[: cuts[0]]
return sentence


def search_title_and_description(py_file: Path, module_id: str) -> tuple[str, str]:
sentences = summary_sentences(py_file)
if not sentences:
return (
f"{module_id} API reference | eigenkit",
f"API reference for {module_id} in eigenkit, an open-source Python "
"library for quantum computing and quantum machine learning.",
)
name = module_id.rpartition(".")[2]
# A summary that opens with the module's own name ("Blocks: reusable parts")
# would say it twice.
first = re.sub(rf"^{re.escape(name)}: ", "", sentences[0], flags=re.IGNORECASE)
lead = opening_clause(first.rstrip("."), TITLE_MAX - len(f"{name}: {TITLE_SUFFIX}"))
description = sentences[0]
for sentence in sentences[1:]:
if len(description) + 1 + len(sentence) > DESCRIPTION_MAX:
break
description += " " + sentence
return f"{name}: {lead}{TITLE_SUFFIX}", description


for py_file in sorted(pkg_root.rglob("*.py")):
rel = py_file.relative_to(pkg_root)
parts = rel.parts # e.g. ('layers', 'q.py') or ('_blocks', ...)
Expand All @@ -194,7 +293,14 @@ def write_member_directive(fd, module_id: str, member: str) -> None:

nav[nav_key] = nav_path.as_posix()

html_title, description = search_title_and_description(py_file, module_id)

with mkdocs_gen_files.open(doc_path, "w") as fd:
# A JSON string is a valid YAML scalar, so `json.dumps` does the quoting.
fd.write("---\n")
fd.write(f"html_title: {json.dumps(html_title, ensure_ascii=False)}\n")
fd.write(f"description: {json.dumps(description, ensure_ascii=False)}\n")
fd.write("---\n\n")
if module_id == "eigenkit.algorithms":
fd.write("# algorithms\n\n")
for member in algorithms_api_members:
Expand Down
8 changes: 7 additions & 1 deletion overrides/main.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,14 @@
{% endblock %}

{#- Search engines show the home page's title; the others keep Material's.
`page.is_homepage` is false here because index.md sits in a nav section. -#}
`page.is_homepage` is false here because index.md sits in a nav section.
An API reference page brings its own title as `html_title` in its front
matter (`docs/gen_ref_pages.py`). -#}
{% block htmltitle %}
{% if page and page.file.src_uri == "index.md" %}
<title>{{ config.extra.home_title }}</title>
{% elif page and page.meta and page.meta.html_title %}
<title>{{ page.meta.html_title }}</title>
{% else %}
{{ super() }}
{% endif %}
Expand All @@ -28,6 +32,8 @@
{% set is_home = page and page.file.src_uri == "index.md" %}
{% if is_home %}
{% set preview_title = config.extra.home_title %}
{% elif page and page.meta and page.meta.html_title %}
{% set preview_title = page.meta.html_title %}
{% elif page and page.title %}
{% set preview_title = (page.title | striptags) ~ " - " ~ config.site_name %}
{% else %}
Expand Down
Loading