diff --git a/docs/algorithms/hhl.md b/docs/algorithms/hhl.md index 948abd5..1f18c18 100644 --- a/docs/algorithms/hhl.md +++ b/docs/algorithms/hhl.md @@ -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. diff --git a/docs/algorithms/hqnn.md b/docs/algorithms/hqnn.md index 4138256..4567d31 100644 --- a/docs/algorithms/hqnn.md +++ b/docs/algorithms/hqnn.md @@ -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/). diff --git a/docs/algorithms/index.md b/docs/algorithms/index.md index 4bee04c..532e8ae 100644 --- a/docs/algorithms/index.md +++ b/docs/algorithms/index.md @@ -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 | |---|---|---| diff --git a/docs/algorithms/iqae.md b/docs/algorithms/iqae.md index 49a3c5c..7d7f0ca 100644 --- a/docs/algorithms/iqae.md +++ b/docs/algorithms/iqae.md @@ -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/). diff --git a/docs/algorithms/qaoa.md b/docs/algorithms/qaoa.md index 5db228c..9dd3b5f 100644 --- a/docs/algorithms/qaoa.md +++ b/docs/algorithms/qaoa.md @@ -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. diff --git a/docs/algorithms/qsvc-qsvr.md b/docs/algorithms/qsvc-qsvr.md index 00ce917..f719092 100644 --- a/docs/algorithms/qsvc-qsvr.md +++ b/docs/algorithms/qsvc-qsvr.md @@ -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. diff --git a/docs/algorithms/reservoir.md b/docs/algorithms/reservoir.md index 676d681..919af38 100644 --- a/docs/algorithms/reservoir.md +++ b/docs/algorithms/reservoir.md @@ -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. diff --git a/docs/algorithms/vqe.md b/docs/algorithms/vqe.md index 9b1c7ca..8323673 100644 --- a/docs/algorithms/vqe.md +++ b/docs/algorithms/vqe.md @@ -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 @@ -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. diff --git a/docs/gen_ref_pages.py b/docs/gen_ref_pages.py index 5e7a866..7c4b089 100644 --- a/docs/gen_ref_pages.py +++ b/docs/gen_ref_pages.py @@ -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 @@ -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 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', ...) @@ -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: diff --git a/overrides/main.html b/overrides/main.html index 872f37f..17991d9 100644 --- a/overrides/main.html +++ b/overrides/main.html @@ -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 }} + {% elif page and page.meta and page.meta.html_title %} + {{ page.meta.html_title }} {% else %} {{ super() }} {% endif %} @@ -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 %}