mtpy.utils package
Submodules
mtpy.utils.array2raster module
mtpy.utils.basemap_tools module
- mtpy.utils.basemap_tools.add_basemap_frame(basemap, tick_interval=None, coastline_kwargs={}, states_kwargs={}, mlabels=[False, False, False, True], plabels=[True, False, False, False])[source]
Add a standard map frame (lat/lon labels and tick marks, coastline and states) to basemap. :param basemap: :param tick_interval: Tick interval in degrees, defaults to None. :param coastline_kwargs: Dictionary containing arguments to pass into the drawcoastlines function, defaults to {}. :param states_kwargs: Dictionary containing arguments to pass into the drawstates function, defaults to {}. :param mlabels: Where to place meridian (longitude) labels on plot (list containing True/False for [left,right,top,bottom]), defaults to [False, False, False, True]. :param plabels: Where to place parallels (latitudes) labels on plot (list containing True/False for [left,right,top,bottom]), defaults to [True, False, False, False].
- mtpy.utils.basemap_tools.compute_lonlat0_from_modem_data(stations_obj)[source]
Compute lat0 and lon0 for creating a basemap, using data centre point in modem data file.
- mtpy.utils.basemap_tools.compute_map_extent_from_modem_data(stations_obj, buffer=None, buffer_factor=0.1)[source]
Compute extent for a plot from data extent from ModEM data file. :param buffer_factor:
Defaults to 0.1.
- Parameters:
stations_obj
data_fn – Full path to modem data file.
buffer – Optional argument; buffer in latitude/longitude (if not provided,, defaults to None.
- mtpy.utils.basemap_tools.compute_tick_interval_from_map_extent(lonMin, lonMax, latMin, latMax)[source]
Estimate an even tick interval based on map extent based on some sensible options.
- mtpy.utils.basemap_tools.get_latlon_extents_from_modem_data(stations_obj)[source]
Get latlon extents from modem data.
- mtpy.utils.basemap_tools.initialise_basemap(stations_obj, buffer=None, **basemap_kwargs)[source]
Create a new basemap instance.
- mtpy.utils.basemap_tools.plot_data(x, y, values, basemap=None, cbar=False, **param_dict)[source]
Plot array data, either 1d or 2d. :param **param_dict: :param x: X position of points. :param y: Y position of points. :param values: Values to plot, if 1D, a scatter plot will be made, if 2D, a pcolormesh plot will be made. :param basemap: Supply a basemap, if None, data will be plotted on current axes, defaults to None. :param cbar: True/False, whether or not to show a colorbar, defaults to False.
mtpy.utils.calculator module
mtpy/utils/calculator.py
Helper functions for standard calculations, e.g. error propagation
@UofA, 2013 (LK)
- mtpy.utils.calculator.centre_point(xarray, yarray)[source]
Get the centre point of arrays of x and y values.
- mtpy.utils.calculator.compute_determinant_error(z_array, z_err_array, method='theoretical', repeats=1000)[source]
Compute the error of the determinant of z using a stochastic method seed random z arrays with a normal distribution around the input array :param repeats:
Defaults to 1000.
- Parameters:
z_array – Z (impedance) array containing real and imaginary values.
z_err_array – Impedance error array containing real values, in MT we assume the real and imag errors are the same.
method – Method to use, theoretical calculation or stochastic, defaults to “theoretical”.
- Returns:
Error: array of real values with same shape as z_err_array representing the error in the determinant of Z.
- Returns:
Error_sqrt: array of real values with same shape as z_err_array representing the error in the (determinant of Z)**0.5.
- mtpy.utils.calculator.get_period_list(period_min, period_max, periods_per_decade, include_outside_range=True)[source]
Get a list of values (e.g. periods), evenly spaced in log space and including values on multiples of 10 :return s: Numpy array containing list of values.
- mtpy.utils.calculator.get_rotation_matrix(angle, clockwise=False)[source]
get the rotation matrix for the proper rotation
- Parameters:
angle (float) – angle in degrees to rotate by
clockwise (bool) – [ True | False ] if False counterclockwise rotation matrix is returned
- mtpy.utils.calculator.invertmatrix_incl_errors(inmatrix, inmatrix_error=None)[source]
Invertmatrix incl errors.
- mtpy.utils.calculator.make_log_increasing_array(z1_layer, target_depth, n_layers, increment_factor=0.999)[source]
Create depth array with log increasing cells, down to target depth, inputs are z1_layer thickness, target depth, number of layers (n_layers)
- mtpy.utils.calculator.multiplymatrices_incl_errors(inmatrix1, inmatrix2, inmatrix1_error=None, inmatrix2_error=None)[source]
Multiplymatrices incl errors.
- mtpy.utils.calculator.nearest_index(val, array)[source]
Find the index of the nearest value in the array. :param val: The value to search for. :param array: The array to search in. :return: Index: integer describing position of nearest value in array.
- mtpy.utils.calculator.propagate_error_polar2rect(r, r_error, phi, phi_error)[source]
Find error estimations for the transformation from polar to cartesian coordinates.
Uncertainties in polar representation define a section of an annulus. Find the 4 corners of this section and additionally the outer boundary point, which is defined by phi = phi0, rho = rho0 + sigma rho. The cartesian “box” defining the uncertainties in x,y is the outer bound around the annulus section, defined by the four outermost points. So check the four corners as well as the outer boundary edge of the section to find the extrema in x znd y. These give you the sigma_x/y.
- mtpy.utils.calculator.propagate_error_rect2polar(x, x_error, y, y_error)[source]
Propagate error rect2polar.
- mtpy.utils.calculator.reorient_data2D(x_values, y_values, x_sensor_angle=0, y_sensor_angle=90)[source]
Re-orient time series data of a sensor pair, which has not been in default (x=0, y=90) orientation.
Input: - x-values - Numpy array - y-values - Numpy array Note: same length for both! - If not, the shorter length is taken
Optional: - Angle of the x-sensor - measured in degrees, clockwise from North (0) - Angle of the y-sensor - measured in degrees, clockwise from North (0)
Output: - corrected x-values (North) - corrected y-values (East)
- mtpy.utils.calculator.rhophi2z(rho, phi, freq)[source]
Convert impedance-style information given in Rho/Phi format into complex valued Z.
Input: rho - 2x2 array (real) - in Ohm m phi - 2x2 array (real) - in degrees freq - scalar - frequency in Hz
Output: Z - 2x2 array (complex)
- mtpy.utils.calculator.rotate_matrix_errors(error, angle)[source]
Rotate errors of a matrix
- Parameters:
error (np.array) – error matrix (2 x 2)
angle (float) – rotation angle in degrees
- Returns:
propogated errors
- Return type:
None or np.array
- mtpy.utils.calculator.rotate_matrix_with_errors(in_matrix, angle, error=None, clockwise=True)[source]
Rotate a matrix including errors given an angle in degrees.
- Parameters:
in_matrix (np.ndarray) – A n x 2 x 2 matrix to rotate.
angle (float) – Angle to rotate by assuming clockwise positive from 0 = north.
error (np.ndarray, optional) – A n x 2 x 2 matrix of associated errors,, defaults to None.
clockwise (bool) – rotate clockwise [True] or counter-clockwise [False]
- Raises:
MTex – If input array is incorrect.
- Returns:
Rotated matrix.
- Return type:
np.ndarray
- Returns:
Rotated matrix errors.
- Return type:
np.ndarray
- mtpy.utils.calculator.rotate_vector_with_errors(in_vector, angle, error=None, clockwise=True)[source]
Rotate a vector including errors given an angle in degrees.
- Parameters:
in_vector
in_matrix (np.ndarray) – A n x 1 x 2 vector to rotate.
angle (float) – Angle to rotate by assuming clockwise positive from 0 = north.
error (np.ndarray, optional) – A n x 1 x 2 vector of associated errors,, defaults to None.
- Raises:
MTex – If input array is incorrect.
- Returns:
Rotated vector.
- Return type:
np.ndarray
- Returns:
Rotated vector errors.
- Return type:
np.ndarray
- mtpy.utils.calculator.roundsf(number, sf)[source]
Round a number to a specified number of significant figures (sf).
- mtpy.utils.calculator.z_error2r_phi_error(z_real, z_imag, error)[source]
Error estimation from rectangular to polar coordinates.
By standard error propagation, relative error in resistivity is 2*relative error in z amplitude.
Uncertainty in phase (in degrees) is computed by defining a circle around the z vector in the complex plane. The uncertainty is the absolute angle between the vector to (x,y) and the vector between the origin and the tangent to the circle. :return s: Tuple containing relative error in resistivity, absolute error in phase.
mtpy.utils.concatenate_input module
- Description:
This script collates data from raw data files in a folder, within a time-range provided by the user and outputs corresponding .EX, .EY, .EZ, .BX, .BY and .BZ files in an output folder.
References:
CreationDate: 2017/10/23 Developer: rakib.hassan@ga.gov.au
- Revision History:
LastUpdate: 2017/10/23 RH
mtpy.utils.configfile module
Helper functions for the handling of configuration files (survey.cfg and BIRRP.cfg style).
@UofA, 2013 (LK)
- mtpy.utils.configfile.read_configfile(filename)[source]
Read a general config file and return the content as dictionary.
Config files without sections or only DEFAULT section -> return dictionary
Config files with sections -> return nested dictionary (main level keys are section heads)
Config files with sections as well as section-less entries -> return nested dictionary, which includes a top level ‘DEFAULT’ key
- mtpy.utils.configfile.read_survey_configfile(filename)[source]
Read in a survey configuration file and return a dictionary.
Input config file must contain station names as section headers!
The output dictionary keys are station names (capitalised), the values are (sub-)dictionaries. The configuration file must contain sections for all stations, each containing all mandatory keywords:
latitude (deg)
longitude (deg)
elevation (in meters)
sampling_interval (in seconds)
station_type (MT, (Q)E, (Q)B)
Not mandatory, but recommended - declination (in degrees, positive to East) - this is set to ‘0.0’, if omitted
Depending on the type of station the following entries are required.
E-field recorded:
E_logger_type (‘edl’/’elogger’/’qel’)
E_logger_gain (factor/gain-level)
E_instrument_type (‘electrodes’/’dipole’)
E_instrument_amplification (applied amplification factor)
E_Xaxis_azimuth (degrees)
E_Xaxis_length (in meters)
E_Yaxis_azimuth (degrees)
E_Yaxis_length (in meters)
B-field recorded: - B_logger_type (‘edl’/’qel_blogger’) - B_logger_gain (factor/gain level) - B_instrument_type (‘coil(s)’, ‘fluxgate’) - B_instrument_amplification (applied amplification factor) - B_Xaxis_azimuth (degrees) - B_Yaxis_azimuth (degrees)
A global section can be used to include parameters for all stations. The name of the section must be one of:
global/main/default/general
- mtpy.utils.configfile.read_survey_txt_file(survey_file, delimiter=None)[source]
- Read survey file and return a dictionary of dictionaries where the first
nested dictionary is keyed by the station name. Each station dictionarly includes all the information input in the survey file with keywords verbatim as the headers in survey file, all lower case.
Must be included in survey file ================= ========================================================= key word description ================= ========================================================= station station name lat(itude) latitude (decimal degrees is best) long(itude) longitude (decimal degrees is best) elev(ation) elevation (in meters) ex/E_Xaxis_length dipole length in north direction (in meters) ey/E_Yaxis_length dipole length in east direction (in meters) E_Xaxis_azimuth orientaion of Ex (degrees) E_Yaxis_azimuth orientaion of Ey (degrees)
sampling_interval sampling interval in seconds hx coil number in north direction for calibration hy coil number in east direction for calibration hz coil number in vertical direction for calibration date date of deployment notes any notes that might help later station_type type of data collected (MT, E, B) declination declination in degrees (N = 0 and East = 90) ================= =========================================================
Information on E-field data: ========================== ================================================ key word description ========================== ================================================ E_logger_type type of data logger used to record data E_logger_gain factor/gain level E_instrument_type type of electrodes used E_instrument_amplification applied amplification factor E_Xaxis_azimuth orientaion of Ex (degrees) E_Xaxis_length length of dipole for Ex (in meters) E_Yaxis_azimuth orientaion of Ey (degrees) E_Yaxis_length length of dipole for Ey (in meters) ========================== ================================================
- Information on B-field data:
survey_file : string (full path to file)
- survey_lstlist
list of dictionaries with key words the same as the headers in survey file, all lower case
- mtpy.utils.configfile.write_config_from_survey_txt_file(survey_file, save_name=None, delimiter='\t')[source]
Write a survey configuration file from a survey txt file .
- Arguments::
- survey_filestring
full path to survey text file. See read_survey_txt_file for the assumed header information.
- save_namestring
name to save file to. If save_name = None, then file saved as os.path.join(os.path.dirname(survey_file,
os.path.basename(survey_file).cfg)
- Outputs::
- cfg_fnstring
full path to saved config file
- mtpy.utils.configfile.write_dict_to_configfile(dictionary, output_filename)[source]
Write a dictionary into a configuration file.
The dictionary can contain pure key-value pairs as well as a level-1 nested dictionary. In the first case, the entries are stored in a ‘DEFAULT’ section. In the latter case, the dictionary keys are taken as section heads and the sub-dictionaries key-value pairs fill up the respective section
mtpy.utils.convert_modem_data_to_geogrid module
mtpy.utils.edi_folders module
- Description:
Find path to all the directories which contain a given type of files: .edi, .py .jpg, .pdf
- How to Run:
python mtpy/utils/edi_folders.py . EDI python mtpy/utils/edi_folders.py /e/Data/ EDI 2 python mtpy/utils/edi_folders.py /e/Data/ PY
CreationDate: 26/11/2017 Developer: fei.zhang@ga.gov.au
- Revision History:
LastUpdate: 26/11/2017 FZ started the first version
- class mtpy.utils.edi_folders.EdiFolders(startDir, edifiles_threshold=1, filetype='.edi')[source]
Bases:
object
- mtpy.utils.edi_folders.recursive_glob(dirname, ext='*.edi')[source]
Under the dirname recursively find all files with extension ext.
Return a list of the full-path to the types of files of interest.
This function is useful to handle a nested directories of EDI files. :param dirname: A single dir OR a list of dirs. :param ext: Eg, “.edi”, “.xml”, defaults to “*.edi”. :return: A list of path2files.
mtpy.utils.estimate_tf_quality_factor module
Created on Wed Mar 6 09:43:07 2019
Estimate Transfer Function Quality
based on simple statistics
@author: jpeacock
- class mtpy.utils.estimate_tf_quality_factor.EMTFStats(z_object, t_object, **kwargs)[source]
Bases:
objectClass to estimate data quality of EM transfer functions. :param **kwargs: :param t_object: :param z_object: :param tf_dir: Transfer function directory. :type tf_dir: string :param stat_limits: Criteria for statistics based on a 0-5 rating scale. :type stat_limits: dictionary
- compute_statistics()[source]
Compute statistics of the transfer functions in a given directory.
Statistics are:
one-lag autocorrelation coefficient, estimator for smoothness
average of errors on components
fit to a least-squres smooth curve
normalized standard deviation of the first derivative, another smoothness estimator
- Parameters:
tf_dir (string) – Path to directory of transfer functions.
- Return s:
Data frame of all the statistics estimated.
- Rtype s:
pandas.DataFrame
- estimate_data_quality(stat_df)[source]
Convert the statistical estimates into the rating between 0-5 given a certain criteria.
Note
To change the criteria change self.stat_limits
- Parameters:
stat_df (pandas.DataFrame) – Dataframe of the statistics.
stat_fn (string) – Name of .csv file of statistics.
- Return s:
A dataframe of the converted statistics.
- Rtype s:
pandas.DataFrame
- estimate_quality_factor(weights={'bad': 0.35, 'corr': 0.2, 'diff': 0.2, 'fit': 0.05, 'std': 0.2}, round_qf=False)[source]
Convenience function doing all the steps to estimate quality factor.
- summarize_data_quality(quality_df, weights={'bad': 0.35, 'corr': 0.2, 'diff': 0.2, 'fit': 0.05, 'std': 0.2})[source]
Summarize the data quality into a single number for each station. :param quality_df: Dataframe of the quality factors. :type quality_df: pandas.DataFrame :param quality_fn: Name of .csv file of quality factors. :type quality_fn: string :return s: A dataframe of the summarized quality factors. :rtype s: pandas.DataFrame
mtpy.utils.exceptions module
Specific exceptions for MTpy.
@UofA, 2013 (LK)
mtpy.utils.filehandling module
Helper functions for file handling.
The various functions deal with renaming, sorting, concatenation of time series, extraction of names and times from filenames, reading configuration files, ….
@UofA, 2013 (LK)
- mtpy.utils.filehandling.EDL_get_starttime_fromfilename(filename)[source]
Return starttime of data file in epoch seconds.
Starting time is determined by the filename. This has to be of the form ‘somthing/*.stationname.ddmmyyHHMMSS.??’
- mtpy.utils.filehandling.EDL_get_stationname_fromfilename(filename)[source]
Edl get stationname fromfilename.
- mtpy.utils.filehandling.EDL_make_Nhour_files(n_hours, inputdir, sampling, stationname=None, outputdir=None)[source]
See ‘EDL_make_dayfiles’ for description and syntax.
Only difference: output files are blocks of (max) N hours, starting to count at midnight (00:00h) each day.
Conditions:
24%%N = 0
input data files start on the hour marks
Not working yet!!
- mtpy.utils.filehandling.EDL_make_dayfiles(inputdir, sampling, stationname=None, outputdir=None)[source]
Concatenate ascii time series to dayfiles (calendar day, UTC reference).
Data can be within a single directory or a list of directories. However, the files in the directory(ies) ‘inputdir’ have to be for one station only, and named with a 2 character suffix, defining the channel!
If the time series are interrupted/discontinuous at some point, a new file will be started after that point, where the file index ‘idx’ is increased by 1. If no stationname is given, the leading non-datetime characters in the first filename are used.
Files are named as ‘stationname_samplingrate_date_idx.channel’ Stationname, channel, and sampling are written to a header line.
Output data consists of a single column float data array. The data are stored into one directory. If ‘outputdir’ is not specified, a subdirectory ‘dayfiles’ will be created witihn the current working directory.
Note: Midnight cannot be in the middle of a file, because only file starts are checked for a new day!!
- mtpy.utils.filehandling.get_filename(fn, save_path, fn_basename)[source]
Get file name from inputs. :param fn: DESCRIPTION. :type fn: TYPE :param save_path: DESCRIPTION. :type save_path: TYPE :param fn_basename: DESCRIPTION. :type fn_basename: TYPE :return: DESCRIPTION. :rtype: TYPE
- mtpy.utils.filehandling.get_pathlist(masterdir, search_stringlist=None, search_stringfile=None, start_dict={}, split='_', extension='', folder=False)[source]
Get a list of files or folders by searching on a string contained in search_stringlist or alternatively search_stringfile
returns: dictionary containing search strings as keys and file/folder as values
masterdir - directory to search in search_stringlist = list containing string identifiers for files or folders,
e.g. k0101 will work for edifile k0101.edi or folder k0101.
- search_stringfile = alternative to search_stringlist (need to provide one)
will get search_stringlist from a file, full path or make sure you are in the correct directory!
start_dict = starting dictionary to append to, default is an empty dict split = if no exact match is found, search string will be split using split
character, useful when matching up edi’s to inversion directories that both contain additional characters
extension = file extension, e.g. ‘.edi’
- mtpy.utils.filehandling.get_sampling_interval_fromdatafile(filename, length=3600)[source]
Find sampling interval from data file.
Provide data file (purely numerical content) and total data length in seconds (default 3600). Data are read in by the Numpy ‘loadtxt’-function, the lentgh of the data array yields the sampling interval.
Lines beginning with # are ignored.
- mtpy.utils.filehandling.get_ts_header_string(header_dictionary)[source]
Return a MTpy time series data file header string from a dictionary.
- mtpy.utils.filehandling.make_unique_folder(wd, basename='run')[source]
Make a folder that doesn’t exist already.
- mtpy.utils.filehandling.read_2c2_file(filename)[source]
Read in BIRRP 2c2 coherence files and return 4 lists containing [period],[freq],[coh],[zcoh]. Note if any of the coherences are negative a value of 0 will be given to them.
- mtpy.utils.filehandling.read_data_header(fn_raw)[source]
Deprecated!!! USE
read_ts_header
INSTEAD
Read the header line of MTpy TS data files.
- input:
MTpy TS data file name
- output:
list of header elements: stationname, channel, sampling rate, starttime first sample, starttime last sample, unit, lat, lon, elevation
- mtpy.utils.filehandling.read_geotiff(filename, target_epsg=None, bounds=None)[source]
Read in a geotiff. :param bounds:
Defaults to None.
- Parameters:
filename (TYPE) – DESCRIPTION.
target_epsg (TYPE, optional) – DESCRIPTION, defaults to None.
- Returns:
DESCRIPTION.
- Return type:
TYPE
- mtpy.utils.filehandling.read_stationdatafile(textfile, read_duplicates=True)[source]
Read a space delimited file containing station info of any sort - 3 columns: station x, y, … - to a dictionary - station:[x,y,…] textfile = full path to text file read_duplicates = True/False - if stations are listed more than once do you
want to read all information or just the first occurrence, default True
example: import mtpy.utils.filehandling as fh stationdict = fh.read_stationxyfile(textfile)
- mtpy.utils.filehandling.read_surface_ascii(ascii_fn)[source]
Read in surface which is ascii format () unlike original function, returns numpy array of lon, lat, elev (no projections)
The ascii format is assumed to be: ncols 2743 nrows 2019 xllcorner 111.791666666667 (lon of lower left) yllcorner -45.341666666667 (lat of lower left) cellsize 0.016666666667 NODATA_value -9999 elevation data origin (0,0) is NW upper left. NW ————–> E | | | | S
- mtpy.utils.filehandling.read_ts_file(mtdatafile)[source]
Read an MTpy TS data file and provide the content as tuple:
(station, channel,samplingrate,t_min,nsamples,unit,lat,lon,elev, data) If header information is incomplete, the tuple is filled up with ‘None’.
- mtpy.utils.filehandling.read_ts_header(tsfile)[source]
Read in the header line from MTpy timeseries data files.
Return header as dictionary. Return empty dict, if no header line was found.
- mtpy.utils.filehandling.reorient_files(lo_files, configfile, lo_stations=None, outdir=None)[source]
Reorient files.
- mtpy.utils.filehandling.sort_folder_list(wkdir, order_file, indices=[0, 9999], delimiter='')[source]
Sort subfolders in wkdir according to order in order_file
wkdir = working directory containing subfolders order = full path to text file containing order.
needs to contain a string to search on that is the same length for each item in the list
indices = indices to search on; default take the whole string
returns a list of directories, in order..
- mtpy.utils.filehandling.validate_save_file(savepath=None, savefile=None, basename=None, prioritise_savefile=False)[source]
Return savepath, savefile and basename, ensuring they are internally consistent and populating missing fields from the others or using defaults.
Prioritises savepath and basename. I.e. if savepath, savefile and basename are all valid but inconsistent, savefile will be updated to reflect savepath and basename :param prioritise_savefile:
Defaults to False.
- Parameters:
savepath – Directory to save to, defaults to None.
savefile – Full file path to save to, defaults to None.
basename – Base file name to save to, defaults to None.
mtpy.utils.gis_tools module
GIS_TOOLS
This module contains tools to help project between coordinate systems. The module will first use GDAL if installed. If GDAL is not installed then pyproj is used. A test has been made for new versions of GDAL which swap the input lat and lon when using transferPoint, so the user should not have to worry about which version they have.
Main functions are:
project_point_ll2utm
project_point_utm2ll
These can take in a point or an array or list of points to project.
- latitude and longitude can be input as:
‘DD:mm:ss.ms’
‘DD.decimal_degrees’
float(DD.decimal_degrees)
Created on Fri Apr 14 14:47:48 2017 Revised: 5/2020 JP Revised: 10/2023 JP
@author: jrpeacock
- mtpy.utils.gis_tools.assert_elevation_value(elevation)[source]
Make sure elevation is a floating point number. :param elevation: Elevation as a float or string that can convert. :type elevation: float or str
- mtpy.utils.gis_tools.assert_lat_value(latitude)[source]
Make sure the latitude value is in decimal degrees, if not change it.
And that the latitude is within -90 < lat > 90. :param latitude: Latitude in decimal degrees or other format. :type latitude: float or string
- mtpy.utils.gis_tools.assert_lon_value(longitude)[source]
Make sure the longitude value is in decimal degrees, if not change it.
And that the latitude is within -180 < lat > 180. :param longitude: :param latitude: Longitude in decimal degrees or other format. :type latitude: float or string
- mtpy.utils.gis_tools.convert_position_float2str(position)[source]
Convert position float to a string in the format of DD:MM:SS. :param position: Decimal degrees of latitude or longitude. :type position: float :return s: Latitude or longitude in format of DD:MM:SS.ms.
- mtpy.utils.gis_tools.convert_position_str2float(position_str)[source]
Convert a position string in the format of DD:MM:SS to decimal degrees. :param position_str: :param position: Latitude or longitude om DD:MM:SS.ms. :type position: float :return s: Latitude or longitude as a float.
- mtpy.utils.gis_tools.project_point(x, y, old_epsg, new_epsg)[source]
Transform point to new epsg. :param x: DESCRIPTION. :type x: TYPE :param y: DESCRIPTION. :type y: TYPE :param old_epsg: DESCRIPTION. :type old_epsg: TYPE :param new_epsg: DESCRIPTION. :type new_epsg: TYPE :return: DESCRIPTION. :rtype: TYPE
- mtpy.utils.gis_tools.project_point_ll2utm(lat, lon, datum='WGS84', epsg=None)[source]
Project a point that is in latitude and longitude to the specified UTM coordinate system. :param lon: :param lat: :param latitude: Latitude in [ ‘DD:mm:ss.ms’ | ‘DD.decimal’ | float ]. :type latitude: [ string | float ] :param longitude: Longitude in [ ‘DD:mm:ss.ms’ | ‘DD.decimal’ | float ]. :type longitude: [ string | float ] :param datum: Well known datum, defaults to “WGS84”. :type datum: string, optional :param epsg: EPSG number defining projection
(see http://spatialreference.org/ref/ for moreinfo) Overrides utm_zone if both are provided, defaults to None.
- Returns:
Project point(s) * tuple is (easting, northing,utm_zone) * recarray has attributes (easting, northing, utm_zone, elevation).
- Return type:
tuple if a single point, np.recarray if multiple points
- mtpy.utils.gis_tools.project_point_utm2ll(easting, northing, utm_epsg, datum_epsg=4326)[source]
Project a point that is in UTM to the specified geographic coordinate system. :param datum_epsg:
Defaults to 4326.
- Parameters:
utm_epsg
easting (float) – Easting in meters.
northing (float) – Northing in meters.
datum (string) – Well known datum.
utm_zone ([ string | int ]) – Utm_zone {0-9}{0-9}{C-X} or {+, -}{0-9}{0-9}.
epsg ([ int | string ]) – EPSG number defining projection (see http://spatialreference.org/ref/ for moreinfo) Overrides utm_zone if both are provided.
- Returns:
Project point(s) * tuple is (easting, northing,utm_zone) * recarray has attributes (easting, northing, utm_zone, elevation).
- Return type:
tuple if a single point, np.recarray if multiple points
- mtpy.utils.gis_tools.validate_input_values(values, location_type=None)[source]
Make sure the input values for lat, lon, easting, northing will be an numpy array with a float data type
can input a string as a comma separated list :param location_type:
Defaults to None.
- Parameters:
values ([ float | string | list | numpy.ndarray ]) – Values to project, can be given as: * float * string of a single value or a comma separate string ‘34.2, 34.5’ * list of floats or string * numpy.ndarray.
- Returns:
Array of floats.
- Return type:
numpy.ndarray(dtype=float)
mtpy.utils.matplotlib_utils module
mtpy.utils.mtpy_decorator module
- class mtpy.utils.mtpy_decorator.deprecated(reason)[source]
Bases:
object- Description:
used to mark functions, methods and classes deprecated, and prints warning message when it called decorators based on https://stackoverflow.com/a/40301488
- Usage:
todo: write usage
Author: YingzhiGou Date: 20/06/2017
mtpy.utils.plot_rms_iterations module
- mtpy.utils.plot_rms_iterations.concatenate_log_files(directory)[source]
Any file of the pattern ‘*.log’ will be included.
The files are
- sorted alphanumerically and this is the order they will be
concatenated in. It is up to the user to ensure that the files are named correctly to achieve the desired order. :param directory: :type directory: str
mtpy.utils.sensor_orientation_correction module
Created on Fri Oct 7 23:28:58 2022
@author: jpeacock
- mtpy.utils.sensor_orientation_correction.correct4sensor_orientation(Z_prime, Bx=0, By=90, Ex=0, Ey=90, Z_prime_error=None)[source]
Correct a Z-array for wrong orientation of the sensors.
- Assume, E’ is measured by sensors orientated with the angles
E’x: a E’y: b
- Assume, B’ is measured by sensors orientated with the angles
B’x: c B’y: d
- With those data, one obtained the impedance tensor Z’:
E’ = Z’ * B’
- Now we define change-of-basis matrices T,U so that
E = T * E’ B = U * B’
=> T contains the expression of the E’-basis in terms of E (the standard basis) and U contains the expression of the B’-basis in terms of B (the standard basis) The respective expressions for E’x-basis vector and E’y-basis vector are the columns of T. The respective expressions for B’x-basis vector and B’y-basis vector are the columns of U.
We obtain the impedance tensor in default coordinates as:
- E’ = Z’ * B’ => T^(-1) * E = Z’ * U^(-1) * B
=> E = T * Z’ * U^(-1) * B => Z = T * Z’ * U^(-1)
- Parameters:
Z_prime_error – Defaults to None.
Ey – Defaults to 90.
Ex – Defaults to 0.
By – Defaults to 90.
Bx – Defaults to 0.
Z_prime – Impedance tensor to be adjusted.
- Return s:
Adjusted impedance tensor.
- Rtype s:
np.ndarray(Z_prime.shape, dtype=’complex’)
- Return s:
Impedance tensor standard deviation in default orientation.
- Rtype s:
np.ndarray(Z_prime.shape, dtype=’real’)
mtpy.utils.shapefiles module
Module contents
Got rid of the GDAL check because have moved geographic operations to use pyproj. There are still some functions that use GDAL, but those are for raster and shapefile making. Therefore the check is not needed.
Created on Tue Sep 5 14:35:54 2023
@author: jpeacock