### Install SeeMPS2 Directly from GitHub via Pip Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/getting_started.rst Install the SeeMPS2 project directly from its internet source (GitHub) using pip. This method installs the required dependencies, compiles the library, and installs it into your current Python environment. ```bash pip install git+https://github.com/juanjosegarciaripoll/seemps2.git ``` -------------------------------- ### Install SeeMPS2 from Local Folder via Pip Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/getting_started.rst Install the SeeMPS2 project into your Python environment after cloning the repository. This command uses pip to install the library and its required dependencies. ```bash pip install seemps2 ``` -------------------------------- ### Clone SeeMPS2 Repository with Git Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/getting_started.rst Clone the SeeMPS2 project from GitHub to obtain a local copy of the repository. This command fetches all project files, including notebooks and the Python library. ```bash git clone https://github.com/juanjosegarciaripoll/seemps2.git ``` -------------------------------- ### Setup Quantum Space and Target Function Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/Interpolation.ipynb Initializes a quantum `Space` object with a specified number of qubits and defines the target m-qubit function (`f_m`) using a Gaussian distribution, normalizing it. ```python n = 3 qubits_per_dimension = [n] L = np.sqrt(2*np.pi*2**n) space = Space(qubits_per_dimension, L=[[-L/2,L/2]], closed=False) m = 12 M = 2**m new_space = space.increase_resolution([m]) x_m = new_space.x[0] f_m = gaussian(x_m) f_m /= np.linalg.norm(f_m) ``` -------------------------------- ### Example: HeisenbergHamiltonian Construction Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/seemps_objects_hamiltonians.rst Demonstrates how to construct a Heisenberg Hamiltonian using ConstantTIHamiltonian. It involves defining spin operators and combining them to form the Hamiltonian. ```python >>> import seemps.systems.spin as sp >>> σx, σy, σz = sp.sigma_matrices() >>> SdotS = 0.25 * (sp.kron(σx, σx) + sp.kron(σy, σy) + sp.kron(σz, σz)) >>> ConstantTIHamiltonian(size, SdotS) ``` -------------------------------- ### Sequential Two-Site Unitary Application Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/algorithms/tensor_update.rst Example of sequentially applying a list of two-site unitaries from left to right on a quantum state represented by an MPS. It demonstrates the use of `update_2site_right` for in-place updates. ```python ... if center > 1: state.recenter(1) for j in range(L - 1): ## C = np.einsum("ijk,klm,nrjl -> inrm", state[j], state[j + 1], U[j]) state.update_2site_right( _contract_nrjl_ijk_klm(U[j], state[j], state[j + 1]), j, strategy ) ... ``` -------------------------------- ### Create initial MPS from interval Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/Chebyshev.ipynb Generates an initial Matrix Product State (MPS) that represents a regular, equispaced interval within the canonical Chebyshev interval [-1, 1]. This MPS serves as the starting point for function composition. ```Python mps_x = mps_interval(domain) ``` -------------------------------- ### MPSArnoldiRepresentation.restart_with_vector Method Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/algorithms/generated/seemps.optimization.arnoldi.MPSArnoldiRepresentation.restart_with_vector.rst Restarts the Arnoldi representation with a specified vector. This method is part of the MPSArnoldiRepresentation class, used for optimization processes. It typically involves re-initializing the Arnoldi basis using a new starting vector, which can be crucial for convergence or adapting to changes in the problem. ```APIDOC seemps.optimization.arnoldi.MPSArnoldiRepresentation.restart_with_vector .. automethod:: seemps.optimization.arnoldi.MPSArnoldiRepresentation.restart_with_vector Method Signature: restart_with_vector(self, vector) Description: Restarts the Arnoldi representation with the given vector. Parameters: - vector: The initial vector to restart the Arnoldi process with. The type and shape are expected to be compatible with the internal representation of the Arnoldi method. Returns: None. This method modifies the internal state of the MPSArnoldiRepresentation object. Related Methods: - __init__: Initializes the MPSArnoldiRepresentation. - add_vector: Adds a new vector to the Arnoldi representation. ``` -------------------------------- ### Import SeeMPS and NumPy Libraries Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/DMRG.ipynb Imports essential tools for DMRG calculations, including Hamiltonian construction, optimization algorithms, state representation, and numerical operations. ```Python from seemps.hamiltonians import ConstantTIHamiltonian from seemps.optimization import dmrg from seemps.state import MPS, product_state import numpy as np ``` -------------------------------- ### Get Eigenvector (MPSArnoldiRepresentation) Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/algorithms/generated/seemps.optimization.arnoldi.MPSArnoldiRepresentation.eigenvector.rst Retrieves the eigenvector associated with the MPSArnoldiRepresentation. This method is part of the Arnoldi iteration process for optimization problems. ```APIDOC seemps.optimization.arnoldi.MPSArnoldiRepresentation.eigenvector Retrieves the eigenvector. Parameters: None Returns: The eigenvector (e.g., a numpy.ndarray or similar numerical structure). Example: # Assuming 'arnoldi_rep' is an instance of MPSArnoldiRepresentation # eigenvector = arnoldi_rep.eigenvector() ``` -------------------------------- ### Import necessary libraries Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/Chebyshev.ipynb Imports essential modules for numerical operations, plotting, and MPS analysis, including functions for Chebyshev approximation and interval representation. ```Python import numpy as np import matplotlib.pyplot as plt from seemps.analysis.mesh import RegularInterval from seemps.analysis.factories import mps_interval from seemps.analysis.chebyshev import ( interpolation_coefficients, projection_coefficients, cheb2mps, ) ``` -------------------------------- ### Run Phase Transition Experiment with Larger System Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/DMRG.ipynb Executes the `experiment_00` function with a larger system size (N=30) and an increased number of steps (31) to observe the quantum phase transition behavior across a wider range of the transverse magnetic field. ```Python experiment_00(N=30, steps=31) ``` -------------------------------- ### Chebyshev Expansion Methods Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/seemps_analysis_loading.rst Methods for composing univariate functions on generic initial MPS or MPO structures and computing MPS approximations of functions using Chebyshev polynomials. ```python from seemps.analysis.chebyshev import cheb2mps from seemps.analysis.chebyshev import cheb2mpo from seemps.analysis.chebyshev import interpolation_coefficients from seemps.analysis.chebyshev import projection_coefficients from seemps.analysis.chebyshev import estimate_order ``` -------------------------------- ### MPS Class and Creation Methods Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/seemps_objects_mps.rst Documentation for the core MPS class and its static methods for creating MPS instances from various inputs, including vectors, tensors, and specific quantum states. ```APIDOC seemps.state.MPS Represents a Matrix-Product State (MPS). Stores a sequence of tensors and associated metadata. seemps.state.MPS.from_vector(vector, dims, **kwargs) Creates an MPS from a state vector. Parameters: vector: The input state vector. dims: A list of physical dimensions for each site. Returns: An MPS instance. seemps.state.MPS.from_tensor(tensor, dims, **kwargs) Creates an MPS from a tensor representation. Parameters: tensor: The input tensor. dims: A list of physical dimensions for each site. Returns: An MPS instance. seemps.state.AKLT(**kwargs) Creates an AKLT (Affleck-Kennedy-Lieb-Tasaki) state. seemps.state.GHZ(**kwargs) Creates a GHZ (Greenberger-Horne-Zeilinger) state. seemps.state.product_state(dims, **kwargs) Creates a product state. Parameters: dims: A list of physical dimensions for each site. Returns: An MPS instance representing a product state. seemps.state.random_uniform_mps(dims, **kwargs) Creates a random MPS with uniform weights. Parameters: dims: A list of physical dimensions for each site. Returns: An MPS instance. seemps.state.W(**kwargs) Creates a W state. ``` -------------------------------- ### cheb2mpo: Convert Chebyshev polynomial to Matrix Polynomial Object Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/algorithms/generated/seemps.analysis.chebyshev.cheb2mpo.rst This snippet documents the `cheb2mpo` function from the `seemps.analysis.chebyshev` module. It is intended for converting Chebyshev polynomials into a Matrix Polynomial Object representation. Specific details regarding parameters, return values, and usage examples are not available in the provided text. ```python from seemps.analysis.chebyshev import cheb2mpo # Documentation for cheb2mpo function # Purpose: Convert Chebyshev polynomial to Matrix Polynomial Object # Module: seemps.analysis.chebyshev # Further details on parameters, return values, and usage are not provided in the input. ``` -------------------------------- ### Construct Initial Conditions for Chebyshev Expansion Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/algorithms/chebyshev.rst Methods for building the initial MPS or MPO states required for function composition. This includes creating discretized domains using `Interval` objects and constructing MPS from these intervals using `mps_interval`. ```python from seemps.analysis.mesh import Interval, RegularInterval, ChebyshevInterval from seemps.analysis.factories import mps_interval # Example usage (conceptual): # interval = RegularInterval(start=-1.0, stop=1.0, n_points=100) # mps_from_interval = mps_interval(interval) ``` -------------------------------- ### Visualize Exact and MPS Approximations Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/Chebyshev.ipynb Generates a 3D surface plot to visualize the exact bivariate Gaussian function and its MPS approximations obtained using serial ('A') and interleaved ('B') qubit orderings. This provides a visual comparison of the accuracy and characteristics of the MPS representations. ```python fig = plt.figure() ax = fig.add_subplot(111, projection="3d") ax.plot_surface(X, Y, y_vec, label="Exact") ax.plot_surface(X, Y, y_mps_A, label="MPS serial") ax.plot_surface(X, Y, y_mps_B, label="MPS interleaved") ax.legend() ``` -------------------------------- ### Tensorized Operations for MPS Construction Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/seemps_analysis_loading.rst Methods for constructing MPS corresponding to domain discretizations, and composing them using tensor products and sums to build multivariate domains. ```python from seemps.analysis.mesh import RegularInterval from seemps.analysis.mesh import ChebyshevInterval from seemps.analysis.factories import mps_interval from seemps.analysis.factories import mps_tensor_product from seemps.analysis.factories import mps_tensor_sum ``` -------------------------------- ### Plot Exact Function and Find Min/Max Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/Optimization.ipynb Creates a regular interval domain, evaluates the defined function over this domain, and finds the exact minimum and maximum values using NumPy's `argmin` and `argmax`. The function is then plotted with markers indicating these exact extrema. ```python start = -1 stop = 1 num_qubits = 15 domain = RegularInterval(start, stop, 2**num_qubits) x = domain.to_vector() y_vec = func(x) i_min_vec = np.argmin(y_vec) y_min_vec = y_vec[i_min_vec] i_max_vec = np.argmax(y_vec) y_max_vec = y_vec[i_max_vec] print("Min: ", y_min_vec, " Max: ", y_max_vec) plt.plot(x, y_vec) plt.scatter(x[i_min_vec], y_min_vec, color="r", label="Exact min.") plt.scatter(x[i_max_vec], y_max_vec, color="r", label="Exact max.") plt.xlabel("x") plt.ylabel("f(x)") plt.legend() ``` -------------------------------- ### Create equivalent operators U3 and U4 Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/seemps_register.rst Demonstrates the creation of equivalent quantum operators using LocalRotationsLayer, TwoQubitGatesLayer, ParameterizedLayeredCircuit, and VQECircuit from the seemps.register.circuits module. ```python from seemps.register.circuits import * U1 = LocalRotationsLayer(register_size=2, operator='Sz') U2 = TwoQubitGatesLayer(register_size=2) U3 = ParameterizedLayeredCircuit(register_size=2, layers=[U1, U2]) U4 = VQECircuit(register_size=2, layers=2) ``` -------------------------------- ### Interpolate Quantum Function using Fourier and Finite Differences Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/Interpolation.ipynb Demonstrates interpolating a quantum function using both Fourier and finite differences methods. It converts the results to vectors for further analysis and comparison. ```python f_fourier_mps = fourier_interpolation(f_n_mps, space, [n], [m]) f_fd_mps = finite_differences_interpolation(f_n_mps, space) f_fourier = f_fourier_mps.to_vector() f_fd = f_fd_mps.to_vector() ``` -------------------------------- ### MPO and MPOList Creation and Manipulation Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/seemps_objects_mpo.rst Details on creating and manipulating Matrix-Product Operators (MPO) and MPOList objects in SeeMPS. This includes initialization from tensors, reconstruction from state vectors, scaling by scalars, and extending the MPO to include new quantum subsystems. ```python import seemps # Creating an MPO from tensors (example) # mpo = seemps.MPO(tensors) # Creating an MPOList from a sequence of operators # mpo_list = seemps.MPOList([mpo1, mpo2]) # Scaling an MPO by a scalar # scaled_mpo = mpo * 2.5 # Extending an MPO to include new subsystems # extended_mpo = mpo.extend(new_subsystems) ``` -------------------------------- ### Apply parameterized rotations to MPS state Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/seemps_register.rst Shows how to apply parameterized rotations to an MPS state using LocalRotationsLayer. It illustrates two ways to provide parameters: at construction time or during the apply method. ```python p = [0.13, -0.25] U1 = LocalRotationsLayer(register_size=2, operator='Sz', same_angle=False, default_parameters=p) state = U1.apply(state) ``` ```python p = [0.13, -0.25] U1 = LocalRotationsLayer(register_size=2, operator='Sz', same_angle=False) state = U1.apply(state, p) ``` -------------------------------- ### Crank-Nicolson Method Equation Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/algorithms/crank_nicolson.rst The core mathematical representation of the Crank-Nicolson method, showing the approximation of the state at the k+1 iteration based on the state at the k iteration. ```math \left(\mathbb{I}+\frac{i\Delta t}{2}H\right)\psi_{k+1}=\left(\mathbb{I}-\frac{i\Delta t}{2}H\right)\psi_{k}. ``` -------------------------------- ### Compare MPS Approximation with Exact Function Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/Chebyshev.ipynb Evaluates the exact bivariate Gaussian function and its MPS approximations (in both serial and interleaved orders) on a grid. It then calculates and prints the maximum absolute error for each MPS representation, demonstrating the accuracy of the approximation and the effect of qubit ordering. ```python x = domain.to_vector() X, Y = np.meshgrid(x, x) y_vec = np.exp(-(X**2 + Y**2)) shape = (x.size, x.size) y_mps_A = mps_gaussian_2d_A.to_vector().reshape(shape) y_mps_B = mps_gaussian_2d_B.to_vector().reshape(shape) # Note: the interleaved tensor must be reshaped to be compared with the serial tensor. # This is not a good practice so the required function is not present in the library. y_mps_B = reorder_tensor(y_mps_B, [num_qubits, num_qubits]) print("Error in Chebyshev norm in serial order: ", np.max(np.abs(y_vec - y_mps_A))) print("Error in Chebyshev norm in interleaved order: ", np.max(np.abs(y_vec - y_mps_B))) ``` -------------------------------- ### Study Quantum Phase Transition with DMRG Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/DMRG.ipynb Defines and executes an experiment to explore the quantum phase transition as a function of the transverse magnetic field 'h'. It computes and plots magnetization values and optionally compares DMRG results with exact diagonalization for small system sizes. ```Python import matplotlib.pyplot as plt from time import process_time def experiment_00(N: int = 30, steps: int = 21): """Explore the quantum phase transition as a function of the transverse magnetic field $h$. Plots the magnetizations of the ground state, computed with a small symmetry breaking term.""" h = np.linspace(0, 2, steps) epsilon = 0 sx = np.array([[0, 1], [1, 0]]) sz = np.array([[1, 0], [0, -1]]) sz_values = [] sx_values = [] extras = "" ZZ = ConstantTIHamiltonian(size=N, interaction=np.kron(sz, sz)) X = ConstantTIHamiltonian(size=N, local_term=sx) for hi in h: H = ConstantTIHamiltonian( size=N, interaction=np.kron(sz, sz), local_term=-hi * sx + epsilon * sz ) time = process_time() result = dmrg(H, guess=product_state(np.ones(2) / np.sqrt(2), N), maxiter=100) time = process_time() - time sz_values.append(ZZ.to_mpo().expectation(result.state)) sx_values.append(X.to_mpo().expectation(result.state)) if N <= 20: E, psi0 = eigsh(H.to_matrix(), v0=result.state.to_vector(), k=1, which="SA") E = E[0] psi0 = psi0[:, 0] sz_exact = np.vdot(psi0, ZZ.to_matrix() @ psi0) sx_exact = np.vdot(psi0, X.to_matrix() @ psi0) extras = ( f", errors: E = {abs(E - result.energy):6e}, " f"Sz = {sz_exact - sz_values[-1]:6e}, " f"Sx = {sx_exact - sx_values[-1]:6e}" ) print(f"Energy = {result.energy:+6f}, time = {time:5f}s" + extras) fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(8, 4)) ax1.plot(h, sz_values) ax1.set_xlabel(r"$h$") ax1.set_ylabel(r"$\langle{\sigma^z_{i}\cdot \sigma^z_{i+1}}\rangle$") ax2.plot(h, sx_values) ax2.set_xlabel(r"$h$") ax2.set_ylabel(r"$\langle{S_x}\rangle$") fig.tight_layout() experiment_00(N=15) ``` -------------------------------- ### Import MPS Tensor Sum Function Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/Chebyshev.ipynb Imports the necessary `mps_tensor_sum` function from the `seemps.analysis.factories` module, which is used for constructing MPS representations of sums of functions. ```python from seemps.analysis.factories import mps_tensor_sum ``` -------------------------------- ### Generic Polynomial Construction Methods Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/seemps_analysis_loading.rst Methods for constructing generic polynomials in the monomial basis from a collection of coefficients. This allows for direct MPS representation of polynomial functions. ```python from seemps.analysis.polynomials import mps_from_polynomial ``` -------------------------------- ### Jinja2 Template for Sphinx API Docs Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/_templates/autosummary/base.rst This Jinja2 template is designed for use with Sphinx to generate API documentation. It dynamically includes content based on object types and uses filters for formatting. ```jinja {% if objtype == 'property' %} :orphan: {% endif %} {{ fullname | escape | underline}} .. currentmodule:: {{ module }} {% if objtype == 'property' %} property {% endif %} .. auto{{ objtype }}:: {{ fullname | replace("numpy.", "numpy::") }} ``` -------------------------------- ### Jinja2 Comment for Module Name Clarification Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/_templates/autosummary/base.rst A Jinja2 comment explaining how to handle ambiguous module names in the `fullname` variable by using `::` as a separator to specify the module. ```jinja {# In the fullname (e.g. `numpy.ma.MaskedArray.methodname`), the module name is ambiguous. Using a `::` separator (e.g. `numpy::ma.MaskedArray.methodname`) specifies `numpy` as the module name. #} ``` -------------------------------- ### Construct Quadrature MPS Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/Integration.ipynb Constructs the necessary quadrature MPS for integration. It first creates a 1D Clenshaw-Curtis quadrature MPS and then generalizes it to a 10-dimensional quadrature MPS using tensor products. ```Python from seemps.analysis.integration import mps_clenshaw_curtis from seemps.analysis.factories import mps_tensor_product # Assuming 'start', 'stop', 'num_qubits', and 'dimension' are defined from previous steps # start = -1 # stop = 1 # num_qubits = 3 # dimension = 10 mps_quad_1d = mps_clenshaw_curtis(start, stop, num_qubits) mps_quad_10d = mps_tensor_product([mps_quad_1d] * dimension) ``` -------------------------------- ### cgs Function Documentation Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/algorithms/generated/seemps.cgs.cgs.rst Details the functionality, parameters, and return values of the cgs function. This entry serves as the primary documentation for the function, extracted from the module's docstring. ```python def cgs(self, x: np.ndarray, y: np.ndarray, z: np.ndarray, n_iter: int = 1000, tol: float = 1e-05, **kwargs) -> tuple[np.ndarray, np.ndarray, np.ndarray] ``` -------------------------------- ### Load MPO Black-Box with TT-Cross DMRG Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/TT-Cross.ipynb Demonstrates loading a bivariate function into a Matrix Product Operator (MPO) using `BlackBoxLoadMPO`. The function is first represented as an MPS and then unfolded into an MPO. This is suitable for bivariate functions where inputs correspond to MPO rows and columns. ```python from seemps.analysis.cross import BlackBoxLoadMPO import numpy as np from seemps.analysis.mesh import Mesh, RegularInterval from seemps.truncate.simplify_mpo import mps_as_mpo from seemps.analysis.cross import cross_dmrg # Define the bivariate black-box function func = lambda x, y: np.exp(-(x**2 + y**2)) # Define mesh parameters start, stop = -1, 1 num_qubits = 10 interval = RegularInterval(start, stop, 2**num_qubits) dimension = 2 mesh = Mesh([interval] * dimension) # Create BlackBoxLoadMPO instance black_box = BlackBoxLoadMPO(func, mesh) # Perform TT-Cross using cross_dmrg mps = cross_dmrg(black_box).mps # Convert MPS to MPO mpo = mps_as_mpo(mps) print(f"Generated MPO with shape: {mpo.shape}") ``` -------------------------------- ### Multiscale Interpolative Construction Methods Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/seemps_analysis_loading.rst Methods for constructing polynomial interpolants of univariate functions in MPS using the Lagrange interpolation framework. These are useful for adaptive function approximation. ```python from seemps.analysis.lagrange import lagrange_basic from seemps.analysis.lagrange import lagrange_rank_revealing from seemps.analysis.lagrange import lagrange_local_rank_revealing ``` -------------------------------- ### Load MPS Black-Box with TT-Cross DMRG Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/TT-Cross.ipynb Demonstrates loading a function into an MPS using `BlackBoxLoadMPS`. This representation imposes quantization on degrees of freedom. It's suitable for MPS with small physical dimensions and supports serial or interleaved orders. ```python from seemps.analysis.cross import BlackBoxLoadMPS import numpy as np from seemps.analysis.mesh import Mesh, RegularInterval from seemps.analysis.factories import mps_interval from seemps.analysis.cross import cross_dmrg # Define the black-box function func = lambda tensor: np.exp(-np.sum(tensor**2, axis=0)) # Define mesh parameters start, stop = -1, 1 num_qubits = 10 interval = RegularInterval(start, stop, 2**num_qubits) dimension = 2 mesh = Mesh([interval] * dimension) # Create BlackBoxLoadMPS instance black_box = BlackBoxLoadMPS(func, mesh, base=2, mps_order="A") # Perform TT-Cross using cross_dmrg mps = cross_dmrg(black_box).mps print(f"Generated MPS with bond dimensions: {mps.bond_dimensions()}") ``` -------------------------------- ### Apply TEBD to Quantum State Evolution Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/algorithms/tebd_evolution.rst Demonstrates how to evolve a matrix-product state (MPS) using the 2nd order Trotter decomposition for a Heisenberg Hamiltonian. It initializes an MPS, defines the Hamiltonian, sets up the evolution operator, and applies it iteratively over time steps. ```Python import seemps # Initialize a random MPS with 20 qubits mps = seemps.random_uniform_mps(2, 20) # Define a Heisenberg Hamiltonian for 20 qubits H = seemps.hamiltonians.HeisenbergHamiltonian(20) # Set the time step dt = 0.1 # Create a 2nd order Trotter evolution operator U = seemps.evolution.trotter.Trotter2ndOrder(H, dt) # Define a strategy for state updates, e.g., setting a tolerance strategy = seemps.state.DEFAULT_STRATEGY.replace(tolerance = 1e-8) # Initialize time t = 0.0 # Evolve the MPS for 50 steps for steps in range(0, 50): mps = U.apply_inplace(mps) t += dt # The final MPS after evolution print(mps) ``` -------------------------------- ### Sine Operator MPO (sin(x)) Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/seemps_analysis_operators.rst Creates an MPO representation for the sine operator sin(x). Essential for modeling periodic phenomena and quantum systems. ```python from seemps.analysis.operators import sin_mpo # Example usage: sin(x) # sin_x_op = sin_mpo() ``` -------------------------------- ### Chebyshev Analysis Functions Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/algorithms/chebyshev.rst Provides core functions for Chebyshev analysis, including calculating projection and interpolation coefficients, estimating the order of Chebyshev expansions, and converting between different representations. ```python projection_coefficients(f, n) Calculates the projection coefficients of a function f onto a Chebyshev basis of degree n. Parameters: f: The function to project. n: The degree of the Chebyshev basis. Returns: An array of projection coefficients. ``` ```python interpolation_coefficients(f, x_points) Calculates the interpolation coefficients of a function f at given points. Parameters: f: The function to interpolate. x_points: The points at which to interpolate. Returns: An array of interpolation coefficients. ``` ```python estimate_order(f, tol) Estimates the required order for a Chebyshev expansion of function f based on a tolerance. Parameters: f: The function for which to estimate the order. tol: The tolerance for the estimation. Returns: The estimated order (integer). ``` ```python cheb2mps(coeffs) Converts Chebyshev polynomial coefficients to a monomial basis representation. Parameters: coeffs: An array of Chebyshev coefficients. Returns: An array of monomial coefficients. ``` ```python cheb2mpo(coeffs) Converts Chebyshev polynomial coefficients to a monomial polynomial object. Parameters: coeffs: An array of Chebyshev coefficients. Returns: A monomial polynomial object. ``` -------------------------------- ### Mesh and Interval Classes API Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/seemps_analysis_spaces.rst Provides implicit representations for multivariate spaces using Interval and Mesh classes. These classes avoid exponential memory overhead by not explicitly storing all points. ```APIDOC seemps.analysis.mesh.Mesh: Represents a multivariate space as a collection of Interval objects. Allows indexing using multidimensional indices. Related classes: ~seemps.analysis.mesh.Interval ~seemps.analysis.mesh.RegularInterval ~seemps.analysis.mesh.ChebyshevInterval ~seemps.analysis.mesh.IntegerInterval ``` ```APIDOC seemps.analysis.mesh.Interval: Base class for univariate discretizations. Represents an interval implicitly and can be indexed like an array. Subclasses: ~seemps.analysis.mesh.RegularInterval ~seemps.analysis.mesh.ChebyshevInterval ~seemps.analysis.mesh.IntegerInterval ``` ```APIDOC seemps.analysis.mesh.RegularInterval: Represents a univariate interval with a regular discretization. Defines points uniformly spaced within the interval. Inherits from: ~seemps.analysis.mesh.Interval ``` ```APIDOC seemps.analysis.mesh.ChebyshevInterval: Represents a univariate interval with an irregular discretization based on Chebyshev zeros or extrema. Inherits from: ~seemps.analysis.mesh.Interval ``` ```APIDOC seemps.analysis.mesh.IntegerInterval: Represents a univariate interval with a regular discretization using integers. Inherits from: ~seemps.analysis.mesh.Interval ``` -------------------------------- ### MPO Application to MPS Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/seemps_objects_mpo.rst Demonstrates how to apply Matrix-Product Operators (MPO) to Matrix-Product States (MPS) efficiently. This operation preserves the MPS form and has a cost linear in system size. Two methods are provided: the `apply` method for controlled contraction and simplification, and the `@` operator for a default contraction strategy. ```python import seemps # Assume mps is a seemps.MPS object and mpo is a seemps.MPO object # Applying MPO using the @ operator (default strategy) # Fmps = mpo @ mps # Applying MPO using the apply method with custom strategy # strategy = seemps.Strategy(tolerance=1e-9) # Fmps = mpo.apply(mps, strategy=strategy) ``` -------------------------------- ### Compare DMRG Energy with Exact Diagonalization Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/DMRG.ipynb Validates the DMRG result by comparing its computed ground state energy against the exact ground state energy obtained via exact diagonalization for small systems. ```Python from scipy.sparse.linalg import eigsh E, _ = eigsh(H.to_matrix(), k=1, which="SA") print(f"Exact energy = {result.energy}") ``` -------------------------------- ### Define target grid and function for interpolation Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/Interpolation.ipynb Sets up a new, higher-resolution grid (m-qubit) by increasing the resolution of the original space. It also defines the benchmark Gaussian function on this new grid, which will be used to compare against the interpolated results. ```python # Define m-qubit function on the interpolated grid m = n+1 M = 2**m new_space = space.increase_resolution([m]) x_m = new_space.x[0] f_m = gaussian(x_m) ``` -------------------------------- ### Combine MPS States using MPSSum Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/seemps_objects_sum.rst Demonstrates how to combine two Matrix-Product States (MPS) using addition and scalar multiplication, resulting in an MPSSum object. Shows implicit creation and access to weights and states. ```python mps1 = random_uniform_mps(2, 10) mps2 = product_state([1.0, 0.0], 10) mps3 = 0.5 * mps1 - 0.3 * mps2 print(mps3) # Expected output: print(mps3.weights) # Expected output: [1, -1] # mps3.states[0] and mps3.states[1] contain rescaled versions of mps1 and mps2. ``` -------------------------------- ### Compose MPS Black-Box with TT-Cross DMRG Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/TT-Cross.ipynb Demonstrates composing scalar functions on multiple MPS using `BlackBoxComposeMPS`. The `func` parameter takes a list of MPS and applies a scalar function to them. This is useful for combining multiple independent MPS representations. ```python from seemps.analysis.cross import BlackBoxComposeMPS import numpy as np from seemps.analysis.mesh import RegularInterval from seemps.analysis.factories import mps_interval from seemps.analysis.cross import cross_dmrg # Define the composite function func = lambda mps_list: mps_list[0] * np.sin(mps_list[1] * mps_list[2]) + mps_list[1] * np.cos(mps_list[0] * mps_list[2]) # Define mesh and create initial MPS start, stop, num_qubits = -1, 1, 10 interval = RegularInterval(start, stop, 2**num_qubits) # Create three identical MPS for demonstration mps_x = mps_interval(interval) # Create BlackBoxComposeMPS instance black_box = BlackBoxComposeMPS(func, [mps_x, mps_x, mps_x]) # Perform TT-Cross using cross_dmrg mps = cross_dmrg(black_box).mps print(f"Generated MPS with bond dimensions: {mps.bond_dimensions()}") ``` -------------------------------- ### Solve Harmonic Oscillator Ground State with DMRG Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/PDE.ipynb This function computes the ground state energy and wavefunction of the harmonic oscillator MPO using the DMRG algorithm. It iterates over different grid densities (number of qubits), plots the resulting wavefunctions, and prints the calculated ground state energy. It requires seemps.optimization.dmrg, matplotlib, and numpy. ```Python from seemps.optimization import dmrg import matplotlib.pyplot as plt import numpy as np def experiment_0(nmax: int, a: float = -5): fig, ax = plt.subplots() for n in range(3, nmax): x, H = harmonic_oscillator_mpo(n, a) guess = product_state(np.ones(2) / np.sqrt(2), n) result = dmrg(H, guess=guess, maxiter=50) print(f"n = {n} qubits, E = {result.energy}") psi = np.abs(result.state.to_vector()) * np.sqrt(2**n) ax.plot(x, psi, label=f"n={n}") ax.legend() fig.tight_layout() ``` -------------------------------- ### Compute Ground State Energy with DMRG Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/DMRG.ipynb Calculates the ground state energy of the defined Hamiltonian using the DMRG algorithm. It utilizes a simple product state as an initial guess for the optimization. ```Python result = dmrg(H, guess=product_state(np.ones(2) / np.sqrt(2), N)) print(f"DMRG energy = {result.energy}") ``` -------------------------------- ### Python Imports for MPS Optimization Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/Optimization.ipynb Imports necessary libraries including NumPy for numerical operations, Matplotlib for plotting, and specific components from the `seemps` library for MPS state representation, regular interval meshes, and optimization routines. ```python import numpy as np import matplotlib.pyplot as plt from seemps.state import MPS from seemps.analysis.mesh import RegularInterval from seemps.analysis.optimization import optimize_mps ``` -------------------------------- ### Load Function into MPS Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/Optimization.ipynb Loads the evaluated function vector into a Matrix Product State (MPS) using `MPS.from_vector`. This step prepares the data for MPS-based optimization. It also prints the maximum bond dimension of the resulting MPS and the error introduced by the MPS representation. ```python # Load the function in MPS using SVD mps = MPS.from_vector(y_vec, [2] * num_qubits, normalize=False) y_mps = mps.to_vector() err = np.max(np.abs(y_mps - y_vec)) print("Maxbond: ", mps.max_bond_dimension()) print("Loading error: ", err) ``` -------------------------------- ### Plot Quantum Function Interpolation Comparison Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/Interpolation.ipynb Generates a plot comparing the original n-qubit function, the target m-qubit function, and the results from Fourier and finite differences interpolation. Includes labels and a legend for clarity. ```python fig, ax = plt.subplots() ax.set_xlabel('x') ax.set_ylabel('f(x)') ax.plot(x_n, f_n, linestyle='solid', label='n-qubit function') ax.plot(x_m, f_m, linestyle='dotted', label='m-qubit function') ax.plot(x_m, f_fourier.real, linestyle='dashed', label='Fourier m-qubit function') ax.plot(x_m, f_fd, linestyle='dashdot', label='Finite differences m-qubit function') ax.legend() ``` -------------------------------- ### Define Function and Interpolation Coefficients Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/Chebyshev.ipynb Defines a target function $g(x) = e^{-x}$ and calculates its Chebyshev interpolation coefficients over a specified interval. This prepares the transcendental part of the multivariate function for MPS representation. ```python func = lambda x: np.exp(-x) start, stop = -1, 1 coeffs = interpolation_coefficients(func, start=start, stop=stop) ``` -------------------------------- ### Create initial MPS from Gaussian function Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/Interpolation.ipynb Defines a one-dimensional grid and a Gaussian function on it. It then constructs an MPS representation of this function for an n-qubit system, setting up the initial state for interpolation. ```python # Define n-qubit function n = 3 N = 2**n qubits_per_dimension = [n] L = np.sqrt(2*np.pi*2**n) space = Space(qubits_per_dimension, L=[[-L/2,L/2]], closed=False) x_n = space.x[0] f_n = gaussian(x_n) f_n_mps = MPS.from_vector(f_n, [2]*n, normalize=False) ``` -------------------------------- ### MPSArnoldiRepresentation Methods Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/algorithms/generated/seemps.optimization.arnoldi.MPSArnoldiRepresentation.rst Details the methods available for the MPSArnoldiRepresentation class, covering operations like adding vectors, building Krylov bases, accessing eigenvectors, and managing the representation's state. ```APIDOC MPSArnoldiRepresentation: add_vector(vector) Adds a vector to the representation. build_Krylov_basis() Constructs the Krylov basis. eigenvector() Returns the current eigenvector approximation. energy_and_variance() Calculates the energy and variance. exponential() Computes the exponential of the representation. restart_with_ground_state() Restarts the representation with the ground state. restart_with_vector(vector) Restarts the representation with a specified vector. empty() Creates an empty MPSArnoldiRepresentation. operator() Returns the operator associated with the representation. H() Returns the Hamiltonian operator. N() Returns the number of vectors in the basis. V() Returns the Krylov basis vectors. strategy() Returns the optimization strategy. tol_ill_conditioning() Returns the tolerance for ill-conditioning. gamma() Returns the gamma parameter. orthogonalize() Orthogonalizes the representation. ``` -------------------------------- ### Write and Read MPS to HDF5 Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/seemps_hdf5.rst Demonstrates saving an MPS object to an HDF5 file using seemps.hdf5.write_mps and subsequently reading it back with seemps.hdf5.read_mps. Requires the h5py and seemps libraries. ```python import h5py import seemps # Create a single file, overwriting any existing one with h5py.File("data.hdf5", "w") as file: seemps.hdf5.write_mps(file, "state", my_mps) # Read the MPS from the same file, reopening it as read-only with h5py.File("data.hdf5", "r") as file: seemps.hdf5.read_mps(file, "state") ``` -------------------------------- ### Create MPS for $x^2 + y^2$ in Serial and Interleaved Orders Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/Chebyshev.ipynb Sets up the domain and creates an initial MPS for a single variable $x$. It then computes the MPS for $x^2$ and uses `mps_tensor_sum` to construct the MPS for the bivariate function $h(x, y) = x^2 + y^2$. This is done for both 'A' (serial) and 'B' (interleaved) qubit orderings, suitable for separable and correlated functions respectively. ```python num_qubits = 6 domain = RegularInterval(start, stop, 2**num_qubits) mps_x = mps_interval(domain) mps_x_squared = mps_x * mps_x # x^2 mps_domain_A = mps_tensor_sum( [mps_x_squared, mps_x_squared], mps_order="A" ) # x^2 + y^2 serial mps_domain_B = mps_tensor_sum( [mps_x_squared, mps_x_squared], mps_order="B" ) # x^2 + y^2 interleaved ``` -------------------------------- ### Load Multivariate Function using Cross-DMRG Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/examples/Integration.ipynb Loads a multivariate function into an MPS representation using tensor cross-interpolation (TCI) via the `cross_dmrg` function. It sets up a Chebyshev interval mesh for a specified dimension and defines a sample function $f(x_1, ..., x_{10}) = \prod_{i=1}^{10} x_i^3$. ```Python import numpy as np from seemps.analysis.mesh import ChebyshevInterval, Mesh from seemps.analysis.cross import BlackBoxLoadMPS, cross_dmrg import seemps.tools seemps.tools.DEBUG = 2 start, stop = -1, 1 num_qubits = 3 interval = ChebyshevInterval( start, stop, 2**num_qubits, endpoints=True ) # Chebyshev extrema dimension = 10 mesh = Mesh([interval] * dimension) func = lambda tensor: np.sum(tensor**3, axis=0) # x^3 * y^3 * ... black_box = BlackBoxLoadMPS(func, mesh) mps_func = cross_dmrg(black_box).mps ``` -------------------------------- ### MPSSum Class API Source: https://github.com/juanjosegarciaripoll/seemps2/blob/main/docs/seemps_objects_sum.rst Documentation for the MPSSum class, which represents a sum of Matrix-Product States (MPS). Includes methods for combining MPS states, converting them to other formats, and accessing internal properties. ```APIDOC seemps.state.MPSSum Represents a sum of Matrix-Product States (MPS). Attributes: weights (list[float]): A list of scalar weights for each MPS in the sum. states (list[MPS]): A list of MPS objects that constitute the sum. Methods: __init__(self, states: list[MPS], weights: list[float] = None) Initializes an MPSSum object. Parameters: states: A list of MPS objects. weights: A list of weights corresponding to each MPS. If None, defaults to ones. join(self, other: 'MPSSum') -> 'MPSSum' Combines this MPSSum with another MPSSum. Parameters: other: Another MPSSum object to combine with. Returns: A new MPSSum object representing the combined sum. to_vector(self) -> np.ndarray Converts the MPSSum to a dense vector representation. Returns: A numpy array representing the state vector. (Implicit Operations) Supports arithmetic operations like addition, subtraction, and scalar multiplication, which implicitly create new MPSSum objects. Example: mps_sum = weight * mps1 + mps2 This operation internally manages the states and weights. ```