Code Monkey home page Code Monkey logo

unitfulparsablestring.jl's Introduction

UnitfulParsableString Build Status Stable Dev Build Status UnitfulParsableString Downloads

UnitfulParsableString.jl expand Unitful.jl to add the method Unitful.string which convert Quantity (or some type) to parsable String.

julia> using Unitful

julia> string(1.0u"m*s") 
"1.0 m s" # <- julia cannot parse

julia> string(1.0u"m*s") |> Unitful.uparse
ERROR: Base.Meta.ParseError("extra token \"m\" after end of expression")

julia> using UnitfulParsableString

julia> string(1.0u"m*s")
"1.0(m*s)" # <- julia can parse

julia> string(1.0u"m*s") |> Unitful.uparse
1.0 m s

Expression of Unit

Unitful.string(unit::Units)

Values of Unitful.Units subtypes are converted to string that julia can parse as following rules.

Multi-units are expressed as basicaly separeted by "*", but sometimes "/" is used exceptionally for simplicity, see below for details. Exponents are expressed as "^x" or "^-x" (x > 0) in principle, except for units with a rational exponent y, which are expressed by wrapping them in parentheses as "^(y)".

Detail of separatoers

When all exponential of the units is positive, all separates are "*".

julia> string(u"m*s^2")
"m*s^2"

When all exponential of the units is negative, all separates are "*" and the negative exponential is expressed as "^-|w|".

julia> string(u"(m*s)^-1") # all exponents are negative
"m^-1*s^-1"                # -> separater is "*"

When both positive and negative exponentials coexist, if there are rational exponentials, all separates are "*" and the negative exponential is expressed as "^-|w|".

julia> string(u"m^(1/2)*s^-2") # positive and negative exponent coexist
"m^(1/2)*s^-2"                 # if rational exponent exist -> separater is "*"

When both positive and negative exponentials coexist, if not there are rational exponentials, the separates of the units with negative exponential are "/" and the negative exponential is expressed as "^|w|".

julia> string(u"m*s^-2") # positive and negative exponent coexist
"m/s^2"                  # if rational exponent never exist -> "/" can be use for separater

Detail of rational exponents

When the exponentials are rational, if the velue n//m is strictly same as n/m, it is expressed as "^(n/m)".

julia> string(u"m^(1//2)") # 1//2 == 1/2
"m^(1/2)"

If not the velue n//m is strictly same as n/m, it is expressed as "^(n//m)".

julia> string(u"m^(1//3)") # 1//3 != 1/3
"m^(1//3)"

Expression of Quantity

Unitful.string(x::Quantity)

Values of Unitful.Quantity subtypes to string that julia can parse as following rules.

The Unitful.Quantity x have value and units (they can be get x.val and unit(x)). Thus, the work of this function is simply shown as follows:

string( ["(",] string(value), [")",] ["*",] ["(",] string(units) [,")"] )

The presence or absence of each bracket is determined by the return values of the has_value_bracket(x) and has_unit_bracket(x) functions. And the sepaprator "*" is inserted, if has_value_bracket(x) && has_unit_bracket(x) == true.

The has_value_bracket(x) returns false if string(x) contains only digits, and true if it contains non-digits. However, if typeof(x) is a specific type, the process is lightened by multiple dispatching.

The has_unit_bracket(x) returns false if the unit(x) consists of single type unit, and true if it consists of multi type units.

Note: see Unitful.string(x::Unitlike) about the string expression of unit.
Note: if unit(x) == NoUnits, this method output only string(x.val).

At the case of Int the bracket is absence and, at the case of the unit consists of only s the bracket is absence.
has_value_bracket(x) = false && has_unit_bracket(x) == false

julia> string(u"1s^2")	# u"1s^2" -> 1 s²
"1s^2"

At the case of Float64 the bracket is absence and, at the case of the unit consists of kg and m the bracket is presence.
has_value_bracket(x) = false && has_unit_bracket(x) == true

julia> string(u"1.0m*kg")	# u"1.0m*kg" -> 1.0 kg m
"1.0(kg*m)"

At the case of Rational the bracket is presence and, at the case of the unit consists of m the bracket is absence.
has_value_bracket(x) = true && has_unit_bracket(x) == false

julia> string((1//2)u"m")	# (1//2)u"m" -> 1//2 m
"(1//2)m"

At the case of Rational the bracket is presence and, at the case of the unit consists of m and s the bracket is presence.
has_value_bracket(x) = true && has_unit_bracket(x) == true

julia> string((1+2im)u"m/s")	# (1+2im)u"m/s" -> (1 + 2im) m s⁻¹
"(1 + 2im)*(m/s)"

Parsability

expamle

julia> using UnitfulParsableString 

julia> x = u"1.0m^2/K^(1//3)"
1.0 m² K⁻¹ᐟ³

julia>  x |> string |> uparse == x
true

julia> x = 2u"m"//3u"s"
2//3 m s⁻¹

julia> x |> string |> uparse == x
true

See more test/runtest.jl.

Note

UnitfulParsableString.jl not change the display, show and print functions about Unitful.jl.

julia> using Unitful

julia> 1.0u"m"
1.0 m

julia> 1.0u"m*s"
1.0 m s

julia> using UnitfulParsableString

julia> 1.0u"m"
1.0 m

julia> 1.0u"m*s"
1.0 m s

Limitation

This package not support Logscaled units i.e., Gain or Lebel yet. Array of Quantity is now supported, but implementation is too rough. Please use at your own risk.

Related Packages

  • Unitful.jl - Implements dimensional numerical quantities for Julia

unitfulparsablestring.jl's People

Contributors

michikawa07 avatar jagot avatar dependabot[bot] avatar

Stargazers

 avatar Ujjwal Panda avatar Michael Hatherly avatar Qi Zhang avatar Thomas Poulsen avatar Benoît Pasquier avatar

Watchers

 avatar

Forkers

jagot

unitfulparsablestring.jl's Issues

`Unitful.string` is actually `Base.string`

This package extends Unitful.string. But Unitful does not define a string function, so it actually extends Base.string. Calling it Unitful.string just seems confusing to me. Is there a reason for doing it like this?

It also means that this package would break if an actual Unitful.string function is defined in Unitful (the function in this package would then no longer extend Base.string but instead Unitful.string, which might have a different purpose and might not even be exported).

Also, irrespective of whether extending Unitful.string or Base.string, this is type piracy. It might be better to define a UnitfulParsableString.string function. It could have a fallback method that calls Base.string so that it can be used as a replacement. Of course, this would be a breaking change.

What do you think of this?

Does not seem to work on symbols defined outside `Unitful.jl`, e.g, `UnitfulAtomic.jl`

For example,

julia> string(1u"bohr")
"1a₀"

julia> Unitful.uparse(string(1u"bohr"); unit_context=[Unitful,UnitfulAtomic])
ERROR: ArgumentError: Symbol a₀ could not be found in unit modules Module[Unitful, UnitfulAtomic]
Stacktrace:
 [1] lookup_units(unitmods::Vector{Module}, sym::Symbol)
   @ Unitful ~/.julia/packages/Unitful/SUQzL/src/user.jl:707
 [2] lookup_units(unitmods::Vector{Module}, ex::Expr)
   @ Unitful ~/.julia/packages/Unitful/SUQzL/src/user.jl:674
 [3] uparse(str::String; unit_context::Vector{Module})
   @ Unitful ~/.julia/packages/Unitful/SUQzL/src/user.jl:662
 [4] top-level scope
   @ REPL[20]:1
julia> versioninfo()
Julia Version 1.8.1
Commit afb6c60d69a (2022-09-06 15:09 UTC)

TagBot trigger issue

This issue is used to trigger TagBot; feel free to unsubscribe.

If you haven't already, you should update your TagBot.yml to include issue comment triggers.
Please see this post on Discourse for instructions and more details.

If you'd like for me to do this for you, comment TagBot fix on this issue.
I'll open a PR within a few hours, please be patient!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.