Simulator that mimics running on quantum hardware.
qsimcirq.QSimSimulator(
qsim_options: Union[None, Dict, qsimcirq.QSimOptions
] = None,
seed: value.RANDOM_STATE_OR_SEED_LIKE = None,
circuit_memoization_size: int = 0
)
Used in the notebooks
Implementors of this interface should implement the _run method.
Args 
qsim_options

An options dict or QSimOptions object with options
to use for all circuits run using this simulator. See the
QSimOptions class for details.

seed

A random state or seed object, as defined in cirq.value.

circuit_memoization_size

The number of last translated circuits
to be memoized from simulation executions, to eliminate
translation overhead. Every simulation will perform a linear
search through the list of memoized circuits using circuit
equality checks, so a large circuit_memoization_size with large
circuits will incur a significant runtime overhead.
Note that every resolved parameterization results in a separate
circuit to be memoized.

Raises 
ValueError if internal keys 'c', 'i' or 's' are included in 'qsim_options'.

Methods
compute_amplitudes
compute_amplitudes(
program: "cirq.AbstractCircuit",
bitstrings: Sequence[int],
param_resolver: "study.ParamResolverOrSimilarType" = None,
qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT
) > Sequence[complex]
Computes the desired amplitudes.
The initial state is assumed to be the all zeros state.
Args 
program

The circuit to simulate.

bitstrings

The bitstrings whose amplitudes are desired, input
as an integer array where each integer is formed from measured
qubit values according to qubit_order from most to least
significant qubit, i.e. in bigendian ordering.

param_resolver

Parameters to run with the program.

qubit_order

Determines the canonical ordering of the qubits. This
is often used in specifying the initial state, i.e. the
ordering of the computational basis states.

Returns 
List of amplitudes.

compute_amplitudes_sweep
View source
compute_amplitudes_sweep(
program: circuits.Circuit,
bitstrings: Sequence[int],
params: study.Sweepable,
qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT
) > Sequence[Sequence[complex]]
Computes the desired amplitudes using qsim.
The initial state is assumed to be the all zeros state.
Args 
program

The circuit to simulate.

bitstrings

The bitstrings whose amplitudes are desired, input as an
string array where each string is formed from measured qubit values
according to qubit_order from most to least significant qubit,
i.e. in bigendian ordering.

param_resolver

Parameters to run with the program.

qubit_order

Determines the canonical ordering of the qubits. This is
often used in specifying the initial state, i.e. the ordering of the
computational basis states.

Returns 
List of amplitudes.

compute_amplitudes_sweep_iter
compute_amplitudes_sweep_iter(
program: "cirq.AbstractCircuit",
bitstrings: Sequence[int],
params: study.Sweepable,
qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT
) > Iterator[Sequence[complex]]
Computes the desired amplitudes.
The initial state is assumed to be the all zeros state.
Args 
program

The circuit to simulate.

bitstrings

The bitstrings whose amplitudes are desired, input
as an integer array where each integer is formed from measured
qubit values according to qubit_order from most to least
significant qubit, i.e. in bigendian ordering.

params

Parameters to run with the program.

qubit_order

Determines the canonical ordering of the qubits. This
is often used in specifying the initial state, i.e. the
ordering of the computational basis states.

Returns 
An Iterator over lists of amplitudes. The outer dimension indexes
the circuit parameters and the inner dimension indexes bitstrings.

get_seed
View source
get_seed()
run
run(
program: "cirq.AbstractCircuit",
param_resolver: "cirq.ParamResolverOrSimilarType" = None,
repetitions: int = 1
) > "cirq.Result"
Samples from the given Circuit.
By default, the run_async
method invokes this method on another
thread. So this method is supposed to be thread safe.
Args 
program

The circuit to sample from.

param_resolver

Parameters to run with the program.

repetitions

The number of times to sample.

Returns 
Result for a run.

run_async
run_async(
program, *, repetitions
)
Asynchronously samples from the given Circuit.
By default, this method invokes run
synchronously and simply exposes
its result is an awaitable. Child classes that are capable of true
asynchronous sampling should override it to use other strategies.
Args 
program

The circuit to sample from.

repetitions

The number of times to sample.

Returns 
An awaitable Result.

run_batch
run_batch(
programs: Sequence['cirq.AbstractCircuit'],
params_list: Optional[List['cirq.Sweepable']] = None,
repetitions: Union[int, List[int]] = 1
) > List[List['cirq.Result']]
Runs the supplied circuits.
Each circuit provided in programs
will pair with the optional
associated parameter sweep provided in the params_list
, and be run
with the associated repetitions provided in repetitions
(if
repetitions
is an integer, then all runs will have that number of
repetitions). If params_list
is specified, then the number of
circuits is required to match the number of sweeps. Similarly, when
repetitions
is a list, the number of circuits is required to match
the length of this list.
By default, this method simply invokes run_sweep
sequentially for
each (circuit, parameter sweep, repetitions) tuple. Child classes that
are capable of sampling batches more efficiently should override it to
use other strategies. Note that child classes may have certain
requirements that must be met in order for a speedup to be possible,
such as a constant number of repetitions being used for all circuits.
Refer to the documentation of the child class for any such requirements.
Args 
programs

The circuits to execute as a batch.

params_list

Parameter sweeps to use with the circuits. The number
of sweeps should match the number of circuits and will be
paired in order with the circuits.

repetitions

Number of circuit repetitions to run. Can be specified
as a single value to use for all runs, or as a list of values,
one for each circuit.

Returns 
A list of lists of TrialResults. The outer list corresponds to
the circuits, while each inner list contains the TrialResults
for the corresponding circuit, in the order imposed by the
associated parameter sweep.

run_sweep
run_sweep(
program: "cirq.AbstractCircuit",
params: study.Sweepable,
repetitions: int = 1
) > List[study.Result]
Samples from the given Circuit.
In contrast to run, this allows for sweeping over different parameter
values.
Args 
program

The circuit to sample from.

params

Parameters to run with the program.

repetitions

The number of times to sample.

Returns 
Result list for this run; one for each possible parameter
resolver.

run_sweep_async
run_sweep_async(
program, params, repetitions=1
)
Asynchronously sweeps and samples from the given Circuit.
By default, this method invokes run_sweep
synchronously and simply
exposes its result is an awaitable. Child classes that are capable of
true asynchronous sampling should override it to use other strategies.
Args 
program

The circuit to sample from.

params

One or more mappings from parameter keys to parameter values
to use. For each parameter assignment, repetitions samples
will be taken.

repetitions

The number of times to sample.

Returns 
An awaitable Result.

run_sweep_iter
run_sweep_iter(
program: "cirq.AbstractCircuit",
params: study.Sweepable,
repetitions: int = 1
) > Iterator[study.Result]
Runs the supplied Circuit, mimicking quantum hardware.
In contrast to run, this allows for sweeping over different parameter
values.
Args 
program

The circuit to simulate.

params

Parameters to run with the program.

repetitions

The number of repetitions to simulate.

Returns 
Result list for this run; one for each possible parameter
resolver.

sample
sample(
program: "cirq.AbstractCircuit",
*,
repetitions: int = 1,
params: "cirq.Sweepable" = None
) > "pd.DataFrame"
Samples the given Circuit, producing a pandas data frame.
Args 
program

The circuit to sample from.

repetitions

The number of times to sample the program, for each
parameter mapping.

params

Maps symbols to one or more values. This argument can be
a dictionary, a list of dictionaries, a cirq.Sweep , a list of
cirq.Sweep , etc. The program will be sampled repetition
times for each mapping. Defaults to a single empty mapping.

Returns 
A pandas.DataFrame with a row for each sample, and a column for
each measurement key as well as a column for each symbolic
parameter. Measurement results are stored as a big endian integer
representation with one bit for each measured qubit in the key.
See cirq.big_endian_int_to_bits and similar functions for how
to convert this integer into bits.
There is an also index column containing the repetition number,
for each parameter assignment.

Examples:
a, b, c = cirq.LineQubit.range(3)
sampler = cirq.Simulator()
circuit = cirq.Circuit(cirq.X(a),
cirq.measure(a, key='out'))
print(sampler.sample(circuit, repetitions=4))
out
0 1
1 1
2 1
3 1
circuit = cirq.Circuit(cirq.X(a),
cirq.CNOT(a, b),
cirq.measure(a, b, c, key='out'))
print(sampler.sample(circuit, repetitions=4))
out
0 6
1 6
2 6
3 6
circuit = cirq.Circuit(cirq.X(a)**sympy.Symbol('t'),
cirq.measure(a, key='out'))
print(sampler.sample(
circuit,
repetitions=3,
params=[{'t': 0}, {'t': 1}]))
t out
0 0 0
1 0 0
2 0 0
0 1 1
1 1 1
2 1 1
sample_expectation_values
sample_expectation_values(
program: "cirq.AbstractCircuit",
observables: Union['cirq.PauliSumLike', List['cirq.PauliSumLike']],
*,
num_samples: int,
params: "cirq.Sweepable" = None,
permit_terminal_measurements: bool = False
) > List[List[float]]
Calculates estimated expectation values from samples of a circuit.
Please see also cirq.work.measure_observables
for more control over how to measure
a suite of observables.
This method can be run on any device or simulator that supports circuit sampling. Compare
with simulate_expectation_values
in simulator.py, which is limited to simulators
but provides exact results.
Args 
program

The circuit which prepares a state from which we sample expectation values.

observables

A list of observables for which to calculate expectation values.

num_samples

The number of samples to take. Increasing this value increases the
statistical accuracy of the estimate.

params

Parameters to run with the program.

permit_terminal_measurements

If the provided circuit ends in a measurement, this
method will generate an error unless this is set to True. This is meant to
prevent measurements from ruining expectation value calculations.

Returns 
A list of expectationvalue lists. The outer index determines the sweep, and the inner
index determines the observable. For instance, results[1][3] would select the fourth
observable measured in the second sweep.

simulate
simulate(
program: "cirq.AbstractCircuit",
param_resolver: "study.ParamResolverOrSimilarType" = None,
qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
initial_state: Any = None
) > TSimulationTrialResult
Simulates the supplied Circuit.
This method returns a result which allows access to the entire
simulator's final state.
Args 
program

The circuit to simulate.

param_resolver

Parameters to run with the program.

qubit_order

Determines the canonical ordering of the qubits. This
is often used in specifying the initial state, i.e. the
ordering of the computational basis states.

initial_state

The initial state for the simulation. The form of
this state depends on the simulation implementation. See
documentation of the implementing class for details.

Returns 
SimulationTrialResults for the simulation. Includes the final state.

simulate_expectation_values
simulate_expectation_values(
program: "cirq.AbstractCircuit",
observables: Union['cirq.PauliSumLike', List['cirq.PauliSumLike']],
param_resolver: "study.ParamResolverOrSimilarType" = None,
qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
initial_state: Any = None,
permit_terminal_measurements: bool = False
) > List[float]
Simulates the supplied circuit and calculates exact expectation
values for the given observables on its final state.
This method has no perfect analogy in hardware. Instead compare with
Sampler.sample_expectation_values, which calculates estimated
expectation values by sampling multiple times.
Args 
program

The circuit to simulate.

observables

An observable or list of observables.

param_resolver

Parameters to run with the program.

qubit_order

Determines the canonical ordering of the qubits. This
is often used in specifying the initial state, i.e. the
ordering of the computational basis states.

initial_state

The initial state for the simulation. The form of
this state depends on the simulation implementation. See
documentation of the implementing class for details.

permit_terminal_measurements

If the provided circuit ends with
measurement(s), this method will generate an error unless this
is set to True. This is meant to prevent measurements from
ruining expectation value calculations.

Returns 
A list of expectation values, with the value at index n
corresponding to observables[n] from the input.

Raises 
ValueError if 'program' has terminal measurement(s) and
'permit_terminal_measurements' is False.

simulate_expectation_values_sweep
View source
simulate_expectation_values_sweep(
program: "cirq.Circuit",
observables: Union['cirq.PauliSumLike', List['cirq.PauliSumLike']],
params: "study.Sweepable",
qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
initial_state: Any = None,
permit_terminal_measurements: bool = False
) > List[List[float]]
Simulates the supplied circuit and calculates exact expectation
values for the given observables on its final state.
This method has no perfect analogy in hardware. Instead compare with
Sampler.sample_expectation_values, which calculates estimated
expectation values by sampling multiple times.
Args 
program

The circuit to simulate.

observables

An observable or list of observables.

param_resolver

Parameters to run with the program.

qubit_order

Determines the canonical ordering of the qubits. This
is often used in specifying the initial state, i.e. the
ordering of the computational basis states.

initial_state

The initial state for the simulation. The form of
this state depends on the simulation implementation. See
documentation of the implementing class for details.

permit_terminal_measurements

If the provided circuit ends with
measurement(s), this method will generate an error unless this
is set to True. This is meant to prevent measurements from
ruining expectation value calculations.

Returns 
A list of expectation values, with the value at index n
corresponding to observables[n] from the input.

Raises 
ValueError if 'program' has terminal measurement(s) and
'permit_terminal_measurements' is False. (Note: We cannot test this
until Cirq's are_any_measurements_terminal is released.)

simulate_expectation_values_sweep_iter
simulate_expectation_values_sweep_iter(
program: "cirq.AbstractCircuit",
observables: Union['cirq.PauliSumLike', List['cirq.PauliSumLike']],
params: "study.Sweepable",
qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
initial_state: Any = None,
permit_terminal_measurements: bool = False
) > Iterator[List[float]]
Simulates the supplied circuit and calculates exact expectation
values for the given observables on its final state, sweeping over the
given params.
This method has no perfect analogy in hardware. Instead compare with
Sampler.sample_expectation_values, which calculates estimated
expectation values by sampling multiple times.
Args 
program

The circuit to simulate.

observables

An observable or list of observables.

params

Parameters to run with the program.

qubit_order

Determines the canonical ordering of the qubits. This
is often used in specifying the initial state, i.e. the
ordering of the computational basis states.

initial_state

The initial state for the simulation. The form of
this state depends on the simulation implementation. See
documentation of the implementing class for details.

permit_terminal_measurements

If the provided circuit ends in a
measurement, this method will generate an error unless this
is set to True. This is meant to prevent measurements from
ruining expectation value calculations.

Returns 
An Iterator over expectationvalue lists. The outer index determines
the sweep, and the inner index determines the observable. For
instance, results[1][3] would select the fourth observable measured
in the second sweep.

Raises 
ValueError if 'program' has terminal measurement(s) and
'permit_terminal_measurements' is False.

simulate_sweep
View source
simulate_sweep(
program: circuits.Circuit,
params: study.Sweepable,
qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
initial_state: Optional[Union[int, np.ndarray]] = None
) > List['SimulationTrialResult']
Simulates the supplied Circuit.
This method returns a result which allows access to the entire
wave function. In contrast to simulate, this allows for sweeping
over different parameter values.
Avoid using this method with use_gpu=True
in the simulator options;
when used with GPU this method must copy state from device to host memory
multiple times, which can be very slow. This issue is not present in
simulate_expectation_values_sweep
.
Args 
program

The circuit to simulate.

params

Parameters to run with the program.

qubit_order

Determines the canonical ordering of the qubits. This is
often used in specifying the initial state, i.e. the ordering of the
computational basis states.

initial_state

The initial state for the simulation. This can either
be an integer representing a pure state (e.g. 11010) or a numpy
array containing the full state vector. If none is provided, this
is assumed to be the allzeros state.

Returns 
List of SimulationTrialResults for this run, one for each
possible parameter resolver.

Raises 
TypeError

if an invalid initial_state is provided.

simulate_sweep_iter
simulate_sweep_iter(
program: "cirq.AbstractCircuit",
params: study.Sweepable,
qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
initial_state: Any = None
) > Iterator[TSimulationTrialResult]
Simulates the supplied Circuit.
This method returns a result which allows access to the entire final
simulator state. In contrast to simulate, this allows for sweeping
over different parameter values.
Args 
program

The circuit to simulate.

params

Parameters to run with the program.

qubit_order

Determines the canonical ordering of the qubits. This
is often used in specifying the initial state, i.e. the
ordering of the computational basis states.

initial_state

The initial state for the simulation. The form of
this state depends on the simulation implementation. See
documentation of the implementing class for details.

Returns 
Iterator over SimulationTrialResults for this run, one for each
possible parameter resolver.
