

# Submitting quantum tasks to simulators


Amazon Braket provides access to several simulators that can test your quantum tasks. You can submit quantum tasks individually or you can [run multiple programs](https://docs.aws.amazon.com/braket/latest/developerguide/braket-batching-tasks.html).

 **Simulators** 
+  **Density matrix simulator, DM1 ** : `arn:aws:braket:::device/quantum-simulator/amazon/dm1` 
+  **State vector simulator, SV1 ** : `arn:aws:braket:::device/quantum-simulator/amazon/sv1` 
+  **Tensor network simulator, TN1 ** : `arn:aws:braket:::device/quantum-simulator/amazon/tn1` 
+  **The local simulator** : `LocalSimulator()` 

**Note**  
You can cancel quantum tasks in the `CREATED` state for QPUs and on-demand simulators. You can cancel quantum tasks in the `QUEUED` state on a best-effort basis for on-demand simulators and QPUs. Note that QPU `QUEUED` quantum tasks are unlikely to be cancelled successfully during QPU availability windows.

**Topics**
+ [

## Local state vector simulator (`braket_sv`)
](#braket-simulator-sv)
+ [

## Local density matrix simulator (`braket_dm`)
](#braket-simulator-dm)
+ [

## Local AHS simulator (`braket_ahs`)
](#braket-simulator-ahs-local)
+ [

## State vector simulator (SV1)
](#braket-simulator-sv1)
+ [

## Density matrix simulator (DM1)
](#braket-simulator-dm1)
+ [

## Tensor network simulator (TN1)
](#braket-simulator-tn1)
+ [

# About embedded simulators
](embedded-simulator.md)
+ [

# Compare Amazon Braket simulators
](choose-a-simulator.md)
+ [

# Example quantum tasks on Amazon Braket
](braket-submit-tasks-to-braket.md)
+ [

# Testing a quantum task with the local simulator
](braket-send-to-local-simulator.md)

## Local state vector simulator (`braket_sv`)


The local state vector simulator (`braket_sv`) is part of the Amazon Braket SDK that runs locally in your environment. It is well-suited for rapid prototyping on small circuits (up to 25 qubits) depending on the hardware specifications of your Braket notebook instance or your local environment.

The local simulator supports all gates in the Amazon Braket SDK, but QPU devices support a smaller subset. You can find the supported gates of a device in the device properties.

**Note**  
The local simulator supports advanced OpenQASM features which may not be supported on QPU devices or other simulators. For more information on supported features, see the examples provided in the [OpenQASM Local Simulator notebook](https://github.com/aws/amazon-braket-examples/blob/main/examples/braket_features/Simulating_Advanced_OpenQASM_Programs_with_the_Local_Simulator.ipynb).

For more information about how to work with simulators, see [the Amazon Braket examples](https://github.com/aws/amazon-braket-examples/blob/main/examples/getting_started/1_Running_quantum_circuits_on_simulators/1_Running_quantum_circuits_on_simulators.ipynb).

## Local density matrix simulator (`braket_dm`)


The local density matrix simulator (`braket_dm`) is part of the Amazon Braket SDK that runs locally in your environment. It is well-suited for rapid prototyping on small circuits with noise (up to 12 qubits) depending on the hardware specifications of your Braket notebook instance or your local environment.

You can build common noisy circuits from the ground up using gate noise operations such as bit-flip and depolarizing error. You can also apply noise operations to specific qubits and gates of existing circuits that are intended to run both with and without noise.

The `braket_dm` local simulator can provide the following results, given the specified number of shots:
+ Reduced density matrix: Shots = 0

**Note**  
The local simulator supports advanced OpenQASM features, which may not be supported on QPU devices or other simulators. For more information about supported features, see the examples provided in the [OpenQASM Local Simulator notebook](https://github.com/aws/amazon-braket-examples/blob/main/examples/braket_features/Simulating_Advanced_OpenQASM_Programs_with_the_Local_Simulator.ipynb).

To learn more about the local density matrix simulator, see [the Braket introductory noise simulator example](https://github.com/aws/amazon-braket-examples/blob/main/examples/braket_features/Simulating_Noise_On_Amazon_Braket.ipynb).

## Local AHS simulator (`braket_ahs`)


The local AHS (Analog Hamiltonian Simulation) simulator (`braket_ahs`) is part of the Amazon Braket SDK that runs locally in your environment. It can be used to simulate results from an AHS program. It is well-suited for prototyping on small registers (up to 10-12 atoms) depending on the hardware specifications of your Braket notebook instance or your local environment.

The local simulator supports AHS programs with one uniform driving field, one (non-uniform) shifting field, and arbitrary atom arrangements. For details, refer to the Braket [AHS class](https://github.com/aws/amazon-braket-sdk-python/blob/main/src/braket/ahs/analog_hamiltonian_simulation.py#L29) and the Braket [AHS program schema](https://github.com/aws/amazon-braket-schemas-python/blob/main/src/braket/ir/ahs/program_v1.py).

To learn more about the local AHS simulator, see the [Hello AHS: Run your first Analog Hamiltonian Simulation](braket-get-started-hello-ahs.md) page and the [Analog Hamiltonian Simulation example notebooks](https://github.com/aws/amazon-braket-examples/tree/main/examples/analog_hamiltonian_simulation).

## State vector simulator (SV1)


SV1 is an on-demand, high-performance, universal state vector simulator. It can simulate circuits of up to 34 qubits. You can expect a 34-qubit, dense, and square circuit (circuit depth = 34) to take approximately 1–2 hours to complete, depending on the type of gates used and other factors. Circuits with all-to-all gates are well suited for SV1. It returns results in forms such as a full state vector or an array of amplitudes.

 SV1 has a maximum runtime of 6 hours. It has a default of 35 concurrent quantum tasks, and a maximum of 100 (50 in us-west-1 and eu-west-2) concurrent quantum tasks.

 ** SV1 results** 

 SV1 can provide the following results, given the specified number of shots:
+ Sample: Shots > 0
+ Expectation: Shots >= 0
+ Variance: Shots >= 0
+ Probability: Shots > 0
+ Amplitude: Shots = 0
+ Adjoint Gradient: Shots = 0

For more about results, see [Result types](https://docs.aws.amazon.com/braket/latest/developerguide/braket-result-types.html).

 SV1 is always available, it runs your circuits on demand, and it can run multiple circuits in parallel. The runtime scales linearly with the number of operations and exponentially with the number of qubits. The number of shots has a small impact on the runtime. To learn more, visit [Compare simulators](https://docs.aws.amazon.com/braket/latest/developerguide/braket-devices.html#choose-a-simulator).

Simulators support all gates in the Braket SDK, but QPU devices support a smaller subset. You can find the supported gates of a device in the device properties.

## Density matrix simulator (DM1)


DM1 is an on-demand, high-performance, density matrix simulator. It can simulate circuits of up to 17 qubits.

 DM1 has a maximum runtime of 6 hours, a default of 35 concurrent quantum tasks, and a maximum of 50 concurrent quantum tasks.

 ** DM1 results** 

 DM1 can provide the following results, given the specified number of shots:
+ Sample: Shots > 0
+ Expectation: Shots >= 0
+ Variance: Shots >= 0
+ Probability: Shots > 0
+ Reduced density matrix: Shots = 0, up to max 8 qubits 

For more information about results, see [Result types](https://docs.aws.amazon.com/braket/latest/developerguide/braket-result-types.html).

 DM1 is always available, it runs your circuits on demand, and it can run multiple circuits in parallel. The runtime scales linearly with the number of operations and exponentially with the number of qubits. The number of shots has a small impact on the runtime. To learn more, see [Compare simulators](https://docs.aws.amazon.com/braket/latest/developerguide/braket-devices.html#choose-a-simulator).

 **Noise gates and limitations** 

```
AmplitudeDamping
    Probability has to be within [0,1]
BitFlip
    Probability has to be within [0,0.5]
Depolarizing
    Probability has to be within [0,0.75]
GeneralizedAmplitudeDamping
    Probability has to be within [0,1]
PauliChannel
    The sum of the probabilities has to be within [0,1]
Kraus
    At most 2 qubits
    At most 4 (16) Kraus matrices for 1 (2) qubit
PhaseDamping
    Probability has to be within [0,1]
PhaseFlip
    Probability has to be within [0,0.5]
TwoQubitDephasing
    Probability has to be within [0,0.75]
TwoQubitDepolarizing
    Probability has to be within [0,0.9375]
```

## Tensor network simulator (TN1)


TN1 is an on-demand, high-performance, tensor network simulator. TN1 can simulate certain circuit types with up to 50 qubits and a circuit depth of 100 or smaller. TN1 is particularly powerful for sparse circuits, circuits with local gates, and other circuits with special structure, such as quantum Fourier transform (QFT) circuits. TN1 operates in two phases. First, the *rehearsal phase* attempts to identify an efficient computational path for your circuit, so TN1 can estimate the runtime of the next stage, which is called the *contraction phase*. If the estimated contraction time exceeds the TN1 simulation runtime limit, TN1 does not attempt contraction.

 TN1 has a runtime limit of 6 hours. It is limited to a maximum of 10 (5 in eu-west-2) concurrent quantum tasks.

 ** TN1 results** 

The contraction phase consists of a series of matrix multiplications. The series of multiplications continues until a result is reached or until it is determined that a result cannot be reached.

 **Note**: Shots must be > 0.

Result types include:
+ Sample
+ Expectation
+ Variance

For more about results, see [Result types](https://docs.aws.amazon.com/braket/latest/developerguide/braket-result-types.html).

 TN1 is always available, it runs your circuits on demand, and it can run multiple circuits in parallel. To learn more, see [Compare simulators](https://docs.aws.amazon.com/braket/latest/developerguide/braket-devices.html#choose-a-simulator).

Simulators support all gates in the Braket SDK, but QPU devices support a smaller subset. You can find the supported gates of a device in the device properties.

Visit the Amazon Braket GitHub repository for a [TN1 example notebook](https://github.com/aws/amazon-braket-examples/blob/main/examples/braket_features/Using_the_tensor_network_simulator_TN1.ipynb) to help you get started with TN1.

 **Best practices for working with TN1 ** 
+ Avoid all-to-all circuits.
+ Test a new circuit or class of circuits with a small number of shots, to learn the circui's "hardness" for TN1.
+ Split large shot simulations over multiple quantum tasks.

# About embedded simulators


Embedded simulators operate by having the simulation embedded directly within the algorithm code. Also, it is contained within the same container and runs the simulation directly on the hybrid job instance. This approach is useful for removing bottlenecks typically associated with communicating between the simulation and a remote device. By keeping all computations in a single, cohesive environment, embedded simulators can greatly reduce memory requirements and decrease the number of circuit executions needed to achieve a target result. This can lead to substantial performance improvements, often by a factor of ten or more, as compared to traditional setups that rely on remote simulation. For more information about how embedded simulators enhance performance and enable streamlined hybrid jobs, refer to the [Run a hybrid job with Amazon Braket Hybrid Jobs](https://docs.aws.amazon.com/braket/latest/developerguide/braket-jobs-works.html) documentation page.

## PennyLane's lightning simulators


You can use PennyLane's lightning simulators as embedded simulators on Braket. With PennyLane's lightning simulators, you can use advanced gradient computation methods, such as [adjoint differentiation](https://docs.pennylane.ai/en/stable/introduction/interfaces.html#simulation-based-differentiation), to evaluate gradients faster. The [lightning.qubit simulator](https://docs.pennylane.ai/projects/lightning/en/stable/lightning_qubit/device.html) is available as a device through Braket NBIs and as an embedded simulator, whereas the lightning.gpu simulator needs to be run as an embedded simulator with a GPU instance. See the [Embedded simulators in Braket Hybrid Jobs](https://github.com/amazon-braket/amazon-braket-examples/blob/main/examples/hybrid_jobs/4_Embedded_simulators_in_Braket_Hybrid_Jobs/Embedded_simulators_in_Braket_Hybrid_Jobs.ipynb) notebook for an example of using lightning.gpu.

# Compare Amazon Braket simulators
Compare simulators

This section helps you select the Amazon Braket simulator that is best suited for your quantum task, by describing some concepts, limitations, and use cases.

 **Choosing between local simulators and on-demand simulators (SV1, TN1, DM1)** 

The performance of *local simulators* depends on the hardware that hosts the local environment, such as a Braket notebook instance, used to run your simulator. *On-demand simulators* run in the AWS cloud and are designed to scale beyond typical local environments. On-demand simulators are optimized for larger circuits, but add some latency overhead per quantum task or batch of quantum tasks. This can imply a trade-off if many quantum tasks are involved. Given these general performance characteristics, the following guidance can help you choose how to run simulations, including ones with noise.

For **simulations**:
+ When employing fewer than 18 qubits, use a local simulator.
+ When employing 18–24 qubits, choose a simulator based on the workload.
+ When employing more than 24 qubits, use an on-demand simulator.

For **noise simulations**:
+ When employing fewer than 9 qubits, use a local simulator.
+ When employing 9–12 qubits, choose a simulator based on the workload.
+ When employing more than 12 qubits, use DM1.

 **What is a state vector simulator?** 

 SV1 is a universal state vector simulator. It stores the full wave function of the quantum state and sequentially applies gate operations to the state. It stores all possibilities, even the extremely unlikely ones. The SV1 simulator's run time for a quantum task increases linearly with the number of gates in the circuit.

 **What is a density matrix simulator?** 

 DM1 simulates quantum circuits with noise. It stores the full density matrix of the system and sequentially applies the gates and noise operations of the circuit. The final density matrix contains complete information about the quantum state after the circuit runs. The runtime generally scales linearly with the number of operations and exponentially with the number of qubits.

 **What is a tensor network simulator?** 

 TN1 encodes quantum circuits into a structured graph.
+ The nodes of the graph consist of quantum gates, or qubits.
+ The edges of the graph represent connections between gates.

As a result of this structure, TN1 can find simulated solutions for relatively large and complex quantum circuits.

 ** TN1 requires two phases** 

Typically, TN1 operates in a two-phase approach to simulating quantum computation.
+  **The rehearsal phase:** In this phase, TN1 comes up with a way to traverse the graph in an efficient manner, which involves visiting every node so that you can obtain the measurement you desire. As a customer, you do not see this phase because TN1 performs both phases together for you. It completes the first phase and determines whether to perform the second phase on its own based on practical constraints. You have no input into that decision after the simulation has begun.
+  **The contraction phase:** This phase is analogous to the execution phase of a computation in a classical computer. The phase consists of a series of matrix multiplications. The order of these multiplications has a great effect on the difficulty of the computation. Therefore, the rehearsal phase is accomplished first to find the most effective computation paths across the graph. After it finds the contraction path during the rehearsal phase, TN1 contracts together the gates of your circuit to produce the results of the simulation.

 ** TN1 graphs are analogous to a map** 

Metaphorically, you can compare the underlying TN1 graph to the streets of a city. In a city with a planned grid, it is easy to find a route to your destination using a map. In a city with unplanned streets, duplicate street names, and so forth, it can be difficult to find a route to your destination by looking at a map.

If TN1 did not perform the rehearsal phase, it would be like walking around the streets of the city to find your destination, instead of looking at a map first. It can really pay off in terms of walking time to spend more time looking at the map. Similarly, the rehearsal phase provides valuable information.

You might say that the TN1 has a certain “awareness” of the structure of the underlying circuit that it traverses. It gains this awareness during the rehearsal phase.

 **Types of problems best suited for each of these types of simulators** 

 SV1 is well-suited for any class of problems that rely primarily on having a certain number of qubits and gates. Generally, the time required grows linearly with the number of gates, while it does not depend on the number of shots. SV1 is generally faster than TN1 for circuits under 28 qubits.

 SV1 can be slower for higher qubit numbers because it actually simulates all possibilities, even the extremely unlikely ones. It has no way to determine which outcomes are likely. Thus, for a 30-qubit evaluation, SV1 must calculate 2^30 configurations. The limit of 34 qubits for the Amazon Braket SV1 simulator is a practical constraint due to memory and storage limitations. You can think of it like this: Each time you add a qubit to SV1, the problem becomes twice as hard.

For many classes of problems, TN1 can evaluate much larger circuits in realistic time than SV1 because TN1 takes advantage of the structure of the graph. It essentially tracks the evolution of solutions from its starting place and it retains only the configurations that contribute to an efficient traversal. Put another way, it saves the configurations to create an ordering of matrix multiplication that results in a simpler evaluation process.

For TN1, the number of qubits and gates matters, but the structure of the graph matters a lot more. For example, TN1 is very good at evaluating circuits (graphs) in which the gates are short-range (that is, each qubit is connected by gates only to its nearest neighbour qubits), and circuits (graphs) in which the connections (or gates) have similar range. A typical range for TN1 is having each qubit talk only to other qubits that are 5 qubits away. If most of the structure can be decomposed into simpler relationships such as these, which can be represented in *more*, *smaller*, or *more uniform* matrices, TN1 performs the evaluation efficiently.

 **Limitations of TN1 ** 

 TN1 can be slower than SV1 depending on the graph's structural complexity. For certain graphs, TN1 terminates the simulation after the rehearsal stage, and shows a status of `FAILED`, for either of these two reasons:
+  **Cannot find a path** — If the graph is too complex, it is too difficult to find a good traversal path and the simulator gives up on the computation. TN1 cannot perform the contraction. You may see an error message similar to this one: `No viable contraction path found.` 
+  **Contraction stage is too difficult** — In some graphs, TN1 can find a traversal path, but it is very long and extremely time-consuming to evaluate. In this case, the contraction is so expensive that the cost would be prohibitive and instead, TN1 exits after the rehearsal phase. You may see an error message similar to this one: `Predicted runtime based on best contraction path found exceeds TN1 limit.` 

**Note**  
You are billed for the rehearsal stage of TN1 even if contraction is not performed and you see a `FAILED` status.

The predicted runtime also depends on the shot count. In worst-case scenarios, TN1 contraction time depends linearly on the shot count. The circuit may be contractable with fewer shots. For example, you might submit a quantum task with 100 shots, which TN1 decides is uncontractable, but if you resubmit with only 10, the contraction proceeds. In this situation, to attain 100 samples, you could submit 10 quantum tasks of 10 shots for the same circuit and combine the results in the end.

As a best practice, we recommend that you always test your circuit or circuit class with a few shots (for example, 10) to find out how hard your circuit is for TN1, before you proceed with a higher number of shots.

**Note**  
The series of multiplications that forms the contraction phase begins with small, NxN matrices. For example, a 2-qubit gate requires a 4x4 matrix. The intermediate matrices required during a contraction that is adjudged to be too difficult are gigantic. Such a computation would require days to complete. That is why Amazon Braket does not attempt extremely complex contractions.

 **Concurrency** 

All Braket simulators give you the ability to run multiple circuits concurrently. Concurrency limits vary by simulator and region. For more information on concurrency limits, see the [Quotas](https://docs.aws.amazon.com/braket/latest/developerguide/braket-quotas.html) page.

# Example quantum tasks on Amazon Braket


This section walks through the stages of running an example quantum task, from selecting the device to viewing the result. As a best practice for Amazon Braket, we recommend that you begin by running the circuit on a simulator, such as SV1.

**Topics**
+ [

## Specify the device
](#braket-example-specify-device)
+ [

## Submit an example quantum task
](#braket-submit-example-task)
+ [

## Submit a parametrized task
](#braket-submit-parametrized-task)
+ [

## Specify shots
](#braket-shots)
+ [

## Poll for results
](#braket-polling-results)
+ [

## View the example results
](#braket-example-results)

## Specify the device


First, select and specify the device for your quantum task. This example shows how to choose the simulator, SV1.

```
from braket.aws import AwsDevice

# Choose the on-demand simulator to run the circuit
device = AwsDevice("arn:aws:braket:::device/quantum-simulator/amazon/sv1")
```

You can view some of the properties of this device as follows:

```
print(device.name)
for iter in device.properties.action['braket.ir.jaqcd.program']:
    print(iter)
```

```
SV1
('version', ['1.0', '1.1'])
('actionType', 'braket.ir.jaqcd.program')
('supportedOperations', ['ccnot', 'cnot', 'cphaseshift', 'cphaseshift00', 'cphaseshift01', 'cphaseshift10', 'cswap', 'cy', 'cz', 'ecr', 'h', 'i', 'iswap', 'pswap', 'phaseshift', 'rx', 'ry', 'rz', 's', 'si', 'swap', 't', 'ti', 'unitary', 'v', 'vi', 'x', 'xx', 'xy', 'y', 'yy', 'z', 'zz'])
('supportedResultTypes', [ResultType(name='Sample', observables=['x', 'y', 'z', 'h', 'i', 'hermitian'], minShots=1, maxShots=100000), ResultType(name='Expectation', observables=['x', 'y', 'z', 'h', 'i', 'hermitian'], minShots=0, maxShots=100000), ResultType(name='Variance', observables=['x', 'y', 'z', 'h', 'i', 'hermitian'], minShots=0, maxShots=100000), ResultType(name='Probability', observables=None, minShots=1, maxShots=100000), ResultType(name='Amplitude', observables=None, minShots=0, maxShots=0)])
('disabledQubitRewiringSupported', None)
```

## Submit an example quantum task


Submit an example quantum task to run on the on-demand simulator.

```
from braket.circuits import Circuit, Observable

# Create a circuit with a result type
circ = Circuit().rx(0, 1).ry(1, 0.2).cnot(0, 2).variance(observable=Observable.Z(), target=0)
# Add another result type
circ.probability(target=[0, 2])

# Set up S3 bucket (where results are stored)
my_bucket = "amazon-braket-s3-demo-bucket"  # The name of the bucket
my_prefix = "your-folder-name"  # The name of the folder in the bucket
s3_location = (my_bucket, my_prefix)

# Submit the quantum task to run
my_task = device.run(circ, s3_location, shots=1000, poll_timeout_seconds=100, poll_interval_seconds=10)
# The positional argument for the S3 bucket is optional if you want to specify a bucket other than the default

# Get results of the quantum task
result = my_task.result()
```

The `device.run()` command creates a quantum task through the `CreateQuantumTask` API. After a short initialization time, the quantum task is queued until capacity exists to run the quantum task on a device. In this case, the device is SV1. After the device completes the computation, Amazon Braket writes the results to the Amazon S3 location specified in the call. The positional argument `s3_location` is required for all devices except the local simulator.

**Note**  
The Braket quantum task action is limited to 5MB in size.

## Submit a parametrized task


 Amazon Braket on-demand and local simulators and QPUs also support specifying values of free parameters at task submission. You can do this by using the `inputs` argument to `device.run()`, as shown in the following example. The `inputs` must be a dictionary of string-float pairs, where the keys are the parameter names.

Parametric compilation can improve the performance of executing parametric circuits on certain QPUs. When submitting a parametric circuit as a quantum task to a supported QPU, Braket will compile the circuit once, and cache the result. There is no recompilation for subsequent parameter updates to the same circuit, resulting in faster runtimes for tasks that use the same circuit. Braket automatically uses the updated calibration data from the hardware provider when compiling your circuit to ensure the highest quality results.

**Note**  
Parametric compilation is supported on all superconducting, gate-based QPUs from Rigetti Computing with the exception of pulse level programs.

```
from braket.circuits import Circuit, FreeParameter, Observable

# Create the free parameters
alpha = FreeParameter('alpha')
beta = FreeParameter('beta')

# Create a circuit with a result type
circ = Circuit().rx(0, alpha).ry(1, alpha).cnot(0, 2).xx(0, 2, beta)
circ.variance(observable=Observable.Z(), target=0)

# Add another result type
circ.probability(target=[0, 2])

# Submit the quantum task to run
my_task = device.run(circ, inputs={'alpha': 0.1, 'beta': 0.2}, shots=100)
```

## Specify shots


The shots argument refers to the number of desired measurement shots. Simulators such as SV1 support two simulation modes.
+ For shots = 0, the simulator performs an exact simulation, returning the true values for all result types. (Not available on TN1.)
+ For non-zero values of shots, the simulator samples from the output distribution to emulate the shot noise of real QPUs. QPU devices only allow shots > 0.

For information about the maximum number of shots per quantum task, refer to [Braket Quotas](braket-quotas.md).

## Poll for results


When executing `my_task.result()`, the SDK begins polling for a result with the parameters you define upon quantum task creation:
+  `poll_timeout_seconds` is the number of seconds to poll the quantum task before it times out when running the quantum task on the on-demand simulator and or QPU devices. The default value is 432,000 seconds, which is 5 days.
+  **Note:** For QPU devices such as Rigetti and IonQ, we recommend that you allow a few days. If your polling timeout is too short, results may not be returned within the polling time. For example, when a QPU is unavailable, a local timeout error is returned.
+  `poll_interval_seconds` is the frequency with which the quantum task is polled. It specifies how often you call the Braket API to get the status when the quantum task is run on the on-demand simulator and on QPU devices. The default value is 1 second.

This asynchronous execution facilitates the interaction with QPU devices that are not always available. For example, a device could be unavailable during a regular maintenance window.

The returned result contains a range of metadata associated with the quantum task. You can check the measurement result with the following commands:

```
print('Measurement results:\n', result.measurements)
print('Counts for collapsed states:\n', result.measurement_counts)
print('Probabilities for collapsed states:\n', result.measurement_probabilities)
```

```
Measurement results:
 [[1 0 1]
 [0 0 0]
 [0 0 0]
 ...
 [0 0 0]
 [0 0 0]
 [1 0 1]]
Counts for collapsed states:
 Counter({'000': 766, '101': 220, '010': 11, '111': 3})
Probabilities for collapsed states:
 {'101': 0.22, '000': 0.766, '010': 0.011, '111': 0.003}
```

## View the example results


Because you've also specified the `ResultType`, you can view the returned results. The result types appear in the order in which they were added to the circuit.

```
print('Result types include:\n', result.result_types)
print('Variance=', result.values[0])
print('Probability=', result.values[1])

# Plot the result and do some analysis
import matplotlib.pyplot as plt
plt.bar(result.measurement_counts.keys(), result.measurement_counts.values())
plt.xlabel('bitstrings')
plt.ylabel('counts')
```

```
Result types include:
 [ResultTypeValue(type=Variance(observable=['z'], targets=[0], type=<Type.variance: 'variance'>), value=0.693084), ResultTypeValue(type=Probability(targets=[0, 2], type=<Type.probability: 'probability'>), value=array([0.777, 0.   , 0.   , 0.223]))]
Variance= 0.693084
Probability= [0.777 0.    0.    0.223]
Text(0, 0.5, 'counts')
```

![\[Bar chart showing the number of counts to different bitstrings, with the highest bar for "000" containing over 700 counts.\]](http://docs.aws.amazon.com/braket/latest/developerguide/images/demo-result.png)


# Testing a quantum task with the local simulator


You can send quantum tasks directly to a local simulator for rapid prototyping and testing. This simulator runs in your local environment, so you do not need to specify an Amazon S3 location. The results are computed directly in your session. To run a quantum task on the local simulator, you must only specify the shots parameter.

**Note**  
The execution speed and maximum number of qubits the local simulator can process depends on the Amazon Braket notebook instance type, or on your local hardware specifications.

The following commands are all identical and instantiate the state vector (noise free) local simulator.

```
# Import the LocalSimulator module
from braket.devices import LocalSimulator

# The following are identical commands
device = LocalSimulator()
device = LocalSimulator("default")
device = LocalSimulator(backend="default")
device = LocalSimulator(backend="braket_sv")
```

Then run a quantum task with the following.

```
my_task = device.run(circ, shots=1000)
```

To instantiate the local density matrix (noise) simulator customers change the backend as follows.

```
# Import the LocalSimulator module
from braket.devices import LocalSimulator

device = LocalSimulator(backend="braket_dm")
```

## Measuring specific qubits on the local simulator


The local state vector simulator and local density matrix simulator support running circuits where a subset of the circuit's qubits can be measured, which is often called *partial measurement*.

For example, in the following code you can create a two-qubit circuit and only measure the first qubit by adding a `measure` instruction with the target qubits to the end of the circuit.

```
# Import the LocalSimulator module
from braket.devices import LocalSimulator 

# Use the local simulator device
device = LocalSimulator()

# Define a bell circuit and only measure 
circuit = Circuit().h(0).cnot(0, 1).measure(0)

# Run the circuit
task = device.run(circuit, shots=10)

# Get the results
result = task.result()

# Print the measurement counts for qubit 0
print(result.measurement_counts)
```