Skip to content

Commit

Permalink
Add .style.yapf and apply formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
bmhowe23 committed Dec 3, 2024
1 parent 6537ef0 commit c76a858
Show file tree
Hide file tree
Showing 23 changed files with 293 additions and 299 deletions.
1 change: 1 addition & 0 deletions .git-blame-ignore-revs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# To be updated
25 changes: 12 additions & 13 deletions .github/actions/get-cudaq-build/get_assets.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
import subprocess
import zipfile


def download_asset_github(repo, tag, pattern, install_dir=None):
# Construct the gh command
if tag:
gh_command = f"gh release download {tag} --repo {repo} -p '{pattern}'"
else:
gh_command = f"gh release download --repo {repo} -p '{pattern}'"

print(f"Executing command: {gh_command}")

# Execute the gh command
Expand All @@ -26,32 +27,30 @@ def download_asset_github(repo, tag, pattern, install_dir=None):
with zipfile.ZipFile(pattern, 'r') as zip_ref:
zip_ref.extractall(install_dir)


def download_asset_wget(url, pattern):
try:
result = subprocess.run(['wget', url + pattern], capture_output=True, text=True, check=True)
result = subprocess.run(['wget', url + pattern],
capture_output=True,
text=True,
check=True)
except subprocess.CalledProcessError as e:
print(f"An error occurred: {e}")
print(f"wget output: {e.output}")


def main():
# Read the entry from a JSON file
with open('.cudaq_version', 'r') as json_file:
assets = json.load(json_file)

for name, info in assets.items():
if "tag" in info:
download_asset_github(
info["repository"],
info["tag"],
info["pattern"],
info.get("install_dir")
)
download_asset_github(info["repository"], info["tag"],
info["pattern"], info.get("install_dir"))
if "url" in info:
download_asset_wget(
info["url"],
info["pattern"]
)
download_asset_wget(info["url"], info["pattern"])


if __name__ == "__main__":
main()

9 changes: 9 additions & 0 deletions .style.yapf
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# ============================================================================ #
# Copyright (c) 2024 NVIDIA Corporation & Affiliates. #
# All rights reserved. #
# #
# This source code and the accompanying materials are made available under #
# the terms of the Apache License 2.0 which accompanies this distribution. #
# ============================================================================ #
[style]
based_on_style = google
16 changes: 8 additions & 8 deletions docs/sphinx/examples/qec/python/circuit_level_noise.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,25 +32,26 @@
# sample the steane memory circuit with noise on each cx gate
# reading out the syndromes after each stabilizer round (xor'd against the previous)
# and readout out the data qubits at the end of the experiment
syndromes, data = qec.sample_memory_circuit(steane, statePrep, nShots, nRounds, noise)
syndromes, data = qec.sample_memory_circuit(steane, statePrep, nShots, nRounds,
noise)
print("From sample function:\n")
print("syndromes:\n",syndromes)
print("data:\n",data)
print("syndromes:\n", syndromes)
print("data:\n", data)

# Get a decoder
decoder = qec.get_decoder("single_error_lut", H)
nLogicalErrors = 0

# Logical Mz each shot (use Lx if preparing in X-basis)
logical_measurements = (Lz@data.transpose()) % 2
logical_measurements = (Lz @ data.transpose()) % 2
# only one logical qubit, so do not need the second axis
logical_measurements = logical_measurements.flatten()
print("LMz:\n", logical_measurements)

# initialize a Pauli frame to track logical flips
# through the stabilizer rounds
pauli_frame = np.array([0,0], dtype=np.uint8)
for shot in range(0,nShots):
pauli_frame = np.array([0, 0], dtype=np.uint8)
for shot in range(0, nShots):
print("shot:", shot)
for syndrome in syndromes:
print("syndrome:", syndrome)
Expand All @@ -60,7 +61,7 @@

# see if the decoded result anti-commutes with the observables
print("decode result:", data_prediction)
decoded_observables = (observables@data_prediction) % 2
decoded_observables = (observables @ data_prediction) % 2
print("decoded_observables:", decoded_observables)

# update pauli frame
Expand All @@ -79,4 +80,3 @@

# Count how many shots the decoder failed to correct the errors
print("Number of logical errors:", nLogicalErrors)

10 changes: 5 additions & 5 deletions docs/sphinx/examples/qec/python/code_capacity_noise.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
print(f"data: {data}")

# Calculate which syndromes are flagged.
syndrome = Hz@data % 2
syndrome = Hz @ data % 2
print(f"syndrome: {syndrome}")

# Decode the syndrome to predict what happen to the data
Expand All @@ -37,11 +37,11 @@
print(f"data_prediction: {data_prediction}")

# See if this prediction flipped the observable
predicted_observable = observable@data_prediction % 2
predicted_observable = observable @ data_prediction % 2
print(f"predicted_observable: {predicted_observable}")

# See if the observable was actually flipped
actual_observable = observable@data % 2
actual_observable = observable @ data % 2
print(f"actual_observable: {actual_observable}")
if (predicted_observable != actual_observable):
nLogicalErrors += 1
Expand All @@ -52,5 +52,5 @@
# Can also generate syndromes and data from a single line with:
syndromes, data = qec.sample_code_capacity(Hz, nShots, p)
print("From sample function:")
print("syndromes:\n",syndromes)
print("data:\n",data)
print("syndromes:\n", syndromes)
print("data:\n", data)
11 changes: 5 additions & 6 deletions docs/sphinx/examples/qec/python/pseudo_threshold.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,17 @@
for i in range(nShots):
data = qec.generate_random_bit_flips(Hz.shape[1], p)
# Calculate which syndromes are flagged.
syndrome = Hz@data % 2
syndrome = Hz @ data % 2

convergence, result = decoder.decode(syndrome)
data_prediction = np.array(result)

predicted_observable = observable@data_prediction % 2
predicted_observable = observable @ data_prediction % 2

actual_observable = observable@data % 2
actual_observable = observable @ data % 2
if (predicted_observable != actual_observable):
nLogicalErrors += 1
LERates.append(nLogicalErrors/nShots)
nLogicalErrors += 1
LERates.append(nLogicalErrors / nShots)

# Count how many shots the decoder failed to correct the errors
print("PERates:", PERates)
Expand All @@ -57,4 +57,3 @@
# Show the plot
# plt.show()
# plt.savefig("myplot.png")

17 changes: 7 additions & 10 deletions docs/sphinx/examples/solvers/python/adapt_h2.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,30 +27,27 @@

# Create the molecular hamiltonian
geometry = [('H', (0., 0., 0.)), ('H', (0., 0., .7474))]
molecule = solvers.create_molecule(geometry,
'sto-3g',
0,
0,
casci=True)
molecule = solvers.create_molecule(geometry, 'sto-3g', 0, 0, casci=True)

# Create the ADAPT operator pool
operators = solvers.get_operator_pool(
"spin_complement_gsd", num_orbitals=molecule.n_orbitals)
operators = solvers.get_operator_pool("spin_complement_gsd",
num_orbitals=molecule.n_orbitals)

# Get the number of electrons so we can
# capture it in the initial state kernel
numElectrons = molecule.n_electrons


# Define the initial Hartree Fock state
@cudaq.kernel
def initState(q: cudaq.qview):
for i in range(numElectrons):
x(q[i])


# Run ADAPT-VQE
energy, thetas, ops = solvers.adapt_vqe(initState,
molecule.hamiltonian,
operators)
energy, thetas, ops = solvers.adapt_vqe(initState, molecule.hamiltonian,
operators)

# Print the result.
print("<H> = ", energy)
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@

geometry = [('N', (0.0, 0.0, 0.5600)), ('N', (0.0, 0.0, -0.5600))]
molecule = solvers.create_molecule(geometry,
'sto-3g',
0,
0,
nele_cas=2,
norb_cas=3,
verbose=True)
'sto-3g',
0,
0,
nele_cas=2,
norb_cas=3,
verbose=True)

print('N2 HF Hamiltonian')
print('Energies : ', molecule.energies)
Expand All @@ -28,14 +28,14 @@

geometry = [('N', (0.0, 0.0, 0.5600)), ('N', (0.0, 0.0, -0.5600))]
molecule = solvers.create_molecule(geometry,
'sto-3g',
0,
0,
nele_cas=2,
norb_cas=3,
MP2=True,
integrals_natorb=True,
verbose=True)
'sto-3g',
0,
0,
nele_cas=2,
norb_cas=3,
MP2=True,
integrals_natorb=True,
verbose=True)

print('N2 Natural Orbitals from MP2 Hamiltonian')
print('Energies: ', molecule.energies)
Expand All @@ -47,15 +47,14 @@

geometry = [('N', (0.0, 0.0, 0.5600)), ('N', (0.0, 0.0, -0.5600))]
molecule = solvers.create_molecule(geometry,
'sto-3g',
0,
0,
nele_cas=2,
norb_cas=3,
casscf=True,
integrals_casscf=True,
verbose=True)

'sto-3g',
0,
0,
nele_cas=2,
norb_cas=3,
casscf=True,
integrals_casscf=True,
verbose=True)

print('N2 Active Space Hamiltonian Using CASSF Orbitals - HF orbitals')
print('Energies: ', molecule.energies)
Expand All @@ -67,16 +66,16 @@

geometry = [('N', (0.0, 0.0, 0.5600)), ('N', (0.0, 0.0, -0.5600))]
molecule = solvers.create_molecule(geometry,
'sto-3g',
0,
0,
nele_cas=2,
norb_cas=3,
MP2=True,
natorb=True,
casscf=True,
integrals_casscf=True,
verbose=True)
'sto-3g',
0,
0,
nele_cas=2,
norb_cas=3,
MP2=True,
natorb=True,
casscf=True,
integrals_casscf=True,
verbose=True)

print('N2 Active Space Hamiltonian Using CASSF Orbitals - MP2 natural orbitals')
print('N2 HF Hamiltonian')
Expand Down
8 changes: 4 additions & 4 deletions docs/sphinx/examples/solvers/python/molecular_docking_qaoa.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
G.add_node(i, weight=weight)
G.add_edges_from(edges)

# Set some parameters we'll need
# Set some parameters we'll need
penalty = 6.0
num_layers = 3

Expand All @@ -34,9 +34,9 @@
init_params = np.random.uniform(-np.pi / 8, np.pi / 8, parameter_count)

# Run QAOA, specify full parameterization and counterdiabatic
# Full parameterization uses an optimization parameter for
# every term in the clique Hamiltonian and the mixer hamiltonian.
# Specifying counterdiabatic adds extra Ry rotations at the
# Full parameterization uses an optimization parameter for
# every term in the clique Hamiltonian and the mixer hamiltonian.
# Specifying counterdiabatic adds extra Ry rotations at the
# end of each layer.
opt_value, opt_params, opt_config = solvers.qaoa(H,
num_layers,
Expand Down
20 changes: 8 additions & 12 deletions docs/sphinx/examples/solvers/python/uccsd_vqe.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,7 @@

# Create the molecular hamiltonian
geometry = [('H', (0., 0., 0.)), ('H', (0., 0., .7474))]
molecule = solvers.create_molecule(geometry,
'sto-3g',
0,
0,
casci=True)
molecule = solvers.create_molecule(geometry, 'sto-3g', 0, 0, casci=True)

# Get the number of qubits and electrons
numQubits = molecule.n_orbitals * 2
Expand All @@ -35,11 +31,11 @@ def ansatz(thetas: list[float]):

# Run VQE
energy, params, all_data = solvers.vqe(ansatz,
molecule.hamiltonian,
initialX,
optimizer=minimize,
method='L-BFGS-B',
jac='3-point',
tol=1e-4,
options={'disp': True})
molecule.hamiltonian,
initialX,
optimizer=minimize,
method='L-BFGS-B',
jac='3-point',
tol=1e-4,
options={'disp': True})
print(f'Final <H> = {energy}')
4 changes: 2 additions & 2 deletions libs/qec/python/cudaq_qec/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

# ============================================================================ #
# Copyright (c) 2024 NVIDIA Corporation & Affiliates. #
# All rights reserved. #
Expand Down Expand Up @@ -28,9 +27,11 @@
from .plugins import decoders, codes
import pkgutil, importlib, traceback


def iter_namespace(ns_pkg):
return pkgutil.iter_modules(ns_pkg.__path__, ns_pkg.__name__ + ".")


for finder, name, ispkg in iter_namespace(plugins.decoders):
try:
importlib.import_module(name)
Expand All @@ -42,4 +43,3 @@ def iter_namespace(ns_pkg):
importlib.import_module(name)
except ModuleNotFoundError as e:
pass

Loading

0 comments on commit c76a858

Please sign in to comment.