> ## Documentation Index
> Fetch the complete documentation index at: https://docs.haiqu.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Variational

> Variational optimization endpoint. Creates a variational job.

Args:
    user (User): User authenticated with api key.
    data (VariationalProblemSubmitModel): Variational job arguments.
    db: Database.

Returns:
    VariationalJobModel: The new job object.



## OpenAPI

````yaml https://api.haiqu.ai/openapi.json post /variational
openapi: 3.1.0
info:
  title: Haiqu API
  summary: Haiqu RESTful API service.
  description: Cloud service providing the access to Haiqu cloud runtime
  contact:
    name: Haiqu Inc.
    url: https://haiqu.ai/
    email: info@haiqu.ai
  version: 1.4.0
servers: []
security: []
paths:
  /variational:
    post:
      summary: Variational
      description: |-
        Variational optimization endpoint. Creates a variational job.

        Args:
            user (User): User authenticated with api key.
            data (VariationalProblemSubmitModel): Variational job arguments.
            db: Database.

        Returns:
            VariationalJobModel: The new job object.
      operationId: variational_variational_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/VariationalProblemSubmitModel'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/VariationalJobModel'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
      security:
        - APIKeyQuery: []
        - APIKeyHeader: []
components:
  schemas:
    VariationalProblemSubmitModel:
      properties:
        experiment_id:
          type: string
          title: Experiment Id
        circuit_id:
          type: string
          title: Circuit Id
        observable:
          prefixItems:
            - items:
                type: string
              type: array
            - items:
                type: number
              type: array
          type: array
          maxItems: 2
          minItems: 2
          title: Observable
        shots:
          type: integer
          title: Shots
          default: 1000
        device_id:
          type: string
          title: Device Id
        options:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Options
        initial_parameters:
          anyOf:
            - items:
                type: number
              type: array
            - type: 'null'
          title: Initial Parameters
        optimizer_options:
          oneOf:
            - $ref: '#/components/schemas/NFTOptimizerOptions'
            - $ref: '#/components/schemas/ScipyOptimizerOptions'
          title: Optimizer Options
          discriminator:
            propertyName: type
            mapping:
              nft:
                $ref: '#/components/schemas/NFTOptimizerOptions'
              scipy:
                $ref: '#/components/schemas/ScipyOptimizerOptions'
        use_mitigation:
          type: boolean
          title: Use Mitigation
          default: false
        use_compression:
          type: boolean
          title: Use Compression
          default: false
        compression_options:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Compression Options
        name:
          anyOf:
            - type: string
            - type: 'null'
          title: Name
          default: ''
        description:
          anyOf:
            - type: string
            - type: 'null'
          title: Description
          default: ''
      type: object
      required:
        - experiment_id
        - circuit_id
        - observable
        - device_id
      title: VariationalProblemSubmitModel
      description: Submit model for variational problem execution.
    VariationalJobModel:
      properties:
        id:
          type: string
          title: Id
        name:
          anyOf:
            - type: string
            - type: 'null'
          title: Name
        description:
          anyOf:
            - type: string
            - type: 'null'
          title: Description
        user_id:
          type: integer
          title: User Id
        experiment_id:
          type: string
          title: Experiment Id
        status:
          $ref: '#/components/schemas/JobStatus'
        job_type:
          $ref: '#/components/schemas/JobType'
        device_id:
          type: string
          title: Device Id
        creation_date:
          type: string
          format: date-time
          title: Creation Date
        run_date:
          anyOf:
            - type: string
              format: date-time
            - type: 'null'
          title: Run Date
        finish_date:
          anyOf:
            - type: string
              format: date-time
            - type: 'null'
          title: Finish Date
        logs:
          anyOf:
            - type: string
            - type: 'null'
          title: Logs
        quality:
          anyOf:
            - type: number
            - type: 'null'
          title: Quality
        info:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Info
        time:
          anyOf:
            - type: number
            - type: 'null'
          title: Time
        parameters:
          anyOf:
            - additionalProperties: true
              type: object
            - items: {}
              type: array
            - type: 'null'
          title: Parameters
        circuit_id:
          type: string
          title: Circuit Id
        observable:
          prefixItems:
            - items:
                type: string
              type: array
            - items:
                type: number
              type: array
          type: array
          maxItems: 2
          minItems: 2
          title: Observable
        shots:
          type: integer
          title: Shots
        options:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Options
        optimizer_options:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Optimizer Options
        use_mitigation:
          type: boolean
          title: Use Mitigation
          default: false
        optimal_parameters:
          anyOf:
            - items:
                type: number
              type: array
            - type: 'null'
          title: Optimal Parameters
        min_loss:
          anyOf:
            - type: number
            - type: 'null'
          title: Min Loss
        loss_history:
          anyOf:
            - items:
                type: number
              type: array
            - type: 'null'
          title: Loss History
        weights_history:
          anyOf:
            - items:
                items:
                  type: number
                type: array
              type: array
            - type: 'null'
          title: Weights History
        compression_stats:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Compression Stats
      type: object
      required:
        - id
        - user_id
        - experiment_id
        - status
        - job_type
        - device_id
        - creation_date
        - circuit_id
        - observable
        - shots
      title: VariationalJobModel
      description: Job returned for variational problem execution.
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
      type: object
      title: HTTPValidationError
    NFTOptimizerOptions:
      properties:
        type:
          type: string
          const: nft
          title: Type
          default: nft
        randomized_order:
          type: boolean
          title: Randomized Order
          default: false
        reset_interval:
          type: integer
          title: Reset Interval
          default: 32
        maxfev:
          type: integer
          title: Maxfev
          default: 200
        maxiter:
          type: integer
          title: Maxiter
          default: 100
        eps:
          type: number
          title: Eps
          default: 1.e-32
      type: object
      title: NFTOptimizerOptions
      description: >-
        Configuration options for the NFT (Nakanishi-Fujii-Todo) optimizer.


        The NFT algorithm is a gradient-free optimizer designed for variational
        quantum

        algorithms. For detailed information about the algorithm, see the paper:

        https://arxiv.org/abs/1903.12166


        Preconditions:
            NFT requires the following conditions on the parameterized quantum circuit:

            1. Parameters must be independent: each parameter must appear in exactly one
               gate (no reusing the same parameter across multiple gates).

            2. Parameterized gates must be rotations of the form ``R_j(θ_j) = exp(-i*θ_j*A_j/2)``
               where ``A_j² = I`` (e.g., RX, RY, RZ gates satisfy this).

            3. The cost function must be a sum of expectation values of Hermitian operators:
               ``L(θ) = Σ_k w_k ⟨ψ_k|U†(θ) H_k U(θ)|ψ_k⟩``.

        Scaling:
            NFT updates one parameter at a time. Each full sweep through N parameters
            requires ≥2N function evaluations (depending on reset_interval).

        Args:
            randomized_order: If True, shuffles the order of parameters to update
                each lap (full sweep through all parameters). Default: False.
            reset_interval: How often to reset the recycled loss value.
                Set to 0 to disable resets. Default: 32.
            maxfev: Maximum number of function evaluations (circuit executions).
                Optimization stops when this limit is reached. Default: 200.
            maxiter: Maximum number of iterations (parameter updates). Default: 100.
            eps: Small epsilon value to avoid division by zero in the analytic
                solution. Default: 1e-32.

        Notes:
            Stopping criterion: Optimization stops when **either** maxfev or maxiter
            is reached, whichever comes first.

            Function evaluations per iteration: Each iteration uses 2-3 function
            evaluations. The very first iteration and the first iteration of each
            reset interval use 3 evaluations. Subsequent iterations reuse the
            previous optimal value, requiring only 2 evaluations.

            Result histories: ``job.result().loss_history`` and
            ``weights_history`` record one entry per NFT iteration (parameter
            update), not per circuit evaluation. History length therefore tracks
            ``maxiter``, not ``maxfev``.

        Example:
            >>> from haiqu.sdk.qml import NFTOptimizerOptions
            >>> optimizer = NFTOptimizerOptions(maxfev=500, maxiter=200)
    ScipyOptimizerOptions:
      properties:
        type:
          type: string
          const: scipy
          title: Type
          default: scipy
        method:
          type: string
          enum:
            - cobyla
            - nelder-mead
            - powell
            - cobyqa
          title: Method
        maxfev:
          type: integer
          title: Maxfev
          default: 200
        options:
          additionalProperties: true
          type: object
          title: Options
      type: object
      required:
        - method
      title: ScipyOptimizerOptions
      description: >-
        Configuration for any derivative-free ``scipy.optimize.minimize``
        method.


        The Haiqu backend wraps ``scipy.optimize.minimize`` for the four
        supported

        derivative-free methods. ``maxfev`` is the only option that is universal

        across all of them, so it gets a typed slot; everything else goes in the

        free-form ``options`` dict and is validated against a per-method
        whitelist

        at construction time, mirroring what ``scipy.optimize.minimize``
        accepts.


        Methods:
            - ``cobyla``: Constrained Optimization BY Linear Approximation. Trust-region
              method with linear surrogates; robust default on noisy expectation values.
            - ``nelder-mead``: Downhill simplex. No surrogate model; forgiving on noisy
              or non-smooth objectives but tends to need more evaluations.
            - ``powell``: Direction-set method that minimizes along conjugate directions;
              often fast on well-conditioned problems.
            - ``cobyqa``: COBYLA's quadratic-approximation successor; typically higher
              quality per evaluation than COBYLA at modest extra cost.

        Args:
            method: scipy method name. One of ``cobyla``, ``nelder-mead``, ``powell``, ``cobyqa``.
            maxfev: Maximum number of function evaluations (circuit executions).
                Default: 200. The Haiqu backend enforces this cap uniformly across
                methods even when scipy's native option name differs.
            options: Per-method options forwarded to ``scipy.optimize.minimize``.
                Allowed keys are validated at construction time; an unknown key raises
                ``ValueError``.

                Per-method allowed keys:

                - ``cobyla``: ``rhobeg``, ``tol``, ``maxiter``, ``catol``, ``disp``,
                  ``f_target``
                - ``nelder-mead``: ``xatol``, ``fatol``, ``adaptive``, ``maxiter``,
                  ``disp``
                - ``powell``: ``xtol``, ``ftol``, ``direc``, ``maxiter``, ``disp``
                - ``cobyqa``: ``rhobeg``, ``final_tr_radius``, ``maxiter``,
                  ``f_target``, ``disp``

                ``maxfev`` is intentionally excluded; pass it via the top-level field.
                ``maxiter`` is allowed for every method so scipy's own iteration /
                evaluation budget can be raised when it would otherwise stop before
                Haiqu's ``maxfev``.

        Notes:
            Final result selection: scipy methods can wander after they have found a
            good point. Haiqu therefore returns the best-so-far parameters tracked
            across the optimization, not the final scipy iterate.

            Result histories: ``job.result().loss_history`` and
            ``weights_history`` record one entry per objective / circuit
            evaluation, not per scipy iteration. Length is capped by ``maxfev`` and
            can exceed ``options["maxiter"]`` (e.g. Nelder–Mead / COBYQA init
            batches dump n+1 or 2n+1 entries on the first tick).

        Example:
            >>> from haiqu.sdk.qml import ScipyOptimizerOptions
            >>> ScipyOptimizerOptions(method="cobyla", maxfev=200, options={"rhobeg": 0.5})
            >>> ScipyOptimizerOptions(
            ...     method="cobyla",
            ...     maxfev=2000,
            ...     options={"rhobeg": 0.3, "tol": 1e-8, "maxiter": 2000},
            ... )
            >>> ScipyOptimizerOptions(method="powell", maxfev=500, options={"xtol": 1e-6})
            >>> ScipyOptimizerOptions(method="nelder-mead", options={"adaptive": True})
    JobStatus:
      type: string
      enum:
        - Submitted
        - Initializing
        - Queued
        - Validating
        - Running
        - Cancelled
        - Done
        - Error
      title: JobStatus
      description: Class for job status.
    JobType:
      type: string
      enum:
        - User local job
        - Analytics
        - Device specific analytics
        - Data Loading
        - Hybrid
        - Run
        - State Compression
        - Transpilation
        - Variational
        - Pretraining
        - SKQD
      title: JobType
      description: Class for job types.
    ValidationError:
      properties:
        loc:
          items:
            anyOf:
              - type: string
              - type: integer
          type: array
          title: Location
        msg:
          type: string
          title: Message
        type:
          type: string
          title: Error Type
      type: object
      required:
        - loc
        - msg
        - type
      title: ValidationError
  securitySchemes:
    APIKeyQuery:
      type: apiKey
      in: query
      name: HAIQU_API_KEY
    APIKeyHeader:
      type: apiKey
      in: header
      name: authorization

````