use of javax.measure.quantity.Angle in project sis by apache.
the class EPSGDataAccess method createPrimeMeridian.
/**
* Creates a prime meridian defining the origin from which longitude values are determined.
*
* <div class="note"><b>Example:</b>
* some EPSG codes for prime meridians are:
*
* <table class="sis" summary="EPSG codes examples">
* <tr><th>Code</th> <th>Description</th></tr>
* <tr><td>8901</td> <td>Greenwich</td></tr>
* <tr><td>8903</td> <td>Paris</td></tr>
* <tr><td>8904</td> <td>Bogota</td></tr>
* <tr><td>8905</td> <td>Madrid</td></tr>
* <tr><td>8906</td> <td>Rome</td></tr>
* </table></div>
*
* @param code value allocated by EPSG.
* @return the prime meridian for the given code.
* @throws NoSuchAuthorityCodeException if the specified {@code code} was not found.
* @throws FactoryException if the object creation failed for some other reason.
*
* @see #createGeodeticDatum(String)
* @see org.apache.sis.referencing.datum.DefaultPrimeMeridian
*/
@Override
public synchronized PrimeMeridian createPrimeMeridian(final String code) throws NoSuchAuthorityCodeException, FactoryException {
ArgumentChecks.ensureNonNull("code", code);
PrimeMeridian returnValue = null;
try (ResultSet result = executeQuery("Prime Meridian", "PRIME_MERIDIAN_CODE", "PRIME_MERIDIAN_NAME", "SELECT PRIME_MERIDIAN_CODE," + " PRIME_MERIDIAN_NAME," + " GREENWICH_LONGITUDE," + " UOM_CODE," + " REMARKS," + " DEPRECATED" + " FROM [Prime Meridian]" + " WHERE PRIME_MERIDIAN_CODE = ?", code)) {
while (result.next()) {
final Integer epsg = getInteger(code, result, 1);
final String name = getString(code, result, 2);
final double longitude = getDouble(code, result, 3);
final String unitCode = getString(code, result, 4);
final String remarks = getOptionalString(result, 5);
final boolean deprecated = getOptionalBoolean(result, 6);
final Unit<Angle> unit = owner.createUnit(unitCode).asType(Angle.class);
final PrimeMeridian primeMeridian = owner.datumFactory.createPrimeMeridian(createProperties("Prime Meridian", name, epsg, remarks, deprecated), longitude, unit);
returnValue = ensureSingleton(primeMeridian, returnValue, code);
}
} catch (SQLException exception) {
throw databaseFailure(PrimeMeridian.class, code, exception);
}
if (returnValue == null) {
throw noSuchAuthorityCode(PrimeMeridian.class, code);
}
return returnValue;
}
use of javax.measure.quantity.Angle in project sis by apache.
the class DefaultPrimeMeridian method formatTo.
/**
* Formats this prime meridian as a <cite>Well Known Text</cite> {@code PrimeMeridian[…]} element.
*
* @return {@code "PrimeMeridian"} (WKT 2) or {@code "PrimeM"} (WKT 1).
*
* @see <a href="http://docs.opengeospatial.org/is/12-063r5/12-063r5.html#53">WKT 2 specification §8.2.2</a>
*/
@Override
protected String formatTo(final Formatter formatter) {
super.formatTo(formatter);
final Convention convention = formatter.getConvention();
final boolean isWKT1 = (convention.majorVersion() == 1);
final Unit<Angle> contextualUnit = formatter.toContextualUnit(Units.DEGREE);
Unit<Angle> unit = contextualUnit;
if (!isWKT1) {
unit = getAngularUnit();
if (convention != Convention.INTERNAL) {
unit = WKTUtilities.toFormattable(unit);
}
}
formatter.append(getGreenwichLongitude(unit));
if (isWKT1) {
return WKTKeywords.PrimeM;
}
if (!convention.isSimplified() || !contextualUnit.equals(unit) || beConservative(formatter, contextualUnit)) {
formatter.append(unit);
}
return formatter.shortOrLong(WKTKeywords.PrimeM, WKTKeywords.PrimeMeridian);
}
use of javax.measure.quantity.Angle in project sis by apache.
the class FranceGeocentricInterpolation method load.
/**
* Unconditionally loads the grid for the given file without in-memory compression.
*
* @param in reader of the RGF93 datum shift file.
* @param file path to the file being read, used only for error reporting.
* @throws IOException if an I/O error occurred.
* @throws NumberFormatException if a number can not be parsed.
* @throws NoSuchElementException if a data line is missing a value.
* @throws FactoryException if an problem is found with the file content.
* @throws ArithmeticException if the width or the height exceed the integer capacity.
*/
static DatumShiftGridFile.Float<Angle, Length> load(final BufferedReader in, final Path file) throws IOException, FactoryException, NoninvertibleTransformException {
DatumShiftGridFile.Float<Angle, Length> grid = null;
double x0 = 0;
double xf = 0;
double y0 = 0;
double yf = 0;
double Δx = 0;
double Δy = 0;
int nx = 0;
int ny = 0;
/*
* The header should be like below, but the only essential line for this class is the one
* starting with "GR3D1". We also check that "GR3D2" declares the expected interpolation.
*
* GR3D 002024 024 20370201
* GR3D1 -5.5000 10.0000 41.0000 52.0000 .1000 .1000
* GR3D2 INTERPOLATION BILINEAIRE
* GR3D3 PREC CM 01:5 02:10 03:20 04:50 99>100
*/
String line;
while (true) {
line = in.readLine();
if (line == null) {
throw new EOFException(Errors.format(Errors.Keys.UnexpectedEndOfFile_1, file));
}
final int length = CharSequences.skipTrailingWhitespaces(line, 0, line.length());
if (length <= 0) {
// Skip empty lines.
continue;
}
int p = CharSequences.skipLeadingWhitespaces(line, 0, length);
if (line.charAt(p) == '#') {
// Skip comment lines (not officially part of the format).
continue;
}
if (!line.regionMatches(true, p, HEADER, 0, HEADER.length())) {
// End of header.
break;
}
if ((p += HEADER.length()) < length) {
final char c = line.charAt(p);
p = CharSequences.skipLeadingWhitespaces(line, p + 1, length);
switch(c) {
case '1':
{
if (grid != null) {
throw new FactoryException(Errors.format(Errors.Keys.DuplicatedElement_1, HEADER));
}
final double[] gridGeometry = CharSequences.parseDoubles(line.substring(p, length), ' ');
if (gridGeometry.length == 6) {
x0 = gridGeometry[0];
xf = gridGeometry[1];
y0 = gridGeometry[2];
yf = gridGeometry[3];
Δx = gridGeometry[4];
Δy = gridGeometry[5];
nx = Math.toIntExact(Math.round((xf - x0) / Δx + 1));
ny = Math.toIntExact(Math.round((yf - y0) / Δy + 1));
grid = new DatumShiftGridFile.Float<>(3, Units.DEGREE, Units.METRE, false, x0, y0, Δx, Δy, nx, ny, PARAMETERS, file);
}
break;
}
case '2':
{
final String interp = line.substring(p, length);
if (!interp.matches("(?i)INTERPOLATION[^A-Z]+BILINEAIRE")) {
final LogRecord record = Errors.getResources((Locale) null).getLogRecord(Level.WARNING, Errors.Keys.UnsupportedInterpolation_1, interp);
record.setLoggerName(Loggers.COORDINATE_OPERATION);
Logging.log(FranceGeocentricInterpolation.class, "createMathTransform", record);
// We declare 'createMathTransform' method because it is closer to public API.
}
break;
}
}
}
}
if (grid == null) {
throw new FactoryException(Errors.format(Errors.Keys.CanNotParseFile_2, HEADER, file));
}
/*
* Loads the data with the sign of all offsets reversed. Data columns are
*
* (unknown), longitude, latitude, tX, tY, tZ, accuracy code, data sheet (ignored)
*
* where the longitude and latitude values are in RGF93 system.
* Example:
*
* 00002 -5.500000000 41.000000000 -165.027 -67.100 315.813 99 -0158
* 00002 -5.500000000 41.100000000 -165.169 -66.948 316.007 99 -0157
* 00002 -5.500000000 41.200000000 -165.312 -66.796 316.200 99 -0157
*
* Translation values in the IGN file are from NTF to RGF93, but Apache SIS implementation needs
* the opposite direction (from RGF93 to NTF). The reason is that SIS expect the source datum to
* be the datum in which longitude and latitude values are expressed.
*/
final float[] tX = grid.offsets[0];
final float[] tY = grid.offsets[1];
final float[] tZ = grid.offsets[2];
do {
final StringTokenizer t = new StringTokenizer(line.trim());
// Ignored
t.nextToken();
// Longitude in degrees
final double x = Double.parseDouble(t.nextToken());
// Latitude in degrees
final double y = Double.parseDouble(t.nextToken());
// Column index
final int i = Math.toIntExact(Math.round((x - x0) / Δx));
// Row index
final int j = Math.toIntExact(Math.round((y - y0) / Δy));
if (i < 0 || i >= nx) {
throw new FactoryException(Errors.format(Errors.Keys.ValueOutOfRange_4, "x", x, x0, xf));
}
if (j < 0 || j >= ny) {
throw new FactoryException(Errors.format(Errors.Keys.ValueOutOfRange_4, "y", y, y0, yf));
}
final int p = j * nx + i;
if (!Double.isNaN(tX[p]) || !Double.isNaN(tY[p]) || !Double.isNaN(tZ[p])) {
throw new FactoryException(Errors.format(Errors.Keys.ValueAlreadyDefined_1, x + ", " + y));
}
// See javadoc for the reason why we reverse the sign.
tX[p] = -parseFloat(t.nextToken());
tY[p] = -parseFloat(t.nextToken());
tZ[p] = -parseFloat(t.nextToken());
final double accuracy = ACCURACY[Math.min(ACCURACY.length - 1, Math.max(0, Integer.parseInt(t.nextToken()) - 1))];
if (!(accuracy >= grid.accuracy)) {
// Use '!' for replacing the initial NaN.
grid.accuracy = accuracy;
}
} while ((line = in.readLine()) != null);
return grid;
}
use of javax.measure.quantity.Angle in project sis by apache.
the class NTv2Test method testRGF93.
/**
* Implementation of {@link #testLoader()} and {@link #testRGF93(Path)}.
*
* @param xmin negative of value of {@code "W_LONG"} record.
* @param xmax negative of value of {@code "E_LONG"} record.
* @param ymin value of the {@code "S_LAT"} record.
* @param ymax value of the {@code "N_LAT"} record.
*/
private static void testRGF93(final Path file, final double xmin, final double xmax, final double ymin, final double ymax) throws IOException, FactoryException, TransformException {
final double cellSize = 360;
final DatumShiftGridFile<Angle, Angle> grid = NTv2.getOrLoad(file);
assertInstanceOf("Should not be compressed.", DatumShiftGridFile.Float.class, grid);
assertEquals("coordinateUnit", Units.ARC_SECOND, grid.getCoordinateUnit());
assertEquals("translationUnit", Units.ARC_SECOND, grid.getTranslationUnit());
assertEquals("translationDimensions", 2, grid.getTranslationDimensions());
assertTrue("isCellValueRatio", grid.isCellValueRatio());
assertEquals("cellPrecision", (ACCURACY / 10) / cellSize, grid.getCellPrecision(), 0.5E-6 / cellSize);
/*
* Verify the envelope and the conversion between geographic coordinates and grid indices.
* The cells are expected to have the same size (360″ or 0.1°) in longitudes and latitudes.
*/
final Envelope envelope = grid.getDomainOfValidity();
assertEquals("xmin", xmin - cellSize / 2, envelope.getMinimum(0), STRICT);
assertEquals("xmax", xmax + cellSize / 2, envelope.getMaximum(0), STRICT);
assertEquals("ymin", ymin - cellSize / 2, envelope.getMinimum(1), STRICT);
assertEquals("ymax", ymax + cellSize / 2, envelope.getMaximum(1), STRICT);
assertMatrixEquals("coordinateToGrid", new Matrix3(-cellSize, 0, xmax, 0, +cellSize, ymin, 0, 0, 1), grid.getCoordinateToGrid().inverse().getMatrix(), STRICT);
/*
* Test the same point than FranceGeocentricInterpolationTest, which is itself derived from the
* NTG_88 guidance note. If we were using the official NTF_R93.gsb file, we would obtain after
* conversion the grid indices listed on the left side. But since we are using a sub-set of the
* grid, we rather obtain the grid indices on the right side.
*
* gridX ≈ 75.7432814 in official file, ≈ 3.7432814 in the test file.
* gridY ≈ 78.4451225 in official file, ≈ 4.4451225 in the test file.
*/
final double[] position = FranceGeocentricInterpolationTest.samplePoint(1);
final double[] expected = FranceGeocentricInterpolationTest.samplePoint(3);
final double[] indices = new double[position.length];
final double[] vector = new double[2];
for (int i = 0; i < expected.length; i++) {
position[i] *= DatumShiftGridLoader.DEGREES_TO_SECONDS;
expected[i] *= DatumShiftGridLoader.DEGREES_TO_SECONDS;
// We will test the interpolated shifts rather than final coordinates.
expected[i] -= position[i];
}
grid.getCoordinateToGrid().transform(position, 0, indices, 0, 1);
grid.interpolateInCell(indices[0], indices[1], vector);
// Was positive toward west.
vector[0] *= -cellSize;
vector[1] *= +cellSize;
assertArrayEquals("interpolateInCell", expected, vector, FranceGeocentricInterpolationTest.ANGULAR_TOLERANCE * DatumShiftGridLoader.DEGREES_TO_SECONDS);
// Same test than above, but let DatumShiftGrid do the conversions for us.
assertArrayEquals("interpolateAt", expected, grid.interpolateAt(position), FranceGeocentricInterpolationTest.ANGULAR_TOLERANCE * DatumShiftGridLoader.DEGREES_TO_SECONDS);
assertSame("Grid should be cached.", grid, NTv2.getOrLoad(file));
}
use of javax.measure.quantity.Angle in project sis by apache.
the class Proj4 method definition.
/**
* Infers a {@literal Proj.4} definition from the given projected, geographic or geocentric coordinate reference system.
* This method does not need the Proj.4 native library; it can be used in a pure Java application.
* However the returned definition string may differ depending on whether the Proj.4 library is available or not.
*
* @param crs the coordinate reference system for which to create a Proj.4 definition.
* @return the definition of the given CRS in a Proj.4 format.
* @throws FactoryException if the Proj.4 definition string can not be created from the given CRS.
*/
public static String definition(final CoordinateReferenceSystem crs) throws FactoryException {
ArgumentChecks.ensureNonNull("crs", crs);
/*
* If the given CRS object is associated to a Proj.4 structure, let Proj.4 formats itself
* the definition string. Note that this operation may fail if there is no Proj.4 library
* in the current system, or no JNI bindings to that library.
*/
try {
for (final Identifier id : crs.getIdentifiers()) {
if (id instanceof PJ) {
return ((PJ) id).getCode();
}
}
} catch (UnsatisfiedLinkError e) {
// Thrown the first time that we try to use the library.
Logging.unexpectedException(Logging.getLogger(Modules.GDAL), Proj4.class, "definition", e);
} catch (NoClassDefFoundError e) {
// Thrown on all attempts after the first one.
Logging.recoverableException(Logging.getLogger(Modules.GDAL), Proj4.class, "definition", e);
}
/*
* If we found no Proj.4 structure, formats the definition string ourself. The string may differ from
* what Proj.4 would have given. In particular, we do not provide "+init=" or "+datum=" parameter.
* But the definition should still be semantically equivalent.
*/
final String method;
final GeodeticDatum datum;
final ParameterValueGroup parameters;
final CoordinateSystem cs = crs.getCoordinateSystem();
if (crs instanceof GeodeticCRS) {
if (cs instanceof EllipsoidalCS) {
method = "latlon";
} else if (cs instanceof CartesianCS) {
method = "geocent";
} else {
throw new FactoryException(Errors.format(Errors.Keys.UnsupportedCoordinateSystem_1, cs.getClass()));
}
datum = ((GeodeticCRS) crs).getDatum();
parameters = null;
} else if (crs instanceof ProjectedCRS) {
Projection c = ((ProjectedCRS) crs).getConversionFromBase();
datum = ((ProjectedCRS) crs).getDatum();
method = name(c.getMethod());
parameters = c.getParameterValues();
} else {
throw new FactoryException(Errors.format(Errors.Keys.UnsupportedType_1, crs.getClass()));
}
/*
* Append the map projection parameters. Those parameters may include axis lengths (a and b),
* but not necessarily. If axis lengths are specified, then we will ignore the Ellipsoid instance
* associated to the CRS.
*/
final StringBuilder definition = new StringBuilder(100);
definition.append(Proj4Factory.PROJ_PARAM).append(method);
boolean hasSemiMajor = false;
boolean hasSemiMinor = false;
if (parameters != null) {
definition.append(Proj4Factory.STANDARD_OPTIONS);
for (final GeneralParameterValue parameter : parameters.values()) {
if (parameter instanceof ParameterValue<?>) {
final ParameterValue<?> pv = (ParameterValue<?>) parameter;
final Object value;
Unit<?> unit = pv.getUnit();
if (unit != null) {
unit = Units.isAngular(unit) ? Units.DEGREE : unit.getSystemUnit();
// Always in metres or degrees.
value = pv.doubleValue(unit);
} else {
value = pv.getValue();
if (value == null) {
continue;
}
}
final String pn = name(parameter.getDescriptor());
hasSemiMajor |= pn.equals("a");
hasSemiMinor |= pn.equals("b");
definition.append(" +").append(pn).append('=').append(value);
}
}
}
/*
* Append datum information: axis lengths if they were not part of the parameters, then prime meridian.
*/
final Ellipsoid ellipsoid = datum.getEllipsoid();
if (!hasSemiMajor)
definition.append(" +a=").append(ellipsoid.getSemiMajorAxis());
if (!hasSemiMinor)
definition.append(" +b=").append(ellipsoid.getSemiMinorAxis());
final PrimeMeridian pm = datum.getPrimeMeridian();
if (pm != null) {
double lon = pm.getGreenwichLongitude();
final Unit<Angle> unit = pm.getAngularUnit();
if (unit != null) {
lon = unit.getConverterTo(Units.DEGREE).convert(lon);
}
definition.append(" +pm=").append(lon);
}
/*
* Appends axis directions. This method always format a vertical direction (up or down)
* even if the coordinate system is two-dimensional, because Proj.4 seems to require it.
* Also extract axis units in the process.
*/
// Horizontal at index 0, vertical at index 1.
final Unit<?>[] units = new Unit<?>[2];
boolean validCS = true;
definition.append(' ').append(Proj4Factory.AXIS_ORDER_PARAM);
final int dimension = Math.min(cs.getDimension(), 3);
boolean hasVertical = false;
for (int i = 0; i < dimension; i++) {
final CoordinateSystemAxis axis = cs.getAxis(i);
final AxisDirection dir = axis.getDirection();
int unitIndex = 0;
if (!AxisDirections.isCardinal(dir)) {
if (!AxisDirections.isVertical(dir)) {
throw new FactoryException(Errors.format(Errors.Keys.UnsupportedAxisDirection_1, dir));
}
hasVertical = true;
unitIndex = 1;
}
final Unit<?> old = units[unitIndex];
units[unitIndex] = axis.getUnit();
validCS &= (old == null || old.equals(units[unitIndex]));
definition.appendCodePoint(Character.toLowerCase(dir.name().codePointAt(0)));
}
if (!hasVertical && dimension < 3) {
// Add a UP direction if not already present.
definition.append('u');
}
/*
* Append units of measurement, then verify the coordinate system validity.
*/
for (int i = 0; i < units.length; i++) {
final Unit<?> unit = units[i];
if (unit != null && !unit.equals(Units.DEGREE) && !unit.equals(Units.METRE)) {
validCS &= Units.isLinear(unit);
definition.append(" +");
// "+vto_meter" parameter.
if (i == 1)
definition.append('v');
definition.append("to_meter=").append(Units.toStandardUnit(unit));
}
}
/*
* Append the "+towgs84" element if any. This is the last piece of information.
* Note that the use of a "+towgs84" parameter is an "early binding" approach,
* which is usually not recommended. But Proj4 works that way.
*/
if (validCS) {
if (datum instanceof DefaultGeodeticDatum) {
for (final BursaWolfParameters bwp : ((DefaultGeodeticDatum) datum).getBursaWolfParameters()) {
if (Utilities.equalsIgnoreMetadata(CommonCRS.WGS84.datum(), bwp.getTargetDatum())) {
definition.append(" +towgs84=").append(bwp.tX).append(',').append(bwp.tY).append(',').append(bwp.tZ);
if (!bwp.isTranslation()) {
definition.append(',').append(bwp.rX).append(',').append(bwp.rY).append(',').append(bwp.rZ).append(',').append(bwp.dS);
}
break;
}
}
}
return definition.toString();
}
/*
* If we reach this point, we detected a coordinate system that we can not format as a
* Proj.4 definition string. Format an error message with axis directions and units.
*/
definition.setLength(0);
definition.append('(');
for (int i = 0; i < units.length; i++) {
final CoordinateSystemAxis axis = cs.getAxis(i);
if (i != 0)
definition.append(", ");
definition.append(axis.getUnit()).append(' ').append(Types.getCodeName(axis.getDirection()));
}
throw new FactoryException(Errors.format(Errors.Keys.IllegalCoordinateSystem_1, definition.append(')')));
}
Aggregations