Unit.java

  1. /* Copyright 2002-2023 CS GROUP
  2.  * Licensed to CS GROUP (CS) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * CS licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *   http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.orekit.utils.units;

  18. import java.io.Serializable;
  19. import java.util.List;

  20. import org.hipparchus.fraction.Fraction;
  21. import org.hipparchus.util.FastMath;
  22. import org.hipparchus.util.Precision;
  23. import org.orekit.errors.OrekitException;
  24. import org.orekit.errors.OrekitMessages;

  25. /** Basic handling of multiplicative units.
  26.  * <p>
  27.  * This class is by no means a complete handling of units. For complete
  28.  * support, look at libraries like {@code UOM}. This class handles only
  29.  * time, length, mass and current dimensions, as well as angles (which are
  30.  * dimensionless).
  31.  * </p>
  32.  * <p>
  33.  * Instances of this class are immutable.
  34.  * </p>
  35.  * @see <a href="https://github.com/netomi/uom">UOM</a>
  36.  * @author Luc Maisonobe
  37.  * @since 11.0
  38.  */
  39. public class Unit implements Serializable {

  40.     /** No unit. */
  41.     public static final Unit NONE = new Unit("n/a", 1.0, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO);

  42.     /** Dimensionless unit. */
  43.     public static final Unit ONE = new Unit("1", 1.0, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO);

  44.     /** Percentage unit. */
  45.     public static final Unit PERCENT = new Unit("%", 1.0e-2, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO);

  46.     /** Second unit. */
  47.     public static final Unit SECOND = new Unit("s", 1.0, Fraction.ZERO, Fraction.ZERO, Fraction.ONE, Fraction.ZERO, Fraction.ZERO);

  48.     /** Minute unit. */
  49.     public static final Unit MINUTE = SECOND.scale("min", 60.0);

  50.     /** Hour unit. */
  51.     public static final Unit HOUR = MINUTE.scale("h", 60);

  52.     /** Day unit. */
  53.     public static final Unit DAY = HOUR.scale("d", 24.0);

  54.     /** Julian year unit.
  55.      * @see <a href="https://www.iau.org/publications/proceedings_rules/units/">SI Units at IAU</a>
  56.      */
  57.     public static final Unit YEAR = DAY.scale("a", 365.25);

  58.     /** Hertz unit. */
  59.     public static final Unit HERTZ = SECOND.power("Hz", Fraction.MINUS_ONE);

  60.     /** Metre unit. */
  61.     public static final Unit METRE = new Unit("m", 1.0, Fraction.ZERO, Fraction.ONE, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO);

  62.     /** Kilometre unit. */
  63.     public static final Unit KILOMETRE = METRE.scale("km", 1000.0);

  64.     /** Kilogram unit. */
  65.     public static final Unit KILOGRAM = new Unit("kg", 1.0, Fraction.ONE, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO);

  66.     /** Gram unit. */
  67.     public static final Unit GRAM = KILOGRAM.scale("g", 1.0e-3);

  68.     /** Ampere unit. */
  69.     public static final Unit AMPERE = new Unit("A", 1.0, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO, Fraction.ONE, Fraction.ZERO);

  70.     /** Radian unit. */
  71.     public static final Unit RADIAN = new Unit("rad", 1.0, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO, Fraction.ONE);

  72.     /** Degree unit. */
  73.     public static final Unit DEGREE = RADIAN.scale("°", FastMath.toRadians(1.0));

  74.     /** Arc minute unit. */
  75.     public static final Unit ARC_MINUTE = DEGREE.scale("′", 1.0 / 60.0);

  76.     /** Arc second unit. */
  77.     public static final Unit ARC_SECOND = ARC_MINUTE.scale("″", 1.0 / 60.0);

  78.     /** Revolution unit. */
  79.     public static final Unit REVOLUTION = RADIAN.scale("rev", 2.0 * FastMath.PI);

  80.     /** Newton unit. */
  81.     public static final Unit NEWTON = KILOGRAM.multiply(null, METRE).divide("N", SECOND.power(null, Fraction.TWO));

  82.     /** Pascal unit. */
  83.     public static final Unit PASCAL = NEWTON.divide("Pa", METRE.power(null, Fraction.TWO));

  84.     /** Bar unit. */
  85.     public static final Unit BAR = PASCAL.scale("bar", 100000.0);

  86.     /** Joule unit. */
  87.     public static final Unit JOULE = NEWTON.multiply("J", METRE);

  88.     /** Watt unit. */
  89.     public static final Unit WATT = JOULE.divide("W", SECOND);

  90.     /** Coulomb unit. */
  91.     public static final Unit COULOMB = SECOND.multiply("C", AMPERE);

  92.     /** Volt unit. */
  93.     public static final Unit VOLT = WATT.divide("V", AMPERE);

  94.     /** Ohm unit. */
  95.     public static final Unit OHM = VOLT.divide("Ω", AMPERE);

  96.     /** tesla unit. */
  97.     public static final Unit TESLA = VOLT.multiply(null, SECOND).divide("T", METRE.power(null, Fraction.TWO));

  98.     /** Solar Flux Unit. */
  99.     public static final Unit SOLAR_FLUX_UNIT = WATT.divide(null, METRE.power(null, Fraction.TWO).multiply(null, HERTZ)).scale("SFU", 1.0e-22);

  100.     /** Total Electron Content Unit. */
  101.     public static final Unit TOTAL_ELECTRON_CONTENT_UNIT = METRE.power(null, new Fraction(-2)).scale("TECU", 1.0e+16);

  102.     /** Earth Radii used as Bstar unit in CCSDS OMM. */
  103.     public static final Unit EARTH_RADII = new Unit("ER", 1.0, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO, Fraction.ONE, Fraction.ZERO);

  104.     /** Serializable UID. */
  105.     private static final long serialVersionUID = 20210402L;

  106.     /** Name name of the unit. */
  107.     private final String name;

  108.     /** Scaling factor to SI units. */
  109.     private final double scale;

  110.     /** Mass exponent. */
  111.     private final Fraction mass;

  112.     /** Length exponent. */
  113.     private final Fraction length;

  114.     /** Time exponent. */
  115.     private final Fraction time;

  116.     /** Current exponent. */
  117.     private final Fraction current;

  118.     /** Angle exponent. */
  119.     private final Fraction angle;

  120.     /** Simple constructor.
  121.      * @param name name of the unit
  122.      * @param scale scaling factor to SI units
  123.      * @param mass mass exponent
  124.      * @param length length exponent
  125.      * @param time time exponent
  126.      * @param current current exponent
  127.      * @param angle angle exponent
  128.      */
  129.     public Unit(final String name, final double scale,
  130.                 final Fraction mass, final Fraction length,
  131.                 final Fraction time, final Fraction current,
  132.                 final Fraction angle) {
  133.         this.name    = name;
  134.         this.scale   = scale;
  135.         this.mass    = mass;
  136.         this.length  = length;
  137.         this.time    = time;
  138.         this.current = current;
  139.         this.angle   = angle;
  140.     }

  141.     /** Get the name of the unit.
  142.      * @return name of the unit
  143.      */
  144.     public String getName() {
  145.         return name;
  146.     }

  147.     /** Get the scaling factor to SI units.
  148.      * @return scaling factor to SI units
  149.      */
  150.     public double getScale() {
  151.         return scale;
  152.     }

  153.     /** Get the mass exponent.
  154.      * @return mass exponent
  155.      */
  156.     public Fraction getMass() {
  157.         return mass;
  158.     }

  159.     /** Get the length exponent.
  160.      * @return length exponent
  161.      */
  162.     public Fraction getLength() {
  163.         return length;
  164.     }

  165.     /** Get the time exponent.
  166.      * @return time exponent
  167.      */
  168.     public Fraction getTime() {
  169.         return time;
  170.     }

  171.     /** Get the current exponent.
  172.      * @return current exponent
  173.      */
  174.     public Fraction getCurrent() {
  175.         return current;
  176.     }

  177.     /** Get the angle exponent.
  178.      * @return angle exponent
  179.      */
  180.     public Fraction getAngle() {
  181.         return angle;
  182.     }

  183.     /** Check if a unit has the same dimension as another unit.
  184.      * @param other other unit to check against
  185.      * @return true if unit has the same dimension as the other unit
  186.      */
  187.     public boolean sameDimension(final Unit other) {
  188.         return time.equals(other.time) && length.equals(other.length)   &&
  189.                mass.equals(other.mass) && current.equals(other.current) &&
  190.                angle.equals(other.angle);
  191.     }

  192.     /** Create the SI unit with same dimension.
  193.      * @return a new unit, with same dimension as instance and scaling factor set to 1.0
  194.      */
  195.     public Unit sameDimensionSI() {
  196.         final StringBuilder builder = new StringBuilder();
  197.         append(builder, KILOGRAM.name, mass);
  198.         append(builder, METRE.name,    length);
  199.         append(builder, SECOND.name,   time);
  200.         append(builder, AMPERE.name,   current);
  201.         append(builder, RADIAN.name,   angle);
  202.         if (builder.length() == 0) {
  203.             builder.append('1');
  204.         }
  205.         return new Unit(builder.toString(), 1.0, mass, length, time, current, angle);
  206.     }

  207.     /** Ensure some units are compatible with reference units.
  208.      * @param description description of the units list (for error message generation)
  209.      * @param reference reference units
  210.      * @param units units to check
  211.      * @param allowScaleDifferences if true, unit with same dimension but different
  212.      * scale (like {@link #KILOMETRE} versus {@link #METRE}) are allowed, otherwise they will trigger an exception
  213.      * @exception OrekitException if units are not compatible (number of elements, dimensions or scaling)
  214.      */
  215.     public static void ensureCompatible(final String description, final List<Unit> reference,
  216.                                         final boolean allowScaleDifferences, final List<Unit> units) {
  217.         if (units.size() != reference.size()) {
  218.             throw new OrekitException(OrekitMessages.WRONG_NB_COMPONENTS,
  219.                                       description, reference.size(), units.size());
  220.         }
  221.         for (int i = 0; i < reference.size(); ++i) {
  222.             if (!reference.get(i).sameDimension(units.get(i))) {
  223.                 throw new OrekitException(OrekitMessages.INCOMPATIBLE_UNITS,
  224.                                           reference.get(i).getName(),
  225.                                           units.get(i).getName());
  226.             }
  227.             if (!(allowScaleDifferences ||
  228.                   Precision.equals(reference.get(i).getScale(), units.get(i).getScale(), 1))) {
  229.                 throw new OrekitException(OrekitMessages.INCOMPATIBLE_UNITS,
  230.                                           reference.get(i).getName(),
  231.                                           units.get(i).getName());
  232.             }
  233.         }
  234.     }

  235.     /** Append a dimension contribution to a unit name.
  236.      * @param builder builder for unit name
  237.      * @param dim name of the dimension
  238.      * @param exp exponent of the dimension
  239.      */
  240.     private void append(final StringBuilder builder, final String dim, final Fraction exp) {
  241.         if (!exp.isZero()) {
  242.             if (builder.length() > 0) {
  243.                 builder.append('.');
  244.             }
  245.             builder.append(dim);
  246.             if (exp.getDenominator() == 1) {
  247.                 if (exp.getNumerator() != 1) {
  248.                     builder.append(Integer.toString(exp.getNumerator()).
  249.                                    replace('-', '⁻').
  250.                                    replace('0', '⁰').
  251.                                    replace('1', '¹').
  252.                                    replace('2', '²').
  253.                                    replace('3', '³').
  254.                                    replace('4', '⁴').
  255.                                    replace('5', '⁵').
  256.                                    replace('6', '⁶').
  257.                                    replace('7', '⁷').
  258.                                    replace('8', '⁸').
  259.                                    replace('9', '⁹'));
  260.                 }
  261.             } else {
  262.                 builder.
  263.                     append("^(").
  264.                     append(exp.getNumerator()).
  265.                     append('/').
  266.                     append(exp.getDenominator()).
  267.                     append(')');
  268.             }
  269.         }
  270.     }

  271.     /** Create an alias for a unit.
  272.      * @param newName name of the new unit
  273.      * @return a new unit representing same unit as the instance but with a different name
  274.      */
  275.     public Unit alias(final String newName) {
  276.         return new Unit(newName, scale, mass, length, time, current, angle);
  277.     }

  278.     /** Scale a unit.
  279.      * @param newName name of the new unit
  280.      * @param factor scaling factor
  281.      * @return a new unit representing scale times the instance
  282.      */
  283.     public Unit scale(final String newName, final double factor) {
  284.         return new Unit(newName, factor * scale, mass, length, time, current, angle);
  285.     }

  286.     /** Create power of unit.
  287.      * @param newName name of the new unit
  288.      * @param exponent exponent to apply
  289.      * @return a new unit representing the power of the instance
  290.      */
  291.     public Unit power(final String newName, final Fraction exponent) {

  292.         final int num = exponent.getNumerator();
  293.         final int den = exponent.getDenominator();
  294.         double s = (num == 1) ? scale : FastMath.pow(scale, num);
  295.         if (den > 1) {
  296.             if (den == 2) {
  297.                 s = FastMath.sqrt(s);
  298.             } else if (den == 3) {
  299.                 s = FastMath.cbrt(s);
  300.             } else {
  301.                 s = FastMath.pow(s, 1.0 / den);
  302.             }
  303.         }

  304.         return new Unit(newName, s,
  305.                         mass.multiply(exponent), length.multiply(exponent),
  306.                         time.multiply(exponent), current.multiply(current),
  307.                         angle.multiply(exponent));
  308.     }

  309.     /** Create root of unit.
  310.      * @param newName name of the new unit
  311.      * @return a new unit representing the square root of the instance
  312.      */
  313.     public Unit sqrt(final String newName) {
  314.         return new Unit(newName, FastMath.sqrt(scale),
  315.                         mass.divide(2), length.divide(2),
  316.                         time.divide(2), current.divide(2),
  317.                         angle.divide(2));
  318.     }

  319.     /** Create product of units.
  320.      * @param newName name of the new unit
  321.      * @param other unit to multiply with
  322.      * @return a new unit representing the this times the other unit
  323.      */
  324.     public Unit multiply(final String newName, final Unit other) {
  325.         return new Unit(newName, scale * other.scale,
  326.                         mass.add(other.mass), length.add(other.length),
  327.                         time.add(other.time), current.add(other.current),
  328.                         angle.add(other.angle));
  329.     }

  330.     /** Create quotient of units.
  331.      * @param newName name of the new unit
  332.      * @param other unit to divide with
  333.      * @return a new unit representing the this divided by the other unit
  334.      */
  335.     public Unit divide(final String newName, final Unit other) {
  336.         return new Unit(newName, scale / other.scale,
  337.                         mass.subtract(other.mass), length.subtract(other.length),
  338.                         time.subtract(other.time), current.subtract(other.current),
  339.                         angle.subtract(other.angle));
  340.     }

  341.     /** Convert a value to SI units.
  342.      * @param value value instance unit
  343.      * @return value in SI units
  344.      */
  345.     public double toSI(final double value) {
  346.         return value * scale;
  347.     }

  348.     /** Convert a value to SI units.
  349.      * @param value value instance unit
  350.      * @return value in SI units
  351.      */
  352.     public double toSI(final Double value) {
  353.         return value == null ? Double.NaN : value.doubleValue() * scale;
  354.     }

  355.     /** Convert a value from SI units.
  356.      * @param value value SI unit
  357.      * @return value in instance units
  358.      */
  359.     public double fromSI(final double value) {
  360.         return value / scale;
  361.     }

  362.     /** Convert a value from SI units.
  363.      * @param value value SI unit
  364.      * @return value in instance units
  365.      */
  366.     public double fromSI(final Double value) {
  367.         return value == null ? Double.NaN : value.doubleValue() / scale;
  368.     }

  369.     /** Parse a unit.
  370.      * <p>
  371.      * The grammar for unit specification allows chains units multiplication and
  372.      * division, as well as putting powers on units.
  373.      * </p>
  374.      * <p>The symbols used for units are the SI units with some extensions.
  375.      * </p>
  376.      * <dl>
  377.      *   <dt>year</dt>
  378.      *   <dd>the accepted non-SI unit for Julian year is "a" but we also accept "yr"</dd>
  379.      *   <dt>day</dt>
  380.      *   <dd>the accepted non-SI unit for day is "d" but we also accept "day"</dd>
  381.      *   <dt>dimensionless</dt>
  382.      *   <dd>both "1" and "#" (U+0023, NUMBER SIGN) are accepted</dd>
  383.      *   <dt>mass</dt>
  384.      *   <dd>"g" is the standard symbol, despite the unit is "kg" (it is the only
  385.      *       unit that has a prefix in its name, so all multiples must be based on "g")</dd>
  386.      *   <dt>degrees</dt>
  387.      *   <dd>the base symbol for degrees is "°" (U+00B0, DEGREE SIGN), but we also accept
  388.      *       "◦" (U+25E6, WHITE BULLET) and "deg"</dd>
  389.      *   <dt>arcminute</dt>
  390.      *   <dd>The base symbol for arcminute is "′" (U+2032, PRIME) but we also accept "'" (U+0027, APOSTROPHE)</dd>
  391.      *   <dt>arcsecond</dt>
  392.      *   <dd>The base symbol for arcsecond is "″" (U+2033, DOUBLE PRIME) but we also accept
  393.      *   "''" (two occurrences of U+0027, APOSTROPHE), "\"" (U+0022, QUOTATION MARK) and "as"</dd>
  394.      * </dl>
  395.      * <p>
  396.      * All the SI prefix (from "y", yocto, to "Y", Yotta) are accepted, as well
  397.      * as integer prefixes. The standard symbol for micro 10⁻⁶ is "µ" (U+00B5, MICRO SIGN),
  398.      * but we also accept "μ" (U+03BC, GREEK SMALL LETTER MU). Beware that some combinations
  399.      * are forbidden, for example "Pa" is Pascal, not peta-years, and "as" is arcsecond for
  400.      * this parser, not atto-seconds, because many people in the space field use mas for
  401.      * milliarcseconds and µas for microarcseconds. Beware that prefixes are case-sensitive!
  402.      * Integer prefixes can be used to specify units like "30s", but only once at the beginning
  403.      * of the specification (i.e. "2rev/d²" is accepted, but "rev/(2d)²" is refused). Conforming
  404.      * with SI brochure "The International System of Units" (9th edition, 2019), each SI
  405.      * prefix is part of the unit and precedes the unit symbol without a separator
  406.      * (i.e. MHz is seen as one identifier).
  407.      * </p>
  408.      * <dl>
  409.      *   <dt>multiplication</dt>
  410.      *   <dd>can specified with either "*" (U+002A, ASTERISK), "×" (U+00D7, MULTIPLICATION SIGN),
  411.      *   "." (U+002E, FULL STOP) or "·" (U+00B7, MIDDLE DOT) as the operator</dd>
  412.      *   <dt>division</dt>
  413.      *   <dd>can be specified with either "/" (U+002F, SOLIDUS) or "⁄" (U+2044, FRACTION SLASH)
  414.      *   as the operator</dd>
  415.      *   <dt>powers</dt>
  416.      *   <dd>can be specified either by
  417.      *     <ul>
  418.      *       <li>prefixing with the unicode "√" (U+221A, SQUARE ROOT) character</li>
  419.      *       <li>postfixing with "**", "^" or implicitly using unicode superscripts</li>
  420.      *     </ul>
  421.      *   </dd>
  422.      * </dl>
  423.      * <p>
  424.      * Exponents can be specified in different ways:
  425.      * <ul>
  426.      *   <li>as an integer, as in "m^-2" or "m⁻²"</li>
  427.      *   <li>directly as unicode characters for the few fractions that unicode supports, as in "Ω^⅞"</li>
  428.      *   <li>as the special decimal value 0.5 which is used by CCSDS, as in "km**0.5"</li>
  429.      *   <li>as a pair of parentheses surrounding two integers separated by a solidus or fraction slash,
  430.      *   as in "Pa^(11/12)"</li>
  431.      * </ul>
  432.      * For integer exponents, the digits must be ASCII digits from the Basic Latin block from
  433.      * unicode if explicit exponent marker "**" or "^" is used, or using unicode superscript
  434.      * digits if implicit exponentiation (i.e. no markers at all) is used. Unicode superscripts
  435.      * are not allowed for fractional exponents because unicode does not provide a superscript solidus.
  436.      * Negative exponents can be used too.
  437.      * <p>
  438.      * These rules mean all the following (silly) examples are parsed properly:
  439.      * MHz, km/√d, kg.m.s⁻¹, µas^⅖/(h**(2)×m)³, km/√(kg.s), km**0.5, 2rev/d²
  440.      * </p>
  441.      * @param unitSpecification unit specification to parse
  442.      * @return parsed unit
  443.      */
  444.     public static Unit parse(final String unitSpecification) {

  445.         // parse the specification
  446.         final List<PowerTerm> terms = Parser.buildTermsList(unitSpecification);

  447.         if (terms == null) {
  448.             // special handling of "n/a"
  449.             return Unit.NONE;
  450.         }

  451.         // build compound unit
  452.         Unit unit = Unit.ONE;
  453.         for (final PowerTerm term : terms) {
  454.             try {
  455.                 Unit u = PrefixedUnit.valueOf(term.getBase().toString());
  456.                 if (!Fraction.ONE.equals(term.getExponent())) {
  457.                     u = u.power(null, term.getExponent());
  458.                 }
  459.                 u = u.scale(null, term.getScale());
  460.                 unit = unit.multiply(null, u);
  461.             } catch (IllegalArgumentException iae) {
  462.                 throw new OrekitException(OrekitMessages.UNKNOWN_UNIT, term.getBase());
  463.             }
  464.         }

  465.         // give final name to unit
  466.         return unit.alias(unitSpecification);

  467.     }

  468.     /** Check if the instance represents the same unit as another instance.
  469.      * <p>
  470.      * The name is not considered so aliases are considered equal.
  471.      * </p>
  472.      * @param unit other unit
  473.      * @return true if the instance and the other unit refer to the same unit
  474.      */
  475.     public boolean equals(final Object unit) {

  476.         if (unit == this) {
  477.             // first fast check
  478.             return true;
  479.         }

  480.         if (unit instanceof Unit) {
  481.             final Unit u = (Unit) unit;
  482.             return Precision.equals(scale, u.scale, 1) &&
  483.                    mass.equals(u.mass) && length.equals(u.length) && time.equals(u.time) &&
  484.                    current.equals(u.current) && angle.equals(u.angle);
  485.         }

  486.         return false;

  487.     }

  488.     /** Get a hashcode for this unit.
  489.      * @return hashcode
  490.      */
  491.     public int hashCode() {
  492.         return 0x67e7 ^
  493.                (Double.hashCode(scale) << 12) ^
  494.                (mass.hashCode()        << 10) ^
  495.                (length.hashCode()      <<  8) ^
  496.                (time.hashCode()        <<  6) ^
  497.                (current.hashCode()     <<  4) ^
  498.                (angle.hashCode()       <<  2);
  499.     }

  500.     /** {@inheritDoc} */
  501.     @Override
  502.     public String toString() {
  503.         return getName();
  504.     }

  505. }