javax.measure.unit.Unit Java Examples

The following examples show how to use javax.measure.unit.Unit. 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: VectorMeasure.java    From microMathematics with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns the <code>String</code> representation of this measurement
 * vector (for example <code>[2.3 m/s, 5.6 m/s]</code>).
 * 
 * @return the textual representation of the measurement vector.
 */
public String toString() {
    double[] values = getValue();
    Unit<Q> unit = getUnit();
    StringBuffer tmp = new StringBuffer();
    tmp.append('[');
    for (double v : values) {
        if (tmp.length() > 1) {
            tmp.append(", ");
        }
        if (unit instanceof CompoundUnit) {
            MeasureFormat.DEFAULT.formatCompound(v, unit, tmp, null);
        } else {
            tmp.append(v).append(" ").append(unit);
        }
    }
    tmp.append("] ");
    return tmp.toString();
}
 
Example #2
Source File: TermParser.java    From microMathematics with GNU General Public License v3.0 6 votes vote down vote up
public static Unit parseUnits(final String text)
{
    if (text == null || text.isEmpty())
    {
        return null;
    }
    try
    {
        // There are two different symbols μ: standard and from greek keyboard.
        // Replace keyboard symbol by the standard one:
        final String unitText = text.replace(/*from Greek Small Letter Mu*/ 'μ', /*to Micro sign*/ 'µ');
        final Measure conv = DecimalMeasure.valueOf("1" + UNIT_SEPARATOR + unitText);
        if (conv != null && conv.getUnit() != null)
        {
            return conv.getUnit();
        }
    }
    catch (Exception ex)
    {
        // nothing to do
    }
    return null;
}
 
Example #3
Source File: AbstractNexusValidator.java    From dawnsci with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Validates that the given field has units consistent with the given unit category.
 * 
 * @param fieldName field name
 * @param dataset field value, an {@link IDataset}
 * @param unitCategory expected unit category
 * @throws Exception if an unexpected exception occurs
 * @throws NexusValidationException if the field's units are not consistent with the given unit category
 */
protected void validateFieldUnits(final String fieldName, final IDataset dataset,
		final NexusUnitCategory unitCategory) throws NexusValidationException {
	List<? extends MetadataType> metadata;
	try {
		metadata = dataset.getMetadata(UnitMetadata.class);
	} catch (Exception e) {
		throw new NexusValidationException("Could not get unit metadata for field '" + fieldName + "'", e);
	}
	// TODO why does getMetadata return a list? Can I assume I'm only interested in the first element?
	if (metadata == null || metadata.isEmpty() || !metadata.get(0).getClass().equals(UnitMetadata.class)) {
		failValidation("No unit metadata for field '" + fieldName + "', expected " + unitCategory);
	}
	
	if (metadata.size() > 1) {
		failValidation("Multiple unit metadata items found for field '" + fieldName + "'");
	}
	
	Unit<?> unit = ((UnitMetadata) metadata.get(0)).getUnit();
	if (!unitCategory.isCompatible(unit)) {
		failValidation("Unit " + unit + " is not compatible with the unit category " + unitCategory);
	}
}
 
Example #4
Source File: DecimalMeasure.java    From microMathematics with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns the decimal measure for the specified textual representation.
 * This method first reads the <code>BigDecimal</code> value, then 
 * the unit if any (value and unit should be separated by white spaces).
 * 
 * @param csq the decimal measure representation (including unit if any).
 * @throws NumberFormatException if the specified character sequence is 
 *         not a valid representation of decimal measure.
 */
@SuppressWarnings("unchecked")
public static <Q extends Quantity> DecimalMeasure<Q> valueOf(CharSequence csq) {
    String str = csq.toString();
    int numberLength = str.length();
    int unitStartIndex = -1;
    for (int i=0; i < str.length(); i++) {
        if (Character.isWhitespace(str.charAt(i))) {
            for (int j=i+1; j < str.length(); j++) {
                if (!Character.isWhitespace(str.charAt(j))) {
                    unitStartIndex = j;
                    break;
                }
            }
            numberLength = i;
            break;
        }
    }
    BigDecimal decimal = new BigDecimal(str.substring(0, numberLength));
    Unit unit = Unit.ONE;
    if (unitStartIndex > 0) {
        unit = Unit.valueOf(str.substring(unitStartIndex));
    }
    return new DecimalMeasure<>(decimal, unit);
}
 
Example #5
Source File: MeasureFormat.java    From microMathematics with GNU General Public License v3.0 6 votes vote down vote up
@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo,
        FieldPosition pos) {
    Measure<?, ?> measure = (Measure<?, ?>) obj;
    Object value = measure.getValue();
    Unit<?> unit = measure.getUnit();
    if (value instanceof Number) {
        if (unit instanceof CompoundUnit)
            return formatCompound(((Number) value).doubleValue(), unit, toAppendTo, pos);
        _numberFormat.format(value, toAppendTo, pos);
    } else {
        toAppendTo.append(value);
    }
    if (!measure.getUnit().equals(Unit.ONE)) {
        toAppendTo.append(' ');
        _unitFormat.format(unit, toAppendTo, pos);
    }
    return toAppendTo;
}
 
Example #6
Source File: AlgorithmGeneratorServiceImpl.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
String convertUnitForTemplateAlgorithm(
    String algorithm, Attribute targetAttribute, Set<Attribute> sourceAttributes) {
  Unit<? extends Quantity> targetUnit = unitResolver.resolveUnit(targetAttribute);

  for (Attribute sourceAttribute : sourceAttributes) {
    Unit<? extends Quantity> sourceUnit = unitResolver.resolveUnit(sourceAttribute);

    String convertUnit = magmaUnitConverter.convertUnit(targetUnit, sourceUnit);

    if (StringUtils.isNotBlank(convertUnit)) {
      String attrMagamSyntax = format("$('%s')", sourceAttribute.getName());
      String unitConvertedMagamSyntax =
          convertUnit.startsWith(".")
              ? attrMagamSyntax + convertUnit
              : attrMagamSyntax + "." + convertUnit;
      algorithm = StringUtils.replace(algorithm, attrMagamSyntax, unitConvertedMagamSyntax);
    }
  }

  return algorithm;
}
 
Example #7
Source File: MeasureFormat.java    From microMathematics with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static Measure measureOf(Number value, Unit unit) {
    if (value instanceof Double) {
        return Measure.valueOf(value.doubleValue(), unit);
    } else if (value instanceof Long) {
        return Measure.valueOf(value.longValue(), unit);
    } else if (value instanceof Float) {
        return Measure.valueOf(value.floatValue(), unit);
    } else if (value instanceof Integer) {
        return Measure.valueOf(value.intValue(), unit);
    } else if (value instanceof BigDecimal) {
        return DecimalMeasure.valueOf((BigDecimal) value, unit);
    } else {
        return Measure.valueOf(value.doubleValue(), unit);
    }
}
 
Example #8
Source File: Intervals.java    From microMathematics with GNU General Public License v3.0 6 votes vote down vote up
/*********************************************************
 * FormulaTermInterval-specific methods
 *********************************************************/

private Pair<Unit, Integer> compareUnits(TermField[] terms)
{
    Unit unit = terms[0].getParser().getUnit();
    int compatibleNumber = 0;
    for (TermField t : terms)
    {
        final Unit tp = t.getParser().getUnit();
        if (unit != null && tp != null && unit.isCompatible(tp))
        {
            compatibleNumber++;
        }
        if (unit == null)
        {
            unit = tp;
        }
    }
    return new Pair<>(unit == null ? null : unit.getStandardUnit(), compatibleNumber);
}
 
Example #9
Source File: UnitResolverImplTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void resolveUnitLabelNoUnitDescriptionWithUnit_directUnitMatchRaw_kgm2() {
  Attribute attr =
      attrMetaFactory
          .create()
          .setName("attr")
          .setLabel("label")
          .setDescription("area density (kg/m2)");
  Unit<? extends Quantity> unit = unitResolverImpl.resolveUnit(attr);
  assertEquals(valueOf("kg/m²"), unit);
}
 
Example #10
Source File: VectorMeasure.java    From microMathematics with GNU General Public License v3.0 5 votes vote down vote up
@Override
public double doubleValue(Unit<Q> unit) {
    double norm = Math.sqrt(_x * _x + _y * _y); 
    if ((unit == _unit) || (unit.equals(_unit)))
        return norm;
    return _unit.getConverterTo(unit).convert(norm);            
}
 
Example #11
Source File: ProjectionFactory.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
void computeTargetCRS(final IScope scope, final CoordinateReferenceSystem crs, final double longitude,
		final double latitude) {
	// If we already know in which CRS we project the data in GAMA, no need to recompute it. This information is
	// normally wiped when an experiment is disposed
	if (targetCRS != null) { return; }
	try {
		if (!GamaPreferences.External.LIB_TARGETED.getValue()) {
			targetCRS = computeDefaultCRS(scope, GamaPreferences.External.LIB_TARGET_CRS.getValue(), true);
		} else {
			if (crs != null && crs instanceof DefaultProjectedCRS) { // Temporary fix of issue 766... a better solution
				final CartesianCS ccs = ((DefaultProjectedCRS) crs).getCoordinateSystem();
				final Unit<?> unitX = ccs.getAxis(0).getUnit();
				if (unitX != null && !unitX.equals(SI.METER)) {
					unitConverter = unitX.getConverterTo(SI.METER);
				}
				targetCRS = crs;
			} else {
				final int index = (int) (0.5 + (longitude + 186.0) / 6);
				final boolean north = latitude > 0;
				final String newCode = EPSGPrefix + (32600 + index + (north ? 0 : 100));
				targetCRS = getCRS(scope, newCode);
			}
		}
	} catch (final GamaRuntimeException e) {
		e.addContext(
				"The cause could be that you try to re-project already projected data (see Gama > Preferences... > External for turning the option to true)");
		throw e;
	}
}
 
Example #12
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 #13
Source File: UnitResolverImplTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void resolveUnitLabelWithUnit_unitOntologyMatch() {
  Attribute attr =
      attrMetaFactory.create().setName("attr").setLabel("weight (kilogram)").setDescription(null);
  Unit<? extends Quantity> unit = unitResolverImpl.resolveUnit(attr);
  assertEquals(valueOf("kg"), unit);
}
 
Example #14
Source File: CalculatedValue.java    From microMathematics with GNU General Public License v3.0 5 votes vote down vote up
public ValueType multiply(CalculatedValue f, CalculatedValue g)
{
    if (unitExists(f, g))
    {
        if (f.unit == null)
        {
            unit = g.unit;
        }
        else if (g.unit == null)
        {
            unit = f.unit;
        }
        else
        {
            unit = f.unit.times(g.unit);
            if (unit != null && unit.isCompatible(Unit.ONE))
            {
                unit = null;
            }
        }
    }
    else
    {
        unit = null;
    }
    if (f.isComplex() || g.isComplex())
    {
        return setComplexValue(f.real * g.real - f.imaginary * g.imaginary, f.real * g.imaginary + f.imaginary
                * g.real);
    }
    else
    {
        return setValue(f.real * g.real);
    }
}
 
Example #15
Source File: CalculatedValue.java    From microMathematics with GNU General Public License v3.0 5 votes vote down vote up
public Unit powUnit(CalculatedValue f, CalculatedValue g)
{
    if (f.unit == null || g.unit != null || g.isComplex())
    {
        return null;
    }
    final int n = (int) g.real;
    if ((double) n != g.real)
    {
        return null;
    }
    return f.unit.pow(n);
}
 
Example #16
Source File: VectorMeasure.java    From microMathematics with GNU General Public License v3.0 5 votes vote down vote up
@Override
public double doubleValue(Unit<Q> unit) {
    double normSquare = _components[0] * _components[0];
    for (int i=1, n=_components.length; i < n;) {
        double d = _components[i++];
        normSquare += d * d;
    }
    if ((unit == _unit) || (unit.equals(_unit)))
        return Math.sqrt(normSquare);
    return _unit.getConverterTo(unit).convert(Math.sqrt(normSquare));            
}
 
Example #17
Source File: SeveralTimesConvertor.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
AmountWrapper getInternalAmount(String description) {
  Unit<?> unit = CategoryMapperUtil.findDurationUnit(description);
  if (unit != null && unit.isCompatible(STANDARD_PER_WEEK_UNIT)) {
    return AmountWrapper.create(
        Amount.rangeOf((double) 3, NonSI.DAY.inverse().getConverterTo(unit).convert(1) - 1, unit)
            .to(STANDARD_PER_WEEK_UNIT),
        false);
  }
  return null;
}
 
Example #18
Source File: UnitResolverImplTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void resolveUnitLabelNoUnitDescriptionWithUnit_directUnitMatch() {
  Attribute attr =
      attrMetaFactory.create().setName("attr").setLabel("label").setDescription("height (cm)");
  Unit<? extends Quantity> unit = unitResolverImpl.resolveUnit(attr);
  assertEquals(valueOf("cm"), unit);
}
 
Example #19
Source File: UnitResolverImplTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void resolveUnitLabelNoUnitDescriptionWithUnit_unitOntologyMatch_kgm2() {
  Attribute attr =
      attrMetaFactory
          .create()
          .setName("attr")
          .setLabel("label")
          .setDescription("area density (kg/m^2)");
  Unit<? extends Quantity> unit = unitResolverImpl.resolveUnit(attr);
  assertEquals(valueOf("kg/m²"), unit);
}
 
Example #20
Source File: UnitResolverImplTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void resolveUnitLabelNoUnitDescriptionWithUnit_directUnitMatch_kgm2_2() {
  Attribute attr =
      attrMetaFactory
          .create()
          .setName("attr")
          .setLabel("label")
          .setDescription("area density (kg/m²)");
  Unit<? extends Quantity> unit = unitResolverImpl.resolveUnit(attr);
  assertEquals(valueOf("kg/m²"), unit);
}
 
Example #21
Source File: UnitResolverImplTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void resolveUnitLabelNoUnitDescriptionNoUnit() {
  Attribute attr =
      attrMetaFactory.create().setName("attr").setLabel("weight").setDescription("weight");
  Unit<? extends Quantity> unit = unitResolverImpl.resolveUnit(attr);
  assertNull(unit);
}
 
Example #22
Source File: UnitResolverImplTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void resolveUnitLabelNoUnit() {
  Attribute attr =
      attrMetaFactory.create().setName("attr").setLabel("weight").setDescription(null);
  Unit<? extends Quantity> unit = unitResolverImpl.resolveUnit(attr);
  assertNull(unit);
}
 
Example #23
Source File: MeasureFormat.java    From microMathematics with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Object parseCompound(Number highValue, String source,
        ParsePosition pos) throws ParseException {
    Unit high = _unitFormat.parseSingleUnit(source, pos);
    int i = pos.getIndex();
    if (i >= source.length()
            || Character.isWhitespace(source.charAt(i)))
        return measureOf(highValue, high);
    Measure lowMeasure = (Measure) parseObject(source, pos);
    Unit unit = lowMeasure.getUnit();
    long l = lowMeasure.longValue(unit)
            + (long) high.getConverterTo(unit).convert(
                    highValue.longValue());
    return Measure.valueOf(l, unit);
}
 
Example #24
Source File: CategoryMapperTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testGetMostGeneralUnit() {
  List<Unit<?>> units = new ArrayList<>();

  units.add(NonSI.DAY.inverse());
  units.add(NonSI.YEAR.inverse());
  units.add(NonSI.MONTH.inverse());

  Unit<?> unit = CategoryMapperUtil.getMostGeneralUnit(units);
  assertEquals(YEAR.inverse().toString(), unit.toString());
}
 
Example #25
Source File: MeasureFormat.java    From microMathematics with GNU General Public License v3.0 5 votes vote down vote up
StringBuffer formatCompound(double value, Unit<?> unit,
        StringBuffer toAppendTo, FieldPosition pos) {
    if (!(unit instanceof CompoundUnit)) {
        toAppendTo.append((long) value);
        return _unitFormat.format(unit, toAppendTo, pos);
    }
    Unit<?> high = ((CompoundUnit<?>) unit).getHigher();
    Unit<?> low = ((CompoundUnit<?>) unit).getLower(); // The unit in which the value is stated.
    long highValue = (long) low.getConverterTo(high).convert(value);
    double lowValue = value
            - high.getConverterTo(low).convert(highValue);
    formatCompound(highValue, high, toAppendTo, pos);
    formatCompound(lowValue, low, toAppendTo, pos);
    return toAppendTo;
}
 
Example #26
Source File: UnitResolverImplTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void resolveUnitLabelNoUnitDescriptionWithUnit_unitOntologyMatch() {
  Attribute attr =
      attrMetaFactory
          .create()
          .setName("attr")
          .setLabel("label")
          .setDescription("height (centimeter)");
  Unit<? extends Quantity> unit = unitResolverImpl.resolveUnit(attr);
  assertEquals(valueOf("cm"), unit);
}
 
Example #27
Source File: UnitResolverImplTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testIsUnitEmpty() {
  Unit<?> unit = Unit.valueOf("");
  Unit<?> unit1 = Unit.valueOf("¹");
  Unit<?> unitKg = Unit.valueOf("kg");
  assertTrue(unitResolverImpl.isUnitEmpty(null));
  assertTrue(unitResolverImpl.isUnitEmpty(unit));
  assertTrue(unitResolverImpl.isUnitEmpty(unit1));
  assertFalse(unitResolverImpl.isUnitEmpty(unitKg));
}
 
Example #28
Source File: CategoryMapperUtil.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static Unit<?> findDurationUnit(String description) {
  Set<String> tokens = Sets.newHashSet(description.toLowerCase().split(NON_LETTER_REGEX));

  List<Unit<?>> candidateUnits = new ArrayList<>();

  for (Unit<?> unit : DURATION_UNITS) {
    if (tokens.contains(unit.inverse().toString().toLowerCase())) {
      candidateUnits.add(unit);
    }
  }

  return getMostGeneralUnit(candidateUnits);
}
 
Example #29
Source File: CalculatedValue.java    From microMathematics with GNU General Public License v3.0 5 votes vote down vote up
public CalculatedValue(double real, Unit u)
{
    this.valueType = ValueType.REAL;
    this.real = real;
    this.imaginary = 0.0;
    unit = u;
}
 
Example #30
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);
}