Skip to content

Commit

Permalink
Parse units with unit_from_string to include other units
Browse files Browse the repository at this point in the history
  • Loading branch information
theHenks authored and fhagemann committed Dec 10, 2024
1 parent 250b02a commit 8e4efa2
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/lprops.jl
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@ function _props2lprops(pd::PropDict)
if haskey(pd, :val) && length(keys(pd)) <= 3 && (haskey(pd, :unit) || haskey(pd, :err))
if haskey(pd, :unit)
if haskey(pd, :err)
Unitful.Quantity.(measurement.(pd.val, ifelse(isnothing(pd.err), NaN, pd.err)), Unitful.uparse(pd.unit))
Unitful.Quantity.(measurement.(pd.val, ifelse(isnothing(pd.err), NaN, pd.err)), units_from_string(pd.unit))
else
Unitful.Quantity.(pd.val, Unitful.uparse(pd.unit))
Unitful.Quantity.(pd.val, units_from_string(pd.unit))
end
elseif haskey(pd, :err)
measurement.(pd.val, ifelse(isnothing(pd.err), NaN, pd.err))
else
throw(ArgumentError("_props2lprops can't handle PropDict $pd"))
end
elseif haskey(pd, :unit) && length(keys(pd)) == 1
Unitful.Quantity(NaN, Unitful.uparse(pd.unit))
Unitful.Quantity(NaN, units_from_string(pd.unit))
else
PropDict(Dict([key => _props2lprops(val) for (key, val) in pd]))
end
Expand Down
24 changes: 24 additions & 0 deletions src/utils/unit_utils.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# This file is a part of LegendDataManagement.jl, licensed under the MIT License (MIT).

const _pseudo_unit_expr = r"(^|[^A-Za-z])(ADC|adc|sample)([^A-Za-z]|$)"

function units_from_string(s::AbstractString)
if isempty(s) || s == "none"
NoUnits
elseif !isnothing(match(_pseudo_unit_expr, s))
NoUnits
else
try
uparse(s, unit_context=[Unitful, UnitfulAtomic])
catch e
s == "e" && return u"e_au" # parse "e" as u"e_au" from UnitfulAtomic
if e isa ErrorException
rethrow(ArgumentError("Unknown physical unit \"$s\""))
else
rethrow(e)
end
end
end
end

units_to_string(u::Unitful.Unitlike) = string(u)

0 comments on commit 8e4efa2

Please sign in to comment.