
    z	i}F                       S r SSKJr  SSKrSSKrSSKrSSKJrJr  SSK	J
r
JrJrJrJrJrJr  SSKJrJr  SSKrSSKrSSKrSSKJr  SSKJr  SS	KJrJrJrJr  SS
K J!r!  SSK"J#r#  SSK$J%r%  \(       a  SSKJ&r&  \r'\RP                  4r)Sr*\RV                  " \*\RX                  \RZ                  -  5      r.SS\R^                  S4           SS jjr0  S       SS jjr1    SS jr2g)z!User interface of qpy serializer.    )annotationsN)JSONEncoderJSONDecoder)UnionListBinaryIOTypeOptionalCallableTYPE_CHECKING)IterableMapping)QuantumCircuit)QiskitError)formatscommon	binary_io	type_keys)QpyError)user_config)__version__)
annotationa  ^
    v?
    (?:
        (?:(?P<epoch>[0-9]+)!)?                           # epoch
        (?P<release>[0-9]+(?:\.[0-9]+)*)                  # release segment
        (?P<pre>                                          # pre-release
            [-_\.]?
            (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
            [-_\.]?
            (?P<pre_n>[0-9]+)?
        )?
        (?P<post>                                         # post release
            (?:-(?P<post_n1>[0-9]+))
            |
            (?:
                [-_\.]?
                (?P<post_l>post|rev|r)
                [-_\.]?
                (?P<post_n2>[0-9]+)?
            )
        )?
        (?P<dev>                                          # dev release
            [-_\.]?
            (?P<dev_l>dev)
            [-_\.]?
            (?P<dev_n>[0-9]+)?
        )?
    )
    (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
$Fc                  ^^^^ [        U [        5      (       d  U /n U  H9  n[        [        U5      [        5      (       a  M#  [        S[        U5       S35      e   Tc  [        R                  mOY[        R                  T:  d  T[        R                  :  a1  [        ST S[        R                   S[        R                   S35      e[        R                  [        5      nUR                  S5      R                  S	5       Vs/ s H  n[        U5      PM     n	n[         R"                  R%                  T5      n
[&        R(                  " [*        R,                  S
TU	S   U	S   U	S   [/        U 5      U
5      nUR1                  U5        [        R2                  " U[         R4                  R6                  5        [*        R8                  [*        R:                  -   nUUUU4S jnTS:  Ga  UR=                  5       (       a  [        U[>        5      (       d  / nURA                  5       nURC                  [/        U 5      [*        RD                  -  S5        U  H*  nURG                  URA                  5       5        U" X5        M,     URC                  U5        U HK  nUR1                  [&        R(                  " [*        RH                  /[*        RJ                  " U5      Q76 5        MM     URC                  SS5        g/ n[/        U 5      [*        RD                  -  n[L        RN                  " 5        nU  H+  nURG                  URA                  5       5        U" UU5        M-     U HQ  nUR1                  [&        R(                  " [*        RH                  /[*        RJ                  " UU-   U-   5      Q76 5        MS     URC                  S5        [P        RR                  " UU5        SSS5        gU  H  nU" X5        M     gs  snf ! , (       d  f       g= f)a  Write QPY binary data to a file

This function is used to save a circuit to a file for later use or transfer
between machines. The QPY format is backwards compatible and can be
loaded with future versions of Qiskit.

For example:

.. plot::
   :include-source:
   :nofigs:
   :context: reset

    from qiskit.circuit import QuantumCircuit
    from qiskit import qpy

    qc = QuantumCircuit(2, name='Bell', metadata={'test': True})
    qc.h(0)
    qc.cx(0, 1)
    qc.measure_all()

from this you can write the qpy data to a file:

.. code-block:: python

    with open('bell.qpy', 'wb') as fd:
        qpy.dump(qc, fd)

or a gzip compressed file:

.. code-block:: python

    import gzip

    with gzip.open('bell.qpy.gz', 'wb') as fd:
        qpy.dump(qc, fd)

Which will save the qpy serialized circuit to the provided file.

Args:
    programs: QPY supported object(s) to store in the specified file like object.
        QPY supports :class:`.QuantumCircuit`.
    file_obj: The file like object to write the QPY data too
    metadata_serializer: An optional JSONEncoder class that
        will be passed the ``.metadata`` attribute for each program in ``programs`` and will be
        used as the ``cls`` kwarg on the `json.dump()`` call to JSON serialize that dictionary.
    use_symengine: This flag is no longer used by QPY versions supported by this function and
        will have no impact on the generated QPY payload except to set a field in a QPY v13 file
        header which is unused.
    version: The QPY format version to emit. By default this defaults to
        the latest supported format of :attr:`~.qpy.QPY_VERSION`, however for
        compatibility reasons if you need to load the generated QPY payload with an older
        version of Qiskit you can also select an older QPY format version down to the minimum
        supported export version, which only can change during a Qiskit major version release,
        to generate an older QPY format version.  You can access the current QPY version and
        minimum compatible version with :attr:`.qpy.QPY_VERSION` and
        :attr:`.qpy.QPY_COMPATIBILITY_VERSION` respectively.

        .. note::

            If specified with an older version of QPY the limitations and potential bugs stemming
            from the QPY format at that version will persist. This should only be used if
            compatibility with loading the payload with an older version of Qiskit is necessary.

        .. note::

            If serializing a :class:`.QuantumCircuit` that contains
            :class:`.ParameterExpression` objects with ``version`` set low with the intent to
            load the payload using a historical release of Qiskit, it is safest to set the
            ``use_symengine`` flag to ``False``.  Versions of Qiskit prior to 1.2.4 cannot load
            QPY files containing ``symengine``-serialized :class:`.ParameterExpression` objects
            unless the version of ``symengine`` used between the loading and generating
            environments matches.
    annotation_factories: Mapping of namespaces to functions that create new instances of
        :class:`.annotation.QPUSerializer`, for handling the dumping of custom
        :class:`.Annotation` objects.  The subsequent call to :func:`load` will need to use
        similar serializer objects, that understand the custom output format of those
        serializers.


Raises:
    TypeError: When invalid data type is input.
    ValueError: When an unsupported version number is passed in for the ``version`` argument.
'z' is not a supported data type.Nz1Dumping payloads with the specified QPY version (zN) is not supported by this version of Qiskit. Try selecting a version between z and z for `qpy.dump`.release.s   QISKITr         c           	     8   > [         R                  " U UTTTTS9  g )N)metadata_serializeruse_symengineversionannotation_factories)r   write_circuit)
out_streamcircuitr#   r    r!   r"   s     N/home/james-whalen/.local/lib/python3.13/site-packages/qiskit/qpy/interface.py_write_circuitdump.<locals>._write_circuit   s#     3'!5	
       )*
isinstancer   
issubclasstyper   	TypeErrorr   QPY_VERSIONQPY_COMPATIBILITY_VERSION
ValueErrorVERSION_PATTERN_REGEXsearchr   groupsplitintr   SymExprEncodingassignstructpackr   FILE_HEADER_V10_PACKlenwritewrite_type_keyProgramCIRCUITFILE_HEADER_V10_SIZETYPE_KEY_SIZEseekableKNOWN_BAD_SEEKERStellseekCIRCUIT_TABLE_ENTRY_SIZEappendCIRCUIT_TABLE_ENTRY_PACKCIRCUIT_TABLE_ENTRYioBytesIOshutilcopyfileobj)programsfile_objr    r!   r"   r#   programversion_matchxversion_partsencodingheaderheader_bytes_writtenr(   file_offsetstable_startoffsetbuffer_offsetsoffset_table_sizecircuits_buffers     ````              r'   dumpr_   Y   s\   x h)): $w-88aW.MNOO  $$		)	)G	3wASAS7S?y IG//0f6H6H5IIY[
 	
 *00=M%2%8%8%C%I%I#%NO%NSV%NMO((//>H[[$$aaaH	F NN6
(I$5$5$=$=>"77':O:OO
 
 "}z(<M'N'NL"--/KMM#h-'*J*JJAN###HMMO4x1 $ MM+&&KK88;B;V;VW];^ ' MM!Q  N #H0P0P P'G"))/*>*>*@A"?G<  ( -FNN#<<$88 47H H6 Q -  $$Q'""?H=! &  G8-  O Ph s   O4(B1O99
Pc                B	   [         R                  " SU R                  S5      5      S   nU R                  S5        U[        R
                  :  a  [        SU S35      eUS:  a`  [        R                  R                  [         R                  " [        R                  U R                  [        R                  5      5      5      nO_[        R                  R                  [         R                  " [        R                  U R                  [        R                  5      5      5      n[        R                   " 5       nUR#                  S5      nUb,  UR$                  U:  a  ['        S	UR$                   S
U S35      eUR(                  R+                  [        R,                  5      S:w  a  [        S5      e[.        R1                  [2        5      nUR5                  S5      R7                  S5       Vs/ s H  n[9        U5      PM     n	nUR:                  UR<                  UR>                  4n
U	S   U
S   :  d<  U	S   U
S   :X  a  U
S   U	S   :  d$  U	S   U
S   :X  ab  U
S   U	S   :X  aV  U
S   U	S   :  aJ  [@        RB                  " SSRE                  U
 Vs/ s H  n[G        U5      PM     sn5       S[2         S35        UR$                  S:  a  [H        RJ                  RL                  nO[        RN                  " U 5      nU[H        RJ                  RP                  :X  a  ['        S5      eU[H        RJ                  RL                  :w  a  [S        SU S35      eUR$                  S:  a  SnO'URT                  [H        RV                  RX                  :H  nUR$                  S:  a  / n[[        UR\                  5       Ho  nUR_                  [        R`                  " [         R                  " [        Rb                  U R                  [        Rd                  5      5      6 Rf                  5        Mq     / n[[        UR\                  5       HX  nUR$                  S:  a  U R                  WU   5        UR_                  [h        Rj                  " U UR$                  UUUS95        MZ     U$ s  snf s  snf )a  Load a QPY binary file

This function is used to load a serialized QPY Qiskit program file and create
:class:`~qiskit.circuit.QuantumCircuit` objects from its contents.
For example:

.. code-block:: python

    from qiskit import qpy

    with open('bell.qpy', 'rb') as fd:
        circuits = qpy.load(fd)

or with a gzip compressed file:

.. code-block:: python

    import gzip
    from qiskit import qpy

    with gzip.open('bell.qpy.gz', 'rb') as fd:
        circuits = qpy.load(fd)

which will read the contents of the qpy and return a list of
:class:`~qiskit.circuit.QuantumCircuit` objects from the file.

Args:
    file_obj: A file like object that contains the QPY binary
        data for a circuit.
    metadata_deserializer: An optional JSONDecoder class
        that will be used for the ``cls`` kwarg on the internal
        ``json.load`` call used to deserialize the JSON payload used for
        the ``.metadata`` attribute for any programs in the QPY file.
        If this is not specified the circuit metadata will
        be parsed as JSON with the stdlib ``json.load()`` function using
        the default ``JSONDecoder`` class.
    annotation_factories: Mapping of namespaces to functions that create new instances of
        :class:`.annotation.QPUSerializer`, for handling the loading of custom
        :class:`.Annotation` objects.

Returns:
    The list of Qiskit programs contained in the QPY data.
    A list is always returned, even if there is only 1 program in the QPY data.

Raises:
    QiskitError: if ``file_obj`` is not a valid QPY file
    TypeError: When invalid data type is loaded.
    MissingOptionalLibraryError: If the ``symengine`` engine library is
        not installed when loading a QPY version 10, 11, or 12 payload
        that is using symengine symbolic encoding and contains
        :class:`.ParameterExpression` instances.
    QpyError: if known but unsupported data type is loaded.
!6sB   r   r   z#The QPY format version being read, zh, isn't supported by this Qiskit version. Please upgrade your version of Qiskit to load this QPY payload
   min_qpy_versionzQPY version z. is lower than the configured minimum version r   QISKITz"Input file is not a valid QPY filer   r   z;The qiskit version used to generate the provided QPY file, z+, is newer than the current qiskit version zj. This may result in an error if the QPY file uses instructions not present in this current qiskit version   zPayloads of type `ScheduleBlock` cannot be loaded as of Qiskit 2.0. Use an earlier version of Qiskit if you want to load `ScheduleBlock` payloads.z"Invalid payload format data kind 'z'.Fr+   )metadata_deserializerr!   r#   )6r:   unpackreadrG   r   r0   r   r   FILE_HEADER_makeFILE_HEADER_PACKFILE_HEADER_SIZEFILE_HEADER_V10r<   rB   r   
get_configgetqpy_versionr   prefacedecodeENCODEr3   r4   r   r5   r6   r7   major_versionminor_versionpatch_versionwarningswarnjoinstrr   r@   rA   read_type_keySCHEDULE_BLOCKr/   symbolic_encodingr8   	SYMENGINErangenum_programsrI   rK   rJ   rH   r[   r   read_circuit)rQ   rg   r#   r"   dataconfigrd   rS   rT   env_qiskit_versionqiskit_versiontype_keyr!   program_offsets_rP   is                    r'   loadr     s(   x mmFHMM!$45a8GMM!###1' ;b b
 	

 |""((MM((g667
 &&,,MM,,g::;
 ##%Fjj!23O"t'7'7/'I4++, -&'q*
 	

 ||6==)X5>??)00=M*7*=*=i*H*N*Ns*ST*SQ#a&*ST(($*<*<d>P>PQN 	1q 11q!^A%66>!;LOabcOd;d q!^A%66q!%7%::q!$6q$99 	XX~>~!s1v~>?@ A88C} E	
 !$$,,''19$$333]
 	
 9$$,,,<XJbIJJ"..)2K2K2U2UU2t(()A""++]]88 g&F&FG
 & * H4$$%r!MM/!,-""  &;+%9	
	 & OK U" ?s   +RRc                |    [         R                  " SU R                  S5      5      S   nU R                  SS5        U$ )a[  This function identifies the QPY version of the file.

This function will read the header of ``file_obj`` and will
return the QPY format version. It will **not** advance the
cursor of ``file_obj``. If you are using this for a subsequent
read, such as to call :func:`.load`, you can pass ``file_obj``
directly. For example::

    from qiskit import qpy

    qpy_version = qpy.get_qpy_version(qpy_file)
    if qpy_version > 12:
        qpy.load(qpy_file)

Args:
    file_obj: A file like object that contains the QPY binary
        data for a circuit.

Returns:
    The QPY version of the specified file.
ra   rb   r   i)r:   rh   ri   rG   )rQ   r"   s     r'   get_qpy_versionr     s5    2 mmFHMM!$45a8GMM"aNr*   )rP   z5Union[List[QPY_SUPPORTED_TYPES], QPY_SUPPORTED_TYPES]rQ   r   r    zOptional[Type[JSONEncoder]]r!   boolr"   r7   r#   >Optional[Mapping[str, Callable[[], annotation.QPYSerializer]]])NN)rQ   r   rg   zOptional[Type[JSONDecoder]]r#   r   returnzList[QPY_SUPPORTED_TYPES])rQ   r   r   r7   )3__doc__
__future__r   gziprL   rN   jsonr   r   typingr   r   r   r	   r
   r   r   collections.abcr   r   r:   rx   reqiskit.circuitr   qiskit.exceptionsr   
qiskit.qpyr   r   r   r   qiskit.qpy.exceptionsr   qiskitr   qiskit.versionr   r   QPY_SUPPORTED_TYPESGzipFilerE   VERSION_PATTERNcompileVERBOSE
IGNORECASEr3   r0   r_   r   r    r*   r'   <module>r      s2   ( "  	  ) Q Q Q -   	 ) ) < < *  &) %  ]]$ 
 D 

?BJJ4NO  8<%%[_v.Cv.v. 5v. 	v.
 v. Yv.v :>[_dd6d Yd 	dNr*   