-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnumpy_partial_trace.py
37 lines (32 loc) · 1.07 KB
/
numpy_partial_trace.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import numpy as np
# https://scicomp.stackexchange.com/questions/30052/calculate-partial-trace-of-an-outer-product-in-python
def partial_trace(rho, keep, dims, optimize=False):
"""Calculate the partial trace
ρ_a = Tr_b(ρ)
Parameters
----------
ρ : 2D array
Matrix to trace
keep : array
An array of indices of the spaces to keep after
being traced. For instance, if the space is
A x B x C x D and we want to trace out B and D,
keep = [0,2]
dims : array
An array of the dimensions of each space.
For instance, if the space is A x B x C x D,
dims = [dim_A, dim_B, dim_C, dim_D]
Returns
-------
ρ_a : 2D array
Traced matrix
"""
keep = np.asarray(keep)
dims = np.asarray(dims)
Ndim = dims.size
Nkeep = np.prod(dims[keep])
idx1 = [i for i in range(Ndim)]
idx2 = [Ndim+i if i in keep else i for i in range(Ndim)]
rho_a = rho.reshape(np.tile(dims,2))
rho_a = np.einsum(rho_a, idx1+idx2, optimize=optimize)
return rho_a.reshape(Nkeep, Nkeep)