public static void main(String[] args) throws Exception { Geometry circle = createCircle(); PreparedGeometry prepCircle = PreparedGeometryFactory.prepare(circle); int count = 0; int inCount = 0; for (int i = 0; i < MAX_ITER; i++) { count++; Point randPt = createRandomPoint(); if (prepCircle.intersects(randPt)) { inCount++; } //System.out.println("Approximation to PI: " + (4.0 * inCount / (double) count)); } double approxPi = 4.0 * inCount / (double) count; double approxDiffPct = 1.0 - approxPi / Math.PI; System.out.println("Approximation to PI: " + approxPi + " ( % difference from actual = " + 100 * approxDiffPct + " )" ); }
/** * Inserts a collection of Geometrys into the index. * * @param geoms a collection of Geometrys to insert */ public void insert(Collection geoms) { for (Iterator i = geoms.iterator(); i.hasNext(); ) { Geometry geom = (Geometry) i.next(); index.insert(geom.getEnvelopeInternal(), PreparedGeometryFactory.prepare(geom)); } }
/** */ public List<VectorFeature> intersectingFeatures (Geometry geom) { final PreparedGeometry pGeom = PreparedGeometryFactory.prepare(geom); final List<VectorFeature> result = new ArrayList<VectorFeature>(); _spatialIndex.query(geom.getEnvelopeInternal(), new ItemVisitor() { public void visitItem (Object item) { VectorFeature feature = (VectorFeature)item; if (pGeom.intersects(feature.getGeometry())) { result.add(feature); } } }); return result; }
private Shapefile load() { if (state.compareAndSet(NOT_LOADED, LOADED)) { try { final List<PreparedGeometry> geometries = new ArrayList<>(); for (String typeName : datastore.getTypeNames()) { SimpleFeatureSource source = datastore.getFeatureSource(typeName); crs = source.getBounds().getCoordinateReferenceSystem(); final SimpleFeatureCollection features = source.getFeatures(); SimpleFeatureIterator it = features.features(); while (it.hasNext()) { SimpleFeature feature = it.next(); Geometry g = (Geometry) feature.getDefaultGeometry(); if (bufferDistance > 0) g = g.buffer(bufferDistance); geometries.add(PreparedGeometryFactory.prepare(g)); this.features.add(feature); } it.close(); } this.geometries = geometries; } catch (IOException e) { throw new RuntimeException(e); } } else if (state.get() == CLOSED) throw new RuntimeException("Shapefile is closed and can't be accessed"); return this; }
public FastLiteShape( Geometry geom ) { super(geom, new AffineTransform(), false); this.prepared = PreparedGeometryFactory.prepare(geom); GeometryFactory gf = new GeometryFactory(); pointCS = new LiteCoordinateSequence(1, 2); point = gf.createPoint(pointCS); rectCS = new LiteCoordinateSequence(5, 2); rect = gf.createPolygon(gf.createLinearRing(rectCS), null); // System.out.println("Crop area: " + geom); }
/** * Check for intersection. * * @param geometry the geometry to check against. * @param usePrepared use prepared geometry. * @return true if the geometries intersect. */ public boolean intersects( Geometry geometry, boolean usePrepared ) { if (!getEnvelope().intersects(geometry.getEnvelopeInternal())) { return false; } if (usePrepared) { if (preparedGeometry == null) { preparedGeometry = PreparedGeometryFactory.prepare(getGeometry()); } return preparedGeometry.intersects(geometry); } else { return getGeometry().intersects(geometry); } }
/** * Check for cover. * * @param geometry the geometry to check against. * @param usePrepared use prepared geometry. * @return true if the current geometries covers the supplied one. */ public boolean covers( Geometry geometry, boolean usePrepared ) { if (!getEnvelope().covers(geometry.getEnvelopeInternal())) { return false; } if (usePrepared) { if (preparedGeometry == null) { preparedGeometry = PreparedGeometryFactory.prepare(getGeometry()); } return preparedGeometry.covers(geometry); } else { return getGeometry().covers(geometry); } }
private void linkBasinWithNetwork() throws Exception { FeatureExtender fExt = new FeatureExtender(inNetwork.getSchema(), new String[]{NetworkChannel.NETNUMNAME}, new Class[]{Integer.class}); DefaultFeatureCollection newCollection = new DefaultFeatureCollection(); SimpleFeatureIterator hillslopeFeatures = inHillslope.features(); while( hillslopeFeatures.hasNext() ) { SimpleFeature hFeature = hillslopeFeatures.next(); Object netNum = hFeature.getAttribute(NetworkChannel.NETNUMNAME); Geometry hGeometry = (Geometry) hFeature.getDefaultGeometry(); PreparedGeometry preparedHGeometry = PreparedGeometryFactory.prepare(hGeometry); SimpleFeatureIterator netFeatures = inNetwork.features(); while( netFeatures.hasNext() ) { SimpleFeature nFeature = netFeatures.next(); Geometry geometry = (Geometry) nFeature.getDefaultGeometry(); if (geometry.getNumGeometries() != 1) { throw new ModelsRuntimeException("The network geometries have to be single lines.", this); } LineString nLine = (LineString) geometry.getGeometryN(0); Point startPoint = nLine.getStartPoint(); if (preparedHGeometry.contains(startPoint)) { SimpleFeature extendFeature = fExt.extendFeature(nFeature, new Object[]{netNum}); newCollection.add(extendFeature); break; } } } inNetwork = newCollection; }
@Override public void setup( final Configuration configuration, final List<ColumnInterface> columnList) throws IOException { m_spatialIndex = new STRtree(); m_buffer = configuration.getFloat(GeoEnrichmentJob.KEY_BUFFER, 0.000001F); final URL url = getUrl(configuration); final ShapefileDataStoreFactory factory = new ShapefileDataStoreFactory(); final Map params = new HashMap(); params.put(ShapefileDataStoreFactory.URLP.key, url); final DataStore dataStore = factory.createDataStore(params); try { final String[] typeNames = dataStore.getTypeNames(); final SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeNames[0]); m_geometryName = featureSource.getSchema().getGeometryDescriptor().getLocalName(); final SimpleFeatureCollection featureCollection = featureSource.getFeatures(); featureCollection.accepts(new FeatureVisitor() { public void visit(final Feature feature) { final Geometry geometry = (Geometry) feature.getProperty(m_geometryName).getValue(); final PreparedGeometry preparedGeometry = PreparedGeometryFactory.prepare(geometry); m_spatialIndex.insert(geometry.getEnvelopeInternal(), new PreparedFeature(feature, preparedGeometry)); } }, new NullProgressListener()); } finally { dataStore.dispose(); } }
public static boolean intersects(Geometry cachedGeom, Geometry g2) { if (intersectsCacheGeom == null || intersectsCacheGeom != cachedGeom) { intersectsCacheGeom = cachedGeom; intersectsCacheGeomPrep = PreparedGeometryFactory.prepare(cachedGeom); } return intersectsCacheGeomPrep.intersects(g2); }
public static boolean contains(Geometry cachedGeom, Geometry g2) { if (containsCacheGeom == null || containsCacheGeom != cachedGeom) { containsCacheGeom = cachedGeom; containsCacheGeomPrep = PreparedGeometryFactory.prepare(cachedGeom); // System.out.println(hitCount); hitCount = 0; } hitCount++; return containsCacheGeomPrep.contains(g2); }
public static Geometry intersection(Geometry cachedGeom, Geometry g2) { if (intersectionCacheGeom == null || intersectionCacheGeom != cachedGeom) { intersectionCacheGeom = cachedGeom; intersectionCacheGeomPrep = PreparedGeometryFactory.prepare(cachedGeom); } hitCount++; if (! intersectionCacheGeomPrep.intersects(g2)) return g2.getFactory().createGeometryCollection(null); if (intersectionCacheGeomPrep.contains(g2)) return g2; return cachedGeom.intersection(g2); }
public static Geometry intersectionSim(Geometry cachedGeom, Geometry g2) { if (intersectionCacheGeom == null || intersectionCacheGeom != cachedGeom) { intersectionCacheGeom = cachedGeom; intersectionCacheGeomPrep = PreparedGeometryFactory.prepare(cachedGeom); } hitCount++; if (! intersectionCacheGeomPrep.intersects(g2)) return g2.getFactory().createGeometryCollection(null); if (intersectionCacheGeomPrep.contains(g2)) return g2; return intersectionSim(intersectionCacheGeomPrep, g2); }
private static PreparedGeometry cacheFind(Geometry g) { PreparedGeometry pg = cache.get(g); if (pg == null) { pg = PreparedGeometryFactory.prepare(g); cache.put(g, pg); //System.out.println("cache size = " + cache.size()); } return pg; }
public static boolean intersectsPrep(Geometry g1, Geometry g2) { if (intersectsCacheGeom == null || intersectsCacheGeom != g1) { intersectsCacheGeom = g1; intersectsCacheGeomPrep = PreparedGeometryFactory.prepare(g1); } return intersectsCacheGeomPrep.intersects(g2); }
public static boolean containsPrep(Geometry g1, Geometry g2) { if (containsCacheGeom == null || containsCacheGeom != g1) { containsCacheGeom = g1; containsCacheGeomPrep = PreparedGeometryFactory.prepare(g1); // System.out.println(hitCount); hitCount = 0; } hitCount++; return containsCacheGeomPrep.contains(g2); }
public static Geometry intersectionPrep(Geometry g1, Geometry g2) { if (intersectionCacheGeom == null || intersectionCacheGeom != g1) { intersectionCacheGeom = g1; intersectionCacheGeomPrep = PreparedGeometryFactory.prepare(g1); } hitCount++; if (! intersectionCacheGeomPrep.intersects(g2)) return g2.getFactory().createGeometryCollection(null); if (intersectionCacheGeomPrep.contains(g2)) return g2; return g1.intersection(g2); }
/** * Creates a prepared geometry. <p> Prepared geometries make operations like intersection must faster. </p> */ public static PreparedGeometry prepare(Geometry g) { return PreparedGeometryFactory.prepare(g); }
@operator ( value = "masked_by", category = { IOperatorCategory.SPATIAL }, concept = { IConcept.GEOMETRY, IConcept.SPATIAL_COMPUTATION, IConcept.OBSTACLE }) @doc ( examples = { @example ( value = "perception_geom masked_by obstacle_list", equals = "the geometry representing the part of perception_geom visible from the agent position considering the list of obstacles obstacle_list.", isExecutable = false) }) public static IShape masked_by(final IScope scope, final IShape source, final IContainer<?, IShape> obstacles, Integer precision) { final IAgent a = scope.getAgent(); final List<IShape> obst = obstacles == null ? new ArrayList<IShape>() : obstacles.listValue(scope, Types.GEOMETRY, false); final ILocation location = a != null ? a.getLocation() : new GamaPoint(0, 0); if (precision == null) { precision = 120; } final Geometry visiblePercept = GeometryUtils.GEOMETRY_FACTORY.createGeometry(source.getInnerGeometry()); final boolean isPoint = source.isPoint(); if (obstacles != null && !obstacles.isEmpty(scope)) { final Geometry pt = GeometryUtils.GEOMETRY_FACTORY.createPoint(GeometryUtils.toCoordinate(location)); final Geometry locG = pt.buffer(0.01).getEnvelope(); double percep_dist = 0; for (final ILocation p : source.getPoints()) { final double dist = location.euclidianDistanceTo(p); if (dist > percep_dist) { percep_dist = dist; } } final Geometry gbuff = pt.buffer(percep_dist, precision / 4); final List<IShape> geoms = new ArrayList<IShape>(); for (int k = 1; k < gbuff.getNumPoints(); k++) { final IList coordinates = GamaListFactory.create(Types.POINT, 4); coordinates.add(location); coordinates.add(new GamaPoint(gbuff.getCoordinates()[k - 1])); coordinates.add(new GamaPoint(gbuff.getCoordinates()[k])); coordinates.add(location); final IShape gg = Spatial.Operators.inter(scope, source, Spatial.Creation.polygon(scope, coordinates)); if (gg != null && (isPoint || !gg.isPoint())) { geoms.add(new GamaShape(gg)); } } final GamaList geomsVisible = (GamaList) GamaListFactory.create(); final PreparedGeometry ref = PreparedGeometryFactory.prepare(locG); for (final IShape geom : geoms) { if (!intersection(geom, obst)) { geomsVisible.addValue(scope, geom); } else { final IShape perceptReal = difference(scope, geom, obst, ref); if (perceptReal != null && (isPoint || !perceptReal.isPoint())) { geomsVisible.addValue(scope, perceptReal); } } } if (!geomsVisible.isEmpty(scope)) { IShape result = Cast.asGeometry(scope, geomsVisible, false); if (result.getInnerGeometry() instanceof GeometryCollection) { result = Spatial.Transformations.enlarged_by(scope, result, 0.1); } return result; } return null; } return new GamaShape(visiblePercept); }
public void setup() { Geometry sinePoly = createSineStar(new Coordinate(0, 0), 100000.0, nPts); pg = PreparedGeometryFactory.prepare(sinePoly); g = createSineStar(new Coordinate(10, 10), 100000.0, 100); }
@Execute public void process() throws Exception { checkNull(inRaster); ISurfaceInterpolator interpolator; if (pMode.equals(IDW)) { interpolator = new IDWInterpolator(pBuffer); } else { interpolator = new TPSInterpolator(pBuffer); } RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inRaster); int rows = regionMap.getRows(); int cols = regionMap.getCols(); WritableRaster outWR = CoverageUtilities.renderedImage2WritableRaster(inRaster.getRenderedImage(), false); WritableRandomIter outIter = CoverageUtilities.getWritableRandomIterator(outWR); GridGeometry2D gridGeometry = inRaster.getGridGeometry(); PreparedGeometry preparedRoi = null; if (inROI != null) { List<Geometry> roiList = FeatureUtilities.featureCollectionToGeometriesList(inROI, false, null); GeometryCollection gc = new GeometryCollection(roiList.toArray(GeometryUtilities.TYPE_GEOMETRY), gf); preparedRoi = PreparedGeometryFactory.prepare(gc); } pm.beginTask("Filling holes...", cols - 2); for( int c = 1; c < cols - 1; c++ ) { for( int r = 1; r < rows - 1; r++ ) { if (pm.isCanceled()) { return; } double value = outIter.getSampleDouble(c, r, 0); if (isNovalue(value)) { DirectPosition worldPosition = gridGeometry.gridToWorld(new GridCoordinates2D(c, r)); double[] coordinate = worldPosition.getCoordinate(); Coordinate pointCoordinate = new Coordinate(coordinate[0], coordinate[1]); Point point = gf.createPoint(pointCoordinate); if (preparedRoi == null || preparedRoi.intersects(point)) { // TODO this could be done considering more points and more far away points. // For now, this works. List<Coordinate> surroundingValids = getValidSurroundingPoints(outIter, gridGeometry, c, r); if (surroundingValids.size() > 3) { double newValue = interpolator.getValue(surroundingValids.toArray(new Coordinate[0]), pointCoordinate); outIter.setSample(c, r, 0, newValue); } } } } pm.worked(1); } pm.done(); outIter.done(); outRaster = CoverageUtilities.buildCoverage("nulled", outWR, regionMap, inRaster.getCoordinateReferenceSystem()); }
@SuppressWarnings("unchecked") @Execute public void process() throws Exception { checkNull(inVector, pMaxOverlap, inRaster); RandomIter rasterIter = CoverageUtilities.getRandomIterator(inRaster); GridGeometry2D gridGeometry = inRaster.getGridGeometry(); double[] tm_utm_tac = new double[3]; STRtree circlesTree = FeatureUtilities.featureCollectionToSTRtree(inVector); List<SimpleFeature> circlesList = FeatureUtilities.featureCollectionToList(inVector); DefaultFeatureCollection outFC = new DefaultFeatureCollection(); for( SimpleFeature circleFeature : circlesList ) { Geometry geometry = (Geometry) circleFeature.getDefaultGeometry(); Polygon circle = (Polygon) geometry.getGeometryN(0); PreparedGeometry preparedCircle = PreparedGeometryFactory.prepare(circle); List<SimpleFeature> circlesAround = circlesTree.query(circle.getEnvelopeInternal()); List<Geometry> intersectedCircles = new ArrayList<Geometry>(); for( SimpleFeature circleAround : circlesAround ) { if (circleAround.equals(circleFeature)) { continue; } Geometry circleAroundGeometry = (Geometry) circleAround.getDefaultGeometry(); if (preparedCircle.intersects(circleAroundGeometry)) { intersectedCircles.add(circleAroundGeometry); } } Point centroid = circle.getCentroid(); int intersectionsCount = intersectedCircles.size(); if (intersectionsCount != 0) { // check how many circles overlapped if (intersectionsCount > pMaxOverlapCount) { continue; } // check if the circles overlap too much, i.e. cover their baricenter boolean intersected = false; for( Geometry intersectedCircle : intersectedCircles ) { if (intersectedCircle.intersects(centroid)) { intersected = true; break; } } if (intersected) { continue; } } // check if the center has a raster value, i.e. is not empty double value = CoverageUtilities.getValue(inRaster, centroid.getCoordinate()); if (!HMConstants.isNovalue(value)) { continue; } // check if the inner part of the circle is indeed rather empty // min, max, mean, var, sdev, activeCellCount, passiveCellCount double[] stats = OmsZonalStats.polygonStats(circle, gridGeometry, rasterIter, false, tm_utm_tac, 0, pm); // if we have many more active cells than passive cells, that is not a circle double activeCells = stats[5]; double novalues = stats[6]; if (activeCells * 1.5 > novalues) { continue; } // take it as valid circle outFC.add(circleFeature); } outCircles = outFC; rasterIter.done(); }
@Execute public void process() throws Exception { checkNull(inMap1, inMap2); outMap = new DefaultFeatureCollection(); if (!doKeepFirstAttributes) { SimpleFeatureCollection inMapTmp = inMap1; inMap1 = inMap2; inMap2 = inMapTmp; } List<Geometry> geometries = FeatureUtilities.featureCollectionToGeometriesList(inMap2, false, null); GeometryCollection geometryCollection = new GeometryCollection(geometries.toArray(new Geometry[geometries.size()]), gf); Geometry intersectionGeometry = geometryCollection.buffer(0); PreparedGeometry preparedIntersectionGeometry = PreparedGeometryFactory.prepare(intersectionGeometry); List<SimpleFeature> mainFeatures = FeatureUtilities.featureCollectionToList(inMap1); if (mainFeatures.size() == 0) { throw new ModelsIllegalargumentException("No features found in the layer.", this); } EGeometryType geometryType = EGeometryType.forGeometry((Geometry) mainFeatures.get(0).getDefaultGeometry()); Class< ? > multiClazz = geometryType.getMultiClazz(); EGeometryType newGeometryType = EGeometryType.forClass(multiClazz); FeatureGeometrySubstitutor sub = new FeatureGeometrySubstitutor(inMap1.getSchema(), multiClazz); pm.beginTask("Performing intersection...", mainFeatures.size()); for( SimpleFeature feature : mainFeatures ) { Geometry geometry = (Geometry) feature.getDefaultGeometry(); if (preparedIntersectionGeometry.intersects(geometry)) { Geometry intersection = geometry.intersection(intersectionGeometry); EGeometryType intersectionGeometryType = EGeometryType.forGeometry(intersection); if (intersectionGeometryType.isCompatibleWith(newGeometryType)) { SimpleFeature newFeature = sub.substituteGeometry(feature, intersection); ((DefaultFeatureCollection) outMap).add(newFeature); } else { pm.errorMessage("Could not add intersection result geometry to layer due to incompatibility: " + intersection); } } pm.worked(1); } pm.done(); }
/** * Retrieve all the trees envelopes that intersect the geometry. * * @param checkGeom the {@link com.vividsolutions.jts.geom.Geometry} to use to check. * @param doOnlyEnvelope check for the geom envelope instead of a intersection with it. * @param minMaxZ an array to be filled with the min and max z to be used as style. * @return the list of envelopes contained in the supplied geometry. * @throws Exception */ @Override public synchronized List<Geometry> getEnvelopesInGeometry( Geometry checkGeom, boolean doOnlyEnvelope, double[] minMaxZ ) throws Exception { checkOpen(); ArrayList<Geometry> envelopeListForTile = new ArrayList<Geometry>(); Envelope env = checkGeom.getEnvelopeInternal(); PreparedGeometry preparedGeometry = null; if (!doOnlyEnvelope) { preparedGeometry = PreparedGeometryFactory.prepare(checkGeom); } double min = Double.POSITIVE_INFINITY; double max = Double.NEGATIVE_INFINITY; List< ? > filesList = mainLasFolderIndex.query(env); for( Object fileName : filesList ) { if (fileName instanceof String) { String name = (String) fileName; File lasFile = new File(lasFolder, name); File lasIndexFile = FileUtilities.substituteExtention(lasFile, "lasfix"); String absolutePath = lasIndexFile.getAbsolutePath(); STRtreeJGT lasIndex = fileName2IndexMap.get(absolutePath); if (lasIndex == null) { lasIndex = OmsLasIndexReader.readIndex(absolutePath); fileName2IndexMap.put(absolutePath, lasIndex); } List< ? > queryBoundables = lasIndex.queryBoundables(env); for( Object object : queryBoundables ) { if (object instanceof ItemBoundable) { ItemBoundable itemBoundable = (ItemBoundable) object; double[] item = (double[]) itemBoundable.getItem(); if (item.length > 0) { Envelope bounds = (Envelope) itemBoundable.getBounds(); Polygon envelopePolygon = LasIndexer.envelopeToPolygon(bounds); envelopePolygon.setUserData(new double[]{item[2], item[3]}); if (minMaxZ != null) { min = Math.min(min, item[2]); max = Math.max(max, item[2]); } if (doOnlyEnvelope) { envelopeListForTile.add(envelopePolygon); } else { if (preparedGeometry.intersects(envelopePolygon)) { envelopeListForTile.add(envelopePolygon); } } } } } } } if (minMaxZ != null) { minMaxZ[0] = min; minMaxZ[1] = max; } return envelopeListForTile; }
private PreparedGeometry getFloodingArea( SimpleFeatureCollection inFloodingAreas ) throws Exception { List<Geometry> geometriesList = FeatureUtilities.featureCollectionToGeometriesList(inFloodingAreas, true, null); Geometry polygonUnion = CascadedPolygonUnion.union(geometriesList); PreparedGeometry preparedGeometry = PreparedGeometryFactory.prepare(polygonUnion); return preparedGeometry; }