uom icon indicating copy to clipboard operation
uom copied to clipboard

Multiply Ratio and Angle

Open jacg opened this issue 1 year ago • 4 comments

Ratio and Angle cannot be multiplied, because of mismatching Kinds.

Why would I want this to work? Imagine a weighted-mean function, here hard-wired for Length:

pub fn mean_weighted_length(data: &[Length], weights: &[Ratio]) -> Option<Length> {
    let total_weight: Ratio = weights.iter().cloned().sum();
    data.iter()
        .cloned()
        .zip(weights.iter().cloned())
        .map(   |(d, w)| d * w)
        .reduce(| a, b | a + b)
        .map(|x| x / total_weight)
}

I should be able to write such a function for any Quantity, not just Length. And it fails to compile if Length is replaced with Angle:

pub fn mean_weighted_angle(data: &[Angle], weights: &[Ratio]) -> Option<Angle> {
    let total_weight: Ratio = weights.iter().cloned().sum();
    data.iter()
        .cloned()
        .zip(weights.iter().cloned())
        .map(   |(d, w)| d * w)
        .reduce(| a, b | a + b)
        .map(|x| x / total_weight)
}

jacg avatar Jul 18 '22 22:07 jacg

Short answer is that Kinds are messing things up. Adding an .into() to the reduce fixes the problem.

-        .map(|x| x / total_weight)
+        .map(|x| (x / total_weight).into())

The long answer is that uom uses an associated type, Kind, to distinguish between quantities with otherwise equal dimensions. e.g. Ratio and Angle or ThermodynamicTemperature and TemperatureInterval. See how Ratio's Dimension has a Kind of uom::Kind while Angle's Dimension has a Kind of AngleKind.

The current implementation of multiplication and division sets the output type's Kind to uom::Kind. See the discussion in #313 for a more discussion (I'm going to post there next). After doing multiplication or division you can force the desired Kind by adding a type annotation to the result or by using the turbo fish.

I guessed Kind was the issue after reading the issue, but verified by running your example. I tried to emphasize the important part in the error message below but it doesn't stand out well. The expected type includes Kind = (dyn AngleKind + 'static) while the actual type includes Kind = (dyn Kind + 'static)

   = note: expected enum `Option<Quantity<(dyn Dimension<Th = Z0, N = Z0, I = Z0, L = Z0, M = Z0, T = Z0, Kind = (dyn AngleKind + 'static), 
J = Z0> + 'static), (dyn uom::si::Units<f32, thermodynamic_temperature = uom::si::thermodynamic_temperature::kelvin, time = uom::si::time::s
econd, length = uom::si::length::meter, mass = uom::si::mass::kilogram, electric_current = uom::si::electric_current::ampere, luminous_inten
sity = uom::si::luminous_intensity::candela, amount_of_substance = uom::si::amount_of_substance::mole> + 'static), _>>`
              found enum `Option<Quantity<dyn Dimension<Th = Z0, N = Z0, I = Z0, L = Z0, M = Z0, T = Z0, Kind = (dyn Kind + 'static), J = Z0
>, dyn uom::si::Units<f32, thermodynamic_temperature = uom::si::thermodynamic_temperature::kelvin, time = uom::si::time::second, length = uo
m::si::length::meter, mass = uom::si::mass::kilogram, electric_current = uom::si::electric_current::ampere, luminous_intensity = uom::si::lu
minous_intensity::candela, amount_of_substance = uom::si::amount_of_substance::mole>, _>>`

iliekturtles avatar Jul 19 '22 00:07 iliekturtles

Apologies, I should have stated explicitly that it was obvious to me (so obvious, apparently, that it didn't seem worth mentioning) that Kinds were getting in the way, and why Kinds exist. What I didn't understand is how to work around the problem, which you've explained. Thank you.

Going off on a slight tangent, I'm trying to make a generic weighted_mean. This version

This version


pub fn weighted_mean<T>(data: &[T], weights: &[Ratio]) -> Option<T>
where
    T: Mul<Ratio> + Div<Ratio> + Add<Output = T> + Clone,
    <T as Mul<Ratio>>::Output: Into<T>,
    <T as Div<Ratio>>::Output: Into<T>,
{
    assert_eq!(data.len(), weights.len());
    let total_weight: Ratio = weights.iter().cloned().sum();
    data.iter().cloned()
        .zip(weights.iter().cloned())
        .map(   |(d, w)| (d * w).into())
        .reduce(| a, b |  a + b        )
        .map(   | x    | (x / total_weight).into())
}

seems to work.

Here are some tests that I'm using, in case it's useful
#[cfg(test)]
mod tests {
    use super::*;

    pub fn mm    (x: f32) -> Length { Length::new::<uom::si::length::millimeter>(x) }
    pub fn ratio (x: f32) -> Ratio  {  Ratio::new::<uom::si::ratio ::ratio     >(x) }
    pub fn radian(x: f32) -> Angle  {  Angle::new::<uom::si::angle ::radian    >(x) }

    #[test]
    fn length() {
        let lengths = vec![   mm(2.0),    mm(4.0)];
        let weights = vec![ratio(8.0), ratio(2.0)];
        let wav: Length = weighted_mean(&lengths, &weights).unwrap();
        assert_eq!(wav, mm(2.4))
    }

    #[test]
    fn angle() {
        let angles  = vec![radian(2.0), radian(4.0)];
        let weights = vec![ ratio(8.0),  ratio(2.0)];
        let wav: Angle = weighted_mean(&angles, &weights).unwrap();
        assert_eq!(wav, mm(2.4))
    }
}

The two tests are essentially identical, with the second using Angle where the first used Length.

Does this look like a reasonable approach, or have I missed something?

jacg avatar Jul 19 '22 14:07 jacg

  • If total_weight is 0 you'll get a NaN or divide by zero error.
  • I take it you intended the return to be Option<T>?

Everything else looks reasonable. Will be even better once #307 is merged since you'll be able to drop the .cloned() calls!

iliekturtles avatar Jul 21 '22 23:07 iliekturtles

Thanks. Good point about zero-weight-sum. Yes, intended the Option to guard against zero-length input. For my needs, zero-sum-weights should probably panic but I need to think about it a bit more. Currently travelling, hope to find some time to work on #307 in the second half of next week.

jacg avatar Jul 22 '22 07:07 jacg