Unit.java

  1. /* Copyright 2002-2022 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.     /** Serializable UID. */
  103.     private static final long serialVersionUID = 20210402L;

  104.     /** Name name of the unit. */
  105.     private final String name;

  106.     /** Scaling factor to SI units. */
  107.     private final double scale;

  108.     /** Mass exponent. */
  109.     private final Fraction mass;

  110.     /** Length exponent. */
  111.     private final Fraction length;

  112.     /** Time exponent. */
  113.     private final Fraction time;

  114.     /** Current exponent. */
  115.     private final Fraction current;

  116.     /** Angle exponent. */
  117.     private final Fraction angle;

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

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

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

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

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

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

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

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

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

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

  205.     /** Append a dimension contribution to a unit name.
  206.      * @param builder builder for unit name
  207.      * @param dim name of the dimension
  208.      * @param exp exponent of the dimension
  209.      */
  210.     private void append(final StringBuilder builder, final String dim, final Fraction exp) {
  211.         if (!exp.isZero()) {
  212.             if (builder.length() > 0) {
  213.                 builder.append('.');
  214.             }
  215.             builder.append(dim);
  216.             if (exp.getDenominator() == 1) {
  217.                 if (exp.getNumerator() != 1) {
  218.                     builder.append(Integer.toString(exp.getNumerator()).
  219.                                    replace('-', '⁻').
  220.                                    replace('0', '⁰').
  221.                                    replace('1', '¹').
  222.                                    replace('2', '²').
  223.                                    replace('3', '³').
  224.                                    replace('4', '⁴').
  225.                                    replace('5', '⁵').
  226.                                    replace('6', '⁶').
  227.                                    replace('7', '⁷').
  228.                                    replace('8', '⁸').
  229.                                    replace('9', '⁹'));
  230.                 }
  231.             } else {
  232.                 builder.
  233.                     append("^(").
  234.                     append(exp.getNumerator()).
  235.                     append('/').
  236.                     append(exp.getDenominator()).
  237.                     append(')');
  238.             }
  239.         }
  240.     }

  241.     /** Create an alias for a unit.
  242.      * @param newName name of the new unit
  243.      * @return a new unit representing same unit as the instance but with a different name
  244.      */
  245.     public Unit alias(final String newName) {
  246.         return new Unit(newName, scale, mass, length, time, current, angle);
  247.     }

  248.     /** Scale a unit.
  249.      * @param newName name of the new unit
  250.      * @param factor scaling factor
  251.      * @return a new unit representing scale times the instance
  252.      */
  253.     public Unit scale(final String newName, final double factor) {
  254.         return new Unit(newName, factor * scale, mass, length, time, current, angle);
  255.     }

  256.     /** Create power of unit.
  257.      * @param newName name of the new unit
  258.      * @param exponent exponent to apply
  259.      * @return a new unit representing the power of the instance
  260.      */
  261.     public Unit power(final String newName, final Fraction exponent) {

  262.         final int num = exponent.getNumerator();
  263.         final int den = exponent.getDenominator();
  264.         double s = (num == 1) ? scale : FastMath.pow(scale, num);
  265.         if (den > 1) {
  266.             if (den == 2) {
  267.                 s = FastMath.sqrt(s);
  268.             } else if (den == 3) {
  269.                 s = FastMath.cbrt(s);
  270.             } else {
  271.                 s = FastMath.pow(s, 1.0 / den);
  272.             }
  273.         }

  274.         return new Unit(newName, s,
  275.                         mass.multiply(exponent), length.multiply(exponent),
  276.                         time.multiply(exponent), current.multiply(current),
  277.                         angle.multiply(exponent));
  278.     }

  279.     /** Create root of unit.
  280.      * @param newName name of the new unit
  281.      * @return a new unit representing the square root of the instance
  282.      */
  283.     public Unit sqrt(final String newName) {
  284.         return new Unit(newName, FastMath.sqrt(scale),
  285.                         mass.divide(2), length.divide(2),
  286.                         time.divide(2), current.divide(2),
  287.                         angle.divide(2));
  288.     }

  289.     /** Create product of units.
  290.      * @param newName name of the new unit
  291.      * @param other unit to multiply with
  292.      * @return a new unit representing the this times the other unit
  293.      */
  294.     public Unit multiply(final String newName, final Unit other) {
  295.         return new Unit(newName, scale * other.scale,
  296.                         mass.add(other.mass), length.add(other.length),
  297.                         time.add(other.time), current.add(other.current),
  298.                         angle.add(other.angle));
  299.     }

  300.     /** Create quotient of units.
  301.      * @param newName name of the new unit
  302.      * @param other unit to divide with
  303.      * @return a new unit representing the this divided by the other unit
  304.      */
  305.     public Unit divide(final String newName, final Unit other) {
  306.         return new Unit(newName, scale / other.scale,
  307.                         mass.subtract(other.mass), length.subtract(other.length),
  308.                         time.subtract(other.time), current.subtract(other.current),
  309.                         angle.subtract(other.angle));
  310.     }

  311.     /** Convert a value to SI units.
  312.      * @param value value instance unit
  313.      * @return value in SI units
  314.      */
  315.     public double toSI(final double value) {
  316.         return value * scale;
  317.     }

  318.     /** Convert a value to SI units.
  319.      * @param value value instance unit
  320.      * @return value in SI units
  321.      */
  322.     public double toSI(final Double value) {
  323.         return value == null ? Double.NaN : value.doubleValue() * scale;
  324.     }

  325.     /** Convert a value from SI units.
  326.      * @param value value SI unit
  327.      * @return value in instance units
  328.      */
  329.     public double fromSI(final double value) {
  330.         return value / scale;
  331.     }

  332.     /** Convert a value from SI units.
  333.      * @param value value SI unit
  334.      * @return value in instance units
  335.      */
  336.     public double fromSI(final Double value) {
  337.         return value == null ? Double.NaN : value.doubleValue() / scale;
  338.     }

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

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

  415.         if (terms == null) {
  416.             // special handling of "n/a"
  417.             return Unit.NONE;
  418.         }

  419.         // build compound unit
  420.         Unit unit = Unit.ONE;
  421.         for (final PowerTerm term : terms) {
  422.             try {
  423.                 Unit u = PrefixedUnit.valueOf(term.getBase().toString());
  424.                 if (!Fraction.ONE.equals(term.getExponent())) {
  425.                     u = u.power(null, term.getExponent());
  426.                 }
  427.                 u = u.scale(null, term.getScale());
  428.                 unit = unit.multiply(null, u);
  429.             } catch (IllegalArgumentException iae) {
  430.                 throw new OrekitException(OrekitMessages.UNKNOWN_UNIT, term.getBase());
  431.             }
  432.         }

  433.         // give final name to unit
  434.         return unit.alias(unitSpecification);

  435.     }

  436.     /** Check if the instance represents the same unit as another instance.
  437.      * <p>
  438.      * The name is not considered so aliases are considered equal.
  439.      * </p>
  440.      * @param unit other unit
  441.      * @return true if the instance and the other unit refer to the same unit
  442.      */
  443.     public boolean equals(final Object unit) {

  444.         if (unit == this) {
  445.             // first fast check
  446.             return true;
  447.         }

  448.         if (unit instanceof Unit) {
  449.             final Unit u = (Unit) unit;
  450.             return Precision.equals(scale, u.scale, 1) &&
  451.                    mass.equals(u.mass) && length.equals(u.length) && time.equals(u.time) &&
  452.                    current.equals(u.current) && angle.equals(u.angle);
  453.         }

  454.         return false;

  455.     }

  456.     /** Get a hashcode for this unit.
  457.      * @return hashcode
  458.      */
  459.     public int hashCode() {
  460.         return 0x67e7 ^
  461.                (Double.hashCode(scale) << 12) ^
  462.                (mass.hashCode()        << 10) ^
  463.                (length.hashCode()      <<  8) ^
  464.                (time.hashCode()        <<  6) ^
  465.                (current.hashCode()     <<  4) ^
  466.                (angle.hashCode()       <<  2);
  467.     }

  468.     /** {@inheritDoc} */
  469.     @Override
  470.     public String toString() {
  471.         return getName();
  472.     }

  473. }