# sphdistance

Create Voronoi distance, node, or natural nearest-neighbor grid on a sphere

## Synopsis

gmt sphdistance [ table ] -G grdfile -I increment -R region [ -C ] [ -D ] [ -E d|n|z[dist] ] [ -L unit ] [ -N nodetable ] [ -Q voronoi.txt ] [ -V[level] ] [ -b binary ] [ -d nodata[+c col] ] [ -e regexp ] [ -h headers ] [ -i flags ] [ -j flags ] [ -qi flags ] [ -r reg ] [ -:[i|o] ] [ --PAR=value ]

Note: No space is allowed between the option flag and the associated arguments.

## Description

sphdistance reads one or more ASCII [or binary] files (or standard input) containing (lon, lat) and performs the construction of Voronoi polygons. These polygons are then processed to calculate the nearest distance to each node of the lattice and written to the specified grid. The Voronoi algorithm used is STRIPACK [Renka, 1997]. As an option, you may provide pre-calculated Voronoi polygon file in the format written by sphtriangulate, thus bypassing the memory- and time-consuming triangularization.

## Required Arguments

table

  One or more ASCII (or binary, see -bi[ncols][type]) data table file(s) holding a number of data columns. If no tables are given then we read from standard input.

-G outgrid[=ID][+d divisor][+n invalid][+o offset|a][+s scale|a][:driver[dataType][+c options]]

> Optionally, append =ID for writing a specific file format. The following modifiers are supported:

> > - +d - Divide data values by given divisor [Default is 1].

> > - +n - Replace data values matching invalid with a NaN.

> > - +o - Offset data values by the given offset, or append a for automatic range offset to preserve precision for integer grids [Default is 0].

> > - +s - Scale data values by the given scale, or append a for automatic scaling to preserve precision for integer grids [Default is 1].

> Note: Any offset is added before any scaling. +sa also sets +oa (unless overridden). To write specific formats via GDAL, use =gd and supply driver (and optionally dataType) and/or one or more concatenated GDAL -co options using +c. See the “Writing grids and images” cookbook section for more details.

-I x_inc[+e|n][/y_inc[+e|n]]

  Set the grid spacing as x_inc [and optionally y_inc].

  Geographical (degrees) coordinates: Optionally, append an increment unit. Choose among:

  > - d - Indicate arc degrees

  > - m - Indicate arc minutes

  > - s - Indicate arc seconds

  > If one of e (meter), f (foot), k (km), M (mile), n (nautical mile) or u (US survey foot), the the increment will be converted to the equivalent degrees longitude at the middle latitude of the region (the conversion depends on PROJ_ELLIPSOID). If y_inc is not given or given but set to 0 it will be reset equal to x_inc; otherwise it will be converted to degrees latitude.

  All coordinates: The following modifiers are supported:

  > - +e - Slightly adjust the max x (east) or y (north) to fit exactly the given increment if needed [Default is to slightly adjust the increment to fit the given domain].

  > - +n - Define the number of nodes rather than the increment, in which case the increment is recalculated from the number of nodes, the registration (see GMT File Formats), and the domain. Note: If -R grdfile is used then the grid spacing and the registration have already been initialized; use -I and -R to override these values.

-R west/east/south/north[/zmin/zmax][+r][+u unit]

> Specify the region of interest.

> The region may be specified in one of several ways:

> 1. -R west/east/south/north. This is the standard way to specify geographic regions when using map projections where meridians and parallels are rectilinear. The coordinates may be specified in decimal degrees or in [±]dd:mm[:ss.xxx][W|E|S|N] format.

> 2. -R west/south/east/north+r. This form is useful for map projections that are oblique, making meridians and parallels poor choices for map boundaries. Here, we instead specify the lower left corner and upper right corner geographic coordinates, followed by the modifier +r. This form guarantees a rectangular map even though lines of equal longitude and latitude are not straight lines.

> 3. -R g or -R d. These forms can be used to quickly specify the global domain (0/360 for -Rg and -180/+180 for -Rd in longitude, with -90/+90 in latitude).

> 4. -R code1,code2,…[+e|r|R incs]. This indirectly supplies the region by consulting the DCW (Digital Chart of the World) database and derives the bounding regions for one or more countries given by the codes. Simply append one or more comma-separated countries using either the two-character ISO 3166-1 alpha-2 convention (e.g., NO) or the full country name (e.g., Norway). To select a state within a country (if available), append .state (e.g, US.TX), or the full state name (e.g., Texas). To specify a whole continent, spell out the full continent name (e.g., -RAfrica). Finally, append any DCW collection abbreviations or full names for the extent of the collection or named region. All names are case-insensitive. The following modifiers can be appended:

>    > - +r to adjust the region boundaries to be multiples of the steps indicated by inc, xinc/yinc, or winc/einc/sinc/ninc [default is no adjustment]. For example, -R FR+r1 will select the national bounding box of France rounded to nearest integer degree, where inc can be positive to expand the region or negative to shrink the region.

>    > - +R to adjust the region by adding the amounts specified by inc, xinc/yinc, or winc/einc/sinc/ninc [default is no extension], where inc can be positive to expand the region or negative to shrink the region.

>    > - +e to adjust the region boundaries to be multiples of the steps indicated by inc, xinc/yinc, or winc/einc/sinc/ninc, while ensuring that the bounding box is adjusted by at least 0.25 times the increment [default is no adjustment], where inc can be positive to expand the region or negative to shrink the region.

> 5. -R xmin/xmax/ymin/ymax[+u unit] specifies a region in projected units (e.g., UTM meters) where xmin/xmax/ymin/ymax are Cartesian projected coordinates compatible with the chosen projection (-J) and unit is an allowable distance unit [e]; we inversely project to determine the actual rectangular geographic region. For projected regions centered on (0,0) you may use the short-hand -R halfwidth[/halfheight]+u unit, where halfheight defaults to halfwidth if not given. This short-hand requires the +u modifier.

> 6. -R justify lon0/lat0/nx/ny, where justify is a 2-character combination of L|C|R (for left, center, or right) and T|M|B (for top, middle, or bottom) (e.g., BL for lower left). The two character code justify indicates which point on a rectangular region region the lon0/lat0 coordinates refer to and the grid dimensions nx and ny are used with grid spacings given via -I to create the corresponding region. This method can be used when creating grids. For example, -RCM 25/25/50/50 specifies a 50x50 grid centered on 25,25.

> 7. -R gridfile. This will copy the domain settings found for the grid in specified file. Note that depending on the nature of the calling module, this mechanism will also set grid spacing and possibly the grid registration (see Grid registration: The -r option).

> 8. -Ra[uto] or -Re[xact]. Under modern mode, and for plotting modules only, you can automatically determine the region from the data used. You can either get the exact area using -Re [Default if no -R is given] or a slightly larger area sensibly rounded outwards to the next multiple of increments that depend on the data range using -Ra.

## Optional Arguments

-C

  For large data sets you can save some memory (at the expense of more processing) by only storing one form of location coordinates (geographic or Cartesian 3-D vectors) at any given time, translating from one form to the other when necessary [Default keeps both arrays in memory]. Not applicable with -Q.

-D

  Used to skip duplicate points since the algorithm cannot handle them. [Default assumes there are no duplicates].

-Ed|n|z[dist]

  Specify the quantity that should be assigned to the grid nodes. Append one of three directives:

  - d: Compute distances to the nearest data point [Default].

  - n: Assign the ID numbers of the Voronoi polygons that each grid node is inside.

  - z: For a natural nearest-neighbor grid where we assign all nodes inside the polygon the z-value of the center node.

  Optionally, append the resampling interval along Voronoi arcs in spherical degrees [1].

-L unit

  Specify the unit used for distance calculations. Choose among d (spherical degree), e (m), f (feet), k (km), M (mile), n (nautical mile) or u (survey foot).

-N nodetable

  Read the information pertaining to each Voronoi polygon (the unique node (lon, lat) and polygon area) from a separate file [Default acquires this information from the ASCII segment headers of the output file]. Required if binary input via -Q is used.

-Q voronoi.txt

  Append the name of a file with pre-calculated Voronoi polygons [Default performs the Voronoi construction on input data]. For binary data -bi you must specify the node information separately (via -N).

-V[level]

  Select verbosity level [w]. (See full description) (See cookbook information).

-bi record[+b|l] (more …)

  Select native binary format for primary table input. [Default is 2 input columns].

-bo record[+b|l] (more …)

  Select native binary format for table output. [Default is same as input].

-d[i|o][+c col]nodata (more …)

  Replace input columns that equal nodata with NaN and do the reverse on output.

-e[~]“pattern” | -e[~]/regexp/[i] (more …)

  Only accept data records that match the given pattern.

-h[i|o][n][+c][+d][+m segheader][+r remark][+t title] (more …)

  Skip or produce header record(s).

-i cols[+l][+d divisor][+s scale|d|k][+o offset][,…][,t[word]] (more …)

  Select input columns and transformations (0 is first column, t is trailing text, append word to read one word only).

-je|f|g (more …)

  Determine how spherical distances or coordinate transformations are calculated.

-qi[~]rows|limits[+c col][+a|t|s] (more …)

  Select input rows or data limit(s) [default is all rows].

-r[g|p] (more …)

  Set node registration [gridline].

-:[i|o] (more …)

  Swap 1st and 2nd column on input and/or output.

-^ or just -

  Print a short message about the syntax of the command, then exit (Note: on Windows just use -).

-+ or just +

  Print an extensive usage (help) message, including the explanation of any module-specific option (but not the GMT common options), then exit.

-? or no arguments

  Print a complete usage (help) message, including the explanation of all options, then exit.

--PAR=value

  Temporarily override a GMT default setting; repeatable. See gmt.conf for parameters.

## ASCII Format Precision

The ASCII output formats of numerical data are controlled by parameters in your gmt.conf file. Longitude and latitude are formatted according to FORMAT_GEO_OUT, absolute time is under the control of FORMAT_DATE_OUT and FORMAT_CLOCK_OUT, whereas general floating point values are formatted according to FORMAT_FLOAT_OUT. Be aware that the format in effect can lead to loss of precision in ASCII output, which can lead to various problems downstream. If you find the output is not written with enough precision, consider switching to binary output (-bo if available) or specify more decimals using the FORMAT_FLOAT_OUT setting.

## Grid Values Precision

Regardless of the precision of the input data, GMT programs that create grid files will internally hold the grids in 4-byte floating point arrays. This is done to conserve memory and furthermore most if not all real data can be stored using 4-byte floating point values. Data with higher precision (i.e., double precision values) will lose that precision once GMT operates on the grid or writes out new grids. To limit loss of precision when processing data you should always consider normalizing the data prior to processing.

## Examples

Note: Below are some examples of valid syntax for this module. The examples that use remote files (file names starting with `@`) can be cut and pasted into your terminal for testing. Other commands requiring input files are just dummy examples of the types of uses that are common but cannot be run verbatim as written.

To compute a distance grid of the distances between a set of points in the remote file hotspots.txt and then contour them on a sphere with a 200 km interval and annotations every 1000 km, try:

    gmt begin map
      gmt sphtriangulate @hotspots.txt -Qv -D > t.txt
      gmt sphdistance -Rg -I1 -Qt.txt -Gt.nc -Lk
      gmt grdcontour t.nc -JG-140/30/7i -C200 -A1000 -Bafg
    gmt end show

To construct Voronoi polygons from the points in the file testdata.txt and then calculate distances from the data to a global 1x1 degree grid, use

    gmt sphdistance testdata.txt -Rg -I1 -Gglobedist.nc

To generate the same grid in two steps using sphtriangulate separately, try

    gmt sphtriangulate testdata.txt -Qv > voronoi.txt
    gmt sphdistance -Qvoronoi.txt -Rg -I1 -Gglobedist.nc

## Notes

The STRIPACK algorithm and implementation expect that there are no duplicate points in the input. It is best that the user ensures that this is the case. GMT has tools, such as blockmean and others, to combine close points into single entries. Also, sphdistance has a -D option to determine and exclude duplicates, but it is a very brute-force yet exact comparison that is very slow for large data sets. Detection of duplicates in the STRIPACK library will exit the module.

## See Also

gmt, sphtriangulate, triangulate

## References

Renka, R, J., 1997, Algorithm 772: STRIPACK: Delaunay Triangulation and Voronoi Diagram on the Surface of a Sphere, AMC Trans. Math. Software, 23(3), 416-434.