Go to content Go to navigation and search

Home

Current Oracle Spatial Blog Articles

    Tip: Drop that Spatial Index!
    Convert Single Geometry to Multi-part Geometry in Oracle Spatial
    Optimized Rectangle to 5 Point Polygon
    Centroid Package now supports Y ordinate seeding
    Convert GeoJSON document to Sdo_Geometry objects
    Implementation Of Travelling Salesman Problem
    Create Polygon From Bearings And Distances
    Function That Returns a Compass Point From a Whole Circle Bearing
    Playing around with Centroids by using different seed values
    GeoRaptor 4.x Update 2
    Simple Oracle C Sprintf or Java String.format
    Some Oriented Point Functions
    Extracting Inner Rings Changed Ordinate Ordering: A Trap For Players Who Don't Read Documentation!
    PLS-00306: wrong number or types of arguments in call to 'SDO_GEOMETRY'
    Converting Google Earth Formatted Longitude/Latitude points to decimal degrees
    Oracle Business Intelligence Warehousing and Analytics - Spatial Summit
    How far inside, is inside? Measuring actual distance.
    Noding and building a polygon from single, overlapping linestrings
    Analyzing Spatial Query Performance Improvements in Oracle Spatial and Graph 12c Through Cross-Vendor Comparison
    ST_VertexN / ST_PointN - Extracting a specific point from any geometry
    Convert Single Point stored in SDO_ORDINATES to SDO_POINT_TYPE
    Aggregate APPEND Islands and XOR polygons
    Circular Arcs in Geodetic Polygons
    Some SDO_GEOMETRY/DIMINFO handling functions
    Applying And Extending Oracle Spatial - Book Released
    Changing all DIMINFO sdo_tolerance values for all metadata records in one go.
    Building Polygons from Incomplete Linestrings using ST_PolygonBuilder
    Computing Cardinal Directions to nearby geometries
    Intersecting two aggregated polygon layers with SC4O
    Spatial and Oracle 12c
    Update Triggers and SDO_GEOMETRY Equality
    Duplicate Geometry data and Data Models
    CENTROID package update
    How to calculate cumulative length of a linestring
    Useful Package of Wrapper Functions for Sdo_Util.AffineTransforms
    Compute Location from known Lat/Long point using delta easting and northing in miles
    SDO_AGGR_SET_UNION
    Sorting SDO_GEOMETRY data using the ORDER BY clause of a SELECT statement
    Creating linestrings from points
    Rounding Coordinates or Ordinates in SDO_GEOMETRY
    Effects of Sdo_Geometry Ordinate Precision on Performance
    Effects of Sdo_Geometry Ordinate Precision on Storage
    The Spatial filtering of geometries: The effect of tolerances on relationships
    Application of Delaunay Triangulation and Inverse Distance Weighting (IDW) in Oracle for Soils Interpolation
    Selecting all SDO_GTYPE values for all tables/sdo_geometry columns in a schema
    CENTROID package - Tips for Use
    Announcing the Spatial Companion For Oracle (SC4O)
    Filtering Rings (Oracle Spatial)
    Splitting a polygon using one or more linestrings
    isValid, isSimple, Dimension and CoordDim methods for SDO_Geometry
    Line Merging or Collecting lines together: ST_LineMerger
    ST_DeleteVertex for Oracle SDO_Geometry based on Jaspa/JTS
    3D/4D and SRID aware Conversion functions for SDO_Geometry: WKT and EWKT
    Topological vs Non-Topological Simplification/Generalization of Aggregated Area Geometies in Oracle
    Filtering very short linestrings via bitmap function index
    CENTROID For Oracle
    Gridding a sdo_geometry line/polygon object (Oracle)
    Finding centre and radius of a circular geometry
    Constraining geometry type for sdo_geometry column in a table.
    CASE Statements and SDO_GEOMETRY
    The Power of Constraints and Indexes for Spatial Constraints: stopping duplicate points
    Replacement for SDO_GEOM.RELATE - ST_Relate based on JTS
    Changing Oracle Spatial Index Parameters on existing index
    Writing Excel Spreadsheets files from within the Oracle database using Java and PL/SQL
    Writing xSV (eg csv) files from within the Oracle database using Java and PL/SQL
    A simple spike finder for Spatial/Locator
    JTS Java class compilation for 11g and above
    Random Spatial Search Procedure
    Geometry Snapping using JTS in Oracle
    Exposing JTS's MinimumBoundingCircle functionality
    Exposing JTS's Densifier functionality
    Using JTS's Comparison Functions - HausdorffSimilarityMeasure & AreaSimilarityMeasure with SDO_GEOMETRY
    Free JTS-based Area/Length Functions
    Handy way of systematically fixing polygon geometries with 13349 and other errors
    Standalone CENTROID package now available for download
    Free Union, Intersection, Xor and Difference Functions for Oracle Locator - Part 4 Processing Geodetic data
    Configurable Buffer: JTS and Oracle
    Free Union, Intersection, Xor and Difference Functions for Oracle Locator - Part 3
    Free Union, Intersection, Xor and Difference Functions for Oracle Locator - Part 2
    Free Union, Intersection, Xor and Difference Functions for Oracle Locator - Part 1
    Building Lines into Polygons in Oracle Locator / Spatial
    Finding Intersection Points between Line and Polygon
    SDO2GeoJSON
    Free version of sdo_length
    Alternative to my SQL based GetNumRings function
    External Tables and SDO_Geometry data.
    layer_gtype keyword issue when indexing linear data on 11g
    String Tokenizer for Oracle
    Free Aggregate Method for Concatenating 2D Lines in Oracle Locator 10g
    Reducing 5 Vertex Polygon to Optimized Rectangle
    Square Buffer
    Converting decimal seconds to string
    SDO_GEOM.VALIDATE_GEOMETRY_WITH_CONTEXT - 13356 Issues
    Valid conversion unit values for Oracle sdo_geom.sdo_length()
    Removing Steps in Gridded Vector Data - SmoothGrid for Oracle
    Oracle Spatial DISJOINT search/filtering
    Creating SDO_Geometry from geometric data recorded in the columns of a table
    Concave Hull Geometries in Oracle 11gR2
    Projecting SDO_GEOM_METADATA DIMINFO XY ordinates
    Instantiating MDSYS.VERTEX_TYPE
    New PL/SQL Packages - Rotate oriented point
    GeoRaptor Development Team
    Fast Refreshing Materialized View Containing SDO_GEOMETRY and SDO_GEOM.SDO_AREA function
    Performance of PL/SQL Functions using SQL vs Pure Code
    Implementing the BEST VicGrid Projection in Oracle 10gR2
    Making Sdo Geometry Metadata Update Generic Code
    ORA-13011 errors when using SDO_GEOM.VALIDATE_LAYER_WITH_CONTEXT()
    Extract Polygons from Compound Polygon
    Detecting sdo_geometries with compound (3-point Arcs) segments
    GEOMETRY_COLUMNS for Oracle Spatial
    Convert GML to SDO_Geometry in Oracle 10gR2
    Spatial Sorting of Data via Morton Key
    Swapping Ordinates in an SDO_GEOMETRY object
    New To_3D Function
    Extend (Reduce/Contract/Skrink) Function for Oracle
    Loading and Processing GPX 1.1 files using Oracle XMLDB
    Loading Spatial Data from an external CSV file in Oracle
    Calling the Oracle Spatial shapefile loader from within the Oracle database itself
    Implementing SDO_VertexUpdate/ST_VertexUpdate for Oracle
    Implementing SDO_RemovePoint/ST_RemovePoint for Oracle
    Implementing SDO_AddPoint/ST_AddPoint for Oracle
    ESRI ArcSDE Exverted and Inverted Polygons and Oracle Spatial
    Funky Fix Ordinates By Formula
    Implementing a SetPoint/ST_SetPoint function in Oracle
    Implementing an ST_SnapToGrid (PostGIS) function for Oracle Spatial
    Generating random point data
    Implementing an Affine/ST_Affine function for Oracle Spatial
    Implementing a Scale/ST_Scale function for Oracle Spatial
    Implementing a Parallel/ST_Parallel function for linestring data for Oracle Spatial
    Implementing a Rotate/ST_Rotate function for Oracle Spatial
    Limiting table list returned when connecting to Oracle Database using ODBC
    ST_Azimuth for Oracle: AKA Cogo.Bearing
    Implementing a Translate/ST_Translate/Move function for Oracle Spatial
    Elem_Info_Array Processing: An alternative to SDO_UTIL.GetNumRings and querying SDO_ELEM_INFO itself
    Minumum Bounding Rectangle (MBR) Object Type for Oracle
    How to extract elements from the result of an sdo_intersection of two polygons.
    How to restart a database after failed parameter change
    Fixing failed spatial indexes after import using data pump
    generate_series: an Oracle implementation in light of SQL Design Patterns
    Multi-Centroid Shootout
    Oracle Spatial Centroid Shootout
    On the use of ROLLUP in Oracle SELECT statements
    Surrounding Parcels
    Spatial Pipelining
    Using Oracle's SDO_NN Operator - Some examples
    Converting distances and units of measure in Oracle Locator
    Split Sdo_Geometry Linestring at a known point
    Forcing an Sdo_Geometry object to contain only points, lines or areas
    Unpacking USER_SDO_GEOM_METADATA's DIMINFO structure using SQL
    Generating multi-points from single point records in Oracle Spatial
    Object Tables of Sdo_Geometry
    Oracle Locator vs Oracle Spatial: A Reflection on Oracle Licensing of the SDO_GEOM Package
    FAST REFRESHing of Oracle Materialized Views containing Sdo_Geometry columns
    Australian MGA/AMG Zone Calculation from geographic (longitude/latitude) data
    Loading Shapefiles (SHP) into Oracle Spatial
    Oracle Spatial Mapping and Map Rendering Performance Tips
    The significance of sdo_lb/sdo_ub in USER_SDO_GEOM_METDATA: Do I need it?
    Oracle Spatial Forum - Melbourne April 2007
    Layer_GTypes for spatial indexes
    Oracle's SQL/MM Compliant Types
    Tips and Tricks

Search

    Browse

RSS / Atom

Email me

textpattern

Creative Commons License
All Blog Articles, Data Models and Free Source Code by Simon Greener, The SpatialDB Advisor is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

Filtering Rings (Oracle Spatial)

Thursday March 01 2012 at 05:16

Keywordsfilter inner ring rings from polygon by area hole holes
Summary

This article shows how to build a PL/Sql function that allows a user to filter the inner rings or holes of a (multi)polygon by area.

Note: This article was edited on 1st March 2012 to cope with situation where all inner rings are filtered away by the change to using SDO_AGGR_SET_UNION which is not subject to the same licensing as SDO_AGGR_UNION. The changes are reflected only in the Filter_Rings PL/SQL function at the end of this article. In addition, a pure PL/SQL version of the Filter_Rings function is presented that is SDO_DIFFERENCE free as well.

I recently wrote an article Filtering Rings in Polygon.

How can we do this for Oracle?

If you recall I have written an article on How to extract elements from the result of an sdo_intersection of two polygons .

Well we can combine these two generate a solution to the filtering problem.

First, note how we can construct an Oracle SDO_GEOMETRY from a WKT input:

  1. SELECT mdsys.sdo_geometry('POLYGON((0 0,20 0,20 20,0 20,0 0),(10 10,10 11,11 11,11 10,10 10),(5 5,5 7,7 7,7 5,5 5))',NULL) AS geom
  2.   FROM DUAL;
  3. --
  4. GEOM
  5. ------------------------------------------------------------------------------------------------
  6. MDSYS.SDO_GEOMETRY(2003,NULL,NULL,MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,1,11,2003,1,21,2003,1),MDSYS.SDO_ORDINATE_ARRAY(0,0,20,0,20,20,0,20,0,0,10,10,10,11,11,11,11,10,10,10,5,5,5,7,7,7,7,5,5,5))
  7. --
  8. 1 ROWS selected

Now there are a few approaches we could take all on the basis of the SDO_UTIL.EXTRACT function and the GetNumRings function I wrote for the article Elem_Info_Array Processing: An alternative to SDO_UTIL.GetNumRings and querying SDO_ELEM_INFO itself

1. Generate_Series

Firstly, in the article generate_series: an Oracle implementation in light of SQL Design Patterns in which I showed a number of methods for generating an integer series of numbers. We can use this function with the GetNumRings and Extract functions as follows.

  1. SELECT GetNumRings(mdsys.sdo_geometry('POLYGON((0 0,20 0,20 20,0 20,0 0),(10 10,10 11,11 11,11 10,10 10),(5 5,5 7,7 7,7 5,5 5))',NULL)) AS numRings
  2.   FROM DUAL;
  3. --
  4. NUMRINGS
  5. --------
  6. 3
  7. --
  8. 1 ROWS selected
  9. SELECT b.column_value AS ring_no,
  10.        Sdo_Util.EXTRACT(mdsys.sdo_geometry('POLYGON((0 0,20 0,20 20,0 20,0 0),(10 10,10 11,11 11,11 10,10 10),(5 5,5 7,7 7,7 5,5 5))',NULL),1,b.column_value) AS ring
  11.  FROM TABLE(geom.generate_series(1,
  12.                                  sdo_util.GetNumRings(mdsys.sdo_geometry('POLYGON((0 0,20 0,20 20,0 20,0 0),(10 10,10 11,11 11,11 10,10 10),(5 5,5 7,7 7,7 5,5 5))',NULL)),
  13.                                  1)) b;
  14. --
  15. RING_NO RING
  16. ------- ------------------------------------------------------------------------------------------------------------------------------
  17. 1       MDSYS.SDO_GEOMETRY(2003,NULL,NULL,MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,1),MDSYS.SDO_ORDINATE_ARRAY(0,0,20,0,20,20,0,20,0,0))
  18. 2       MDSYS.SDO_GEOMETRY(2003,NULL,NULL,MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,1),MDSYS.SDO_ORDINATE_ARRAY(10,10,11,10,11,11,10,11,10,10))
  19. 3       MDSYS.SDO_GEOMETRY(2003,NULL,NULL,MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,1),MDSYS.SDO_ORDINATE_ARRAY(5,5,7,5,7,7,5,7,5,5))
  20. --
  21. 3 ROWS selected

To filter the rings and rebuild we can do the following:

  1. SELECT SDO_AGGR_UNION(SDOAGGRTYPE(c.ring,0.05)).Get_WKT() AS filtered_geom
  2.   FROM (SELECT b.column_value AS ring_no,
  3.                Sdo_Util.EXTRACT(mdsys.sdo_geometry('POLYGON((10 10,10 20,20 20,20 10,10 10),(0 0,0 1,1 1,1 0,0 0),(5 5,5 7,7 7,7 5,5 5))',NULL),1,b.column_value) AS ring
  4.           FROM TABLE(geom.generate_series(
  5.                           1,
  6.                           GetNumRings(mdsys.sdo_geometry('POLYGON((10 10,10 20,20 20,20 10,10 10),(0 0,0 1,1 1,1 0,0 0),(5 5,5 7,7 7,7 5,5 5))',NULL)),
  7.                           1)) b
  8.         ) c
  9.   WHERE c.ring_no = 1
  10.      OR ( c.ring_no > 1 AND SDO_GEOM.SDO_AREA(c.ring,0.05) > 2);
  11. --
  12. FILTERED_GEOM
  13. -------------------------------------------------------------
  14. POLYGON ((20.0 20.0, 0.0 20.0, 0.0 0.0, 20.0 0.0, 20.0 20.0))
  15. --
  16. 1 ROWS selected

While we end up with a POLYGON you will note that the inner ring has been dissolved into the polygon. This is because we used the SDO_AGGR_UNION aggregate operator. There is no other useful aggregate operator that we can use that will maintain any inner rings. So, we will have to resort to “uglier” SQL to achieve our aim.

In the Oracle “toolkit” there is the SDO_DIFFERENCE geoprocessing operator. This will do what we want but it is not an aggregate operator. The operator acts on two single SDO_GEOMETRY objects so will will have to “serve up” to this operator the outer ring separately from the inner rings (which can be aggregated).

  1. SELECT SDO_GEOM.SDO_DIFFERENCE(a.outer_ring,d.inner_rings,0.05).Get_WKT() AS filtered_geom
  2.  FROM (SELECT sdo_util.EXTRACT(mdsys.sdo_geometry('POLYGON((0 0,20 0,20 20,0 20,0 0),(10 10,10 11,11 11,11 10,10 10),(5 5,5 7,7 7,7 5,5 5))',NULL),1,1) AS outer_ring
  3.   3           FROM DUAL) a,
  4.   4        (SELECT SDO_AGGR_UNION(SDOAGGRTYPE(c.ring,0.05)) AS inner_rings
  5.   5           FROM (SELECT b.column_value AS ring_no,
  6.   6                        Sdo_Util.EXTRACT(mdsys.sdo_geometry('POLYGON((0 0,20 0,20 20,0 20,0 0),(10 10,10 11,11 11,11 10,10 10),(5 5,5 7,7 7,7 5,5 5))',NULL),1,b.column_value) AS ring
  7.   7                   FROM TABLE(geom.generate_series(
  8.   8                           1,
  9.   9                           GetNumRings(mdsys.sdo_geometry('POLYGON((0 0,20 0,20 20,0 20,0 0),(10 10,10 11,11 11,11 10,10 10),(5 5,5 7,7 7,7 5,5 5))',NULL)),
  10.  10                           1)) b
  11.  11                ) c
  12.  12          WHERE c.ring_no > 1 AND SDO_GEOM.SDO_AREA(c.ring,0.05) > 2
  13.  13*       ) d;
  14. --
  15. FILTERED_GEOM
  16. -----------------------------------------------------------------------------------------------------------
  17. POLYGON ((0.0 20.0, 0.0 0.0, 20.0 0.0, 20.0 20.0, 0.0 20.0), (5.0 7.0, 7.0 7.0, 7.0 5.0, 5.0 5.0, 5.0 7.0))
  18. --
  19. 1 ROWS selected

Which is exactly what we want.

Put in a function….

2. Use of Geom.ExtractElementsPiped

But what if you don’t want to use generate_series? I have encapsulated element extraction into the the ExplodeGeometry or ExtractElementsPiped functions in my GEOM package. We can use these to do the function extraction as follows:

  1. SELECT b.geometry
  2.  FROM TABLE(geom.ExtractElementsPiped(mdsys.sdo_geometry('POLYGON((10 10,10 20,20 20,20 10,10 10),(0 0,0 1,1 1,1 0,0 0),(5 5,5 7,7 7,7 5,5 5))',NULL),0) ) b;
  3. --
  4. GEOMETRY
  5. ------------------------------------------------------------------------------------------------------------------------------
  6. MDSYS.SDO_GEOMETRY(2003,NULL,NULL,MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,1),MDSYS.SDO_ORDINATE_ARRAY(0,0,20,0,20,20,0,20,0,0))
  7. MDSYS.SDO_GEOMETRY(2003,NULL,NULL,MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,1),MDSYS.SDO_ORDINATE_ARRAY(10,10,11,10,11,11,10,11,10,10))
  8. MDSYS.SDO_GEOMETRY(2003,NULL,NULL,MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,1),MDSYS.SDO_ORDINATE_ARRAY(5,5,7,5,7,7,5,7,5,5))
  9. --
  10. 3 ROWS selected

But, as we learned above, we cannot just filter these polygons and reconstruct the original polygon with SDO_AGGR_UNION. The final solution for this approach based on the last SQL of section 1 above would be:

  1. SELECT SDO_GEOM.SDO_DIFFERENCE(a.outer_ring,d.inner_rings,0.05).Get_WKT() AS filtered_geom
  2.  FROM (SELECT sdo_util.EXTRACT(mdsys.sdo_geometry('POLYGON((0 0,20 0,20 20,0 20,0 0),(10 10,10 11,11 11,11 10,10 10),(5 5,5 7,7 7,7 5,5 5))',NULL),1,1) AS outer_ring
  3.          FROM DUAL) a,
  4.       (SELECT SDO_AGGR_UNION(SDOAGGRTYPE(c.ring,0.05)) AS inner_rings
  5.          FROM (SELECT rownum AS ring_no,
  6.                       b.geometry AS ring
  7.                  FROM TABLE(geom.ExtractElementsPiped(mdsys.sdo_geometry('POLYGON((0 0,20 0,20 20,0 20,0 0),(10 10,10 11,11 11,11 10,10 10),(5 5,5 7,7 7,7 5,5 5))',NULL),0)) b
  8.               ) c
  9.         WHERE c.ring_no > 1 AND SDO_GEOM.SDO_AREA(c.ring,0.05) > 2
  10.       ) d;
  11. --
  12. FILTERED_GEOM
  13. -----------------------------------------------------------------------------------------------------------
  14. POLYGON ((0.0 20.0, 0.0 0.0, 20.0 0.0, 20.0 20.0, 0.0 20.0), (5.0 7.0, 7.0 7.0, 7.0 5.0, 5.0 5.0, 5.0 7.0))
  15. --
  16. 1 ROWS selected

3. Use of Hierarchical Query

Generate_Series provides for a range of integer number generation and is, in many ways, overkill for what we are doing here. We can use a simple hierarchical query to generate our ring numbers for SDO_UTIL.EXTRACT. However, Generate_Series (or ExtractElementsPiped etc) is needed if you are running on 9i as the following hierarchical query doesn’t work in 9i.

The final SQL if you use a hierarchical query is as follows:

  1. SELECT SDO_GEOM.SDO_DIFFERENCE(a.outer_ring,d.inner_rings,0.05).Get_WKT() AS filtered_geom
  2.  FROM (SELECT sdo_util.EXTRACT(mdsys.sdo_geometry('POLYGON((0 0,20 0,20 20,0 20,0 0),(10 10,10 11,11 11,11 10,10 10),(5 5,5 7,7 7,7 5,5 5))',NULL),1,1) AS outer_ring
  3.          FROM DUAL) a,
  4.       (SELECT SDO_AGGR_UNION(SDOAGGRTYPE(c.ring,0.05)) AS inner_rings
  5.          FROM (SELECT level AS ring_no,
  6.                       Sdo_Util.EXTRACT(mdsys.sdo_geometry('POLYGON((0 0,20 0,20 20,0 20,0 0),(10 10,10 11,11 11,11 10,10 10),(5 5,5 7,7 7,7 5,5 5))',NULL),1,LEVEL) AS ring
  7.                  FROM DUAL
  8.                CONNECT BY LEVEL <= GetNumRings(mdsys.sdo_geometry('POLYGON((0 0,20 0,20 20,0 20,0 0),(10 10,10 11,11 11,11 10,10 10),(5 5,5 7,7 7,7 5,5 5))',NULL) )
  9.               ) c
  10.         WHERE c.ring_no > 1 AND SDO_GEOM.SDO_AREA(c.ring,0.05) > 2
  11.       ) d;
  12. --
  13. FILTERED_GEOM
  14. -----------------------------------------------------------------------------------------------------------
  15. POLYGON ((0.0 20.0, 0.0 0.0, 20.0 0.0, 20.0 20.0, 0.0 20.0), (5.0 7.0, 7.0 7.0, 7.0 5.0, 5.0 5.0, 5.0 7.0))
  16. --
  17. 1 ROWS selected

4. Encapsulate in a Function

Regardless as to the approach taken to extract the elements, it will be cleaner to encapsulate our algorithm inside a function as follows.

NOTE: This function requires my GEOM package to be able to compile and run.

  1.   /** ----------------------------------------------------------------------------------------
  2.   * @function   : Filter_Rings
  3.   * @precis     : Function that allows a user to remove inner rings from a polygon/multipolygon
  4.   *               based on an area value.
  5.   * @version    : 1.0
  6.   * @usage      : FUNCTION Filter_Rings(p_geometry   in mdsys.sdo_geometry,
  7.   *                                     p_tolerance in number,
  8.   *                                     p_area      in number,
  9.   *                                     p_ring      in number := 0)
  10.   *                 RETURN mdsys.sdo_geometry DETERMINISTIC;
  11.   *               eg select Filter_Rings(mdsys.sdo_geometry('POLYGON((0 0,20 0,20 20,0 20,0 0),(10 10,10 11,11 11,11 10,10 10),(5 5,5 7,7 7,7 5,5 5))',null),
  12.   *                                      10,
  13.   *                                      0.05)
  14.   *                    from dual;
  15.   * @param      : p_geometry  : mdsys.sdo_geometry : Original polygon/multipolygon
  16.   * @param      : p_area      : number : Area in square srid units below which an inner ring is removed.
  17.   * @param      : p_tolerance : number : Standard Oracle diminfo tolerance.
  18.   * @Param      : p_ring      : number : The number of the internal ring to be removed
  19.   * @return     : mdsys.sdo_geometry : input geometry with any qualifying inner rings removed
  20.   * @history    : Simon Greener - December 2008 - Original coding.
  21.   * @copyright  : Licensed under a Creative Commons Attribution-Share Alike 2.5 Australia License.
  22.   *               http://creativecommons.org/licenses/by-sa/2.5/au/
  23.   **/
  24.   FUNCTION Filter_Rings(p_geometry  IN mdsys.sdo_geometry,
  25.                         p_tolerance IN NUMBER,
  26.                         p_area      IN NUMBER,
  27.                         p_ring      IN NUMBER := 0)
  28.     RETURN MDSYS.SDO_GEOMETRY
  29.   IS
  30.     v_geom mdsys.sdo_geometry;
  31.     v_ok   NUMBER;
  32.   BEGIN
  33.     IF ( p_geometry IS NULL
  34.          OR
  35.          MOD(p_geometry.sdo_gtype,10) NOT IN (3,7) ) THEN
  36.        raise_application_error(-20001,'p_geometry is null or is not a polygon',TRUE);
  37.     END IF;
  38.     BEGIN
  39.       -- Can only use this if Enterprise Edition and SDO
  40.       SELECT 1
  41.         INTO v_Ok
  42.         FROM v$version
  43.        WHERE banner LIKE '%Enterprise Edition%';
  44.       SELECT 1
  45.         INTO v_Ok
  46.         FROM dba_registry
  47.        WHERE comp_id = 'SDO';
  48.       EXCEPTION
  49.         WHEN OTHERS THEN
  50.           raise_application_error(-20001,'Not licensed for use of sdo_difference/sdo_area',TRUE);
  51.           RETURN p_geometry;
  52.     END;
  53.    SELECT CASE WHEN e.inner_rings IS NULL THEN a.outer_rings ELSE mdsys.SDO_GEOM.SDO_DIFFERENCE(a.outer_rings,e.inner_rings,p_tolerance) END AS filtered_geom    
  54.      INTO v_geom
  55.      FROM (SELECT 1 AS id, SDO_AGGR_SET_UNION(CAST(COLLECT(MDSYS.SDO_UTIL.EXTRACT(p_geometry,level,1)) AS SDO_Geometry_Array),p_tolerance) AS outer_rings
  56.              FROM DUAL
  57.            CONNECT BY level <= &&defaultSchema..GEOM.getnumouterrings(p_geometry)
  58.            ) a
  59.            LEFT OUTER JOIN
  60.            (SELECT 1 AS id, SDO_AGGR_SET_UNION(d.geom_array, p_tolerance) AS inner_rings
  61.               FROM (SELECT CAST(COLLECT(c.ring) AS SDO_Geometry_Array) AS geom_array, COUNT(*) AS geomCount, p_tolerance
  62.                       FROM (SELECT s.geom_no,
  63.                                    level AS ring_no,
  64.                                    MDSYS.SDO_UTIL.EXTRACT(s.geom,s.geom_no,LEVEL) AS ring
  65.                               FROM (SELECT r.geom_no, r.geom
  66.                                       FROM (SELECT level AS geom_no,
  67.                                                    MDSYS.SDO_UTIL.EXTRACT(p_geometry,level) AS geom
  68.                                               FROM DUAL
  69.                                              CONNECT BY LEVEL <= &&defaultSchema..GEOM.getNumOuterRings(p_geometry)
  70.                                             ) r
  71.                                      WHERE &&defaultSchema..GEOM.GetNumInnerRings(r.geom) > 0
  72.                                    ) s
  73.                             CONNECT BY level <= &&defaultSchema..GEOM.GetNumRings(s.geom)
  74.                            ) c
  75.                      WHERE c.ring_no > 1
  76.                        AND MDSYS.SDO_GEOM.SDO_AREA(c.ring,p_tolerance) > p_area
  77.                        AND c.ring_no <> p_ring
  78.                    ) d
  79.               WHERE d.geomcount > 0
  80.            ) e
  81.            ON (e.id = a.id);
  82.     RETURN v_geom;
  83.   END Filter_Rings;

I have not extended this function to allow it to handle multipolygons in order to to make this blog too complicated.

Testing it we get:

  1. WITH testGeom AS (
  2.   SELECT mdsys.sdo_geometry('POLYGON((0 0,20 0,20 20,0 20,0 0),(10 10,10 11,11 11,11 10,10 10),(5 5,5 7,7 7,7 5,5 5))',NULL) AS geom
  3.     FROM DUAL
  4. )
  5. SELECT geom.filter_rings(a.geom,0.005,2.0).Get_WKT() AS filtered_geom
  6.   FROM testGeom a;
  7. --
  8. FILTERED_GEOM
  9. -----------------------------------------------------------------------------------------------------------
  10. POLYGON ((0.0 20.0, 0.0 0.0, 20.0 0.0, 20.0 20.0, 0.0 20.0), (5.0 5.0, 5.0 7.0, 7.0 7.0, 7.0 5.0, 5.0 5.0))
  11. --
  12. 1 ROWS selected

Or to filter out all inner rings…

  1. WITH testGeom AS (
  2.   SELECT mdsys.sdo_geometry('POLYGON((0 0,20 0,20 20,0 20,0 0),(10 10,10 11,11 11,11 10,10 10),(5 5,5 7,7 7,7 5,5 5))',NULL) AS geom
  3.     FROM DUAL
  4. )
  5. SELECT geom.filter_rings(a.geom,0.005,10.0).Get_WKT() AS filtered_geom
  6.   FROM testGeom a;
  7. --
  8. FILTERED_GEOM
  9. -----------------------------------------------------------
  10. POLYGON ((0.0 0.0, 20.0 0.0, 20.0 20.0, 0.0 20.0, 0.0 0.0))
  11. --
  12. 1 ROWS selected

Which are the answers we are after.

Non-SQL, Locator Friendly Version

Two problems with the above function arise:

  1. SQL inside functions is slower than native PL/SQL.
  2. The above uses SDO_GEOM.SDO_DIFFERENCE which is an advanced Spatial function requiring expensive licensing. (Though one could use my SC4O.ST_Difference function.)

So, can we create a function that is free of SQL and could be run on Locator?

Yes, here is how we can do this:

  1.   /** ----------------------------------------------------------------------------------------
  2.   * @function   : Filter_Rings
  3.   * @precis     : Function that allows a user to remove inner rings from a polygon/multipolygon
  4.   *               based on an area value.
  5.   * @version    : 1.0
  6.   * @usage      : FUNCTION Filter_Rings(p_geometry   in mdsys.sdo_geometry,
  7.   *                                     p_tolerance in number,
  8.   *                                     p_area      in number,
  9.   *                                     p_ring      in number := 0)
  10.   *                 RETURN mdsys.sdo_geometry DETERMINISTIC;
  11.   *               eg select Filter_Rings(mdsys.sdo_geometry('POLYGON((0 0,20 0,20 20,0 20,0 0),(10 10,10 11,11 11,11 10,10 10),(5 5,5 7,7 7,7 5,5 5))',null),
  12.   *                                      10,
  13.   *                                      0.05)
  14.   *                    from dual;
  15.   * @param      : p_geometry  : mdsys.sdo_geometry : Original polygon/multipolygon
  16.   * @param      : p_area      : number : Area in square srid units below which an inner ring is removed.
  17.   * @param      : p_tolerance : number : Standard Oracle diminfo tolerance.
  18.   * @Param      : p_ring      : number : The number of the internal ring to be removed
  19.   * @return     : mdsys.sdo_geometry : input geometry with any qualifying inner rings removed
  20.   * @history    : Simon Greener - December 2008 - Original coding.
  21.   * @copyright  : Licensed under a Creative Commons Attribution-Share Alike 2.5 Australia License.
  22.   *               http://creativecommons.org/licenses/by-sa/2.5/au/
  23.   **/
  24.   FUNCTION Filter_Rings(p_geometry  IN mdsys.sdo_geometry,
  25.                         p_tolerance IN NUMBER,
  26.                         p_area      IN NUMBER,
  27.                         p_ring      IN NUMBER := 0)
  28.     RETURN MDSYS.SDO_GEOMETRY
  29.   IS
  30.      v_vertices        mdsys.vertex_set_type;
  31.      v_ords            mdsys.sdo_ordinate_array :=  NEW mdsys.sdo_ordinate_array(NULL);
  32.      v_num_dims        pls_integer;
  33.      v_num_elems       pls_integer;
  34.      v_actual_etype    pls_integer;
  35.      v_ring_elem_count pls_integer := 1;
  36.      v_ring            mdsys.sdo_geometry;
  37.      v_num_rings       pls_integer;
  38.      v_geom mdsys.sdo_geometry;
  39.      v_ok   NUMBER;    
  40.   BEGIN
  41.     IF ( p_geometry IS NULL OR MOD(p_geometry.sdo_gtype,10) NOT IN (3,7) ) THEN
  42.        raise_application_error(-20001,'p_geometry is null or is not a polygon',TRUE);
  43.     END IF;
  44.     IF ( DBMS_DB_VERSION.VERSION <= 10 ) THEN
  45.         BEGIN
  46.           -- Can only use this if Enterprise Edition and SDO
  47.           SELECT 1
  48.             INTO v_Ok
  49.             FROM v$version
  50.            WHERE banner LIKE '%Enterprise Edition%';
  51.           SELECT 1
  52.             INTO v_Ok
  53.             FROM dba_registry
  54.            WHERE comp_id = 'SDO';
  55.           EXCEPTION
  56.             WHEN OTHERS THEN
  57.               raise_application_error(-20001,'Not licensed for use of sdo_area',TRUE);
  58.               RETURN p_geometry;
  59.         END;
  60.     END IF;
  61.     /* The processing below assumes the structure of a polygon/multipolygon
  62.        is correct and passes sdo_geom.validate_geometry */
  63.     v_num_dims  := p_geometry.get_dims();
  64.     v_num_elems := MDSYS.SDO_UTIL.GETNUMELEM(p_geometry);  -- Gets number of 1003 geometries
  65.     <<all_elements>>
  66.     FOR v_elem_no IN 1..v_num_elems LOOP
  67.         -- Need to process and check all inner rings
  68.         --
  69.         -- Process all rings in the extracted single - 2003 - polygon
  70.         v_num_rings := &&defaultSchema..GEOM.GetNumRings(MDSYS.SDO_UTIL.EXTRACT(p_geometry,v_elem_no),0);
  71.         <<All_Rings>>
  72.         FOR v_ring_no IN 1..v_num_rings LOOP
  73.             v_ring := MDSYS.SDO_UTIL.EXTRACT(p_geometry,v_elem_no,v_ring_no);
  74.             IF ( v_ring IS NOT NULL ) THEN
  75.                IF ( v_ring_no = 1 ) THEN -- outer ring
  76.                  v_geom := CASE WHEN ( v_geom IS NULL ) THEN v_ring ELSE mdsys.sdo_util.APPEND(v_geom,v_ring) END;
  77.                ELSE -- Inner Ring
  78.                   IF ( mdsys.sdo_geom.sdo_area(v_ring,p_tolerance) > p_area ) THEN
  79.                      IF ( v_ring.sdo_ordinates.COUNT <> v_num_dims * 2 ) THEN -- If optimized rectangle don't swap
  80.                         v_ring := &&defaultSchema..GEOM.Reverse_Geometry(v_ring);
  81.                      END IF;
  82.                      v_ring.sdo_elem_info(2) := v_ring.sdo_elem_info(2) + 1000;
  83.                      v_geom := mdsys.sdo_util.APPEND(v_geom,v_ring);
  84.                   END IF;
  85.                END IF;
  86.             END IF;
  87.         END LOOP All_Rings;
  88.     END LOOP all_elements;
  89.     RETURN v_geom;
  90.   END Filter_Rings;

NOTE: This function requires my GEOM package to be able to compile and run: mdsys.SDO_GEOM.SDO_AREA is only an issue for versions before 10g.

Testing we get:

  1. SELECT id, filtered_geom
  2.   FROM (
  3. SELECT 1 AS id,filter_rings(a.mgeom,0.005,2.0)   AS filtered_geom FROM testGeoms a UNION ALL
  4. SELECT 2 AS id,filter_rings(a.mgeom,0.005,200.0) AS filtered_geom FROM testGeoms a UNION ALL
  5. SELECT 3 AS id,filter_rings(a.geom,0.005,2.0)    AS filtered_geom FROM testGeoms a UNION ALL
  6. SELECT 4 AS id,filter_rings(a.geom,0.005,10.0)   AS filtered_geom FROM testGeoms a UNION ALL
  7. SELECT 5 AS id,filter_rings(a.cgeom,0.005,2.0)   AS filtered_geom FROM testGeoms a UNION ALL
  8. SELECT 6 AS id,filter_rings(a.cmgeom,0.005,2.0)  AS filtered_geom FROM testGeoms a UNION ALL
  9. SELECT 7 AS id,filter_rings(a.twosq,0.005,3.0)   AS filtered_geom FROM testGeoms a
  10. )
  11. ORDER BY id;
  12. -- Results
  13. ID FILTERED_GEOM
  14. -- ---------------------------------------------------------------------------------------------------------------------
  15. 1  SDO_GEOMETRY(2007,NULL,NULL,SDO_ELEM_INFO_ARRAY(1,1003,1,11,2003,1,21,1003,1),SDO_ORDINATE_ARRAY(0,0,20,0,20,20,0,20,0,0,5,5,5,7,7,7,7,5,5,5,40,40,50,40,50,50,40,50,40,40))
  16. 2  SDO_GEOMETRY(2007,NULL,NULL,SDO_ELEM_INFO_ARRAY(1,1003,1,11,1003,1),SDO_ORDINATE_ARRAY(0,0,20,0,20,20,0,20,0,0,40,40,50,40,50,50,40,50,40,40))
  17. 3  SDO_GEOMETRY(2007,NULL,NULL,SDO_ELEM_INFO_ARRAY(1,1003,1,11,2003,1),SDO_ORDINATE_ARRAY(0,0,20,0,20,20,0,20,0,0,5,5,5,7,7,7,7,5,5,5))
  18. 4  SDO_GEOMETRY(2003,NULL,NULL,SDO_ELEM_INFO_ARRAY(1,1003,1),SDO_ORDINATE_ARRAY(0,0,20,0,20,20,0,20,0,0))
  19. 5  SDO_GEOMETRY(2003,NULL,NULL,SDO_ELEM_INFO_ARRAY(1,1005,2,1,2,1,5,2,2),SDO_ORDINATE_ARRAY(6,10,10,1,14,10,10,14,6,10))
  20. 6  SDO_GEOMETRY(2007,NULL,NULL,SDO_ELEM_INFO_ARRAY(1,1005,2,1,2,1,5,2,2,11,2005,2,11,2,2,15,2,1,21,1005,2,21,2,1,25,2,2),SDO_ORDINATE_ARRAY(6,10,10,1,14,10,10,14,6,10,13,10,10,2,7,10,10,13,13,10,106,110,110,101,114,110,110,114,106,110))
  21. 7  SDO_GEOMETRY(2007,NULL,NULL,SDO_ELEM_INFO_ARRAY(1,1003,3,5,1003,1,15,2003,3),SDO_ORDINATE_ARRAY(-10,-10,60,60,0,0,50,0,50,50,0,50,0,0,10,10,12,12))
  22. --
  23.  7 ROWS selected

There is an issue with the third resulting polygon as the original polygon was 2003. I will see if I can track down why this is occurring.

I hope this helpful to someone.

Creative Commons License

post this at del.icio.uspost this at Diggpost this at Technoratipost this at Redditpost this at Farkpost this at Yahoo! my webpost this at Windows Livepost this at Google Bookmarkspost this to Twitter

Comment