Go to content Go to navigation and search


Current Oracle Spatial Blog Articles

    Using Oracle's ST_GEOMETRY type hierarchy with SDO_GEOMETRY: ST_PointN and ST_NumPoints
    Making Sdo Geometry Metadata
    SC4O Test log
    The Frontage Problem: Creating references from land parcel street frontage boundary to point in street
    Scheduling the Export of Spatial Data in Oracle to a Shapefile each night
    Oracle CENTROID package update
    Book: "Applying And Extending Oracle Spatial"
    Create Polygons and Linestrings From Bearings And Distances (COGO)
    Simple Implementation Of Travelling Salesman Problem
    ST_Densify for Object PLSQL
    PLSQL ST_AsEWKT and ST_FromWKT Functions For Oracle (any version)
    Useful Package of Wrapper Functions for Sdo_Util.AffineTransforms
    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
    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
    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
    Compute Location from known Lat/Long point using delta easting and northing in miles
    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
    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
    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
    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



RSS / Atom

Email me


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.

Simple Implementation Of Travelling Salesman Problem

Monday September 03 2018 at 18:11

KeywordsTravelling Salesman SDO_NN PLSQL Oracle Locator

Implementation of Travelling Salesman problem using Oracle Locator and Pl/Sql only.

UPDATE: This function is now a part of the Oracle Object implementation.

The Travelling Salesman is a well known problem in graph theory:

The Travelling Salesman Problem describes a salesman who must travel between N cities.
The order in which he does so is something he does not care about, as long as he visits each one during his trip, and finishes where he was at first.
Each city is connected to other close by cities, or nodes, by airplanes, or by road or railway.
Each of those links between the cities has one or more weights (or the cost) attached.
The cost describes how “difficult” it is to traverse this edge on the graph, and may be given, for example, by the cost of an airplane ticket or train ticket,
or perhaps by the length of the edge, or time required to complete the traversal.
The salesman wants to keep both the travel costs, as well as the distance he travels as low as possible.

While there are many solutions out there in Java and other languages, I thought I would create an implementation using PL/SQL and Oracle Spatial alone. I do not profess that this is a true, or full, implementation of the problem, but it is an example of what could be done even in PL/SQL.

My implementation has two parts:

1. A function that is compiled against specific tables and which uses the nearest neighbour SDO_NN operator.
2. A separate function that runs against collections of gometries independently of the source of the data.

This article describes the first implementation. This implementation requires:

  • A table of points coded only in SDO_POINT_TYPE;
  • Points can be 2D or 3D;
  • Table has unique integer column (either primary key or unique constraint/index);
  • Table is spatially indexed;

One can create a sample dataset that implements these requirements as follows.

  1. DROP   TABLE ProjPoint2D  PURGE;
  2. CREATE TABLE ProjPoint2D ( id INTEGER, geom mdsys.sdo_geometry );
  3.     INSERT INTO ProjPoint2D (id, geom)
  4. WITH mGeom AS (
  7. SDO_ELEM_INFO_ARRAY(1,1,20),
  8. SDO_ORDINATE_ARRAY(358443.819,5407099.906, 358716.043,5407087.437, 358651.624,5407224.588, 358680.717,5407399.144,
  9.  358952.941,5407444.861, 359314.521,5407415.768, 359370.628,5407249.525, 359349.847,5407137.31,
  10.  359108.794,5407089.515, 358930.082,5407241.213, 358826.18,5407336.803, 358819.946,5407463.563,
  11.  359056.843,5407552.919, 359283.35,5407615.261, 359075.545,5407523.827, 358485.38,5407735.787,
  12.  358393.946,5407552.919, 358312.903,5407311.866, 358319.137,5407087.437, 358360.698,5406991.847)) AS mPoint
  13.  FROM dual
  14. )
  15. SELECT t.id,sdo_geometry(2001,a.mPoint.sdo_srid,sdo_point_type(t.x,t.y,t.z),NULL,NULL) AS point
  16.   FROM mGeom a,
  17.        TABLE(sdo_util.getVertices(a.mPoint)) t;
  18. COMMIT;
  19. SELECT 'Inserted '||COUNT(*)||' records into ProjPoint2D' FROM ProjPoint2D;
  21. COMMIT;
  23.   v_shape mdsys.sdo_geometry;
  24.   v_srid  INTEGER;
  25. BEGIN
  26.   SELECT SDO_AGGR_MBR(a.geom), a.geom.sdo_srid INTO v_shape, v_srid FROM ProjPoint2D a GROUP BY a.geom.sdo_srid ;
  31.     v_srid);
  32. END;
  33. /
  35. COMMIT;
  36. CREATE INDEX ProjPoint2D_GEOM ON ProjPoint2D(geom)
  37.        INDEXTYPE IS mdsys.spatial_index
  38.        parameters('sdo_indx_dims=2, layer_gtype=point');

The function has the following interface:

  2. FUNCTION ST_TravellingSalesman(
  3.   p_table_name       IN varchar2,
  4.   p_table_gid_name   IN varchar2,
  5.   p_geom_column_name IN varchar2,
  6.   p_table_gid_value  IN NUMBER,
  7.   p_unit             IN varchar2 DEFAULT NULL
  8. )
  9. RETURN sdo_geometry Deterministic
  10. AS
  11.  ... etc ...
  12. BEGIN
  13.   -- Algorithm starts with point (Node) identified by p_table_gid_value of column in table p_table_name called p_table_gid_name.
  14.   -- Add first ID to list of nodes that have already been processed.
  15.   -- Iterate over all points in table
  16.   ---- For current node (gid) find nearest point (node) in table to it which is not in already processed node list.
  17.   ---- Add found node XY(Z) values to return linestring.
  18.   ---- Add found node ID to list of nodes that have already been processed
  19.   RETURN path_as_linestring;
  20. END ST_TravellingSalesman;
  21. /
  22. SHOW errors

An example of how to call the function with our sample data is as follows.

  1. SELECT st_travellingsalesman(p_table_name=>'PROJPOINT2D', -
  2.                              p_table_gid_name=>'ID', -
  3.                              p_geom_column_name =>'GEOM', -
  4.                              p_table_gid_value=>1, -
  5.                              p_unit=>NULL) AS path-
  6.   FROM dual;
  7. -- Now let's test it
  8. PATH
  9. ----
  10. SDO_GEOMETRY(2002,NULL,NULL,MDSYS.SDO_ELEM_INFO_ARRAY(1,2,1),MDSYS.SDO_ORDINATE_ARRAY(358443.819,5407099.906, 358319.137,5407087.437, 358360.698,5406991.847, 358312.903,5407311.866, 358393.946,5407552.919, 358485.38,5407735.787, 358680.717,5407399.144, 358819.946,5407463.563, 358826.18,5407336.803, 358930.082,5407241.213, 358952.941,5407444.861, 359075.545,5407523.827, 359056.843,5407552.919, 359283.35,5407615.261, 359314.521,5407415.768, 359370.628,5407249.525, 359349.847,5407137.31, 359108.794,5407089.515, 358716.043,5407087.437, 358651.624,5407224.588))

This looks like the following:

There is also a 2.5D linestring example which shows a different solution for the same XY points as it takes in to account the slope length between each of the points.

Contact me for the actual source code.

I hope this article helps someone out there.

Contact me for the actual source code.

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 [5]

Travelling Salesman…

Hi Simon,

is possible for me to get an access to mentioned code?


— Miroslav Matas · 22 November 2016, 21:20 · #

I would love to have a copy of the source code for the Traveling Salesman problem. I work as a database developer contractor for the US Forest Service and we are starting to implement more and more SDO geometry into our applications. This would help me get a feel of how we can utilize the Oracle Spatial functions to perform better analysis of our spatial data.

Thanks for the Blog…it is excellent.


— Linda Samet · 31 January 2017, 09:13 · #

Hi Simon
great Blog. Thanks for doing this!!!
Can I get the complete code for your example? That would be great…

Greetings from Germany…

— Seb · 8 December 2017, 06:09 · #

Hi Simon,

This is really a great deal of work. Would it be possible to share the source code of the travelling salesman function?

Best Regards,

— Muhammad Bilal · 9 February 2018, 10:29 · #

Hi Simon ,

Great work , i appreciate that .
Can i get the source code of TSP function ?

thank you.


— Mohannad Hendi · 10 September 2018, 23:22 · #