# 3. Calculating Quantities¶

There are various built-in functions to calculate quantities, not limited to:

## 3.1. Approximate Spectral Functions¶

The module approx_spectral, contains a Lanczos method for estimating any quantities of the form tr(fn(A)). Where A is any operator that implements a dot product with a vector. For example, estimating the trace of the sqrt of a matrix would naievly require diagonalising it:

import quimb as qu

rho = qu.rand_rho(2**12)
rho_el = qu.eigvalsh(rho)
sum(rho_el ** 0.5)

54.32566715771646

qu.tr_sqrt_approx(rho)

54.45773513531054


Diagonalization has a cost of O(n^3), which is essentially reduced to O(k * n^2) for this stochastic method. For a general function approx_spectral_function() can be used.

However, the real advantage occurs when the full matrix does not need to be fully represented, e.g. in the case of ‘partial trace states’. One can then calculate quantities for subsystems that would not be possible to explicitly represent.

For example, the partial trace, followed by partial transpose, followed by vector multiplication can be ‘lazily’ evaluated as a tensor contraction (see lazy_ptr_ppt_dot()). In this way the logarithmic negativity of subsytems can be efficiently calculated:

psi = qu.rand_ket(2**20)
dims = [2**8, 2**4, 2**8]
qu.logneg_subsys_approx(psi, dims, sysa=0, sysb=2)

5.7437225898123465


To inspect the process you can supply an info dict, and optionally also have the trials plotted like so:

%config InlineBackend.figure_formats = ['svg']

# estimate a 2D partition function
beta = 2.0
H = qu.ham_heis_2D(4, 4, bz=1.7, sparse=True)

# if plot=False, the desired keys should be filled before supplying info
info = {}

Z = qu.approx_spectral_function(
H, f=lambda x: qu.exp(-beta * x),
tol=1e-2,
info=info,
progbar=True,
plot=True,
)

1.217(12)e+11:  40%|############################4                                          | 411/1024 [00:34<00:50, 12.03it/s]

info.keys()

dict_keys(['estimate', 'error', 'samples', 'estimates_raw', 'estimates_window', 'estimates_fit', 'estimates', 'fig', 'axs'])