javax.measure.Unit Java Examples

The following examples show how to use javax.measure.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: UnitServicesTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests the default system of units.
 */
@Test
public void testDefaultSystemOfUnits() {
    final ServiceProvider provider = ServiceProvider.current();
    Set<? extends Unit<?>> units = provider.getSystemOfUnitsService().getSystemOfUnits().getUnits();
    assertTrue("METRE",                units.contains(Units.METRE));
    assertTrue("KILOMETRE",            units.contains(Units.KILOMETRE));
    assertTrue("CUBIC_METRE",          units.contains(Units.CUBIC_METRE));
    assertTrue("METRES_PER_SECOND",    units.contains(Units.METRES_PER_SECOND));
    assertTrue("KILOMETRES_PER_HOUR",  units.contains(Units.KILOMETRES_PER_HOUR));
    assertTrue("NAUTICAL_MILE",        units.contains(Units.NAUTICAL_MILE));
    assertTrue("STATUTE_MILE",         units.contains(Units.STATUTE_MILE));
    assertTrue("DEGREE",               units.contains(Units.DEGREE));
    assertTrue("RADIAN",               units.contains(Units.RADIAN));
    assertTrue("GRAD",                 units.contains(Units.GRAD));
}
 
Example #2
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 #3
Source File: UnitRegistry.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a read only view over the units explicitly defined by this system.
 * This include the base and derived units which are assigned a special name and symbol.
 * This set does not include new units created by arithmetic or other operations.
 */
@Override
@SuppressWarnings("ReturnOfCollectionOrArrayField")
public Set<Unit<?>> getUnits() {
    if (Units.initialized) {                    // Force Units class initialization.
        synchronized (this) {
            if (units == null) {
                units = new HashSet<>();
                for (final Object value : HARD_CODED.values()) {
                    if (value instanceof AbstractUnit<?>) {
                        final AbstractUnit<?> unit = (AbstractUnit<?>) value;
                        if ((unit.scope & includes) != 0) {
                            units.add(unit);
                        }
                    }
                }
                units = Collections.unmodifiableSet(units);
            }
        }
    }
    return units;
}
 
Example #4
Source File: QuantityType.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Convert this QuantityType to a new {@link QuantityType} using the given target unit.
 *
 * @param targetUnit the unit to which this {@link QuantityType} will be converted to.
 * @return the new {@link QuantityType} in the given {@link Unit} or {@code null} in case of a
 */
@SuppressWarnings("unchecked")
public @Nullable QuantityType<T> toUnit(Unit<?> targetUnit) {
    if (!targetUnit.equals(getUnit())) {
        try {
            UnitConverter uc = getUnit().getConverterToAny(targetUnit);
            Quantity<?> result = Quantities.getQuantity(uc.convert(quantity.getValue()), targetUnit);

            return new QuantityType<T>(result.getValue(), (Unit<T>) targetUnit);
        } catch (UnconvertibleException | IncommensurableException e) {
            logger.debug("Unable to convert unit from {} to {}", getUnit(), targetUnit);
            return null;
        }
    }
    return this;
}
 
Example #5
Source File: StandardDefinitions.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an ellipsoid from hard-coded values for the given code.
 *
 * @param  code  the EPSG code.
 * @return the ellipsoid for the given code.
 */
static Ellipsoid createEllipsoid(final short code) {
    String  name;          // No default value
    String  alias          = null;
    double  semiMajorAxis; // No default value
    double  other;         // No default value
    boolean ivfDefinitive  = true;
    Unit<Length> unit      = Units.METRE;
    switch (code) {
        case 7030: name  = "WGS 84";                   alias = "WGS84";        semiMajorAxis = 6378137.0; other = 298.257223563; break;
        case 7043: name  = "WGS 72";                   alias = "NWL 10D";      semiMajorAxis = 6378135.0; other = 298.26;        break;
        case 7019: alias = "International 1979";       name  = "GRS 1980";     semiMajorAxis = 6378137.0; other = 298.257222101; break;
        case 7022: name  = "International 1924";       alias = "Hayford 1909"; semiMajorAxis = 6378388.0; other = 297.0;         break;
        case 7008: name  = "Clarke 1866";              ivfDefinitive = false;  semiMajorAxis = 6378206.4; other = 6356583.8;     break;
        case 7048: name  = "GRS 1980 Authalic Sphere"; ivfDefinitive = false;  semiMajorAxis = other = AUTHALIC_RADIUS;          break;
        default:   throw new AssertionError(code);
    }
    final Map<String,Object> map = properties(code, name, alias, false);
    if (ivfDefinitive) {
        return DefaultEllipsoid.createFlattenedSphere(map, semiMajorAxis, other, unit);
    } else {
        return DefaultEllipsoid.createEllipsoid(map, semiMajorAxis, other, unit);
    }
}
 
Example #6
Source File: UCUMFormat.java    From uom-systems with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@SuppressWarnings({ "rawtypes" })
public Appendable format(final Unit<?> unknownUnit, Appendable appendable) throws IOException {
    
    if (!(unknownUnit instanceof ComparableUnit)) {
        throw new UnsupportedOperationException("The UCUM format supports only known units (Comparable units)");
    }
    
    final ComparableUnit unit = (ComparableUnit) unknownUnit;
    final UCUMFormatHelper formatHelper = UCUMFormatHelper.of(this, unit);
    final CharSequence symbol = formatHelper.findSymbolFor(symbolProviders, unit);
    
    if (symbol == null) {
        throw new IllegalArgumentException("Cannot format the given Object as UCUM units (unsupported unit " + unit.getClass().getName() + "). "
                + "Custom units types should override the toString() method as the default implementation uses the UCUM format.");
    }

    appendable.append(symbol);
    formatHelper.appendAnnotation(symbol, appendable);

    return appendable;
}
 
Example #7
Source File: UCUMFormat.java    From uom-systems with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private CharSequence symbolForKilogram(ComparableUnit unit) throws IOException {
    
    final Unit<?> systemUnit = unit.getSystemUnit();
    if (!systemUnit.equals(SI.KILOGRAM)) {
        return null;
    }

    final UnitConverter converter = 
            UCUMFormatHelper.toKnownPrefixConverterIfPossible(
                    unit.getConverterTo(systemUnit)
                    .concatenate(MultiplyConverter.ofPrefix(MetricPrefix.KILO)));
    
    final StringBuilder sb = new StringBuilder();
    final boolean printSeparator = true;
    
    // A special case because KILOGRAM is a BaseUnit instead of
    // a transformed unit, for compatibility with existing SI
    // unit system.
    format(SI.GRAM, sb);
    formatConverter(converter, printSeparator, sb, symbolMap);    
    
    return sb;
}
 
Example #8
Source File: SampleDimension.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the units of measurement for this sample dimension.
 * This unit applies to values obtained after the {@linkplain #getTransferFunction() transfer function}.
 * May be absent if not applicable.
 *
 * @return the units of measurement.
 * @throws IllegalStateException if this sample dimension use different units.
 *
 * @see #getMeasurementRange()
 */
public Optional<Unit<?>> getUnits() {
    Unit<?> unit = null;
    for (final Category category : converted().categories) {
        final NumberRange<?> r = category.range;
        if (r instanceof MeasurementRange<?>) {
            final Unit<?> c = ((MeasurementRange<?>) r).unit();
            if (c != null) {
                if (unit == null) {
                    unit = c;
                } else if (!unit.equals(c)) {
                    throw new IllegalStateException();
                }
            }
        }
    }
    return Optional.ofNullable(unit);
}
 
Example #9
Source File: ReferencingUtilities.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the unit used for all axes in the given coordinate system.
 * If not all axes use the same unit, then this method returns {@code null}.
 *
 * <p>This method is used either when the coordinate system is expected to contain exactly one axis,
 * or for operations that support only one units for all axes, for example Well Know Text version 1
 * (WKT 1) formatting.</p>
 *
 * @param  cs  the coordinate system for which to get the unit, or {@code null}.
 * @return the unit for all axis in the given coordinate system, or {@code null}.
 *
 * @see org.apache.sis.internal.referencing.AxisDirections#getAngularUnit(CoordinateSystem, Unit)
 */
public static Unit<?> getUnit(final CoordinateSystem cs) {
    Unit<?> unit = null;
    if (cs != null) {
        for (int i=cs.getDimension(); --i>=0;) {
            final CoordinateSystemAxis axis = cs.getAxis(i);
            if (axis != null) {                                         // Paranoiac check.
                final Unit<?> candidate = axis.getUnit();
                if (candidate != null) {
                    if (unit == null) {
                        unit = candidate;
                    } else if (!unit.equals(candidate)) {
                        return null;
                    }
                }
            }
        }
    }
    return unit;
}
 
Example #10
Source File: ParametersTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Implementation of {@link #testValueDomain()} on a single descriptor instance.
 * This method test two paths:
 *
 * <ul>
 *   <li>The special case for {@link DefaultParameterDescriptor} instances.</li>
 *   <li>The fallback for generic cases. For that test, we wrap the descriptor in an anonymous class
 *       for hiding the fact that the descriptor is an instance of {@code DefaultParameterDescriptor}.</li>
 * </ul>
 */
private static <T extends Comparable<? super T>> void verifyValueDomain(
        final Range<T> valueDomain, final ParameterDescriptor<T> descriptor)
{
    assertEquals(valueDomain, Parameters.getValueDomain(descriptor));
    assertEquals(valueDomain, Parameters.getValueDomain(new ParameterDescriptor<T>() {
        @Override public ReferenceIdentifier      getName()          {return descriptor.getName();}
        @Override public Collection<GenericName>  getAlias()         {return descriptor.getAlias();}
        @Override public Set<ReferenceIdentifier> getIdentifiers()   {return descriptor.getIdentifiers();}
        @Override public InternationalString      getRemarks()       {return descriptor.getRemarks();}
        @Override public int                      getMinimumOccurs() {return descriptor.getMinimumOccurs();}
        @Override public int                      getMaximumOccurs() {return descriptor.getMaximumOccurs();}
        @Override public Class<T>                 getValueClass()    {return descriptor.getValueClass();}
        @Override public Set<T>                   getValidValues()   {return descriptor.getValidValues();}
        @Override public Comparable<T>            getMinimumValue()  {return descriptor.getMinimumValue();}
        @Override public Comparable<T>            getMaximumValue()  {return descriptor.getMaximumValue();}
        @Override public T                        getDefaultValue()  {return descriptor.getDefaultValue();}
        @Override public Unit<?>                  getUnit()          {return descriptor.getUnit();}
        @Override public ParameterValue<T>        createValue()      {return descriptor.createValue();}
        @Override public String                   toWKT()            {return descriptor.toWKT();}
    }));
}
 
Example #11
Source File: DefaultEllipsoid.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Ensures that the semi-minor axis uses the same unit than the semi-major one.
 * The {@link #unit} field shall be set to the semi-major axis unit before this method call.
 *
 * @param  uom  the semi-minor axis unit.
 */
private void harmonizeAxisUnits(final Unit<Length> uom) {
    if (unit == null) {
        unit = uom;
    } else if (uom != null && uom != unit) {
        semiMinorAxis = uom.getConverterTo(unit).convert(semiMinorAxis);
    }
}
 
Example #12
Source File: DefaultSymbols.java    From sldeditor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates the default text symbolizer.
 *
 * @return the text symbolizer
 */
public static TextSymbolizer createDefaultTextSymbolizer() {
    Expression fontFamily = ff.literal("Serif");
    Expression fontSize = ff.literal(10.0);
    Expression fontStyle = ff.literal("normal");
    Expression fontWeight = ff.literal("normal");
    Expression rotation = ff.literal(0.0);
    Expression label = ff.literal("Test");

    String geometryFieldName = null;
    Expression geometryField = ff.property(geometryFieldName);

    String name = Localisation.getString(SLDTreeTools.class, "TreeItem.newText");
    AnchorPoint anchor = null;
    Displacement displacement = null;

    PointPlacement pointPlacement = styleFactory.pointPlacement(anchor, displacement, rotation);

    Expression fillColour = ff.literal(DEFAULT_COLOUR);
    Expression fillColourOpacity = ff.literal(1.0);

    Fill fill = styleFactory.fill(null, fillColour, fillColourOpacity);

    Halo halo = null;

    List<Expression> fontFamilyList = new ArrayList<>();
    fontFamilyList.add(fontFamily);
    Font font = styleFactory.font(fontFamilyList, fontStyle, fontWeight, fontSize);

    Description description = null;
    Unit<?> unit = null;

    return styleFactory.textSymbolizer(
            name, geometryField, description, unit, label, font, pointPlacement, halo, fill);
}
 
Example #13
Source File: AbstractEnvelope.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the envelope span along the specified dimension, in terms of the given units.
 * The default implementation invokes {@link #getSpan(int)} and converts the result.
 *
 * @param  dimension  the dimension to query.
 * @param  unit  the unit for the return value.
 * @return the span in terms of the given unit.
 * @throws IndexOutOfBoundsException if the given index is out of bounds.
 * @throws IncommensurableException if the length can't be converted to the specified units.
 */
public double getSpan(final int dimension, final Unit<?> unit)
        throws IndexOutOfBoundsException, IncommensurableException
{
    double value = getSpan(dimension);
    final CoordinateSystemAxis axis = getAxis(getCoordinateReferenceSystem(), dimension);
    if (axis != null) {
        final Unit<?> source = axis.getUnit();
        if (source != null) {
            value = source.getConverterToAny(unit).convert(value);
        }
    }
    return value;
}
 
Example #14
Source File: CRSBuilder.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a coordinate system (CS) with the same axis directions than the given CS but potentially different units.
 * If a coordinate system exists in the EPSG database with the requested characteristics, that CS will be returned
 * in order to have a richer set of metadata (name, minimal and maximal values, <i>etc</i>). Otherwise an CS with
 * an arbitrary name will be returned.
 *
 * @see CoordinateSystems#replaceAngularUnit(CoordinateSystem, Unit)
 */
private EllipsoidalCS replaceAngularUnit(final EllipsoidalCS cs, final Unit<Angle> unit) throws FactoryException {
    final Integer epsg = CoordinateSystems.getEpsgCode(unit, CoordinateSystems.getAxisDirections(cs));
    if (epsg != null) try {
        return getCSAuthorityFactory().createEllipsoidalCS(epsg.toString());
    } catch (NoSuchAuthorityCodeException e) {
        reader.owner.warning(null, e);
    }
    return (EllipsoidalCS) CoordinateSystems.replaceAngularUnit(cs, unit);
}
 
Example #15
Source File: Scalar.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a quantity quantity of same type than this quantity but with a different value and/or unit.
 * If the new value and unit are the same than this quantity, then {@code this} instance is returned.
 * Positive and negative zeros are considered two different values.
 */
private Quantity<?> of(final double newValue, final Unit<?> newUnit) {
    if (unit != newUnit || Double.doubleToRawLongBits(value) != Double.doubleToRawLongBits(newValue)) {
        return Quantities.create(newValue, newUnit);
    }
    return this;
}
 
Example #16
Source File: StringColumnUnitMapper.java    From jadira with Apache License 2.0 5 votes vote down vote up
@Override
public void setValidTypes(List<Class<Unit<?>>> types) {
	for (Class<Unit<?>> next : types) {
		Unit<?> unit;
		try {
			unit = next.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			throw new IllegalStateException("Cannot instantiate " + next.getName() + ": " + e.getMessage(), e);
		}
		unitsMap.put(unit.getSymbol(), unit);
	}
	this.validTypes = Collections.unmodifiableList(types);
}
 
Example #17
Source File: EPSGFactoryFallback.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the interface for the given {@code *_MASK} constant.
 * This is used for formatting error message only.
 */
private static Class<?> toClass(final int kind) {
    switch (kind) {
        case CRS:            return CoordinateReferenceSystem.class;
        case DATUM:          return Datum.class;
        case ELLIPSOID:      return Ellipsoid.class;
        case PRIME_MERIDIAN: return PrimeMeridian.class;
        case UNIT:           return Unit.class;
        case AXIS:           return CoordinateSystemAxis.class;
        case CS:             return CoordinateSystem.class;
        default:             return IdentifiedObject.class;
    }
}
 
Example #18
Source File: Variable.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the unit of measurement and the epoch to the same value than the given variable.
 * This method is not used in CF-compliant files; it is reserved for the handling of some
 * particular conventions, for example HYCOM.
 *
 * @param  other      the variable from which to copy unit and epoch, or {@code null} if none.
 * @param  overwrite  if non-null, set to the given unit instead than the unit of {@code other}.
 * @return the epoch (may be {@code null}).
 *
 * @see #getUnit()
 */
public final Instant setUnit(final Variable other, Unit<?> overwrite) {
    if (other != null) {
        unit  = other.getUnit();        // May compute the epoch as a side effect.
        epoch = other.epoch;
    }
    if (overwrite != null) {
        unit = overwrite;
    }
    unitParsed = true;
    return epoch;
}
 
Example #19
Source File: CRSBuilder.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies if the user-defined CRS created from GeoTIFF values
 * matches the given CRS created from the EPSG geodetic dataset.
 * This method does not verify the EPSG code of the given CRS.
 *
 * @param  crs  the CRS created from the EPSG geodetic dataset.
 */
private void verify(final GeocentricCRS crs) throws FactoryException {
    /*
     * Note: current createUnit(…) implementation does not allow us to distinguish whether METRE ou DEGREE units
     * were specified in the GeoTIFF file or if we got the default values. We do not compare units of that reason.
     */
    final Unit<Length> linearUnit = createUnit(GeoKeys.GeogLinearUnits, GeoKeys.GeogLinearUnitSize, Length.class, Units.METRE);
    final Unit<Angle> angularUnit = createUnit(GeoKeys.AngularUnits, GeoKeys.AngularUnitSize, Angle.class, Units.DEGREE);
    final GeodeticDatum datum = crs.getDatum();
    verifyIdentifier(crs, datum, GeoKeys.GeodeticDatum);
    verify(datum, angularUnit, linearUnit);
}
 
Example #20
Source File: GeographicToGeocentric.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Implementation of {@link #createMathTransform(MathTransformFactory, ParameterValueGroup)}
 * shared with {@link GeocentricToGeographic}.
 */
static MathTransform create(final MathTransformFactory factory, final Parameters values)
        throws FactoryException
{
    final ParameterValue<?> semiMajor = values.parameter(Constants.SEMI_MAJOR);
    final Unit<Length> unit = semiMajor.getUnit().asType(Length.class);
    return EllipsoidToCentricTransform.createGeodeticConversion(factory, semiMajor.doubleValue(),
            values.parameter(Constants.SEMI_MINOR).doubleValue(unit), unit, values.intValue(DIMENSION) >= 3,
            EllipsoidToCentricTransform.TargetType.CARTESIAN);
}
 
Example #21
Source File: MapProjectionParameters.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Invoked when a new parameter value is set. This method sets both axis length to the given radius.
 */
@Override
protected void setValue(final Object value, final Unit<?> unit) {
    super.setValue(value, unit);        // Perform argument check.
    final double r = (Double) value;    // At this point, can not be anything else than Double.
    semiMajor.setValue(r, unit);
    semiMinor.setValue(r, unit);
}
 
Example #22
Source File: DerivedScalar.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new quantity of the same type than this quantity but a different value and/or unit.
 *
 * @see ScalarFallback#create(double, Unit)
 */
@Override
@SuppressWarnings("unchecked")
Quantity<Q> create(final double newValue, final Unit<Q> newUnit) {
    assert newUnit == getSystemUnit() : newUnit;
    final Fallback<Q> quantity = new Fallback<>(this, newValue);
    return (Q) Proxy.newProxyInstance(Scalar.class.getClassLoader(), new Class<?>[] {type}, quantity);
}
 
Example #23
Source File: AbstractCRS.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Formats the given coordinate system.
 *
 * <p>In WKT 2 format, this method should not be invoked if {@link #isBaseCRS(Formatter)} returned {@code true}
 * because ISO 19162 excludes the coordinate system definition in base CRS. Note however that WKT 1 includes the
 * coordinate systems. The SIS-specific {@link Convention#INTERNAL} formats also those coordinate systems.</p>
 *
 * <div class="note"><b>Note:</b> the {@code unit} and {@code isWKT1} arguments could be computed by this method,
 * but are requested in order to avoid computing them twice, because the caller usually have them anyway.</div>
 *
 * @param  formatter  the formatter where to append the coordinate system.
 * @param  cs         the coordinate system to append.
 * @param  unit       the value of {@code ReferencingUtilities.getUnit(cs)}.
 * @param  isWKT1     {@code true} if formatting WKT 1, or {@code false} for WKT 2.
 */
final void formatCS(final Formatter formatter, final CoordinateSystem cs, final Unit<?> unit, final boolean isWKT1) {
    assert unit == ReferencingUtilities.getUnit(cs) : unit;
    assert (formatter.getConvention().majorVersion() == 1) == isWKT1 : isWKT1;
    assert isWKT1 || !isBaseCRS(formatter) || formatter.getConvention() == Convention.INTERNAL;    // Condition documented in javadoc.

    final Unit<?> oldUnit = formatter.addContextualUnit(unit);
    if (isWKT1) {                               // WKT 1 writes unit before axes, while WKT 2 writes them after axes.
        formatter.append(unit);
        if (unit == null) {
            formatter.setInvalidWKT(this, null);
        }
    } else {
        formatter.append(toFormattable(cs));    // WKT2 only, since the concept of CoordinateSystem was not explicit in WKT 1.
        formatter.indent(+1);
    }
    if (!isWKT1 || formatter.getConvention() != Convention.WKT1_IGNORE_AXES) {
        if (cs != null) {                       // Should never be null, except sometime temporarily during construction.
            final int dimension = cs.getDimension();
            for (int i=0; i<dimension; i++) {
                formatter.newLine();
                formatter.append(toFormattable(cs.getAxis(i)));
            }
        }
    }
    if (!isWKT1) {                              // WKT 2 writes unit after axes, while WKT 1 wrote them before axes.
        formatter.newLine();
        formatter.append(unit);
        formatter.indent(-1);
    }
    formatter.restoreContextualUnit(unit, oldUnit);
    formatter.newLine();                        // For writing the ID[…] element on its own line.
}
 
Example #24
Source File: DefaultCylindricalCS.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns {@code VALID} if the given argument values are allowed for this coordinate system,
 * or an {@code INVALID_*} error code otherwise. This method is invoked at construction time.
 *
 * <p>The current implementation rejects all directions that are known to be non-spatial.
 * We conservatively accept custom axis directions because some of them are created from
 * strings like "South along 90°E".</p>
 */
@Override
final int validateAxis(final AxisDirection direction, final Unit<?> unit) {
    if (!AxisDirections.isSpatialOrUserDefined(direction, false)) {
        return INVALID_DIRECTION;
    }
    if (!Units.isAngular(unit) && !Units.isLinear(unit)) {
        return INVALID_UNIT;
    }
    return VALID;
}
 
Example #25
Source File: SexagesimalConverterTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Converts the given value to an other unit, compares with the expected value, and verify
 * the inverse conversion. Then tries again with the negative of the given values.
 */
private static <Q extends Quantity<Q>> void checkConversion(
        final double expected, final Unit<Q> unitExpected,
        final double actual,   final Unit<Q> unitActual)
{
    final UnitConverter converter = unitActual.getConverterTo(unitExpected);
    final UnitConverter inverse   = converter.inverse();
    assertEquals( expected, converter.convert( actual), TOLERANCE);
    assertEquals( actual,   inverse.convert( expected), TOLERANCE);
    assertEquals(-expected, converter.convert(-actual), TOLERANCE);
    assertEquals(-actual,   inverse.convert(-expected), TOLERANCE);
}
 
Example #26
Source File: NumberItem.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Try to convert a {@link DecimalType} into a new {@link QuantityType}. The unit for the new
 * type is derived either from the state description (which might also give a hint on items w/o dimension) or from
 * the system default unit of the given dimension.
 *
 * @param originalType the source {@link DecimalType}.
 * @param dimension the dimension to which the new {@link QuantityType} should adhere.
 * @return the new {@link QuantityType} from the given originalType, {@code null} if a unit could not be calculated.
 */
public @Nullable QuantityType<?> toQuantityType(DecimalType originalType,
        @Nullable Class<? extends Quantity<?>> dimension) {
    Unit<? extends Quantity<?>> itemUnit = getUnit(dimension);
    if (itemUnit != null) {
        return new QuantityType<>(originalType.toBigDecimal(), itemUnit);
    }

    return null;
}
 
Example #27
Source File: Proj4Parser.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the vertical or horizontal axis unit.
 * This unit applies only to linear axes, not angular axes neither parameters.
 *
 * @param  vertical  {@code true} for querying the vertical unit, or {@code false} for the horizontal one.
 * @return the vertical or horizontal axis unit of measurement, or {@code Units.METRE} if unspecified.
 * @throws NumberFormatException if the unit conversion factor can not be parsed.
 * @throws ParserException if the unit symbol can not be parsed.
 */
final Unit<?> unit(final boolean vertical) throws ParserException {
    String v = parameters.remove(vertical ? "vto_meter" : "to_meter");
    if (v != null) {
        return Units.METRE.divide(Double.parseDouble(v));
    }
    v = parameters.remove(vertical ? "vunits" : "units");
    if (v != null) {
        return Units.valueOf(v);
    }
    return Units.METRE;
}
 
Example #28
Source File: CRSBuilder.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns {@code true} if the coordinate system may be one of the predefined CS. A returns value of {@code true}
 * is not a guarantee that the coordinate system in the netCDF file matches the predefined CS; it only tells that
 * this is reasonable chances to be the case based on a brief inspection of the first coordinate system axis.
 * If {@code true}, then {@link #isLongitudeFirst} will have been set to an indication of axis order.
 *
 * @param  expected  the expected unit of measurement of the first axis.
 *
 * @see #epsgCandidateCS(Unit)
 */
final boolean isPredefinedCS(final Unit<?> expected) {
    final Axis axis = getFirstAxis();
    final Unit<?> unit = axis.getUnit();
    if (unit == null || expected.equals(unit)) {
        isLongitudeFirst = AxisDirection.EAST.equals(axis.direction);
        if (isLongitudeFirst || AxisDirection.NORTH.equals(axis.direction)) {
            return true;
        }
    }
    return false;
}
 
Example #29
Source File: UnitUtilsTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testGetDimensionName() {
    assertThat(UnitUtils.getDimensionName(SIUnits.CELSIUS), is(Temperature.class.getSimpleName()));
    assertThat(UnitUtils.getDimensionName(SmartHomeUnits.KILOWATT_HOUR), is(Energy.class.getSimpleName()));
    assertThat(UnitUtils.getDimensionName(SmartHomeUnits.WATT), is(Power.class.getSimpleName()));
    assertThat(UnitUtils.getDimensionName(MetricPrefix.MEGA(SmartHomeUnits.KILOWATT_HOUR)),
            is(Energy.class.getSimpleName()));

    Unit<?> unit = UnitUtils.parseUnit("°F");
    assertNotNull(unit);
    assertThat(UnitUtils.getDimensionName(unit), is(Temperature.class.getSimpleName()));
    unit = UnitUtils.parseUnit("m");
    assertNotNull(unit);
    assertThat(UnitUtils.getDimensionName(unit), is(Length.class.getSimpleName()));
}
 
Example #30
Source File: InterpolatedMolodenskyTransform.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Invoked by constructor and by {@link #getParameterValues()} for setting all parameters other than axis lengths.
 *
 * @param  pg         where to set the parameters.
 * @param  semiMinor  the semi minor axis length, in unit of {@code unit}.
 * @param  unit       the unit of measurement to declare.
 * @param  Δf         ignored.
 */
@Override
final void completeParameters(final Parameters pg, final double semiMinor, final Unit<?> unit, double Δf) {
    super.completeParameters(pg, semiMinor, unit, Δf);
    if (pg != context) {
        Δf = Δfmod / semiMinor;
        pg.getOrCreate(Molodensky.AXIS_LENGTH_DIFFERENCE).setValue(Δa, unit);
        pg.getOrCreate(Molodensky.FLATTENING_DIFFERENCE) .setValue(Δf, Units.UNITY);
    }
    grid.getParameterValues(pg);
}