How to update a tensor element-wise in ITensors ?

Here is a minimal rewrite of your code that demonstrates it should be updating T2:

using ITensors: ITensor, Index, random_itensor
using Random: Random
function main()
  Random.seed!(1234)
  a_1, a_2, i_1, i_2 = Index.((2, 2, 2, 2))
  R2 = random_itensor(a_1, a_2, i_1, i_2)
  T2 = random_itensor(a_1, a_2, i_1, i_2)
  Scaled_R2 = random_itensor(a_1, a_2, i_1, i_2)
  function update_T2!(T2::ITensor, R2::ITensor, Scaled_R2::ITensor)
    fvv = random_itensor(a_1, a_2)
    foo = random_itensor(i_1, i_2)
    nv = 2
    nocc = 2
    shiftp = 0.20
    for a in 1:nv, b in 1:nv, i in 1:nocc, j in 1:nocc
      numerator = R2[a_1 => a, a_2 => b, i_1 => i, i_2 => j]
      denominator = fvv[a_1 => a, a_2 => a] + fvv[a_1 => b, a_2 => b] - foo[i_1 => i, i_2 => i] - foo[i_1 => j, i_2 => j] + shiftp
      Scaled_R2[a_1 => a, a_2 => b, i_1 => i, i_2 => j] = numerator / denominator
    end
    T2 .-= Scaled_R2
    return T2
  end
  @show T2
  update_T2!(T2, R2, Scaled_R2)
  @show T2
  return nothing
end

When I run main() I get the output:

julia> main()
T2 = ITensor ord=4
Dim 1: (dim=2|id=592)
Dim 2: (dim=2|id=579)
Dim 3: (dim=2|id=308)
Dim 4: (dim=2|id=949)
NDTensors.Dense{Float64, Vector{Float64}}
 2×2×2×2
[:, :, 1, 1] =
  1.6218076699653694  -0.5347089043694231
 -0.7636889550217101  -0.8371161519624881

[:, :, 2, 1] =
 -0.09989094954741905  -0.240570071975397
 -0.726142325634263     0.9427328405545989

[:, :, 1, 2] =
 0.44588457807333104  -1.4451163776340619
 0.4604268914916924    0.3716847353731026

[:, :, 2, 2] =
 1.9522884266156713  -0.7578371325188665
 0.3237050517386015   1.1693426324343965
T2 = ITensor ord=4
Dim 1: (dim=2|id=592)
Dim 2: (dim=2|id=579)
Dim 3: (dim=2|id=308)
Dim 4: (dim=2|id=949)
NDTensors.Dense{Float64, Vector{Float64}}
 2×2×2×2
[:, :, 1, 1] =
 2.212330480674426   -2.2440191884987355
 1.0922381970413777  -0.82496215138259

[:, :, 2, 1] =
 -0.3416953884869767  8.401621007271215
 -5.33919777706203    0.12228179003341455

[:, :, 1, 2] =
  0.7516874457199619   0.8084381798095097
 -2.353150269542973   -0.21578545586345294

[:, :, 2, 2] =
 2.2143522987879845  0.07399335046884059
 0.3979494267800609  0.276824871640005

Note that I am indexing into the ITensors in the loop using the ITensor Indices, which is better practice since otherwise the code can become incorrect if ITensors are input with Indices that are ordered in a different way. I also shortened T2 .= T2 .- Scaled_R2 to T2 .-= Scaled_R2, those are equivalent to each other.

Also functions that change object in-place in Julia have a convention that their name ends in !.

So the issue you are seeing is probably coming from a different part of your code.

1 Like