1   /* Copyright 2002-2024 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  
19  import java.io.Serializable;
20  import java.util.List;
21  
22  import org.hipparchus.CalculusFieldElement;
23  import org.hipparchus.fraction.Fraction;
24  import org.hipparchus.util.FastMath;
25  import org.hipparchus.util.Precision;
26  import org.orekit.errors.OrekitException;
27  import org.orekit.errors.OrekitMessages;
28  
29  /** Basic handling of multiplicative units.
30   * <p>
31   * This class is by no means a complete handling of units. For complete
32   * support, look at libraries like {@code UOM}. This class handles only
33   * time, length, mass and current dimensions, as well as angles (which are
34   * dimensionless).
35   * </p>
36   * <p>
37   * Instances of this class are immutable.
38   * </p>
39   * @see <a href="https://github.com/netomi/uom">UOM</a>
40   * @author Luc Maisonobe
41   * @since 11.0
42   */
43  public class Unit implements Serializable {
44  
45      /** No unit. */
46      public static final Unit NONE = new Unit("n/a", 1.0, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO);
47  
48      /** Dimensionless unit. */
49      public static final Unit ONE = new Unit("1", 1.0, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO);
50  
51      /** Percentage unit. */
52      public static final Unit PERCENT = new Unit("%", 1.0e-2, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO);
53  
54      /** Second unit. */
55      public static final Unit SECOND = new Unit("s", 1.0, Fraction.ZERO, Fraction.ZERO, Fraction.ONE, Fraction.ZERO, Fraction.ZERO);
56  
57      /** Minute unit. */
58      public static final Unit MINUTE = SECOND.scale("min", 60.0);
59  
60      /** Hour unit. */
61      public static final Unit HOUR = MINUTE.scale("h", 60);
62  
63      /** Day unit. */
64      public static final Unit DAY = HOUR.scale("d", 24.0);
65  
66      /** Julian year unit.
67       * @see <a href="https://www.iau.org/publications/proceedings_rules/units/">SI Units at IAU</a>
68       */
69      public static final Unit YEAR = DAY.scale("a", 365.25);
70  
71      /** Hertz unit. */
72      public static final Unit HERTZ = SECOND.power("Hz", Fraction.MINUS_ONE);
73  
74      /** Metre unit. */
75      public static final Unit METRE = new Unit("m", 1.0, Fraction.ZERO, Fraction.ONE, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO);
76  
77      /** Kilometre unit. */
78      public static final Unit KILOMETRE = METRE.scale("km", 1000.0);
79  
80      /** Kilogram unit. */
81      public static final Unit KILOGRAM = new Unit("kg", 1.0, Fraction.ONE, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO);
82  
83      /** Gram unit. */
84      public static final Unit GRAM = KILOGRAM.scale("g", 1.0e-3);
85  
86      /** Ampere unit. */
87      public static final Unit AMPERE = new Unit("A", 1.0, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO, Fraction.ONE, Fraction.ZERO);
88  
89      /** Radian unit. */
90      public static final Unit RADIAN = new Unit("rad", 1.0, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO, Fraction.ONE);
91  
92      /** Degree unit. */
93      public static final Unit DEGREE = RADIAN.scale("°", FastMath.toRadians(1.0));
94  
95      /** Arc minute unit. */
96      public static final Unit ARC_MINUTE = DEGREE.scale("′", 1.0 / 60.0);
97  
98      /** Arc second unit. */
99      public static final Unit ARC_SECOND = ARC_MINUTE.scale("″", 1.0 / 60.0);
100 
101     /** Revolution unit. */
102     public static final Unit REVOLUTION = RADIAN.scale("rev", 2.0 * FastMath.PI);
103 
104     /** Newton unit. */
105     public static final Unit NEWTON = KILOGRAM.multiply(null, METRE).divide("N", SECOND.power(null, Fraction.TWO));
106 
107     /** Pascal unit. */
108     public static final Unit PASCAL = NEWTON.divide("Pa", METRE.power(null, Fraction.TWO));
109 
110     /** Bar unit. */
111     public static final Unit BAR = PASCAL.scale("bar", 100000.0);
112 
113     /** Joule unit. */
114     public static final Unit JOULE = NEWTON.multiply("J", METRE);
115 
116     /** Watt unit. */
117     public static final Unit WATT = JOULE.divide("W", SECOND);
118 
119     /** Coulomb unit. */
120     public static final Unit COULOMB = SECOND.multiply("C", AMPERE);
121 
122     /** Volt unit. */
123     public static final Unit VOLT = WATT.divide("V", AMPERE);
124 
125     /** Ohm unit. */
126     public static final Unit OHM = VOLT.divide("Ω", AMPERE);
127 
128     /** tesla unit. */
129     public static final Unit TESLA = VOLT.multiply(null, SECOND).divide("T", METRE.power(null, Fraction.TWO));
130 
131     /** Solar Flux Unit. */
132     public static final Unit SOLAR_FLUX_UNIT = WATT.divide(null, METRE.power(null, Fraction.TWO).multiply(null, HERTZ)).scale("SFU", 1.0e-22);
133 
134     /** Total Electron Content Unit. */
135     public static final Unit TOTAL_ELECTRON_CONTENT_UNIT = METRE.power(null, new Fraction(-2)).scale("TECU", 1.0e+16);
136 
137     /** Earth Radii used as Bstar unit in CCSDS OMM. */
138     public static final Unit EARTH_RADII = new Unit("ER", 1.0, Fraction.ZERO, Fraction.ZERO, Fraction.ZERO, Fraction.ONE, Fraction.ZERO);
139 
140     /** Serializable UID. */
141     private static final long serialVersionUID = 20210402L;
142 
143     /** Name name of the unit. */
144     private final String name;
145 
146     /** Scaling factor to SI units. */
147     private final double scale;
148 
149     /** Mass exponent. */
150     private final Fraction mass;
151 
152     /** Length exponent. */
153     private final Fraction length;
154 
155     /** Time exponent. */
156     private final Fraction time;
157 
158     /** Current exponent. */
159     private final Fraction current;
160 
161     /** Angle exponent. */
162     private final Fraction angle;
163 
164     /** Simple constructor.
165      * @param name name of the unit
166      * @param scale scaling factor to SI units
167      * @param mass mass exponent
168      * @param length length exponent
169      * @param time time exponent
170      * @param current current exponent
171      * @param angle angle exponent
172      */
173     public Unit(final String name, final double scale,
174                 final Fraction mass, final Fraction length,
175                 final Fraction time, final Fraction current,
176                 final Fraction angle) {
177         this.name    = name;
178         this.scale   = scale;
179         this.mass    = mass;
180         this.length  = length;
181         this.time    = time;
182         this.current = current;
183         this.angle   = angle;
184     }
185 
186     /** Get the name of the unit.
187      * @return name of the unit
188      */
189     public String getName() {
190         return name;
191     }
192 
193     /** Get the scaling factor to SI units.
194      * @return scaling factor to SI units
195      */
196     public double getScale() {
197         return scale;
198     }
199 
200     /** Get the mass exponent.
201      * @return mass exponent
202      */
203     public Fraction getMass() {
204         return mass;
205     }
206 
207     /** Get the length exponent.
208      * @return length exponent
209      */
210     public Fraction getLength() {
211         return length;
212     }
213 
214     /** Get the time exponent.
215      * @return time exponent
216      */
217     public Fraction getTime() {
218         return time;
219     }
220 
221     /** Get the current exponent.
222      * @return current exponent
223      */
224     public Fraction getCurrent() {
225         return current;
226     }
227 
228     /** Get the angle exponent.
229      * @return angle exponent
230      */
231     public Fraction getAngle() {
232         return angle;
233     }
234 
235     /** Check if a unit has the same dimension as another unit.
236      * @param other other unit to check against
237      * @return true if unit has the same dimension as the other unit
238      */
239     public boolean sameDimension(final Unit other) {
240         return time.equals(other.time) && length.equals(other.length)   &&
241                mass.equals(other.mass) && current.equals(other.current) &&
242                angle.equals(other.angle);
243     }
244 
245     /** Create the SI unit with same dimension.
246      * @return a new unit, with same dimension as instance and scaling factor set to 1.0
247      */
248     public Unit sameDimensionSI() {
249         final StringBuilder builder = new StringBuilder();
250         append(builder, KILOGRAM.name, mass);
251         append(builder, METRE.name,    length);
252         append(builder, SECOND.name,   time);
253         append(builder, AMPERE.name,   current);
254         append(builder, RADIAN.name,   angle);
255         if (builder.length() == 0) {
256             builder.append('1');
257         }
258         return new Unit(builder.toString(), 1.0, mass, length, time, current, angle);
259     }
260 
261     /** Ensure some units are compatible with reference units.
262      * @param description description of the units list (for error message generation)
263      * @param reference reference units
264      * @param units units to check
265      * @param allowScaleDifferences if true, unit with same dimension but different
266      * scale (like {@link #KILOMETRE} versus {@link #METRE}) are allowed, otherwise they will trigger an exception
267      * @exception OrekitException if units are not compatible (number of elements, dimensions or scaling)
268      */
269     public static void ensureCompatible(final String description, final List<Unit> reference,
270                                         final boolean allowScaleDifferences, final List<Unit> units) {
271         if (units.size() != reference.size()) {
272             throw new OrekitException(OrekitMessages.WRONG_NB_COMPONENTS,
273                                       description, reference.size(), units.size());
274         }
275         for (int i = 0; i < reference.size(); ++i) {
276             if (!reference.get(i).sameDimension(units.get(i))) {
277                 throw new OrekitException(OrekitMessages.INCOMPATIBLE_UNITS,
278                                           reference.get(i).getName(),
279                                           units.get(i).getName());
280             }
281             if (!(allowScaleDifferences ||
282                   Precision.equals(reference.get(i).getScale(), units.get(i).getScale(), 1))) {
283                 throw new OrekitException(OrekitMessages.INCOMPATIBLE_UNITS,
284                                           reference.get(i).getName(),
285                                           units.get(i).getName());
286             }
287         }
288     }
289 
290     /** Append a dimension contribution to a unit name.
291      * @param builder builder for unit name
292      * @param dim name of the dimension
293      * @param exp exponent of the dimension
294      */
295     private void append(final StringBuilder builder, final String dim, final Fraction exp) {
296         if (!exp.isZero()) {
297             if (builder.length() > 0) {
298                 builder.append('.');
299             }
300             builder.append(dim);
301             if (exp.getDenominator() == 1) {
302                 if (exp.getNumerator() != 1) {
303                     builder.append(Integer.toString(exp.getNumerator()).
304                                    replace('-', '⁻').
305                                    replace('0', '⁰').
306                                    replace('1', '¹').
307                                    replace('2', '²').
308                                    replace('3', '³').
309                                    replace('4', '⁴').
310                                    replace('5', '⁵').
311                                    replace('6', '⁶').
312                                    replace('7', '⁷').
313                                    replace('8', '⁸').
314                                    replace('9', '⁹'));
315                 }
316             } else {
317                 builder.
318                     append("^(").
319                     append(exp.getNumerator()).
320                     append('/').
321                     append(exp.getDenominator()).
322                     append(')');
323             }
324         }
325     }
326 
327     /** Create an alias for a unit.
328      * @param newName name of the new unit
329      * @return a new unit representing same unit as the instance but with a different name
330      */
331     public Unit alias(final String newName) {
332         return new Unit(newName, scale, mass, length, time, current, angle);
333     }
334 
335     /** Scale a unit.
336      * @param newName name of the new unit
337      * @param factor scaling factor
338      * @return a new unit representing scale times the instance
339      */
340     public Unit scale(final String newName, final double factor) {
341         return new Unit(newName, factor * scale, mass, length, time, current, angle);
342     }
343 
344     /** Create power of unit.
345      * @param newName name of the new unit
346      * @param exponent exponent to apply
347      * @return a new unit representing the power of the instance
348      */
349     public Unit power(final String newName, final Fraction exponent) {
350 
351         final int num = exponent.getNumerator();
352         final int den = exponent.getDenominator();
353         double s = (num == 1) ? scale : FastMath.pow(scale, num);
354         if (den > 1) {
355             if (den == 2) {
356                 s = FastMath.sqrt(s);
357             } else if (den == 3) {
358                 s = FastMath.cbrt(s);
359             } else {
360                 s = FastMath.pow(s, 1.0 / den);
361             }
362         }
363 
364         return new Unit(newName, s,
365                         mass.multiply(exponent), length.multiply(exponent),
366                         time.multiply(exponent), current.multiply(current),
367                         angle.multiply(exponent));
368     }
369 
370     /** Create root of unit.
371      * @param newName name of the new unit
372      * @return a new unit representing the square root of the instance
373      */
374     public Unit sqrt(final String newName) {
375         return new Unit(newName, FastMath.sqrt(scale),
376                         mass.divide(2), length.divide(2),
377                         time.divide(2), current.divide(2),
378                         angle.divide(2));
379     }
380 
381     /** Create product of units.
382      * @param newName name of the new unit
383      * @param other unit to multiply with
384      * @return a new unit representing the this times the other unit
385      */
386     public Unit multiply(final String newName, final Unit other) {
387         return new Unit(newName, scale * other.scale,
388                         mass.add(other.mass), length.add(other.length),
389                         time.add(other.time), current.add(other.current),
390                         angle.add(other.angle));
391     }
392 
393     /** Create quotient of units.
394      * @param newName name of the new unit
395      * @param other unit to divide with
396      * @return a new unit representing the this divided by the other unit
397      */
398     public Unit divide(final String newName, final Unit other) {
399         return new Unit(newName, scale / other.scale,
400                         mass.subtract(other.mass), length.subtract(other.length),
401                         time.subtract(other.time), current.subtract(other.current),
402                         angle.subtract(other.angle));
403     }
404 
405     /** Convert a value to SI units.
406      * @param value value instance unit
407      * @return value in SI units
408      */
409     public double toSI(final double value) {
410         return value * scale;
411     }
412 
413     /** Convert a value to SI units.
414      * @param value value instance unit
415      * @return value in SI units
416      */
417     public double toSI(final Double value) {
418         return value == null ? Double.NaN : value.doubleValue() * scale;
419     }
420 
421     /** Convert a value to SI units.
422      * @param <T> type of the field elements
423      * @param value value instance unit
424      * @return value in SI units
425      * @since 12.1
426      */
427     public <T extends CalculusFieldElement<T>> T toSI(final T value) {
428         return value.multiply(scale);
429     }
430 
431     /** Convert a value from SI units.
432      * @param value value SI unit
433      * @return value in instance units
434      */
435     public double fromSI(final double value) {
436         return value / scale;
437     }
438 
439     /** Convert a value from SI units.
440      * @param value value SI unit
441      * @return value in instance units
442      */
443     public double fromSI(final Double value) {
444         return value == null ? Double.NaN : value.doubleValue() / scale;
445     }
446 
447     /** Convert a value from SI units.
448      * @param <T> type of the field elements
449      * @param value value SI unit
450      * @return value in instance units
451      */
452     public <T extends CalculusFieldElement<T>> T fromSI(final T value) {
453         return value.divide(scale);
454     }
455 
456     /** Parse a unit.
457      * <p>
458      * The grammar for unit specification allows chains units multiplication and
459      * division, as well as putting powers on units.
460      * </p>
461      * <p>The symbols used for units are the SI units with some extensions.
462      * </p>
463      * <dl>
464      *   <dt>year</dt>
465      *   <dd>the accepted non-SI unit for Julian year is "a" but we also accept "yr"</dd>
466      *   <dt>day</dt>
467      *   <dd>the accepted non-SI unit for day is "d" but we also accept "day"</dd>
468      *   <dt>dimensionless</dt>
469      *   <dd>both "1" and "#" (U+0023, NUMBER SIGN) are accepted</dd>
470      *   <dt>mass</dt>
471      *   <dd>"g" is the standard symbol, despite the unit is "kg" (it is the only
472      *       unit that has a prefix in its name, so all multiples must be based on "g")</dd>
473      *   <dt>degrees</dt>
474      *   <dd>the base symbol for degrees is "°" (U+00B0, DEGREE SIGN), but we also accept
475      *       "◦" (U+25E6, WHITE BULLET) and "deg"</dd>
476      *   <dt>arcminute</dt>
477      *   <dd>The base symbol for arcminute is "′" (U+2032, PRIME) but we also accept "'" (U+0027, APOSTROPHE)</dd>
478      *   <dt>arcsecond</dt>
479      *   <dd>The base symbol for arcsecond is "″" (U+2033, DOUBLE PRIME) but we also accept
480      *   "''" (two occurrences of U+0027, APOSTROPHE), "\"" (U+0022, QUOTATION MARK) and "as"</dd>
481      * </dl>
482      * <p>
483      * All the SI prefix (from "y", yocto, to "Y", Yotta) are accepted, as well
484      * as integer prefixes. The standard symbol for micro 10⁻⁶ is "µ" (U+00B5, MICRO SIGN),
485      * but we also accept "μ" (U+03BC, GREEK SMALL LETTER MU). Beware that some combinations
486      * are forbidden, for example "Pa" is Pascal, not peta-years, and "as" is arcsecond for
487      * this parser, not atto-seconds, because many people in the space field use mas for
488      * milliarcseconds and µas for microarcseconds. Beware that prefixes are case-sensitive!
489      * Integer prefixes can be used to specify units like "30s", but only once at the beginning
490      * of the specification (i.e. "2rev/d²" is accepted, but "rev/(2d)²" is refused). Conforming
491      * with SI brochure "The International System of Units" (9th edition, 2019), each SI
492      * prefix is part of the unit and precedes the unit symbol without a separator
493      * (i.e. MHz is seen as one identifier).
494      * </p>
495      * <dl>
496      *   <dt>multiplication</dt>
497      *   <dd>can specified with either "*" (U+002A, ASTERISK), "×" (U+00D7, MULTIPLICATION SIGN),
498      *   "." (U+002E, FULL STOP) or "·" (U+00B7, MIDDLE DOT) as the operator</dd>
499      *   <dt>division</dt>
500      *   <dd>can be specified with either "/" (U+002F, SOLIDUS) or "⁄" (U+2044, FRACTION SLASH)
501      *   as the operator</dd>
502      *   <dt>powers</dt>
503      *   <dd>can be specified either by
504      *     <ul>
505      *       <li>prefixing with the unicode "√" (U+221A, SQUARE ROOT) character</li>
506      *       <li>postfixing with "**", "^" or implicitly using unicode superscripts</li>
507      *     </ul>
508      *   </dd>
509      * </dl>
510      * <p>
511      * Exponents can be specified in different ways:
512      * <ul>
513      *   <li>as an integer, as in "m^-2" or "m⁻²"</li>
514      *   <li>directly as unicode characters for the few fractions that unicode supports, as in "Ω^⅞"</li>
515      *   <li>as the special decimal value 0.5 which is used by CCSDS, as in "km**0.5"</li>
516      *   <li>as a pair of parentheses surrounding two integers separated by a solidus or fraction slash,
517      *   as in "Pa^(11/12)"</li>
518      * </ul>
519      * For integer exponents, the digits must be ASCII digits from the Basic Latin block from
520      * unicode if explicit exponent marker "**" or "^" is used, or using unicode superscript
521      * digits if implicit exponentiation (i.e. no markers at all) is used. Unicode superscripts
522      * are not allowed for fractional exponents because unicode does not provide a superscript solidus.
523      * Negative exponents can be used too.
524      * <p>
525      * These rules mean all the following (silly) examples are parsed properly:
526      * MHz, km/√d, kg.m.s⁻¹, µas^⅖/(h**(2)×m)³, km/√(kg.s), km**0.5, 2rev/d²
527      * </p>
528      * @param unitSpecification unit specification to parse
529      * @return parsed unit
530      */
531     public static Unit parse(final String unitSpecification) {
532 
533         // parse the specification
534         final List<PowerTerm> terms = Parser.buildTermsList(unitSpecification);
535 
536         if (terms == null) {
537             // special handling of "n/a"
538             return Unit.NONE;
539         }
540 
541         // build compound unit
542         Unit unit = Unit.ONE;
543         for (final PowerTerm term : terms) {
544             try {
545                 Unit u = PrefixedUnit.valueOf(term.getBase().toString());
546                 if (!Fraction.ONE.equals(term.getExponent())) {
547                     u = u.power(null, term.getExponent());
548                 }
549                 u = u.scale(null, term.getScale());
550                 unit = unit.multiply(null, u);
551             } catch (IllegalArgumentException iae) {
552                 throw new OrekitException(OrekitMessages.UNKNOWN_UNIT, term.getBase());
553             }
554         }
555 
556         // give final name to unit
557         return unit.alias(unitSpecification);
558 
559     }
560 
561     /** Check if the instance represents the same unit as another instance.
562      * <p>
563      * The name is not considered so aliases are considered equal.
564      * </p>
565      * @param unit other unit
566      * @return true if the instance and the other unit refer to the same unit
567      */
568     public boolean equals(final Object unit) {
569 
570         if (unit == this) {
571             // first fast check
572             return true;
573         }
574 
575         if (unit instanceof Unit) {
576             final Unit u = (Unit) unit;
577             return Precision.equals(scale, u.scale, 1) &&
578                    mass.equals(u.mass) && length.equals(u.length) && time.equals(u.time) &&
579                    current.equals(u.current) && angle.equals(u.angle);
580         }
581 
582         return false;
583 
584     }
585 
586     /** Get a hashcode for this unit.
587      * @return hashcode
588      */
589     public int hashCode() {
590         return 0x67e7 ^
591                (Double.hashCode(scale) << 12) ^
592                (mass.hashCode()        << 10) ^
593                (length.hashCode()      <<  8) ^
594                (time.hashCode()        <<  6) ^
595                (current.hashCode()     <<  4) ^
596                (angle.hashCode()       <<  2);
597     }
598 
599     /** {@inheritDoc} */
600     @Override
601     public String toString() {
602         return getName();
603     }
604 
605 }