bsc-quantic / Tenet.jl

Composable Tensor Network library in Julia
https://bsc-quantic.github.io/Tenet.jl/
Apache License 2.0
17 stars 1 forks source link

Implement `@unsafe_region` macro for relaxed tensor operations #149

Closed jofrevalles closed 3 weeks ago

jofrevalles commented 3 weeks ago

This PR resolves issue #147 by introducing a new macro @unsafe_region, allowing users to temporarily relax index size checks when performing tensor operations within a specified code block. This feature is particularly useful for updating tensors in a tensor network where intermediate steps might involve tensors with mismatched sizes.

Example usage

julia> using Tenet

julia> tn = TensorNetwork([
           Tensor(rand(2, 2, 2), [:i, :j, :k]),
           Tensor(rand(2, 2), [:j, :l]),
           Tensor(rand(2, 2, 2, 2), [:l, :k, :m, :n]),
           Tensor(rand(2, 2, 2), [:n, :o, :p])])
TensorNetwork (#tensors=4, #inds=8)

julia> a = Tensor(rand(3, 2), (:i, :j)); push!(tn, a)
ERROR: DimensionMismatch: size(tensor,i)=3 but should be equal to size(tn,i)=2
Stacktrace:
 [1] push!(tn::TensorNetwork, tensor::Tensor{Float64, 2, Matrix{Float64}})
   @ Tenet ~/git/Tenet.jl/src/TensorNetwork.jl:255
 [2] top-level scope
   @ REPL[11]:1

julia> Tenet.@unsafe_region tn begin
           a = Tensor(rand(3, 2), (:i, :j))
           push!(tn, a)
           pop!(tn, a)
       end
3×2 Tensor{Float64, 2, Matrix{Float64}}:
 0.638985  0.725609
 0.850249  0.315764
 0.141707  0.642034
jofrevalles commented 3 weeks ago

It looks great! Thanks @jofrevalles!

Would you mind adding some tests?

Done, @mofeing !