Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature enhancement and bug fixes #7

Open
wants to merge 156 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
156 commits
Select commit Hold shift + click to select a range
61e90fd
changed the version of numpy to 1.24.4 for the compatibility with dwa…
Sep 15, 2024
91576f5
revert the version for numpy while specify the requirement for pydantic
Sep 16, 2024
f2cb8e5
added pydanic version requirement
Sep 16, 2024
5ab1411
added mock sampler with topology pegasus
Sep 18, 2024
3464315
added mock sampler with topology pegasus
Sep 18, 2024
06fa6fa
used chip_id for mock sampler's embeddings file name
Sep 18, 2024
f8858d0
replace sampler.solver with sampler.properties[chip_id] in the save_e…
Sep 18, 2024
5d1a0c6
added mock sampler with pegasus topology, put constraint in loops for…
Sep 18, 2024
e36cec0
WIP - need to resolve the index out of bounds error
Sep 18, 2024
02eb30d
Create a wrapper class for sampler
Sep 23, 2024
3d6848c
Adjust all examples to use wrapper class
Sep 23, 2024
05e3734
Updated wrapper class to inherits from MockDWaveSampler
Sep 24, 2024
e9e74b4
Added argument description for sampler_type parameter
Sep 25, 2024
64cb9e5
Updated the script to take ShimmingSampler
Sep 25, 2024
45e63c9
Override sample method in the wrapper class
Sep 25, 2024
2a653e0
Changed cached file path to use local version
Oct 2, 2024
4ec0bf1
Removed redundant imports
Oct 2, 2024
425d5c5
Added error checks and used Andrew's raster search
Oct 2, 2024
60dbaf8
Updated example one with param[L] adjustment
Oct 2, 2024
6b2fe3d
Add suitably parameterized simulated annealing as default mocking sam…
jackraymond Oct 2, 2024
efbcbcb
Corrected special case handling of zero coupling, other tidy up
jackraymond Oct 2, 2024
3517b5e
Modified parameter to take a sampler and removed default to DWave Sam…
Oct 4, 2024
9554bc0
Fixed the issue of embeddings, remove passing a graph to embed_loop f…
Oct 4, 2024
de6e956
Changed hard coded threshold for alpha_phi and alpha_J to parameters …
Oct 4, 2024
81eb97f
Adjust experiment parameters to get sensible results
Oct 9, 2024
efbf62f
Changed plots to be displayed on one canvas
Oct 9, 2024
70d06c5
Minor adjustment on format
Oct 9, 2024
d945df3
Changed the parameters to accept a asmpler and uses raster embedding …
Oct 9, 2024
47de524
Displayed plots on signle canvas
Oct 10, 2024
bd1b659
Changed parameters to match paper
Oct 10, 2024
e3e0d4e
Changed parameters to match paper
Oct 10, 2024
e240f0b
Changed example1_2 plot to match the paper
Oct 10, 2024
c44d9f3
Adjust plotting format for example1_2 and example2_2
Oct 11, 2024
e885743
Added plots for magnetization and frustration
Oct 11, 2024
d0e14b6
Added references to the figures in paper for each plot
Oct 12, 2024
5325a6a
Display buckyball results on screen instead of saving to file
Oct 12, 2024
89aa3cb
Final clean up for plots
Oct 15, 2024
8e10966
Clean up comments and syntax
Oct 16, 2024
02d65d1
Clean up comments and syntax
Oct 16, 2024
168b579
Hardcode flux-to-h conversion
kevinchern Oct 18, 2024
e597577
Remove code related to embedding, which is unused. Add plt.show() in …
jackraymond Oct 18, 2024
9e7233f
Update function signature for raster_embedding after minorminer refac…
jackraymond Oct 18, 2024
628dbef
Update requirements and remove tikzplotlib
kevinchern Oct 18, 2024
a2be940
Revert hard-coded flux bias conversion
kevinchern Oct 18, 2024
d4eb561
Included heatmap plots produced for example3_2. Run all shimtype at o…
Oct 18, 2024
a43d570
merge changes
Oct 18, 2024
a5c2686
Add matplotlib import
kevinchern Oct 21, 2024
cfa25b6
Modified parameters to raster embedding search
Oct 23, 2024
d5e91e4
Added debug statements
Oct 23, 2024
99b8760
Merge branch 'development' of https://github.com/AndyZzzZzzZzz/shimmi…
Oct 23, 2024
ca36b8f
Changed raster_breadth to original default
Oct 23, 2024
60df199
Fix constant J visualization bug
kevinchern Nov 5, 2024
63ee04d
Fixed the defect main function in embed_loops
Nov 9, 2024
784c3d7
Minor refactor
Nov 9, 2024
93fb57e
Merge branch 'development' of https://github.com/AndyZzzZzzZzz/shimmi…
Nov 9, 2024
bbff90d
Change sampler to MockDWaveSampler
Nov 9, 2024
eed876f
Fixed defect main function
Nov 13, 2024
620c62c
Fix minor import issue
Nov 13, 2024
be919fd
Warn user about execution time before running experiments
Nov 13, 2024
0cadcb7
Merge branch 'dwavesystems:main' into development
jackraymond Nov 14, 2024
384796f
Update/simplify documentation example0
jackraymond Nov 14, 2024
4d28683
Removed code to reset chip_id
Nov 18, 2024
566b197
Update README.md
jackraymond Nov 19, 2024
6a10e11
Update handling of client
jackraymond Nov 19, 2024
eb228fd
Simplify embed functions. Default to many embeddings for loops, one i…
jackraymond Nov 19, 2024
87cef62
Simplify __main__ routines for embedded cases
jackraymond Nov 19, 2024
c71f92d
Documentation improvements and refactoring to example0
jackraymond Nov 19, 2024
783a67b
Refactoring and documentation of example1
jackraymond Nov 19, 2024
c2716da
Add option to disable caching
jackraymond Nov 19, 2024
74eb39e
Document main() arguments, add use_cache, refactor
jackraymond Nov 19, 2024
87cac2b
Document main arguments, add verbose option, add title to figure wind…
jackraymond Nov 19, 2024
5b9ca9a
Documentation changes to buckyball example
jackraymond Nov 19, 2024
75d128f
Document main arguments, add use_cache option, refactor. example2_2
jackraymond Nov 19, 2024
4fc27a3
example1_1 enforce pep8 line wrapping in docstrings
jackraymond Nov 19, 2024
cb57657
Add documentation, verbose option, to example3_1
jackraymond Nov 19, 2024
d0e2341
Significant refactor of 3_2, use_cache and max_num_emb options added,…
jackraymond Nov 19, 2024
1253497
minor fix
Nov 19, 2024
3a996ba
added type hinting
Nov 19, 2024
233895f
Added type hinting
Nov 19, 2024
dd5a6f7
minor fix
Nov 19, 2024
0c1862b
minor fix
Nov 19, 2024
86668e8
Modularize visalization code
Nov 19, 2024
863baac
Added dictionary comprehension and some minor fix
Nov 19, 2024
825b64d
Add type hinting to functions
Nov 19, 2024
4c98c2a
Simplify type hinting to functions
Nov 20, 2024
cee21de
Added type hinting
Nov 20, 2024
5905ae4
Added missing documentation for model_type
Nov 20, 2024
f6677f6
Use dictionary for make fbo dict
Nov 20, 2024
917e02c
Update type hinting
Nov 20, 2024
5390171
Added two guards for file loading
Nov 20, 2024
f765079
Removed unused imports
Nov 20, 2024
37e41a8
Removed unused imports
Nov 20, 2024
ca84104
Removed unused imports
Nov 20, 2024
09797a3
Added type hinting
Nov 20, 2024
2abafe7
Revert floating point
Nov 21, 2024
cd44627
Cleaned dubugging statement
Nov 21, 2024
b080f9e
Changed model type to coupling in parameter
Nov 21, 2024
4477541
Revert floating point
Nov 21, 2024
e79d5be
Cleaned dubugging statement
Nov 21, 2024
68dee31
Changed model type to coupling in parameter
Nov 21, 2024
e2cac9a
Added label for example3_1 plots
Nov 21, 2024
e8cc3e3
Updated reference to plots in the paper
Nov 22, 2024
1017a11
Added titles for heatplots
Nov 22, 2024
e6cab14
suppress warning
Nov 22, 2024
6a1bb7e
Added horizontal title for example3_2
Nov 23, 2024
43e685c
Merge pull request #2 from AndyZzzZzzZzz/andy
AndyZzzZzzZzz Nov 23, 2024
3061c9b
Merge pull request #1 from AndyZzzZzzZzz/jack
AndyZzzZzzZzz Nov 23, 2024
e0c5057
Refactored sampler_wrapper. Added flux_biases_baseline option and tested
jackraymond Nov 27, 2024
1c5214f
Update tutorial_code/example1_1_fm_loop_balancing.py
AndyZzzZzzZzz Nov 27, 2024
2c46df0
Update tutorial_code/example1_1_fm_loop_balancing.py
AndyZzzZzzZzz Nov 27, 2024
5f4eba8
Merge pull request #3 from AndyZzzZzzZzz/andy
AndyZzzZzzZzz Nov 27, 2024
3994c77
Saved remote changes
Dec 1, 2024
744f4be
Merge branch 'development' of https://github.com/AndyZzzZzzZzz/shimmi…
Dec 1, 2024
d23792e
Used black to autoformat code
Dec 1, 2024
ff2c545
Used black to autoformat code
Dec 1, 2024
604f69e
Adjust to renaming of minorminer functions
jackraymond Dec 6, 2024
257aa23
Adjust shim tutorial to modified minorminer names and conventions
jackraymond Dec 6, 2024
68892d4
Update function names to match the most recent version of minorminer
Dec 9, 2024
1d660d7
Minor correct to function parameters
Dec 9, 2024
ef3b409
Update imports and corresponding function names from updated minormin…
Dec 10, 2024
2260982
Added the argument as_ndarray
Dec 10, 2024
693ae4b
Changed raster breadth to lattice size
Dec 10, 2024
e9df503
Changed flu_bias_baseline from 0 to 1e-5 * num qubits
Dec 10, 2024
78f234b
Add to nd_array parameter
Dec 10, 2024
18f6ed0
Changed raster_breadth to sublattice_size
Dec 10, 2024
d0db247
Minor change to parameters
Dec 10, 2024
cf0593c
minor fix
Dec 10, 2024
388dc67
Merge branch 'development' into andy
AndyZzzZzzZzz Dec 10, 2024
29160e4
Revert overriden changes in development
Dec 10, 2024
91146a7
Revert overriden changes in development
Dec 10, 2024
f4f468c
Merge branch 'andy' of https://github.com/AndyZzzZzzZzz/shimming-tuto…
Dec 10, 2024
39cd247
Merge pull request #4 from AndyZzzZzzZzz/andy
AndyZzzZzzZzz Dec 11, 2024
2810b53
Minor fix to matplotlib deprecated function
Dec 12, 2024
3624039
Minor fix to matplotlib deprecated function
Dec 12, 2024
3286df8
Removed embedding helperss
Dec 12, 2024
d16df56
Fixed pyflakes warnings
Dec 12, 2024
1309af3
Fixed pyflakes warnings
Dec 12, 2024
bf33fc1
Black reformat
Dec 12, 2024
337bd19
Black reformat
Dec 12, 2024
bab6378
Merge pull request #5 from AndyZzzZzzZzz/andy
jackraymond Dec 12, 2024
ae8aa59
Merge branch 'development' of https://github.com/AndyZzzZzzZzz/shimmi…
Dec 12, 2024
308c2a1
Exposed max_num_emb in main parameter
Dec 12, 2024
4803cb4
Minor fix to the progress bar
Dec 12, 2024
0657f01
Minor fix to max_num_emb parameter
Dec 12, 2024
934a579
Added max_num_emb to arguments along with documentation
Dec 13, 2024
5632d21
Added max_num_emb to arguments along with documentation
Dec 13, 2024
3d6e782
Added max_num_emb to arguments along with documentation
Dec 13, 2024
a7a4304
Added default for max_num_emb in main and passed it into the function
Dec 13, 2024
fb4dc24
Black reformat
Dec 13, 2024
e8cae3a
Merge remote-tracking branch 'upstream/main' into development
Dec 13, 2024
607b68a
Removed some duplicate statement introduced in merging
Dec 13, 2024
3e435cc
Removed advantage property pkl file
Dec 13, 2024
771159d
Change defaults for loop experiments back to max_num_embs=float('inf')
jackraymond Dec 19, 2024
35c8061
Match function name to most recent minorminer version
Dec 20, 2024
d921407
Merge branch 'development' of https://github.com/AndyZzzZzzZzz/shimmi…
Dec 20, 2024
3fa30bc
Make consistent with minorminer new modules https://github.com/dwaves…
jackraymond Dec 27, 2024
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
60 changes: 50 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,38 +1,78 @@
# Shimming Tutorial

This repository contains supplementary code for the tutorial [Calibration refinement in quantum annealing](https://arxiv.org/abs/2304.10352).
This repository contains supplementary code for
Tutorial: Calibration refinement in quantum annealing
https://doi.org/10.3389/fcomp.2023.1238988

Install the dependencies with
```bash
# Python version 3.10
# Python version 3.13
pip install -r requirements.txt
```

Code examples demonstrate orbits for selected models (executed locally),
calculation of embeddings (exectued locally),
and iterative shimming results for several models (executed by default on
Leap-hosted Quantum Processing Units).

## Orbit preliminaries
Each example has configurable parameters. See the main() function
documentation in each module for a description of parameters. This includes
the flexbility to modify the model, target processor, or embedding
heuristic for increased performance. To reduce the total number
of iterations (programmings, thence QPU access time) or learning rate(s).

## Orbit examples (run locally)

For generation of Figure 4
```
python -m example0_1_orbits
```

For generation of Figure 9
```
python -m example2_1_frustrated_loop_orbits
```

For generation of Figure 11
```
python -m example2_3_buckyball_orbits
```

For generation of orbits related to Figures 13-16
```
python -m example3_1_tafm_get_orbits
```

## Ferromagnetic loop example
For generation of Figure 6: **Balancing qubits in a FM chain with flux-bias offsets**. <br>
Requires 300 sequential QPU-job submissions.
```
python -m example1_1_fm_loop_balancing
```
For generation of **Balancing qubits and couplers in a FM chain with flux-bias offsets and coupler adjustments** related to Figure 7. <br>
Requires 300 sequential QPU-job submissions.
```
python -m example1_2_fm_loop_correlations
```

## Frustrated loop example
For generation of Figure 10: **Shimming a frustrated loop**. <br>
Requires 300 sequential QPU-job submissions.
```
python -m example2_1_frustrated_loop_orbits
python -m example2_2_frustrated_loop_anneal
```

## Buckyball example
```
python -m example2_3_buckyball_orbits
```
## Triangular antiferromagnet example
For generation of the following figures:
- Figure 13: **Shimming an embedded cylindrical triangular antiferromagnet**. <br>
- Figure 14: **Shimming an isotropic, infinite triangular antiferromagnet**. <br>
- Figure 15: **Shimming an isotropic, infinite triangular antiferromagnet, starting with halved boundary couplers**. <br>
- Figure 16: **Complex order parameter ψ**. <br>

## Triangular Antiferromagnet example
Generation of embeddings may require several minutes.
Data is collected in 3 blocks each requiring 800 sequential QPU-job submissions.
One figure is presented per block (interrupting data collection until the
figure is closed); along with one summary figure.
```
python -m example3_1_tafm_get_orbits
python -m example3_2_tafm_forward_anneal
```
12 changes: 2 additions & 10 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,12 +1,4 @@
networkx==2.8.8
numpy==1.24.1
dimod==0.12.3
pynauty==2.8.6
matplotlib==3.6.3
tikzplotlib==0.10.1
dwave-networkx==0.8.13
dwave-system==1.18.0
dwave-ocean-sdk==6.3.0
minorminer==0.2.11
matplotlib==3.9.2
dwave-ocean-sdk==8.0.1
tqdm==4.64.1
pydantic < 2.0
131 changes: 103 additions & 28 deletions tutorial_code/embed_loops.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,27 +13,61 @@
# limitations under the License.
#
import os

import dimod
import warnings
import numpy as np

from dwave.system.samplers import DWaveSampler
from dwave.system.testing import MockDWaveSampler

from minorminer.utils.parallel_embeddings import (
find_sublattice_embeddings,
embeddings_to_array,
lattice_size,
)

from helpers.embedding_helpers import raster_embedding_search
from minorminer.utils.feasibility import (
embedding_feasibility_filter,
lattice_size_lower_bound,
)


def embed_loops(L, try_to_load=True, raster_breadth=2):
"""Embed loops of length L
def embed_loops(
sampler: MockDWaveSampler,
L: int,
use_cache: bool = True,
**kwargs,
) -> np.ndarray:
"""Embeds a ring of length L.

Args:
L (int): chain length
try_to_load (bool, optional): Flag for loading from cached data. Defaults to True.
raster_breadth (int, optional): breadth parameter for raster embedding search. Defaults to 2.
sampler (int): DWaveSampler for which to embed
L (int): lattice length
use_cache (bool, default=True): When True, embeddings are
saved to and loaded from a local directory whenever
possible. If writing to a directory is not possible
a warning is thrown.

Returns:
numpy.ndarray: a matrix of embeddings
Returns:
np.ndarray: An matrix of embeddings
"""
sampler = DWaveSampler() # As configured
if not isinstance(L, int):
raise ValueError(f"'L' must be an integer. Received type {type(L).__name__}.")
if L <= 0:
raise ValueError(f"'L' must be a positive integer. Received {L}.")

if not isinstance(use_cache, bool):
raise ValueError(
f"'use_cache' must be a boolean. Received type {type(use_cache).__name__}."
)

solver_name = sampler.properties["chip_id"] # sampler.solver.name
cache_filename = f"cached_embeddings/{solver_name}_L{L:04d}_embeddings_cached.txt"

if use_cache and os.path.exists(cache_filename):
embeddings = np.loadtxt(cache_filename, dtype=int)
print(f"Loaded {cache_filename}")
return embeddings

bqm = dimod.BinaryQuadraticModel(
vartype="SPIN",
)
Expand All @@ -42,29 +76,70 @@ def embed_loops(L, try_to_load=True, raster_breadth=2):
G = dimod.to_networkx_graph(bqm)
A = sampler.to_networkx_graph()

cache_filename = (
f"cached_embeddings/{sampler.solver.name}__L{L:04d}_embeddings_cached.txt"
if not embedding_feasibility_filter(S=G, T=A):
raise ValueError(f"Embedding {G} on {A} is infeasible")
sublattice_size = kwargs.pop(
"sublattice_size",
min(lattice_size_lower_bound(S=G, T=A) + 1, lattice_size(T=A)),
)

if not isinstance(sublattice_size, int) or sublattice_size <= 0:
raise ValueError(
f"'sublattice_size' must be a positive integer. Received {sublattice_size}."
)

print(
"Creating embeddings may take several minutes."
"\nTo accelerate the process a smaller lattice (L) might be "
"considered and/or the search restricted to max_num_emb=1."
)
if try_to_load:
max_num_emb = kwargs.pop("max_num_emb", G.number_of_nodes()//A.number_of_nodes())
embedder_kwargs = {"timeout": kwargs.pop("timeout", 10)}
embeddings = embeddings_to_array(
find_sublattice_embeddings(
S=G,
T=A,
sublattice_size=sublattice_size,
max_num_emb=max_num_emb,
embedder_kwargs=embedder_kwargs,
**kwargs,
),
node_order=sorted(G.nodes()),
as_ndarray=True,
)

if embeddings.size == 0:
raise ValueError(
"No feasible embeddings found. "
"\nModifying the source (lattice) and target "
"(processor), or find_sublattice_embeddings arguments "
"such as timeout may resolve the issue."
)

if use_cache:
try:
embeddings = np.loadtxt(cache_filename, dtype=int)
print(f"Loaded embedding from file {cache_filename}")
return embeddings
except (ValueError, FileNotFoundError) as e:
print(f"Failed to load {cache_filename} with `np.loadtxt`")
print("Error:", e)
print("Finding embedding via raster embedding search instead.")
embeddings = raster_embedding_search(A, G, raster_breadth=raster_breadth)

os.makedirs("cached_embeddings/", exist_ok=True)
np.savetxt(cache_filename, embeddings, fmt="%d")
os.makedirs("cached_embeddings/", exist_ok=True)
np.savetxt(cache_filename, embeddings, fmt="%d")
except:
warnings.warn("Embedding cache files could not be created")

return embeddings


def main():
L = 8 # Length of chain to embed
embeddings = embed_loops(L, raster_breadth=2)
def main(max_num_emb=None):
from time import perf_counter

L = 2048 # L=2048 anticipate ~ 2.5 seconds on i7
sampler = MockDWaveSampler(topology_type="pegasus", topology_shape=[16])
t0 = perf_counter()
embeddings = embed_loops(
sampler=sampler, L=L, max_num_emb=max_num_emb, use_cache=False
)
t1 = perf_counter() - t0
if embeddings.size >= 1:
print(f"Loop {L} embedding successfully found in {t1} seconds")
else:
print(f"Something is wrong, {L}x{L} embedding not found")


if __name__ == "__main__":
Expand Down
Loading