Skip to content

Examples of non-ideal unit validation #3824

@ctessum

Description

@ctessum

There are some cases where unit validation is more permissive in the current version of MTK using DynamicsQuanitities than it was in the previous version using Unitful.

Mixed media

Sometimes there is a system with multiple quantities that have the same SI units, but nonetheless are not fungible. For example, we might have "oil" and "water". In this case, it is common to represent the units as kg_oil and kg_water, to serve as a reminder that the two units shouldn't cancel each other. In MTK, we would represent this as:

using ModelingToolkit, DynamicQuantities, Test
using ModelingToolkit: get_unit, ValidationError

@register_unit kg_oil 1u"kg"
@register_unit kg_water 1u"kg"

@constants m_o = 1 [unit=1.0u"kg_oil", description="Mass of oil"]
@constants m_w = 1 [unit=1.0u"kg_water", description="Mass of water"]

@test_throws ValidationError get_unit(m_w + m_o) # This test fails

In the above test, we should not be able to add the oil and water together (they don't mix!) so we would expect a unit validation error in this case, but MTK currently allows to do this without a unit validation error.

Mixing Ratios

Mixing ratios are unit-less in one sense, but in another sense they are a ratio of two different units which are not equivalent. For example:

@register_unit m_oil 1u"m"
@register_unit m_water 1u"m"

@constants mass_ratio = 1 [unit=1us"kg_oil/kg_water"]
@constants volume_ratio = 1 [unit=1us"m_oil^3/m_water^3"]

@test_throws ValidationError get_unit(mass_ratio + volume_ratio) # This test fails

In the code above, would expect that if we add a mass mixing ratio and a volume mixing ratio there would be a unit validation error, because that's not allowed! However, MTK currently allows this without a unit validation error.

Powers of mixing ratios

This is similar to the previous ones, but it isn't appropriate to add different powers of mixing ratios together, although this is currently allowed in MTK:

@test_throws ValidationError get_unit(mass_ratio + mass_ratio^2) # This test fails

It could be argued that all of the examples above are functioning as expected, but on the other hand these all represent human errors that are commonly made in practice (at least in my experience) so it could be good to be able to catch them with unit validation. These are also all things that were considered errors in the previous version with Unitful.

Just something to consider.

Environment (please complete the following information):

  • Output of using Pkg; Pkg.status()
  [06fc5a27] DynamicQuantities v1.8.0
  [961ee093] ModelingToolkit v10.10.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions