§
    º³Ùg¦0  ã                   ó  — d Z ddlmZmZmZmZmZ ddlmZ ddl	m
Z
 ddlZddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ 	 	 	 	 d#deeef         deee                  dededee         deeeef         ef         fd„Z d„ Z!	 	 	 	 	 d$deee         ej"        f         deee                  dededededeee         ej"        f         fd„Z#	 	 d%dedeee                  dedeeef         fd„Z$d&d „Z%d!„ Z&d"„ Z'dS )'z+Utility functions for working with Results.é    )ÚSequenceÚUnionÚOptionalÚDictÚList)ÚCounter)ÚdeepcopyN)ÚQiskitError)ÚResult)ÚCounts)ÚProbDistribution)ÚQuasiDistribution)Ú_bin_to_hex)ÚresultsFTÚresultÚindicesÚinplaceÚformat_marginalÚmarginalize_memoryÚreturnc                 ó  — t          | t          ¦  «        �rL|st          | ¦  «        } t          | j        ¦  «        D �]#\  }}|                      |¦  «        }t          ||¦  «        }i }	|                     ¦   «         D ]\  }
}||	t          |
¦  «        <   Œ|	|j	        _
        |�Kt          |¦  «        |j        _        t          |j        dd¦  «        }|�t          ||¦  «        |j        _        t          |j	        dd¦  «        �[|�Y|du rt#          |j	        d¦  «         Œä|€Œçt%          |d¬¦  «        }t'          j        |j	        j        |d¬¦  «        |j	        _        �Œ%| S t          | |¦  «        }|r|�t-          | ||¦  «        }|S )a˜  Marginalize counts from an experiment over some indices of interest.

    Args:
        result: result to be marginalized
            (a Result object or a dict(str, int) of counts).
        indices: The bit positions of interest
            to marginalize over. If ``None`` (default), do not marginalize at all.
        inplace: Default: False. Operates on the original Result
            argument if True, leading to loss of original Job Result.
            It has no effect if ``result`` is a dict.
        format_marginal: Default: False. If True, takes the output of
            marginalize and formats it with placeholders between cregs and
            for non-indices.
        marginalize_memory: If True, then also marginalize the memory field (if present).
            If False, remove the memory field from the result.
            If None, leave the memory field as is.

    Returns:
        Result or dict(str, int): A Result object or a dictionary with
            the observed counts, marginalized to only account for frequency
            of observations of bits of interest.

    Raises:
        QiskitError: in case of invalid indices to marginalize over.
    NÚ
creg_sizesÚmemoryFT©Úreverse)Ú
return_hex)Ú
isinstancer   r	   Ú	enumerater   Ú
get_countsÚ_marginalizeÚitemsr   ÚdataÚcountsÚlenÚheaderÚmemory_slotsÚgetattrÚ_adjust_creg_sizesr   ÚdelattrÚsortedÚ
results_rsÚmarginal_memoryr   Ú_format_marginal)r   r   r   r   r   ÚiÚexperiment_resultr#   Ú
new_countsÚnew_counts_hexÚkÚvÚcsizeÚsorted_indicesÚmarg_countss                  úI/granary/edev/quantum/lib/python3.11/site-packages/qiskit/result/utils.pyÚmarginal_countsr8   !   sÃ  € õ@ �&�&Ñ!Ô!ñ "Øð 	&Ý˜fÑ%Ô%ˆFÝ$-¨f¬nÑ$=Ô$=ð 	ñ 	Ñ ˆAÐ Ø×&Ò& qÑ)Ô)ˆFÝ% f¨gÑ6Ô6ˆJØˆNØ"×(Ò(Ñ*Ô*ð 3ð 3‘��1Ø12��{¨1™~œ~Ñ.Ð.Ø,:ÐÔ"Ô)àÐ"Ý8;¸G¹¼Ð!Ô(Ô5ÝÐ 1Ô 8¸,ÈÑMÔM�ØÐ$Ý:LÈUÐT[Ñ:\Ô:\Ð%Ô,Ô7åÐ(Ô-¨x¸Ñ>Ô>ÐJÈwÐObØ%¨Ð.Ð.ÝÐ-Ô2°HÑ=Ô=Ð=Ð=Ø'Ð/Øå%+Ø¨ð&ñ &ô &�Nõ 5?Ô4NØ)Ô.Ô5°~ÐRVð5ñ 5ô 5Ð%Ô*Ô1ùð ˆå" 6¨7Ñ3Ô3ˆØð 	I˜wÐ2Ý*¨6°;ÀÑHÔHˆKØÐó    c                 óp  ‡— d„ | D ¦   «         }t          |¦  «        }d„ | D ¦   «         Šˆfd„t          dt          ‰¦  «        dz   ¦  «        D ¦   «         dd…         }d}|D ]H}t          |t          |¦  «        ¦  «        D ](}|||         k    r|}||         dxx         dz  cc<    nŒ)ŒId„ |D ¦   «         }|S )z,Helper to reduce creg_sizes to match indicesc                 ó"   — g | ]}|d          d g‘ŒS )r   © ©Ú.0Úcregs     r7   ú
<listcomp>z&_adjust_creg_sizes.<locals>.<listcomp>j   s    € Ð:Ð:Ð: t�t˜A”w �lÐ:Ð:Ð:r9   c                 ó   — g | ]\  }}|‘ŒS r<   r<   )r>   Ú_Úxs      r7   r@   z&_adjust_creg_sizes.<locals>.<listcomp>o   s   € Ð*Ð*Ð*‘t�q˜!�Ð*Ð*Ð*r9   c                 óF   •— g | ]}t          ‰d |d…         ¦  «        dz
  ‘ŒS )r   é   )Úsum)r>   rC   Ú	creg_numss     €r7   r@   z&_adjust_creg_sizes.<locals>.<listcomp>p   s1   ø€ ÐSÐSÐS°•3�y  1 Q Ô'Ñ(Ô(¨1Ñ,ÐSÐSÐSr9   r   rE   Nc                 ó*   — g | ]}|d          dk    ¯|‘ŒS )rE   r   r<   r=   s     r7   r@   z&_adjust_creg_sizes.<locals>.<listcomp>|   s!   € ÐFÐFÐF˜t¸¸a¼ÀAº¸�d¸¸¸r9   )r*   Úranger$   )	r   r   Únew_creg_sizesÚindices_sortÚcreg_limitsÚcreg_idxÚindÚidxrG   s	           @r7   r(   r(   f   s  ø€ ð ;Ð:¨zÐ:Ñ:Ô:€NÝ˜'‘?”?€Lð +Ð*˜zÐ*Ñ*Ô*€IØSÐSÐSÐSµe¸A½sÀ9¹~¼~ÐPQÑ?QÑ6RÔ6RÐSÑSÔSÐTUÐTVÐTVÔW€Kð €HØð ð ˆÝ˜¥3 {Ñ#3Ô#3Ñ4Ô4ð 	ð 	ˆCØ�k #Ô&Ò&Ð&Ø�Ø˜sÔ# AÐ&Ð&Ô&¨!Ñ+Ð&Ð&Ñ&Ø�ð 'øð
 GÐF ~ÐFÑFÔF€NØÐr9   éè  r   Ú
int_returnÚ
hex_returnÚavg_dataÚparallel_thresholdc                 ó
  — |r|rt          d¦  «        ‚t          | t          j        ¦  «        r¾|rt          d¦  «        ‚|rt          d¦  «        ‚|€|                      ¦   «         S | j        dk    rt          j        | |¦  «        S | j        dk    r,|rt          j        | |¦  «        S t          j	        | |¦  «        S | j        dk    rt          j
        | |¦  «        S t          d¦  «        ‚t          j        | ||||¬	¦  «        S )
a³  Marginalize shot memory

    This function is multithreaded and will launch a thread pool with threads equal to the number
    of CPUs by default. You can tune the number of threads with the ``RAYON_NUM_THREADS``
    environment variable. For example, setting ``RAYON_NUM_THREADS=4`` would limit the thread pool
    to 4 threads.

    Args:
        memory: The input memory list, this is either a list of hexadecimal strings to be marginalized
            representing measure level 2 memory or a numpy array representing level 0 measurement
            memory (single or avg) or level 1 measurement memory (single or avg).
        indices: The bit positions of interest to marginalize over. If
            ``None`` (default), do not marginalize at all.
        int_return: If set to ``True`` the output will be a list of integers.
            By default the return type is a bit string. This and ``hex_return``
            are mutually exclusive and can not be specified at the same time. This option only has an
            effect with memory level 2.
        hex_return: If set to ``True`` the output will be a list of hexadecimal
            strings. By default the return type is a bit string. This and
            ``int_return`` are mutually exclusive and can not be specified
            at the same time. This option only has an effect with memory level 2.
        avg_data: If a 2 dimensional numpy array is passed in for ``memory`` this can be set to
            ``True`` to indicate it's a avg level 0 data instead of level 1
            single data.
        parallel_threshold: The number of elements in ``memory`` to start running in multiple
            threads. If ``len(memory)`` is >= this value, the function will run in multiple
            threads. By default this is set to 1000.

    Returns:
        marginal_memory: The list of marginalized memory

    Raises:
        ValueError: if both ``int_return`` and ``hex_return`` are set to ``True``
    z=Either int_return or hex_return can be specified but not bothz3int_return option only works with memory list inputz3hex_return option only works with memory list inputNrE   é   é   zInvalid input memory array)Ú
return_intr   rT   )Ú
ValueErrorr   ÚnpÚndarrayÚcopyÚndimr+   Úmarginal_measure_level_1_avgÚmarginal_measure_level_0_avgÚmarginal_measure_level_1Úmarginal_measure_level_0r,   )r   r   rQ   rR   rS   rT   s         r7   r,   r,   €   s0  € ðT ð Z�jð ZÝÐXÑYÔYÐYå�&�"œ*Ñ%Ô%ð 7Øð 	TÝÐRÑSÔSÐSØð 	TÝÐRÑSÔSÐSØˆ?Ø—;’;‘=”=Ð ØŒ;˜!ÒÐÝÔ:¸6À7ÑKÔKÐKØŒ;˜!ÒÐØð LÝ!Ô>¸vÀwÑOÔOÐOå!Ô:¸6À7ÑKÔKÐKØŒ;˜!ÒÐÝÔ6°v¸wÑGÔGÐGÝÐ5Ñ6Ô6Ð6ÝÔ%ØØØØØ-ðñ ô ð r9   r#   c                 óx  — t          t          |                      ¦   «         ¦  «                             dd¦  «        ¦  «        }|�Xt          |¦  «        dk    s/t	          |¦  «                             t          |¦  «        ¦  «        st          d|dz
  › d�¦  «        ‚t          | t          ¦  «        rt          j        | |¦  «        }nÝt          | t          t          f¦  «        rt          j        | |¦  «        }n«t          t!          |                      ¦   «         ¦  «        ¦  «        }t          |t$          t&          j        f¦  «        rt          j        | |¦  «        }nFt          |t*          t&          j        f¦  «        rt          j        | |¦  «        }nt          d¦  «        ‚|r|�t/          | ||¦  «        S |S )	al  Marginalize counts from an experiment over some indices of interest.

    Unlike :func:`~.marginal_counts` this function respects the order of
    the input ``indices``. If the input ``indices`` list is specified then the order
    the bit indices are specified will be the output order of the bitstrings
    in the marginalized output.

    Args:
        counts: result to be marginalized
        indices: The bit positions of interest
            to marginalize over. If ``None`` (default), do not marginalize at all.
        format_marginal: Default: False. If True, takes the output of
            marginalize and formats it with placeholders between cregs and
            for non-indices.
    Returns:
        dict(str, int): A marginalized dictionary
    Raises:
        QiskitError: If any value in ``indices`` is invalid or the ``counts`` dict
        is invalid.
    ú Ú Nr   úindices must be in range [0, rE   ú].z(Values of counts must be an int or float)r$   ÚmaxÚkeysÚreplaceÚsetÚissubsetrI   r
   r   r   r+   r8   r   r   Úmarginal_distributionÚnextÚiterÚvaluesÚintrZ   ÚintegerÚfloatÚfloatingr-   )r#   r   r   Ú
num_clbitsÚresÚfirst_values         r7   rl   rl   Ç   sˆ  € õ2 •S˜Ÿš™œÑ'Ô'×/Ò/°°RÑ8Ô8Ñ9Ô9€JØÐ¥ G¡¤°Ò 1Ð 1½¸W¹¼×9NÒ9NÍuÐU_ÑO`ÔO`Ñ9aÔ9aÐ 1ÝÐL¸*Àq¹.ÐLÐLÐLÑMÔMÐMå�&�&Ñ!Ô!ð JÝÔ(¨°Ñ9Ô9ˆˆÝ	�FÕ-Õ/@ÐAÑ	BÔ	Bð 	JÝÔ.¨v°wÑ?Ô?ˆˆå�4 §¢¡¤Ñ0Ô0Ñ1Ô1ˆÝ�k¥C­¬Ð#4Ñ5Ô5ð 	JÝÔ,¨V°WÑ=Ô=ˆCˆCÝ˜¥e­R¬[Ð%9Ñ:Ô:ð 	JÝÔ2°6¸7ÑCÔCˆCˆCåÐHÑIÔIÐIàð 6˜7Ð.Ý ¨¨WÑ5Ô5Ð5Ø€Jr9   c                 óÚ  ‡— t          t          t          | ¦  «        ¦  «                             dd¦  «        ¦  «        }|�-t	          t          |¦  «        ¦  «        t	          |¦  «        k    r2i }|                      ¦   «         D ]\  Š}t          ‰¦  «        Š||‰<   Œ|S |r<t	          |¦  «                             t	          t          |¦  «        ¦  «        ¦  «        st          d|dz
  › d�¦  «        ‚t          |d¬¦  «        }t          ¦   «         }|                      ¦   «         D ]6\  Š}d                     ˆfd	„|D ¦   «         ¦  «        }||xx         |z  cc<   Œ7t          |¦  «        S )
z4Get the marginal counts for the given set of indicesrc   rd   Nre   rE   rf   Tr   c                 óB   •— g | ]}t          ‰¦  «        | d z
           ‘ŒS )rE   )Ú_remove_space_underscore)r>   rO   Úkeys     €r7   r@   z _marginalize.<locals>.<listcomp>  s-   ø€ ÐVÐVÐVÀsÕ3°CÑ8Ô8¸#¸À¹ÔBÐVÐVÐVr9   )r$   rm   rn   ri   rj   rI   r!   ry   rk   r
   r*   r   ÚjoinÚdict)r#   r   rt   ÚretÚvalr0   Únew_keyrz   s          @r7   r    r    ö   sr  ø€ å•T�$˜v™,œ,Ñ'Ô'×/Ò/°°RÑ8Ô8Ñ9Ô9€Jð 	ˆ�C¥ jÑ 1Ô 1Ñ2Ô2µc¸'±l´lÒBÐBØˆØŸš™œð 	ð 	‰HˆC�Ý*¨3Ñ/Ô/ˆCØˆC�‰HˆHØˆ
àð N�#˜g™,œ,×/Ò/µµE¸*Ñ4EÔ4EÑ0FÔ0FÑGÔGð NÝÐL¸*Àq¹.ÐLÐLÐLÑMÔMÐMõ �W dÐ+Ñ+Ô+€Gõ ‘”€JØ—L’L‘N”Nð #ð #‰ˆˆSØ—'’'ÐVÐVÐVÐVÈgÐVÑVÔVÑWÔWˆØ�7ÐÐÔ˜sÑ"ÐÐÑÐÝ�
ÑÔÐr9   c                 óÚ  ‡— i }t          t          | ¦  «        ¦  «        }t          |                     dd¦  «        ¦  «        }t	          |d¬¦  «        }|D ]”}t          t          ||¦  «        ¦  «        Šd                     ˆfd„t          |¦  «        D ¦   «         ¦  «        ddd…         }t          |¦  «        D ]#\  }	}
|
dk    r|d|	…         dz   ||	d…         z   }Œ$||         ||<   Œ•|S )z[Take the output of marginalize and add placeholders for
    multiple cregs and non-indices.rc   rd   Tr   c                 ó,   •— g | ]}|‰v r‰|         nd ‘ŒS )rB   r<   )r>   ÚindexÚ
index_dicts     €r7   r@   z$_format_marginal.<locals>.<listcomp>  s-   ø€ Ð^Ð^Ð^À5 %¨:Ð"5Ð"5ˆZ˜ÔÐ¸3Ð^Ð^Ð^r9   Néÿÿÿÿ)
rm   rn   r$   ri   r*   r|   Úzipr{   rI   r   )r#   r6   r   Úformat_countsÚcounts_templateÚ
counts_lenÚindices_revÚcountÚ
count_bitsr‚   Úbitrƒ   s              @r7   r-   r-     s  ø€ ð €MÝ�4 ™<œ<Ñ(Ô(€OÝ�_×,Ò,¨S°"Ñ5Ô5Ñ6Ô6€JÝ˜¨$Ð/Ñ/Ô/€Kàð 7ð 7ˆÝ�#˜k¨5Ñ1Ô1Ñ2Ô2ˆ
Ø—W’WØ^Ð^Ð^Ð^ÍEÐR\ÑL]ÔL]Ð^Ñ^Ô^ñ
ô 
à
ˆ$ˆBˆ$ôˆ
õ $ OÑ4Ô4ð 	Kð 	K‰JˆE�3Ø�cŠzˆzØ'¨¨¨Ô/°#Ñ5¸
À5À6À6Ô8JÑJ�
øØ$/°Ô$6ˆ�jÑ!Ð!ØÐr9   c                 óV   — |                       dd¦  «                              dd¦  «        S )z1Removes all spaces and underscores from bitstringrc   rd   rB   )ri   )Ú	bitstrings    r7   ry   ry   %  s(   € à×Ò˜S "Ñ%Ô%×-Ò-¨c°2Ñ6Ô6Ð6r9   )NFFT)NFFFrP   )NF)N)(Ú__doc__Útypingr   r   r   r   r   Úcollectionsr   r\   r	   ÚnumpyrZ   Úqiskit.exceptionsr
   Úqiskit.result.resultr   Úqiskit.result.countsr   Ú'qiskit.result.distributions.probabilityr   Ú!qiskit.result.distributions.quasir   Úqiskit.result.postprocessr   Úqiskit._accelerater   r+   r|   rp   ÚboolÚstrr8   r(   r[   r,   rl   r    r-   ry   r<   r9   r7   ú<module>rœ      s¼  ðð 2Ð 1à 8Ð 8Ð 8Ð 8Ð 8Ð 8Ð 8Ð 8Ð 8Ð 8Ð 8Ð 8Ð 8Ð 8Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð à Ð Ð Ð à )Ð )Ð )Ð )Ð )Ð )Ø 'Ð 'Ð 'Ð 'Ð 'Ð 'Ø 'Ð 'Ð 'Ð 'Ð 'Ð 'Ø DÐ DÐ DÐ DÐ DÐ DØ ?Ð ?Ð ?Ð ?Ð ?Ð ?à 1Ð 1Ð 1Ð 1Ð 1Ð 1à 4Ð 4Ð 4Ð 4Ð 4Ð 4ð
 $(ØØ!Ø)-ðBð BØ�$˜�,ÔðBà�d˜3”iÔ ðBð ðBð ð	Bð
 ! œðBð ˆ4��S�Œ>˜6Ð!Ô"ðBð Bð Bð BðJð ð ð8 $(ØØØØ"ðDð DØ�$�s”)˜RœZÐ'Ô(ðDà�d˜3”iÔ ðDð ðDð ð	Dð
 ðDð ðDð ˆ4�Œ9�b”jÐ Ô!ðDð Dð Dð DðR (,Ø!ð,ð ,Øð,à�h˜s”mÔ$ð,ð ð,ð 
ˆ#ˆsˆ(„^ð	,ð ,ð ,ð ,ð^ð ð ð ð6ð ð ð(7ð 7ð 7ð 7ð 7r9   