Search in sources :

Example 21 with Unit

use of javax.measure.Unit in project uom-se by unitsofmeasurement.

the class LocalUnitFormatParser method parseUnit.

public final Unit parseUnit() throws TokenException {
    Unit result = CompoundExpr();
    consumeToken(0);
    {
        return result;
    }
}
Also used : Unit(javax.measure.Unit) AbstractUnit(tec.uom.se.AbstractUnit)

Example 22 with Unit

use of javax.measure.Unit in project uom-se by unitsofmeasurement.

the class LocalUnitFormatParser method ExponentExpr.

public final Unit ExponentExpr() throws TokenException {
    Unit result = AbstractUnit.ONE;
    Exponent exponent = null;
    Token token = null;
    if (jj_2_2(2147483647)) {
        switch((nextTokenIndex == -1) ? jj_ntk() : nextTokenIndex) {
            case INTEGER:
                token = consumeToken(INTEGER);
                break;
            case E:
                token = consumeToken(E);
                break;
            default:
                laA[5] = genInt;
                consumeToken(-1);
                throw new TokenException();
        }
        consumeToken(CARET);
        result = AtomicExpr();
        double base;
        if (token.kind == INTEGER) {
            base = Integer.parseInt(token.image);
        } else {
            base = StrictMath.E;
        }
        {
            return result.transform(new LogConverter(base).inverse());
        }
    } else {
        switch((nextTokenIndex == -1) ? jj_ntk() : nextTokenIndex) {
            case OPEN_PAREN:
            case INTEGER:
            case FLOATING_POINT:
            case UNIT_IDENTIFIER:
                result = AtomicExpr();
                switch((nextTokenIndex == -1) ? jj_ntk() : nextTokenIndex) {
                    case CARET:
                    case SUPERSCRIPT_INTEGER:
                        exponent = Exp();
                        break;
                    default:
                        laA[6] = genInt;
                }
                if (exponent != null) {
                    if (exponent.pow != 1) {
                        result = result.pow(exponent.pow);
                    }
                    if (exponent.root != 1) {
                        result = result.root(exponent.root);
                    }
                }
                {
                    return result;
                }
            case LOG:
            case NAT_LOG:
                switch((nextTokenIndex == -1) ? jj_ntk() : nextTokenIndex) {
                    case LOG:
                        consumeToken(LOG);
                        switch((nextTokenIndex == -1) ? jj_ntk() : nextTokenIndex) {
                            case INTEGER:
                                token = consumeToken(INTEGER);
                                break;
                            default:
                                laA[7] = genInt;
                        }
                        break;
                    case NAT_LOG:
                        token = consumeToken(NAT_LOG);
                        break;
                    default:
                        laA[8] = genInt;
                        consumeToken(-1);
                        throw new TokenException();
                }
                consumeToken(OPEN_PAREN);
                result = AddExpr();
                consumeToken(CLOSE_PAREN);
                double base = 10;
                if (token != null) {
                    if (token.kind == INTEGER) {
                        base = Integer.parseInt(token.image);
                    } else if (token.kind == NAT_LOG) {
                        base = StrictMath.E;
                    }
                }
                {
                    return result.transform(new LogConverter(base));
                }
            default:
                laA[9] = genInt;
                consumeToken(-1);
                throw new TokenException();
        }
    }
}
Also used : LogConverter(tec.uom.se.function.LogConverter) Unit(javax.measure.Unit) AbstractUnit(tec.uom.se.AbstractUnit)

Example 23 with Unit

use of javax.measure.Unit in project sis by apache.

the class Extents method getVerticalRange.

/**
 * Returns the union of chosen vertical ranges found in the given extent, or {@code null} if none.
 * This method gives preference to heights above the Mean Sea Level when possible.
 * Depths have negative height values: if the
 * {@linkplain org.apache.sis.referencing.cs.DefaultCoordinateSystemAxis#getDirection() axis direction}
 * is toward down, then this method reverses the sign of minimum and maximum values.
 *
 * <div class="section">Multi-occurrences</div>
 * If the given {@code Extent} object contains more than one vertical extent, then this method
 * performs a choice based on the vertical datum and the unit of measurement:
 *
 * <ul class="verbose">
 *   <li><p><b>Choice based on vertical datum</b><br>
 *   Only the extents associated (indirectly, through their CRS) to the same non-null {@link VerticalDatumType}
 *   will be taken in account. If all datum types are null, then this method conservatively uses only the first
 *   vertical extent. Otherwise the datum type used for filtering the vertical extents is:</p>
 *
 *   <ul>
 *     <li>{@link VerticalDatumType#GEOIDAL} or {@link VerticalDatumType#DEPTH DEPTH} if at least one extent
 *         uses those datum types. For this method, {@code DEPTH} is considered as equivalent to {@code GEOIDAL}
 *         except for the axis direction.</li>
 *     <li>Otherwise, the first non-null datum type found in iteration order.</li>
 *   </ul>
 *
 *   <div class="note"><b>Rational:</b> like {@linkplain #getGeographicBoundingBox(Extent) geographic bounding box},
 *   the vertical range is an approximative information; the range returned by this method does not carry any
 *   information about the vertical CRS and this method does not attempt to perform coordinate transformation.
 *   But this method is more useful if the returned ranges are close to a frequently used surface, like the
 *   Mean Sea Level. The same simplification is applied in the
 *   <a href="http://docs.opengeospatial.org/is/12-063r5/12-063r5.html#31">{@code VerticalExtent} element of
 *   Well Known Text (WKT) format</a>, which specifies that <cite>“Vertical extent is an approximate description
 *   of location; heights are relative to an unspecified mean sea level.”</cite></div></li>
 *
 *   <li><p><b>Choice based on units of measurement</b><br>
 *   If, after the choice based on the vertical datum described above, there is still more than one vertical
 *   extent to consider, then the next criterion checks for the units of measurement.</p>
 *   <ul>
 *     <li>If no range specify a unit of measurement, return the first range and ignore all others.</li>
 *     <li>Otherwise take the first range having a unit of measurement. Then:<ul>
 *       <li>All other ranges having an incompatible unit of measurement will be ignored.</li>
 *       <li>All other ranges having a compatible unit of measurement will be converted to
 *           the unit of the first retained range, and their union will be computed.</li>
 *     </ul></li>
 *   </ul>
 *
 *   <div class="note"><b>Example:</b>
 *   Heights or depths are often measured using some pressure units, for example hectopascals (hPa).
 *   An {@code Extent} could contain two vertical elements: one with the height measurements in hPa,
 *   and the other element with heights transformed to metres using an empirical formula.
 *   In such case this method will select the first vertical element on the assumption that it is
 *   the "main" one that the metadata producer intended to show. Next, this method will search for
 *   other vertical elements using pressure unit. In our example there is none, but if such elements
 *   were found, this method would compute their union.</div></li>
 * </ul>
 *
 * @param  extent  the extent to convert to a vertical measurement range, or {@code null}.
 * @return a vertical measurement range created from the given extent, or {@code null} if none.
 *
 * @since 0.4
 */
public static MeasurementRange<Double> getVerticalRange(final Extent extent) {
    MeasurementRange<Double> range = null;
    VerticalDatumType selectedType = null;
    if (extent != null) {
        for (final VerticalExtent element : extent.getVerticalElements()) {
            double min = element.getMinimumValue();
            double max = element.getMaximumValue();
            final VerticalCRS crs = element.getVerticalCRS();
            VerticalDatumType type = null;
            Unit<?> unit = null;
            if (crs != null) {
                final VerticalDatum datum = crs.getDatum();
                if (datum != null) {
                    type = datum.getVerticalDatumType();
                    if (VerticalDatumType.DEPTH.equals(type)) {
                        type = VerticalDatumType.GEOIDAL;
                    }
                }
                final CoordinateSystemAxis axis = crs.getCoordinateSystem().getAxis(0);
                unit = axis.getUnit();
                if (AxisDirection.DOWN.equals(axis.getDirection())) {
                    final double tmp = min;
                    min = -max;
                    max = -tmp;
                }
            }
            if (range != null) {
                /*
                     * If the new range does not specify any datum type or unit, then we do not know how to
                     * convert the values before to perform the union operation. Conservatively do nothing.
                     */
                if (type == null || unit == null) {
                    continue;
                }
                /*
                     * If the new range is not measured relative to the same kind of surface than the previous range,
                     * then we do not know how to combine those ranges. Do nothing, unless the new range is a Mean Sea
                     * Level Height in which case we forget all previous ranges and use the new one instead.
                     */
                if (!type.equals(selectedType)) {
                    if (!type.equals(VerticalDatumType.GEOIDAL)) {
                        continue;
                    }
                } else if (selectedType != null) {
                    /*
                         * If previous range did not specify any unit, then unconditionally replace it by
                         * the new range since it provides more information. If both ranges specify units,
                         * then we will compute the union if we can, or ignore the new range otherwise.
                         */
                    final Unit<?> previous = range.unit();
                    if (previous != null) {
                        if (previous.isCompatible(unit)) {
                            range = (MeasurementRange<Double>) range.union(MeasurementRange.create(min, true, max, true, unit));
                        }
                        continue;
                    }
                }
            }
            range = MeasurementRange.create(min, true, max, true, unit);
            selectedType = type;
        }
    }
    return range;
}
Also used : MeasurementRange(org.apache.sis.measure.MeasurementRange) VerticalDatumType(org.opengis.referencing.datum.VerticalDatumType) VerticalExtent(org.opengis.metadata.extent.VerticalExtent) VerticalCRS(org.opengis.referencing.crs.VerticalCRS) CoordinateSystemAxis(org.opengis.referencing.cs.CoordinateSystemAxis) VerticalDatum(org.opengis.referencing.datum.VerticalDatum) Unit(javax.measure.Unit)

Example 24 with Unit

use of javax.measure.Unit in project com.revolsys.open by revolsys.

the class MeasureOverlay method setMeasureGeometry.

public void setMeasureGeometry(Geometry measureGeometry) {
    if (measureGeometry == null) {
        measureGeometry = EMPTY_GEOMETRY;
    }
    if (measureGeometry != this.measureGeometry) {
        this.measureGeometry = measureGeometry;
        if (measureGeometry == null) {
            this.measureLabel = "";
        } else {
            Unit<Length> lengthUnit = Units.METRE;
            final CoordinateSystem coordinateSystem = measureGeometry.getCoordinateSystem();
            if (coordinateSystem instanceof ProjectedCoordinateSystem) {
                lengthUnit = coordinateSystem.getLengthUnit();
            }
            final double length = measureGeometry.getLength(lengthUnit);
            @SuppressWarnings("unchecked") final Unit<Area> areaUnit = (Unit<Area>) lengthUnit.multiply(lengthUnit);
            final double area = measureGeometry.getArea(areaUnit);
            final String unitString = lengthUnit.toString();
            synchronized (MEASURE_FORMAT) {
                final StringBuilder label = new StringBuilder();
                final String lengthString = MEASURE_FORMAT.format(Doubles.makePrecise(100, length));
                label.append(lengthString);
                label.append(unitString);
                if (this.measureDataType == DataTypes.POLYGON && measureGeometry instanceof Polygon) {
                    final String areaString = MEASURE_FORMAT.format(Doubles.makePrecise(100, area));
                    label.append(" \n");
                    label.append(areaString);
                    label.append(unitString);
                    label.append('\u00B2');
                }
                this.measureLabel = label.toString();
            }
        }
        setXorGeometry(null);
    }
}
Also used : Area(javax.measure.quantity.Area) Length(javax.measure.quantity.Length) CoordinateSystem(com.revolsys.geometry.cs.CoordinateSystem) ProjectedCoordinateSystem(com.revolsys.geometry.cs.ProjectedCoordinateSystem) ProjectedCoordinateSystem(com.revolsys.geometry.cs.ProjectedCoordinateSystem) LineString(com.revolsys.geometry.model.LineString) Unit(javax.measure.Unit) Polygon(com.revolsys.geometry.model.Polygon)

Example 25 with Unit

use of javax.measure.Unit in project n2a by frothga.

the class ExportJob method biophysicalUnits.

public String biophysicalUnits(String value) {
    value = value.trim();
    int unitIndex = findUnits(value);
    // no number or no units, so probably something else
    if (unitIndex == 0 || unitIndex >= value.length())
        return value;
    String unitString = value.substring(unitIndex).trim();
    String numberString = value.substring(0, unitIndex);
    Unit<?> unit;
    try {
        unit = UCUM.parse(unitString);
    } catch (Exception e) {
        return value;
    }
    double v = 0;
    try {
        v = Double.valueOf(numberString);
    } catch (NumberFormatException error) {
        return value;
    }
    // Determine power in numberString itself
    double power = 1;
    if (v != 0)
        power = Math.pow(10, Math.floor((Math.getExponent(v) + 1) / baseRatio));
    // Find closest matching unit
    Entry<Unit<?>, String> closest = null;
    // like closest, but only ratios >= 1
    Entry<Unit<?>, String> closestAbove = null;
    double closestRatio = Double.POSITIVE_INFINITY;
    double closestAboveRatio = Double.POSITIVE_INFINITY;
    for (Entry<Unit<?>, String> e : nmlUnits.entrySet()) {
        Unit<?> u = e.getKey();
        if (u.isCompatible(unit)) {
            try {
                UnitConverter converter = unit.getConverterToAny(u);
                double ratio = converter.convert(power);
                if (ratio < 1) {
                    ratio = 1 / ratio;
                } else {
                    if (ratio < closestAboveRatio) {
                        closestAboveRatio = ratio;
                        closestAbove = e;
                    }
                }
                if (ratio < closestRatio) {
                    closestRatio = ratio;
                    closest = e;
                }
            } catch (UnconvertibleException | IncommensurableException e1) {
            }
        }
    }
    if (closest == null) {
        // completely give up on conversion
        return value;
    }
    if (closestAboveRatio <= 1000 + epsilon)
        closest = closestAbove;
    try {
        UnitConverter converter = unit.getConverterToAny(closest.getKey());
        v = converter.convert(v);
    } catch (Exception error) {
    }
    return print(v) + closest.getValue();
}
Also used : IncommensurableException(javax.measure.IncommensurableException) UnitConverter(javax.measure.UnitConverter) UnconvertibleException(javax.measure.UnconvertibleException) Unit(javax.measure.Unit) IncommensurableException(javax.measure.IncommensurableException) UnconvertibleException(javax.measure.UnconvertibleException) ParseException(gov.sandia.n2a.language.ParseException)

Aggregations

Unit (javax.measure.Unit)52 AbstractUnit (tech.units.indriya.AbstractUnit)12 AbstractUnit (tec.uom.se.AbstractUnit)11 UnitConverter (javax.measure.UnitConverter)5 Test (org.junit.Test)5 CoordinateSystem (com.revolsys.geometry.cs.CoordinateSystem)4 ProjectedCoordinateSystem (com.revolsys.geometry.cs.ProjectedCoordinateSystem)4 BigDecimal (java.math.BigDecimal)4 Length (javax.measure.quantity.Length)4 CoordinateSystemAxis (org.opengis.referencing.cs.CoordinateSystemAxis)4 GeographicCoordinateSystem (com.revolsys.geometry.cs.GeographicCoordinateSystem)3 Format (java.text.Format)3 NumberFormat (java.text.NumberFormat)3 IncommensurableException (javax.measure.IncommensurableException)3 Angle (javax.measure.quantity.Angle)3 TestUnit (javax.measure.test.TestUnit)3 Test (org.junit.jupiter.api.Test)3 IdentifiedObject (org.opengis.referencing.IdentifiedObject)3 CoordinateSystem (org.opengis.referencing.cs.CoordinateSystem)3 ChainedCoordinatesOperation (com.revolsys.geometry.cs.projection.ChainedCoordinatesOperation)2