Skip to content

Python sdk

analyzer special

analysis_params

AnalysisOptionalDevicesParams (HardwareListParams) pydantic-model

Source code in classiq/interface/analyzer/analysis_params.py
class AnalysisOptionalDevicesParams(HardwareListParams):
    qubit_count: int = pydantic.Field(
        default=...,
        description="number of qubits in the data",
        ge=MIN_QUBITS,
        le=MAX_QUBITS,
    )
qubit_count: ConstrainedIntValue pydantic-field required

number of qubits in the data

ChemistryGenerationParams (BaseModel) pydantic-model

Source code in classiq/interface/analyzer/analysis_params.py
class ChemistryGenerationParams(pydantic.BaseModel):
    class Config:
        title = "Chemistry"

    molecule: MoleculeProblem = pydantic.Field(
        title="Molecule",
        default=...,
        description="The molecule to generate the VQE ansatz for",
    )
    optimizer_preferences: OptimizerPreferences = pydantic.Field(
        default=..., description="Execution options for the classical Optimizer"
    )

    def initial_point(self) -> Optional[numpy.ndarray]:
        if self.optimizer_preferences.initial_point is not None:
            return numpy.ndarray(
                self.optimizer_preferences.initial_point  # type: ignore[arg-type]
            )
        else:
            return None
molecule: MoleculeProblem pydantic-field required

The molecule to generate the VQE ansatz for

optimizer_preferences: OptimizerPreferences pydantic-field required

Execution options for the classical Optimizer

HardwareListParams (BaseModel) pydantic-model

Source code in classiq/interface/analyzer/analysis_params.py
class HardwareListParams(pydantic.BaseModel):
    devices: Optional[List[PydanticNonEmptyString]] = pydantic.Field(
        default=None, description="Devices"
    )
    providers: List[Provider]
    from_ide: bool = Field(default=False)

    @pydantic.validator("providers", always=True)
    def set_default_providers(
        cls, providers: Optional[List[AnalyzerProviderVendor]]
    ) -> List[AnalyzerProviderVendor]:
        if providers is None:
            providers = list(AnalyzerProviderVendor)
        return providers
devices: List[classiq.interface.helpers.custom_pydantic_types.ConstrainedStrValue] pydantic-field

Devices

HardwareParams (BaseModel) pydantic-model

Source code in classiq/interface/analyzer/analysis_params.py
class HardwareParams(pydantic.BaseModel):
    device: PydanticNonEmptyString = pydantic.Field(default=None, description="Devices")
    provider: AnalyzerProviderVendor
device: ConstrainedStrValue pydantic-field

Devices

LatexParams (AnalysisParams) pydantic-model

Source code in classiq/interface/analyzer/analysis_params.py
class LatexParams(AnalysisParams):
    gate_names: List[GateNamsMapping] = pydantic.Field(
        default=..., description="List of gate names as apper in the qasm"
    )
gate_names: List[classiq.interface.analyzer.analysis_params.GateNamsMapping] pydantic-field required

List of gate names as apper in the qasm

cytoscape_graph

CytoScapeEdge (BaseModel) pydantic-model

Source code in classiq/interface/analyzer/cytoscape_graph.py
class CytoScapeEdge(pydantic.BaseModel):
    data: CytoScapeEdgeData = pydantic.Field(
        default=..., description="Edge's Data, mainly the source and target of the Edge"
    )
data: CytoScapeEdgeData pydantic-field required

Edge's Data, mainly the source and target of the Edge

CytoScapeEdgeData (BaseModel) pydantic-model

Source code in classiq/interface/analyzer/cytoscape_graph.py
class CytoScapeEdgeData(pydantic.BaseModel):
    source: str = pydantic.Field(
        default=..., description="the Id of the Node that is the Source of the edge"
    )
    target: str = pydantic.Field(
        default=..., description="the Id of the Node that is the Target the edge"
    )
source: str pydantic-field required

the Id of the Node that is the Source of the edge

target: str pydantic-field required

the Id of the Node that is the Target the edge

CytoScapeGraph (BaseModel) pydantic-model

Source code in classiq/interface/analyzer/cytoscape_graph.py
class CytoScapeGraph(pydantic.BaseModel):
    nodes: List[CytoScapeNode] = pydantic.Field(
        default_factory=list,
        description="Nodes of the Graph",
    )
    edges: List[CytoScapeEdge] = pydantic.Field(
        default_factory=list,
        description="Edges of the Graph",
    )
edges: List[classiq.interface.analyzer.cytoscape_graph.CytoScapeEdge] pydantic-field

Edges of the Graph

nodes: List[classiq.interface.analyzer.cytoscape_graph.CytoScapeNode] pydantic-field

Nodes of the Graph

CytoScapeNode (BaseModel) pydantic-model

Source code in classiq/interface/analyzer/cytoscape_graph.py
class CytoScapeNode(pydantic.BaseModel):
    data: Dict[str, Any] = pydantic.Field(
        default=...,
        description="Data of the Node, such as label, and color, can be of free form",
    )
    position: Optional[CytoScapePosition] = pydantic.Field(
        default=..., description="Position of the Node to be rendered in Cytocape"
    )
data: Dict[str, Any] pydantic-field required

Data of the Node, such as label, and color, can be of free form

position: CytoScapePosition pydantic-field required

Position of the Node to be rendered in Cytocape

CytoScapePosition (BaseModel) pydantic-model

Source code in classiq/interface/analyzer/cytoscape_graph.py
class CytoScapePosition(pydantic.BaseModel):
    x: int = pydantic.Field(
        default=..., description="X coordinate in the Cytoscape View"
    )
    y: int = pydantic.Field(
        default=..., description="Y coordinate in the Cytoscape View"
    )
x: int pydantic-field required

X coordinate in the Cytoscape View

y: int pydantic-field required

Y coordinate in the Cytoscape View

HardwareConnectivityGraphResult (VersionedModel) pydantic-model

Source code in classiq/interface/analyzer/cytoscape_graph.py
class HardwareConnectivityGraphResult(VersionedModel):
    graph: Optional[CytoScapeGraph] = pydantic.Field(
        default=...,
        description="The Cytoscape graph in the desired Structure for the FE",
    )
    error: ConnectivityErrors = pydantic.Field(
        default=ConnectivityErrors.EMPTY,
        description="Any errors encountered while generating the graph",
    )
error: ConnectivityErrors pydantic-field

Any errors encountered while generating the graph

graph: CytoScapeGraph pydantic-field required

The Cytoscape graph in the desired Structure for the FE

__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

result

Analysis (VersionedModel) pydantic-model

Source code in classiq/interface/analyzer/result.py
class Analysis(VersionedModel):
    input_properties: QuantumCircuitProperties = pydantic.Field(
        default=..., description="Input circuit properties"
    )
    native_properties: NativeQuantumCircuitProperties = pydantic.Field(
        default=..., description="Transpiled circuit properties"
    )
input_properties: QuantumCircuitProperties pydantic-field required

Input circuit properties

native_properties: NativeQuantumCircuitProperties pydantic-field required

Transpiled circuit properties

__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

AvailableHardware (BaseModel) pydantic-model

Source code in classiq/interface/analyzer/result.py
class AvailableHardware(pydantic.BaseModel):
    ibm_quantum: Optional[Dict[PydanticNonEmptyString, bool]] = pydantic.Field(
        default=None,
        description="available IBM Quantum devices with boolean indicates if a given device has enough qubits.",
    )
    azure_quantum: Optional[Dict[PydanticNonEmptyString, bool]] = pydantic.Field(
        default=None,
        description="available Azure Quantum devices with boolean indicates if a given device has enough qubits.",
    )
    amazon_braket: Optional[Dict[PydanticNonEmptyString, bool]] = pydantic.Field(
        default=None,
        description="available Amazon Braket devices with boolean indicates if a given device has enough qubits.",
    )
amazon_braket: Dict[classiq.interface.helpers.custom_pydantic_types.ConstrainedStrValue, bool] pydantic-field

available Amazon Braket devices with boolean indicates if a given device has enough qubits.

azure_quantum: Dict[classiq.interface.helpers.custom_pydantic_types.ConstrainedStrValue, bool] pydantic-field

available Azure Quantum devices with boolean indicates if a given device has enough qubits.

ibm_quantum: Dict[classiq.interface.helpers.custom_pydantic_types.ConstrainedStrValue, bool] pydantic-field

available IBM Quantum devices with boolean indicates if a given device has enough qubits.

DevicesResult (VersionedModel) pydantic-model

Source code in classiq/interface/analyzer/result.py
class DevicesResult(VersionedModel):
    devices: AvailableHardware
    status: GraphStatus
__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

GraphResult (VersionedModel) pydantic-model

Source code in classiq/interface/analyzer/result.py
class GraphResult(VersionedModel):
    kind: Literal["graph"] = Field(default="graph")
    details: str
__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

HardwareComparisonData (VersionedModel) pydantic-model

Source code in classiq/interface/analyzer/result.py
class HardwareComparisonData(VersionedModel):
    kind: Literal["hardware_comparison"] = Field(default="hardware_comparison")
    data: List[SingleHardwareInformation]
__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

HardwareComparisonInformation (BaseModel) pydantic-model

Source code in classiq/interface/analyzer/result.py
class HardwareComparisonInformation(pydantic.BaseModel):
    devices: List[str] = pydantic.Field(
        default=..., description="Device which is used for the transpilation."
    )
    providers: List[str] = pydantic.Field(
        default=..., description="Provider cloud of the device."
    )
    depth: List[pydantic.NonNegativeInt] = pydantic.Field(
        default=..., description="Circuit depth."
    )
    multi_qubit_gate_count: List[pydantic.NonNegativeInt] = pydantic.Field(
        default=..., description="Number of multi qubit gates."
    )
    total_gate_count: List[pydantic.NonNegativeInt] = pydantic.Field(
        default=..., description="Number of total gates."
    )

    @pydantic.root_validator
    def validate_equal_length(cls, values: Dict[str, list]) -> Dict[str, list]:
        lengths = list(map(len, values.values()))
        if len(set(lengths)) != 1:
            raise ClassiqValueError("All lists should have the same length")
        return values
depth: List[pydantic.types.NonNegativeInt] pydantic-field required

Circuit depth.

devices: List[str] pydantic-field required

Device which is used for the transpilation.

multi_qubit_gate_count: List[pydantic.types.NonNegativeInt] pydantic-field required

Number of multi qubit gates.

providers: List[str] pydantic-field required

Provider cloud of the device.

total_gate_count: List[pydantic.types.NonNegativeInt] pydantic-field required

Number of total gates.

NativeQuantumCircuitProperties (QuantumCircuitProperties) pydantic-model

Source code in classiq/interface/analyzer/result.py
class NativeQuantumCircuitProperties(QuantumCircuitProperties):
    native_gates: Set[BasisGates] = pydantic.Field(
        default=..., description="Native gates used for decomposition"
    )
native_gates: Set[classiq.interface.analyzer.result.BasisGates] pydantic-field required

Native gates used for decomposition

QuantumCircuitProperties (BaseModel) pydantic-model

Source code in classiq/interface/analyzer/result.py
class QuantumCircuitProperties(pydantic.BaseModel):
    depth: pydantic.NonNegativeInt = pydantic.Field(
        default=..., description="Circuit depth"
    )
    auxiliary_qubits: pydantic.NonNegativeInt = pydantic.Field(
        default=..., description="Number of Auxiliary qubits"
    )
    classical_bits: pydantic.NonNegativeInt = pydantic.Field(
        default=..., description="Number of classical bits"
    )
    gates_count: pydantic.NonNegativeInt = pydantic.Field(
        default=..., description="Total number of gates in the circuit"
    )
    multi_qubit_gates_count: pydantic.NonNegativeInt = pydantic.Field(
        default=..., description="Number of multi-qubit gates in circuit"
    )
    non_entangled_subcircuits_count: pydantic.NonNegativeInt = pydantic.Field(
        default=..., description="Number of non-entangled sub-circuit "
    )
auxiliary_qubits: NonNegativeInt pydantic-field required

Number of Auxiliary qubits

classical_bits: NonNegativeInt pydantic-field required

Number of classical bits

depth: NonNegativeInt pydantic-field required

Circuit depth

gates_count: NonNegativeInt pydantic-field required

Total number of gates in the circuit

multi_qubit_gates_count: NonNegativeInt pydantic-field required

Number of multi-qubit gates in circuit

non_entangled_subcircuits_count: NonNegativeInt pydantic-field required

Number of non-entangled sub-circuit

RbResults (VersionedModel) pydantic-model

Source code in classiq/interface/analyzer/result.py
class RbResults(VersionedModel):
    mean_fidelity: float
    average_error: float
    A: float
    B: float
    success_probability: List[float]
    parameters_error: Tuple[float, ...]
__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

SingleHardwareInformation (BaseModel) pydantic-model

Source code in classiq/interface/analyzer/result.py
class SingleHardwareInformation(pydantic.BaseModel):
    devices: str = pydantic.Field(
        default=..., description="Device which is used for the transpilation."
    )
    providers: str = pydantic.Field(
        default=..., description="Provider cloud of the device."
    )
    depth: pydantic.NonNegativeInt = pydantic.Field(
        default=..., description="Circuit depth."
    )
    multi_qubit_gate_count: pydantic.NonNegativeInt = pydantic.Field(
        default=..., description="Number of multi qubit gates."
    )
    total_gate_count: pydantic.NonNegativeInt = pydantic.Field(
        default=..., description="Number of total gates."
    )
depth: NonNegativeInt pydantic-field required

Circuit depth.

devices: str pydantic-field required

Device which is used for the transpilation.

multi_qubit_gate_count: NonNegativeInt pydantic-field required

Number of multi qubit gates.

providers: str pydantic-field required

Provider cloud of the device.

total_gate_count: NonNegativeInt pydantic-field required

Number of total gates.

applications special

qsvm

QSVMData (VersionedModel) pydantic-model

Source code in classiq/interface/applications/qsvm.py
class QSVMData(VersionedModel):
    data: DataList
    labels: Optional[LabelsInt] = None
    internal_state: Optional[QSVMInternalState] = None

    class Config:
        smart_union = True
        extra = "forbid"

    @pydantic.validator("data", pre=True)
    def set_data(cls, data: Union[IterableType, ArrayLike]) -> list:
        return listify(data)

    @pydantic.validator("labels", pre=True)
    def set_labels(
        cls, labels: Optional[Union[IterableType, ArrayLike]]
    ) -> Optional[list]:
        if labels is None:
            return None
        else:
            return listify(labels)
__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

QSVMInternalState (VersionedModel) pydantic-model

Source code in classiq/interface/applications/qsvm.py
class QSVMInternalState(VersionedModel):
    underscore_sparse: bool
    class_weight: list
    classes: list
    underscore_gamma: float
    underscore_base_fit: list
    support: list
    support_vectors: list
    underscore_n_support: list
    dual_coef_2: list
    intercept: list
    underscore_p_a: list
    underscore_p_b: list
    fit_status: int
    shape_fit: Shape
    underscore_intercept: list
    dual_coef: list

    class_weight__shape: Shape
    classes__shape: Shape
    underscore_base_fit__shape: Shape
    support__shape: Shape
    support_vectors__shape: Shape
    underscore_n_support__shape: Shape
    dual_coef_2__shape: Shape
    intercept__shape: Shape
    underscore_p_a__shape: Shape
    underscore_p_b__shape: Shape
    underscore_intercept__shape: Shape
    dual_coef__shape: Shape

    set_class_weight = validate_array_to_list("class_weight")
    set_classes = validate_array_to_list("classes")
    set_underscore_base_fit = validate_array_to_list("underscore_base_fit")
    set_support = validate_array_to_list("support")
    set_support_vectors = validate_array_to_list("support_vectors")
    set_underscore_n_support = validate_array_to_list("underscore_n_support")
    set_dual_coef_2 = validate_array_to_list("dual_coef_2")
    set_intercept = validate_array_to_list("intercept")
    set_underscore_p_a = validate_array_to_list("underscore_p_a")
    set_underscore_p_b = validate_array_to_list("underscore_p_b")
    set_underscore_intercept = validate_array_to_list("underscore_intercept")
    set_dual_coef = validate_array_to_list("dual_coef")
__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

QSVMPredictResult (VersionedModel) pydantic-model

Source code in classiq/interface/applications/qsvm.py
class QSVMPredictResult(VersionedModel):
    data: list  # serialized np.array
__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

QSVMTestResult (VersionedModel) pydantic-model

Source code in classiq/interface/applications/qsvm.py
class QSVMTestResult(VersionedModel):
    data: float  # between 0 to 1
__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

ast_node

SourceReference (HashablePydanticBaseModel) pydantic-model

Source code in classiq/interface/ast_node.py
class SourceReference(HashablePydanticBaseModel):
    start_line: int
    start_column: int
    end_line: int
    end_column: int
    file_name: Optional[str] = pydantic.Field(default=None)

    def __str__(self) -> str:
        file_string = (
            f"file {os.path.basename(self.file_name)} " if self.file_name else ""
        )
        start_character_string = (
            f" character {self.start_column + 1}" if self.start_column > 0 else ""
        )
        return f"{file_string}line {self.start_line + 1}{start_character_string}"

__str__(self) special

Return str(self).

Source code in classiq/interface/ast_node.py
def __str__(self) -> str:
    file_string = (
        f"file {os.path.basename(self.file_name)} " if self.file_name else ""
    )
    start_character_string = (
        f" character {self.start_column + 1}" if self.start_column > 0 else ""
    )
    return f"{file_string}line {self.start_line + 1}{start_character_string}"

backend special

backend_preferences

AliceBobBackendPreferences (BackendPreferences) pydantic-model

Source code in classiq/interface/backend/backend_preferences.py
class AliceBobBackendPreferences(BackendPreferences):
    backend_service_provider: ProviderTypeVendor.ALICE_BOB
    distance: Optional[int] = pydantic.Field(
        default=None, description="Repetition code distance"
    )
    kappa_1: Optional[float] = pydantic.Field(
        default=None, description="One-photon dissipation rate (Hz)"
    )
    kappa_2: Optional[float] = pydantic.Field(
        default=None, description="Two-photon dissipation rate (Hz)"
    )
    average_nb_photons: Optional[float] = pydantic.Field(
        default=None, description="Average number of photons"
    )
    api_key: pydantic_backend.PydanticAliceBobApiKeyType = pydantic.Field(
        ..., description="AliceBob API key"
    )
    _parameters: Dict[str, Any] = PrivateAttr(default_factory=dict)

    @pydantic.root_validator(pre=True)
    def _set_backend_service_provider(cls, values: Dict[str, Any]) -> Dict[str, Any]:
        return values_with_discriminator(
            values, "backend_service_provider", ProviderVendor.ALICE_AND_BOB
        )

    @property
    def parameters(self) -> Dict[str, Any]:
        self._parameters = {
            "distance": self.distance,
            "kappa_1": self.kappa_1,
            "kappa_2": self.kappa_2,
            "average_nb_photons": self.average_nb_photons,
        }
        self._parameters = {k: v for k, v in self._parameters.items() if v is not None}
        return self._parameters
api_key: ConstrainedStrValue pydantic-field required

AliceBob API key

average_nb_photons: float pydantic-field

Average number of photons

distance: int pydantic-field

Repetition code distance

kappa_1: float pydantic-field

One-photon dissipation rate (Hz)

kappa_2: float pydantic-field

Two-photon dissipation rate (Hz)

AwsBackendPreferences (BackendPreferences) pydantic-model

Source code in classiq/interface/backend/backend_preferences.py
class AwsBackendPreferences(BackendPreferences):
    backend_service_provider: ProviderTypeVendor.AMAZON_BRAKET
    aws_role_arn: pydantic_backend.PydanticAwsRoleArn = pydantic.Field(
        description="ARN of the role to be assumed for execution on your Braket account."
    )
    s3_bucket_name: str = pydantic.Field(description="S3 Bucket Name")
    s3_folder: pydantic_backend.PydanticS3BucketKey = pydantic.Field(
        description="S3 Folder Path Within The S3 Bucket"
    )
    job_timeout: pydantic_backend.PydanticExecutionTimeout = pydantic.Field(
        description="Timeout for Jobs sent for execution in seconds.",
        default=AWS_DEFAULT_JOB_TIMEOUT_SECONDS,
    )

    @validator("s3_bucket_name")
    def _validate_s3_bucket_name(
        cls, s3_bucket_name: str, values: Dict[str, Any]
    ) -> str:
        s3_bucket_name = s3_bucket_name.strip()
        if not s3_bucket_name.startswith("amazon-braket-"):
            raise ClassiqValueError('S3 bucket name should start with "amazon-braket-"')
        return s3_bucket_name

    @pydantic.root_validator(pre=True)
    def _set_backend_service_provider(cls, values: Dict[str, Any]) -> Dict[str, Any]:
        return values_with_discriminator(
            values, "backend_service_provider", ProviderVendor.AMAZON_BRAKET
        )
aws_role_arn: ConstrainedStrValue pydantic-field required

ARN of the role to be assumed for execution on your Braket account.

job_timeout: ConstrainedIntValue pydantic-field

Timeout for Jobs sent for execution in seconds.

s3_bucket_name: str pydantic-field required

S3 Bucket Name

s3_folder: ConstrainedStrValue pydantic-field required

S3 Folder Path Within The S3 Bucket

AzureBackendPreferences (BackendPreferences) pydantic-model

Source code in classiq/interface/backend/backend_preferences.py
class AzureBackendPreferences(BackendPreferences):
    backend_service_provider: ProviderTypeVendor.AZURE_QUANTUM

    location: str = pydantic.Field(
        default="East US", description="Azure personal resource region"
    )

    credentials: Optional[AzureCredential] = pydantic.Field(
        default=None,
        description="The service principal credential to access personal quantum workspace",
    )

    @property
    def run_through_classiq(self) -> bool:
        return self.credentials is None

    @pydantic.root_validator(pre=True)
    def _set_backend_service_provider(cls, values: Dict[str, Any]) -> Dict[str, Any]:
        return values_with_discriminator(
            values, "backend_service_provider", ProviderVendor.AZURE_QUANTUM
        )
credentials: AzureCredential pydantic-field

The service principal credential to access personal quantum workspace

location: str pydantic-field

Azure personal resource region

AzureCredential (BaseSettings) pydantic-model

Source code in classiq/interface/backend/backend_preferences.py
class AzureCredential(pydantic.BaseSettings):
    tenant_id: str = pydantic.Field(description="Azure Tenant ID")
    client_id: str = pydantic.Field(description="Azure Client ID")
    client_secret: str = pydantic.Field(description="Azure Client Secret")
    resource_id: pydantic_backend.PydanticAzureResourceIDType = pydantic.Field(
        description="Azure Resource ID (including Azure subscription ID, resource "
        "group and workspace), for personal resource",
    )

    class Config:
        title = "Azure Service Principal Credential"
        env_prefix = "AZURE_"
        case_sensitive = False
client_id: str pydantic-field required

Azure Client ID

client_secret: str pydantic-field required

Azure Client Secret

resource_id: ConstrainedStrValue pydantic-field required

Azure Resource ID (including Azure subscription ID, resource group and workspace), for personal resource

tenant_id: str pydantic-field required

Azure Tenant ID

BackendPreferences (BaseModel) pydantic-model

Source code in classiq/interface/backend/backend_preferences.py
class BackendPreferences(BaseModel):
    # Due to the way the field is currently implemented, i.e. it redefined with different types
    # in the subclass, it shouldn't be dumped with exclude_unset. This causes this field not to appear.
    # For example: don't use obj.dict(exclude_unset=True).
    backend_service_provider: str = pydantic.Field(
        ..., description="Provider company or cloud for the requested backend."
    )
    backend_name: str = pydantic.Field(
        ..., description="Name of the requested backend or target."
    )

    @property
    def hw_provider(self) -> Provider:
        return Provider(self.backend_service_provider)

    @pydantic.validator("backend_service_provider", pre=True)
    def validate_backend_service_provider(
        cls, backend_service_provider: Any
    ) -> Provider:
        return validate_backend_service_provider(backend_service_provider)

    @classmethod
    def batch_preferences(
        cls, *, backend_names: Iterable[str], **kwargs: Any
    ) -> List[BackendPreferences]:
        return [cls(backend_name=name, **kwargs) for name in backend_names]

    def is_nvidia_backend(self) -> bool:
        return False
backend_name: str pydantic-field required

Name of the requested backend or target.

backend_service_provider: str pydantic-field required

Provider company or cloud for the requested backend.

IBMBackendPreferences (BackendPreferences) pydantic-model

Source code in classiq/interface/backend/backend_preferences.py
class IBMBackendPreferences(BackendPreferences):
    backend_service_provider: ProviderTypeVendor.IBM_QUANTUM
    access_token: Optional[str] = pydantic.Field(
        default=None,
        description="IBM Quantum access token to be used"
        " with IBM Quantum hosted backends",
    )
    provider: IBMBackendProvider = pydantic.Field(
        default_factory=IBMBackendProvider,
        description="Provider specs. for identifying a single IBM Quantum provider.",
    )

    @pydantic.root_validator(pre=True)
    def _set_backend_service_provider(cls, values: Dict[str, Any]) -> Dict[str, Any]:
        return values_with_discriminator(
            values, "backend_service_provider", ProviderVendor.IBM_QUANTUM
        )
access_token: str pydantic-field

IBM Quantum access token to be used with IBM Quantum hosted backends

provider: IBMBackendProvider pydantic-field

Provider specs. for identifying a single IBM Quantum provider.

IonqBackendPreferences (BackendPreferences) pydantic-model

Source code in classiq/interface/backend/backend_preferences.py
class IonqBackendPreferences(BackendPreferences):
    backend_service_provider: ProviderTypeVendor.IONQ
    api_key: pydantic_backend.PydanticIonQApiKeyType = pydantic.Field(
        ..., description="IonQ API key"
    )

    @pydantic.root_validator(pre=True)
    def _set_backend_service_provider(cls, values: Dict[str, Any]) -> Dict[str, Any]:
        return values_with_discriminator(
            values, "backend_service_provider", ProviderVendor.IONQ
        )
api_key: ConstrainedStrValue pydantic-field required

IonQ API key

OQCBackendPreferences (BackendPreferences) pydantic-model

Source code in classiq/interface/backend/backend_preferences.py
class OQCBackendPreferences(BackendPreferences):
    backend_service_provider: ProviderTypeVendor.OQC
    username: str = pydantic.Field(description="OQC username")
    password: str = pydantic.Field(description="OQC password")

    @pydantic.root_validator(pre=True)
    def _set_backend_service_provider(cls, values: Dict[str, Any]) -> Dict[str, Any]:
        return values_with_discriminator(
            values, "backend_service_provider", ProviderVendor.OQC
        )
password: str pydantic-field required

OQC password

username: str pydantic-field required

OQC username

chemistry special

fermionic_operator

FermionicOperator (HashablePydanticBaseModel) pydantic-model

Specification of a Fermionic operator. Input: List of ladder operators, each ladder operator is described by a tuple of its index and a character indicating if it's a creation ('+') or annihilation operator ('-').

Source code in classiq/interface/chemistry/fermionic_operator.py
class FermionicOperator(HashablePydanticBaseModel):
    """
    Specification of a Fermionic operator.
    Input:
    List of ladder operators, each ladder operator is described by a tuple of its
    index and a character indicating if it's a creation ('+') or annihilation operator ('-').
    """

    op_list: list = pydantic.Field(
        description=(
            "A list of tuples each containing an index and a character; for "
            "example [('+', 0), ('-', 1)]."
        ),
    )

    @staticmethod
    def _validate_single_op(op: tuple) -> LadderOperator:
        if not isinstance(op, tuple):
            try:  # type: ignore[unreachable] # it is reachable...
                op = tuple(op)
            except Exception as exc:
                raise ClassiqValueError("Ladder operator should be a tuple.") from exc
        if len(op) != 2:
            raise ClassiqValueError(
                "Ladder operator tuple should be of length two; for example ('+', 1)."
            )

        op_symbol = op[0]
        if op_symbol == "LadderOperator.PLUS":
            op_symbol = "+"
        elif op_symbol == "LadderOperator.MINUS":
            op_symbol = "-"
        if op_symbol not in ("+", "-"):
            raise ClassiqValueError(
                f"The first term in a ladder operator tuple indicates if its a raising "
                f"(LadderOperator.PLUS / '+') or lowering (LadderOperator.MINUS / '-') "
                f"operator. Received {op_symbol}"
            )
        op_index = op[1]
        if not isinstance(op_index, int):
            raise ClassiqValueError(
                "The second term in a ladder operator tuple indicates its index and should be of type int"
            )

        return (op_symbol, op_index)

    @pydantic.validator("op_list")
    def _validate_op_list(cls, op_list: list) -> list:
        return list(map(cls._validate_single_op, op_list))

    def __mul__(self, coeff: Union[float, int]) -> SummedFermionicOperator:
        if isinstance(coeff, (float, int)):
            return SummedFermionicOperator(op_list=[(self, float(coeff))])
        raise ClassiqValueError(
            "The coefficient multiplying Fermionic Operator should be of type float"
        )

    __rmul__ = __mul__

    def __add__(
        self, other: Union[SummedFermionicOperator, FermionicOperator]
    ) -> SummedFermionicOperator:
        if isinstance(other, SummedFermionicOperator):
            return SummedFermionicOperator(op_list=[(self, 1.0)] + other.op_list)
        elif isinstance(other, FermionicOperator):
            return SummedFermionicOperator(op_list=[(self, 1.0)] + [(other, 1.0)])
        raise ClassiqValueError(
            "FermionicOperator can be summed together only with type FermionicOperator or SummedFermionicOperator"
        )

    class Config:
        frozen = True

    @staticmethod
    def _to_ladder_op(char: str) -> str:
        return "a" + _SUPERSCRIPT_PLUS if char == "+" else "a"

    @staticmethod
    def _to_subscript(num: int) -> str:
        return "".join(_SUBSCRIPT_UNICODE_CHARS[digit] for digit in str(num))

    def __str__(self) -> str:
        return "".join(
            f"{self._to_ladder_op(char)}{self._to_subscript(index)}"
            for (char, index) in self.op_list
        )

    @property
    def all_indices(self) -> Set[int]:
        return {op[1] for op in self.op_list}
op_list: list pydantic-field required

A list of tuples each containing an index and a character; for example [('+', 0), ('-', 1)].

__str__(self) special

Return str(self).

Source code in classiq/interface/chemistry/fermionic_operator.py
def __str__(self) -> str:
    return "".join(
        f"{self._to_ladder_op(char)}{self._to_subscript(index)}"
        for (char, index) in self.op_list
    )

SummedFermionicOperator (HashablePydanticBaseModel) pydantic-model

Specification of a summed Fermionic operator. Input: List of fermionic operators tuples, The first term in the tuple is the FermionicOperator and the second term is its coefficient. For example: op1 = FermionicOperator(op_list=[('+', 0), ('-', 1)]) op2 = FermionicOperator(op_list=[('-', 0), ('-', 1)]) summed_operator = SummedFermionicOperator(op_list=[(op1, 0.2), (op2, 6.7)])

Source code in classiq/interface/chemistry/fermionic_operator.py
class SummedFermionicOperator(HashablePydanticBaseModel):
    """
    Specification of a summed Fermionic operator.
    Input:
    List of fermionic operators tuples, The first term in the tuple is the FermionicOperator and the second term is its coefficient.
    For example:
    op1 = FermionicOperator(op_list=[('+', 0), ('-', 1)])
    op2 = FermionicOperator(op_list=[('-', 0), ('-', 1)])
    summed_operator = SummedFermionicOperator(op_list=[(op1, 0.2), (op2, 6.7)])
    """

    op_list: list = pydantic.Field(
        description="A list of tuples each containing a FermionicOperator and a coefficient.",
    )

    class Config:
        frozen = True

    @staticmethod
    def _validate_single_op(op: tuple) -> FermionicOperatorTuple:
        # is it tuple - if not, convert to tuple
        if not isinstance(op, tuple):
            try:  # type: ignore[unreachable] # it is reachable...
                op = tuple(op)
            except Exception as exc:
                raise ClassiqValueError("Operator should be a tuple.") from exc
        if len(op) != 2:
            raise ClassiqValueError("Operator tuple should be of length two.")

        # is it FermionicOperator - if not, convert to FermionicOperator
        if not isinstance(op[0], FermionicOperator):
            try:
                op = (FermionicOperator(**op[0]), op[1])
            except Exception as exc:
                raise ClassiqValueError(
                    "The first term in the operator tuple should be an instance of the FermionicOperator class"
                ) from exc

        if not isinstance(op[1], float):
            raise ClassiqValueError(
                "The second term in the operator tuple indicates its coefficient and should be of type float"
            )

        return op  # type: ignore[return-value] # mypy thinks that it is `Tuple[Any, ...]`, though the asserts here tell otherwise..

    @pydantic.validator("op_list")
    def _validate_op_list(cls, op_list: list) -> list:
        return list(map(cls._validate_single_op, op_list))

    def __add__(
        self, other: Union[SummedFermionicOperator, FermionicOperator]
    ) -> SummedFermionicOperator:
        if isinstance(other, SummedFermionicOperator):
            return SummedFermionicOperator(op_list=self.op_list + other.op_list)
        elif isinstance(other, FermionicOperator):
            return SummedFermionicOperator(op_list=self.op_list + [(other, 1.0)])
        raise ClassiqValueError(
            "FermionicOperator can be summed together only with type FermionicOperator or SummedFermionicOperator"
        )

    def is_close(self, other: SummedFermionicOperator) -> bool:
        if not isinstance(other, SummedFermionicOperator):
            return False  # type: ignore[unreachable]

        if len(self.op_list) != len(other.op_list):
            return False

        for (op1, coeff1), (op2, coeff2) in zip(self.op_list, other.op_list):
            if op1 != op2 or not np.isclose(coeff1, coeff2):
                return False

        return True

    @property
    def _all_indices(self) -> Set[int]:
        return set(
            itertools.chain.from_iterable(op.all_indices for op, _ in self.op_list)
        )

    @property
    def num_qubits(self) -> int:
        return len(self._all_indices)

    def __str__(self) -> str:
        return " + \n".join(str(op[1]) + " * " + str(op[0]) for op in self.op_list)
op_list: list pydantic-field required

A list of tuples each containing a FermionicOperator and a coefficient.

__str__(self) special

Return str(self).

Source code in classiq/interface/chemistry/fermionic_operator.py
def __str__(self) -> str:
    return " + \n".join(str(op[1]) + " * " + str(op[0]) for op in self.op_list)

ground_state_problem

GroundStateProblem (HashablePydanticBaseModel) pydantic-model

Source code in classiq/interface/chemistry/ground_state_problem.py
class GroundStateProblem(HashablePydanticBaseModel):
    kind: str

    mapping: FermionMapping = pydantic.Field(
        default=FermionMapping.JORDAN_WIGNER,
        description="Fermionic mapping type",
        title="Fermion Mapping",
    )
    z2_symmetries: bool = pydantic.Field(
        default=False,
        description="whether to perform z2 symmetries reduction",
    )
    num_qubits: Optional[int] = pydantic.Field(default=None)

    @pydantic.validator("z2_symmetries")
    def _validate_z2_symmetries(
        cls, z2_symmetries: bool, values: Dict[str, Any]
    ) -> bool:
        if z2_symmetries and values.get("mapping") == FermionMapping.FAST_BRAVYI_KITAEV:
            raise ClassiqValueError(
                "z2 symmetries reduction can not be used for fast_bravyi_kitaev mapping"
            )
        return z2_symmetries

    class Config:
        frozen = True
mapping: FermionMapping pydantic-field

Fermionic mapping type

z2_symmetries: bool pydantic-field

whether to perform z2 symmetries reduction

HamiltonianProblem (GroundStateProblem) pydantic-model

Source code in classiq/interface/chemistry/ground_state_problem.py
class HamiltonianProblem(GroundStateProblem):
    kind: Literal["hamiltonian"] = pydantic.Field(default="hamiltonian")

    hamiltonian: SummedFermionicOperator = pydantic.Field(
        description="Hamiltonian as a fermionic operator"
    )
    num_particles: List[pydantic.PositiveInt] = pydantic.Field(
        description="Tuple containing the numbers of alpha particles and beta particles"
    )

    @pydantic.validator("num_particles")
    def _validate_num_particles(cls, num_particles: List[int]) -> List[int]:
        assert isinstance(num_particles, list)
        assert len(num_particles) == 2

        # This probably will never happen, since pydantic automatically converts
        #   floats to ints
        assert isinstance(num_particles[0], int)
        assert num_particles[0] >= 1

        assert isinstance(num_particles[1], int)
        assert num_particles[1] >= 1

        return num_particles
hamiltonian: SummedFermionicOperator pydantic-field required

Hamiltonian as a fermionic operator

num_particles: List[pydantic.types.PositiveInt] pydantic-field required

Tuple containing the numbers of alpha particles and beta particles

MoleculeProblem (GroundStateProblem) pydantic-model

Source code in classiq/interface/chemistry/ground_state_problem.py
class MoleculeProblem(GroundStateProblem):
    kind: Literal["molecule"] = pydantic.Field(default="molecule")

    molecule: Molecule
    basis: str = pydantic.Field(default="sto3g", description="Molecular basis set")
    freeze_core: bool = pydantic.Field(default=False)
    remove_orbitals: List[int] = pydantic.Field(
        default_factory=list, description="list of orbitals to remove"
    )
basis: str pydantic-field

Molecular basis set

remove_orbitals: List[int] pydantic-field

list of orbitals to remove

molecule

Atom (HashablePydanticBaseModel) pydantic-model

Source code in classiq/interface/chemistry/molecule.py
class Atom(HashablePydanticBaseModel):
    symbol: Literal[tuple(ELEMENTS)] = pydantic.Field(description="The atom symbol")  # type: ignore[valid-type]
    x: float = pydantic.Field(description="The x coordinate of the atom")
    y: float = pydantic.Field(description="The y coordinate of the atom")
    z: float = pydantic.Field(description="The z coordinate of the atom")
symbol: Literal['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', 'Ac', 'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf', 'Es', 'Fm', 'Md', 'No', 'Lr', 'Rf', 'Db', 'Sg', 'Bh', 'Hs', 'Mt', 'Ds', 'Rg', 'Cn', 'Nh', 'Fl', 'Mc', 'Lv', 'Ts', 'Og'] pydantic-field required

The atom symbol

x: float pydantic-field required

The x coordinate of the atom

y: float pydantic-field required

The y coordinate of the atom

z: float pydantic-field required

The z coordinate of the atom

Molecule (HashablePydanticBaseModel) pydantic-model

Source code in classiq/interface/chemistry/molecule.py
class Molecule(HashablePydanticBaseModel):
    atoms: List[Atom] = pydantic.Field(
        description="A list of atoms each containing the atoms symbol and  its (x,y,z) location",
        min_items=1,
    )
    spin: pydantic.NonNegativeInt = pydantic.Field(
        default=1, description="spin of the molecule"
    )
    charge: pydantic.NonNegativeInt = pydantic.Field(
        default=0, description="charge of the molecule"
    )

    @property
    def atoms_type(self) -> List[AtomType]:
        return [(atom.symbol, [atom.x, atom.y, atom.z]) for atom in self.atoms]

    @pydantic.validator("atoms", each_item=True, pre=True)
    def _validate_atoms(cls, atom: Union[AtomType, Atom]) -> Atom:
        if isinstance(atom, (list, tuple)):
            return cls._validate_old_atoms_type(atom)
        return atom

    @staticmethod
    def _validate_old_atoms_type(atom: AtomType) -> Atom:
        if len(atom) != 2:
            raise ClassiqValueError(
                "each atom should be a list of two entries: 1) name pf the elemnt (str) 2) list of its (x,y,z) location"
            )
        if not isinstance(atom[0], str):
            raise ClassiqValueError(
                f"atom name should be a string. unknown element: {atom[0]}."
            )
        if len(atom[1]) != 3:
            raise ClassiqValueError(
                f"location of the atom is of length three, representing the (x,y,z) coordinates of the atom, error value: {atom[1]}"
            )
        for idx in atom[1]:
            if not isinstance(idx, (float, int)):
                raise ClassiqValueError(
                    f"coordinates of the atom should be of type float. error value: {idx}"
                )
        symbol, coordinate = atom

        return Atom(symbol=symbol, x=coordinate[0], y=coordinate[1], z=coordinate[2])

    class Config:
        frozen = True
atoms: ConstrainedListValue pydantic-field required

A list of atoms each containing the atoms symbol and its (x,y,z) location

charge: NonNegativeInt pydantic-field

charge of the molecule

spin: NonNegativeInt pydantic-field

spin of the molecule

operator

PauliOperator (HashablePydanticBaseModel, VersionedModel) pydantic-model

Specification of a Pauli sum operator.

Source code in classiq/interface/chemistry/operator.py
class PauliOperator(HashablePydanticBaseModel, VersionedModel):
    """
    Specification of a Pauli sum operator.
    """

    pauli_list: PydanticPauliList = pydantic.Field(
        description="A list of tuples each containing a pauli string comprised of I,X,Y,Z characters and a complex coefficient; for example [('IZ', 0.1), ('XY', 0.2)].",
    )
    is_hermitian: bool = pydantic.Field(default=False)
    has_complex_coefficients: bool = pydantic.Field(default=True)

    def show(self) -> str:
        if self.is_hermitian:
            # If the operator is hermitian then the coefficients must be numeric
            return "\n".join(
                f"{summand[1].real:+.3f} * {summand[0]}" for summand in self.pauli_list  # type: ignore[union-attr]
            )
        return "\n".join(
            f"+({summand[1]:+.3f}) * {summand[0]}" for summand in self.pauli_list
        )

    @pydantic.validator("pauli_list", each_item=True, pre=True)
    def _validate_pauli_monomials(
        cls, monomial: Tuple[PydanticPauliMonomialStr, ParameterComplexType]
    ) -> Tuple[PydanticPauliMonomialStr, ParameterComplexType]:
        _PauliMonomialLengthValidator(  # type: ignore[call-arg]
            monomial=monomial
        )  # Validate the length of the monomial.
        coeff = cls._validate_monomial_coefficient(monomial[1])
        parsed_monomial = _PauliMonomialParser(string=monomial[0], coeff=coeff)  # type: ignore[call-arg]
        return (parsed_monomial.string, parsed_monomial.coeff)

    @staticmethod
    def _validate_monomial_coefficient(
        coeff: Union[sympy.Expr, ParameterComplexType]
    ) -> ParameterComplexType:
        if isinstance(coeff, str):
            validate_expression_str(coeff)
        elif isinstance(coeff, sympy.Expr):
            coeff = str(coeff)
        return coeff

    @pydantic.validator("pauli_list")
    def _validate_pauli_list(cls, pauli_list: PydanticPauliList) -> PydanticPauliList:
        if not all_equal(len(summand[0]) for summand in pauli_list):
            raise ClassiqValueError("Pauli strings have incompatible lengths.")
        return pauli_list

    @pydantic.root_validator
    def _validate_hermitianity(cls, values: Dict[str, Any]) -> Dict[str, Any]:
        pauli_list = values.get("pauli_list", [])
        if all(isinstance(summand[1], complex) for summand in pauli_list):
            values["is_hermitian"] = all(
                np.isclose(complex(summand[1]).real, summand[1])
                for summand in pauli_list
            )
        if values.get("is_hermitian", False):
            values["has_complex_coefficients"] = False
            values["pauli_list"] = [
                (summand[0], complex(summand[1].real)) for summand in pauli_list
            ]
        else:
            values["has_complex_coefficients"] = not all(
                np.isclose(complex(summand[1]).real, summand[1])
                for summand in pauli_list
                if isinstance(summand[1], complex)
            )
        return values

    def __mul__(self, coefficient: complex) -> "PauliOperator":
        multiplied_ising = [
            (monomial[0], self._multiply_monomial_coefficient(monomial[1], coefficient))
            for monomial in self.pauli_list
        ]
        return self.__class__(pauli_list=multiplied_ising)

    @staticmethod
    def _multiply_monomial_coefficient(
        monomial_coefficient: ParameterComplexType, coefficient: complex
    ) -> ParameterComplexType:
        if isinstance(monomial_coefficient, ParameterType):
            return str(sympy.sympify(monomial_coefficient) * coefficient)
        return monomial_coefficient * coefficient

    @property
    def is_commutative(self) -> bool:
        return all(
            self._is_sub_pauli_commutative(
                [summand[0][qubit_num] for summand in self.pauli_list]
            )
            for qubit_num in range(self.num_qubits)
        )

    @staticmethod
    def _is_sub_pauli_commutative(qubit_pauli_string: Union[List[str], str]) -> bool:
        unique_paulis = set(qubit_pauli_string) - {"I"}
        return len(unique_paulis) <= 1

    @property
    def num_qubits(self) -> int:
        return len(self.pauli_list[0][0])

    def to_matrix(self) -> np.ndarray:
        if not all(isinstance(summand[1], complex) for summand in self.pauli_list):
            raise ClassiqValueError(
                "Supporting only Hamiltonian with numeric coefficients."
            )
        return sum(
            cast(complex, summand[1]) * to_pauli_matrix(summand[0])
            for summand in self.pauli_list
        )  # type: ignore[return-value]

    @staticmethod
    def _extend_pauli_string(
        pauli_string: PydanticPauliMonomialStr, num_extra_qubits: int
    ) -> PydanticPauliMonomialStr:
        return "I" * num_extra_qubits + pauli_string

    def extend(self, num_extra_qubits: int) -> "PauliOperator":
        new_pauli_list = [
            (self._extend_pauli_string(pauli_string, num_extra_qubits), coeff)
            for (pauli_string, coeff) in self.pauli_list
        ]
        return self.copy(update={"pauli_list": new_pauli_list}, deep=True)

    @staticmethod
    def _reorder_pauli_string(
        pauli_string: PydanticPauliMonomialStr,
        order: Collection[int],
        new_num_qubits: int,
    ) -> PydanticPauliMonomialStr:
        reversed_pauli_string = pauli_string[::-1]
        reversed_new_pauli_string = ["I"] * new_num_qubits

        for logical_pos, actual_pos in enumerate(order):
            reversed_new_pauli_string[actual_pos] = reversed_pauli_string[logical_pos]

        return "".join(reversed(reversed_new_pauli_string))

    @staticmethod
    def _validate_reorder(
        order: Collection[int],
        num_qubits: int,
        num_extra_qubits: int,
    ) -> None:
        if num_extra_qubits < 0:
            raise ClassiqValueError("Number of extra qubits cannot be negative")

        if len(order) != num_qubits:
            raise ClassiqValueError("The qubits order doesn't match the Pauli operator")

        if len(order) != len(set(order)):
            raise ClassiqValueError("The qubits order is not one-to-one")

        if not all(pos < num_qubits + num_extra_qubits for pos in order):
            raise ClassiqValueError(
                "The qubits order contains qubits which do no exist"
            )

    @classmethod
    def reorder(
        cls,
        operator: "PauliOperator",
        order: Collection[int],
        num_extra_qubits: int = 0,
    ) -> "PauliOperator":
        cls._validate_reorder(order, operator.num_qubits, num_extra_qubits)

        new_num_qubits = operator.num_qubits + num_extra_qubits
        new_pauli_list = [
            (cls._reorder_pauli_string(pauli_string, order, new_num_qubits), coeff)
            for pauli_string, coeff in operator.pauli_list
        ]
        return cls(pauli_list=new_pauli_list)

    @classmethod
    def from_unzipped_lists(
        cls,
        operators: List[List[Pauli]],
        coefficients: Optional[List[complex]] = None,
    ) -> "PauliOperator":
        if coefficients is None:
            coefficients = [1] * len(operators)

        if len(operators) != len(coefficients):
            raise ClassiqValueError(
                f"The number of coefficients ({len(coefficients)}) must be equal to the number of pauli operators ({len(operators)})"
            )

        return cls(
            pauli_list=[
                (pauli_integers_to_str(op), coeff)
                for op, coeff in zip(operators, coefficients)
            ]
        )

    class Config:
        frozen = True
pauli_list: ConstrainedListValue pydantic-field required

A list of tuples each containing a pauli string comprised of I,X,Y,Z characters and a complex coefficient; for example [('IZ', 0.1), ('XY', 0.2)].

__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

PauliOperatorV1 (HashablePydanticBaseModel) pydantic-model

Specification of a Pauli sum operator.

Source code in classiq/interface/chemistry/operator.py
class PauliOperatorV1(HashablePydanticBaseModel):
    """
    Specification of a Pauli sum operator.
    """

    pauli_list: PydanticPauliList = pydantic.Field(
        description="A list of tuples each containing a pauli string comprised of I,X,Y,Z characters and a complex coefficient; for example [('IZ', 0.1), ('XY', 0.2)].",
    )
    is_hermitian: bool = pydantic.Field(default=False)
    has_complex_coefficients: bool = pydantic.Field(default=True)

    def show(self) -> str:
        if self.is_hermitian:
            # If the operator is hermitian then the coefficients must be numeric
            return "\n".join(
                f"{summand[1].real:+.3f} * {summand[0]}" for summand in self.pauli_list  # type: ignore[union-attr]
            )
        return "\n".join(
            f"+({summand[1]:+.3f}) * {summand[0]}" for summand in self.pauli_list
        )

    @pydantic.validator("pauli_list", each_item=True, pre=True)
    def _validate_pauli_monomials(
        cls, monomial: Tuple[PydanticPauliMonomialStr, ParameterComplexType]
    ) -> Tuple[PydanticPauliMonomialStr, ParameterComplexType]:
        _PauliMonomialLengthValidator(  # type: ignore[call-arg]
            monomial=monomial
        )  # Validate the length of the monomial.
        coeff = cls._validate_monomial_coefficient(monomial[1])
        parsed_monomial = _PauliMonomialParser(string=monomial[0], coeff=coeff)  # type: ignore[call-arg]
        return (parsed_monomial.string, parsed_monomial.coeff)

    @staticmethod
    def _validate_monomial_coefficient(
        coeff: Union[sympy.Expr, ParameterComplexType]
    ) -> ParameterComplexType:
        if isinstance(coeff, str):
            validate_expression_str(coeff)
        elif isinstance(coeff, sympy.Expr):
            coeff = str(coeff)
        return coeff

    @pydantic.validator("pauli_list")
    def _validate_pauli_list(cls, pauli_list: PydanticPauliList) -> PydanticPauliList:
        if not all_equal(len(summand[0]) for summand in pauli_list):
            raise ClassiqValueError("Pauli strings have incompatible lengths.")
        return pauli_list

    @pydantic.root_validator
    def _validate_hermitianity(cls, values: Dict[str, Any]) -> Dict[str, Any]:
        pauli_list = values.get("pauli_list", [])
        if all(isinstance(summand[1], complex) for summand in pauli_list):
            values["is_hermitian"] = all(
                np.isclose(complex(summand[1]).real, summand[1])
                for summand in pauli_list
            )
        if values.get("is_hermitian", False):
            values["has_complex_coefficients"] = False
            values["pauli_list"] = [
                (summand[0], complex(summand[1].real)) for summand in pauli_list
            ]
        else:
            values["has_complex_coefficients"] = not all(
                np.isclose(complex(summand[1]).real, summand[1])
                for summand in pauli_list
                if isinstance(summand[1], complex)
            )
        return values

    def __mul__(self, coefficient: complex) -> "PauliOperatorV1":
        multiplied_ising = [
            (monomial[0], self._multiply_monomial_coefficient(monomial[1], coefficient))
            for monomial in self.pauli_list
        ]
        return self.__class__(pauli_list=multiplied_ising)

    @staticmethod
    def _multiply_monomial_coefficient(
        monomial_coefficient: ParameterComplexType, coefficient: complex
    ) -> ParameterComplexType:
        if isinstance(monomial_coefficient, ParameterType):
            return str(sympy.sympify(monomial_coefficient) * coefficient)
        return monomial_coefficient * coefficient

    @property
    def is_commutative(self) -> bool:
        return all(
            self._is_sub_pauli_commutative(
                [summand[0][qubit_num] for summand in self.pauli_list]
            )
            for qubit_num in range(self.num_qubits)
        )

    @staticmethod
    def _is_sub_pauli_commutative(qubit_pauli_string: Union[List[str], str]) -> bool:
        unique_paulis = set(qubit_pauli_string) - {"I"}
        return len(unique_paulis) <= 1

    @property
    def num_qubits(self) -> int:
        return len(self.pauli_list[0][0])

    def to_matrix(self) -> np.ndarray:
        if not all(isinstance(summand[1], complex) for summand in self.pauli_list):
            raise ClassiqValueError(
                "Supporting only Hamiltonian with numeric coefficients."
            )
        return sum(
            cast(complex, summand[1]) * to_pauli_matrix(summand[0])
            for summand in self.pauli_list
        )  # type: ignore[return-value]

    @staticmethod
    def _extend_pauli_string(
        pauli_string: PydanticPauliMonomialStr, num_extra_qubits: int
    ) -> PydanticPauliMonomialStr:
        return "I" * num_extra_qubits + pauli_string

    def extend(self, num_extra_qubits: int) -> "PauliOperatorV1":
        new_pauli_list = [
            (self._extend_pauli_string(pauli_string, num_extra_qubits), coeff)
            for (pauli_string, coeff) in self.pauli_list
        ]
        return self.copy(update={"pauli_list": new_pauli_list}, deep=True)

    @staticmethod
    def _reorder_pauli_string(
        pauli_string: PydanticPauliMonomialStr,
        order: Collection[int],
        new_num_qubits: int,
    ) -> PydanticPauliMonomialStr:
        reversed_pauli_string = pauli_string[::-1]
        reversed_new_pauli_string = ["I"] * new_num_qubits

        for logical_pos, actual_pos in enumerate(order):
            reversed_new_pauli_string[actual_pos] = reversed_pauli_string[logical_pos]

        return "".join(reversed(reversed_new_pauli_string))

    @staticmethod
    def _validate_reorder(
        order: Collection[int],
        num_qubits: int,
        num_extra_qubits: int,
    ) -> None:
        if num_extra_qubits < 0:
            raise ClassiqValueError("Number of extra qubits cannot be negative")

        if len(order) != num_qubits:
            raise ClassiqValueError("The qubits order doesn't match the Pauli operator")

        if len(order) != len(set(order)):
            raise ClassiqValueError("The qubits order is not one-to-one")

        if not all(pos < num_qubits + num_extra_qubits for pos in order):
            raise ClassiqValueError(
                "The qubits order contains qubits which do no exist"
            )

    @classmethod
    def reorder(
        cls,
        operator: "PauliOperatorV1",
        order: Collection[int],
        num_extra_qubits: int = 0,
    ) -> "PauliOperatorV1":
        cls._validate_reorder(order, operator.num_qubits, num_extra_qubits)

        new_num_qubits = operator.num_qubits + num_extra_qubits
        new_pauli_list = [
            (cls._reorder_pauli_string(pauli_string, order, new_num_qubits), coeff)
            for pauli_string, coeff in operator.pauli_list
        ]
        return cls(pauli_list=new_pauli_list)

    @classmethod
    def from_unzipped_lists(
        cls,
        operators: List[List[Pauli]],
        coefficients: Optional[List[complex]] = None,
    ) -> "PauliOperatorV1":
        if coefficients is None:
            coefficients = [1] * len(operators)

        if len(operators) != len(coefficients):
            raise ClassiqValueError(
                f"The number of coefficients ({len(coefficients)}) must be equal to the number of pauli operators ({len(operators)})"
            )

        return cls(
            pauli_list=[
                (pauli_integers_to_str(op), coeff)
                for op, coeff in zip(operators, coefficients)
            ]
        )

    class Config:
        frozen = True
pauli_list: ConstrainedListValue pydantic-field required

A list of tuples each containing a pauli string comprised of I,X,Y,Z characters and a complex coefficient; for example [('IZ', 0.1), ('XY', 0.2)].

PauliOperators (VersionedModel) pydantic-model

Source code in classiq/interface/chemistry/operator.py
class PauliOperators(VersionedModel):
    operators: List[PauliOperator]
__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

combinatorial_optimization special

mht_qaoa_input

MhtQaoaInput (BaseModel) pydantic-model

Source code in classiq/interface/combinatorial_optimization/mht_qaoa_input.py
class MhtQaoaInput(BaseModel):
    reps: pydantic.PositiveInt = pydantic.Field(
        default=3, description="Number of QAOA layers."
    )
    plot_list: List[PlotData] = pydantic.Field(
        description="The list of (x,y,t) plots of the MHT problem."
    )
    misdetection_maximum_time_steps: pydantic.NonNegativeInt = pydantic.Field(
        default=0,
        description="The maximum number of time steps a target might be misdetected.",
    )
    penalty_energy: float = pydantic.Field(
        default=2,
        description="Penalty energy for invalid solutions. The value affects "
        "the converges rate. Small positive values are preferred",
    )
    three_local_coeff: float = pydantic.Field(
        default=0,
        description="Coefficient for the 3-local terms in the Hamiltonian. It is related to the angular acceleration.",
    )
    one_local_coeff: float = pydantic.Field(
        default=0, description="Coefficient for the 1-local terms in the Hamiltonian."
    )
    is_penalty: bool = pydantic.Field(
        default=True, description="Build Pubo using penalty terms"
    )
    max_velocity: float = pydantic.Field(
        default=0, description="Max allowed velocity for a segment"
    )

    def is_valid_cost(self, cost: float) -> bool:
        return True

    @pydantic.validator("plot_list")
    def round_plot_list_times_and_validate(
        cls, plot_list: List[PlotData]
    ) -> List[PlotData]:
        MhtQaoaInput._check_all_ids_are_distinct(plot_list)
        MhtQaoaInput._round_to_tolerance_decimals(plot_list)

        time_stamps = sorted({plot.t for plot in plot_list})
        time_diff_set = {
            np.round(time_stamps[i] - time_stamps[i - 1], decimals=_TOLERANCE_DECIMALS)
            for i in range(1, len(time_stamps))
        }

        if len(time_diff_set) != 1:
            raise ClassiqValueError(
                "The time difference between each time stamp is not equal"
            )

        return plot_list

    @staticmethod
    def _round_to_tolerance_decimals(plot_list: List[PlotData]) -> None:
        for plot in plot_list:
            plot.t = np.round(plot.t, decimals=_TOLERANCE_DECIMALS)

    @staticmethod
    def _check_all_ids_are_distinct(plot_list: List[PlotData]) -> None:
        if not more_itertools.all_unique(plot.plot_id for plot in plot_list):
            raise ClassiqValueError("Plot IDs should be unique.")
is_penalty: bool pydantic-field

Build Pubo using penalty terms

max_velocity: float pydantic-field

Max allowed velocity for a segment

misdetection_maximum_time_steps: NonNegativeInt pydantic-field

The maximum number of time steps a target might be misdetected.

one_local_coeff: float pydantic-field

Coefficient for the 1-local terms in the Hamiltonian.

penalty_energy: float pydantic-field

Penalty energy for invalid solutions. The value affects the converges rate. Small positive values are preferred

plot_list: List[classiq.interface.combinatorial_optimization.mht_qaoa_input.PlotData] pydantic-field required

The list of (x,y,t) plots of the MHT problem.

reps: PositiveInt pydantic-field

Number of QAOA layers.

three_local_coeff: float pydantic-field

Coefficient for the 3-local terms in the Hamiltonian. It is related to the angular acceleration.

PlotData (BaseModel) pydantic-model

Source code in classiq/interface/combinatorial_optimization/mht_qaoa_input.py
class PlotData(BaseModel):
    # We are currently ignoring units. This might need to be handled in the future
    x: float = pydantic.Field(description="The X coordinate of this plot")
    y: float = pydantic.Field(description="The Y coordinate of this plot")
    t: float = pydantic.Field(description="The time stamp of this plot")
    plot_id: pydantic.NonNegativeInt = pydantic.Field(
        description="The plot ID of this plot"
    )
plot_id: NonNegativeInt pydantic-field required

The plot ID of this plot

t: float pydantic-field required

The time stamp of this plot

x: float pydantic-field required

The X coordinate of this plot

y: float pydantic-field required

The Y coordinate of this plot

optimization_problem

MaxCutProblem (BaseModel) pydantic-model

Source code in classiq/interface/combinatorial_optimization/optimization_problem.py
class MaxCutProblem(BaseModel):
    qaoa_reps: pydantic.PositiveInt = pydantic.Field(
        default=1, description="Number of layers in qaoa ansatz."
    )
    optimizer_preferences: CombinatorialOptimizer = pydantic.Field(
        default_factory=CombinatorialOptimizer,
        description="preferences for the VQE execution",
    )
    serialized_graph: Dict[str, Any]
optimizer_preferences: CombinatorialOptimizer pydantic-field

preferences for the VQE execution

qaoa_reps: PositiveInt pydantic-field

Number of layers in qaoa ansatz.

result

AnglesResult (VersionedModel) pydantic-model

Source code in classiq/interface/combinatorial_optimization/result.py
class AnglesResult(VersionedModel):
    initial_point: List[float]
__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

PyomoObjectResult (VersionedModel) pydantic-model

Source code in classiq/interface/combinatorial_optimization/result.py
class PyomoObjectResult(VersionedModel):
    details: str
__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

execution special

result

ResourceEstimatorResult (VersionedModel) pydantic-model

Source code in classiq/interface/execution/result.py
class ResourceEstimatorResult(VersionedModel):
    report_json: str
__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

executor special

aws_execution_cost

ExecutionCostForTimePeriod (BaseModel) pydantic-model

Source code in classiq/interface/executor/aws_execution_cost.py
class ExecutionCostForTimePeriod(pydantic.BaseModel):
    start: date = pydantic.Field(
        description="The beginning of the time period for tasks usage and cost ("
        "inclusive).",
    )
    end: date = pydantic.Field(
        description="The end of the time period for tasks usage and cost (exclusive).",
    )
    granularity: Granularity = pydantic.Field(
        description="Either MONTHLY or DAILY, or HOURLY.", default=Granularity.daily
    )
    cost_scope: CostScope = pydantic.Field(
        description="Either user or organization", default=CostScope.user
    )

    class Config:
        json_encoders = {date: lambda v: v.strftime("%Y-%m-%d")}

    @validator("end")
    def date_order(cls, v: date, values: Dict[str, Any], **kwargs: Any) -> date:
        if "start" in values and v <= values["start"]:
            raise ClassiqValueError('"end" date should be after "start" date')
        return v
cost_scope: CostScope pydantic-field

Either user or organization

end: date pydantic-field required

The end of the time period for tasks usage and cost (exclusive).

granularity: Granularity pydantic-field

Either MONTHLY or DAILY, or HOURLY.

start: date pydantic-field required

The beginning of the time period for tasks usage and cost (inclusive).

__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

estimation

OperatorsEstimation (BaseModel) pydantic-model

Estimate the expectation value of a list of Pauli operators on a quantum state given by a quantum program.

Source code in classiq/interface/executor/estimation.py
class OperatorsEstimation(pydantic.BaseModel):
    """
    Estimate the expectation value of a list of Pauli operators on a quantum state given
    by a quantum program.
    """

    quantum_program: QuantumCode
    operators: PauliOperators

execution_preferences

ExecutionPreferences (BaseModel) pydantic-model

Source code in classiq/interface/executor/execution_preferences.py
class ExecutionPreferences(pydantic.BaseModel):
    timeout_sec: Optional[pydantic.PositiveInt] = pydantic.Field(
        default=None,
        description="If set, limits the execution runtime. Value is in seconds. "
        "Not supported on all platforms.",
    )
    noise_properties: Optional[NoiseProperties] = pydantic.Field(
        default=None, description="Properties of the noise in the circuit"
    )
    random_seed: int = pydantic.Field(
        default_factory=create_random_seed,
        description="The random seed used for the execution",
    )
    backend_preferences: BackendPreferencesTypes = backend_preferences_field(
        backend_name=ClassiqSimulatorBackendNames.SIMULATOR
    )
    num_shots: Optional[pydantic.PositiveInt] = pydantic.Field(default=None)
    transpile_to_hardware: TranspilationOption = pydantic.Field(
        default=TranspilationOption.DECOMPOSE,
        description="Transpile the circuit to the hardware basis gates before execution",
        title="Transpilation Option",
    )
    job_name: Optional[str] = pydantic.Field(
        min_length=1,
        description="The job name",
    )

    def __init__(self, **kwargs: Any) -> None:
        super().__init__(**kwargs)

    @pydantic.validator("backend_preferences", always=True)
    def validate_timeout_for_aws(
        cls, backend_preferences: BackendPreferencesTypes, values: Dict[str, Any]
    ) -> BackendPreferencesTypes:
        timeout = values.get("timeout_sec", None)
        if (
            not isinstance(backend_preferences, AwsBackendPreferences)
            or timeout is None
        ):
            return backend_preferences
        if (
            timeout != backend_preferences.job_timeout
            and backend_preferences.job_timeout != AWS_DEFAULT_JOB_TIMEOUT_SECONDS
        ):
            raise ClassiqValueError(DIFFERENT_TIMEOUT_MSG)
        if timeout > MAX_EXECUTION_TIMEOUT_SECONDS:
            raise ClassiqValueError(TIMEOUT_LARGE_FOR_AWS_MSG)

        backend_preferences.job_timeout = timeout
        return backend_preferences
backend_preferences: Union[classiq.interface.backend.backend_preferences.AzureBackendPreferences, classiq.interface.backend.backend_preferences.ClassiqBackendPreferences, classiq.interface.backend.backend_preferences.IBMBackendPreferences, classiq.interface.backend.backend_preferences.AwsBackendPreferences, classiq.interface.backend.backend_preferences.IonqBackendPreferences, classiq.interface.backend.backend_preferences.GCPBackendPreferences, classiq.interface.backend.backend_preferences.AliceBobBackendPreferences, classiq.interface.backend.backend_preferences.OQCBackendPreferences] pydantic-field

Preferences for the requested backend to run the quantum circuit.

job_name: ConstrainedStrValue pydantic-field

The job name

noise_properties: NoiseProperties pydantic-field

Properties of the noise in the circuit

random_seed: int pydantic-field

The random seed used for the execution

timeout_sec: PositiveInt pydantic-field

If set, limits the execution runtime. Value is in seconds. Not supported on all platforms.

transpile_to_hardware: TranspilationOption pydantic-field

Transpile the circuit to the hardware basis gates before execution

execution_request

ExecutionJobDetails (VersionedModel) pydantic-model

Source code in classiq/interface/executor/execution_request.py
class ExecutionJobDetails(VersionedModel):
    id: str

    name: Optional[str]
    start_time: datetime
    end_time: Optional[datetime]

    provider: Optional[str]
    backend_name: Optional[str]

    status: JobStatus

    num_shots: Optional[int]
    program_id: Optional[str]

    error: Optional[str]
__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

ExecutionJobsQueryResults (VersionedModel) pydantic-model

Source code in classiq/interface/executor/execution_request.py
class ExecutionJobsQueryResults(VersionedModel):
    results: List[ExecutionJobDetails]
__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

ExecutionRequest (BaseModel) pydantic-model

Source code in classiq/interface/executor/execution_request.py
class ExecutionRequest(BaseModel, json_encoders=CUSTOM_ENCODERS):
    execution_payload: ExecutionPayloads
    preferences: ExecutionPreferences = pydantic.Field(
        default_factory=ExecutionPreferences,
        description="preferences for the execution",
    )
preferences: ExecutionPreferences pydantic-field

preferences for the execution

__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

QuantumProgramExecution (QuantumProgram) pydantic-model

Source code in classiq/interface/executor/execution_request.py
class QuantumProgramExecution(QuantumProgram):
    execution_type: Literal["quantum_program2"] = "quantum_program2"
__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

QuantumProgramExecutionRequest (ExecutionRequest) pydantic-model

Source code in classiq/interface/executor/execution_request.py
class QuantumProgramExecutionRequest(ExecutionRequest):
    execution_payload: QuantumCodeExecution
__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

execution_result

ExecuteGeneratedCircuitResults (VersionedModel) pydantic-model

Source code in classiq/interface/executor/execution_result.py
class ExecuteGeneratedCircuitResults(VersionedModel):
    results: ResultsCollection
__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

iqae_result

IQAEResult (VersionedModel, QmodPyObject) pydantic-model

Source code in classiq/interface/executor/iqae_result.py
class IQAEResult(VersionedModel, QmodPyObject):
    estimation: float
    confidence_interval: Tuple[float, float]
    iterations_data: List[IQAEIterationData]
    warnings: List[str]
__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

optimizer_preferences

CombinatorialOptimizer (OptimizerPreferences) pydantic-model

Source code in classiq/interface/executor/optimizer_preferences.py
class CombinatorialOptimizer(OptimizerPreferences):
    cost_type: CostType = pydantic.Field(
        default=CostType.CVAR,
        description="Summarizing method of the measured bit strings",
    )
    alpha_cvar: Optional[PydanticAlphaParamCVAR] = pydantic.Field(
        default=None, description="Parameter for the CVAR summarizing method"
    )
    is_maximization: bool = pydantic.Field(
        default=False,
        description="Whether the optimization goal is to maximize",
    )
    should_check_valid_solutions: bool = pydantic.Field(
        default=False,
        description="Whether to check if all the solutions satisfy the constraints",
    )

    @pydantic.validator("alpha_cvar", pre=True, always=True)
    def check_alpha_cvar(
        cls, alpha_cvar: Optional[PydanticAlphaParamCVAR], values: Dict[str, Any]
    ) -> Optional[PydanticAlphaParamCVAR]:
        cost_type = values.get("cost_type")
        if alpha_cvar is not None and cost_type != CostType.CVAR:
            raise ClassiqValueError("Use CVAR params only for CostType.CVAR.")

        if alpha_cvar is None and cost_type == CostType.CVAR:
            alpha_cvar = PydanticAlphaParamCVAR(0.2)

        return alpha_cvar
alpha_cvar: PydanticAlphaParamCVAR pydantic-field

Parameter for the CVAR summarizing method

cost_type: CostType pydantic-field

Summarizing method of the measured bit strings

is_maximization: bool pydantic-field

Whether the optimization goal is to maximize

should_check_valid_solutions: bool pydantic-field

Whether to check if all the solutions satisfy the constraints

OptimizerPreferences (BaseModel) pydantic-model

Source code in classiq/interface/executor/optimizer_preferences.py
class OptimizerPreferences(BaseModel):
    name: OptimizerType = pydantic.Field(
        default=OptimizerType.COBYLA, description="Classical optimization algorithm."
    )
    num_shots: Optional[pydantic.PositiveInt] = pydantic.Field(
        default=None,
        description="Number of repetitions of the quantum ansatz.",
    )
    max_iteration: pydantic.PositiveInt = pydantic.Field(
        default=100, description="Maximal number of optimizer iterations"
    )
    tolerance: Optional[pydantic.PositiveFloat] = pydantic.Field(
        default=None, description="Final accuracy in the optimization"
    )
    step_size: Optional[pydantic.PositiveFloat] = pydantic.Field(
        default=None,
        description="step size for numerically " "calculating the gradient",
    )
    random_seed: Optional[int] = pydantic.Field(
        default=None,
        description="The random seed used for the generation",
    )
    initial_point: Optional[List[float]] = pydantic.Field(
        default=None,
        description="Initial values for the ansatz parameters",
    )
    skip_compute_variance: bool = pydantic.Field(
        default=False,
        description="If True, the optimizer will not compute the variance of the ansatz.",
    )

    @pydantic.validator("tolerance", pre=True, always=True)
    def check_tolerance(
        cls, tolerance: Optional[pydantic.PositiveFloat], values: Dict[str, Any]
    ) -> Optional[pydantic.PositiveFloat]:
        optimizer_type = values.get("type")
        if tolerance is not None and optimizer_type == OptimizerType.SPSA:
            raise ClassiqValueError("No tolerance param for SPSA optimizer")

        if tolerance is None and optimizer_type != OptimizerType.SPSA:
            tolerance = pydantic.PositiveFloat(0.001)

        return tolerance

    @pydantic.validator("step_size", pre=True, always=True)
    def check_step_size(
        cls, step_size: Optional[pydantic.PositiveFloat], values: Dict[str, Any]
    ) -> Optional[pydantic.PositiveFloat]:
        optimizer_type = values.get("name")
        if step_size is not None and optimizer_type not in (
            OptimizerType.L_BFGS_B,
            OptimizerType.ADAM,
        ):
            raise ClassiqValueError(
                "Use step_size only for L_BFGS_B or ADAM optimizers."
            )

        if step_size is None and optimizer_type in (
            OptimizerType.L_BFGS_B,
            OptimizerType.ADAM,
        ):
            step_size = pydantic.PositiveFloat(0.05)

        return step_size
initial_point: List[float] pydantic-field

Initial values for the ansatz parameters

max_iteration: PositiveInt pydantic-field

Maximal number of optimizer iterations

name: OptimizerType pydantic-field

Classical optimization algorithm.

num_shots: PositiveInt pydantic-field

Number of repetitions of the quantum ansatz.

random_seed: int pydantic-field

The random seed used for the generation

skip_compute_variance: bool pydantic-field

If True, the optimizer will not compute the variance of the ansatz.

step_size: PositiveFloat pydantic-field

step size for numerically calculating the gradient

tolerance: PositiveFloat pydantic-field

Final accuracy in the optimization

quantum_code

QuantumBaseCode (BaseModel) pydantic-model

Source code in classiq/interface/executor/quantum_code.py
class QuantumBaseCode(BaseModel):
    syntax: QuantumInstructionSet = pydantic.Field(
        default=QuantumInstructionSet.QASM, description="The syntax of the program."
    )
    code: CodeType = pydantic.Field(
        ..., description="The textual representation of the program"
    )

    @pydantic.validator("code")
    def load_quantum_program(
        cls, code: Union[CodeType, IonqQuantumCircuit], values: Dict[str, Any]
    ) -> CodeType:
        syntax = values.get("syntax")
        if isinstance(code, IonqQuantumCircuit):
            if syntax != QuantumInstructionSet.IONQ:
                raise ClassiqValueError(
                    f"Invalid code type {type(code)} for syntax: {syntax}"
                )
            return code.json()

        return code
code: str pydantic-field required

The textual representation of the program

syntax: QuantumInstructionSet pydantic-field

The syntax of the program.

QuantumCode (QuantumBaseCode) pydantic-model

Source code in classiq/interface/executor/quantum_code.py
class QuantumCode(QuantumBaseCode):
    arguments: MultipleArguments = pydantic.Field(
        default=(),
        description="The parameters dictionary for a parametrized quantum program.",
    )
    output_qubits_map: OutputQubitsMap = pydantic.Field(
        default_factory=dict,
        description="The map of outputs to their qubits in the circuit.",
    )
    registers_initialization: Optional[RegistersInitialization] = pydantic.Field(
        default_factory=None,
        description="Initial conditions for the different registers in the circuit.",
    )
    synthesis_execution_data: Optional[ExecutionData] = pydantic.Field(default=None)
    synthesis_execution_arguments: Arguments = pydantic.Field(default_factory=dict)

    class Config:
        validate_assignment = True

    @pydantic.validator("arguments")
    def validate_arguments(
        cls, arguments: MultipleArguments, values: Dict[str, Any]
    ) -> MultipleArguments:
        if arguments and values.get("syntax") not in (
            QuantumInstructionSet.QSHARP,
            QuantumInstructionSet.QASM,
        ):
            raise ClassiqValueError("Only QASM or Q# programs support arguments")

        if values.get("syntax") == QuantumInstructionSet.QSHARP and len(arguments) > 1:
            raise ClassiqValueError(
                f"Q# programs supports only one group of arguments. {len(arguments)} given"
            )

        return arguments

    @pydantic.validator("synthesis_execution_data")
    def validate_synthesis_execution_data(
        cls,
        synthesis_execution_data: Optional[ExecutionData],
        values: Dict[str, Any],
    ) -> Optional[ExecutionData]:
        if (
            synthesis_execution_data is not None
            and values.get("syntax") is not QuantumInstructionSet.QASM
        ):
            raise ClassiqValueError("Only QASM supports the requested configuration")

        return synthesis_execution_data

    @staticmethod
    def from_file(
        file_path: Union[str, Path],
        syntax: Optional[Union[str, QuantumInstructionSet]] = None,
        arguments: MultipleArguments = (),
    ) -> QuantumCode:
        path = Path(file_path)
        code = path.read_text()
        if syntax is None:
            syntax = QuantumInstructionSet.from_suffix(path.suffix.lstrip("."))
        return QuantumCode(syntax=syntax, code=code, arguments=arguments)
arguments: Tuple[Dict[classiq.interface.backend.pydantic_backend.ConstrainedStrValue, Any], ...] pydantic-field

The parameters dictionary for a parametrized quantum program.

output_qubits_map: Dict[str, Tuple[int, ...]] pydantic-field

The map of outputs to their qubits in the circuit.

registers_initialization: Dict[str, classiq.interface.executor.register_initialization.RegisterInitialization] pydantic-field

Initial conditions for the different registers in the circuit.

result

EstimationResult (BaseModel, QmodPyObject) pydantic-model

Source code in classiq/interface/executor/result.py
class EstimationResult(BaseModel, QmodPyObject):
    value: Complex = pydantic.Field(..., description="Estimation for the operator")
    variance: Complex = pydantic.Field(..., description="Variance of the estimation")
    metadata: EstimationMetadata = pydantic.Field(
        ..., description="Metadata for the estimation"
    )
metadata: EstimationMetadata pydantic-field required

Metadata for the estimation

value: Complex pydantic-field required

Estimation for the operator

variance: Complex pydantic-field required

Variance of the estimation

EstimationResults (VersionedModel) pydantic-model

Source code in classiq/interface/executor/result.py
class EstimationResults(VersionedModel):
    results: List[EstimationResult]

    def __len__(self) -> int:
        return len(self.results)

    def __iter__(self) -> Iterator[EstimationResult]:  # type: ignore[override]
        # TODO This is a bug waiting to happen. We change the meaning of
        # __iter__ in a derived class.
        return iter(self.results)

    def __getitem__(self, index: int) -> EstimationResult:
        return self.results[index]
__json_encoder__(obj) special staticmethod

partial(func, args, *keywords) - new function with partial application of the given arguments and keywords.

ExecutionDetails (BaseModel, QmodPyObject) pydantic-model

Source code in classiq/interface/executor/result.py
class ExecutionDetails(BaseModel, QmodPyObject):
    vendor_format_result: Dict[str, Any] = pydantic.Field(
        ..., description="Result in proprietary vendor format"
    )
    counts: Counts = pydantic.Field(
        default_factory=dict