org.locationtech.spatial4j.shape.Shape Java Examples
The following examples show how to use
org.locationtech.spatial4j.shape.Shape.
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: DateNRStrategyTest.java From lucene-solr with Apache License 2.0 | 6 votes |
private Shape randomShape() { Calendar cal1 = randomCalendar(); UnitNRShape s1 = tree.toShape(cal1); if (rarely()) { return s1; } try { Calendar cal2 = randomCalendar(); UnitNRShape s2 = tree.toShape(cal2); if (cal1.compareTo(cal2) < 0) { return tree.toRangeShape(s1, s2); } else { return tree.toRangeShape(s2, s1); } } catch (IllegalArgumentException e) { assert e.getMessage().startsWith("Differing precision"); return s1; } }
Example #2
Source File: RandomSpatialOpFuzzyPrefixTreeTest.java From lucene-solr with Apache License 2.0 | 6 votes |
protected Shape gridSnap(Shape snapMe) { if (snapMe == null) return null; if (snapMe instanceof ShapePair) { ShapePair me = (ShapePair) snapMe; return new ShapePair(gridSnap(me.shape1), gridSnap(me.shape2), me.biasContainsThenWithin); } if (snapMe instanceof Point) { snapMe = snapMe.getBoundingBox(); } //The next 4 lines mimic PrefixTreeStrategy.createIndexableFields() double distErrPct = ((PrefixTreeStrategy) strategy).getDistErrPct(); double distErr = SpatialArgs.calcDistanceFromErrPct(snapMe, distErrPct, ctx); int detailLevel = grid.getLevelForDistance(distErr); CellIterator cells = grid.getTreeCellIterator(snapMe, detailLevel); //calc bounding box of cells. List<Shape> cellShapes = new ArrayList<>(1024); while (cells.hasNext()) { Cell cell = cells.next(); if (!cell.isLeaf()) continue; cellShapes.add(cell.getShape()); } return new ShapeCollection<>(cellShapes, ctx).getBoundingBox(); }
Example #3
Source File: StrategyTestCase.java From lucene-solr with Apache License 2.0 | 6 votes |
protected List<Document> getDocuments(Iterator<SpatialTestData> sampleData) { List<Document> documents = new ArrayList<>(); while (sampleData.hasNext()) { SpatialTestData data = sampleData.next(); Document document = new Document(); document.add(new StringField("id", data.id, Field.Store.YES)); document.add(new StringField("name", data.name, Field.Store.YES)); Shape shape = data.shape; shape = convertShapeFromGetDocuments(shape); if (shape != null) { for (Field f : strategy.createIndexableFields(shape)) { document.add(f); } if (storeShape)//just for diagnostics document.add(new StoredField(strategy.getFieldName(), shape.toString())); } documents.add(document); } return documents; }
Example #4
Source File: SpatialDocMaker.java From lucene-solr with Apache License 2.0 | 6 votes |
@Override public Document makeDocument() throws Exception { DocState docState = getDocState(); Document doc = super.makeDocument(); // Set SPATIAL_FIELD from body DocData docData = docState.docData; // makeDocument() resets docState.getBody() so we can't look there; look in Document String shapeStr = doc.getField(DocMaker.BODY_FIELD).stringValue(); Shape shape = makeShapeFromString(strategy, docData.getName(), shapeStr); if (shape != null) { shape = shapeConverter.convert(shape); //index for (Field f : strategy.createIndexableFields(shape)) { doc.add(f); } } return doc; }
Example #5
Source File: SpatialArgsTest.java From lucene-solr with Apache License 2.0 | 6 votes |
@Test public void calcDistanceFromErrPct() { final SpatialContext ctx = usually() ? SpatialContext.GEO : new Geo3dSpatialContextFactory().newSpatialContext(); final double DEP = 0.5;//distErrPct //the result is the diagonal distance from the center to the closest corner, // times distErrPct Shape superwide = ctx.makeRectangle(-180, 180, 0, 0); //0 distErrPct means 0 distance always assertEquals(0, SpatialArgs.calcDistanceFromErrPct(superwide, 0, ctx), 0); assertEquals(180 * DEP, SpatialArgs.calcDistanceFromErrPct(superwide, DEP, ctx), 0); Shape supertall = ctx.makeRectangle(0, 0, -90, 90); assertEquals(90 * DEP, SpatialArgs.calcDistanceFromErrPct(supertall, DEP, ctx), 0); Shape upperhalf = ctx.makeRectangle(-180, 180, 0, 90); assertEquals(45 * DEP, SpatialArgs.calcDistanceFromErrPct(upperhalf, DEP, ctx), 0.0001); Shape midCircle = ctx.makeCircle(0, 0, 45); assertEquals(60 * DEP, SpatialArgs.calcDistanceFromErrPct(midCircle, DEP, ctx), 0.0001); }
Example #6
Source File: SerializedDVStrategy.java From lucene-solr with Apache License 2.0 | 6 votes |
@Override public ShapeValues getValues(LeafReaderContext readerContext) throws IOException { final BinaryDocValues docValues = DocValues.getBinary(readerContext.reader(), fieldName); return new ShapeValues() { @Override public boolean advanceExact(int doc) throws IOException { return docValues.advanceExact(doc); } @Override public Shape value() throws IOException { BytesRef bytesRef = docValues.binaryValue(); DataInputStream dataInput = new DataInputStream(new ByteArrayInputStream(bytesRef.bytes, bytesRef.offset, bytesRef.length)); return binaryCodec.readShape(dataInput); } }; }
Example #7
Source File: SpatialExample.java From lucene-solr with Apache License 2.0 | 6 votes |
private Document newSampleDocument(int id, Shape... shapes) { Document doc = new Document(); doc.add(new StoredField("id", id)); doc.add(new NumericDocValuesField("id", id)); //Potentially more than one shape in this field is supported by some // strategies; see the javadocs of the SpatialStrategy impl to see. for (Shape shape : shapes) { for (Field f : strategy.createIndexableFields(shape)) { doc.add(f); } //store it too; the format is up to you // (assume point in this example) Point pt = (Point) shape; doc.add(new StoredField(strategy.getFieldName(), pt.getX()+" "+pt.getY())); } return doc; }
Example #8
Source File: BBoxStrategy.java From lucene-solr with Apache License 2.0 | 6 votes |
@Override public Query makeQuery(SpatialArgs args) { Shape shape = args.getShape(); if (!(shape instanceof Rectangle)) throw new UnsupportedOperationException("Can only query by Rectangle, not " + shape); Rectangle bbox = (Rectangle) shape; Query spatial; // Useful for understanding Relations: // http://edndoc.esri.com/arcsde/9.1/general_topics/understand_spatial_relations.htm SpatialOperation op = args.getOperation(); if( op == SpatialOperation.BBoxIntersects ) spatial = makeIntersects(bbox); else if( op == SpatialOperation.BBoxWithin ) spatial = makeWithin(bbox); else if( op == SpatialOperation.Contains ) spatial = makeContains(bbox); else if( op == SpatialOperation.Intersects ) spatial = makeIntersects(bbox); else if( op == SpatialOperation.IsEqualTo ) spatial = makeEquals(bbox); else if( op == SpatialOperation.IsDisjointTo ) spatial = makeDisjoint(bbox); else if( op == SpatialOperation.IsWithin ) spatial = makeWithin(bbox); else { //no Overlaps support yet throw new UnsupportedSpatialOperation(op); } return new ConstantScoreQuery(spatial); }
Example #9
Source File: RandomSpatialOpFuzzyPrefixTreeTest.java From lucene-solr with Apache License 2.0 | 6 votes |
private Shape toNonGeo(Shape shape) { if (!ctx.isGeo()) return shape;//already non-geo if (shape instanceof Rectangle) { Rectangle rect = (Rectangle) shape; if (rect.getCrossesDateLine()) { return new ShapePair( ctx2D.makeRectangle(rect.getMinX(), 180, rect.getMinY(), rect.getMaxY()), ctx2D.makeRectangle(-180, rect.getMaxX(), rect.getMinY(), rect.getMaxY()), biasContainsThenWithin); } else { return ctx2D.makeRectangle(rect.getMinX(), rect.getMaxX(), rect.getMinY(), rect.getMaxY()); } } //no need to do others; this addresses the -180/+180 ambiguity corner test problem return shape; }
Example #10
Source File: RandomSpatialOpFuzzyPrefixTreeTest.java From lucene-solr with Apache License 2.0 | 6 votes |
@Override protected Document newDoc(String id, Shape shape) { Document doc = new Document(); doc.add(new StringField("id", id, Field.Store.YES)); if (shape != null) { Collection<Shape> shapes; if (shape instanceof ShapePair) { shapes = new ArrayList<>(2); shapes.add(((ShapePair)shape).shape1); shapes.add(((ShapePair)shape).shape2); } else { shapes = Collections.singleton(shape); } for (Shape shapei : shapes) { for (Field f : strategy.createIndexableFields(shapei)) { doc.add(f); } } if (storeShape)//just for diagnostics doc.add(new StoredField(strategy.getFieldName(), shape.toString())); } return doc; }
Example #11
Source File: Geo3dRptTest.java From lucene-solr with Apache License 2.0 | 6 votes |
@Test public void testFailureLucene6535() throws IOException { setupStrategy(); final List<GeoPoint> points = new ArrayList<>(); points.add(new GeoPoint(planetModel, 18 * DEGREES_TO_RADIANS, -27 * DEGREES_TO_RADIANS)); points.add(new GeoPoint(planetModel, -57 * DEGREES_TO_RADIANS, 146 * DEGREES_TO_RADIANS)); points.add(new GeoPoint(planetModel, 14 * DEGREES_TO_RADIANS, -180 * DEGREES_TO_RADIANS)); points.add(new GeoPoint(planetModel, -15 * DEGREES_TO_RADIANS, 153 * DEGREES_TO_RADIANS)); final GeoPoint[] pathPoints = new GeoPoint[] { new GeoPoint(planetModel, 55.0 * DEGREES_TO_RADIANS, -26.0 * DEGREES_TO_RADIANS), new GeoPoint(planetModel, -90.0 * DEGREES_TO_RADIANS, 0.0), new GeoPoint(planetModel, 54.0 * DEGREES_TO_RADIANS, 165.0 * DEGREES_TO_RADIANS), new GeoPoint(planetModel, -90.0 * DEGREES_TO_RADIANS, 0.0)}; final GeoPath path = GeoPathFactory.makeGeoPath(planetModel, 29 * DEGREES_TO_RADIANS, pathPoints); final Shape shape = new Geo3dShape<>(path,ctx); final Rectangle rect = ctx.makeRectangle(131, 143, 39, 54); testOperation(rect,SpatialOperation.Intersects,shape,true); }
Example #12
Source File: SpatialUtils.java From lucene-solr with Apache License 2.0 | 6 votes |
/** * Parses a 'geom' parameter (might also be used to parse shapes for indexing). {@code geomStr} can either be WKT or * a rectangle-range syntax (see {@link #parseRectangle(String, org.locationtech.spatial4j.context.SpatialContext)}. */ public static Shape parseGeomSolrException(String geomStr, SpatialContext ctx) { if (geomStr.length() == 0) { throw new IllegalArgumentException("0-length geometry string"); } char c = geomStr.charAt(0); if (c == '[' || c == '{') { return parseRectangeSolrException(geomStr, ctx); } //TODO parse a raw point? try { return ctx.readShapeFromWkt(geomStr); } catch (ParseException e) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Expecting WKT or '[minPoint TO maxPoint]': " + e, e); } }
Example #13
Source File: Geo3dShape.java From lucene-solr with Apache License 2.0 | 6 votes |
@Override public SpatialRelation relate(Shape other) { int relationship; if (other instanceof Geo3dShape<?>) { relationship = relate((Geo3dShape<?>) other); } else if (other instanceof Rectangle) { relationship = relate((Rectangle) other); } else if (other instanceof Point) { relationship = relate((Point) other); } else { throw new RuntimeException("Unimplemented shape relationship determination: " + other.getClass()); } switch (relationship) { case GeoArea.DISJOINT: return SpatialRelation.DISJOINT; case GeoArea.OVERLAPS: return (other instanceof Point ? SpatialRelation.CONTAINS : SpatialRelation.INTERSECTS); case GeoArea.CONTAINS: return (other instanceof Point ? SpatialRelation.CONTAINS : SpatialRelation.WITHIN); case GeoArea.WITHIN: return SpatialRelation.CONTAINS; } throw new RuntimeException("Undetermined shape relationship: " + relationship); }
Example #14
Source File: DistanceStrategyTest.java From lucene-solr with Apache License 2.0 | 5 votes |
@Test public void testRecipScore() throws IOException { Point p100 = ctx.getShapeFactory().pointXY(2.02, 0.98); adoc("100", p100); Point p101 = ctx.getShapeFactory().pointXY(-1.001, 4.001); adoc("101", p101); adoc("103", (Shape)null);//test score for nothing commit(); double dist = ctx.getDistCalc().distance(p100, p101); Shape queryShape = ctx.makeCircle(2.01, 0.99, dist); checkValueSource(strategy.makeRecipDistanceValueSource(queryShape), new float[]{1.00f, 0.10f, 0f}, 0.09f); }
Example #15
Source File: ShapeRectRelationTestCase.java From lucene-solr with Apache License 2.0 | 5 votes |
@Test public void testGeoPolygonRect() { new AbstractRectIntersectionTestHelper(ctx) { @Override protected Shape generateRandomShape(Point nearP) { final Point centerPoint = randomPoint(); final int maxDistance = random().nextInt(maxRadius -20) + 20; final Circle pointZone = ctx.getShapeFactory().circle(centerPoint, maxDistance); final int vertexCount = random().nextInt(3) + 3; while (true) { ShapeFactory.PolygonBuilder builder = ctx.getShapeFactory().polygon(); for (int i = 0; i < vertexCount; i++) { final Point point = randomPointIn(pointZone); builder.pointXY(point.getX(), point.getY()); } try { return builder.build(); } catch (IllegalArgumentException e) { // This is what happens when we create a shape that is invalid. Although it is conceivable that there are cases where // the exception is thrown incorrectly, we aren't going to be able to do that in this random test. continue; } } } @Override protected Point randomPointInEmptyShape(Shape shape) { throw new IllegalStateException("unexpected; need to finish test code"); } @Override protected int getWithinMinimum(int laps) { // Long/thin so lets just find 1. return 1; } }.testRelateWithRectangle(); }
Example #16
Source File: PackedQuadPrefixTree.java From lucene-solr with Apache License 2.0 | 5 votes |
protected void buildNotRobustly(double x, double y, int level, List<Cell> matches, long term, Shape shape, int maxLevel) { double w = levelW[level] / 2; double h = levelH[level] / 2; // Z-Order // http://en.wikipedia.org/wiki/Z-order_%28curve%29 checkBattenbergNotRobustly(QUAD[0], x - w, y + h, level, matches, term, shape, maxLevel); checkBattenbergNotRobustly(QUAD[1], x + w, y + h, level, matches, term, shape, maxLevel); checkBattenbergNotRobustly(QUAD[2], x - w, y - h, level, matches, term, shape, maxLevel); checkBattenbergNotRobustly(QUAD[3], x + w, y - h, level, matches, term, shape, maxLevel); }
Example #17
Source File: SpatialFileQueryMaker.java From lucene-solr with Apache License 2.0 | 5 votes |
protected Query makeQueryFromShape(Shape shape) { SpatialArgs args = new SpatialArgs(operation, shape); if (!Double.isNaN(distErrPct)) args.setDistErrPct(distErrPct); Query filterQuery = strategy.makeQuery(args); if (score) { //wrap with distance computing query DoubleValuesSource valueSource = strategy.makeDistanceValueSource(shape.getCenter()); return new FunctionScoreQuery(filterQuery, valueSource); } else { return filterQuery; // assume constant scoring } }
Example #18
Source File: FunctionArguments.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Get the geo shape * * @param func function * @param v value * @param context * @return shape * @throws ValueExprEvaluationException */ public static Shape getShape(Function func, Value v, SpatialContext context) throws ValueExprEvaluationException { Literal wktLiteral = getLiteral(func, v, GEO.WKT_LITERAL); try { ShapeReader reader = context.getFormats().getWktReader(); return reader.read(wktLiteral.getLabel()); } catch (IOException | InvalidShapeException | ParseException e) { throw new ValueExprEvaluationException("Invalid argument for " + func.getURI() + ": " + wktLiteral, e); } }
Example #19
Source File: StrategyTestCase.java From lucene-solr with Apache License 2.0 | 5 votes |
protected void testOperation(Shape indexedShape, SpatialOperation operation, Shape queryShape, boolean match) throws IOException { assertTrue("Faulty test", operation.evaluate(indexedShape, queryShape) == match || indexedShape.equals(queryShape) && (operation == SpatialOperation.Contains || operation == SpatialOperation.IsWithin)); adoc("0", indexedShape); commit(); Query query = strategy.makeQuery(new SpatialArgs(operation, queryShape)); SearchResults got = executeQuery(query, 1); assert got.numFound <= 1 : "unclean test env"; if ((got.numFound == 1) != match) fail(operation+" I:" + indexedShape + " Q:" + queryShape); deleteAll();//clean up after ourselves }
Example #20
Source File: Geo3dShapeFactory.java From lucene-solr with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") @Override public Shape build() { GeoPolygonFactory.PolygonDescription description = new GeoPolygonFactory.PolygonDescription(points, polyHoles); GeoPolygon polygon = GeoPolygonFactory.makeGeoPolygon(planetModel, description); if (polygon == null) { throw new InvalidShapeException("Invalid polygon, all points are coplanar"); } return new Geo3dShape<>(polygon, context); }
Example #21
Source File: DistanceStrategyTest.java From lucene-solr with Apache License 2.0 | 5 votes |
@Test public void testDistanceOrder() throws IOException { ShapeFactory shapeFactory = ctx.getShapeFactory(); adoc("100", shapeFactory.pointXY(2, 1)); adoc("101", shapeFactory.pointXY(-1, 4)); adoc("103", (Shape)null);//test score for nothing commit(); //FYI distances are in docid order checkDistValueSource(shapeFactory.pointXY(4, 3), 2.8274937f, 5.0898066f, 180f); checkDistValueSource(shapeFactory.pointXY(0, 4), 3.6043684f, 0.9975641f, 180f); }
Example #22
Source File: PackedQuadPrefixTree.java From lucene-solr with Apache License 2.0 | 5 votes |
@Override public CellIterator getTreeCellIterator(Shape shape, int detailLevel) { if (detailLevel > maxLevels) { throw new IllegalArgumentException("detailLevel:" + detailLevel +" exceed max: " + maxLevels); } return new PrefixTreeIterator(shape, (short) detailLevel); }
Example #23
Source File: SpatialArgsParser.java From lucene-solr with Apache License 2.0 | 5 votes |
/** * Parses a string such as "Intersects(ENVELOPE(-10,-8,22,20)) distErrPct=0.025". * * @param v The string to parse. Mandatory. * @param ctx The spatial context. Mandatory. * @return Not null. * @throws IllegalArgumentException if the parameters don't make sense or an add-on parameter is unknown * @throws ParseException If there is a problem parsing the string * @throws InvalidShapeException When the coordinates are invalid for the shape */ public SpatialArgs parse(String v, SpatialContext ctx) throws ParseException, InvalidShapeException { int idx = v.indexOf('('); int edx = v.lastIndexOf(')'); if (idx < 0 || idx > edx) { throw new ParseException("missing parens: " + v, -1); } SpatialOperation op = SpatialOperation.get(v.substring(0, idx).trim()); String body = v.substring(idx + 1, edx).trim(); if (body.length() < 1) { throw new ParseException("missing body : " + v, idx + 1); } Shape shape = parseShape(body, ctx); SpatialArgs args = newSpatialArgs(op, shape); if (v.length() > (edx + 1)) { body = v.substring(edx + 1).trim(); if (body.length() > 0) { Map<String, String> aa = parseMap(body); readNameValuePairs(args, aa); if (!aa.isEmpty()) { throw new IllegalArgumentException("unused parameters: " + aa); } } } args.validate(); return args; }
Example #24
Source File: RandomSpatialOpFuzzyPrefixTreeTest.java From lucene-solr with Apache License 2.0 | 5 votes |
public ShapePair(Shape shape1, Shape shape2, boolean containsThenWithin) { super(Arrays.asList(shape1, shape2), RandomSpatialOpFuzzyPrefixTreeTest.this.ctx); this.shape1 = shape1; this.shape2 = shape2; this.shape1_2D = toNonGeo(shape1); this.shape2_2D = toNonGeo(shape2); biasContainsThenWithin = containsThenWithin; }
Example #25
Source File: FacetHeatmap.java From lucene-solr with Apache License 2.0 | 5 votes |
FacetHeatmap(Map<String, Object> argsMap, PrefixTreeStrategy strategy, Shape boundsShape, int gridLevel, int maxCells, String format) { this.argsMap = argsMap; this.strategy = strategy; this.boundsShape = boundsShape; this.gridLevel = gridLevel; this.maxCells = maxCells; this.format = format; }
Example #26
Source File: QuadPrefixTree.java From lucene-solr with Apache License 2.0 | 5 votes |
protected void checkBattenbergNotRobustly( char c, double cx, double cy, int level, List<Cell> matches, BytesRef str, Shape shape, int maxLevel) { assert str.length == level; assert str.offset == 0; double w = levelW[level] / 2; double h = levelH[level] / 2; int strlen = str.length; Rectangle rectangle = ctx.getShapeFactory().rect(cx - w, cx + w, cy - h, cy + h); SpatialRelation v = shape.relate(rectangle); if (SpatialRelation.CONTAINS == v) { str.bytes[str.length++] = (byte)c;//append //str.append(SpatialPrefixGrid.COVER); matches.add(new QuadCell(BytesRef.deepCopyOf(str), v.transpose())); } else if (SpatialRelation.DISJOINT == v) { // nothing } else { // SpatialRelation.WITHIN, SpatialRelation.INTERSECTS str.bytes[str.length++] = (byte)c;//append int nextLevel = level+1; if (nextLevel >= maxLevel) { //str.append(SpatialPrefixGrid.INTERSECTS); matches.add(new QuadCell(BytesRef.deepCopyOf(str), v.transpose())); } else { buildNotRobustly(cx, cy, nextLevel, matches, str, shape, maxLevel); } } str.length = strlen; }
Example #27
Source File: DefaultSpatialAlgebra.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public Shape intersection(Shape s1, Shape s2) { if (s1 instanceof Point && s2 instanceof Point) { Point p1 = (Point) s1; Point p2 = (Point) s2; int diff = compare(p2, p1); if (diff == 0) { return s1; } else { return createEmptyPoint(); } } return notSupported(); }
Example #28
Source File: DateRangeField.java From lucene-solr with Apache License 2.0 | 5 votes |
@Override protected String getStoredValue(Shape shape, String shapeStr) { // even if shapeStr is set, it might have included some dateMath, so see if we can resolve it first: if (shape instanceof UnitNRShape) { UnitNRShape unitShape = (UnitNRShape) shape; if (unitShape.getLevel() == tree.getMaxLevels()) { //fully precise date. We can be fully compatible with DatePointField (incl. 'Z') return shape.toString() + 'Z'; } } return (shapeStr == null ? shape.toString() : shapeStr);//we don't normalize ranges here; should we? }
Example #29
Source File: Geo3dShapeFactory.java From lucene-solr with Apache License 2.0 | 5 votes |
@Override @SuppressWarnings("deprecation") public Shape lineString(List<Point> list, double distance) { LineStringBuilder builder = lineString(); for (Point point : list) { builder.pointXY(point.getX(), point.getY()); } builder.buffer(distance); return builder.build(); }
Example #30
Source File: DefaultSpatialAlgebra.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public Shape difference(Shape s1, Shape s2) { if (s1 instanceof Point && s2 instanceof Point) { Point p1 = (Point) s1; Point p2 = (Point) s2; int diff = compare(p2, p1); if (diff == 0) { return createEmptyPoint(); } return s1; } return notSupported(); }