
    i                        S r SSKrSSKrSSKJr  SSKJrJrJrJrJ	r	J
r
Jr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JrJ r 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+J,r,J-r-  S	SK.J/r/  S	SK0J1r1  S	SKJ2r2  S	SK3J4r4  S	SK5J6r6  S	SKJ7r7  S	SK8J9r9  \Rt                  " \;5      r<Sr= " S S5      r>g)zQiskit runtime service.    N)datetime)	DictCallableOptionalUnionListAnyTypeSequenceTuple)	BackendV2)QiskitBackendNotFoundError)filter_backends)ibm_backend   )ProxyConfiguration)is_crn)configuration_from_server_data)AccountManagerAccountChannelType
RegionTypePlanType)VersionClient)RuntimeClient)RequestsApiError)IBMInputValueError)IBMRuntimeErrorRuntimeProgramNotFoundRuntimeJobNotFound)ResultDecoder)RuntimeJobV2)validate_job_tags)ClientParameters)RuntimeOptions)
IBMBackend)QasmBackendConfigurationruntimec                      ^  \ rS rSrSrU 4S jr             SRS\\   S\\   S\\   S\\   S	\\   S
\\   S\\	   S\\
   S\\
   S\\\\\\
   \/\4      S\\   S\\\      S\\\      SS4U 4S jjjrS
\S\\   4S jrS
\S\4S jrSSS jr        STS\\   S\\   S
\\   S\\   S\\   S	\\   S\\   S\\
   S\4S jjrS\S
\S\4S jr\S\S\\\\
\4   4   4S j5       r SUS
\\   S\4S jjrS\	\\4   4S jr     SVSSS.S	\\   S \\   S
\\   S!\\
   S"\\S#/\
4      S$\\
   S%\\   S&\S\S#   4S' jjjrS
\\   S\\ \\\   4      4S( jr!S
\SS4S) jr" SUS*\S
\\   S$\\
   S%\\   S\#4
S+ jjr$S\\\\4      4S, jr%\   SWS\\   S	\\   S\\   S\
4S- jj5       r&\              SXS\\   S\\   S
\\   S\\   S\\   S	\\   S\\	   S\\
   S.\\
   S/\\
   S\\
   S\\'   S\\(   S\\\      SS4S0 jj5       r)\    SYS1\\
   S\\   S\\   S	\\   S\	4
S2 jj5       r*   SZS	\S
\\   S$\\
   S%\\   S\+4
S3 jjr,     S[S4\S5\S6\\\-\4      S7\\\.\/   \0\.\/      4      S8\\   S9\\
   S%\\   S\14S: jjr2S;\S\14S< jr3           S\S=\\   S>\S*\\   S?\
S4\S
\\   S@\\\      S8\\   SA\\4   SB\\4   SC\
S\\1   4SD jjr5S;\SS4SE jr6S\\\4   4SF jr7SG\S\14SH jr8SSSI jr9   SWS \\   S
\\   S"\\S#/\
4      S&\S\:RF                  4
SJ jjr;S\0\\\4      4SK jr<S\4SL jr=\>S\4SM j5       r?S\4SN jr@SO\S\
4SP jrASQrBU =rC$ )]QiskitRuntimeService0   z6Class for interacting with the Qiskit Runtime service.c                 |   > UR                  SS 5      nUS:X  a  SSKJn  [        TU ]  U5      $ [        TU ]  U 5      $ )Nchannellocalr   )QiskitRuntimeLocalService)getfake_provider.local_servicer/   super__new__)clsargskwargsr-   r/   	__class__s        c/home/james-whalen/.local/lib/python3.13/site-packages/qiskit_ibm_runtime/qiskit_runtime_service.pyr3   QiskitRuntimeService.__new__3   s=    **Y-gN7?#<==7?3''    Nr-   tokenurlfilenamenameinstanceproxiesverifyprivate_endpointurl_resolverregionplans_preferencetagsreturnc                   > [         TU ]  5         / U l        / U l        U R	                  UUUUUUU(       a  [        S0 UD6OSUS9U l        U	b  XR                  l        [        U R                  R                  U R                  R                  U R                  R                  U R                  R                  U R                  R                  U R                  R                  U R                  R                  U
S9U l        U R                  R                  U l        Xl        0 U l        SU l        [)        U R                  5      U l        / U l        / U l        U=(       d    U R                  R0                  U l        U=(       d    U R                  R4                  U l        U=(       d    U R                  R8                  U l        U R                  R                  (       a  U R                  R                  U R=                  5        Vs/ s H  oS   PM	     sn;  a#  [?        SU R                  R                   S35      eSU l        U R                  R                  [)        U R                  5      0U l         g0 U l         U RC                  U5      nU R.                   Vs/ s H  ofRE                  S	5      PM     nnU R.                   Vs1 s H  ofRE                  S
5      iM     nnU R:                  (       a  SRG                  U R:                  5      OSnU R2                  (       a  U R2                  OSnU R6                  (       a"  SRG                  U R6                  5      nSU S3nOSRG                  U5      nSU S3nSU SU U 3n[H        RK                  SU R6                  (       a  SOSUSRG                  U5      5        U H  u  nnU RM                  U5        M     gs  snf s  snf s  snf )a  QiskitRuntimeService constructor.

Recommended uses:

* Direct instantiation:

    .. code-block:: python

        from qiskit_ibm_runtime import QiskitRuntimeService

        service = QiskitRuntimeService(
            channel="ibm_quantum_platform",
            token="API_KEY",
            instance="CRN"
            )

* Saving default acccount:

    .. code-block:: python

        from qiskit_ibm_runtime import QiskitRuntimeService

        QiskitRuntimeService.save_account(
            token="API_KEY",
            instance="CRN",
            set_as_default = True
            )

        service = QiskitRuntimeService()

The minimum required information for service authentication to a non-local channel is the
``token``. The ``local`` channel doesn't require authentication.
For non-local channels, it is recommended to always provide the relevant ``instance``
to minimize API calls. If an ``instance`` is not defined, the service will fetch all
instances accessible within the account, filtered by ``region``, ``plans_preference``,
and ``tags``. If ``plans_preference`` is not set, free and trial instances will be prioritized
over paid instances.

Also note that only one account per API token can be used. The API token is linked to the
account it was created in. If you want to use multiple accounts, you must create multiple
API tokens.

The service will attempt to load an account from file if (a) no explicit ``token``
was provided during instantiation  or (b) a ``name`` is specified, even if an explicit
``token`` was provided to the service constructor. The account will be selected based on
the following criteria:

- If a ``filename`` is specified, account details will be loaded from ``filename``,
  else they will be loaded from the default configuration file.

- If a ``name`` is specified, the corresponding account details will be loaded from
  the configuration file, including ``channel``, ``token``, ``instance``, ``region``,
  ``plans_preference``, and the advanced configuration parameters: ``url``,
  ``url_resolver``, ``private_endpoint``,  ``verify``, and  ``proxies``.
  **Important Note**: An explicit ``instance`` value provided during instantiation
  will **overwrite** the value of the loaded ``instance``.

- If no ``name`` is specified: if ``channel`` is specified, the service will load the
  default account associated with that channel from the configuration file. Else,
  it will fall back to the overall default account, defined when calling :meth:`.save_account`
  with ``set_as_default=True``.

Args:
    Optional[ChannelType] channel: String that identifies the service platform. This is
        set to ``ibm_quantum_platform`` by default, but can additionally take ``local``
        and ``ibm_cloud`` as values.
        If ``local`` is selected, the local testing mode will be used, and
        primitive queries will run on a local simulator. For more details, check the
        `Qiskit Runtime local testing mode
        <https://quantum.cloud.ibm.com/docs/guides/local-testing-mode>`_  documentation.
        For non-local modes, the channel is used to resolve the default API URL value.
        ``ibm_cloud`` was the identifier for the legacy IBM Cloud platform, and
        its url will be redirected to the new ``ibm_quantum_platform`` url.
    Optional[str] token: IBM Cloud API key. Providing an API key is required for IQP
        authentication. If not provided explicitly, the default saved account will be
        queried for this API key.
    Optional[str] url: The API URL. Defaults to different values depending on the selected
        channel:  https://quantum.cloud.ibm.com  (``ibm_quantum_platform``), or
        https://quantum-computing.cloud.ibm.com (``ibm_cloud``).
    Optional[str] filename: Full path of the file where the account is created.
        Default: _DEFAULT_ACCOUNT_CONFIG_JSON_FILE.
    Optional[str] name: Name of the account to load from file.
    Optional[str] instance: The service instance to use.
        For ``ibm_cloud`` and ``ibm_quantum_platform``, this is the Cloud Resource
        Name (CRN) or the service name. If set, it will define an instance for
        service instantiation, if not set, the service will fetch all instances accessible
        within the account following the specified filtering criteria.
    Optional[dict] proxies: Proxy configuration. Supported optional keys are
        ``urls`` (a dictionary mapping protocol or protocol and host to the URL of the proxy,
        documented at https://requests.readthedocs.io/en/latest/api/#requests.Session.proxies),
        ``username_ntlm``, ``password_ntlm`` (username and password to enable NTLM user
        authentication)
    Optional[bool] verify: Whether to verify the server's TLS certificate.
    Optional[bool] private_endpoint: Connect to private API URL.
    Optional[Callable] url_resolver: Function used to resolve the runtime url.
    Optional[str] region: Set a region preference for automatic instance selection.
        This argument is **ignored** if an ``instance`` is specified.
        Accepted values are ``us-east`` or ``eu-de``.
        An instance with this region will be prioritized if an instance is not passed in.
    Optional[List[str]] plans_preference: A list of account plan names
        ordered by priority for automatic instance selection.
        This argument is **ignored** if an ``instance`` is specified.
        Only instances with the given plan names will be considered.
        For example, if you want to avoid using your premium accounts you can just
        pass in ``"open"`` to only use your open plan instances.
        Accepted values include (but are not limited to): ``open``, ``premium``,
        ``flex``, ``on-prem``, ``pay-as-you-go``.
    Optional[List[str]] tags: Set a list of tags to filter available instances for automatic
        instance selection. This argument is **ignored** if an ``instance`` is specified.

Returns:
    An instance of QiskitRuntimeService or QiskitRuntimeLocalService for local channel.

Raises:
    IBMInputValueError: If an input is invalid.
N)r;   r<   r?   r-   r=   r>   r@   rA   r-   r;   r<   r?   r@   rA   rB   rC   Fcrnz\The given API token is associated with an account that does not have access to the instance za. To use this instance, use an API token generated from the account with this instance available.Tr>   plan, Nonezus-east, eu-dez, plans_preference: )z), and available plans: (z(tags: z
, region: a"  Instance was not set at service instantiation. %sBased on the following filters: %s, the available account instances are: %s. If you need a specific instance set it explicitly either by using a saved account with a saved default instance or passing it in directly to QiskitRuntimeService(). z3Free and trial plan instances will be prioritized.  )'r2   __init___all_instances_saved_instances_discover_accountr   _accountrB   r$   r-   r;   r<   r?   r@   rA   _client_params_channel_url_resolver_backend_configs_default_instancer   _active_api_client_backends_list_backend_instance_groupsrD   _regionrE   _plans_preferencerF   _tags	instancesr   _api_clients_resolve_cloud_instancesr0   joinloggerwarning_get_or_create_cloud_client)selfr-   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   instinstance_backendsinstance_namesinstance_plan_namestags_str
region_strjoined_preferencesplans_preference_strjoined_plan_namesfilters_r7   s                            r8   rQ   QiskitRuntimeService.__init__=   s[   H 	46+-..5<&11$ / 	
 '-=MM*.MM))--%%!!]]++MM))==''!]];;%	
 --)EG!&"/0C0C"D46>@%5!5!5!1!ST]]5S5S/T]]//
==!!}}%%dnnFV-WFVd5kFV-WW($$(MM$:$:#; <44  &*D"!%!7!7tGZGZ9[ \D "D $ = =h GCGC`C`aC`xll62C`Na595R5R#5RV$5R   # 15

tyy,H)-;KJ%%*.))D4J4J*K")=>P=QQR'S$$(II.A$B!)BCTBUUV'W$z
|H\G]^GNN9 -- N		.) -a006 -W .X b#s   OOO"c                     XR                   R                  :w  aW  XR                  ;   a  U R                  U   U l         O3U R                  U5      nU R                  R	                  X05        X l         U R                   R                  5       U l        U R                   Vs/ s H  o3S   PM	     sn$ s  snf ! [         a    [        R                  SU5        / s $ f = f)z.Retrieve all backends from the given instance.r>   zInvalid instance %s)
r[   	_instancerb   _create_new_cloud_api_clientupdatelist_backendsr\   	Exceptionre   rf   )rh   r?   
new_clientbackends       r8    _discover_backends_from_instance5QiskitRuntimeService._discover_backends_from_instance  s    
	22<<<000.2.?.?.ID+!%!B!B8!LJ%%,,h-CD.8+"&"9"9"G"G"ID373F3FG3FFO3FGGG 	NN0(;I	s$   BB5 B0-B5 0B5 5"CCc                 Z   [        U R                  R                  U R                  R                  U R                  R                  UU R                  R
                  U R                  R                  U R                  R                  U R                  S9U l	        [        U R                  5      $ )z*Create a new api_client given an instance.rI   )r$   rU   r-   r;   r<   r@   rA   rB   rX   rV   r   )rh   r?   s     r8   rw   1QiskitRuntimeService._create_new_cloud_api_client+  s|    .MM))--%%!!MM))==''!]];;++	
 T0011r:   c                   ^^^ U R                   (       aI  U R                   V^s/ s H+  m[        U4S jU R                    5       5      (       d  M)  TPM-     snU l        U R                  (       a6  U R                   Vs/ s H  oR                  US   ;   d  M  UPM     snU l        U R                  (       ad  U R                   Vs/ s H  o"R                  5       PM     snmU R                   Vs/ s H  o3S   T;   d  M  UPM     nn[        UU4S jS9U l        O!/ SQm[        U R                  U4S jS9U l        U R                  (       d|  SnU R                   (       a  US	U R                    S
3-  nU R                  (       a  USU R                   S
3-  nU R                  (       a  USU R                   3-  n[        SU S35      egs  snf s  snf s  snf s  snf )z6Filter instances by saved region and plan preferences.c              3   N   >#    U  H  oR                  5       TS    ;   v   M     g7f)rF   N)lower).0tagds     r8   	<genexpr>NQiskitRuntimeService._filter_instances_by_saved_preferences.<locals>.<genexpr>?  s     F:Cyy{ai/:s   "%rJ   rK   c                 ,   > TR                  U S   5      $ )NrK   index)r   planss    r8   <lambda>MQiskitRuntimeService._filter_instances_by_saved_preferences.<locals>.<lambda>O  s    u{{1V9/Er:   key)freetrialpaygopaidsubscriptionc                 ,   > TR                  U S   5      $ )Npricing_typer   )r   ordered_pricing_typess    r8   r   r   V  s    399!N:KLr:   rO   ztags: rL   zregion: zplan: z6No matching instances found for the following filters:.N)r`   r]   allr^   r_   r   sortedr   )rh   r   rK   groupfiltered_groupserror_stringr   r   s    `    @@r8   &_filter_instances_by_saved_preferences;QiskitRuntimeService._filter_instances_by_saved_preferences9  s   :: 66-6AF4::FF 6-D) <<88-8aLLAeH<T8-D) !!.2.D.DE.DdZZ\.DEE $(#@#@#@%&MUZDZ#@   -3%E-D)
 %W!,2--L-D)
 ,,Lzz&B 77||(4<<. ;;%%&)?)?(@ AA$H."  -;--
 Fs)   (G	G	=GGG.G>Gc	           	         Sn	U=(       d    Sn
U(       an  U(       a*  [        XAU/5      (       a  [        R                  SUU5        O([        XAU/5      (       a  [        R                  SU5        [        R                  " XVS9n	OU(       a  U(       a  US;  a  [        S5      eU(       a/  [        R                  " UUUUUU
S9n	[        R                  S	5        O{U(       a  [        R                  S
U5        [        R                  " XVUS9n	OHU(       a/  [        R                  " SUUUUU
S9n	[        R                  S	5        OU(       a  [        S5      eU	c  [        R                  " US9n	U(       a  X9l        U(       a  Xyl	        Ub  Xl
        U	R                  S;   aI  U	R                  (       a8  [        U	R                  5      (       d  U R                  XR                  S9U	l        U	R                  5         U	$ )zADiscover account for ibm_cloud and ibm_quantum_platform channels.NTz]Loading account from file %s with name %s. Any input 'channel', 'token' or 'url' are ignored.zPLoading account with name %s. Any input 'channel', 'token' or 'url' are ignored.)r=   r>   	ibm_cloudibm_quantum_platformz;'channel' can only be 'ibm_cloud', or 'ibm_quantum_platform)r-   r;   r<   r?   r@   rA   zGLoading account with the given token. A saved account will not be used.z3Loading default %s account. Input 'url' is ignored.r=   r>   r-   r   zT'url' is not valid as a standalone parameter. Try also passing in 'token' or 'name'.)r=   )accountr?   )anyre   rf   r   r0   
ValueErrorr   create_accountr?   r@   rA   r-   r   _get_crn_from_instance_namevalidate)rh   r;   r<   r?   r-   r=   r>   r@   rA   r   verify_s              r8   rT   &QiskitRuntimeService._discover_accountf  s    .D,--NNC 	 ,--NNC
 %(((FG7*OO !^__!00#%#" ] NN#XZab(,,hSZ[,,.!G NNY f 
 ?$(((;G'%O#N OODD  7++,,#??*:*:  @  G
 	r:   r   c                 f   U R                   (       d  UR                  5       U l         U R                    Vs/ s H  o3S   U:X  d  M  UPM     nnU(       aF  [        U5      S:  a/  [        R	                  S5        U Vs/ s H  oUS   PM	     snU l        US   S   $ [        SU S35      es  snf s  snf )z+Get the crn from the instance service name.r>   r   z7Multiple instances found. Using all matching instances.rJ   r   zThe instance specified (z) is not a valid instance name.)rR   list_instanceslenre   rf   rS   r   )rh   r   r?   itemmatching_instancesri   s         r8   r   0QiskitRuntimeService._get_crn_from_instance_name  s     """)"8"8":D/3/B/B_/Bt6lV^F^d/B_%&*XYAS(TASeAS(T%%a(//$*8*4WW  `
 )Us   B)B)<B.paramsc                 l    [        SSU R                  0U R                  5       D6nUR                  5       $ )zCheck the version of the remote server in a set of client parameters for all channels.

Args:
    params: Parameters used for server connection.

Returns:
    A dictionary with version information.
r<   rP   )r   r<   connection_parametersversion)r   version_finders     r8   _check_api_version'QiskitRuntimeService._check_api_version  s2     'X6::X9U9U9WX%%''r:   c                 ~    Uc  U R                   $ U R                  R                  US5      nUc  [        SU 35      eU$ )aX  Return the saved api client for a given instance for all channels.
If no instance is provided, return the current active api client.

Args:
    instance: IBM Cloud account CRN

Returns:
    An instance of ``RuntimeClient`` that matches the specified instance.

Raises:
    IBMInputValueError: If no saved api client matches the given instance.
Nz(No API client found for given instance: )r[   rb   r0   r   rh   r?   clients      r8   _get_api_client$QiskitRuntimeService._get_api_client  sM      ***&&**8T:F~(+ST\S])^__Mr:   c                     U R                   $ )zReturn dictionary of saved api clients identified by their corresponding instance
for all channels.

Returns:
    An dictionary of {instance: RuntimeClient}
)rb   rh   s    r8   _get_api_clients%QiskitRuntimeService._get_api_clients  s        r:   F)use_fractional_gatescalibration_idmin_num_qubitsdynamic_circuitsrr   zibm_backend.IBMBackendr   r   r6   c          	      
  ^^ / n	[        5       n
U R                  U5      nU H  u  pU(       a  X;  a  M  U/nO:U R                   H*  nXS   :X  d  M  [        R	                  SUS   US   5        M,     U H  nX;   a  M
  U(       a:  U R                   H*  nXS   :X  d  M  [        R	                  SUS   US   5        M,     U
R                  U5        U R                  U5        U R                  UUUUS9=n(       d  M  U	R                  U5        M     M     U(       a  XS'   T(       a  [        [        U4S jU	5      5      n	Tb  [        [        U4S	 jU	5      5      n	U	 H  nUUR                  l        M     [        U	4S
U0UD6$ )a  Return all backends accessible via this account, subject to optional filtering.

Args:
    name: Backend name to filter by.
    min_num_qubits: Minimum number of qubits the backend has to have.
    instance: IBM Cloud account CRN
    dynamic_circuits: Filter by whether the backend supports dynamic circuits.
    filters: More complex filters, such as lambda functions.
        For example::

            QiskitRuntimeService.backends(
                filters=lambda b: b.max_shots > 50000
            )
            QiskitRuntimeService.backends(
                filters=lambda x: ("rz" in x.basis_gates )
            )
    use_fractional_gates: Set True to allow for the backends to include
        fractional gates. Note that our backends now
        support dynamic circuits and fractional gates simultaneously.
        You no longer have to disable this flag when
        using dynamic circuits features (e.g. ``if_else``) in your
        algorithm. Control flow instructions are not removed from the
        backend when this flag is set to True.
        If ``None``, then both fractional gates and control flow operations are
        included in the backends.
    calibration_id: The calibration id used for instantiating the backend. This should only
        be used when selecting a single backend as the calibration id is defined per backend.

    **kwargs: Simple filters that require a specific value for an attribute in
        backend configuration or status.
        Examples::

            # Get the operational real backends
            QiskitRuntimeService.backends(simulator=False, operational=True)

            # Get the backends with at least 127 qubits
            QiskitRuntimeService.backends(min_num_qubits=127)

            # Get the backends that support OpenPulse
            QiskitRuntimeService.backends(open_pulse=True)

        For the full list of backend attributes, see the `IBMBackend class documentation
        <https://quantum.cloud.ibm.com/docs/api/qiskit-ibm-runtime>`_

Returns:
    The list of available backends that match the filter.

Raises:
    IBMInputValueError: If an input is invalid.
    QiskitBackendNotFoundError: If the backend is not in any instance.
rJ   zLoading instance: %s, plan: %sr>   rK   zUsing instance: %s, plan: %sr?   r   r   backend_namec                 >   > U R                  5       R                  T:  $ N)configurationn_qubitsbr   s    r8   r   /QiskitRuntimeService.backends.<locals>.<lambda>j  s    !2!;!;~!Mr:   c                 F   > S[        U R                  5       S/ 5      ;   T:H  $ )Nr   supported_features)getattrr   )r   r   s    r8   r   r   o  s%    *gaoo6GI]_a.bb'(r:   rr   )setrc   r]   re   rf   addrg   _create_backend_objappendlistfilteroptionsr   r   )rh   r>   r   r?   r   rr   r   r   r6   backendsunique_backendsrj   ri   backends_availableinst_detailsr   r|   s     ` `            r8   r   QiskitRuntimeService.backends  s   ~ &(% 99(C(9$D1&*V"$($A$ALE22<(0(0 %B !32(,(E(E#66"NN > ,V 4 ,V 4 )F  ##L1006"66 !)=#1	 7  7  OOG,' !3 ):B %)>"MxXH '( H  G3GGOO0  xCCFCCr:   c           
         U(       a  [        U5      (       d1  U R                  U R                  U5      nU(       d  [        U S35      eU R                  (       a-  U R                   Vs/ s H  nX R                  U5      4PM     sn$ XR                  U5      4/$ U R                  (       ag  U R                  R                  nU R                  (       a-  U R                   Vs/ s H  nX R                  U5      4PM     sn$ X0R                  U5      4/$ U R                  (       d  U R                  R                  5       U l        U R                  (       dZ  U R                   Vs/ s H-  nUS   US   US   U R                  US   5      US   US   S.PM/     snU l
        U R                  5         U R                   Vs/ s H  o"S   US   4PM     sn$ s  snf s  snf s  snf s  snf )	Nz is not a valid instance.r>   rJ   rK   rF   r   )r>   rJ   rK   r   rF   r   r   )r   r   rU   r   rS   r}   rZ   r?   rR   r   r]   r   )rh   r?   ri   default_crns       r8   rc   -QiskitRuntimeService._resolve_cloud_instances|  s   (##;;DMM8T,z9R-STT $$ !% 5 5 5 @@FG 5  DDXNOPP!! --00K$$ !% 5 5 5 @@FG 5  !"G"G"TUVV"""&--">">"@D,, !//
- 0D !L; L $ E Ed5k R L$($8 0
-D) 779<@<Y<YZ<YDed:./<YZZ?
- [s   (G G!4G;G c                     XR                   R                  :w  aD  U R                  R                  U5      nUc  U R	                  U5      nX R                  U'   X l         gg)zJFind relevant cloud client for a given instance and set active api client.N)r[   rv   rb   r0   rw   r   s      r8   rg   0QiskitRuntimeService._get_or_create_cloud_client  sX    ..888&&**84F~::8D.4!!(+&,# 9r:   r   c                     XR                   ;   au  U R                   U   nU(       a  SUR                  ;  d  U(       d  SUR                  ;   d  U(       a0  [        U R                  R	                  XS9UUS9nXPR                   U'   O1[        U R                  R	                  XS9UUS9nXPR                   U'    U(       a"  [        R                  " UUU U R                  US9$ g! [
         a   n[        R                  SX5         SnAgSnAff = f)a  Given a backend configuration return the backend object.

Args:
    backend_name: Name of backend to instantiate.
    instance: the current CRN.
    use_fractional_gates: Set True to allow for the backends to include
        fractional gates, False to include control flow operations, and
        None to include both fractional gates and control flow
        operations.  See :meth:`~.QiskitRuntimeService.backends` for
        further details.

Returns:
    A backend object.
rzz)r   r   )
raw_configr?   r   z*Unable to create configuration for %s. %s N)r?   r   service
api_clientr   )
rY   basis_gatesr   r[   backend_configurationrz   re   rf   r   r&   )rh   r   r?   r   r   configexs          r8   r   (QiskitRuntimeService._create_backend_obj  s    *!	444..|< *e6;M;M.M0Uf>P>P5P%;#'#:#:#P#P)5 $Q $ "*-AF ;A)),7 8#66LL%1  M   &)= 7=%%l3
 ))!$22-    	NNGZ	s   BC! 0C! !
D+DDc                 6    U R                   R                  5       $ )zReturn the IBM Quantum account currently in use for the session.

Returns:
    A dictionary with information about the account currently in the session.
)rU   to_saved_formatr   s    r8   active_account#QiskitRuntimeService.active_account  s     }},,..r:   c                 ,    [         R                  " XUS9$ )aP  Delete a saved account from disk.

Args:
    filename: Name of file from which to delete the account.
    name: Name of the saved account to delete.
    channel: Channel type of the default account to delete.
        Ignored if account name is provided.

Returns:
    True if the account was deleted.
    False if no account was found.
r   )r   deleter   s      r8   delete_account#QiskitRuntimeService.delete_account  s    $ $$h7SSr:   	overwriteset_as_defaultc                 j    [         R                  " U UUUUUU(       a  [        S0 UD6OSUUU	U
UUUS9  g)a  Save the account to disk for future use.

Args:
    token: IBM Cloud API key.
    url: The API URL. Defaults to https://cloud.ibm.com.
    instance: This is an optional parameter to specify the CRN  or service name.
        If set, it will define a default instance for service instantiation,
        if not set, the service will fetch all instances accessible within the account.
    channel: Channel type. ``ibm_cloud`` or ``ibm_quantum_platform``.
    filename: Full path of the file where the account is saved.
    name: Name of the account to save.
    proxies: Proxy configuration. Supported optional keys are
        ``urls`` (a dictionary mapping protocol or protocol and host to the URL of the proxy,
        documented at https://requests.readthedocs.io/en/latest/api/#requests.Session.proxies),
        ``username_ntlm``, ``password_ntlm`` (username and password to enable NTLM user
        authentication)
    verify: Verify the server's TLS certificate.
    overwrite: ``True`` if the existing account is to be overwritten.
    set_as_default: If ``True``, the account is saved in filename,
        as the default account.
    private_endpoint: Connect to private API URL.
    region: Set a region preference. `us-east` or `eu-de`. An instance with this region
        will be prioritized if an instance is not passed in.
    plans_preference: A list of account plan names
        (``open``, ``premium``, etc.), ordered by preference. An instance with the first
        value in the list will be prioritized and only instances
        with the given plan names will be considered. For example, if you want to avoid
        using your premium accounts you can just pass in ``"open"`` to only use your open plan
        instances. ``plans_preference`` is ignored if an ``instance`` is specified.
    tags: Set a list of tags to filter available instances. Instances with these tags
        will be prioritized if an instance is not passed in.

Nr;   r<   r?   r-   r=   r>   r@   rA   r   r   rB   rD   rE   rF   rP   )r   saver   r   s                 r8   save_account!QiskitRuntimeService.save_account  sJ    f 	5<&11$)--	
r:   defaultc                 p    [        [        S [        R                  " XX#S9R	                  5       5      5      $ )a  List the accounts saved on disk.

Args:
    default: If set to True, only default accounts are returned.
    channel: Channel type.``ibm_cloud`` or ``ibm_quantum_platform``.
    filename: Name of file whose accounts are returned.
    name: If set, only accounts with the given name are returned.

Returns:
    A dictionary with information about the accounts saved on disk.

Raises:
    ValueError: If an invalid account is found on disk.
c                 >    U S   [         R                  " U S   5      4$ )Nr   r   )r   r   )kvs    r8   r   5QiskitRuntimeService.saved_accounts.<locals>.<lambda>h  s    BqE7#:#:2a5#ABr:   r   r-   r=   r>   )dictmapr   r   itemsr  s       r8   saved_accounts#QiskitRuntimeService.saved_accountsQ  s6    * B###x%'	
 	
r:   c                     U R                  UUUUS9nU(       d"  SnU R                  S;   a  Sn[        SU-   5      eUS   $ )a1  Return a single backend matching the specified filtering.

Args:
    name: Name of the backend.
    instance: Specify the IBM Cloud account CRN.
    use_fractional_gates: Set True to allow for the backends to include
        fractional gates. Currently this feature cannot be used
        simultaneously with dynamic circuits, PEC, PEA, or gate
        twirling.  When this flag is set, control flow instructions are
        automatically removed from the backend.
        When you use a dynamic circuits feature (e.g. ``if_else``) in your
        algorithm, you must disable this flag to create executable ISA circuits.
        This flag might be modified or removed when our backend
        supports dynamic circuits and fractional gates simultaneously.
        If ``None``, then both fractional gates and control flow operations are
        included in the backends.
    calibration_id: The calibration id used for instantiating the backend.

Returns:
    Backend: A backend matching the filtering.

Raises:
    QiskitBackendNotFoundError: if no backend could be found.
r   rO   r   zz Learn more about available backends here https://quantum.cloud.ibm.com/docs/en/guides/qpu-information#view-your-resources No backend matches the criteria.r   )r   rW   r   )rh   r>   r?   r   r   r   cloud_msg_urls          r8   r|   QiskitRuntimeService.backendo  sc    > ==!5)	 ! 
 M}} EEg  --OR_-_``{r:   
program_idinputsr   result_decoder
session_idstart_sessionc                 X   UnUc  [        5       nO [        U[        5      (       a  [        S0 UD6nUR                  U R                  S9  UR
                  n	[        U	[        5      (       a  U R                  UR                  5       S9n	U	R                  5       n
U
R                  SL aA  U
R                  S:w  a1  [        R                  " SU	R                   SU
R                   S35        U(       a  UR                  S	S
5      OS
n U R                  R!                  UUR                  5       UUR"                  UR$                  UUR&                  UR(                  UUR*                  UR,                  US9nUS   (       a)  US   UR                  5       :w  a  U R                  US   S9n	[9        U	U R                  US   UUUR"                  UR&                  U UUR,                  S9
$ ! [.         a=  nUR0                  S:X  a  [3        SUR4                   35      Se[7        SU 35      SeSnAff = f)a  Execute the runtime program.

Args:
    program_id: Program ID.
    inputs: Program input parameters. These input values are passed
        to the runtime program.
    options: Runtime options that control the execution environment.
    result_decoder: A :class:`ResultDecoder` subclass used to decode job results.
        If more than one decoder is specified, the first is used for interim results and
        the second final results. If not specified, a program-specific decoder or the default
        ``ResultDecoder`` is used.
    session_id: Job ID of the first job in a runtime session.
    start_session: Set to True to explicitly start a runtime session. Defaults to False.

Returns:
    A ``RuntimeJobV2`` instance representing the execution.

Raises:
    IBMInputValueError: If input is invalid.
    RuntimeProgramNotFound: If the program cannot be found.
    IBMRuntimeError: An error occurred running the program.
N)r-   r>   TactivezThe backend z currently has a status of r   r   r   )r  r   r   image	log_levelr  job_tagsmax_execution_timer  session_timeprivater     zProgram not found: zFailed to run program: r|   id)
r|   r   job_idr  r  r  rF   r   r   r  rP   )r%   
isinstancer   r   r-   r|   strget_backend_namestatusoperational
status_msgwarningswarnr>   r0   r[   program_runr  r  r  r  r  r  r   status_coder   messager   r"   )rh   r  r  r   r  r  r  r   qrt_optionsr|   r"  r   responser   s                 r8   _runQiskitRuntimeService._run  s   B '.?(*K&&(373KT\\2%%gs##ll(D(D(FlGG!%&*;*;x*GMMw||n,GHYHYGZZ[\ /5&**Y*!	L..::%(99;!''%//%$--#.#A#A+(55#++- ; H( I8I#6+:V:V:X#Xll(;l<G..D>!)##%%''
 	
   	L~~$,/B2::,-OPVZZ!$;B4"@AtK	Ls   A.G" "
H),8H$$H)r  c                     U R                   R                  USS9nU R                  U5      $ ! [         a  nUR                  S:w  a  [	        SU 35      SeSnU R
                  R                  5        HW  u  pEUc  M
  X@R                   R                  :w  d  M%   XPl         U R                   R                  USS9n  O! [         a     MU  f = f   Ub  U R                  U5      s SnA$ [        SU 35      SeSnAff = f)zRetrieve a runtime job.

Args:
    job_id: Job ID.

Returns:
    Runtime job retrieved.

Raises:
    RuntimeJobNotFound: If the job doesn't exist.
    IBMRuntimeError: If the request failed.
T)exclude_paramsr  zFailed to retrieve job: NJob not found: )
r[   job_getr   r(  r   rb   r  rv   _decode_jobr    )rh   r  r+  r   r?   r   s         r8   jobQiskitRuntimeService.job  s   	K..66vd6SH" ))!   	K~~$%(@&EFDPH$($5$5$;$;$= 'H8O8O8Y8Y,Y!28/#'#:#:#B#B6Z^#B#_+ ! ! %> #''11$vh%?@dJ	KsK   - 
C:AC5<C5 B:8C5:
CC5CC5 C:&C55C:limitskippendingr  created_aftercreated_before
descendingc                 z   U(       ap  X`R                   R                  :w  aW  X`R                  ;   a  U R                  U   U l         O3U R                  U5      nU R                  R	                  Xl05        Xl         U(       a  [        U5        / nU=(       d    SnUn U R                   R                  UUUUUUUU	U
US9
nUS   nUS   nUU-  n[        U5      UU-
  :X  a  O8U(       a  [        U5      U:  a  O!U[        U5      -
  nOSnU[        U5      -  nM|  U Vs/ s H  nU R                  U5      PM     sn$ s  snf )a@  Retrieve all runtime jobs, subject to optional filtering.

Args:
    limit: Number of jobs to retrieve. ``None`` means no limit.
    skip: Starting index for the job retrieval.
    backend_name: Name of the backend to retrieve jobs from.
    pending: Filter by job pending state. If ``True``, 'QUEUED' and 'RUNNING'
        jobs are included. If ``False``, 'DONE', 'CANCELLED' and 'ERROR' jobs
        are included.
    program_id: Filter by Program ID.
    instance: Filter by IBM Cloud instance crn.
    job_tags: Filter by tags assigned to jobs. Matched jobs are associated with all tags.
    session_id: Filter by session id. All jobs in the session will be
        returned in desceding order of the job creation date.
    created_after: Filter by the given start date, in local time. This is used to
        find jobs whose creation dates are after (greater than or equal to) this
        local date/time.
    created_before: Filter by the given end date, in local time. This is used to
        find jobs whose creation dates are before (less than or equal to) this
        local date/time.
    descending: If ``True``, return the jobs in descending order of the job
        creation date (i.e. newest first) until the limit is reached.

Returns:
    A list of runtime jobs.

Raises:
    IBMInputValueError: If an input value is invalid.
   )
r5  r6  r   r7  r  r  r  r8  r9  r:  jobscount)	r[   rv   rb   rw   rx   r#   jobs_getr   r2  )rh   r5  r6  r   r7  r  r?   r  r  r8  r9  r:  r{   job_responsescurrent_page_limitoffsetjobs_responsejob_pager>  r3  s                       r8   r=  QiskitRuntimeService.jobs  sY   V $;$;$E$EE,,,*.*;*;H*E'!>>xH
!!((()?@*4'h'"[b 33<<()%!%+-% = M %V,H "'*EX%M=!UT\1}%.%*S-?%?"%'"c(m#FA D 2??#  %???s   D8c                    [         R                  " S[        SS9   U R                  R	                  U5        g! [
         a=  nUR                  S:X  a  [        SUR                   35      Se[        SU 35      SeSnAff = f)z(DEPRECATED) Delete a runtime job.

Note that this operation cannot be reversed.

Args:
    job_id: ID of the job to delete.

Raises:
    RuntimeJobNotFound: The job doesn't exist.
    IBMRuntimeError: Method is not supported.
zThe delete_job() method is deprecated and will be removed in a future release. The new IBM Quantum Platform does not support deleting jobs.   
stacklevelr  r0  NzFailed to delete job: )
r%  r&  DeprecationWarningr[   
job_deleter   r(  r    r)  r   )rh   r  r   s      r8   
delete_jobQiskitRuntimeService.delete_jobu  s     	K		
	K##..v6 	K~~$(?2::,)GHdR!$:2$"?@dJ	Ks   8 
A?8A::A?c                    U R                   R                  5       nUR                  S5      (       d  UR                  S5      (       aB  [        UR                  SUR                  S5      5      UR                  SS5      -
  S5      nX!S'   U$ )zaReturn usage information for the current active instance.

Returns:
    Dict with usage details.
usage_limit_secondsusage_allocation_secondsusage_consumed_secondsr   usage_remaining_seconds)r[   cloud_usager0   max)rh   
usage_dictusage_remainings      r8   usageQiskitRuntimeService.usage  s     ,,88:
>>/00JNNC]4^4^!4jnnE_6`a..!91=>O
 5D01r:   raw_datac                    U R                   R                  n SU;   a  U R                  US   USS9nOSn [        UU R                   U US   UR                  S0 5      R                  SS5      UR                  S	S5      UR                  S
5      UR                  S5      UR                  S5      UR                  SS5      S9
$ ! [         a$    [        R
                  R                  US   SS9n Nf = f)zDecode job data received from the server.

Args:
    raw_data: Raw job data received from the server.

Returns:
    Decoded job data.
r|   F)r?   r   N)r   apir  programrO   createdr(   r  rF   r  )
r|   r   r   r  r  creation_dater  r  rF   r  )	r[   rv   r   r   r   IBMRetiredBackend	from_namer"   r0   )rh   rY  r?   r|   s       r8   r2   QiskitRuntimeService._decode_job  s    **44	H$22Y'(QV 3   ..D>||Ir266tR@",,y$7,,y)||L1f%LLE2
 	
 * 	!33==%i0 > G	s   C C +C0/C0c                 0   [         R                  " S[        SS9   U R                  5       R	                  S5      S   nUR	                  S5      nUR	                  S5      nX#:  aF  U R                  SS	S
S9nU(       a-  [        R                  SUS   5         US   R                  SS9  ggg! [         a2  n[        R                  SUS   R                  5       U5         SnAgSnAff = f! [         a   n[        R                  SU5         SnAgSnAff = f)z(DEPRECATED) Check the number of pending jobs and wait for the oldest pending job if
the maximum number of pending jobs has been reached.
zThe check_pending_jobs() method is deprecated and will be removed in a future release. The new IBM Quantum Platform does not support this functionality.rG  rH  
byInstancer   pendingJobsmaxPendingJobsr   FT)r5  r:  r7  zeThe pending jobs limit has been reached. Waiting for job %s to finish before submitting the next one.i,  )timeoutz8An error occurred while waiting for job %s to finish: %sNz5Unable to retrieve open plan pending jobs details. %s)r%  r&  rJ  rW  r0   r=  re   rf   wait_for_final_staterz   debugr  )rh   rW  pending_jobsmax_pending_jobsoldest_runningr   s         r8   check_pending_jobs'QiskitRuntimeService.check_pending_jobs  s   
 	P		
	XJJL$$\215E 99]3L$yy)9:/!%ud!S!NNW&q)
&q)>>s>K " 0 % V*1-446   	XNNRTVWW	Xs<   A:C+ B, ,
C(6(C#C+ #C((C+ +
D5DDc                   ^ / nU(       a"  U R                  U5      nUR                  5       nOU R                  (       d@  U R                  R	                  5        H!  n UR                  5       nU(       a  XW-  nM!  M#     O<U R                  (       d  U R                  R                  5       U l        U R                  n/ nU H"  n	U	S   S   S:X  d  M  UR                  U	5        M$     U(       d  U(       ac  U R                  " S
TX2S.UD6n
U
 Vs/ s H  oR                  PM     nnUR                  5        H  nUS   U;  d  M  UR                  U5        M!     T(       a  [        [        U4S jU5      5      nU(       d  [        S5      e[!        US S9nU H  n U R#                  US   S	9s  $    [        S5      e! [
         a     GMo  f = fs  snf ! [$         a     MI  f = f)a   Return the least busy available backend.

Args:
    min_num_qubits: Minimum number of qubits the backend has to have.
    instance: IBM Cloud account CRN.
    filters: Filters can be defined as for the :meth:`backends` method.
        An example to get the operational backends with 5 qubits::

            QiskitRuntimeService.least_busy(n_qubits=5, operational=True)

Returns:
    The backend with the fewest number of pending jobs.

Raises:
    QiskitBackendNotFoundError: If no backend matches the criteria.
r"  r>   online)r   rr   r?   c                    > U S   T:  $ )NqubitsrP   r   s    r8   r   1QiskitRuntimeService.least_busy.<locals>.<lambda>"  s    q{n/Lr:   r  c                     U S   $ )Nqueue_lengthrP   )r   s    r8   r   rr  %  s	    1^;Lr:   r   r  rP   )r   ry   rZ   rb   valuesr   r\   r[   r   r   r>   copyremover   r   r   r   r|   rz   )rh   r   r?   rr   r6   all_backendsr   client_backends
candidatesr|   r   backfiltered_backend_names	candidatesorted_backendss    `             r8   
least_busyQiskitRuntimeService.least_busy  s   . ))(3F!//1L''++224&,&:&:&<O&$7 ' 5 &&&*&=&=&K&K&M#..L
#Gx (H4!!'* $ f}} -wU[H =E%EHDiiH"%E'__.	V$,BB%%i0 / f%LjYZJ,-OPP 1LM#D||f|66 $ ))KLLC ( " &F  s*   F9GG9
GG
GGc                 z    U R                   (       d  U R                  R                  5       U l         U R                   $ )zReturn a list that contains a series of dictionaries with the
    following instance identifiers per instance: "crn", "plan", "name".

Returns:
    A list with instances available for the active account.
)rR   rU   r   r   s    r8   ra   QiskitRuntimeService.instances.  s.     """&--">">"@D"""r:   c                 .    U R                   R                  $ )z.Return the crn of the current active instance.)r[   rv   r   s    r8   active_instance$QiskitRuntimeService.active_instance9  s    &&000r:   c                     U R                   $ )zCReturn the channel type used.

Returns:
    The channel type used.
)rW   r   s    r8   r-   QiskitRuntimeService.channel=  s     }}r:   c                 L    SR                  U R                  R                  5      $ )Nz<{}>)formatr7   __name__r   s    r8   __repr__QiskitRuntimeService.__repr__F  s    }}T^^4455r:   otherc                    U R                   UR                   :H  =(       aa    U R                  R                  UR                  R                  :H  =(       a-    U R                  R                  UR                  R                  :H  $ r   )rW   rU   r?   r;   )rh   r  s     r8   __eq__QiskitRuntimeService.__eq__I  sY    MMU^^+ <&&%..*A*AA<##u~~';';;	
r:   )rU   r[   rR   rb   rY   r]   r\   rW   rV   rZ   r_   r^   rS   r`   rX   )NNNNNNNNNNNNN)rG   N)NNNNNNNNr   )NNNNN)NNN)NNNNNNNNFNFNNN)NNNN)NFN)NNNFN)
   r   NNNNNNNNT)Dr  
__module____qualname____firstlineno____doc__r3   r   r   r   r  boolr   r   rQ   r}   r   rw   r   r   r   rT   r   staticmethodr$   r   r   r   r   r   intr	   r   r   rc   rg   r&   r   r   r   r   r   r   r  Backendr|   r%   r
   r!   r   r"   r,  r3  r   r=  rL  rW  r2  rl  r   r  ra   r  propertyr-   r  r  __static_attributes____classcell__)r7   s   @r8   r*   r*   0   s   @( *.#!"&""&"&!%+/QU $04$(X7+&X7 }X7 c]	X7
 3-X7 smX7 3-X7 $X7 X7 #4.X7 xc8D>3(G(LMNX7 X7 #49-X7 tCy!X7 
X7 X7t c (2S 2] 2+^  $!"&)-"&"04!%Z}Z c]Z 3-	Z
 +&Z 3-Z smZ ,-Z Z 
Zx7 c c " 
(#3 
(S%c	BR=R8S 
( 
( #'3- 
0!$sM'9": ! #(,"&+/HLxD 05(,xDsmxD !xD 3-	xD
 #4.xD ($<#=t#CDExD 'tnxD !xD xD 
&	'xDt([# ([4cSWX[S\nH]C^ ([T-C -D - )-@@ 3-@ 'tn	@
 !@ 
@D/c3h 8 / "&")-T3-TsmT +&T 
	T T& #!"&)-"&""&!%$))-+0'+/3$(A
}A
c]A
 3-A
 +&	A

 3-A
 smA
 $A
 A
 D>A
 !A
 #4.A
 $A
 #8,A
 tCy!A
 
A
 A
F "&)-"&"	
$
+&
 3-
 sm	

 

 
@ #'/4(,-- 3-- 'tn	-
 !- 
-f :>^b$((-(,W
W
 W
 % 456	W

 !tM':HT-EX<Y'Y!Z[W
 SMW
  ~W
 !W
 
W
r*# *, *F  "&*"&(,$(,0-1[@}[@ [@ sm	[@
 [@ [@ 3-[@ 49%[@ SM[@  )[@ !*[@ [@ 
l	[@zK K K6tCH~  #
D #
\ #
J#XN )-"&HL	BM BM 3-BM ($<#=t#CDE	BM
 BM 
		BMH	#8DcN3 	#1 1   6# 6
C 
D 
 
r:   r*   )?r  loggingr%  r   typingr   r   r   r   r   r	   r
   r   r   qiskit.providers.backendr   r  qiskit.providers.exceptionsr   qiskit.providers.providerutilsr   qiskit_ibm_runtimer   r@   r   utilsr   utils.backend_decoderr   accountsr   r   r   r   r   api.clientsr   api.clients.runtimer   api.exceptionsr   
exceptionsr   r   r   r    utils.result_decoderr!   runtime_job_v2r"   r#   api.client_parametersr$   runtime_optionsr%   r&   modelsr'   	getLoggerr  re   SERVICE_NAMEr*   rP   r:   r8   <module>r     s        T T T 9 B : * '  A P P & . , * S S / ( $ 3 + # ,			8	$^
 ^
r:   