Java Code Examples for javax.measure.Unit#multiply()

The following examples show how to use javax.measure.Unit#multiply() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UnitFormat.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Applies a multiplication or division operation between the given units.
 *
 * @param  unit      the left operand, which is the unit parsed so far.
 * @param  term      the right operation, which is the newly parsed unit.
 * @param  position  the parse position to report if parsing fail.
 */
Unit<?> apply(final Unit<?> unit, final Unit<?> term, final int position) {
    switch (code) {
        case NOOP:     return term;
        case IMPLICIT:
        case MULTIPLY: return unit.multiply(term);
        case DIVIDE:   return unit.divide(term);
        case EXPONENT: {
            if (UnitDimension.isDimensionless(term.getDimension())) {
                final String symbol = term.getSymbol();
                if (symbol == null || symbol.isEmpty()) {
                    final double scale = Units.toStandardUnit(term);
                    final int power = (int) scale;
                    if (power == scale) {
                        return unit.pow(power);
                    }
                }
            }
            throw new ParserException(Errors.format(Errors.Keys.NotAnInteger_1, term), symbols, position);
        }
        default: throw new AssertionError(code);
    }
}
 
Example 2
Source File: UCUMFormatParser.java    From uom-systems with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
final public Unit Term() throws TokenException {
    Unit result = ONE;
    Unit temp = ONE;
    result = Component();
    label_1:
    while (true) {
        switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
            case DOT:
            case SOLIDUS:
                break;
            default:
                jj_la1[0] = jj_gen;
                break label_1;
        }
        switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
            case DOT:
                jj_consume_token(DOT);
                temp = Component();
                result = result.multiply(temp);
                break;
            case SOLIDUS:
                jj_consume_token(SOLIDUS);
                temp = Component();
                result = result.divide(temp);
                break;
            default:
                jj_la1[1] = jj_gen;
                jj_consume_token(-1);
                throw new TokenException();
        }
    }
    {
        return result;
    }
}
 
Example 3
Source File: UnitFormatParser.java    From uom-systems with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
final public Unit AddExpr() throws TokenException {
    Unit result = ONE;
    Number n1 = null;
    Token sign1 = null;
    Number n2 = null;
    Token sign2 = null;
    if (jj_2_1(2147483647)) {
        n1 = NumberExpr();
        sign1 = Sign();
    } else {
    }
    result = MulExpr();
    switch ((nextTokenIndex == -1) ? jj_ntk() : nextTokenIndex) {
        case PLUS:
        case MINUS:
            sign2 = Sign();
            n2 = NumberExpr();
            break;
        default:
            laA[1] = genInt;
    }
    if (n1 != null) {
        if (sign1.image.equals("-")) {
            result = result.multiply(-1);
        }
        result = result.shift(n1.doubleValue());
    }
    if (n2 != null) {
        double offset = n2.doubleValue();
        if (sign2.image.equals("-")) {
            offset = -offset;
        }
        result = result.shift(offset);
    }
    {
        return result;
    }
}
 
Example 4
Source File: GeometryUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
public static Unit<Length> lookup(final String name) {
  final String lowerCaseName = name.toLowerCase();

  Unit<Length> unit = lookup(SI.class, lowerCaseName);
  if (unit != null) {
    return unit;
  }

  unit = lookup(NonSI.class, lowerCaseName);
  if (unit != null) {
    return unit;
  }

  if (lowerCaseName.endsWith("s")) {
    return lookup(lowerCaseName.substring(0, lowerCaseName.length() - 1));
  }
  if (lowerCaseName.startsWith("kilo") && (lowerCaseName.length() > 4)) {
    final Unit<Length> u = lookup(lowerCaseName.substring(4));
    if (u != null) {
      return u.multiply(1000);
    }
  }
  // if we get here, try some aliases
  if (lowerCaseName.equals("feet")) {
    return USCustomary.FOOT;
  }
  // if we get here, try some aliases
  if (lowerCaseName.equals("meter")) {
    return Units.METRE;
  }
  if (lowerCaseName.equals("unity")) {
    return (Unit) AbstractUnit.ONE;
  }
  return null;
}
 
Example 5
Source File: VariableWrapper.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the given unit symbol and set the {@link #epoch} if the parsed unit is a temporal unit.
 * This method is called by {@link #getUnit()}. This implementation delegates the work to the UCAR
 * library and converts the result to {@link Unit} and {@link java.time.Instant} objects.
 */
@Override
protected Unit<?> parseUnit(final String symbols) throws Exception {
    if (TIME_UNIT_PATTERN.matcher(symbols).matches()) {
        /*
         * UCAR library has two methods for getting epoch: getDate() and getDateOrigin().
         * The former adds to the origin the number that may appear before the unit, for example
         * "2 hours since 1970-01-01 00:00:00". If there is no such number, then the two methods
         * are equivalent. It is not clear that adding such number is the right thing to do.
         */
        final DateUnit temporal = new DateUnit(symbols);
        epoch = temporal.getDateOrigin().toInstant();
        return Units.SECOND.multiply(temporal.getTimeUnit().getValueInSeconds());
    } else {
        /*
         * For all other units, we get the base unit (meter, radian, Kelvin, etc.) and multiply by the scale factor.
         * We also need to take the offset in account for constructing the °C unit as a unit shifted from its Kelvin
         * base. The UCAR library does not provide method giving directly this information, so we infer it indirectly
         * by converting the 0 value.
         */
        final SimpleUnit ucar = SimpleUnit.factoryWithExceptions(symbols);
        if (ucar.isUnknownUnit()) {
            return Units.valueOf(symbols);
        }
        final String baseUnit = ucar.getUnitString();
        Unit<?> unit = Units.valueOf(baseUnit);
        final double scale  = ucar.getValue();
        final double offset = ucar.convertTo(0, SimpleUnit.factoryWithExceptions(baseUnit));
        unit = unit.shift(offset);
        if (!Double.isNaN(scale)) {
            unit = unit.multiply(scale);
        }
        return unit;
    }
}
 
Example 6
Source File: ConventionalUnitTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests operations on kilogram.
 * The management of SI prefixes need to make a special case for kilogram.
 *
 * @see <a href="https://issues.apache.org/jira/browse/SIS-382">SIS-382</a>
 * @see UnitFormatTest#testParseKilogram()
 */
@Test
public void testKilogram() {
    assertSame(Units.GRAM, Units.KILOGRAM.divide(1E+3));
    verify(Units.KILOGRAM, Units.KILOGRAM.divide(1E+6), "mg", 1E-6);

    Unit<?> unit = Units.KILOGRAM.divide(1E+9);
    assertEquals("µg", unit.getSymbol());
    unit = unit.divide(Units.METRE);
    assertEquals("µg∕m", unit.getSymbol());
    unit = unit.multiply(1E+3);
    assertEquals("mg∕m", unit.getSymbol());
}
 
Example 7
Source File: UCUMFormatParser.java    From uom-systems with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
final public Unit Component() throws TokenException {
    Unit result = (AbstractUnit) ONE;
    Token token = null;
    if (jj_2_1(2147483647)) {
        result = Annotatable();
        token = jj_consume_token(ANNOTATION);
        {
            return ((AbstractUnit)result).annotate(token.image.substring(1, token.image.length() - 1));
        }
    } else {
        switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
            case ATOM:
                result = Annotatable(); {
                return result;
            }
            case ANNOTATION:
                token = jj_consume_token(ANNOTATION); {
                return ((AbstractUnit)result).annotate(token.image.substring(1, token.image.length() - 1));
            }
            case FACTOR:
                token = jj_consume_token(FACTOR);
                long factor = Long.parseLong(token.image); {
                return result.multiply(factor);
            }
            case SOLIDUS:
                jj_consume_token(SOLIDUS);
                result = Component(); {
                return ONE.divide(result);
            }
            case 14:
                jj_consume_token(14);
                result = Term();
                jj_consume_token(15); {
                return result;
            }
            default:
                jj_la1[2] = jj_gen;
                jj_consume_token(-1);
                throw new TokenException();
        }
    }
}
 
Example 8
Source File: UnitFormatParser.java    From uom-systems with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
final public Unit MulExpr() throws TokenException {
    Unit result = ONE;
    Unit temp = ONE;
    result = ExponentExpr();
    label_2:
    while (true) {
        switch ((nextTokenIndex == -1) ? jj_ntk() : nextTokenIndex) {
            case ASTERISK:
            case MIDDLE_DOT:
            case SOLIDUS:
                break;
            default:
                laA[2] = genInt;
                break label_2;
        }
        switch ((nextTokenIndex == -1) ? jj_ntk() : nextTokenIndex) {
            case ASTERISK:
            case MIDDLE_DOT:
                switch ((nextTokenIndex == -1) ? jj_ntk() : nextTokenIndex) {
                    case ASTERISK:
                        consumeToken(ASTERISK);
                        break;
                    case MIDDLE_DOT:
                        consumeToken(MIDDLE_DOT);
                        break;
                    default:
                        laA[3] = genInt;
                        consumeToken(-1);
                        throw new TokenException();
                }
                temp = ExponentExpr();
                result = result.multiply(temp);
                break;
            case SOLIDUS:
                consumeToken(SOLIDUS);
                temp = ExponentExpr();
                result = result.divide(temp);
                break;
            default:
                laA[4] = genInt;
                consumeToken(-1);
                throw new TokenException();
        }
    }
    {
        return result;
    }
}
 
Example 9
Source File: UnitFormatParser.java    From uom-systems with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
final public Unit AtomicExpr() throws TokenException {
    Unit result = ONE;
    Number n = null;
    Token token = null;
    switch ((nextTokenIndex == -1) ? jj_ntk() : nextTokenIndex) {
        case INTEGER:
        case FLOATING_POINT:
            n = NumberExpr();
            if (n instanceof Integer) {
                {
                    return result.multiply(n.intValue());
                }
            } else {
                {
                    return result.multiply(n.doubleValue());
                }
            }
        case UNIT_IDENTIFIER:
            token = consumeToken(UNIT_IDENTIFIER);
            Unit unit = symbols.getUnit(token.image);
            if (unit == null) {
                Prefix prefix = symbols.getPrefix(token.image);
                if (prefix != null) {
                    String prefixSymbol = symbols.getSymbol(prefix);
                    unit = symbols.getUnit(token.image.substring(prefixSymbol.length()));
                    if (unit != null) {
                        {
                            return unit.transform(MultiplyConverter.ofPrefix(prefix));
                        }
                    }
                }
                {
                    throw new TokenException();
                }
            } else {
                {
                    return unit;
                }
            }
        case OPEN_PAREN:
            consumeToken(OPEN_PAREN);
            result = AddExpr();
            consumeToken(CLOSE_PAREN); {
            return result;
        }
        default:
            laA[10] = genInt;
            consumeToken(-1);
            throw new TokenException();
    }
}
 
Example 10
Source File: UnitFormat.java    From sis with Apache License 2.0 4 votes vote down vote up
/**
 * Parses the given text as an instance of {@code Unit}.
 * If the parse completes without reading the entire length of the text, an exception is thrown.
 *
 * <p>The parsing is lenient: symbols can be products or quotients of units like “m∕s”,
 * words like “meters per second”, or authority codes like {@code "urn:ogc:def:uom:EPSG::1026"}.
 * The product operator can be either {@code '.'} (ASCII) or {@code '⋅'} (Unicode) character.
 * Exponent after symbol can be decimal digits as in “m2” or a superscript as in “m²”.</p>
 *
 * <p>This method differs from {@link #parse(CharSequence, ParsePosition)} in the treatment of white spaces:
 * that method with a {@link ParsePosition} argument stops parsing at the first white space,
 * while this {@code parse(…)} method treats white spaces as multiplications.
 * The reason for this difference is that white space is normally not a valid multiplication symbol;
 * it could be followed by a text which is not part of the unit symbol.
 * But in the case of this {@code parse(CharSequence)} method, the whole {@code CharSequence} shall be a unit symbol.
 * In such case, white spaces are less ambiguous.</p>
 *
 * <p>The default implementation delegates to
 * <code>{@linkplain #parse(CharSequence, ParsePosition) parse}(symbols, new ParsePosition(0))</code>
 * and verifies that all non-white characters have been parsed.
 * Units separated by spaces are multiplied; for example "kg m**-2" is parsed as kg/m².</p>
 *
 * @param  symbols  the unit symbols or URI to parse.
 * @return the unit parsed from the specified symbols.
 * @throws ParserException if a problem occurred while parsing the given symbols.
 *
 * @see Units#valueOf(String)
 */
@Override
public Unit<?> parse(final CharSequence symbols) throws ParserException {
    final Position position = new Position();
    Unit<?> unit = parse(symbols, position);
    final int length = symbols.length();
    int unrecognized;
    while ((unrecognized = CharSequences.skipLeadingWhitespaces(symbols, position.getIndex(), length)) < length) {
        if (position.finished || !Character.isLetter(Character.codePointAt(symbols, unrecognized))) {
            throw new ParserException(Errors.format(Errors.Keys.UnexpectedCharactersAfter_2,
                    CharSequences.trimWhitespaces(symbols, 0, unrecognized),
                    CharSequences.trimWhitespaces(symbols, unrecognized, length)),
                    symbols, unrecognized);
        }
        position.setIndex(unrecognized);
        unit = unit.multiply(parse(symbols, position));
    }
    return unit;
}