-
-
Notifications
You must be signed in to change notification settings - Fork 209
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[WIP] Optional unit rewriting #1252
Closed
Closed
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
91429e5
Experiment with having unit rewriting alongside original unit checking.
9dd1904
Fix bug in conditional validation.
191cbac
Need to use Constants so that `get_unit` will work correctly after re…
246c9f3
Dropping trig functions b/c even though I could handle them now, `get…
3cb883c
Added debug flag to rewrite_units.
2dc5b92
Remembered I need to handle roots.
1198ece
We might save a bunch of work by short-circuiting here: just see if t…
3c36e78
Reformatting/comments.
31faede
Added some rewrite tests.
2d8ed11
Should be able to skip this too, now that we're using safe_get_unit u…
6e134a2
Cleanup.
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,180 @@ | ||
"Wrapper for Unitful.convfact that returns a Constant & throws ValidationError instead of DimensionError." | ||
function unitfactor(u, t) | ||
try | ||
cf = Unitful.convfact(u, t) | ||
return cf == 1 ? 1 : Constant(cf*u/t) | ||
catch err | ||
throw(ValidationError("Unable to convert [$t] to [$u]")) | ||
end | ||
end | ||
|
||
"Turn an expression into a Julia function w/ correct units behavior." # mostly for testing | ||
function functionize(pt) | ||
syms = Symbolics.get_variables(pt) | ||
eval(build_function(constructunit(pt), syms, expression = Val{false})) | ||
end | ||
|
||
"Represent a constant as a Symbolic (esp. for lifting units to metadata level)." | ||
struct Constant{T, M} <: SymbolicUtils.Symbolic{T} | ||
val::T | ||
metadata::M | ||
end | ||
|
||
Constant(x) = Constant(x, Dict(VariableUnit => Unitful.unit(x))) | ||
Base.:*(x::Num, y::Unitful.Quantity) = value(x) * y | ||
Base.:*(x::Unitful.Quantity, y::Num) = x * value(y) | ||
Base.show(io::IO, v::Constant) = Base.show(io, v.val) | ||
|
||
Unitless = Union{typeof.([exp, log, sinh, asinh, asin, | ||
cosh, acosh, acos, | ||
tanh, atanh, atan, | ||
coth, acoth, acot, | ||
sech, asech, asec, | ||
csch, acsch, acsc])...} | ||
isunitless(f::Unitless) = true | ||
|
||
#Should run this at the end of @variables and @parameters | ||
set_unitless(x::Vector) = [_has_unit(y) ? y : SymbolicUtils.setmetadata(y,VariableUnit,unitless) for y in x] | ||
|
||
"Convert symbolic expression `x` to have units `u` if possible." | ||
function unitcoerce(u::Unitful.Unitlike, x::Symbolic) | ||
st = _has_unit(x) ? x : constructunit(x) | ||
tu = _get_unit(st) | ||
output = unitfactor(u, tu) * st | ||
return SymbolicUtils.setmetadata(output, VariableUnit, u) | ||
end | ||
|
||
"Convert a set of expressions to a common unit, defined by the first dimensional quantity encountered." | ||
function uniformize(subterms) | ||
newterms = Vector{Any}(undef, size(subterms)) | ||
firstunit = nothing | ||
for (idx, st) in enumerate(subterms) | ||
if !isequal(st, 0) | ||
st = constructunit(st) | ||
tu = _get_unit(st) | ||
if firstunit === nothing | ||
firstunit = tu | ||
end | ||
newterms[idx] = unitfactor(firstunit, tu) * st | ||
else | ||
newterms[idx] = 0 | ||
end | ||
end | ||
return newterms | ||
end | ||
|
||
constructunit(x::Num) = constructunit(value(x)) | ||
function constructunit(x::Unitful.Quantity) | ||
return Constant(x.val, Dict(VariableUnit => Unitful.unit(x))) | ||
end | ||
|
||
function constructunit(x) #This is where it all starts | ||
maybeunit = safe_get_unit(x,"") | ||
if maybeunit !== nothing | ||
return SymbolicUtils.setmetadata(x, VariableUnit, maybeunit) | ||
else # Something needs to be rewritten | ||
op = operation(x) | ||
args = arguments(x) | ||
constructunit(op, args) | ||
end | ||
end | ||
|
||
function constructunit(op, args) # Fallback | ||
if isunitless(op) | ||
try | ||
args = unitcoerce.(unitless, args) | ||
return SymbolicUtils.setmetadata(op(args...), VariableUnit, unitless) | ||
catch err | ||
if err isa Unitful.DimensionError | ||
argunits = get_unit.(args) | ||
throw(ValidationError("Unable to coerce $args to dimensionless from $argunits for function $op.")) | ||
else | ||
rethrow(err) | ||
end | ||
end | ||
else | ||
throw(ValidationError("Unknown function $op supplied with $args with units $argunits")) | ||
end | ||
end | ||
|
||
function constructunit(op::typeof(+), subterms) | ||
newterms = uniformize(subterms) | ||
output = +(newterms...) | ||
return SymbolicUtils.setmetadata(output, VariableUnit, _get_unit(newterms[1])) | ||
end | ||
|
||
function constructunit(op::Conditional, subterms) | ||
newterms = Vector{Any}(undef, 3) | ||
firstunit = nothing | ||
newterms[1] = constructunit(subterms[1]) | ||
newterms[2:3] = uniformize(subterms[2:3]) | ||
output = op(newterms...) | ||
return SymbolicUtils.setmetadata(output, VariableUnit, _get_unit(newterms[2])) | ||
end | ||
|
||
function constructunit(op::Union{Differential,Difference}, subterms) | ||
numerator = constructunit(only(subterms)) | ||
nu = _get_unit(numerator) | ||
denominator = op isa Differential ? constructunit(op.x) : constructunit(op.t) #TODO: make consistent! | ||
du = _get_unit(denominator) | ||
output = op isa Differential ? Differential(denominator)(numerator) : Difference(denominator)(numerator) | ||
return SymbolicUtils.setmetadata(output, VariableUnit, nu/du) | ||
end | ||
|
||
function constructunit(op::typeof(^), subterms) | ||
base, exponent = subterms | ||
base = constructunit(base) | ||
bu = _get_unit(base) | ||
exponent = constructunit(exponent) | ||
exponent = unitfactor(unitless, _get_unit(exponent)) * exponent | ||
output = base^exponent | ||
output_unit = bu == unitless ? unitless : (exponent isa Real ? bu^exponent : (1*bu)^exponent) | ||
return SymbolicUtils.setmetadata(output, VariableUnit, output_unit) | ||
end | ||
|
||
Root = Union{typeof(sqrt),typeof(cbrt)} | ||
function constructunit(op::Root,args) | ||
arg = constructunit(only(args)) | ||
argunit = _get_unit(arg) | ||
return SymbolicUtils.setmetadata(op(arg), VariableUnit, op(argunit)) | ||
end | ||
|
||
function constructunit(op::Comparison, subterms) | ||
newterms = uniformize(subterms) | ||
output = op(newterms...) | ||
return SymbolicUtils.setmetadata(output, VariableUnit, unitless) | ||
end | ||
|
||
function constructunit(op::typeof(*), subterms) | ||
newterms = Vector{Any}(undef, size(subterms)) | ||
pu = unitless | ||
for (idx, st) in enumerate(subterms) | ||
st = constructunit(st) | ||
pu *= _get_unit(st) | ||
newterms[idx] = st | ||
end | ||
output = op(newterms...) | ||
return SymbolicUtils.setmetadata(output, VariableUnit, pu) | ||
end | ||
|
||
function constructunit(eq::ModelingToolkit.Equation) | ||
newterms = uniformize([eq.lhs, eq.rhs]) | ||
return ~(newterms...) | ||
#return SymbolicUtils.setmetadata(output,VariableUnit,firstunit) #Fix this once Symbolics.jl Equations accept units | ||
end | ||
|
||
"Rewrite a set of equations by inserting appropriate unit conversion factors." | ||
function rewrite_units(eqs::Vector{Equation}; debug = false) | ||
output = similar(eqs) | ||
allgood = true | ||
for (idx, eq) in enumerate(eqs) | ||
try | ||
output[idx] = constructunit(eq) | ||
catch err | ||
allgood = false | ||
err isa ValidationError && !debug ? @warn("in eq [$idx], "*err.message) : rethrow(err) | ||
end | ||
end | ||
allgood || throw(ValidationError("Some equations had invalid units. See warnings for details.")) | ||
return output | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
should probably show unit if it's there. Good way to know it's not just a number.