
    z	i}}                    n   S 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JrJrJrJr  SSKrSSKJr  SS	KJr  SS
KJrJr  SSKJrJr  SSKJrJrJr  \R@                  " \RB                  " S\RD                  S9RG                  SS5      SS9RI                  SS9r%SS jr&SS jr'SS jr( " S S\5      r)g)z

BitArray
    )annotations)defaultdict)partial)chainrepeat)CallableIterableLiteralMappingSequenceN)NDArray)QiskitError)Countssampled_expectation_value   )ObservablesArrayObservablesArrayLike)ShapedMixin
ShapeInputshape_tuple   dtypeaxisc                    U S-  U S-  S:  -   $ )z@Return the minimum number of bytes needed to store ``num_bits``.   r    num_bitss    `/home/james-whalen/.local/lib/python3.13/site-packages/qiskit/primitives/containers/bit_array.py_min_num_bytesr#   %   s    q=HqL1,--    BitArrayc                v    [         R                  " U R                  SSS9nUSSU R                  * S-
  S24   nU$ )Nr   bigr   bitorder.r   )np
unpackbitsarrayr!   )	bit_arrayarrs     r"   _unpackr/   *   sA    
--	b5
AC
c2+++a/"44
5CJr$   c                    U SS S S24   n U R                   S   nU* S-  nUS:  a.  S/U R                  S-
  -  US4/-   n[        R                  " XSS9n [        R                  " U SSS	9n X4$ )
N.r   r   r   )r   r   r   )constant_valuesr'   r(   )shapendimr*   padpackbits)r.   r!   pad_size	pad_widths       r"   _packr8   0   s{    
c4R4i.Cyy}Hy1}H!|H1-(A?	ffSQ7
++cU
3C=r$   c                  (  ^  \ rS rSrSrS$U 4S jjrS%S jrS&S jrS'S jrS(S jr	S&S jr
S&S	 jrS
 rS r\S)S j5       r\S*S j5       r\S*S j5       r\S+S j5       r\S,S j5       r      S-S jrS.S jr\ S/     S0S jj5       r\ S1     S2S jj5       r\ S1     S3S jj5       rS/S4S jjrS1S5S jjrS1S6S jjrS1S7S jjrS8S jrS(S jrS9S jr S9S jr!      S:S jr"S;S jr#\S<S=S  jj5       r$\S>S! j5       r%\S>S" j5       r&S#r'U =r($ )?r%   ;   a)  Stores an array of bit values.

This object contains a single, contiguous block of data that represents an array of bitstrings.
The last axis is over packed bits, the second last axis is over shots, and the preceding axes
correspond to the shape of the pub that was executed to sample these bits.
c                  > [         TU ]  5         [        U[        R                  5      (       d  [        S[        U5       35      eUR                  [        R                  :w  a  [        SUR                   S35      eUR                  S:  a  [        S5      eUR                  S   [        U5      =n:w  a  [        SU S35      eXl        X l        U R                  R                  S	S
 U l        g	)aU  
Args:
    array: The ``uint8`` data array.
    num_bits: How many bit are in each outcome.

Raises:
    TypeError: If the input is not a NumPy array with type ``numpy.uint8``.
    ValueError: If the input array has fewer than two axes, or the size of the last axis
        is not the smallest number of bytes that can contain ``num_bits``.
z"Input must be a numpy.ndarray not z'Input array must have dtype uint8, not .   z,The input array must have at least two axes.r   z$The input array is expected to have z bytes per shot.N)super__init__
isinstancer*   ndarray	TypeErrortyper   uint8r3   
ValueErrorr2   r#   _array	_num_bits_shape)selfr,   r!   expected	__class__s       r"   r@   BitArray.__init__C   s     	%,,@eNOO;;"(("Eekk]RSTUU::>KLL;;r?>(+CCxDCH:M]^__!kk'',r$   c                   U R                   UR                   :w  a  [        SU  SU S35      eU R                  U R                  4-   nUR                  UR                  4-   n [        R
                  " X#5      U R                  R                  S   4-   n[        R                  " U R                  U5      [        R                  " UR                  U5      4$ ! [         a  n[        U  SU S35      UeSnAff = f)zSValidation and broadcasting of two bit arrays before element-wise binary operation.z'num_bits' must match in z and r<   r   z' are not compatible for this operation.N)	r!   rF   r2   	num_shotsr*   broadcast_shapesrG   broadcast_tor,   )rJ   other
self_shapeother_shaper2   exs         r"   _prepare_broadcastableBitArray._prepare_broadcastable^   s    ==ENN*8eE7!LMMZZ4>>"33
kkU__$66	c''
@DKKDUDUVXDYC[[E tzz512??5;;PU3VVV  	cvU5'1XYZ`bb	cs   "1C 
C6C11C6c                n    [        [        R                  " U R                  U5      6 U R                  5      $ N)r%   r*   bitwise_andrV   r!   rJ   rR   s     r"   __and__BitArray.__and__j   '    (C(CE(JKT]][[r$   c                h   U R                   =o!R                   :w  a  gU R                  UR                  /nUS-  S:  a[  [        R                  " SU* S-  -	  /S/US-  -  -   [        R                  S9nU Vs/ s H  n[        R
                  " XT5      PM     nn[        R                  " USS06$ s  snf )NFr   r      r   	equal_nan)r!   rG   r*   r,   rE   rZ   array_equal)rJ   rR   narrsmaskr.   s         r"   __eq__BitArray.__eq__m   s    A>>1U\\*q51988SqbAX./3%162BB"((SD9=>#BNN3-D>~~t5u55 ?s   7 B/c                j    [        [        R                  " U R                  5      U R                  5      $ rY   )r%   r*   bitwise_notrG   r!   rJ   s    r"   
__invert__BitArray.__invert__w   s     t{{3T]]CCr$   c                n    [        [        R                  " U R                  U5      6 U R                  5      $ rY   )r%   r*   
bitwise_orrV   r!   r[   s     r"   __or__BitArray.__or__z   s'    t'B'B5'IJDMMZZr$   c                n    [        [        R                  " U R                  U5      6 U R                  5      $ rY   )r%   r*   bitwise_xorrV   r!   r[   s     r"   __xor__BitArray.__xor__}   r^   r$   c                b    SU R                    SU R                   SU R                   S3nSU S3$ )Nz<shape=z, num_shots=z, num_bits=>z	BitArray())r2   rO   r!   )rJ   descs     r"   __repr__BitArray.__repr__   s9    L0@DMM?Z[\4&""r$   c                   [        U[        5      (       aN  [        U5      U R                  S-   :X  a  [	        S5      e[        U5      U R                  S-   :  a  [	        S5      e[        U R                  U   U R                  5      $ )Nr   zJBitArray cannot be sliced along the shots axis, use slice_shots() instead.r=   zHBitArray cannot be sliced along the bits axis, use slice_bits() instead.)rA   tuplelenr3   
IndexErrorr%   rG   r!   )rJ   indicess     r"   __getitem__BitArray.__getitem__   su    gu%%7|tyy1}, `  7|tyy1}, ^  G,dmm<<r$   c                    U R                   $ )zThe raw NumPy array of data.)rG   rj   s    r"   r,   BitArray.array   s     {{r$   c                    U R                   $ )zThe number of bits in the register that this array stores data for.

For example, a ``ClassicalRegister(5, "meas")`` would result in ``num_bits=5``.
)rH   rj   s    r"   r!   BitArray.num_bits   s     ~~r$   c                4    U R                   R                  S   $ )zThe number of shots sampled from the register in each configuration.

More precisely, the length of the second last axis of :attr:`~.array`.
r>   )rG   r2   rj   s    r"   rO   BitArray.num_shots   s     {{  $$r$   c                n    [         R                  U S5      U-  n[        U5      SS  R                  U5      $ )Nr'   r=   )int
from_bytesbinzfill)datar!   re   vals       r"   _bytes_to_bitstringBitArray._bytes_to_bitstring   s2    nnT5)D03x|!!(++r$   c                4    [         R                  U S5      U-  $ )Nr'   )r   r   )r   re   s     r"   _bytes_to_intBitArray._bytes_to_int   s    ~~dE*T11r$   c                  Uc3  U R                   R                  SU R                   R                  S   5      OU R                   U   n[        [        5      nU H#  nXB" UR                  5       5      ==   S-  ss'   M%     [        U5      $ )Nr   r   )rG   reshaper2   r   r   tobytesdict)rJ   loc	converterr.   countsshot_rows         r"   _get_countsBitArray._get_counts   sz     ADdkk!!"dkk&7&7&;<QUQ\Q\]`QaS!H9X--/01Q61 F|r$   c                B    [         U R                     R                  SS9$ )zCompute the number of ones appearing in the binary representation of each shot.

Returns:
    A ``numpy.uint64``-array with shape ``(*shape, num_shots)``.
r   r   )_WEIGHT_LOOKUPrG   sumrj   s    r"   bitcountBitArray.bitcount   s!     dkk*..B.77r$   c                   [         R                  " U [        S9n U R                  S:  a  [	        S5      eUS:X  a  U SSSS24   n OUS:w  a  [	        S	U S
35      eU R
                  S   nU* S-  =n(       aF  [         R                  " [        U R
                  SS U5      [        S9n[         R                  " X@/SS9n [        [         R                  " U SS9US9$ )ai  Construct a new bit array from an array of bools.

Args:
    array: The array to convert, with "bitstrings" along the last axis.
    order: One of ``"big"`` or ``"little"``, indicating whether ``array[..., 0]``
        correspond to the most significant bits or the least significant bits of each
        bitstring, respectively.

Returns:
    A new bit array.
r   r=   z"Expecting at least two dimensions.little.Nr   r'   zunknown value for order: '''. Valid values are 'big' and 'little'.r   r   r    )r*   asarrayboolr3   rF   r2   zerosr   concatenater%   r5   )r,   orderr!   	remainderr4   s        r"   from_bool_arrayBitArray.from_bool_array   s     

5-::>ABBH#tt)$Ee^,UG3Z[  ;;r?"a'9' ((;u{{3B'7C4PCNNC<b9EE3hGGr$   c                   [        U [        5      =n(       a  U /n O[        U 5      n U (       d  [        S5      eU  Vs/ s H*  n[        U[        5      (       a  UR                  5       OUPM,     n nS U  5       n[        R                  XA5      nU(       dX  UR                  [        U 5      -  S:  a  [        S5      eUR                  [        U 5      UR                  [        U 5      -  5      nU$ s  snf )a  Construct a new bit array from one or more ``Counts``-like objects.

The ``counts`` can have keys that are (uniformly) integers, hexstrings, or bitstrings.
Their values represent numbers of occurrences of that value.

Args:
    counts: One or more counts-like mappings with the same number of shots.
    num_bits: The desired number of bits per shot. If unset, the biggest value found sets
        this value, with a minimum of one bit.

Returns:
    A new bit array with shape ``()`` for single input counts, or ``(N,)`` for an iterable
    of :math:`N` counts.

Raises:
    ValueError: If different mappings have different numbers of shots.
    ValueError: If no counts dictionaries are supplied.
z%At least one counts mapping expected.c              3  |   #    U  H2  oR                  5         H  u  p#[        X#5        H  oDv   M     M     M4     g 7frY   )itemsr   ).0mappingvscountvs        r"   	<genexpr>'BitArray.from_counts.<locals>.<genexpr>  s.     dgIBRXY[RcQRcs   :<r   z;All of your mappings need to have the same number of shots.)rA   r   listrF   r   int_outcomesr%   from_samplesrO   r}   r   )r   r!   	singletonr   r   r-   s         r"   from_countsBitArray.from_counts   s    . #673393XF&\F !HII _e
^dSZj&&A&AG  "wN^d 	 
 ed))$9	""S[014 !^__!))#f+y7J7JcRXk7YZI
s   1C/c                P  ^^ [        U 5      n  [        U 5      n[	        U/U 5      n[        U[        5      (       a&  UR                  S5      (       a  SOSmU4S jU 5       nUc6  [        U5      n[        [        [        R                  U5      5      nUS:X  a  Sn[        U5      mS	R                  U4S
 jU 5       5      n[        R                   " U[        R"                  [%        U5      S9n['        UR)                  ST5      U5      $ ! [         a  n[        S5      UeSnAff = f)a  Construct a new bit array from an iterable of bitstrings, hexstrings, or integers.

All samples are assumed to be integers if the first one is. Strings are all assumed to be
bitstrings whenever the first string doesn't start with ``"0x"``.

Consider pairing this method with :meth:`~reshape` if your samples represent nested data.

Args:
    samples: A list of bitstrings, a list of integers, or a list of hexstrings.
    num_bits: The desired number of bits per sample. If unset, the biggest sample provided
        is used to determine this value, with a minimum of one bit.

Returns:
    A new bit array.

Raises:
    ValueError: If no strings are given.
z At least one sample is required.N0x   r=   c              3  8   >#    U  H  n[        UTS 9v   M     g7f))baseN)r   )r   r   r   s     r"   r   (BitArray.from_samples.<locals>.<genexpr>.  s     84CC$'4s   r   r   r$   c              3  F   >#    U  H  oR                  TS 5      v   M     g7f)r'   N)to_bytes)r   r   	num_bytess     r"   r   r   9  s     G$3Y66$s   !)r   r   r   )iternextStopIterationrF   r   rA   str
startswithr   maxmapr   
bit_lengthr#   joinr*   
frombufferrE   r}   r%   r   )	samplesr!   first_samplerU   intsr   r,   r   r   s	          @@r"   r   BitArray.from_samples  s    , w-	I=L l^W-lC((%00662AD848D:D3s~~t45H1}"8,	xxG$GGd"((#d)Db)4h??'  	I?@bH	Is   D
 

D%D  D%c                    US;  a  [        SU S35      e[        R                  " U R                  SS9SU R                  * S24   nUS:X  a
  USSSS24   nUR                  [        R                  5      $ )	ao  Convert this :class:`~BitArray` to a boolean array.

Args:
    order: One of ``"big"`` or ``"little"``, respectively indicating whether the most significant
        bit or the least significant bit of each bitstring should be placed at ``[..., 0]``.

Returns:
    A NumPy array of bools.

Raises:
    ValueError: If the order is not one of ``"big"`` or ``"little"``.
)r'   r   zInvalid value for order: 'r   r   r   .Nr   )rF   r*   r+   r,   r!   astypebool_)rJ   r   r.   s      r"   to_bool_arrayBitArray.to_bool_array=  s|     )),UG3Z[  mmDJJR0t}}n6F1FGHc4R4i.Czz"((##r$   c                    SU R                   -  S-
  n[        U R                  U R                   US9nU R                  XS9$ )a'  Return a counts dictionary with bitstring keys.

Args:
    loc: Which entry of this array to return a dictionary for. If ``None``, counts from
        all positions in this array are unioned together.

Returns:
    A dictionary mapping bitstrings to the number of occurrences of that bitstring.
r=   r   r!   re   r   r   )r!   r   r   r   )rJ   r   re   r   s       r"   
get_countsBitArray.get_countsT  sD     $--!#D44t}}SWX	C==r$   c                h    [        U R                  SU R                  -  S-
  S9nU R                  XS9$ )a:  Return a counts dictionary, where bitstrings are stored as ``int``\s.

Args:
    loc: Which entry of this array to return a dictionary for. If ``None``, counts from
        all positions in this array are unioned together.

Returns:
    A dictionary mapping ``ints`` to the number of occurrences of that ``int``.

r=   r   )re   r   )r   r   r!   r   )rJ   r   r   s      r"   get_int_countsBitArray.get_int_countsb  s8     D..Q5E5IJ	C==r$   c                D   SU R                   -  S-
  n[        U R                  U R                   US9nUc3  U R                  R	                  SU R                  R
                  S   5      OU R                  U   nU Vs/ s H  oS" UR                  5       5      PM     sn$ s  snf )zReturn a list of bitstrings.

Args:
    loc: Which entry of this array to return a dictionary for. If ``None``, counts from
        all positions in this array are unioned together.

Returns:
    A list of bitstrings.
r=   r   r   r   )r!   r   r   rG   r   r2   r   )rJ   r   re   r   r.   r   s         r"   get_bitstringsBitArray.get_bitstringsp  s     $--!#D44t}}SWX	@Cdkk!!"dkk&7&7&;<QUQ\Q\]`Qa>ABc(	(**,-cBBBs   ;Bc                   [        U5      n[        R                  " U[        S9=o R                  :X  a#  [        XR
                  R                  SS 5      nOJX R                  U R                  -  :X  a#  [        XR
                  R                  SS 5      nO[        S5      e[        U R
                  R                  U5      U R                  5      $ )a  Return a new reshaped bit array.

The :attr:`~num_shots` axis is either included or excluded from the reshaping procedure
depending on which picture the new shape is compatible with. For example, for a bit array
with shape ``(20, 5)`` and ``64`` shots, a reshape to ``(100,)`` would leave the
number of shots intact, whereas a reshape to ``(200, 32)`` would change the number of
shots to ``32``.

Args:
    *shape: The new desired shape.

Returns:
    A new bit array.

Raises:
    ValueError: If the size corresponding to your new shape is not equal to either
        :attr:`~size`, or the product of :attr:`~size` and :attr:`~num_shots`.
r   r>   Nr   z$Cannot change the size of the array.)r   r*   prodr   sizerG   r2   rO   rF   r%   r   r!   )rJ   r2   r   s      r"   r   BitArray.reshape  s    & E"GGE--D));{{'8'8'=>EYY//{{'8'8'=>ECDD++E2DMMBBr$   c                .  ^  [        U5      S:X  a'  [        [        [        T R                  5      5      5      n[        U5      S:X  a  [        US   [        5      (       a  US   n[        U5      T R                  :w  a  [        S5      eU HB  nUT R                  :  d  T R                  U-   S:  d  M(  [        SU ST R                   S35      e   [        U 4S jU 5       5      S-   n[        T R                  R                  U5      T R                  5      $ )	a  Return a bit array with axes transposed.

Args:
    axes: None, tuple of ints or n ints. See `ndarray.transpose
        <https://numpy.org/doc/stable/reference/generated/
        numpy.ndarray.transpose.html#numpy.ndarray.transpose>`_
        for the details.

Returns:
    BitArray: A bit array with axes permuted.

Raises:
    ValueError: If ``axes`` don't match this bit array.
    ValueError: If ``axes`` includes any indices that are out of bounds.
r   r   zaxes don't match bit arrayaxis - is out of bounds for bit array of dimension r<   c              3  P   >#    U  H  oS :  a  UOTR                   U-   v   M     g7f)r   N)r3   )r   irJ   s     r"   r   %BitArray.transpose.<locals>.<genexpr>  s"     BTq&Qdii!m3Ts   #&)r>   r   )r}   r|   reversedranger3   rA   r   rF   r%   rG   	transposer!   )rJ   axesr   s   `  r"   r   BitArray.transpose  s      t9>%		"234Dt9>ja(;;7Dt9		!9::ADII~Q!2 A3KDII;VWX  
 BTBBXM--d3T]]CCr$   c                    [        U[        5      (       a  U4nU H4  nUS:  d  X R                  :  d  M  [        SU SU R                   S35      e   [	        U 5      nUSU4   n[        U5      u  p4[        X45      $ )a  Return a bit array sliced along the bit axis of some indices of interest.

.. note::

    The convention used by this method is that the index ``0`` corresponds to
    the least-significant bit in the :attr:`~array`, or equivalently
    the right-most bitstring entry as returned by
    :meth:`~get_counts` or :meth:`~get_bitstrings`, etc.

    If this bit array was produced by a sampler, then an index ``i`` corresponds to the
    :class:`~.ClassicalRegister` location ``creg[i]``.

Args:
    indices: The bit positions of interest to slice along.

Returns:
    A bit array sliced along the bit axis.

Raises:
    IndexError: If there are any invalid indices of the bit axis.
r   index z) is out of bounds for the number of bits r<   .)rA   r   r!   r~   r/   r8   r%   )rJ   r   indexr.   r!   s        r"   
slice_bitsBitArray.slice_bits  s    , gs##jGEqyE]]2 UG#LT]]O[\]   dm#w,c
&&r$   c                    [        U[        5      (       a  U4nU H4  nUS:  d  X R                  :  d  M  [        SU SU R                   S35      e   U R                  nUSUSS24   n[        X0R                  5      $ )a  Return a bit array sliced along the shots axis of some indices of interest.

Args:
    indices: The shots positions of interest to slice along.

Returns:
    A bit array sliced along the shots axis.

Raises:
    IndexError: If there are any invalid indices of the shots axis.
r   r   z* is out of bounds for the number of shots r<   .N)rA   r   rO   r~   rG   r%   r!   )rJ   r   r   r.   s       r"   slice_shotsBitArray.slice_shots  s     gs##jGEqyE^^3 UG#MdnnM]]^_  
 kk#w/"]]++r$   c           	        [        U[        5      (       a  U4n[        U[        [        45      (       a  U4n[        R                  " U[        S9n[        U5      n[        U5      U:w  a  [        S5      eU R                  R                  S   n[        R                  " U5      nUS:  a  UR                  5       U R                  :  a3  [        S[        UR                  5       5       SU R                   S35      eUR                  5       U R                  * :  a3  [        S[        UR                  5       5       SU R                   S35      eU R                  SU R                  U R                  -  5      nUS:X  a  U$ XR                  -  n[        R                   " X   U[        R"                  " U5         5      R                  S:  a7  [%        [        R&                  " SU4[        R(                  S9U R                  S	9$ [        R*                  " US
5      u  pgUS-
  U-
  nUR-                  [        R(                  5      n	[        R.                  " U[        R(                  S9n
[        R0                  R3                  X[        R(                  " S5      U	-  5        [        R.                  " U[        R(                  S9n[        R0                  R3                  X[        R                  " U[        R(                  S9U	-  5        [%        UR                  UR                  U
-  U:H  R5                  SS9   U R                  S	9$ )a  Post-select this bit array based on sliced equality with a given bitstring.

.. note::
    If this bit array contains any shape axes, it is first flattened into a long list of shots
    before applying post-selection. This is done because :class:`~BitArray` cannot handle
    ragged numbers of shots across axes.

Args:
    indices: A list of the indices of the cbits on which to postselect.
        If this bit array was produced by a sampler, then an index ``i`` corresponds to the
        :class:`~.ClassicalRegister` location ``creg[i]`` (as in :meth:`~slice_bits`).
        Negative indices are allowed.

    selection: A list of binary values (will be cast to ``bool``) of length matching
        ``indices``, with ``indices[i]`` corresponding to ``selection[i]``. Shots will be
        discarded unless all cbits specified by ``indices`` have the values given by
        ``selection``.

Returns:
    A new bit array with ``shape=(), num_bits=data.num_bits, num_shots<=data.num_shots``.

Raises:
    IndexError: If ``max(indices)`` is greater than or equal to :attr:`num_bits`.
    IndexError: If ``min(indices)`` is less than negative :attr:`num_bits`.
    ValueError: If the lengths of ``selection`` and ``indices`` do not match.
r   z.Lengths of indices and selection do not match.r   r   r   z& out of bounds for the number of bits r<   r   r    r   r   r   )rA   r   r   r*   r   r}   rF   rG   r2   r   r!   r~   minr   r   rO   intersect1dlogical_notr%   emptyrE   divmodr   r   rn   atall)rJ   r   	selectionnum_indicesr   	flattenedbyte_significancebit_significancebyte_idx
bit_offsetbitmaskselection_bytess               r"   
postselectBitArray.postselect  s   > gs##jGi$--"IJJy5	'ly>[(MNNKK%%b)	**W%?{{}- S/00VW[WdWdVeefg  {{}~- S/00VW[WdWdVeefg  LLTYY%?@	 ! 	==  >>',gbnnY6O.PQVVYZZBHHa^288Dt}}]] /1ii.C+M%66%,,RXX6
 ((9BHH5
BHHQK:,EF ((9BHH=
rzz)288'LPZ'Z	
 y//'9oMRRXZR[\]]
 	
r$   c                ~   [         R                  " U5      n[        R                  " [        R                  " U R
                  5      [        S9R                  U R
                  5      n[        R                  " X!5      u  p40 n[        R                  " U[        S9n[        R                  " UR
                  5       HW  nX7   nXG   R                  5        H:  u  pX;  a  U R                  U5      XX'    [        XX   U	5      nXg==   X-  -  ss'   M<     MY     U$ ! [         a  n[        UR                   5      UeSnAff = f)a  Compute the expectation values of the provided observables, broadcasted against
this bit array.

.. note::

    This method returns the real part of the expectation value even if
    the operator has complex coefficients due to the specification of
    :func:`~.sampled_expectation_value`.

Args:
    observables: The observable(s) to take the expectation value of.
        Must have a shape broadcastable with with this bit array and
        the same number of qubits as the number of bits of this bit array.
        The observables must be diagonal (I, Z, 0 or 1) too.

Returns:
    An array of expectation values whose shape is the broadcast shape of ``observables``
    and this bit array.

Raises:
    ValueError: If the provided observables does not have a shape broadcastable with
        this bit array.
    ValueError: If the provided observables does not have the same number of qubits as
        the number of bits of this bit array.
    ValueError: If the provided observables are not diagonal.
r   N)r   coercer*   fromiterndindexr2   objectr   broadcast_arrays
zeros_likefloatr   r   r   r   rF   message)rJ   observablesarr_indices
bc_indicesbc_obsr   r.   r   r   paulicoeffexpvalrU   s                r"   expectation_valuesBitArray.expectation_valuesP  s   6 '--k:kk"**TZZ"8GOOPTPZPZ[00J
mmJe4ZZ
 0 01E#C & 3 3 5$"&//#"6FK96v{EJF 
fn,
 !6 2 
 # 9$RZZ0b89s   1D
D<!D77D<c           
        [        U 5      S:X  a  [        S5      eU S   R                  nU S   R                  nU S   R                  nUS:X  a  [        S5      e[        U 5       H  u  pVUR                  U:w  a  [        SU SU SUR                   S35      eUR                  U:w  a  [        SU S	U SUR                   S
35      eUR                  U:w  d  Mu  [        SU SU SUR                   S35      e   US:  d  X:  a  [        SU SU S35      e[        R                  " U  Vs/ s H  ofR                  PM     snUS9n[        Xr5      $ s  snf )a  Join a sequence of bit arrays along an existing axis.

Args:
    bit_arrays: The bit arrays must have (1) the same number of bits,
        (2) the same number of shots, and
        (3) the same shape, except in the dimension corresponding to axis
        (the first, by default).
    axis: The axis along which the arrays will be joined. Default is 0.

Returns:
    The concatenated bit array.

Raises:
    ValueError: If the sequence of bit arrays is empty.
    ValueError: If any bit arrays has a different number of bits.
    ValueError: If any bit arrays has a different number of shots.
    ValueError: If any bit arrays has a different number of dimensions.
r   z*Need at least one bit array to concatenatez2Zero-dimensional bit arrays cannot be concatenatedOAll bit arrays must have same number of bits, but the bit array at index 0 has ! bits and the bit array at index  has  bits.PAll bit arrays must have same number of shots, but the bit array at index 0 has " shots and the bit array at index  shots.zUAll bit arrays must have same number of dimensions, but the bit array at index 0 has z) dimension(s) and the bit array at index z dimension(s).r   r   r<   r   )
r}   rF   r!   rO   r3   	enumerater*   r   r,   r%   )
bit_arraysr   r!   rO   r3   r   bar   s           r"   r   BitArray.concatenate|  s   ( z?aIJJa=))qM++	!}!!19QRRz*EA{{h& 88@z B223E"++fN 
 ||y( 88A{ C223E",,wP 
 ww$ 88<v >223E"''.R  +& !8t|uTF*WX\W]]^_``~~*=*Bxx*=DI'' >s   +Ec           
        [        U 5      S:X  a  [        S5      eU S   R                  nU S   R                  n[	        U 5       Hc  u  p4UR                  U:w  a  [        SU SU SUR                   S35      eUR                  U:w  d  MF  [        SU SU S	UR                   S
35      e   [
        R                  " U  Vs/ s H  oDR                  PM     snSS9n[        XQ5      $ s  snf )a  Join a sequence of bit arrays along the shots axis.

Args:
    bit_arrays: The bit arrays must have (1) the same number of bits,
        and (2) the same shape.

Returns:
    The stacked bit array.

Raises:
    ValueError: If the sequence of bit arrays is empty.
    ValueError: If any bit arrays has a different number of bits.
    ValueError: If any bit arrays has a different shape.
r   $Need at least one bit array to stackr"  r#  r$  r%  LAll bit arrays must have same shape, but the bit array at index 0 has shape  and the bit array at index  has shape r<   r>   r   )	r}   rF   r!   r2   r)  r*   r   r,   r%   )r*  r!   r2   r   r+  r   s         r"   concatenate_shotsBitArray.concatenate_shots  s      z?aCDDa=))1##z*EA{{h& 88@z B223E"++fN 
 xx5  >>CW E223KzL  + ~~*=*Bxx*=BG'' >s   ?C%c           
        [        U 5      S:X  a  [        S5      eU S   R                  nU S   R                  n[	        U 5       Hc  u  p4UR                  U:w  a  [        SU SU SUR                   S35      eUR                  U:w  d  MF  [        SU SU S	UR                   S
35      e   [
        R                  " U  Vs/ s H  n[        U5      PM     snSS9n[        U5      u  pV[        XV5      $ s  snf )a  Join a sequence of bit arrays along the bits axis.

.. note::
    This method is equivalent to per-shot bitstring concatenation.

Args:
    bit_arrays: Bit arrays that have (1) the same number of shots,
        and (2) the same shape.

Returns:
    The stacked bit array.

Raises:
    ValueError: If the sequence of bit arrays is empty.
    ValueError: If any bit arrays has a different number of shots.
    ValueError: If any bit arrays has a different shape.
r   r.  r&  r'  r$  r(  r/  r0  r1  r<   r   r   )
r}   rF   rO   r2   r)  r*   r   r/   r8   r%   )r*  rO   r2   r   r+  r   r!   s          r"   concatenate_bitsBitArray.concatenate_bits  s   & z?aCDDqM++	1##z*EA||y( 88A{ C223E",,wP 
 xx5  >>CW E223KzL  +  ~~Z@Zrwr{Z@rJt'' As   ?C2)rG   rH   rI   )r,   NDArray[np.uint8]r!   r   )rR   
'BitArray'returnztuple[NDArray[np.uint8], ...])rR   r8  r9  r8  )rR   r8  r9  r   )r9  r8  )r9  r7  )r9  r   )r   bytesr!   r   re   r   r9  r   )r   r:  re   r   r9  r   )r   int | tuple[int, ...] | Noner   zCallable[[bytes], str | int]r9  zdict[str, int] | dict[int, int])r9  zNDArray[np.uint64])r'   )r,   NDArray[np.bool_]r   Literal['big', 'little']r9  r8  rY   )r   z;Mapping[str | int, int] | Iterable[Mapping[str | int, int]]r!   
int | Noner9  r8  )r   zIterable[str] | Iterable[int]r!   r>  r9  r8  )r   r=  r9  r<  )r   r;  r9  zdict[str, int])r   r;  r9  zdict[int, int])r   r;  r9  z	list[str])r2   r   r9  r8  )r   zint | Sequence[int]r9  r8  )r   zSequence[int] | intr  z!Sequence[bool | int] | bool | intr9  r%   )r  r   r9  zNDArray[np.float64])r   )r*  Sequence[BitArray]r   r   r9  r%   )r*  r?  r9  r%   ))__name__
__module____qualname____firstlineno____doc__r@   rV   r\   rf   rk   ro   rs   ry   r   propertyr,   r!   rO   staticmethodr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r   r2  r5  __static_attributes____classcell__)rL   s   @r"   r%   r%   ;   s   -6
W\6D[\#
=     % % , , 2 22?[	(8 DI!H !H)A!H	!H !HF   $(K(( 
( (T GK+@.+@:D+@	+@ +@Z$.>>CC8D<#'J,.Y
$Y
 5Y
 
	Y
v*X 0( 0(d !( !(F (( ((r$   )r!   r   r9  r   )r-   r%   r9  r7  )r.   r7  r9  ztuple[NDArray[np.uint8], int])*rD  
__future__r   collectionsr   	functoolsr   	itertoolsr   r   typingr   r	   r
   r   r   numpyr*   numpy.typingr   qiskit.exceptionsr   qiskit.resultr   r   observables_arrayr   r   r2   r   r   r   r+   arangerE   r   r   r   r#   r/   r8   r%   r   r$   r"   <module>rT     s    # #  # A A    ) ; E 7 7 ryyBHH=EEb!LSTUYY_`Ya.
A({ A(r$   