
    {	ih                        S r SSKrSSKrSSKrSSKJr  SSKJrJrJ	r	  SSK
rSSKJrJrJrJr  SSKJrJr  SSKJr  SSKJr  SS	KJr  S
SKJr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*  \RV                  " \,5      r- " S S\R\                  5      r/ " S S\5      r0 " S S5      r1S r2g)z'
Noise model class for Aer simulators.
    N)Optional)warncatch_warningsfilterwarnings)QuantumCircuitInstructionDelayReset)	PauliGateUnitaryGate)QubitProperties)PassManager)apply_prefix   )_excited_population_truncate_t2_value)basic_device_gate_errors)basic_device_readout_errors)BaseQuantumError)QuantumError)ReadoutError)
NoiseError)RelaxationNoisePass   )BASIS_GATESc                   ,   ^  \ rS rSrSrU 4S jrSrU =r$ )AerJSONEncoder)   z
JSON encoder for NumPy arrays and complex numbers.

This functions as the standard JSON Encoder but adds support
for encoding:
    complex numbers z as lists [z.real, z.imag]
    ndarrays as nested lists.
c                   > [        U[        R                  5      (       a  UR                  5       $ [        U[        5      (       a  UR
                  UR                  /$ [        US5      (       a  UR                  5       $ [        TU ])  U5      $ )Nto_dict)
isinstancenpndarraytolistcomplexrealimaghasattrr    superdefault)selfo	__class__s     V/home/james-whalen/.local/lib/python3.13/site-packages/qiskit_aer/noise/noise_model.pyr*   AerJSONEncoder.default4   sh    a$$88:a!!FFAFF##1i  99;wq!!     )__name__
__module____qualname____firstlineno____doc__r*   __static_attributes____classcell__r-   s   @r.   r   r   )   s    " "r0   r   c                   0   ^  \ rS rSrSrSrU 4S jrSrU =r$ )QuantumErrorLocation>   z?Instruction for referencing a multi-qubit error in a NoiseModelTc                 P   > [         TU ]  SUR                  S/ UR                  S9  g)zvConstruct a new quantum error location instruction.

Args:
    qerror (QuantumError): the quantum error to reference.

qerror_locr   )labelN)r)   __init__
num_qubitsid)r+   qerrorr-   s     r.   r@   QuantumErrorLocation.__init__C   s'     	v'8'8!RvyyQr0   r1   )	r2   r3   r4   r5   r6   
_directiver@   r7   r8   r9   s   @r.   r;   r;   >   s    IJR Rr0   r;   c                      \ rS rSrSr\" / SQ5      r\" / SQ5      r\" SS/5      rS,S jr	\
S	 5       r\
S
 5       r\
S 5       r\       S-S j5       r\       S-SSS\S\S\S\S\\   S\S\\   4S jj5       rS rS rS rS rS rS rS.S jrS.S jrS.S jrS.S  jrS/S! jr \!S" 5       r"S# r#S$ r$S% r%S& r&S' r'S( r(S)\\)   4S* jr*S+r+g)0
NoiseModelL   a  Noise model class for Aer simulators.

This class is used to represent noise model for the
:class:`~qiskit_aer.QasmSimulator`. It can be used to construct
custom noise models for simulator, or to automatically generate a basic
device noise model for an IBMQ backend. See the
:mod:`~qiskit_aer.noise` module documentation for additional
information.

**Example: Basic device noise model**

An approximate :class:`NoiseModel` can be generated automatically from the
properties of real device backends from the IBMQ provider using the
:meth:`~NoiseModel.from_backend` method.

.. code-block:: python

    from qiskit import IBMQ, Aer
    from qiskit_aer.noise import NoiseModel

    provider = IBMQ.load_account()
    backend = provider.get_backend('ibmq_vigo')
    noise_model = NoiseModel.from_backend(backend)
    print(noise_model)


**Example: Custom noise model**

Custom noise models can be used by adding :class:`QuantumError` to circuit
gate, reset or measure instructions, and :class:`ReadoutError` to measure
instructions.

.. code-block:: python

    import qiskit_aer.noise as noise

    # Error probabilities
    prob_1 = 0.001  # 1-qubit gate
    prob_2 = 0.01   # 2-qubit gate

    # Depolarizing quantum errors
    error_1 = noise.depolarizing_error(prob_1, 1)
    error_2 = noise.depolarizing_error(prob_2, 2)

    # Add errors to noise model
    noise_model = noise.NoiseModel()
    noise_model.add_all_qubit_quantum_error(error_1, ['rz', 'sx', 'x'])
    noise_model.add_all_qubit_quantum_error(error_2, ['cx'])
    print(noise_model)

)u1u2u3uprrxryrzrB   xyzhssdgsxsxdgttdg)swapcxcyczcsxcpcucu1cu2cu3rxxryyrzzrzxecrccxcswapNc                     Uc  [        / SQ5      U l        O&[        S U R                  U5       5       5      U l        [        5       U l        [        5       U l        0 U l        0 U l        SU l        0 U l        / U l	        g)a  Initialize an empty noise model.

Args:
    basis_gates (list[str] or None): Specify an initial basis_gates
        for the noise model. If None a default value of ['id', 'rz', 'sx', 'cx']
        is used (Default: None).

Additional Information:
Errors added to the noise model will have their instruction
appended to the noise model basis_gates if the instruction is in
the :class:`~qiskit_aer.QasmSimulator` basis_gates. If
the instruction is not in the
:class:`~qiskit_aer.QasmSimulator` basis_gates it is
assumed to be a label for a standard gate, and that gate should be
added to the `NoiseModel` basis_gates either using the init method,
or the :meth:`add_basis_gates` method.
N)rB   rQ   rX   r]   c              3   *   #    U  H	  u  pUv   M     g 7fNr1   ).0name_s      r.   	<genexpr>&NoiseModel.__init__.<locals>.<genexpr>   s     #d8cWTD8cs   )
set_basis_gates_instruction_names_labels_noise_instructions_noise_qubits_default_quantum_errors_local_quantum_errors_default_readout_error_local_readout_errors_custom_noise_passes)r+   basis_gatess     r.   r@   NoiseModel.__init__   s    $  !$$< =D ##d8V8VWb8c#d dD#&5  !U (*$
 &(" '+# &("$&!r0   c                 ,    [        U R                  5      $ )z4Return basis_gates for compiling to the noise model.)sortedrv   r+   s    r.   r   NoiseModel.basis_gates   s     d''((r0   c                 ,    [        U R                  5      $ )z:Return the set of noisy instructions for this noise model.)r   rx   r   s    r.   noise_instructionsNoiseModel.noise_instructions   s     d..//r0   c                 ,    [        U R                  5      $ )z4Return the set of noisy qubits for this noise model.)r   ry   r   s    r.   noise_qubitsNoiseModel.noise_qubits   s     d(())r0   c	                 @   Ub  [        S[        SS9  OSn[        USS5      n	[        U	[        5      (       d  Sn	Sn
U	S:X  a  U(       d  [        S[
        5        SnUR                  nUR                  n
U(       aK  [        R                  " U
5      n
U H/  u  pnX   U   n[        X5      Ul        U
R                  XU5        M1     UR                  R                  nU(       d  [        S	U S
3[
        5        UR                  nOU	S::  a  [        S[        SS9  UR                  5       nUR!                  5       nUR"                  n[%        UR&                  5       Vs/ s H;  n[)        UR+                  U5      UR-                  U5      UR/                  U5      S9PM=     nn[        USS5      nU(       d  [1        S	U S35      eO[1        U S35      e[3        US9nU(       a#  [5        XS9 H  u  nnUR7                  UXS9  M     [9        5          [;        S[        SS9  [=        UUUUUUUU
S9nSSS5        W H  u  nnnUR?                  UUXS9  M     U(       a  U(       a   U Vs/ s H  n[A        UR.                  US9PM     nn U Vs/ s H  nUR*                  PM     nnU Vs/ s H#  n[E        UR*                  UR,                  5      PM%     nn[G        U Vs/ s H  nUc  [H        RJ                  OUPM     snU Vs/ s H  nUc  [H        RJ                  OUPM     snU[L        UU
S9nURN                  RQ                  U5        U$ U$ s  snf ! , (       d  f       GN+= fs  snf ! [B         a    Sn Nf = fs  snf s  snf s  snf s  snf ! [B         a     U$ f = f)av  Return a noise model derived from a devices backend properties.

This function generates a noise model based on:

* 1 and 2 qubit gate errors consisting of a
  :func:`depolarizing_error` followed
  by a :func:`thermal_relaxation_error`.

* Single qubit :class:`ReadoutError` on all measurements.

The error (noise) parameters are tuned for each individual qubit based on
the :math:`T_1`, :math:`T_2`, frequency and readout error parameters for
each qubit, and the gate error and gate time parameters for each gate
obtained from the device backend properties.

Note that if un-physical parameters are supplied, they are internally truncated to
the theoretical bound values. For example, if :math:`T_2 > 2 T_1`, :math:`T_2`
parameter will be truncated to :math:`2 T_1`.

**Additional Information**

The noise model includes the following errors:

* If ``readout_error=True`` include single qubit readout
  errors on measurements.

* If ``gate_error=True`` and ``thermal_relaxation=True`` include:

    * Single-qubit gate errors consisting of a :func:`depolarizing_error`
      followed by a :func:`thermal_relaxation_error` for the qubit the
      gate acts on.

    * Two-qubit gate errors consisting of a 2-qubit
      :func:`depolarizing_error` followed by single qubit
      :func:`thermal_relaxation_error` on each qubit participating in
      the gate.

* If ``gate_error=True`` is ``True`` and ``thermal_relaxation=False``:

    * An N-qubit :func:`depolarizing_error` on each N-qubit gate.

* If ``gate_error=False`` and ``thermal_relaxation=True`` include
  single-qubit :func:`thermal_relaxation_errors` on each qubits
  participating in a multi-qubit gate.

For best practice in simulating a backend make sure that the
circuit is compiled using the set of basis gates in the noise
module by setting ``basis_gates=noise_model.basis_gates``
and using the device coupling map with
``coupling_map=backend.configuration().coupling_map``

**Specifying custom gate times**

The ``gate_lengths`` kwarg can be used to specify custom gate times
to add gate errors using the :math:`T_1` and :math:`T_2` values from
the backend properties. This should be passed as a list of tuples
``gate_lengths=[(name, value), ...]``
where ``name`` is the gate name string, and ``value`` is the gate time
in nanoseconds.

If a custom gate is specified that already exists in
the backend properties, the ``gate_lengths`` value will override the
gate time value from the backend properties.
If non-default values are used gate_lengths should be a list

Args:
    backend (Backend): backend. For BackendV2, `warnings`
                       options are ignored, and their default values are used.
    gate_error (bool): Include depolarizing gate errors (Default: True).
    readout_error (Bool): Include readout errors in model
                          (Default: True).
    thermal_relaxation (Bool): Include thermal relaxation errors
                               (Default: True).
    temperature (double): qubit temperature in milli-Kelvin (mK) for
                          thermal relaxation errors (Default: 0).
    gate_lengths (list): Custom gate times for thermal relaxation errors.
                          Used to extend or override the gate times in
                          the backend properties (Default: None))
    gate_length_units (str): Time units for gate length values in
                             gate_lengths. Can be 'ns', 'ms', 'us',
                             or 's' (Default: 'ns').
    warnings (bool): DEPRECATED, Display warnings (Default: None).

Returns:
    NoiseModel: An approximate noise model for the device backend.

Raises:
    NoiseError: If the input backend is not valid.
Nz"warnings" argument has been deprecated as of qiskit-aer 0.12.0 and will be removed no earlier than 3 months from that release date. Use the warnings filter in Python standard library instead.r   
stacklevelTversionr   zXWhen a BackendV2 is supplied, `warnings` are ignored, and their default values are used.zQiskit backend ze has no QubitProperties, so the resulting noise model will not include any thermal relaxation errors.r   z from_backend using V1 based backend is deprecated as of Aer 0.15 and will be removed no sooner than 3 months from that release date. Please use backends based on V2.)t1t2	frequencydtz" does not have a BackendPropertiesz is not a Qiskit backendr   )targetwarningsignorezqiskit_aer.noisecategorymodule)
gate_errorthermal_relaxationgate_lengthsgate_length_unitstemperaturer   r   freqr   )t1st2sr   op_typesexcited_state_populationsr   ))r   DeprecationWarninggetattrr!   intUserWarningoperation_namesr   copydeepcopyr   durationupdate_instruction_propertiesqubit_propertiesr   
propertiesconfigurationr   rangerA   r   r   r   r   r   rG   r   add_readout_errorr   r   r   add_quantum_errorr   
ValueErrorr   r   r"   infr	   r~   append)clsbackendr   readout_errorr   r   r   r   r   backend_interface_versionr   r   r   op_namequbitsvaluepropall_qubit_propertiesr   r   qnoise_modelerrorgate_errorsrq   r   r   r   rR   
delay_passs                                 r.   from_backendNoiseModel.from_backend   s   J N # H$+GY$E!3S99()%$)G
 J!11K^^Fv..:*GU!?62D$0$JDM88$O /; $+>>#B#B '%gY /S S
 B&!+: # !++-J#113M'33K
 }778	$ 9A  !}}Q'JMM!,<
H\H\]^H_ 9	 ! $ a0B ?7);]!^__  y(@ABB [9 !<Z!W--eV-O "X 8.@I[\2%#5)"3'!	K  $/D&%))%v)Q $/ "61 2-1 (Q[[kR1 * -+?@+?4tww+?@H\]H\)$''477;H\]0=@AS19!3SA=@AS19!3SA".G!
 0077
C {{$( $-  1,0)1 A]AA   s   AM M#M) 'M$M) N M;"N (*N N N<N N

!(N 
M!$M) )M87M8;N 
NNbackend_propertiesBackendPropertiesr   r   r   r   r   r   r   c	                    S H"  n	[        X5      (       a  M  [        SU	 S35      e   [        5       n
UR                   H  nU
R	                  UR
                  5        M      [        U
5      n
[        UR                  5      n[        U
S9nU(       a%  [        U5       H  u  pUR                  X5        M     [        UUUUUUS9nU H  u  npUR                  UUU5        M     U(       a   [        U5       Vs/ s H  n[        UR!                  U5      US9PM     nn [%        [        U5       Vs/ s H  nUR'                  U5      PM     sn[        U5       Vs/ s H-  n[)        UR'                  U5      UR+                  U5      5      PM/     snU[,        US9nUR.                  R1                  U5        U$ U$ s  snf ! ["         a    Sn Nf = fs  snf s  snf ! ["         a     U$ f = f)	a|	  Return a noise model derived from a backend properties.
We assume the structure of the class `BackendProperties` in `qiskit-ibm-runtime`

This method basically generates a noise model in the same way as
:meth:`~.NoiseModel.from_backend`. One small difference is that the ``dt`` option is
required to be set manually if you want to add thermal relaxation noises to delay
instructions with durations in ``dt`` time unit. Because it is not supplied by a
:class:`BackendProperties` object unlike a :class:`Backend` object.
Note that the resulting noise model is the same as described in
:meth:`~.NoiseModel.from_backend` so please refer to it for the details.

Args:
    backend_properties (BackendProperties): The property of backend.
        We assume the structure of the class `BackendProperties` in `qiskit-ibm-runtime`
    gate_error (Bool): Include depolarizing gate errors (Default: True).
    readout_error (Bool): Include readout errors in model (Default: True).
    thermal_relaxation (Bool): Include thermal relaxation errors (Default: True).
        If no ``t1`` and ``t2`` values are provided (i.e. None) in ``target`` for a qubit,
        an identity ``QuantumError` (i.e. effectively no thermal relaxation error)
        will be added to the qubit even if this flag is set to True.
        If no ``frequency`` is not defined (i.e. None) in ``target`` for a qubit,
        no excitation is considered in the thermal relaxation error on the qubit
        even with non-zero ``temperature``.
    temperature (double): qubit temperature in milli-Kelvin (mK) for
                          thermal relaxation errors (Default: 0).
    gate_lengths (Optional[list]): Custom gate times for thermal relaxation errors.
                          Used to extend or override the gate times in
                          the backend properties (Default: None))
    gate_length_units (str): Time units for gate length values in
                             gate_lengths. Can be 'ns', 'ms', 'us',
                             or 's' (Default: 'ns').
    dt (Optional[float]): Backend sample time (resolution) in seconds (Default: None).
                Required to convert time unit of durations to seconds
                if including thermal relaxation errors on delay instructions.

Returns:
    NoiseModel: An approximate noise model for the device backend.

Raises:
    NoiseError: If the input backend properties are not valid.
)gatesr   r   r   r   z3Backend properties are missing the required field ''r   )r   r   r   r   r   r   N)r   r   r   r   r   )r(   r   ru   r   addgatelistlenr   rG   r   r   r   r   r   r   r   r   r   r   r   r   r	   r~   r   )r   r   r   r   r   r   r   r   r   required_fieldr   r   rA   r   r   r   r   rq   r   r   r   s                        r.   from_backend_properties"NoiseModel.from_backend_properties  s   j KN->> I.IYYZ[  K
 e&,,DOODII& -;'+223
 [9 !<=O!P--e< "Q /!1%/#
 $/D&))%v> $/ 1
 #:.	- / (/99!<+ /	 * -0;@;LM;La+..q1;LM "'z!2!2A ++=+@+@+CEWEZEZ[\E]^!2 ".G	
 0077
C {3-  1,0)1 N   sT   +F> 8#F9F> G 0GG 4G
'G 9F> >GG
G 
G('G(c                     U R                   (       a  gU R                  (       a  gU R                  (       a  gU R                  (       a  gU R                  (       a  gg)z2Return True if the noise model has no noise terms.FT)rz   r|   r{   r}   r~   r   s    r.   is_idealNoiseModel.is_ideal8  sC     ''&&%%%%$$r0   c                 J    SR                  [        U R                  5      5      $ )zNoise model reprz<NoiseModel on {}>)formatr   rx   r   s    r.   __repr__NoiseModel.__repr__G  s    #**40H0H+IJJr0   c                 j   U R                  5       (       a  g/ nU R                   H#  nUR                  SR                  U5      5        M%     U R                  b  SU;  a  UR                  S5        / nU R
                  R                  5        H.  u  p$UR                  5        H  nUR                  X%45        M     M0     U R                   H  nSU4nXc;  d  M  UR                  U5        M!     SnUSR                  U R                  5      -  nU R                  (       a'  USR                  [        U R                  5      5      -  nU R                  (       a'  USR                  [        U R                  5      5      -  nU(       a  USR                  U5      -  nU(       a  US	R                  U5      -  nU$ )
z!Noise model string representationzNoiseModel: Idealz{}measurezNoiseModel:z
  Basis gates: {}z
  Instructions with noise: {}z
  Qubits with noise: {}z
  All-qubits errors: {}z
  Specific qubit errors: {})r   rz   r   r   r|   r{   itemskeysr}   r   rx   r   ry   )r+   default_error_opsinstlocal_error_opsdicr   tmpoutputs           r.   __str__NoiseModel.__str__K  s    ==??& 00D$$T[[%67 1&&2 11!((3 3399;ID((*&&~6 % < 00Ff%C)&&s+ 1
 '..t/?/?@@##7>>tDD\D\?]^^F188d>P>P9QRRF1889JKKF5<<_MMFr0   c                 V   [        U[        5      (       aN  U R                  UR                  :w  d4  U R                  UR                  :w  d  U R                  UR                  :w  a  gU R                  U5      (       d  gU R                  U5      (       d  gU R                  U5      (       d  gg)z#Test if two noise models are equal.FT)r!   rG   r   r   r   _readout_errors_equal_all_qubit_quantum_errors_equal_local_quantum_errors_equal)r+   others     r.   __eq__NoiseModel.__eq__p  s     5*--5#4#44  E$6$66&&%*B*BB))%0033E:://66r0   c                 $    U R                  5         g)zReset the noise model.N)r@   r   s    r.   resetNoiseModel.reset  s    r0   c                     U R                  U5       H7  u  p#U[        S   ;   d  M  US;  d  M  U R                  R                  U5        M9     g)a	  Add additional gates to the noise model basis_gates.

This should be used to add any gates that are identified by a
custom gate label in the noise model.

Args:
    instructions (list[str] or
                  list[Instruction]): the instructions error applies to.
	automatic)r   r   
initializekraussuperoproerrorN)rw   r   rv   r   )r+   instructionsrq   rr   s       r.   add_basis_gatesNoiseModel.add_basis_gates  sH     55lCGD {;//``%%))$/ Dr0   c                    [        U[        5      (       d   [        U5      nUR	                  5       (       a  gU R                  U5       GH  u  pVU R                  X5        X`R                  ;   aJ  U R                  U   R                  U5      nXpR                  U'   U(       a  [        R                  SU5        OXR                  U'   X`R                  ;   aJ  U R                  U R                  U   R                  5       5      nU(       a  [        R                  SUU5        U R                  R                  U5        U R!                  U5        GM     g! [         a  n[        S5      UeSnAff = f)a.  
Add a quantum error to the noise model that applies to all qubits.

Args:
    error (QuantumError): the quantum error object.
    instructions (str or list[str] or
                  Instruction or
                  list[Instruction]): the instructions error applies to.
    warnings (bool): Display warning if appending to an instruction that
                     already has an error (Default: True).

Raises:
    NoiseError: if the input parameters are invalid.

Additional Information:
    If the error object is ideal it will not be added to the model.
#Input is not a valid quantum error.Nz^WARNING: all-qubit error already exists for instruction "%s", composing with additional error.zlWARNING: all-qubit error for instruction "%s" will not apply to qubits: %s as specific error already exists.)r!   r   r   r   idealrw   _check_number_of_qubitsrz   composeloggerwarningr{   	_keys2strr   rx   r   r   )	r+   r   r   r   exrq   r?   	new_errorlocal_qubitss	            r.   add_all_qubit_quantum_error&NoiseModel.add_all_qubit_quantum_error  sI   & %!122P$U+ ;;==  99,GKD((5444 88?GGN	6?,,U3NN; 	 7<,,U3222#~~d.H.H.O.T.T.VWNN? $ $$((/  &5 H  P !FGROPs   E 
E-E((E-c                 "   [        U[        5      (       d   [        U5      n [	        U5      nUR                  5       (       a  gU H  nU R                  R                  U5        M      U R                  U5       GHV  u  pxU R                  X5        [        U[        5      (       d  [        S5      eU R                  X5        XR                  ;   a  U R                  U   n	O0 n	UR                  [        U5      :w  a.  [        SR                  [        U5      UR                  5      5      eX9;   a6  X   R!                  U5      n
XU'   U(       a  ["        R%                  SUU5        OXU'   XR                  U'   XR&                  ;   a  U(       a  ["        R%                  SUU5        U R(                  R                  U5        U R+                  U5        GMY     g! [         a  n[        S5      UeSnAff = f! [
         a  n[        S5      UeSnAff = f)aT  
Add a quantum error to the noise model.

Args:
    error (QuantumError): the quantum error object.
    instructions (str or list[str] or
                  Instruction or
                  list[Instruction]): the instructions error applies to.
    qubits (Sequence[int]): qubits instruction error applies to.
    warnings (bool): Display warning if appending to an instruction that
                     already has an error (Default: True).

Raises:
    NoiseError: if the input parameters are invalid.

Additional Information:
    If the error object is ideal it will not be added to the model.
r   N1Qubits must be convertible to a tuple of integersz$QuantumCircuit invalid instructions.z9Number of qubits ({}) does not match  the error size ({})zeWARNING: quantum error already exists for instruction "%s" on qubits %s , appending additional error.zxWARNING: Specific error for instruction "%s" on qubits %s overrides previously defined all-qubit error for these qubits.)r!   r   r   r   tuple	TypeErrorr   ry   r   rw   r   strr{   rA   r   r   r   r   r   rz   rx   r   )r+   r   r   r   r   r  qubitrq   r?   
qubit_dictr  s              r.   r   NoiseModel.add_quantum_error  s   ( %!122P$U+	Z6]F ;;==E""5)   99,GKD((5eS)) !GHH((5222!77>

 3v;. ++16#f+u?O?O+P  #&.66u=	%.6"NN8  &+6"0:&&u- 444NN<  $$((/  &Y H  P !FGROP  	ZPQWYY	Zs.   G G3 
G0G++G03
H=H		Hc                 &   [        U[        5      (       d   [        U5      nUR                  5       (       a  gUR                  S:w  a  [        S5      eU R
                  b  U(       a  [        R                  S5        Xl        U R                  (       aF  U R                  U R                  R                  5       5      nU(       a  [        R                  SU5        U R                  R                  S5        g! [         a  n[        S5      UeSnAff = f)a  
Add a single-qubit readout error that applies measure on all qubits.

Args:
    error (ReadoutError): the quantum error object.
    warnings (bool): Display warning if appending to an instruction that
                     already has an error (Default: True)

Raises:
    NoiseError: if the input parameters are invalid.

Additional Information:
    If the error object is ideal it will not be added to the model.
#Input is not a valid readout error.Nr   z=All-qubit readout errors must defined as single-qubit errors.zSWARNING: all-qubit readout error already exists, overriding with new readout error.z}WARNING: The all-qubit readout error will not apply to measure of qubits qubits: %s as specific readout errors already exist.r   )r!   r   r   r   number_of_qubitsr|   r   r   r}   r  r   rx   r   )r+   r   r   r  r  s        r.   add_all_qubit_readout_error&NoiseModel.add_all_qubit_readout_error(  s    " %..P$U+
 ;;== !!Q&\]]&&29 ',# %%>>$*D*D*I*I*KLL@ !	 	  $$Y/9  P !FGROPs   C5 5
D?DDc                    [        U[        5      (       d   [        U5      n [        U5      nUR                  5       (       a  gU H  nU R                  R                  U5        M      UR                  [        U5      :w  a.  [        SR                  [        U5      UR                  5      5      eX R                  ;   a  U(       a  [        R                  SU5        XR                  U'   U R                  b  U(       a  [        R                  SU5        U R                  R                  S5        g! [         a  n[        S5      UeSnAff = f! [         a  n[        S5      UeSnAff = f)a  
Add a readout error to the noise model.

Args:
    error (ReadoutError): the quantum error object.
    qubits (list[int] or tuple[int]): qubits instruction error applies to.
    warnings (bool): Display warning if appending to an instruction that
                     already has an error [Default: True]

Raises:
    NoiseError: if the input parameters are invalid.

Additional Information:
    If the error object is ideal it will not be added to the model.
r  Nr  z@Number of qubits ({}) does not match the readout error size ({})zWWARNING: readout error already exists for qubits %s, overriding with new readout error.zsWARNING: Specific readout error on qubits %s overrides previously defined all-qubit readout error for these qubits.r   )r!   r   r   r	  r
  r   ry   r   r  r   r   r}   r   r   r|   rx   )r+   r   r   r   r  r  s         r.   r   NoiseModel.add_readout_errorZ  sT   $ %..P$U+	Z6]F
 ;;== E""5)  !!S[0""(&Ve6L6L"M 
 ///=
 .3""6* &&2@ 	 	  $$Y/Q  P !FGROP  	ZPQWYY	Zs.   D/ E /
E
9EE

E(E##E(c                    / nU R                   R                  5        H,  u  p4UR                  5       nU/US'   UR                  U5        M.     U R                  R                  5        HK  u  p6UR                  5        H2  u  ptUR                  5       nU/US'   U/US'   UR                  U5        M4     MM     U R
                  b+  U R
                  R                  5       nUR                  U5        U R                  R                  5        H,  u  ptUR                  5       nU/US'   UR                  U5        M.     SU0nU(       a-  [        R                  " [        R                  " U[        S95      nU$ )z
Return the noise model as a dictionary.

Args:
    serializable (bool): if `True`, return a dict containing only types
        that can be serializable by the stdlib `json` module.

Returns:
    dict: a dictionary for a noise model.

operationsgate_qubitserrors)r   )rz   r   r    r   r{   r|   r}   jsonloadsdumpsr   )	r+   serializable
error_listrq   r   
error_dictr  r   rets	            r.   r    NoiseModel.to_dict  sQ    
  77==?KDJ(,vJ|$j) @ !% : : @ @ BD!+!1!1!3"]]_
,06
<(-3H
=)!!*-	 "4 !C &&244<<>Jj) "77==?MFJ)/J}%j) @
 $**TZZ@AC
r0   c           	         [        S[        SS9  S n[        5       nU R                  S/ 5      nU GH.  nUS   nUS:X  a  US    Vs/ s H
  oa" U5      PM     nn[	        [        XtS	   5      5      n[        U5      n	UR                  S
S5      =(       d    U	R                  U	l        US   n
UR                  SS5      nUb  U H  nUR                  XUSS9  M     M  UR                  XSS9  M  US:X  aT  US	   nUR                  SS5      n[        U5      nUb  U H  nUR                  XSS9  M     GM  UR                  USS9  GM  [        SR                  U5      5      e   U$ s  snf )z
Load NoiseModel from a dictionary.
Args:
    noise_dict (dict): A serialized noise model.
Returns:
    NoiseModel: the noise model.
Raises:
    NoiseError: if dict cannot be converted to NoiseModel.
zzfrom_dict has been deprecated as of qiskit-aer 0.15.0 and will be removed no earlier than 3 months from that release date.r   r   c                    [        S U  5       5      S-   n[        U5      nU  GH  nUS   S:X  a  UR                  [        5       US   S9  M*  US   S:X  a.  UR                  [	        S[        US   5      SUS	   S
9US   S9  Ma  US   S:X  a"  UR                  [        US	   S   S9US   S9  M  US   S:X  a$  UR                  [        US	   S   5      US   S9  M  [        5          [        S[        SS9  UR                  [        US   [        US   5      S9US   S9  S S S 5        GM     U$ ! , (       d  f       GM  = f)Nc              3   >   #    U  H  n[        US    5      v   M     g7f)r   N)max)rp   r   s     r.   rs   INoiseModel.from_dict.<locals>.inst_dic_list_to_circuit.<locals>.<genexpr>  s     D8CSX//8s   r   rq   r   r   )qargsr   r   params)rq   rA   
num_clbitsr(  unitary)datapaulir   z"qiskit_aer.noise.errors.errorutilsr   )r?   r+  )r%  r   r   r
   r   r   r   r   r   r   r   _standard_gate_unitary)dic_listrA   circr   s       r.   inst_dic_list_to_circuit6NoiseModel.from_dict.<locals>.inst_dic_list_to_circuit  sY   D8DDqHJ!*-Dv;')KKs8}K=[G+KK#!('*3x='9'(#&x=	 "(m    [I-KKXq1A B#h-KX[G+KK	#h-*: ;3x=KQ')&$%7#G
 '&)&k8NsSY{8[ #&h-	 $  *)%  < K *)s   &:D//
D?	r  typerC   r   probabilitiesrB   Nr  r  Fr   r   zInvalid error type: {})r   r   rG   getr	  zipr   rB   _idr   r  r   r   r  r   r   )
noise_dictr0  r   r  r   
error_typedicscircuits	noise_opsrC   instruction_namesall_gate_qubitsr  r3  r   s                  r.   	from_dictNoiseModel.from_dict  s    	T		
!	H !l "-EvJ X%GL^G\]G\t4T:G\]!#ho0F"GH	%i0"YYtT2?fii
$),$7!"'))M4"@".'6#55"{U 6  (7  ;;E < 
 y( %o 6"'))M4"@&}5".'6#55gUZ5[ (7  ;;Ge;T !!9!@!@!LMMK L C ^s   E&c                 r   [        U[        [        45      (       d  U/n/ nU H  n[        U[        5      (       a7  UR                  n[        USUR                  5      nUR                  XE45        MO  [        U[        5      (       a  UR                  X345        Mx  [        SR                  U5      5      e   U$ )z?Return two lists of instruction name strings and label strings.r?   zInvalid instruction type {})
r!   r   r	  r   rq   r   r   r  r   r   )r+   r   names_labelsr   rq   r?   s         r.   rw   $NoiseModel._instruction_names_labels(  s    ,u66(>L D $,,yygtyy9##TM2D#&&##TL1 !>!E!Ed!KLL ! r0   c                 >  ^^ UU4S jnTU R                   ;   a!  TR                  S:w  a  [        U" S5      5      eTU R                  ;   a!  TR                  S:w  a  [        U" S5      5      eTU R                  ;   a"  TR                  S:w  a  [        U" S5      5      egg)a	  
Check if error is corrected number of qubits for standard instruction.

Args:
    error (QuantumError): the quantum error object.
    name (str): qobj instruction name to apply error to.

Raises:
    NoiseError: If instruction and error qubit number do not match.
c                    > SR                  TR                  5      SR                  U 5      -   SR                  T5      -   nU$ )Nz{} qubit QuantumErrorz cannot be applied to {} qubitz instruction "{}".)r   rA   )r  msgr   rq   s     r.   error_message9NoiseModel._check_number_of_qubits.<locals>.error_messageF  sJ    '..u/?/?@299+FG&--d34 
 Jr0   r   r      N)_1qubit_instructionsrA   r   _2qubit_instructions_3qubit_instructions)r+   r   rq   rF  s    `` r.   r   "NoiseModel._check_number_of_qubits:  s    	 4,,,1A1AQ1F]1-..4,,,1A1AQ1F]1-..4,,,1A1AQ1F]1-.. 2G,r0   c                 x    SR                  U Vs/ s H  nSR                  U5      PM     sn5      nUSS $ s  snf )z8Convert dicitonary keys to comma seperated print string. z{}, N)joinr   )r+   r   keyr   s       r.   r  NoiseModel._keys2strU  s8    ggT:Tcv}}S)T:;3Bx ;s   7c                 :   U R                   UR                   :w  a  g[        U R                  R                  5       5      [        UR                  R                  5       5      :w  a  gU R                  R	                  5        H  u  p#X1R                  U   :w  d  M    g   g)z0Check two noise models have equal readout errorsFT)r|   r   r}   r   r   r+   r   rQ  r   s       r.   r    NoiseModel._readout_errors_equalZ  s     &&%*F*FF$,,1134u?Z?Z?_?_?a8bb44::<JC33C88 = r0   c                    [        U R                  R                  5       5      [        UR                  R                  5       5      :w  a  gU R                  R                  5        H  u  p#X1R                  U   :w  d  M    g   gz6Check two noise models have equal local quantum errorsFT)r   rz   r   r   rT  s       r.   r   *NoiseModel._all_qubit_quantum_errors_equalg  sp    $..3356&))..0;
 
 66<<>JC55c:: ? r0   c                    [        U R                  R                  5       5      [        UR                  R                  5       5      :w  a  gU R                  R                  5        H  u  p#UR                  U   n[        UR                  5       5      [        UR                  5       5      :w  a    gUR                  5        H  u  pVXdU   :w  d  M      g   X1R                  U   :w  d  M    g   grW  )r   r{   r   r   )r+   r   rQ  r   inner_dict2	inner_keyinner_values          r.   r   &NoiseModel._local_quantum_errors_equalr  s    $,,1134u?Z?Z?_?_?a8bb44::<JC55c:Kejjl#vk.>.>.@'AA*/++-&	i"88  +8 33C88 = r0   returnc                 r    / nUR                  U R                  5        [        U5      S:  a  [        U5      $ g)z
Return the pass manager that add custom noises defined as noise passes
(stored in the _custom_noise_passes field). Note that the pass manager
does not include passes to add other noises (stored in the different field).
r   N)extendr~   r   r   )r+   passess     r.   _pass_managerNoiseModel._pass_manager  s4     d//0v;?v&&r0   )rv   r~   rz   r|   r{   r}   rx   ry   ro   )TTTr   NnsN)T)F),r2   r3   r4   r5   r6   ru   rI  rJ  rK  r@   propertyr   r   r   classmethodr   boolfloatr   r   r  r   r   r   r   r   r   r   r  r   r  r   r    staticmethodr>  rw   r   r  r   r   r   r   rb  r7   r1   r0   r.   rG   rG   L   s   2j 	
0 	
& w/0/'b ) )
 0 0 * *  V Vp   "#''+!%"l/l l 	l
 !l l tnl l UOl l\K#J00"7'rP'd00d=0~*X ` `D$/6
	
x4 
r0   rG   c                   ^  0 S[         R                  " S[        S9_S[         R                  " SS/SS//[        S9_S[         R                  " SS/S	S//[        S9_S
[         R                  " SS/SS//[        S9_S[         R                  " SS/SS//[        S9[         R                  " S5      -  _S[         R                  " SS/SS	//[        S9_S[         R                  " SS/SS//[        S9_S[         R                  " SS/S[         R
                  " S	[         R                  -  S-  5      //[        S9_S[         R                  " SS/S[         R
                  " S[         R                  -  S-  5      //[        S9_S[         R                  " / SQ/ SQ/ SQ/ SQ/[        S9_S[         R                  " / SQ/ SQ/ SQ/ SQ/[        S9_S[         R                  " / SQ/ SQ/ SQ/ SQ/[        S9_S[         R                  " / SQ/ SQ/ SQ/ SQ/[        S9_S[         R                  " / SQ/ SQ/ SQ/ SQ/ S Q/ S!Q/ S"Q/ S#Q/[        S9_S$[         R                  " / SQ/ SQ/ SQ/ S#Q/ S Q/ SQ/ S"Q/ S!Q/[        S9_S%[         R                  " / SQ/ SQ/ SQ/ S#Q/ S Q/ S!Q/ SQ/ S"Q/[        S9_n[        U 4S& jUR                  5        5       S 5      $ )'N)rB   Ir   )dtype)rR   Xr   r   )rS   Yy             y              ?)rT   Z)rU   H)rV   S)rW   Sdg)rZ   T   )r[   Tdg)r]   CXcx_01)r   r   r   r   )r   r   r   r   )r   r   r   r   )r   r   r   r   )cx_10)r_   CZ)r   r   r   rp  )r\   SWAP)rk   CCXccx_012ccx_102)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   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   r   r   )r   r   r   r   r   r   r   r   )ccx_021ccx_201)ccx_120ccx_210c              3   <   >#    U  H  u  pTU;   d  M  Uv   M     g 7fro   r1   )rp   rQ  r   rq   s      r.   rs   )_standard_gate_unitary.<locals>.<genexpr>  s     Q)A:3TS[)As   	)	r"   eyer%   arraysqrtexppinextr   )rq   unitary_matricess   ` r.   r-  r-    s   =RVVAW-=BHHq!fq!f-W== 	BHHq#hQ0@= 	BHHq!fq"g.g>	=
 	BHHq!fq"g.g>K= 	BHHq!fq"g.g>= 	1a&1c(!37C= 	BHHq!fq"&&beea*@&AB'R= 	1a&1bffS255[1_.E*F!GwW= 	rxx<|DG 
= 	BHH<|DG
=  	bhh<}EW
!=& 	"((<|DG
'=, 	-bhh((((((((	 /
-=F 	((((((((	 !
G=` 	((((((((	 !
a=~ Q)9)?)?)AQSWXXr0   )3r6   r   r  loggingtypingr   r   r   r   r   numpyr"   qiskit.circuitr   r   r	   r
   (qiskit.circuit.library.generalized_gatesr   r   qiskit.providersr   qiskit.transpilerr   qiskit.utilsr   device.modelsr   r   r   r   errors.base_quantum_errorr   errors.quantum_errorr   errors.readout_errorr   
noiseerrorr   ra  r   backends.backend_utilsr   	getLoggerr2   r   JSONEncoderr   r;   rG   r-  r1   r0   r.   <module>r     s        9 9  D D K , ) % B 3 6 7 . . " ' 0			8	$"T%% "*R; R D"AYr0   