Try Live
Add Docs
Rankings
Pricing
Enterprise
Docs
Install
Install
Docs
Pricing
Enterprise
More...
More...
Try Live
Rankings
Add Docs
TensorCircuit NG
https://github.com/tensorcircuit/tensorcircuit-ng
Admin
TensorCircuit NG is a next-generation open-source quantum computing framework built on tensor
...
Tokens:
183,840
Snippets:
1,313
Trust Score:
5.4
Update:
1 month ago
Context
Skills
Chat
Benchmark
91.1
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# TensorCircuit NG TensorCircuit-NG is the next-generation open-source high-performance quantum computing framework built on tensor network engines. It provides unified infrastructure for quantum circuit simulation across multiple ML backends (JAX, TensorFlow, PyTorch), supporting automatic differentiation, JIT compilation, hardware acceleration, vectorized parallelism, and distributed training. The framework seamlessly composes quantum circuits, neural networks, and tensor networks with exceptional simulation efficiency. TensorCircuit-NG supports diverse quantum computing paradigms including ideal state simulation (`Circuit`), noisy density matrix simulation (`DMCircuit`), Clifford/stabilizer circuits (`StabilizerCircuit`), qudit systems (`QuditCircuit`), MPS-based approximate simulation (`MPSCircuit`), analog quantum simulation (`AnalogCircuit`), symmetry-constrained circuits (`U1Circuit`), and fermionic Gaussian state simulation (`FGSSimulator`). It also provides quantum hardware access and CPU/GPU/QPU hybrid deployment capabilities. ## Backend and Runtime Configuration ### Set Backend Configure the machine learning backend (numpy, tensorflow, jax, pytorch) for tensor operations and automatic differentiation. ```python import tensorcircuit as tc # Set backend to JAX for JIT compilation and auto-diff tc.set_backend("jax") # Set backend to TensorFlow tc.set_backend("tensorflow") # Set backend to PyTorch tc.set_backend("pytorch") # Get current backend K = tc.get_backend() print(K.name) # Output: jax_backend # Context manager for temporary backend with tc.runtime_backend("tensorflow") as K: c = tc.Circuit(2) c.H(0) print(c.wavefunction()) ``` ### Set Data Type Configure the numerical precision for quantum state simulation. ```python import tensorcircuit as tc # Set to double precision (complex128) tc.set_dtype("complex128") # Set to single precision (default, complex64) tc.set_dtype("complex64") # Get current dtype settings dtype, rdtype = tc.get_dtype() print(dtype, rdtype) # Output: complex64 float32 ``` ### Set Contractor Configure the tensor network contraction strategy for optimal performance on large circuits. ```python import tensorcircuit as tc # Use automatic contractor selection tc.set_contractor("auto") # Use greedy contraction (fast for small circuits) tc.set_contractor("greedy") # Use cotengra for optimized large-scale contraction # tc.set_contractor("cotengra-30-10") # format: cotengra-{max_repeats}-{max_time} # Get current contractor contractor = tc.get_contractor() ``` ## Circuit Construction and Simulation ### Basic Circuit Operations Create quantum circuits and apply quantum gates with flexible parameter handling. ```python import tensorcircuit as tc import numpy as np tc.set_backend("jax") # Create a 3-qubit circuit c = tc.Circuit(3) # Apply single-qubit gates c.H(0) # Hadamard gate on qubit 0 c.X(1) # Pauli-X gate on qubit 1 c.Y(2) # Pauli-Y gate on qubit 2 c.Z(0) # Pauli-Z gate on qubit 0 c.S(1) # S gate (sqrt of Z) c.T(2) # T gate (fourth root of Z) # Apply parameterized rotation gates theta = tc.array_to_tensor(0.5) c.rx(0, theta=theta) # Rotation around X-axis c.ry(1, theta=0.3) # Rotation around Y-axis c.rz(2, theta=np.pi/4) # Rotation around Z-axis # General rotation gate with 3 parameters c.r(0, theta=0.1, alpha=0.2, phi=0.3) # Apply two-qubit gates c.CNOT(0, 1) # Controlled-NOT (control: 0, target: 1) c.CZ(1, 2) # Controlled-Z c.SWAP(0, 2) # SWAP gate # Parameterized two-qubit gates c.rzz(0, 1, theta=0.5) # ZZ rotation c.rxx(1, 2, theta=0.3) # XX rotation c.ryy(0, 2, theta=0.2) # YY rotation # Three-qubit gates c.toffoli(0, 1, 2) # Toffoli (CCX) c.fredkin(0, 1, 2) # Fredkin (CSWAP) # Get the output wavefunction psi = c.wavefunction() print(psi.shape) # Output: (8,) for 3 qubits # Get as different forms psi_ket = c.wavefunction(form="ket") # Shape: (8, 1) psi_bra = c.wavefunction(form="bra") # Shape: (1, 8) ``` ### Custom Gates and Unitary Operations Apply arbitrary unitary matrices and custom gates to circuits. ```python import tensorcircuit as tc import numpy as np tc.set_backend("jax") K = tc.get_backend() c = tc.Circuit(3) # Apply a custom single-qubit unitary custom_gate = np.array([[1, 1], [1, -1]]) / np.sqrt(2) # Hadamard c.any(0, unitary=custom_gate) # Apply a custom two-qubit gate iswap_matrix = np.array([ [1, 0, 0, 0], [0, 0, 1j, 0], [0, 1j, 0, 0], [0, 0, 0, 1] ]) c.any(0, 1, unitary=iswap_matrix) # Apply controlled version of any gate c.cany(0, 1, unitary=tc.gates.x().tensor) # Equivalent to CNOT # Apply multi-controlled gate c.mpo(0, 1, 2, mpo=tc.gates.toffoli()) # Apply exponential of Pauli strings: exp(-i * theta * Z0 Z1) c.exp1(0, 1, unitary=tc.gates._zz_matrix, theta=0.5) # Get the circuit unitary matrix U = c.matrix() print(U.shape) # Output: (8, 8) for 3 qubits ``` ### Circuit with Custom Initial State Initialize circuits with custom quantum states instead of the default |0⟩^n state. ```python import tensorcircuit as tc import numpy as np tc.set_backend("jax") # Create initial state (Bell state) bell_state = np.array([1, 0, 0, 1]) / np.sqrt(2) # Create circuit with custom input c = tc.Circuit(2, inputs=bell_state) c.H(0) c.CNOT(0, 1) psi = c.wavefunction() print(psi) # Initialize from MPS tensors # MPS tensor format: (left_bond, physical, right_bond) tensors = [ np.array([[[1.0], [0.0]]]), # Site 0: |0⟩ np.array([[[1.0]], [[0.0]]]), # Site 1: |0⟩ ] c_mps = tc.Circuit(2, tensors=tensors) c_mps.X(0) print(c_mps.wavefunction()) # Output: [0, 0, 1, 0] (|10⟩) ``` ## Expectation Values and Measurements ### Computing Expectation Values Compute expectation values of quantum observables efficiently. ```python import tensorcircuit as tc import numpy as np tc.set_backend("jax") K = tc.get_backend() c = tc.Circuit(4) c.H(0) c.CNOT(0, 1) c.rx(2, theta=0.5) c.ry(3, theta=0.3) # Single Pauli expectation z0 = c.expectation((tc.gates.z(), [0])) print(f"<Z0> = {z0}") # Output: <Z0> = 0.0 (for |+⟩ state) # Two-qubit correlation z0z1 = c.expectation((tc.gates.z(), [0]), (tc.gates.z(), [1])) print(f"<Z0Z1> = {z0z1}") # Using Pauli string shorthand exp_z01 = c.expectation_ps(z=[0, 1]) # <Z0 Z1> exp_x0 = c.expectation_ps(x=[0]) # <X0> exp_xy = c.expectation_ps(x=[0], y=[1]) # <X0 Y1> print(f"<Z0Z1> = {exp_z01}, <X0> = {exp_x0}, <X0Y1> = {exp_xy}") # Expectation with dense Hamiltonian matrix n = 2 H = tc.quantum.heisenberg_hamiltonian(n, [1.0, 1.0, 1.0]) # Heisenberg model c2 = tc.Circuit(n) c2.H(0) c2.CNOT(0, 1) energy = tc.templates.measurements.operator_expectation(c2, H) print(f"Energy = {K.real(energy)}") # Expectation with sparse Hamiltonian (efficient for large systems) from tensorcircuit.quantum import PauliStringSum2COO # Build Hamiltonian: H = Z0Z1 + Z1Z2 + X0 + X1 + X2 n = 3 pauli_structures = [ tc.quantum.xyz2ps({"z": [0, 1]}, n=n), tc.quantum.xyz2ps({"z": [1, 2]}, n=n), tc.quantum.xyz2ps({"x": [0]}, n=n), tc.quantum.xyz2ps({"x": [1]}, n=n), tc.quantum.xyz2ps({"x": [2]}, n=n), ] weights = [1.0, 1.0, -0.5, -0.5, -0.5] H_sparse = PauliStringSum2COO(pauli_structures, weights) c3 = tc.Circuit(n) c3.h(range(n)) energy_sparse = tc.templates.measurements.sparse_expectation(c3, H_sparse) print(f"Sparse H energy = {K.real(energy_sparse)}") ``` ### Sampling and Measurement Sample measurement outcomes from quantum circuits. ```python import tensorcircuit as tc tc.set_backend("jax") K = tc.get_backend() c = tc.Circuit(3) c.H(0) c.CNOT(0, 1) c.CNOT(1, 2) # Create GHZ state # Sample with state-based perfect sampling samples = c.sample(allow_state=True, batch=1000, format="count_dict_bin") print(samples) # Output: {'000': ~500, '111': ~500} # Sample as raw bitstrings raw_samples = c.sample(allow_state=True, batch=10, format="sample_bin") print(raw_samples) # Output: ['000', '111', '000', ...] # Sample specific qubits partial_samples = c.sample(allow_state=True, batch=100, format="count_dict_bin") print(partial_samples) # Measure specific qubits (collapses state, returns outcome) c2 = tc.Circuit(2) c2.H(0) c2.H(1) outcome, prob = c2.measure(0, with_prob=True) print(f"Measured qubit 0: {outcome}, probability: {prob}") # Mid-circuit measurement (post-selection) c3 = tc.Circuit(2) c3.H(0) c3.CNOT(0, 1) c3.mid_measurement(0, keep=0) # Post-select on |0⟩ for qubit 0 psi = c3.wavefunction() # Normalize manually after post-selection psi = psi / K.norm(psi) print(psi) # Output: [1, 0, 0, 0] (|00⟩) ``` ## Automatic Differentiation and JIT Compilation ### Gradient Computation Leverage automatic differentiation for variational quantum algorithms. ```python import tensorcircuit as tc tc.set_backend("jax") K = tc.get_backend() n = 4 nlayers = 2 def energy(params): """Compute energy expectation for a variational circuit.""" c = tc.Circuit(n) for j in range(nlayers): for i in range(n): c.rx(i, theta=params[j, i, 0]) c.ry(i, theta=params[j, i, 1]) for i in range(n - 1): c.cnot(i, i + 1) # Compute <Z0Z1> + <Z1Z2> + <Z2Z3> loss = 0.0 for i in range(n - 1): loss += c.expectation_ps(z=[i, i + 1]) return K.real(loss) # Compute gradient grad_fn = K.grad(energy) # Compute value and gradient together (more efficient) vg_fn = K.value_and_grad(energy) # JIT compile for speed vg_fn_jit = K.jit(vg_fn) # Initialize parameters params = K.implicit_randn(shape=[nlayers, n, 2], stddev=0.1) # Compute loss and gradients loss, grads = vg_fn_jit(params) print(f"Loss: {loss}, Gradient shape: {grads.shape}") # Training loop import tensorflow as tf # or use optax for JAX opt = K.optimizer(tf.keras.optimizers.Adam(0.1)) for step in range(100): loss, grads = vg_fn_jit(params) params = opt.update(grads, params) if step % 20 == 0: print(f"Step {step}: Loss = {loss:.6f}") ``` ### Vectorized Parallelism (vmap) Use vectorized mapping for batched circuit evaluation. ```python import tensorcircuit as tc import numpy as np tc.set_backend("jax") K = tc.get_backend() n = 4 def circuit_expectation(params): """Single circuit evaluation.""" c = tc.Circuit(n) for i in range(n): c.rx(i, theta=params[i]) for i in range(n - 1): c.cnot(i, i + 1) return K.real(c.expectation_ps(z=[0, 1])) # Vectorize over batch of parameters batched_fn = K.vmap(circuit_expectation) # JIT the vectorized function batched_fn_jit = K.jit(batched_fn) # Evaluate batch of circuits in parallel batch_size = 100 batch_params = K.implicit_randn(shape=[batch_size, n]) results = batched_fn_jit(batch_params) print(f"Batch results shape: {results.shape}") # Output: (100,) # Nested vmap for parameter and structure vectorization def parameterized_circuit(params, structure): """Circuit with parameterized structure.""" c = tc.Circuit(n) for i in range(n): c.rx(i, theta=params[i] * structure[i]) return K.real(c.expectation_ps(z=[0])) # Vmap over both parameters and structures double_vmap = K.vmap(K.vmap(parameterized_circuit, vectorized_argnums=1), vectorized_argnums=0) double_vmap_jit = K.jit(double_vmap) n_params = 50 n_structures = 20 all_params = K.implicit_randn(shape=[n_params, n]) all_structures = K.ones([n_structures, n]) results_matrix = double_vmap_jit(all_params, all_structures) print(f"Results shape: {results_matrix.shape}") # Output: (50, 20) ``` ## Noisy Quantum Simulation ### Density Matrix Circuit (DMCircuit) Simulate noisy quantum circuits using density matrix formalism. ```python import tensorcircuit as tc import numpy as np tc.set_backend("jax") K = tc.get_backend() # Create density matrix circuit c = tc.DMCircuit(2) c.H(0) c.CNOT(0, 1) # Apply depolarizing noise c.depolarizing(0, px=0.01, py=0.01, pz=0.01) c.depolarizing(1, px=0.01, py=0.01, pz=0.01) # Apply amplitude damping (T1 decay) c.amplitudedamping(0, gamma=0.05) # Apply phase damping (T2 dephasing) c.phasedamping(1, gamma=0.03) # Get the density matrix rho = c.densitymatrix() print(f"Density matrix shape: {rho.shape}") # Output: (4, 4) # Compute purity purity = K.real(K.trace(rho @ rho)) print(f"Purity: {purity}") # < 1 for mixed state # Compute expectation value exp_zz = c.expectation((tc.gates.z(), [0]), (tc.gates.z(), [1])) print(f"<Z0Z1>: {exp_zz}") # Quantum information measures entropy = tc.quantum.entropy(rho) print(f"Von Neumann entropy: {entropy}") # Entanglement entropy (for subsystem [0]) ent_entropy = tc.quantum.entanglement_entropy(rho, [0]) print(f"Entanglement entropy: {ent_entropy}") ``` ### Monte Carlo Noise Simulation Simulate noise via Monte Carlo trajectory sampling on state vector circuits. ```python import tensorcircuit as tc tc.set_backend("jax") K = tc.get_backend() def noisy_circuit(key): """Single Monte Carlo trajectory with noise.""" c = tc.Circuit(2) c.H(0) c.CNOT(0, 1) # Monte Carlo depolarizing: randomly applies I, X, Y, or Z c.depolarizing(0, px=0.01, py=0.01, pz=0.01) c.depolarizing(1, px=0.01, py=0.01, pz=0.01) return K.real(c.expectation_ps(z=[0, 1])) # Vectorize over random keys for Monte Carlo sampling batch_noisy = K.vmap(noisy_circuit) batch_noisy_jit = K.jit(batch_noisy) # Run many trajectories n_trajectories = 1000 keys = K.implicit_randu(shape=[n_trajectories]) results = batch_noisy_jit(keys) # Average over trajectories mean_exp = K.mean(results) std_exp = K.std(results) print(f"<Z0Z1> = {mean_exp:.4f} ± {std_exp/np.sqrt(n_trajectories):.4f}") ``` ### Noise Model Configuration Configure systematic noise models for realistic device simulation. ```python import tensorcircuit as tc from tensorcircuit.noisemodel import NoiseConf tc.set_backend("jax") K = tc.get_backend() # Create noise configuration noise_conf = NoiseConf() # Add single-qubit depolarizing noise after rx gates error1q = tc.channels.generaldepolarizingchannel(0.01, 1) noise_conf.add_noise("rx", error1q) noise_conf.add_noise("ry", error1q) noise_conf.add_noise("rz", error1q) # Add two-qubit noise after CNOT gates error2q = tc.channels.generaldepolarizingchannel(0.02, 2) noise_conf.add_noise("cnot", [error2q], [[0, 1], [1, 2]]) # Specify qubit pairs # Create and run circuit with noise model c = tc.Circuit(3) c.rx(0, theta=0.5) c.ry(1, theta=0.3) c.cnot(0, 1) c.cnot(1, 2) # Compute noisy expectation via Monte Carlo noisy_exp = c.expectation( (tc.gates.z(), [0]), noise_conf=noise_conf, nmc=1000 # Number of Monte Carlo samples ) print(f"Noisy <Z0>: {K.real(noisy_exp)}") ``` ## Variational Quantum Algorithms ### Variational Quantum Eigensolver (VQE) Implement VQE for finding ground state energies. ```python import tensorcircuit as tc import numpy as np tc.set_backend("jax") K = tc.get_backend() # Define Hamiltonian: Transverse-field Ising model # H = -J * sum(Z_i Z_{i+1}) - h * sum(X_i) n = 6 J, h = 1.0, 0.5 def build_hamiltonian(): pauli_structures = [] weights = [] # ZZ interactions for i in range(n - 1): pauli_structures.append(tc.quantum.xyz2ps({"z": [i, i + 1]}, n=n)) weights.append(-J) # Transverse field for i in range(n): pauli_structures.append(tc.quantum.xyz2ps({"x": [i]}, n=n)) weights.append(-h) return tc.quantum.PauliStringSum2COO(pauli_structures, weights) H = build_hamiltonian() # Define variational ansatz nlayers = 3 def vqe_energy(params): c = tc.Circuit(n) # Initial layer for i in range(n): c.h(i) # Variational layers for j in range(nlayers): for i in range(n): c.rx(i, theta=params[j, i, 0]) c.rz(i, theta=params[j, i, 1]) for i in range(n - 1): c.cnot(i, i + 1) return K.real(tc.templates.measurements.sparse_expectation(c, H)) # Compile gradient function vqe_vg = K.jit(K.value_and_grad(vqe_energy)) # Optimization params = K.implicit_randn(shape=[nlayers, n, 2], stddev=0.1) import optax # JAX optimizer library optimizer = optax.adam(0.05) opt_state = optimizer.init(params) for step in range(200): energy, grads = vqe_vg(params) updates, opt_state = optimizer.update(grads, opt_state) params = optax.apply_updates(params, updates) if step % 40 == 0: print(f"Step {step}: Energy = {energy:.6f}") print(f"Final VQE energy: {energy:.6f}") ``` ### QAOA for MaxCut Implement Quantum Approximate Optimization Algorithm. ```python import tensorcircuit as tc import numpy as np tc.set_backend("tensorflow") K = tc.get_backend() import tensorflow as tf # Define graph (MaxCut problem) edges = [(0, 1), (1, 2), (2, 3), (3, 0), (0, 2)] n = 4 nlayers = 3 def qaoa_circuit(gamma, beta): c = tc.Circuit(n) # Initial superposition for i in range(n): c.h(i) # QAOA layers for j in range(nlayers): # Cost Hamiltonian: exp(-i * gamma * Z_i Z_j) for each edge for (i, k) in edges: c.exp1(i, k, unitary=tc.gates._zz_matrix, theta=gamma[j]) # Mixer Hamiltonian: exp(-i * beta * X_i) for i in range(n): c.rx(i, theta=beta[j]) # Compute MaxCut cost cost = 0.0 for (i, k) in edges: cost += 0.5 * (1 - c.expectation_ps(z=[i, k])) return K.real(cost) def loss_fn(gamma, beta): return -qaoa_circuit(gamma, beta) # Maximize cost = minimize negative # Compile with JIT qaoa_vg = K.jit(K.value_and_grad(loss_fn, argnums=(0, 1))) # Initialize parameters gamma = K.implicit_randn(shape=[nlayers], stddev=0.1) beta = K.implicit_randn(shape=[nlayers], stddev=0.1) # Optimize opt = K.optimizer(tf.keras.optimizers.Adam(0.1)) for step in range(150): loss, (grad_gamma, grad_beta) = qaoa_vg(gamma, beta) gamma, beta = opt.update((grad_gamma, grad_beta), (gamma, beta)) if step % 30 == 0: print(f"Step {step}: MaxCut value = {-loss:.4f}") print(f"Final MaxCut value: {-loss:.4f}") ``` ## Machine Learning Integration ### Keras Integration (TensorFlow) Integrate quantum circuits as Keras layers for hybrid quantum-classical models. ```python import tensorcircuit as tc import tensorflow as tf import numpy as np tc.set_backend("tensorflow") K = tc.get_backend() n = 4 nlayers = 2 def quantum_layer(inputs, weights): """Quantum circuit as a differentiable function.""" c = tc.Circuit(n) # Encode classical input for i in range(n): c.rx(i, theta=inputs[i]) # Variational layers for j in range(nlayers): for i in range(n): c.ry(i, theta=weights[j, i]) for i in range(n - 1): c.cnot(i, i + 1) # Output: expectation values outputs = K.stack([K.real(c.expectation_ps(z=[i])) for i in range(n)]) return outputs # Create Keras layer ql = tc.KerasLayer( quantum_layer, weights_shape=[nlayers, n], initializer=tf.keras.initializers.RandomUniform(-np.pi, np.pi) ) # Build hybrid model model = tf.keras.Sequential([ tf.keras.layers.Dense(n, activation='tanh'), ql, tf.keras.layers.Dense(2, activation='softmax') ]) # Compile and train model.compile( optimizer=tf.keras.optimizers.Adam(0.01), loss='sparse_categorical_crossentropy', metrics=['accuracy'] ) # Dummy training data X_train = np.random.randn(100, n).astype(np.float32) y_train = np.random.randint(0, 2, size=100) model.fit(X_train, y_train, epochs=10, batch_size=16, verbose=1) ``` ### PyTorch Integration Use quantum circuits within PyTorch neural networks. ```python import tensorcircuit as tc import torch import numpy as np tc.set_backend("tensorflow") # Backend for quantum computation K = tc.get_backend() n = 4 nlayers = 2 def qnn_forward(x, weights): """Quantum neural network forward pass.""" 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): c.ry(i, theta=weights[j, i]) for i in range(n - 1): c.cnot(i, i + 1) return K.stack([K.real(c.expectation_ps(z=[i])) for i in range(n)]) # Create PyTorch module qnn = tc.TorchLayer( qnn_forward, weights_shape=[nlayers, n], use_vmap=True, use_jit=True ) # Build hybrid model class HybridModel(torch.nn.Module): def __init__(self): super().__init__() self.classical_pre = torch.nn.Linear(8, n) self.quantum = qnn self.classical_post = torch.nn.Linear(n, 2) def forward(self, x): x = torch.tanh(self.classical_pre(x)) x = self.quantum(x) return self.classical_post(x) model = HybridModel() # Training setup optimizer = torch.optim.Adam(model.parameters(), lr=0.01) criterion = torch.nn.CrossEntropyLoss() # Dummy data X = torch.randn(64, 8) y = torch.randint(0, 2, (64,)) # Training step model.train() for epoch in range(10): optimizer.zero_grad() outputs = model(X) loss = criterion(outputs, y) loss.backward() optimizer.step() print(f"Epoch {epoch}: Loss = {loss.item():.4f}") ``` ## Advanced Circuit Types ### MPS Circuit for Large-Scale Simulation Use Matrix Product State approximation for circuits with limited entanglement. ```python import tensorcircuit as tc tc.set_backend("jax") K = tc.get_backend() # Create MPS circuit with bond dimension control n = 20 # Can handle many more qubits than exact simulation c = tc.MPSCircuit(n, split={"max_singular_values": 32}) # Bond dimension ≤ 32 c.h(0) for i in range(n - 1): c.cnot(i, i + 1) # Create a large GHZ-like state # Compute expectation (much faster than exact for large n) exp_z0zn = c.expectation((tc.gates.z(), [0]), (tc.gates.z(), [n-1])) print(f"<Z0 Z{n-1}> = {exp_z0zn}") # Get MPS tensors tensors = c.get_tensors() print(f"Number of MPS tensors: {len(tensors)}") print(f"Bond dimensions: {[t.shape for t in tensors]}") ``` ### Stabilizer Circuit (Clifford Simulation) Efficiently simulate Clifford circuits using stabilizer formalism. ```python import tensorcircuit as tc # StabilizerCircuit requires stim backend try: c = tc.StabilizerCircuit(10) # Only Clifford gates allowed c.H(0) c.S(1) c.CNOT(0, 1) c.CZ(1, 2) # Can handle 1000+ qubits efficiently for i in range(2, 10): c.H(i) c.CNOT(i-1, i) # Sample efficiently samples = c.sample(batch=1000, format="count_dict_bin") print(samples) # Compute Pauli expectation exp_z = c.expectation_ps(z=[0, 1]) print(f"<Z0Z1> = {exp_z}") except ModuleNotFoundError: print("Install stim for StabilizerCircuit: pip install stim") ``` ### Qudit Circuit Simulate quantum systems with d-level qudits. ```python import tensorcircuit as tc import numpy as np tc.set_backend("jax") # Create 3-level (qutrit) circuit d = 3 n = 2 c = tc.QuditCircuit(n, d=d) # Apply qudit gates c.h(0) # Generalized Hadamard for qutrits # Custom qutrit gate qutrit_x = np.array([ [0, 0, 1], [1, 0, 0], [0, 1, 0] ], dtype=np.complex64) c.any(1, unitary=qutrit_x) # Two-qudit gate c.cnot(0, 1) # Get state (d^n dimensional) psi = c.wavefunction() print(f"Qutrit state shape: {psi.shape}") # Output: (9,) for 2 qutrits ``` ### Fermion Gaussian State Simulator Efficiently simulate non-interacting fermionic systems. ```python import tensorcircuit as tc import numpy as np tc.set_backend("jax") K = tc.get_backend() # Create 8-site fermionic system with sites 0, 2, 4 occupied sim = tc.FGSSimulator(L=8, filled=[0, 2, 4]) # Apply hopping evolution: exp(-i * chi * (c_i^dag c_j + h.c.)) for i in range(7): sim.evol_hp(i=i, j=i+1, chi=0.5) # Hopping with strength 0.5 # Get correlation matrix <c_i^dag c_j> C = sim.cmatrix() print(f"Correlation matrix shape: {C.shape}") # Compute entanglement entropy for subsystem [0, 1, 2, 3] entropy = sim.entropy([0, 1, 2, 3]) print(f"Entanglement entropy: {entropy}") # Compute two-point correlator corr = sim.correlation(0, 4) # <c_0^dag c_4> print(f"Two-point correlator <c0† c4>: {corr}") ``` ## Framework Translation ### Convert Between Frameworks Translate circuits between TensorCircuit, Qiskit, and Cirq. ```python import tensorcircuit as tc from tensorcircuit import translation tc.set_backend("numpy") # Create TensorCircuit circuit c = tc.Circuit(3) c.h(0) c.rx(1, theta=0.5) c.cnot(0, 1) c.ry(2, theta=0.3) c.cz(1, 2) # Get quantum intermediate representation (QIR) qir = c.to_qir() print(f"QIR has {len(qir)} operations") # Convert to Qiskit try: qiskit_circuit = translation.qir2qiskit(qir, 3) print(qiskit_circuit) except ImportError: print("Install qiskit for conversion: pip install qiskit") # Convert to Cirq try: cirq_circuit = translation.qir2cirq(qir, 3) print(cirq_circuit) except ImportError: print("Install cirq for conversion: pip install cirq") # Convert Qiskit circuit to TensorCircuit try: from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) tc_circuit = translation.qiskit2tc(qc) print(tc_circuit.wavefunction()) except ImportError: print("Install qiskit for conversion") ``` ## Summary TensorCircuit-NG provides a comprehensive quantum computing simulation platform optimized for variational quantum algorithms, quantum machine learning, and quantum-classical hybrid applications. Its key strengths include: seamless integration with modern ML frameworks (JAX, TensorFlow, PyTorch) enabling automatic differentiation and GPU acceleration; support for multiple simulation paradigms (state vector, density matrix, MPS, stabilizer, fermionic); and highly optimized tensor network contraction for large-scale simulations. The framework excels in research scenarios requiring rapid prototyping of variational algorithms (VQE, QAOA, QML), noise-aware simulation for NISQ device modeling, and integration of quantum components into classical neural network architectures. Users can leverage vectorized parallelism (vmap) for efficient parameter sweeps, JIT compilation for production-ready performance, and built-in templates for common quantum computing patterns. The unified API design allows switching between backends and circuit types with minimal code changes, while the QIR-based translation system enables interoperability with other quantum frameworks.