# cirq.SimulatorBase

A base class for the built-in simulators.

Most implementors of this interface should implement the `_create_partial_act_on_args` and `_create_step_result` methods. The first one creates the simulator's quantum state representation at the beginning of the simulation. The second creates the step result emitted after each `Moment` in the simulation.

Iteration in the subclass is handled by the `_core_iterator` implementation here, which handles moment stepping, application of operations, measurement collection, and creation of noise. Simulators with more advanced needs can override the implementation if necessary.

Sampling is handled by the implementation of `_run`. This implementation iterates the circuit to create a final step result, and samples that result when possible. If not possible, due to noise or classical probabilities on a state vector, the implementation attempts to fully iterate the unitary prefix once, then only repeat the non-unitary suffix from copies of the state obtained by the prefix. If more advanced functionality is required, then the `_run` method can be overridden.

Note that state here refers to simulator state, which is not necessarily a state vector. The included simulators and corresponding states are state vector, density matrix, Clifford, and MPS. Each of these use the default `_core_iterator` and `_run` methods.

`dtype` The `numpy.dtype` used by the simulation.
`noise` A noise model to apply while simulating.
`seed` The random seed to use for this simulator.
`ignore_measurement_results` If True, then the simulation will treat measurement as dephasing instead of collapsing process. This is only applicable to simulators that can model dephasing.
`split_untangled_states` If True, optimizes simulation by running unentangled qubit sets independently and merging those states at the end.

## Methods

### `run`

View source

Samples from the given Circuit.

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`

View source

Asynchronously samples from the given Circuit.

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_batch`

View source

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.

Raises
`ValueError` If length of `programs` is not equal to the length of `params_list` or the length of `repetitions`.

### `run_sweep`

View source

Samples from the given Circuit.

This allows for sweeping over different parameter values, unlike the `run` method.

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`

View source

Asynchronously 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` 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_iter`

View source

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.

Raises
`ValueError` If the circuit has no measurements.

### `sample`

View source

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.

Raises
`ValueError` If a supplied sweep is invalid.

#### 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`

View source

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 expectation-value lists. The outer index determines the sweep, and the inner index determines the observable. For instance, results would select the fourth observable measured in the second sweep.

Raises
`ValueError` If the number of samples was not positive, if empty observables were supplied, or if the provided circuit has terminal measurements and `permit_terminal_measurements` is true.

### `simulate`

View source

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_moment_steps`

View source

Returns an iterator of StepResults for each moment simulated.

If the circuit being simulated is empty, a single step result should be returned with the state being set to the initial state.

Args
`circuit` The Circuit to simulate.
`param_resolver` A ParamResolver for determining values of Symbols.
`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 be either a raw state or a `TActOnArgs`. The form of the raw state depends on the simulation implementation. See documentation of the implementing class for details.

Returns
Iterator that steps through the simulation, simulating each moment and returning a StepResult for each moment.

### `simulate_sweep`

View source

Wraps computed states in a list.

Prefer overriding `simulate_sweep_iter`.

### `simulate_sweep_iter`

View source

Simulates the supplied Circuit.

This particular implementation overrides the base implementation such that an unparameterized prefix circuit is simulated and fed into the parameterized suffix circuit.

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 be either a raw state or an `OperationTarget`. The form of the raw state depends on the simulation implementation. See documentation of the implementing class for details.

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

[{ "type": "thumb-down", "id": "missingTheInformationINeed", "label":"Missing the information I need" },{ "type": "thumb-down", "id": "tooComplicatedTooManySteps", "label":"Too complicated / too many steps" },{ "type": "thumb-down", "id": "outOfDate", "label":"Out of date" },{ "type": "thumb-down", "id": "samplesCodeIssue", "label":"Samples / code issue" },{ "type": "thumb-down", "id": "otherDown", "label":"Other" }]
[{ "type": "thumb-up", "id": "easyToUnderstand", "label":"Easy to understand" },{ "type": "thumb-up", "id": "solvedMyProblem", "label":"Solved my problem" },{ "type": "thumb-up", "id": "otherUp", "label":"Other" }]
{"ft_lang_label":"__label__en","ft_lang_prob":0.6846011,"math_prob":0.9468333,"size":12757,"snap":"2022-27-2022-33","text_gpt3_token_len":3037,"char_repetition_ratio":0.15941347,"word_repetition_ratio":0.2434686,"special_character_ratio":0.212354,"punctuation_ratio":0.16590074,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9791867,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-06-28T09:37:23Z\",\"WARC-Record-ID\":\"<urn:uuid:cb03809a-f636-44f1-a20c-ba3566402bd1>\",\"Content-Length\":\"446880\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:f60ae07c-ceb0-4afe-97b9-4f2dc45220fc>\",\"WARC-Concurrent-To\":\"<urn:uuid:57499a19-c176-4d5a-86c4-b88b35ec602b>\",\"WARC-IP-Address\":\"216.239.32.27\",\"WARC-Target-URI\":\"https://quantumai.google/reference/python/cirq/SimulatorBase\",\"WARC-Payload-Digest\":\"sha1:U5FLGOFLLAFCSYGSYNX5UEBZR3W25WKT\",\"WARC-Block-Digest\":\"sha1:PFBKWEXWE7TCBWXVMSW523SCOJ5SREYN\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-27/CC-MAIN-2022-27_segments_1656103360935.27_warc_CC-MAIN-20220628081102-20220628111102-00767.warc.gz\"}"}