grdmath (1) - Linux Manuals
grdmath: Reverse Polish Notation (RPN) calculator for grids (element by element)
NAMEgrdmath - Reverse Polish Notation (RPN) calculator for grids (element by element)
grdmath [ min_area[/min_level/max_level][+ag|i|s |S][+r|l][ppercent] ] [ resolution[+] ] [ increment ] [ ] [ ] [ region ] [ [level] ] [ -bi<binary> ] [ -di<nodata> ] [ -f<flags> ] [ -h<headers> ] [ -i<flags> ] [ -n<flags> ] [ -r ] [ -x[[-]n] ] operand [ operand ] OPERATOR [ operand ] OPERATOR ... = outgrdfile
grdmath will perform operations like add, subtract, multiply, and divide on one or more grid files or constants using Reverse Polish Notation (RPN) syntax (e.g., Hewlett-Packard calculator-style). Arbitrarily complicated expressions may therefore be evaluated; the final result is written to an output grid file. Grid operations are element-by-element, not matrix manipulations. Some operators only require one operand (see below). If no grid files are used in the expression then options -R, -I must be set (and optionally -r). The expression = outgrdfile can occur as many times as the depth of the stack allows in order to save intermediate results. Complicated or frequently occurring expressions may be coded as a macro for future use or stored and recalled via named memory locations.
- If operand can be opened as a file it will be read as a grid file. If not a file, it is interpreted as a numerical constant or a special symbol (see below).
- The name of a 2-D grid file that will hold the final result. (See GRID FILE FORMATS below).
- Features with an area smaller than min_area in km^2 or of hierarchical level that is lower than min_level or higher than max_level will not be plotted [Default is 0/0/4 (all features)]. Level 2 (lakes) contains regular lakes and wide river bodies which we normally include as lakes; append +r to just get river-lakes or +l to just get regular lakes. By default (+ai) we select the ice shelf boundary as the coastline for Antarctica; append +ag to instead select the ice grounding line as coastline. For expert users who wish to print their own Antarctica coastline and islands via psxy you can use +as to skip all GSHHG features below 60S or +aS to instead skip all features north of 60S. Finally, append +ppercent to exclude polygons whose percentage area of the corresponding full-resolution feature is less than percent. See GSHHG INFORMATION below for more details. (-A is only relevant to the LDISTG operator)
- Selects the resolution of the data set to use with the operator LDISTG ((f)ull, (h)igh, (i)ntermediate, (l)ow, and (c)rude). The resolution drops off by 80% between data sets [Default is l]. Append + to automatically select a lower resolution should the one requested not be available [abort if not found].
- x_inc [and optionally y_inc] is the grid spacing. Optionally, append a suffix modifier. Geographical (degrees) coordinates: Append m to indicate arc minutes or s to indicate arc seconds. If one of the units e, f, k, M, n or u is appended instead, the increment is assumed to be given in meter, foot, km, Mile, nautical mile or US survey foot, respectively, and 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 given but set to 0 it will be reset equal to x_inc; otherwise it will be converted to degrees latitude. All coordinates: If = is appended then the corresponding max x (east) or y (north) may be slightly adjusted to fit exactly the given increment [by default the increment may be adjusted slightly to fit the given domain]. Finally, instead of giving an increment you may specify the number of nodes desired by appending + to the supplied integer argument; the increment is then recalculated from the number of nodes and the domain. The resulting increment value depends on whether you have selected a gridline-registered or pixel-registered grid; see App-file-formats for details. Note: if -Rgrdfile is used then the grid spacing has already been initialized; use -I to override the values.
- By default any derivatives calculated are in z_units/ x(or y)_units. However, the user may choose this option to convert dx,dy in degrees of longitude,latitude into meters using a flat Earth approximation, so that gradients are in z_units/meter.
- Turn off strict domain match checking when multiple grids are manipulated [Default will insist that each grid domain is within 1e-4 * grid_spacing of the domain of the first grid listed].
- -R[unit]xmin/xmax/ymin/ymax[r] (more ...)
- Specify the region of interest.
- -V[level] (more ...)
- Select verbosity level [c].
- -bi[ncols][t] (more ...)
- Select native binary input. The binary input option only applies to the data files needed by operators LDIST, PDIST, and INSIDE.
- -dinodata (more ...)
- Replace input columns that equal nodata with NaN.
- -f[i|o]colinfo (more ...)
- Specify data types of input and/or output columns.
- -g[a]x|y|d|X|Y|D|[col]z[+|-]gap[u] (more ...)
- Determine data gaps and line breaks.
- -h[i|o][n][+c][+d][+rremark][+rtitle] (more ...)
- Skip or produce header record(s).
- -icols[l][sscale][ooffset][,...] (more ...)
- Select input columns (0 is first column).
- -n[b|c|l|n][+a][+bBC][+c][+tthreshold] (more ...)
- Select interpolation mode for grids.
- -r (more ...)
- Set pixel node registration [gridline]. Only used with -R -I.
- -x[[-]n] (more ...)
- Limit number of cores used in multi-threaded algorithms (OpenMP required).
- -^ or just -
- Print a short message about the syntax of the command, then exits (NOTE: on Windows use just -).
- -+ or just +
- Print an extensive usage (help) message, including the explanation of any module-specific option (but not the GMT common options), then exits.
- -? or no arguments
- Print a complete usage (help) message, including the explanation of options, then exits.
- Print GMT version and exit.
- Print full path to GMT share directory and exit.
Choose among the following 169 operators. "args" are the number of input and output arguments.
A + B
B if A == NaN, else A
return arc(A,B) on [0 pi]
atan2 (A, B)
Binomial cumulative distribution function for p = A, n = B, and x = C
Binomial probability density function for p = A, n = B, and x = C
A & B (bitwise AND operator)
A << B (bitwise left-shift operator)
~A (bitwise NOT operator, i.e., return two's complement)
A | B (bitwise OR operator)
A >> B (bitwise right-shift operator)
1 if bit B of A is set, else 0 (bitwise TEST operator)
A ^ B (bitwise XOR operator)
Cartesian azimuth from grid nodes to stack x,y (i.e., A, B)
Cartesian back-azimuth from grid nodes to stack x,y (i.e., A, B)
Cartesian distance between grid nodes and stack x,y (i.e., A, B)
As CDIST but only to nodes that are != 0
ceil (A) (smallest integer >= A)
Chi-squared critical value for alpha = A and nu = B
Chi-squared cumulative distribution function for chi2 = A and nu = B
Chi-squared probability density function for chi2 = A and nu = B
Combinations n_C_r, with n = A and r = B
Correlation coefficient r(A, B)
cos (A) (A in radians)
cos (A) (A in degrees)
cot (A) (A in radians)
cot (A) (A in degrees)
csc (A) (A in radians)
csc (A) (A in degrees)
Curvature of A (Laplacian)
d^2(A)/dx^2 2nd derivative
d^2(A)/dy^2 2nd derivative
d^2(A)/dxdy 2nd derivative
Converts Degrees to Radians
d(A)/dx Central 1st derivative
d(A)/dy Central 1st derivative
Converts Spherical Degrees to Kilometers
Replace NaNs in A with values from B
A / B
Places duplicate of A on the stack
Exponential cumulative distribution function for x = A and lambda = B
Exponential distribution critical value for alpha = A and lambda = B
Exponential probability density function for x = A and lambda = B
Error function erf (A)
Complementary Error function erfc (A)
1 if A == B, else 0
Inverse error function of A
Exchanges A and B on the stack
A! (A factorial)
Local Extrema: +2/-2 is max/min, +1/-1 is saddle with max/min in x, 0 elsewhere
F cumulative distribution function for F = A, nu1 = B, and nu2 = C
F distribution critical value for alpha = A, nu1 = B, and nu2 = C
Reverse order of values in each row
Reverse order of values in each column
floor (A) (greatest integer <= A)
A % B (remainder after truncated division)
F probability density function for F = A, nu1 = B, and nu2 = C
1 if A >= B, else 0
1 if A > B, else 0
hypot (A, B) = sqrt (A*A + B*B)
Modified Bessel function of A (1st kind, order 0)
Modified Bessel function of A (1st kind, order 1)
B if A != 0, else C
Modified Bessel function of A (1st kind, order B)
1 if B <= A <= C, else 0
1 when inside or on polygon(s) in A, else 0
1 / A
1 if A is finite, else 0
1 if A == NaN, else 0
Bessel function of A (1st kind, order 0)
Bessel function of A (1st kind, order 1)
Bessel function of A (1st kind, order B)
Modified Kelvin function of A (2nd kind, order 0)
Modified Bessel function of A (2nd kind, order 1)
Converts Kilometers to Spherical Degrees
Modified Bessel function of A (2nd kind, order B)
Kurtosis of A
Laplace cumulative distribution function for z = A
Laplace distribution critical value for alpha = A
Compute minimum distance (in km if -fg) from lines in multi-segment ASCII file A
As LDIST, from lines in ASCII file B but only to nodes where A != 0
As LDIST, but operates on the GSHHG dataset (see -A, -D for options).
1 if A <= B, else 0
log (A) (natural log)
log10 (A) (base 10)
log (1+A) (accurate for small A)
log2 (A) (base 2)
LMS scale estimate (LMS STD) of A
The lowest (minimum) value of A
Laplace probability density function for z = A
Laplace random noise with mean A and std. deviation B
1 if A < B, else 0
Median Absolute Deviation (L1 STD) of A
Maximum of A and B
Mean value of A
Median value of A
Minimum of A and B
A mod B (remainder after floored division)
Mode value (Least Median of Squares) of A
A * B
NaN if A == B, else A
1 if A != B, else 0
Normalize (A) so max(A)-min(A) = 1
NaN if A == NaN, 1 if A == 0, else 0
Normal, random values with mean A and std. deviation B
NaN if B == NaN, else A
Poisson cumulative distribution function for x = A and lambda = B
Compute minimum distance (in km if -fg) from points in ASCII file A
As PDIST, from points in ASCII file B but only to nodes where A != 0
Permutations n_P_r, with n = A and r = B
Associated Legendre polynomial P(A) degree B order C
Normalized associated Legendre polynomial P(A) degree B order C (geophysical convention)
Compute mean x and y from ASCII file A and place them on the stack
Delete top element from the stack
A ^ B
Poisson distribution P(x,lambda), with x = A and lambda = B
The B'th Quantile (0-100%) of A
Psi (or Digamma) of A
Legendre function Pv(A) of degree v = real(B) + imag(C)
Legendre function Qv(A) of degree v = real(B) + imag(C)
R2 = A^2 + B^2
Convert Radians to Degrees
Uniform random values between A and B
Rayleigh cumulative distribution function for z = A
Rayleigh distribution critical value for alpha = A
rint (A) (round to integral value nearest to A)
Rayleigh probability density function for z = A
Cyclicly shifts the top A stack items by an amount B
Rotate A by the (constant) shift B in x-direction
Rotate A by the (constant) shift B in y-direction
Spherical (Great circle|geodesic) distance (in km) between nodes and stack (A, B)
As SDIST but only to nodes that are != 0
Spherical azimuth from grid nodes to stack lon, lat (i.e., A, B)
Spherical back-azimuth from grid nodes to stack lon, lat (i.e., A, B)
sec (A) (A in radians)
sec (A) (A in degrees)
sign (+1 or -1) of A
sin (A) (A in radians)
sinc (A) (sin (pi*A)/(pi*A))
sin (A) (A in degrees)
Skewness of A
Standard deviation of A
Heaviside step function: H(A)
Heaviside step function in x: H(x-A)
Heaviside step function in y: H(y-A)
A - B
Sum of all values in A
tan (A) (A in radians)
tan (A) (A in degrees)
Unit weights cosine-tapered to zero within A and B of x and y grid margins
Student's t cumulative distribution function for t = A, and nu = B
Student's t distribution critical value for alpha = A and nu = B
Chebyshev polynomial Tn(-1<t<+1,n), with t = A, and n = B
Student's t probability density function for t = A, and nu = B
The highest (maximum) value of A
Weibull cumulative distribution function for x = A, scale = B, and shape = C
Weibull distribution critical value for alpha = A, scale = B, and shape = C
Weibull density distribution P(x,scale,shape), with x = A, scale = B, and shape = C
wrap A in radians onto [-pi,pi]
0 if A == NaN and B == NaN, NaN if B == NaN, else A
Bessel function of A (2nd kind, order 0)
Bessel function of A (2nd kind, order 1)
Re and Im orthonormalized spherical harmonics degree A order B
Cos and Sin normalized spherical harmonics degree A order B (geophysical convention)
Bessel function of A (2nd kind, order B)
Normal cumulative distribution function for z = A
Normal probability density function for z = A
Normal distribution critical value for alpha = A
The following symbols have special meaning:
1.192092896e-07 (single precision epsilon
Minimum x value
Maximum x value
Range of x values
The number of x nodes
Minimum y value
Maximum y value
Range of y values
The number of y nodes
Grid with x-coordinates
Grid with y-coordinates
Grid with normalized [-1 to +1] x-coordinates
Grid with normalized [-1 to +1] y-coordinates
Grid with column numbers 0, 1, ..., NX-1
Grid with row numbers 0, 1, ..., NY-1
NOTES ON OPERATORS
The operator SDIST calculates spherical distances in km between the
(lon, lat) point on the stack and all node positions in the grid. The
grid domain and the (lon, lat) point are expected to be in degrees.
Similarly, the SAZ and SBAZ operators calculate spherical
azimuth and back-azimuths in degrees, respectively. The operators
LDIST and PDIST compute spherical distances in km if -fg is
set or implied, else they return Cartesian distances. Note: If the current
PROJ_ELLIPSOID is ellipsoidal then
geodesics are used in calculations of distances, which can be slow.
You can trade speed with accuracy by changing the algorithm used to
compute the geodesic (see PROJ_GEODESIC).
The operator LDISTG is a version of LDIST that operates on the GSHHG data. Instead of reading an ASCII file, it directly accesses one of the GSHHG data sets as determined by the -D and -A options.
- The operator POINT reads a ASCII table, computes the mean x and mean y values and places these on the stack. If geographic data then we use the mean 3-D vector to determine the mean location.
- The operator PLM calculates the associated Legendre polynomial of degree L and order M (0 <= M <= L), and its argument is the sine of the latitude. PLM is not normalized and includes the Condon-Shortley phase (-1)^M. PLMg is normalized in the way that is most commonly used in geophysics. The C-S phase can be added by using -M as argument. PLM will overflow at higher degrees, whereas PLMg is stable until ultra high degrees (at least 3000).
The operators YLM and YLMg calculate normalized spherical
harmonics for degree L and order M (0 <= M <= L) for all positions in
the grid, which is assumed to be in degrees. YLM and YLMg return
two grids, the real (cosine) and imaginary (sine) component of the
complex spherical harmonic. Use the POP operator (and EXCH) to
get rid of one of them, or save both by giving two consecutive = file.nc calls.
The orthonormalized complex harmonics YLM are most commonly used in physics and seismology. The square of YLM integrates to 1 over a sphere. In geophysics, YLMg is normalized to produce unit power when averaging the cosine and sine terms (separately!) over a sphere (i.e., their squares each integrate to 4 pi). The Condon-Shortley phase (-1)^M is not included in YLM or YLMg, but it can be added by using -M as argument.
- All the derivatives are based on central finite differences, with natural boundary conditions.
- Files that have the same names as some operators, e.g., ADD, SIGN, =, etc. should be identified by prepending the current directory (i.e., ./LOG).
- Piping of files is not allowed.
- The stack depth limit is hard-wired to 100.
- All functions expecting a positive radius (e.g., LOG, KEI, etc.) are passed the absolute value of their argument. (9) The bitwise operators (BITAND, BITLEFT, BITNOT, BITOR, BITRIGHT, BITTEST, and BITXOR) convert a grid's single precision values to unsigned 32-bit ints to perform the bitwise operations. Consequently, the largest whole integer value that can be stored in a float grid is 2^24 or 16,777,216. Any higher result will be masked to fit in the lower 24 bits. Thus, bit operations are effectively limited to 24 bit. All bitwise operators return NaN if given NaN arguments or bit-settings <= 0.
- When OpenMP support is compiled in, a few operators will take advantage of the ability to spread the load onto several cores. At present, the list of such operators is: LDIST.
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.
GRID FILE FORMATS
By default GMT writes out grid as single precision floats in a COARDS-complaint netCDF file format. However, GMT is able to produce grid files in many other commonly used grid file formats and also facilitates so called "packing" of grids, writing out floating point data as 1- or 2-byte integers. To specify the precision, scale and offset, the user should add the suffix =id[/scale/offset[/nan]], where id is a two-letter identifier of the grid type and precision, and scale and offset are optional scale factor and offset to be applied to all grid values, and nan is the value used to indicate missing data. In case the two characters id is not provided, as in =/scale than a id=nf is assumed. When reading grids, the format is generally automatically recognized. If not, the same suffix can be added to input grid file names. See grdconvert and Section grid-file-format of the GMT Technical Reference and Cookbook for more information.
When reading a netCDF file that contains multiple grids, GMT will read, by default, the first 2-dimensional grid that can find in that file. To coax GMT into reading another multi-dimensional variable in the grid file, append ?varname to the file name, where varname is the name of the variable. Note that you may need to escape the special meaning of ? in your shell program by putting a backslash in front of it, or by placing the filename and suffix between quotes or double quotes. The ?varname suffix can also be used for output grids to specify a variable name different from the default: "z". See grdconvert and Sections modifiers-for-CF and grid-file-format of the GMT Technical Reference and Cookbook for more information, particularly on how to read splices of 3-, 4-, or 5-dimensional grids.
GEOGRAPHICAL AND TIME COORDINATES
When the output grid type is netCDF, the coordinates will be labeled "longitude", "latitude", or "time" based on the attributes of the input data or grid (if any) or on the -f or -R options. For example, both -f0x -f1t and -R90w/90e/0t/3t will result in a longitude/time grid. When the x, y, or z coordinate is time, it will be stored in the grid as relative time since epoch as specified by TIME_UNIT and TIME_EPOCH in the gmt.conf file or on the command line. In addition, the unit attribute of the time variable will indicate both this unit and epoch.
STORE, RECALL AND CLEAR
You may store intermediate calculations to a named variable that you may recall and place on the stack at a later time. This is useful if you need access to a computed quantity many times in your expression as it will shorten the overall expression and improve readability. To save a result you use the special operator STO@label, where label is the name you choose to give the quantity. To recall the stored result to the stack at a later time, use [RCL]@label, i.e., RCL is optional. To clear memory you may use CLR@label. Note that STO and CLR leave the stack unchanged.
The coastline database is GSHHG (formerly GSHHS) which is compiled from three sources: World Vector Shorelines (WVS), CIA World Data Bank II (WDBII), and Atlas of the Cryosphere (AC, for Antarctica only). Apart from Antarctica, all level-1 polygons (ocean-land boundary) are derived from the more accurate WVS while all higher level polygons (level 2-4, representing land/lake, lake/island-in-lake, and island-in-lake/lake-in-island-in-lake boundaries) are taken from WDBII. The Antarctica coastlines come in two flavors: ice-front or grounding line, selectable via the -A option. Much processing has taken place to convert WVS, WDBII, and AC data into usable form for GMT: assembling closed polygons from line segments, checking for duplicates, and correcting for crossings between polygons. The area of each polygon has been determined so that the user may choose not to draw features smaller than a minimum area (see -A); one may also limit the highest hierarchical level of polygons to be included (4 is the maximum). The 4 lower-resolution databases were derived from the full resolution database using the Douglas-Peucker line-simplification algorithm. The classification of rivers and borders follow that of the WDBII. See the GMT Cookbook and Technical Reference Appendix K for further details.
Users may save their favorite operator combinations as macros via the file grdmath.macros in their current or user directory. The file may contain any number of macros (one per record); comment lines starting with # are skipped. The format for the macros is name = arg1 arg2 ... arg2 : comment where name is how the macro will be used. When this operator appears on the command line we simply replace it with the listed argument list. No macro may call another macro. As an example, the following macro expects three arguments (radius x0 y0) and sets the modes that are inside the given circle to 1 and those outside to 0:
INCIRCLE = CDIST EXCH DIV 1 LE : usage: r x y INCIRCLE to return 1 inside circle
To compute all distances to north pole:
gmt grdmath -Rg -I1 0 90 SDIST = dist_to_NP.nc
To take log10 of the average of 2 files, use
gmt grdmath file1.nc file2.nc ADD 0.5 MUL LOG10 = file3.nc
Given the file ages.nc, which holds seafloor ages in m.y., use the relation depth(in m) = 2500 + 350 * sqrt (age) to estimate normal seafloor depths:
gmt grdmath ages.nc SQRT 350 MUL 2500 ADD = depths.nc
To find the angle a (in degrees) of the largest principal stress from the stress tensor given by the three files s_xx.nc s_yy.nc, and s_xy.nc from the relation tan (2*a) = 2 * s_xy / (s_xx - s_yy), use
gmt grdmath 2 s_xy.nc MUL s_xx.nc s_yy.nc SUB DIV ATAN 2 DIV = direction.nc
To calculate the fully normalized spherical harmonic of degree 8 and order 4 on a 1 by 1 degree world map, using the real amplitude 0.4 and the imaginary amplitude 1.1:
gmt grdmath -R0/360/-90/90 -I1 8 4 YML 1.1 MUL EXCH 0.4 MUL ADD = harm.nc
To extract the locations of local maxima that exceed 100 mGal in the file faa.nc:
gmt grdmath faa.nc DUP EXTREMA 2 EQ MUL DUP 100 GT MUL 0 NAN = z.nc gmt grd2xyz z.nc -s > max.xyz
To demonstrate the use of named variables, consider this radial wave where we store and recall the normalized radial arguments in radians:
gmt grdmath -R0/10/0/10 -I0.25 5 5 CDIST 2 MUL PI MUL 5 DIV STO@r COS @r SIN MUL = wave.nc
Abramowitz, M., and I. A. Stegun, 1964, Handbook of Mathematical Functions, Applied Mathematics Series, vol. 55, Dover, New York.
Holmes, S. A., and W. E. Featherstone, 2002, A unified approach to the Clenshaw summation and the recursive computation of very high degree and order normalised associated Legendre functions. Journal of Geodesy, 76, 279-299.
Press, W. H., S. A. Teukolsky, W. T. Vetterling, and B. P. Flannery, 1992, Numerical Recipes, 2nd edition, Cambridge Univ., New York.
COPYRIGHT2015, P. Wessel, W. H. F. Smith, R. Scharroo, J. Luis, and F. Wobbe