# Problem combining Unitful and MonteCarloMeasurements

**URL:** https://discourse.julialang.org/t/problem-combining-unitful-and-montecarlomeasurements/35418
**Category:** Modelling & Simulations
**Tags:** unitful, measurements
**Created:** [March 2, 2020, 4:40pm UTC](https://discourse.julialang.org/t/problem-combining-unitful-and-montecarlomeasurements/35418 "2020-03-02T16:40:30Z")
**Posts on this page:** 13
**Page:** 1

<div class="post-metadata">

### Author: ![klaff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/klaff/32/7637_2.png) [@klaff](https://discourse.julialang.org/u/klaff)
#### Post date: [March 2, 2020, 4:40pm UTC](https://discourse.julialang.org/t/problem-combining-unitful-and-montecarlomeasurements/35418/1 "2020-03-02T16:40:30Z")

</div>

Consider the functions `f1` and `f2`:

```julia
using MonteCarloMeasurements
using Unitful

function f1(Vi)
    if Vi ≤ 0.0
        return 0.0
    elseif Vi ≥ 1.0
        return 1.0
    else
        Vi
    end
end

function f2(Vi)
    if Vi ≤ 0.0u"V"
        return 0.0u"V"
    elseif Vi ≥ 1.0u"V"
        return 1.0u"V"
    else
        return Vi
    end
end

```

then `f1(0.0..1.0)` succeeds, but `f1(-0.5..1.5)` fails. This is understandable as the second distribution spans the discontinuities. If I then `register_primitive(f1)` and subsequently execute `f1(-0.5..1.5)`, it succeeds and inspection of the result shows it is as I expect.

However, if I try the same thing with f2 (which I intend to be the exact same function except that now I’m using Unitful and everything should be in units compatible with `u"V"`), f2 fails, regardless of `register_primitive(f2)`.

EDIT: Adding calls to f2: `f2((0.0..1.0)u"V")` works, `f2((-0.5..1.5)u"V")` always fails.

---

<div class="post-metadata">

### Author: ![simeonschaub](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/simeonschaub/32/216566_2.png) [@simeonschaub](https://discourse.julialang.org/u/simeonschaub)
#### Post date: [March 2, 2020, 7:53pm UTC](https://discourse.julialang.org/t/problem-combining-unitful-and-montecarlomeasurements/35418/3 "2020-03-02T19:53:00Z")

</div>

The problem here is that `(-0.5..1.5)u"V"` is creating an object of type `Quantity{Particles}`, whereas `register_primitive` only overloads `f2` for `Particles`, so that second method never gets called. I don’t immediately see a very clean workaround for this from the `MonteCarloMeasurements` side, but it would be worth opening an issue there, maybe other people have better ideas. As a quick solution to your case, you could overload `Quantity{Particles}`, with the following definition:

```julia
function f2(x::Quantity{Particles{T,N}}) where {T,N}
    u = unit(x)
    x = ustrip(u, x)
    v = map(x -> f2(x * u), Vector(x))
    return Particles{eltype(v),N}(v)
end

```

, but I agree that that’s definitely cumbersome.

Edit:  
I got the definition wrong at first, now it works, but the result throws an error when printed.

---

<div class="post-metadata">

### Author: ![klaff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/klaff/32/7637_2.png) [@klaff](https://discourse.julialang.org/u/klaff)
#### Post date: [March 2, 2020, 8:42pm UTC](https://discourse.julialang.org/t/problem-combining-unitful-and-montecarlomeasurements/35418/4 "2020-03-02T20:42:12Z")

</div>

Thank you, that makes good sense. For now I’m dropping Unitful out of this piece of work.

---

<div class="post-metadata">

### Author: ![klaff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/klaff/32/7637_2.png) [@klaff](https://discourse.julialang.org/u/klaff)
#### Post date: [March 2, 2020, 8:53pm UTC](https://discourse.julialang.org/t/problem-combining-unitful-and-montecarlomeasurements/35418/5 "2020-03-02T20:53:56Z")

</div>

And I submitted an issue. Thank you for your help.

---

<div class="post-metadata">

### Author: ![baggepinnen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/baggepinnen/32/693_2.png) [@baggepinnen](https://discourse.julialang.org/u/baggepinnen)
#### Post date: [March 2, 2020, 9:53pm UTC](https://discourse.julialang.org/t/problem-combining-unitful-and-montecarlomeasurements/35418/6 "2020-03-02T21:53:13Z")

</div>

Thanks for the issue, and the help Simeon. I [responded in the issue](https://github.com/baggepinnen/MonteCarloMeasurements.jl/issues/68#issuecomment-593640846).

The code Simeon shared is close to a `register_primitive` for the special type `Quantity{Particles}`. Hopefully, we should be able to do this a bit more automatic, possibly while working with the reverse representation, i.e., `Particles{Quantity}`.

---

<div class="post-metadata">

### Author: ![klaff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/klaff/32/7637_2.png) [@klaff](https://discourse.julialang.org/u/klaff)
#### Post date: [March 3, 2020, 3:36am UTC](https://discourse.julialang.org/t/problem-combining-unitful-and-montecarlomeasurements/35418/7 "2020-03-03T03:36:02Z")

</div>

Here’s my workaround for simple Monte Carlo with units:

```julia
using Unitful
using Plots
using Distributions, Random

function systematic_sample(d, N=10000)
    e=0.5/N
    y = e:1/N:1
    o = map(y) do y
        quantile(d,y)
    end
    permute!(o, randperm(N))
end

U(min,max) = systematic_sample(Uniform(min,max))
hist(X) = histogram([x.val for x in X])

function f2(Vi)
    if Vi ≤ 0.0u"V"
        return 0.0u"V"
    elseif Vi ≥ 1.0u"V"
        return 1.0u"V"
    else
        return Vi
    end
end

p = U(-0.5,1.5)u"V"
p2 = f2.(p)
extrema(p2)
hist(p2)

```

I’ve stolen your systematic sample function (simplified a bit) and just went to ordinary broadcasting. This lets me hang on to Unitful and I have a syntax that is simple and readable. Because I have some piece wise linear things (which is really how I got to the above MWE) I’d already lost some of the speed advantage of MCM over the brute force method.

---

<div class="post-metadata">

### Author: ![baggepinnen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/baggepinnen/32/693_2.png) [@baggepinnen](https://discourse.julialang.org/u/baggepinnen)
#### Post date: [March 3, 2020, 5:54am UTC](https://discourse.julialang.org/t/problem-combining-unitful-and-montecarlomeasurements/35418/8 "2020-03-03T05:54:43Z")

</div>

How does the workaround scale to when you have multiple uncertain values and vectors of uncertain variables?

---

<div class="post-metadata">

### Author: ![baggepinnen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/baggepinnen/32/693_2.png) [@baggepinnen](https://discourse.julialang.org/u/baggepinnen)
#### Post date: [March 3, 2020, 5:56am UTC](https://discourse.julialang.org/t/problem-combining-unitful-and-montecarlomeasurements/35418/9 "2020-03-03T05:56:01Z")

</div>

Another workaround would be to run your computations with scalar units first and then when it’s verified to be correct, you can switch to uncertain values for the uncertainty propagation?

---

<div class="post-metadata">

### Author: ![klaff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/klaff/32/7637_2.png) [@klaff](https://discourse.julialang.org/u/klaff)
#### Post date: [March 3, 2020, 2:40pm UTC](https://discourse.julialang.org/t/problem-combining-unitful-and-montecarlomeasurements/35418/10 "2020-03-03T14:40:20Z")

</div>

Let me describe my present application. I’m using Julia in place of a spreadsheet for electronic design calculations. To that end, I want to have concise, readable representations of the relationships that include units (no Mars Orbiter mistakes here, please) and include tolerances (which I want to be aware of in the first pass, not as an afterthought).

After looking at Measurements.jl, MonteCarloMeasurements.jl, IntervalArithmetic.jl, and probably some things I can’t remember, I think I want the following for this work:

1. Independent distributions that don’t forget who they are. In other words, if a and b are distinct distributions with the same properties, then I expect a/a to be one with zero deviation. Interval arithmetic doesn’t satisfy this.

2. I want to be able to choose distributions - I generally don’t have the input distributions, only the specification limits, so I may choose to be somewhat conservative and use a uniform dist like in my MWE, or maybe a truncated ±3σ normal. Measurements.jl doesn’t allow that choice.

3. I have functions which can take a variety of forms from simple linear equations or piece-wise linear approximations or non-linear things including saturation effects.

4. I want to have physical units attached. MonteCarloMeasurements.jl does this if the functions are simple.

5. Speed is not a big deal (right now). I am doing related simulations, some with Julia-based tools, some with other circuit-specific tools, but this work is more likely to inform what corners I simulate, at least for now.

6. One additional thing I would like is to be able to get both statistical values and worst-case values in one pass, where by worst case I mean the calculation over the product of all the min/max values (not always true though) of the input values. Extrema of results based on uniform dist inputs gets close.

I’m noodling on the idea of a struct that carries the upper and lower limits and the cloud of distribution points, and an application function (tmap for tolerancing map?) that does a worst-case calculation based on a Base.Iterators.product of the input spec limits, and also does the Monte Carlo calc, and then produces a similar struct for the computed output. I think I’ll let that idea simmer while I go back to work!

Thank you for your work on MonteCarloMeasurements, it’s a cool package!

---

<div class="post-metadata">

### Author: ![baggepinnen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/baggepinnen/32/693_2.png) [@baggepinnen](https://discourse.julialang.org/u/baggepinnen)
#### Post date: [March 31, 2020, 7:21am UTC](https://discourse.julialang.org/t/problem-combining-unitful-and-montecarlomeasurements/35418/11 "2020-03-31T07:21:06Z")

</div>

I’ve added some support for Unitful in [this PR](https://github.com/baggepinnen/MonteCarloMeasurements.jl/pull/72)  
I’m not a user of Unitful myself so I’m not sure what to test, but anyone interested is welcome to try it out and provide some tests cases if it fails.

---

<div class="post-metadata">

### Author: ![klaff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/klaff/32/7637_2.png) [@klaff](https://discourse.julialang.org/u/klaff)
#### Post date: [March 31, 2020, 4:56pm UTC](https://discourse.julialang.org/t/problem-combining-unitful-and-montecarlomeasurements/35418/12 "2020-03-31T16:56:02Z")

</div>

Thank you! I would love to try it out. It may be a few days or a week before I have time.

---

<div class="post-metadata">

### Author: ![naveenatmit](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/naveenatmit/32/23854_2.png) [@naveenatmit](https://discourse.julialang.org/u/naveenatmit)
#### Post date: [April 11, 2023, 7:42am UTC](https://discourse.julialang.org/t/problem-combining-unitful-and-montecarlomeasurements/35418/13 "2023-04-11T07:42:00Z")

</div>

Is there any solution now to use Julia for simple worst case calculations that we sometimes do manually in excel?

---

<div class="post-metadata">

### Author: ![baggepinnen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/baggepinnen/32/693_2.png) [@baggepinnen](https://discourse.julialang.org/u/baggepinnen)
#### Post date: [April 11, 2023, 10:32am UTC](https://discourse.julialang.org/t/problem-combining-unitful-and-montecarlomeasurements/35418/14 "2023-04-11T10:32:39Z")

</div>

I don’t know what you do in excel, but have a look at

> **[GitHub - JuliaIntervals/IntervalArithmetic.jl: Rigorous floating-point...](https://github.com/JuliaIntervals/IntervalArithmetic.jl)**
>
> Rigorous floating-point calculations using interval arithmetic in Julia - GitHub - JuliaIntervals/IntervalArithmetic.jl: Rigorous floating-point calculations using interval arithmetic in Julia
