### Install SKLearn and Requests Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/sklearn_svc.html Installs the necessary libraries for the tutorial. Ensure you have scikit-learn and requests installed before proceeding. ```bash pip install scikit-learn requests ``` -------------------------------- ### Navigate to Examples Directory Source: https://tensorcircuit.readthedocs.io/en/latest/contribs/development_windows.html Change the current directory to 'examples' within the Docker container to access the provided scripts. ```bash cd examples ``` -------------------------------- ### Setup Backend and Imports Source: https://tensorcircuit.readthedocs.io/en/latest/whitepaper/5-density-matrix.html Imports necessary libraries and sets the backend for TensorCircuit. This is a common setup for most TensorCircuit simulations. ```python import numpy as np import tensorcircuit as tc K = tc.set_backend("tensorflow") ``` -------------------------------- ### Install Docker Desktop from Command Line Source: https://tensorcircuit.readthedocs.io/en/latest/contribs/development_windows.html Use this command to install Docker Desktop silently from the command line after downloading the installer. ```bash "Docker Desktop Installer.exe" install ``` -------------------------------- ### Install Dependencies Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/vqe_h2o.html Install the necessary libraries for generating fermionic and qubit Hamiltonians. This includes openfermion and openfermionpyscf. ```bash pip install openfermion openfermionpyscf ``` -------------------------------- ### Setup Imports and Backend Configuration Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/torch_qml.html Imports necessary libraries and sets the backend for TensorCircuit. This setup is required before defining quantum circuits or interfaces. ```python import time import numpy as np import tensorflow as tf import torch import tensorcircuit as tc K = tc.set_backend("tensorflow") # Use TensorFlow as the backend, while wrapping the quantum function in the PyTorch interface ``` -------------------------------- ### Install TensorCircuit (Linux x86) Source: https://tensorcircuit.readthedocs.io/en/latest/quickstart.html Use this command for a standard installation on Linux x86 systems. Ensure you have pip installed. ```bash pip install tensorcircuit ``` -------------------------------- ### Example: Setting Dense Layer Weights Source: https://tensorcircuit.readthedocs.io/en/latest/api/applications/van.html Demonstrates how to set the weights of a Dense layer using NumPy arrays obtained from another Dense layer. This involves getting weights from one layer and setting them to another. ```python >>> layer_a = tf.keras.layers.Dense(1, ... kernel_initializer=tf.constant_initializer(1.)) >>> a_out = layer_a(tf.convert_to_tensor([[1., 2., 3.]])) >>> layer_a.get_weights() [array([[1.], [1.], [1.]], dtype=float32), array([0.], dtype=float32)] >>> layer_b = tf.keras.layers.Dense(1, ... kernel_initializer=tf.constant_initializer(2.)) >>> b_out = layer_b(tf.convert_to_tensor([[10., 20., 30.]])) >>> layer_b.get_weights() [array([[2.], [2.], [2.]], dtype=float32), array([0.], dtype=float32)] >>> layer_b.set_weights(layer_a.get_weights()) >>> layer_b.get_weights() [array([[1.], [1.], ``` -------------------------------- ### Install TensorCircuit Nightly Build Source: https://tensorcircuit.readthedocs.io/en/latest/quickstart.html To install the latest nightly build, first uninstall the stable version, then install the nightly package. ```bash pip uninstall tensorcircuit ``` ```bash pip install tensorcircuit-nightly ``` -------------------------------- ### tensorcircuit.about.about() Source: https://tensorcircuit.readthedocs.io/en/latest/api/about.html Prints the information for tensorcircuit installation and environment. ```APIDOC ## tensorcircuit.about.about() ### Description Prints the information for tensorcircuit installation and environment. ### Method Call ### Endpoint N/A ### Parameters None ### Request Example ```python import tensorcircuit tensorcircuit.about.about() ``` ### Response None (prints to console) ``` -------------------------------- ### Setup and Imports for Classical Shadows Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/classical_shadows.html Imports necessary libraries and sets the backend and data type for TensorCircuit operations. This setup is required before implementing classical shadows. ```python import tensorcircuit as tc from tensorcircuit import shadows import numpy as np from functools import partial import time import matplotlib.pyplot as plt tc.set_backend("jax") tc.set_dtype("complex128") ``` -------------------------------- ### Minimal VMAP Example Source: https://tensorcircuit.readthedocs.io/en/latest/whitepaper/6-3-vmap.html This snippet shows a minimal example of VMAP usage. It demonstrates the output format for complex numbers. ```python 1.4287995e-08-9.5050003e-09j, -7.1439974e-09-6.5384995e-09j, -2.3792996e-08-7.8779987e-09j]]], dtype=complex64)>) ``` -------------------------------- ### Install Tensorcircuit Source: https://tensorcircuit.readthedocs.io/en/latest/contribs/development_Mac.html Installs the Tensorcircuit Python package using pip. ```bash pip install tensorcircuit ``` -------------------------------- ### Install Docker Desktop with Windows Command Prompt Source: https://tensorcircuit.readthedocs.io/en/latest/contribs/development_windows.html This command is used to install Docker Desktop when using the Windows Command Prompt. ```cmd start /w "" "Docker Desktop Installer.exe" install ``` -------------------------------- ### Install TensorCircuit in Develop Mode Source: https://tensorcircuit.readthedocs.io/en/latest/contribution.html Install your local fork of TensorCircuit in develop mode to immediately test code modifications. ```bash python setup.py develop ``` -------------------------------- ### Install Development Dependencies Source: https://tensorcircuit.readthedocs.io/en/latest/contribution.html Install the necessary Python packages for local development, including core requirements and development-specific tools. ```bash pip install -r requirements/requirements.txt pip install -r requirements/requirements-dev.txt ``` -------------------------------- ### Run Noisy QML Example Source: https://tensorcircuit.readthedocs.io/en/latest/contribs/development_windows.html Execute the 'noisy_qml.py' script using Python to observe its output. This is an example of running a TensorCircuit script within the Docker environment. ```python python noisy_qml.py ``` -------------------------------- ### Install Python Package Source: https://tensorcircuit.readthedocs.io/en/latest/contribs/development_Mac.html Use this command to install various Python packages, including TensorCircuit backends like Jax and PyTorch. ```bash pip install [Package Name] ``` -------------------------------- ### Example of eigsh_lanczos with JIT compilation Source: https://tensorcircuit.readthedocs.io/en/latest/api/backends/jax_backend.html Demonstrates how to use eigsh_lanczos with JAX. The first example shows efficient JIT compilation when the linear operator A remains constant across iterations. The second example illustrates inefficient JIT compilation when A changes in each iteration, leading to performance degradation. ```python import jax import numpy as np def A(H,x): return jax.np.dot(H,x) for n in range(100): H = jax.np.array(np.random.rand(10,10)) x = jax.np.array(np.random.rand(10,10)) res = eigsh_lanczos(A, [H],x) #jitting is triggerd only at n=0 ``` ```python import jax import numpy as np for n in range(100): def A(H,x): return jax.np.dot(H,x) H = jax.np.array(np.random.rand(10,10)) x = jax.np.array(np.random.rand(10,10)) res = eigsh_lanczos(A, [H],x) #jitting is triggerd at every step n ``` -------------------------------- ### Example of JIT compilation with eigsh (jit once) Source: https://tensorcircuit.readthedocs.io/en/latest/api/backends/jax_backend.html This example illustrates the use of the `eigsh` function with JAX's JIT compilation. JIT compilation is invoked only once at the start, as the Python ID of the matrix-vector product function `A` is consistent throughout the loop. ```python import jax import numpy as np def A(H,x): return jax.np.dot(H,x) for n in range(100): H = jax.np.array(np.random.rand(10,10)) x = jax.np.array(np.random.rand(10,10)) res = eigsh(A, [H],x) #jitting is triggerd only at n=0 ``` -------------------------------- ### Setup for Quantum Dropout Tutorial Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/qaoa_quantum_dropout.html Imports necessary libraries and sets up backend and parameters for the QAOA and quantum dropout simulation. Includes setting the number of layers, circuits, and dropout ratio. ```python import tensorcircuit as tc import optax import jax.numpy as jnp import tensorflow as tf import networkx as nx import matplotlib.pyplot as plt import numpy as np from functools import partial from IPython.display import clear_output import random K = tc.set_backend("jax") nlayers = 30 # the number of layers ncircuits = 6 # six circuits with different initial parameters are going to be optimized at the same time R = 0.5 # dropout ratio, 0 means no dropout, 1 means all dropout ``` -------------------------------- ### Get Logical-Physical Mapping from Qiskit Source: https://tensorcircuit.readthedocs.io/en/latest/_modules/tensorcircuit/compiler/qiskit_compiler.html Determines the logical-to-physical qubit mapping by comparing a Qiskit QuantumCircuit before and after compilation. If the 'before' circuit is not provided, it assumes a default 'measure(q, q)' setup. ```python def _get_logical_physical_mapping_from_qiskit( qc_after: Any, qc_before: Any = None ) -> Dict[int, int]: """ get ``logical_physical_mapping`` from qiskit Circuit by comparing the circuit after and before compiling :param qc_after: qiskit ``QuantumCircuit`` after compiling :type qc_after: Any :param qc_before: qiskit ``QuantumCircuit`` before compiling, if None, measure(q, q) is assumed :type qc_before: Any :return: logical_physical_mapping :rtype: Dict[int, int] """ logical_physical_mapping = {} for inst in qc_after.data: if inst[0].name == "measure": if qc_before is None: logical_q = qc_after.find_bit(inst[2][0]).index else: for instb in qc_before.data: if ( instb[0].name == "measure" and qc_before.find_bit(instb[2][0]).index == qc_after.find_bit(inst[2][0]).index ): logical_q = qc_before.find_bit(instb[1][0]).index break logical_physical_mapping[logical_q] = qc_after.find_bit(inst[1][0]).index return logical_physical_mapping ``` -------------------------------- ### JIT Compilation and Gradient Calculation Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/circuit_basics.html JIT compiles a function for acceleration. The first run may be slow, but subsequent evaluations are fast. This example shows how to get both the value and gradient of an energy function. ```python energy_vag_jit = K.jit(K.value_and_grad(energy)) print(energy_vag_jit(params)) ``` -------------------------------- ### Get Layer Weights Example Source: https://tensorcircuit.readthedocs.io/en/latest/api/keras.html Demonstrates how to retrieve the weights of a Keras layer and set the weights of another layer using the retrieved values. This is useful for transferring learned parameters between models or layers. ```python >>> layer_a = tf.keras.layers.Dense(1, ... kernel_initializer=tf.constant_initializer(1.)) >>> a_out = layer_a(tf.convert_to_tensor([[1., 2., 3.]])) >>> layer_a.get_weights() [array([[1.], [1.], [1.]], dtype=float32), array([0.], dtype=float32)] >>> layer_b = tf.keras.layers.Dense(1, ... kernel_initializer=tf.constant_initializer(2.)) >>> b_out = layer_b(tf.convert_to_tensor([[10., 20., 30.]])) >>> layer_b.get_weights() [array([[2.], [2.], [2.]], dtype=float32), array([0.], dtype=float32)] >>> layer_b.set_weights(layer_a.get_weights()) >>> layer_b.get_weights() [array([[1.], [1.], [1.]], dtype=float32), array([0.], dtype=float32)] ``` -------------------------------- ### Setup and Backend Configuration Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/qaoa_bo.html Imports necessary libraries and configures the TensorCircuit backend with JAX, sets data types, and initializes the cotengra optimizer for efficient tensor network contraction. It also sets up the device for computation. ```python import tensorcircuit as tc from jax import numpy as jnp import optax import torch import networkx as nx import matplotlib.pyplot as plt import numpy as np import cotengra as ctg from typing import Union import time import odbo from IPython.display import clear_output K = tc.set_backend("jax") tc.set_dtype("complex128") dtype = torch.float64 # cotengra package to speed up the calculation opt_ctg = ctg.ReusableHyperOptimizer( methods=["greedy", "kahypar"], parallel=True, minimize="combo", max_time=20, max_repeats=128, progbar=True, ) tc.set_contractor("custom", optimizer=opt_ctg, preprocessing=True) nlayers = 10 device = torch.device("cuda" if torch.cuda.is_available() else "cpu") acqfn = "ucb" ``` -------------------------------- ### Generate Heisenberg Hamiltonian Source: https://tensorcircuit.readthedocs.io/en/latest/_modules/tensorcircuit/quantum.html Generates a Heisenberg Hamiltonian with optional external fields (ZZ, XX, YY, Z, X, Y couplings). Requires TensorFlow to be installed. The example shows how to generate a Hamiltonian for a 1D line graph and extract its eigenvalues. ```python def heisenberg_hamiltonian( g: Graph, hzz: float = 1.0, hxx: float = 1.0, hyy: float = 1.0, hz: float = 0.0, hx: float = 0.0, hy: float = 0.0, sparse: bool = True, numpy: bool = False, ) -> Tensor: """ Generate Heisenberg Hamiltonian with possible external fields. Currently requires tensorflow installed :Example: >>> g = tc.templates.graphs.Line1D(6) >>> h = qu.heisenberg_hamiltonian(g, sparse=False) >>> tc.backend.eigh(h)[0][:10] array([-11.2111025, -8.4721365, -8.472136 , -8.472136 , -6. , -5.123106 , -5.123106 , -5.1231055, -5.1231055, -5.1231055], dtype=float32) :param g: input circuit graph :type g: Graph :param hzz: zz coupling, default is 1.0 :type hzz: float :param hxx: xx coupling, default is 1.0 :type hxx: float :param hyy: yy coupling, default is 1.0 :type hyy: float :param hz: External field on z direction, default is 0.0 :type hz: float ``` -------------------------------- ### QAOA Solver Setup Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/qubo_problem.html Initializes parameters for the QAOA solver, including the number of layers and iterations. A callback function is defined to record the loss during training. ```python iterations = 500 nlayers = 2 loss_list = [] def record_loss(loss, params): loss_list.append(loss) ``` -------------------------------- ### Install Miniconda for Tensorflow Source: https://tensorcircuit.readthedocs.io/en/latest/contribs/development_Mac.html Installs Miniconda, which is recommended for installing Tensorflow optimized for MacOS (tensorflow-macos) or with GPU acceleration (tensorflow-metal). This script downloads and installs Miniconda, then activates the environment and installs Tensorflow dependencies. ```bash curl -o ~/miniconda.sh https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-arm64.sh bash ~/miniconda.sh -b -p $HOME/miniconda source ~/miniconda/bin/activate conda install -c apple tensorflow-deps ``` -------------------------------- ### Setup Backend and Gates Source: https://tensorcircuit.readthedocs.io/en/latest/whitepaper/6-2-pauli-string-expectation.html Initializes the backend (TensorFlow or JAX) and imports necessary libraries. It also defines the `xx` gate matrix used in the ansatz circuit. ```python import time from functools import partial import numpy as np import tensorflow as tf import tensornetwork as tn import optax import tensorcircuit as tc K = tc.set_backend("tensorflow") xx = tc.gates._xx_matrix # xx gate matrix to be utilized ``` -------------------------------- ### Setup and Imports for QAOA Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/qubo_problem.html Imports necessary libraries and sets up the backend for TensorCircuit. Ensures reproducibility by setting random seeds and specifying data types. ```python import tensorcircuit as tc import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import time from tensorcircuit.applications.optimization import ( QUBO_QAOA, QUBO_QAOA_cvar, cvar_loss, ) from tensorcircuit.templates.ansatz import QAOA_ansatz_for_Ising from tensorcircuit.templates.conversions import QUBO_to_Ising K = tc.set_backend("tensorflow") tf.random.set_seed(530) tc.set_dtype("float32") tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) ``` -------------------------------- ### Instantiate and Call a Module Source: https://tensorcircuit.readthedocs.io/en/latest/api/applications/van.html Demonstrates how to instantiate a custom module and call it with input tensors. Shows how module names are prepended to variable names. ```python >>> mod = MyModule() >>> mod(tf.ones([1, 2])) >>> mod.w ``` -------------------------------- ### Setup Imports and Backend Configuration Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/operator_spreading.html Imports necessary libraries and sets the backend and data type for TensorCircuit operations. Ensure these are configured before running circuit simulations. ```python import numpy as np import tensorflow as tf import tensorcircuit as tc import matplotlib.pyplot as plt tc.set_backend("tensorflow") tc.set_dtype("complex128") dtype = np.complex128 ``` -------------------------------- ### Install Vanilla Tensorflow Source: https://tensorcircuit.readthedocs.io/en/latest/contribs/development_Mac.html Installs the standard Tensorflow package developed by Google. Skip the Miniconda installation if you intend to use this version. ```bash pip install tensorflow ``` -------------------------------- ### Setup QAOA for NAE3SAT Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/qaoa_nae3sat.html Imports necessary libraries and sets up backend and parameters for the QAOA optimization. This includes defining the number of layers and circuits to optimize concurrently. ```python import tensorcircuit as tc import optax import tensorflow as tf import networkx as nx import matplotlib.pyplot as plt import numpy as np from IPython.display import clear_output import random K = tc.set_backend("jax") nlayers = 30 # the number of layers ncircuits = 6 # six circuits with different initial parameters are going to be optimized at the same time ``` -------------------------------- ### Setup TensorCircuit Backend Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/contractors.html Initializes the TensorCircuit backend with TensorFlow and imports necessary libraries. ```python import tensorcircuit as tc import numpy as np import cotengra as ctg import opt_einsum as oem K = tc.set_backend("tensorflow") ``` -------------------------------- ### Create Range Tensor with CuPy Source: https://tensorcircuit.readthedocs.io/en/latest/_modules/tensorcircuit/backends/cupy_backend.html Creates a tensor with values ranging from start to stop with a given step, using CuPy's arange function. If stop is None, it defaults to start and starts from 0. ```python def arange(self, start: int, stop: Optional[int] = None, step: int = 1) -> Tensor: if stop is None: return cp.arange(start=0, stop=start, step=step) return cp.arange(start=start, stop=stop, step=step) ``` -------------------------------- ### Setup TensorCircuit Environment Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/portfolio_optimization.html Imports necessary libraries and sets the backend for TensorCircuit. Configure TensorFlow logging to reduce verbosity. ```python import tensorcircuit as tc import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorcircuit.templates.ansatz import QAOA_ansatz_for_Ising from tensorcircuit.templates.conversions import QUBO_to_Ising from tensorcircuit.applications.optimization import QUBO_QAOA, QAOA_loss from tensorcircuit.applications.finance.portfolio import StockData, QUBO_from_portfolio K = tc.set_backend("tensorflow") tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) ``` -------------------------------- ### Install Docker Desktop with PowerShell Source: https://tensorcircuit.readthedocs.io/en/latest/contribs/development_windows.html This command is used to install Docker Desktop when using PowerShell. ```powershell Start-Process '.inuild ew-docker-desktop-installer.exe' -Wait install ``` -------------------------------- ### Get QuVector Representation Source: https://tensorcircuit.readthedocs.io/en/latest/api/densitymatrix.html Gets the representation of the output state as a `QuVector` without computing the circuit. ```APIDOC ## quvector ### Description Get the representation of the output state in the form of `QuVector` while maintaining the circuit uncomputed ### Returns #### Success Response - **QuVector** - `QuVector` representation of the output state from the circuit ``` -------------------------------- ### Setup and Backend Configuration Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/barren_plateaus.html Initializes the TensorFlow backend and sets the complex data type for TensorCircuit operations. Imports necessary libraries. ```python import numpy as np import tensorflow as tf import tensorcircuit as tc tc.set_backend("tensorflow") tc.set_dtype("complex64") Rx = tc.gates.rx Ry = tc.gates.ry Rz = tc.gates.rz ``` -------------------------------- ### Setup Backend and Imports Source: https://tensorcircuit.readthedocs.io/en/latest/whitepaper/4-gradient-optimization.html Import necessary libraries and set the backend for TensorCircuit. This is a prerequisite for using TensorCircuit functionalities. ```python import numpy as np import scipy.optimize as optimize import tensorflow as tf import tensorcircuit as tc K = tc.set_backend("tensorflow") ``` -------------------------------- ### Initialize TensorCircuit and Parameters Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/qaoa.html Sets up the TensorCircuit backend and defines global parameters for the QAOA simulation, including the number of layers, circuits to optimize, and nodes in the graph. ```python import tensorcircuit as tc import tensorflow as tf import networkx as nx import matplotlib.pyplot as plt import numpy as np from IPython.display import clear_output import random K = tc.set_backend("tensorflow") nlayers = 3 # the number of layers ncircuits = 6 # six circuits with different initial parameters are going to be optimized at the same time nnodes = 8 # the number of nodes ``` -------------------------------- ### Setup TensorCircuit Backend Source: https://tensorcircuit.readthedocs.io/en/latest/whitepaper/6-3-vmap.html Sets the backend for TensorCircuit and prints the version. Imports numpy and tensorcircuit. ```python import numpy as np import tensorcircuit as tc tc.set_backend("tensorflow") print(tc.__version__) nwires = 5 nlayers = 2 batch = 6 ``` -------------------------------- ### TensorCircuit Setup Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/mera.html Initializes TensorCircuit with the TensorFlow backend and complex128 data type. This setup is required before defining quantum circuits. ```python import numpy as np import tensorflow as tf import tensorcircuit as tc tc.set_backend("tensorflow") tc.set_dtype("complex128") ``` -------------------------------- ### Initialize QuantumNet with a Quantum Function Source: https://tensorcircuit.readthedocs.io/en/latest/api/torchnn.html This example demonstrates how to wrap a quantum function (qpred) with QuantumNet. The quantum function defines a quantum circuit and calculates expectation values. QuantumNet takes the quantum function and its weights shape as input. ```python K = tc.set_backend("tensorflow") n = 6 nlayers = 2 batch = 2 def qpred(x, weights): c = tc.Circuit(n) for i in range(n): c.rx(i, theta=x[i]) for j in range(nlayers): for i in range(n - 1): c.cnot(i, i + 1) for i in range(n): c.rx(i, theta=weights[2 * j, i]) c.ry(i, theta=weights[2 * j + 1, i]) ypred = K.stack([c.expectation_ps(x=[i]) for i in range(n)]) ypred = K.real(ypred) return ypred ql = tc.torchnn.QuantumNet(qpred, weights_shape=[2*nlayers, n]) ql(torch.ones([batch, n])) ``` -------------------------------- ### Initialize Jax Backend Source: https://tensorcircuit.readthedocs.io/en/latest/_modules/tensornetwork/backends/jax/jax_backend.html Initializes the Jax backend, setting up necessary imports and configurations. Ensure Jax is installed before using this backend. ```python import numpy as np from typing import Optional, Text, Union, Sequence, Tuple from tensornetwork.backends import abstract_backend from tensornetwork.backends.jax import decompositions Tensor = np.ndarray _CACHED_MATVECS = {} _CACHED_FUNCTIONS = {} class JaxBackend(abstract_backend.AbstractBackend): """See abstract_backend.AbstractBackend for documentation.""" def __init__(self, dtype: Optional[np.dtype] = None, precision: Optional[Text] = None) -> None: # pylint: disable=global-variable-undefined global libjax # Jax module global jnp # jax.numpy module global jsp # jax.scipy module super().__init__() try: #pylint: disable=import-outside-toplevel import jax except ImportError as err: raise ImportError("Jax not installed, please switch to a different " "backend or install Jax.") from err libjax = jax jnp = libjax.numpy jsp = libjax.scipy self.name = "jax" self._dtype = np.dtype(dtype) if dtype is not None else None self.jax_precision = precision if precision is not None else libjax.lax.Precision.DEFAULT #pylint: disable=line-too-long ``` -------------------------------- ### JaxBackend Initialization Source: https://tensorcircuit.readthedocs.io/en/latest/_modules/tensorcircuit/backends/jax_backend.html Initializes the JaxBackend, setting up necessary JAX modules and checking for optional dependencies like optax. ```APIDOC ## JaxBackend() ### Description Initializes the JaxBackend. This involves importing JAX and its submodules (numpy, scipy), and optionally optax. It also sets up global variables for these modules. ### Method __init__ ### Parameters None ### Request Example ```python b = JaxBackend() ``` ### Response None ``` -------------------------------- ### Initialize QAOA Optimizer and Loss Tracking Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/qaoa.html Sets up initial parameters, an optimizer (Adam), and a list to track losses for multiple circuits during QAOA optimization. ```python params = K.implicit_randn( shape=[ncircuits, 2 * nlayers], stddev=0.1 ) # initial parameters opt = K.optimizer(tf.keras.optimizers.Adam(1e-2)) list_of_loss = [[] for i in range(ncircuits)] ``` -------------------------------- ### Robust JSON GET Request Source: https://tensorcircuit.readthedocs.io/en/latest/_modules/tensorcircuit/cloud/utils.html Performs a GET request and returns the JSON response, with built-in retry logic for network issues. ```python @reconnect() def rget_json(*args: Any, **kws: Any) -> Any: r = requests.get(*args, **kws) return r.json() ``` -------------------------------- ### Set Up Custom Contractors Source: https://tensorcircuit.readthedocs.io/en/latest/_modules/tensorcircuit/cons.html Demonstrates how to configure TensorCircuit contractors with custom optimizers and parameters. This includes setting up cotengra for hyperoptimization and opt_einsum for greedy contraction strategies. ```python import cotengra as ctg import opt_einsum as oem import tensorcircuit as tc import sys sys.setrecursionlimit(10000) # for successfullt ctg parallel opt = ctg.ReusableHyperOptimizer( methods=["greedy", "kahypar"], parallel=True, minimize="write", max_time=30, max_repeats=4096, progbar=True, ) tz.set_contractor("custom", optimizer=opt, preprocessing=True) tz.set_contractor("custom_stateful", optimizer=oem.RandomGreedy, max_time=60, max_repeats=128, minimize="size") tz.set_contractor("plain-experimental", local_steps=3) ``` -------------------------------- ### Robust GET Request Source: https://tensorcircuit.readthedocs.io/en/latest/_modules/tensorcircuit/cloud/utils.html A robust GET request function that automatically retries on connection errors and sets appropriate headers and timeouts. ```python rget = reconnect()(requests.get) ``` -------------------------------- ### from_qsim_file Source: https://tensorcircuit.readthedocs.io/en/latest/_modules/tensorcircuit/abstractcircuit.html Class method to initialize an AbstractCircuit from a Qsim file. Parses the file content to reconstruct the circuit. ```APIDOC ## from_qsim_file ### Description Initialize an AbstractCircuit from a Qsim file. ### Parameters - file (str): The path to the Qsim file. - circuit_params (Optional[Dict[str, Any]]): Optional dictionary of parameters to initialize the circuit. ### Returns - AbstractCircuit: An instance of AbstractCircuit initialized from the Qsim file. ``` -------------------------------- ### Get Current Default Device Source: https://tensorcircuit.readthedocs.io/en/latest/_modules/tensorcircuit/cloud/apis.html Gets the current default quantum device without changing it globally. This is an alias for `set_device(set_global=False)`. ```python get_device() ``` -------------------------------- ### Switch Backend to JAX Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/tfim_vqe.html Demonstrates how to switch the TensorCircuit backend to JAX at runtime. This allows for using JAX's features without modifying the core code. ```python tc.set_backend("jax") # change to jax backend ``` -------------------------------- ### Get Current Default Provider Source: https://tensorcircuit.readthedocs.io/en/latest/_modules/tensorcircuit/cloud/apis.html Gets the current default cloud provider without changing it globally. This is an alias for `set_provider(set_global=False)`. ```python get_provider() ``` -------------------------------- ### Pauli String Expectation Example Source: https://tensorcircuit.readthedocs.io/en/latest/api/mpscircuit.html Example demonstrating the calculation of Pauli string expectation for a 2-qubit circuit with X and H gates. ```python >>> c = tc.Circuit(2) >>> c.X(0) >>> c.H(1) >>> c.expectation_ps(x=[1], z=[0]) array(-0.99999994+0.j, dtype=complex64) ``` -------------------------------- ### Initialize QAOA Training Parameters Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/portfolio_optimization.html Sets up the parameters for the Quantum Approximate Optimization Algorithm (QAOA), including the number of training iterations and layers for the ansatz. It also defines a callback function to record the loss during training. ```python iterations = 1000 nlayers = 12 loss_list = [] # define a callback function to recode the loss def record_loss(loss, params): loss_list.append(loss) ``` -------------------------------- ### CuPyBackend Initialization Source: https://tensorcircuit.readthedocs.io/en/latest/_modules/tensorcircuit/backends/cupy_backend.html Initializes the CuPy backend. It checks for CuPy installation and raises an error if not found. ```APIDOC ## CuPyBackend() ### Description Initializes the CuPy backend. Requires CuPy to be installed. ### Method `__init__` ### Parameters None ### Request Example ```python b = CuPyBackend() ``` ### Response Initializes the backend with CuPy and CuPyX modules. ``` -------------------------------- ### Initialize Jax Backend Source: https://tensorcircuit.readthedocs.io/en/latest/_modules/tensorcircuit/backends/jax_backend.html Initializes the Jax backend, importing necessary libraries like jax, jax.scipy, and optionally optax. Raises an ImportError if Jax is not installed. ```python def __init__(self) -> None: global libjax # Jax module global jnp # jax.numpy module global jsp # jax.scipy module global sparse # jax.experimental.sparse global optax # optax super(JaxBackend, self).__init__() try: import jax except ImportError: raise ImportError( "Jax not installed, please switch to a different " "backend or install Jax." ) import jax.scipy from jax.experimental import sparse try: import optax except ImportError: logger.warning( "optax not installed, `optimizer` from jax backend cannot work" ) libjax = jax jnp = libjax.numpy jsp = libjax.scipy self.name = "jax" ``` -------------------------------- ### Initialize PyTorch Backend Source: https://tensorcircuit.readthedocs.io/en/latest/_modules/tensornetwork/backends/pytorch/pytorch_backend.html Initializes the PyTorch backend. Requires PyTorch to be installed. If not found, it raises an ImportError. ```python class PyTorchBackend(abstract_backend.AbstractBackend): """See base_backend.BaseBackend for documentation.""" def __init__(self) -> None: super().__init__() # pylint: disable=global-variable-undefined global torchlib try: # pylint: disable=import-outside-toplevel import torch except ImportError as err: raise ImportError("PyTorch not installed, please switch to a different " "backend or install PyTorch.") from err torchlib = torch self.name = "pytorch" ``` -------------------------------- ### Expectation Value Calculation Example Source: https://tensorcircuit.readthedocs.io/en/latest/api/circuit.html Demonstrates calculating expectation values with Pauli X and Y operators, including an example with readout error correction. ```python >>> c = tc.Circuit(2) >>> c.H(0) >>> c.rx(1, theta=np.pi/2) >>> c.sample_expectation_ps(x=[0], y=[1]) -0.99999976 >>> readout_error = [] >>> readout_error.append([0.9,0.75]) >>> readout_error.append([0.4,0.7]) >>> c.sample_expectation_ps(x=[0], y=[1],readout_error = readout_error) ``` -------------------------------- ### Example Circuit Block Source: https://tensorcircuit.readthedocs.io/en/latest/quickstart.html Demonstrates the usage of a pre-defined example block within a TensorCircuit circuit. This serves as a shortcut for common circuit structures. ```python c = tc.Circuit(4) c = tc.templates.blocks.example_block(c, tc.backend.ones([16])) ``` -------------------------------- ### Initialize and Run Optimization in Python Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/optimization_and_expressibility.html Initializes the parameters for the variational quantum circuit and calls the main optimization function. This snippet demonstrates how to set up the initial state and execute the training process. ```python v = tf.random.uniform([num_trial, L, N], minval=0.0, maxval=2 * np.pi, dtype=tf.float64) E_initial, E_final, S_initial, S_final = opt_main(v) ``` -------------------------------- ### Initialize DARBO Optimizer Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/qaoa_bo.html Instantiates the DARBO_optimizer with specified parameters and prints the initial mode. This setup is for a 'small' mode optimization. ```python mode = "small" darbo_opt = DARBO_optimizer( eval_objective, 2 * nlayers, tr_length, failure_tolerance, mode, device ) print(f"initial mode: {darbo_opt.get_mode()}") ``` -------------------------------- ### Import Libraries and Print Version Source: https://tensorcircuit.readthedocs.io/en/latest/whitepaper/6-4-quoperator.html Imports necessary libraries (numpy, tensornetwork, tensorcircuit) and prints the installed tensorcircuit version. Ensure tensorcircuit is installed before running. ```python import numpy as np import tensornetwork as tn import tensorcircuit as tc print(tc.__version__) ``` -------------------------------- ### Circuit Class Initialization Source: https://tensorcircuit.readthedocs.io/en/latest/api/circuit.html Demonstrates how to initialize a Circuit object with a specified number of qubits. ```APIDOC ## Circuit Class ### Description Represents a quantum circuit, allowing for the application of various quantum gates. ### Parameters - **nqubits** (int) - The number of qubits in the circuit. - **inputs** (Optional[Any]) - Optional inputs for the circuit. - **mps_inputs** (Optional[tensorcircuit.quantum.QuOperator]) - Optional MPS inputs. - **split** (Optional[Dict[str, Any]]) - Optional split dictionary. ### Example ```python c = tc.Circuit(3) ``` ``` -------------------------------- ### Install Tensorflow Metal Plugin Source: https://tensorcircuit.readthedocs.io/en/latest/contribs/development_Mac.html Installs the tensorflow-metal PluggableDevice for enhanced Tensorflow performance on compatible MacOS hardware. This is an optional step and may not be recommended for all users. ```bash pip install tensorflow-metal ``` -------------------------------- ### from_qsim_file Source: https://tensorcircuit.readthedocs.io/en/latest/api/basecircuit.html Loads a circuit from a QSIM file. ```APIDOC ## from_qsim_file ### Description Loads a circuit from a QSIM file. ### Method classmethod ### Parameters #### Path Parameters - **file** (str) - Required - The path to the QSIM file. - **circuit_params** (Optional[Dict[str, Any]]) - Optional - Additional parameters for circuit construction. ``` -------------------------------- ### Switch Simulation Backends Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/circuit_basics.html Demonstrates how to switch between different simulation backends like TensorFlow, JAX, and PyTorch. Note that full functionality may not be guaranteed on all backends. ```python # we can easily switch simulation backends away from NumPy! with tc.runtime_backend("tensorflow") as K: c = get_circuit(3) print(c.state()) with tc.runtime_backend("jax") as K: c = get_circuit(3) print(c.state()) with tc.runtime_backend("pytorch") as K: # best performance and full functionality are not guaranteed on pytorch backend c = get_circuit(3) print(c.state()) ``` -------------------------------- ### Verify Tensorflow Installation Source: https://tensorcircuit.readthedocs.io/en/latest/contribs/development_Mac.html This Python script verifies the Tensorflow installation by loading the CIFAR-100 dataset, defining a ResNet50 model, compiling it, and performing a short training run. ```python import tensorflow as tf cifar = tf.keras.datasets.cifar100 (x_train, y_train), (x_test, y_test) = cifar.load_data() model = tf.keras.applications.ResNet50( include_top=True, weights=None, input_shape=(32, 32, 3), classes=100,) loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) model.compile(optimizer="adam", loss=loss_fn, metrics=["accuracy"]) model.fit(x_train, y_train, epochs=5, batch_size=64) ``` -------------------------------- ### example_block() Source: https://tensorcircuit.readthedocs.io/en/latest/genindex.html Provides an example block for circuit construction. Found in the tensorcircuit.templates.blocks module. ```APIDOC ## example_block() ### Description Provides an example block for circuit construction. ### Module tensorcircuit.templates.blocks ``` -------------------------------- ### TensorFlow Arange Sequence Source: https://tensorcircuit.readthedocs.io/en/latest/_modules/tensorcircuit/backends/tensorflow_backend.html Creates a sequence of numbers with a specified start, stop, and step. If only one argument is provided, it's treated as the stop value starting from 0. ```python def arange(self, start: int, stop: Optional[int] = None, step: int = 1) -> Tensor: if stop is None: return tf.range(start=0, limit=start, delta=step) return tf.range(start=start, limit=stop, delta=step) ``` -------------------------------- ### Build Source Distribution and Wheel for PyPI Source: https://tensorcircuit.readthedocs.io/en/latest/contribution.html Create source distribution and wheel files for the project, which are necessary for uploading to PyPI. ```bash python setup.py sdist bdist_wheel export VERSION=0.x.y twine upload dist/tensorcircuit-${VERSION}-py3-none-any.whl dist/tensorcircuit-${VERSION}.tar.gz ``` -------------------------------- ### Conditional Measurement Example Source: https://tensorcircuit.readthedocs.io/en/latest/_modules/tensorcircuit/basecircuit.html Performs a conditional measurement on a specified qubit in the Z basis. This method is jittable and can return the measured result as an integer tensor. The example demonstrates its use with `conditional_gate` and `expectation`. ```python c = tc.Circuit(2) c.H(0) r = c.cond_measurement(0) c.conditional_gate(r, [tc.gates.i(), tc.gates.x()], 1) c.expectation([tc.gates.z(), [0]]), c.expectation([tc.gates.z(), [1]]) # two possible outputs: (1, 1) or (-1, -1) ``` -------------------------------- ### Initialize and Use MPSCircuit Source: https://tensorcircuit.readthedocs.io/en/latest/_modules/tensorcircuit/mpscircuit.html Demonstrates basic usage of MPSCircuit by initializing a 3-qubit circuit, applying single-qubit (Hadamard, RX) and two-qubit (CNOT) gates, and calculating an expectation value. ```python mps = tc.MPSCircuit(3) mps.H(1) mps.CNOT(0, 1) mps.rx(2, theta=tc.num_to_tensor(1.)) mps.expectation((tc.gates.z(), 2)) ``` -------------------------------- ### Load Circuit from Qsim File Source: https://tensorcircuit.readthedocs.io/en/latest/_modules/tensorcircuit/abstractcircuit.html The `from_qsim_file` class method allows loading a circuit definition from a file formatted according to the Qsim input specification. It automatically determines the number of qubits if not provided. ```python @classmethod def from_qsim_file( cls, file: str, circuit_params: Optional[Dict[str, Any]] = None, ) -> "AbstractCircuit": with open(file, "r") as f: lines = f.readlines() if circuit_params is None: circuit_params = {} if "nqubits" not in circuit_params: circuit_params["nqubits"] = int(lines[0]) c = cls(**circuit_params) c = cls._apply_qsim(c, lines) return c ``` -------------------------------- ### tensorcircuit.cloud.abstraction.Task.status Source: https://tensorcircuit.readthedocs.io/en/latest/genindex.html Gets the status of the task. ```APIDOC ## status() ### Description Gets the status of the task. ### Method (tensorcircuit.cloud.abstraction.Task method) ``` -------------------------------- ### tensorcircuit.mpscircuit.MPSCircuit.state Source: https://tensorcircuit.readthedocs.io/en/latest/genindex.html Gets the state of the MPSCircuit. ```APIDOC ## state() ### Description Gets the state of the MPSCircuit. ### Method (tensorcircuit.mpscircuit.MPSCircuit method) ``` -------------------------------- ### VQE Optimization Loop Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/vqe_h2o.html Sets up the optimizer and runs the VQE optimization loop for a specified number of steps. It prints the energy at intervals to monitor convergence. ```python vags = tc.backend.jit(tc.backend.value_and_grad(vqe)) lr = tf.keras.optimizers.schedules.ExponentialDecay( decay_rate=0.5, decay_steps=300, initial_learning_rate=0.5e-2 ) opt = tc.backend.optimizer(tf.keras.optimizers.Adam(lr)) param = tc.backend.implicit_randn(shape=[depth, n, 4], stddev=0.02, dtype="float32") for i in range(600): e, g = vags(param) param = opt.update(g, param) if i % 100 == 0: print(e) ``` -------------------------------- ### tensorcircuit.densitymatrix.DMCircuit2.state Source: https://tensorcircuit.readthedocs.io/en/latest/genindex.html Gets the state of the DMCircuit2. ```APIDOC ## state() ### Description Gets the state of the DMCircuit2. ### Method (tensorcircuit.densitymatrix.DMCircuit2 method) ``` -------------------------------- ### tensorcircuit.densitymatrix.DMCircuit.state Source: https://tensorcircuit.readthedocs.io/en/latest/genindex.html Gets the state of the DMCircuit. ```APIDOC ## state() ### Description Gets the state of the DMCircuit. ### Method (tensorcircuit.densitymatrix.DMCircuit method) ``` -------------------------------- ### Device Initialization and Management Source: https://tensorcircuit.readthedocs.io/en/latest/_modules/tensorcircuit/cloud/abstraction.html Instantiate or retrieve a Device object. Devices can be specified with a name and an optional provider. ```python d = Device.from_name("simulator", provider="local") print(d) ``` -------------------------------- ### Parallel Optimization with vmap and partial Source: https://tensorcircuit.readthedocs.io/en/latest/tutorials/qaoa_quantum_dropout.html Optimizes QAOA circuits in parallel using JAX's vmap and partial for handling non-hashable graph weights. It includes initialization of parameters, optimizer setup, and the optimization loop. ```python # use vvag to get the losses and gradients with different random circuit instances QAOA_vvag = K.jit( K.vvag(partial(QAOAansatz_rnd, g=rnd_graphs_w), argnums=0, vectorized_argnums=0) ) params_rnd = K.implicit_randn( shape=[ncircuits, 2 * nlayers], stddev=0.1 ) # initial parameters if type(K).__name__ == "JaxBackend": opt = K.optimizer(optax.adam(1e-2)) else: opt = K.optimizer(tf.keras.optimizers.Adam(1e-2)) list_of_loss = [[] for i in range(ncircuits)] for i in range(2000): loss, grads = QAOA_vvag(params_rnd) params_rnd = opt.update(grads, params_rnd) # gradient descent # visualise the progress clear_output(wait=True) list_of_loss = np.hstack((list_of_loss, K.numpy(loss)[:, np.newaxis])) plt.xlabel("Iteration") plt.ylabel("Cost") for index in range(ncircuits): plt.plot(range(i + 1), list_of_loss[index]) legend = [f"circuit {leg}" for leg in range(ncircuits)] plt.legend(legend) plt.show() ```