Skip to content

Commit 8144420

Browse files
Add more descriptive errors to ncon (#216)
* add more descriptive errors to ncon * add nconstylecheck function to mitigate checking the network twice
1 parent 04c8428 commit 8144420

File tree

2 files changed

+19
-7
lines changed

2 files changed

+19
-7
lines changed

src/implementation/ncon.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ function ncon(
2828
)
2929
length(tensors) == length(network) == length(conjlist) ||
3030
throw(ArgumentError("number of tensors and of index lists should be the same"))
31-
isnconstyle(network) || throw(ArgumentError("invalid NCON network: $network"))
31+
nconstylecheck(network) # asserts that the network is in ncon style
3232
output′ = nconoutput(network, output)
3333

3434
if length(tensors) == 1

src/indexnotation/ncontree.jl

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,37 @@
1+
const NCONSTYLE = "Valid ncon style network"
2+
13
# check if a list of indices specifies a tensor contraction in ncon style
24
function isnconstyle(network)
5+
return _nconstyle_error(network) == NCONSTYLE
6+
end
7+
8+
function _nconstyle_error(network)
39
allindices = Vector{Int}()
410
for ind in network
5-
all(i -> isa(i, Integer), ind) || return false
11+
all(i -> isa(i, Integer), ind) || return "All indices must be integers"
612
append!(allindices, ind)
713
end
814
while length(allindices) > 0
915
i = pop!(allindices)
1016
if i > 0 # positive labels represent contractions or traces and should appear twice
1117
k = findfirst(isequal(i), allindices)
12-
k === nothing && return false
18+
k === nothing && return "Index $i appears only once in the network"
1319
l = findnext(isequal(i), allindices, k + 1)
14-
l !== nothing && return false
20+
l !== nothing && return "Index $i appears more than twice in the network"
1521
deleteat!(allindices, k)
1622
elseif i < 0 # negative labels represent open indices and should appear once
17-
findfirst(isequal(i), allindices) === nothing || return false
23+
findfirst(isequal(i), allindices) === nothing || return "Index $i appears more than once in the network"
1824
else # i == 0
19-
return false
25+
return "Index 0 is not allowed in the network"
2026
end
2127
end
22-
return true
28+
return NCONSTYLE
29+
end
30+
31+
function nconstylecheck(network)
32+
err = _nconstyle_error(network)
33+
err === NCONSTYLE || throw(ArgumentError(err))
34+
return nothing
2335
end
2436

2537
function ncontree(network)

0 commit comments

Comments
 (0)