SciNim / Unchained

A fully type safe, compile time only units library.
https://scinim.github.io/Unchained
109 stars 0 forks source link

Units from declarative macro instead of manually coded definitions #24

Closed Vindaar closed 2 years ago

Vindaar commented 2 years ago

Further progress towards #8.

After cleaning this up (especially the duplicated parsing logic & partially duplicated types in main & for definition), we are essentially ready to replace most of the current logic based on UnitKind etc. by a more type aware logic based on DefinedUnit elements. This will significantly clean up how individual units are added and maintained.

edit: making good progress... edit 2: it is done.

With this now complete, #8 should essentially be solved now. This means in theory we can define any unit system as follows:

declareQuantities:
  Base:
    Time
    Length
    Mass
    ....
  Derived:                 # derived quantities are those based on a 'linear combination' of base quantities
    Frequency:             [(Time, -1)]
    Velocity:              [(Length, 1), (Time, -1)]
    Acceleration:          [(Length, 1), (Time, -2)]
    ...

declareUnits:
  BaseUnits:               # define the base units of the system. Must correspond to `Base` quantities
    Gram:                  # the long name
      short: g             # the short name
      prefix: siKilo       # can be used to define a different prefix as the base type
      quantity: Mass       # the quantity it corresponds to
    Meter:
      short: m
      quantity: Length
    Second:
      short: s
      quantity: Time

  Derived:                 # derived units are those corresponding to derived quantities
    Newton:
      short: N
      quantity: Force      # generate SI based derivative based on Quantity & quantity dimensionality
    Joule:
      short: J
      quantity: Energy
    ...
    Radian:
      short: rad
      quantity: Angle
      autoConvert: false   # autoConvert can be used to forbid conversions
    ...
                           # multiple units for one quantity can be defined
    Gauss:
      short: G
      quantity: MagneticFieldStrength
      conversion: 1e-4.T   # their conversion to the main unit of that quantity must be defined
    ...

                           # natural unit conversions from given units can be defined as such:
  NaturalUnits:
    Gram: 1.7826627e-33.eV # relative to g and not kg!
    Meter: 1.9732705e-7.eV⁻¹
    ...

                           # generate all units with SI prefixes of the base
generateSiPrefixedUnits:
  (m, Meter)
  (s, Second)
  ...
  (T, Tesla) exclude [f]   # individual prefixes can be excluded if ambiguous

So feel free to define the CGS or whatever you please.