tensorcircuit.interfaces.scipy#

Interface wraps quantum function as a scipy function for optimization

tensorcircuit.interfaces.scipy.scipy_interface(fun: Callable[[...], Any], shape: Optional[Tuple[int, ...]] = None, jit: bool = True, gradient: bool = True) → Callable[[...], Any]#

Convert fun into a scipy optimize interface compatible version

Example

n = 3

def f(param):
    c = tc.Circuit(n)
    for i in range(n):
        c.rx(i, theta=param[0, i])
        c.rz(i, theta=param[1, i])
    loss = c.expectation(
        [
            tc.gates.y(),
            [
                0,
            ],
        ]
    )
    return tc.backend.real(loss)

# A gradient-based optimization interface

f_scipy = tc.interfaces.scipy_optimize_interface(f, shape=[2, n])
r = optimize.minimize(f_scipy, np.zeros([2 * n]), method="L-BFGS-B", jac=True)

# A gradient-free optimization interface

f_scipy = tc.interfaces.scipy_optimize_interface(f, shape=[2, n], gradient=False)
r = optimize.minimize(f_scipy, np.zeros([2 * n]), method="COBYLA")
Parameters
  • fun (Callable[..., Any]) – The quantum function with scalar out that to be optimized

  • shape (Optional[Tuple[int, ...]], optional) – the shape of parameters that fun accepts, defaults to None

  • jit (bool, optional) – whether to jit fun, defaults to True

  • gradient (bool, optional) – whether using gradient-based or gradient free scipy optimize interface, defaults to True

Returns

The scipy interface compatible version of fun

Return type

Callable[…, Any]

tensorcircuit.interfaces.scipy.scipy_optimize_interface(fun: Callable[[...], Any], shape: Optional[Tuple[int, ...]] = None, jit: bool = True, gradient: bool = True) → Callable[[...], Any][source]#

Convert fun into a scipy optimize interface compatible version

Example

n = 3

def f(param):
    c = tc.Circuit(n)
    for i in range(n):
        c.rx(i, theta=param[0, i])
        c.rz(i, theta=param[1, i])
    loss = c.expectation(
        [
            tc.gates.y(),
            [
                0,
            ],
        ]
    )
    return tc.backend.real(loss)

# A gradient-based optimization interface

f_scipy = tc.interfaces.scipy_optimize_interface(f, shape=[2, n])
r = optimize.minimize(f_scipy, np.zeros([2 * n]), method="L-BFGS-B", jac=True)

# A gradient-free optimization interface

f_scipy = tc.interfaces.scipy_optimize_interface(f, shape=[2, n], gradient=False)
r = optimize.minimize(f_scipy, np.zeros([2 * n]), method="COBYLA")
Parameters
  • fun (Callable[..., Any]) – The quantum function with scalar out that to be optimized

  • shape (Optional[Tuple[int, ...]], optional) – the shape of parameters that fun accepts, defaults to None

  • jit (bool, optional) – whether to jit fun, defaults to True

  • gradient (bool, optional) – whether using gradient-based or gradient free scipy optimize interface, defaults to True

Returns

The scipy interface compatible version of fun

Return type

Callable[…, Any]