Skip to content

Commit e320844

Browse files
committed
Standardize Docstrings and Enable Doctest Validation
- Refactor docstrings across the tnco package for consistency, improving clarity and technical accuracy according to the project's documentation standards. - Add Examples sections to utility functions in `tnco.utils` and `tnco.app` to demonstrate usage and provide executable documentation. - Update `.github/workflows/run_tests.yml` to automatically run doctests during the CI process, ensuring examples remain correct as the codebase evolves. - Standardize the use of double backticks for variable names and technical terms throughout the documentation. - Perform minor cleanup of imports and type hints in tnco and tests modules for better maintainability.
1 parent aa52fd4 commit e320844

File tree

30 files changed

+963
-747
lines changed

30 files changed

+963
-747
lines changed

.github/workflows/run_tests.yml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,13 @@ jobs:
6969
fi
7070
pip install .[parallel,testing] --config-settings=cmake.build-type=${{ matrix.target }} --verbose
7171
72+
- name: Run Doctests for ${{ matrix.os }}, with ${{ matrix.compiler }} and python==${{
73+
matrix.python-version }} (${{ matrix.target }})
74+
run: |
75+
for f in $(grep -l ">>>" $(find tnco -name "*.py")); do
76+
python3 -m doctest $f || exit 1
77+
done
78+
7279
- name: Run Tests for ${{ matrix.os }}, with ${{ matrix.compiler }} and python==${{
7380
matrix.python-version }} (${{ matrix.target }})
7481
if: matrix.os == 'ubuntu-latest' && matrix.compiler == 'g++' && matrix.python-version

tests/test_contraction.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
import more_itertools as mit
2222
import pytest
23+
2324
from tnco.ctree import ContractionTree
2425
from tnco.optimize.finite_width import Optimizer as FW_Optimizer
2526
from tnco.optimize.finite_width.cost_model import \

tests/test_core.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,13 @@
2323

2424
import more_itertools as mit
2525
import pytest
26+
from tnco_core import Bitset as Bitset_
27+
from tnco_core import ContractionTree as ContractionTree_
28+
from tnco_core import Node
29+
from tnco_core import Tree as Tree_
30+
from tnco_core import float1024
31+
from tnco_core.utils import all_close, all_logclose
32+
2633
from tnco.bitset import Bitset
2734
from tnco.ctree import ContractionTree, traverse_tree
2835
from tnco.optimize.finite_width.cost_model import \
@@ -32,12 +39,6 @@
3239
from tnco.optimize.prob import BaseProbability, Greedy, MetropolisHastings
3340
from tnco.testing.utils import generate_random_inds, generate_random_tensors
3441
from tnco.utils.tn import get_random_contraction_path
35-
from tnco_core import Bitset as Bitset_
36-
from tnco_core import ContractionTree as ContractionTree_
37-
from tnco_core import Node
38-
from tnco_core import Tree as Tree_
39-
from tnco_core import float1024
40-
from tnco_core.utils import all_close, all_logclose
4142

4243
# Initialize RNG
4344
rng = Random(

tnco/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14+
"""Tensor Network Contraction Optimizer (tnco)."""
1415

1516
from importlib import metadata
1617

tnco/app/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14+
"""Application module for tnco."""
1415

1516
from tnco.app.app import Optimizer, dump_results, load_tn
1617
from tnco.app.tn import Tensor, TensorNetwork

tnco/app/app.py

Lines changed: 131 additions & 115 deletions
Large diffs are not rendered by default.

tnco/app/circuit/sampling.py

Lines changed: 59 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from collections import defaultdict
2020
from dataclasses import dataclass
2121
from random import Random
22-
from typing import Dict, FrozenSet, Iterable, Optional, Tuple, Union
22+
from typing import Any, Dict, FrozenSet, Iterable, Optional, Tuple, Union
2323

2424
import autoray as ar
2525
import more_itertools as mit
@@ -37,14 +37,14 @@
3737
def is_classical_operation(m: Matrix) -> bool:
3838
"""Check if given matrix is a classical operation.
3939
40-
Check if given matrix is a classical operation. An operation is classical
41-
if 'm @ v' only permutes the elements of 'v' (excluding a change of phase).
40+
An operation is classical if ``m @ v`` only permutes the elements of ``v``
41+
(excluding a change of phase).
4242
4343
Args:
4444
m: Matrix to check.
4545
4646
Returns:
47-
True if 'm' is a classical operation.
47+
``True`` if ``m`` is a classical operation.
4848
"""
4949
m = ar.do('asarray', m)
5050
if m.ndim != 2 or m.shape[0] != m.shape[1] and int(math.log2(
@@ -104,56 +104,54 @@ def sample(
104104
qubit_order: Optional[Iterable[Qubit]] = None,
105105
normalize: Optional[bool] = True,
106106
return_intermediate_state_only: Optional[bool] = False,
107-
dtype: Optional[any] = None,
107+
dtype: Optional[Any] = None,
108108
optimization_backend: Optional[str] = None,
109109
contraction_backend: Optional[str] = None,
110110
seed: Optional[int] = None,
111111
verbose: Optional[int] = False,
112112
**optimize_params
113113
) -> Union[Tuple[Dict[str, int], Tuple[Qubit]], SamplingIntermediateState]:
114-
"""Sample bitstring from a circuit.
114+
"""Sample bitstrings from a circuit.
115115
116-
Sample bitstring from a circuit using the Bravyi-Gosset-Liu algorithm
116+
Sample bitstrings from a circuit using the Bravyi-Gosset-Liu algorithm
117117
presented in "How to Simulate Quantum Measurement without Computing
118118
Marginals", Phys. Rev. Lett. 128, 220503 (2022).
119119
120120
Args:
121-
circuit: The circuit to sample from. If a 'SamplingIntermediateState'
122-
is passed insted, the optimization phase of the circuit is skipped
121+
circuit: The circuit to sample from. If a ``SamplingIntermediateState``
122+
is passed instead, the optimization phase of the circuit is skipped
123123
and the intermediate state is used to sample.
124-
optimizer: The 'Optimizer' to use for the tensor network optimization.
124+
optimizer: The ``Optimizer`` to use for the tensor network optimization.
125125
n_samples: The number of total samples to collect.
126-
simplify: If 'True', gates that cancel each other will be simplified.
127-
use_matrix_commutation: If 'True', gates will be commuted by performing
128-
the actual matrix commutation while simplifying the circuit.
129-
decompose_hyper_inds: If 'True', decompose gates to get hyper-indices.
130-
fuse: Fuse tensors together up a width smaller than 'fuse'. The width
126+
simplify: If ``True``, gates that cancel each other will be simplified.
127+
use_matrix_commutation: If ``True``, gates will be commuted by
128+
performing the actual matrix commutation while simplifying the
129+
circuit.
130+
decompose_hyper_inds: If ``True``, decompose gates to get hyper-indices.
131+
fuse: Fuse tensors together up a width smaller than ``fuse``. The width
131132
is defined as sum of the logarithms of all the dimensions of a
132133
given tensor.
133134
qubit_order: If provided, the order of qubits to use.
134-
normalize: If True, the total number of hits are divided by the number
135-
of samples.
136-
load_params: The parameters to pass to 'tnco.utils.circuit.load' to
137-
convert circuit to a tensor.
138-
optimizer_params: The parameters to pass to 'tnco.app.Optimizer' to
139-
initialize a new optimizer.
135+
normalize: If ``True``, the total number of hits are divided by the
136+
number of samples.
140137
optimize_params: The parameters to pass to
141-
'tnco.app.Optimizer.optimize' to optimize each partial contraction.
142-
return_intermediate_state_only: If True, skip the sampling and return
143-
the 'SamplingIntermediateState'.
138+
``tnco.app.Optimizer.optimize`` to optimize each partial
139+
contraction.
140+
return_intermediate_state_only: If ``True``, skip the sampling and
141+
return the ``SamplingIntermediateState``.
144142
dtype: The type to use for the contraction.
145143
optimization_backend: The backend to use to manipulate arrays while
146-
loading and optimazing the tensor network.
144+
loading and optimizing the tensor network.
147145
contraction_backend: The backend to use for the contraction.
148146
seed: The seed to use for the sampling.
149147
verbose: Verbose output.
150148
151149
Returns:
152-
If 'return_intermediate_state_only', a 'SamplingIntermediateState' is
153-
return to be reused multiple times. Othewise, it return a dictionary
154-
with the fraction of hits for each bitstring sampled, and the order of
155-
qubits. If 'normalize=False', the the number of hits is returned
156-
instead of its fraction.
150+
If ``return_intermediate_state_only``, a ``SamplingIntermediateState``
151+
is returned to be reused multiple times. Otherwise, it returns a
152+
dictionary with the fraction of hits for each bitstring sampled, and
153+
the order of qubits. If ``normalize=False``, the number of hits is
154+
returned instead of its fraction.
157155
"""
158156

159157
# Short for asarray
@@ -416,42 +414,30 @@ def _(circuit: qiskit.QuantumCircuit, *args, **kwargs):
416414

417415
@dataclass(frozen=True)
418416
class Sampler:
419-
"""Sample bitstrings from circuit.
417+
"""Sample bitstrings from a circuit.
420418
421-
Sample bitstring from a circuit using the Bravyi-Gosset-Liu algorithm
419+
Sample bitstrings from a circuit using the Bravyi-Gosset-Liu algorithm
422420
presented in "How to Simulate Quantum Measurement without Computing
423421
Marginals", Phys. Rev. Lett. 128, 220503 (2022).
424422
425423
Args:
426424
max_width: Maximum width to use. The width is defined as sum of the
427-
logarithms of all the dimensions of a given tensor. Tensors are
425+
logarithms of all the dimensions of a given tensor. Tensors are
428426
contracted so that the width of the contracted tensor is smaller
429-
than 'max_width'.
427+
than ``max_width``.
430428
n_jobs: Number of processes to use. By default, all available cores are
431-
used. If 'n_jobs' is a positive number, 'n_jobs' processes will be
432-
used. If 'n_jobs' is negative, 'n_cpus + n_jobs + 1' will be used.
433-
If 'n_jobs' is zero, it will raise a 'ValueError'. (See:
434-
'tnco.parallel.Parallel')
429+
used. If ``n_jobs`` is a positive number, ``n_jobs`` processes will
430+
be used. If ``n_jobs`` is negative, ``n_cpus + n_jobs + 1`` will be
431+
used. If ``n_jobs`` is zero, it will raise a ``ValueError``. (See:
432+
``tnco.parallel.Parallel``)
435433
width_type: The type to use to represent the width. (See:
436-
'tnco.optimize.finite_width.cost_model.SimpleCostModel')
434+
``tnco.optimize.finite_width.cost_model.SimpleCostModel``)
437435
cost_type: The type to use to represent the cost. (See:
438-
'tnco.optimize.finite_width.cost_model.SimpleCostModel')
439-
output_format: Format to use for the output. See Notes for more
440-
details.
441-
output_filename: If provided, dump the output to 'output_filename'. If
442-
'output_filfename' has a '.gzip' or '.bz2' extension, it will be
443-
compressed accordingly.
444-
output_compression: If 'auto', the output will be compressed to the
445-
format specified by 'output_compression'. Otherwise, the
446-
compression format will be deduced from 'output_filename'. Valid
447-
'output_compression' are 'none', 'bz2' and 'json'. If
448-
'output_filename' is not provided, it will raise a 'ValueError'.
449-
overwrite_output_file: If 'True', the 'output_filename' will be
450-
overwritten if it exists.
451-
atol: Absolute tollerance when checking for hyper-indices.
436+
``tnco.optimize.finite_width.cost_model.SimpleCostModel``)
437+
atol: Absolute tolerance when checking for hyper-indices.
452438
dtype: The type to use for the arrays.
453439
optimization_backend: The backend to use to manipulate arrays while
454-
loading and optimazing the tensor network.
440+
loading and optimizing the tensor network.
455441
seed: Seed to use.
456442
verbose: Verbose output.
457443
"""
@@ -460,7 +446,7 @@ class Sampler:
460446
width_type: Optional[str] = 'float32'
461447
cost_type: Optional[str] = 'float64'
462448
atol: Optional[float] = 1e-5
463-
dtype: Optional[any] = None
449+
dtype: Optional[Any] = None
464450
optimization_backend: Optional[str] = None
465451
seed: Optional[int] = None
466452
verbose: Optional[int] = False
@@ -501,48 +487,43 @@ def sample(
501487
contraction_backend: Optional[str] = None,
502488
**optimize_params
503489
) -> Union[Tuple[Dict[str, int], Tuple[Qubit]], SamplingIntermediateState]:
504-
"""Sample bitstring from a circuit.
490+
"""Sample bitstrings from a circuit.
505491
506-
Sample bitstring from a circuit using the Bravyi-Gosset-Liu algorithm
492+
Sample bitstrings from a circuit using the Bravyi-Gosset-Liu algorithm
507493
presented in "How to Simulate Quantum Measurement without Computing
508494
Marginals", Phys. Rev. Lett. 128, 220503 (2022).
509495
510496
Args:
511-
circuit: Circuit to sample from. If a 'SamplingIntermediateState'
512-
is passed insted, the optimization phase of the circuit is
497+
circuit: Circuit to sample from. If a ``SamplingIntermediateState``
498+
is passed instead, the optimization phase of the circuit is
513499
skipped and the intermediate state is used to sample.
514500
n_samples: The number of total samples to collect.
515-
simplify: If 'True', gates that cancel each other will be
501+
simplify: If ``True``, gates that cancel each other will be
516502
simplified.
517-
use_matrix_commutation: If 'True', gates will be commuted by
503+
use_matrix_commutation: If ``True``, gates will be commuted by
518504
performing the actual matrix commutation while simplifying the
519505
circuit.
520-
decompose_hyper_inds: If 'True', decompose gates to get
506+
decompose_hyper_inds: If ``True``, decompose gates to get
521507
hyper-indices.
522-
fuse: Fuse tensors together up a width smaller than 'fuse'. The
508+
fuse: Fuse tensors together up a width smaller than ``fuse``. The
523509
width is defined as sum of the logarithms of all the dimensions
524510
of a given tensor.
525511
qubit_order: If provided, the order of qubits to use.
526-
normalize: If True, the total number of hits are divided by the
512+
normalize: If ``True``, the total number of hits are divided by the
527513
number of samples.
528-
load_params: Parameters to pass to 'tnco.utils.circuit.load' to
529-
convert circuit to a tensor.
530-
optimizer_params: Parameters to pass to 'tnco.app.Optimizer' to
531-
initialize a new optimizer.
532-
optimize_params: Parameters to pass to 'tnco.app.Optimizer.optimize'
533-
to optimize each partial contraction.
534-
return_intermediate_state_only: If True, skip the sampling and
535-
return the 'SamplingIntermediateState'.
514+
return_intermediate_state_only: If ``True``, skip the sampling and
515+
return the ``SamplingIntermediateState``.
536516
contraction_backend: The backend to use for the contraction.
537517
**optimize_params: Parameters to use to optimize the tensor network
538-
contraction. (See 'tnco.app.Optimizer.optimize')
518+
contraction. (See ``tnco.app.Optimizer.optimize``)
539519
540520
Returns:
541-
If 'return_intermediate_state_only', a 'SamplingIntermediateState'
542-
is return to be reused multiple times. Othewise, it return a
543-
dictionary with the fraction of hits for each bitstring sampled,
544-
and the order of qubits. If 'normalize=False', the the number of
545-
hits is returned instead of its fraction.
521+
If ``return_intermediate_state_only``, a
522+
``SamplingIntermediateState`` is returned to be reused multiple
523+
times. Otherwise, it returns a dictionary with the fraction of hits
524+
for each bitstring sampled, and the order of qubits. If
525+
``normalize=False``, the number of hits is returned instead of its
526+
fraction.
546527
"""
547528

548529
return sample(

tnco/app/cli.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14+
"""Command-line interface utilities."""
1415

1516
from inspect import Parameter, Signature, signature
1617
from typing import Callable
@@ -22,10 +23,11 @@
2223

2324

2425
def wraps(fn: Callable) -> Callable:
25-
"""Apply 'fn' signature.
26+
"""Decorator to copy the signature and docstring from a function.
2627
27-
'wraps' is a decorator to add 'self' + 'fn' signature, and 'fn.__doc__' to
28-
a function. Useful when a non-method function is added as a method.
28+
``wraps`` is a decorator to add ``self`` + ``fn`` signature, and
29+
``fn.__doc__`` to a function. Useful when a non-method function is added as
30+
a method.
2931
3032
Args:
3133
fn: Function to copy the signature and the docstring from.

0 commit comments

Comments
 (0)