qsimcirq.QSimSimulator  |  Quantum Simulator  |  Google Quantum AI (2024)

qsimcirq.QSimSimulator | Quantum Simulator | Google Quantum AI (1) View source on GitHub

Simulator that mimics running on quantum hardware.

qsimcirq.QSimSimulator( qsim_options: Union[None, Dict, qsimcirq.QSimOptions] = None, seed: cirq.RANDOM_STATE_OR_SEED_LIKE = None, noise: cirq.NOISE_MODEL_LIKE = None, circuit_memoization_size: int = 0)

Used in the notebooks

Used in the tutorials
  • Get started with qsimcirq
  • Noise simulation in qsimcirq
  • Simulate a large quantum circuit
  • Quantum Virtual Machine
  • QVM Basic Example

Implementors of this interface should implement the _run method.

Args

qsim_optionsAn options dict or QSimOptions object with optionsto use for all circuits run using this simulator. See theQSimOptions class for details.
seedA random state or seed object, as defined in cirq.value.
noiseA cirq.NoiseModel to apply to all circuits simulated withthis simulator.
circuit_memoization_sizeThe number of last translated circuitsto be memoized from simulation executions, to eliminatetranslation overhead. Every simulation will perform a linearsearch through the list of memoized circuits using circuitequality checks, so a large circuit_memoization_size with largecircuits will incur a significant runtime overhead.Note that every resolved parameterization results in a separatecircuit 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: 'cirq.ParamResolverOrSimilarType' = None, qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT) -> Sequence[complex]

Computes the desired amplitudes.

The initial state is assumed to be the all zeros state.

Args
programThe circuit to simulate.
bitstringsThe bitstrings whose amplitudes are desired, inputas an integer array where each integer is formed from measuredqubit values according to qubit_order from most to leastsignificant qubit, i.e. in big-endian ordering. If inputtinga binary literal add the prefix 0b or 0B.For example: 0010 can be input as 0b0010, 0B0010, 2, 0x2, etc.
param_resolverParameters to run with the program.
qubit_orderDetermines the canonical ordering of the qubits. Thisis often used in specifying the initial state, i.e. theordering of the computational basis states.
Returns
List of amplitudes.

compute_amplitudes_sweep

compute_amplitudes_sweep( program: 'cirq.AbstractCircuit', bitstrings: Sequence[int], params: 'cirq.Sweepable', qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT) -> Sequence[Sequence[complex]]

Wraps computed amplitudes in a list.

Prefer overriding compute_amplitudes_sweep_iter.

compute_amplitudes_sweep_iter

View source

compute_amplitudes_sweep_iter( program: cirq.Circuit, bitstrings: Sequence[int], params: cirq.Sweepable, qubit_order: cirq.QubitOrderOrList = cirq.QubitOrder.DEFAULT) -> Iterator[Sequence[complex]]

Computes the desired amplitudes using qsim.

The initial state is assumed to be the all zeros state.

Args
programThe circuit to simulate.
bitstringsThe bitstrings whose amplitudes are desired, input as anstring array where each string is formed from measured qubit valuesaccording to qubit_order from most to least significant qubit,i.e., in big-endian ordering.
param_resolverParameters to run with the program.
qubit_orderDetermines the canonical ordering of the qubits. This isoften used in specifying the initial state, i.e., the ordering of thecomputational basis states.
Yields
Amplitudes.

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.

This mode of operation for a sampler will provide resultsin the form of measurement outcomes. It will not provideaccess to state vectors (even if the underlyingsampling mechanism is a simulator). This method will substituteparameters in the param_resolver attributes for sympy.Symbolsused within the Circuit. This circuit will be executed a numberof times specified in the repetitions attribute, though somesimulated implementations may instead sample from the finaldistribution rather than execute the circuit each time.

Args
programThe circuit to sample from.
param_resolverParameters to run with the program.
repetitionsThe number of times to sample.
Returns
cirq.Result that contains all the measurements for a run.

run_async

run_async( program, param_resolver=None, repetitions=1)

Asynchronously samples from the given Circuit.

Provides measurement outcomes as a cirq.Result object. Thisinterface will operate in a similar way to the run methodexcept for executing asynchronously.

Args
programThe circuit to sample from.
param_resolverParameters to run with the program.
repetitionsThe number of times to sample.
Returns
Result for a run.

run_batch

run_batch( programs: Sequence['cirq.AbstractCircuit'], params_list: Optional[Sequence['cirq.Sweepable']] = None, repetitions: Union[int, Sequence[int]] = 1) -> Sequence[Sequence['cirq.Result']]

Runs the supplied circuits.

Each circuit provided in programs will pair with the optionalassociated parameter sweep provided in the params_list, and be runwith the associated repetitions provided in repetitions (ifrepetitions is an integer, then all runs will have that number ofrepetitions). If params_list is specified, then the number ofcircuits is required to match the number of sweeps. Similarly, whenrepetitions is a list, the number of circuits is required to matchthe length of this list.

By default, this method simply invokes run_sweep sequentially foreach (circuit, parameter sweep, repetitions) tuple. Child classes thatare capable of sampling batches more efficiently should override it touse other strategies. Note that child classes may have certainrequirements 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
programsThe circuits to execute as a batch.
params_listParameter sweeps to use with the circuits. The numberof sweeps should match the number of circuits and will bepaired in order with the circuits.
repetitionsNumber of circuit repetitions to run. Can be specifiedas 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 tothe circuits, while each inner list contains the TrialResultsfor the corresponding circuit, in the order imposed by theassociated parameter sweep.
Raises
ValueErrorIf length of programs is not equal to the lengthof params_list or the length of repetitions.

run_batch_async

run_batch_async( programs, params_list=None, repetitions=1)

Runs the supplied circuits asynchronously.

See docs for cirq.Sampler.run_batch.

run_sweep

run_sweep( program: 'cirq.AbstractCircuit', params: 'cirq.Sweepable', repetitions: int = 1) -> Sequence['cirq.Result']

Samples from the given Circuit.

This allows for sweeping over different parameter values,unlike the run method. The params argument will provide amapping from sympy.Symbols used within the circuit to a set ofvalues. Unlike the run method, which specifies a singlemapping from symbol to value, this method allows a "sweep" ofvalues. This allows a user to specify execution of a family ofrelated circuits efficiently.

Args
programThe circuit to sample from.
paramsParameters to run with the program.
repetitionsThe 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 samples from the given Circuit.

By default, this method invokes run_sweep synchronously and simplyexposes its result is an awaitable. Child classes that are capable oftrue asynchronous sampling should override it to use other strategies.

Args
programThe circuit to sample from.
paramsParameters to run with the program.
repetitionsThe number of times to sample.
Returns
Result list for this run; one for each possible parameter resolver.

run_sweep_iter

run_sweep_iter( program: 'cirq.AbstractCircuit', params: 'cirq.Sweepable', repetitions: int = 1) -> Iterator['cirq.Result']

Runs the supplied Circuit, mimicking quantum hardware.

In contrast to run, this allows for sweeping over different parametervalues.

Args
programThe circuit to simulate.
paramsParameters to run with the program.
repetitionsThe number of repetitions to simulate.
Returns
Result list for this run; one for each possible parameterresolver.
Raises
ValueErrorIf the circuit has no measurements.

sample

sample( program: 'cirq.AbstractCircuit', *, repetitions: int = 1, params: 'cirq.Sweepable' = None) -> 'pd.DataFrame'

Samples the given Circuit, producing a pandas data frame.

This interface will operate in a similar way to the run methodexcept that it returns a pandas data frame rather than a cirq.Resultobject.

Args
programThe circuit to sample from.
repetitionsThe number of times to sample the program, for eachparameter mapping.
paramsMaps symbols to one or more values. This argument can bea dictionary, a list of dictionaries, a cirq.Sweep, a list ofcirq.Sweep, etc. The program will be sampled repetitiontimes for each mapping. Defaults to a single empty mapping.
Returns
A pandas.DataFrame with a row for each sample, and a column foreach measurement key as well as a column for each symbolicparameter. Measurement results are stored as a big endian integerrepresentation with one bit for each measured qubit in the key.See cirq.big_endian_int_to_bits and similar functions for howto convert this integer into bits.There is an also index column containing the repetition number,for each parameter assignment.
Raises
ValueErrorIf 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)) out0 11 12 13 1
circuit = cirq.Circuit(cirq.X(a), cirq.CNOT(a, b), cirq.measure(a, b, c, key='out'))print(sampler.sample(circuit, repetitions=4)) out0 61 62 63 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 out0 0 01 0 02 0 00 1 11 1 12 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) -> Sequence[Sequence[float]]

Calculates estimated expectation values from samples of a circuit.

Please see also cirq.work.observable_measurement.measure_observablesfor more control over how to measure a suite of observables.

This method can be run on any device or simulator that supports circuit sampling. Comparewith simulate_expectation_values in simulator.py, which is limited to simulatorsbut provides exact results.

Args
programThe circuit which prepares a state from which we sample expectation values.
observablesA list of observables for which to calculate expectation values.
num_samplesThe number of samples to take. Increasing this value increases thestatistical accuracy of the estimate.
paramsParameters to run with the program.
permit_terminal_measurementsIf the provided circuit ends in a measurement, thismethod will generate an error unless this is set to True. This is meant toprevent measurements from ruining expectation value calculations.
Returns
A list of expectation-value lists. The outer index determines the sweep, and the innerindex determines the observable. For instance, results[1][3] would select the fourthobservable measured in the second sweep.
Raises
ValueErrorIf the number of samples was not positive, if empty observables weresupplied, or if the provided circuit has terminal measurements andpermit_terminal_measurements is true.

sample_from_amplitudes

sample_from_amplitudes( circuit: 'cirq.AbstractCircuit', param_resolver: 'cirq.ParamResolver', seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE', repetitions: int = 1, qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT) -> Dict[int, int]

Uses amplitude simulation to sample from the given circuit.

This implements the algorithm outlined by Bravyi, Gosset, and Liu inhttps://arxiv.org/abs/2112.08499 to more efficiently calculate samplesgiven an amplitude-based simulator.

Simulators which also implement SimulatesSamples or SimulatesFullStateshould prefer run() or simulate(), respectively, as this methodonly accelerates sampling for amplitude-based simulators.

Args
circuitThe circuit to simulate.
param_resolverParameters to run with the program.
seedRandom state to use as a seed. This must be providedmanually - if the simulator has its own seed, it will not beused unless it is passed as this argument.
repetitionsThe number of repetitions to simulate.
qubit_orderDetermines the canonical ordering of the qubits. Thisis often used in specifying the initial state, i.e. theordering of the computational basis states.
Returns
A dict of bitstrings sampled from the final state of circuit tothe number of occurrences of that bitstring.
Raises
ValueErrorif 'circuit' has non-unitary elements, as differencesin behavior between sampling steps break this algorithm.

simulate

simulate( program: 'cirq.AbstractCircuit', param_resolver: 'cirq.ParamResolverOrSimilarType' = None, qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT, initial_state: Any = None) -> TSimulationTrialResult

Simulates the supplied Circuit.

This method returns a result which allows access to the entiresimulator's final state.

Args
programThe circuit to simulate.
param_resolverParameters to run with the program.
qubit_orderDetermines the canonical ordering of the qubits. Thisis often used in specifying the initial state, i.e. theordering of the computational basis states.
initial_stateThe initial state for the simulation. The form ofthis state depends on the simulation implementation. Seedocumentation 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: 'cirq.ParamResolverOrSimilarType' = None, qubit_order: 'cirq.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 withSampler.sample_expectation_values, which calculates estimatedexpectation values by sampling multiple times.

Args
programThe circuit to simulate.
observablesAn observable or list of observables.
param_resolverParameters to run with the program.
qubit_orderDetermines the canonical ordering of the qubits. Thisis often used in specifying the initial state, i.e. theordering of the computational basis states.
initial_stateThe initial state for the simulation. The form ofthis state depends on the simulation implementation. Seedocumentation of the implementing class for details.
permit_terminal_measurementsIf the provided circuit ends withmeasurement(s), this method will generate an error unless thisis set to True. This is meant to prevent measurements fromruining expectation value calculations.
Returns
A list of expectation values, with the value at index ncorresponding to observables[n] from the input.
Raises
ValueError if 'program' has terminal measurement(s) and'permit_terminal_measurements' is False.

simulate_expectation_values_sweep

simulate_expectation_values_sweep( program: 'cirq.AbstractCircuit', observables: Union['cirq.PauliSumLike', List['cirq.PauliSumLike']], params: 'cirq.Sweepable', qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT, initial_state: Any = None, permit_terminal_measurements: bool = False) -> List[List[float]]

Wraps computed expectation values in a list.

Prefer overriding simulate_expectation_values_sweep_iter.

simulate_expectation_values_sweep_iter

View source

simulate_expectation_values_sweep_iter( program: cirq.Circuit, observables: Union[cirq.PauliSumLike, List[cirq.PauliSumLike]], params: cirq.Sweepable, qubit_order: cirq.QubitOrderOrList = cirq.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.

This method has no perfect analogy in hardware. Instead compare withSampler.sample_expectation_values, which calculates estimatedexpectation values by sampling multiple times.

Args
programThe circuit to simulate.
observablesAn observable or list of observables.
paramsParameters to run with the program.
qubit_orderDetermines the canonical ordering of the qubits. Thisis often used in specifying the initial state, i.e., theordering of the computational basis states.
initial_stateThe initial state for the simulation. The form ofthis state depends on the simulation implementation. Seedocumentation of the implementing class for details.
permit_terminal_measurementsIf the provided circuit ends withmeasurement(s), this method will generate an error unless thisis set to True. This is meant to prevent measurements fromruining expectation value calculations.
Yields
Lists of expectation values, with the value at index ncorresponding to observables[n] from the input.
Raises
ValueError if 'program' has terminal measurement(s) and'permit_terminal_measurements' is False. (Note: We cannot test thisuntil Cirq's are_any_measurements_terminal is released.)

simulate_into_1d_array

View source

simulate_into_1d_array( program: cirq.AbstractCircuit, param_resolver: cirq.ParamResolverOrSimilarType = None, qubit_order: cirq.QubitOrderOrList = cirq.ops.QubitOrder.DEFAULT, initial_state: Any = None) -> Tuple[cirq.ParamResolver, np.ndarray, Sequence[int]]

Same as simulate() but returns raw simulation result without wrapping it.

The returned result is not wrapped in a StateVectorTrialResult but can be usedto create a StateVectorTrialResult.
Returns
Tuple of (param resolver, final state, qubit order)

simulate_moment_expectation_values

View source

simulate_moment_expectation_values( program: cirq.Circuit, indexed_observables: Union[Dict[int, Union[cirq.PauliSumLike, List[cirq.PauliSumLike]]], cirq. PauliSumLike, List[cirq.PauliSumLike]], param_resolver: cirq.ParamResolver, qubit_order: cirq.QubitOrderOrList = cirq.QubitOrder.DEFAULT, initial_state: Any = None) -> List[List[float]]

Calculates expectation values at each moment of a circuit.

Args
programThe circuit to simulate.
indexed_observablesA map of moment indices to an observableor list of observables to calculate after that moment. As aconvenience, users can instead pass in a single observableor observable list to calculate after ALL moments.
param_resolverParameters to run with the program.
qubit_orderDetermines the canonical ordering of the qubits. Thisis often used in specifying the initial state, i.e., theordering of the computational basis states.
initial_stateThe initial state for the simulation. The form ofthis state depends on the simulation implementation. Seedocumentation of the implementing class for details.
permit_terminal_measurementsIf the provided circuit ends withmeasurement(s), this method will generate an error unless thisis set to True. This is meant to prevent measurements fromruining expectation value calculations.
Returns
A list of expectation values for each moment m in the circuit,where value n corresponds to indexed_observables[m][n].
Raises
ValueError if 'program' has terminal measurement(s) and'permit_terminal_measurements' is False. (Note: We cannot test thisuntil Cirq's are_any_measurements_terminal is released.)

simulate_sweep

simulate_sweep( program: 'cirq.AbstractCircuit', params: 'cirq.Sweepable', qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT, initial_state: Any = None) -> List[TSimulationTrialResult]

Wraps computed states in a list.

Prefer overriding simulate_sweep_iter.

simulate_sweep_iter

View source

simulate_sweep_iter( program: cirq.Circuit, params: cirq.Sweepable, qubit_order: cirq.QubitOrderOrList = cirq.QubitOrder.DEFAULT, initial_state: Optional[Union[int, np.ndarray]] = None) -> Iterator[cirq.StateVectorTrialResult]

Simulates the supplied Circuit.

This method returns a result which allows access to the entirewave function. In contrast to simulate, this allows for sweepingover 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 memorymultiple times, which can be very slow. This issue is not present insimulate_expectation_values_sweep.

Args
programThe circuit to simulate.
paramsParameters to run with the program.
qubit_orderDetermines the canonical ordering of the qubits. This isoften used in specifying the initial state, i.e., the ordering of thecomputational basis states.
initial_stateThe initial state for the simulation. This can eitherbe an integer representing a pure state (e.g. 11010) or a numpyarray containing the full state vector. If none is provided, thisis assumed to be the all-zeros state.
Returns
Iterator over SimulationTrialResults for this run, one for eachpossible parameter resolver.
Raises
TypeErrorif an invalid initial_state is provided.
qsimcirq.QSimSimulator  |  Quantum Simulator  |  Google Quantum AI (2024)
Top Articles
Stampin Pretty
Libidoverlust: Häufigkeit, Arztbesuch
Room Background For Zepeto
Is pickleball Betts' next conquest? 'That's my jam'
The Daily News Leader from Staunton, Virginia
Z-Track Injection | Definition and Patient Education
Encore Atlanta Cheer Competition
GAY (and stinky) DOGS [scat] by Entomb
What Happened To Father Anthony Mary Ewtn
Buckaroo Blog
2013 Chevy Cruze Coolant Hose Diagram
Zendaya Boob Job
Methodist Laborworkx
Think Up Elar Level 5 Answer Key Pdf
Studentvue Columbia Heights
Teenleaks Discord
Are They Not Beautiful Wowhead
Truth Of God Schedule 2023
Alexander Funeral Home Gallatin Obituaries
Gem City Surgeons Miami Valley South
Hellraiser III [1996] [R] - 5.8.6 | Parents' Guide & Review | Kids-In-Mind.com
Troy Bilt Mower Carburetor Diagram
The Pretty Kitty Tanglewood
Sunset Time November 5 2022
27 Paul Rudd Memes to Get You Through the Week
Elbert County Swap Shop
Kabob-House-Spokane Photos
Watson 853 White Oval
10 Best Places to Go and Things to Know for a Trip to the Hickory M...
Login.castlebranch.com
Sinfuldeed Leaked
Craigslist West Seneca
Property Skipper Bermuda
Cbs Fantasy Mlb
10 games with New Game Plus modes so good you simply have to play them twice
Nsav Investorshub
Wait List Texas Roadhouse
Dispensaries Open On Christmas 2022
The Realreal Temporary Closure
Actor and beloved baritone James Earl Jones dies at 93
Guy Ritchie's The Covenant Showtimes Near Grand Theatres - Bismarck
Amc.santa Anita
LoL Lore: Die Story von Caitlyn, dem Sheriff von Piltover
Blackwolf Run Pro Shop
Sky Dental Cartersville
Wisconsin Volleyball titt*es
Union Supply Direct Wisconsin
Suppress Spell Damage Poe
About us | DELTA Fiber
Deshuesadero El Pulpo
Houston Primary Care Byron Ga
Craigs List Sarasota
Latest Posts
Article information

Author: Laurine Ryan

Last Updated:

Views: 5619

Rating: 4.7 / 5 (77 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Laurine Ryan

Birthday: 1994-12-23

Address: Suite 751 871 Lissette Throughway, West Kittie, NH 41603

Phone: +2366831109631

Job: Sales Producer

Hobby: Creative writing, Motor sports, Do it yourself, Skateboarding, Coffee roasting, Calligraphy, Stand-up comedy

Introduction: My name is Laurine Ryan, I am a adorable, fair, graceful, spotless, gorgeous, homely, cooperative person who loves writing and wants to share my knowledge and understanding with you.