### Install TensorCircuit-NG Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Installs the TensorCircuit-NG library using pip. This is the general installation command for x86 Linux systems. Additional packages for specific features may need to be installed separately. ```Bash pip install tensorcircuit-ng ``` -------------------------------- ### Install TensorCircuit-NG Nightly Build Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Uninstalls the stable version of TensorCircuit-NG and installs the latest nightly build from PyPI. This provides access to the most recent features and bug fixes. ```Bash pip uninstall tensorcircuit-ng pip install tensorcircuit-nightly ``` -------------------------------- ### TensorCircuit Backend Agnosticism Examples Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Showcases TensorCircuit's backend agnosticism by demonstrating how to set and use different backends like TensorFlow and Jax. It includes examples of creating tensors and accessing backend-agnostic APIs. ```python >>> import tensorcircuit as tc >>> K = tc.set_backend("tensorflow") >>> K.ones([2,2]) >>> tc.backend.eye(3) >>> tc.set_backend("jax") >>> tc.backend.name 'jax' >>> tc.backend.implicit_randu() WARNING:absl:No GPU/TPU found, falling back to CPU. (Set TF_CPP_MIN_LOG_LEVEL=0 and rerun for more info.) DeviceArray([0.7400521], dtype=float32) ``` ```python >>> [s for s in dir(tc.backend) if not s.startswith("_")] ['abs', 'acos', 'acosh', 'addition', 'adjoint', 'arange', 'argmax', 'argmin', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'broadcast_left_multiplication', 'broadcast_right_multiplication', 'cast', 'cholesky', 'concat', 'cond', 'conj', 'convert_to_tensor', 'coo_sparse_matrix', 'coo_sparse_matrix_from_numpy', 'copy', 'cos', 'cosh', 'cumsum', 'deserialize_tensor', 'device', 'device_move', 'diagflat', 'diagonal', 'divide', 'dtype', 'eigh', 'eigs', 'eigsh', 'eigsh_lanczos', 'eigvalsh', 'einsum', 'eps' ``` -------------------------------- ### Install Tensorcircuit Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_Mac_cn.md Installs the Tensorcircuit library using pip. This is the final step to get Tensorcircuit ready for use. ```bash pip install tensorcircuit ``` -------------------------------- ### Apply Example Block to Circuit Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst This snippet demonstrates applying a pre-defined circuit block, `example_block`, to a TensorCircuit. It initializes a circuit with 4 qubits and then applies the `example_block` using a provided set of parameters. This showcases the use of reusable circuit components. ```python import tensorcircuit as tc c = tc.Circuit(4) c = tc.templates.blocks.example_block(c, tc.backend.ones([16])) ``` -------------------------------- ### Install Jax or PyTorch Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_Mac_cn.md Installs optional backends for Tensorcircuit, specifically Jax or PyTorch. Use 'pip install [Package Name]' to install the desired package. ```bash pip install [Package Name] ``` -------------------------------- ### JIT-Compiled Bitstring Sampling with JAX Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Provides an example of using JAX for just-in-time (JIT) compilation of a bitstring sampling function in TensorCircuit. This optimizes the performance of sampling operations on larger circuits. ```Python import jax import tensorcircuit as tc K = tc.set_backend("jax") @K.jit def sam(key): K.set_random_state(key) n = 50 c = tc.Circuit(n) for i in range(n): c.H(i) return c.perfect_sampling() sam(jax.random.PRNGKey(42)) sam(jax.random.PRNGKey(43)) ``` -------------------------------- ### Install TensorCircuit-NG with CUDA support Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Installs TensorCircuit-NG with support for Nvidia GPUs. This requires installing the appropriate CUDA-enabled versions of underlying machine learning frameworks like TensorFlow, JAX, or PyTorch. ```Bash pip install 'tensorflow[and-cuda]' ``` ```Bash pip install 'jax[cuda-12]' ``` ```Bash pip install tensorcircuit-ng ``` -------------------------------- ### JAX Interface for Quantum Circuits Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Provides an example of using the JAX interface to seamlessly integrate TensorCircuit with JAX's ecosystem, including automatic differentiation and JIT compilation. It shows how to wrap a quantum circuit and use JAX's `value_and_grad`. ```python import tensorcircuit as tc import jax import jax.numpy as jnp tc.set_backend("tensorflow") def circuit(params): c = tc.Circuit(2) c.rx(0, theta=params[0]) c.ry(1, theta=params[1]) c.cnot(0, 1) return tc.backend.real(c.expectation_ps(z=[1])) jax_circuit = tc.interfaces.jax_interface(circuit, jit=True) params = jnp.ones(2) value, grad = jax.value_and_grad(jax_circuit)(params) print("Value:", value) print("Gradient:", grad) ``` -------------------------------- ### Install Tensorcircuit Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_Mac.md Installs the Tensorcircuit library using pip. ```bash pip install tensorcircuit ``` -------------------------------- ### Configure Cotengra Contractor Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Sets up a custom contractor using the cotengra library for optimized tensor network contraction. This example configures a ReusableHyperOptimizer with specific methods, parallel processing, and minimization targets, along with preprocessing for gate merging. ```python import tensorcircuit as tc import cotengra as ctg optr = ctg.ReusableHyperOptimizer( methods=["greedy", "kahypar"], parallel=True, minimize="flops", max_time=120, max_repeats=4096, progbar=True, ) tc.set_contractor("custom", optimizer=optr, preprocessing=True) ``` -------------------------------- ### Install Jax, Pytorch Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_Mac.md Installs optional backends like Jax or PyTorch using pip. Replace '[Package Name]' with the specific package you wish to install. ```bash pip install [Package Name] ``` -------------------------------- ### Install Vanilla Tensorflow Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_Mac.md Installs the standard Tensorflow package developed by Google using pip. ```bash pip install tensorflow ``` -------------------------------- ### Install and Upgrade Dependencies (Bash) Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/llm.md Installs or upgrades the package installer (pip) and then installs core, development, optional, and type-checking dependencies from their respective requirement files. ```bash pip install --upgrade pip pip install -r requirements/requirements.txt pip install -r requirements/requirements-dev.txt pip install -r requirements/requirements-extra.txt pip install -r requirements/requirements-types.txt ``` -------------------------------- ### JAX Interface with DLPack Support Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Demonstrates enabling DLPack support within the JAX interface for efficient, zero-copy tensor conversions between different backends and JAX. ```python import tensorcircuit as tc import jax import jax.numpy as jnp def circuit(params): # ... circuit definition ... return tc.backend.real(c.expectation_ps(z=[1])) # Enable DLPack for zero-copy tensor conversion jax_circuit = tc.interfaces.jax_interface(circuit, jit=True, enable_dlpack=True) ``` -------------------------------- ### Install Optional Backends (Jax, PyTorch, Qiskit, Cirq) Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_MacARM.md Installs optional backend libraries for Tensorcircuit. Users can choose to install Jax, PyTorch, Qiskit, or Cirq based on their specific project requirements. ```python pip install [Package Name] ``` -------------------------------- ### Run TensorCircuit-NG with Docker Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Launches a TensorCircuit-NG Docker container with GPU access and host network enabled. This command allows users to run TensorCircuit-NG in a pre-configured environment. ```Bash sudo docker run -it --network host --gpus all tensorcircuit/tensorcircuit ``` -------------------------------- ### Install Tensorcircuit Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_MacARM.md Installs the Tensorcircuit library using pip. This is the final step after setting up the environment and dependencies. ```python pip install tensorcircuit ``` -------------------------------- ### Sphinx Documentation Build (HTML/PDF) Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribution.rst Commands to build HTML and PDF versions of the documentation using Sphinx. Assumes Sphinx is installed and the source files are in 'docs/source'. ```bash sphinx-build source build/html ``` ```bash make latexpdf LATEXMKOPTS="-silent" ``` -------------------------------- ### Hybridize Quantum Circuits with PyTorch Modules Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Shows how to integrate TensorCircuit quantum functions with PyTorch modules, allowing for hybrid classical-quantum machine learning models. This example sets up a simple quantum circuit with parameterized gates. ```Python import tensorcircuit as tc from tensorcircuit.interfaces import torch_interface import torch tc.set_backend("tensorflow") def f(params): c = tc.Circuit(1) c.rx(0, theta=params[0]) c.ry(0, theta=params[1]) ``` -------------------------------- ### PyTorch Interface for Quantum Circuits Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Demonstrates using the PyTorch interface to run quantum circuits with JIT compilation. It shows how to define a quantum function, wrap it with the PyTorch interface, and perform backward passes for gradient computation. ```python import tensorcircuit as tc import torch # Assume f is a defined quantum function def f(a): # ... quantum circuit logic ... return c.expectation([tc.gates.z(), [0]]) f_torch = tc.interfaces.torch_interface(f, jit=True) a = torch.ones([2], requires_grad=True) b = f_torch(a) c = b ** 2 c.backward() print(a.grad) ``` -------------------------------- ### Configure Stateful RandomGreedy Contractor Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Configures a stateful contractor using the RandomGreedy optimizer from opt-einsum. This setup specifies parameters like maximum time, maximum repeats, and the minimization objective for the contraction path search. ```python import tensorcircuit as tc import opt_einsum as oem tc.set_contractor("custom_stateful", optimizer=oem.RandomGreedy, max_time=60, max_repeats=128, minimize="size") ``` -------------------------------- ### Get State Vector and Sample Bitstrings in TensorCircuit Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Demonstrates how to obtain the output state vector of a quantum circuit using `c.state()` and how to perform perfect bitstring sampling with probabilities using `c.perfect_sampling()`. These methods leverage tensor network algorithms. ```Python state_vector = c.state() bitstring, probability = c.perfect_sampling() ``` -------------------------------- ### Measure Qubits and Get Probabilities in TensorCircuit Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Illustrates how to measure specific qubits in a TensorCircuit. It shows how to get the measurement outcome and optionally its probability using `c.measure()` and `c.measure(with_prob=True)`. A jittable version `c.measure_jit()` is also available. ```Python measurement_outcome = c.measure(0, 1) probability_outcome = c.measure(0, 1, with_prob=True) jittable_outcome = c.measure_jit(0, 1) ``` -------------------------------- ### Install Tensorflow Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_Mac_cn.md Installs the Tensorflow package using pip. This command installs the standard Tensorflow package. For Apple Metal optimization, tensorflow-metal can be installed subsequently. ```bash pip install tensorflow ``` -------------------------------- ### Navigate to Examples Directory Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_windows.rst Changes the current working directory to the 'examples' folder within the TensorCircuit project. This is necessary to access and run the provided example scripts. ```bash cd examples ``` -------------------------------- ### Verify TensorFlow Installation (General) Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_MacARM.md Verifies a TensorFlow installation by loading the CIFAR-100 dataset, building a ResNet50 model, compiling it with the Adam optimizer, 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) ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribution.rst Installs the necessary Python packages for local development, including core requirements, development tools, type checking, and extra packages. ```bash pip install -r requirements/requirements.txt pip install -r requirements/requirements-dev.txt pip install -r requirements/requirements-types.txt pip install -r requirements/requirements-extra.txt ``` -------------------------------- ### Install Xcode Command Line Tools on MacOS Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_MacM2.md Installs the necessary command line tools for Xcode on MacOS. This can be done directly via the command line or by downloading an installer image from Apple's developer website. ```shell xcode-select --install ``` -------------------------------- ### Install Xcode Command Line Tools Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_Mac.md Installs the necessary Xcode command line tools on MacOS. This can be done automatically via the command line or manually by downloading the tools from Apple's developer website. ```bash xcode-select --install ``` -------------------------------- ### Install Xcode Command Line Tools Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_Mac_cn.md Installs the necessary command-line developer tools for MacOS. This can be done directly via the terminal or by downloading the installer from Apple's developer portal if network connectivity is an issue. ```bash xcode-select --install ``` -------------------------------- ### Initialize and Apply Gates in TensorCircuit Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Demonstrates the basic usage of the `tc.Circuit` object in TensorCircuit. It shows how to initialize a circuit with a specified number of qubits, apply single-qubit gates like Hadamard (H) and Rx, and multi-qubit gates like CNOT. ```Python n = 2 c = tc.Circuit(n) c.H(1) c.rx(2, theta=0.2) c.cnot(0, 1) ``` -------------------------------- ### Install TensorFlow with MacOS Optimization (v2.12-) Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_MacARM.md Installs TensorFlow optimized for MacOS for versions prior to 2.13, using tensorflow-macos and tensorflow-metal. This ensures compatibility with older setups. ```python pip install tensorflow-macos pip install tensorflow-metal ``` -------------------------------- ### Verify Tensorflow Installation Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_Mac_cn.md Verifies the Tensorflow installation by loading the CIFAR-100 dataset, building a ResNet50 model, compiling it with the Adam optimizer, and performing a short training run. This confirms that Tensorflow is set up correctly and can perform basic operations. ```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) ``` -------------------------------- ### PyTorch Interface with Keyword Arguments Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Illustrates a more flexible PyTorch interface that supports static non-tensor inputs as keyword arguments. This allows for easier integration of classical parameters into quantum functions. ```python import tensorcircuit as tc import torch def f(a, i): s = 0. for _ in range(i): s += a return s f_torch = tc.interfaces.torch_interface_kws(f) f_torch(torch.ones([2]), i=3) ``` -------------------------------- ### Install TensorCircuit-NG Package Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/README.md Instructions for installing the TensorCircuit-NG package using pip. It shows the basic installation command and how to install with optional dependencies like TensorFlow. ```Bash pip install tensorcircuit-ng ``` ```Bash pip install "tensorcircuit-ng[tensorflow]" ``` ```Bash pip install tensorcircuit-nightly ``` -------------------------------- ### Install Miniconda for Tensorflow Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_Mac.md Installs Miniconda, a minimal installer for conda, which is recommended for installing Tensorflow optimized for MacOS or Tensorflow GPU. This involves downloading a script, running it, and activating the conda environment. ```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 ``` -------------------------------- ### Install Tensorcircuit Package Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_MacM2.md Installs the Tensorcircuit Python package using pip. This command should be run after all necessary dependencies and environments have been set up. ```shell pip install tensorcircuit ``` -------------------------------- ### Install TensorFlow from Wheel File Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_MacM2.md Installs TensorFlow version 2.4.1 using a pre-compiled wheel file. Ensure the wheel file is downloaded to the specified path before running this command. ```shell pip install ~/Downloads/tensorflow-2.4.1-py3-none-any.whl ``` -------------------------------- ### Install Local Package in Editable Mode Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribution.rst Installs the TensorCircuit-NG package in editable mode, allowing immediate testing of local code modifications. ```bash pip install -e . ``` -------------------------------- ### Verify Tensorflow Installation Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_Mac.md Verifies the Tensorflow installation by loading the CIFAR-100 dataset, defining a ResNet50 model, compiling it, and performing a short training run. This confirms that Tensorflow is operational and can perform basic machine learning tasks. ```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) ``` -------------------------------- ### Calculate Expectation Values in TensorCircuit Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Demonstrates how to calculate expectation values of local observables in TensorCircuit. Examples include calculating \langle Z_0Z_1 \rangle and \langle X_0 \rangle, as well as measuring a general observable `m` on multiple qubits. ```Python expectation_zz = c.expectation([tc.gates.z(), [0]], [tc.gates.z(), [1]]) expectation_x = c.expectation([tc.gates.x(), [0]]) expectation_m = c.expectation([m, [0, 1, 2]]) ``` -------------------------------- ### Install Miniconda for MacOS Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_MacARM.md Installs Miniconda, a minimal installer for conda, on MacOS. This is recommended to manage Python environments and dependencies, especially for versions that might have compatibility issues. ```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 ``` -------------------------------- ### JIT Acceleration for Quantum Circuits Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Illustrates the performance benefits of Just-In-Time (JIT) compilation for quantum circuits in TensorCircuit. It compares the execution time of a noisy quantum circuit with and without JIT compilation when called multiple times. ```python import tensorcircuit as tc import time K = tc.set_backend("tensorflow") # Define a quantum circuit function def noisy_circuit(key): c = tc.Circuit(5) for i in range(5): c.h(i) c.depolarizing(i, px=0.01, py=0.01, pz=0.01, status=key[i]) return c.expectation_ps(z=[0]) # Compare performance with and without JIT start = time.time() for _ in range(100): noisy_circuit(K.ones([5])) print("Without JIT:", time.time() - start) jitted_circuit = K.jit(noisy_circuit) start = time.time() for _ in range(100): jitted_circuit(K.ones([5])) print("With JIT:", time.time() - start) ``` -------------------------------- ### Install Miniconda for Tensorflow Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_Mac_cn.md Installs Miniconda, a minimal installer for conda, which is recommended for managing Tensorflow environments, especially for Apple-optimized versions like tensorflow-macos and 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 ``` -------------------------------- ### GitHub Release Tagging and Pushing Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribution.rst Steps to create a Git tag for a new release version and push it to the remote repository (origin). ```bash git tag v0.x.y git push origin v0.x.y ``` -------------------------------- ### Calculate Quantum Loss and Gradients with TensorFlow Backend (tf.GradientTape) Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst This example demonstrates calculating quantum loss and gradients using TensorFlow's `tf.GradientTape` for automatic differentiation. It defines a loss function for a quantum circuit and then uses `tf.GradientTape` to compute the gradients. ```Python import tensorcircuit as tc import tensorflow as tf K = tc.set_backend("tensorflow") n = 1 def loss(params, n): c = tc.Circuit(n) for i in range(n): c.rx(i, theta=params[0, i]) for i in range(n): c.rz(i, theta=params[1, i]) loss = 0.0 for i in range(n): loss += c.expectation([tc.gates.z(), [i]]) return tf.math.real(loss) def vgf(params, n): with tf.GradientTape() as tape: tape.watch(params) l = loss(params, n) return l, tape.gradient(l, params) vgf = tf.function(vgf) params = tf.random.normal([2, n]) print(vgf(params, n)) # get the quantum loss and the gradient ``` -------------------------------- ### Noisy Circuit Simulation with Thermal Relaxation Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Defines a quantum circuit with a thermal relaxation channel and calculates the expectation value of the Pauli-Z operator. This example showcases how to simulate noise using the `thermalrelaxation` method. ```python import tensorcircuit as tc def noisecircuit(random): c = tc.Circuit(1) c.x(0) c.thermalrelaxation( 0, t1=300, t2=400, time=1000, method="ByChoi", excitedstatepopulation=0, status=random, ) return c.expectation_ps(z=[0]) ``` -------------------------------- ### PyPI Release Build and Upload Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribution.rst Commands to build the package distribution files and upload them to PyPI using twine. Requires setting the VERSION environment variable. ```bash python -m build export VERSION=0.x.y twine upload dist/tensorcircuit_ng-${VERSION}-py3-none-any.whl dist/tensorcircuit_ng-${VERSION}.tar.gz ``` -------------------------------- ### Import Qiskit Circuit into TensorCircuit Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Shows how to create a TensorCircuit object from a Qiskit `QuantumCircuit`. This allows seamless integration with existing Qiskit workflows and the ability to leverage TensorCircuit's simulation capabilities. ```Python from qiskit import QuantumCircuit # Assuming 'qc' is an existing Qiskit QuantumCircuit object c_from_qiskit = tc.Circuit.from_qiskit(qc, n) ``` -------------------------------- ### Installing TensorCircuit-NG via Pip Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/README_cn.md Provides the command-line instruction to install the TensorCircuit-NG package using pip. It also shows how to install with specific backend dependencies like TensorFlow. ```Shell pip install tensorcircuit-ng ``` ```Shell pip install tensorcircuit-ng[tensorflow] ``` -------------------------------- ### Install Jax and Optax using Conda Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_MacM2.md Installs Jax version 0.3.0 and Optax version 0.1.4 using the Conda package manager. These are essential libraries for numerical computation and optimization, often used with TensorFlow. ```shell conda install jax==0.3.0 conda install optax==0.1.4 ``` -------------------------------- ### Install Tensorflow-Metal Plugin Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_Mac.md Installs the tensorflow-metal PluggableDevice, which enables Tensorflow to utilize Apple's Metal GPU acceleration. This is an optional step. ```bash pip install tensorflow-metal ``` -------------------------------- ### Installing TensorCircuit-NG Nightly Build Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/README_cn.md Demonstrates how to install the latest development version of TensorCircuit-NG using pip, which includes the newest features and bug fixes. ```Shell pip uninstall tensorcircuit-ng pip install tensorcircuit-nightly ``` -------------------------------- ### Set TensorFlow Backend Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Sets the backend for TensorCircuit operations to TensorFlow and returns the backend object. ```python import tensorcircuit as tc K = tc.set_backend("tensorflow") ``` -------------------------------- ### Install Missing Chardet Package Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_MacM2.md Installs the 'chardet' package using Conda, which may be required if encountering an 'ERROR: package Chardet not found.' error during TensorFlow or Jax installation. ```shell conda install chardet ``` -------------------------------- ### Set Plain Experimental Contractor Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Applies the 'plain-experimental' contractor provided by TensorCircuit. This is a simpler contractor, potentially useful for specific circuit topologies like those with ring structures. ```python import tensorcircuit as tc tc.set_contractor("plain-experimental") ``` -------------------------------- ### Install Tensorflow Metal Plugin Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_Mac_cn.md Installs the tensorflow-metal plugin, which provides Metal GPU acceleration for Tensorflow on compatible Apple hardware. This is recommended for performance optimization. ```bash pip install tensorflow-metal ``` -------------------------------- ### Install Docker Desktop via Command Line (Bash) Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_windows.rst This command installs Docker Desktop using the downloaded installer in a Bash terminal. ```bash "Docker Desktop Installer.exe" install ``` -------------------------------- ### Execute Quantum Circuit with JAX Interface Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst This snippet demonstrates how to use the JAX interface to execute a quantum circuit. It shows how to define a circuit, apply gates, calculate expectations, and then integrate it with JAX for automatic differentiation and JIT compilation. The `jax_interface` function is used to create a JAX-compatible version of the circuit function. ```python import tensorcircuit as tc import jax import jax.numpy as jnp # Assume multi_output_circuit is defined elsewhere def multi_output_circuit(params): c = tc.Circuit(2) c.rx(0, theta=params[0]) c.ry(1, theta=params[1]) z0 = c.expectation([tc.gates.z(), [0]]) z1 = c.expectation([tc.gates.z(), [1]]) return tc.backend.real(z0), tc.backend.real(z1) jax_circuit = tc.interfaces.jax_interface(multi_output_circuit, jit=True, output_shape=[[], []], output_dtype=[jnp.float32, jnp.float32]) # Now you can use JAX features params = jnp.ones(2) value, grad = jax.value_and_grad(tc.utils.append(jax_circuit, sum))(params) ``` -------------------------------- ### JAX Interface with Explicit Output Shape Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Shows how to specify the output shape and data type for the JAX interface, which can lead to performance improvements by allowing JAX to optimize compilation. ```python import tensorcircuit as tc import jax import jax.numpy as jnp def circuit(params): # ... circuit definition ... return tc.backend.real(c.expectation_ps(z=[1])) # Specify output shape and dtype jax_circuit = tc.interfaces.jax_interface(circuit, jit=True, output_shape=(1,), output_dtype=jnp.float32) ``` -------------------------------- ### Install Docker Desktop via Command Line (PowerShell) Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_windows.rst This command installs Docker Desktop using the downloaded installer in PowerShell, waiting for the process to complete. ```powershell Start-Process '.\win\build\Docker Desktop Installer.exe' -Wait install ``` -------------------------------- ### Docker Image Build and Tagging Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribution.rst Commands to build a Docker image from the Dockerfile, tag it with a specific version and 'latest', and push it to DockerHub. ```bash sudo docker build . -f docker/Dockerfile -t tensorcircuit sudo docker tag tensorcircuit:latest tensorcircuit/tensorcircuit:0.x.y sudo docker push tensorcircuit/tensorcircuit:0.x.y sudo docker tag tensorcircuit:latest tensorcircuit/tensorcircuit:latest sudo docker push tensorcircuit/tensorcircuit:latest ``` -------------------------------- ### Install Tensorcircuit Prerequisites Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_MacARM.md Installs essential Python libraries required for Tensorcircuit, including NumPy for numerical operations, SciPy for scientific computing, TensorNetwork for tensor network operations, and NetworkX for graph manipulation. ```python pip install numpy scipy tensornetwork networkx ``` -------------------------------- ### Runtime Backend and Dtype Context Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Demonstrates setting the backend and dtype within a context manager for specific operations. Operations inside the `with` block use TensorFlow and complex128, while operations outside use the default NumPy and complex64. ```python import tensorcircuit as tc with tc.runtime_backend("tensorflow"): with tc.runtime_dtype("complex128"): m = tc.backend.eye(2) n = tc.backend.eye(2) print(m, n) ``` -------------------------------- ### Export TensorCircuit to Qiskit Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Demonstrates how to convert a TensorCircuit object to a Qiskit `QuantumCircuit`. This is useful for further processing, hardware execution, or visualization using Qiskit's ecosystem. ```Python qiskit_circuit = c.to_qiskit() ``` -------------------------------- ### Configure Git User Information Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribution.rst Sets your Git username and email to match your GitHub account for proper attribution in commits. ```bash git config user.name git config user.email ``` -------------------------------- ### PyTorch TorchLayer for Quantum Neural Networks Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Shows how to use `tc.TorchLayer` (alias for `tc.torchnn.QuantumNet`) to wrap quantum functions as PyTorch modules. It supports features like `use_vmap` for batching and `vectorized_argnums` for efficient gradient computation. ```python import tensorcircuit as tc import torch n = 3 p = 0.1 K = tc.backend def f(state, noise, weights): c = tc.Circuit(n, inputs=state) for i in range(n): c.rz(i, theta=weights[i]) for i in range(n): c.depolarizing(i, px=p, py=p, pz=p, status=noise[i]) return K.real(c.expectation_ps(x=[0])) layer = tc.TorchLayer(f, [n], use_vmap=True, vectorized_argnums=[0, 1]) state = torch.ones([2, 2**n]) / 2 ** (n / 2) noise = 0.2 * torch.ones([2, n], dtype="float32") l = layer(state, noise) lsum = torch.sum(l) print(l) lsum.backward() for p in layer.parameters(): print(p.grad) ``` -------------------------------- ### Install Miniconda on MacOS ARM64 Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_MacM2.md Installs Miniconda, a minimal installer for conda, on MacOS with an ARM64 architecture. This is recommended for managing Python environments and dependencies, especially for compatibility with specific packages. ```shell 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 ``` -------------------------------- ### TensorFlow KerasLayer for Quantum Circuits Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Demonstrates using `tc.KerasLayer` to integrate quantum circuits into Keras models. It explains how to handle multiple inputs using a dictionary format, aligning with Keras conventions. ```python import tensorcircuit as tc import tensorflow as tf n = 3 p = 0.1 K = tc.backend def f(inputs, weights): state = inputs["state"] noise = inputs["noise"] c = tc.Circuit(n, inputs=state) for i in range(n): c.rz(i, theta=weights[i]) for i in range(n): c.depolarizing(i, px=p, py=p, pz=p, status=noise[i]) return K.real(c.expectation_ps(x=[0])) layer = tc.KerasLayer(f, [n]) v = {"state": K.ones([1, 2**n]) / 2 ** (n / 2), "noise": 0.2 * K.ones([1, n])} with tf.GradientTape() as tape: l = layer(v) grad = tape.gradient(l, layer.trainable_variables) ``` -------------------------------- ### Install JAX with CUDA 12 support Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/faq.rst This command installs JAX with CUDA 12 support, enabling GPU acceleration. It's recommended to use a virtual environment and ensure your NVIDIA drivers and CUDA toolkit are compatible. ```bash pip install -U "jax[cuda12]" ``` -------------------------------- ### Install TensorFlow with MacOS Optimization (v2.13+) Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_MacARM.md Installs TensorFlow optimized for MacOS, including the tensorflow-metal package for GPU acceleration. This is recommended for performance on Apple Silicon. ```python pip install tensorflow pip install tensorflow-metal ``` -------------------------------- ### Optimize Quantum Function with SciPy Interface Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst This example shows how to use the SciPy interface to optimize a quantum function. The `scipy_optimize_interface` transforms a quantum function into a format compatible with SciPy optimizers, providing both the function value and its gradient. This allows leveraging SciPy's optimization algorithms for quantum circuit parameter tuning. ```python import tensorcircuit as tc import numpy as np from scipy import optimize 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) 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) ``` -------------------------------- ### Create and Activate Conda Environment with Python 3.8.5 Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_MacM2.md Creates a new Conda virtual environment named 'NewEnv' and specifies Python version 3.8.5. It then activates this newly created environment for package installations. ```shell conda create --name NewEnv python==3.8.5 conda activate NewEnv ``` -------------------------------- ### VMAP for Parallel Circuit Evaluation Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Demonstrates the use of vectorized mapping (vmap) in TensorCircuit for parallel evaluation of quantum circuits. It shows how to process a batch of parameters to evaluate a parameterized circuit in parallel. ```python import tensorcircuit as tc K = tc.set_backend("tensorflow") # Define a parameterized circuit def param_circuit(params): c = tc.Circuit(2) c.rx(0, theta=params[0]) c.ry(1, theta=params[1]) return K.real(c.expectation([tc.gates.z(), [0]])) # Create batch of parameters batch_params = K.ones([10, 2]) # Vectorize the circuit evaluation vmap_circuit = K.vmap(param_circuit) results = vmap_circuit(batch_params) ``` -------------------------------- ### Sphinx Documentation Build (Chinese) Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribution.rst Command to build the Chinese version of the documentation using Sphinx, specifying the language and output directory. ```bash sphinx-build source -D language="zh" build/html_cn ``` -------------------------------- ### Use MPS as Input State for TensorCircuit Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Demonstrates how to represent a quantum state using Matrix Product States (MPS) and use it as an input for a TensorCircuit. This allows for more efficient state representation. ```Python n = 3 nodes = [tc.gates.Gate(np.array([0.0, 1.0])) for _ in range(n)] mps = tc.quantum.QuVector([nd[0] for nd in nodes]) c = tc.Circuit(n, mps_inputs=mps) c.x(0) c.expectation_ps(z=[0]) # 1.0 ``` -------------------------------- ### Code Linting with Pylint (Bash) Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/llm.md Analyzes the TensorCircuit library and example Python files for coding standard violations, potential errors, and code smells using Pylint. It helps maintain code quality and consistency. ```bash pylint tensorcircuit tests examples/*.py ``` -------------------------------- ### Apply MPO as Gate on TensorCircuit Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Illustrates applying a Matrix Product Operator (MPO) directly as a gate onto a TensorCircuit. This is useful for applying complex, multi-qubit operations represented in MPO format. ```Python x0, x1 = tc.gates.x(), tc.gates.x() mpo = tc.quantum.QuOperator([x0[0], x1[0]], [x0[1], x1[1]]) c = tc.Circuit(2) c.mpo(0, 1, mpo=mpo) c.state() # array([0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j], dtype=complex64) ``` -------------------------------- ### Extract Circuit Unitary Matrix Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst Shows how to extract the unitary matrix representing the entire quantum circuit. This is done by initializing the circuit with an identity input state and then calling `c.state()`. ```Python n = 2 c = tc.Circuit(n, inputs=tc.backend.eye(2**n)) c.X(1) reshaped_state = tc.backend.reshapem(c.state()) ``` -------------------------------- ### Install TensorFlow without MacOS Optimization Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_MacARM.md Installs TensorFlow version 2.7 using Conda, configuring channels for optimal package availability. This method is suitable if specific version control or environment isolation is needed. ```bash conda config --add channels conda-forge conda config --set channel_priority strict conda create -n tc_venv python tensorflow=2.7 ``` -------------------------------- ### Execute Noisy QML Example Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_windows.rst Runs the 'noisy_qml.py' script using the Python interpreter. This example demonstrates a noisy quantum machine learning application within the TensorCircuit environment. ```python python noisy_qml.py ``` -------------------------------- ### Run Tests with Coverage Report (Bash) Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/llm.md Executes all tests, generates an XML coverage report for integration with CI/CD systems, and provides verbose output. The `-svv` flags ensure detailed logging and verbose test execution. ```bash pytest --cov=tensorcircuit --cov-report=xml -svv --benchmark-skip ``` -------------------------------- ### Build and Install TensorCircuit (Bash) Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_MacM1.rst Builds and installs the TensorCircuit package locally after cloning the repository. ```bash python setup.py build python setup.py install ``` -------------------------------- ### Calculate Quantum Loss and Gradients with TensorFlow Backend Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst This snippet shows how to define a quantum circuit, calculate its expectation value as a loss, and compute the loss and its gradients using TensorFlow as the backend for TensorCircuit. It utilizes `K.jit` and `K.value_and_grad` for optimization. ```Python import tensorcircuit as tc K = tc.set_backend("tensorflow") n = 1 def loss(params, n): c = tc.Circuit(n) for i in range(n): c.rx(i, theta=params[0, i]) for i in range(n): c.rz(i, theta=params[1, i]) loss = 0.0 for i in range(n): loss += c.expectation([tc.gates.z(), [i]]) return K.real(loss) vgf = K.jit(K.value_and_grad(loss), static_argnums=1) params = K.implicit_randn([2, n]) print(vgf(params, n)) # get the quantum loss and the gradient ``` -------------------------------- ### TensorCircuit Runtime Configuration Source: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/infras.rst Manages runtime settings for ML backends, data types, and contractors. Offers global, function-level, and context-based setup methods. ```Python import tensorcircuit.cons as cons # Example usage: # cons.set_backend("jax") # cons.set_dtype("complex128") # with cons.contract_context(method="auto"): # # perform operations ```