geosoft.gxpy.grid submodule¶
Geosoft grid and image handling, including all supported file formats .
- Classes
Grid
grid dataset
- Constants
- FILE_READ
0 open for read, files are not changed
- FILE_READWRITE
1 open for read and write, files can be changed
- FILE_NEW
2 new grid file, accompanied by
overwrite=
parameter
Note
Regression tests provide usage examples: Tests
-
class
Grid
(file_name=None, in_memory=False, dtype=None, mode=None, kx=1, dim=None, overwrite=False, **kwargs)[source]¶ Bases:
geosoft.gxpy.geometry.Geometry
Grid and image class.
- Constructors
open an existing grid/image
create a new grid/image
create a copy
create a windowed grid based on grid indexes
create a new grid from a 2d data array
create by fitting a minimum-curvature surface to located data.
A grid instance supports iteration that yields (x, y, z, grid_value) by points along rows. For example, the following prints the x, y, z, grid_value of every non-dummy point in a grid:
import geosoft.gxpy.grid as gxgrd with gxgrd.Grid.open('some.grd') ad g: for x, y, z, v in g: if v is not None: print(x, y, z, v)
Specific grid cell values can be indexed (null grid values are None):
import geosoft.gxpy.grid as gxgrd with gxgrd.Grid.open('some.grd') as g: for ix in range(g.nx): for iy in range(g.ny): x, y, z, v = g[ix, iy] if v is not None: print(x, y, z, v)
New in version 9.1.
Changed in version 9.2.1: added iterator support
-
__init__
(file_name=None, in_memory=False, dtype=None, mode=None, kx=1, dim=None, overwrite=False, **kwargs)[source]¶ Initialize self. See help(type(self)) for accurate signature.
-
close
(discard=False)[source]¶ Close the grid and release all instance resources.
- Parameters
discard –
True
to discard associated files on close
Changed in version 9.4: added
discard
parameter
-
property
coordinate_system
¶ grid coordinate system as a
geosoft.gxpy.coordinate_system.Coordinate_system
instance.Can be set from any
geosoft.gxpy.coordinate_system.Coordinate_system
constructor.New in version 9.2.
Changed in version 9.3: added ability to set directly
-
classmethod
copy
(grd, file_name=None, dtype=None, overwrite=False, in_memory=False, mode=1)[source]¶ Create a new Grid instance as a copy of an existing grid.
- Parameters
grd –
Grid
instance to save as a new grid, or a grid file namefile_name – name of the new grid (file with optional decorations). If not specified a temporary file is created.
dtype – numpy data type, None to use type of the parent grid
overwrite – True to overwrite if the file exists, False to not overwrite.
in_memory – True to create a grin in memory.
mode –
open
mode for working with the copy.
New in version 9.2.
-
static
decorate_name
(name, decorations='')[source]¶ Deprecated since version 9.2: use gxpy.grid.name_parts()
-
property
decoration
¶ grid descriptive decoration
New in version 9.2.
-
delete_files
(delete=True)[source]¶ Delete the files associated with this grid when deleting the grid object. Note that files are not deleted until all references to this object are deleted and garbage collection is performed.
- Parameters
delete – set to False to reverse a previous delete request
New in version 9.1.
-
property
dtype
¶ numpy data type for the grid
New in version 9.2.
-
property
dummy_value
¶ Return the grid data dummy value.
-
property
dx
¶ separation between grid points in the grid x direction
New in version 9.2.
-
property
dy
¶ separation between grid points in the grid y direction
New in version 9.2.
-
property
extent
¶ Grid cell extent as
geosoft.gxpy.geometry.Point2
.New in version 9.3.1.
-
extent_2d
()[source]¶ Return the 2D extent of the grid on the grid plane.
Extent is to the outer edge of grid “cells”, which extend half a cell beyond the edge points.
:returns:(min_x, min_y, max_x, max_y)
New in version 9.2.
Changed in version 9.4: - extent to the cell edges.
-
extent_3d
()[source]¶ Return the 3D extent of the grid in the base coordinate system.
- Returns
(min_x, min_y, min_z, max_x, max_y, max_z)
New in version 9.2.
-
extent_cell_2d
()[source]¶ Deprecated since version 9.4: - same as
extent_2d()
-
extent_cell_3d
()[source]¶ Deprecated since version 9.4: - same as
extent_3d()
-
extent_point_2d
()[source]¶ Return the 2D extent of the grid point (cell centers) on the grid plane.
:returns:(min_x, min_y, max_x, max_y)
New in version 9.4.
-
property
file_name
¶ grid file name without decorations
New in version 9.2.
-
property
file_name_decorated
¶ grid file name with decorations
New in version 9.2.
-
classmethod
from_data_array
(data, file_name=None, properties=None, overwrite=False)[source]¶ Create grid from a 2D data array or
geosoft.gxapi.GXPG
.- Parameters
data – 2D numpy data array, a 2d list, ir a
geosoft.gxapi.GXPG
.file_name – name of the file, default creates a temporary file name
properties – grid properties as a dictionary
overwrite –
True
to overwrite existing grid.
- Returns
Grid
instance
New in version 9.1.
Changed in version 9.4: - support for default temporary file name and creation from a GXPG.
-
generate_color_map
(method=0)[source]¶ Generate color map for grid based on statistics and method
- Parameters
method – ITR_ZONE constants
- Returns
A
geosoft.gxpy.group.Color_map
instance.
New in version 9.4.0.
-
get_default_color_map
()[source]¶ Get default color map for grid
- Returns
A
geosoft.gxpy.group.Color_map
instance.
New in version 9.4.0.
-
get_value
(x, y)[source]¶ Return a grid value at a point as a float. For scalar data the point value will be interpolated between neighbors. For color data the nearest value is returned as a color int.
- Parameters
x – X location on the grid plane
y – Y location on the grid plane
- Returns
grid value, or None if outside of grid area
-
property
gridtype
¶ grid type (e.g. ‘GRD’, ‘HGD’ etc. ‘MEMORY’ for in-memory grid)
New in version 9.2.
-
property
gximg
¶ The
geosoft.gxapi.GXIMG
instance handle.
-
gxpg
(copy=False)[source]¶ Get a copy of the
geosoft.gxapi.GXPG
instance for the grid.- Parameters
copy –
True
to return a copy of the grids pager. The default isFalse
, which returns the shared grid pager, such that changes to the pager change the grid and the pager is invalid when thr grid is closed or loses context.
New in version 9.1.
Changed in version 9.4: added
copy
parameter
-
property
gxtype
¶ Geosoft data type for the grid
New in version 9.2.
-
image_file
(image_file_name=None, image_type='PNG', pix_width=None, shade=False, color_map=None, contour=None, display_area=None, pix_32_bit=False)[source]¶ Save as a georeferenced image file.
- Parameters
image_file_name – image file name. The extension should be consistent with the image_type. If not specified a temporary PNG file is created.
image_type – image type, one ot the RASTER_FORMAT constants in
geosoft.gxpy.map
.pix_width – desired image width in pixels, default is the width of the aggregate base layer
shade –
True
to add shading effectcolor_map –
geosoft.gxpy.group.Color_map
instance, or a colour ramp file name, default is grid’s defaultcontour – colour contour interval if colours need to break at exact levels
display_area –
geosoft.gxpy.geometry.Point2
instance, which defines the desired display area. The display area coordinate system can be different from the grid.pix_32_bit – make 32-bit image (with 8-bit alpha background)
- Returns
image file name.
See also
geosoft.gxpy.grid.image_file
, which creates an image directly from a grid file.Note
Unless read-only this method saves the grid as a temporary file from which an aggregate and image are created. If the grid already exists as a grid file it is more efficient to call
geosoft.gxpy.grid.image_file
.New in version 9.3.1.
-
indexWindow
(name, x0=0, y0=0, nx=None, ny=None)[source]¶ Deprecated since version 9.2: gxpy.Grid.index_window()
-
classmethod
index_window
(grd, name=None, x0=0, y0=0, nx=None, ny=None, overwrite=False)[source]¶ Create a windowed instance of a grid.
- Parameters
grd –
Grid
instancename – name for the windowed_grid, default is constructed from input grid
x0 – integer index of the first X point
y0 – integer index of the first Y point
nx – number of points in x
ny – number of points in y
overwrite – True to overwrite existing file, default is False
New in version 9.2.
-
property
is_color
¶ returns True if grid contains colors. is_int will also be True
-
property
is_crooked_path
¶ True if this grid follows a crooked path section.
-
property
is_int
¶ returns True if base grid type is integer, which includes color integers
-
mask
(mask)[source]¶ Mask against blank areas in
mask
grid. Both grids must be same dimension.- Parameters
mask – reference mask grid, file of
Grid
instance.
New in version 9.4.
-
property
metadata
¶ Return the grid metadata as a dictionary. Can be set, in which case the dictionary items passed will be added to, or replace existing metadata.
See also
New in version 9.2.
-
classmethod
minimum_curvature
(data, unit_of_measure=None, file_name=None, overwrite=False, max_segments=1000, coordinate_system=None, cs='', area='', '', '', '', bclip='', logopt='', logmin='', idsf='', bkd='', srd='', iwt='', edgclp='', tol='', pastol='100', itrmax='', ti='', icgr='')[source]¶ Create a minimum-curvature surface grid from (x, y, value) located data.
Reference: Smith and Wessel, 1990, Gridding with continuous curvature splines in tension.
- Parameters
data – list of [(x, y, value), …] or a callback that returns lists, or a tuple (gdb, value_channel, x_channel, y_channel) where x_channel and y_channel, if not specified, default to the current database (x, y) channels. See below.
unit_of_measure – string unit of measurement descriptor.
file_name –
name of the grid file, None for a temporary grid. See supported file formats)
overwrite – True to overwrite existing file
max_segments – Maximum number of line segments if using a callback, defaults to 1000.
coordinate_system – coordinate system
Gridding parameters follow the nomenclature of the rangrid.con file: https://github.com/GeosoftInc/gxc/blob/master/reference/con_files/rangrid.con
- Parameters
cs – The grid cell size in reference system units.
area – (xmin, ymin, xmax, ymax) - grid area, default is the data limits
bclip – 0 to use all data (default), 1 to only use data in the dat area.
logopt – 1 for log(value) minimum cliped to log(logmin); 2 for
logmin + log(value/logmin)
for postivevalue
,-logmin - log(-value/logmin
for negativevalue
logmin – see
logopt
, default is 1.idsf – low-pass desampling factor in cells, default is 1. Effectively a low-pass filter that can smooth noisy data that has clustered locations.
bkd – Blanking distance. All grid cells farther than the blanking distance from a valid point will be blanked in the output grid. The default is the nominal sample interval, i.e. sqrt(area/#data). This parameter should normally be set to just greater than the maximum sampling interval through which interpolation is desired. If there are too many holes in the resulting grid, increase appropriately.
srd – The maximum search radius to use for establishing the starting values for the coarse grid. The default is four times the coarse grid size defined by
icgr
. If no data is found within the maximum search radius, the mean of the data is used as the starting value. If the search radius is too small, the starting grid can be a poor approximation of the desired grid, resulting in excessive processing time. If too large, too much time will be consumed establishing the original coarse grid.iwt – The weighting power to use to establish the coarse starting grid. The default is 2, for inverse distance squared. There is little reason to change this from the default.
edgclp – Edge clipping parameter, the number of grid cells to extend beyond the outside limits of the data. The default (-1) is not to apply edge clipping to the blanking distanced grid. Use this parameter to ensure the grid does not extend too far beyond the actual data limits, which can occur when using a large blanking distance with widely spaced data.
tol – The tolerance required for each grid cell. The default is 0.1 percent of the range of the data. Decrease for a more accurate grid.
pastol – The percentage of points that must meet the tolerance. The iteration process will stop when the percentage of points change by higher than this required percentage in iteration. The default is 100.0 percent. Decrease for rough data to reduce minimum curvature overshoot, and increase for a to make the grid surface more accurately match the data. Overshoot can also be controlled by increasing tension (ti).
itrmax – Maximum number of iterations to use in solving the minimum curvature function. The default is 200 iterations. Increase for a more accurate grid. A value of 1000 is typically sufficient for maximum accuracy.
ti – The degree of internal tension ( between 0 and 1 ). The default is no tension (0.0) which produces a true minimum curvature surface. Increasing tension can prevent overshooting of valid data in sparse areas at the expense of increased local curvature near data points.
icgr – The course grid size relative to the final grid size. Allowable factors are 16,8,4,2 or 1. The default is 8. The optimum is a factor close to half the nominal data spacing, although in most situations the default is fine. This parameter effects the length of time it takes to find a solution.
The
data
parameter:The data can be provided to the gridding algorithm either as a list array, a callback function that returns list array segments, or a
geosoft.gxpy.gdb.Geosoft_database
instance. In the case of a list or a callback, a temporary database is constructed internally.A callback is passed a sequence number, 0, 1, 2, … and is expected to return a list array with each call or None when there is no more data. See the example below. When a callback is used, the
max_segments
parameter sets the maximum number of lines for the temporary database as each return from the callback will create a new line in the internal temporary database.If a database instance is passed it must be the first item in a tuple of 2 or 4 items: (gdb_instance, value_channel) or (gdb_instance, value_channel, x_channel, y_channel). In the first case the default spatial (x, y) channels in the database are assumed.
Examples:
import numpy as np import geosoft.gxpy.grid as gxgrd # simple data array xyv = [(45., 10., 100), (60., 25., 77.), (50., 8., 80.)] grid = gxgrd.Grid.minimum_curvature(xyv) # or a numpy array grid = gxgrd.Grid.minimum_curvature(np.array(xyv)) # a database, grid to a cell size of 100 import geosoft.gxpy.gdb as gxgdb gdb = gxgdb.Geosoft_database.open('some_mag_data.gdb') grid = gxgrd.Grid.minimum_curvature((gdb, 'tmi'), cs=100) # a callback, used for very large data, or to feed data efficiently from some other source. nxyv = np.array([[(45., 10., 100), (60., 25., 77.), (50., 8., 81.), (55., 11., 66.)], [(20., 15., 108), (25., 5., 77.), (33., 9., np.nan), (28., 2., 22.)], [(35., 18., 110), (40., 31., 77.), (13., 4., 83.), (44., 4., 7.)]]) def feed_data(n): if n >= len(nxyv): return None return nxyv[n] grid = gxgrd.Grid.minimum_curvature(feed_data, cs=1.)
New in version 9.4.
-
property
name
¶ Grid name, usually the file name without path or extension.
New in version 9.2.
-
classmethod
new
(file_name=None, properties=None, overwrite=False, in_memory=False)[source]¶ Create a new grid file.
- Parameters
file_name –
name of the grid file, None for a temporary grid. See supported file formats)
in_memory – Creates an in-memory grid (file_name will be ignored)
properties – dictionary of grid properties, see
properties()
overwrite – True to overwrite existing file
New in version 9.1.
-
np
(dtype=None)[source]¶ Return a numpy array of grid values in the working dtype.
- Parameters
dtype – desired data type, default is the work_dtype, ignored for color grids
- Returns
numpy array shape (nx, ny) or (nx, ny, 4) containing RGBA bytes in case of color grids
New in version 9.3.1.
-
property
nx
¶ grid x dimension (number of columns)
New in version 9.2.
-
property
ny
¶ grid y dimension (number of rows)
New in version 9.2.
-
classmethod
open
(file_name, dtype=None, mode=0, coordinate_system=None, cell_size=None, expand=None)[source]¶ Open an existing grid file.
- Parameters
file_name –
name of the grid file, with decorations. See supported file formats)
dtype – numpy data type, which will be the grid data type.
mode –
open mode:
FILE_READ
only read the file, properties cannot be changed
FILE_READWRITE
grid stays the same, but properties may change
coordinate_system – desired coordinate system. The grid will be reprojected if necessary.
cell_size – desired cell size, defaults to the current cell size.
expand – if reprojecting or resampling the are can be expanded by this percentage to allow for curved edges in the new coordinate system space. The default expands by 1%. Set to 0 to prevent expansion.
If reprojecting or setting the cell size different from the original grid, the mode must be FILE_READ.
If reprojecting without setting the cell size a default cell size will be calculated in the new coordinate system that is nominally equivalent to the current cell size.
New in version 9.1.
Changed in version 9.4: added reprojection support
-
properties
()[source]¶ Get the grid properties dictionary
- Returns
dictionary of all grid properties
New in version 9.1.
Changed in version 9.4: added ‘unit_of_measure’
-
read_column
(column=None, start=0, length=0)[source]¶ - Parameters
column – column to read, if not specified the next column is read starting from column 0
start – the first point in the column, default is 0
length – number of points to read, the default is to the end of the col.
- Returns
geosoft.gxvv.GXvv
instance
New in version 9.1.
-
read_row
(row=None, start=0, length=None)[source]¶ - Parameters
row – row to read, if not specified the next row is read starting from row 0
start – the first point in the row, default is 0
length – number of points to read, the default is to the end of the row.
- Returns
geosoft.gxvv.GXvv
instance
New in version 9.1.
-
property
remove_on_close
¶ Remove files on close setting, can be set.
-
property
rot
¶ grid rotation angle, degrees azimuth
Note that grid rotations in the gxapi GXIMG are degrees clockwise, which is the opposite of degree azimuth, used here. All horizontal plane angles in the Python gxpy module are degrees azimuth for consistency.
New in version 9.2.
-
property
rotation_cos_sine
¶ Returns grid rotation (cosine, sine).
New in version 9.3.1.
-
set_properties
(properties)[source]¶ Set grid properties from a properties dict. Settable property keys are:
‘x0’
grid X origin location (default 0.0)
‘y0’
grid Y origin location (0.0)
‘dx’
grid X point separation (1.0)
‘dy’
grid Y point separation (1.0)
‘rot’
grid rotation angle in degrees azimuth (0.0)
‘unit_of_measure’
unit of measure for the grid data
‘coordinate_system’
coordinate system (unchanged)
Not all keys need be passed, though typically one will get the properties from the grid and modify those that need to change and pass the properties back.
- Parameters
properties – properties dictionary
New in version 9.1.
-
statistics
(gxst=None)[source]¶ Calculate and return current grid data statistics as a dictionary.
- Parameters
gxst – gxapi.GXST instance, to which stats will be accumulated, or None.
- Returns
dictionary of grid data statistics:
min
minimum
max
maximum
mean
mean
geometric_mean
geometric mean
variance
variance
sd
standard deviation
skew
skew
kurtosis
kurtosis
sum
sum of all data
sum_power_2
sum of data**2
sum_power_3
sum of data**3
sum_power_4
sum of data**4
num_data
number of valid data values
num_dummy
number of dummy values
New in version 9.4.
-
property
unit_of_measure
¶ Units of measurement (a string) for the grid data, can be set.
New in version 9.2.
-
write_column
(data, column=None, start=0, length=None)[source]¶ - Parameters
data – data to write,
geosoft.gxpy.vv.GXvv
instance or an arraycolumn – column to write, if not specified the next column is written starting from column 0
start – the first point in the column, default is 0
length – number of points to write, the default is to the end of the row.
New in version 9.4.
-
write_row
(data, row=None, start=0, length=None)[source]¶ - Parameters
data – data to write,
geosoft.gxpy.vv.GXvv
instance or an arrayrow – row to write, if not specified the next row is written starting from row 0
start – the first point in the row, default is 0
length – number of points to read, the default is to the end of the row.
New in version 9.4.
-
write_rows
(data, ix0=0, iy0=0, order=1)[source]¶ Write data to a grid by rows.
- Parameters
data – array of data to write, numpy, list or
geosoft.gxapi.GXPG
ix0 – grid X index of first point
iy0 – grid Y index of first point, top index if writing rows top to bottom
order – 1: bottom to top; -1: top to bottom
New in version 9.1.
Changed in version 9.4: accepts list or GXPG
-
property
x0
¶ grid origin x location in the plane coordinate system
New in version 9.2.
-
xy_from_index
(ix, iy)[source]¶ Return the rotated location of grid index ix, iy
- Parameters
ix – grid index x
iy – grid index y
New in version 9.4.
-
xyz
(item)[source]¶ Returns the (x, y, z) location of an indexed point in the grid.
- Parameters
item – tuple (ix, iy) grid point, or the point number counting by row
- Returns
tuple (x, y, z) location
New in version 9.2.1.
-
xyzv
()[source]¶ Return a numpy float array of (x, y, z, v) grid points.
x, y, z) is the location of each grid point in 3D space and v is the grid value at that location. Dummies will be numpy.nan.
- Returns
numpy array shape (nx, ny, 4)
New in version 9.2.
-
property
y0
¶ grid origin y location in the plane coordinate system
New in version 9.2.
-
exception
GridException
(message)[source]¶ Bases:
geosoft.GXRuntimeError
Exceptions from
geosoft.gxpy.grid
.New in version 9.1.
-
array_locations
(properties)[source]¶ Create an array of (x,y,z) points for a grid defined by properties :param properties: grid properties :returns: array of points, shaped (ny, nx, 3)
New in version 9.1.
-
decorate_name
(name, decorations='')[source]¶ Properly decorate a grid name.
- Parameters
name – file name
decorations – file decorations, semicolon delimited
- Returns
decorated file name
New in version 9.1.
-
delete_files
(file_name)[source]¶ Delete all files associates with this grid name.
- Parameters
file_name – name of the grid file
New in version 9.2.
-
figure_map
(grid_file, map_file=None, shade=True, color_map=None, contour=None, **kwargs)[source]¶ Create a map figure from a grid file.
- Parameters
grid_file – grid file name
map_file – name of the map file, if
None
a default map is created.shade –
True
to add shading effectcolor_map –
geosoft.gxpy.group.Color_map
instance, or a colour ramp file name, default is user’s defaultcontour – colour contour interval if colours need to break at exact levels
kwargs – passed to
geosoft.gxpy.agg.Aggregate_image.figure_map
andgeosoft.gxpy.map.Map.new
- Returns
geosoft.gxpy.map.Map
instance
New in version 9.3.
-
grid_bool
(*args, **kwargs)[source]¶ Deprecated since version 9.4: use
geosoft.gxpy.grid_utility.grid_bool
-
grid_mosaic
(*args, **kwargs)[source]¶ Deprecated since version 9.4: use
geosoft.gxpy.grid_utility.grid_mosaic
-
image_file
(grid_file, image_file=None, image_type='PNG', pix_width=None, shade=True, color_map=None, contour=None, display_area=None, pix_32_bit=False)[source]¶ Save a grid file grid as a georeferenced image file.
- Parameters
grid_file – grid file name
image_file – image file name. The extension should be consistent with the image_type. If not specified a temporary PNG file is created.
image_type – image type, one ot the RASTER_FORMAT constants in
geosoft.gxpy.map
.pix_width – desired image width in pixels, default is the width of the aggregate base layer
shade –
True
to add shading effectcolor_map –
geosoft.gxpy.group.Color_map
instance, or a colour ramp file name, default is grid’s defaultcontour – colour contour interval if colours need to break at exact levels
display_area –
geosoft.gxpy.geometry.Point2
instance, which defines the desired display area. The display area coordinate system can be different from the grid.pix_32_bit – make 32-bit image (with 8-bit alpha background)
- Returns
image file name.
New in version 9.3.1.
-
name_parts
(name)[source]¶ Return folder, undecorated file name + ext, file root, ext, decorations.
If extension is not specified, “.grd” assumed
For example:
>>> import geosoft.gxpy.grid as gxgrd >>> namep = gxgrd.name_parts("f:/someFolder/name.grd(GRD;TYPE=SHORT)") >>> print(namep) ('f:/someFolder/','name.grd','name','.grd','(GRD;TYPE=SHORT)')
New in version 9.1.
-
reopen
(g, dtype=None, mode=1)[source]¶ Reopen a grid to access the grid as an existing grid.
Some gxapi.GXIMU methods will not work with grids open as new grids. This method closes the grid and reopens in the specific mode
- Parameters
g –
Grid
instancedtype – data type, None to match the data type of the grid being reopened
mode –
FILE_READWRITE
(default) orFILE_READ
- Returns
new
Grid
instance
New in version 9.4.