use of org.apache.sis.geometry.DirectPosition2D in project sis by apache.
the class MilitaryGridReferenceSystemTest method verifyConsistency.
/**
* Encodes random coordinates, decodes them and verifies that the results are approximatively equal
* to the original coordinates.
*
* @throws TransformException if an error occurred while computing the coordinate.
*/
@Test
@DependsOnMethod({ "testEncodeUTM", "testDecodeUTM", "testEncodeUPS", "testDecodeUPS" })
public void verifyConsistency() throws TransformException {
final Random random = TestUtilities.createRandomNumberGenerator();
final MilitaryGridReferenceSystem.Coder coder = coder();
final DirectPosition2D expected = new DirectPosition2D();
final DirectPosition2D position = new DirectPosition2D(CommonCRS.WGS84.geographic());
for (int i = 0; i < 100; i++) {
// Latitude (despite the 'x' field name)
position.x = random.nextDouble() * 180 - 90;
// Longitude (despite the 'y' field name)
position.y = random.nextDouble() * 358 - 179;
final String reference = coder.encode(position);
final DirectPosition r = decode(coder, reference);
final ProjectedCRS crs = (ProjectedCRS) r.getCoordinateReferenceSystem();
assertSame(expected, crs.getConversionFromBase().getMathTransform().transform(position, expected));
final double distance = expected.distance(r.getOrdinate(0), r.getOrdinate(1));
if (!(distance < 1.5)) {
// Use '!' for catching NaN.
final String lineSeparator = System.lineSeparator();
fail("Consistency check failed for φ = " + position.x + " and λ = " + position.y + lineSeparator + "MGRS reference = " + reference + lineSeparator + "Parsing result = " + r + lineSeparator + "Projected φ, λ = " + expected + lineSeparator + "Distance (m) = " + distance + lineSeparator);
}
}
}
use of org.apache.sis.geometry.DirectPosition2D in project sis by apache.
the class LocationServlet method init.
/**
* Read GeoRSS data (location information provide sis-location-config.xml )
* and build quad-tree.
*
* @param config
* Servlet configuration file
* @exception ServletException
* General exception for servlet
*/
@SuppressWarnings("unchecked")
public void init(ServletConfig config) throws ServletException {
this.context = config.getServletContext();
long startTime = 0;
long endTime = 0;
int capacity = -1, depth = -1;
this.qtreeIdxPath = this.context.getInitParameter("org.apache.sis.services.config.qIndexPath");
this.georssStoragePath = this.context.getInitParameter("org.apache.sis.services.config.geodataPath");
if (!this.qtreeIdxPath.endsWith("/"))
this.qtreeIdxPath += "/";
if (!this.georssStoragePath.endsWith("/"))
this.georssStoragePath += "/";
InputStream indexStream = null;
try {
indexStream = new FileInputStream(qtreeIdxPath + "node_0.txt");
} catch (FileNotFoundException e) {
System.out.println("[INFO] Existing qtree index at: [" + qtreeIdxPath + "] not found. Creating new index.");
}
if (indexStream != null) {
startTime = System.currentTimeMillis();
this.tree = QuadTreeReader.readFromFile(qtreeIdxPath, "tree_config.txt", "node_0.txt");
try {
indexStream.close();
} catch (IOException e) {
e.printStackTrace();
}
endTime = System.currentTimeMillis();
this.timeToLoad = "Quad Tree fully loaded from index files in " + Double.toString((endTime - startTime) / 1000L) + " seconds";
System.out.println("[INFO] Finished loading tree from stored index");
} else {
startTime = System.currentTimeMillis();
WireFeedInput wf = new WireFeedInput(true);
// read quad tree properties set in config xml file
InputStream configStream = null;
try {
configStream = new FileInputStream(this.context.getInitParameter("org.apache.sis.services.config.filePath"));
} catch (Exception e) {
e.printStackTrace();
}
if (configStream != null) {
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document configDoc = docBuilder.parse(configStream);
NodeList capacityNode = configDoc.getElementsByTagName("capacity");
if (capacityNode.item(0) != null) {
capacity = Integer.parseInt(capacityNode.item(0).getFirstChild().getNodeValue());
}
NodeList depthNode = configDoc.getElementsByTagName("depth");
if (depthNode.item(0) != null) {
depth = Integer.parseInt(depthNode.item(0).getFirstChild().getNodeValue());
}
// TODO make this
this.tree = new QuadTree(capacity, depth);
// configurable
NodeList urlNodes = configDoc.getElementsByTagName("url");
for (int i = 0; i < urlNodes.getLength(); i++) {
// read in georss and build tree
String georssUrlStr = urlNodes.item(i).getFirstChild().getNodeValue();
WireFeed feed = null;
try {
feed = wf.build(new XmlReader(new URL(georssUrlStr)));
} catch (Exception e) {
System.out.println("[ERROR] Error obtaining geodata url: [" + georssUrlStr + "]: Message: " + e.getMessage() + ": skipping and continuing");
continue;
}
Channel c = (Channel) feed;
List<Item> items = (List<Item>) c.getItems();
for (Item item : items) {
GeoRSSModule geoRSSModule = (GeoRSSModule) item.getModule(GeoRSSModule.GEORSS_GEORSS_URI);
if (geoRSSModule == null)
geoRSSModule = (GeoRSSModule) item.getModule(GeoRSSModule.GEORSS_GML_URI);
if (geoRSSModule == null)
geoRSSModule = (GeoRSSModule) item.getModule(GeoRSSModule.GEORSS_W3CGEO_URI);
// then discard it
if (geoRSSModule != null && geoRSSModule.getPosition() != null) {
String filename = "";
if (item.getGuid() != null)
filename = cleanStr(item.getGuid().getValue()) + ".txt";
else
filename = cleanStr(item.getLink()) + ".txt";
GeoRSSData data = new GeoRSSData(filename, new DirectPosition2D(geoRSSModule.getPosition().getLongitude(), geoRSSModule.getPosition().getLatitude()));
if (this.tree.insert(data)) {
data.saveToFile(item, geoRSSModule, georssStoragePath);
} else {
System.out.println("[INFO] Unable to store data at location " + data.getLatLon().y + ", " + data.getLatLon().x + " under filename " + data.getFileName());
}
}
}
}
configStream.close();
endTime = System.currentTimeMillis();
this.timeToLoad = "Quad Tree fully loaded from retrieving GeoRSS files over the network in " + Double.toString((endTime - startTime) / 1000L) + " seconds";
QuadTreeWriter.writeTreeToFile(tree, qtreeIdxPath);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
} else {
throw new ServletException("Unable to read location service XML config: null!");
}
}
}
use of org.apache.sis.geometry.DirectPosition2D in project sis by apache.
the class AffineTransform2D method transform.
/**
* Transforms the specified {@code ptSrc} and stores the result in {@code ptDst}.
*/
@Override
public final DirectPosition transform(final DirectPosition ptSrc, DirectPosition ptDst) {
ensureDimensionMatches("ptSrc", 2, ptSrc);
/*
* Try to write directly in the destination point if possible. Following
* code avoid the creation of temporary objects (except if ptDst is null).
*/
if (ptDst == ptSrc) {
if (ptSrc instanceof Point2D) {
final Point2D point = (Point2D) ptSrc;
super.transform(point, point);
return ptSrc;
}
} else {
if (ptDst == null) {
final DirectPosition2D point = new DirectPosition2D(ptSrc.getOrdinate(0), ptSrc.getOrdinate(1));
super.transform(point, point);
return point;
}
ensureDimensionMatches("ptDst", 2, ptDst);
if (ptDst instanceof Point2D) {
final Point2D point = (Point2D) ptDst;
point.setLocation(ptSrc.getOrdinate(0), ptSrc.getOrdinate(1));
super.transform(point, point);
return ptDst;
}
}
/*
* At this point, we have no choice to create a temporary Point2D.
*/
final Point2D.Double point = new Point2D.Double(ptSrc.getOrdinate(0), ptSrc.getOrdinate(1));
super.transform(point, point);
ptDst.setOrdinate(0, point.x);
ptDst.setOrdinate(1, point.y);
return ptDst;
}
use of org.apache.sis.geometry.DirectPosition2D in project sis by apache.
the class LinearTransformBuilderTest method test2D.
/**
* Implementation of {@link #testExact2D()} and {@link #testNonExact2D()}.
*
* @param rd the random number generator to use.
* @param numPts the number of points to generate.
* @param addErrors {@code true} for adding a random error in the target points.
* @param scaleTolerance tolerance threshold for floating point comparisons.
*/
private static void test2D(final Random rd, final int numPts, final boolean addErrors, final double scaleTolerance, final double translationTolerance) throws FactoryException {
/*
* Create an AffineTransform to use as the reference implementation.
*/
final AffineTransform ref = AffineTransform.getRotateInstance(// Rotation angle
rd.nextDouble() * (2 * StrictMath.PI), // Center X
rd.nextDouble() * 30 - 12, // Center Y
rd.nextDouble() * 10 - 8);
final Map<DirectPosition2D, DirectPosition2D> pos = new HashMap<>(numPts);
for (int i = 0; i < numPts; i++) {
final DirectPosition2D src = new DirectPosition2D(rd.nextDouble() * 100 - 50, rd.nextDouble() * 200 - 75);
final DirectPosition2D tgt = new DirectPosition2D();
assertSame(tgt, ref.transform(src, tgt));
if (addErrors) {
tgt.x += rd.nextDouble() * 10 - 5;
tgt.y += rd.nextDouble() * 10 - 5;
}
assertNull(pos.put(src, tgt));
}
/*
* Create the fitted transform to test.
*/
final LinearTransformBuilder builder = new LinearTransformBuilder();
builder.setControlPoints(pos);
final Matrix m = builder.create(null).getMatrix();
/*
* Compare the coefficients with the reference implementation.
*/
assertEquals("m₀₀", ref.getScaleX(), m.getElement(0, 0), scaleTolerance);
assertEquals("m₀₁", ref.getShearX(), m.getElement(0, 1), scaleTolerance);
assertEquals("m₀₂", ref.getTranslateX(), m.getElement(0, 2), translationTolerance);
assertEquals("m₁₀", ref.getShearY(), m.getElement(1, 0), scaleTolerance);
assertEquals("m₁₁", ref.getScaleY(), m.getElement(1, 1), scaleTolerance);
assertEquals("m₁₂", ref.getTranslateY(), m.getElement(1, 2), translationTolerance);
assertArrayEquals("correlation", new double[] { 1, 1 }, builder.correlation(), scaleTolerance);
}
use of org.apache.sis.geometry.DirectPosition2D in project sis by apache.
the class Proj4FactoryTest method testMercatorProjection.
/**
* Tests EPSG:3395 on a point.
*/
static void testMercatorProjection(final MathTransform mt) throws TransformException {
DirectPosition pt = new DirectPosition2D(20, 40);
pt = mt.transform(pt, pt);
assertEquals("Easting", 2226389.816, pt.getOrdinate(0), 0.01);
assertEquals("Northing", 4838471.398, pt.getOrdinate(1), 0.01);
}
Aggregations