javax.measure.converter.UnitConverter Java Examples

The following examples show how to use javax.measure.converter.UnitConverter. 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: Unit.java    From microMathematics with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns a converter of numeric values from this unit to another unit.
 *
 * @param  that the unit to which to convert the numeric values.
 * @return the converter from this unit to <code>that</code> unit.
 * @throws ConversionException if the conveter cannot be constructed
 *         (e.g. <code>!this.isCompatible(that)</code>).
 */
public final UnitConverter getConverterTo(Unit<?> that)
        throws ConversionException {
    if (this.equals(that))
        return UnitConverter.IDENTITY;
    Unit<?> thisSystemUnit = this.getStandardUnit();
    Unit<?> thatSystemUnit = that.getStandardUnit();
    if (thisSystemUnit.equals(thatSystemUnit))
        return that.toStandardUnit().inverse().concatenate(
                this.toStandardUnit());
    // Use dimensional transforms.
    if (!thisSystemUnit.getDimension()
            .equals(thatSystemUnit.getDimension()))
        throw new ConversionException(this + " is not compatible with "
                + that);
    // Transform between SystemUnit and BaseUnits is Identity. 
    UnitConverter thisTransform = this.toStandardUnit().concatenate(
            transformOf(this.getBaseUnits()));
    UnitConverter thatTransform = that.toStandardUnit().concatenate(
            transformOf(that.getBaseUnits()));
    return thatTransform.inverse().concatenate(thisTransform);
}
 
Example #2
Source File: Unit.java    From microMathematics with GNU General Public License v3.0 6 votes vote down vote up
private static UnitConverter transformOf(Unit<?> baseUnits) {
    if (baseUnits instanceof BaseUnit)
        return Dimension.getModel().getTransform((BaseUnit<?>) baseUnits);
    // Product of units.
    ProductUnit<?> productUnit = (ProductUnit<?>) baseUnits;
    UnitConverter converter = UnitConverter.IDENTITY;
    for (int i = 0; i < productUnit.getUnitCount(); i++) {
        Unit<?> unit = productUnit.getUnit(i);
        UnitConverter cvtr = transformOf(unit);
        if (!cvtr.isLinear())
            throw new ConversionException(baseUnits
                    + " is non-linear, cannot convert");
        if (productUnit.getUnitRoot(i) != 1)
            throw new ConversionException(productUnit
                    + " holds a base unit with fractional exponent");
        int pow = productUnit.getUnitPow(i);
        if (pow < 0) { // Negative power.
            pow = -pow;
            cvtr = cvtr.inverse();
        }
        for (int j = 0; j < pow; j++) {
            converter = converter.concatenate(cvtr);
        }
    }
    return converter;
}
 
Example #3
Source File: ProductUnit.java    From microMathematics with GNU General Public License v3.0 6 votes vote down vote up
@Override
public UnitConverter toStandardUnit() {
    if (hasOnlyStandardUnit())
        return UnitConverter.IDENTITY;
    UnitConverter converter = UnitConverter.IDENTITY;
    for (int i = 0; i < _elements.length; i++) {
        UnitConverter cvtr = _elements[i]._unit.toStandardUnit();
        if (!cvtr.isLinear())
            throw new ConversionException(_elements[i]._unit
                    + " is non-linear, cannot convert");
        if (_elements[i]._root != 1)
            throw new ConversionException(_elements[i]._unit
                    + " holds a base unit with fractional exponent");
        int pow = _elements[i]._pow;
        if (pow < 0) { // Negative power.
            pow = -pow;
            cvtr = cvtr.inverse();
        }
        for (int j = 0; j < pow; j++) {
            converter = converter.concatenate(cvtr);
        }
    }
    return converter;
}
 
Example #4
Source File: CategoryMapperUtil.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static Unit<?> getMostGeneralUnit(List<Unit<?>> candidateUnits) {
  candidateUnits.sort(
      (o1, o2) -> {
        UnitConverter converterTo = o1.inverse().getConverterTo(o2.inverse());
        if (converterTo.convert(1) > 1) {
          return -1;
        } else {
          return 1;
        }
      });

  return candidateUnits.isEmpty() ? null : candidateUnits.get(0);
}
 
Example #5
Source File: Unit.java    From microMathematics with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns the unit derived from this unit using the specified converter.
 * The converter does not need to be linear. For example:[code]
 * Unit<Dimensionless> DECIBEL = Unit.ONE.transform(
 *     new LogConverter(10).inverse().concatenate(
 *           new RationalConverter(1, 10)));[/code]
 *
 * @param operation the converter from the transformed unit to this unit.
 * @return the unit after the specified transformation.
 */
public final Unit<Q> transform(UnitConverter operation) {
    if (this instanceof TransformedUnit) {
        TransformedUnit<Q> tf = (TransformedUnit<Q>) this;
        Unit<Q> parent = tf.getParentUnit();
        UnitConverter toParent = tf.toParentUnit().concatenate(operation);
        if (toParent == UnitConverter.IDENTITY)
            return parent;
        return new TransformedUnit<>(parent, toParent);
    }
    if (operation == UnitConverter.IDENTITY) 
        return this;
    return new TransformedUnit<>(this, operation);
}
 
Example #6
Source File: WorldProjection.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public void createUnitTransformations(final UnitConverter unitConverter) {
	otherUnitToMeter = coord -> {
		coord.x = unitConverter.convert(coord.x);
		coord.y = unitConverter.convert(coord.y);
		coord.z = unitConverter.convert(coord.z);
	};
	meterToOtherUnit = coord -> {
		coord.x = unitConverter.inverse().convert(coord.x);
		coord.y = unitConverter.inverse().convert(coord.y);
		coord.z = unitConverter.inverse().convert(coord.z);
	};
}
 
Example #7
Source File: VectorMeasure.java    From microMathematics with GNU General Public License v3.0 5 votes vote down vote up
@Override
public MultiDimensional<Q> to(Unit<Q> unit) {
    if ((unit == _unit) || (unit.equals(_unit)))
        return this;
    UnitConverter cvtr = _unit.getConverterTo(unit);
    double[] newValues = new double[_components.length];
    for (int i=0; i < _components.length; i++) {
        newValues[i] = cvtr.convert(_components[i]);
    }
    return new MultiDimensional<>(newValues, unit);
}
 
Example #8
Source File: VectorMeasure.java    From microMathematics with GNU General Public License v3.0 5 votes vote down vote up
@Override
public ThreeDimensional<Q> to(Unit<Q> unit) {
    if ((unit == _unit) || (unit.equals(_unit)))
        return this;
    UnitConverter cvtr = _unit.getConverterTo(unit);
    return new ThreeDimensional<>(cvtr.convert(_x), cvtr.convert(_y), cvtr.convert(_z), unit);
}
 
Example #9
Source File: VectorMeasure.java    From microMathematics with GNU General Public License v3.0 5 votes vote down vote up
@Override
public TwoDimensional<Q> to(Unit<Q> unit) {
    if ((unit == _unit) || (unit.equals(_unit)))
        return this;
    UnitConverter cvtr = _unit.getConverterTo(unit);
    return new TwoDimensional<>(cvtr.convert(_x), cvtr.convert(_y), unit);
}
 
Example #10
Source File: TransformedUnit.java    From microMathematics with GNU General Public License v3.0 4 votes vote down vote up
public UnitConverter toStandardUnit() {
    return _parentUnit.toStandardUnit().concatenate(_toParentUnit);
}
 
Example #11
Source File: NumericAlgorithmGenerator.java    From molgenis with GNU Lesser General Public License v3.0 4 votes vote down vote up
String generateUnitConversionAlgorithm(Attribute targetAttribute, Attribute sourceAttribute) {
  String algorithm = null;

  Unit<? extends Quantity> targetUnit = unitResolver.resolveUnit(targetAttribute);

  Unit<? extends Quantity> sourceUnit = unitResolver.resolveUnit(sourceAttribute);

  if (sourceUnit != null) {
    if (targetUnit != null && !sourceUnit.equals(targetUnit)) {
      // if units are convertible, create convert algorithm
      UnitConverter unitConverter;
      try {
        unitConverter = sourceUnit.getConverterTo(targetUnit);
      } catch (ConversionException e) {
        unitConverter = null;
        // algorithm sets source unit and assigns source value to target
        algorithm =
            String.format(
                "$('%s').unit('%s').value();", sourceAttribute.getName(), sourceUnit.toString());
      }

      if (unitConverter != null) {
        // algorithm sets source unit and assigns value converted to target unit to target
        algorithm =
            String.format(
                "$('%s').unit('%s').toUnit('%s').value();",
                sourceAttribute.getName(), sourceUnit.toString(), targetUnit.toString());
      }
    } else {
      // algorithm sets source unit and assigns source value to target
      algorithm =
          String.format(
              "$('%s').unit('%s').value();", sourceAttribute.getName(), sourceUnit.toString());
    }
  }

  if (algorithm == null) {
    // algorithm assigns source value to target
    algorithm = String.format("$('%s').value();", sourceAttribute.getName());
  }

  return algorithm;
}
 
Example #12
Source File: WorldProjection.java    From gama with GNU General Public License v3.0 4 votes vote down vote up
public void updateUnit(final UnitConverter unitConverter) {
	if (unitConverter != null)
		createUnitTransformations(unitConverter);
}
 
Example #13
Source File: ProjectionFactory.java    From gama with GNU General Public License v3.0 4 votes vote down vote up
public UnitConverter getUnitConverter() {
	return unitConverter;
}
 
Example #14
Source File: BaseUnit.java    From microMathematics with GNU General Public License v3.0 4 votes vote down vote up
@Override
public UnitConverter toStandardUnit() {
    return UnitConverter.IDENTITY;
}
 
Example #15
Source File: UnitFormat.java    From microMathematics with GNU General Public License v3.0 4 votes vote down vote up
public String nameFor(Unit<?> unit) {
    // Searches label database.
    String label = _unitToName.get(unit);
    if (label != null)
        return label;
    if (unit instanceof BaseUnit)
        return ((BaseUnit<?>) unit).getSymbol();
    if (unit instanceof AlternateUnit)
        return ((AlternateUnit<?>) unit).getSymbol();
    if (unit instanceof TransformedUnit) {
        TransformedUnit<?> tfmUnit = (TransformedUnit<?>) unit;
        Unit<?> baseUnits = tfmUnit.getStandardUnit();
        UnitConverter cvtr = tfmUnit.toStandardUnit();
        StringBuffer result = new StringBuffer();
        String baseUnitName = baseUnits.toString();
        if ((baseUnitName.indexOf('ยท') >= 0) ||
            (baseUnitName.indexOf('*') >= 0) ||
            (baseUnitName.indexOf('/') >= 0)) {
            // We could use parentheses whenever baseUnits is an
            // instanceof ProductUnit, but most ProductUnits have aliases,
            // so we'd end up with a lot of unnecessary parentheses.
            result.append('(');
            result.append(baseUnitName);
            result.append(')');
        } else {
            result.append(baseUnitName);
        }
        if (cvtr instanceof AddConverter) {
            result.append('+');
            result.append(((AddConverter) cvtr).getOffset());
        } else if (cvtr instanceof RationalConverter) {
            long dividend = ((RationalConverter) cvtr).getDividend();
            if (dividend != 1) {
                result.append('*');
                result.append(dividend);
            }
            long divisor = ((RationalConverter) cvtr).getDivisor();
            if (divisor != 1) {
                result.append('/');
                result.append(divisor);
            }
        } else if (cvtr instanceof MultiplyConverter) {
            result.append('*');
            result.append(((MultiplyConverter) cvtr).getFactor());
        } else { // Other converters.
            return "[" + baseUnits + "?]";
        }
        return result.toString();
    }
    // Compound unit.
    if (unit instanceof CompoundUnit) {
        CompoundUnit<?> cpdUnit = (CompoundUnit<?>) unit;
        return nameFor(cpdUnit.getHigher()).toString() + ":"
                + nameFor(cpdUnit.getLower());
    }
    return null; // Product unit.
}
 
Example #16
Source File: AlternateUnit.java    From microMathematics with GNU General Public License v3.0 4 votes vote down vote up
@Override
public final UnitConverter toStandardUnit() {
    return UnitConverter.IDENTITY;
}
 
Example #17
Source File: CompoundUnit.java    From microMathematics with GNU General Public License v3.0 4 votes vote down vote up
@Override
public UnitConverter toStandardUnit() {
    return _low.toStandardUnit();
}
 
Example #18
Source File: Dimension.java    From microMathematics with GNU General Public License v3.0 4 votes vote down vote up
public UnitConverter getTransform(BaseUnit<?> unit) {
    if (unit.equals(SI.CANDELA)) return new RationalConverter(1, 683);
    return UnitConverter.IDENTITY;
}
 
Example #19
Source File: TransformedUnit.java    From microMathematics with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Creates a transformed unit from the specified parent unit.
 *
 * @param parentUnit the untransformed unit from which this unit is 
 *        derived.
 * @param  toParentUnit the converter to the parent units.
 * @throws IllegalArgumentException if <code>toParentUnit == 
 *         {@link UnitConverter#IDENTITY UnitConverter.IDENTITY}</code>
 */
TransformedUnit(Unit<Q> parentUnit, UnitConverter toParentUnit) {
    if (toParentUnit == UnitConverter.IDENTITY)
        throw new IllegalArgumentException("Identity not allowed");
    _parentUnit = parentUnit;
    _toParentUnit = toParentUnit;
}
 
Example #20
Source File: TransformedUnit.java    From microMathematics with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Returns the converter to the parent unit.
 *
 * @return the converter to the parent unit.
 */
public UnitConverter toParentUnit() {
    return _toParentUnit;
}
 
Example #21
Source File: Dimension.java    From microMathematics with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Returns the normalization transform of the specified base unit
 * ({@link UnitConverter#IDENTITY IDENTITY} if the base unit is 
 * not recognized).
 * 
 * @param unit the base unit for which the transform is returned.
 * @return the normalization transform.
 */
UnitConverter getTransform(BaseUnit<?> unit);
 
Example #22
Source File: Unit.java    From microMathematics with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Returns the converter from this unit to its system unit.
 * 
 * @return <code>this.getConverterTo(this.getSystemUnit())</code>
 */
public abstract UnitConverter toStandardUnit();