Classes

Loop

class comet.pyhed.loop.Loop(Input, config=None, verbose=False)[source]

Class for the computation of arbitrary shaped polygon loops. Some functions automatically return this loopclass as result. It is recommended to use these (you may take a look at the example)

Parameters:
  • Input (string or raw loop class) – Filename of a prior saved loopfile (recommended). Alternatively the output of the function computeLoopPositions (not recommended). For the latter case plenty of convenience functions are found in the the loop submodule of pyhed starting with “build”….
  • config (string or pyhed.config) – Defines the configuration file for the loop.

Example

>>> # example: import
>>> loopclass = Loop('path/to/loopfile')
>>> # example: create circular loop
>>> loopclass = buildCircle(10, 12)  # 10 m radius, 12 dipoles
calcAndExportFieldsForFenics(export_vtk=False, num_cpu=32, **kwargs)[source]

Calculates and export primary fields for fenics secondary field calculation.

Parameters:kwargs (dict) – Keyword parameters are redirected to calculate.
calculate(num_cpu=12, loop_mesh=None, dipole_mesh=None, interpolate=False, savename=None, cell_center=False, verbose=False, mode='auto', matrix=False, field_matrix=None, max_node_count=None, **kwargs)[source]

Computation of the loop field with respect to the config.

Parameters:
  • num_cpu (integer [ 12 ]) – Maximum number of processes allowed for this task.

  • loop_mesh (string or mesh instance [ None ]) – Optional. Possibility to give a user defined mesh for the calculation.

  • dipole_mesh (string or mesh instance [ None ]) – Optional. Possibility to give a user defined mesh for the calculation (interpolate=True or matrix=True only).

  • interpolate (boolean [ True ]) – The loop dipoles can either be calculated directly (False) or once on a seperated mesh (dipolemesh) and then interpolated to the loopmesh (True). If a dipoleFieldName is given, this field will be used for the interpolation.

  • savename (string [ None ]) – Optional. If savename is not None, the loop will be saved under the name defined in savename.

  • cell_center (boolean [ True ]) – A default the field of the loop will be calculated at the cell center of the mesh cells. This flag allows for calculation at the mesh nodes. Affects only the definition of the final loopmesh, the dipolemesh will always be calculated at the nodes for interpolation reasons.

  • verbose (boolean [ False ]) – Turn on verbose mode.

  • mode (string [ ‘auto’ ]) – Five posibilities: ‘auto’, ‘config’, ‘te’, ‘tm’, ‘tetm’

    ‘auto’: Automatic detection wether the loop is grounded or not. Grounded wires are calculated with te and tm mode (see HED). Non grounded wires are calculated with te mode only (sufficient).

    ‘config’: the default config decides the mode the field is calculated in.

    ‘te’, ‘tm’, ‘tetm’: Calculates the field in the choosen mode.

  • matrix (boolean [ False ]) – Alternatively calculation approach. At first the field on a highly dense dipole mesh will be triggered. After that the field will be interpolated to the single dipole positions by the means of a matrix vector multiplication with a matrix containing appropriate weighting factors. This Approach takes longer than direct calculation in the first run, but the calculated matrix can be used for further calculations with different frequencies or resistivity models (as long as the loopmesh and dipolemesh remain the same).

  • field_matrix (list or string [ None ]) – Interpolation matrices or file path if calculation with matrix=True. Will be calculated automatically if None.

  • max_node_count (integer [ None ]) – As all points will be calculated at once, the computational effort scales lineary with the reciever count, the transmitter count and the used hankel factors. If the limits of the available memory is reached max_node_count can be used to define the maximum chunk of nodes to be computated at once. Other nodes will be computed afterwards.

Keyword Arguments:
 
  • arguments are redirected to loop.save and to define (Keyword) –
  • drop_tol (float [ 1e-2 ]) in the cylindrical coordinate (the) –
  • to avoid instabilities around the source. (transformation) –
calculateDipoleField(verbose=False, drop_tol=0.01, num_cpu=12, max_node_count=None)[source]

Calculates field on dipole mesh.

Parameters:
  • verbose (boolean [ False ]) – Turn on verbose mode.
  • drop_tol (float [ 1e-2 ]) – Singularity fix. All horizontal distances between drop_tol and the transmitter dipole are placed between the first reciever outside the tolerance and the tolerance, maintaining the correct order and angle.
  • num_cpu (integer [ 12 ]) – Maximum number of processes allowed for this task.
  • max_node_count (integer [ None ]) – As all points will be calculated at once, the computational effort scales lineary with the reciever count, the transmitter count and the used hankel factors. If the limits of the available memory is reached max_node_count can be used to define the maximum chunk of nodes to be computated at once. Other nodes will be computed afterwards.
calculateFieldFromMatrix()[source]

Calculates the primary field on basis of the interpolation matrix and the dipole field.

calculateFieldMatrix(num_cpu=8, verbose=False)[source]

If wished the calcualtion of the total loop field can be done by interpolation and superposition of one highly accurate dipole field to the different transmitter positions of the loop. This is done either done directly or via a vector matrix multiplication.

This function is called to initialize and append the weights to the interpolation matrix from the dipolemesh to the loopmesh for all tx positions with respect to pos, phi, and ds.

This function will be called if calculate is called with matrix=True.

Parameters:
  • num_cpu (integer [ 8 ]) – Define the maximum number of cores allowed for this operation.
  • verbose (boolean [ False ]) – Turn on verbose mode.
calculateInterpolationMatrix(Pos)[source]

Calculates the interpolation matrix.

If one wished the field can be interpolated to another mesh. The interpolation matrix from the loopmesh to an arbitrary set of coordinates is calculated with this function. This function is called to initialize and append the weights to the interpolation matrix.

Note: The loop class does not hold a reference of the resulting matrix, instead gives it back to the caller.

Parameters:Pos (np.ndarray or pg.core.PosVector) – Transmitter positions of shape (n, 3) with n positions. Values are expected to be floats (the conversion to a pg.PosVector will not check again).
Returns:mat – Sparse interpolation matrix with number of columns equal to the number of nodes in the loopmesh and number of rows equal to the number of input positions.
Return type:pg.core.SparseMapMatrix
calculateSecField(num_cpu=8, **kwargs)[source]

Calculates the secondary field using custEM.

Calculates primary field as well if not found.

Needs a FEM suited mesh as well as a parameter distribution provided by other functions of this class (See createFEMMesh and prepareSecondaryFieldCalculation).

Parameters:
  • num_cpu (integer [ 8 ]) – Maximum number of processes allowed for this task. The actual calculation will be done in an mpirun environment with the selected number of cores.
  • kwargs (dict) – Keyword arguments are redirected to local_apps.
createDefaultSecondaryConfig(base=None, prefix='', suffix='', m_dir='.', r_dir='.')[source]

Short cut to generate a secondary config with some default params.

Parameters:
  • prefix (string) – String to be added to the getDefaultLoopMeshBaseName string to define the automatic generated names for the default secondary config.
  • suffix (string) – String to be added to the getDefaultLoopMeshBaseName string to define the automatic generated names for the default secondary config.
createDipoleMesh(quadratic=True, savename='_default_dipole_mesh.bms', save=False, verbose=False)[source]

Creates a suitable dipole mesh for calculation via a single dipole.

Parameters:
  • quadratic (boolean [ True ]) – If chosen, uses a quadratic (2nd order) mesh for dipole calculation.
  • savename (string [ ‘_default_dipole_mesh.bms’ ]) – Define output name.
  • save (boolean [ True ]) – Additional save of dipole mesh under savename.
  • verbose (boolean [ False ]) – Turn on verbose mode.
createFEMMesh(para_mesh_2d=None, savename=None, exportVTK=False, exportH5=True, box_x=[None, None], box_y=[None, None], box_z=None, box_cell_size=None, source_poly=None, source_setup='edges', source_loops=None, inner_area_cell_size=0.3, outer_area_cell_size=10, subsurface_cell_size=None, poly_2d=None, number_of_loops=None, **kwargs)[source]

Builds the FEM mesh for the secondary field computation.

Needs at least on of the two possible parameter meshes in order to continue.

para_mesh_2d: string or pg.Mesh [ None ]
Used to get the outer dimensions of the FEMMesh.
savename: string [ None ]
Define output save name of FEM mesh. Default name will be generated if None. If no savename is given, the dafaultname will be ‘_default_LoopMesh’ + looptype + number of dipoles.
exportVTK: boolean [ False ]
Turn on optional vtk export.
source_setup: string [ ‘edges’ ]
Defines the way the sources are incorporated into the mesh. “nodes” simply insert the dipole positions (fallback), “edges” defines strait edges between the nodes (usually the best approach). “etra” can be used for a special setup where multiple loops are build in an elongated transmitter with inline receiver array. Raises an exception if source_setup differs from the three options.
source_loops: list [ None ]
If a list of loop classes is given, their tx representation after custEM is implemented in the mesh for custEM magnetic field calculations using automatic source detection.
inner_area_cell_size: float [ 0.3 ]
Maximum allowed area (m²) for all cell in the source plane within the source polygons (if closed loop). Very important for kernel calculation! See tutorial for custEM for further explanations.
outer_area_cell_size: float [ 10 ]
Maximum allowed area (m²) for all cells in the source plane outside the source polygons (or anywhere for not closed loop). See tutorial for custEM for further explanations.
subsurface_cell_size: float [ None ]
Maximum allowed volume (m³) for all cells within inner mesh box (not the tetrahedron boundary to 10 km). Optional.
limits: list of len 2 [ None ]
Minimum and maximum y value, the anomalies should be set in the fem mesh. Uses the x limits of the 2D parameter mesh as default if None.
custEM:
Install via conda on Linux only. See install instructions of comet.
createLoopMesh(savename=None, exportVTK=False, airspace=False, verbose=False, xmax=None, xmin=None, ymax=None, ymin=None, zmin=None)[source]

Builds the mesh where the loop will be calculated in.

savename: string [ None ]
Saves the created mesh under savename, as long as savenmae is not none. If no basename is given, the dafaultname will be ‘_default_LoopMesh’ + looptype + number of dipoles + ‘.bms’.
exportVTK: boolean [ False ]
Switch to export the resulting mesh to a vtk with the given savename.
airspace: boolean [ False ]
Enables airspace.
verbose: boolean [ False ]
Turn on berbose mode.
createSecondaryConfig(mod_name, mesh_name, m_dir='.', r_dir='.', pf_name=None, p2=False, approach='E_s', pf_EH_flag='E')[source]

Initializes an instance of a secondary config for use of custEM.

Parameters:
  • mod_name (string) – Name of the mod instance (for saving and import in mpi environment)
  • mesh_name (string) – Basename of mesh imported by the fenics functions (.h5). Mind the subfolder ‘/_h5’ that will be added to the string.
  • m_dir (string) – Path to mesh directory of custEM.
  • r_dir (string) – Path to result directory of custEM.
  • pf_name (string) – File name under which the primary field will be saved in the appropriate directory of custEM.
effectiveArea()[source]

Returns self.area * self.turns (0 for not closed loops).

exportFenicsHDF5Mesh(save_h5, dipole_mesh=False, **kwargs)[source]

Exports the mesh in a h5 file. Can save the loopmesh or the dipole mesh seperately.

Need pygimli to work.

Parameters:
  • save_h5 (string) – Filename of the resulting h5 mesh (hdf5 data container in fenics syntax).
  • dipole_mesh (boolean [ False ]) – Save dipole mesh instead of loop mesh (Call this function twice if you want to save both meshes).
  • kwargs (dict) – Keyword arguments are redirected to pygimli.meshtools.exportFenicsHDF5Mesh
exportVTK(save_vtk, secondary=False, **kwargs)[source]

Exports the field in a vtk file.

Uses the loopmesh to save field with default configurations in a vtk file.

Parameters:
  • save_vtk (string) – Filename of the resulting vtk file.
  • kwargs (dict) – Keyword arguments are redirected to the function pyhed.IO.savefieldvtk.
getDefaultLoopMeshBaseName()[source]

Returns string with default base name of the loop mesh.

initCustEM(secondary_config=None, init_primary_field_class=True, procs_per_proc=2)[source]

Initalizes instance of custEM mod class for FEM calculation.

Parameters:
  • secondary_config (string or pyhed.SecondaryConfig [ None ]) – Initialized secondary config class to be used for the mod instance or path to corresponding file containing the secondary config. Uses secondary_config over loop.secondary_config. Throws Exception if both values are None.
  • init_primary_field_class (boolean [ True ]) – Additionally initializing the primary field class of the mod class instance (used for primary field export).
load(savename=None, config=None, config2=None, verbose=True, load_meshes=True, overwrite_dir=False)[source]

Load Loop from files.

Parameters:
  • savename (string [ None ]) – Basename of the lop class files. Other names are autogenerated using this basename.
  • config (string [ None ]) – Tell the load function to explicitely load config from given path. Else the saved filepath in the main archive is used.
  • config2 (string [ None ]) – See config, but for secondary configuration.
  • verbose (boolean [ True ]) – Turn on verbose mode.
  • load_meshes (boolean [ True ]) – If originally saved, the meshes are loaded by default. However, this takes more time then the rest of the load function and can be ommitted if only the other parts are of interest.
loadFieldMatrix(name, verbose=True)[source]

Loads the three matrices needed for recalculation of the primary field from numpy archive. See saevFieldmatrix for detailed description.

Parameters:
  • name (string) – Path to file to be loaded.
  • verbose (boolean [ True ]) – Turn on verbose mode.
loadSecondaryConfig(savename=None)[source]

Imports previously saved secondary config.

Parameters:savename (string [ None ]) – Used savename over loop.sec_savename. Throws Exception if both values are None. Replaces loop.sec_savename.
prepareSecondaryFieldCalculation(savename=None, secondary_config=None, fem_mesh=None, para_mesh_2d=None, set_marker=False, anomaly_vector=None, valid_marker=None, verbose=False, num_cpu=32, force_primary=False, export_vtk=False, mod_name=None, **kwargs)[source]

Based on the given secondary config a MOD instance using the third party module custEM will be initialized. This includes the optional generation of a FEM suited mesh containing resistivity information from a 2D parameter mesh.

Parameters:
  • savename (string [ None ]) – Name under which loopclass and secondary config (+= ‘_sec.cfg’) are to be saved. Needed for secondary approach.
  • secondary_config (pyhed.SecondaryConfig or string [ None ]) – Filename of configuration file or initialized class instance of a secondary configuration. Optional if already given manually.
  • fem_mesh (pg.Mesh or string [None]) – FEM suited mesh or filename, respectively. Optional. If not given a suited mesh will be generated if a valid para_mesh_2d is provided.
  • para_mesh_2d (pg.Mesh or string [ None ]) – 2D parameter mesh providing cell indices for the appending of resitivity information. Needed for automatic FEM mesh generation. Can be set manually beforehand.
  • set_marker (boolean [ True ]) – Flag to decide if the fem mesh has got the needed marker for the resitivity distribution. Can be omitted if already done and saved (e.g. if same mesh is used again).
  • anomaly_vector (np.ndarray [ None ]) – Conductivity values [S/m] of the parameter mesh to be used in the seocondary field approach. Uses given value over array found in secondary config. Raises Exception if neither found nor given.
  • ground_marker (np.ndarray [ None ]) – Corresponding marker for each entry in the anomaly vector. Each marker corresponds to a layer number of the 1d primary field beginning at 1 for the first layer, counting upward (0 belongs to the air layer). None results in np.ones_like(anomaly_vector, dtype=int).
  • verbose (boolean [ False ]) – Turn on verbose mode.
  • num_cpu (integer [ 32 ]) – Maximum number of processes allowed for this task.
  • force_primary (boolean [ False ]) – Force a recalculation of the primary field.
  • mod_name (string or None [ None ]) – Overrides mod name. Useful if looping over many loops, as default name could be similar.
  • magnetic (boolean [ True ]) – Prepares magnetic primary fields. If False only dummies are created to avoid error messages from custEM during import. Set to False if secondary electric approach is used for secondary field calculation.
  • electric (boolean [ True ]) – Prepares electric primary fields. If False only dummies are created to avoid error messages from custEM during import. Set to False if secondary magnetic approach is used for secondary field calculation.
  • Returns
  • ——–
  • tuple ((savename, sec_savename)) – Absolute file paths for the secondary approach.
  • Usage
  • ——
  • In order to prepare a secondary field calculation you need
  • - a secondary config (default is provided)
  • - a conductivity vector (*)
  • - a 2d parameter mesh matching the anomalies (*)
  • - a marker_vector (*)
  • *if not in secondary config or proviedd beforehand
  • and optionally either
  • - fem_mesh (without marker -> set_marker=True (default))
  • or
  • - fem_mesh (with marker -> set_marker=False)
  • or
  • - no fem_mesh (auto creation)
save(savename=None, config_savename=None, config2_savename=None, save_mesh=True, save_field=True)[source]

Saves the loop class in files.

Saves npz archive with loop itself.

Saves config.

Saves secondary config if initialized.

Saves mesh if save_mesh=True.

Saves field if save_field=True.

Parameters:
  • savename (string [ None ]) – File basename for saving loop class and its components.
  • config_savename (string [ None ]) – Explicit savename for config. Automatically generated if None.
  • config2_savename (string [ None ]) – Explicit savename for secondary config. Automatically generated if None.
  • save_mesh (boolean [ True ]) – Saves mesh.
  • save_field (boolean [ True ]) – Saves fields.
saveFieldMatrix(name, verbose=True)[source]

Saves the three matrices needed for recalculation of the primary field.

A compressed numpy archive is loaded and the matrices are build afterwards, therefore import time is ~20% higher compared to the pure pygimli way ( .field_matrix.save(’…’) ). However, because the single arrays (indices and values) are saved in one compressed file archive they need only one third space on the hard disk compared to saving three separate matrices using pygimli syntax.

Parameters:
  • name (string) – Path for file to be saved.
  • verbose (boolean [ True ]) – Turn on verbose mode.
saveLoopMesh(savename=None)[source]

Saves loopmesh using the given savename or an autogenerated name.

Updates self.loop_mesh_name in case of changes.

Parameters:savename – Export path name. Used over default name if given.
saveSecondaryConfig(savename=None)[source]

Saves secondary config in ASCII file.

Parameters:savename (string [ None ]) – Used savename over loop.sec_savename. Throws Exception if both values are None. Replaces loop.sec_savename.
setAnomalies(anomaly, sort=True)[source]

Handle anomaly vector and marker of the 2d parameter mesh.

Parameters:
  • anomaly (array_like [ None ]) – Vector with conductivities in S/m. Expect one entry for each cell in parameter mesh.
  • sort (boolean [ False ]) – If True, set the same marker for double values in anomaly vector. This is for blocky 2d structures, where only a few different regions are required. Use default False if dealing with smooth inversion results, for example in a structural coupling.
setDipoleMesh(mesh, savename='_default_dipole_mesh', verbose=True)[source]

Sets the dipolemesh and saves it under savename.

Parameters:
  • mesh (string or mesh instance) – Pygimli mesh instance or file path to pygimli mesh.
  • savename (string [ None ]) – Used savename for mesh, if mesh is already a mesh instance.
  • verbose (boolean [ False ]) – Turn on verbose mode.
setFEMMarker_old(valid_marker=None)[source]

Sets and checks the domain marker of the 3D FEM mesh.

Parameters:valid_marker (array_like [ None ]) – If None, checks which domains of the 2D mesh are actually transferred to the 3D FEM mesh. The markers are saved in the valid_marker attribute. If given, sets vector directly after some checks.
setFEMMesh(mesh, valid_marker=None, savename=None)[source]

Sets the FEM mesh as loopmesh and handles the domain markers.

Parameters:
  • mesh (string or mesh instance) – Pygimli mesh instance or file path to pygimli mesh.
  • valid_marker (array_like [ None ]) – If None, checks which domains of the 2D mesh are actually transferred to the 3D FEM mesh. The markers are saved in the valid_marker attribute. If given, sets vector directly after some checks.
  • savename (string [ None ]) – Useful if multiple loops are using the same mesh (saves diskspace). Ignored if mesh is a string already.
  • Calls *_setFEMMarker* is paramesh has been set.
  • Furthermore calls *updateFEMAnomaly* if anomaly has been set through
  • either *setParamesh2D* or *setAnomaly*
  • Produces error message if valid_marker array is given, but no paramesh
  • is found
setFEMMesh_old(mesh, valid_marker=None, savename=None)[source]

Sets the FEM mesh as loopmesh and handles the domain markers.

Parameters:
  • mesh (string or mesh instance) – Pygimli mesh instance or file path to pygimli mesh.
  • valid_marker (array_like [ None ]) – If None, checks which domains of the 2D mesh are actually transferred to the 3D FEM mesh. The markers are saved in the valid_marker attribute. If given, sets vector directly after some checks.
  • savename (string [ None ]) – Useful if multiple loops are using the same mesh (saves diskspace). Ignored if mesh is a string already.
setFrequency(frequency)[source]

Sets the frequency, not angular frequency for the field calculation.

setLoopMesh(mesh, savename=None)[source]

Sets the loopmesh.

Parameters:
  • mesh (string or mesh instance) – Pygimli mesh instance or file path to pygimli mesh.
  • savename (string [ None ]) – Used savename for mesh, if mesh is already a mesh instance. Alternatively a default name is generated with getDefaultLoopMeshBaseName.
setLoopMeshName(savename=None)[source]

Sets loop mesh name or figures it out from sec config.

setMeshParameters(refinement_para=1.0, max_area_factor=1.0, tetgen_quality=1.2)[source]

Alters the Parameter responsible for the quality and size used during automatic mesh generation.

Parameters:
  • refinement_para (float [1]) – An increase of refinement_para decreases the size of the smallest cell at the dipoles and therefore incrreases the total number of refinement cells around the dipole. Omitts refinement if value is negative.
  • max_area_factor (positive float [1]) – The max_area_para lineary affects the maximum volume of a cell. An increase of the parameter allows for greater cells and therefore decreases the total number of cells outside of the refined section of the mesh. Set to 0.5 for a fine mesh and anywhere near 2 for a coarse mesh. Highly affects the total number of nodes/cells in the mesh.
  • tetgen_quality (float [1.2]) – The tetgen_quality parameter is directly piped to the corresponding tetgen call in the meshgeneration process. Decrease this parameter (e.g. to 1.12) to increase the homogeneity of the triangles. Be careful with this one, tetgen very easy starts to split cells in smaller and smaller pieces and therefore increase the total cellcount to very high values (millions and more).
setModel(rho, d=None, thickness=True, resistivity=True)[source]

Sets the synthetic 1D layered earth model for dipole calculation.

Parameters:
  • rho (float or array_like) – Resistivity/conductivity distribution for a layered earth.
  • d (float or array_like or None [None]) – Thickness or layer depth. Empty (None, 0, or []) for halfspace.
  • thickness (boolean [True]) – The parameter d is used as thickness (True, len(rho) - 1) or depth (False, len(rho)), respectively.
  • resistivity (boolean [True]) – The parameter rho is used as Resistivity (True) or conductivity (False), respectively.
setParaMesh2D(para_mesh_2d, limits=None, append_boundary=False, preserve_edges=False, anomaly=None, sort=True, **kwargs)[source]

Sets 2D parameter mesh for secondary field calculation.

Parameters:
  • para_mesh_2d (string or pg.Mesh) – 2D parameter mesh or path to mesh.
  • limits ([float, float] or None) – Minimum and maximum values for y of the area where 2D parameters are to be transferred to the 3D FEM mesh. Default are the x extension of the 2D parameter mesh.
  • append_boundary (boolean [ False ]) – Fills in an additional boundary with prolongated resistivity values around the transferred 2D values. This is useful as it reduces artifacts at the edge of the 2D domain oin the FEM mesh.
  • anomaly (None or np.ndarray [ None ]) – Optionally. Alternatively use setAnomalies. Anomaly vector (conductivity vector) with values for each cell in the 2D parameter domain. Attention: conductivity is used, not resistivity!
  • sort (boolean [ False ]) – Optionally. Alternatively use setAnomalies. If True, set the same marker for double values in anomaly vector. This is for blocky 2d structures, where only a few different regions are required. Use default False if dealing with smooth inversion results, for example in a structural coupling.
  • kwargs to *appendTriangleBoundary*
  • Calls *setAnomalies* of anomaly is given.
  • Furthermore calls *updateFEMAnomaly* if FEMMesh has been set already.
setParaMeshMarkerAndVals(anomaly=None, sort=True)[source]

Handle anomaly vector and marker of the 2d parameter mesh.

Parameters:
  • anomaly (array_like [ None ]) – Vector with conductivities in S/m. Expect one entry for each cell in parameter mesh. If not given, and sort is True an error is raised.
  • sort (boolean [ False ]) – If True, set the same marker for double values in anomaly vector. This is for blocky 2d structures, where only a few different regions are required. Use default False if dealing with smooth inversion results, for example in a structural coupling.
setPrimaryConfig(config)[source]

Sets the primary config which handles the resistivity distribution as well as the frequency of the primary field. For setting the 1D model directly see setModel.

Parameters:config (path or comet.pyhed.config.Config instance) – Configuration class instance or file path.
setSecondaryConfig(secondary_config)[source]

Sets class attribute with secondary config or loads file.

Parameters:secondary_config (string or pyhed.SecondaryConfig) – Seondary config class instance or file path.
show(**kwargs)[source]

Plots the Loopdiscretisation and the dipole directions and Length. For inspection of the loop-class and debugging purpose. Or for your curiosity.

Parameters:kwargs (dict) – Keyword arguments are redirected to pyhed.plot.plot_bib.showLoop.
updateFEMAnomaly(anomaly=None, set_marker=True, set_attributes=False, vtk_name=None, ground_marker=None, export_H5=False, sort=True)[source]

Transfers resistivity anomalies from 2D para mesh in FEM mesh.

Parameters:
  • anomaly_vector (array_like [ None ]) – Array containing the resistivity anomalies of the 2D parameter mesh. If None, the secondary config is asked for a anomaly vector. (For setting the marker for exmaple).
  • set_marker (boolean [ True ]) – Transfers the marker from the parameter mesh to the FEM mesh. This only has to be done once and can then switched off for performance.
  • set_attribute (boolean [ False ]) – Sets the attribute in the FEM mesh for debugging purposes. The anomaly vector for calculation is stored in secondary_config.
  • vtk_name (string [ None ]) – Optional vtk export with name = vtk_name if vtk_name is not None.
  • ground_marker (array_like [None]) – Corresponding marker for each entry in the anomaly vector. Each marker corresponds to a layer number of the 1d primary field beginning at 1 for the first layer, counting upward (0 belongs to the air layer). None results in np.ones_like(anomaly_vector, dtype=int).
updateFEMAnomaly_old(anomaly=None, set_marker=True, set_attributes=False, vtk_name=None, ground_marker=None, export_H5=False)[source]

Transfers resistivity anomalies from 2D para mesh in FEM mesh.

Parameters:
  • anomaly_vector (array_like [ None ]) – Array containing the resistivity anomalies of the 2D parameter mesh. If None, the secondary config is asked for a anomaly vector. (For setting the marker for exmaple).
  • set_marker (boolean [ True ]) – Transfers the marker from the parameter mesh to the FEM mesh. This only has to be done once and can then switched off for performance.
  • set_attribute (boolean [ False ]) – Sets the attribute in the FEM mesh for debugging purposes. The anomaly vector for calculation is stored in secondary_config.
  • vtk_name (string [ None ]) – Optional vtk export with name = vtk_name if vtk_name is not None.
  • ground_marker (array_like [None]) – Corresponding marker for each entry in the anomaly vector. Each marker corresponds to a layer number of the 1d primary field beginning at 1 for the first layer, counting upward (0 belongs to the air layer). None results in np.ones_like(anomaly_vector, dtype=int).

Survey

class comet.snmr.survey.Survey(earth=None, loops=None)[source]

Survey class for containment and handling of SNMR datasets (FIDS).

addLoop(loop)[source]

Appends a given loop instance to the loops in survey and returns id

addSounding(fid)[source]

Appends a given sounding instance to the sounds in survey and returns id

createKernel(fid=0, dimension=1)[source]

Returns a initialized kernel instance for the chosen sounding.

Parameters:
  • sound_index (integer) – Index of the sounding the kernelclass is calcualting the kernel for. In order to calculate the kernel, pulses, tx and rx are taken as references from the sounding.
  • Note (createKernel does not set or change any values in survey nor in)
  • the corresponding sounding. However when calculating, the kernel class
  • will override the frequency in the given loops (tx and rx) and set it
  • to the larmor frequency calculated from the earth magnetic fields
  • magnitude. Use the *setEarth* method before or after you generate the
  • kernel instances, but obviously before calculation.
createSounding(tx=0, rx=0, check_double=True)[source]

Creates a new sounding based on the given ids for tx and rx.

Parameters:
  • tx (integer [ 0 ]) – Index of the transmitter loop in loops.
  • rx (integer [ 0 ]) – Index of the receiver loop in loops. Same number than tx indicates a coincident measurement.
  • check_double (boolean [ True ]) – If True, omits creating another instance of the same fid (tx/rx combination). Instead the index of the original fid is returned. If False new fid is created and its index is returned.
  • Note (tx and rx indices can be setted regardless if there is an actual)
  • loop in loops or just a *None* placeholder. In other words you can
  • create your soundings and loops in arbitrary order.
data

Complex data cube (pulses * gates) from soundings.

data_phases

Single data phases of the FIDs.

error

Complex error cube (pulses * gates) from soundings.

gates

Time gates gathered from soundings.

loadLoopMesh(savename, indices=None, dipolename=None)[source]

Loads mesh and distribute reference to given indices.

loadMRSD(filename, remove_df=True, build_loops=False, x_offsets=None, segments=80, max_length=None, tx=None, rx=None, fids=None, debug=False)[source]
Parameters:
  • filename (string) – Path to .mrsd file to be imported.
  • build_loops (boolean [ True ]) – If True, the saved config in the mrsd file is used to construct loops for transmitter and receiver. However, the information in the mrsd fiel is not complete. There are some defaults we assume in autogenerating the loops, especially when it comes to figure-of-eight loops. Feel free to replace the loops with custom created loops of the pyhed library. Or switch this off if you only want to see the data or define all the loops yourself.
  • x_offsets (list or None [ None ]) – One information that is missing in mrsd files, is the relative position of the loops to each other. Here one can fill in this information giving a simple list of offsets in positive x direction (all loops (midpoints) are placed at y=0 and z=0). Expect one float per used loop by the data file or raises an error. Ignored if None and multiple loops are found (in this case no loops are build at all). Coincident measurements do not require this, x is set to 0 by default.
  • segments (integer [ 80 ]) – Number of dipoles used to auto build the loops. Ignored if build_loops is False or not given any x_offsets.
  • max_length (float [ None ]) – Maximum length of a dipole when auto generating the loops. Overrides segments. Ignored if build_loops is False or not given any x_offsets.
loadMRSD_h5(filename, remove_df=True, build_loops=False, x_offsets=None, segments=80, max_length=None, tx=None, rx=None, fids=None, debug=False)[source]

See loadMRSD instead.

loadMRSD_mat(filename, remove_df=True, build_loops=False, x_offsets=None, segments=80, max_length=None, tx=None, rx=None, fids=None, debug=False)[source]

See loadMRSD instead.

pulses

Pulse moment vectors gathered from soundings.

response

Complex data cube (pulses * gates) from soundings.

rx_indices

Indices of the used receiver of each sounding.

set1DModel(thk=[], res=[1000.0])[source]

Modifies loop config in terms of primary field resistivity.

setEarth(earth=None, incl=60.0, decl=2.0, mag=4.8e-05, rad=False)[source]

Defines the Earth in terms of inclination, declination and mag.

Parameters:
  • earth (comet.snmr.survey.Earth [ None ]) – Already initialized earth class will be setted. Or created through the other optional arguments.
  • inclination (float [ 60. ]) – Inclination of the earth magnetic field in rad or degree.
  • declination (float [ 2. ]) – Declination of the earth magnetic field in rad or degree.
  • magnitude (float [48000 * 1e-9]) – Magnitude of the earth magnetic field in Tesla.
  • rad (boolean [ False ]) – Input inclination and declination in rad?
setLoopConfig(config, update_loop_configs=True)[source]

Loop config in terms of primary field resistivity and frequency.

setResponse(array)[source]

Set a response array from e.g. an inversion as data set for plotting.

tx_indices

Indices of the used transitter of each sounding.

FID

class comet.snmr.survey.FID(tx=0, rx=0, pulses=None)[source]

Single SNMR experiment (sounding) using a simple Free Induction Decay (FID).

Attributes to be setted directly:

amperes

Ampere vector [A].

curie

Curie factor for kernel calculation. Read only. Calculated automatically by setting temperature.

deadtime

Effective deadtime (device + half pulse) [s].

filterGates(mint=0.0, maxt=2.0)[source]

Dismiss not desired time gates.

Parameters:
  • mint (float [0.0]) – Cut all data reqired before mint (in seconds). This is done using the gate midpoints including deadtime.
  • maxt (float [2.0]) – Cut all data reqired after maxt (in seconds). This is done using the gate midpoints including deadtime.
  • Append new .gating to restore old gates
  • raw_data remain untouched)
gates

Time gate midpoint vector [s] (including deadtime).

gating(num_gates=42, verbose=False)[source]

(extracted from MRSMatlab, 2017)

y=exp(x) For some interval x(a:b) the exact mean within exp(x(a:b)) yAverage = exp(mean(log(y(a:b)))) t(yAverage) = mean(t(a:b))

Problem: Logarithm is nice for exact average of exponential function. But signals are noise contaminated. 1. Logarithm of gaussian noise changes noise structure from gaussian to lorenzian. Averaging of lorenzian distributed noise is not zero. 2. Since noise can make signal negative a dc shift is added to make signals positive. This deminishes the accurancy of averaging in logspace. For large constant shift averaging in logspace becomes equivalent to average in linspace. However this is nice for noise structure. So we have a tradeoff. Finally, from some amount of intervals on, e.g. 20 within interval [0 1]/s averaging is sufficiently exact in any case.

MMP 18/10/2011

getRotatedAmplitudes()[source]

Returns Data and Error as real component of the rotated Vecs.

load(savename, df_removed=True)[source]

Load previously saved FID class instance from savename (.npz) (numpy compressed binary data structure).

Usually imported data are cleansed from frequency offsets (df) before saving. However there is no auto detection for that. In rare cases (if you know what youre doing) data are saved without removing df first. Then df_removed has to be set to False. Otherwise the raw data

pulses

Pulse moment vector [As].

rotateAmplitudes(raw_data=False)[source]

One of the three main ways for NMR forward modelling is to use rotated amplitudes, instead of using the amplitudes of the complex data or the complex data itself. If the phase information of the noise free data is known (synthetic data) or fitted (e.g. monoexponential fit) the rotated Amplitudes (also complex, do not confuse) have the advantage of containing all the information in the real part (together with noise), where the imaginary part contians only noise and can therefore be discarded later.

Can be used on gated or ungated data, however this call alters the raw_data!

Parameters:raw_data (boolean [ True ]) – Flag to decide if raw data or gated data are rotated. Default is raw data, however if no raw data are
Returns:
Return type:complex rotated raveled data.
save(savename)[source]

Saves FID class instance under savename. Expect savename with ending .npz (numpy compressed binary data structure).

setDataPhase(data_phase)[source]

Sets variable data_phase. Expect single float value for data phase in rad.

setFrequencyOffset(df)[source]

Sets frequency offset of tx pulse to larmor frequency.

Expect one value per pulse or one single value (used for all pulses). None is treated as zero offset (internal initialization).

setGatedDataErrorAndGates(data, error, gates, rotated=False, phases=None, midpoints=True)[source]

Sets the processed and gated data vector along with the gates (time discretization) and error cube.

Parameters:
  • data (np.ndarray) – Data vector of shape (number of pulses, number of gates). Expect complex valued vector.
  • error (np.ndarray) – Error vector of the same shape as the data vector.
  • gates (np.ndarray) – Simple time vector in seconds with shape matching the dimension 1 of the data and error vector. Expect gates without deadtime.
  • rotated (boolean [ False ]) – Define whether the data are already rotated or not. thee is no autodetect for that.
  • phases (np.ndarray [ None ]) – Define phases as simple vector containing phases in rad. Expect one value per pulse.
  • midpoints (boolean [ True ]) – If True (default) the given times in the gates vector are interpreted as midpoint of gates. However if False the vector is interpreted as outer limits of the gates, so gate 1 would be defined between time 1 and time 2 and gate 2 between time 2 and 3 and so on.
  • Sets
  • —-
  • This functionality fills the following attributes
  • *data_gated*, *gates*, *error_gated*, *rotated*
  • and optionally
  • *phi* (phases)
setGates(gates, midpoints=True)[source]

Define time gates.

Parameters:
  • gates (np.ndarray) – Define gates midpoints. Expect array with float in [s]. See midpoints for definition of how the input array is interpreted.
  • midpoints (boolean [ True ]) – If True (default) the given times in the gates vector are interpreted as midpoint of gates. However if False the vector is interpreted as outer limits of the gates, so gate 1 would be defined between time 1 and time 2 and gate 2 between timne 2 and 3 and so on.
  • Sets
  • —-gates and _gates_thk if not the midpoints are given
setPhases(phi)[source]

Sets variable phi. No check for length if vector is done. See setGatedDataErrorAndGates or setRawDataErrorAndTimes for more details.

setPulseDuration(taup, deadtime_device=0.005)[source]

Sets pulse duration [s] and internal deadtime from the device.

Parameters:
  • taup (float) – Pulse duration in seconds.
  • deadtime_device (float [ 0.005 ]) – Internal deadtime of the measurement device in seconds. 0.005 seconds are default for synthetic studies.
  • Sets
  • —-
  • *taup1*,
  • *deadtime_device*,
  • *deadtime* (half pulse + deadtime_device)
setPulses(pulses)[source]

Set pulse moment vector. Expect array with float in [As].

pulses

setRawDataErrorAndTimes(data, error, times, rotated=False, phases=None, remove_df=True, omit_regating=False)[source]

Sets the raw (processed but ungated) data vector along with the time discretization and errorvector.

Parameters:
  • data (np.ndarray) – Data vector of shape (number of pulses, times). Expect complex valued vector.
  • error (np.ndarray) – Error vector of the same shape as the data vector.
  • times (np.ndarray) – Simple time vector in seconds with shape matching the dimension 1 of the data and error vector, expect times without deadtime!
  • rotated (boolean [ False ]) – Define whether the data are already rotated or not. There is no autodetect for that.
  • phases (np.ndarray [ None ]) – Define phases as simple vector containing phases in rad. Expect one value per pulse.
  • remove_df (boolean [ True ]) – Removes the frequency offset in the given data stored in the attribute df [Hz].
  • omit_regating (boolean [ False ]) – When setting the raw data, the gated data need to be recalculated. By default this is done via regating with the original settings for the gating.
  • Sets
  • —-
  • This functionality fills the following attributes
  • *data_raw*, *times*, *error_raw*, *raw_rotated*
  • and optionally
  • *phi* (phases)
setResponse(array)[source]

Sets a respinse array with the same shape as the data e.g. from an inversion instance. For plotting only.

setRotated(rotated, raw_data=False)[source]

Sets rotation of data. True = rotatedAmplitudes, False = complex.

setRx(index, turns=None)[source]

Define index of receiver loop and turns.

setTx(index, turns=None)[source]

Define index of transmitter loop and turns.

temperature

Middle temperature [K]. Default = 281 K (8°C or 46.4°F).

times

Time vector [s] of raw data (including deadtime).

Kernel

class comet.snmr.kernel.Kernel(survey=None, fid=0, dimension=1, name=None)[source]

Basic class to solve the NMR kernel computation.

Parameters:
  • name (string [ None ]) – If kernel is loaded from file.
  • survey (survey class instance [ None ]) – Calls setSurvey to define underlaying survey class. Holds important attributes like pulse moments and the loops for tx and rx.
  • tx (integer [ 0 ]) – Transmitter index in corresponding survey.
  • rx (integer [ 0 ]) – Receiver index in corresponding survey.
  • fid (interger [ 0 ]) – Sounding index in corresponding survey.
  • dimension (integer [1]) – Defines the kernel integration.

Example

>>> from comet.snmr import kernel as k
>>> from comet.snmr import survey
>>> site = survey.Survey()
>>> kernel = k.kernel(site)
>>> kernel.calculate()
>>> kernel.save('savename')
>>> kernel.show()
BFieldCalculation(loop_mesh=None, dipole_mesh=None, interpolate=False, just_loop_fields=False, recalc_loop_fields=False, recalc_primary=False, num_cpu=12, **kwargs)[source]

Calculates the Bfield for the kernel function for tx and rx.

internal call of loop.calculate() including decision if cell based or node based Bfield is needed. All optional parameters are piped to the loop.calculate() call. Based on the desired dimension of the kernel a specialised mesh may be automatically generated for the calculation.

Part 1/3 of the kernel calculation. Called automatically if kernel.calculate is called.

calcMagnetization()[source]

Creates 3D mesh and calcualtes magnetization vector after excitation. Returns magnetization vector of shape (num_pulses, num_cells_3d, 3)

calculate(loop_mesh=None, dipole_mesh=None, interpolate=False, savename=None, forceNew=False, slices=True, slice_name=None, **kwargs)[source]

All three parts of the kernel calulation are called here.

All given kwargs are directed to BfieldCalculation(), see function info for details about possible keyword arguments.

>>> self.BFieldCalculation(**kwargs)
>>> self.ellipticalDecomposition()
>>> self.kernelIntegration()
>>> if savename is not None:
        self.save(savename)
Keyword Arguments:
 destinations – none for now, with exception of “num_cpu”, [12] which is directed to BfieldCalculation and/or sliceKernel
create1DKernelMesh(max_length=0.1, area=100.0, quality=32, zvec=None, size_factor=2.5, z_factor=2.5, export_xyplane=None, max_dipoles=2000, calc_3D_stats=True, xmin=None, xmax=None, ymin=None, ymax=None)[source]

In order to integrate the kernel to a 1D structure without interpolation errors, a special mesh consisting of triangular zylinders has to be defined.

Parameters:
  • max_length (float [ 0.1 ]) – Defines the smallest edge length for the discretisation of the loop . In order to get admirable kernel results a value of 0.1 meters should be the maximum.
  • area (float [ 100. ]) – Defines the maximum Area a triangle in the loop slice can have.
  • quality (float [ 32. ]) – Defines the smallest angle inside a triangle. Be careful with values above 35.
  • zvec (array_like [ None ]) – Usualy the zvec is defined automatically, this flag gives the user the optional possibility to give a zvec from outside the funktion.
  • size_factor (float [ 2.5 ]) – Extension of the kernel mesh (and therefore integration volume) in the x and y direction. Should be at least 2 times the loop diameter or shortest edge length. This value defines the multipier.
  • z_factor (float [ 2.5 ]) – Maximum depth of the Kernel. Should be at least 2 times the loop diameter or shortest edge length. This value defines the multipier.
  • export_xyplane (string [ None ]) – Filename for the resulting kernel mesh plane in 2D can be exported for debugging or simply to check the mesh (vtk).
  • max_dipoles (interger [ 2000 ]) – Fallback for high node density loops. This sets an overall maximum for the number of dipoles used for the loop discretization. However this only comes into account in rare cases.
create2DKernelMesh(area=15.0, quality=34, yvec=None, x_factor=5, z_factor=2, savename=None, export_xzplane=None, calc_3D_stats=True, order=0)[source]

Similary to the mesh in the 1D case a special mesh consisting of triangluar zylinders is generated. The Zylinders are pointing in the y direction to allow a perfect integration to the x-z plane.

Parameters:
  • area (float [15.]) – Affects the maximum area a triangle in the 2D slice is allowed to have. Higher Values lead to bigger cells.
  • quality (float [34]) – Defines the smallest angle inside a triangle. Be careful with values above 34.5. Higher values = more cells.
  • yvec (ndarray, list [None]) – Usualy the y vector is defined automatically, this flag gives the user the optional possibility to give a YVec from outside the function.
  • x_factor (float [2]) – Extension of the kernel mesh (and therefore integration volume) in the x direction. Should be at least 2 times the loop diameter or shortest edge length. This value defines the multipier.
  • z_factor (float [2]) – Extension of the kernel mesh (and therefore integration volume) in the z direction. Should be at least 2 times the loop diameter or shortest edge length. This value defines the multipier.
  • savename (string [None]) – If a savename is given, the resulting 2D Mesh is saved in the .bms format for later use.
  • export_xyplane (string [ None ]) – Filename for the resulting kernel mesh plane in 2D can be exported for debugging or simply to check the mesh (vtk).
createMagnetizationMesh()[source]

Creates full 3D mesh for display and calcualtion of magnetization vectors. Not needed for normal kernel calculation routine and big, therefore separate.

createSeperatedLoopMesh(name='SepLoopMesh', dipole=True, exportVTK=False, refinement_para=1.0, max_area_factor=1.0)[source]

Creates a mesh that contains the receiver and the transmitter loop.

createYVec(max_length=0.2, max_num=300, y_factor=2.0, calc_3D_stats=True)[source]

Creates the y vector discretization for the 2D kernel mesh.

The y vector represents the y values of the 3D Kernel mesh before the integration to 2D.

Parameters:
  • max_length (float [ 0.2 ]) – Maximum distance between two slices inbetween the source dipoles.
  • max_num (integer [ 300 ]) – Maximum number of slices. Overrides max_length if they conflict.
  • y_factor (float [ 2. ]) – Extension of the kernel mesh (and therefore integration volume) in the y direction. Should be at least 2 times the loop diameter or shortest edge length. This value defines the multipier.
createZVector(numz, minz, min_thk=0.5)[source]

Creates a sinus hyperbolicus shaped Z discretisation in numz steps between 0 and minz.

ellipticalDecomposition()[source]

Computes the counter and corotating parts of the given magnetic fields with respect to a given earth magnetic field.

Parameters:
  • Bfield (complex field [3, n] or string) – Optional. Possibility to insert a pre calculated field.
  • Inclination (float) – Inclination of the earth magnetic field at the loop site in rad [0… 2pi]
  • Declination (float) – Declination of the magnetic field at the loop site in rad [0… 2pi]
  • B (np.array of shape (3, n)) – Magnetic field of the loop
  • Second part of the kernel calculation.
  • - mainly from Weichman et al. (2000)
static ellipticalDecomposition_multi(Bfield, earth)[source]

Computes the counter and corotating parts of the given magnetic fields with respect to a given earth magnetic field.

Parameters:
  • Bfield (complex field [3, n] or string) – Optional. Possibility to insert a pre calculated field.
  • Inclination (float) – Inclination of the earth magnetic field at the loop site in rad [0… 2pi]
  • Declination (float) – Declination of the magnetic field at the loop site in rad [0… 2pi]
  • B (np.array of shape (3, n)) – Magnetic field of the loop
  • Second part of the kernel calculation.
  • Literature
  • ———-
  • - Weichman et al. (2000)
  • - Hertrich (2005, Appendix)
  • - Hertrich (2008, eq. 6 ff.)
export2DKernel(fig=None, ax=None, savename=None, png_dpi=300, noYLabel=False, index=0, colorBar=True, size=13, pdf=None, fixed_cbar=False, **kwargs)[source]

Exports 2D Kernel for given pulse moment. Kwargs are redirected to show.

export2DKernel2PDF(name, fixed_cbar=False, **kwargs)[source]

Export 2D Kernel for all pulse moments as stiched pdf. Kwargs are redirected to export2DKernel.

exportMagnetization(name, vtk_export=False, pulse=0)[source]

Export a previously calculated magnetization vector as numpy vector and optionally vtk file.

fid

Reference to sounding (FID) class instance in survey.

getSliceCoords()[source]

Returns input coordinates for custEM Slice interpolation of magnetic fields to the kernel slices.

interpolateBFieldToKernel(recalc_prim_on_kernel=False, recalc_primary=False, num_cpu=32, calc_3D_stats=True)[source]

Takes the rx Bfield and interpolates it to the kernel mesh.

static kernelCalculation_multi(fid, earth, txalpha, txbeta, txzeta, txperpend, rxalpha=None, rxbeta=None, rxzeta=None, rxperpend=None, calc_theta=False)[source]
kernelIntegration(calc_theta=False)[source]

Computes the integration of the kernel with respect to the desired dimension.

Parameters:
  • decomposition ((alpha, beta, zeta)) – Bfield_part essentially consists of the output from the elliptical decomposition of the magnetic field.
  • measurement (class) – An instance of a measurement class has to be given in order to keep the number of input arguments manageable.
  • earthmagnitude (float) – Magnitude of the earth magnetic field [Tesla]. Aproximatly about 30000 to 65000 nT (1 nT = 1e-9 Tesla).
  • Third part of the kernel calculation.
larmor

Larmor frequency [Hz] from earth defined in survey.

load(savename, load_loopmesh=True, kernelmesh2d=None, load_kernelmesh=True, use_order_refinement=True)[source]

Load a previously saved kernel (.npz-format).

pulses

Reference to pulse moments from sounding (FID).

release_memory()[source]

Calling this function is releasing some attributes that are using a fairly big amount of memory.

Sets the following attributes back to None:

  • The interpolation matrix between the loop meshes and the kernel mesh

interpolationMatrix

  • local copies of the magnetic fields (fields in tx and rx are not

effected) txBfield, rxBfield

  • the 3D kernel mesh cell center and volumes

kernelMeshCellVolume, kernelMeshCellCenter

  • the elliptical decomposition of the tx and rx bfields

txalpha, txbeta, txzeta, txperpend, rxalpha, rxbeta, rxzeta, rxperpend

Note: a recalculation of the kernel will take about the same amount of time as the first call, as all cached variables are gone, however apart from a recalculation, the other purposes of the kernel class (export, figures, inversion(without recalculation)) are not effected.

Another note: If you want to use this method only for saving disk space in case you save the kernel class, then you might consider the light flag of the .save method instead.

rx

Reference to receiver class instance in survey.

rx_area

Area of the receiver loop.

save(savename=None, save_interpolation_mat=False, save_loopmesh=False, light=True, kernelmesh_name=None)[source]

Save the basic information to restore the Kernel class later.

set1DKernelMesh(mesh, calc_3D_stats=True)[source]

Sets the 1D kernel mesh.

Parameters:
  • mesh (stirng or pygimli.Mesh) – Filename or mesh instance of a 2D mesh in the x-y plane.
  • Need
  • —-
  • z discretization – Can be setted via createZVector, setZVector or direct use of create1DKernelMesh. However the needed information to do that may not be available on the fly, therefore no default z vector is created.
set2DKernelMesh(inmesh, yvec=None, order=0, integration_mat=None, calc_3D_stats=True)[source]

kwargs to createYVec if YVec is None

setModel(*args, **kwargs)[source]

Pipes args and kwargs to self.tx.setModel. Same for rx.

setPulsesDirectly(pulses)[source]

Set pulse moment vector manually if not supported by survey + fid. (This is called when loading a kernel from the harddisk, mainly for plotting reasons). For all calculation purposes a survey and fid class is recommended.

setRx(rx, **kwargs)[source]

Sets initialized loop or pipe arg and kwargs to loadLoop.

setSurvey(survey, fid=0)[source]

Sets survey class containing necessary information for the kernel.

Parameters:
  • survey (comet.snmr.survey.Survey or None) – Sets given survey class instance or create empty class instance.
  • fid (integer [ 0 ]) – Index of corresponding sounding in the survey.
setTx(tx, **kwargs)[source]

Sets initialized loop or pipe arg and kwargs to loadLoop.

setZVector(vector, min_thk=0.5)[source]

Defines the attribute zvec.

Sets the given vector as z discretization. Attention: the value for min_thk defines the minimum thickness of the discretization used in the end. For all thicknesses in vector smaller than min_thk, the Kernel is integrated to match the min_thk. For calulation of the kernel function the original given vector is used.

Parameters:
  • vector (array_like) – Z discretization in m to be used for the kernel calculation. If a new vector is to be created, please also take a look at the method createZVector.
  • min_thk (float) – Minimum thickness te kernel and zvec is integrated if returned. This leads to higher accuracy in the vicinity of the loop.
show(toplot=['real', 'imag', 'amp', 'phase', '0D'], indices=None, savename=None, normed=False, suptitle=None, ax=None, pulse_in_log=False, kernel_absolute_values=False, cbar_percentage=0.99, fixed_cbar=False, lut=33, show_marked_edges=False, **kwargs)[source]

Visualise the Kernel with respect to the desired dimension.

Automatically defined within the kernel class via the parameter kernel.dimension = [0…3]. Plotting of a kernel in the desired dimension is only possible if the kernel is also calculated with respect to that dimension. It’s not possible to calculate the kernel with kernel.dimension = 1 and then plot the kernel with kernel.dimension = 2.

0D :
Simple Graph plotting kernel-values over pulsemoments
1D :
Graph with 1D integrated kernels over the depth of the model
2D :
Slice of the x-z-plane with triangle mesh containing the 2D
3D :
Export of the kernel in vtk format for visualising.

none so far

Plots the 1D integrated Kernel with a given z discretisation over the measured pulse sequences.

toplot: list [ [‘real’, ‘imag’, ‘amp’, ‘phase’, ‘1D’] ]
There are different possibilities to plot the kernel. This parameter defines which part of the kernel is shown. Possible options are: ‘real’, ‘imag’, ‘amp’, ‘phase’, ‘0D’ (integrated over z). All strings in the toplot variable will be plotted in the same order given in the list.
cMap: string [‘viridis’]
Defines the colormap used to display the kernel. In order to get a good contrast between the max and min as well as being useful in comparison with MRSMatlab, ‘viridis’ is the default colormap. Any colormap reachable by the plt.get_cmap(…) method can be chosen.
normed: bool [True]
A on the dimension based normalisation of the plot permits a better assessment of the kernel distribution.
ax: plotting ax or list of axes [None]
Plot on a predefined ax and gives back the ax. A onedimensionla list of axes is also accepted, if the number of items in ‘toplot’ is the same as the available axes.
lut: None or int [None]
Number of colors for the colorbar. If lut is not None it must be an integer giving the number of entries desired in the lookup table, and name must be a standard mpl colormap name.
indices: list
By default one 2D plot is created for each pulsemoment. In order to limit the number of plots the optional paramter indices can be given as a list of indices referring to the pulse moments to be shown.
cMap: string [‘viridis’]
See Parameter 1D.
normed: bool [True]
A on the dimension based normalisation of the plot permits a better assessment of the kernel distribution.
show_marked_edges: boolean [ False ]
Whether or not marked edges gets drawn.
possible kwargs for matplotlib:
cMin, cMax for range of the colorbar. All other kwargs are reaching matplotlib functions.
default label 2D:
‘integrated kernel (2D) [nV/$m^2$] pulsemoment: {:.3f} As’ .format(self.pulses[i])

A self-sufficient plot of the kernel without any integration would result in a set of 3D Cubes and is not implemented for now.

Instead the kernel will be saved in vtk format which can be easily handled.

savename: string
A String defining the relative path to the vtk-file the kernel will be saved in. If not given the default savename will be flagged with the string ‘_default_’ and contain some information about the kernel.

Example

2D:

>>> ax, cbar = kernel.show(indices=[16], cMin=-1,
>>>                        cMax=2, size=20, pad=0.7)
>>> ax.set_ylim(-50, 0)
sliceKernel2D(savename=None, forceNew=False, loopSaveName=None, num_cpu=None, new_bfield=False, loop_mesh=None, slice_name=None, **kwargs)[source]

2D Kernel in a memory saving parallel computation approach.

tx

Reference to transmitter class instance in survey.

tx_area

Area of the transmitter loop.

zvec

z discretisation