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

Add random circuit algo #139

Merged
merged 16 commits into from
Mar 29, 2024
87 changes: 87 additions & 0 deletions notebooks/auxilary/Random_Circuit.ipynb
rmshaffer marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# Random Circuit\n",
"Generates a random quantum circuit\n",
"\n",
"<u>Circuit Generation for Testing</u>\n",
"\n",
"Random quantum circuits generator allows to create a diverse set of circuits with a variety of output probability distributions. Users can utilize random circuits to test performance of quantum simulators and QPUs. \n",
rmshaffer marked this conversation as resolved.
Show resolved Hide resolved
"\n",
"<u> Benchmarking quantum compilation stacks</u>\n",
"\n",
"Random circuits sampled from a fixed gates set (as in the example below) are often used for benchmarking performance of quantum compilation passes: circuit mapping / routing and circuit optimization passes. "
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# Run on a local simulator"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from braket.devices import LocalSimulator\n",
"from braket.experimental.auxilary_functions.random_circuit.random_circuit import random_circuit\n",
"from braket.circuits.gates import CNot, Rx, Rz, CPhaseShift, XY\n",
"\n",
"# Code here\n",
"local_simulator = LocalSimulator()\n",
"gate_set = [CNot, Rx, Rz, CPhaseShift, XY]\n",
"circuit = random_circuit(num_qubits=5, \n",
" num_gates=30,\n",
" gate_set=gate_set,\n",
" seed=42)\n",
"task = local_simulator.run(circuit, shots=100)\n",
"result = task.result()\n",
"print(\"--Circuit--\")\n",
"print(circuit)\n",
"print(\"\\n--Counts--\")\n",
"print(result.measurement_counts)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.6"
},
"vscode": {
"interpreter": {
"hash": "5904cb9a2089448a2e1aeb5d493d227c9de33e591d7c07e4016fb81e71061a5d"
}
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
rmshaffer marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
The `random_circuit` function generates a random quantum circuit using the Amazon Braket SDK.
The function creates a diverse set of circuits that can be used for testing Braket SDK functionality and compiler benchmarking.
<!--
[metadata-name]: Random Quantum Circuit Generator
[metadata-tags]: Textbook
[metadata-url]: https://github.com/aws-samples/amazon-braket-algorithm-library/tree/main/src/braket/experimental/algorithms/random_circuit
rmshaffer marked this conversation as resolved.
Show resolved Hide resolved
-->
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import inspect
import math
import random
from typing import List

from braket.circuits import Circuit, Gate, Instruction
from braket.circuits.gates import CNot, H, S, T


def random_circuit(
num_qubits: int, num_gates: int, gate_set: List[Gate] = [CNot, S, T, H], seed=None
rmshaffer marked this conversation as resolved.
Show resolved Hide resolved
) -> Circuit:
"""
Generates a random quantum circuit.

Args:
num_qubits (int): Number of qubits in the circuit.
num_gates (int): Number of instructions (gates) in the circuit.
gate_set (List[Gate]): List of basis gates for the random circuit.
seed (Optional[int]): Random seed for reproducibility (default is None).
rmshaffer marked this conversation as resolved.
Show resolved Hide resolved

Returns:
Circuit: random quantum circuit.
"""
# Set the seed if provided
if seed is not None:
random.seed(seed)

instructions = []
for _ in range(num_gates):
gate = random.choice(gate_set)
gate_qubits = gate.fixed_qubit_count()

# Select random qubits for the gate
qubits = random.sample(range(num_qubits), gate_qubits)

# Get the constructor's signature to determine required parameters
init_signature = inspect.signature(gate.__init__)

# Calculate the number of parameters (excluding 'self')
num_params = len(init_signature.parameters) - 1

# Generate random parameters for the gate in the range [0, 2*pi]
params = [random.uniform(0, 2 * math.pi) for _ in range(num_params)]

# Create the gate instance
g = gate(*params)

# Add the gate as an instruction
instructions.append(Instruction(g, qubits))

# Create a circuit with the list of instructions
circuit = Circuit().add(instructions)
return circuit
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from braket.circuits import Circuit

from braket.experimental.auxilary_functions.random_circuit.random_circuit import random_circuit


def test_random_circuit_returns_circuit():
circuit = random_circuit(num_qubits=3, num_gates=5, seed=1)
assert isinstance(circuit, Circuit)


def test_random_circuit_instruction_count():
num_gates = 5
circuit = random_circuit(num_qubits=3, num_gates=num_gates, seed=1)
assert len(circuit.instructions) == num_gates


def test_random_circuit_consistency_with_seed():
circuit1 = random_circuit(num_qubits=3, num_gates=5, seed=1)
circuit2 = random_circuit(num_qubits=3, num_gates=5, seed=1)
assert circuit1 == circuit2


def test_random_circuit_variability_without_seed():
circuit1 = random_circuit(num_qubits=3, num_gates=5)
circuit2 = random_circuit(num_qubits=3, num_gates=5)
assert circuit1 != circuit2