geosoft.gxpy.utility submodule¶
Utility functions to support Geosoft Python scripts and modules.
Note
Regression tests provide usage examples: Tests
-
class
geosoft.gxpy.utility.
Property_tree
¶ Bases:
object
Class to work with property trees, supporting serialization to things like XML.
-
exception
geosoft.gxpy.utility.
UtilityException
¶ Bases:
Exception
Exceptions from
geosoft.gxpy.utility
.New in version 9.1.
-
geosoft.gxpy.utility.
check_version
(v, raise_on_fail=True)¶ Check the minimum API version.
Parameters: - v – minimum version string required (ie “9.1” or “9.2.4”)
- raise_on_fail – if True, raises an error if the version check fails, returns False otherwise
Returns: True if version is OK, False otherwise(unless raise_on_fail is False)
Note
A valid version consists of two or three dot-separated numeric components, with an optional development version tag on the end. The development version tag consists of the letter ‘b’ (for beta) followed by a number. If the numeric components of two version numbers are equal, then a development version will always be deemed earlier (lesser) than one without.
The following are valid version numbers (shown in order of used for meeting minimum requirements):
- 9.1 or 9.1.0 (they are equivalent)
- 9.1.1b0 (development version)
- 9.1.1
- 9.2
The following are examples of invalid version numbers:
- 1
- 2.7.2.2
- 1.3.a4
- 1.3pl1
- 1.3c4
The rationale for this version numbering system is explained in the distutils documentation.
New in version 9.1.
-
geosoft.gxpy.utility.
crc32
(bytes, crc=0)¶ Return 32-bit CRC of a byte buffer.
Parameters: - bytes – byte buffer (fulfills the Buffer Protocol)
- crc – seed crc, can be passed along to accumulate the crc
New in version 9.2.
-
geosoft.gxpy.utility.
crc32_file
(filename, crc=0)¶ Return 32-bit CRC of a file.
Parameters: - filename – file name
- crc – seed crc, default 0
New in version 9.2.
-
geosoft.gxpy.utility.
crc32_str
(s, crc=0)¶ Return 32-bit CRC of a string.
Parameters: - s – string
- crc – seed crc, default 0
New in version 9.2.
-
geosoft.gxpy.utility.
datetime_from_year
(year)¶ Return the Python datetime from a decimal Gregorian year.
Parameters: year – decimal year on the Gregorian calendar. Returns: datetime (resolved to 1 millisecond) New in version 9.2.
-
geosoft.gxpy.utility.
decode
(s, f)¶ Decode a string (s) to a numpy format defined by string (f).
Parameters: - s – string to decode
- f –
format string:
b Boolean i (signed) integer u unsigned integer f floating-point S string, interpreted as ‘U’ unicode a string, interpreted as ‘U’ unicode U unicode, requires length suffix, ie ‘U1’, ‘U14’
Times: Times in the form hh:mm:ss.sss return a decimal hour.
Dates: Dates in form yyyy-mm-dd, yyyy-m-d, yy/mm/dd or yyyy/m/d will be decoded naturally and return a decimal Gregorian year. Other date formats will raise a ValueErr.
Errors: TypeError if unable to recognize type ValueError if there is a problem with the string. New in version 9.1.
-
geosoft.gxpy.utility.
dict_from_lst
(lst, ordered=False)¶ Return a dictionary from a Geosoft
geosoft.gxapi.GXLST
instance.Parameters: - lst –
geosoft.gxapi.GXLST
instance - ordered – True to return an OrderedDict
Returns: python dictionary from a Geosoft GXLST
New in version 9.1.
- lst –
-
geosoft.gxpy.utility.
dict_from_reg
(reg, ordered=False)¶ dictionary from a
geosoft.gxapi.GXREG
instanceParameters: - reg –
geosoft.gxapi.GXREG
instance - ordered – True to return and OrderedDict
Returns: python dictionary from a Geosoft GXREG
New in version 9.1.
- reg –
-
geosoft.gxpy.utility.
dict_from_xml
(xml)¶ Return a dictionary of an xml string.
Parameters: xml – xml string Returns: dictionary of the XML content. If the XML root is ‘__gx_xml__’, the root is stripped.
Based on: https://github.com/martinblech/xmltodict
Tag attributes will become keys with ‘@’ as the first character, and the key value will be the attribute setting.
For example, XML string:
<?xml version="1.0" encoding="UTF-8"?> <gmd:MD_Metadata xsi:schemaLocation="http://www.isotc211.org/2005/gmd ../schemas/iso19139fra/gmd/gmd.xsd"> <geosoft xmlns="http://www.geosoft.com/schema/geo"> <dataset version="1" beta="abc"> <title>test_grid_1</title> <file_format>Geosoft Grid</file_format> </dataset> </geosoft> </gmd:MD_Metadata>
returns dictionary:
{'gmd:MD_Metadata': { '@xsi:schemaLocation': "http://www.isotc211.org/2005/gmd ../schemas/iso19139fra/gmd/gmd.xsd", 'geosoft': { '@xmlns': "http://www.geosoft.com/schema/geo", 'dataset': { '@beta': "abc", '@version': "1", 'title': "test_grid_1", 'file_format': "Geosoft Grid" } } } }
See also
New in version 9.2.
-
geosoft.gxpy.utility.
display_message
(title, message)¶ Display a message to the user.
Parameters: - title – message title
- message – message
New in version 9.1.
-
geosoft.gxpy.utility.
dtype_gx
(gtype)¶ Returns: numpy dtype from a GX type New in version 9.1.
-
geosoft.gxpy.utility.
dummyMask
(npd)¶ Deprecated since version 9.2: use dummy_mask()
-
geosoft.gxpy.utility.
dummy_mask
(npd)¶ Return a 1-D dummy mask that is True for all rows in a 2D numpy array that have a Geosoft dummy value.
Parameters: npd – numpy data array Returns: numpy 1D array, True for any row that had a dummy in any data field New in version 9.2.
-
geosoft.gxpy.utility.
dummy_none
(v)¶ Returns None if dummy, otherwise the value.
New in version 9.2.
-
geosoft.gxpy.utility.
dummy_to_nan
(data)¶ Replaces dummies in float data to numpy.nan. All other data types are returned unchanged.
Parameters: data – float value or a numpy array Returns: data with dummies replaced by numpy.nan New in version 9.2.
-
geosoft.gxpy.utility.
folder_temp
()¶ Return the Geosoft temporary folder name.
Note
If creating temporary files, better to use gx method
temp_file()
, which will create the temporary file in the GX-specific foldertemp_folder
.New in version 9.1.
-
geosoft.gxpy.utility.
folder_user
()¶ Return the Geosoft user configurations folder name.
New in version 9.1.
-
geosoft.gxpy.utility.
folder_workspace
()¶ Return the Geosoft project folder name.
New in version 9.1.
-
geosoft.gxpy.utility.
geosoft_metadata
(geosoft_file_name)¶ Get the metadata dictionary for a geosoft data file.
Parameters: geosoft_file_name – geosoft supported file name Returns: dictionary of the metadata If the metadata for the file does not exist {‘metadata’: {}} is returned.
New in version 9.2.
-
geosoft.gxpy.utility.
get_parameters
(group='_', parms=None, default=None)¶ Get parameters from the Project Parameter Block.
Parameters: - group – name in the parameter block group name
- parms – if specified only these keys are searched and the value is replaced by the found parameter. Parameter keys are not case sensitive, though if parms is not provided all returned keys will be upper-case.
- default – default value for parameters not found, ignored if parms is provided as a dict, in which case the current key:value settings will be unchanged.
Returns: dictionary containing group parameters
Changed in version 9.2.1: Now retains case on keys passed in to parms, which allows callers to maintain case. Note that if not specifying parms, the returned keys will always be upper-case. Fixed bug handling file name construction on Windows.
New in version 9.1.
Get a dictionary shared by an external application. The shared dictionary is cleared (popped) so a subsequent call will return an empty dictionary.
New in version 9.1.
-
geosoft.gxpy.utility.
gxDummy
(dtype)¶ Deprecated since version 9.2: use gx_dummy()
-
geosoft.gxpy.utility.
gx_dtype
(dtype)¶ Returns: GX type for a numpy dtype New in version 9.1.
-
geosoft.gxpy.utility.
gx_dummy
(dtype)¶ Return the dummy for this value, or this type.
Returns: GX dummy for this data Raises: KeyError if the dtype is not supported New in version 9.2.
-
geosoft.gxpy.utility.
is_float
(gxtype)¶ Return True of gxtype can be stored in a 64-bit float
-
geosoft.gxpy.utility.
is_int
(gxtype)¶ Return True of gxtype can be stored in a 64-bit integer
-
geosoft.gxpy.utility.
is_string
(gxtype)¶ Return length of a gxtype string, 0 (False) if not a string.
-
geosoft.gxpy.utility.
merge_dict
(d, d2)¶ Update a dictionary by adding key-values from second dictionary. Unlike Python’s update(), this adds new keys to nested dictionaries rather than replace everything in a nested dictionary.
Parameters: - d – dictionary to update
- d2 – new items to add or replace
Returns: merged dictionary
New in version 9.2.
-
geosoft.gxpy.utility.
normalize_file_name
(fn)¶ Normalize a file name string by replacing ‘’ with ‘/’. This is useful for writing file names to control files.
Parameters: fn – file name Returns: normalized file name New in version 9.2.
-
geosoft.gxpy.utility.
rdecode
(s)¶ Geosoft string (number, date, time, geographic) conversion to a number, always works.
Parameters: s – string to decode Returns: decoded number, gxapi.rDUMMY if unable to decode the string See rdecode_err(string) for more details.
New in version 9.1.
-
geosoft.gxpy.utility.
rdecode_err
(s)¶ Geosoft string conversion to a number, raising ValueError on failure
Parameters: s – string to be decoded Returns: float of decoded string - If unable to decode string:
- rdecode_err() raises ValueErrorrdecode() returns gxapi.rDUMMY
Any string that begins with “*” character is interpreted as a dummy.
If unable to directly convert simple string, decoder will clean-up the string by removing leading/trailing white space and converting ‘o’ or ‘O’ to numeral ‘0’.
If decoder still fails, it will attempt to decode time and geographic formatted strings to return decimal hours or decimal degrees respectively:
Date: yyyy-mm-ddyyyy/mm/dddate will be fractional Gregorian yearTime: hh:mm:ss.ssAM/amhh:mm:ss.ssPM/pmPM/pm adds 12 hours (for example 2:30pm returns 14.5)Geographic: [+/-]deg mm ss.ss[N/S/E/W/n/s/e/w][+/-]deg.mm.ss.ss[N/S/E/W/n/s/e/w]S/s and W/w return negative of decoded valueExample:“-90 15 18.0” = “90 15 18.0W” = “90.15.18w”, returns -90.255“14” = “14N” = “14.00.00” = “14 00 00”, returns 14.0Note that mm and ss.ss can go over 60.0 and will be decoded as minutes or seconds as presented. For example, “20 90 0.00” will return 21.5.
New in version 9.1.
-
geosoft.gxpy.utility.
reg_from_dict
(rd, max_size=4096, json_encode=True)¶ geosoft.gxapi.GXREG
instance from a dictionaryParameters: - rd – dictionary
- max_size – maximum “key=value” string size
- json – True to encode non-string values as sas json strings (prefix ‘_JSON:’)
False will encode non-string values as
str(value)
Returns: geosoft.gxapi.GXREG
instanceNon-string values in the dictionary are converted to JSON strings and stored as “_JSON:json-string}”
-
geosoft.gxpy.utility.
run_external_python
(script, script_args='', python_args='', dict=None, console=True, catcherr=True)¶ Run a python script as an external program, returning results as a dictionary. External program calls gxpy.utility.get_shared_dict() to get the caller’s dictionary, and gxpy.utility.set_shared_dict(return_dictionary) to return a dictionary back to caller.
Parameters: - script – full path of the python script
- dict – dictionary passed to the external script (get_shared_dict() to retrieve)
- script_args – command line arguments as a string
- python_args – command line arguments as a string
- console – True (default) will create a separate console for the process.
- catcherr – True (default) Catch and re-raise errors from the sub-process.
Returns: dictionary passed back from caller via set_shared_dict(dict)
New in version 9.1.
-
geosoft.gxpy.utility.
save_parameters
(group='_', parms=None)¶ Save parameters to the Project Parameter Block. Parameter group names and member names are converted to uppercase.
Parameters: - group – parameter block group name, default is ‘_’
- parms – dict containing named parameter settings, must be specified
New in version 9.1.
Save a dictionary to be shared by an separate application. This is a companion file to run_external_python().
Parameters: dict – dictionary of parameters to save New in version 9.1.
-
geosoft.gxpy.utility.
str_significant
(value, n, mode=0)¶ Return a formatted string to n significant figures.
Parameters: - value – value to format
- mode – 0 round, 1 ceiling, -1 floor
Returns: string to n significant figures
-
geosoft.gxpy.utility.
time_stamp
()¶ current date-time as a string.
-
geosoft.gxpy.utility.
uuid
()¶ Returns: a uuid as a string New in version 9.2.
-
geosoft.gxpy.utility.
xml_from_dict
(d, pretty=False)¶ Return a unicode XML string of a dictionary.
Parameters: - d – dictionary
- pretty – True to indent with line-feeds for pretty-printing
If the dictionary does not have a single node root, the root XML will be ‘__gx_xml__’.
Based on: https://github.com/martinblech/xmltodict
See also
New in version 9.2.
-
geosoft.gxpy.utility.
yearFromJulianDay2
(jd1, jd2)¶ Julian year
Parameters: - jd1 – part 1 Julian date (https://pypi.python.org/pypi/jdcal)
- jd2 – part 2 Julian date
Returns: decimal Gregorian year (Western calendar year)
New in version 9.1.
-
geosoft.gxpy.utility.
year_from_datetime
(dt)¶ Return a decimal Gregorian calendar year from a Python datetime.
Parameters: dt – datetime Returns: decimal Gregorian year to an accuracy of 1 millisecond New in version 9.2.