Skip to content

Commit 6fb16e9

Browse files
committed
feat(templates): Implement enhanced, object-oriented lattice module
This commit introduces a new, robust lattice module under `tensorcircuit.templates.lattice` and addresses all reviewer feedback, significantly enhancing its functionality, usability, and robustness. The new module provides an `AbstractLattice` base class, a `TILattice` class for procedurally generated periodic structures (e.g., `SquareLattice`, `HoneycombLattice`), and a `CustomizeLattice` class for user-defined geometries. Key features and improvements include: - A benchmark-proven, high-performance neighbor search for `CustomizeLattice`, which defaults to a KDTree-based algorithm (when Scipy is available) after performance data confirmed its superiority over the baseline distance-matrix method across all tested scales (N=10 to 2000). - Dynamic modification APIs for `CustomizeLattice`: - `from_lattice()`: To convert any lattice type into a customizable one. - `add_sites()`: To dynamically add new sites. - `remove_sites()`: To dynamically remove existing sites. - The `show()` visualization method's default behavior has been fixed (`show_bonds_k=None`) to prevent warnings on lattices with un-calculated neighbors, improving user experience. - Comprehensive test coverage has been added for all new features, including API contracts, dynamic modifications, edge cases, and visualization logic. - Full documentation and type hints are provided for all public APIs, conforming to the project's coding standards.
1 parent 48c3726 commit 6fb16e9

File tree

6 files changed

+2803
-0
lines changed

6 files changed

+2803
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,4 @@ docs/source/locale/zh/LC_MESSAGES/textbook.po
3131
docs/source/locale/zh/LC_MESSAGES/whitepapertoc_cn.po
3232
docs/source/locale/zh/LC_MESSAGES/textbooktoc.po
3333
test.qasm
34+
venv/

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Change Log
22

33
## Unreleased
4+
- Add `Lattice` module (`tensorcircuit.templates.lattice`) for creating and manipulating various lattice geometries, including `SquareLattice`, `HoneycombLattice`, and `CustomizeLattice`.
45

56
## v1.2.1
67

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# benchmark_neighbors.py
2+
"""
3+
A script to benchmark the performance of neighbor-finding algorithms
4+
for the CustomizeLattice class.
5+
6+
This script compares the KDTree-based method against the baseline
7+
all-to-all distance matrix method across a range of lattice sizes.
8+
9+
To run this script from the project root directory:
10+
python benchmark_neighbors.py
11+
"""
12+
import logging
13+
import timeit
14+
from typing import Any, Dict, List
15+
16+
17+
18+
logging.getLogger("tensorcircuit.templates.lattice").setLevel(logging.WARNING)
19+
20+
21+
def run_benchmark() -> None:
22+
"""
23+
Executes the benchmark test and prints the results in a formatted table.
24+
"""
25+
site_counts: List[int] = [10, 50, 100, 200, 500, 1000, 1500, 2000]
26+
max_k: int = 1
27+
number_of_runs: int = 5
28+
results: List[Dict[str, Any]] = []
29+
30+
print("=" * 75)
31+
print("Starting neighbor finding benchmark for CustomizeLattice...")
32+
print(f"Each test will be run {number_of_runs} times to get a stable average.")
33+
print("=" * 75)
34+
print(
35+
f"{'Sites (N)':>10} | {'KDTree Time (s)':>18} | {'Baseline Time (s)':>20} | {'Speedup':>10}"
36+
)
37+
print("-" * 75)
38+
39+
for n_sites in site_counts:
40+
setup_code = f"""
41+
import numpy as np
42+
from tensorcircuit.templates.lattice import CustomizeLattice
43+
44+
np.random.seed(42)
45+
coords = np.random.rand({n_sites}, 2)
46+
ids = list(range({n_sites}))
47+
lat = CustomizeLattice(dimensionality=2, identifiers=ids, coordinates=coords)
48+
"""
49+
stmt_kdtree = f"lat._build_neighbors(max_k={max_k})"
50+
stmt_baseline = f"lat._build_neighbors_by_distance_matrix(max_k={max_k})"
51+
52+
try:
53+
time_kdtree = (
54+
timeit.timeit(stmt=stmt_kdtree, setup=setup_code, number=number_of_runs)
55+
/ number_of_runs
56+
)
57+
time_baseline = (
58+
timeit.timeit(
59+
stmt=stmt_baseline, setup=setup_code, number=number_of_runs
60+
)
61+
/ number_of_runs
62+
)
63+
64+
speedup = time_baseline / time_kdtree if time_kdtree > 0 else float("inf")
65+
results.append(
66+
{
67+
"n_sites": n_sites,
68+
"time_kdtree": time_kdtree,
69+
"time_baseline": time_baseline,
70+
"speedup": speedup,
71+
}
72+
)
73+
print(
74+
f"{n_sites:>10} | {time_kdtree:>18.6f} | {time_baseline:>20.6f} | {speedup:>9.2f}x"
75+
)
76+
77+
except Exception as e:
78+
print(f"An error occurred at N={n_sites}: {e}")
79+
break
80+
81+
print("-" * 75)
82+
print("Benchmark complete.")
83+
84+
85+
if __name__ == "__main__":
86+
run_benchmark()

tensorcircuit/templates/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,6 @@
55
from . import graphs
66
from . import measurements
77
from . import conversions
8+
from . import lattice
89

910
costfunctions = measurements

0 commit comments

Comments
 (0)