pyfrp.modules package¶
Submodules¶
pyfrp.modules.pyfrp_IO_module module¶
Input/Output module for PyFRAP toolbox.
Handles saving/loading PyFRAP projects into pickled files and the memory handling that comes with it.
-
pyfrp.modules.pyfrp_IO_module.
cleanUp
()¶ Calls garbage collector to clean up.
-
pyfrp.modules.pyfrp_IO_module.
copyAndRenameFile
(fn, fnNew, debug=False)¶ Copies file
fn
into same directory asfn
and renames itfnNew
.Note
If copying fails, then function will return old filename.
Parameters: - fn (str) – Filepath of original file.
- fnNew (str) – New filename.
Keyword Arguments: debug (bool) – Print out debugging messages.
Returns: Path to new file.
Return type: str
-
pyfrp.modules.pyfrp_IO_module.
copyMeshFiles
(fn, fnGeo, fnMsh, debug=False)¶ Copies meshfiles to new location.
If
fn
does not end onmeshfiles
, will create a foldermeshfiles
where to dump new files.Note
If
fnGeo
is a merged file, will try to copy all used .geo and .msh files and also update the merged file such that it refers to the new mesh files.Parameters: - fn (str) – Filepath or parent directory where to put meshfiles.
- fnGeo (str) – Filepath of geo file.
- fnMsh (str) – Filepath of msh file.
Keyword Arguments: debug (bool) – Print out debugging messages.
Returns: Tuple containing:
- fnGeoNew (str): New geo file location.
- fnMshNew (str): New msh file location.
Return type: tuple
-
pyfrp.modules.pyfrp_IO_module.
loadEmbryo
(fn, update=True)¶ Loads embryo object from pickle file and brings it up-to-date.
Parameters: fn (str) – Filename. Keyword Arguments: update (bool) – Update to current version. Returns: Embryo file. Return type: pyfrp.subclasses.pyfrp_embryo
-
pyfrp.modules.pyfrp_IO_module.
loadFromPickle
(fn)¶ Loads obj from pickled format.
Parameters: fn (str) – Filename. Returns: Output filename. Return type: str
-
pyfrp.modules.pyfrp_IO_module.
loadMolecule
(fn, update=True)¶ Loads molecule object from pickle file and brings it up-to-date.
Parameters: fn (str) – Filename. Keyword Arguments: update (bool) – Update to current version. Returns: Molecule file. Return type: pyfrp.subclasses.pyfrp_molecule
-
pyfrp.modules.pyfrp_IO_module.
saveToPickle
(obj, fn=None)¶ Saves obj into pickled format.
Note
If
fn==Non
, will try to save toobj.name
, otherwise unnamed.pkKeyword Arguments: fn (str) – Output file name. Returns: Output filename. Return type: str
-
pyfrp.modules.pyfrp_IO_module.
writeTableToCSV
(l, header, fn, col=False)¶ Writes table to csv file.
If
col=True
, columns are given vial
, otherwise rows are given.Parameters: - l (list) – List of rows or columns.
- header (list) – List of headers.
- col (bool) – Flag on how rows/columns are given.
Returns: Tuple containing:
- header (list): Header of table.
- table (list): Table as a list of rows.
Return type: tuple
pyfrp.modules.pyfrp_fit_module module¶
Parameter fitting module for PyFRAP toolbox. Contains functions for the following two tasks:
- Fitting a PyFRAP simulation to FRAP data analyzed by PyFRAP and saving its results in a
pyfrp.subclasses.pyfrp_fit.fit`
instance. - Pinning PyFRAP simulation and data between 0 and 1.
- Likelihood profiling functions.
-
pyfrp.modules.pyfrp_fit_module.
FRAPFitting
(fit, debug=False, ax=None)¶ Main fitting function.
Fits simulation result to analyzed data.
Parameters: fit (pyfrp.subclasses.pyfrp_fit) – Fit object containing all important information needed.
Keyword Arguments: - debug (bool) – Display debugging output and plots.
- ax (matplotlib.axes) – Axes to display plots in.
Returns: Performed fit.
Return type:
-
pyfrp.modules.pyfrp_fit_module.
FRAPObjFunc
(x, fit, debug, ax, returnFit)¶ Objective function for fitting FRAP experiments.
Does the following.
- Checks input using
pyfrp.modules.pyfrp_fit_module.checkInput()
. - Assigns input variables using
pyfrp.modules.pyfrp_fit_module.assignInputVariables()
. - Adjust kinetic scales using
pyfrp.modules.pyfrp_fit_module.downscaleKinetics()
. - Scales simulation vector using
pyfrp.modules.pyfrp_fit_module.scaleROIs()
. - Adds reaction kinetics using using
pyfrp.modules.pyfrp_fit_module.addKineticsToSolution()
. - Equalizes simulation vector using
pyfrp.modules.pyfrp_fit_module.equalize()
. - Computes and returns SSD.
Parameters: - x (list) – Input vector, consiting of [D,(prod),(degr)].
- fit (pyfrp.subclasses.pyfrp_fit) – Fit object.
- debug (bool) – Display debugging output and plots.
- ax (matplotlib.axes) – Axes to display plots in.
- returnFit (bool) – Return fit instead of SSD.
Returns: SSD of fit. Except
returnFit==True
, then will return fit itself.Return type: float
- Checks input using
-
pyfrp.modules.pyfrp_fit_module.
addKineticsToSolution
(scaledSimVecs, tvec, prod, degr)¶ Adds reaction kinetics to simulation solution.
Parameters: - scaledSimVecs (list) – List of scaled simulation vectors by ROI.
- tvec (numpy.ndarray) – Data time vector.
- prod (float) – Production rate.
- degr (float) – Degredation rate.
Returns: List of rescaled simulation vectors by ROI.
Return type: (list)
-
pyfrp.modules.pyfrp_fit_module.
assignInputVariables
(x, fit)¶ Decodes array given to objective function to suit fitting options.
If
fit.fitProd
orfit.fitDegr
are selected, will usex[1]
orx[2]
as input values for degradation and production rate.If
fit.equOn=True
, then will use last entry ofx0
for equalization factors, otherwise will return empty list for equFacts.Parameters: - x (list) – Input vector of objective function.
- fit (pyfrp.subclasses.pyfrp_fit) – Fit object.
Returns: Tuple containing:
- Dnew (float): Diffusion rate.
- prod (float): Production rate.
- degr (float): Degredation rate.
- equFacts (list): Equalization factors.
Return type: tuple
-
pyfrp.modules.pyfrp_fit_module.
checkInput
(x, iteration, fit)¶ Checks if input vector
x
is non-negative.Parameters: - x (list) – Input vector of objective function.
- iteration (int) – Number of iteration.
- fit (pyfrp.subclasses.pyfrp_fit) – Fit object.
Returns: True
if everythings positive,False
else.Return type: bool
-
pyfrp.modules.pyfrp_fit_module.
computeBkgd
(vec, useMin=False, debug=False)¶ Computes background value of vector.
Parameters: vec (numpy.ndarray) – Vector to be pinned.
Keyword Arguments: - useMin (bool) – Use minimum value for background computation.
- debug (bool) – Print debugging messages.
Returns: Background value.
Return type: float
-
pyfrp.modules.pyfrp_fit_module.
computeEquFactors
(dataVec, simVec)¶ Computes equalization factors per ROI.
The purpose of equalization factors is to account for immobile fractions, adjusting the level of the simulation vector to the data vector.
Check requirements: Checks if
0.1<=dataVec[i]/simVec[i]<=3
, if not, sets = 1. In practical terms, this means that the volume fraction is not allowed to increase by more than 3fold (>3), and that the immobile fraction cannot be more than 90% (< 0.1)Parameters: - dataVec (numpy.ndarray) – Data vector of ROI.
- simVec (numpy.ndarray) – Scaled simulation vector of ROI.
Returns: Array of equalization factors.
Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_fit_module.
computeFitLikelihoodProfiles
(fit, epsPerc=0.1, steps=100, debug=False)¶ Computes likelihood profile of all parameters fitted in fit.
Warning
Since we don’t yet fit the loglikelihood function, we only compute the SSD. Even though the SSD is proportional to the loglikelihood, it should be used carefully.
See also
pyfrp.modules.pyfrp_fit_module.computeLikehoodProfile()
.Parameters: fit (pyfrp.subclasses.pyfrp_fit.fit) – Fit object.
Keyword Arguments: - epsPerc (float) – Percentage of variation.
- steps (int) – Number of values around optimal parameter value.
- debug (bool) – Show debugging messages
Returns: Tuple containing:
- names (list): List of parameter names.
- xvaryVec (List): List of parameter variation arrays.
- SSDsVec (list): List of corresponding SSDs.
Return type: tuple
-
pyfrp.modules.pyfrp_fit_module.
computeLikelihoodProfile
(xOpt, fit, idx, steps=100, epsPerc=0.1, debug=False)¶ Computes likelihood profile of parameter with index idx of fit.
Warning
Since we don’t yet fit the loglikelihood function, we only compute the SSD. Even though the SSD is proportional to the loglikelihood, it should be used carefully.
Parameters: - xOpt (list) – Vector with optimal parameters.
- fit (pyfrp.subclasses.pyfrp_fit.fit) – Fit object.
- idx (int) – Index of parameter in xOpt of which profile is calculated.
Keyword Arguments: - epsPerc (float) – Percentage of variation.
- steps (int) – Number of values around optimal parameter value.
- debug (bool) – Show debugging messages
Returns: Tuple containing:
- xvary (numpy.ndarray): Array with varied parameter.
- SSDs (list): Corresponding SSDs.
Return type: tuple
-
pyfrp.modules.pyfrp_fit_module.
computeNorm
(vec, useMax=False, debug=False)¶ Computes norming value of vector.
Parameters: vec (numpy.ndarray) – Vector to be pinned.
Keyword Arguments: - useMax (bool) – Use maximum value for norm value computation.
- debug (bool) – Print debugging messages.
Returns: Norming value.
Return type: float
-
pyfrp.modules.pyfrp_fit_module.
computePinVals
(vec, useMin=False, useMax=False, bkgdVal=None, debug=False)¶ Computes pinning values of vector.
Parameters: vec (numpy.ndarray) – Vector to be pinned.
Keyword Arguments: - useMin (bool) – Use minimum value for background computation.
- useMax (bool) – Use maximum value for norm value computation.
- bkgdVal (float) – Use this background value instead of newly computing it.
- debug (bool) – Print debugging messages.
Returns: Tuple containing:
- bkgdVal (float): Background value.
- normVal (float): Norming value.
Return type: tuple
-
pyfrp.modules.pyfrp_fit_module.
cutTvec
(tvec, tCutIndex)¶ Cuts time vector as index.
Parameters: - tvec (numpy.ndarray) – Time vector.
- tCutIndex (int) – Index to cut at.
Returns: Cut time vector.
Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_fit_module.
downscaleKinetics
(prod, degr, rate)¶ Adjusts time-scale of kinetics so prod/degr will have same weight as diffusion rate.
Parameters: - prod (float) – Production rate.
- degr (float) – Degredation rate.
- rate (float) – Scaling rate.
Returns: Tuple containing:
- prod (float): Scaled production rate.
- degr (float): Scaled degredation rate.
Return type: tuple
-
pyfrp.modules.pyfrp_fit_module.
equalize
(dataVecs, simVecs, equFacts, fromVecs=False)¶ Equalizes all simulation vectors of all ROIs defined in
fit.ROIsFitted
.If
fromVecs=True
, will usefindMinEquFacts()
to compute the equalization factors that minimize SSD from a set of equalization factors given by the ratio between simulation and data vector.Parameters: - simVecs (list) – List of scaled simulation vectors by ROI.
- dataVecs (list) – List of data vectors by ROI.
- equFacts (list) – List of equalization factors.
Keyword Arguments: fromVecs (bool) – Compute equalization factors from data/simulation ratio.
Returns: Tuple containing:
- equSimVecs (list): List of equalized simulation vectors.
- equFacts (list): List of (optimal) equalization factors by ROI.
Return type: tuple
-
pyfrp.modules.pyfrp_fit_module.
findMinEquFacts
(dataVecs, simVecs)¶ Computes list of equalization factors per ROI in
fit.ROIsFitted
and then finds the one that minimizes SSD.Does this by:
- Computing equalization factors per ROI via
computeEquFactors()
. - Computing SSD for each equalization factor per ROI.
- Selecting equalization factor per ROI that minimizes SSD.
Parameters: - simVecs (list) – List of scaled simulation vectors by ROI.
- dataVecs (list) – List of data vectors by ROI.
- equFacts (list) – List of equalization factors.
Returns: Tuple containing:
- equSimVecs (list): List of equalized simulation vectors.
- equFactsFinal (list): List of optimal equalization factors by ROI.
Return type: tuple
- Computing equalization factors per ROI via
-
pyfrp.modules.pyfrp_fit_module.
getTvecCutIndex
(tvec, tCut)¶ Finds last index of time vector before time vector exceeds tCut.
Parameters: - tvec (numpy.ndarray) – Time vector.
- tCut (float) – Time to cut at.
Returns: Last index.
Return type: int
-
pyfrp.modules.pyfrp_fit_module.
interpolateSolution
(tvecData, tvecScaled, yvec)¶ Interpolates scaled simulation vector onto data time vector.
Parameters: - tvecData (numpy.ndarray) – Data time vector.
- tvecScaled (numpy.ndarray) – Scaled simulation time vector.
- yvec (numpy.ndarray) – Simulation values.
Returns: Scaled simulation vector.
Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_fit_module.
pinConc
(vec, bkgdVal, normVal, axes=None, debug=False, tvec=None, color='b')¶ Substract background and normalize: Pin concentrations between 0 and 1.
Parameters: - vec (numpy.ndarray) – Vector to be pinned.
- bkgdVal (float) – Background value.
- normVal (float) – Norming value.
Keyword Arguments: - axes (list) – List of matplotlib.axes for debugging plots.
- tvec (numpy.ndarray) – Time vector (only necessay when plotting).
- debug (bool) – Print debugging messages.
- color (str) – Color of plots.
Returns: Pinned vector.
Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_fit_module.
plotFitLikehoodProfiles
(fit, epsPerc=0.1, steps=100, debug=False, axes=None)¶ Computes and plots likelihood profile of all parameters fitted in fit.
Warning
Since we don’t yet fit the loglikelihood function, we only plot the SSD. Even though the SSD is proportional to the loglikelihood, it should be used carefully.
See also
pyfrp.modules.pyfrp_fit_module.computeFitLikehoodProfiles()
.Parameters: - xOpt (list) – Vector with optimal parameters.
- fit (pyfrp.subclasses.pyfrp_fit.fit) – Fit object.
- idx (int) – Index of parameter in xOpt of which profile is calculated.
Keyword Arguments: - epsPerc (float) – Percentage of variation.
- steps (int) – Number of values around optimal parameter value.
- debug (bool) – Show debugging messages
Returns: List of matplotlib.axes objects used for plotting.
Return type: list
-
pyfrp.modules.pyfrp_fit_module.
scaleROIs
(fit, Dnew)¶ Scales all simulation vectors of all ROIs defined in
fit.ROIsFitted
.Parameters: - fit (pyfrp.subclasses.pyfrp_fit) – Fit object.
- Dnew (float) – Scaling diffusion rate.
Returns: Tuple containing:
- fit (pyfrp.subclasses.pyfrp_fit): Updated fit object.
- tvecScaled (numpy.ndarray): Scaled time vector.
- tvecData (numpy.ndarray): Data time vector.
- scaledSimVecs (list): List of scaled simulation vectors by ROI.
- dataVecs (list): List of data vectors by ROI.
Return type: tuple
-
pyfrp.modules.pyfrp_fit_module.
scaleTime
(tvec, D, Dnew)¶ Scales time vector with D/Dnew.
Parameters: - tvec (numpy.ndarray) – Time vector.
- D (float) – Relative diffusion rate.
- Dnew (float) – Scaling diffusion rate.
Returns: Scaled time vector.
Return type: numpy.ndarray
pyfrp.modules.pyfrp_geometry_module module¶
PyFRAP module for simple geometric operations, such as
- Angle computation.
- Normal computation.
-
pyfrp.modules.pyfrp_geometry_module.
checkColinear
(vec1, vec2)¶ Returns True if two vectors are colinear.
Parameters: - vec1 (numpy.ndarray) – Vector 1.
- vec2 (numpy.ndarray) – Vector 2.
Returns: True if colinear.
Return type: bool
-
pyfrp.modules.pyfrp_geometry_module.
computeNormal
(vertices, method='cross')¶ Computes normal.
Vertices should be given as
>>> vertices=[[x1,y1,z1],[x2,y2,z2],...]
Currently there are two methods available:
cross
, see alsonormalByCross()
.newells
, see alsonewells()
.
If method is unknown, will fall back to
cross
.Parameters: vertices (list) – List of vertex coordinates. Keyword Arguments: method (str) – Method of normal computation. Returns: Normal vector. Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_geometry_module.
decodeEuclideanBase
(d)¶ Decodes a euclidean base vector given as a literal.
Example:
>>> decodeEuclideanBase('z') >>> array([ 0., 0., 1.])
Parameters: d (str) – Direction (“x”/”y”/”z”) Returns: Base vector. Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_geometry_module.
flipCoordinate
(x, destAxis, origAxis='x', debug=False)¶ Transforms coodinate from one axis to another by rolling the coordinates, e.g. clockwise turning the point.
destAxis
andorigAxis
are given as one ofx,y,z
.Parameters: - x (numpy.ndarray) – Coordinate to turn.
- destAxis (str) – Destination axis.
Keyword Arguments: - origAxis (str) – Original axis.
- debug (bool) – Print debugging output.
Returns: Transformed coordinate.
Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_geometry_module.
getAngle
(vec1, vec2)¶ Returns angle between two vectors in radians.
Angle is calculated via
\[\phi = \frac{v_1 \dot v_2}{|v_1| |v_2|}\]Note
Checks for numerical errors and corrects them if necessary.
Parameters: - vec1 (numpy.ndarray) – Vector 1.
- vec2 (numpy.ndarray) – Vector 2.
Returns: Angle.
Return type: float
-
pyfrp.modules.pyfrp_geometry_module.
getRotMatrix
(n1, n2)¶ Builds rotation matrix for the rotation of a vector n2 onto n1.
Taken from http://stackoverflow.com/questions/9423621/3d-rotations-of-a-plane .
Parameters: - n1 (numpy.ndarray) – Vector to be rotated to.
- n2 (numpy.ndarray) – Vector to rotate.
Returns: Rotation matrix
Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_geometry_module.
newellsMethod
(vertices)¶ Computes normal using Newell’s method.
Adapted from http://stackoverflow.com/questions/39001642/calculating-surface-normal-in-python-using-newells-method.
Vertices should be given as
>>> vertices=[[x1,y1,z1],[x2,y2,z2],...]
Parameters: vertices (list) – List of vertex coordinates. Returns: Normal vector to surface. Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_geometry_module.
normalByCross
(vec1, vec2)¶ Returns normalised normal vectors of plane spanned by two vectors.
Normal vector is computed by:
\[\mathbf{n} = \frac{\mathbf{v_1} \times \mathbf{v_2}}{|\mathbf{v_1} \times \mathbf{v_2}|}\]Note
Will return zero vector if
vec1
andvec2
are colinear.Parameters: - vec1 (numpy.ndarray) – Vector 1.
- vec2 (numpy.ndarray) – Vector 2.
Returns: Normal vector.
Return type: numpy.ndarray
pyfrp.modules.pyfrp_gmsh_IO_module module¶
PyFRAP module for reading/writing gmsh .geo files. Module mainly has the following features:
- Read .geo files.
- Translate geometric entities and variables defined in .geo files.
- Construct
pyfrp.pyfrp_gmsh_geometry.domain
object describing complete geometry.- Update parameters in .geo files.
- Add/Remove some geometric entities.
- Add/update box fields to allow refinement of certain ROIs in mesh.
This module together with pyfrp.pyfrp_gmsh_geometry and pyfrp.pyfrp_gmsh_module works partially as a python gmsh wrapper, however is incomplete. If you want to know more about gmsh, go to http://gmsh.info/doc/texinfo/gmsh.html .
-
pyfrp.modules.pyfrp_gmsh_IO_module.
addBoxField
(fn, volSizeIn, volSizeOut, rangeX, rangeY, rangeZ, comment='', fnOut='', overwrite=True, sameComment=True)¶ Adds box field to .geo file by doing the following:
- Copies file into temp file for backup using
copyIntoTempFile()
. - Finds all IDs of previous
Field
entities usinggetAllIDsOfType()
. - Finds current background field using
getBkgdFieldID()
. - If previous fields exist, removes them from file using
removeElementFromFile()
. - Finds last non-empty line using
getLastNonEmptyLine()
. - Removes empty lines at end of file using
removeTailingLines()
. - Writes comment using
writeComment()
. - Writes box field using
writeBoxField()
. - Writes background field using
writeBackgroundField()
.
Note
Comment is useful to describe in .geo file what the the box field actually does.
Note
Generally, background field will use
volSizeIn
as background mesh volume size.Note
Unit for parameter is pixels.
Note
If
fnOut
is not specified, will overwrite input file.Note
Will always remove previous background fields. If
overwrite=True
, will remove all fields. If additionallysameComment=True
, will look for the field that has the same comment ascomment
and only remove this particular one.See also: http://gmsh.info/doc/texinfo/gmsh.html#Specifying-mesh-element-sizes .
Parameters: - fn (str) – Filename of .geo file.
- volSizeIn (float) – Mesh element volume inside box.
- volSizeOut (float) – Mesh element volume outside box.
- rangeX (list) – Range of box field in x-direction given as
[minVal,maxVal]
. - rangeY (list) – Range of box field in y-direction given as
[minVal,maxVal]
. - rangeZ (list) – Range of box field in z-direction given as
[minVal,maxVal]
.
Keyword Arguments: - comment (str) – Comment to be added before box field.
- fnOut (str) – Filepath for output.
- overwrite (bool) – Overwrite previously exisiting box fields.
- sameComment (bool) – Only remove box field with particular comment.
- Copies file into temp file for backup using
-
pyfrp.modules.pyfrp_gmsh_IO_module.
applyParmDic
(val, parmDic)¶ Applies parameter dictionary to variable value.
Example:
>>> parmDic={'radius',3} >>> applyParmDic('radius',parmDic) >>> 3
And also applies mathemtical expressions:
>>> parmDic={'radius',3} >>> applyParmDic('radius^2-radius',parmDic) >>> 6
Parameters: - val (str) – Value string of geometric variable.
- parmDic (dict) – Parameter dictionary.
Returns: Evaluated value.
Return type: val (float)
-
pyfrp.modules.pyfrp_gmsh_IO_module.
convertMathExpr
(val)¶ Converts math expressions from .geo syntax into python syntax.
Note
Not all translations have been implemented yet. You can simply add here expressions by adding a translation to the translations list (
translations.append([CExpression,PythonExpression])
).
-
pyfrp.modules.pyfrp_gmsh_IO_module.
copyIntoTempFile
(fn, close=True)¶ Copies file into tempfile.
Note
Will create temporary file using
tempfile.mkstemp()
. You should have read/write access to whereevermkstemp
is putting files.Note
If
close==True
, will returnfh=None
andtempFile=None
.Parameters: fn (str) – Filename of file. Keyword Arguments: close (bool) – Close files after copying. Returns: Tuple containing: - tempFile (file): File handle to temp file.
- fh (file): File handle to original file.
- tempPath (tempPath): Path to temp file.
Return type: tuple
-
pyfrp.modules.pyfrp_gmsh_IO_module.
findComment
(fn, comment)¶ Finds a specific comment in .geo file and returns line in which it appears, otherwise -1.
Note
Will only look for an exact match.
Parameters: - fn (str) – Filename of .geo file.
- comment (str) – Comment to look for.
Returns: Line number of appearance.
Return type: int
-
pyfrp.modules.pyfrp_gmsh_IO_module.
genMergeGeoFile
(meshFiles, fnGeo)¶ Generates merged .geo file.
Parameters: - meshFiles (list) – List of meshfiles that will be included.
- fnGeo (str) – Output geometry file.
Returns: True if no error/warning occured.
Return type: bool
-
pyfrp.modules.pyfrp_gmsh_IO_module.
getAllIDsOfType
(fn, elementType)¶ Finds all IDs of a specific .geo element type in a .geo file.
Parameters: - fn (str) – Filename of .geo file.
- elementType (str) – Type of parameter, for example
"Point"
.
Returns: List of IDs.
Return type: list
-
pyfrp.modules.pyfrp_gmsh_IO_module.
getBkgdFieldID
(fn)¶ Finds ID of background field in .geo file.
Note
Will return
None
if .geo file has no background field specified.Parameters: fn (str) – Filename of .geo file. Returns: ID of background field. Return type: int
-
pyfrp.modules.pyfrp_gmsh_IO_module.
getCorrespondingGeoFile
(fn, meshFileExt='.msh')¶ Returns the corresponding geometry file to a mesh file.
Assumes that meshfile has same name and lives in the same folder.
Parameters: fn (str) – Path to mesh file. Keyword Arguments: meshFileExt (str) – Extension of meshfile. Returns: Tuple containing: - exists (bool): Flag if corresponding file exits.
- fnGeo (str): Path to geometry file.
Return type: tuple
-
pyfrp.modules.pyfrp_gmsh_IO_module.
getFieldByComment
(fn, comment, lineDiff=3)¶ Returns field that is preceeded by comment
comment
.Note
Will only look for an exact match.
Parameters: - fn (str) – Filename of .geo file.
- comment (str) – Comment to look for.
Keyword Arguments: lineDiff (int) – Maximum allowed difference between line of comment and field.
Returns: Line number of appearance.
Return type: int
-
pyfrp.modules.pyfrp_gmsh_IO_module.
getId
(var, delimOpen='(', delimClose=')')¶ Returns ID of object that is given between the delimiters
delimOpen
anddelimClose
.Example:
>>> getId("Point(3)") >>> ("Point",3)
Parameters: var (str) – String describing geoFile variable name.
Keyword Arguments: - delimOpen (str) – Openening delimiter of ID.
- delimClose (str) – Closing delimiter of ID.
Returns: Tuple containing:
- typ (str): Type of geometric variable.
- Id (str): Id of geometric variable.
Return type: tuple
-
pyfrp.modules.pyfrp_gmsh_IO_module.
getLargestIDOfType
(fn, elementType)¶ Finds largest ID of a specific .geo element type in a .geo file.
Parameters: - fn (str) – Filename of .geo file.
- elementType (str) – Type of parameter, for example
"Point"
.
Returns: Largest ID.
Return type: int
-
pyfrp.modules.pyfrp_gmsh_IO_module.
getLastNonEmptyLine
(fn)¶ Finds index of last non-empty line in .geo file.
Parameters: fn (str) – Filename of .geo file. Returns: Index of last non-empty line. Return type: int
-
pyfrp.modules.pyfrp_gmsh_IO_module.
getLinesByID
(fn, elementId, elementType='')¶ Finds all lines in .geo file that contain geometric entitity with ID
elementId
.Note
IDs in geometric files can be given per entitity type. That is, one can have for example a point with ID=1 (
Point(1)
) aswell as a line with ID=1 (Line(1)
). Thus one may want to useelementType
to restrict the search for a specific element type.Parameters: - fn (str) – Filename of .geo file.
- elementId (int) – ID to look for.
Keyword Arguments: elementType (str) – Type of element to restrict search on.
Returns: Line numbers at which element appears.
Return type: list
-
pyfrp.modules.pyfrp_gmsh_IO_module.
getVals
(val, parmDic, openDelim='{', closeDelim='}', sep=', ')¶ Translates value of parameter into list of floats.
Uses parameter dictionary to translate predefined variables into floats.
Example:
>>> getVals("{10,3,5}") >>> [10.,3.,5.]
Parameters: - val (str) – Value string of geometric variable.
- parmDic (dict) – Parameter dictionary.
Keyword Arguments: - openDelim (str) – Opening delimiter.
- closeDelim (str) – Closing delimiter.
- sep (str) – Seperator between values.
Returns: List of translated values.
Return type: rList (list)
-
pyfrp.modules.pyfrp_gmsh_IO_module.
initBkgdField
(line, domain)¶ Initiates background field when reading a .geo file.
Parameters: - line (str) – Line in geo file.
- domain (pyfrp.modules.pyfrp_gmsh_geometry.domain) – Domain object.
Returns: Updated domain.
Return type:
-
pyfrp.modules.pyfrp_gmsh_IO_module.
initField
(val, domain, Id)¶ Adds the right type of field object to domain.
Parameters: - val (str) – Value string.
- domain (pyfrp.modules.pyfrp_gmsh_geometry.domain) – Domain object.
- Id (int) – Id of new field.
Returns: Updated domain.
Return type:
-
pyfrp.modules.pyfrp_gmsh_IO_module.
isMergeFile
(fn)¶ Checks if geo file is a merge file and returns and returns the meshes used inside the merge file.
Parameters: fn (str) – Path to geo file. Returns: Tuple containing: - isMerge (bool): Flag if corresponding file is merge file.
- mergedFiles (list): List of mesh files used in merge file.
Return type: tuple
-
pyfrp.modules.pyfrp_gmsh_IO_module.
mergeMeshes
(meshFiles, fn, run=True, debug=False, redirect=False, fnStout=None, fnSterr=None, volSizeMax=None)¶ Generates meshfile merging all meshes in meshFiles.
If one of the files that is supposed to be merged is already a merged file, then this function will try to find the original mesh files to write a complete merged file. See also
isMergeFile()
andgenMergeGeoFile()
.If
run==True
is selected, then gmsh will be run viapyfrp.modules.pyfrp_gmsh_module.runGmsh()
and generate the corresponding .msh file of the merged .geo file.Parameters: - meshFiles (list) – List of path to mesh files.
- fn (str) – Name of output .geo file.
Keyword Arguments: - run (bool) – Run gmsh on merged .geo file.
- debug (bool) – Print debugging messages.
- redirect (bool) – Redirect gmsh stout/sterr into seperate files.
- fnStout (str) – File for gmsh stout.
- fnSterr (str) – File for gmsh sterr.
- volSizeMax (float) – Maximum allowed mesh element size.
Returns: Tuple containing:
- fn (str): Path to generated .geo file.
- fnOut (str): Path to generated .msh file.
Return type: tuple
-
pyfrp.modules.pyfrp_gmsh_IO_module.
readFieldLine
(line, domain, parmDic)¶ Reads line that belongs to field definition in .geo file.
If line defines new field, will create new field using
initField()
.Otherwise will try to find field in domain and set new property value.
Parameters: - line (str) – Line to read.
- domain (pyfrp.modules.pyfrp_gmsh_geometry.domain) – Domain object.
- parmDic (dict) – Parameter dictionary.
Returns: Updated domain.
Return type:
-
pyfrp.modules.pyfrp_gmsh_IO_module.
readGeoFile
(fn)¶ Reads in .geo file and tries to extract geometry defined in .geo file into a
pyfrp.modules.pyfrp_gmsh_geometry.domain
.Parameters: fn (str) – Filename of .geo file. Returns: Tuple containing: - parmDic (dict): Updated parameter dictionary.
- domain (pyfrp.modules.pyfrp_gmsh_geometry.domain): Domain object.
Return type: tuple
-
pyfrp.modules.pyfrp_gmsh_IO_module.
readGeoLine
(line, parmDic, domain)¶ Reads in line from .geo file.
Tries to extract type of geometric object and its parameters and uses this to append a geomtric entity to
domain
.If
line
describes a parameter, stores parameter name and its value inparmDic
.Parameters: - line (str) – Line to be splitted.
- parmDic (dict) – Parameter dictionary.
- domain (pyfrp.modules.pyfrp_gmsh_geometry.domain) – Domain object, storing all geometric entities.
Returns: Tuple containing:
- parmDic (dict): Updated parameter dictionary.
- typ (str): Object type type.
- Id (int): ID of object.
- vals (list): Values of object.
- domain (pyfrp.modules.pyfrp_gmsh_geometry.domain): Updated domain object.
Return type: tuple
-
pyfrp.modules.pyfrp_gmsh_IO_module.
readParameter
(line, parmDic)¶ Reads in parameter from line and translates values using
parmDic
.Parameters: - line (str) – Line to be splitted.
- parmDic (dict) – Parameter dictionary.
Returns: Tuple containing:
- var (str): Name of variable.
- val (float): Value of variable
Return type: tuple
-
pyfrp.modules.pyfrp_gmsh_IO_module.
readStlFile
(fn, domain=None, volSizePx=20.0)¶ Reads stl file to domain.
Note
Uses numpy-stl package. You may need to install via
pip install numpy-stl
If no domain is given, will create new one
Parameters: fn (str) – Path to stl file.
Keyword Arguments: - volSizePx (float) – Mesh density assigned at vertices.
- domain (pyfrp.modules.pyfrp_gmsh_geometry.domain) – A domain object.
Returns: A domain object.
Return type:
-
pyfrp.modules.pyfrp_gmsh_IO_module.
removeCommentFromFile
(fn, comment)¶ Removes comment
comment
from .geo file.Note
Will remove all appearances of
comment
.Note
Will also remove comments that only start with
comment
.Parameters: - fn (str) – Filename of .geo file.
- comment (str) – Comment to remove
-
pyfrp.modules.pyfrp_gmsh_IO_module.
removeElementFromFile
(fn, elementType, elementId, delimOpen='(', delimClose=')')¶ Removes element with type
elementType
and IDelementID
from .geo file.Parameters: - fn (str) – Filename of .geo file.
- elementId (int) – ID of element to remove.
- elementType (str) – Type of element to remove.
Keyword Arguments: - delimOpen (str) – Openening delimiter of ID.
- delimClose (str) – Closing delimiter of ID.
-
pyfrp.modules.pyfrp_gmsh_IO_module.
removeTailingLines
(filePath, idx)¶ Removes all empty lines at the end of a .geo file.
Note
Will create temporary file using
tempfile.mkstemp()
. You should have read/write access to whereevermkstemp
is putting files.Parameters: - filePath (str) – Filename of .geo file.
- idx (int) – Index of last non-empty line
-
pyfrp.modules.pyfrp_gmsh_IO_module.
repairDefaultGeoFiles
(debug=False)¶ Copies default geometry files from backup folder to meshfile folder. Useful if geometry files got somehow overwritten or corrupted.
Keyword Arguments: debug (bool) – Print debugging messages. Returns: True
if success,False
otherwise.Return type: bool
-
pyfrp.modules.pyfrp_gmsh_IO_module.
sortKeysByLength
(dic)¶ Sorts dictionary by length of keys.
-
pyfrp.modules.pyfrp_gmsh_IO_module.
splitLine
(line, delim='=', closer=';')¶ Splits line at
delim
, trimmingcloser
.Example:
>>> splitLine("Point(3)={1,3,1};") >>> ("Point(3)","{1,3,1}")
Parameters: line (str) – Line to be splitted.
Keyword Arguments: - delim (str) – Delimiter at which to be splitted.
- closer (str) – Closing character to be trimmed.
Returns: Tuple containing:
- var (str): Name of variable.
- val (str): Value of variable
Return type: tuple
-
pyfrp.modules.pyfrp_gmsh_IO_module.
updateParmGeoFile
(fn, name, val)¶ Updates parameter in .geo file.
Note
Will create temporary file using
tempfile.mkstemp()
. You should have read/write access to whereevermkstemp
is putting files.Parameters: - fn (str) – Filename of .geo file.
- name (str) – Name of parameter.
- val (float) – Value of parameter.
-
pyfrp.modules.pyfrp_gmsh_IO_module.
writeAttractorField
(f, fieldID, NodesList)¶ Writes attractor field into into file.
See also: http://gmsh.info/doc/texinfo/gmsh.html#Specifying-mesh-element-sizes and
:pyfrp.modules.pyfrp_gmsh_geometry.attractorField
.Parameters: - f (file) – Filehandle.
- fieldID (int) – ID of new box field.
- NodesList (list) – List of vertex IDs at which attractor is placed.
Returns: Filehandle.
Return type: file
-
pyfrp.modules.pyfrp_gmsh_IO_module.
writeBackgroundField
(f, fieldID)¶ Writes background field into into file.
Note
Will take finest mesh for background field. See also: http://gmsh.info/doc/texinfo/gmsh.html#Specifying-mesh-element-sizes .
Parameters: - f (file) – Filehandle.
- fieldID (int) – ID of new background field.
Returns: Filehandle.
Return type: file
-
pyfrp.modules.pyfrp_gmsh_IO_module.
writeBoundaryLayerField
(f, fieldID, elements, fieldOpts)¶ Writes boundary layer mesh.
-
pyfrp.modules.pyfrp_gmsh_IO_module.
writeBoxField
(f, fieldID, volSizeIn, volSizeOut, rangeX, rangeY, rangeZ)¶ Writes box field into into file.
See also: http://gmsh.info/doc/texinfo/gmsh.html#Specifying-mesh-element-sizes .
Parameters: - f (file) – Filehandle.
- fieldID (int) – ID of new box field.
- volSizeIn (float) – Mesh element volume inside box.
- volSizeOut (float) – Mesh element volume outside box.
- rangeX (list) – Range of box field in x-direction given as
[minVal,maxVal]
. - rangeY (list) – Range of box field in y-direction given as
[minVal,maxVal]
. - rangeZ (list) – Range of box field in z-direction given as
[minVal,maxVal]
.
Returns: Filehandle.
Return type: file
-
pyfrp.modules.pyfrp_gmsh_IO_module.
writeComment
(f, comment)¶ Writes comment line into file.
Parameters: - f (file) – Filehandle.
- comment (str) – Comment to be written.
Returns: Filehandle.
Return type: file
-
pyfrp.modules.pyfrp_gmsh_IO_module.
writeFieldProp
(f, fieldID, prop, val)¶ Writes field property to file.
Parameters: - f (file) – File to write to.
- fieldID (int) – ID of field.
- prop (str) – Name of property to write.
- val (str) – Value to write.
Returns: Filehandle.
Return type: file
-
pyfrp.modules.pyfrp_gmsh_IO_module.
writeFieldPropByDict
(f, fieldID, dic)¶ Writes dictionary of field properties to file.
Parameters: - f (file) – File to write to.
- fieldID (int) – ID of field.
Keyword Arguments: dic (dict) – Keyword Arguments.
Returns: Filehandle.
Return type: file
-
pyfrp.modules.pyfrp_gmsh_IO_module.
writeMergeLine
(f, fnMsh)¶ Adds merge line to geo file.
Parameters: - f (file) – File handle.
- fnMsh (str) – Mesh file to be added.
Returns: File handle.
Return type: file
-
pyfrp.modules.pyfrp_gmsh_IO_module.
writeMinField
(f, fieldID, ids, charExtendFromBoundary=True)¶ Writes minimum field into into file.
Note
Useful to determine background mesh. It’s often reasonable to take the finest mesh for background field. See also: http://gmsh.info/doc/texinfo/gmsh.html#Specifying-mesh-element-sizes .
Parameters: - f (file) – Filehandle.
- fieldID (int) – ID of new background field.
- ids (list) – List of field IDs used for background mesh computation.
Returns: Filehandle.
Return type: file
-
pyfrp.modules.pyfrp_gmsh_IO_module.
writeThresholdField
(f, fieldID, IField, LcMin, LcMax, DistMin, DistMax)¶ Writes threshold field into into file.
See also: http://gmsh.info/doc/texinfo/gmsh.html#Specifying-mesh-element-sizes . and
:pyfrp.modules.pyfrp_gmsh_geometry.thresholdField
.Parameters: - f (file) – Filehandle.
- fieldID (int) – ID of new box field.
- IField (int) – ID of vertex that is center to threshold field.
- LcMin (float) – Minimum volSize of threshold field.
- LcMax (float) – Maximum volSize of threshold field.
- DistMin (float) – Minimun density of field.
- DistMax (float) – Maximum density of field.
Returns: Filehandle.
Return type: file
pyfrp.modules.pyfrp_gmsh_geometry module¶
PyFRAP module for creating/extracting gmsh geometries for PyFRAP toolbox. Module mainly has the following classes:
- A
domain
class, acting as a canvas.- A
vertex
class, substituting gmsh’s Point.- A
edge
class, parenting all different kind of edges.- A
line
class, substituting gmsh’s Line.- A
arc
class, substituting gmsh’s Circle.- A
bSpline
class, substituting gmsh’s bSpline.- A
lineLoop
class, substituting gmsh’s Line Loop.- A
ruledSurface
class, substituting gmsh’s Ruled Surface.- A
surfaceLoop
class, substituting gmsh’s Surface Loop.- A
volume
class, substituting gmsh’s Volume.- A
field
class, parenting all different kind of fields.- A
attractorField
class, substituting gmsh’s Attractor field.- A
boundaryLayerField
class, substituting gmsh’s Boundary Layer field.- A
thresholdField
class, substituting gmsh’s Threshold field.- A
minField
class, substituting gmsh’s Min field.
This module together with pyfrp.pyfrp_gmsh_IO_module and pyfrp.pyfrp_gmsh_module works partially as a python gmsh wrapper, however is incomplete. If you want to know more about gmsh, go to http://gmsh.info/doc/texinfo/gmsh.html .
-
class
pyfrp.modules.pyfrp_gmsh_geometry.
arc
(domain, vstart, vcenter, vend, Id)¶ Bases:
pyfrp.modules.pyfrp_gmsh_geometry.edge
Arc class storing information from gmsh .geo cicle.
Will compute
angleOffset
,angle
andpOffset
on creation.Parameters: - domain (pyfrp.modules.pyfrp_gmsh_geometry.domain) – Domain arc belongs to.
- vstart (pyfrp.modules.pyfrp_gmsh_geometry.vertex) – Start vertex.
- vcenter (pyfrp.modules.pyfrp_gmsh_geometry.vertex) – Center vertex.
- vend (pyfrp.modules.pyfrp_gmsh_geometry.vertex) – End vertex.
- Id (int) – ID of arc.
-
computeAngle
()¶ Computes and returns angle of arc.
-
computeAngleOffset
()¶ Computes and returns offset angle of arc.
-
computePOffset
()¶ Computes and returns offset point of arc.
-
computeRadius
()¶ Computes and returns radius of arc.
Returns: Radius of arc. Return type: float
-
draw
(ax=None, color=None, ann=None, backend='mpl', render=False, drawVertices=True)¶ Draws arc.
There are two different backends for drawing, namely
- Matplotlib (
backend='mpl'
) - VTK (
backend='vtk'
)
Matplotlib is easier to handle, but slower. VTK is faster for complex geometries.
Note
If
backend=mpl
,ax
should be amatplotlib.axes
, ifbackend='vtk'
,ax
should be avtk.vtkRenderer
object.Note
If no axes is given, will create new one, see also
pyfrp.modules.pyfrp_plot_module.makeGeometryPlot()
orpyfrp.modules.pyfrp_vtk_module.makeVTKCanvas()
.Warning
Annotations are not properly working with
backend='vtk'
.Keyword Arguments: - ax (matplotlib.axes) – Matplotlib axes to be plotted in.
- color (str) – Color of line.
- ann (bool) – Show annotations.
- render (bool) – Render in the end (only in vtk mode).
- drawVertices (bool) – Also draw vertices.
Returns: Updated axes.
Return type: matplotlib.axes
- Matplotlib (
-
drawMPL
(ax=None, color=None, ann=None, render=False)¶ Draws arc into matplotlib axes.
Note
If
ann=None
, will setann=False
.Note
If no axes is given, will create new one, see also
pyfrp.modules.pyfrp_plot_module.makeGeometryPlot()
.Keyword Arguments: - ax (matplotlib.axes) – Matplotlib axes to be plotted in.
- color (str) – Color of line.
- ann (bool) – Show annotations.
Returns: Axes.
Return type: matplotlib.axes
-
drawVTK
(ax=None, color=None, ann=None, render=False)¶ Draws arc into VTK renderer.
Note
If
ann=None
, will setann=False
.Note
If no axes is given, will create new
vtkRenderer
, see alsopyfrp.modules.pyfrp_vtk_module.makeVTKCanvas()
.See also
pyfrp.modules.pyfrp_vtk_module.drawVTKArc()
.Keyword Arguments: - ax (vtk.vtkRenderer) – Renderer to draw in.
- color (str) – Color of line.
- ann (bool) – Show annotations.
- render (bool) – Render in the end.
Returns: Updated renderer.
Return type: vtk.vtkRenderer
-
getAngle
()¶ Returns angle of arc.
-
getAngleOffset
()¶ Returns offset angle of arc.
-
getFirstVertex
(orientation)¶ Returns first vertex of arc given a orientation.
Orientation can be either forward (1), or reverse (-1).
Parameters: orientation (int) – Orientation of arc. Returns: Vertex. Return type: pyfrp.pyfrp_gmsh_geometry.vertex
-
getLastVertex
(orientation)¶ Returns last vertex of arc given a orientation.
Orientation can be either forward (1), or reverse (-1).
Parameters: orientation (int) – Orientation of arc. Returns: Vertex. Return type: pyfrp.pyfrp_gmsh_geometry.vertex
-
getNormVec
()¶ Computes and returns vectors normal to arc.
Returns: Tuple containing: - v1n (numpy.ndarray): Normal vector to
vstart-vcenter
. - v2n (numpy.ndarray): Normal vector to
vend-vcenter
.
Return type: tuple - v1n (numpy.ndarray): Normal vector to
-
getPlotVec
()¶ Returns vectors for plotting arc.
Returns: Tuple containing: - x (numpy.ndarray): x-array.
- y (numpy.ndarray): y-array.
- z (numpy.ndarray): z-array.
Return type: tuple
-
getPointOnArc
(a)¶ Returns point on arc at angle
a
.Returns: Tuple containing: - x (float): x-coordinate.
- y (float): y-coordinate.
- z (float): z-coordinate.
Return type: tuple
-
getRadius
()¶ Returns radius of arc.
-
getSubElements
()¶ Returns all elements that define this element.
Returns: List of elements. Return type: list
-
getVcenter
()¶ Returns center vertex of arc.
-
getVend
()¶ Returns end vertex of arc.
-
getVstart
()¶ Returns start vertex of arc.
-
getXcenter
()¶ Returns center coordinate of arc.
-
getXend
()¶ Returns end coordinate of arc.
-
getXstart
()¶ Returns start coordinate of arc.
-
inArc
(x, debug=False)¶ Tells if coordinate
x
is on arc or not.Returns: True
if on arc,False
otherwise.Return type: bool
-
writeToFile
(f)¶ Writes arc to file.
Parameters: f (file) – File to write to. Returns: File. Return type: file
-
class
pyfrp.modules.pyfrp_gmsh_geometry.
attractorField
(domain, Id, NodesList=[])¶ Bases:
pyfrp.modules.pyfrp_gmsh_geometry.field
Attractor field class storing information from gmsh .geo.
Subclasses from
field
.Parameters: - domain (pyfrp.modules.pyfrp_gmsh_geometry.domain) – Domain surface belongs to.
- Id (int) – ID of field.
Keyword Arguments: NodesList (list) – List of IDs of the Nodes that attractor field centers around.
-
addNodeByID
(ID)¶ Adds vertex object to NodesList given the ID of the vertex.
Parameters: ID (int) – ID of vertex to be added. Returns: Updated NodesList. Return type: list
-
getSubElements
()¶ Returns all elements that define this element.
Returns: List of elements. Return type: list
-
includedInThresholdField
()¶ Returns all the threshholdFields where attractorField is included in.
Returns: List of threshholdField objects. Return type: list
-
initNodesList
(NodesList)¶ Adds a list of vertices to NodesList.
See also
addNodeByID()
.Parameters: NodesList (list) – List of vertex IDs. Returns: Updated NodesList. Return type: list
-
setFieldAttr
(name, val)¶ Sets field attribute.
Note
Value can have any data type.
Parameters: - name (str) – Name of attribute.
- val (float) – Value of attribute.
-
writeToFile
(f)¶ Writes attractor field to file.
See also
pyfrp.modules.pyfrp_gmsh_IO_module.writeAttractorField()
.Parameters: f (file) – File to write to. Returns: File. Return type: file
-
class
pyfrp.modules.pyfrp_gmsh_geometry.
bSpline
(domain, vertices, Id)¶ Bases:
pyfrp.modules.pyfrp_gmsh_geometry.edge
Bspline class storing information from gmsh .geo BSpline.
Parameters: - domain (pyfrp.modules.pyfrp_gmsh_geometry.domain) – Domain arc belongs to.
- vertices (list) – List of vertex objects.
- Id (int) – ID of spline.
-
draw
(ax=None, color=None, ann=None, backend='mpl', render=False, drawVertices=False)¶ Draws spline.
There are two different backends for drawing, namely
- Matplotlib (
backend='mpl'
) - VTK (
backend='vtk'
)
Matplotlib is easier to handle, but slower. VTK is faster for complex geometries.
Note
If
backend=mpl
,ax
should be amatplotlib.axes
, ifbackend='vtk'
,ax
should be avtk.vtkRenderer
object.Note
If no axes is given, will create new one, see also
pyfrp.modules.pyfrp_plot_module.makeGeometryPlot()
orpyfrp.modules.pyfrp_vtk_module.makeVTKCanvas()
.Warning
Annotations are not properly working with
backend='vtk'
.Keyword Arguments: - ax (matplotlib.axes) – Matplotlib axes to be plotted in.
- color (str) – Color of line.
- ann (bool) – Show annotations.
- render (bool) – Render in the end (only in vtk mode).
- drawVertices (bool) – Also draw vertices.
Returns: Updated axes.
Return type: matplotlib.axes
- Matplotlib (
-
drawMPL
(ax=None, color=None, ann=None)¶ Draws spline into matplotlib axes.
Note
If
ann=None
, will setann=False
.Note
If no axes is given, will create new one, see also
pyfrp.modules.pyfrp_plot_module.makeGeometryPlot()
.Keyword Arguments: - ax (matplotlib.axes) – Matplotlib axes to be plotted in.
- color (str) – Color of line.
- ann (bool) – Show annotations.
Returns: Axes.
Return type: matplotlib.axes
-
drawVTK
(ax=None, color=None, ann=None, render=False)¶ Draws spline into VTK renderer.
Note
If
ann=None
, will setann=False
.Note
If no axes is given, will create new
vtkRenderer
, see alsopyfrp.modules.pyfrp_vtk_module.makeVTKCanvas()
.See also
pyfrp.modules.pyfrp_vtk_module.drawVTKLine()
.Keyword Arguments: - ax (vtk.vtkRenderer) – Renderer to draw in.
- color (str) – Color of line.
- ann (bool) – Show annotations.
- render (bool) – Render in the end.
Returns: Updated renderer.
Return type: vtk.vtkRenderer
-
getFirstVertex
(orientation)¶ Returns first vertex of arc given a orientation.
Orientation can be either forward (1), or reverse (-1).
Parameters: orientation (int) – Orientation of arc. Returns: Vertex. Return type: pyfrp.pyfrp_gmsh_geometry.vertex
-
getLastVertex
(orientation)¶ Returns last vertex of arc given a orientation.
Orientation can be either forward (1), or reverse (-1).
Parameters: orientation (int) – Orientation of arc. Returns: Vertex. Return type: pyfrp.pyfrp_gmsh_geometry.vertex
-
getMiddle
()¶ Returns midpoint of bSpline.
Midpoint in this case is defined as the coordinate of the mid vertex.
Returns: Midpoint. Return type: numpy.ndarray
-
getSubElements
()¶ Returns all elements that define this element.
Returns: List of elements. Return type: list
-
initVertices
(vertices)¶ Initiates list of vertices.
If vertex is given by Id, will use
pyfrp.modules.pyfrp_gmsh_geometry.getVertexById()
to identify vertex.Parameters: vertices (list) – List of vertex objects. Returns: List of vertex objects. Return type: list
-
writeToFile
(f)¶ Writes bSpline to file.
Parameters: f (file) – File to write to. Returns: File. Return type: file
-
class
pyfrp.modules.pyfrp_gmsh_geometry.
boundaryLayerField
(domain, Id, AnisoMax=10000000000, hwall_n=1.0, hwall_t=1, ratio=1.1, thickness=10.0, hfar=1.0, IntersectMetrics=1, Quads=0.0)¶ Bases:
pyfrp.modules.pyfrp_gmsh_geometry.field
Boundary Layer field class storing information from gmsh .geo.
Creates boundary layer mesh around vertices, edges or surfacesin geometry. Boundary layer density is given by
\[h_{wall} * ratio^{(dist/h_{wall})}.\]Subclasses from
field
.Example: Adding a box surrounded with a boundary layer to a geometry:
>>> vertices,lines,loops,surfaces,sloops,vols=d.addCuboidByParameters([256-50,256-50,-160],100,100,120,10,genVol=False)
Adjust volSize:
>>> d.setGlobalVolSize(30.)
Add boundary layer:
>>> volSizeLayer=10. >>> blf=d.addBoundaryLayerField(hfar=volSizeLayer,hwall_n=volSizeLayer,hwall_t=volSizeLayer,thickness=30.,Quads=0.) >>> blf.addFaceListByID(pyfrp_misc_module.objAttrToList(surfaces,'Id')) >>> blf.setAsBkgdField() >>> d.draw()
Write to file:
>>> d.writeToFile("dome_boundary.geo")
Generate mesh:
>>> fnMesh=pyfrp_gmsh_module.runGmsh("dome_boundary.geo") >>> m=pyfrp_mesh.mesh(None) >>> m.setFnMesh(fnMesh) >>> m.plotMesh()
See also http://gmsh.info/doc/texinfo/gmsh.html#Specifying-mesh-element-sizes .
Parameters: - domain (pyfrp.modules.pyfrp_gmsh_geometry.domain) – Domain surface belongs to.
- Id (int) – ID of field.
Keyword Arguments: - AnisoMax (float) – Threshold angle for creating a mesh fan in the boundary layer.
- IntersectMetrics (int) – Intersect metrics of all faces.
- Quad (int) – Generate recombined elements in the boundary layer.
- har (float) – Element size far from the wall.
- hwall_n (float) – Mesh Size Normal to the The Wall.
- hwall_t (float) – Mesh Size Tangent to the Wall.
- ratio (float) – Size Ratio Between Two Successive Layers.
- thickness (float) – Maximal thickness of the boundary layer.
- List (list) – List of field IDs.
-
addEdgeByID
(ID)¶ Adds edge object to EdgesList given the ID of the edge.
Parameters: ID (int) – ID of edge to be added. Returns: Updated EgesList. Return type: list
-
addEdgeListByID
(IDs)¶ Adds a list of edge objects to EdgesList given the ID of the edges.
Parameters: IDs (list) – List of IDs of edges to be added. Returns: Updated EgesList. Return type: list
-
addFaceByID
(ID)¶ Adds surface object to FacesList given the ID of the surface.
Parameters: ID (int) – ID of surface to be added. Returns: Updated FacesList. Return type: list
-
addFaceListByID
(IDs)¶ Adds a list of surfaces objects to FacesList given the ID of the surfaces.
Parameters: IDs (list) – List of IDs of surfaces to be added. Returns: Updated FacesList. Return type: list
-
addNodeByID
(ID)¶ Adds vertex object to NodesList given the ID of the vertex.
Parameters: ID (int) – ID of vertex to be added. Returns: Updated NodesList. Return type: list
-
addNodeListByID
(IDs)¶ Adds a list of vertex objects to NodesList given the ID of the vertex.
Parameters: IDs (list) – List of IDs of vertices to be added. Returns: Updated NodesList. Return type: list
-
buildElementDict
()¶ Builds element dictionary for writing to file.
-
getSubElements
()¶ Returns all elements that define this element.
Returns: List of elements. Return type: list
-
setFieldAttr
(name, val)¶ Sets field attribute.
Note
Value can have any data type.
Parameters: - name (str) – Name of attribute.
- val (float) – Value of attribute.
-
writeToFile
(f)¶ Writes boundaryLayerField to file.
See also
pyfrp.modules.pyfrp_gmsh_IO_module.writeBoundaryLayerField()
.Parameters: f (file) – File to write to. Returns: File. Return type: file
-
class
pyfrp.modules.pyfrp_gmsh_geometry.
boxField
(domain, Id, volSizeIn=10.0, volSizeOut=20.0, xRange=[], yRange=[], zRange=[])¶ Bases:
pyfrp.modules.pyfrp_gmsh_geometry.field
Box field class storing information from gmsh .geo.
Subclasses from
field
.Parameters: - domain (pyfrp.modules.pyfrp_gmsh_geometry.domain) – Domain surface belongs to.
- Id (int) – ID of field.
Keyword Arguments: - volSizeIn (float) – Mesh element volume inside box.
- volSizeOut (float) – Mesh element volume outside box.
- xRange (list) – Range of box field in x-direction given as
[minVal,maxVal]
. - yRange (list) – Range of box field in y-direction given as
[minVal,maxVal]
. - zRange (list) – Range of box field in z-direction given as
[minVal,maxVal]
.
-
getSubElements
()¶ Returns all elements that define this element.
Returns: List of elements. Return type: list
-
initBox
(xRange, yRange, zRange)¶ Initializes bounding box.
-
setRange
(coord, vec)¶ Sets the bounding box range along a given axis.
Parameters: - coord (str) – Axis along range is set (
"X","Y","Z"
) - vec (list) – Range of box
[minVal,maxVal]
Returns: Tuple containing:
- coordMin (float): New minimum value.
- coordMax (float): New maximum value.
Return type: tuple
- coord (str) – Axis along range is set (
-
writeToFile
(f)¶ Writes box field to file.
See also
pyfrp.modules.pyfrp_gmsh_IO_module.writeBoxField()
.Parameters: f (file) – File to write to. Returns: File. Return type: file
-
class
pyfrp.modules.pyfrp_gmsh_geometry.
domain
¶ Domain class storing embryo geometry entities.
Parameters: - edges (list) – List of edges.
- vertices (list) – List of vertices.
- arcs (list) – List of arcs.
- lines (list) – List of lines.
- bSplines (list) – List of bSplines.
- lineLoops (list) – List of lineLoops.
- surfaceLoops (list) – List of surfaceLoops.
- ruledSurfaces (list) – List of ruledSurfaces.
- volumes (list) – List of volumes.
- fields (list) – List of fields.
- annXOffset (float) – Offset of annotations in x-direction.
- annYOffset (float) – Offset of annotations in y-direction.
- annZOffset (float) – Offset of annotations in z-direction.
-
addAllSurfacesToLoop
()¶ Adds all surfaces in domain to a single surfaceLoop.
Returns: New surfaceLoop instance. Return type: pyfrp.modules.pyfrp_gmsh_geometry.surfaceLoop
-
addArc
(vstart, vcenter, vend, Id=None)¶ Adds new
pyfrp.modules.pyfrp_gmsh_geometry.arc
instance at pointx
and appends it toedges
andarcs
list.Parameters: - vstart (pyfrp.modules.pyfrp_gmsh_geometry.vertex) – Start vertex.
- vcenter (pyfrp.modules.pyfrp_gmsh_geometry.vertex) – Center vertex.
- vend (pyfrp.modules.pyfrp_gmsh_geometry.vertex) – End vertex.
Keyword Arguments: Id (int) – ID of arc.
Returns: New line instance.
Return type:
-
addAttractorField
(Id=None, NodesList=[])¶ Adds new
pyfrp.modules.pyfrp_gmsh_geometry.attractorField
instance.Keyword Arguments: - Id (int) – ID of field.
- NodesList (list) – List of IDs of the Nodes that attractor field centers around.
Returns: New attractorField instance.
Return type:
-
addBSpline
(vertices, Id=None)¶ Adds new
pyfrp.modules.pyfrp_gmsh_geometry.line
instance at pointx
and appends it toedges
andlines
list.Parameters: vertices (list) – List of vertex objects. Keyword Arguments: Id (int) – ID of spline. Returns: New spline instance. Return type: pyfrp.modules.pyfrp_gmsh_geometry.bSpline
-
addBoundaryLayerField
(Id=None, AnisoMax=10000000000, hwall_n=1.0, hwall_t=1, ratio=1.1, thickness=10.0, hfar=1.0, IntersectMetrics=1, Quads=0.0)¶ Adds new
pyfrp.modules.pyfrp_gmsh_geometry.boundaryLayerField
instance.Keyword Arguments: - Id (int) – ID of field.
- AnisoMax (float) – Threshold angle for creating a mesh fan in the boundary layer.
- IntersectMetrics (int) – Intersect metrics of all faces.
- Quad (int) – Generate recombined elements in the boundary layer.
- har (float) – Element size far from the wall.
- hwall_n (float) – Mesh Size Normal to the The Wall.
- hwall_t (float) – Mesh Size Tangent to the Wall.
- ratio (float) – Size Ratio Between Two Successive Layers.
- thickness (float) – Maximal thickness of the boundary layer.
- List (list) – List of field IDs.
Returns: New boundaryLayerField instance.
Return type:
-
addBoxField
(Id=None, volSizeIn=10.0, volSizeOut=20.0, xRange=[], yRange=[], zRange=[])¶ Adds new
pyfrp.modules.pyfrp_gmsh_geometry.boxField
instance.Keyword Arguments: - Id (int) – ID of field.
- volSizeIn (float) – Mesh element volume inside box.
- volSizeOut (float) – Mesh element volume outside box.
- xRange (list) – Range of box field in x-direction given as
[minVal,maxVal]
. - yRange (list) – Range of box field in y-direction given as
[minVal,maxVal]
. - zRange (list) – Range of box field in z-direction given as
[minVal,maxVal]
.
Returns: New boxField instance.
Return type:
-
addCircleByParameters
(center, radius, z, volSize, plane='z', genLoop=False, genSurface=False)¶ Adds circle to domain by given center and radius.
Will create 5 new
pyfrp.modules.pyfrp_gmsh_geometry.vertex
objects[vcenter,v1,v2,v3,v4]
and four new pyfrp.modules.pyfrp_gmsh_geometry.arc objects [a1,a2,a3,a4] and builds circle.Circle will be at
z=z
and vertices will have mesh sizevolSize
.For example:
>>> d=pyfrp_gmsh_geometry.domain() >>> d.addCircleByParameters([256,256],100,50,30.) >>> d.addCircleByParameters([256,256],100,50,30.,plane="x") >>> d.addCircleByParameters([256,256],100,50,30.,plane="y") >>> d.draw()
will generate:
Note
Plane can be given as
"x","y","z"
. See alsopyfrp.modules.pyfrp_geometry_module.flipCoordinate()
.Parameters: - center (numpy.ndarray) – Center of circle.
- radius (float) – Radius of the circle.
- z (float) – Height at which circle is placed.
- volSize (float) – Mesh size of vertices.
Keyword Arguments: - plane (str) – Plane in which circle is placed.
- genLoop (bool) – Create lineLoop.
- genSurface (bool) – Create ruledSurface.
Returns: Tuple containing:
- vertices (list): List of vertices.
- arcs (list): List of arcs.
- loop (pyfrp.modules.pyfrp_gmsh_geometry.lineLoop): Line loop.
- surface (pyfrp.modules.pyfrp_gmsh_geometry.ruledSurface): Ruled Surface.
Return type: tuple
-
addCuboidByParameters
(offset, sidelengthX, sidelengthY, height, volSize, plane='z', genLoops=True, genSurfaces=True, genVol=True)¶ Adds Cuboid to domain by given offset, sidelengths in x- and y-direction and height.
Will define vertices and then call
pyfrp.modules.pyfrp_gmsh_geometry.domain.addPrismByParameters()
.Note
Plane can be given as
"x","y","z"
. See alsopyfrp.modules.pyfrp_geometry_module.flipCoordinate()
.For example:
>>> d=pyfrp_gmsh_geometry.domain()
>>> d.draw()
will generate:
Parameters: - offset (numpy.ndarray) – Offset of cuboid.
- sidelengthX (float) – Sidelength in x-direction.
- sidelengthY (float) – Sidelength in y-direction.
- height (float) – Height of cuboid.
- volSize (float) – Mesh size of vertices.
Keyword Arguments: - plane (str) – Plane in which prism is placed.
- genLoops (bool) – Generate line loops.
- genSurfaces (bool) – Generate surfaces.
- genVol (bool) – Generate surface loop and corresponding volume.
Returns: Tuple containing:
- vertices (list): List of vertices.
- lines (list): List of lines.
- loops (list): List of loops.
- surfaces (list): List of surfaces.
- surfaceLoop (pyfrp.modules.pyfrp_gmsh_geometry.surfaceLoop): Generated surface loop.
- vol (pyfrp.modules.pyfrp_gmsh_geometry.volume): Generated volume.
Return type: tuple
-
addCylinderByParameters
(center, radius, z, height, volSize, plane='z', genLoops=True, genSurfaces=True, genVol=True)¶ Adds cylinder to domain by given center and radius and height.
Will create.
- 2 new circles at
z=z
andz=z+height
, seepyfrp.modules.pyfrp_gmsh_geometry.domain.addCircleByParameters()
. - 4
pyfrp.modules.pyfrp_gmsh_geometry.line
objects connecting the two circles.
If selected, will create:
- 6
pyfrp.modules.pyfrp_gmsh_geometry.lineLoop
objects around the 6 surfaces. - 6 corresponding
pyfrp.modules.pyfrp_gmsh_geometry.ruledSurface
objects. - 1
pyfrp.modules.pyfrp_gmsh_geometry.surfaceLoop
. - 1 corresponding
pyfrp.modules.pyfrp_gmsh_geometry.volume
.
For example:
>>> d=pyfrp_gmsh_geometry.domain() >>> d.addCylinderByParameters([256,256],100,50,100,30.,plane="z",genLoops=True,genSurfaces=True,genVol=True) >>> d.draw()
would return:
Note
Plane can be given as
"x","y","z"
. See alsopyfrp.modules.pyfrp_geometry_module.flipCoordinate()
.Parameters: - center (numpy.ndarray) – Center of cylinder.
- radius (float) – Radius of the cylinder.
- z (float) – Height at which cylinder is placed.
- height (float) – Height of cylinder.
- volSize (float) – Mesh size of vertices.
Keyword Arguments: - plane (str) – Plane in which cylinder is placed.
- genLoops (bool) – Generate line loops.
- genSurfaces (bool) – Generate surfaces.
- genVol (bool) – Generate surface loop and corresponding volume.
Returns: Tuple containing:
- vertices (list): List of vertices.
- arcs (list): List of arcs.
- lines (list): List of lines.
- loops (list): List of loops.
- surfaces (list): List of surfaces.
- surfaceLoop (pyfrp.modules.pyfrp_gmsh_geometry.surfaceLoop): Generated surface loop.
- vol (pyfrp.modules.pyfrp_gmsh_geometry.volume): Generated volume.
Return type: tuple
- 2 new circles at
-
addEnclosingVolume
()¶ Adds volume enclosing all surfaces.
See also
addAllSurfacesToLoop()
.Returns: New volume instance. Return type: pyfrp.modules.pyfrp_gmsh_geometry.volume
-
addLine
(v1, v2, Id=None)¶ Adds new
pyfrp.modules.pyfrp_gmsh_geometry.line
instance at pointx
and appends it toedges
andlines
list.Parameters: - v1 (pyfrp.modules.pyfrp_gmsh_geometry.vertex) – Start vertex.
- v2 (pyfrp.modules.pyfrp_gmsh_geometry.vertex) – End vertex.
Keyword Arguments: Id (int) – ID of line.
Returns: New line instance.
Return type:
-
addLineLoop
(Id=None, edgeIDs=[])¶ Adds new
pyfrp.modules.pyfrp_gmsh_geometry.lineLoop
instance with given edgeIDs.Keyword Arguments: edgeIDs (list) – List of edge IDs included in line loop. Returns: New lineLoop instance. Return type: pyfrp.modules.pyfrp_gmsh_geometry.lineLoop
-
addMinField
(Id=None, FieldsList=[])¶ Adds new
pyfrp.modules.pyfrp_gmsh_geometry.minField
instance.Keyword Arguments: - Id (int) – ID of field.
- NodesList (list) – List of IDs of the Nodes that attractor field centers around.
Returns: New attractorField instance.
Return type:
-
addPolygonByParameters
(coords, volSize, z=0.0, plane='z')¶ Adds polygon to domain by given vertex coordinates.
Will create a list of new
pyfrp.modules.pyfrp_gmsh_geometry.vertex
objects and a list of new pyfrp.modules.pyfrp_gmsh_geometry.line objects connecting the vertices.Note
Plane can be given as
"x","y","z"
. See alsopyfrp.modules.pyfrp_geometry_module.flipCoordinate()
.Note
Vertices can be given either as a
- list of coordinate triples
[[x1,y1,z1],[x2,y2,z2],...]
. - list of x-y-coordinates and a given z-coordinate
[[x1,y1,z],[x2,y2,z],...]
.
For example:
>>> d=pyfrp_gmsh_geometry.domain() >>> d.addPolygonByParameters([[100,100,100],[200,200,100],[200,100,100]],30.) >>> d.addPolygonByParameters([[100,100,100],[200,200,100],[200,100,100]],30.,plane="x") >>> d.addPolygonByParameters([[100,100,100],[200,200,100],[200,100,100]],30.,plane="y") >>> d.draw()
will generate:
Note
Vertices are created in the order of the coordinates and connected in the same order.
Parameters: - coords (list) – List of coordinates.
- volSize (float) – Mesh size of vertices.
Keyword Arguments: - plane (str) – Plane in which polygon is placed.
- z (float) – Height at which polygon is placed.
- genLoop (bool) – Create lineLoop.
- genSurface (bool) – Create ruledSurface.
Returns: Tuple containing:
- vertices (list): List of vertices.
- lines (list): List of connecting lines.
- loop (pyfrp.modules.pyfrp_gmsh_geometry.lineLoop): Line loop.
- surface (pyfrp.modules.pyfrp_gmsh_geometry.ruledSurface): Ruled Surface.
Return type: tuple
- list of coordinate triples
-
addPrismByParameters
(coords, volSize, height=1.0, z=0.0, plane='z', genLoops=True, genSurfaces=True, genVol=True)¶ Adds prism to domain by given vertex coordinates.
Will create:
- 2 new polygons, see
pyfrp.modules.pyfrp_gmsh_geometry.domain.addPolygonByParameters()
. - n
pyfrp.modules.pyfrp_gmsh_geometry.line
objects connecting the two polyogns.
If selected, will create:
- n+2
pyfrp.modules.pyfrp_gmsh_geometry.lineLoop
objects around the 6 surfaces. - n+2 corresponding
pyfrp.modules.pyfrp_gmsh_geometry.ruledSurface
objects. - 1
pyfrp.modules.pyfrp_gmsh_geometry.surfaceLoop
. - 1 corresponding
pyfrp.modules.pyfrp_gmsh_geometry.volume
.
Note
Plane can be given as
"x","y","z"
. See alsopyfrp.modules.pyfrp_geometry_module.flipCoordinate()
.Note
Vertices can be given either as a
- list of coordinate triples
[[x1,y1,z1],[x2,y2,z2],...]
. Then the list of vertices needs to be of length \(2n\), where where \(n\) is the number of corners of the top and lower polygon. OtherwiseaddPrismByParameters()
will crash. - list of x-y-coordinates, a given z-coordinate and height. This will place the vertices at
[[x1,y1,z],[x2,y2,z],...]
and[[x1,y1,z+height],[x2,y2,z+height],...]
.
For example:
>>> d=pyfrp_gmsh_geometry.domain() >>> d.addPrismByParameters([[256,256],[200,220],[200,200],[210,210],[220,200]],30.,z=50.,height=40.,plane="z",genLoops=True,genSurfaces=True,genVol=True) >>> d.draw()
will generate:
Note
Vertices are created in the order of the coordinates and connected in the same order.
Parameters: - coords (list) – List of coordinates.
- volSize (float) – Mesh size of vertices.
Keyword Arguments: - plane (str) – Plane in which prism is placed.
- z (float) – Height at which first polygon is placed.
- height (float) – Height of prism.
- genLoops (bool) – Generate line loops.
- genSurfaces (bool) – Generate surfaces.
- genVol (bool) – Generate surface loop and corresponding volume.
Returns: Tuple containing:
- vertices (list): List of vertices.
- lines (list): List of lines.
- loops (list): List of loops.
- surfaces (list): List of surfaces.
- surfaceLoop (pyfrp.modules.pyfrp_gmsh_geometry.surfaceLoop): Generated surface loop.
- vol (pyfrp.modules.pyfrp_gmsh_geometry.volume): Generated volume.
Return type: tuple
- 2 new polygons, see
-
addRectangleByParameters
(offset, sidelengthX, sidelengthY, z, volSize, plane='z')¶ Adds rectangle to domain by given offset and sidelengths.
Will create a list of four
pyfrp.modules.pyfrp_gmsh_geometry.vertex
objects and a list of four pyfrp.modules.pyfrp_gmsh_geometry.line objects connecting the vertices.Note
Plane can be given as
"x","y","z"
. See alsopyfrp.modules.pyfrp_geometry_module.flipCoordinate()
.Note
The
offset
is defined as the bottom left corner.For example:
>>> d=pyfrp_gmsh_geometry.domain() >>> d.addRectangleByParameters([256,256],100,200,50,30.) >>> d.addRectangleByParameters([256,256],100,200,50,30.,plane="x") >>> d.addRectangleByParameters([256,256],100,200,50,30.,plane="y") >>> d.draw()
will generate:
Parameters: - offset (numpy.ndarray) – Offset of rectangle.
- sidelengthX (float) – Sidelength in x-direction.
- sidelengthY (float) – Sidelength in y-direction.
- z (float) – Height at which rectangle is placed.
- volSize (float) – Mesh size of vertices.
Keyword Arguments: - plane (str) – Plane in which rectangle is placed.
- genLoop (bool) – Create lineLoop.
- genSurface (bool) – Create ruledSurface.
Returns: Tuple containing:
- vertices (list): List of vertices.
- lines (list): List of connecting lines.
- loop (pyfrp.modules.pyfrp_gmsh_geometry.lineLoop): Line loop.
- surface (pyfrp.modules.pyfrp_gmsh_geometry.ruledSurface): Ruled Surface.
Return type: tuple
-
addRuledSurface
(Id=None, lineLoopID=None)¶ Adds new
pyfrp.modules.pyfrp_gmsh_geometry.ruledSurface
instance with given lineLoop.Keyword Arguments: lineLoopID (ID) – ID of line loop. Returns: New ruledSurface instance. Return type: pyfrp.modules.pyfrp_gmsh_geometry.ruledSurface
-
addSquareByParameters
(offset, sidelength, z, volSize, plane='z')¶ Adds square to domain by given offset and sidelength.
Will create a list of four
pyfrp.modules.pyfrp_gmsh_geometry.vertex
objects and a list of four pyfrp.modules.pyfrp_gmsh_geometry.line objects connecting the vertices.Note
Plane can be given as
"x","y","z"
. See alsopyfrp.modules.pyfrp_geometry_module.flipCoordinate()
.Note
The
offset
is defined as the bottom left corner.For example:
>>> d=pyfrp_gmsh_geometry.domain() >>> d.addSquareByParameters([256,256],100,50,30.) >>> d.addSquareByParameters([256,256],100,50,30.,plane="x") >>> d.addSquareByParameters([256,256],100,50,30.,plane="y") >>> d.draw()
will generate:
Parameters: - offset (numpy.ndarray) – Offset of square.
- sidelength (float) – Sidelength of square.
- z (float) – Height at which square is placed.
- volSize (float) – Mesh size of vertices.
Keyword Arguments: - plane (str) – Plane in which square is placed.
- genLoop (bool) – Create lineLoop.
- genSurface (bool) – Create ruledSurface.
Returns: Tuple containing:
- vertices (list): List of vertices.
- lines (list): List of connecting lines.
- loop (pyfrp.modules.pyfrp_gmsh_geometry.lineLoop): Line loop.
- surface (pyfrp.modules.pyfrp_gmsh_geometry.ruledSurface): Ruled Surface.
Return type: tuple
-
addSurfaceLoop
(Id=None, surfaceIDs=[])¶ Adds new
pyfrp.modules.pyfrp_gmsh_geometry.surfaceLoop
instance with given surfaceIDs.Keyword Arguments: surfaceIDs (list) – List of surface IDs included in surface loop. Returns: New surfaceLoop instance. Return type: pyfrp.modules.pyfrp_gmsh_geometry.surfaceLoop
-
addThresholdField
(Id=None, IField=None, LcMin=5.0, LcMax=20.0, DistMin=30.0, DistMax=60.0)¶ Adds new
pyfrp.modules.pyfrp_gmsh_geometry.thresholdField
instance.Keyword Arguments: - Id (int) – ID of field.
- IField (int) – ID of vertex that is center to threshold field.
- LcMin (float) – Minimum volSize of threshold field.
- LcMax (float) – Maximum volSize of threshold field.
- DistMin (float) – Minimun density of field.
- DistMax (float) – Maximum density of field.
Returns: New thresholdField instance.
Return type:
-
addVertex
(x, Id=None, volSize=None)¶ Adds new
pyfrp.modules.pyfrp_gmsh_geometry.vertex
instance at pointx
and appends it tovertices
list.Note
volSize
does not have any effect on the geometry itself but is simply stored in the vertex object for further usage.Parameters: x (numpy.ndarray) – Coordinate of vertex.
Keyword Arguments: - Id (int) – ID of vertex.
- volSize (float) – Element size at vertex.
Returns: New vertex instance.
Return type:
-
addVolume
(Id=None, surfaceLoopID=None)¶ Adds new
pyfrp.modules.pyfrp_gmsh_geometry.volume
instance with given surfaceLoop.Keyword Arguments: surfaceLoopID (ID) – ID of surface loop. Returns: New volume instance. Return type: pyfrp.modules.pyfrp_gmsh_geometry.volume
-
checkIdExists
(Id, objList, debug=False)¶ Checks if any object in
objList
already has IDId
.Parameters: - Id (int) – ID to be checked.
- objList (list) – List of objects, for example
edges
.
Keyword Arguments: debug (bool) – Print debugging output.
Returns: True if any object has ID
Id
.Return type: bool
-
cleanUpUnusedEdges
(debug=False)¶ Cleans up all unused edges in domain.
See also:
pyfrp.pyfrp_modules.pyfrp_gmsh_geometry.edge.delete()
.Keyword Arguments: debug (bool) – Print debugging output.
-
draw
(ax=None, color='k', ann=None, drawSurfaces=False, surfaceColor='b', alpha=0.2, backend='mpl', asSphere=True, size=5, annElements=[True, True, True])¶ Draws complete domain.
There are two different backends for drawing, namely
- Matplotlib (
backend='mpl'
) - VTK (
backend='vtk'
)
Matplotlib is easier to handle, but slower. VTK is faster for complex geometries.
Note
If
backend=mpl
,ax
should be amatplotlib.axes
, ifbackend='vtk'
,ax
should be avtk.vtkRenderer
object.Note
If no axes is given, will create new one, see also
pyfrp.modules.pyfrp_plot_module.makeGeometryPlot()
orpyfrp.modules.pyfrp_vtk_module.makeVTKCanvas()
.Warning
Annotations are not properly working with
backend='vtk'
.With
annElements
the user has the possibility to only annotate given elements. For exampleannElements=[False,True,False]
only annotates edges.Keyword Arguments: - ax (matplotlib.axes) – Matplotlib axes to be plotted in.
- color (str) – Color of domain.
- ann (bool) – Show annotations.
- asSphere (bool) – Draws vertex as sphere (only in vtk mode).
- size (float) – Size of vertex (only in vtk mode).
- annElements (list) – Only annotate some element types.
Returns: Updated axes.
Return type: matplotlib.axes
- Matplotlib (
-
fixAllLoops
(debug=False)¶ Tries to fix all loops in domain.
See also:
pyfrp.pyfrp_modules.pyfrp_gmsh_geometry.lineLoop.fix()
.Keyword Arguments: debug (bool) – Print debugging output.
-
fixAllSurfaces
(debug=False, iterations=2, addPoints=False)¶ Tries to fix all surfaces in domain.
Does this by reiniating all
lineLoop
.See also:
pyfrp.pyfrp_modules.pyfrp_gmsh_geometry.ruledSurface.initLineLoop()
.Keyword Arguments: - iterations (int) – Number of iterations used for subdivision of surfaces.
- addPoints (bool) – Allow adding points inside surface triangles.
- debug (bool) – Print debugging messages.
-
genMinBkgd
(FieldsList=[])¶ Generates minimum field as background field.
If domain already has minimum field, will take it and set it as background field. If domain has multiple minimum fields, will take the first one that appears in
fields
list.Keyword Arguments: FieldsList (list) – List of field IDs included in minField. Returns: Minimum field. Return type: pyfrp.modules.pyfrp_gmsh_geometry.minField
-
getAllFieldsOfType
(typ)¶ Returns all fields of domain with specific typ.
Returns: List of pyfrp.modules.pyfrp_gmsh_geometry.field
objects.Return type: list
-
getAllMaxID
()¶ Returns maximum ID over all elements.
Returns: Maximum ID. Return type: int
-
getAllObjectsWithProp
(objName, attr, val)¶ Filters all objects of type objName given attribute value.
Possible objects names are:
- vertices
- lines
- arcs
- lineLoops
- ruledSurfaces
- surfaceLoops
- volumes
- fields
Note
val
can have any datatype.Parameters: - objName (str) – Name of object list.
- attr (str) – Name of attribute.
- val (str) – Value of attribute.
Returns: List of objects that fulfill requirement.
Return type: list
-
getBkgdField
()¶ Returns background field of domain.
Returns: Background field. Return type: pyfrp.modules.pyfrp_gmsh_geometry.field
-
getEdgeById
(ID)¶ Returns edge with ID
ID
.Returns
(False,False)
if edge cannot be found.Parameters: ID (int) – ID of edge. Returns: Tuple containing: - e (pyfrp.modules.pyfrp_gmsh_geometry.edge): Edge.
- i (int): Position in
edges
list.
Return type: tuple
-
getEdgeByVertices
(v1, v2)¶ Returns edge between vertex
v1
andv2
.Returns
(False,False)
if edge cannot be found.Parameters: - v1 (pyfrp.modules.pyfrp_gmsh_geometry.vertex) – Vertex 1.
- v2 (pyfrp.modules.pyfrp_gmsh_geometry.vertex) – Vertex 2.
Returns: Tuple containing:
- e (pyfrp.modules.pyfrp_gmsh_geometry.edge): Edge.
- i (int): Position in
edges
list.
Return type: tuple
-
getExtend
()¶ Returns extend of domain in all 3 dimensions.
Returns: Tuple containing: - minx (float): Minimal x-coordinate.
- maxx (float): Maximal x-coordinate.
- miny (float): Minimal y-coordinate.
- maxy (float): Maximal y-coordinate.
- minz (float): Minimal z-coordinate.
- maxz (float): Maximal z-coordinate.
Return type: tuple
-
getFieldById
(ID)¶ Returns field with ID
ID
.Returns
(False,False)
if field cannot be found.Parameters: ID (int) – ID of field. Returns: Tuple containing: - f (pyfrp.modules.pyfrp_gmsh_geometry.field): Field.
- i (int): Position in
fields
list.
Return type: tuple
-
getLineLoopById
(ID)¶ Returns lineLoop with ID
ID
.Returns
(False,False)
if lineLoop cannot be found.Parameters: ID (int) – ID of lineLoop. Returns: Tuple containing: - l (pyfrp.modules.pyfrp_gmsh_geometry.lineLoop): lineLoop.
- i (int): Position in
lineLoops
list.
Return type: tuple
-
getMaxID
(element)¶ Returns maximum ID for a specific element.
Possible elements are:
- vertices
- lines
- arcs
- lineLoops
- ruledSurfaces
- surfaceLoops
- volumes
Parameters: element (str) – Element type. Returns: Maximum ID. Return type: int
-
getNewId
(objList, Id=None)¶ Returns free ID for object type.
Parameters: objList (list) – List of objects, for example edges
.Keyword Arguments: Id (int) – ID to be checked. Returns: New free ID. Return type: int
-
getRuledSurfaceById
(ID)¶ Returns ruledSurface with ID
ID
.Returns
(False,False)
if ruledSurface cannot be found.Parameters: ID (int) – ID of ruledSurface. Returns: Tuple containing: - l (pyfrp.modules.pyfrp_gmsh_geometry.ruledSurface): ruledSurface.
- i (int): Position in
ruledSurfaces
list.
Return type: tuple
-
getRuledSurfacesByNormal
(direction, onlyAbs=True)¶ Returns all surfaces in domain that have given normal vector.
The direction can be given in multiple ways:
- A
numpy.ndarray
: The method will look for all surfaces with same normal vector than array. - A
str
: The method will first check ifdirection='all'
is given. If so, return all surfaces. Otherwise the method will decode the string (“x”/”y”,”z”) usingpyfrp.modules.pyfrp_geometry_module.decodeEuclideanBase()
, then proceed the same way as with thenumpy.ndarray
. - A
list
of the previous options: Will find all surface matching each of them.
Note
If
onlyAbs=True
, will only look for matches in terms of absolute value. If a list of directions is given, then one can also specifiy a list ofonlyAbs
values.Parameters: direction (numpy.ndarray) – Direction to be matched. Keyword Arguments: onlyAbs (bool) – Only try to match in terms of absolute value. Returns: List of matching surfaces. Return type: list - A
-
getSurfaceLoopById
(ID)¶ Returns surfaceLoop with ID
ID
.Returns
(False,False)
if surfaceLoop cannot be found.Parameters: ID (int) – ID of surfaceLoop. Returns: Tuple containing: - l (pyfrp.modules.pyfrp_gmsh_geometry.surfaceLoop): surfaceLoop.
- i (int): Position in
surfaceLoops
list.
Return type: tuple
-
getVertexById
(ID)¶ Returns vertex with ID
ID
.Returns
(False,False)
if vertex cannot be found.Parameters: ID (int) – ID of vertex. Returns: Tuple containing: - v (pyfrp.modules.pyfrp_gmsh_geometry.vertex): Vertex.
- i (int): Position in
vertices
list.
Return type: tuple
-
getVertexByX
(x)¶ Returns vertex at coordinate
x
.Returns
(False,False)
if vertex cannot be found.Parameters: x (numpy.ndarry) – Coordinate of vertex. Returns: Tuple containing: - v (pyfrp.modules.pyfrp_gmsh_geometry.vertex): Vertex.
- i (int): Position in
vertices
list.
Return type: tuple
-
getVolumeById
(ID)¶ Returns volume with ID
ID
.Returns
(False,False)
if volume cannot be found.Parameters: ID (int) – ID of volume. Returns: Tuple containing: - l (pyfrp.modules.pyfrp_gmsh_geometry.volume): volume.
- i (int): Position in
volumes
list.
Return type: tuple
-
hasBkgdField
()¶ Checks if domain already has a background field.
Returns: True if background field already exists. Return type: bool
-
incrementAllIDs
(offset)¶ Adds offset to all entity IDs.
Parameters: offset (int) – Offset to be added.
-
incrementID
(objList)¶ Returns ID that is by one larger for a specific object type.
Parameters: objList (list) – List of objects, for example edges
.Returns: Incremented ID. Return type: int
-
incrementIDs
(offset, element)¶ Adds offset to all entity IDs.
Possible elements are:
- vertices
- lines
- arcs
- lineLoops
- ruledSurfaces
- surfaceLoops
- volumes
- fields
Parameters: - offset (int) – Offset to be added.
- element (str) – Element type to increment.
-
insertEdge
(obj, copy=False, strict=True, debug=False)¶ Inserts edge into domain.
See also
pyfrp.modules.pyfrp_gmsh_geometry.domain.insertElement()
.Parameters: obj (pyfrp.modules.pyfrp_gmsh_geometry.edge) – A edge.
Keyword Arguments: - copy (bool) – Inserts copy of object.
- strict (bool) – Don’t allow IDs to be assigned to multiple elements.
- debug (bool) – Print debugging output.
Returns: Updated edges list.
Return type: list
-
insertElement
(element, obj, copy=False, strict=True, debug=False)¶ Inserts gmshElement into domain.
Checks if there is already a element with ID.
Note
If
copy=True
, will generate copy of element. This might mess with some connection between elements. Thuscopy=False
as default.Possible values for
element
are:- vertices
- lines
- arcs
- lineLoops
- bSplines
- ruledSurfaces
- surfaceLoops
- volumes
- fields
- auto
Note
element='auto'
will automatically detect the type of element and insert it at the right point.Will automatically set
self
as element’s domain.Note
If
strict=True
, will not allow double IDs.Parameters: - element (str) – Name of element list where object belongs.
- obj (pyfrp.modules.pyfrp_gmsh_geometry.gmshElement) – Element to insert.
Keyword Arguments: - copy (bool) – Inserts copy of object.
- strict (bool) – Don’t allow IDs to be assigned to multiple elements.
- debug (bool) – Print debugging output.
Returns: Updated respective element list.
Return type: list
-
insertField
(obj, copy=False, strict=True, debug=False)¶ Inserts field into domain.
See also
pyfrp.modules.pyfrp_gmsh_geometry.domain.insertElement()
.Parameters: obj (pyfrp.modules.pyfrp_gmsh_geometry.field) – A field.
Keyword Arguments: - copy (bool) – Inserts copy of object.
- strict (bool) – Don’t allow IDs to be assigned to multiple elements.
- debug (bool) – Print debugging output.
Returns: Updates fields list.
Return type: list
-
insertLineLoop
(obj, copy=False, strict=True, debug=False)¶ Inserts line loop into domain.
See also
pyfrp.modules.pyfrp_gmsh_geometry.domain.insertElement()
.Parameters: obj (pyfrp.modules.pyfrp_gmsh_geometry.lineLoop) – A line loop.
Keyword Arguments: - copy (bool) – Inserts copy of object.
- strict (bool) – Don’t allow IDs to be assigned to multiple elements.
- debug (bool) – Print debugging output.
Returns: Updated lineLoops list.
Return type: list
-
insertRuledSurface
(obj, copy=False, strict=True, debug=False)¶ Inserts ruled surface into domain.
See also
pyfrp.modules.pyfrp_gmsh_geometry.domain.insertElement()
.Parameters: obj (pyfrp.modules.pyfrp_gmsh_geometry.ruledSurface) – A ruled surface.
Keyword Arguments: - copy (bool) – Inserts copy of object.
- strict (bool) – Don’t allow IDs to be assigned to multiple elements.
- debug (bool) – Print debugging output.
Returns: Updated ruledSurfaces list.
Return type: list
-
insertSurfaceLoop
(obj, copy=False, strict=True, debug=False)¶ Inserts surface loop into domain.
See also
pyfrp.modules.pyfrp_gmsh_geometry.domain.insertElement()
.Parameters: obj (pyfrp.modules.pyfrp_gmsh_geometry.surfaceLoop) – A surface loop.
Keyword Arguments: - copy (bool) – Inserts copy of object.
- strict (bool) – Don’t allow IDs to be assigned to multiple elements.
- debug (bool) – Print debugging output.
Returns: Updated surfaceLoops list.
Return type: list
-
insertVertex
(obj, copy=False, strict=True, debug=False)¶ Inserts vertex into domain.
See also
pyfrp.modules.pyfrp_gmsh_geometry.domain.insertElement()
.Parameters: obj (pyfrp.modules.pyfrp_gmsh_geometry.vertex) – A vertex.
Keyword Arguments: - copy (bool) – Inserts copy of object.
- strict (bool) – Don’t allow IDs to be assigned to multiple elements.
- debug (bool) – Print debugging output.
Returns: Updated edges list.
Return type: list
-
insertVolume
(obj, copy=False, strict=True, debug=False)¶ Inserts volume into domain.
See also
pyfrp.modules.pyfrp_gmsh_geometry.domain.insertElement()
.Parameters: obj (pyfrp.modules.pyfrp_gmsh_geometry.volume) – A volume.
Keyword Arguments: - copy (bool) – Inserts copy of object.
- strict (bool) – Don’t allow IDs to be assigned to multiple elements.
- debug (bool) – Print debugging output.
Returns: Updates volumes list.
Return type: list
-
merge
(d)¶ Merges domain d into this domain.
Does this by:
- Incrementing all IDs in
d
such that there is no overlap withself
. - Merging all element lists.
- Making sure that all elements refer to
self
as domain.
See also
incrementAllIDs()
andsetDomainGlobally()
.Parameters: d (pyfrp.modules.pyfrp_geometry_module.domain) – Domain to merge. - Incrementing all IDs in
-
removeDuplicateEdgeIDs
(debug=False)¶ Checks if multiple edges have the same ID and tries to remove one of them.
Checkss if edges with same ID have the same start and end vertex. If so, removes it all but one. Otherwise fixes index.
Returns: Updated edges list. Return type: list
-
removeDuplicateVerticesIDs
()¶ Checks if multiple vertices have the same ID and tries to remove one of them.
Checks if vertices with same ID have the same coordinate. If so, remove all but one. Otherwise fixes index.
Returns: Updated vertices list. Return type: list
-
removeDuplicates
(debug=False)¶
-
save
(fn)¶ Saves domain to pickle file.
Parameters: fn (str) – Output filename.
-
setAnnOffset
(offset)¶ Sets annotation offset for plotting.
Parameters: offset (numpy.ndarray) – New offset.
-
setDomainForElementType
(element)¶ Makes sure that
self
is domain for all elements of given type.Possible elements are:
- vertices
- lines
- arcs
- lineLoops
- ruledSurfaces
- surfaceLoops
- volumes
- fields
Parameters: - offset (int) – Offset to be added.
- element (str) – Element type to increment.
-
setDomainGlobally
()¶ Makes sure that
self
is domain for all elements.
-
setGlobalVolSize
(volSize)¶ Sets volSize for all nodes in geometry.
-
simplifySurfaces
(iterations=3, triangIterations=2, addPoints=False, fixSurfaces=True, debug=False)¶ Tries to simplify surfaces inside the domain.
Does this by:
- For
iterations
iterations, do: - Find all surfaces with the same normal vector.
- Try to fuse this surfaces, see also
pyfrp.modules.pyfrp_geometry_module.ruledSurface.fuse()
. - Clean up edges via
pyfrp.modules.pyfrp_geometry_module.domain.cleanUpUnusedEdges()
.
- For
- Fixing loops via
pyfrp.modules.pyfrp_geometry_module.domain.fixAllLoops()
. - Fixing surfaces via
pyfrp.modules.pyfrp_geometry_module.domain.fixAllSurfaces()
.
Keyword Arguments: - iterations (int) – Number of iterations used for simplification.
- triangIterations (int) – Number of iterations used for subdivision of surfaces.
- addPoints (bool) – Allow adding points inside surface triangles.
- fixSurfaces (bool) – Allow fixing of surfaces, making sure they are coherent with Gmsh requirements.
- debug (bool) – Print debugging messages.
-
verticesCoordsToList
()¶ Returns list of coordinates from all vertrices.
Returns: List of (x,y,z) coordinates. Return type: list
-
writeElements
(element, f)¶ Writes all entities of a specific element type to file.
Possible elements are:
- vertices
- lines
- arcs
- lineLoops
- bSplines
- ruledSurfaces
- surfaceLoops
- volumes
- fields
Parameters: - element (str) – Element type to write.
- f (file) – File to write to.
-
writeToFile
(fn)¶ Writes domain to file.
Parameters: fn (str) – File path to write to.
-
class
pyfrp.modules.pyfrp_gmsh_geometry.
edge
(domain, Id, typ)¶ Bases:
pyfrp.modules.pyfrp_gmsh_geometry.gmshElement
Edge class storing information from gmsh .geo circles and lines.
Parameters: - domain (pyfrp.modules.pyfrp_gmsh_geometry.domain) – Domain vertex belongs to.
- Id (int) – ID of edge.
- typ (int) – Type of edge (1=arc/0=line).
-
addToBoundaryLayer
(boundField=None, **fieldOpts)¶ Adds edge to a boundary layer field.
If no field is given, will create new one with given parameters and add it to a minField. If no minField exists, will create a new one too and set it as background field.
See also
pyfrp.modules.pyfrp_gmsh_geometry.domain.addBoundaryLayerField()
pyfrp.modules.pyfrp_gmsh_geometry.domain.addMinField()
andpyfrp.modules.pyfrp_gmsh_geometry.domain.genMinBkgd()
.Keyword Arguments: - boundField (pyfrp.modules.pyfrp_gmsh_geometry.boundaryLayerField) – Boundary layer field object.
- fieldOpts (dict) – See documentation of boundary layer field of all available options.
Returns: Boundary layer field around edge.
Return type:
-
decodeTyp
()¶ Decodes type of edge into string.
-
delete
(debug=False)¶ Deletes edge if it is not used in any loop or field.
Returns: True if deletion was successful. Return type: bool
-
getDomain
()¶ Returns domain edge belongs to.
-
getTyp
()¶ Returns Type of edge.
-
includedInField
()¶ Checks if edge is included in a field.
Note
Only checks for boundary layer fields, since they are the only ones who can evolve around edge.
Returns: Tuple containing: - included (bool): True if included.
- fields (list): List of
pyfrp.modules.pyfrp_gmsh_geometry.fields
objects that include edge.
Return type: tuple
-
includedInLoop
()¶ Checks if edge is included in a loop.
Returns: Tuple containing: - included (bool): True if included.
- loops (list): List of
pyfrp.modules.pyfrp_gmsh_geometry.lineLoop
objects that include edge.
Return type: tuple
-
class
pyfrp.modules.pyfrp_gmsh_geometry.
field
(domain, typ, Id)¶ Bases:
pyfrp.modules.pyfrp_gmsh_geometry.gmshElement
Field class storing information from gmsh .geo.
Parameters: - domain (pyfrp.modules.pyfrp_gmsh_geometry.domain) – Domain surface belongs to.
- Id (int) – ID of field.
- typ (str) – Type of field.
-
getSubElements
()¶ Returns all elements that define this element.
Returns: List of elements. Return type: list
-
isBkgdField
()¶ Returns true if field is background field.
Returns: True if background field. Return type: bool
-
setAsBkgdField
()¶ Sets this mesh as background field for the whole domain.
-
setFieldAttr
(name, val)¶ Sets attribute of field.
Note
Value can have any data type.
Parameters: - name (str) – Name of attribute.
- val (str) – Value.
-
setFieldAttributes
(**kwargs)¶ Sets multiple field attributes.
-
class
pyfrp.modules.pyfrp_gmsh_geometry.
gmshElement
(domain, Id)¶ Bases:
object
-
extract
(d=None, strict=True, copy=False, debug=False)¶ Extracts element and all elements necessary to define it.
Note
If
d
is specified, then all extracted elements are inserted intod
usinginsertElement()
.Keyword Arguments: - d (pyfrp.modules.pyfrp_gmsh_geometry.domain) – Domain to insert element
- copy (bool) – Inserts copy of object.
- strict (bool) – Don’t allow IDs to be assigned to multiple elements.
- debug (bool) – Print debugging output.
Returns: List of elements.
Return type: list
-
getAllSubElements
(elements=[])¶ Finds all elements that are necessary to define this element recursively.
Returns: List of elements. Return type: list
-
getCopy
()¶ Returns copy of element.
Uses copy.copy to generate copy.
Returns: Copy of element. Return type: pyfrp.modules.pyfrp_gmsh_geometry.gmshElement
-
getDomain
()¶ Returns element’s domain.
Returns: Element’s domain. Return type: pyfrp.modules.pyfrp_gmsh_geometry.domain
-
getID
()¶ Returns ID of element.
Returns: ID of element. Return type: int
-
getSubElements
()¶ Returns all elements that define this element.
Returns: List of elements. Return type: list
-
getType
()¶ Returns type of element.
Returns: Type of element. Return type: str
-
getTypeList
()¶ Returns the element list of domain for this element.
Returns: Element list. Return type: list
-
getTypeListName
()¶ Returns the element lists name.
Returns: Name of element list. Return type: str
-
setDomain
(d)¶ Sets element’s domain.
Parameters: d (pyfrp.modules.pyfrp_gmsh_geometry.domain) – New domain Returns: New domain. Return type: pyfrp.modules.pyfrp_gmsh_geometry.domain
-
setID
(Id)¶ Sets ID of element.
Parameters: Id (int) – New ID of element. Returns: New ID of element. Return type: int
-
-
class
pyfrp.modules.pyfrp_gmsh_geometry.
line
(domain, v1, v2, Id)¶ Bases:
pyfrp.modules.pyfrp_gmsh_geometry.edge
Line class storing information from gmsh .geo lines.
Parameters: - domain (pyfrp.modules.pyfrp_gmsh_geometry.domain) – Domain line belongs to.
- v1 (pyfrp.modules.pyfrp_gmsh_geometry.vertex) – Start vertex.
- v2 (pyfrp.modules.pyfrp_gmsh_geometry.vertex) – End vertex.
- Id (int) – ID of line.
-
draw
(ax=None, color=None, ann=None, backend='mpl', render=False, drawVertices=False)¶ Draws line.
There are two different backends for drawing, namely
- Matplotlib (
backend='mpl'
) - VTK (
backend='vtk'
)
Matplotlib is easier to handle, but slower. VTK is faster for complex geometries.
Note
If
backend=mpl
,ax
should be amatplotlib.axes
, ifbackend='vtk'
,ax
should be avtk.vtkRenderer
object.Note
If no axes is given, will create new one, see also
pyfrp.modules.pyfrp_plot_module.makeGeometryPlot()
orpyfrp.modules.pyfrp_vtk_module.makeVTKCanvas()
.Warning
Annotations are not properly working with
backend='vtk'
.Keyword Arguments: - ax (matplotlib.axes) – Matplotlib axes to be plotted in.
- color (str) – Color of line.
- ann (bool) – Show annotations.
- render (bool) – Render in the end (only in vtk mode).
- drawVertices (bool) – Also draw vertices.
Returns: Updated axes.
Return type: matplotlib.axes
- Matplotlib (
-
drawMPL
(ax=None, color=None, ann=None)¶ Draws line into matplotlib axes.
Note
If
ann=None
, will setann=False
.Note
If no axes is given, will create new one, see also
pyfrp.modules.pyfrp_plot_module.makeGeometryPlot()
.Keyword Arguments: - ax (matplotlib.axes) – Matplotlib axes to be plotted in.
- color (str) – Color of line.
- ann (bool) – Show annotations.
Returns: Axes.
Return type: matplotlib.axes
-
drawVTK
(ax=None, color=None, ann=None, render=False)¶ Draws line into VTK renderer.
Note
If
ann=None
, will setann=False
.Note
If no axes is given, will create new
vtkRenderer
, see alsopyfrp.modules.pyfrp_vtk_module.makeVTKCanvas()
.See also
pyfrp.modules.pyfrp_vtk_module.drawVTKLine()
.Keyword Arguments: - ax (vtk.vtkRenderer) – Renderer to draw in.
- color (str) – Color of line.
- ann (bool) – Show annotations.
- render (bool) – Render in the end.
Returns: Updated renderer.
Return type: vtk.vtkRenderer
-
getDirection
(orientation)¶ Returns direction of line.
Orientation can be either forward (1), or reverse (-1).
Parameters: orientation (int) – Orientation of line. Returns: Direction of line. Return type: numpy.ndarray
-
getFirstVertex
(orientation)¶ Returns first vertex of line given a orientation.
Orientation can be either forward (1), or reverse (-1).
Parameters: orientation (int) – Orientation of line. Returns: Vertex. Return type: pyfrp.pyfrp_gmsh_geometry.vertex
-
getLastVertex
(orientation)¶ Returns last vertex of line given a orientation.
Orientation can be either forward (1), or reverse (-1).
Parameters: orientation (int) – Orientation of line. Returns: Vertex. Return type: pyfrp.pyfrp_gmsh_geometry.vertex
-
getMiddle
()¶ Returns midpoint of line.
\[m = \frac{x(v_1) + x(v_2)}{2}\]Returns: Midpoint. Return type: numpy.ndarray
-
getSubElements
()¶ Returns all elements that define this element.
Returns: List of elements. Return type: list
-
writeToFile
(f)¶ Writes line to file.
Parameters: f (file) – File to write to. Returns: File. Return type: file
-
class
pyfrp.modules.pyfrp_gmsh_geometry.
lineLoop
(domain, edgeIDs, ID)¶ Bases:
pyfrp.modules.pyfrp_gmsh_geometry.gmshElement
Lineloop class storing information from gmsh .geo.
Object has two major attributes:
- edges (list): List of pyfrp.moduels.pyfrp_gmsh_geometry.edge objects.
- orientations (list): List of orientations of each element, either
1
or-1
Parameters: - domain (pyfrp.modules.pyfrp_gmsh_geometry.domain) – Domain loop belongs to.
- edgeIDs (list) – List of edge IDs.
- Id (int) – ID of loop.
-
addEdgeByID
(ID)¶ Adds edge to lineloop.
Parameters: ID (int) – ID of edge to be added. Returns: Updated edgeIDs list. Return type: list
-
approxBySpline
(angleThresh=0.314, debug=False)¶ Approximates parts of line loop by spline.
Summarizes all consecutive lines in loop that have a small angle inbetween to a spline.
Note
The choice of
angleThresh
is crucial for this function to work. It should be chosen on a by-case basis if necessary.Example:
Load test file:
>>> d,dd = pyfrp_gmsh_IO_module.readGeoFile("pyfrp/meshfiles/examples/splineTest.geo")
Draw:
>>> d.setAnnOffset([0.1,0.1,0.00]) >>> ax=d.draw(backend='mpl',asSphere=False,ann=True,annElements=[False,True,False])
returns the following
Approximate by spline and draw again
>>> d.lineLoops[0].approxBySpline(angleThresh=0.1*np.pi) >>> ax=d.draw(backend='mpl',asSphere=False,ann=True,annElements=[False,True,False])
returns
And write to file
>>> d.writeToFile("pyfrp/meshfiles/examples/approximated.geo")
Keyword Arguments: - angleThresh (float) – Angular threshold in radians.
- debug (bool) – Print debugging messages.
Returns: True if approximated.
Return type: bool
-
checkClosed
(fix=False, debug=False)¶ Checks if lineLoop is closed.
Keyword Arguments: - debug (bool) – Print debugging messages.
- fix (bool) – Close if necessary.
Returns: True if closed.
Return type: bool
-
delete
(debug=False)¶ Deletes loop if it is not used in any surface.
Returns: True if deletion was successful. Return type: bool
-
draw
(ax=None, color='k', ann=None, backend='mpl', drawVertices=False)¶ Draws complete line loop.
There are two different backends for drawing, namely
- Matplotlib (
backend='mpl'
) - VTK (
backend='vtk'
)
Matplotlib is easier to handle, but slower. VTK is faster for complex geometries.
Note
If
backend=mpl
,ax
should be amatplotlib.axes
, ifbackend='vtk'
,ax
should be avtk.vtkRenderer
object.Note
If no axes is given, will create new one, see also
pyfrp.modules.pyfrp_plot_module.makeGeometryPlot()
orpyfrp.modules.pyfrp_vtk_module.makeVTKCanvas()
.Warning
Annotations are not properly working with
backend='vtk'
.Keyword Arguments: - ax (matplotlib.axes) – Matplotlib axes to be plotted in.
- color (str) – Color of line loop.
- ann (bool) – Show annotations.
- drawVertices (bool) – Also draw vertices.
Returns: Updated axes.
Return type: matplotlib.axes
- Matplotlib (
-
fix
()¶ Fixes loop.
-
fuse
(loop, maxL=1000, debug=False, surface=None)¶ Fuses lineLoop with other loop.
-
getCenterOfMass
()¶ Computes center of mass of surface.
Returns: Center of mass. Return type: numpy.ndarray
-
getEdges
()¶ Returns list of edges included in lineLoop.
-
getSubElements
()¶ Returns all elements that define this element.
Returns: List of elements. Return type: list
-
getVertices
()¶ Returns all vertices included in loop.
-
hasCommonEdge
(loop)¶ Checks if lineLoop has common edges with other lineLoop.
Parameters: loop (pyfrp.modules.pyfrp_gmsh_geometry.lineLoop) – lineLoop object. Returns: Tuple containing: - hasCommon (bool): True if loops have common edge.
- edges (list): List of common edges.
Return type: tuple
-
includedInSurface
()¶ Checks if loop is included in a surface.
Returns: Tuple containing: - included (bool): True if included.
- loops (list): List of
pyfrp.modules.pyfrp_gmsh_geometry.ruledSurface
objects that include loop.
Return type: tuple
-
initEdges
(IDs)¶ Constructs
edges
andorientations
list at object initiations from list of IDs.Parameters: IDs (list) – List of IDs Returns: Tuple containing: - edges (list): List of pyfrp.moduels.pyfrp_gmsh_geometry.edge objects.
- orientations (list): List of orientations of each element, either
1
or-1
Return type: tuple
-
insertEdgeByID
(ID, pos)¶ Inserts edge to lineloop at position.
Parameters: - ID (int) – ID of edge to be inserted.
- pos (int) – Position at which ID to be inserted.
Returns: Updated edgeIDs list.
Return type: list
-
isCoplanar
()¶ Returns if all edges lie in single plane.
Does this by
- picking the first two vertices as first vector
vec1 = v1 - v0
- looping through vertices and computung the normal vector
between
vec1
andvec2=v[i]-v0
. - Checking if all normal vectors are colinear.
Returns: True if coplanar. Return type: bool - picking the first two vertices as first vector
-
printLoop
()¶ Prints loop.
-
removeEdgeByID
(ID)¶ Remove edge from lineloop.
Parameters: ID (int) – ID of edge to be removed. Returns: Updated edgeIDs list. Return type: list
-
removeFromAllSurfaces
()¶ Removes lineLoop from all surfaces.
-
removeFromSurface
(surface)¶ Removes lineLoop from surface.
-
reverseEdge
(ID)¶ Reverses the orientation of an edge in the line loop.
Parameters: ID (int) – ID of edge to be reversed. Returns: Updated orientations list. Return type: list
-
writeToFile
(f)¶ Writes line loop to file.
Parameters: f (file) – File to write to. Returns: File. Return type: file
-
class
pyfrp.modules.pyfrp_gmsh_geometry.
minField
(domain, Id, FieldsList=[])¶ Bases:
pyfrp.modules.pyfrp_gmsh_geometry.field
Minimum field class storing information from gmsh .geo.
Subclasses from
field
.Parameters: - domain (pyfrp.modules.pyfrp_gmsh_geometry.domain) – Domain surface belongs to.
- Id (int) – ID of field.
Keyword Arguments: FieldsList (list) – List of field IDs.
-
addAllFields
()¶ Adds all fields in domain to FieldsList if not already in there.
Returns: Updated FieldsList. Return type: list
-
addFieldByID
(ID)¶ Adds field object to FieldsList given the ID of the field.
Parameters: ID (int) – ID of field to be added. Returns: Updated FieldsList. Return type: list
-
getSubElements
()¶ Returns all elements that define this element.
Returns: List of elements. Return type: list
-
initFieldsList
(FieldsList)¶ Adds a list of vertices to NodesList.
See also
addNodeByID()
.Parameters: FieldsList (list) – List of field IDs. Returns: Updated FieldsList. Return type: list
-
setFieldAttr
(name, val)¶
-
writeToFile
(f)¶ Writes minimum field to file.
See also
pyfrp.modules.pyfrp_gmsh_IO_module.writeMinField()
.Parameters: f (file) – File to write to. Returns: File. Return type: file
-
class
pyfrp.modules.pyfrp_gmsh_geometry.
ruledSurface
(domain, loopID, ID)¶ Bases:
pyfrp.modules.pyfrp_gmsh_geometry.gmshElement
ruledSurface class storing information from gmsh .geo.
Parameters: - domain (pyfrp.modules.pyfrp_gmsh_geometry.domain) – Domain surface belongs to.
- loopID (int) – ID of surrounding loop.
- Id (int) – ID of surface.
-
addToBoundaryLayer
(boundField=None, **fieldOpts)¶ Adds surface to a boundary layer field.
If no field is given, will create new one with given parameters and add it to a minField. If no minField exists, will create a new one too and set it as background field.
See also
pyfrp.modules.pyfrp_gmsh_geometry.domain.addBoundaryLayerField()
pyfrp.modules.pyfrp_gmsh_geometry.domain.addMinField()
andpyfrp.modules.pyfrp_gmsh_geometry.domain.genMinBkgd()
.Keyword Arguments: - boundField (pyfrp.modules.pyfrp_gmsh_geometry.boundaryLayerField) – Boundary layer field object.
- fieldOpts (dict) – See documentation of boundary layer field of all available options.
Returns: Boundary layer field around edge.
Return type:
-
delete
()¶ Deletes surface if it is not used in any surfaceLoop.
Returns: True if deletion was successful. Return type: bool
-
draw
(ax=None, color='b', edgeColor='k', drawLoop=True, ann=None, alpha=0.2, backend='mpl')¶ Draws surface and fills it with color.
Note
If
ann=None
, will setann=False
.Note
If no axes is given, will create new one.
Warning
Does not work for surfaces surrounded by arcs yet.
Keyword Arguments: - ax (matplotlib.axes) – Matplotlib axes to be plotted in.
- color (str) – Color of surface.
- ann (bool) – Show annotations.
- edgeColor (str) – Color of lineLoop around.
- alpha (float) – Transparency of surface.
Returns: Axes.
Return type: matplotlib.axes
-
fuse
(surface, maxL=1000, debug=False, sameNormal=False)¶ Fuses surface with another surface.
Will not do anything if surfaces do not have an edge in common.
-
getCenterOfMass
()¶ Computes center of mass of surface.
Returns: Center of mass. Return type: numpy.ndarray
-
getEdges
()¶ Returns all edges included in surface.
-
getNormal
(method='cross')¶ Computes normal to surface.
First checks if surface is coplanar using
pyfrp.modules.pyfrp_gmsh_geometry.ruledSurface.isCoplanar()
. Then finds two independent vectors that span surface and passes them on topyfrp.modules.pyfrp_geometry_module.computeNormal()
.Currently there are two methods available:
cross
, see alsonormalByCross()
.newells
, see alsonewells()
.
If method is unknown, will fall back to
cross
.Keyword Arguments: method (str) – Method of normal computation. Returns: Normal vector to surface. Return type: numpy.ndarray
-
getSubElements
()¶ Returns all elements that define this element.
Returns: List of elements. Return type: list
-
getVertices
()¶ Returns all vertices included in surface.
-
hasCommonEdge
(surface)¶ Checks if surface has common edge with other surface.
Parameters: surface (pyfrp.modules.pyfrp_gmsh_geometry.ruledSurface) – Surface object. Returns: Tuple containing: - hasCommon (bool): True if loops have common edge.
- e (pyfrp.modules.pyfrp_gmsh_geometry.edge): Edge that is in common.
Return type: tuple
-
hasSameNormal
(surface, sameOrientation=False)¶ Checks if sufrace has the same normal vector as another surface.
Parameters: surface (pyfrp.modules.pyfrp_gmsh_geometry.ruledSurface) – Surface object. Keyword Arguments: sameOrientation (bool) – Forces surfaces to also have same orientation. Returns: True if same normal vector. Return type: bool
-
includedInLoop
()¶ Checks if surface is included in a surfaceLoop.
Returns: Tuple containing: - included (bool): True if included.
- loops (list): List of
pyfrp.modules.pyfrp_gmsh_geometry.surfaceLoops
objects that include surface.
Return type: tuple
-
initLineLoop
(loopID, debug=False, addPoints=False, iterations=2)¶ Checks length of lineLoop and if length of lineLoop is greater than 4, will perform triangulation so Gmsh can handle surface.
-
isCoplanar
()¶ Returns if surface lies in single plane.
Returns: True if coplanar. Return type: bool
-
normalToPlane
()¶ Checks if surface lies within either x-y-/x-z-/y-z-plane.
Does this by checking if
1.
is in the normal vector.Returns: True if in plane. Return type: bool
-
removeFromAllLoops
()¶ Removes surface from all surface loops.
-
rotateToNormal
(normal, ownNormal=None)¶ Rotates surface such that it lies in the plane with normal vector
normal
.See also
pyfrp.modules.pyfrp_geometry_module.getRotMatrix()
.Parameters: normal (numpy.ndarray) – Normal vector. Returns: Rotation matrix. Return type: numpy.ndarray
-
rotateToPlane
(plane)¶ Rotates surface such that it lies in plane.
See also
pyfrp.modules.pyfrp_geometry_module.getRotMatrix()
.Possible planes are:
xy
xz
yz
Parameters: plane (str) – Plane to rotate to. Returns: Rotation matrix. Return type: numpy.ndarray
-
rotateToSurface
(s)¶ Rotates surface such that it lies in the same plane as a given surface.
See also
pyfrp.modules.pyfrp_geometry_module.getRotMatrix()
.Parameters: s (pyfrp.modules.pyfrp_gmsh_geometry.ruledSurface) – A surface. Returns: Rotation matrix. Return type: numpy.ndarray
-
writeToFile
(f)¶ Writes ruled surface to file.
Parameters: f (file) – File to write to. Returns: File. Return type: file
-
class
pyfrp.modules.pyfrp_gmsh_geometry.
surfaceLoop
(domain, surfaceIDs, ID)¶ Bases:
pyfrp.modules.pyfrp_gmsh_geometry.gmshElement
surfaceLoop class storing information from gmsh .geo.
Parameters: - domain (pyfrp.modules.pyfrp_gmsh_geometry.domain) – Domain loop belongs to.
- surfaceIDs (list) – List of surfaces.
- Id (int) – ID of loop.
-
addSurfaceByID
(ID)¶ Adds surface to surfaceloop.
Parameters: ID (int) – ID of surface to be added. Returns: Updated surfaceIDs list. Return type: list
-
getSubElements
()¶ Returns all elements that define this element.
Returns: List of elements. Return type: list
-
initSurfaces
(IDs)¶ Constructs
surfaces
list at object initiations from list of IDs.Parameters: IDs (list) – List of IDs. Returns: List of pyfrp.modules.pyfrp_gmsh_geometry.ruledSurface objects. Return type: list
-
insertSurfaceByID
(ID, pos)¶ Inserts surface to surfaceloop at position.
Parameters: - ID (int) – ID of surface to be inserted.
- pos (int) – Position at which ID to be inserted.
Returns: Updated surfaceIDs list.
Return type: list
-
removeSurfaceByID
(ID)¶ Remove surface from surfaceloop.
Parameters: ID (int) – ID of surface to be removed. Returns: Updated surfaceIDs list. Return type: list
-
writeToFile
(f)¶ Writes surface loop to file.
Parameters: f (file) – File to write to. Returns: File. Return type: file
-
class
pyfrp.modules.pyfrp_gmsh_geometry.
thresholdField
(domain, Id, IField=None, LcMin=5.0, LcMax=20.0, DistMin=30.0, DistMax=60.0)¶ Bases:
pyfrp.modules.pyfrp_gmsh_geometry.field
Threshold field class storing information from gmsh .geo.
Subclasses from
field
.Parameters: - domain (pyfrp.modules.pyfrp_gmsh_geometry.domain) – Domain surface belongs to.
- Id (int) – ID of field.
Keyword Arguments: - IField (int) – ID of vertex that is center to threshold field.
- LcMin (float) – Minimum volSize of threshold field.
- LcMax (float) – Maximum volSize of threshold field.
- DistMin (float) – Minimun density of field.
- DistMax (float) – Maximum density of field.
-
getSubElements
()¶ Returns all elements that define this element.
Returns: List of elements. Return type: list
-
writeToFile
(f)¶ Writes threshold field to file.
See also
pyfrp.modules.pyfrp_gmsh_IO_module.writeThresholdField()
.Parameters: f (file) – File to write to. Returns: File. Return type: file
-
class
pyfrp.modules.pyfrp_gmsh_geometry.
vertex
(domain, x, Id, volSize=None)¶ Bases:
pyfrp.modules.pyfrp_gmsh_geometry.gmshElement
Vertex class storing information from gmsh .geo Points.
Note
volSize
does not have any effect on the geometry itself but is simply stored in the vertex object for further usage.Parameters: - domain (pyfrp.modules.pyfrp_gmsh_geometry.domain) – Domain vertex belongs to.
- x (numpy.ndarray) – Coordinate of vertex.
- Id (int) – ID of vertex.
Keyword Arguments: volSize (float) – Element size at vertex.
-
addToAttractor
(attrField=None, LcMin=5.0, LcMax=20.0, DistMin=30.0, DistMax=60.0)¶ Adds vertex to a attractor field.
If no field is given, will create new one with given parameters. Will also create a new threshhold field around attractor and add fields to minField. If no minField exists, will create a new one too and set it as background field.
See also
addAttractorField()
,addThresholdField()
,addMinField()
andgenMinBkgd()
.Keyword Arguments: - attrField (pyfrp.modules.pyfrp_gmsh_geometry.attractorField) – Attractor field object.
- LcMin (float) – Minimum volSize of threshold field.
- LcMax (float) – Maximum volSize of threshold field.
- DistMin (float) – Minimun density of field.
- DistMax (float) – Maximum density of field.
Returns: Attractor field around vertex.
Return type:
-
addToBoundaryLayer
(boundField=None, **fieldOpts)¶ Adds vertex to a boundary layer field.
If no field is given, will create new one with given parameters and add it to a minField. If no minField exists, will create a new one too and set it as background field.
See also
pyfrp.modules.pyfrp_gmsh_geometry.domain.addBoundaryLayerField()
pyfrp.modules.pyfrp_gmsh_geometry.domain.addMinField()
andpyfrp.modules.pyfrp_gmsh_geometry.domain.genMinBkgd()
.Keyword Arguments: - boundField (pyfrp.modules.pyfrp_gmsh_geometry.boundaryLayerField) – Boundary layer field object.
- fieldOpts (dict) – See documentation of boundary layer field of all available options.
Returns: Boundary layer field around vertex.
Return type:
-
draw
(ax=None, color=None, ann=None, backend='mpl', asSphere=True, size=10, render=False)¶ Draws vertex.
There are two different backends for drawing, namely
- Matplotlib (
backend='mpl'
) - VTK (
backend='vtk'
)
Matplotlib is easier to handle, but slower. VTK is faster for complex geometries.
Note
If
backend=mpl
,ax
should be amatplotlib.axes
, ifbackend='vtk'
,ax
should be avtk.vtkRenderer
object.Note
If no axes is given, will create new one, see also
pyfrp.modules.pyfrp_plot_module.makeGeometryPlot()
orpyfrp.modules.pyfrp_vtk_module.makeVTKCanvas()
.Warning
Annotations are not properly working with
backend='vtk'
.Keyword Arguments: - ax (matplotlib.axes) – Matplotlib axes to be plotted in.
- color (str) – Color of vertex.
- ann (bool) – Show annotations.
- asSphere (bool) – Draws vertex as sphere (only in vtk mode).
- size (float) – Size of vertex (only in vtk mode).
- render (bool) – Render in the end (only in vtk mode).
Returns: Updated axes.
Return type: matplotlib.axes
- Matplotlib (
-
drawMPL
(ax=None, color=None, ann=None)¶ Draws vertrex into matplotlib axes.
Note
If
ann=None
, will setann=False
.Note
If no axes is given, will create new one, see also
pyfrp.modules.pyfrp_plot_module.makeGeometryPlot()
.Keyword Arguments: - ax (matplotlib.axes) – Matplotlib axes to be plotted in.
- color (str) – Color of domain.
- ann (bool) – Show annotations.
Returns: Axes.
Return type: matplotlib.axes
-
drawVTK
(size=10, asSphere=True, ax=None, ann=None, color=[0, 0, 0], render=False)¶ Draws vertrex into VTK renderer.
Note
If
ann=None
, will setann=False
.Note
If no axes is given, will create new
vtkRenderer
, see alsopyfrp.modules.pyfrp_vtk_module.makeVTKCanvas()
.Keyword Arguments: - ax (vtk.vtkRenderer) – Renderer to draw in.
- color (str) – Color of vertex.
- ann (bool) – Show annotations.
- asSphere (bool) – Draws vertex as sphere.
- size (float) – Size of vertex.
- render (bool) – Render in the end.
Returns: Updated renderer.
Return type: vtk.vtkRenderer
-
setX
(x)¶ Sets coordinate if vertex to
x
.Returns: New vertex coordinate. Return type: numpy.ndarray
-
writeToFile
(f)¶ Writes vertex to file.
Parameters: f (file) – File to write to. Returns: File. Return type: file
-
class
pyfrp.modules.pyfrp_gmsh_geometry.
volume
(domain, surfaceLoopID, ID)¶ Bases:
pyfrp.modules.pyfrp_gmsh_geometry.gmshElement
Volume class storing information from gmsh .geo.
Parameters: - domain (pyfrp.modules.pyfrp_gmsh_geometry.domain) – Domain surface belongs to.
- surfaceLoopID (int) – ID of surrounding surface loop.
- Id (int) – ID of surface loop.
-
getSubElements
()¶ Returns all elements that define this element.
Returns: List of elements. Return type: list
-
writeToFile
(f)¶ Writes Volume to file.
Parameters: f (file) – File to write to. Returns: File. Return type: file
pyfrp.modules.pyfrp_gmsh_module module¶
PyFRAP module for running Gmsh on .geo files. Module mainly has the following features:
- Functions for updating parameters in standard .geo files.
- Mesh refinement.
- Running Gmsh
This module together with pyfrp.pyfrp_gmsh_geometry and pyfrp.pyfrp_gmsh_IO_module works partially as a python gmsh wrapper, however is incomplete. If you want to know more about gmsh, go to http://gmsh.info/doc/texinfo/gmsh.html .
-
pyfrp.modules.pyfrp_gmsh_module.
getGmshBin
(fnPath=None)¶ Returns path to Gmsh binary defined in path file.
-
pyfrp.modules.pyfrp_gmsh_module.
refineMsh
(fn, debug=False)¶ Refines mesh by splitting elements.
Note
Debug will also activate full debugging output of gmsh. See also http://gmsh.info/doc/texinfo/gmsh.html#Command_002dline-options .
Parameters: fn (str) – Filepath. Keyword Arguments: debug (bool) – Print debugging messages. Returns: Path to mesh file. Return type: str
-
pyfrp.modules.pyfrp_gmsh_module.
runGmsh
(fn, fnOut=None, debug=False, redirect=False, fnStout=None, fnSterr=None, volSizeMax=None)¶ Runs Gmsh generating mesh from .geo file.
Note
Debug will also activate full debugging output of gmsh. See also http://gmsh.info/doc/texinfo/gmsh.html#Command_002dline-options .
Note
If
redirect=True
, butfnStout
orfnSterr
is not specified, will dump stout/sterr intomeshfiles/gmshLogs/
.Note
Gmsh is run with the following settings (if all flags are activated):
gmsh -v -3 -optimize -algo3d -clmax volSizeMax -o fnOut fn
This requires that Gmsh was compiled with TetGen algorithm. PyFRAP can be installed with Gmsh + TetGen included by choosing the--gmsh
flag. See also http://pyfrap.readthedocs.org/en/latest/setup.html#pyfrap-setup-py-api .Parameters: fn (str) – Filepath.
Keyword Arguments: - fnOut (str) – Output filepath.
- debug (bool) – Print debugging messages.
- redirect (bool) – Redirect gmsh stout/sterr into seperate files.
- fnStout (str) – File for gmsh stout.
- fnSterr (str) – File for gmsh sterr.
- volSizeMax (float) – Maximum allowed mesh element size.
Returns: Path to mesh file.
Return type: str
-
pyfrp.modules.pyfrp_gmsh_module.
updateBallGeo
(fn, radius, center, run=True, debug=False)¶ Upates parameters in default ball.geo file.
Note
Debug will also activate full debugging output of gmsh. See also http://gmsh.info/doc/texinfo/gmsh.html#Command_002dline-options .
Note
For function to work, parameters in geo file need to be defined as follows:
- radius -> radius
- center -> center_x , center_y
Parameters: - fn (str) – Filepath.
- radius (float) – New ball radius.
- center (list) – New ball center.
Keyword Arguments: - run (bool) – Run gmsh on updated file.
- debug (bool) – Print debugging messages.
Returns: Path to mesh file.
Return type: str
-
pyfrp.modules.pyfrp_gmsh_module.
updateConeGeo
(fn, upperRadius, lowerRadius, height, center, run=True, debug=False)¶ Upates parameters in default cone.geo file.
Note
Debug will also activate full debugging output of gmsh. See also http://gmsh.info/doc/texinfo/gmsh.html#Command_002dline-options .
Note
For function to work, parameters in geo file need to be defined as follows:
- upperRadius -> upper_radius
- lowerRadius -> lower_radius
- slice_height -> slice_height
- center -> center_x , center_y
Parameters: - fn (str) – Filepath.
- upperRadius (float) – New upper cone radius.
- lowerRadius (float) – New lower cone radius.
- height (float) – New cone height.
- center (list) – New cone center.
Keyword Arguments: - run (bool) – Run gmsh on updated file.
- debug (bool) – Print debugging messages.
Returns: Path to mesh file.
Return type: str
-
pyfrp.modules.pyfrp_gmsh_module.
updateCylinderGeo
(fn, radius, height, center, run=True, debug=False)¶ Upates parameters in default cylinder.geo file.
Note
Debug will also activate full debugging output of gmsh. See also http://gmsh.info/doc/texinfo/gmsh.html#Command_002dline-options .
Note
For function to work, parameters in geo file need to be defined as follows:
- radius -> radius
- height -> height
- center -> center_x , center_y
Parameters: - fn (str) – Filepath.
- radius (float) – New cylinder radius.
- height (float) – New cylinder height.
- center (list) – New cylinder center.
Keyword Arguments: - run (bool) – Run gmsh on updated file.
- debug (bool) – Print debugging messages.
Returns: Path to mesh file.
Return type: str
-
pyfrp.modules.pyfrp_gmsh_module.
updateDomeGeo
(fn, radius, slice_height, center, run=False, debug=False)¶ Upates parameters in default dome.geo file.
Note
Debug will also activate full debugging output of gmsh. See also http://gmsh.info/doc/texinfo/gmsh.html#Command_002dline-options .
Note
The way that dome.geo is written, gmsh will automatically compute the dome geometry from slice_height and radius.
Note
For function to work, parameters in geo file need to be defined as follows:
- radius -> radius
- slice_height -> slice_height
- center -> center_x , center_y
Parameters: - fn (str) – Filepath.
- radius (float) – New dome imaging radius.
- slice_height (float) – Height of imaging slice.
- center (list) – New dome center.
Keyword Arguments: - run (bool) – Run gmsh on updated file.
- debug (bool) – Print debugging messages.
Returns: Path to mesh file.
Return type: str
-
pyfrp.modules.pyfrp_gmsh_module.
updateVolSizeGeo
(fn, volSize_px, run=False, debug=False)¶ Upates parameter that defines mesh element volume in .geo file.
Note
Debug will also activate full debugging output of gmsh. See also http://gmsh.info/doc/texinfo/gmsh.html#Command_002dline-options .
Note
For function to work, parameters in geo file need to be defined as follows:
- volSize_px -> volSize_px
Parameters: - fn (str) – Filepath.
- volSize_px (float) – New mesh element size.
Keyword Arguments: - run (bool) – Run gmsh on updated file.
- debug (bool) – Print debugging messages.
Returns: Path to mesh file.
Return type: str
pyfrp.modules.pyfrp_idx_module module¶
Indexing module for PyFRAP toolbox. Mainly contains functions that help finding either
- image indices
- mesh indices
- extended indices
for all types of ROIs, such as
- circular
pyfrp.subclasses.pyfrp_ROI.radialROI
- rectangular
pyfrp.subclasses.pyfrp_ROI.rectangleROI
- quadratic
pyfrp.subclasses.pyfrp_ROI.squarelROI
- polygonial
pyfrp.subclasses.pyfrp_ROI.polyROI
Also provides functions to handle indices in case of quadrant reduction and a powerful suite
of check functions that help to figure out if a list of coordinates is inside a ROI., using
numpy.where
.
-
pyfrp.modules.pyfrp_idx_module.
checkInsideCircle
(x, y, center, radius)¶ Checks if coordinate (x,y) is in circle with given radius and center.
Note
If
x
andy
arefloat
, will returnbool
, otherwisenumpy.ndarray
of booleans.Parameters: - x (numpy.ndarray) – Array of x-coordinates.
- y (numpy.ndarray) – Array of y-coordinates.
- center (numpy.ndarray) – Center of circle.
- radius (float) – Radius of circle.
Returns: True if inside, otherwise False.
Return type: bool
-
pyfrp.modules.pyfrp_idx_module.
checkInsideImg
(x, y, res, offset=[0, 0])¶ Checks if coordinate (x,y) is inside image.
Note
If
x
andy
arefloat
, will returnbool
, otherwisenumpy.ndarray
of booleans.Parameters: - x (numpy.ndarray) – Array of x-coordinates.
- y (numpy.ndarray) – Array of y-coordinates.
- res (int) – Resolution of image (e.g. 512).
Returns: True if inside, otherwise False.
Return type: bool
-
pyfrp.modules.pyfrp_idx_module.
checkInsidePoly
(x, y, poly)¶ Checks if coordinate (x,y) is inside polyogn.
Adapted from http://www.ariel.com.au/a/python-point-int-poly.html.
Note
If
x
andy
arefloat
, will returnbool
, otherwisenumpy.ndarray
of booleans.Parameters: - poly (list) – List of (x,y)-coordinates of corners.
- x (float) – x-coordinate.
- y (float) – y-coordinate.
Returns: True if inside, otherwise False.
Return type: bool
-
pyfrp.modules.pyfrp_idx_module.
checkInsidePolyVec
(x, y, poly)¶ Checks if coordinate (x,y) is inside polyogn, checks first if vector or just value.
Note
If
x
andy
arefloat
, will returnbool
, otherwisenumpy.ndarray
of booleans.Parameters: - poly (list) – List of (x,y)-coordinates of corners.
- x (numpy.ndarray) – Array of x-coordinates.
- y (numpy.ndarray) – Array of y-coordinates.
Returns: True if inside, otherwise False.
Return type: bool
-
pyfrp.modules.pyfrp_idx_module.
checkInsideRectangle
(x, y, offset, sidelengthX, sidelengthY)¶ Checks if coordinate (x,y) is in rectangle with given offset and sidelength.
Note
If
x
andy
arefloat
, will returnbool
, otherwisenumpy.ndarray
of booleans.Note
Offset is set to be bottom left corner.
Parameters: - x (numpy.ndarray) – Array of x-coordinates.
- y (numpy.ndarray) – Array of y-coordinates.
- offset (numpy.ndarray) – Offset of rectangle.
- sidelengthX (float) – Sidelength in x-direction.
- sidelengthY (float) – Sidelength in y-direction.
Returns: True if inside, otherwise False.
Return type: bool
-
pyfrp.modules.pyfrp_idx_module.
checkInsideSquare
(x, y, offset, sidelength)¶ Checks if coordinate (x,y) is in square with given offset and sidelength.
Note
If
x
andy
arefloat
, will returnbool
, otherwisenumpy.ndarray
of booleans.Note
Offset is set to be bottom left corner.
Parameters: - x (numpy.ndarray) – Array of x-coordinates.
- y (numpy.ndarray) – Array of y-coordinates.
- offset (numpy.ndarray) – Offset of square.
- sidelength (float) – Sidelength.
Returns: True if inside, otherwise False.
Return type: bool
-
pyfrp.modules.pyfrp_idx_module.
checkQuad
(x, y, res)¶ Checks if coordinate (x,y) is inside first quadrant.
Note
If
x
andy
arefloat
, will returnbool
, otherwisenumpy.ndarray
of booleans.Parameters: - x (float) – x-coordinate.
- y (float) – y-coordinate.
- res (int) – Resolution of image (e.g. 512).
Returns: True if inside, otherwise False.
Return type: bool
-
pyfrp.modules.pyfrp_idx_module.
checkSquCentered
(offset, sidelength, res)¶ Checks if square is centered in image.
Note
Need a correction by .5 because there is a difference between pixels and coordinates.
Parameters: - offset (numpy.ndarray) – Offset of square.
- sidelength (float) – Sidelength.
- res (int) – Resolution of image (e.g. 512).
Returns: True if centered, otherwise False.
Return type: bool
-
pyfrp.modules.pyfrp_idx_module.
checkSquareCenteredFromInd
(ind_sq_x, ind_sq_y, res)¶ Checks if square described by indices is cenntered in image.
Parameters: - ind_sq_x (list) – Image indices in x-direction.
- ind_sq_y (list) – Image indices y x-direction.
- res (int) – Resolution of image (e.g. 512).
Returns: True if centered, otherwise False.
Return type: bool
-
pyfrp.modules.pyfrp_idx_module.
checkSquareSize
(ind_sq_x, ind_sq_y, sidelength)¶ Checks if square described by indices has right size.
Parameters: - ind_sq_x (list) – Image indices in x-direction.
- ind_sq_y (list) – Image indices y x-direction.
- sidelength (float) – Sidelength of square.
Returns: True if equal size, otherwise False.
Return type: bool
-
pyfrp.modules.pyfrp_idx_module.
getAllIdxImg
(res, debug=False)¶ Returns all indices of image.
Parameters: res (int) – Resolution of image (e.g. 512). Keyword Arguments: debug (bool) – Print debugging messages. Returns: Tuple containing: - indX (list): List of indices inside image in x-direction.
- indY (list): List of indices inside image in y-direction.
Return type: tuple
-
pyfrp.modules.pyfrp_idx_module.
getCenterOfMass
(xs, axis=0, masses=None)¶ Computes center of mass of a given set of points.
Note
If
masses==None
, then all points are assigned \(m_i=1\).Center of mass is computed by:
\[C=\frac{1}{M}\sum\limits_i m_i (x_i)^T\]where
\[M = \sum\limits_i m_i\]Parameters: xs (numpy.ndarray) – Coordinates. Keyword Arguments: masses (numpy.ndarray) – List of masses. Returns: Center of mass. Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_idx_module.
getCircleIdxImg
(center, radius, res, debug=False)¶ Returns all indices of image that lie within given circle.
Parameters: - center (numpy.ndarray) – Center of circle.
- radius (float) – Radius of circle.
- res (int) – Resolution of image (e.g. 512).
Keyword Arguments: debug (bool) – Print debugging messages.
Returns: Tuple containing:
- ind_circ_x (list): List of indices inside circle in x-direction.
- ind_circ_y (list): List of indices inside circle in y-direction.
Return type: tuple
-
pyfrp.modules.pyfrp_idx_module.
getCircleIdxMesh
(center, radius, mesh, zmin='-inf', zmax='inf', debug=False)¶ Returns all indices of mesh that lie within given circle and between
zmin
andzmax
.Parameters: - center (numpy.ndarray) – Center of circle.
- radius (float) – Radius of circle.
- mesh (fipy.Gmsh3DImporter) – Mesh.
Keyword Arguments: - zmin (float) – Minimal z-coordinate.
- zmax (float) – Maximal z-coordinate.
- debug (bool) – Print debugging messages.
Returns: List of mesh indices inside circle.
Return type: list
-
pyfrp.modules.pyfrp_idx_module.
getCommonExtendedPixels
(ROIs, res, debug=False, procedures=None)¶ Finds theoretical pixels that could be filled up with rim concentration for a list of
pyfrp.subclasses.pyfrp_ROI.ROI
ROIs.The
procedures
input is only necessary if ROI is apyfrp.subclasses.pyfrp_ROI.customROI
, combining multiple ROIs via addition/substraction.Parameters: - ROIs (list) – List of ROIs.
- res (int) – Resolution of image (e.g. 512).
Keyword Arguments: - debug (bool) – Print debugging messages.
- procedures (list) – List of addition/substraction procedures.
Returns: Tuple containing:
- indX (list): List of x-indices.
- indY (list): List of y-indices.
Return type: tuple
-
pyfrp.modules.pyfrp_idx_module.
getCommonXYExtend
(ROIs, debug=False)¶ Finds common x-y-extend of a list of
pyfrp.subclasses.pyfrp_ROI.ROI
ROIs..Parameters: ROIs (list) – List of ROIs. Returns: Tuple containing: - xExtend (list):
[minx,maxx]
. - yExtend (list):
[miny,maxy]
.
Return type: tuple - xExtend (list):
-
pyfrp.modules.pyfrp_idx_module.
getExtendedPixelsCircle
(center, radius, res, debug=False)¶ Finds theoretical pixels that could be filled up with rim concentration for a circle.
Parameters: - center (numpy.ndarray) – Center of circle.
- radius (float) – Radius of circle.
- res (int) – Resolution of image (e.g. 512).
Keyword Arguments: debug (bool) – Print debugging messages.
Returns: Tuple containing:
- indX (list): List of x-indices.
- indY (list): List of y-indices.
Return type: tuple
-
pyfrp.modules.pyfrp_idx_module.
getExtendedPixelsPolygon
(corners, res, debug=False)¶ Finds theoretical pixels that could be filled up with rim concentration for a polygon.
Parameters: - corners (list) – List of (x,y)-coordinates of corners.
- res (int) – Resolution of image (e.g. 512).
Keyword Arguments: debug (bool) – Print debugging messages.
Returns: Tuple containing:
- indX (list): List of x-indices.
- indY (list): List of y-indices.
Return type: tuple
-
pyfrp.modules.pyfrp_idx_module.
getExtendedPixelsRectangle
(offset, sidelengthX, sidelengthY, res, debug=False)¶ Finds theoretical pixels that could be filled up with rim concentration for a rectangle.
Parameters: - offset (numpy.ndarray) – Offset of rectangle.
- sidelengthX (float) – Sidelength in x-direction.
- sidelengthY (float) – Sidelength in y-direction.
- res (int) – Resolution of image (e.g. 512).
Keyword Arguments: debug (bool) – Print debugging messages.
Returns: Tuple containing:
- indX (list): List of x-indices.
- indY (list): List of y-indices.
Return type: tuple
-
pyfrp.modules.pyfrp_idx_module.
getExtendedPixelsSquare
(offset, sidelength, res, debug=False)¶ Finds theoretical pixels that could be filled up with rim concentration for a square.
Parameters: - offset (numpy.ndarray) – Offset of square.
- sidelength (float) – Sidelength.
- res (int) – Resolution of image (e.g. 512).
Keyword Arguments: debug (bool) – Print debugging messages.
Returns: Tuple containing:
- indX (list): List of x-indices.
- indY (list): List of y-indices.
Return type: tuple
-
pyfrp.modules.pyfrp_idx_module.
getPolyIdxImg
(corners, res, debug=False)¶ Returns all indices of image that lie within given polygon.
Parameters: - corners (list) – List of (x,y)-coordinates of corners.
- res (int) – Resolution of image (e.g. 512).
Keyword Arguments: debug (bool) – Print debugging messages.
Returns: Tuple containing:
- indX (list): List of indices inside polygon in x-direction.
- indY (list): List of indices inside polygon in y-direction.
Return type: tuple
-
pyfrp.modules.pyfrp_idx_module.
getPolyIdxMesh
(corners, mesh, zmin='-inf', zmax='inf', debug=False)¶ Returns all indices of mesh that lie within given polygon and between
zmin
andzmax
.Parameters: - corners (list) – List of (x,y)-coordinates of corners.
- mesh (fipy.Gmsh3DImporter) – Mesh.
Keyword Arguments: - zmin (float) – Minimal z-coordinate.
- zmax (float) – Maximal z-coordinate.
- debug (bool) – Print debugging messages.
Returns: List of mesh indices inside polygon.
Return type: list
-
pyfrp.modules.pyfrp_idx_module.
getRectangleIdxImg
(offset, sidelengthX, sidelengthY, res, debug=False)¶ Returns all indices of image that lie within given rectangle.
Note
Offset is set to be bottom left corner.
Parameters: - offset (numpy.ndarray) – Offset of rectangle.
- sidelengthX (float) – Sidelength in x-directiion.
- sidelengthY (float) – Sidelength in y-directiion.
- res (int) – Resolution of image (e.g. 512).
Keyword Arguments: debug (bool) – Print debugging messages.
Returns: Tuple containing:
- indX (list): List of indices inside rectangle in x-direction.
- indY (list): List of indices inside rectangle in y-direction.
Return type: tuple
-
pyfrp.modules.pyfrp_idx_module.
getRectangleIdxMesh
(sidelengthX, sidelengthY, offset, mesh, zmin='-inf', zmax='inf', debug=False)¶ Returns all indices of mesh that lie within given rectangle and between
zmin
andzmax
.Note
Offset is set to be bottom left corner.
Parameters: - offset (numpy.ndarray) – Offset of rectangle.
- sidelengthX (float) – Sidelength in x-directiion.
- sidelengthY (float) – Sidelength in y-directiion.
- mesh (fipy.Gmsh3DImporter) – Mesh.
Keyword Arguments: - zmin (float) – Minimal z-coordinate.
- zmax (float) – Maximal z-coordinate.
- debug (bool) – Print debugging messages.
Returns: List of mesh indices inside rectangle.
Return type: list
-
pyfrp.modules.pyfrp_idx_module.
getSliceIdxMesh
(z, zmin, zmax, debug=False)¶ Returns all indices of mesh that lie within given slice between
zmin
andzmax
.Parameters: - z (float) – z-coordinates of mesh.
- zmin (float) – Minimal z-coordinate.
- zmax (float) – Maximal z-coordinate.
Keyword Arguments: debug (bool) – Print debugging messages.
Returns: List of mesh indices inside slice.
Return type: list
-
pyfrp.modules.pyfrp_idx_module.
getSquareIdxImg
(offset, sidelength, res, debug=False)¶ Returns all indices of image that lie within given square.
Note
Offset is set to be bottom left corner.
Parameters: - offset (numpy.ndarray) – Offset of square.
- sidelengtX (float) – Sidelength.
- res (int) – Resolution of image (e.g. 512).
Keyword Arguments: debug (bool) – Print debugging messages.
Returns: Tuple containing:
- indX (list): List of indices inside square in x-direction.
- indY (list): List of indices inside square in y-direction.
Return type: tuple
-
pyfrp.modules.pyfrp_idx_module.
getSquareIdxMesh
(sidelength, offset, mesh, zmin='-inf', zmax='inf', debug=False)¶ Returns all indices of mesh that lie within given square and between
zmin
andzmax
.Note
Offset is set to be bottom left corner.
Parameters: - offset (numpy.ndarray) – Offset of square.
- sidelength (float) – Sidelength.
- mesh (fipy.Gmsh3DImporter) – Mesh.
Keyword Arguments: - zmin (float) – Minimal z-coordinate.
- zmax (float) – Maximal z-coordinate.
- debug (bool) – Print debugging messages.
Returns: List of mesh indices inside square.
Return type: list
-
pyfrp.modules.pyfrp_idx_module.
idx2QuadImg
(indX, indY, res, debug=False)¶ Reduces indices found for whole domain to first quadrant.
Note
Need a correction by .5 because there is a difference between pixels and coordinates.
Parameters: - indX (list) – List of indices in x-direction.
- indY (list) – List of indices in y-direction.
- res (int) – Resolution of image (e.g. 512).
Keyword Arguments: debug (bool) – Print debugging messages.
Returns: Tuple containing:
- indXQuad (list): List of reduced indices.
- indYQuad (list): List of reduced indices.
Return type: tuple
-
pyfrp.modules.pyfrp_idx_module.
ind2mask
(vals, ind_x, ind_y, val)¶ Converts indices lists into mask.
Parameters: - vals (numpy.ndarray) – Array on which to be masked.
- ind_x (list) – Indices in x-direction.
- ind_y (list) – Indices in y-direction.
- val (float) – Value that is assigned to pixels in indices-lists.
Returns: Masked array.
Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_idx_module.
mask2ind
(mask, res)¶ Converts mask into indices list.
Parameters: - mask (numpy.ndarray) – Mask array.
- res (int) – Resolution of image (e.g. 512).
Returns: Tuple containing:
- indX_new (list): List of x-indices.
- indY_new (list): List of y-indices.
Return type: tuple
-
pyfrp.modules.pyfrp_idx_module.
maskMeshByDistance
(x, y, d, grid)¶ Filters all (x,y) coordinates that are more than d in meshgrid given some actual coordinates (x,y).
Parameters: - x (numpy.ndarray) – x-coordinates.
- y (numpy.ndarray) – y-coordinates.
- d (float) – Maximum distance.
- grid (numpy.ndarray) – Numpy meshgrid.
Returns: List of booleans.
Return type: idxs (list)
-
pyfrp.modules.pyfrp_idx_module.
nearestNeighbour3D
(xi, yi, zi, x, y, z, k=1, minD=None)¶ Finds k nearest neighbour to points.
Example:
>>> from pyfrp.modules import pyfrp_idx_module >>> import numpy as np >>> import matplotlib.pyplot as plt
>>> N=50
>>> x=np.random.random(N) >>> y=np.random.random(N) >>> z=np.random.random(N)
>>> xi=[0.,1.] >>> yi=[0.,1.] >>> zi=[0.,1.]
>>> idx,dist=pyfrp_idx_module.nearestNeighbour3D(xi,yi,zi,x,y,z,k=1)
>>> fig=plt.figure() >>> ax=fig.add_subplot(111,projection='3d') >>> ax.scatter(x,y,z,color='k')
>>> ax.scatter(x[idx[0]],y[idx[0]],z[idx[0]],color='b',s=50) >>> ax.scatter(x[idx[1]],y[idx[1]],z[idx[1]],color='r',s=50) >>> ax.scatter(xi,yi,zi,color='g',s=50)
>>> plt.show()
Note
To avoid that the a point is nearest neighbour to itself, one can choose minD=0 to avoid that points with distances
0
are returned. Note, if this could be the possibility, one might have at leastk=2
to avoid an empty return.Parameters: - xi (numpy.ndarray) – x-coordinates of points to find neighbours to.
- yi (numpy.ndarray) – x-coordinates of points to find neighbours to.
- zi (numpy.ndarray) – x-coordinates of points to find neighbours to.
- x (numpy.ndarray) – x-coordinates of possible neighbours.
- y (numpy.ndarray) – x-coordinates of possible neighbours.
- z (numpy.ndarray) – x-coordinates of possible neighbours.
Keyword Arguments: - k (int) – Number of neighbours to find per point.
- minD (float) – Minimum distance nearest neighbour must be away.
Returns: Tuple containing:
- indexes (list): Indices of k -closest neighbours per point.
- dists (list): Distances of k -closest neighbours per point.
Return type: tuple
-
pyfrp.modules.pyfrp_idx_module.
regions2quad
(inds, res, debug=False)¶ Reduces indices of regions specified in
inds
found for whole domain to first quadrant.Parameters: - inds (list) – List of indices-list doubles.
- res (int) – Resolution of image (e.g. 512).
Keyword Arguments: debug (bool) – Print debugging messages.
Returns: List of reduced indices-list doubles.
Return type: list
-
pyfrp.modules.pyfrp_idx_module.
remRepeatedImgIdxs
(idxX, idxY, debug=False)¶ Remove repeated indices tupels from index lists for images.
Parameters: - idxX (list) – List of x-indices.
- idxY (list) – List of y-indices.
Keyword Arguments: debug (bool) – Print debugging messages.
Returns: Tuple containing:
- idxX (list): Filtred list of x-indices.
- idxY (list): Filtered list of y-indices.
Return type: tuple
-
pyfrp.modules.pyfrp_idx_module.
triangulatePoly
(coords, addPoints=False, iterations=2, debug=False)¶ Triangulates a polygon with given coords using a Delaunay triangulation.
Uses http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.Delaunay.html#scipy.spatial.Delaunay to calculate triangulation, then filters the triangles actually lying within the polygon.
Parameters: coords (list) – List of (x,y)-coordinates of corners.
Keyword Arguments: - addPoints (bool) – Allow incremental addition of points.
- iterations (int) – Number of iterations of additional point adding.
- debug (boo) – Print debugging messages.
Returns: Tuple containing:
- triFinal (list): List of found triangles.
- coordsTri (list): List of vertex coordinates.
Return type: tuple
pyfrp.modules.pyfrp_img_module module¶
Image analysis module for PyFRAP toolbox. This is one of the key modules of PyFRAP, gathering all necessary image manipulation and reading functions used by PyFRAP. Mainly focuses on:
- Analyzing complete FRAP datasets as specified in a
pyfrp.subclasses.pyfrp_analysis.analysis
instance.- Reading concentrations from images over specific regions as specified in
pyfrp.subclasses.pyfrp_ROI.ROI
instances.- Handling and saving rim concentrations.
- Image manipulation through filters/quadrant reduction.
- Image plotting and histograms.
- Fiji wrapping.
-
pyfrp.modules.pyfrp_img_module.
analyzeDataset
(analysis, signal=None, embCount=None, debug=False, debugAll=False, showProgress=True)¶ Main dataset analysis function doing the following steps.
- Reset all data arrays for all ROIs.
- Computes flattening/norm/background mask if necessary.
- Loops through images, processing images and computing mean concentraions per ROI.
- Showing final debugging plots if selected.
Parameters: analysis (pyfrp.subclasses.pyfrp_analysis) – Object containing all necessary information for analysis.
Keyword Arguments: - signal (PyQt4.QtCore.pyqtSignal) – PyQT signal to send progress to GUI.
- embCount (int) – Counter of counter process if multiple datasets are analyzed.
- debug (bool) – Print final debugging messages and show debugging plots.
- debugAll (bool) – Print debugging messages and show debugging plots of each step.
- showProgress (bool) – Print out progress.
Returns: Performed analysis.
Return type:
-
pyfrp.modules.pyfrp_img_module.
computeFlatMask
(img, dataOffset)¶ Computes flattening mask from image.
Parameters: - img (numpy.ndarray) – Image to be used.
- dataOffset (int) – Offset used.
Returns: Flattening mask.
Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_img_module.
computeMeanImg
(fnFolder, fileList, dataEnc, median=False)¶ Computes Mean Image from a list of files.
Parameters: - fnFolder (str) – Path to folder containing files.
- fileList (list) – List of file names in fnFolder.
- dataEnc (str) – Encoding of images, e.g. uint16.
Keyword Arguments: median (bool) – Apply median filter per image.
Returns: Mean image.
Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_img_module.
computeRadialProfile
(img, center)¶ Computes radial profile of image from center.
Parameters: - img (numpy.ndarray) – Image to be profiled
- center (list) – Center of image.
Returns: Tuple containing:
- r (numpy.ndarray): Array of radii.
- v (numpy.ndarray): Array of corresponding image values.
Return type: tuple
-
pyfrp.modules.pyfrp_img_module.
convSkio2NP
(img)¶ Returns mean concentration over given indices.
Parameters: - idxX (list) – x-indices of pixels used.
- idxY (list) – y-indices of pixels used.
- vals (numpy.ndarray) – Input image.
Keyword Arguments: debug (bool) – Print debugging messages.
Returns: Mean concentration.
Return type: float
-
pyfrp.modules.pyfrp_img_module.
dist
(p1, p2)¶ Computes euclidean distance between two points p1 and p2.
-
pyfrp.modules.pyfrp_img_module.
extractCZI
(folder, fijiBin=None, macroPath=None, debug=False, batch=True)¶ Converts all czi files in folder to tif files using Fiji.
Parameters: folder (str) – Path to folder containing czi files
Keyword Arguments: - fijiBin (str) – Path to fiji binary
- macroPath (str) – Path to fiji macro
- debug (bool) – Print out debugging messages
- batch (bool) – Execute in batch mode.
Returns: Returns 0 if success, -1 if error
Return type: int
-
pyfrp.modules.pyfrp_img_module.
extractLSM
(folder, fijiBin=None, macroPath=None, debug=False, batch=True)¶ Converts all lsm files in folder to tif files using Fiji.
Parameters: folder (str) – Path to folder containing lsm files
Keyword Arguments: - fijiBin (str) – Path to fiji binary
- macroPath (str) – Path to fiji macro
- debug (bool) – Print out debugging messages
- batch (bool) – Execute in batch mode.
Returns: Returns 0 if success, -1 if error
Return type: int
-
pyfrp.modules.pyfrp_img_module.
extractMicroscope
(folder, ftype, fijiBin=None, macroPath=None, debug=False, batch=True)¶ Converts all microscopy files of type ftype in folder to files using Fiji.
Parameters: - folder (str) – Path to folder containing czi files
- ftype (str) – Type of microscopy file, such as lsm or czi
Keyword Arguments: - fijiBin (str) – Path to fiji binary
- macroPath (str) – Path to fiji macro
- debug (bool) – Print out debugging messages
- batch (bool) – Execute in batch mode.
Returns: Returns 0 if success, -1 if error
Return type: int
-
pyfrp.modules.pyfrp_img_module.
findMinOffset
(fnFolder, fileList, dataEnc, oldOffset=None, defaultAdd=1.0, debug=False)¶ Simple function that loops through all images in file list and returns minimum integer that needs to be added such that all pixels are positiv.
Parameters: - fnFolder (str) – Path to folder containing files.
- fileList (list) – List of file names in fnFolder.
- dataEnc (str) – Encoding of images, e.g. uint16.
Keyword Arguments: - oldOffset (int) – Take some other offset into account.
- defaultAdd (int) – Default value added to minimal offset.
- debug (bool) – Show debugging outputs.
Returns: Minimal Offset
Return type: int
-
pyfrp.modules.pyfrp_img_module.
findProblematicNormingPixels
(img, imgPre, dataOffset, axes=None, debug=False)¶ Checks which pixels are problematic for norming.
Note that function will temporarily set >>> np.errstate(divide=’raise’) so numpy RuntimeWarning actually gets raised instead of just printed.
Parameters: - img (numpy.ndarray) – Image to be normed.
- imgPre (numpy.ndarray) – Image to be normed.
- dataOffset (int) – Offset used for norming.
Keyword Arguments: - axes (list) – List with matplotlib axes used for plotting. If not specified,
- generate new ones. (will) –
- debug (bool) – Show debugging outputs and plots.
Returns: Binary mask of problematic pixels.
Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_img_module.
fixedThresh
(img, thresh, smaller=False, fill=<Mock name='mock.nan' id='140635021242256'>)¶ Apply fixed threshold to image and fill pixels with values greater than thresh with fill value .
Parameters: - img (numpy.ndarray) – Image for thresholding.
- thresh (float) – Threshold used.
Keyword Arguments: - fill (float) – Fill values for pixels that are smaller or greater than thresh.
- smaller (bool) – Apply fill to pixels smaller or greater than thresh.
Returns: Tuple containing:
- img (numpy.ndarray): Output image.
- indX (numpy.ndarray): x-indices of pixels that where thresholded.
- indY (numpy.ndarray): y-indices of pixels that where thresholded.
Return type: tuple
-
pyfrp.modules.pyfrp_img_module.
flattenImg
(img, mask)¶ Flattens image with flattening mask.
-
pyfrp.modules.pyfrp_img_module.
flipQuad
(img, debug=False, testimg=False)¶ Flip image into quaddrant.
Parameters: img (numpy.ndarray) – Input image.
Keyword Arguments: - debug (bool) – Print debugging messages and show debugging plots.
- testimg (bool) – Check with test image if flip works properly
Returns: Flipped image.
Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_img_module.
gaussianFilter
(img, sigma=2.0, debug=False, axes=None)¶ Applies gaussian filter to image.
Parameters: img (numpy.ndarray) – Input image.
Keyword Arguments: - sigma (float) – Standard deviation of gaussian kernel applied.
- axes (list) – List of matplotlib axes used for plotting. If not specified, will generate new ones.
- debug (bool) – Print debugging messages and show debugging plots.
Returns: Processed image.
Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_img_module.
genFakeIC
(res, valIn, valOut, offset, sidelength, radius, center, fill=0.0, debug=False)¶ Create fake image consisting of circular ROI with pixel value valOut and a square ROI centered inside circle with pixel value valIn.
Note
If
fill=np.nan
, thenpyfrp.modules.pyfrp_sim_module.applyInterpolatedICs()
will not work.Parameters: - res (int) – Resolution of desired image.
- valIn (float) – Value inside bleached region.
- valOut (float) – Value outside of bleached region.
- offset (numpy.ndarray) – Offset of bleached square.
- sidelength (float) – Sidelength of bleached square.
- radius (float) – Radius of circular ROI.
- center (list) – Center of circular ROI.
Keyword Arguments: - fill (float) – Fill value for everything outside of circular domain.
- debug (bool) – Print debugging messages.
Returns: Generated image.
Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_img_module.
genFakeSigmoidIC
(res, valIn, valOut, rJump, rate, radius, center, fill=0.0, debug=False)¶ Create fake image consisting of circular ROI with pixel value valOut that decays with a sigmoid function towards center.
Note
If
fill=np.nan
, thenpyfrp.modules.pyfrp_sim_module.applyInterpolatedICs()
will not work.Parameters: - res (int) – Resolution of desired image.
- valIn (float) – Value inside bleached region.
- valOut (float) – Value outside of bleached region.
- radius (float) – Radius of circular ROI.
- center (list) – Center of circular ROI.
- rate (float) – Decay rate of sigmoid.
- rJump (float) – Radius at which decay happens.
Keyword Arguments: - fill (float) – Fill value for everything outside of circular domain.
- debug (bool) – Print debugging messages.
Returns: Generated image.
Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_img_module.
getCommonRange
(imgs)¶ Finds common range of list of images.
Parameters: imgs (list) – List of images. Returns: Tuple containing: - minVal (float): Lowest value over all images.
- maxVal (float): Largest value over all images.
Return type: tuple
-
pyfrp.modules.pyfrp_img_module.
getImgSmoothness
(arr)¶ Returns smoothness of img.
Smoothness \(s\) is computed as:
\[s=\frac{d_{\mathrm{max}}}{\bar{d}}\]where \(d_{\mathrm{max}}\) is the maximum derivation from the nearest neighbour over the whole array, and \(\bar{d}\) the average derivation.
Parameters: arr (numpy.ndarray) – Some image. Returns: Tuple containing: - s (float): Smoothmess coefficient.
- dmax(float): Maximum diff.
Return type: tuple
-
pyfrp.modules.pyfrp_img_module.
getIntRangeDtype
(dtype)¶ Returns range of int based dtype.
-
pyfrp.modules.pyfrp_img_module.
getMaxRangeChannel
(img, debug=False)¶ Loops through all channels of image and returns channel of image with maximal range.
Parameters: img (numpy.ndarray) – Input image. Keyword Arguments: debug (bool) – Print debugging messages. Returns: - Tuple containing:
- img (numpy.ndarray): Monochromatic image.
- ind_max (int): Index of channel chosen.
Return type: tuple
-
pyfrp.modules.pyfrp_img_module.
getMeanIntensitiesImgs
(fnFolder, fileList, dataEnc)¶ Reads all images in folder, returns mean intensity vector.
Parameters: - fnFolder (str) – Path to folder containing files.
- fileList (list) – List of file names in fnFolder.
- dataEnc (str) – Encoding of images, e.g. uint16.
Returns: Array of mean intensities per image.
Return type: list
-
pyfrp.modules.pyfrp_img_module.
getRimConc
(ROIs, img, debug=False)¶ Computes mean rim concentration from ROIs that have useForRim flag on.
Parameters: - ROIs (list) – List of pyfrp.subclasses.pyfrp_ROI objects.
- img (numpy.ndarray) – Input image.
Keyword Arguments: debug (bool) – Print debugging messages and show debugging plots.
Returns: Rim concentration.
Return type: float
-
pyfrp.modules.pyfrp_img_module.
imgHist
(img, binMin=0, binMax=65535, nbins=256, binSize=1, binsFit=True, fixSize=False, density=False)¶ Creates histogram for image with some good default settings.
Parameters: img (numpy.ndarray) – Input image.
Keyword Arguments: - nbins (int) – Number of bins of histogram.
- binSize (int) – Size of bins.
- binMin (float) – Minimum value of bins.
- binMax (float) – Maximum value of bins.
- binsFit (bool) – Fits bin range properly around range of image.
- fixSize (bool) – Use binSize for fixed bin size.
- density (bool) – Normalize histogram as probability density function.
Returns: Tuple containing:
- bins (float): Bin array of histogram.
- hist (float): Histogram array.
- w (float): Width of bins.
Return type: tuple
-
pyfrp.modules.pyfrp_img_module.
loadImg
(fn, enc, dtype='float')¶ Loads image from filename fn with encoding enc and returns it as with given dtype.
Parameters: - fn (str) – File path.
- enc (str) – Image encoding, e.g. ‘uint16’.
Keyword Arguments: dtype (str) – Datatype of pixels of returned image.
Returns: Loaded image.
Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_img_module.
meanConc
(idxX, idxY, vals, debug=False)¶ Returns mean concentration over given indices.
Parameters: - idxX (list) – x-indices of pixels used.
- idxY (list) – y-indices of pixels used.
- vals (numpy.ndarray) – Input image.
Keyword Arguments: debug (bool) – Print debugging messages.
Returns: Mean concentration.
Return type: float
-
pyfrp.modules.pyfrp_img_module.
meanExtConc
(idxX, idxY, img, concRim, numExt, addRimImg, debug=False)¶ Returns mean concentration, taking potential pixels outside of image into account.
Parameters: - idxX (list) – x-indices of pixels used.
- idxY (list) – y-indices of pixels used.
- img (numpy.ndarray) – Input image.
- concRim (float) – Rim concentration applied to pixels outside of image.
- numExt (int) – Number of pixels outside of image.
- addRimImg (bool) – Add rim concentraion.
Keyword Arguments: debug (bool) – Print debugging messages.
Returns: Mean extendended concentration.
Return type: float
-
pyfrp.modules.pyfrp_img_module.
medianFilter
(img, radius=1, debug=False, dtype='uint16', scaleImg=False, method='scipy', axes=None)¶ Applies median filter to image.
Note
Skimage algorithm requires images to be scaled up into 16bit range.
Parameters: img (numpy.ndarray) – Input image.
Keyword Arguments: - radius (int) – Odd integer defining median kernel size.
- axes (list) – List of matplotlib axes used for plotting. If not specified, will generate new ones.
- debug (bool) – Print debugging messages and show debugging plots.
- dtype (str) – Optimal image dtype necessary for scaling.
- scaleImg (bool) – Scale image to full range of dtype.
- method (str) – Median algorithm used (scipy/skimage).
Returns: Processed image.
Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_img_module.
normImg
(img, imgPre, dataOffset=1.0, debug=False)¶ Norms image by preimage.
Parameters: - img (numpy.ndarray) – Input image.
- imgPre (numpy.ndarray) – Norming mask.
Keyword Arguments: - dataOffset (float) – Offset used for norming.
- debug (bool) – Print debugging messages and show debugging plots.
Returns: Processed image.
Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_img_module.
otsuImageJ
(img, maxVal, minVal, debug=False)¶ Python implementation of Fiji’s Otsu algorithm.
See also http://imagej.nih.gov/ij/source/ij/process/AutoThresholder.java.
Parameters: - img (numpy.ndarray) – Image as 2D-array.
- maxVal (int) – Value assigned to pixels above threshold.
- minVal (int) – Value assigned to pixels below threshold.
Keyword Arguments: debug (bool) – Show debugging outputs and plots.
Returns: Tuple containing:
- kStar (int): Optimal threshold
- binImg (np.ndarray): Binary image
Return type: tuple
-
pyfrp.modules.pyfrp_img_module.
plotRadialHist
(img, center, nbins=10, byMean=True, axes=None, color='r', linestyle='-', fullOutput=False, maxR=None, plotBinSize=False, label='', legend=False, linewidth=1.0)¶ Plots radial histogram of image from center.
Example:
>>> axes=pyfrp_img_module.plotRadialHist(emb.simulation.ICimg,emb.geometry.getCenter(),nbins=100)
Parameters: - img (numpy.ndarray) – Image to be profiled
- center (list) – Center of image.
Keyword Arguments: - nbins (int) – Number of bins of histogram.
- byMean (bool) – Norm bins by number of items in bin.
- maxR (float) – Maximum radius considered.
- plotBinSize (bool) – Include number of items in bin on secondary axis.
- axes (matplotlib.axes) – Matplotlib axes used for plotting. If not specified, will generate new one.
- color (str) – Color of plot.
- linestyle (str) – Linestyle of plot.
- fullOutput (bool) – Also return result arrays from radialImgHist ?
- linewidth (float) – Linewidth of plot.
Returns: Tuple containing:
- ax (matplotlib.axes): Matplotlib axes.
- ax2 (matplotlib.axes): Matplotlib axes for secondary axes. None if plotBinSize==False
- bins (numpy.ndarray): Bin vector.
- binsMid (numpy.ndarray): Array of midpoints of bins.
- histY (numpy.ndarray): Array of number of items per bin.
- binY (numpy.ndarray): Array of average value per bin.
Return type: tuple
-
pyfrp.modules.pyfrp_img_module.
plotRadialProfile
(img, center, ax=None, color='r', linestyle='-', fullOutput=False, linewidth=1.0)¶ Plots radial profile of image from center.
Example:
>>> ax=pyfrp_img_module.plotRadialProfile(emb.simulation.ICimg,emb.geometry.getCenter(),color='g')
Parameters: - img (numpy.ndarray) – Image to be profiled
- center (list) – Center of image.
Keyword Arguments: - ax (matplotlib.axes) – Matplotlib axes used for plotting. If not specified, will generate new one.
- color (str) – Color of plot.
- linestyle (str) – Linestyle of plot.
- fullOutput (bool) – Also return result arrays from computeRadialProfile ?
- linewidth (float) – Linewidth of plot.
Returns: Tuple containing:
- ax (matplotlib.axes): Matplotlib axes.
- r (numpy.ndarray): Array of radii.
- v (numpy.ndarray): Array of corresponding image values.
Return type: tuple
-
pyfrp.modules.pyfrp_img_module.
processImg
(img, processDic, flatteningMask, bkgdMask, preMask, dataOffset=1.0, axes=None, debug=False)¶ Main image processing function containing the following steps:
- Quadrant reduction.
- Median filter.
- Gaussian filter.
- Norming.
- Background substraction.
- Flattening.
Parameters: - img (numpy.ndarray) – Input image.
- processDic (dict) – Dictionary defining what to do. See also pyfrp.subclasses.pyfrp_analysis .
- flatteningMask (np.ndarray) – Flattening mask that will be used if flattening is selected.
- bkgdMask (numpy.ndarray) – Background mask that will be used if background substraction is selected.
- preMask (numpy.ndarray) – Preimage mask that will be used if norming is selected.
Keyword Arguments: - dataOffset (float) – Offset used for norming.
- axes (list) – List of matplotlib axes used for plotting. If not specified, will generate new ones.
- debug (bool) – Print debugging messages and show debugging plots.
Returns: Processed image.
Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_img_module.
radialImgHist
(img, center, nbins=10, byMean=True, maxR=None)¶ Computes radial histogram of image from center.
Parameters: - img (numpy.ndarray) – Image to be profiled
- center (list) – Center of image.
Keyword Arguments: - nbins (int) – Number of bins of histogram.
- byMean (bool) – Norm bins by number of items in bin.
- maxR (float) – Maximum radius considered.
Returns: Tuple containing:
- bins (numpy.ndarray): Bin vector.
- binsMid (numpy.ndarray): Array of midpoints of bins.
- histY (numpy.ndarray): Array of number of items per bin.
- binY (numpy.ndarray): Array of average value per bin.
Return type: tuple
-
pyfrp.modules.pyfrp_img_module.
runFijiMacro
(macroPath, macroArgs, fijiBin=None, debug=False, batch=True)¶ Runs Fiji Macro.
Parameters: - macroPath (str) – Path to fiji macro
- macroArgs (str) – Arguments being passed to Fiji macro
Keyword Arguments: - fijiBin (str) – Path to fiji binary
- debug (bool) – Print out debugging messages
- batch (bool) – Execute in batch mode.
Returns: Returns 0 if success, -1 if error
Return type: int
-
pyfrp.modules.pyfrp_img_module.
saveImg
(img, fn, enc='uint16', scale=True, maxVal=None)¶ Saves image as tif file.
scale
triggers the image to be scaled to either the maximum range of encoding ormaxVal
. See alsoscaleToEnc()
.Parameters: - img (numpy.ndarray) – Image to save.
- fn (str) – Filename.
Keyword Arguments: - enc (str) – Encoding of image.
- scale (bool) – Scale image.
- maxVal (int) – Maximum value to which image is scaled.
Returns: Filename.
Return type: str
-
pyfrp.modules.pyfrp_img_module.
scaleToEnc
(img, enc, maxVal=None)¶ Scales image to either the maximum range of encoding or
maxVal
.Possible encodings:
- 4bit
- 8bit
- 16bit
- 32bit
Parameters: - img (numpy.ndarray) – Image to save.
- enc (str) – Encoding of image.
Keyword Arguments: maxVal (int) – Maximum value to which image is scaled.
Returns: Scaled image.
Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_img_module.
showImgAndHist
(img, axes=None, sup='', title=None, color='b', vmin=None, vmax=None, binMin=0, binMax=65535, nbins=256, binSize=1, binsFit=True, fixSize=False, density=False)¶ Creates plot of image and corresponding histogram.
Parameters: img (numpy.ndarray) – Image to be plotted.
Keyword Arguments: - nbins (int) – Number of bins of histogram.
- binSize (int) – Size of bins.
- binMin (float) – Minimum value of bins.
- binMax (float) – Maximum value of bins.
- binsFit (bool) – Fits bin range properly around range of image.
- fixSize (bool) – Use binSize for fixed bin size.
- density (bool) – Normalize histogram as probability density function.
- vmin (float) – Minimum display value of image.
- vmax (float) – Maximum display value of image.
- title (list) – List of titles of plots.
- sup (str) – Supporting title of figure.
- axes (list) – List of matplotlib axes used for plotting. If not specified, will generate new ones.
- color (str) – Color of histogram plot.
Returns: Tuple containing:
- bins (float): Bin array of histogram.
- hist (float): Histogram array.
- w (float): Width of bins.
Return type: tuple
-
pyfrp.modules.pyfrp_img_module.
substractBkgd
(img, bkgd, substractMean=True, nonNeg=True)¶ Substracts background from image.
Parameters: - img (numpy.ndarray) – Input image.
- bkgd (numpy.ndarray) – Background mask that will be used.
Keyword Arguments: - substractMean (bool) – Substract mean background.
- nonNeg (bool) – Fill negative pixels with 1. to avoid further problems.
Returns: Processed image.
Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_img_module.
symmetryTest
(img, debug=False)¶ Checks if images is LR and UD symmetirc. If so, returns True.
Parameters: img (numpy.ndarray) – Input image. Keyword Arguments: debug (bool) – Print debugging messages and show debugging plots. Returns: True if image is both LR and UD symmetric Return type: bool
-
pyfrp.modules.pyfrp_img_module.
unflipQuad
(img, debug=False, testimg=False)¶ Unflip image from quaddrant into normal picture.
Parameters: img (numpy.ndarray) – Input image.
Keyword Arguments: - debug (bool) – Print debugging messages and show debugging plots.
- testimg (bool) – Check with test image if unflip works properly
Returns: Unflipped image.
Return type: numpy.ndarray
pyfrp.modules.pyfrp_integration_module module¶
Integration module for PyFRAP toolbox.
Warning
Might get merged with simulation module at some point.
-
pyfrp.modules.pyfrp_integration_module.
calcTetSidelengths
(point0, point1, point2, point3)¶ Calculates sidelengths of tetrahedron given by 4 points.
Note
Taking point0 as base point.
-
pyfrp.modules.pyfrp_integration_module.
getAvgConc
(val, cvs, ind)¶ Integrates simulation result over specific set of indices.
Parameters: - val (fipy.CellVariable) – PDE solution variable.
- cvs (numpy.ndarray) – Array containing cell volumes.
- ind (list) – List of indices.
Returns: Integration result.
Return type: float
pyfrp.modules.pyfrp_misc_module module¶
Miscellaneous module for PyFRAP toolbox. Contains functions handling:
- Filepath management (Windowns/Unix conversion etc.)
- String searching/replacing
- List matching/comparison
- Dictionary to object and back conversion/extraction.
- Settings path management.
- Embryo wizard.
- etc.
-
pyfrp.modules.pyfrp_misc_module.
addPathToWinPATHs
(path)¶ Adds a path to Windows’ PATH list.
Note
Only adds path if file exits.
Note
You will need to restart the terminal to be sure that the change has any effect.
Parameters: path (str) – Path to be added. Returns: True if successful. Return type: bool
-
pyfrp.modules.pyfrp_misc_module.
appDtype
(l, s, dtype='int')¶ Appends string to list and convert to right dtype.
Note
Will use
s.strip()
before conversion to avoid unnecessary spaces.Note
Will remove quotes from strings using
removeQuoteSignsFromString()
.Parameters: - l (list) – A list.
- s (str) – String to append.
Keyword Arguments: dtype (str) – Data type (float,int,str)
Returns: List with appended value.
Return type: list
-
pyfrp.modules.pyfrp_misc_module.
assignIfVal
(var, val, valCheck)¶ Assigns val to var if var==valCheck.
Parameters: - var (var) – Variable
- val (any) – Value to be assigned
- valCheck (any) – Value to be checked for
-
pyfrp.modules.pyfrp_misc_module.
buildEmbryoWizard
(fn, ftype, name, nChannel=1, fnDest=None, createEmbryo=True, recoverIdent=['recover', 'post'], bleachIdent=['bleach'], preIdent=['pre'], colorPrefix='_c00', cleanUp=True)¶ Creates embryo object ready for analysis from microscope data.
- Extracts microscope data into .tif files
- Builds folder structure
- Moves image files in proper folders
- Creates embryo object and automatically sets filepaths properly
Parameters: - fn (str) – Path to embryo folder
- ftype (str) – Type of microscopy file, such as lsm or czi
- name (str) – Name of embryo
Keyword Arguments: - nChannel (int) – Defines which channel of the images contains relevant data
- fnDest (str) – Path of embryo data structure
- createEmbryo (boo) – Flag if embryo object should be created
- recoverIdent (list) – List of identifiers for recovery data
- bleachIdent (list) – List of identifiers for bleach data
- preIdent (list) – List of identifiers for pre-bleach data
- colorPrefix (str) – Defines how to detect if multichannel or not
- cleanUp (bool) – Clean up .tif files from other channels afterwards.
Returns: Created Embryo in case of success, otherwise -1
Return type:
-
pyfrp.modules.pyfrp_misc_module.
checkDataMultiChannel
(fn, recoverIdent=['recover', 'post'], bleachIdent=['bleach'], preIdent=['pre'], colorPrefix='_c00')¶ Checks if extracted bleach/pre/recover microscopy data are multichannel.
Parameters: fn (str) – Path to folder containing images
Keyword Arguments: - recoverIdent (list) – List of identifiers for recovery data
- bleachIdent (list) – List of identifiers for bleach data
- preIdent (list) – List of identifiers for pre-bleach data
- colorPrefix (str) – Defines how to detect if multichannel or not
Returns: Tuple containing:
- recoverMulti (bool): True if recover is multichannel
- preMulti (bool): True if pre is multichannel
- bleachMulti (bool): True if bleach is multichannel
Return type: tuple
-
pyfrp.modules.pyfrp_misc_module.
checkIfGmshBin
(fn)¶
-
pyfrp.modules.pyfrp_misc_module.
checkMultiChannel
(fn, ident, colorPrefix='_c00')¶ Checks if extracted microscopy with identifier are multichannel.
Parameters: - fn (str) – Path to folder containing images
- ident (list) – List of identifiers, for example [“recover”,”post”]
Keyword Arguments: colorPrefix (str) – Defines how to detect if multichannel or not
Returns: True if multichannel, False if not
Return type: bool
-
pyfrp.modules.pyfrp_misc_module.
checkPaths
(fnPath=None)¶ Checks if all paths in paths file exist.
If
fnPath
is not given, will use the return ofgetPathFile
.Keyword Arguments: fnPath (str) – Path to path file.
-
pyfrp.modules.pyfrp_misc_module.
cleanUpImageFiles
(fn, ftype, ident=None, debug=False, colorPrefix='_c00', nChannel=None)¶ Removes all image files fullfilling
*ident*colorPrefix*ftype
fromfn
.If
nChannel=None
, will remove all files of ftype.Parameters: - fn (str) – Path to folder containing images.
- ftype (str) – Type of file, for example “tif”.
Keyword Arguments: - debug (bool) – Debugging flag
- colorPrefix (str) – String prefix before channel number.
- nChannel (int) – Defines which channel to delete
- ident (list) – List of identifiers, for example [“recover”,”post”].
Returns: Returns 0 if success, -1 if error
Return type: int
-
pyfrp.modules.pyfrp_misc_module.
compareArrays
(arr1, arr2)¶ Converts two lists/arrays into numpy arrays and compares then elementwise.
Parameters: - arr1 (numpy.ndarray) – Some array.
- arr2 (numpy.ndarray) – Other arrayy.
Returns: True if elemet are the same element wise.
Return type: bool
-
pyfrp.modules.pyfrp_misc_module.
compareObjAttr
(obj1, obj2)¶ Compare the values of two objects.
Parameters: - obj1 (object) – First object.
- object2 (object) – Second object.
Returns: Tuple containing:
- same (dict): Dictionary of attributes with same values
- different (dict): Dictionary of attributes with different values
- notInBoth (dict): Dictionary of attributes that are not in both objects
Return type: tuple
-
pyfrp.modules.pyfrp_misc_module.
compareROIs
(emb1, emb2, byName=True)¶ Compares the list of ROIs between to
pyfrp.subclasses.pyfrp_embryo.embryo`
objects.Parameters: - emb1 (pyfrp.subclasses.pyfrp_embryo.embryo) – First embryo.
- emb2 (pyfrp.subclasses.pyfrp_embryo.embryo) – Second embryo.
Returns: Tuple containing:
- sameAll (list): List of same output of
compareObjAttr(ROI,ROI2)
per ROI, see alsocompareObjAttr()
. - differentAll (list): List of different output of
compareObjAttr(ROI,ROI2)
per ROI, see alsocompareObjAttr()
. - notInBothAll (list): List of notInBoth output of
compareObjAttr(ROI,ROI2)
per ROI, see alsocompareObjAttr()
. - notFound (dict): Dictionary of ROI names that are in
emb1
but notemb2
.
Return type: tuple
-
pyfrp.modules.pyfrp_misc_module.
compareVectors
(x, y)¶ Compares two vectors.
Parameters: - x (numpy.ndarray) – Vector 1.
- y (numpy.ndarray) – Vector 2.
Returns: True if vectors are identical
Return type: bool
-
pyfrp.modules.pyfrp_misc_module.
complValsFast
(l1, l2)¶ Returns complimentary values of two lists, faster version.
Parameters: - l1 (list) – A list.
- l2 (list) – Another list.
Returns: List with complimentary values.
Return type: list
-
pyfrp.modules.pyfrp_misc_module.
complValsSimple
(l1, l2)¶ Returns complimentary values of two lists.
Parameters: - l1 (list) – A list.
- l2 (list) – Another list.
Returns: List with complimentary values.
Return type: list
-
pyfrp.modules.pyfrp_misc_module.
copyListOfFiles
(l, dest)¶ Copies list of files using shutil.copy.
Parameters: - l (list) – List of files.
- dest (str) – Destination of files.
Returns: Returns 0 if success, -1 if error
Return type: int
-
pyfrp.modules.pyfrp_misc_module.
dict2string
(dic, sep='=', newline=False)¶ Build string with variable name and its value from dict.
Parameters: dic (dict) – Dictionary.
Keyword Arguments: - sep (list) – Seperator between variable and value.
- newline (bool) – Start newline after each variable.
Returns: Built string.
Return type: str
-
pyfrp.modules.pyfrp_misc_module.
enumeratedName
(baseName, listOfNames, sep='_')¶ Generates a new name given a list of names.
Example:
>>> baseName=embryo >>> listOfNames=[embryo_1,embryo_5] >>> enumeratedName(baseNamem,listOfNames) "embryo_6"
Parameters: - baseName (str) – basename used for naming
- listOfNames (list) – List of names
Keyword Arguments: sep (str) – Seperator between basename and number
Returns: New name that has not been used yet
Return type: str
-
pyfrp.modules.pyfrp_misc_module.
findDateString
(s, sep='', lendate=8, yearreq='', monthreq='', debug=False)¶ Finds date in string.
Useful for example to find date a filename.
Parameters: s (str) – String
Keyword Arguments: - sep (str) – Separator between date parts.
- lendate (int) – Length of dates in characters.
- yearreq (str) – Date must contain year, for example (“16”).
- monthreq (str) – Date must cotain month, for example (“03”).
Returns: Date found, or empty string if date was not found.
Return type: str
-
pyfrp.modules.pyfrp_misc_module.
findFn
(fn, base, lvlsUp=3, folder=False, debug=False)¶ Finds filename within folder structure
Parameters: - fn (str) – File name to look for
- base (str) – Base path to look in
Keyword Arguments: - lvlsUp (int) – How many levels to go up
- debug (bool) – Debugging flag
- folder (bool) – Look for folder
Returns: Path to preimage
Return type: str
Raises: OSError
– If file cannot be found
-
pyfrp.modules.pyfrp_misc_module.
findIntString
(s, idxvec=[], debug=False)¶ Finds integers in string.
Parameters: s (str) – String
Keyword Arguments: - idxvec (list) – List of already found indices.
- debug (bool) – Show debugging output.
Returns: List of indices if integers in string.
Return type: list
-
pyfrp.modules.pyfrp_misc_module.
findPreimage
(key, base, lvlsUp=1, fType='tif', debug=False)¶ Finds preimage automatically
Parameters: - key (str) – Key pattern to look for, e.g. “_pre”
- base (str) – Base path to look in
Keyword Arguments: - lvlsUp (int) – How many levels to go up.
- fType (str) – Filetype of preimage
- debug (bool) – Debugging flag
Returns: Path to preimage
Return type: str
Raises: OSError
– If preimage cannot be found
-
pyfrp.modules.pyfrp_misc_module.
fixPath
(path)¶ Fixes path by expanding user and making sure that path is according to OS definitions.
Parameters: path (str) – Path to fix. Returns: Fixed path. Return type: str
-
pyfrp.modules.pyfrp_misc_module.
getAllObjWithAttrVal
(listOfObjects, AttributeName, AttributeValue)¶ Filters all objects from a list that have a given attribute value.
Parameters: - listOfObjects (list) – List of objects that all possess the same attribute.
- AttributeName (str) – Name of attribute.
- AttributeValue (str) – Value of attribute.
Returns: List of objects that fulfill requirement.
Return type: list
-
pyfrp.modules.pyfrp_misc_module.
getConfDir
()¶
-
pyfrp.modules.pyfrp_misc_module.
getFijiBin
(fnPath=None)¶
-
pyfrp.modules.pyfrp_misc_module.
getGUIDir
()¶
-
pyfrp.modules.pyfrp_misc_module.
getIdxOfNLargest
(x, N)¶ Returns indices of N largest values in array/list.
Parameters: - x (numpy.nparray) – An array.
- N (int) – Number of values.
Returns: Tuple containing:
- list: List containing N largest numbers.
- list: List containing indices of N largest numbers.
Return type: tuple
-
pyfrp.modules.pyfrp_misc_module.
getMacroDir
()¶
-
pyfrp.modules.pyfrp_misc_module.
getMeshfilesDir
()¶
-
pyfrp.modules.pyfrp_misc_module.
getModulesDir
()¶
-
pyfrp.modules.pyfrp_misc_module.
getNLargest
(x, N)¶ Returns N largest values in array/list.
Parameters: - x (numpy.nparray) – An array.
- N (int) – Number of values.
Returns: List containing N largest numbers.
Return type: list
-
pyfrp.modules.pyfrp_misc_module.
getOpenscadBin
(fnPath=None)¶
-
pyfrp.modules.pyfrp_misc_module.
getPath
(identifier, fnPath=None, defaultOutput='')¶ Extracts path with identifier from path definition file.
If not defined diferently, will first look in configurations/paths, then configurations/paths.default.
Parameters: identifier (str) – Identifier of path Keyword Arguments: fnPath (str) – Path to path definition file Returns: Path Return type: str
-
pyfrp.modules.pyfrp_misc_module.
getPathFile
()¶
-
pyfrp.modules.pyfrp_misc_module.
getSortedFileList
(fnFolder, fType)¶ Gets sorted file list from folder for files of type fType
Parameters: - fnFolder (str) – Folder path.
- fType (str) – File type.
Returns: list of filenames.
Return type: list
-
pyfrp.modules.pyfrp_misc_module.
getSubclassesDir
()¶
-
pyfrp.modules.pyfrp_misc_module.
leastCommonSubstring
(S, T)¶ Find longest common substring.
Parameters: - S (str) – String to find substring in.
- T (str) – Substring.
Returns: Least common substring.
Return type: str
-
pyfrp.modules.pyfrp_misc_module.
lenRange
(l)¶ Return the range of values in list
Parameters: l (list) – List Returns: Range of values of list Return type: float
-
pyfrp.modules.pyfrp_misc_module.
lin2winPath
(p)¶ Converts Linux Path to Win path (/ -> )
Parameters: p (str) – Path. Returns: Converted path. Return type: str
-
pyfrp.modules.pyfrp_misc_module.
makeEmbryoFolderStruct
(fn)¶ Creates default folder structure for embryo object.
fn
|–recover
|–pre
|–bleach
|–lsm
|–meshfiles
Parameters: fn (str) – Path to embryo folder Returns: 0 Return type: int
-
pyfrp.modules.pyfrp_misc_module.
matchVals
(l1, l2)¶ Returns matching values of two lists.
Parameters: - l1 (list) – A list.
- l2 (list) – Another list.
Returns: List of matching values.
Return type: list
-
pyfrp.modules.pyfrp_misc_module.
mkdir
(fn)¶ Tries to make folder if not already existent.
Parameters: fn (str) – Path of folder to create. Returns: True if success, False otherwise. Return type: bool
-
pyfrp.modules.pyfrp_misc_module.
modIdx
(i, l)¶ Returns index of list when input is larger than list by returning the modulo of the length of the list.
Useful if lists refer to loop etc.
Parameters: - i (int) – Index.
- l (list) – Some list.
Returns: New index.
Return type: int
-
pyfrp.modules.pyfrp_misc_module.
moveImageFiles
(fn, fnTarget, ftype, ident, isMulti, fnDest=None, debug=False, colorPrefix='_c00', nChannel=1)¶ Moves all image files fullfilling ident*(isMulti*colorPrefix) to fnDest+fnTarget.
Parameters: - fn (str) – Path to folder containing images.
- fnTarget (str) – Name of folder files should go in, for example “recover”.
- ftype (str) – Type of file, for example “tif”.
- ident (list) – List of identifiers, for example [“recover”,”post”].
- isMulti (bool) – Flag if images are multichannel or not.
Keyword Arguments: - fnDest (str) – Path containing fnTarget
- debug (bool) – Debugging flag
- colorPrefix (str) – Defines how to detect if multichannel or not
- nChannel (int) – Defines which channel of the images contains relevant data
Returns: Returns 0 if success, -1 if error
Return type: int
-
pyfrp.modules.pyfrp_misc_module.
moveListOfFiles
(l, dest)¶ Moves list of files using shutil.move.
Parameters: - l (list) – List of files.
- dest (str) – Destination of files.
Returns: Returns 0 if success, -1 if error
Return type: int
-
pyfrp.modules.pyfrp_misc_module.
objAttr2Dict
(obj, attr=[])¶ Writes all object attributes with names defined in list in the form attributeName = attributeValue into dictionary.
If
attr=[]
, all attributes are written into dictionary, otherwise only the ones specified inattr
.Parameters: obj (object) – Object to be printed. Keyword Arguments: maxL (int) – Maximum length threshold.
-
pyfrp.modules.pyfrp_misc_module.
objAttrToList
(listOfObjects, AttributeName)¶ Extracts a single object attribute from a list of objects and saves it into list.
Parameters: - listOfObjects (list) – List of objects that all possess the same attribute
- AttributeName (str) – Name of attribute to be appended
Returns: List containing value of attribute of all objects
Return type: list
-
pyfrp.modules.pyfrp_misc_module.
popRange
(l, idxStart, idxEnd)¶ Basically
list.pop()
for range of indices.Parameters: - l (list) – A list
- idxStart (int) – Start index of range.
- idxEnd (int) – End index of range.
Returns: Tuple containing:
- popped (list): Popped items.
- l (list): Resulting list.
Return type: tuple
-
pyfrp.modules.pyfrp_misc_module.
printPaths
(fnPath=None)¶ Prints out path file.
If
fnPath
is not given, will use the return ofgetPathFile
.Keyword Arguments: fnPath (str) – Path to path file.
-
pyfrp.modules.pyfrp_misc_module.
rangeLists
(ls)¶ Return the range of values in list of lists
Parameters: ls (list) – List of lists Returns: Tuple containing: - minL (float): Minimum value over all lists
- maxL (float): Maximum value over all lists
Return type: tuple
-
pyfrp.modules.pyfrp_misc_module.
remRepeatsList
(l)¶ Removes repeated entries from list.
Similar to numpy.unique.
Parameters: l (list) – List Returns: Filtered list. Return type: list
-
pyfrp.modules.pyfrp_misc_module.
removeAllOccFromList
(l, val)¶ Removes all occurences of value in list.
Parameters: - l (list) – A list.
- val (value) – Value to remove.
Returns: List without removed values.
Return type: list
-
pyfrp.modules.pyfrp_misc_module.
removeListOfFiles
(l)¶ Removes list of files using os.remove.
Parameters: l (list) – List of files. Returns: Returns 0 if success, -1 if error Return type: int
-
pyfrp.modules.pyfrp_misc_module.
removeQuoteSignsFromString
(s)¶ Removes Quote signs from string.
Example: >>> a=‘“Test(‘Test’)”’ >>> removeQuoteSignsFromString() >>> ‘Test(Test)’
Parameters: s (str) – A string. Returns: String without quote signs. Return type: str
-
pyfrp.modules.pyfrp_misc_module.
setPath
(identifier, val, fnPath=None)¶ Sets path in path file.
If
fnPath
is not given, will use the return ofgetPathFile
.Parameters: - identifier (str) – Identifier of path.
- val (str) – Value of path.
Keyword Arguments: fnPath (str) – Path to path file.
-
pyfrp.modules.pyfrp_misc_module.
simpleHist
(x, y, bins)¶ Performs a simple histogram onto x-array.
Parameters: - x (numpy.ndarray) – x coordinates of data
- y (numpy.ndarray) – y coordinates of data
- bins (int) – number of bins
Returns: Tuple containing:
- xBin (numpy.ndarray): Center of bins
- yBin (numpy.ndarray): Bin Values
Return type: tuple
-
pyfrp.modules.pyfrp_misc_module.
slashToFn
(fn)¶ Append / or to filepath if necessary.
Parameters: fn (str) – Filepath Returns: Filepath Return type: str
-
pyfrp.modules.pyfrp_misc_module.
sortImageFiles
(fn, fnDest, ftype, recoverIdent=['recover', 'post'], bleachIdent=['bleach'], preIdent=['pre'], nChannel=1, debug=False, colorPrefix='_c00', cleanUp=True)¶ Sorts all image data in fn into the respective folders of embryo project.
Parameters: - fn (str) – Path to folder containing images
- fnDest (str) – Path of embryo project.
- ftype (str) – Type of microscopy file, such as lsm or czi
Keyword Arguments: - recoverIdent (list) – List of identifiers for recovery data
- bleachIdent (list) – List of identifiers for bleach data
- preIdent (list) – List of identifiers for pre-bleach data
- nChannel (int) – Defines which channel of the images contains relevant data
- debug (bool) – Debugging flag
- colorPrefix (str) – Defines how to detect if multichannel or not
- cleanUp (bool) – Clean up .tif files from other channels afterwards.
Returns: 0
Return type: int
-
pyfrp.modules.pyfrp_misc_module.
sortListsWithKey
(l, keyList)¶ Sorts two lists according to key list.
Example:
>>> l=[1,3,5] >>> keyList=[2,5,1]
would result in
>>> [5,1,3],[1,2,5]
Parameters: - l (list) – list to be sorted.
- keyList (list) – list after which is being sorted.
Returns: Tuple containing:
- sortedList (list): Sorted list
- sortedKeys (list): Sorted keys
Return type: tuple
-
pyfrp.modules.pyfrp_misc_module.
str2list
(l, dtype='int', openDelim='[', closeDelim=']', sep=', ')¶ String with lists/sublists to list filled with integers.
Example:
>>> l="[1,2,[3,4]]" >>> str2list(l) >>> [1,2,[3,4]]
Parameters: l (str) – A list or tuple as a string.
Keyword Arguments: - dtype (str) – Data type (float,int,str)
- openDelim (str) – Opening delimiter.
- closeDelim (str) – Closing delimiter.
- sep (str) – Seperator between values.
Returns: Tuple containing:
- lnew (list): Converted string.
- i (int): Last character visited.
Return type: tuple
-
pyfrp.modules.pyfrp_misc_module.
translateNPFloat
(x)¶ Translates string into numpy float.
If string==+/-‘inf’, will return +/- numpy.inf, otherwise will leave x unchanged.
This function is necessary to prevent Sphinx from not being able to import modules because np.inf is an default value for an keyword arg, but numpy is mocked.
Parameters: x (float) – Input number/string. Returns: Translated float. Return type: float
-
pyfrp.modules.pyfrp_misc_module.
txtLineReplace
(filePath, pattern, subst)¶ Replaces line in file that starts with
pattern
and substitutes it withsubst
.Note
Will create temporary file using
tempfile.mkstemp()
. You should have read/write access to whereevermkstemp
is putting files.Parameters: - filePath (str) – Filename.
- pattern (str) – Pattern to be looked for.
- subst (str) – String used as a replacement.
-
pyfrp.modules.pyfrp_misc_module.
unzipLists
(l)¶ Unzips two zipped lists into seperate lists.
Parameters: l (list) – Zipped lists Returns: Tuple containing: - l1 (list): Unzipped list 1.
- l2 (list): Unzipped list 2.
Return type: tuple
-
pyfrp.modules.pyfrp_misc_module.
updateObj
(objBlank, obj, debug=False)¶ Updates object with respect to blank object.
If object does not have attribute, will add attribute from objBlank with value of objBlank.
Parameters: - objBlank (object) – Object Template
- obj (object) – Object to be updated
Keyword Arguments: debug (bool) – Print debugging output.
Returns: Updated object.
Return type: object
-
pyfrp.modules.pyfrp_misc_module.
vars2dict
(var, loc, filt=[])¶ Builds dict of list of variables (only works if vars are in locals()).
Parameters: - var (list) – List of variable names.
- loc (dict) – Handle to locals().
Returns: Built dictionary.
Return type: dict
-
pyfrp.modules.pyfrp_misc_module.
win2linPath
(p)¶ Converts Win Path to Linux path (-> /)
Parameters: p (str) – Path. Returns: Converted path. Return type: str
pyfrp.modules.pyfrp_openscad_module module¶
PyFRAP module for handling building geometries via openscad.
-
pyfrp.modules.pyfrp_openscad_module.
runOpenscad
(fn, fnOut=None)¶ Runs openscad to convert scad file to stl file.
If
fnOut=None
, then the output file will have the same filename as the input file.Parameters: fn (str) – Path to scad file. Keyword Arguments: fnOut (str) – Output filename. Returns: Output filename. Return type: str
pyfrp.modules.pyfrp_optimization_module module¶
Optimization module for PyFRAP toolbox.
Currently contains all functions necessary to transform a constrained FRAP optimization problem into a unconstrained one, making it suitable to Nelder-Mead optimization algorithm.
-
pyfrp.modules.pyfrp_optimization_module.
buildBoundLists
(fit)¶ Builds list of lower bounds and upper bounds.
Parameters: fit (pyfrp.subclasses.pyfrp_fit) – Fit object. Returns: Tuple containing: - LBs (list): List of lower bounds.
- UBs (list): List of upper bounds.
Return type: tuple
-
pyfrp.modules.pyfrp_optimization_module.
constrObjFunc
(x, fit, debug, ax, returnFit)¶ Objective function when using Constrained Nelder-Mead.
Calls
pyfrp.modules.pyfrp_optimization_module.xTransform()
to transform x into constrained version, then usespyfrp.modules.pyfrp_fit_module.FRAPObjFunc()
to find SSD.Parameters: - x (list) – Input vector, consiting of [D,(prod),(degr)].
- fit (pyfrp.subclasses.pyfrp_fit) – Fit object.
- debug (bool) – Display debugging output and plots.
- ax (matplotlib.axes) – Axes to display plots in.
- returnFit (bool) – Return fit instead of SSD.
Returns: SSD of fit. Except
returnFit==True
, then will return fit itself.Return type: float
-
pyfrp.modules.pyfrp_optimization_module.
transformX0
(x0, LB, UB)¶ Transforms
x0
into constrained form, obeying upper boundsUB
and lower boundsLB
.Idea taken from http://www.mathworks.com/matlabcentral/fileexchange/8277-fminsearchbnd–fminsearchcon
Parameters: - x0 (list) – Input initial vector, consiting of [D,(prod),(degr)].
- LB (list) – List of lower bounds for
D,prod,degr
. - UB (list) – List of upper bounds for
D,prod,degr
.
Returns: Transformed x-values.
Return type: list
-
pyfrp.modules.pyfrp_optimization_module.
xTransform
(x, LB, UB)¶ Transforms
x
into constrained form, obeying upper boundsUB
and lower boundsLB
.Note
Will add tiny offset to LB(D), to avoid singularities.
Idea taken from http://www.mathworks.com/matlabcentral/fileexchange/8277-fminsearchbnd–fminsearchcon
Parameters: - x (list) – Input vector, consiting of [D,(prod),(degr)].
- LB (list) – List of lower bounds for
D,prod,degr
. - UB (list) – List of upper bounds for
D,prod,degr
.
Returns: Transformed x-values.
Return type: list
pyfrp.modules.pyfrp_plot_module module¶
Plotting module for PyFRAP toolbox.
Contains functions and classes that are often used by PyFRAP toolbox and simplify plot creation and management.
-
class
pyfrp.modules.pyfrp_plot_module.
FRAPBoundarySelector
(embryo=None, fn=None)¶ Simple GUI widget to select circular FRAP boundaries.
Has useful center marker that is activatable that helps finding the center of the image.
Mouse Input:
- Left: Set center.
- Right: Set Radius.
- Middle: Activate center marker.
Keyboard Input:
- Left Arrow: Move center to the left.
- Right Arrow: Move center to the right.
- Up Arrow: Move center upwards.
- Down Arrow: Move center downwards.
- Control + Up Arrow: Increase circle radius.
- Control + Down Arrow: Decrease circle radius.
Note
If
embryo
is given at initiation, will use first image specified in embryo’sfileList
as background image.Example Usage:
>>> sel=FRAPBoundarySelector(fn="path/to/img/file")
Use mouse/keyboard to define circular boundary.
>>> center,radius=sel.getResults()
Keyword Arguments: - embryo (pyfrp.subclasses.pyfrp_embryo.embryo) – PyFRAP embryo instance.
- fn (str) – Filepath to image file taken for boundary selection.
-
checkInput
()¶ Checks if at least one of the two keyword arguments,
embryo
orfn
, is given.If not, prints error message and closes down widget.
-
clearCenter
()¶ Removes center marker from canvas.
-
clearCenterMarker
()¶ Removes center maker from canvas.
-
clearRadius
()¶ Removes circle from canvas.
-
closeFigure
(event)¶ Returns center and radius at close
event
.
-
computeRadiusFromCoordinate
(x, y)¶ Computes radius from given cordinate
(x,y)
.
-
createCanvas
()¶ Creates figure and canvas used for plotting.
-
decreaseRadius
()¶ Decreases radius by 1 px.
-
drawCenter
()¶ Draws a red marker at selected center on canvas.
-
drawCenterMarker
()¶ Draws a yellow marker in center of the image, making it easier to find image center when selecting center of boundary.
-
drawRadius
()¶ Draws a red circle around selected center with selected radius on canvas.
-
getEmbryo
()¶ Returns
embryo
object if given.``
-
getMouseInput
(event)¶ Directs mouse input to the right actions.
-
getResults
()¶ Returns center and radius.
-
increaseRadius
()¶ Increases radius by 1 px.
-
keyPressed
(event)¶ Directs all key press events to the respective functions.
-
moveDown
()¶ Moves center 1 px down.
-
moveLeft
()¶ Moves center 1 px to the left.
-
moveRight
()¶ Moves center 1 px to the right.
-
moveUp
()¶ Moves center 1 px up.
-
redraw
()¶ Redraws both center and radius if available.
-
showFirstDataImg
()¶ Shows either first data image defined in
embryo.fileList
or image specified byfn
.Note
If both are given, will use the embryo option.
-
showImg
(img)¶ Shows image on canvas.
Parameters: img (numpy.ndarray) – Image to be shown.
-
pyfrp.modules.pyfrp_plot_module.
adjustImshowRange
(axes, vmin=None, vmax=None)¶ Adjust display range of
matplotlib.pyplot.imshow
plots in list of axes.Finds first image artist in each axes in
axes
list and then sets display range to[vmin,vmax]
.Parameters: axes (list) – List of matplotlib axes.
Keyword Arguments: - vmin (float) – Minimum value of display range.
- vmax (float) – Maximum value of display range.
Returns: Updated list of matplotlib axes.
Return type: list
-
pyfrp.modules.pyfrp_plot_module.
closerLabels
(ax, padx=10, pady=10)¶ Moves x/y labels closer to axis.
-
pyfrp.modules.pyfrp_plot_module.
findArtist
(ax, key)¶ Finds
matplotlib.artist
which name containskey
.Note
Will stop searching after first artist is found.
Will return
None
if no artist can be found.Parameters: - ax (matplotlib.axes) – Matplotlib axes.
- key (str) – Key used for search.
Returns: Matplotlib artist.
Return type: matplotlib.artist
-
pyfrp.modules.pyfrp_plot_module.
getPubParms
()¶ Returns dictionary with good parameters for nice publication figures.
Resulting
dict
can be loaded viaplt.rcParams.update()
.Note
Use this if you want to include LaTeX symbols in the figure.
Returns: Parameter dictionary. Return type: dict
-
pyfrp.modules.pyfrp_plot_module.
getRandomColor
()¶ Returns triplet defining a random color.
-
pyfrp.modules.pyfrp_plot_module.
is3DAxes
(ax)¶ Returns if an axes is a 3D axis.
Parameters: ax (matplotlib.axes) – A matplotlib axes. Returns: True if 3d axis. Return type: bool
-
pyfrp.modules.pyfrp_plot_module.
makeFittingLevels
(vmin, vmax, val, nlevels, buff=0.01)¶ Generates array with fitting levels for contour plots.
Note
If
vmin=None
orvmax=None
, will pick the minimum/maximum value ofval
.Parameters: - val (numpy.ndarray) – Array to be plotted.
- vmin (float) – Minimum value displayed in contour plot.
- vmax (float) – Maximum value displayed in contour plot.
- nlevels (int) – Number of contour levels.
Keyword Arguments: buff (float) – Percentage buffer to be added to both sides of the array.
Returns: Tuple containing:
- vmin (float): Minimum value displayed in contour plot.
- vmax (float): Maximum value displayed in contour plot.
- levels (numpy.ndarray): Level array to be handed to contour function.
Return type: tuple
-
pyfrp.modules.pyfrp_plot_module.
makeGeometryPlot
(titles=None, tight=False, sup=None, fig=None, show=True, unit='px')¶ Generates matplotlib figure and single axes optimized for geometry plots.
See also
pyfrp.modules.pyfrp_plot_module.makeSubplot()
.Keyword Arguments: - titles (list) – List of axes titles.
- tight (bool) – Use tight layout.
- sup (str) – Figure title.
- fig (matplotlib.figure) – Figure used for axes.
- show (bool) – Show figure right away.
- unit (str) – Unit displayed in axes label.
Returns: Tuple containing:
- fig (matplotlib.figure): Figure.
- axes (list): List of Matplotlib axes.
Return type: tuple
-
pyfrp.modules.pyfrp_plot_module.
makeSubplot
(size, titles=None, tight=False, sup=None, proj=None, fig=None, show=True)¶ Generates matplotlib figure with (x,y) subplots.
Note
List of
titles
needs to be same size as desired number of axes. Otherwise will turn off titles.Note
List of
proj
needs to be same size as desired number of axes. Otherwise will turn off projections.Example:
>>> makeSubplot([2,2],titles=["Axes 1", "Axes 2", "Axes 3", "Axes 4"],proj=[None,None,'3d',None])
will result in
Parameters: size (list) – Size of subplot arrangement.
Keyword Arguments: - titles (list) – List of axes titles.
- tight (bool) – Use tight layout.
- sup (str) – Figure title.
- proj (list) – List of projections.
- fig (matplotlib.figure) – Figure used for axes.
- show (bool) – Show figure right away.
Returns: Tuple containing:
- fig (matplotlib.figure): Figure.
- axes (list): List of Matplotlib axes.
Return type: tuple
-
pyfrp.modules.pyfrp_plot_module.
plotSolutionVariable
(x, y, val, ax=None, vmin=None, vmax=None, nlevels=25, colorbar=True, plane='xy', zs=None, zdir=None, title='Solution Variable', sup='', dThresh=None, nPts=1000, mode='normal', typ='contour')¶ Plots simulation solution variable as 2D contour plot or 3D surface plot.
Note
If no
ax
is given, will create new one.Note
x
andy
do not necessarily have to be coordinates in x/y-direction, but rather correspond to the two directions defined inplane
.plane
variable controls in which plane the solution variable is supposed to be plotted. Acceptable input variables are"xy","xz","yz"
. See alsopyfrp.subclasses.pyfrp_ROI.ROI.getMaxExtendPlane()
.mode
controls which contour/surface function is used:normal
: Will create rectangular grid and usescipy.interpolate.gridddata
and interpolate solution onto it, then plot usingmatplotlib.pyplot.contourf
, see also http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.contourf and http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.interpolate.griddata.html#scipy.interpolate.griddata .tri
: Will plot irregular grid usingmatplotlib.pyplot.tricontourf
. See also http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.tricontourf .
typ
controls which plot type is used:contour
: Produces contour plots using eithermatplotlib.pyplot.contourf
ormatplotlib.pyplot.tricontourf
.surface
: Produces contour plots using eithermatplotlib.Axed3D.plot_surface
ormatplotlib.pyplot.plot_trisurf
.
Warning
matplotlib.pyplot.tricontourf
has problems whenval
only is in a single level of contour plot. To avoid this, we currently add some noise in this case just to make it plottable. This is not the most elegant solution. (only in case of 3D plotting)Parameters: - x (numpy.ndarray) – x-coordinates.
- y (numpy.ndarray) – y-coordinates.
- val (numpy.ndarray) – Solution variable values.
Keyword Arguments: - ax (matplotlib.axes) – Axes used for plotting.
- vmin (float) – Minimum value displayed in contour plot.
- vmax (float) – Maximum value displayed in contour plot.
- nlevels (int) – Number of contour levels.
- colorbar (bool) – Display color bar.
- plane (str) – Plane in which solution variable is supposed to be plotted.
- zs (float) – In case of a 3D plot, height in direction zdir where to put contour.
- zdir (str) – Orthogonal direction to plane.
- nPts (int) – Number of points used for interpolating (only if
mode=normal
). - mode (str) – Which contour function to use.
- title (str) – Title of plot.
- typ (str) – Type of plot.
Returns: Axes used for plotting.
Return type: matplotlib.axes
-
pyfrp.modules.pyfrp_plot_module.
plotTS
(xvec, yvec, label='', title='', sup='', ax=None, color=None, linewidth=1, legend=True, linestyle='-', show=True, alpha=1.0, legLoc=-1)¶ Plot timeseries all-in-one function.
Parameters: - xvec (numpy.ndarray) – x-data to be plotted.
- yvec (numpy.ndarray) – y-data to be plotted.
Keyword Arguments: - ax (matplotlib.axes) – Matplotlib axes used for plotting. If not specified, will generate new one.
- color (str) – Color of plot.
- linestyle (str) – Linestyle of plot.
- linewidth (float) – Linewidth of plot.
- legend (bool) – Show legend.
- sup (str) – Figure title.
- title (str) – Axes title.
- label (str) – Label for legend.
- show (bool) – Show figure.
- alpha (float) – Transparency of line.
- legLoc (int) – Location of legend.
Returns: Axes used for plotting.
Return type: matplotlib.axes
-
pyfrp.modules.pyfrp_plot_module.
redraw
(ax)¶ Redraws axes’s figure’s canvas.
Makes sure that current axes content is visible.
Parameters: ax (matplotlib.axes) – Matplotlib axes. Returns: Matplotlib axes Return type: matplotlib.axes
-
pyfrp.modules.pyfrp_plot_module.
set3DAxesEqual
(ax)¶ Make axes of 3D plot have equal scale.
This is one possible solution to Matplotlib’s ax.set_aspect(‘equal’) and ax.axis(‘equal’) not working for 3D.
Modified from http://stackoverflow.com/questions/13685386/matplotlib-equal-unit-length-with-equal-aspect-ratio-z-axis-is-not-equal-to .
Parameters: ax (matplotlib.axes) – A matplotlib axes. Returns: Modified matplotlib axes. Return type: matplotlib.axes
-
pyfrp.modules.pyfrp_plot_module.
setPubAxis
(ax)¶ Gets rid of top and right axis.
Parameters: ax (matplotlib.axes) – A matplotlib axes. Returns: Modified matplotlib axes. Return type: matplotlib.axes
-
pyfrp.modules.pyfrp_plot_module.
setPubFigSize
(fig, figWidthPt=180.4, figHeightPt=None, ptPerInches=72.27)¶ Adjusts figure size/aspect.
If
figHeightPt
is not given, will use golden ratio to compute it.Keyword Arguments: - figWidthPt (float) – Width of the figure in pt.
- figHeightPt (float) – Height of the figure in pt.
- ptPerInches (float) – Resolution in pt/inches.
Returns: Adjust figure.
Return type: matplotlib.figure
-
pyfrp.modules.pyfrp_plot_module.
turnAxesForPub
(ax, adjustFigSize=True, figWidthPt=180.4, figHeightPt=None, ptPerInches=72.27)¶ Turns axes nice for publication.
If
adjustFigSize=True
, will also adjust the size the figure.Parameters: ax (matplotlib.axes) – A matplotlib axes.
Keyword Arguments: - adjustFigSize (bool) – Adjust the size of the figure.
- figWidthPt (float) – Width of the figure in pt.
- figHeightPt (float) – Height of the figure in pt.
- ptPerInches (float) – Resolution in pt/inches.
Returns: Modified matplotlib axes.
Return type: matplotlib.axes
pyfrp.modules.pyfrp_sim_module module¶
Simulaton module for PyFRAP toolbox. Handles simulating FRAP experiments and all necessary functions to do so, such as
- Handling initial conditions.
- Mimicing bleaching effects.
- Experiment simulation.
-
pyfrp.modules.pyfrp_sim_module.
applyIdealICs
(phi, simulation, bleachedROI=None, valOut=None)¶ Applies ideal initial conditions.
That is, everything falling inside the bleached ROI in x-y-direction will be set its initial dataVec value, everything else will be set equal to valOut.
Note
The
bleachedROI
and valOut are often stored inside the simulation object. If those two cannot be found, will try to find a ROI called Bleached Square for the bleached ROI and set valOut toconcRim
. If this again fails, will return error.Parameters: - phi (fipy.CellVariable) – PDE solution variable.
- simulation (pyfrp.subclasses.pyfrp_simulation.simulation) – Simulation object.
Keyword Arguments: - bleachedROI (pyfrp.subclasses.pyfrp_ROI.ROI) – Bleached ROI.
- valOut (float) – Value to be assigned outside of bleached ROI.
Returns: Updated solution variable.
Return type: fipy.CellVariable
-
pyfrp.modules.pyfrp_sim_module.
applyImperfectICs
(phi, simulation, center, rJump, sliceHeight, maxVal=1.0, maxMinValPerc=0.25, minMinValPerc=None, rate=0.1, matchWithMaster=True, debug=False)¶ Mimic imperfect bleaching through cone approximation, return phi.
Warning
Not working in current version. Will be integrated in further versions again.
-
pyfrp.modules.pyfrp_sim_module.
applyInterpolatedICs
(phi, simulation, matchWithMaster=True, debug=False, fixNeg=True, fillICWithConcRim=True)¶ Interpolates initial conditions onto mesh.
Uses a bivarariate spline interpolation (http://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.interpolate.RectBivariateSpline.html) to generate an interpolation function of the IC image. Then applies interpolated values to solution variable
phi
if mesh nodes are inside image and masterROI. If not, will apply rim concentration.Note
If no rim concentration has been calculated (for example through running the data analysis) applyInterpolatedICs will try to compute
concRim
by itself. For this it will take the mean concentration outside of bleached square but insidemasterROI
.Note
The bleached square used here is not defined as a
ROI
object here, but rather through the propertiesembryo.sideLengthBleachedPx
andembryo.offsetBleachedPx
. This might change in future versions.Parameters: - phi (fipy.CellVariable) – PDE solution variable.
- simulation (pyfrp.subclasses.pyfrp_simulation.simulation) – Simulation object.
Keyword Arguments: - matchWithMaster (bool) – Match interpolation indices with
masterROI
indices. - debug (bool) – Print debugging messages.
Returns: Updated solution variable.
Return type: fipy.CellVariable
-
pyfrp.modules.pyfrp_sim_module.
applyROIBasedICs
(phi, simulation)¶ Applies ROI-based initial conditions.
First sets concentration on all mesh nodes equal to simulation.embryo.analysis.concRim. Afterwards, mesh nodes get assigned the value of the first entry
dataVec
of the ROI covering them. Note: If a mesh node is covered by two ROIs, will assign the value of the ROI that is last in embryo’sROIs
list. See alsopyfrp.subclasses.pyfrp_simulation.setICMode()
.Parameters: - phi (fipy.CellVariable) – PDE solution variable.
- simulation (pyfrp.subclasses.pyfrp_simulation.simulation) – Simulation object.
Returns: Updated solution variable.
Return type: fipy.CellVariable
-
pyfrp.modules.pyfrp_sim_module.
applyRadialICs
(phi, simulation, radSteps=15, debug=False)¶ Applies radially averaged image data to solution variable as IC.
Note
Will use
embryo.geometry.center
as center circle and the maximum distant pixel from the center as maximum radius.Parameters: - phi (fipy.CellVariable) – PDE solution variable.
- simulation (pyfrp.subclasses.pyfrp_simulation.simulation) – Simulation object.
- radSteps (int) – Number of radial levels.
- debug (bool) – Print debugging messages.
Returns: Updated solution variable.
Return type: fipy.CellVariable
-
pyfrp.modules.pyfrp_sim_module.
fixNegValues
(phi, minVal=None)¶ Fixes negative values in solution variable.
Interpolation sometimes returns negative values if gradients are really steep. Will apply
minVal
to such nodes.If
minVal==None
, will take smallest non-negative value of solution value.
-
pyfrp.modules.pyfrp_sim_module.
rerunReactDiff
(simulation, signal=None, embCount=None, showProgress=True, debug=False)¶ Reruns simulation by extracting values from
simulation.vals
.Performs the following steps:
- Resets
simVecs
of all ROIs. - Extracts values per ROI from
simulation.vals
.
Note
Only works if simulation has been run before with
saveSim
enabled.Parameters: simulation (pyfrp.subclasses.pyfrp_simulation.simulation) – Simulation object.
Keyword Arguments: - signal (PyQt4.QtCore.pyqtSignal) – PyQT signal to send progress to GUI.
- embCount (int) – Counter of counter process if multiple datasets are analyzed.
- debug (bool) – Print final debugging messages and show debugging plots.
- showProgress (bool) – Show simulation progress.
Returns: Updated simulation object.
Return type: - Resets
-
pyfrp.modules.pyfrp_sim_module.
sigmoidBleachingFct
(x, y, z, center, rJump, sliceHeight, maxVal=1.0, maxMinValPerc=0.25, minMinValPerc=0.25, rate=0.1)¶ Generates sigmoid scaling function for imperfect bleaching at coordinates x/y/z.
The idea behind the sigmoid function is:
- Through scattering and other effects, the bleached window becomes blurry in larger depths, resulting
in a radial sigmoid scaling function around
center
. - Similarly, bleaching intensity increases with depth. Thus, a linear term controls the values close
to
center
of the sigmoid function. Bleaching closer to the laser than the imaged height will be rendered stronger, while bleaching effects below will be decreased by bumping up the bleached window. However, only until some threshold is reached.
The sigmoid function is given by:
\[s(r,z) = v_{\mathrm{min}}(z)+(v_{\mathrm{max}}-v_{\mathrm{min}}(z))\frac{1}{1+\exp(-\rho(r-r_\mathrm{Jump}))},\]where \(\rho\) is the sigmoid slope given by
rate
, \(r_\mathrm{Jump}\) is the radius fromcenter
at which sigmoid function has its jump, given byrJump
and \(r\) the radius of coordinate[x,y]
fromcenter
.\(v_{\mathrm{min}}(z)\) is a linear function describing how strong the bleaching is dependent on the depth \(z\) given by
\[v_{\mathrm{min}}(z) = \frac{v_{\mathrm{max}} - v_{\mathrm{max. bleach}}}{h_s} z + v_{\mathrm{max. bleach}},\]where \(v_{\mathrm{max}}\) is the value of the sigmoid function far from
center
, \(v_{\mathrm{max. bleach}}\) is the strongest expected bleaching value (mostly at \(z=0\)) and \(h_s\) is the height of the imaging slice, given bysliceHeight
. The maximum rate of bleaching \(v_{\mathrm{max. bleach}}\) is computed by:\[v_{\mathrm{max. bleach}} = (1-p_{\mathrm{max. bleach}})v_{\mathrm{max}},\]where \(p_{\mathrm{max. bleach}}\) is the percentage of maximum expected bleaching compared to the values in the imaging height, given by
maxMinValPerc
. That is, by how much has the laser power already decreased on its way from entry point of the sample to the imaging height.For sample depths deeper than the imaging height, bleaching is expected to be decrease in intensity, thus the bleached area is getting bumped up. To avoid bumping the bleached area by too much, eventually even resulting in the bleached area having a higher concentration than the area outside, the sigmoid function has a cut-off: If values of \(s(r,z)\) pass
\[v_{\mathrm{min. bleach}} = (1+p_{\mathrm{min. bleach}})v_{\mathrm{max}},\]where \(p_{\mathrm{min. bleach}}\) is the percentage of bleaching to cut-off, then we set
\[s(r,z) = v_{\mathrm{min. bleach}},\]ultimately resulting in a scaling function given by
\[\begin{split}s(r,z) = \left\{\begin{array}{cc} v_{\mathrm{min}}(z)+(v_{\mathrm{max}}-v_{\mathrm{min}}(z))\frac{1}{1+\exp(-\rho(r-r_\mathrm{Jump}))} & \mbox{ if } s(r,z) <= v_{\mathrm{min. bleach}} , \\ v_{\mathrm{min. bleach}} & \mbox{ else } \end{array} \right.\end{split}\]Parameters: - x (numpy.ndarray) – x-coordinates.
- y (numpy.ndarray) – y-coordinates.
- z (numpy.ndarray) – z-coordinates.
- center (list) – Center of bleaching.
- rJump (float) – Radius from center where sigmoid jump is expected.
- sliceHeight (float) – Height at which dataset was recorded.
Keyword Arguments: - maxVal (float) – Value of sigmoid function outside of bleached region.
- maxMinValPerc (float) – Percentage of maximum bleaching intensity.
- minMinValPerc (float) – Percentage of minimum bleaching intensity.
- rate (float) – Rate at which sigmoid increases.
Returns: Return type: numpy.ndarray
- Through scattering and other effects, the bleached window becomes blurry in larger depths, resulting
in a radial sigmoid scaling function around
-
pyfrp.modules.pyfrp_sim_module.
simulateReactDiff
(simulation, signal=None, embCount=None, showProgress=True, debug=False)¶ Simulates reaction diffusion equation goverining FRAP experiment.
Performs the following steps:
Resets
simVecs
of all ROIs.If not generated yet, generates mesh (should never be the case!)
Initializes PDE with Neumann boundary conditions resulting in the problem:
\[\partial_t c = D \nabla^2 c - k_1 c + k_2,\]where \(k_1\) is the degradation rate and \(k_2\) the production rate.
Applies initial conditions defined in
simulation.ICmode
.Simulates FRAP experimment.
Parameters: simulation (pyfrp.subclasses.pyfrp_simulation.simulation) – Simulation object.
Keyword Arguments: - signal (PyQt4.QtCore.pyqtSignal) – PyQT signal to send progress to GUI.
- embCount (int) – Counter of counter process if multiple datasets are analyzed.
- debug (bool) – Print final debugging messages and show debugging plots.
- showProgress (bool) – Show simulation progress.
Returns: Updated simulation object.
Return type:
pyfrp.modules.pyfrp_stats_module module¶
Statistics module for PyFRAP toolbox, mainly used to evaluate goodness of fit, but also providing functions to assess overall measurement statistics.
-
pyfrp.modules.pyfrp_stats_module.
Rsq
(data, x)¶ Computes R-squared values for fit series to data series.
R-squared value is being computed as
\[R^2 = 1 - \frac{\sum\limits_i (x_i - d_i)^2}{\sum\limits_i (d_i - \bar{d} )^2}\]Parameters: - x (numpy.ndarray) –
- data (numpy.ndarray) – Data series.
Returns: R-squared value.
Return type: float
-
pyfrp.modules.pyfrp_stats_module.
compareFitsByAIC
(fits, ROIs=None, sigma=1, fromSSD=True, thresh=None)¶ Computes AIC and Akaike weights for all fits in a list and returning best models given certain criteria.
For the computation of the AIC see
computeAIC()
and the computation of the Akaike weightscomputeAkaikeWeights()
.If threshold
thresh=None
, then will select model with maximum Akaike weight as best model, that is, the model with the highest likelihood of being the best model. Ifthresh
is given, will return list of acceptable models based on\[w_{\mathrm{max}}-w_i<thresh,\]that is, all models that are within a given range of probability of the most likely one.
Parameters: fits (list) – List of fit objects.
Keyword Arguments: - ROIs (list) – List of ROIs to be considered for computation.
- sigma (float) – Standard deviation of normal distribution if known.
- fromSSD (bool) – Simply use SSD as maximum likelihood.
- thresh (float) – Probability range for model selection.
Returns: Tuple containing:
- AICs (list): List of AIC values of the respective fits.
- deltaAICs (numpy.ndarray): List of Akaike difference values of the respective fits.
- weights (numpy.ndarray): List of Akaike difference weights of the respective fits.
- acc (list): List of acceptable fits by model selection.
- ks (list): List of number of parameters fitted of the respective fits.
- ns (list): List of number of datapoints fitted of the respective fits.
Return type: tuple
-
pyfrp.modules.pyfrp_stats_module.
compareFitsByCorrAIC
(fits, ROIs=None, sigma=1, fromSSD=True, thresh=None)¶ Computes AICc and Akaike weights for all fits in a list and returning best models given certain criteria.
For the computation of the corrected AIC see
computeCorrAIC()
and the computation of the Akaike weightscomputeAkaikeWeights()
.If threshold
thresh=None
, then will select model with maximum Akaike weight as best model, that is, the model with the highest likelihood of being the best model. Ifthresh
is given, will return list of acceptable models based on\[w_{\mathrm{max}}-w_i<thresh,\]that is, all models that are within a given range of probability of the most likely one.
Parameters: fits (list) – List of fit objects.
Keyword Arguments: - ROIs (list) – List of ROIs to be considered for computation.
- sigma (float) – Standard deviation of normal distribution if known.
- fromSSD (bool) – Simply use SSD as maximum likelihood.
- thresh (float) – Probability range for model selection.
Returns: Tuple containing:
- AICs (list): List of AICc values of the respective fits.
- deltaAICs (numpy.ndarray): List of Akaike difference values of the respective fits.
- weights (numpy.ndarray): List of Akaike difference weights of the respective fits.
- acc (list): List of acceptable fits by model selection.
- ks (list): List of number of parameters fitted of the respective fits.
- ns (list): List of number of datapoints fitted of the respective fits.
Return type: tuple
-
pyfrp.modules.pyfrp_stats_module.
computeAIC
(fit, ROIs=None, sigma=1, fromSSD=True)¶ Computes Akaike Information Criterion of fit.
The AIC is defined by
\[AIC= 2k - 2\log(L),\]\(k\) is the number of free parameters of the model used in
fit
and \(L\) is the maximum likelihood function of the model, see alsocomputeLogLikelihood()
.Since generally the AIC is only used for model comparison and a normal distribution of the data around the model is assumed, one simply can use the SSD as a log-likelihood function.
fromSSD
controls if just the SSD is used. This is also useful, since \(sigma\) is not necessarily known if the objective function of the fit was not a maximum likelihood function.Note
If
ROIs=None
, will use all ROIs defined infit.ROIsFitted
. IfROIs
are specified, but not infit.ROIsFitted
, will simply skip them.If the AIC or the AICc should be used can be determined using
useAIC()
.Parameters: fit (pyfrp.subclasses.pyfrp_fit.fit) – Fit object.
Keyword Arguments: - ROIs (list) – List of ROIs to be considered for computation.
- sigma (float) – Standard deviation of normal distribution if known.
- fromSSD (bool) – Simply use SSD as maximum likelihood.
Returns: AIC of fit.
Return type: float
-
pyfrp.modules.pyfrp_stats_module.
computeAkaikeWeights
(AICs)¶ Computes Akaike weights for a list of AIC values.
Akaike weightsare given by:
\[w_i = \frac{\exp\left(\frac{-\Delta_{i}}{2}\right)}{\sum\limits_{i=1}^{N} \exp\left(\frac{- \Delta_{i}}{2}\right)},\]where \(\Delta_{i}\) is the Akaike difference of model \(i\) computed by
\[\Delta_{i} = AIC_i - AIC_{\mathrm{min}},\]and \(N\) is the total number of models considered. Note that
\[\sum\limits_{i=1}^{N} \exp\left(\frac{- \Delta_{i}}{2}\right) = 1.\]Parameters: AICs (list) – List of AIC values. Returns: Corresponding Akaike weights. Return type: np.ndarray
-
pyfrp.modules.pyfrp_stats_module.
computeCorrAIC
(fit, ROIs=None, sigma=1, fromSSD=True)¶ Computes corrected Akaike Information Criterion of fit.
The AICc is defined by
\[AICc= AIC + \frac{2k(k+1)}{n-k-1},\]where \(n\) is the number of datapoints used for the fit and \(k\) is the number of free parameters. For the computation of the AIC, please refer to the documentation of
computeAIC()
.Note
If
ROIs=None
, will use all ROIs defined infit.ROIsFitted
. IfROIs
are specified, but not infit.ROIsFitted
, will simply skip them.If the AIC or the AICc should be used can be determined using
useAIC()
.Parameters: fit (pyfrp.subclasses.pyfrp_fit.fit) – Fit object.
Keyword Arguments: - ROIs (list) – List of ROIs to be considered for computation.
- sigma (float) – Standard deviation of normal distribution if known.
- fromSSD (bool) – Simply use SSD as maximum likelihood.
Returns: AICc of fit.
Return type: float
-
pyfrp.modules.pyfrp_stats_module.
computeFitRsq
(fit)¶ Computes R-squared values for fit object.
R-squared values contain:
- Mean R-squared value over all ROIs included in fit, stored in
fit.MeanRsq
. - Product of R-squared value over all ROIs included in fit, stored in
fit.Rsq
. - R-squared value for each ROIs included in fit, stored in
fit.RsqBuROI
.
Parameters: fit (pyfrp.subclasses.pyfrp_fit.fit) – Fit object. Returns: Updated fit object. Return type: pyfrp.subclasses.pyfrp_fit.fit - Mean R-squared value over all ROIs included in fit, stored in
-
pyfrp.modules.pyfrp_stats_module.
computeLogLikelihood
(fit, ROIs=None, neg=True, sigma=1)¶ Computes log-likelihood of fit assuming normal distribution of data around fit.
Generally we assume that the data is distributed normally around the fitted model, that is
\[(m-d) \sim \mathcal{N}(0,\sigma)\]Assuming that all measurements are independent, this results in a likelihood function of
\[\prod\limits_{j=1}^{n} \frac{1}{\sigma \sqrt{2\pi}} \exp\left(-\frac{(m_j-d_j)^2}{2\sigma^2}\right)\]resulting in a log-likelihood function of
\[- \frac{n}{2} \log (2\pi) - \frac{\sum\limits_{j=1}^{n} (m_j-d_j)^2 }{2\sigma^2}\]Function allows to compute both negative and positive log-likelihood by
neg
flag.If the standard deviation \(sigma\) is unknown, but the log-likelihood is only needed for model comparison reasons over the same dataset, all sigma dependent terms can be ignored. Thus this function returns both SSD and log-likelihood.
Note
If
ROIs=None
, will use all ROIs defined infit.ROIsFitted
. IfROIs
are specified, but not infit.ROIsFitted
, will simply skip them.Parameters: fit (pyfrp.subclasses.pyfrp_fit.fit) – Fit object.
Keyword Arguments: - ROIs (list) – List of ROIs to be considered for computation.
- neg (bool) – Compute negative log-likehood.
- sigma (float) – Standard deviation of normal distribution if known.
Returns: Tuple containing:
- sign (float): Sign of likelihood function (-1/1).
- SSD (float): SSD of fit over all ROIs specified in ROIs.
- logLL (float): Log-likehood function at
sigma=sigma
Return type: tuple
-
pyfrp.modules.pyfrp_stats_module.
computeSSD
(data, x)¶ Computes sum of squared differences (SSD) of fit series to data series.
The SSD is computed by
\[SSD = \sum\limits_i (x_i - d_i)^2\]Parameters: - x (numpy.ndarray) –
- data (numpy.ndarray) – Data series.
Returns: SSD.
Return type: float
-
pyfrp.modules.pyfrp_stats_module.
overlapSubSampleError
(d, n, k)¶ Computes error between overlapping subsamples.
Error is calculated by
\[\left|\frac{\bar{d_i}+\epsilon}{\bar{d_j}+\epsilon}\right|,\]where \(i,j \in {1,..,\frac{N}{n-k}}\) and \(\epsilon\) is some offset to avoid singularties.
Note
The resulting error matrix is symmetric.
Parameters: - d (numpy.ndarray) – Data vector.
- n (int) – Size of subsamples.
- k (int) – Overlap.
Returns: Error matrix.
Return type: numpy.ndarray
-
pyfrp.modules.pyfrp_stats_module.
overlapSubSampleSelect
(d, n, k)¶ Takes subsamples of size
n
that overlap on both sides byk
points out of d.Algorithm collects snippets of d from \(j(n-k)\) to \((j+1)n-jk\), where \(j\) is the counter for the subsamples.
Parameters: - d (numpy.ndarray) – Data vector.
- n (int) – Size of subsamples.
- k (int) – Overlap.
Returns: List of
numpy.ndarray
of overlapping subsamples.Return type: list
-
pyfrp.modules.pyfrp_stats_module.
parameterStats
(x)¶ Returns mean, standard deviation and standard error of array.
Note that standard error is computed as
\[\sigma_n = \frac{\sigma}{\sqrt{n}}\]where \(n\) is the number of samples in
x
and :math: \(\sigma\) is the standard deviation overx
.Parameters: x (numpy.ndarray) – List of values. Returns: Tuple containing: - xMean (float): Mean of x.
- xStd (float): Standard deviation of x.
- xSterr (float): Standard error of x.
Return type: tuple
-
pyfrp.modules.pyfrp_stats_module.
selectDataByOverlapSubSample
(d, n, k, thresh, debug=False)¶ Selects data vector based on overlapping subsampling and simple thresholding.
This algorithm combines local derivatives with global changes and filters both datasets that have large local changes as well as large global changes. However, taking means over subsamples prevents neglecting data sets that have short peaks over only 1 or 2 time points, such as bubbles etc.
Parameters: - d (numpy.ndarray) – Data vector.
- n (int) – Size of subsamples.
- k (int) – Overlap.
- thresh (float) – Selecting threshold.
Keyword Arguments: debug (bool) – Print debugging messages.
Returns: True if data set should be neglected.
Return type: bool
-
pyfrp.modules.pyfrp_stats_module.
useAIC
(n, k)¶ Returns if corrected or not corrected version of the AIC should be used.
Rule of thumb is that AIC should be used if
\[\frac{n}{k}>40,\]where \(n\) is the number of datapoints used for the fit and \(k\) is the number of free parameters.
Returns: True
, use AIC,False
use AICc.Return type: bool
pyfrp.modules.pyfrp_term_module module¶
Terminal module for PyFRAP toolbox. Provides extra functions for a nicer custom output inside a Python/bash terminal.
-
pyfrp.modules.pyfrp_term_module.
getArrayDetailsString
(l)¶ Returns string saying “Array of shape x”, where x is the shape of the array.
Parameters: l (numpy.ndarray) – Some array. Returns: Printout of type and shape. Return type: str
-
pyfrp.modules.pyfrp_term_module.
getFunctionCall
(idx=1)¶ Returns the name of function or method that was called idx frames outwards.
Note
idx=0
will of course returngetFunctionCall
.Parameters: idx (int) – Steps outwards. Returns: Name of function or method. Return type: str
-
pyfrp.modules.pyfrp_term_module.
getListDetailsString
(l)¶ Returns string saying “List of length x”, where x is the length of the list.
Parameters: l (list) – Some list. Returns: Printout of type and length. Return type: str
-
pyfrp.modules.pyfrp_term_module.
printAllObjAttr
(obj, maxL=5)¶ Prints all object attributes in the form attributeName = attributeValue.
If attributes are of type
list
ornumpy.ndarray
, will check if the size exceeds threshold. If so, will only print type and dimension of attribute.Parameters: obj (object) – Object to be printed. Keyword Arguments: maxL (int) – Maximum length threshold.
-
pyfrp.modules.pyfrp_term_module.
printAttr
(name, attr, maxL=5)¶ Prints single attribute in the form attributeName = attributeValue.
If attributes are of type
list
ornumpy.ndarray
, will check if the size exceeds threshold. If so, will only print type and dimension of attribute.Parameters: - name (str) – Name of attribute.
- attr (any) – Attribute value.
Keyword Arguments: maxL (int) – Maximum length threshold.
-
pyfrp.modules.pyfrp_term_module.
printDict
(dic, maxL=5)¶ Prints all dictionary entries in the form key = value.
If attributes are of type
list
ornumpy.ndarray
, will check if the size exceeds threshold. If so, will only print type and dimension of attribute.Parameters: dic (dict) – Dictionary to be printed. Returns: True Return type: bool
-
pyfrp.modules.pyfrp_term_module.
printError
(txt, showCall=True, idx=2)¶ Prints Error of the form “ERROR: txt”, while error is rendered red.
Parameters: txt (str) – Text to be printed:
Keyword Arguments: - showCall (bool) – Show function in which print function was called.
- idx (int) – Traceback index that is given to
pyfrp.modules.pyfrp_term_module.getFunctionCall()
.
-
pyfrp.modules.pyfrp_term_module.
printNote
(txt, showCall=True, idx=2)¶ Prints note of the form “NOTE: txt”, while note is rendered green.
Parameters: txt (str) – Text to be printed:
Keyword Arguments: - showCall (bool) – Show function in which print function was called.
- idx (int) – Traceback index that is given to
pyfrp.modules.pyfrp_term_module.getFunctionCall()
.
-
pyfrp.modules.pyfrp_term_module.
printObjAttr
(var, obj)¶ Prints single object attribute in the form attributeName = attributeValue. :param var: Name of attribute. :type var: str :param obj: Object to be printed. :type obj: object
Returns: Name of attribute. Return type: str
-
pyfrp.modules.pyfrp_term_module.
printTable
(l, header, col=False)¶ Prints table using tabulate package.
If
col=True
, columns are given vial
, otherwise rows are given.Parameters: - l (list) – List of rows or columns.
- header (list) – List of headers.
- col (bool) – Flag on how rows/columns are given.
Returns: Tuple containing:
- header (list): Header of table.
- table (list): Table as a list of rows.
Return type: tuple
-
pyfrp.modules.pyfrp_term_module.
printWarning
(txt, showCall=True, idx=2)¶ Prints Warning of the form “WARNING: txt”, while warning is rendered yellow.
Parameters: txt (str) – Text to be printed:
Keyword Arguments: - showCall (bool) – Show function in which print function was called.
- idx (int) – Traceback index that is given to
pyfrp.modules.pyfrp_term_module.getFunctionCall()
.
pyfrp.modules.pyfrp_vtk_module module¶
VTK module for PyFRAP toolbox.
Contains functions that allow drawing/plotting via VTK. For more information about VTK, go to www.vtk.org and http://www.vtk.org/Wiki/VTK/Examples/Python .
-
pyfrp.modules.pyfrp_vtk_module.
drawVTKArc
(pStart, pCenter, pEnd, color=[0, 0, 0], renderer=None, res=32)¶ Draws VTK arc object defined through 3 points into renderer.
If
renderer=None
, will create actor but not add it to renderer.Parameters: - pStart (numpy.ndarray) – Coordinate of start point.
- pCenter (numpy.ndarray) – Coordinate of center point.
- pEnd (numpy.ndarray) – Coordinate of end point.
Keyword Arguments: - color (list) – Color of sphere in normed RGB values.
- renderer (vtk.vtkRenderer) – Renderer to draw in.
- res (int) – Resolution of arc.
Returns: VTK actor.
Return type: vtk.vtkActor
-
pyfrp.modules.pyfrp_vtk_module.
drawVTKLine
(p1, p2, color=[0, 0, 0], renderer=None)¶ Draws VTK line object going from point 1 to point 2 into renderer.
If
renderer=None
, will create actor but not add it to renderer.Parameters: - p1 (numpy.ndarray) – Coordinate of point 1.
- p2 (numpy.ndarray) – Coordinate of point 2.
Keyword Arguments: - color (list) – Color of sphere in normed RGB values.
- renderer (vtk.vtkRenderer) – Renderer to draw in.
Returns: VTK actor.
Return type: vtk.vtkActor
-
pyfrp.modules.pyfrp_vtk_module.
drawVTKPoint
(p, asSphere=True, color=[0, 0, 0], size=10, renderer=None)¶ Draws point into renderer.
If
renderer=None
, will create actor but not add it to renderer.Parameters: p (numpy.ndarray) – Position of point.
Keyword Arguments: - color (list) – Color of sphere in normed RGB values.
- size (float) – Size of vertex/radius of sphere.
- asSphere (bool) – Draw point as sphere.
- renderer (vtk.vtkRenderer) – Renderer to draw in.
Returns: VTK actor.
Return type: vtk.vtkActor
-
pyfrp.modules.pyfrp_vtk_module.
drawVTKPolyLine
(pts, closed=False, color=[0, 0, 0], renderer=None)¶ Draws VTK polyLine object defined through points into renderer.
If
renderer=None
, will create actor but not add it to renderer.Parameters: pts (list) – Coordinates of points.
Keyword Arguments: - color (list) – Color of sphere in normed RGB values.
- renderer (vtk.vtkRenderer) – Renderer to draw in.
- closed (bool) – Close line.
Returns: VTK actor.
Return type: vtk.vtkActor
-
pyfrp.modules.pyfrp_vtk_module.
drawVTKSphere
(center, radius, color=[0, 0, 0], renderer=None)¶ Draws vtk source sphere with given center and radius into renderer.
If
renderer=None
, will create actor but not add it to renderer.Parameters: - center (numpy.ndarray) – Center of sphere.
- radius (float) – Radius of sphere.
Keyword Arguments: - color (list) – Color of sphere in normed RGB values.
- renderer (vtk.vtkRenderer) – Renderer to draw in.
Returns: VTK actor.
Return type: vtk.vtkActor
-
pyfrp.modules.pyfrp_vtk_module.
drawVTKText
(text, position, fontSize=18, color=[0, 0, 0], renderer=None)¶ Draws text in renderer.
Parameters: - text (str) – Text.
- position (numpy.ndarray) – Position where to draw it.
Keyword Arguments: - fontSize (int) – Font Size.
- color (list) – Color of text in normed RGB values.
- renderer (vtk.vtkRenderer) – Renderer to draw in.
Returns: Text actor
Return type: vtk.vtkTextActor
-
pyfrp.modules.pyfrp_vtk_module.
drawVTKVertex
(p, color=[0, 0, 0], size=20, renderer=None)¶ Draws vtk vertex given its position into renderer.
If
renderer=None
, will create actor but not add it to renderer.Parameters: p (numpy.ndarray) – Position of vertex.
Keyword Arguments: - color (list) – Color of sphere in normed RGB values.
- size (float) – Size of vertex.
- renderer (vtk.vtkRenderer) – Renderer to draw in.
Returns: VTK actor.
Return type: vtk.vtkSphereSource
-
pyfrp.modules.pyfrp_vtk_module.
getVTKActor
(color)¶ Returns VTK actor object and colors it.
Note
Colors can also be given as matplotlib string colors.
Parameters: color (list) – Color of sphere in normed RGB values. Returns: VTK actor. Return type: vtk.vtkActor
-
pyfrp.modules.pyfrp_vtk_module.
getVTKArc
(pStart, pCenter, pEnd, res=32)¶ Returns VTK arc object defined through 3 points.
Parameters: - pStart (numpy.ndarray) – Coordinate of start point.
- pCenter (numpy.ndarray) – Coordinate of center point.
- pEnd (numpy.ndarray) – Coordinate of end point.
Keyword Arguments: res (int) – Resolution of arc.
Returns: VTK actor.
Return type: vtk.vtkActor
-
pyfrp.modules.pyfrp_vtk_module.
getVTKLine
(p1, p2)¶ Returns VTK line object going from point 1 to point 2.
Parameters: - p1 (numpy.ndarray) – Coordinate of point 1.
- p2 (numpy.ndarray) – Coordinate of point 2.
Returns: VTK line object.
Return type: vtk.vtkLine
-
pyfrp.modules.pyfrp_vtk_module.
getVTKOutput
(obj)¶ Returns the fitting vtk output.
Fixes versioning problems between vtk versions 5 and older.
Parameters: obj (vtk.vtkObject) – A VTK object. Returns: VTK poly data. Return type: vtk.vtkPolyData
-
pyfrp.modules.pyfrp_vtk_module.
getVTKPolyDataMapper
(polyData)¶ Returns a VTK poly data mapper.
Fixes versioning problems between vtk versions 5 and older.
Parameters: obj (vtk.vtkPolyData) – A VTK poly data object. Returns: VTK poly data mapper. Return type: vtk.vtkPolyDataMapper
-
pyfrp.modules.pyfrp_vtk_module.
getVTKPolyLine
(pts, closed=False)¶ Returns VTK polyLine object defined through points.
Parameters: pts (list) – Coordinates of points. Keyword Arguments: closed (bool) – Close line. Returns: VTK polyData. Return type: vtk.vtkPolyData
-
pyfrp.modules.pyfrp_vtk_module.
getVTKSphere
(center, radius)¶ Returns vtk source sphere object with given center and radius.
Parameters: - center (numpy.ndarray) – Center of sphere.
- radius (float) – Radius of sphere.
Returns: VTK sphere.
Return type: vtk.vtkSphereSource
-
pyfrp.modules.pyfrp_vtk_module.
makeVTKCanvas
(offScreen=False, bkgd=[1, 1, 1], renderer=None)¶ Creates a vtk renderer and includes it into a renderer window.
Warning
offScreen=True
is still in development.If
renderer
is given, will just create the render Window and interactor around it.Keyword Arguments: - offScreen (bool) – Don’t show Window.
- bkgd (list) – Background color of renderer in normed RGB values.
- renderer (vtk.vtkRenderer) – Renderer.
Returns: Tuple containing:
- renderer (vtk.renderer): Renderer.
- renderWindow (vtk.renderWindow): Render Window.
- renderWindowInteractor (vtk.renderWindowInteractor): Render Window Interactor.
Return type: tuple
-
pyfrp.modules.pyfrp_vtk_module.
renderVTK
(renderer)¶ Renders everything contained in renderWindow and starts Interactor.
Parameters: renderer (vtk.vtkRenderer) – A renderer. Returns: Renderer. Return type: vtk.vtkRenderer
pyfrp.modules.pyfrp_zstack_module module¶
Z-stack module for PyFRAP toolbox. Used for reading z-stack datasets and converting them into meshes that then can be used for a FRAP simulation.
Warning
This module is still experimental and unfinished and should not be used. Will be added as stable in further versions.
-
pyfrp.modules.pyfrp_zstack_module.
fillEndStacks
(n, debug=False)¶
-
pyfrp.modules.pyfrp_zstack_module.
getContours
(img, kernel=(10, 10))¶
-
pyfrp.modules.pyfrp_zstack_module.
interpolateContourGaps
(contours)¶
-
pyfrp.modules.pyfrp_zstack_module.
point_inside_polygon
(x, y, poly)¶
Module contents¶
PyFRAP: A Python based FRAP analysis tool box. Basic modules.