Skip to content

Commit

Permalink
Sort indices in nested sums
Browse files Browse the repository at this point in the history
  • Loading branch information
david-pl committed Jan 18, 2025
1 parent 9d0bc75 commit 400aebf
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
19 changes: 14 additions & 5 deletions src/indexing_sums.jl
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,25 @@ struct Sum{T<:QNumber,I,M} <: QTerm
end

# constructor for nested sums
function Sum(term, index1::Index, index2::Index, remaining_indices::Index...)
s_inner = Sum(term, index1)
return Sum(s_inner, index2, remaining_indices...)
function Sum(term, indices::Index...)
# sort indices to make sure we always construct nested sums in the same order
sorted_indices = sort!([indices...], by=i -> i.name)
return _nested_sum(term, sorted_indices...)
end

# this method is required to avoid ambiguity even though it's the exact same as above
function Sum(term::QNumber, index1::Index, index2::Index, remaining_indices::Index...)
function Sum(term::QNumber, indices::Index...)
# sort indices to make sure we always construct nested sums in the same order
sorted_indices = sort!([indices...], by=i -> i.name)
return _nested_sum(term, sorted_indices...)
end

function _nested_sum(term, index1::Index, index2::Index, remaining_indices...)
s_inner = Sum(term, index1)
return Sum(s_inner, index2, remaining_indices...)
return _nested_sum(s_inner, index2, remaining_indices...)
end
_nested_sum(s, index::Index) = Sum(s, index)


hilbert(s::Sum) = hilbert(s.term)

Expand Down
4 changes: 4 additions & 0 deletions test/test_index_basic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,10 @@ end
@test isequal(s, 10 * Sum(σ(1,2,i_ind), i_ind))
s = Sum(σ(1,2,i_ind)*σ(1,2,k_ind),i_ind,k_ind)

s1 = Sum(σ(2,1,i_ind)*σ(1,2,k_ind),i_ind,k_ind)
s2 = Sum(σ(2,1,i_ind)*σ(1,2,k_ind),k_ind,i_ind)
@test isequal(s1, s2)

s1 = simplify(Sum(σ(2,1,k_ind) * sum1, k_ind))
s2 = simplify(Sum(σ(2,1,k_ind)*σ(1,2,i_ind)*a',i_ind,k_ind))
@test isequal(s1, s2)
Expand Down

0 comments on commit 400aebf

Please sign in to comment.