Skip to content
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

Particles & Unitful #152

Closed
aplavin opened this issue Dec 26, 2024 · 3 comments · Fixed by #159
Closed

Particles & Unitful #152

aplavin opened this issue Dec 26, 2024 · 3 comments · Fixed by #159

Comments

@aplavin
Copy link
Contributor

aplavin commented Dec 26, 2024

I noticed that sometimes mixing units and MCM particles results in weird results – nesting two levels of Particles, resulting in 2000*2000 floats underneath:

julia> using MonteCarloMeasurements, Unitful

julia> x = Particles()
4.44089e-19 ± 1.0 Particles{Float64, 2000}


julia> y = 123u"m" * x
1.02318e-15 ± 123.0 Particles{Float64, 2000}
 m

julia> x * y
-2.8e-17 ± 2.0e-15 m ± 98.1 ± 74.0 m Particles{Quantity{Particles{Float64, 2000}, 𝐋, Unitful.FreeUnits{(m,), 𝐋, nothing}}, 2000}

I wonder how to avoid/fix that?

@baggepinnen
Copy link
Owner

It seems you're creating an object with the wrong type, see
https://baggepinnen.github.io/MonteCarloMeasurements.jl/stable/examples/#Unitful-interaction-1

@aplavin
Copy link
Contributor Author

aplavin commented Dec 26, 2024

Thanks, I saw that part, just not sure how to apply it in my case.
I start with a non-unitful Particles that are passed to a (ideally, blackbox) function that does some unitful calculations in it but its input and output are non-unitful:

julia> function f(x)  # simple MWE for f
           y = 123u"m" * x
           ustrip(u"cm", x*y)
       end

julia> x = Particles()  # create an plain non-unitful particles
8.88178e-19 ± 1.0 Particles{Float64, 2000}

julia> f(x)  # apply f to x, expecting to get just Particles{Float64, 2000}:
-1.2e-16 ± 1.3e-13 ± 9810.0 ± 7400.0 Particles{Particles{Float64, 2000}, 2000}

@baggepinnen
Copy link
Owner

baggepinnen commented Jan 7, 2025

The issue is probably some missing methods in the unitful extension. The multiplication 123u"m" * x dispatches to

*(x::AbstractQuantity, y::Number)

in Unitful, instead of

function Base.$f(y::Quantity{S,D,U}, p::$PT{T,N}) where {S, D, U, T <: Quantity, N}
    QT = Base.promote_op($op, typeof(y), T)
    $PT{QT,N}($(op).(y, p.particles))
end

in MCM.jl due to the T <: Quantity. Changing this to T <: Number appears to resolve the issue.

Try out

and see if that works out for you, if it does, I'll make a new release

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants