comet.pyhed.misc package

Submodules

comet.pyhed.misc.console_call module

Part of comet/pyhed/misc

comet.pyhed.misc.console_call.embeddedMPIRun(scriptname, *scriptargs, **kwargs)[source]
Parameters:
  • scriptargs – All given arguments will be piped to the mpirun. Kwargs has to be given in two arguments.
  • kwargs – Only for use in this function, kwargs are not piped to the embeddedMPIRun.
  • kwargs
  • ——
  • python_to_call (string [‘python’ or ‘python3’]) – Programname to be called with mpirun.
  • number_of_processes (int [12]) – Number of processes for mpirun.
comet.pyhed.misc.console_call.embeddedMPIRun_bash(scriptname, *scriptargs, **kwargs)[source]
Parameters:
  • scriptargs – All given arguments will be piped to the mpirun. Kwargs has to be given in two arguments.
  • kwargs – Only for use in this function, kwargs are not piped to the embeddedMPIRun.
  • kwargs
  • ——
  • python_to_call (string [‘python’ or ‘python3’]) – Programname to be called with mpirun.
  • number_of_processes (int [12]) – Number of processes for mpirun.
comet.pyhed.misc.console_call.local_apps(name, *args, **kwargs)[source]

Finds local apps in the comet/pyhed/apps directory by name and call an embeddedMPIRun and returns the subprocess.call.

comet.pyhed.misc.console_call.local_apps_bash(name, *args, **kwargs)[source]

Finds local apps in the comet/pyhed/apps directory by name and call an embeddedMPIRun and returns the subprocess.call.

comet.pyhed.misc.console_call.tetgen151(meshname, maxArea='', quality=1.2, path=None, verbose=False, paraString=None, preserve_facets=False, addparams='', suppress_tetgen_files=False, vtk_out=True)[source]

TetGen A Quality Tetrahedral Mesh Generator and 3D Delaunay Triangulator Version 1.5 May 31, 2014

Copyright (C) 2002 - 2014

What Can TetGen Do?

TetGen generates Delaunay tetrahedralizations, constrained Delaunay tetrahedralizations, and quality tetrahedral meshes.

Command Line Syntax:

Below is the basic command line syntax of TetGen with a list of short descriptions. Underscores indicate that numbers may optionally follow certain switches. Do not leave any space between a switch and its numeric parameter. ‘input_file’ contains input data depending on the switches you supplied which may be a piecewise linear complex or a list of nodes. File formats and detailed description of command line switches are found in user’s manual.

tetgen [-pYrq_Aa_miO_S_T_XMwcdzfenvgkJBNEFICQVh] input_file
-p Tetrahedralizes a piecewise linear complex (PLC).
-Y Preserves the input surface mesh (does not modify it).
-r Reconstructs a previously generated mesh.
-q Refines mesh (to improve mesh quality).
-R Mesh coarsening (to reduce the mesh elements).
-A Assigns attributes to tetrahedra in different regions.
-a Applies a maximum tetrahedron volume constraint.
-m Applies a mesh sizing function.
-i Inserts a list of additional points.
-O Specifies the level of mesh optimization.
-S Specifies maximum number of added points.
-T Sets a tolerance for coplanar test (default 1e-8).
-X Suppresses use of exact arithmetic.
-M No merge of coplanar facets or very close vertices.
-w Generates weighted Delaunay (regular) triangulation.
-c Retains the convex hull of the PLC.
-d Detects self-intersections of facets of the PLC.
-z Numbers all output items starting from zero.
-f Outputs all faces to .face file.
-e Outputs all edges to .edge file.
-n Outputs tetrahedra neighbors to .neigh file.
-v Outputs Voronoi diagram to files.
-g Outputs mesh to .mesh file for viewing by Medit.
-k Outputs mesh to .vtk file for viewing by Paraview.
-J No jettison of unused vertices from output .node file.
-B Suppresses output of boundary information.
-N Suppresses output of .node file.
-E Suppresses output of .ele file.
-F Suppresses output of .face and .edge file.
-I Suppresses mesh iteration numbers.
-C Checks the consistency of the final mesh.
-Q Quiet: No terminal output except errors.
-V Verbose: Detailed information, more terminal output.
-h Help: A brief instruction for using TetGen.

-o2 quadratic mesh

Examples of How to Use TetGen:

‘tetgen object’ reads vertices from object.node, and writes their Delaunay tetrahedralization to object.1.node, object.1.ele (tetrahedra), and object.1.face (convex hull faces).

‘tetgen -p object’ reads a PLC from object.poly or object.smesh (and possibly object.node) and writes its constrained Delaunay tetrahedralization to object.1.node, object.1.ele, object.1.face, (boundary faces) and object.1.edge (boundary edges).

‘tetgen -pq1.414a.1 object’ reads a PLC from object.poly or object.smesh (and possibly object.node), generates a mesh whose tetrahedra have radius-edge ratio smaller than 1.414 and have volume of 0.1 or less, (and writes the mesh to object.1.node, object.1.ele, object.1.face, and object.1.edge… not anymore)

comet.pyhed.misc.load_save module

Part of comet/pyhed/misc

comet.pyhed.misc.load_save.dump2Json(json_name=None, **kwargs)[source]

Dumps all keyword-value combinations given in kwargs into a json file. Supported variable types can by found here:

https://docs.python.org/3/library/json.html

comet.pyhed.misc.load_save.exportSparseMatrixAsNumpyArchive(name, *sparseMats)[source]
comet.pyhed.misc.load_save.json2Dict(name)[source]

Reads a json file from disk and converts it to python dictionary.

comet.pyhed.misc.load_save.loadSparseMatrixFromNumpyArchive(name, csr=True, verbose=True)[source]

comet.pyhed.misc.matrixWrapper module

Part of comet/pyhed/misc

comet.pyhed.misc.matrixWrapper.ComplexNumpyMatrix(mat, copy=False)[source]
comet.pyhed.misc.matrixWrapper.NumpyMatrix(mat, copy=False)[source]

Matrix Wrapper for for ndarrays, providing syntax for pygimli c++ core algorithms (rows, cols, mult, transMult, save(numpy)).

class comet.pyhed.misc.matrixWrapper.RealNumpyMatrix(mat, copy=False)[source]

Bases: sphinx.ext.autodoc.importer._MockObject

Matrix Wrapper for for ndarrays, providing syntax for pygimli c++ core algorithms. Holds reference to a real matrix, providing the correct multiplication algorithms for the pygimli inversion process.

cols()[source]
mult(vector)[source]
rows()[source]
save(name)[source]
transMult(vector)[source]

comet.pyhed.misc.mesh_tools module

Part of comet/pyhed/misc

comet.pyhed.misc.mesh_tools.createConstraintMesh(mesh)[source]

Creates a refined mesh, where every triangle is divided in three triangles, with the midpoint of the original cells as new node. This is only done for each boundary that has a right and a left cell (no boundary edges) and is usefull for displaing the boundary constraints of the original mesh.

>>> import pygimli as pg
>>> import numpy as np
>>> mesh = pg.load('invmesh.bms')
>>> cw = np.load('constraints.npy')
>>> cmesh = createConstraintMesh(mesh)
>>> pg.show(cmesh, data=cw[np.array(cmesh.cellMarkers(), dtype=int)])
comet.pyhed.misc.mesh_tools.createH2(inmesh, order=1, integration_mat=False)[source]

Creates a H-2**N refined mesh with order N and Integration matrix.

comet.pyhed.misc.mesh_tools.sameGeometry(mesh1, mesh2, atol=1e-08, rtol=1e-05)[source]

comet.pyhed.misc.mpi_tools module

Part of comet/pyhed/misc

comet.pyhed.misc.mpi_tools.abortIfError()[source]
comet.pyhed.misc.mpi_tools.importCustemResults(name, ntx=1)[source]
comet.pyhed.misc.mpi_tools.saveFenicsField(savename_base, loop, secondary=False, htr=None, hti=None, hsr=None, hsi=None)[source]

Save fenics fields from loppclass object in mpirun environment in gimli single core sorting for later use in single core tasks.

savename total field :

  • savename_base + ‘_total.npy’

if secondary is True:

savename secondary field:

  • savename_base + ‘_secondary.npy’

Saved variables are:

  • loop.secMOD.PP.H_t_r_cg,
  • loop.secMOD.PP.H_t_i_cg,
  • loop.secMOD.PP.H_s_r_cg,
  • loop.secMOD.PP.H_s_i_cg

comet.pyhed.misc.para_lib module

Part of comet/pyhed/misc

comet.pyhed.misc.para_lib.InterpolationMatrix_para(mesh_name, out_coords, maxCPUCount=12, in_node_count=None, verbose=True)[source]

Multiprocessing over outcoords.

comet.pyhed.misc.poly_tools module

Part of comet/pyhed/misc

comet.pyhed.misc.poly_tools.cleanUpTetgenFiles(basename)[source]

Removes temporary tetgen files.

Parameters:basename (string) – File path. All files with that basename and one of the following endings will be removed (‘.poly’, ‘.ele’, ‘.node’ ‘.face’ ‘.edge’).
comet.pyhed.misc.poly_tools.createPolyBoxWithHalfspace(minx, maxx, miny, maxy, minz, maxz, halfspace_at=0.0, without_halfspace=False, interface_marker=None)[source]

Creates a simple poly file for further mesh build processes.

Imports pygimli.

Parameters:
  • minx (float) – Minimum x dimension.
  • maxx (float) – Maximum x dimension.
  • miny (float) – Minimum y dimension.
  • maxy (float) – Maximum y dimension.
  • minz (float) – Minimum z dimension.
  • maxz (float) – Maximum z dimension.
  • halfspace_at (float) – Z value where the halfspace is considered. Additionally to the corner points of the simple halfspace box, a separation of the z edges will be at halfspace_at.
  • without_halfspace (booleam [ False ]) – An face that closes the 4 edge points at halfspace_at is inserted. This can be ommitted if creating but a tetrahedron boundary around another polygon.
  • interface_marker (integer [ None ]) – Optional marker for the interface face, for later identification.
Returns:

Closed polygon mesh with or without face at the halfspace interface. Note that the first four nodes in the polygon correspond to the four edge nodes at the halfspace interface, for manual connection to other polygons.

Return type:

pg.Mesh

comet.pyhed.misc.test_class module

Part of comet/pyhed/misc

class comet.pyhed.misc.test_class.BaseTest(name)[source]

Bases: object

test()[source]
testing_function()[source]

comet.pyhed.misc.timer module

Part of comet/pyhed/misc

class comet.pyhed.misc.timer.NoneTimer(verbose=True)[source]

Bases: object

exportLog(savename)[source]
getMessage(msg)[source]
importLog(savename)[source]
noHist(msg)[source]
printHistory()[source]
setTimeFactor(factor)[source]
setVerbose(verbose)[source]
silent(msg)[source]
tick(msg, **kwargs)[source]
update()[source]
class comet.pyhed.misc.timer.Timer(verbose=True, timestamps=True, timefactor=1.0)[source]

Bases: object

exportLog(savename)[source]
getMessage(msg, ts=None)[source]
importLog(savename)[source]
noHist(msg, update=True, ts=None)[source]
printHistory()[source]
setTimeFactor(factor)[source]
setTimestamps(bool_timestamps, strftime='%Y-%m-%d %H:%M:%S')[source]
setVerbose(verbose)[source]
silent(msg, update=True, ts=None)[source]
tick(msg, update=True, ts=None, **printkwargs)[source]
time_last
time_total
update()[source]

comet.pyhed.misc.toolbox module

Part of comet/pyhed/misc

exception comet.pyhed.misc.toolbox.NamespaceError(value)[source]

Bases: Exception

Named Error for try except clauses.

comet.pyhed.misc.toolbox.convertCoordinates(gimli, dolfin)[source]

Find sorting between two coordinate arrays if same points. input: arr1, arr2: two coordinate lists of same shape (n, 3) which contains the same coordinates but in a diffrent order. output: arr1_arr2, arr2_arr1: index arrays which converts coordinates from input1 to input2 and from input2 to input1.

comet.pyhed.misc.toolbox.floatString(value, frmt='2.2f', replace='_')[source]

Converts a Float to a string for filenames etc.

comet.pyhed.misc.toolbox.getAllValuesByReference(mat, refarray)[source]

Gets all values from input hdf5 data set found in given reference array of the same dataset.

>>> import h5py
>>> from comet import pyhed as ph
>>> mat = h5py.File('input.mrsd')
>>> # get pulse moments from mrsd file
>>> pulse_mat = mat['proclog']['Q']['q']
>>> pulses = ph.misc.getAllValuesByReference(mat, pulse_mat)
array([ 0.11261871,  0.15802349,  0.1729516 ,  0.24440305,  0.27615926,
...     0.39153588,  0.45558559,  0.64535046,  0.77051771,  1.08620425,
...     1.32817318,  1.85991744,  2.32437798,  3.22896476,  4.11364457,
...     5.66420968,  7.33714431, 10.01091275, 13.18643762, 17.83750801])
comet.pyhed.misc.toolbox.insert(array1, array2, breaking_point_float=0, right=True)[source]

Utility function to insert points between two arrays. Depricated.

comet.pyhed.misc.toolbox.plt_ioff()[source]

Temporal overrides the interactive mode of matplotlib.

comet.pyhed.misc.toolbox.plt_ion()[source]

Temporal overrides the interactive mode of matplotlib.

comet.pyhed.misc.toolbox.printv(string, *args)[source]

for maintenance and debugging

comet.pyhed.misc.toolbox.progressBar(it, prefix='', file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)[source]

Iterable progress bar. Usage

exchange:

>>> for i in range(12):

with:

>>> for i in progressBar(range(12), 'some describing string: '):
comet.pyhed.misc.toolbox.project1DModel(thk, para, out)[source]

projects a simple synthetic layered model to a given discretisation. The discretisation “disOut” has to be a vector for the corners of the desired discretisation. Therefore the output will be a vector with len(outDis) - 1 elements. “parameter” must have one entry more than thickness.

>>> thk = [2.375]
>>> resistivity = [100, 5]
>>> disOut = np.linspace(0, -4.5, 10)
>>> model = project1DModel(thk, resistivity, disOut)
>>> print(model)  # 100 * 0.75 + 5 * 0.25 = 76.25
[ 100.   100.   100.   100.    76.25    5.     5.     5.     5. ]
comet.pyhed.misc.toolbox.refine(array, start='0', end='-1', insert=1, log=False, zerovalue=False, invert=False)[source]

Utility function to refine array. Depricated.

comet.pyhed.misc.toolbox.setNearestMarkers(outmesh, inmesh, y_lim, marker_air=0, marker_half=1, fill_air_ground=False, air_interface=0.0)[source]

Set marker from 2d mesh + limits in y to 3d mesh. Returns list with ommitted marker or empty list. Optinally fills air and groundspace outside the 2d mesh with marker.

comet.pyhed.misc.toolbox.setNearestMarkers_old(outmesh, inmesh, marker_air=0, marker_half=1, fill_air_ground=False)[source]

Set marker from one mesh to another. Returns list with ommitted marker.

comet.pyhed.misc.toolbox.setdebugging(Bool, local=True)[source]

Temporal function used to control debug mode. Do not use.

comet.pyhed.misc.toolbox.temporal_printoptions(threshold=5, **kwargs)[source]

Temporal overrides the printoptions of numpy arrays.

comet.pyhed.misc.vec module

Part of comet/pyhed/misc

comet.pyhed.misc.vec.Ca2Cy(cartesian, dtype=<sphinx.ext.autodoc.importer._MockObject object>, drop_tol=0.01, dipole_z=0.0)[source]

Convert cartesian coords to cylindrical coords.

Parameters:
  • cartesian (np.ndarray) – Coordinate vector of for N positions of shape (3, N).
  • dtype (np.dtype or str) – Optional choice of output data type.
  • drop_tol – Tolerance in m to avoid zeros in horizontal distances (singlularity removal). All values for the resulting horizontal distance below the drop_tol are redistributed between drop_tol and 20% of the distance to the first point outside droptol. Raises Exception if no point lies outside of drop_tol. drop_tol=None disables the singularity removal (default).
Returns:

cylindrical – Coordinate Vector in cylindrical cordinates (radius, phi, z) in given datra type or input data type and with or without singularities removed.

Return type:

np.ndarray

comet.pyhed.misc.vec.Ca2CyField(cartesian, field, dtype=None)[source]

Conversion of 3d vector field from cylindrical coords in cartesian.

# cartesian = cartesian coordinate system (x, y, z) # x = field[x] * cos(phi) - field[y] * sin(phi) # y = - field[x] * sin(Phi) + field[y] * cos(phi) # z = field[z] # output: # field_cylindrical = data in cylindrical coordinates (r, phi, z)

Parameters:
  • cartesian (np.ndarray) – Coordinate vector of for N positions of shape (3, N).
  • field (np.ndarray) – Field vector of for N positions of shape (3, N).
  • dtype (np.dtype or str) – Optional choice of output data type.
Returns:

field – Field vector in cylindrical cordinates (x, y, z) in given datra type or input data type.

Return type:

np.ndarray

comet.pyhed.misc.vec.Cy2Ca(cylindrical, dtype=None)[source]

Convert cartesian coords to cylindrical coords.

Parameters:
  • cylindrical (np.ndarray) – Coordinate vector of for N positions of shape (3, N).
  • dtype (np.dtype or str) – Optional choice of output data type.
Returns:

cartesian – Coordinate Vector in cartesian cordinates (x, y, z) in given datra type or input data type.

Return type:

np.ndarray

comet.pyhed.misc.vec.Cy2CaField(cylindrical, field, dtype=None)[source]

Conversion of 3d vector field from cartesian coords in cylindrical.

# polar = polar coordinate system # x = field[r] * cos(phi) - field[phi] * sin(phi) # y = field[r] * sin(phi) + field[phi] * cos(phi) # z = field[z] # output: # field_cartesian = data in zylindrical coordinates

Parameters:
  • cylindrical (np.ndarray) – Coordinate vector of for N positions of shape (3, N).
  • field (np.ndarray) – Field vector of for N positions of shape (3, N).
  • dtype (np.dtype or str) – Optional choice of output data type.
Returns:

cartesian field – Field vector in cartesian cordinates (x, y, z) in given datra type or input data type.

Return type:

np.ndarray

comet.pyhed.misc.vec.GridtoVector(*args, **kwargs)[source]

# transform the matlab grid to a python vector with the correct shape # can take vector field data with x, y, z coordinates or simple one # dimansional vectors # 2D is not implemented yet

Parameters:
  • order ([‘F’]) – order = ‘F’ -> Fortran style = x varies fastest, instead of z
  • comp ([3]) – number of components
  • # status (implemented)
comet.pyhed.misc.vec.KtoP(cartesian, dtype=<sphinx.ext.autodoc.importer._MockObject object>, drop_tol=0.01)[source]

# status: depricated, use Ca2Cy instead

comet.pyhed.misc.vec.KtoP_all(cartesian, dtype=<sphinx.ext.autodoc.importer._MockObject object>, drop_tol=0.01)[source]

# r = np.sqrt(model[0]**2 + model[1]**2) # phi = np.arctan2(model[1], model[0]) # z = np.copy(model[2])

comet.pyhed.misc.vec.KtoP_field(cartesian, field, dtype=<sphinx.ext.autodoc.importer._MockObject object>)[source]

# status: depricated, please use Ca2CyField instead.

comet.pyhed.misc.vec.PtoK(cylindrical, dtype=<sphinx.ext.autodoc.importer._MockObject object>)[source]

# status: depricated use Cy2Ca instead

comet.pyhed.misc.vec.PtoK_field(cylindrical, field, dtype=<sphinx.ext.autodoc.importer._MockObject object>)[source]

# status: depricated, please use Cy2CaField instead.

comet.pyhed.misc.vec.R3VtoNumpy(R3Vector, **kwargs)[source]

Creates a numpy vector from a pygimli R3Vector.

comet.pyhed.misc.vec.VectortoGrid(vector, shape, order='F', swap=False)[source]

see ‘GridtoVector’ x == VectortoGrid(GridtoVector(x), x.shape) is True

# status: implemented

comet.pyhed.misc.vec.angle(ax1, ax2)[source]

Returns angle between two arbitrary vectors of shape (3, …). Allows broadcasting.

comet.pyhed.misc.vec.areaFromPolyPoints(points)[source]

Get perimeter of a polygon.

comet.pyhed.misc.vec.convertCRStoMap(rowIdx, colPtr)[source]

Converts CRS indices to map indices.

comet.pyhed.misc.vec.cumsumDepth(a, min_thk=0.5)[source]

Summs part of a array, until all layers have a given minimum thickness. only use on array with increasing thickness.

comet.pyhed.misc.vec.fillCRS(crsMat, rowIdx, colPtr, vals)[source]

Fill CRS format SparseMatrix with values. Very Slow.

comet.pyhed.misc.vec.fixSingularity(model, drop_tol=0.01, dipole_z=0.0)[source]

Points in zero get values of drop_tol. Points on drop_tol get Values of up to 20% the value to the first point out of the drop_tol. If all points are in the drop_tol a warning is printed.

comet.pyhed.misc.vec.getConstraints(inv)[source]
comet.pyhed.misc.vec.getIndicesFromConstraintMatrix(mat)[source]
comet.pyhed.misc.vec.getRSparseValues(sparseMapMatrix, indices=True, getInCRS=False)[source]

Get CRS Arrays (Row Index, Column Start_End, Values) from SparseMatrix (CRS format).

comet.pyhed.misc.vec.interpolateField(Mesh, positions, Field, interpolationMatrix=None, verbose=False)[source]

simple case: (meshInput, meshOutput, fieldFromInputMesh) ready

# status: implemented

comet.pyhed.misc.vec.interpolateField_Matrix(Field, InterpolationMatrix, verbose=False)[source]

# status: implemented

comet.pyhed.misc.vec.interpolateField_rotatedMatrix(Field, base_mat=None, sin_mat=None, cos_mat=None)[source]

# status: in testing

comet.pyhed.misc.vec.interpolateVector(Mesh, Slice, Vector, verbose=False)[source]

Interpolates a given vectorfield(Vector) based on the given Mesh to a second mesh or slice. The field can either be real or complex.

# status: implemented

comet.pyhed.misc.vec.linspace2D(Point1, Point2, num)[source]

Internal function. Like linspace but for twodimensional points.

comet.pyhed.misc.vec.linspace3D(Point1, Point2, num)[source]

Internal function. Like linspace but for threedimensional points.

comet.pyhed.misc.vec.perimeterFromPolyPoints(points, circle_radius=None, closed=True)[source]

Get perimeter of a polygon.

comet.pyhed.misc.vec.pointDataToCellData_np(mesh, field, mixed=False, weight=True)[source]

Interpolates vector- or skalarfield data defined on the nodes of the given mesh to its cell midpoints. For now it has to be either a uniform mesh with field (3d, complex or real) or scalar (1d, complex or real) datasets or a mixed mesh with a simple real scalar data set (takes more time).

Parameters:
  • mesh (pg.Mesh) – For now the algorithm takes only pygimli meshes.
  • field (array of shape (n) or (n, 3) or pg.Vector) – Data set with n = number of nodes in the mesh.
  • mixed (bool [False]) – Flag to determine if the mesh is either of mixed (True) shape (cells can consist of variable number of nodes) or uniform (False).
  • weight (bool [True]) – The cell data can be calculated as simple average of the surrounding node values (False) or additionally weighted by their inverse distance from the nodes (True).
  • Output
  • ——
  • newfield (array of shape (c) or (3, c)) – Data set with c = number of cells in the mesh.
comet.pyhed.misc.vec.regular_slice(dim1, dim2, direction, value)[source]

out: regular pygimli 2D-mesh object with given discretisation and orientation with respect to a 3D coordinate system.

for now there are only x-, y- and z-orientated slices possible

# status: implemented

comet.pyhed.misc.vec.regular_sliceFrom3DMesh(mesh, discretisation1, discretisation2, direction, value)[source]

Cut a slice with regular grid discretisation from an arbitrary shaped irregular mesh. Used for plotting purposes with matplotlib.

input: mesh
x discretisation y discreatisation normal direction of the slice value for position of the slice on the normal axis

# status: implemented

comet.pyhed.misc.vec.rotFromAtoB(vec, ax1, ax2)[source]

Rotates input vector vec from one direction ax1 (x, y, z) to another direction ax2 (x, y, z).

comet.pyhed.misc.vec.rotate3(Vec, alpha, axis='z', copy=False)[source]

Rotates 3 dimensional arrays around a given axis with angle alpha.

comet.pyhed.misc.vec.rotate3_all(Vec, alpha, axis='z', copy=False)[source]

‘ijk,k…i->k…j’ … = number of points, broadcasted dimension i = 3 (3 coords per point) j = 3 (3 coords per point) k = number of different dipoles, number of alphas

comet.pyhed.misc.vec.rotationMatrix(axis, theta)[source]

Return the rotation matrix associated with counterclockwise rotation about the given axis (3, n) by theta radians (n,). Supports broadcasting along second axis of input axis.

Array with rotation matrices of shape (3, 3, n) or (3, 3) if n==1.

comet.pyhed.misc.vec.sinhZVolumeFunction(z, z_range=[0, -100], area_range=[0.1, 100])[source]

Maps values from z per z_range to area_range using a sinh function instead of linear interpolation. Values outside z_range are assigned the limits of area_range.

Example

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> area = []
>>> zrange = np.linspace(30, -130, 160)
>>> for z in zrange:
>>>     area.append(sinhZVolumeFunction([z]))
>>> fig, ax = plt.subplots(1, 1)
>>> ax.plot(zrange, area)
comet.pyhed.misc.vec.sinhspace(start, stop, num_step)[source]

Like linspace but using a hyperbolic sine function.

comet.pyhed.misc.vec.sumBetweenIndices(array, indices, use_thickness=False, axis=0)[source]

Split array at given axis and indices and sum up the parts. If use_thickness is True, the difference of the absolute values are used, usfull for array representing a depth for example.

comet.pyhed.misc.vec.translate(Vec, x, y, z=0, copy=False)[source]

Translate a given three dimensional vector and returns either a view of it or a new object.

# status: implemented

comet.pyhed.misc.vec.translateToDipole(Vec, Dipole, copy=False)[source]
comet.pyhed.misc.vec.translate_all(Vec, coords)[source]

Vec: Dim: num_points, 3 coords: Dim = num_dipoles, 3

output: Dim: num_dipoles, num_points, 3

comet.pyhed.misc.vec.uniqueAndSum(indices, to_sum, return_index=False, verbose=False)[source]

Summs double values found by indices in a various number of arrays.

Returns the sorted unique elements of a column_stacked array of indices. Another column_stacked array is returned with values at the unique indices, while values at double indices are properly summed.

Parameters:
  • ar (array_like) – Input array. This will be flattened if it is not already 1-D.
  • to_sum (array_like) – Input array to be summed over axis 0. Other exsisting axes will be broadcasted remain untouched.
  • return_index (bool, optional) – If True, also return the indices of ar (along the specified axis, if provided, or in the flattened array) that result in the unique array.
Returns:

  • unique (ndarray) – The sorted unique values.
  • summed_array (ndarray) – The summed array, whereas all values for a specific index is the sum over all corresponding nonunique values.
  • unique_indices (ndarray, optional) – The indices of the first occurrences of the unique values in the original array. Only provided if return_index is True.

Example

>>> import numpy as np
>>> from comet.pyhed.misc.vec import uniqueAndSum
>>> idx1 = np.array([0, 0, 1, 1, 2, 2])
>>> idx2 = np.array([0, 0, 1, 2, 3, 3])
>>> # indices at positions 0 and 1 and at positions 5 and 6 are not unique
>>> to_sort = np.column_stack((idx1, idx2))
>>> # its possible to stack more than two array
>>> # you need for example 3 array to find unique node positions in a mesh
>>> values = np.arange(0.1, 0.7, 0.1)
>>> print(values)
[ 0.1  0.2  0.3  0.4  0.5  0.6]
>>> # some values to be summed together (for example attributes of nodes)
>>> unique_idx, summed_vals = uniqueAndSum(to_sort, values)
>>> print(unique_idx)
[[0 0]
 [1 1]
 [1 2]
 [2 3]]
>>> print(summed_vals)
[ 0.3  0.3  0.4  1.1]
>>> # [0.1 + 0.2, 03., 0.4, 0.5 + 0.6]

Module contents

Module comet/pyhed/misc