Go to content Go to navigation and search

Home

Current Oracle Spatial Blog Articles

    GeoRaptor 4.x Update 2 (Project has Stalled)
    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
    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.

Implementing an Affine/ST_Affine function for Oracle Spatial

Tuesday February 03 2009 at 09:28

Recently, I published three articles on the implementation of a Move/Translate, Rotate and Scale functions for Oracle Spatial.

Given this I thought to myself “Can I roll all these together into a single Affine function”. Of course, 11gR1’s SDO_UTIL package includes an AFFINETRANSFORMS function but there is not one for 10g.

Now, any implementation relies on the ability to do matrix algebra in Oracle. Luckily, at 10g, Oracle released the UTL_NLA package. This package:

The UTL_NLA package exposes a subset of the BLAS (Basic Linear Algebra Subprograms) and LAPACK (Linear Algebra PACKage )(Version 3.0) operations on vectors and matrices represented as VARRAYs.

After reading the documentation, brushing up on my linear algebra, trolling the PostGIS ST_Affine documentation, and reading articles by known Oracle Gurus such as Marcos Campos, I plunged in.

Here are the function headers I have created within my GEOM package.

  /* ----------------------------------------------------------------------------------------
  * function   : Affine
  * precis     : Applies a 3d affine transformation to the geometry to do things like translate, rotate, scale in one step.
  * version    : 1.0
  * description: Applies a 3d affine transformation to the geometry to do things like translate, rotate, scale in one step.
  *               To apply a 2D affine transformation only supply a, b, d, e, xoff, yoff
  * usage      : Function Affine ( p_geom IN MDSYS.SDO_GEOMETRY,
  * param      : p_geom  : The shape to rotate.
  * paramtype  : p_geom  : MDSYS.SDO_GEOMETRY
  * param      : a, b, c, d, e, f, g, h, i, xoff, yoff, zoff : 
  *               Represent the transformation matrix 
  *                 / a  b  c  xoff \ 
  *                 | d  e  f  yoff |
  *                 | g  h  i  zoff |
  *                 \ 0  0  0     1 /
  *               and the vertices are transformed as follows: 
  *                 x' = a*x + b*y + c*z + xoff
  *                 y' = d*x + e*y + f*z + yoff
  *                 z' = g*x + h*y + i*z + zoff
  * requires   : CODESYS.GEOM.ADD_Coordinate Procedure
  *               SDO_UTIL.GetVertices Funciton
  *               SYS.UTL_NLA Package
  *               SYS.UTL_NLA_ARRAY_DBL Type
  *               SYS.utl_nla_array_int Type
  * return     : newGeom    : Transformed input geometry.
  * rtnType    : newGeom    : MDSYS.SDO_GEOMETRY
  * note       : Cartesian arithmetic only
  * history    : Simon Greener, SpatialDB Advisor - Feb 2009 - Original coding.
  * copyright  : Licensed under a Creative Commons Attribution-Share Alike 2.5 Australia License. (http://creativecommons.org/licenses/by-sa/2.5/au/) . Any bugs or improvements to be supplied back to Simon Greener
  **/
  Function Affine(p_geom in mdsys.sdo_geometry, 
                  p_a number, 
                  p_b number, 
                  p_c number,
                  p_d number, 
                  p_e number, 
                  p_f number, 
                  p_g number, 
                  p_h number, 
                  p_i number, 
                  p_xoff number, 
                  p_yoff number, 
                  p_zoff number)
    return mdsys.sdo_geometry deterministic;

--
-- Overload of main Affine function
--
FUNCTION ST_Affine( p_geom in mdsys.ST_geometry, 
                      p_a number, 
                      p_b number, 
                      p_c number,
                      p_d number, 
                      p_e number, 
                      p_f number, 
                      p_g number, 
                      p_h number, 
                      p_i number, 
                      p_xoff number, 
                      p_yoff number, 
                      p_zoff number)
    Return MDSYS.ST_GEOMETRY DETERMINISTIC;

Let’s test what I have done by executing the tests on the PostGIS ST_Affine documentation page

SELECT GEOM.AsEWKT(
       GEOM.Tolerance( /* Let's round the resultant ordinates */
       GEOM.ST_Affine(foo.the_geom, 
              cos(Constants.pi()), -sin(Constants.pi()), 0, 
              sin(Constants.pi()), cos(Constants.pi()), -sin(Constants.pi()), 
              0, sin(Constants.pi()), cos(Constants.pi()), 
              0, 0, 0).Get_Sdo_Geom(),
       0.05)
       ) as ST_AsEWKT
	FROM (SELECT MDSYS.ST_GEOMETRY.FROM_SDO_GEOM(SDO_GEOMETRY(3002,null,null,sdo_elem_info_array(1,2,1),sdo_ordinate_array(1,2,3,1,4,3))) As the_geom 
          FROM DUAL) foo;

-- Oracle result
ST_ASEWKT
-------------------------------------------------------------
LINESTRING XYZ ( LINESTRING(-1.0 -2.0 -3.0, -1.0 -4.0 -3.0) )

1 rows selected

-- PostGIS Result
		   st_asewkt
-------------------------------
 LINESTRING(-1 -2 -3,-1 -4 -3)
(1 row)

Graphically, this looks like this (before and after):

PostGIS Affine example executed in Oracle

Finally, if we want to execute a 2D affine transformation, simply set the 3D parameters to NULL as in the following example:

SELECT GEOM.AsEWKT(
       GEOM.Tolerance( /* Let's round the resultant ordinates */
       GEOM.ST_Affine(foo.the_geom, 
              cos(Constants.pi()), -sin(Constants.pi()), NULL, 
              sin(Constants.pi()),  cos(Constants.pi()), NULL,
              NULL,                 NULL,                NULL,
              0,                    0,                   NULL).Get_SDO_Geom(),
       0.05)
       ) as geom
	FROM (SELECT MDSYS.ST_GEOMETRY.FROM_SDO_GEOM(MDSYS.SDO_GEOMETRY(2001,null,sdo_point_type(1,2,NULL),null,null)) As the_geom 
          FROM DUAL) foo;

GEOM
---------------------------------------------------------------------------------------------------------------------------
POINT XY (-1.0 -2.0) )

1 rows selected

There are lots of things one can use an affine transformation for. As I find and think up new uses I will add to this blog article.

I hope this work is of use 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 [2]

Simon,

Is Geom.Tolerance equivalent to PostGIS ST_SnapToGrid? I’m assuming it is.

This looks pretty good.
I don’t know enough yet to make any constructive criticism about your actual implementation code.

Keep up the good work!

Regina · 3 February 2009, 17:35 · #

Regina,

Simply put, the short answer is, Yes. My Tolerance function is the equivalent of:

geometry ST_SnapToGrid(geometry geomA, float size);

To make it clear for PostGIS users that might dip their toe into Oracle via XE and come across my packages, I have added two additional wrappers to my Tolerance functions in my GEOM PL/SQL package. One that is the equivalent of the above, and the other the equivalent of the following PostGIS function:

geometry ST_SnapToGrid(geometry geomA, float sizeX, float sizeY);

Now the long answer. The notion of tolerance, while simple, is mis-understand by new users of Oracle Spatial. From the documentation :

Tolerance is used to associate a level of precision with spatial data. Tolerance reflects the distance that two points can be apart and still be considered the same (for example, to accommodate rounding errors).

My tolerance function simply rounds an ordinate value to the supplied (Oracle) tolerance value.

Thus, if an x ordinate has value 100,000.123456789 and we supply 0.005 (ie 1cm) as the tolerance, the ordinate value will be rounded to 100,000.12.

(Note: Oracle tolerances are declared as one would to a "round" function in a C program. So, if your actual tolerance is 0.01 ie 1cm, you supply half this value to Oracle ie 0.005.)

Why do I provide Tolerance? Two reasons:

1. Most neophyte Oracle Spatial users don’t understand that Oracle Spatial will let a GIS package or user load any sort of data (with any precision) and even incorrect data.

In short, Oracle provides no “out of the box” checks on the loaded data.

A GIS loader can create ordinates with a ridiculous number of double precision digits to the right of the decimal point and Oracle won’t check it even though its SDO_GEOM_METADATA – a non-standard metadata registration table (the more standard GEOMETRY_COLUMNS table maintained by PostGIS, called OGIS_GEOMETRY_COLUMNS in Oracle, is not maintained by Oracle Spatial functionality: it must be populated directly my users) – might have a correct stored tolerance for this data. Thus, even if the data is supposedly accurate to 1cm or 1mm, the loader can create geometry objects with values like the above: 100,000.123456789 and Oracle won't check it or care.

Another example. PostGIS creates the enforce_geotype_geom check constraint when a geometry column is added via the AddGeometryColumn function viz:

CONSTRAINT enforce_geotype_geom CHECK ((geometrytype(geom) = ANY (ARRAY[‘MULTIPOLYGON’::text, ‘POLYGON’::text])) OR geom IS NULL)

Oracle has no automatic, equivalent though a user can do this:

ALTER TABLE parcel ADD CONSTRAINT enforce_geotype_geom CHECK (geom.sdo_gtype in (2003,2007) OR geom IS NULL);

A user can, alternatively, add a layer type restriction to an RTree index on creation that will only allow geometry data of the right type to be inserted.

2. Since Oracle does not enforce a tolerance value, naked examination of an SDO_GEOMETRY object’s ordinates will show all digits in the number even if irrelevant. This confuses neophyte users (and often makes data visualisation messy). Rounding the actual stored ordinate values to the supplied tolerance, aids user comprehension of their own data.

I hope this explanation helps.

Simon Greener · 4 February 2009, 01:36 · #