
    {	il                         S r SSKrSSKrSSKJr  SSKJr  SSKJr  SSK	J
r
  SSKJr  S	S
KJr  S	SKJr  S	SKJr  S	SKJrJrJrJrJr  S	SKJr  \R6                  " \5      r " S S\5      rg)z
Aer qasm simulator backend.
    N)warnOptions)	BackendV2   )__version__)AerError   )
AerBackend)AerBackendConfiguration)target_to_backend_properties)cpp_execute_circuitsavailable_methodsMAX_QUBITS_STATEVECTORLEGACY_METHOD_MAPmap_legacy_method_config)aer_controller_executec                     ^  \ rS rSrSr\" / SQ5      r\" / SQ5      rS\\	SSSSS\
" S5      S	S
\\/ S.r/ SQrS
rSrS
rSU 4S jjrU 4S jr\S 5       r\S 5       rS rS rS rS rU 4S jrS rS rS rSS jrSrU =r$ )QasmSimulator)   a.  
Noisy quantum circuit simulator backend.

**Configurable Options**

The `QasmSimulator` supports multiple simulation methods and
configurable options for each simulation method. These may be set using the
appropriate kwargs during initialization. They can also be set of updated
using the :meth:`set_options` method.

Run-time options may also be specified as kwargs using the :meth:`run` method.
These will not be stored in the backend and will only apply to that execution.
They will also override any previously set options.

For example, to configure a density matrix simulator with a custom noise
model to use for every execution

.. code-block:: python

    noise_model = NoiseModel.from_backend(backend)
    backend = QasmSimulator(method='density_matrix',
                            noise_model=noise_model)

**Simulating an IBM Quantum Backend**

The simulator can be automatically configured to mimic an IBM Quantum backend using
the :meth:`from_backend` method. This will configure the simulator to use the
basic device :class:`NoiseModel` for that backend, and the same basis gates
and coupling map.

.. code-block:: python

    backend = QasmSimulator.from_backend(backend)

**Simulation Method Option**

The simulation method is set using the ``method`` kwarg.
Supported simulation methods are

* ``"statevector"``: A dense statevector simulation that can sample
  measurement outcomes from *ideal* circuits with all measurements at
  end of the circuit. For noisy simulations each shot samples a
  randomly sampled noisy circuit from the noise model.
  ``"statevector_cpu"`` is an alias of ``"statevector"``.

* ``"statevector_gpu"``: A dense statevector simulation that provides
  the same functionalities with ``"statevector"``. GPU performs the computation
  to calculate probability amplitudes as CPU does. If no GPU is available,
  a runtime error is raised.

* ``"density_matrix"``: A dense density matrix simulation that may
  sample measurement outcomes from *noisy* circuits with all
  measurements at end of the circuit. It can only simulate half the
  number of qubits as the statevector method.

* ``"density_matrix_gpu"``: A dense density matrix simulation that provides
  the same functionalities with ``"density_matrix"``. GPU performs the computation
  to calculate probability amplitudes as CPU does. If no GPU is available,
  a runtime error is raised.

* ``"stabilizer"``: An efficient Clifford stabilizer state simulator
  that can simulate noisy Clifford circuits if all errors in the noise model are also
  Clifford errors.

* ``"extended_stabilizer"``: An approximate simulated based on a
  ranked-stabilizer decomposition that decomposes circuits into stabilizer
  state terms. The number of terms grows with the number of
  non-Clifford gates.

* ``"matrix_product_state"``: A tensor-network statevector simulator that
  uses a Matrix Product State (MPS) representation for the state.

* ``"automatic"``: The default behavior where the method is chosen
  automatically for each circuit based on the circuit instructions,
  number of qubits, and noise model.

**Additional Backend Options**

The following simulator specific backend options are supported

* ``method`` (str): Set the simulation method (Default: ``"automatic"``).
  Use :meth:`available_methods` to return a list of all availabe methods.

* ``device`` (str): Set the simulation device (Default: ``"CPU"``).
  Use :meth:`available_devices` to return a list of devices supported
  on the current system.

* ``precision`` (str): Set the floating point precision for
  certain simulation methods to either ``"single"`` or ``"double"``
  precision (default: ``"double"``).

* ``executor`` (futures.Executor): Set a custom executor for
  asynchronous running of simulation jobs (Default: None).

* ``max_job_size`` (int or None): If the number of run circuits
  exceeds this value simulation will be run as a set of of sub-jobs
  on the executor. If ``None`` simulation of all circuits are submitted
  to the executor as a single job (Default: None).

* ``max_shot_size`` (int or None): If the number of shots of a noisy
  circuit exceeds this value simulation will be split into multi
  circuits for execution and the results accumulated. If ``None``
  circuits will not be split based on shots. When splitting circuits
  use the ``max_job_size`` option to control how these split circuits
  should be submitted to the executor (Default: None).

* ``enable_truncation`` (bool): If set to True this removes unnecessary
  qubits which do not affect the simulation outcome from the simulated
  circuits (Default: True).

* ``zero_threshold`` (double): Sets the threshold for truncating
  small values to zero in the result data (Default: 1e-10).

* ``validation_threshold`` (double): Sets the threshold for checking
  if initial states are valid (Default: 1e-8).

* ``max_parallel_threads`` (int): Sets the maximum number of CPU
  cores used by OpenMP for parallelization. If set to 0 the
  maximum will be set to the number of CPU cores (Default: 0).

* ``max_parallel_experiments`` (int): Sets the maximum number of
  experiments that may be executed in parallel up to the
  max_parallel_threads value. If set to 1 parallel circuit
  execution will be disabled. If set to 0 the maximum will be
  automatically set to max_parallel_threads (Default: 1).

* ``max_parallel_shots`` (int): Sets the maximum number of
  shots that may be executed in parallel during each experiment
  execution, up to the max_parallel_threads value. If set to 1
  parallel shot execution will be disabled. If set to 0 the
  maximum will be automatically set to max_parallel_threads.
  Note that this cannot be enabled at the same time as parallel
  experiment execution (Default: 0).

* ``max_memory_mb`` (int): Sets the maximum size of memory
  to store a state vector. If a state vector needs more, an error
  is thrown. In general, a state vector of n-qubits uses 2^n complex
  values (16 Bytes). If set to 0, the maximum will be automatically
  set to the system memory size (Default: 0).

These backend options only apply when using the ``"statevector"``
simulation method:

* ``statevector_parallel_threshold`` (int): Sets the threshold that
  the number of qubits must be greater than to enable OpenMP
  parallelization for matrix multiplication during execution of
  an experiment. If parallel circuit or shot execution is enabled
  this will only use unallocated CPU cores up to
  max_parallel_threads. Note that setting this too low can reduce
  performance (Default: 14).

* ``statevector_sample_measure_opt`` (int): Sets the threshold that
  the number of qubits must be greater than to enable a large
  qubit optimized implementation of measurement sampling. Note
  that setting this two low can reduce performance (Default: 10)

These backend options only apply when using the ``"stabilizer"``
simulation method:

* ``stabilizer_max_snapshot_probabilities`` (int): set the maximum
  qubit number for the :class:`~qiskit_aer.library.SaveProbabilities` instruction (Default: 32).

These backend options only apply when using the ``"extended_stabilizer"``
simulation method:

* ``extended_stabilizer_sampling_method`` (string): Choose how to simulate
  measurements on qubits. The performance of the simulator depends
  significantly on this choice. In the following, let n be the number of
  qubits in the circuit, m the number of qubits measured, and S be the
  number of shots (Default: resampled_metropolis).

  - ``"metropolis"``: Use a Monte-Carlo method to sample many output
    strings from the simulator at once. To be accurate, this method
    requires that all the possible output strings have a non-zero
    probability. It will give inaccurate results on cases where
    the circuit has many zero-probability outcomes.
    This method has an overall runtime that scales as n^{2} + (S-1)n.

  - ``"resampled_metropolis"``: A variant of the metropolis method,
    where the Monte-Carlo method is reinitialised for every shot. This
    gives better results for circuits where some outcomes have zero
    probability, but will still fail if the output distribution
    is sparse. The overall runtime scales as Sn^{2}.

  - ``"norm_estimation"``: An alternative sampling method using
    random state inner products to estimate outcome probabilities. This
    method requires twice as much memory, and significantly longer
    runtimes, but gives accurate results on circuits with sparse
    output distributions. The overall runtime scales as Sn^{3}m^{3}.

* ``extended_stabilizer_metropolis_mixing_time`` (int): Set how long the
  monte-carlo method runs before performing measurements. If the
  output distribution is strongly peaked, this can be decreased
  alongside setting extended_stabilizer_disable_measurement_opt
  to True (Default: 5000).

* ``"extended_stabilizer_approximation_error"`` (double): Set the error
  in the approximation for the extended_stabilizer method. A
  smaller error needs more memory and computational time
  (Default: 0.05).

* ``extended_stabilizer_norm_estimation_samples`` (int): The default number
  of samples for the norm estimation sampler. The method will use the
  default, or 4m^{2} samples where m is the number of qubits to be
  measured, whichever is larger (Default: 100).

* ``extended_stabilizer_norm_estimation_repetitions`` (int): The number
  of times to repeat the norm estimation. The median of these reptitions
  is used to estimate and sample output strings (Default: 3).

* ``extended_stabilizer_parallel_threshold`` (int): Set the minimum
  size of the extended stabilizer decomposition before we enable
  OpenMP parallelization. If parallel circuit or shot execution
  is enabled this will only use unallocated CPU cores up to
  max_parallel_threads (Default: 100).

* ``extended_stabilizer_probabilities_snapshot_samples`` (int): If using
  the metropolis or resampled_metropolis sampling method, set the number of
  samples used to estimate probabilities in a probabilities snapshot
  (Default: 3000).

These backend options only apply when using the ``"matrix_product_state"``
simulation method:

* ``matrix_product_state_max_bond_dimension`` (int): Sets a limit
  on the number of Schmidt coefficients retained at the end of
  the svd algorithm. Coefficients beyond this limit will be discarded.
  (Default: None, i.e., no limit on the bond dimension).

* ``matrix_product_state_truncation_threshold`` (double):
  Discard the smallest coefficients for which the sum of
  their squares is smaller than this threshold.
  (Default: 1e-16).

* ``mps_sample_measure_algorithm`` (str): Choose which algorithm to use for
  ``"sample_measure"`` (Default: "mps_apply_measure").

  - ``"mps_probabilities"``: This method first constructs the probability
    vector and then generates a sample per shot. It is more efficient for
    a large number of shots and a small number of qubits, with complexity
    O(2^n * n * D^2) to create the vector and O(1) per shot, where n is
    the number of qubits and D is the bond dimension.

  - ``"mps_apply_measure"``: This method creates a copy of the mps structure
    and measures directly on it. It is more efficient for a small number of
    shots, and a large number of qubits, with complexity around
    O(n * D^2) per shot.

* ``mps_log_data`` (str): if True, output logging data of the MPS
  structure: bond dimensions and values discarded during approximation.
  (Default: False)

These backend options apply in circuit optimization passes:

* ``fusion_enable`` (bool): Enable fusion optimization in circuit
  optimization passes [Default: True]
* ``fusion_verbose`` (bool): Output gates generated in fusion optimization
  into metadata [Default: False]
* ``fusion_max_qubit`` (int): Maximum number of qubits for a operation generated
  in a fusion optimization [Default: 5]
* ``fusion_threshold`` (int): Threshold that number of qubits must be greater
  than or equal to enable fusion optimization [Default: 14]
);u1u2u3uprrxryrzidxyzhssdgsxsxdgttdgswapcxcyczcsxcpcucu1cu2cu3rxxryyrzzrzxccxcswapmcxmcymczmcsxmcpmcphasemcumcu1mcu2mcu3mcrxmcrymcrzmcrmcswapunitarydiagonalmultiplexer
initializedelaypaulimcx_grayecr)quantum_channel
qerror_locroerrorkraussave_expvalsave_expval_varsave_probabilitiessave_probabilities_dictsave_amplitudessave_amplitudes_sq
save_statesave_density_matrixsave_statevectorsave_statevector_dictsave_stabilizerset_statevectorset_density_matrixset_stabilizerresetqasm_simulatorz$https://github.com/Qiskit/qiskit-aerT    .AzA C++ Qasm simulator with noiseN)backend_namebackend_versionn_qubitsurl	simulatorlocalconditionalmemory	max_shotsdescriptioncoupling_mapbasis_gatescustom_instructionsgates)	automaticstatevectorstatevector_gpustatevector_custatevecstatevector_thrustdensity_matrixdensity_matrix_gpudensity_matrix_custatevecdensity_matrix_thrust
stabilizermatrix_product_stateextended_stabilizer)CPUGPUThrustc                 d  > [        S[        5        [        5       U l        [        R
                  c1  [        [        R                  [        R                  5      [        l        Uc%  [        R                  " [        R                  5      nOSUl        U R                  U l        [        TU ]A  XX4S9  g )NzsThe `QasmSimulator` backend will be deprecated in the future. It has been superseded by the `AerSimulator` backend.F)providerbackend_options)r   PendingDeprecationWarningr   _controllerr   _AVAILABLE_METHODSr   _SIMULATION_METHODS_SIMULATION_DEVICESr   	from_dict_DEFAULT_CONFIGURATION
open_pulse_DEFAULT_BASIS_GATES_cached_basis_gatessuper__init__)selfconfiguration
propertiesr   r   	__class__s        \/home/james-whalen/.local/lib/python3.13/site-packages/qiskit_aer/backends/qasm_simulator.pyr   QasmSimulator.__init__  s     &		
 23 ++3/@11110M,  3==m>b>bcM',M$ $(#<#<  	 	
    c                 X  > [         TU ]  5       SS nS[        U R                  R                  5      S-   -  n[        U R                  SS5      nUS;  a  USU SU S	3-  n[        U R                  S
S5      nUb*  UR                  5       (       d  USU S[        U5       S3-  nUS-  nU$ )z'String representation of an AerBackend.N r
   method)Nru   z,
zmethod=''noise_modelznoise_model=))	r   __repr__lenr   __name__getattroptionsis_idealrepr)r   displaypadr   r   r   s        r   r   QasmSimulator.__repr__  s    '"$Sb)S001A56x6,,SE&33GdllM4@";+?+?+A+ASEd;.?-@BBG3r   c                    [        S?0 SS_SS _SS_SS_SS _S	S _S
S _SS_SS_SS _SS _SS _SS _SS _SS_SS_SS_SS_SS _SS _SS_SS _SS _S S _S!S_S"S#_S$S%_S&S'_S(S)_S*S+_S,S-_S.S/_S0S-_S1S2_S3S4_S5S _S6S7_S8S_S9S:_S;S_S<S=_S>S_6$ )@Nshotsi   r   devicer   	precisiondoubleexecutormax_job_sizemax_shot_sizeenable_truncationTzero_thresholdg|=validation_thresholdmax_parallel_threadsmax_parallel_experimentsmax_parallel_shotsmax_memory_mbfusion_enablefusion_verboseFfusion_max_qubit   fusion_threshold   accept_distributed_resultsblocking_qubitsblocking_enablern   r   seed_simulatorstatevector_parallel_thresholdstatevector_sample_measure_opt
   %stabilizer_max_snapshot_probabilities    #extended_stabilizer_sampling_methodresampled_metropolis*extended_stabilizer_metropolis_mixing_timei  'extended_stabilizer_approximation_errorg?+extended_stabilizer_norm_estimation_samplesd   /extended_stabilizer_norm_estimation_repetitions   &extended_stabilizer_parallel_threshold2extended_stabilizer_probabilities_snapshot_samplesi  )matrix_product_state_truncation_thresholdgؗҜ<'matrix_product_state_max_bond_dimensionmps_sample_measure_algorithmmps_heuristicmps_log_datachop_thresholdg:0yE>mps_parallel_thresholdmps_omp_threadsr
   
mps_lapack r   )clss    r   _default_optionsQasmSimulator._default_options  s    0
0
 0
 	0

 0
 0
 0
 0
 #0
 !0
 "&0
 "&0
 &*0
  $0
 0
  !0
" !#0
$ %0
&  '0
( (,)0
* !+0
, "-0
. /0
0 10
2  30
6 ,.70
8 ,.90
< 35=0
@ 1GA0
B 8<C0
D 59E0
F 9<G0
H =>I0
J 47K0
L @DM0
P 7<Q0
R 59S0
T *9U0
V W0
X  Y0
Z $&[0
\ ]0
^ _0
 0	
r   c                 @   [        U[        5      (       a  UR                  c  SnOUR                  n[        SUR                   S3UR
                  UR                  UR                  / [        S5      [        UR                  R                  5       5      UR                  US9	n[        UR                  5      nUR                  nO[        S[!        U5       S35      eSU;  a0  S	S
KJn  UR'                  U5      nUR)                  5       (       d  XS'   U " SXEUS.UD6n	U	$ )z"Initialize simulator from backend.z$created by AerSimulator.from_backendzaer_simulator_from(r   rf   )	rg   rh   ri   rr   rt   ro   rq   max_experimentsrp   z8The backend argument requires a BackendV2 object, not a z objectr   r   )
NoiseModel)r   r   targetr   )
isinstancer   rp   r   namerh   
num_qubitsoperation_namesintlistrq   	get_edgesmax_circuitsr   r   	TypeErrortypenoise.noise_modelr   from_backendr   )
r   backendr   rp   r   r   r   r   r   sims
             r   r   QasmSimulator.from_backend  s    gy))""*D%11327<<.B ' 7 7 ++#33c(!'"6"6"@"@"BC ' 4 4'
M 6gnnEJ^^FMdSZm_\cd  ' 7$11':K'')))4& _V_W^_
r   c                 
   [         R                   " U R                  5      nU R                  R                  5        H  u  p#[	        XU5        M     U R                  5       Ul        U R                  UR                  -   Ul        U$ )zsReturn the simulator backend configuration.

Returns:
    BackendConfiguration: the configuration for the backend.
)	copy_configuration_options_configurationitemssetattr_custom_instructionsrs   r   rr   )r   configkeyvals       r   r   QasmSimulator.configuration;  sn     4../3399;HCF% < &*%>%>%@"!558R8RRr   c                 B    [         R                   " U R                  5      $ z(Return the available simulation methods.)r   r   r   s    r   r   QasmSimulator.available_methodsJ      yy0011r   c                 B    [         R                   " U R                  5      $ r   )r   _AVAILABLE_DEVICESr   s    r   available_devicesQasmSimulator.available_devicesN  r  r   c                 F    [        U5      n[        U R                  XU5      $ )z Execute circuits on the backend.)r   r   r   )r   aer_circuitsr   r   s       r   _execute_circuitsQasmSimulator._execute_circuitsR  s"    )&1#D$4$4lQWXXr   c                 r  > US:X  a  U R                  X5        g US:X  am  U[        ;   a  [        U   u  p#U R                  SU5        Ub2  X R                  5       ;  a  [	        SU SU R                  5        35      eU R                  U5        [        TU ]	  X5        US;   a  U R                  5       U l        g g )Nrs   r   r   zInvalid simulation method z. Available methods are: )r   r   rr   )	_set_configuration_optionr   
set_optionr   r	   _set_method_configr   _basis_gatesr   )r   r   valuer   r   s       r   r  QasmSimulator.set_optionW  s    ''**36(?)) 1% 8&1 U2H2H2J%J0 8!33568  ##E*3&::'+'8'8':D$ ;r   c                    SU R                   ;   a  U R                   S   $ U R                  5       nU R                  R                  nU(       a  [	        U5      R                  U5      nOUn[        U R                  SS5      nU(       a  UR                  nUR                  U5      nOSnU(       d  [        R                  SUUU5        [        U5      $ )zReturn simulator basis gates.

This will be the option value of basis gates if it was set,
otherwise it will be the intersection of the configuration, noise model
and method supported basis gates.
rr   r   NzThe intersection of configuration basis gates (%s), simulation method basis gates (%s), and noise model basis gates (%s) is empty)r   _method_basis_gatesr   rr   setintersectionr   r   loggerwarningsorted)r   method_gatesconfig_gatesrr   r   noise_gatess         r   r  QasmSimulator._basis_gatesi  s     D777..}== //1**66l+88FK&K dllM4@%11K%22;?KKNN8  k""r   c                     U R                   R                  SS5      nUS;   a  [        / SQ5      $ US:X  a  [        / SQ5      $ US:X  a  [        / SQ5      $ US	:X  a  [        / S
Q5      $ [        R                  $ )1Return method basis gates and custom instructionsr   Nrz   r{   r|   r}   )$r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r0   r2   r5   r6   r7   r8   r9   rJ   rK   rN   rO   rQ   r   )&r   r   r   r   r   r0   r,   r-   r.   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r9   rJ   rT   rN   rO   r   r   r   r   r5   r6   r7   r8   r/   r:   rK   rM   r~   )r    r!   r"   r#   r$   r%   r&   r'   r(   r,   r-   r.   r+   rN   rO   rQ   r   )r,   r.   r    r!   r"   r#   r$   r%   r&   r'   r(   r+   u0r)   r*   r   r   r9   cczrN   rO   )_optionsgetr  r   r   r   r   s     r   r  !QasmSimulator._method_basis_gates  s    ""8T2 
 
 %' 'P ++') )T \! ( ** 2 111r   c                 V   SU R                   ;   a  U R                   S   $ U R                  R                  SS5      nUS;   a  [        / SQ5      $ US;   a  [        / SQ5      $ US:X  a  [        / S	Q5      $ US
:X  a  [        / SQ5      $ US:X  a  [        / SQ5      $ [        R
                  $ )r  rs   r   Nrv   rw   rx   ry   )rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   ra   r  )rR   rS   rT   rU   superoprV   rW   rX   rY   r\   r]   r[   ra   rb   r   )rR   rS   rT   rU   rV   rW   rX   rY   r]   r\   r^   rZ   r[   save_matrix_product_stateset_matrix_product_stater~   )rR   rS   rT   rV   rW   rX   rY   r[   r\   r`   rc   r   )rR   rS   rT   r^   )r   r"  r#  r  r   _DEFAULT_CUSTOM_INSTRr$  s     r   r   "QasmSimulator._custom_instructions  s     !D$?$??../DEE""8T2 
 
  &  
 
  $ ++ & \!  **Z[[222r   c                     US;   a	  Sn[         nO7US;   a  Sn[         S-  nO%US:X  a  SnSnOUS	:X  a  S
nSnOUS:X  a  SnSnOSnSnU R                  SU5        U R                  SU5        g)z.Set non-basis gate options when setting methodr'  z&A C++ statevector simulator with noiser  z)A C++ density matrix simulator with noiser   r   z/A C++ matrix product state simulator with noise?   r~   z.A C++ Clifford stabilizer simulator with noisei'  r   z9A C++ Clifford+T extended stabilizer simulator with noiseNrp   ri   )r   r  )r   r   rp   ri   s       r   r   QasmSimulator._set_method_config|  s      
 
 CK-H 
 
 FK-2H--KKH|#JKH,,UKH KH&&}kB&&z8<r   )r   r   )NNN)N) r   
__module____qualname____firstlineno____doc__r  r   r+  r   r   r   r   r   r   r   r  r   r   classmethodr   r   r   r   r  r	  r  r  r  r   r  __static_attributes____classcell__)r   s   @r   r   r   )   s    FP "<	
>@ #	
2 )&*5X8+4" 2
>  1
 1
f % %N22Y
;$$#LK2Z^3@!= !=r   r   )r3  r   loggingwarningsr   qiskit.providers.optionsr   qiskit.providers.backendr   versionr   aererrorr	   
aerbackendr   backendconfigurationr   backendpropertiesr   backend_utilsr   r   r   r   r   controller_wrappersr   	getLoggerr   r  r   r   r   r   <module>rC     sW       , . !  " 9 ;  8			8	$t=J t=r   