How to convert a itensor to a matrix

Hi, Miles and Matt

The MPO Hamiltonian itensor is generated as follows

using ITensors

let
    N = 2
    sites = siteinds("S=1/2",N;conserve_qns = true)

    ampo = OpSum()
    for j=1:N-1
        ampo += "Sz",j,"Sz",j+1
        ampo += 0.5,"S+",j,"S-",j+1
        ampo += 0.5,"S-",j,"S+",j+1
    end

    H = MPO(ampo,sites)

    Hitensor = ITensor(1.)
    for i = 1:N
        Hitensor *= H[i]
    end
end

Basically, all bond indices are constructed, and the resulting Hitensor only has physical indices. I am trying to get its matrix form using matrix(Hitensor), but it returns the following error message:

ERROR: DimensionMismatch: 
Stacktrace:
 [1] matrix(T::ITensor)
   @ ITensors ~/.julia/packages/ITensors/5CAqA/src/itensor.jl:2818
 [2] top-level scope
   @ REPL[64]:1

I’ve checked this doc, but still can not find the correct method.

Can you give me an example to obtain it?

By the way, is this matrix still a sparse matrix? Because my purpose of doing all this is to perform ED calculation for benchmark. I know these is a function eigen to do this. But it turns out to be inefficient for obtaining all eigenvalues without eigenvectors (correct me if I am wrong) when the system size becomes relatively large. So here I simply try to firstly generate a sparse matrix then resort to other packages or even using eig from matlab.

Best,
Junsen

You need to provide the indices for conversion to Matrix(only for 2-dimensional ITensor)/array.Note,the order of indices are important as it may change the representation of the final matrix you get.
You can try the following once.

A=Array(Hitensor,sites[1]',sites[2]',sites[1],sites[2])
println(reshape(A,4,4))

The output is

4Ă—4 Matrix{Float64}:
 0.25   0.0    0.0   0.0
 0.0   -0.25   0.5   0.0
 0.0    0.5   -0.25  0.0
 0.0    0.0    0.0   0.25

The following link may be helpful.
https://docs.juliahub.com/ITensors/P3pqL/0.2.3/ITensorType.html#Convert-to-Array

2 Likes

Thank you for the help. It works now :slight_smile:
Although I am still wondering how to make the function matrix working…

As far I am aware, matrix is for ITensor with 2 indices . In your case,it has 4 indices. matrix doesn’t need indices for conversion as it orders row/column as per ITensor’s internal storage layout.On the other hand, Matrix does need you to specify the indices.
e.g.

ind = Index(3, "i")
randT = randomITensor(ind', dag(ind)) # two indices
M = matrix(randT)
#The above command is equivalent to the  one below.
#M = Matrix(randT, ind', ind)

1 Like

Thank you very much, everything is clear now :grinning:

2 Likes