Skip to content

Commit

Permalink
Nicer error message for string-based element lookup (#72)
Browse files Browse the repository at this point in the history
  • Loading branch information
mfherbst authored Jun 1, 2023
1 parent 652f916 commit 144ea82
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/interface.jl
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,24 @@ end
#

"""The element corresponding to a species/atom (or missing)."""
element(id::Union{Symbol,AbstractString,Integer}) = PeriodicTable.elements[id]
element(id::Union{Symbol,Integer}) = PeriodicTable.elements[id] # Keep for better inlining
function element(name::AbstractString)
try
return PeriodicTable.elements[name]
catch e
if e isa KeyError
throw(ArgumentError(
"Unknown element name: $name. " *
"Note that AtomsBase uses PeriodicTables to resolve element identifiers, " *
"where strings are considered element names. To lookup an element by " *
"element symbol use `Symbol`s instead, e.g. "*
"""`Atom(Symbol("Si"), zeros(3)u"Å")` or `Atom("silicon", zeros(3)u"Å")`."""
))
else
rethrow()
end
end
end


"""
Expand Down
10 changes: 10 additions & 0 deletions test/interface.jl
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,14 @@ using PeriodicTable
get_z_periodicity(syst) = syst[:boundary_conditions][3]
@test @inferred(BoundaryCondition, get_z_periodicity(flexible)) == DirichletZero()
end

# https://github.com/JuliaMolSim/AtomsBase.jl/issues/71
@testset "Atoms element names" begin
@test element("silicon").name == "Silicon"
@test element(:Si).name == "Silicon"
@test element(14).name == "Silicon"

@test_throws ArgumentError element("Si")
@test_throws KeyError element(0)
end
end

0 comments on commit 144ea82

Please sign in to comment.