javax.measure.quantity.Length Java Examples

The following examples show how to use javax.measure.quantity.Length. 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: CRSBuilder.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an optional vertical CRS, or returns {@code null} if no vertical CRS definition is found.
 * This method is different from the other {@code createFooCRS()} methods in that the vertical CRS
 * may be defined <em>in addition</em> of another CRS. Some GeoTIFF values used by this method are:
 *
 * <ul>
 *   <li>A code given by {@link GeoKeys#VerticalCSType}.</li>
 *   <li>If above code is {@link GeoCodes#userDefined}, then:<ul>
 *     <li>a name given by {@link GeoKeys#VerticalCitation},</li>
 *     <li>a {@link VerticalDatum} given by {@link GeoKeys#VerticalDatum}.</li>
 *   </ul></li>
 *   <li>A unit code given by {@link GeoKeys#VerticalUnits} (optional).</li>
 * </ul>
 *
 * @throws NoSuchElementException if a mandatory value is missing.
 * @throws NumberFormatException if a numeric value was stored as a string and can not be parsed.
 * @throws ClassCastException if an object defined by an EPSG code is not of the expected type.
 * @throws FactoryException if an error occurred during objects creation with the factories.
 */
private VerticalCRS createVerticalCRS() throws FactoryException {
    final int epsg = getAsInteger(GeoKeys.VerticalCSType);
    switch (epsg) {
        case GeoCodes.undefined: {
            return null;
        }
        case GeoCodes.userDefined: {
            final String name = getAsString(GeoKeys.VerticalCitation);
            final VerticalDatum datum = createVerticalDatum();
            final Unit<Length> unit = createUnit(GeoKeys.VerticalUnits, (short) 0, Length.class, Units.METRE);
            VerticalCS cs = CommonCRS.Vertical.MEAN_SEA_LEVEL.crs().getCoordinateSystem();
            if (!Units.METRE.equals(unit)) {
                cs = (VerticalCS) CoordinateSystems.replaceLinearUnit(cs, unit);
            }
            return getCRSFactory().createVerticalCRS(properties(name), datum, cs);
        }
        default: {
            return getCRSAuthorityFactory().createVerticalCRS(String.valueOf(epsg));
        }
    }
}
 
Example #2
Source File: ItemStateConverterImplTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void numberItemShouldNotConvertUnitsWhereMeasurmentSystemEquals() {
    NumberItem item = mock(NumberItem.class);
    doReturn(Length.class).when(item).getDimension();

    UnitProvider unitProvider = mock(UnitProvider.class);
    when(unitProvider.getUnit(Length.class)).thenReturn(SIUnits.METRE);
    itemStateConverter.setUnitProvider(unitProvider);

    QuantityType<Length> originalState = new QuantityType<>("100 cm");

    @SuppressWarnings("unchecked")
    QuantityType<Length> convertedState = (QuantityType<Length>) itemStateConverter
            .convertToAcceptedState(originalState, item);

    assertThat(convertedState.getUnit(), is(originalState.getUnit()));
}
 
Example #3
Source File: DefaultEllipsoid.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Formats this ellipsoid as a <cite>Well Known Text</cite> {@code Ellipsoid[…]} element.
 *
 * @return {@code "Ellipsoid"} (WKT 2) or {@code "Spheroid"} (WKT 1).
 *
 * @see <a href="http://docs.opengeospatial.org/is/12-063r5/12-063r5.html#52">WKT 2 specification §8.2.1</a>
 */
@Override
protected String formatTo(final Formatter formatter) {
    super.formatTo(formatter);
    final Convention   convention = formatter.getConvention();
    final boolean      isWKT1     = convention.majorVersion() == 1;
    final Unit<Length> unit       = getAxisUnit();  // Gives to users a chance to override properties.
    double length = getSemiMajorAxis();
    if (isWKT1) {
        length = unit.getConverterTo(Units.METRE).convert(length);
    }
    formatter.append(length);
    final double inverseFlattening = getInverseFlattening();  // Gives to users a chance to override properties.
    formatter.append(isInfinite(inverseFlattening) ? 0 : inverseFlattening);
    if (isWKT1) {
        return WKTKeywords.Spheroid;
    }
    if (!convention.isSimplified() || !Units.METRE.equals(unit)) {
        formatter.append(unit);
    }
    return WKTKeywords.Ellipsoid;
}
 
Example #4
Source File: SystemUnitTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests {@link SystemUnit#asType(Class)} for a quantity unknown to Apache SIS.
 */
@Test
@DependsOnMethod({"testAsType", "testAlternate"})
public void testAsTypeForNewQuantity() {
    /*
     * Tests with a new quantity type unknown to Apache SIS.
     * SIS can not proof that the type is wrong, so it should accept it.
     */
    final Unit<Strange> strange = Units.METRE.asType(Strange.class);
    final Unit<Strange> named   = strange.alternate("strange");
    assertNull  ("Should not have symbol since this is a unit for a new quantity.", strange.getSymbol());
    assertEquals("Should have a name since we invoked 'alternate'.", "strange", named.getSymbol());
    assertSame  ("Should prefer the named instance.", named, Units.METRE.asType(Strange.class));
    assertSame  ("Go back to the fundamental unit.",  Units.METRE, named.asType(Length.class));
    for (final Unit<Strange> unit : Arrays.asList(strange, named)) {
        try {
            unit.asType(Time.class);
            fail("Expected an exception for incompatible quantity types.");
        } catch (ClassCastException e) {
            final String message = e.getMessage();
            assertTrue(message, message.contains("Strange"));
            assertTrue(message, message.contains("Time"));
        }
    }
}
 
Example #5
Source File: FranceGeocentricInterpolationTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests a small grid file with interpolations in geocentric coordinates as {@code short} values.
 *
 * <p>This method is part of a chain.
 * The previous method is {@link #testGridAsFloats()}.</p>
 *
 * @param  grid  the grid created by {@link #testGridAsFloats()}.
 * @return the given grid, but compressed as {@code short} values.
 * @throws TransformException if an error occurred while computing the envelope.
 */
@TestStep
private static DatumShiftGridFile<Angle,Length> testGridAsShorts(DatumShiftGridFile<Angle,Length> grid)
        throws TransformException
{
    grid = DatumShiftGridCompressed.compress((DatumShiftGridFile.Float<Angle,Length>) grid, new double[] {
            FranceGeocentricInterpolation.TX,           //  168 metres
            FranceGeocentricInterpolation.TY,           //   60 metres
            FranceGeocentricInterpolation.TZ},          // -320 metres
            FranceGeocentricInterpolation.PRECISION);
    assertInstanceOf("Failed to compress 'float' values into 'short' values.", DatumShiftGridCompressed.class, grid);
    assertEquals("cellPrecision", 0.0005, grid.getCellPrecision(), STRICT);
    assertEquals("getCellMean",  168, grid.getCellMean(0), STRICT);
    assertEquals("getCellMean",   60, grid.getCellMean(1), STRICT);
    assertEquals("getCellMean", -320, grid.getCellMean(2), STRICT);
    verifyGrid(grid);
    return grid;
}
 
Example #6
Source File: ScalarTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests {@link ScalarFallback}, used when no specialized implementation is available for a given quantity type.
 */
@Test
public void testFallback() {
    final Quantity<Length> q1 = ScalarFallback.factory(24, Units.KILOMETRE, Length.class);
    assertInstanceOf("Dynamic proxy", Proxy .class, q1);
    assertInstanceOf("Dynamic proxy", Length.class, q1);
    assertSame  ("unit", Units.KILOMETRE, q1.getUnit());
    assertEquals("value", 24, q1.getValue().doubleValue(), STRICT);
    assertEquals("toString()", "24 km", q1.toString());

    final Quantity<Length> q2 = ScalarFallback.factory(24, Units.KILOMETRE, Length.class);
    assertEquals("hashCode()", q1.hashCode(), q2.hashCode());
    assertEquals("equals(…)", q1, q2);

    final Quantity<Length> q3 = ScalarFallback.factory(1500, Units.METRE, Length.class);
    final Quantity<Length> q4 = q1.add(q3);
    assertInstanceOf("Dynamic proxy", Proxy .class, q4);
    assertInstanceOf("Dynamic proxy", Length.class, q4);
    assertSame  ("unit", Units.KILOMETRE, q4.getUnit());
    assertEquals("value", 25.5, q4.getValue().doubleValue(), STRICT);
    assertEquals("toString()", "25.5 km", q4.toString());

    final Quantity<Length> q5 = q1.multiply(q3).divide(q2).asType(Length.class);
    assertSame  ("unit", Units.METRE, q5.getUnit());
    assertEquals("value", 1500, q5.getValue().doubleValue(), STRICT);
}
 
Example #7
Source File: ScalarTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests {@link Scalar#multiply(Quantity)}, {@link Scalar#divide(Quantity)} and {@link Quantity#inverse()}.
 * Those tests depend on proper working of {@link Quantities#create(double, Unit)}, which depends in turn on
 * proper declarations of {@link ScalarFactory} in {@link Units} initialization.
 */
@Test
public void testMultiplyDivideQuantity() {
    final Quantity<Length> q1 = new Scalar.Length(24, Units.METRE);
    final Quantity<Time>   q2 = new Scalar.Time  ( 4, Units.SECOND);
    final Quantity<Speed>  q3 = q1.divide(q2).asType(Speed.class);
    assertSame  ("unit", Units.METRES_PER_SECOND, q3.getUnit());
    assertEquals("value", 6, q3.getValue().doubleValue(), STRICT);
    assertInstanceOf("Length/Time", Scalar.Speed.class, q3);

    final Quantity<Area> q4 = q1.multiply(q1).asType(Area.class);
    assertSame  ("unit", Units.SQUARE_METRE, q4.getUnit());
    assertEquals("value", 576, q4.getValue().doubleValue(), STRICT);
    assertInstanceOf("Length⋅Length", Scalar.Area.class, q4);

    final Quantity<Frequency> q5 = q2.inverse().asType(Frequency.class);
    assertSame  ("unit", Units.HERTZ, q5.getUnit());
    assertEquals("value", 0.25, q5.getValue().doubleValue(), STRICT);
    assertInstanceOf("1/Time", Scalar.Frequency.class, q5);
}
 
Example #8
Source File: QuantitiesTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests {@link Quantities#castOrCopy(Quantity)}.
 */
@Test
public void testCastOrCopy() {
    Quantity<Length> q = Quantities.create(5, Units.KILOMETRE);
    assertSame(q, Quantities.castOrCopy(q));

    q = new Quantity<Length>() {
        @Override public Number           getValue()                         {return 8;}
        @Override public Unit<Length>     getUnit ()                         {return Units.CENTIMETRE;}
        @Override public Quantity<Length> add     (Quantity<Length> ignored) {return null;}
        @Override public Quantity<Length> subtract(Quantity<Length> ignored) {return null;}
        @Override public Quantity<?>      multiply(Quantity<?>      ignored) {return null;}
        @Override public Quantity<?>      divide  (Quantity<?>      ignored) {return null;}
        @Override public Quantity<Length> multiply(Number           ignored) {return null;}
        @Override public Quantity<Length> divide  (Number           ignored) {return null;}
        @Override public Quantity<?>      inverse ()                         {return null;}
        @Override public Quantity<Length> to      (Unit<Length>     ignored) {return null;}
        @Override public <T extends Quantity<T>> Quantity<T> asType(Class<T> ignored) {return null;}
    };
    final Length c = Quantities.castOrCopy(q);
    assertNotSame(q, c);
    assertEquals("value", 8, c.getValue().doubleValue(), STRICT);
    assertSame  ("unit", Units.CENTIMETRE, c.getUnit());
}
 
Example #9
Source File: GeodeticObjectParser.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Parses an {@code "Ellipsoid"} element. The syntax is given by
 * <a href="http://docs.opengeospatial.org/is/12-063r5/12-063r5.html#52">WKT 2 specification §8.2.1</a>.
 *
 * The legacy WKT 1 pattern was:
 *
 * {@preformat wkt
 *     SPHEROID["<name>", <semi-major axis>, <inverse flattening> {,<authority>}]
 * }
 *
 * @param  mode    {@link #FIRST}, {@link #OPTIONAL} or {@link #MANDATORY}.
 * @param  parent  the parent element.
 * @return the {@code "Ellipsoid"} element as an {@link Ellipsoid} object.
 * @throws ParseException if the {@code "Ellipsoid"} element can not be parsed.
 *
 * @see org.apache.sis.referencing.datum.DefaultEllipsoid#formatTo(Formatter)
 */
private Ellipsoid parseEllipsoid(final int mode, final Element parent) throws ParseException {
    final Element element = parent.pullElement(mode, WKTKeywords.Ellipsoid, WKTKeywords.Spheroid);
    if (element == null) {
        return null;
    }
    final String name          = element.pullString("name");
    final double semiMajorAxis = element.pullDouble("semiMajorAxis");
    double inverseFlattening   = element.pullDouble("inverseFlattening");
    Unit<Length> unit = parseScaledUnit(element, WKTKeywords.LengthUnit, Units.METRE);
    if (unit == null) {
        unit = Units.METRE;
    }
    final Map<String,?> properties = parseMetadataAndClose(element, name, null);
    final DatumFactory datumFactory = factories.getDatumFactory();
    try {
        if (inverseFlattening == 0) {                           // OGC convention for a sphere.
            return datumFactory.createEllipsoid(properties, semiMajorAxis, semiMajorAxis, unit);
        } else {
            return datumFactory.createFlattenedSphere(properties, semiMajorAxis, inverseFlattening, unit);
        }
    } catch (FactoryException exception) {
        throw element.parseFailed(exception);
    }
}
 
Example #10
Source File: ScalarTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests {@link Scalar#equals(Object)} and {@link Scalar#hashCode()}.
 */
@Test
public void testEqualsAndHashCode() {
    final Quantity<Length> q1 = new Scalar.Length(24, Units.METRE);
    Quantity<Length> q2 = new Scalar.Length(24, Units.METRE);
    assertEquals("hashCode()", q1.hashCode(), q2.hashCode());
    assertEquals("equals(…)", q1, q2);

    q2 = new Scalar.Length(12, Units.METRE);
    assertNotEquals("hashCode()", q1.hashCode(), q2.hashCode());
    assertNotEquals("equals(…)", q1, q2);

    q2 = new Scalar.Length(24, Units.CENTIMETRE);
    assertNotEquals("hashCode()", q1.hashCode(), q2.hashCode());
    assertNotEquals("equals(…)", q1, q2);
}
 
Example #11
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 #12
Source File: SmartHomeUnitsTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testM2Ft() {
    Quantity<Length> cm = Quantities.getQuantity(new BigDecimal("30"), MetricPrefix.CENTI(SIUnits.METRE));

    Quantity<Length> foot = cm.to(ImperialUnits.FOOT);
    assertThat(foot.getUnit(), is(ImperialUnits.FOOT));
    assertThat(foot.getValue().doubleValue(), is(closeTo(0.9842519685039369d, DEFAULT_ERROR)));
}
 
Example #13
Source File: WaterTankUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenUnits_WhenAdd_ThenSuccess() {
    Quantity<Length> total = Quantities.getQuantity(2, METRE).add(Quantities.getQuantity(3, METRE));
    assertEquals(total.getValue().intValue(), 5);

    // compilation error
    // Quantity<Length> total = Quantities.getQuantity(2, METRE).add(Quantities.getQuantity(3, LITRE));

    Quantity<Length> totalKm = Quantities.getQuantity(2, METRE).add(Quantities.getQuantity(3, MetricPrefix.KILO(METRE)));
    assertEquals(totalKm.getValue().intValue(), 3002);
}
 
Example #14
Source File: MolodenskyInterpolation.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Invoked by {@link #createMathTransform(MathTransformFactory, ParameterValueGroup)}
 * after all parameters have been processed.
 */
@Override
MathTransform createGeodeticTransformation(final MathTransformFactory factory,
        final Ellipsoid source, final Ellipsoid target, final boolean withHeights,
        final DatumShiftGridFile<Angle,Length> grid) throws FactoryException
{
    return InterpolatedMolodenskyTransform.createGeodeticTransformation(
            factory, source, withHeights, target, withHeights, grid);
}
 
Example #15
Source File: SmartHomeUnitsTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testM2Yd() {
    Quantity<Length> m = Quantities.getQuantity(BigDecimal.ONE, SIUnits.METRE);

    Quantity<Length> yard = m.to(ImperialUnits.YARD);
    assertThat(yard.getUnit(), is(ImperialUnits.YARD));
    assertThat(yard.getValue().doubleValue(), is(closeTo(1.0936132983377076d, DEFAULT_ERROR)));
}
 
Example #16
Source File: ScriptEngineOSGiTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Before
public void setup() {
    registerVolatileStorageService();

    EventPublisher eventPublisher = event -> {
    };

    registerService(eventPublisher);

    itemRegistry = getService(ItemRegistry.class);
    assertNotNull(itemRegistry);

    itemProvider = new ItemProvider() {

        @Override
        public void addProviderChangeListener(ProviderChangeListener<Item> listener) {
        }

        @Override
        public Collection<Item> getAll() {
            return Arrays.asList(new SwitchItem(ITEM_NAME),
                    createNumberItem(NUMBER_ITEM_TEMPERATURE, Temperature.class),
                    createNumberItem(NUMBER_ITEM_LENGTH, Length.class), new NumberItem(NUMBER_ITEM_DECIMAL));
        }

        @Override
        public void removeProviderChangeListener(ProviderChangeListener<Item> listener) {
        }
    };

    registerService(itemProvider);

    ScriptServiceUtil scriptServiceUtil = getService(ScriptServiceUtil.class);
    assertNotNull(scriptServiceUtil);
    scriptEngine = ScriptServiceUtil.getScriptEngine();
}
 
Example #17
Source File: SmartHomeUnitsTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testM2Ft() {
    Quantity<Length> cm = Quantities.getQuantity(new BigDecimal("30"), MetricPrefix.CENTI(SIUnits.METRE));

    Quantity<Length> foot = cm.to(ImperialUnits.FOOT);
    assertThat(foot.getUnit(), is(ImperialUnits.FOOT));
    assertThat(foot.getValue().doubleValue(), is(closeTo(0.9842519685039369d, DEFAULT_ERROR)));
}
 
Example #18
Source File: SmartHomeUnitsTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testM2Yd() {
    Quantity<Length> m = Quantities.getQuantity(BigDecimal.ONE, SIUnits.METRE);

    Quantity<Length> yard = m.to(ImperialUnits.YARD);
    assertThat(yard.getUnit(), is(ImperialUnits.YARD));
    assertThat(yard.getValue().doubleValue(), is(closeTo(1.0936132983377076d, DEFAULT_ERROR)));
}
 
Example #19
Source File: SmartHomeUnitsTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testM2Ml() {
    Quantity<Length> km = Quantities.getQuantity(BigDecimal.TEN, MetricPrefix.KILO(SIUnits.METRE));

    Quantity<Length> mile = km.to(ImperialUnits.MILE);
    assertThat(mile.getUnit(), is(ImperialUnits.MILE));
    assertThat(mile.getValue().doubleValue(), is(closeTo(6.2137119223733395d, DEFAULT_ERROR)));
}
 
Example #20
Source File: DefaultEllipsoid.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a SIS ellipsoid implementation with the same values than the given arbitrary implementation.
 * If the given object is {@code null}, then this method returns {@code null}.
 * Otherwise if the given object is already a SIS implementation, then the given object is returned unchanged.
 * Otherwise a new SIS implementation is created and initialized to the attribute values of the given object.
 *
 * @param  object  the object to get as a SIS implementation, or {@code null} if none.
 * @return a SIS implementation containing the values of the given object (may be the
 *         given object itself), or {@code null} if the argument was null.
 */
public static DefaultEllipsoid castOrCopy(final Ellipsoid object) {
    if (object == null || object instanceof DefaultEllipsoid) {
        return (DefaultEllipsoid) object;
    }
    final Map<String,?> properties = IdentifiedObjects.getProperties(object);
    final double        semiMajor  = object.getSemiMajorAxis();
    final Unit<Length>  unit       = object.getAxisUnit();
    return object.isIvfDefinitive() ?
            createFlattenedSphere(properties, semiMajor, object.getInverseFlattening(), unit) :
            createEllipsoid      (properties, semiMajor, object.getSemiMinorAxis(),     unit);
}
 
Example #21
Source File: QuantityTypeTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testExponentials() {
    QuantityType<Length> exponential = new QuantityType<>("10E-2 m");
    assertEquals(exponential, new QuantityType<>("10 cm"));

    exponential = new QuantityType<>("10E+3 m");
    assertEquals(exponential, new QuantityType<>("10 km"));

    exponential = new QuantityType<>("10E3 m");
    assertEquals(exponential, new QuantityType<>("10 km"));
}
 
Example #22
Source File: I18nProviderImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private void initDimensionMap() {
    Map<SystemOfUnits, Unit<? extends Quantity<?>>> temperatureMap = new HashMap<>();
    temperatureMap.put(SIUnits.getInstance(), SIUnits.CELSIUS);
    temperatureMap.put(ImperialUnits.getInstance(), ImperialUnits.FAHRENHEIT);
    dimensionMap.put(Temperature.class, temperatureMap);

    Map<SystemOfUnits, Unit<? extends Quantity<?>>> pressureMap = new HashMap<>();
    pressureMap.put(SIUnits.getInstance(), HECTO(SIUnits.PASCAL));
    pressureMap.put(ImperialUnits.getInstance(), ImperialUnits.INCH_OF_MERCURY);
    dimensionMap.put(Pressure.class, pressureMap);

    Map<SystemOfUnits, Unit<? extends Quantity<?>>> speedMap = new HashMap<>();
    speedMap.put(SIUnits.getInstance(), SIUnits.KILOMETRE_PER_HOUR);
    speedMap.put(ImperialUnits.getInstance(), ImperialUnits.MILES_PER_HOUR);
    dimensionMap.put(Speed.class, speedMap);

    Map<SystemOfUnits, Unit<? extends Quantity<?>>> lengthMap = new HashMap<>();
    lengthMap.put(SIUnits.getInstance(), SIUnits.METRE);
    lengthMap.put(ImperialUnits.getInstance(), ImperialUnits.INCH);
    dimensionMap.put(Length.class, lengthMap);

    Map<SystemOfUnits, Unit<? extends Quantity<?>>> intensityMap = new HashMap<>();
    intensityMap.put(SIUnits.getInstance(), SmartHomeUnits.IRRADIANCE);
    intensityMap.put(ImperialUnits.getInstance(), SmartHomeUnits.IRRADIANCE);
    dimensionMap.put(Intensity.class, intensityMap);

    Map<SystemOfUnits, Unit<? extends Quantity<?>>> percentMap = new HashMap<>();
    percentMap.put(SIUnits.getInstance(), SmartHomeUnits.ONE);
    percentMap.put(ImperialUnits.getInstance(), SmartHomeUnits.ONE);
    dimensionMap.put(Dimensionless.class, percentMap);

    Map<SystemOfUnits, Unit<? extends Quantity<?>>> angleMap = new HashMap<>();
    angleMap.put(SIUnits.getInstance(), SmartHomeUnits.DEGREE_ANGLE);
    angleMap.put(ImperialUnits.getInstance(), SmartHomeUnits.DEGREE_ANGLE);
    dimensionMap.put(Angle.class, angleMap);
}
 
Example #23
Source File: MeteoBlueHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private State getStateForType(String type, BigDecimal value) {
    State state = new DecimalType(value);

    if (type.equals("Number:Temperature")) {
        state = new QuantityType<Temperature>(value, SIUnits.CELSIUS);
    } else if (type.equals("Number:Length")) {
        state = new QuantityType<Length>(value, MILLI(SIUnits.METRE));
    } else if (type.equals("Number:Pressure")) {
        state = new QuantityType<Pressure>(value, HECTO(SIUnits.PASCAL));
    } else if (type.equals("Number:Speed")) {
        state = new QuantityType<Speed>(value, SIUnits.KILOMETRE_PER_HOUR);
    }

    return state;
}
 
Example #24
Source File: GeometryCalculations.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * Build geometries with the provided coordinate at the center. The width of the geometry is twice
 * the distance provided. More than one geometry is return when passing the date line.
 *
 * @param distances [x,y] = [longitude, latitude]
 * @param unit
 * @param coordinate
 * @return the geometries that were built
 */
public List<Geometry> buildSurroundingGeometries(
    final double[] distances,
    final Unit<Length> unit,
    final Coordinate coordinate) {
  final List<Geometry> geos = new LinkedList<>();
  final GeodeticCalculator geoCalc = new GeodeticCalculator();
  geoCalc.setStartingGeographicPoint(coordinate.x, coordinate.y);
  try {
    geoCalc.setDirection(0, unit.getConverterTo(Units.METRE).convert(distances[1]));
    final DirectPosition north = geoCalc.getDestinationPosition();
    geoCalc.setDirection(90, unit.getConverterTo(Units.METRE).convert(distances[0]));
    final DirectPosition east = geoCalc.getDestinationPosition();
    geoCalc.setStartingGeographicPoint(coordinate.x, coordinate.y);
    geoCalc.setDirection(-90, unit.getConverterTo(Units.METRE).convert(distances[0]));
    final DirectPosition west = geoCalc.getDestinationPosition();
    geoCalc.setDirection(180, unit.getConverterTo(Units.METRE).convert(distances[1]));
    final DirectPosition south = geoCalc.getDestinationPosition();

    final double x1 = west.getOrdinate(0);
    final double x2 = east.getOrdinate(0);
    final double y1 = north.getOrdinate(1);
    final double y2 = south.getOrdinate(1);

    handleBoundaries(geos, coordinate, x1, x2, y1, y2);
    return geos;
  } catch (final TransformException ex) {
    LOGGER.error("Unable to build geometry", ex);
  }

  return null;
}
 
Example #25
Source File: OrthodromicDistancePartitioner.java    From geowave with Apache License 2.0 5 votes vote down vote up
public OrthodromicDistancePartitioner(
    final CoordinateReferenceSystem crs,
    final CommonIndexModel indexModel,
    final DimensionExtractor<T> dimensionExtractor,
    final double[] distancePerDimension,
    final Unit<Length> geometricDistanceUnit) {
  super(distancePerDimension);
  this.crs = crs;
  this.crsName = crs.getIdentifiers().iterator().next().toString();
  this.geometricDistanceUnit = geometricDistanceUnit;
  this.dimensionExtractor = dimensionExtractor;
  initIndex(indexModel, distancePerDimension);
}
 
Example #26
Source File: ScalarTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests {@link Scalar#multiply(Number)} and {@link Scalar#divide(Number)}.
 * Those tests depend on proper working of {@link Scalar#create(double, Unit)}.
 */
@Test
public void testMultiplyDivideNumber() {
    final Quantity<Length> q1 = new Scalar.Length(24, Units.KILOMETRE);
    assertSame(q1, q1.multiply(1));
    assertSame(q1, q1.divide  (1));

    final Quantity<Length> q2 = q1.multiply(2);
    assertSame  ("unit",  Units.KILOMETRE, q2.getUnit());
    assertEquals("value", 48, q2.getValue().doubleValue(), STRICT);

    final Quantity<Length> q3 = q1.divide(3);
    assertSame  ("unit",  Units.KILOMETRE, q3.getUnit());
    assertEquals("value", 8, q3.getValue().doubleValue(), STRICT);
}
 
Example #27
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 #28
Source File: FranceGeocentricInterpolationTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies the envelope and the interpolation performed by the given grid.
 *
 * @throws TransformException if an error occurred while computing the envelope.
 */
private static void verifyGrid(final DatumShiftGridFile<Angle,Length> grid) throws TransformException {
    final Envelope envelope = grid.getDomainOfValidity();
    assertEquals("xmin",  2.2, envelope.getMinimum(0), 1E-12);
    assertEquals("xmax",  2.5, envelope.getMaximum(0), 1E-12);
    assertEquals("ymin", 48.5, envelope.getMinimum(1), 1E-12);
    assertEquals("ymax", 49.0, envelope.getMaximum(1), 1E-12);
    /*
     * The values in the NTG_88 document are:
     *
     * (gridX=2, gridY=3)  00002    2.400000000   48.800000000  -168.252   -58.630   320.170  01   2314
     * (gridX=2, gridY=4)  00002    2.400000000   48.900000000  -168.275   -58.606   320.189  01   2314
     * (gridX=3, gridY=3)  00002    2.500000000   48.800000000  -168.204   -58.594   320.125  01   2314
     * (gridX=3, gridY=4)  00002    2.500000000   48.900000000  -168.253   -58.554   320.165  01   2314
     *
     * Directions (signs) are reversed compared to NTG_88 document.
     */
    assertEquals("translationDimensions", 3, grid.getTranslationDimensions());
    assertEquals("grid.accuracy",      0.05, grid.accuracy,              STRICT);
    assertEquals("getCellValue",    168.196, grid.getCellValue(0, 2, 1), STRICT);
    assertEquals("getCellValue",     58.778, grid.getCellValue(1, 2, 1), STRICT);
    assertEquals("getCellValue",   -320.127, grid.getCellValue(2, 2, 1), STRICT);
    /*
     * Interpolate the (ΔX, ΔY, ΔZ) at a point.
     * Directions (signs) are reversed compared to NTG_88 document.
     */
    final double[] expected = {
         168.253,       // ΔX: Toward prime meridian
          58.609,       // ΔY: Toward 90° east
        -320.170        // ΔZ: Toward north pole
    };
    final double[] point  = samplePoint(3);
    final double[] vector = grid.interpolateAt(point[0], point[1]);
    assertArrayEquals("(ΔX, ΔY, ΔZ)", expected, vector, 0.0005);
}
 
Example #29
Source File: MetadataBuilder.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the degree of detail in the given dimension.
 * This method does nothing if the given resolution if NaN or infinite.
 * Storage location is:
 *
 * <ul>
 *   <li>{@code metadata/spatialRepresentationInfo/axisDimensionProperties/resolution}</li>
 * </ul>
 *
 * @param  dimension   the axis dimension.
 * @param  resolution  the degree of detail in the grid dataset, or NaN for no-operation.
 * @param  unit        the resolution unit, of {@code null} if unknown.
 */
public final void setAxisResolution(final int dimension, double resolution, final Unit<?> unit) {
    if (Double.isFinite(resolution)) {
        /*
         * Value should be a Quantity<?>. Since GeoAPI does not yet allow that,
         * we convert to metres for now. Future version should store the value
         * as-is with its unit of measurement (TODO).
         */
        if (Units.isLinear(unit)) {
            resolution = unit.asType(Length.class).getConverterTo(Units.METRE).convert(resolution);
        }
        axis(dimension).setResolution(shared(resolution));
    }
}
 
Example #30
Source File: DefaultEllipsoid.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the second defining parameter value, either the inverse of the flattening
 * value or the semi minor axis value, according to what have been defined in the
 * second defining parameter given. This is for JAXB unmarshalling process only.
 *
 * @see #setSemiMajorAxisMeasure(Measure)
 * @see #afterUnmarshal(Unmarshaller, Object)
 */
private void setSecondDefiningParameter(SecondDefiningParameter second) {
    if (second.secondDefiningParameter != null) {
        second = second.secondDefiningParameter;
    }
    boolean duplicate = false;
    if (Boolean.TRUE.equals(second.isSphere)) {
        duplicate = (inverseFlattening != 0);
        if (!duplicate) {
            inverseFlattening = Double.POSITIVE_INFINITY;
        }
    }
    final Measure measure = second.measure;
    if (measure != null) {
        final boolean isIvfDefinitive = second.isIvfDefinitive();
        duplicate |= (isIvfDefinitive ? inverseFlattening : semiMinorAxis) != 0;
        if (!duplicate) {
            ivfDefinitive = isIvfDefinitive;
            double value = measure.value;
            if (isIvfDefinitive) {
                /*
                 * Interpreting an inverse flattening factor of 0 as synonymous of infinity
                 * is a Well-Known Text (WKT) convention, not part of GML standard. However
                 * in practice some software do that.
                 */
                if (value == 0) {
                    value = Double.POSITIVE_INFINITY;
                }
                ensureStrictlyPositive("inverseFlattening", inverseFlattening = value);
            } else {
                ensureStrictlyPositive("semiMinorAxis", semiMinorAxis = value);
                harmonizeAxisUnits(measure.getUnit(Length.class));
            }
        }
    }
    if (duplicate) {
        MetadataUtilities.propertyAlreadySet(DefaultEllipsoid.class,
                "setSecondDefiningParameter", "secondDefiningParameter");
    }
}