Skip to content

Commit b73fdac

Browse files
jyu00chriseclectickt474mbernabeckykd
authored
SamplerV2 options (#1223)
* Add experimental options (#1067) * add options * fix mypy * rename meas err mit * Add additional resilience options * Add additional execution options for twirling * A twirling strategy option and validation * handle default resilience options * add _experimental * Update default resilience options (#1062) * remove default resilience options * add reno * add logic to override default * add test * purge None values from options (cherry picked from commit 76603f2) * add finalize options * add tests * Update qiskit_ibm_runtime/options/resilience_options.py * add validation * lint * lint again * lint again * Allow None values for specific options to be passed through * Fix parameter validation, allow computational basis * black * Fix ZneExtrapolatorType validation * lint * lint again * fix mypy * Fix ZNE extrapolator default option * fix level options * black * use _isreal * Disable gate twirling for default lvl 1 opts * Support for legacy options --------- Co-authored-by: Christopher J. Wood <cjwood@us.ibm.com> Co-authored-by: Kevin Tian <kevin.tian@ibm.com> Co-authored-by: mberna <mariana.bernagozzi@gmail.com> Co-authored-by: Mariana C Bernagozzi <Mariana.Bernagozzi@ibm.com> * fix merge issues * add pydantic * black * lint * Fast forward experimental to latest main (#1178) * Remove min execution time check (#1065) * Remove min execution time check * update unit test * remove integration test * Update `max_execution_time` docstrings (#1059) * Update max_execution_time docstrings * add commas * Update qiskit_ibm_runtime/options/options.py Co-authored-by: Rebecca Dimock <66339736+beckykd@users.noreply.github.com> * Update qiskit_ibm_runtime/options/options.py Co-authored-by: Rebecca Dimock <66339736+beckykd@users.noreply.github.com> * Update qiskit_ibm_runtime/runtime_options.py Co-authored-by: Rebecca Dimock <66339736+beckykd@users.noreply.github.com> * Update releasenotes/notes/max-execution-time-definition-196cb6297693c0f2.yaml Co-authored-by: Rebecca Dimock <66339736+beckykd@users.noreply.github.com> --------- Co-authored-by: Rebecca Dimock <66339736+beckykd@users.noreply.github.com> * Removed remaining code related to Schedules (#1068) Co-authored-by: Kevin Tian <kevin.tian@ibm.com> * Enable datetime parameter for backend properties (#1070) * enable datetime param for backend properties * add test & reno * improve test * Update default resilience options (#1062) * remove default resilience options * add reno * add logic to override default * add test * purge None values from options * fix test (#1074) * Prepare release 0.12.1 (#1075) * Update main branch veresion 0.12.2 (#1076) * use ibmq_qasm_simulator (#1078) * Add reason code to error message (#1072) * Add reason code to error message * add reno * Remove importing PauliSumOp, which is deprecated. (#1079) --------- Co-authored-by: Jake Lishman <jake.lishman@ibm.com> Co-authored-by: Kevin Tian <kevin.tian@ibm.com> * Adjusts default value for optimization_level (#1082) * add instance info (#1083) * add instance info * Add cloud note * Update README.md Co-authored-by: Kevin Tian <kt474@cornell.edu> --------- Co-authored-by: Kevin Tian <kt474@cornell.edu> * Fix links to options in README.md (#1084) * Remove auth parameter (#1077) * Removed auth parameter * Removed calls to migrate() * black and lint --------- Co-authored-by: Kevin Tian <kevin.tian@ibm.com> * Remove opflow and algorithms from serialization tests (#1085) * Remove opflow from tests * Re-add test for PauliSumOp * Fix lint * Fix black --------- Co-authored-by: Kevin Tian <kevin.tian@ibm.com> * RuntimeJobTimeoutError should inherit from JobTimeoutError (#1090) * RuntimeJobTimeoutError inherits from JobTimeoutError * black --------- Co-authored-by: Kevin Tian <kevin.tian@ibm.com> * Allow user to define a default account as an environment variable (#1018) * Allow user to define a default account as an environment variable * Fixed test * Fixed mistaken paste * Cleaned up test * Moved test to TestAccountManager * Added ability to define default channel in save_account * Cleaned up code, fixed bugs * Changed name of parameter * Added test. Cleaned up code surrounding preferences of channel selection * black and lint * Fixed bug when json file was empty * Code cleanup and documentation * Documentation * Removed channel from condition, because unnecessary * changed default_channel to default_account * Changed saving and getting default channel to default account * black * Documentation * Release notes * Reverted diff that was unnecessary --------- Co-authored-by: Kevin Tian <kevin.tian@ibm.com> * Skip test_job_logs (#1094) * Update session max_time docstring (#1089) * Update session max_time docstring * Update qiskit_ibm_runtime/session.py Co-authored-by: Rebecca Dimock <66339736+beckykd@users.noreply.github.com> --------- Co-authored-by: Rebecca Dimock <66339736+beckykd@users.noreply.github.com> * Fix unit tests against qiskit/main (#1099) * Add measurements to sampler * Remove observables from sampler run --------- Co-authored-by: Kevin Tian <kevin.tian@ibm.com> * fix iqp link (#1096) Co-authored-by: Kevin Tian <kevin.tian@ibm.com> * Only return channel strategy supported backends (#1095) * Q-CTRL Backend filters * add reno * fix unit tests * Attempt to fix terra unit tests (#1102) * Attempt to fix terra unit tests * test on my fork * revert coder_qc change * Making account code more generic (#1060) * Making account code more generic by defining subclasses for channel types * Removed channel parameter from _assert_valid_instance * mypy, lint and black * Changed order of decorators * Code cleanup * Documentation fixes * black --------- Co-authored-by: Kevin Tian <kevin.tian@ibm.com> * Remove old deprecations (#1106) * removing old deprecations * update unit tests * Open plan updates (#1105) * Initial edits * edit * Update docs/faqs/max_execution_time.rst * Update docs/faqs/max_execution_time.rst * Update docs/faqs/max_execution_time.rst * Update docs/faqs/max_execution_time.rst * Update docs/faqs/max_execution_time.rst * Update docs/faqs/max_execution_time.rst Co-authored-by: Jessie Yu <jessieyu@us.ibm.com> * Jessie comments * Update docs/faqs/max_execution_time.rst Co-authored-by: Jessie Yu <jessieyu@us.ibm.com> * Update docs/faqs/max_execution_time.rst Co-authored-by: Jessie Yu <jessieyu@us.ibm.com> * Update docs/sessions.rst * Update docs/faqs/max_execution_time.rst --------- Co-authored-by: Jessie Yu <jessieyu@us.ibm.com> * New method to create a new Session object with a given id (#1101) * Added the Session.from_id method * release notes * Added integration test --------- Co-authored-by: Kevin Tian <kevin.tian@ibm.com> * fix test_session_from_id (#1110) * Warn users if job submitted will exceed quota (#1100) * Warn users if job will exceed quota * update reno * update reno again * Removed support for backend as session parameter (#1091) Co-authored-by: Kevin Tian <kevin.tian@ibm.com> * Fix minor todos (#1112) * Change qpu complex wording (#1109) * Don't use QPU complex * don't use the word 'limit' * Update docs/faqs/max_execution_time.rst * Update qiskit_ibm_runtime/options/options.py * Update qiskit_ibm_runtime/runtime_job.py * Update releasenotes/notes/0.11/job-cost-estimation-d0ba83dbc95c3f67.yaml * Clarify usage * reclarify reset time * rogue comma * fix whitespace & formatting * job -> system execution time --------- Co-authored-by: Kevin Tian <kevin.tian@ibm.com> * Add IBM Cloud channel (#1113) * Changes for #1806 * Update docs/faqs/max_execution_time.rst Co-authored-by: Jessie Yu <jessieyu@us.ibm.com> --------- Co-authored-by: Kevin Tian <kt474@cornell.edu> Co-authored-by: Jessie Yu <jessieyu@us.ibm.com> Co-authored-by: Kevin Tian <kevin.tian@ibm.com> * Prepare release 0.12.2 (#1115) * Update main branch 0.13.0 (#1116) * remove error message test (#1125) * Exceptions should inherit from Terra where suitable (#1120) * Changed RuntimeJobFailureError to inherit from JobError * Changed error type --------- Co-authored-by: Kevin Tian <kevin.tian@ibm.com> * update docstring & remove max_time (#1137) * Expose new session details (#1119) * add session details method * add reno * support iqp urls * update details mehotd, add status() * update status() to use enum * revert previous change, wait for impl details * update fields returned * update status method * update docstring & reno * update docstrings for both methods * fix docs build * address comments * fix docs build * fix typo * docs build again * fix indent * fix indent again * fix indent 3rd time * Support only LocalFoldingAmplifier as noise_amplifier option (#1093) * Removed support for all noise_amplifier options other than LocalFoldingAmplifier. Removed deprecation warning. * Removed tests that covered deprecation. Updated documentation --------- Co-authored-by: Kevin Tian <kevin.tian@ibm.com> * Fix target_history date bug (#1143) * fix target_history datetime bug * add reno * add test * Fixed bug when defining shots as int64 (#1151) * Log instance on initialization and when running a job (#1150) * log instances * add _default_instance & fix lint * add test * change var name to current_instance * Move methods into class pages for docs (#1144) * Fix link to `Close a session` (#1152) [1] links to [2] but doesn't go directly to the target section. [1] https://qiskit.org/ecosystem/ibm-runtime/sessions.html#what-happens-when-a-session-ends [2] https://qiskit.org/ecosystem/ibm-runtime/how_to/run_session.html#close-a-session Co-authored-by: Kevin Tian <kevin.tian@ibm.com> * logging instance test is IQP channel only (#1154) * Update deploy yml (#1148) * Allow users to indicate they are done submitting jobs to a session (#1139) * copy changes over * clean up branch again * address comments, update docstrings * catch appropriate error code * update status code to 404 * Update qiskit_ibm_runtime/session.py Co-authored-by: Jessie Yu <jessieyu@us.ibm.com> * set self._active & remove runtime_session * Update releasenotes/notes/session-accepting-jobs-d7ef6b60c0f5527b.yaml Co-authored-by: Jessie Yu <jessieyu@us.ibm.com> --------- Co-authored-by: Jessie Yu <jessieyu@us.ibm.com> * Prepare release 0.13 (#1157) * Update main branch 0.13.1 (#1158) * Update Sphinx theme (#1156) Co-authored-by: Kevin Tian <kevin.tian@ibm.com> * Added IBM Quantum logo (#1164) * sessions changes (#1169) * sessions changes * add more ticks * fix link * fix links * Update docs/sessions.rst Co-authored-by: abbycross <across@us.ibm.com> * Update docs/sessions.rst Co-authored-by: abbycross <across@us.ibm.com> --------- Co-authored-by: abbycross <across@us.ibm.com> * Disallow unsupported options (#1108) * Disallow unsupported options * Moved checking of unsupported options to 'flexible' decorator * Modified the test to give TypeError where needed * Removed empty newline * Moved tests from test_ibm_primitives to test_options, because they don't require a primitive * typo * Release note * black and lint * black again * Fixed test failing in CI * Removed _flexible decorator. Moved _post_init into Options class * lint * lint * Fixed bug * lint --------- Co-authored-by: Kevin Tian <kevin.tian@ibm.com> * fix merge issues * black * lint --------- Co-authored-by: Kevin Tian <kevin.tian@ibm.com> Co-authored-by: Rebecca Dimock <66339736+beckykd@users.noreply.github.com> Co-authored-by: merav-aharoni <merav@il.ibm.com> Co-authored-by: Luciano Bello <bel@zurich.ibm.com> Co-authored-by: Jake Lishman <jake.lishman@ibm.com> Co-authored-by: Esteban Ginez <175813+eginez@users.noreply.github.com> Co-authored-by: Kevin Tian <kt474@cornell.edu> Co-authored-by: mberna <mariana.bernagozzi@gmail.com> Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com> Co-authored-by: Arnau Casau <47946624+arnaucasau@users.noreply.github.com> Co-authored-by: Matt Riedemann <mriedem.os@gmail.com> Co-authored-by: abbycross <across@us.ibm.com> * v2 options * estimator options * update test * lint * fix merge issues * black * fix noise model type * lint again * fix header * fix mypy * use v2 as default * cleanup terra options * black * options need not be callable * fix doc * fix tests * fix version * add sampler option * lint * freeze constants * freeze constants * remove is_simulator * make image work * fix merge issues * fix tests * fix tests * lint * add seed_estimator * resolve merge issues --------- Co-authored-by: Christopher J. Wood <cjwood@us.ibm.com> Co-authored-by: Kevin Tian <kevin.tian@ibm.com> Co-authored-by: mberna <mariana.bernagozzi@gmail.com> Co-authored-by: Mariana C Bernagozzi <Mariana.Bernagozzi@ibm.com> Co-authored-by: Rebecca Dimock <66339736+beckykd@users.noreply.github.com> Co-authored-by: merav-aharoni <merav@il.ibm.com> Co-authored-by: Luciano Bello <bel@zurich.ibm.com> Co-authored-by: Jake Lishman <jake.lishman@ibm.com> Co-authored-by: Esteban Ginez <175813+eginez@users.noreply.github.com> Co-authored-by: Kevin Tian <kt474@cornell.edu> Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com> Co-authored-by: Arnau Casau <47946624+arnaucasau@users.noreply.github.com> Co-authored-by: Matt Riedemann <mriedem.os@gmail.com> Co-authored-by: abbycross <across@us.ibm.com>
1 parent f807061 commit b73fdac

13 files changed

+869
-329
lines changed

qiskit_ibm_runtime/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -189,8 +189,8 @@ def result_callback(job_id, result):
189189
from .version import __version__
190190

191191
from .estimator import EstimatorV2, EstimatorV1 as Estimator
192-
from .sampler import SamplerV1 as Sampler
193-
from .options import Options, EstimatorOptions
192+
from .sampler import SamplerV2, SamplerV1 as Sampler
193+
from .options import Options, EstimatorOptions, SamplerOptions
194194

195195
# Setup the logger for the IBM Quantum Provider package.
196196
logger = logging.getLogger(__name__)

qiskit_ibm_runtime/estimator.py

-1
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,6 @@
6969
class Estimator:
7070
"""Base class for Qiskit Runtime Estimator."""
7171

72-
_PROGRAM_ID = "estimator"
7372
version = 0
7473

7574

qiskit_ibm_runtime/options/__init__.py

+2
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
SimulatorOptions
5252
TwirlingOptions
5353
EstimatorOptions
54+
SamplerOptions
5455
5556
"""
5657

@@ -62,3 +63,4 @@
6263
from .resilience_options import ResilienceOptionsV1 as ResilienceOptions
6364
from .twirling_options import TwirlingOptions
6465
from .estimator_options import EstimatorOptions
66+
from .sampler_options import SamplerOptions

qiskit_ibm_runtime/options/estimator_options.py

+3-115
Original file line numberDiff line numberDiff line change
@@ -13,18 +13,14 @@
1313
"""Primitive options."""
1414

1515
from typing import Union, Literal
16-
import copy
1716

18-
from qiskit.transpiler import CouplingMap
1917
from pydantic.dataclasses import dataclass as pydantic_dataclass
2018
from pydantic import Field, ConfigDict, field_validator
2119

2220
from .utils import (
2321
Dict,
2422
Unset,
2523
UnsetType,
26-
_remove_dict_unset_values,
27-
merge_options,
2824
skip_unset_validation,
2925
)
3026
from .execution_options import ExecutionOptionsV2
@@ -74,6 +70,8 @@ class EstimatorOptions(OptionsV2):
7470
Allowed values are ``"XX"``, ``"XpXm"``, ``"XY4"``.
7571
Default: None
7672
73+
seed_estimator: Seed used to control sampling.
74+
7775
transpilation: Transpilation options. See :class:`TranspilationOptions` for all
7876
available options.
7977
@@ -90,14 +88,14 @@ class EstimatorOptions(OptionsV2):
9088
9189
"""
9290

93-
_VERSION: int = Field(2, frozen=True) # pylint: disable=invalid-name
9491
_MAX_OPTIMIZATION_LEVEL: int = Field(3, frozen=True) # pylint: disable=invalid-name
9592
_MAX_RESILIENCE_LEVEL: int = Field(3, frozen=True) # pylint: disable=invalid-name
9693

9794
# Sadly we cannot use pydantic's built in validation because it won't work on Unset.
9895
optimization_level: Union[UnsetType, int] = Unset
9996
resilience_level: Union[UnsetType, int] = Unset
10097
dynamical_decoupling: Union[UnsetType, DDSequenceType] = Unset
98+
seed_estimator: Union[UnsetType, int] = Unset
10199
transpilation: Union[TranspilationOptions, Dict] = Field(default_factory=TranspilationOptions)
102100
resilience: Union[ResilienceOptionsV2, Dict] = Field(default_factory=ResilienceOptionsV2)
103101
execution: Union[ExecutionOptionsV2, Dict] = Field(default_factory=ExecutionOptionsV2)
@@ -127,113 +125,3 @@ def _validate_resilience_level(cls, resilience_level: int) -> int:
127125
f"0-{EstimatorOptions._MAX_RESILIENCE_LEVEL}"
128126
)
129127
return resilience_level
130-
131-
@staticmethod
132-
def _get_program_inputs(options: dict) -> dict:
133-
"""Convert the input options to program compatible inputs.
134-
135-
Returns:
136-
Inputs acceptable by primitives.
137-
"""
138-
139-
sim_options = options.get("simulator", {})
140-
inputs = {}
141-
inputs["transpilation"] = copy.copy(options.get("transpilation", {}))
142-
inputs["skip_transpilation"] = inputs["transpilation"].pop("skip_transpilation")
143-
coupling_map = sim_options.get("coupling_map", None)
144-
# TODO: We can just move this to json encoder
145-
if isinstance(coupling_map, CouplingMap):
146-
coupling_map = list(map(list, coupling_map.get_edges()))
147-
inputs["transpilation"].update(
148-
{
149-
"optimization_level": options.get("optimization_level"),
150-
"coupling_map": coupling_map,
151-
"basis_gates": sim_options.get("basis_gates", None),
152-
}
153-
)
154-
155-
inputs["resilience_level"] = options.get("resilience_level")
156-
inputs["resilience"] = options.get("resilience", {})
157-
158-
inputs["twirling"] = options.get("twirling", {})
159-
160-
inputs["execution"] = options.get("execution", {})
161-
inputs["execution"].update(
162-
{
163-
"noise_model": sim_options.get("noise_model", Unset),
164-
"seed_simulator": sim_options.get("seed_simulator", Unset),
165-
}
166-
)
167-
168-
# Add arbitrary experimental options
169-
if isinstance(options.get("experimental", None), dict):
170-
inputs = merge_options(inputs, options.get("experimental"))
171-
172-
# Remove image
173-
inputs.pop("image", None)
174-
175-
inputs["_experimental"] = True
176-
inputs["version"] = EstimatorOptions._VERSION
177-
_remove_dict_unset_values(inputs)
178-
179-
return inputs
180-
181-
182-
# @dataclass(frozen=True)
183-
# class _ResilienceLevel0Options:
184-
# resilience_level: int = 0
185-
# resilience: ResilienceOptions = field(
186-
# default_factory=lambda: ResilienceOptions(
187-
# measure_noise_mitigation=False, zne_mitigation=False, pec_mitigation=False
188-
# )
189-
# )
190-
# twirling: TwirlingOptions = field(
191-
# default_factory=lambda: TwirlingOptions(gates=False, measure=False)
192-
# )
193-
194-
195-
# @dataclass(frozen=True)
196-
# class _ResilienceLevel1Options:
197-
# resilience_level: int = 1
198-
# resilience: ResilienceOptions = field(
199-
# default_factory=lambda: ResilienceOptions(
200-
# measure_noise_mitigation=True, zne_mitigation=False, pec_mitigation=False
201-
# )
202-
# )
203-
# twirling: TwirlingOptions = field(
204-
# default_factory=lambda: TwirlingOptions(gates=False, measure=True, strategy="active-accum")
205-
# )
206-
207-
208-
# @dataclass(frozen=True)
209-
# class _ResilienceLevel2Options:
210-
# resilience_level: int = 2
211-
# resilience: ResilienceOptions = field(
212-
# default_factory=lambda: ResilienceOptions(
213-
# measure_noise_mitigation=True, pec_mitigation=False, **asdict(_ZneOptions())
214-
# )
215-
# )
216-
# twirling: TwirlingOptions = field(
217-
# default_factory=lambda: TwirlingOptions(gates=True, measure=True, strategy="active-accum")
218-
# )
219-
220-
221-
# @dataclass(frozen=True)
222-
# class _ResilienceLevel3Options:
223-
# resilience_level: int = 3
224-
# resilience: ResilienceOptions = field(
225-
# default_factory=lambda: ResilienceOptions(
226-
# measure_noise_mitigation=True, zne_mitigation=False, **asdict(_PecOptions())
227-
# )
228-
# )
229-
# twirling: TwirlingOptions = field(
230-
# default_factory=lambda: TwirlingOptions(gates=True, measure=True, strategy="active")
231-
# )
232-
233-
234-
# _DEFAULT_RESILIENCE_LEVEL_OPTIONS = {
235-
# 0: _ResilienceLevel0Options(),
236-
# 1: _ResilienceLevel1Options(),
237-
# 2: _ResilienceLevel2Options(),
238-
# 3: _ResilienceLevel3Options(),
239-
# }

qiskit_ibm_runtime/options/options.py

+68-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
from pydantic.dataclasses import dataclass as pydantic_dataclass
2323
from pydantic import Field, ConfigDict
2424

25-
from .utils import Dict, _to_obj, UnsetType, Unset, _remove_dict_unset_values
25+
from .utils import Dict, _to_obj, UnsetType, Unset, _remove_dict_unset_values, merge_options
2626
from .environment_options import EnvironmentOptions
2727
from .execution_options import ExecutionOptionsV1 as ExecutionOptions
2828
from .simulator_options import SimulatorOptions
@@ -93,10 +93,77 @@ class OptionsV2(BaseOptions):
9393
:class:`SimulatorOptions` for all available options.
9494
"""
9595

96+
_VERSION: int = Field(2, frozen=True) # pylint: disable=invalid-name
97+
98+
# Options not really related to primitives.
9699
max_execution_time: Union[UnsetType, int] = Unset
97100
environment: Union[EnvironmentOptions, Dict] = Field(default_factory=EnvironmentOptions)
98101
simulator: Union[SimulatorOptions, Dict] = Field(default_factory=SimulatorOptions)
99102

103+
@staticmethod
104+
def _get_program_inputs(options: dict) -> dict:
105+
"""Convert the input options to program compatible inputs.
106+
107+
Returns:
108+
Inputs acceptable by primitives.
109+
"""
110+
111+
def _set_if_exists(name: str, _inputs: dict, _options: dict) -> None:
112+
if name in _options:
113+
_inputs[name] = _options[name]
114+
115+
options_copy = copy.deepcopy(options)
116+
sim_options = options_copy.get("simulator", {})
117+
inputs = {}
118+
inputs["transpilation"] = options_copy.get("transpilation", {})
119+
inputs["skip_transpilation"] = inputs["transpilation"].pop("skip_transpilation")
120+
coupling_map = sim_options.get("coupling_map", Unset)
121+
# TODO: We can just move this to json encoder
122+
if isinstance(coupling_map, CouplingMap):
123+
coupling_map = list(map(list, coupling_map.get_edges()))
124+
inputs["transpilation"].update(
125+
{
126+
"optimization_level": options_copy.get("optimization_level", Unset),
127+
"coupling_map": coupling_map,
128+
"basis_gates": sim_options.get("basis_gates", Unset),
129+
}
130+
)
131+
132+
for fld in [
133+
"resilience_level",
134+
"resilience",
135+
"twirling",
136+
"dynamical_decoupling",
137+
"seed_estimator",
138+
]:
139+
_set_if_exists(fld, inputs, options_copy)
140+
141+
inputs["execution"] = options_copy.get("execution", {})
142+
inputs["execution"].update(
143+
{
144+
"noise_model": sim_options.get("noise_model", Unset),
145+
"seed_simulator": sim_options.get("seed_simulator", Unset),
146+
}
147+
)
148+
149+
# Add arbitrary experimental options
150+
if isinstance(options_copy.get("experimental", None), dict):
151+
inputs = merge_options(inputs, options_copy.get("experimental"))
152+
153+
# Remove image
154+
inputs.pop("image", None)
155+
156+
inputs["_experimental"] = True
157+
inputs["version"] = OptionsV2._VERSION
158+
_remove_dict_unset_values(inputs)
159+
160+
# Remove empty dictionaries
161+
for key, val in list(inputs.items()):
162+
if isinstance(val, dict) and not val:
163+
del inputs[key]
164+
165+
return inputs
166+
100167

101168
@dataclass
102169
class Options(BaseOptions):
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
# This code is part of Qiskit.
2+
#
3+
# (C) Copyright IBM 2022.
4+
#
5+
# This code is licensed under the Apache License, Version 2.0. You may
6+
# obtain a copy of this license in the LICENSE.txt file in the root directory
7+
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
8+
#
9+
# Any modifications or derivative works of this code must retain this
10+
# copyright notice, and modified files need to carry a notice indicating
11+
# that they have been altered from the originals.
12+
13+
"""Sampler options."""
14+
15+
from typing import Union, Literal
16+
17+
from pydantic.dataclasses import dataclass as pydantic_dataclass
18+
from pydantic import Field, ConfigDict, field_validator
19+
20+
from .utils import (
21+
Dict,
22+
Unset,
23+
UnsetType,
24+
skip_unset_validation,
25+
)
26+
from .execution_options import ExecutionOptionsV2
27+
from .transpilation_options import TranspilationOptions
28+
from .twirling_options import TwirlingOptions
29+
from .options import OptionsV2
30+
31+
DDSequenceType = Literal["XX", "XpXm", "XY4"]
32+
33+
34+
@pydantic_dataclass(
35+
config=ConfigDict(validate_assignment=True, arbitrary_types_allowed=True, extra="forbid")
36+
)
37+
class SamplerOptions(OptionsV2):
38+
"""Options for v2 Sampler.
39+
40+
Args:
41+
optimization_level: How much optimization to perform on the circuits.
42+
Higher levels generate more optimized circuits,
43+
at the expense of longer transpilation times. This is based on the
44+
``optimization_level`` parameter in qiskit-terra but may include
45+
backend-specific optimization. Default: 1.
46+
47+
* 0: no optimization
48+
* 1: light optimization
49+
* 2: heavy optimization
50+
* 3: even heavier optimization
51+
52+
dynamical_decoupling: Optional, specify a dynamical decoupling sequence to use.
53+
Allowed values are ``"XX"``, ``"XpXm"``, ``"XY4"``.
54+
Default: None
55+
56+
transpilation: Transpilation options. See :class:`TranspilationOptions` for all
57+
available options.
58+
59+
execution: Execution time options. See :class:`ExecutionOptionsV2` for all available options.
60+
61+
twirling: Pauli-twirling related options. See :class:`TwirlingOptions` for all available options.
62+
63+
environment: Options related to the execution environment. See
64+
:class:`EnvironmentOptions` for all available options.
65+
66+
simulator: Simulator options. See
67+
:class:`SimulatorOptions` for all available options.
68+
69+
"""
70+
71+
_MAX_OPTIMIZATION_LEVEL: int = Field(3, frozen=True) # pylint: disable=invalid-name
72+
73+
# Sadly we cannot use pydantic's built in validation because it won't work on Unset.
74+
optimization_level: Union[UnsetType, int] = Unset
75+
dynamical_decoupling: Union[UnsetType, DDSequenceType] = Unset
76+
transpilation: Union[TranspilationOptions, Dict] = Field(default_factory=TranspilationOptions)
77+
execution: Union[ExecutionOptionsV2, Dict] = Field(default_factory=ExecutionOptionsV2)
78+
twirling: Union[TwirlingOptions, Dict] = Field(default_factory=TwirlingOptions)
79+
experimental: Union[UnsetType, dict] = Unset
80+
81+
@field_validator("optimization_level")
82+
@classmethod
83+
@skip_unset_validation
84+
def _validate_optimization_level(cls, optimization_level: int) -> int:
85+
"""Validate optimization_leve."""
86+
if not 0 <= optimization_level <= SamplerOptions._MAX_OPTIMIZATION_LEVEL:
87+
raise ValueError(
88+
"Invalid optimization_level. Valid range is "
89+
f"0-{SamplerOptions._MAX_OPTIMIZATION_LEVEL}"
90+
)
91+
return optimization_level

qiskit_ibm_runtime/qiskit/primitives/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,4 @@
1414

1515
from .base_estimator import BaseEstimatorV2 # type: ignore
1616
from .base_primitive import BasePrimitiveOptions # type: ignore
17+
from .base_sampler import BaseSamplerV2 # type: ignore

0 commit comments

Comments
 (0)