bsc-quantic / Tensors.jl

Tensors and Einstein Summation in Julia
https://bsc-quantic.github.io/Tensors.jl/
Apache License 2.0
0 stars 1 forks source link

Fix `svd` function #16

Closed jofrevalles closed 1 year ago

jofrevalles commented 1 year ago

Summary

This PR addresses an issue with the custom svd function for a Tensor. The issue was related to the incorrect reshaping of the resulting U and V matrices, sometimes leading to incorrect output sizes. The function has been fixed, and new test cases have been added to cover the previous error.

Issue

The original svd function did not correctly reshape the resulting U and V matrices. The problem occurred when the indices of the Tensor had different dimensions. The original code used the following lines to reshape the tensors:

U = reshape(U, size.((t,), left_inds)..., size(U, 2))
Vt = reshape(V', size.((t,), right_inds)..., size(V, 2))

This caused issues for the Vt tensor because the vrind was expected to be its first index but was assigned as the last index in the original code.

Example

Here's an example where the original code failed:

julia> using Tensors

julia> using LinearAlgebra

julia> data = rand(2, 4, 6, 8)
2×4×6×8 Array{Float64, 4}

julia> tensor = Tensor(data, (:i, :j, :k, :l))
2×4×6×8 Tensor{Float64, 4, Array{Float64, 4}}

julia> U, s, V = svd(tensor, labels(tensor)[1:2])

julia> size(U)
(2, 4, 8)

julia> labels(U) # This is OK
(:i, :j, Symbol("5597b37d-a1d6-48a6-9ea7-15047defd0cf"))

julia> size(V)
(6, 8, 8)

julia> labels(V) # This is wrong, label :k should have size 6
(Symbol("436e0761-67dc-4886-aecf-0a2d9abe6a30"), :k, :l)
codecov[bot] commented 1 year ago

Codecov Report

Merging #16 (c272320) into master (4debeba) will not change coverage. The diff coverage is 100.00%.

@@           Coverage Diff           @@
##           master      #16   +/-   ##
=======================================
  Coverage   79.65%   79.65%           
=======================================
  Files           5        5           
  Lines         172      172           
=======================================
  Hits          137      137           
  Misses         35       35           
Impacted Files Coverage Δ
src/Numerics.jl 91.42% <100.00%> (ø)

Help us with your feedback. Take ten seconds to tell us how you rate us. Have a feature suggestion? Share it here.