Welcome to PyFRAP’s API!¶
PyFRAP is a extensive Python based FRAP (Fluorescence Recovery After Photobleaching) analysis software, featuring various tools that help analyzing FRAP datasets, such as
- Import FRAP datasets from timelapse experiments and analyze image data with various options such as
- various filters
- background substraction
- illumination correction
- Simulate the FRAP experiment with exact interpolated initial conditions
- Fit simulated experiment to analyzed data and extract diffusion coefficient
- Statistical analysis of fitting results
- Hierarchical data structure making data exchange/sharing easy
- Comprehensive GUI, making almost all PyFRAP tools available
I have tried to keep the API short but clear. If it is unclear, don’t hesitate to mail.
Installation (setup.py)¶
Installing PyFRAP via setup.py¶
PyFRAP can conveniently be installed via:
python setup.py install
Since PyFRAP requires on I/O of data files that come with it we recommend using:
python setup.py install --user
setuptools comes with multiple installation options, to check them out, type:
python setup.py install --help
PyFRAP has some additional installation options:
Option | Effect |
---|---|
--fiji |
Download and install Fiji during PyFRAP installation. Link Fiji with PyFRAP |
--gmsh |
Download and install Gmsh during PyFRAP installation. Link Gmsh with PyFRAP |
--silent |
Print out less log messages. |
For --fiji
and --gmsh
to work, you need to install wget. To install wget, type:
pip install wget
or if you use the Ananconda distribution:
conda install pywget
PyFRAP setup.py API¶
-
getOptions
()¶ Checks options given to script:
- If
--fiji
is in sys.argv, will set dFiji=1. n - If
--gmsh
is in sys.argv, will set dGmsh=1. - If
--silent
is in sys.argv, will set silent=1.
Note
Makes dGmsh and dFiji global: Not nice but seems easiest way to get options into OverrideInstall.
- If
-
getOpt
(optStr)¶ Checks if optStr is in
sys.argv
. If this is the case, returns 1 and removes it formsys.argv
sosetup.py
will not crash, otherwise returns 0.
-
class
OverrideInstall
(install)¶ Override class subclassing
install
class fromsetuptools
.The Main purpose of this class is to give more possibilities when installing PyFRAP, such as:
- Download Gmsh and enter it automatically into path spec file
- Download Fiji and enter it automatically into path spec file
- Set ownership of data files so that even PyFRAP gets installed as superuser, users will be able to use its full capacities.
Idea taken from here (thanks a bunch!)
-
initOptions
()¶ Parses options into override class.
-
run
()¶ Runs install.
-
addData
()¶ Adds Datafiles to PyFRAP installation.
Makes sure that $USER has proper read/write/execute rights. Note that for Windows it will change rights, since it is not necesary. n Also makes sure that gmsh/Fiji bin ins properly linked.
-
cleanUpExe(fnDL,folderFn,filesBefore,exePath):
Moves it to executables directory and cleans up afterwards.
Parameters: - fnDL (str) – Filename of downloaded file.
- folderFn (str) – Filename of folder containing extracted files.
- filesBefore (list) – Snapshot of
cwd
. - exePath (str) – Path where executables go.
-
downloadGmsh
()¶ Downloads Gmsh, moves it to executables directory and cleans up afterwards.
Note
Only works if
wget
is installed.
-
downloadGmshWin
(arch, gmshVersion)¶ Downloads Gmsh from Gmsh website for Windows
Parameters: - arch (str) – System architecture, e.g. 64/32.
- gmshVersion (str) – gmshVersion String, e.g. 2.12.0 .
Returns: (Donwload filename, Filename of extracted download files)
Return type: (str ,str)
-
downloadGmshOSX
(arch, gmshVersion)¶ Downloads Gmsh from Gmsh website for OSX.
Parameters: - arch (str) – System architecture, e.g. 64/32.
- gmshVersion (str) – gmshVersion String, e.g. 2.12.0 .
Returns: (Donwload filename, Filename of extracted download files)
Return type: (str ,str)
-
downloadGmshLinux
(arch, gmshVersion)¶ Downloads Gmsh from Gmsh website for Linux.
Parameters: - arch (str) – System architecture, e.g. 64/32.
- gmshVersion (str) – gmshVersion String, e.g. 2.12.0 .
Returns: (Donwload filename, Filename of extracted download files)
Return type: (str ,str)
-
makeExeFolder
()¶ Make executables folder if it doesn’t exist yet
-
downloadFiji
()¶ Downloads Gmsh, moves it to executables directory and cleans up afterwards.
Note
Only works if
wget
is installed.
-
downloadFijiLinux
(arch)¶ Downloads Fiji from Fiji website for Linux.
Parameters: arch (str) – System architecture, e.g. 64/32. Returns: (Donwload filename, Filename of extracted download files) Return type: (str ,str)
-
downloadFijiWin
(arch)¶ Downloads Fiji from Fiji website for Windows.
Parameters: arch (str) – System architecture, e.g. 64/32. Returns: (Donwload filename, Filename of extracted download files) Return type: (str ,str)
-
downloadFijiOSX
()¶ Downloads Fiji from Fiji website for OSX.
Returns: (Donwload filename, Filename of extracted download files) Return type: (str ,str)
-
setExePath
(fn, identifier, exePath)¶ Enters executable path into path spec file.
Parameters: - fn (str) – Path to gmsh executable.
- identifier (str) – Identifier in spec file.
- exePath (str) – Path to exe file
-
setGmshPath
(fn)¶ Enters gmsh executable path into path spec file.
Parameters: fn (str) – Path to gmsh executable.
-
setFijiPath
(fn)¶ Enters fiji executable path into path spec file.
Parameters: fn (str) – Path to fiji executable.
-
changePermissions
(filepath, uid, gid, mode)¶ Sets File Permissions.
Parameters: - filepath (str) – Path to file.
- uid (int) – user ID.
- gid (int) – group ID.
- mode (int) – Permission mode.
Returns: True if success
Return type: bool
-
makeAdditionalDataFolders
(folder, fn, uid, gid, mode)¶ Tries to generate additional data folders.
Parameters: - folder (str) – Path to containing folder.
- fn (str) – New folder name
- uid (int) – user ID.
- gid (int) – group ID.
- mode (int) – Permission mode.
Returns: True if success
Return type: bool
The modules package¶
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='140079914734032'>)¶ 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.
The subclasses package¶
pyfrp.subclasses package¶
Submodules¶
pyfrp.subclasses.pyfrp_ROI module¶
-
class
pyfrp.subclasses.pyfrp_ROI.
ROI
(embryo, name, Id, zmin='-inf', zmax='inf', color='b')¶ Bases:
object
-
adaptRefineInMeshByField
(nNodesReq, factor=3.0, addZ=15.0, zIncrement=1.0, fIncrement=1.0, nNodesMax='inf', debug=False, ROIReq=None, fnOut=None)¶ Refines mesh inside ROI adaptively until a given number of nodes inside ROI is reached.
Does this by:
- Refining through
refineInMeshByField()
. - Computing mesh indices via
computeMeshIdx()
. - If number of nodes did not change, increase
addZ
, else increasefactor
. - Check if desired number of nodes is reached or not, if not, repeat.
Note
If the new number of nodes in the ROI exceeds
nNodesMax
, will revert the last step and perform the other operation, e.g. increasingaddZ
instead offactor
and vice versa.Note
If
ROIReq
is given, will try to refine inself
such thatROIReq
has at leastnNodesReq
mesh nodes. If it is not given,nNodesReq
refers to the nodes inself
.Parameters: nNodesReq (int) – Desired number of nodes inside ROI.
Keyword Arguments: - factor (float) – Refinement factor.
- addZ (float) – Number of pixels added above and below ROI for box field.
- zIncrement (float) – Number of pixels addZ is increased per adaptive step.
- fIncrement (float) – Stepsize of refinement factor.
- nNodesMax (float) – Maximum number of nodes allowed in ROI.
- debug (bool) – Print debugging messages.
- ROIReq (pyfrp.subclasses.pyfrp_ROI.ROI) – The ROI object that is referred to with nNodesReq.
- fnOut (str) – Path to output geo file.
Returns: Final number of nodes in ROI.
Return type: int
- Refining through
-
addBoundaryLayerAtSurfaces
(fn=None, segments=48)¶ Adds boundary layer around ROI to the mesh.
Does this by:
- Generating a stl file describing ROI, see also
pyfrp.subclasses.pyfrp_ROI.ROI.render2StlInGeometry()
. - Read in stl file as new
pyfrp.modules.pyfrp_gmsh_geometry.domain
viapyfrp.modules.pyfrp_gmsh_IO_module.readStlFile()
. - Simplify new geometry via
pyfrp.modules.pyfrp_gmsh_geometry.domain.simplifySurfaces()
. - Extracting selected surfaces via
pyfrp.modules.pyfrp_gmsh_geometry.gmshElement.extract()
. - If selected, surface boundaries are approximated into splines via
pyfrp.modules.pyfrp_gmsh_geometry.gmshElement.extract()
. - Reading in geometry’s .geo file via
pyfrp.sublcasses.pyfrp_geometry.geometry.readGeoFile()
. - Merging ROI geometry into main geometry via
pyfrp.modules.pyfrp_gmsh_geometry.domain.merge()
. - Adding a boundary layer mesh via
pyfrp.modules.pyfrp_gmsh_geometry.domain.addBoundaryLayerField()
. - Adding all surfaces of ROI’s domain to boundary layer, see
pyfrp.modules.pyfrp_gmsh_geometry.boundaryLayerField.addFaceListByID()
. - Writing new .geo file.
- Setting new .geo file as
fnGeo
. - Running
genMesh()
. - Clean up .stl and .scad files that are not needed anymore.
Note
volSizeLayer
only allows a single definition of mesh size in layer. Note that thepyfrp.modules.pyfrp_gmsh_geometry.boundaryLayerField
class allows different mesh sizes normal and along surfaces. For more information, see its documentation.Note
If no
fnOut
is given, will save a new .geo file in same folder as originalfnGeo
with subfix:fnGeo_roiName_BL.geo
.Note
pyfrp.modules.pyfrp_gmsh_geometry.domain.simplifySurfaces()
is not a simple procedure, we recommend reading its documentation.If
volSizePx
is given, will overwrite mesh’svolSizePx
and set it globally at all nodes.Parameters: roi (pyfrp.subclasses.pyfrp_ROI.ROI) – An ROI.
Keyword Arguments: - fnOut (str) – Path to new .geo file.
- segments (int) – Number of segments used for convex hull of surface.
- simplify (bool) – Simplify surfaces of stl file.
- 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.
- volSizePx (float) – Global mesh density.
- volSizeLayer (float) – Boundary layer mesh size.
- thickness (float) – Thickness of boundary layer.
- cleanUp (bool) – Clean up temporary files when finished.
- approxBySpline (bool) – Approximate curvatures by spline.
- angleThresh (float) – Threshold angle under which loops are summarized.
- faces (list) – List of faces.
- onlyAbs (bool) – Take absolute value of faces into account.
Returns: Path to new .geo file.
Return type: str
- Generating a stl file describing ROI, see also
-
checkSymmetry
(debug=False)¶
-
checkZInside
(z)¶
-
computeExtIdx
(debug=False)¶ Computes indices of external pixels.
Does this by comparing extended pixels of
self
with the one of the master ROI.Keyword Arguments: debug (bool) – Print out debugging messages. Returns: Tuple containing: - extImgIdxX (list): External image indices in x direction.
- extImgIdxY (list): External image indices in y direction.
Return type: tuple
-
computeExtMask
()¶ Computes mask of extended pixels of ROI.
Mask is a 2D array with the value
1
for pixels inside ROI and0
elsewhere.Note
Returns
None,None,None
if there are no extended pixels.Also returns coordinate arrays, since offset of extended mask is not
[0,0]
. See also http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html .Returns: Tuple containing: - mX (numpy.ndarray): Coordinate array corresponding to pixels of extended mask.
- mY (numpy.ndarray): Coordinate array corresponding to pixels of extended mask.
- extMask (numpy.ndarray): Extended mask.
Return type: tuple
-
computeIdxs
(matchMesh=False, debug=False)¶ Computes image and mesh indices of ROI.
Will do this by:
- Compute image indices.
- Match image indices with master ROI.
- Compute external indices.
- Compute mesh indices.
- Match mesh indices with the ones of master ROI.
Note
If no master ROI is defined, will not do anything.
Note
If master ROI has not been indexed yet, will first index it, then continue.
Note
Will skip mesh index computation if there is no mesh generated yet.
Keyword Arguments: - matchMesh (bool) – Match mesh indices with master ROI.
- debug (bool) – Print out debugging messages.
Returns: Tuple containing:
- imgIdxX (list): Image indices in x direction.
- imgIdxY (list): Image indices in y direction.
- meshIdx (list): Mesh indices.
Return type: tuple
-
computeImgMask
()¶ Computes image mask of ROI.
Image mask is a
dataResPx * dataResPx
array with the value1
for pixels inside ROI and0
elsewhere.Returns: Image mask. Return type: numpy.ndarray
-
computeNumExt
()¶ Computes number of extended pixels of ROI.
Returns: Number of extended pixels. Return type: int
-
copyIdxs
(r)¶ Copies indices of other ROI and inserts them into ROI.
Parameters: r (pyfrp.subclasses.pyfrp_ROI.ROI) – ROI to take indices from. Returns: Tuple containing: - imgIdxX (list): Image indices in x-direction.
- imgIdxY (list): Image indices in y-direction.
- meshIdx (list): Mesh indices.
Return type: tuple
-
emptyIdxs
()¶ Flushes all indices, inserting empty lists for all of them.
Returns: Tuple containing: - imgIdxX (list): Image indices in x-direction.
- imgIdxY (list): Image indices in y-direction.
- meshIdx (list): Mesh indices.
Return type: tuple
-
findIncluded
()¶ Returns list of
pyfrp.subclasses.pyfrp_ROI.customROI
objects in which ROI is included.Returns: List of customROIs. Return type: list
-
genAsOpenscadInGeometry
()¶ Generates intersection between ROI and geometry as solid python object.
See also
pyfrp.subclasses.pyfrp_geometry.geometry.genAsOpenscad()
andpyfrp.subclasses.pyfrp_ROI.ROI.genAsOpenscad()
.Returns: Solid python object. Return type: solid.solidpython.cylinder
-
genGmshDomain
(volSizePx=20.0, genLoops=True, genSurfaces=True, genVol=True, minID=None)¶ Translates ROI into gmsh domain object.
This object can then be used to write ROIs to
.geo
files.Note
If
minID==None
, will grab maximum ID viapyfrp.subclasses.pyfrp_geometry.geometry.getMaxGeoID()
and add 1.Keyword Arguments: - volSizePx (float) – Mesh size of vertices.
- genLoops (bool) – Generate line loops.
- genSurfaces (bool) – Generate surfaces.
- genVol (bool) – Generate surface loop and corresponding volume.
- minID (int) – Id at which geo IDs should start.
Returns: Domain object.
Return type:
-
genMeshFile
(fn=None, volSizePx=20.0, debug=False, minID=None)¶ Writes ROI to geo file.
Note
If
fn
is not given, will save .msh file of ROI in same folder as the geometry file of the embryo with the following path:path/to/embryos/geo/file/nameOfEmbryo_nameOfROI.msh
.See also
pyfrp.subclasses.pyfrp_ROI.polySliceROI.writeToGeoFile()
.Keyword Arguments: - volSizePx (float) – Mesh size of vertices.
- genLoops (bool) – Generate line loops.
- genSurfaces (bool) – Generate surfaces.
- genVol (bool) – Generate surface loop and corresponding volume.
- minID (int) – Id at which geo IDs should start.
Returns: Path to mesh file.
Return type: str
-
getAllIdxs
()¶ Returns all index arrays of ROI.
Returns: Tuple containing: - imgIdxX (list): Image indices in x-direction.
- imgIdxY (list): Image indices in y-direction.
- meshIdx (list): Mesh indices.
Return type: tuple
-
getArea
()¶ Returns area of ROI.
Area is computed as area covered by
imgMask + extMask
Returns: Area of ROI. Return type: float
-
getColor
()¶ Returns color of ROI.
-
getCopy
()¶ Returns deepcopy of ROI object.
Uses
copy.copy
to generate copy of object, see also https://docs.python.org/2/library/copy.html .copy.deepcopy
also generates copies of other objects, includingROI.embryo
.
-
getDataVec
()¶ Returns current data vector of ROI.
Returns: Current data vector. Return type: numpy.ndarray
-
getEncapsulatingBox
()¶ Returns encapsulating box of ROI.
That is, a box defined by
[xmin,xmax],[ymin,ymax],[zmin,zmax]
in which ROI lies fully within.Returns: Tuple containing: - xExtend (list): List describing extend in x-direction (
[xmin,xmax]
). - yExtend (list): List describing extend in y-direction (
[ymin,ymax]
). - zExtend (list): List describing extend in z-direction (
[zmin,zmax]
).
Return type: tuple - xExtend (list): List describing extend in x-direction (
-
getExtImgIdx
()¶ Returns extended image indices of ROI.
Returns: Tuple containing: - extImgIdxX (list): Extended image indices in x-direction.
- extImgIdxY (list): Extended image indices in y-direction.
Return type: tuple
-
getExtMask
()¶ Returns extended mask of ROI.
Returns: Extended mask. Return type: numpy.ndarray
-
getExtend
()¶ Returns x-/y-/z-extend of ROI.
Returns: Tuple containing: - xmin (float): Minimum x-coordinate.
- xmax (float): Maximum x-coordinate.
- ymin (float): Minimum y-coordinate.
- ymax (float): Maximum y-coordinate.
- zmin (float): Minimum z-coordinate.
- zmax (float): Maximum z-coordinate.
Return type: tuple
-
getFittedVec
(fit)¶ Returns fitted simulation vector of ROI of given fit.
Note
To avoid crashes, function returns empty list if ROI is in
ROIsFItted
but has not been fitted yet. Also inserts an empty list at the respective index.Parameters: fit (pyfrp.subclasses.pyfrp_fit) – Fit object. Returns: Fitted simulation vector. Return type: numpy.ndarray
-
getId
()¶ Returns Id of ROI.
Returns: Id. Return type: int
-
getImgIdx
()¶ Returns image indices of ROI.
Returns: Tuple containing: - imgIdxX (list): Image indices in x-direction.
- imgIdxY (list): Image indices in y-direction.
Return type: tuple
-
getImgMask
()¶ Returns image mask of ROI.
Returns: Image mask. Return type: numpy.ndarray
-
getInterpolationError
()¶ Prints out interpolation error for the volume of this ROI.
Interpolation error is defined as:
dataVec[0]/simVec[0]
,That is, by how much does the first simulation value defer from first data value.
Returns: Interpolation error. Return type: float
-
getMaxExtendPlane
()¶ Returns in which plane (“xy”,”xz”,”yz”) the ROI has the biggest extend.
Returns: Plane with largest extend. Return type: str
-
getMaxNodeDistance
()¶ Returns maximum node distance in x/y/z direction for all nodes in ROI.
Returns: Tuple containing: - dmaxX (float): Maximum distance in x-direction
- dmaxY (float): Maximum distance in y-direction
- dmaxZ (float): Maximum distance in z-direction
Return type: tuple
-
getMeshDensity
()¶ Returns average mesh density inside ROI.
Mesh density is defined by
\[\rho=N/V,\]where \(N\) is the number of mesh nodes inside ROI and \(V\) is the volume of ROI, see also
getVolume()
.Returns: Mesh density. Return type: float
-
getMeshIdx
()¶ Returns mesh indices of ROI.
Returns: Mesh indices of ROI. Return type: list
-
getMeshIdxExtend
()¶ Returns extend of ROI’s
meshIdx
.Returns: Tuple containing: - (float): Minimum x-coordinate.
- (float): Maximum x-coordinate.
- (float): Minimum y-coordinate.
- (float): Maximum y-coordinate.
- (float): Minimum z-coordinate.
- (float): Maximum z-coordinate.
Return type: tuple
-
getMeshIdxXExtend
()¶ Returns extend of ROI’s
meshIdx
in x-coordinate.Returns: Tuple containing: - (float): Minimum x-coordinate.
- (float): Maximum x-coordinate.
Return type: tuple
-
getMeshIdxYExtend
()¶ Returns extend of ROI’s
meshIdx
in y-coordinate.Returns: Tuple containing: - (float): Minimum y-coordinate.
- (float): Maximum y-coordinate.
Return type: tuple
-
getMeshIdxZExtend
()¶ Returns extend of ROI’s
meshIdx
in z-coordinate.Returns: Tuple containing: - (float): Minimum z-coordinate.
- (float): Maximum z-coordinate.
Return type: tuple
-
getNImgPxs
()¶ Returns number of image pixels inside ROI.
Returns: Number of indices. Return type: int
-
getNMeshNodes
()¶ Returns number of mesh indices inside ROI.
Returns: Number of nodes. Return type: int
-
getName
()¶ Returns name of ROI.
Returns: Current name. Return type: str
-
getNumExt
()¶ Returns number of extended pixels of ROI.
Returns: Number of extended pixels. Return type: int
-
getOpenscadZExtend
()¶ Returns extend in z-direction suitable for rendering the ROI via openscad.
If either
zmin
orzmax
is infinity, then uses :py:func:getRealZExend to return more meaningful extend.Returns: Z-extend given by [zmin,zmax]
.Return type: list
-
getOrthogonal2Plane
()¶ Returns orthogonal direction to plane of maximum extension.
See also
pyfrp.subclasses.pyfrp_ROI.ROI.getPlaneMidCoordinate()
andpyfrp.subclasses.pyfrp_ROI.ROI.getMaxExtendPlane()
.Returns: Direction. Return type: str
-
getPlaneMidCoordinate
()¶ Returns midpoint of extend orthogonal to plane of maximum extension.
Returns: Midpoint. Return type: float
-
getROIHeight
()¶ Returns height of ROI.
Returns: Height of ROI. Return type: float
-
getRealZExend
()¶ Returns real extend in z-direction.
Real extend returns
\[z_{\mathrm{min}}=\mathrm{max} (z_{\mathrm{min,ROI}},z_{\mathrm{min,geometry}})\]and
\[z_{\mathrm{max}}=\mathrm{min} (z_{\mathrm{max,ROI}},z_{\mathrm{max,geometry}})\]Returns: Z-extend given by [zmin,zmax]
.Return type: list
-
getSimConc
(phi, append=True)¶ Computes the simulation concentration over ROI.
Parameters: phi (fipy.CellVariable) – Solution variable. Keyword Arguments: append (bool) – Append result to simulation vector. Returns: Simulation concentration over ROI. Return type: float
-
getSimVec
()¶ Returns current simulation vector of ROI.
Returns: Current simulation vector. Return type: numpy.ndarray
-
getType
()¶ Returns type of ROI, splitting off all module names etc. .
Returns: Type of ROI. Return type: str
-
getUseForRim
()¶ Returns if the ROI is used for rim calculation.
Returns: Current flag value. Return type: bool
-
getVolume
()¶ Returns volume of ROI.
Since ROIs only behave linearly in z-direction, volume is given by
\[V = A * h,\]where \(h\) is ROI height (see
getROIHeight()
) and \(A\) is ROI area (seegetArea()
).Returns: ROI volume. Return type: float
-
getZExtend
()¶ Returns extend in z-direction.
Returns: Z-extend given by [zmin,zmax]
.Return type: list
-
getdataVecFitted
(fit)¶ Returns fitted data vector of ROI of given fit.
Note
To avoid crashes, function returns empty list if ROI is in
ROIsFItted
but has not been fitted yet. Also inserts an empty list at the respective index.Parameters: fit (pyfrp.subclasses.pyfrp_fit) – Fit object. Returns: Fitted data vector. Return type: numpy.ndarray
-
idxs2Full
()¶
-
idxs2Quad
(debug=False)¶
-
isAnalyzed
()¶ Checks if ROI has been analyzed.
Returns: True if ROI has been analyzed. Return type: bool
-
isFitted
()¶ Checks if ROI has been fitted in ALL fits of embryo.
Returns: True if ROI has been fitted. Return type: bool
-
isMaster
()¶ Returns if ROI is masterROI.
Returns: True if masterROI. Return type: bool
-
isSimulated
()¶ Checks if ROI has been simulated.
Returns: True if ROI has been simulated. Return type: bool
-
matchImgIdx
(r)¶ Matches image indices of
self
with the ones of ROIr
.Does this by generating masks of both ROIs and multiplicating them.
Parameters: r (pyfrp.subclasses.pyfrp_ROI.ROI) – ROI to match with. Returns: Tuple containing: - imgIdxX (list): Matched image indices in x direction.
- imgIdxY (list): Matched image indices in y direction.
Return type: tuple
-
matchMeshIdx
(r, matchZ=False)¶
-
pinAllTS
(bkgdVal=None, normVal=None, bkgdValSim=None, normValSim=None, debug=False)¶ Pins both data and simulation timeseries of ROI.
See also
pyfrp.modules.pyfrp_fit_module.pinConc()
.Keyword Arguments: - bkgdVal (float) – Use this background value instead of newly computing it.
- normVal (float) – Use this norming value instead of newly computing it.
- bkgdValSim (float) – Use this background value for simulation timeseries instead of newly computing it.
- normValSim (float) – Use this norming value for simulation timeseries instead of newly computing it.
- debug (bool) – Print debugging messages.
Returns: Tuple containing:
- dataVecPinned (numpy.ndarray): Pinned data vector.
- simVecPinned (numpy.ndarray): Pinned simulation vector.
Return type: tuple
-
pinDataTS
(bkgdVal=None, normVal=None, debug=False)¶ Pins data timeseries of ROI.
See also
pyfrp.modules.pyfrp_fit_module.pinConc()
.Keyword Arguments: - bkgdVal (float) – Use this background value instead of newly computing it.
- normVal (float) – Use this norming value instead of newly computing it.
- debug (bool) – Print debugging messages.
Returns: Pinned data vector.
Return type: numpy.ndarray
-
pinSimTS
(bkgdVal=None, normVal=None, debug=False)¶ Pins simulation timeseries of ROI.
See also
pyfrp.modules.pyfrp_fit_module.pinConc()
.Keyword Arguments: - bkgdVal (float) – Use this background value instead of newly computing it.
- normVal (float) – Use this norming value instead of newly computing it.
- debug (bool) – Print debugging messages.
Returns: Pinned simulation vector.
Return type: numpy.ndarray
-
plotData
(ax=None, color=None, linewidth=1, legend=True, linestyle='-', label=None, legLoc=-1)¶ Plot data vector of ROI.
If no color is specified, will use color specified in
ROI.color
.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.
- legLoc (int) – Location of legend.
Returns: Axes used for plotting.
Return type: matplotlib.axes
-
plotDataPinned
(ax=None, color=None, linewidth=1, legend=True, linestyle='-', label=None, legLoc=-1)¶ Plot pinned data vector of ROI.
If no color is specified, will use color specified in
ROI.color
.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.
- legLoc (int) – Location of legend.
Returns: Axes used for plotting.
Return type: matplotlib.axes
-
plotFit
(fit, ax=None, color=None, linewidth=1, legend=True, title=None, linestyles=['-', '-.'], show=True)¶ Plot fit for ROI.
If no color is specified, will use color specified in
ROI.color
.Keyword Arguments: - ax (matplotlib.axes) – Matplotlib axes used for plotting. If not specified, will generate new one.
- color (str) – Color of plot.
- linestyles (list) – Linestyles of data and simulation.
- linewidth (float) – Linewidth of plot.
- legend (bool) – Show legend.
- show (bool) – Show figure.
Returns: Axes used for plotting.
Return type: matplotlib.axes
-
plotSim
(ax=None, color=None, linewidth=1, legend=True, linestyle='--', label=None, legLoc=-1)¶ Plot simulation vector of ROI.
If no color is specified, will use color specified in
ROI.color
.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.
- legLoc (int) – Location of legend.
Returns: Axes used for plotting.
Return type: matplotlib.axes
-
plotSimConcProfile
(phi, ax=None, direction='x', mode='normal', nbins=20, color=None, label=None, legend=False)¶ Plots concentration profile of solution variable in single direction.
mode
can be either"normal"
or"hist"
. Ifmode="hist"
, will plot a histogram withnbins
bins usingpyfrp.modules.pyfrp_misc_module.simpleHist()
.Note
direction
sets in which direction the profile should be plotted. ifdirection="r"
, then function will plot a radial profile and usesself.embryo.geometry.center
as center if ROI does not have a center, else uses center of ROI.Note
Will create axes if not given via
ax
.Example:
Grab ROI:
>>> sl=emb.getROIByName("Slice")
Make some plot:
>>> fig,axes=pyfrp_plot_module.makeSubplot([2,2])
Plot some concentration profiles:
>>> ax=sl.plotSimConcProfile(emb.simulation.IC,mode='hist',color='g',label='direction = x',nbins=100,ax=axes[0],legend=False) >>> ax=sl.plotSimConcProfile(emb.simulation.IC,mode='hist',direction='y',color='r',label='direction = y',nbins=100,ax=axes[1],legend=False) >>> ax=sl.plotSimConcProfile(emb.simulation.IC,mode='hist',direction='r',color='b',nbins=100,label='direction = r',ax=axes[2],legend=False) >>> ax=sl.plotSimConcProfile(emb.simulation.IC,mode='normal',direction='r',color='b',label='direction = r',ax=axes[3],legend=False)
Parameters: phi (fipy.CellVariable) – Solution variable
Keyword Arguments: - ax (matplotlib.axes) – Axes to be plotted in.
- direction (str) – Direction to be plotted (x/y/z/r).
- color (str) – Color of plot.
- legend (bool) – Show legend.
- label (str) – Label of plot.
- nbins (int) – Number of bins of histogram.
- mode (str) – Either
normal
orhist
.
Returns: Matplotlib axes used for plotting.
Return type: matplotlib.axes
-
plotSimPinned
(ax=None, color=None, linewidth=1, legend=True, linestyle='--', label=None, legLoc=-1)¶ Plot pinned simulation vector of ROI.
If no color is specified, will use color specified in
ROI.color
.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.
- legLoc (int) – Location of legend.
Returns: Axes used for plotting.
Return type: matplotlib.axes
-
plotSolutionVariable
(phi, ax=None, vmin=None, vmax=None, nlevels=25, colorbar=True, plane='xy', zs=None, zdir=None, mask=True, nPts=1000, mode='normal', title='Solution Variable', typ='contour')¶ Plots simulation solution variable over all indices of ROI as 2D contour plot.
Note
If no
ax
is given, will create new one.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()
.See also http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.tricontourf .
Warning
matplotlib.pyplot.tricontourf
has problems whenphi
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.You can find a more detailed explanation in the documentation of
pyfrp.modules.pyfrp_plot_module.plotSolutionVariable()
.Parameters: phi (fipy.CellVariable) – Solution variable.
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
-
printDetails
()¶ Prints out all attributes of ROI object.
-
refineInMeshByField
(factor=3.0, addZ=15.0, findIdxs=True, debug=False, run=True, fnOut=None)¶ Refines mesh inside ROI by adding box field to mesh file.
The mesh size inside the box is computed by
mesh.volSizePx/factor
. To ensure that there are enough original nodes inside ROI that then allow refinement from,addZ
pixels is added in z-direction both below and above the ROI.See also
pyfrp.subclasses.pyfrp_mesh.mesh.addBoxField()
.Keyword Arguments: - factor (float) – Refinement factor.
- addZ (float) – Number of pixels added above and below ROI for box field.
- findIdxs (bool) – Find mesh indices of ROI after refinement.
- run (bool) – Run Gmsh to generate new mesh after refinement.
- debug (bool) – Print debugging messages.
- fnOut (str) – Path to output geo file.
Returns: Path to new .geo file.
Return type: str
-
render2Openscad
(fn=None, segments=48)¶ Generates .scad file for the ROI.
Note
If
fn
is not given, will save .scad file of ROI in same folder as the geometry file of the embryo with the following path:path/to/embryos/geo/file/nameOfEmbryo_nameOfROI.scad
.Keyword Arguments: - fn (str) – Output filename.
- segments (int) – Number of segments used for convex hull of surface.
Returns: Output filename.
Return type: str
-
render2OpenscadInGeometry
(fn=None, segments=48)¶ Generates .scad file for the intersection between ROI and geometry.
Note
If
fn
is not given, will save .scad file of ROI in same folder as the geometry file of the embryo with the following path:path/to/embryos/geo/file/nameOfEmbryo_nameOfROI.scad
.Keyword Arguments: - fn (str) – Output filename.
- segments (int) – Number of segments used for convex hull of surface.
Returns: Output filename.
Return type: str
-
render2Stl
(fn=None, segments=48)¶ Generates .stl file for the ROI.
Will do this by:
- Generating openscad object via
genAsOpenscad()
. - Rendering this to scad file via
render2Openscad()
. - Calling
pyfrp.modules.pyfrp_openscad_module.runOpenscad()
.
Note
If
fn
is not given, will save .stl file of ROI in same folder as the geometry file of the embryo with the following path:path/to/embryos/geo/file/nameOfEmbryo_nameOfROI.stl
.Keyword Arguments: - fn (str) – Output filename.
- segments (int) – Number of segments used for convex hull of surface.
Returns: Output filename.
Return type: str
- Generating openscad object via
-
render2StlInGeometry
(fn=None, segments=48)¶ Generates .stl file for the intersection between ROI and geometry.
Will do this by:
- Generating openscad object via
genAsOpenscadInGeometry()
. - Rendering this to scad file via
render2OpenscadInGeometry()
. - Calling
pyfrp.modules.pyfrp_openscad_module.runOpenscad()
.
Note
If
fn
is not given, will save .stl file of ROI in same folder as the geometry file of the embryo with the following path:path/to/embryos/geo/file/nameOfEmbryo_nameOfROI.stl
.Keyword Arguments: - fn (str) – Output filename.
- segments (int) – Number of segments used for convex hull of surface.
Returns: Output filename.
Return type: str
- Generating openscad object via
-
resetDataVec
()¶ Resets data vector to an empty list
-
resetSimVec
()¶ Resets simulation vector to an empty list
-
setColor
(color)¶ Sets color of ROI.
Color can be either
str
,float
ortuple
. See also: http://matplotlib.org/api/colors_api.htmlParameters: color (str) – New color. Returns: New color. Return type: str
-
setDataVec
(vec)¶ Sets data vector of ROI.
Parameters: vec (numpy.ndarray) – New data vector. Returns: New data vector. Return type: numpy.ndarray
-
setId
(Id)¶ Sets Id of ROI.
Parameters: Id (int) – New Id. Returns: New Id. Return type: int
-
setName
(n)¶ Sets name of ROI.
Parameters: n (str) – New name. Returns: New name. Return type: str
-
setSimVec
(vec)¶ Sets simulation vector of ROI.
Parameters: vec (numpy.ndarray) – New simulation vector. Returns: New simulation vector. Return type: numpy.ndarray
-
setUseForRim
(b)¶ Marks the ROI to be used for rim calculation.
Parameters: b (bool) – True if ROI should be used, False else. Returns: Current flag value. Return type: bool
-
setZExtend
(zmin, zmax)¶ Sets extend in z-direction.
Parameters: - zmin (float) – Minimum z-coordinate.
- zmax (float) – Maximum z-coordinate.
Returns: New z-extend given by
[zmin,zmax]
.Return type: list
-
showExtImgIdx
(ax=None)¶
-
showIdxs
(axes=None)¶
-
showImgIdx
(ax=None)¶
-
showMeshIdx
(ax=None)¶
-
showMeshIdx2D
(ax=None)¶
-
writeToGeoFile
(fn=None, volSizePx=20.0, genLoops=True, genSurfaces=True, genVol=True, minID=None)¶ Writes ROI to geo file.
Note
If
fn
is not given, will save .geo file of ROI in same folder as the geometry file of the embryo with the following path:path/to/embryos/geo/file/nameOfEmbryo_nameOfROI.geo
.See also
pyfrp.subclasses.pyfrp_ROI.polySliceROI.genGmshDomain()
.Keyword Arguments: - volSizePx (float) – Mesh size of vertices.
- genLoops (bool) – Generate line loops.
- genSurfaces (bool) – Generate surfaces.
- genVol (bool) – Generate surface loop and corresponding volume.
- minID (int) – Id at which geo IDs should start.
Returns: Path to geo file.
Return type: str
-
-
class
pyfrp.subclasses.pyfrp_ROI.
customROI
(embryo, name, Id, color='b')¶ Bases:
pyfrp.subclasses.pyfrp_ROI.ROI
-
addROI
(r, p)¶
-
checkXYInside
(x, y)¶ Checks if coordinates are inside ROI.
Does this by looping through all ROIs specified in
ROIsIncluded
and checking if x/y is supposed to lie inside or outside of the respective ROI.Parameters: - x (np.ndarray) – Array of x-coordinates.
- y (np.ndarray) – Array of y-coordinates.
Returns: Array of booleans with corresponding to [x,y].
Return type: np.ndarray
-
computeXYExtend
()¶ Computes extend of ROI in x/y direction.
Returns: Tuple containing: - xExtend (list): List containing minimum/maximum x-coordinate (
[xmin,xmax]
). - yExtend (list): List containing minimum/maximum y-coordinate (
[ymin,ymax]
).
Return type: tuple - xExtend (list): List containing minimum/maximum x-coordinate (
-
genAsOpenscad
()¶ Generates ROI as solid python object.
Useful if ROI is used to be passed to openscad.
Returns: Solid python object. Return type: solid.solidpython.openscad_object
-
getROIsIncluded
()¶
-
mergeROIs
(r)¶
-
removeROI
(r)¶
-
roiIncluded
(r)¶ Returns if a ROI is included in customROI.
Parameters: r (pyfrp.subclasses.pyfrp_ROI.ROI) – A ROI. Returns: True
if included,False
else.Return type: bool
-
setROIsIncluded
(l)¶
-
showBoundary
(color=None, linewidth=3, ax=None)¶ Shows ROI in a 2D plot by plotting all included ROIs.
If no color is specified, will use color specified in
ROI.color
. Ifcolor=="each"
, will plot each included ROI in its respective color.Keyword Arguments: - ax (matplotlib.axes) – Matplotlib axes used for plotting. If not specified, will generate new one.
- color (str) – Color of plot.
- linewidth (float) – Linewidth of plot.
Returns: Axes used for plotting.
Return type: matplotlib.axes
-
substractROIs
(r)¶
-
updateIdxs
()¶
-
-
class
pyfrp.subclasses.pyfrp_ROI.
polyROI
(embryo, name, Id, corners, color='b')¶ Bases:
pyfrp.subclasses.pyfrp_ROI.ROI
-
addCorner
(c, pos=-1)¶
-
appendCorner
(c)¶
-
checkXYInside
(x, y)¶ Checks if coordinates are inside ROI.
See also
pyfrp.modules.pyfrp_idx_module.checkInsidePoly()
.Parameters: - x (np.ndarray) – Array of x-coordinates.
- y (np.ndarray) – Array of y-coordinates.
Returns: Array of booleans with corresponding to [x,y].
Return type: np.ndarray
-
computeImgIdx
(debug=False)¶ Computes image indices of ROI.
See also
pyfrp.modules.pyfrp_idx_module.getPolyIdxImg()
.Keyword Arguments: debug (bool) – Print debugging messages. Returns: Tuple containing: - imgIdxX (list): Image indices in x-direction.
- imgIdxY (list): Image indices in y-direction.
Return type: tuple
-
computeMeshIdx
(mesh)¶ Computes mesh indices of ROI.
See also
pyfrp.modules.pyfrp_idx_module.getPolyIdxMesh()
.Parameters: mesh (fipy.GmshImporter3D) – Fipy mesh object. Returns: Newly computed mesh indices. Return type: list
-
computeXYExtend
()¶ Computes extend of ROI in x/y direction.
Returns: Tuple containing: - xExtend (list): List containing minimum/maximum x-coordinate (
[xmin,xmax]
). - yExtend (list): List containing minimum/maximum y-coordinate (
[ymin,ymax]
).
Return type: tuple - xExtend (list): List containing minimum/maximum x-coordinate (
-
genAsOpenscad
()¶ Generates ROI as solid python object.
Useful if ROI is used to be passed to openscad.
Returns: Solid python object. Return type: solid.solidpython.linear_extrude
-
getCenterOfMass
()¶ Computes center of mass of ROI.
The center of mass is computed by
\[c = \frac{1}{N} \sum\limits_{i=1}{N} x_i ,\]where \(c\) is the center of mass, \(N\) the number of corners and \(x_i\) is the coordinate of corner \(i\) .
Returns: Center of mass. Return type: numpy.ndarray
-
getCorners
()¶
-
moveCorner
(idx, x, y)¶ Moves corner to new postion.
Parameters: - idx (int) – Index of corner to be moved.
- x (float) – New x-coordinate.
- y (float) – New y-coordinate.
- Results:
- list: Updated corners list.
-
removeCorner
(pos)¶
-
setCorners
(corners)¶
-
showBoundary
(color=None, linewidth=3, ax=None)¶ Shows ROI in a 2D plot.
If no color is specified, will use color specified in
ROI.color
.Keyword Arguments: - ax (matplotlib.axes) – Matplotlib axes used for plotting. If not specified, will generate new one.
- color (str) – Color of plot.
- linewidth (float) – Linewidth of plot.
Returns: Axes used for plotting.
Return type: matplotlib.axes
-
-
class
pyfrp.subclasses.pyfrp_ROI.
polySliceROI
(embryo, name, Id, corners, height, width, sliceBottom, color='b')¶ Bases:
pyfrp.subclasses.pyfrp_ROI.polyROI
,pyfrp.subclasses.pyfrp_ROI.sliceROI
-
checkXYInside
(x, y)¶ Checks if coordinates are inside ROI.
See also
pyfrp.modules.pyfrp_idx_module.checkInsidePoly()
.Parameters: - x (np.ndarray) – Array of x-coordinates.
- y (np.ndarray) – Array of y-coordinates.
Returns: Array of booleans with corresponding to [x,y].
Return type: np.ndarray
-
computeImgIdx
(debug=False)¶ Computes image indices of ROI.
See also
pyfrp.modules.pyfrp_idx_module.getPolyIdxImg()
.Keyword Arguments: debug (bool) – Print debugging messages. Returns: Tuple containing: - imgIdxX (list): Image indices in x-direction.
- imgIdxY (list): Image indices in y-direction.
Return type: tuple
-
computeMeshIdx
(mesh)¶ Computes mesh indices of ROI.
See also
pyfrp.modules.pyfrp_idx_module.getPolyIdxMesh()
.Parameters: mesh (fipy.GmshImporter3D) – Fipy mesh object. Returns: Newly computed mesh indices. Return type: list
-
computeXYExtend
()¶ Computes extend of ROI in x/y direction.
Returns: Tuple containing: - xExtend (list): List containing minimum/maximum x-coordinate (
[xmin,xmax]
). - yExtend (list): List containing minimum/maximum y-coordinate (
[ymin,ymax]
).
Return type: tuple - xExtend (list): List containing minimum/maximum x-coordinate (
-
genAsOpenscad
()¶ Generates ROI as solid python object.
Useful if ROI is used to be passed to openscad.
Returns: Solid python object. Return type: solid.solidpython.linear_extrude
-
genGmshDomain
(volSizePx=20.0, genLoops=True, genSurfaces=True, genVol=True, minID=None)¶ Translates ROI into gmsh domain object.
This object can then be used to write ROIs to
.geo
files.See also
pyfrp.modules.pyfrp_gmsh_geometry.domain.addPrismByParameters()
.Note
If
minID==None
, will grab maximum ID viapyfrp.subclasses.pyfrp_geometry.geometry.getMaxGeoID()
and add 1.Keyword Arguments: - volSizePx (float) – Mesh size of vertices.
- genLoops (bool) – Generate line loops.
- genSurfaces (bool) – Generate surfaces.
- genVol (bool) – Generate surface loop and corresponding volume.
- minID (int) – Id at which geo IDs should start.
Returns: Domain object.
Return type:
-
writeToGeoFile
(fn=None, volSizePx=20.0, genLoops=True, genSurfaces=True, genVol=True, minID=None)¶ Writes ROI to geo file.
Note
If
fn
is not given, will save .geo file of ROI in same folder as the geometry file of the embryo with the following path:path/to/embryos/geo/file/nameOfEmbryo_nameOfROI.geo
.See also
pyfrp.subclasses.pyfrp_ROI.polySliceROI.genGmshDomain()
.Keyword Arguments: - volSizePx (float) – Mesh size of vertices.
- genLoops (bool) – Generate line loops.
- genSurfaces (bool) – Generate surfaces.
- genVol (bool) – Generate surface loop and corresponding volume.
- minID (int) – Id at which geo IDs should start.
Returns: Path to geo file.
Return type: str
-
-
class
pyfrp.subclasses.pyfrp_ROI.
radialROI
(embryo, name, Id, center, radius, color='b')¶ Bases:
pyfrp.subclasses.pyfrp_ROI.ROI
Radial ROI class.
Inherits from
ROI
.Main attributes are:
radius
: Radius of ROI.center
: Center of ROI.
-
center2Mid
()¶
-
checkCentered
()¶
-
checkXYInside
(x, y)¶ Checks if coordinates are inside ROI.
See also
pyfrp.modules.pyfrp_idx_module.checkInsideCircle()
.Parameters: - x (np.ndarray) – Array of x-coordinates.
- y (np.ndarray) – Array of y-coordinates.
Returns: Array of booleans with corresponding to [x,y].
Return type: np.ndarray
-
computeImgIdx
(debug=False)¶ Computes image indices of ROI.
See also
pyfrp.modules.pyfrp_idx_module.getCircleIdxImg()
.Keyword Arguments: debug (bool) – Print debugging messages. Returns: Tuple containing: - imgIdxX (list): Image indices in x-direction.
- imgIdxY (list): Image indices in y-direction.
Return type: tuple
-
computeMeshIdx
(mesh)¶ Computes mesh indices of ROI.
See also
pyfrp.modules.pyfrp_idx_module.getCircleIdxMesh()
.Parameters: mesh (fipy.GmshImporter3D) – Fipy mesh object. Returns: Newly computed mesh indices. Return type: list
-
computeXYExtend
()¶ Computes extend of ROI in x/y direction.
Returns: Tuple containing: - xExtend (list): List containing minimum/maximum x-coordinate (
[xmin,xmax]
). - yExtend (list): List containing minimum/maximum y-coordinate (
[ymin,ymax]
).
Return type: tuple - xExtend (list): List containing minimum/maximum x-coordinate (
-
genAsOpenscad
()¶ Generates ROI as solid python object.
Useful if ROI is used to be passed to openscad.
Note
Will grab extent of geometry to find bounds in z-direction.
Returns: Solid python object. Return type: solid.solidpython.cylinder
-
getCenter
()¶ Returns current center of ROI.
Returns: Current center. Return type: list
-
getCenterOfMass
()¶ Returns center of mass of ROI.
For a radial ROI, this is equivalent to the
center
.
-
getRadius
()¶ Returns current radius of ROI.
Returns: Current radius. Return type: float
-
makeReducable
(auto=False, debug=False)¶
-
setCenter
(c)¶ Sets radius of ROI.
Parameters: c (list) – New center. Returns: New center. Return type: list
-
setRadius
(r)¶ Sets radius of ROI.
Parameters: r (float) – New radius Returns: New radius. Return type: float
-
showBoundary
(color=None, linewidth=3, ax=None)¶ Shows ROI in a 2D plot.
If no color is specified, will use color specified in
ROI.color
.Keyword Arguments: - ax (matplotlib.axes) – Matplotlib axes used for plotting. If not specified, will generate new one.
- color (str) – Color of plot.
- linewidth (float) – Linewidth of plot.
Returns: Axes used for plotting.
Return type: matplotlib.axes
-
class
pyfrp.subclasses.pyfrp_ROI.
radialSliceROI
(embryo, name, Id, center, radius, height, width, sliceBottom, color='b')¶ Bases:
pyfrp.subclasses.pyfrp_ROI.sliceROI
,pyfrp.subclasses.pyfrp_ROI.radialROI
-
checkXYInside
(x, y)¶ Checks if coordinates are inside ROI.
See also
pyfrp.modules.pyfrp_idx_module.checkInsideCircle()
.Parameters: - x (np.ndarray) – Array of x-coordinates.
- y (np.ndarray) – Array of y-coordinates.
Returns: Array of booleans with corresponding to [x,y].
Return type: np.ndarray
-
computeImgIdx
(debug=False)¶ Computes image indices of ROI.
See also
pyfrp.modules.pyfrp_idx_module.getCircleIdxImg()
.Keyword Arguments: debug (bool) – Print debugging messages. Returns: Tuple containing: - imgIdxX (list): Image indices in x-direction.
- imgIdxY (list): Image indices in y-direction.
Return type: tuple
-
computeMeshIdx
(mesh)¶ Computes mesh indices of ROI.
See also
pyfrp.modules.pyfrp_idx_module.getCircleIdxMesh()
.Parameters: mesh (fipy.GmshImporter3D) – Fipy mesh object. Returns: Newly computed mesh indices. Return type: list
-
computeXYExtend
()¶ Computes extend of ROI in x/y direction.
Returns: Tuple containing: - xExtend (list): List containing minimum/maximum x-coordinate (
[xmin,xmax]
). - yExtend (list): List containing minimum/maximum y-coordinate (
[ymin,ymax]
).
Return type: tuple - xExtend (list): List containing minimum/maximum x-coordinate (
-
genAsOpenscad
(allowInf=False)¶ Generates ROI as solid python object.
Useful if ROI is used to be passed to openscad.
Keyword Arguments: allowInf (bool) – Allow infinity in bounds of z-direction. Returns: Solid python object. Return type: solid.solidpython.cylinder
-
genGmshDomain
(volSizePx=20.0, genLoops=True, genSurfaces=True, genVol=True, minID=None)¶ Translates ROI into gmsh domain object.
This object can then be used to write ROIs to
.geo
files.See also
pyfrp.modules.pyfrp_gmsh_geometry.domain.addCuboidByParameters()
.Note
If
minID==None
, will grab maximum ID viapyfrp.subclasses.pyfrp_geometry.geometry.getMaxGeoID()
and add 1.Keyword Arguments: - volSizePx (float) – Mesh size of vertices.
- genLoops (bool) – Generate line loops.
- genSurfaces (bool) – Generate surfaces.
- genVol (bool) – Generate surface loop and corresponding volume.
- minID (int) – Id at which geo IDs should start.
Returns: Domain object.
Return type:
-
writeToGeoFile
(fn=None, volSizePx=20.0, genLoops=True, genSurfaces=True, genVol=True, minID=None)¶ Writes ROI to geo file.
Note
If
fn
is not given, will save .geo file of ROI in same folder as the geometry file of the embryo with the following path:path/to/embryos/geo/file/nameOfEmbryo_nameOfROI.geo
.See also
pyfrp.subclasses.pyfrp_ROI.polySliceROI.genGmshDomain()
.Keyword Arguments: - volSizePx (float) – Mesh size of vertices.
- genLoops (bool) – Generate line loops.
- genSurfaces (bool) – Generate surfaces.
- genVol (bool) – Generate surface loop and corresponding volume.
- minID (int) – Id at which geo IDs should start.
Returns: Path to geo file.
Return type: str
-
-
class
pyfrp.subclasses.pyfrp_ROI.
rectangleROI
(embryo, name, Id, offset, sidelengthX, sidelengthY, color='b')¶ Bases:
pyfrp.subclasses.pyfrp_ROI.ROI
-
centerOffset
()¶
-
checkXYInside
(x, y)¶ Checks if coordinates are inside ROI.
See also
pyfrp.modules.pyfrp_idx_module.checkInsideRectangle()
.Parameters: - x (np.ndarray) – Array of x-coordinates.
- y (np.ndarray) – Array of y-coordinates.
Returns: Array of booleans with corresponding to [x,y].
Return type: np.ndarray
-
computeImgIdx
(debug=False)¶ Computes image indices of ROI.
See also
pyfrp.modules.pyfrp_idx_module.getRectangleIdxImg()
.Keyword Arguments: debug (bool) – Print debugging messages. Returns: Tuple containing: - imgIdxX (list): Image indices in x-direction.
- imgIdxY (list): Image indices in y-direction.
Return type: tuple
-
computeMeshIdx
(mesh)¶ Computes mesh indices of ROI.
See also
pyfrp.modules.pyfrp_idx_module.getRectangleIdxMesh()
.Parameters: mesh (fipy.GmshImporter3D) – Fipy mesh object. Returns: Newly computed mesh indices. Return type: list
-
computeXYExtend
()¶ Computes extend of ROI in x/y direction.
Returns: Tuple containing: - xExtend (list): List containing minimum/maximum x-coordinate (
[xmin,xmax]
). - yExtend (list): List containing minimum/maximum y-coordinate (
[ymin,ymax]
).
Return type: tuple - xExtend (list): List containing minimum/maximum x-coordinate (
-
genAsOpenscad
()¶ Generates ROI as solid python object.
Useful if ROI is used to be passed to openscad.
Note
Will grab extent of geometry to find bounds in z-direction.
Returns: Solid python object. Return type: solid.solidpython.cube
-
getCenterOfMass
()¶ Computes center of mass of ROI.
The center of mass is computed by
\[c = \frac{1}{N} \sum\limits_{i=1}{N} x_i ,\]where \(c\) is the center of mass, \(N\) the number of corners and \(x_i\) is the coordinate of corner \(i\) .
Returns: Center of mass. Return type: numpy.ndarray
-
getCorners
()¶ Returns corners of rectangle in counter-clockwise order, starting with offset.
Returns: List of 2D coordinates of corners. Return type: list
-
getOffset
()¶
-
getSideLengthX
()¶
-
getSideLengthY
()¶
-
makeReducable
(atuo=False, debug=False)¶
-
setOffset
(c)¶
-
setSideLengthX
(s)¶
-
setSideLengthY
(s)¶
-
showBoundary
(color=None, linewidth=3, ax=None)¶ Shows ROI in a 2D plot.
If no color is specified, will use color specified in
ROI.color
.Keyword Arguments: - ax (matplotlib.axes) – Matplotlib axes used for plotting. If not specified, will generate new one.
- color (str) – Color of plot.
- linewidth (float) – Linewidth of plot.
Returns: Axes used for plotting.
Return type: matplotlib.axes
-
-
class
pyfrp.subclasses.pyfrp_ROI.
rectangleSliceROI
(embryo, name, Id, offset, sidelengthX, sidelengthY, height, width, sliceBottom, color='b')¶ Bases:
pyfrp.subclasses.pyfrp_ROI.rectangleROI
,pyfrp.subclasses.pyfrp_ROI.sliceROI
-
checkXYInside
(x, y)¶ Checks if coordinates are inside ROI.
See also
pyfrp.modules.pyfrp_idx_module.checkInsideRectangle()
.Parameters: - x (np.ndarray) – Array of x-coordinates.
- y (np.ndarray) – Array of y-coordinates.
Returns: Array of booleans with corresponding to [x,y].
Return type: np.ndarray
-
computeImgIdx
(debug=False)¶ Computes image indices of ROI.
See also
pyfrp.modules.pyfrp_idx_module.getRectangleIdxImg()
.Keyword Arguments: debug (bool) – Print debugging messages. Returns: Tuple containing: - imgIdxX (list): Image indices in x-direction.
- imgIdxY (list): Image indices in y-direction.
Return type: tuple
-
computeMeshIdx
(mesh)¶ Computes mesh indices of ROI.
See also
pyfrp.modules.pyfrp_idx_module.getRectangleIdxMesh()
.Parameters: mesh (fipy.GmshImporter3D) – Fipy mesh object. Returns: Newly computed mesh indices. Return type: list
-
computeXYExtend
()¶ Computes extend of ROI in x/y direction.
Returns: Tuple containing: - xExtend (list): List containing minimum/maximum x-coordinate (
[xmin,xmax]
). - yExtend (list): List containing minimum/maximum y-coordinate (
[ymin,ymax]
).
Return type: tuple - xExtend (list): List containing minimum/maximum x-coordinate (
-
genAsOpenscad
()¶ Generates ROI as solid python object.
Useful if ROI is used to be passed to openscad.
Returns: Solid python object. Return type: solid.solidpython.cube
-
genGmshDomain
(volSizePx=20.0, genLoops=True, genSurfaces=True, genVol=True, minID=None)¶ Translates ROI into gmsh domain object.
This object can then be used to write ROIs to
.geo
files.See also
pyfrp.modules.pyfrp_gmsh_geometry.domain.addCuboidByParameters()
.Note
If
minID==None
, will grab maximum ID viapyfrp.subclasses.pyfrp_geometry.geometry.getMaxGeoID()
and add 1.Keyword Arguments: - volSizePx (float) – Mesh size of vertices.
- genLoops (bool) – Generate line loops.
- genSurfaces (bool) – Generate surfaces.
- genVol (bool) – Generate surface loop and corresponding volume.
- minID (int) – Id at which geo IDs should start.
Returns: Domain object.
Return type:
-
writeToGeoFile
(fn=None, volSizePx=20.0, genLoops=True, genSurfaces=True, genVol=True, minID=None)¶ Writes ROI to geo file.
Note
If
fn
is not given, will save .geo file of ROI in same folder as the geometry file of the embryo with the following path:path/to/embryos/geo/file/nameOfEmbryo_nameOfROI.geo
.See also
pyfrp.subclasses.pyfrp_ROI.polySliceROI.genGmshDomain()
.Keyword Arguments: - volSizePx (float) – Mesh size of vertices.
- genLoops (bool) – Generate line loops.
- genSurfaces (bool) – Generate surfaces.
- genVol (bool) – Generate surface loop and corresponding volume.
- minID (int) – Id at which geo IDs should start.
Returns: Path to geo file.
Return type: str
-
-
class
pyfrp.subclasses.pyfrp_ROI.
sliceROI
(embryo, name, Id, height, width, sliceBottom, color='b')¶ Bases:
pyfrp.subclasses.pyfrp_ROI.ROI
-
checkXYInside
(x, y)¶ Checks if coordinates are inside ROI.
Only returns
True
, sincesliceROI
is not limited in x/y-direction.Parameters: - x (np.ndarray) – Array of x-coordinates.
- y (np.ndarray) – Array of y-coordinates.
Returns: Array of booleans with corresponding to [x,y], all
True
.Return type: np.ndarray
-
computeImgIdx
(debug=False)¶ Computes image indices of ROI.
See also
pyfrp.modules.pyfrp_idx_module.getAllIdxImg()
.Keyword Arguments: debug (bool) – Print debugging messages. Returns: Tuple containing: - imgIdxX (list): Image indices in x-direction.
- imgIdxY (list): Image indices in y-direction.
Return type: tuple
-
computeMeshIdx
(mesh)¶ Computes mesh indices of ROI.
See also
pyfrp.modules.pyfrp_idx_module.getSliceIdxMesh()
.Parameters: mesh (fipy.GmshImporter3D) – Fipy mesh object. Returns: Newly computed mesh indices. Return type: list
-
computeXYExtend
()¶ Computes extend of ROI in x/y direction.
Note
Since sliceROI theoretically is not having any limits in x/y-direction, function returns limits given by input image, that is,
[0,embryo.dataResPx]
.Returns: Tuple containing: - xExtend (list): List containing minimum/maximum x-coordinate (
[xmin,xmax]
). - yExtend (list): List containing minimum/maximum y-coordinate (
[ymin,ymax]
).
Return type: tuple - xExtend (list): List containing minimum/maximum x-coordinate (
-
computeZExtend
()¶
-
genAsOpenscad
()¶ Generates ROI as solid python object.
Useful if ROI is used to be passed to openscad.
Note
Will grab extent of geometry to find bounds in x/y-direction.
Returns: Solid python object. Return type: solid.solidpython.cube
-
getHeight
()¶
-
getSliceBottom
()¶
-
getWidth
()¶
-
setHeight
(h)¶
-
setSliceBottom
(s)¶
-
setWidth
(w)¶
-
-
class
pyfrp.subclasses.pyfrp_ROI.
squareROI
(embryo, name, Id, offset, sidelength, color='b')¶ Bases:
pyfrp.subclasses.pyfrp_ROI.ROI
-
centerOffset
()¶
-
checkXYInside
(x, y)¶ Checks if coordinates are inside ROI.
See also
pyfrp.modules.pyfrp_idx_module.checkInsideSquare()
.Parameters: - x (np.ndarray) – Array of x-coordinates.
- y (np.ndarray) – Array of y-coordinates.
Returns: Array of booleans with corresponding to [x,y].
Return type: np.ndarray
-
computeImgIdx
(debug=False)¶ Computes image indices of ROI.
See also
pyfrp.modules.pyfrp_idx_module.getSquareIdxImg()
.Keyword Arguments: debug (bool) – Print debugging messages. Returns: Tuple containing: - imgIdxX (list): Image indices in x-direction.
- imgIdxY (list): Image indices in y-direction.
Return type: tuple
-
computeMeshIdx
(mesh)¶ Computes mesh indices of ROI.
See also
pyfrp.modules.pyfrp_idx_module.getSquareIdxMesh()
.Parameters: mesh (fipy.GmshImporter3D) – Fipy mesh object. Returns: Newly computed mesh indices. Return type: list
-
computeXYExtend
()¶ Computes extend of ROI in x/y direction.
Returns: Tuple containing: - xExtend (list): List containing minimum/maximum x-coordinate (
[xmin,xmax]
). - yExtend (list): List containing minimum/maximum y-coordinate (
[ymin,ymax]
).
Return type: tuple - xExtend (list): List containing minimum/maximum x-coordinate (
-
genAsOpenscad
()¶ Generates ROI as solid python object.
Useful if ROI is used to be passed to openscad.
Note
Will grab extent of geometry to find bounds in z-direction.
Returns: Solid python object. Return type: solid.solidpython.cube
-
getCenterOfMass
()¶ Computes center of mass of ROI.
The center of mass is computed by
\[c = \frac{1}{N} \sum\limits_{i=1}{N} x_i ,\]where \(c\) is the center of mass, \(N\) the number of corners and \(x_i\) is the coordinate of corner \(i\) .
Returns: Center of mass. Return type: numpy.ndarray
-
getCorners
()¶ Returns corners of square in counter-clockwise order, starting with offset.
Returns: List of 2D coordinates of corners. Return type: list
-
getOffset
()¶
-
getSideLength
()¶
-
makeReducable
(auto=False, debug=False)¶
-
setOffset
(c)¶
-
setSideLength
(s)¶
-
showBoundary
(color=None, linewidth=3, ax=None)¶ Shows ROI in a 2D plot.
If no color is specified, will use color specified in
ROI.color
.Keyword Arguments: - ax (matplotlib.axes) – Matplotlib axes used for plotting. If not specified, will generate new one.
- color (str) – Color of plot.
- linewidth (float) – Linewidth of plot.
Returns: Axes used for plotting.
Return type: matplotlib.axes
-
-
class
pyfrp.subclasses.pyfrp_ROI.
squareSliceROI
(embryo, name, Id, offset, sidelength, height, width, sliceBottom, color='b')¶ Bases:
pyfrp.subclasses.pyfrp_ROI.squareROI
,pyfrp.subclasses.pyfrp_ROI.sliceROI
-
checkXYInside
(x, y)¶ Checks if coordinates are inside ROI.
See also
pyfrp.modules.pyfrp_idx_module.checkInsideSquare()
.Parameters: - x (np.ndarray) – Array of x-coordinates.
- y (np.ndarray) – Array of y-coordinates.
Returns: Array of booleans with corresponding to [x,y].
Return type: np.ndarray
-
computeImgIdx
(debug=False)¶ Computes image indices of ROI.
See also
pyfrp.modules.pyfrp_idx_module.getSquareIdxImg()
.Keyword Arguments: debug (bool) – Print debugging messages. Returns: Tuple containing: - imgIdxX (list): Image indices in x-direction.
- imgIdxY (list): Image indices in y-direction.
Return type: tuple
-
computeMeshIdx
(mesh)¶ Computes mesh indices of ROI.
See also
pyfrp.modules.pyfrp_idx_module.getSquareIdxMesh()
.Parameters: mesh (fipy.GmshImporter3D) – Fipy mesh object. Returns: Newly computed mesh indices. Return type: list
-
computeXYExtend
()¶ Computes extend of ROI in x/y direction.
Returns: Tuple containing: - xExtend (list): List containing minimum/maximum x-coordinate (
[xmin,xmax]
). - yExtend (list): List containing minimum/maximum y-coordinate (
[ymin,ymax]
).
Return type: tuple - xExtend (list): List containing minimum/maximum x-coordinate (
-
genAsOpenscad
()¶ Generates ROI as solid python object.
Useful if ROI is used to be passed to openscad.
Returns: Solid python object. Return type: solid.solidpython.cube
-
genGmshDomain
(volSizePx=20.0, genLoops=True, genSurfaces=True, genVol=True, minID=None)¶ Translates ROI into gmsh domain object.
This object can then be used to write ROIs to
.geo
files.See also
pyfrp.modules.pyfrp_gmsh_geometry.domain.addCuboidByParameters()
.Note
If
minID==None
, will grab maximum ID viapyfrp.subclasses.pyfrp_geometry.geometry.getMaxGeoID()
and add 1.Keyword Arguments: - volSizePx (float) – Mesh size of vertices.
- genLoops (bool) – Generate line loops.
- genSurfaces (bool) – Generate surfaces.
- genVol (bool) – Generate surface loop and corresponding volume.
Returns: Domain object.
Return type:
-
writeToGeoFile
(fn=None, volSizePx=20.0, genLoops=True, genSurfaces=True, genVol=True, minID=None)¶ Writes ROI to geo file.
Note
If
fn
is not given, will save .geo file of ROI in same folder as the geometry file of the embryo with the following path:path/to/embryos/geo/file/nameOfEmbryo_nameOfROI.geo
.See also
pyfrp.subclasses.pyfrp_ROI.polySliceROI.genGmshDomain()
.Keyword Arguments: - volSizePx (float) – Mesh size of vertices.
- genLoops (bool) – Generate line loops.
- genSurfaces (bool) – Generate surfaces.
- genVol (bool) – Generate surface loop and corresponding volume.
- minID (int) – Id at which geo IDs should start.
Returns: Path to geo file.
Return type: str
-
pyfrp.subclasses.pyfrp_analysis module¶
Essential PyFRAP module containing analysis
class.
-
class
pyfrp.subclasses.pyfrp_analysis.
analysis
(embryo)¶ PyFRAP analysis class storing information about analysis options and some analysis results.
Analysis options are:
gaussian
: Apply gaussian filter to images. Default kernel size isgaussianSigma=2
.median
: Apply gaussian filter to images. Default kernel size ismedianRadius=5
.flatten
: Apply flattening mask.norm
: Norm by pre image.bkgd
: Substract background.quad
: Perform reduction to first quadrant by flipping.flipBeforeProcess
: Flip into quadrant before other processing options are applied.
Analysis options are stored in
process
dictionary. If analysis finds option inprocess.keys
, it will perform option. Analysis options can be turned on/off using the respective functions, such aspyfrp.subclasses.pyfrp_analysis.medianOn()
pyfrp.subclasses.pyfrp_analysis.flattenOn()
- etc.
Processing parameters are stored in
process.values
.The default processing options are
process={}
, meaning that no image modification is applied before concentration readout, see alsogenDefaultProcess()
.Warning
Quadrant reduction is still experimental.
Three other important attributes are:
dataOffset
: The offset of the data that is for example used for norming, see alsogetOptimalOffset()
.addRimImg
: Flag that controls if rim concentrations are added to ROI concentratrtion profiles, see alsosetAddRimImg()
.concRim
: The rim concentration of the first post-bleaching image used later by the simulation for nodes that are outside of original image boundaries.
Note
addRimImg=True
by default. This is generally good, since the simulation value in ROIs is getting evaluated over over mesh nodes both inside the actual image and outside of it.Parameters: embryo (pyfrp.subclasses.pyfrp_embryo.embryo) – PyFRAP embryo instance. -
bkgdOn
()¶ Returns current state of this option.
Returns: True
if switched on,False
else.Return type: bool
-
computeBkgdMask
(flatteningMask, applyProcess=True, applyFlatten=False)¶ Computes background mask.
Takes first
nBkgd
images infnBkgd
and computes mean image of these images. Then, ifapplyProcess
is selected, applies the selected process options defined inprocess
dictionary to it.Note
Will not apply process options
norm
andbkgd
to mean background image.Parameters: flatteningMask (numpy.ndarray) – Flattening mask.
Keyword Arguments: - applyProcess (bool) – Apply processing options to background mask.
- applyFlatten (bool) – Apply flattening to background mask.
Returns: Background mask.
Return type: numpy.ndarray
-
computeFlatteningMask
(applyProcess=True)¶ Computes flattening mask.
Takes first
nFlatten
images infnFlatten
and computes mean image of these images. Then, ifapplyProcess
is selected, applies the selected process options defined inprocess
dictionary to it.Note
Will not apply process options
norm
,flatten
andbkgd
to mean flattening image.Keyword Arguments: applyProcess (bool) – Apply processing options to flattening mask. Returns: Flattening mask. Return type: numpy.ndarray
-
computePreMask
(flatteningMask, bkgdMask, applyProcess=True)¶ Computes norming mask.
Takes first
nPre
images infnPreimage
and computes mean image of these images. Then, ifapplyProcess
is selected, applies the selected process options defined inprocess
dictionary to it.Note
Will not apply process option
norm
to mean background image.Parameters: - flatteningMask (numpy.ndarray) – Flattening mask.
- bkgdMask (numpy.ndarray) – Background mask.
Keyword Arguments: applyProcess (bool) – Apply processing options to background mask.
Returns: Norming mask.
Return type: numpy.ndarray
-
flattenOn
()¶ Returns current state of this option.
Returns: True
if switched on,False
else.Return type: bool
-
flipBeforeProcessOn
()¶ Returns current state of this option.
Returns: True
if switched on,False
else.Return type: bool
-
gaussianOn
()¶ Returns current state of this option.
Returns: True
if switched on,False
else.Return type: bool
-
genDefaultProcess
()¶ Sets
process
dictionary to default options.Default options are:
gaussian=False
median=False
quad=False
flatten=False
bkgd=False
norm=False
flipBeforeProcess=True
Returns: Updated process
dictionary.Return type: dict
-
getAddRimImg
()¶ Returns the addRimImg flag.
See also
setAddRimImg()
.Returns: Flag value. Return type: bool
-
getConcRim
()¶ Returns rim concentration.
Returns: Current rim concentration. Return type: float
-
getDataOffset
()¶ Returns dataoffset used for norming.
Returns: Current offset. Return type: float
-
getFnBkgd
()¶ Returns path to background dataset.
Returns: Path to background dataset. Return type: str
-
getFnFlatten
()¶ Returns path to flattening dataset.
Returns: Path to flattening dataset. Return type: str
-
getFnPre
()¶ Returns path to norming dataset.
Returns: Path to norming dataset. Return type: str
-
getGaussianSigma
()¶ Returns size of gaussian kernel.
See also http://scikit-image.org/docs/dev/api/skimage.filters.html#skimage.filters.gaussian_filter.
Returns: Gaussian sigma. Return type: float
-
getMedianRadius
()¶ Returns size of median kernel.
See also http://scikit-image.org/docs/dev/api/skimage.filters.html#skimage.filters.median and http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.ndimage.filters.median_filter.html.
Returns: New radius. Return type: float
-
getNBkgd
()¶ Returns the number of images used for the computation for the mean background image.
Returns: Number of images used. Return type: int
-
getNFlatten
()¶ Returns the number of images used for the computation for the mean flattening image.
Returns: Number of images used. Return type: int
-
getNPre
()¶ Returns the number of images used for the computation for the mean norming image.
Returns: Number of images used. Return type: int
-
getOptimalOffset
(debug=False)¶ Computes optimal dataoffset for data analysis.
Finds minimal non-zero offset for main dataset, preimage dataset flattening dataset and background dataset, if available. The Idea is that one does not want to have negative pixels, so substraction of a fixed value from an image should always lead to positive pixel values. Thus the offset is computed by
\[offset = max\{ o_{\mathrm{min},\mathrm{data}},o_{\mathrm{min},\mathrm{flatten}} ,o_{\mathrm{min},\mathrm{pre}},o_{\mathrm{min},\mathrm{bkgd}}\}\]where \(o_{\mathrm{min},d}\) is the minimum pixel values of all images in dataset \(d\).
Keyword Arguments: debug (bool) – Print debugging messages. Returns: Optimal offset. Return type: float
-
getProcess
()¶ Returns process dictionary.
-
medianOn
()¶ Returns current state of this option.
Returns: True
if switched on,False
else.Return type: bool
-
normOn
()¶ Returns current state of this option.
Returns: True
if switched on,False
else.Return type: bool
-
parm2Process
(b, key, val)¶ Adds/Removes a new option to
process
dictionary.Parameters: - b (bool) – Flag if process should be added or removed.
- key (str) – Key of option to be added.
- val (any) – Value of dictionary entry.
Returns: Updated
process
dictionary.Return type: dict
-
printAllAttr
()¶ Prints out all attributes of analysis object.
-
printProcess
()¶ Prints out current process options in a nicely formatted way.
-
quadOn
()¶ Returns current state of this option.
Returns: True
if switched on,False
else.Return type: bool
-
removeProcessStep
(dic, step)¶ Removes process step from dictionary.
Parameters: - dic (dict) – A dictionary.
- step (str) – Key of step to be removed.
Returns: Updated dictionary.
Return type: dict
-
run
(signal=None, embCount=None, debug=False, debugAll=False, showProgress=True)¶ Runs analysis by passing analysis object to
pyfrp.modules.pyfrp_img_module.analyzeDataset()
.Will first check if ROI indices are computed for all ROIs and if necessary compute them before starting data 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: Updated analysis instance.
Return type:
-
setAddRimImg
(s)¶ Sets the addRimImg flag.
The addRim flag controls if the rim concentration is added to the concentration of each ROI timeseries depending on how many imaginary pixels they have outside of the actual image.
Parameters: s (bool) – Flag value.
-
setBkgd
(b)¶ Turns on/off background substraction for analysis.
Note
Will use
bkgdMask
for flattening.bkgdMask
is updated viacomputeBkgdMask()
and then automatically updated inprocess
dictionary.Parameters: b (bool) – True
if background substraction should be turned on,False
else.Returns: Updated process dictionary. Return type: dict
-
setConcRim
(s)¶ Sets rim concentration.
Parameters: s (float) – New rim concentration.
-
setDataOffset
(s)¶ Sets dataoffset used for norming.
Parameters: s (float) – New offset.
-
setFlatten
(b)¶ Turns on/off flattening for analysis.
Note
Will use
flatteningMask
for flattening.flatteningMask
is updated viacomputeFlatteningMask()
and then automatically updated inprocess
dictionary.Parameters: b (bool) – True
if flattening should be turned on,False
else.Returns: Updated process dictionary. Return type: dict
-
setFlipBeforeProcess
(b)¶ Turns on/off if image should be flipped into quadrant before or after performing all other image processing for analysis.
Warning
Quadrant reduction is still experimental.
Parameters: b (bool) – True
if image should be flipped before,False
else.Returns: Updated process dictionary. Return type: dict
-
setFnBkgd
(fn)¶ Sets path to background dataset.
Parameters: fn (str) – Path to background dataset.
-
setFnFlatten
(fn)¶ Sets path to flattening dataset.
Parameters: fn (str) – Path to flattening dataset.
-
setFnPre
(fn)¶ Sets path to preimage dataset.
Parameters: fn (str) – Path to preimage dataset.
-
setGaussian
(b)¶ Turns on/off gaussian filter for analysis.
Note
Will use
gaussianSigma
as kernel size. Can be changed viasetGaussianSigma()
.Parameters: b (bool) – True
if gaussian should be turned on,False
else.Returns: Updated process dictionary. Return type: dict
-
setGaussianSigma
(s)¶ Sets size of gaussian kernel and updates its value in
process
dictionary if gaussian filter is turned on.See also http://scikit-image.org/docs/dev/api/skimage.filters.html#skimage.filters.gaussian_filter.
Parameters: s (float) – New sigma.
-
setMedian
(b)¶ Turns on/off median filter for analysis.
Note
Will use
medianRadius
as kernel size. Can be changed viasetMedianRadius()
.Parameters: b (bool) – True
if median should be turned on,False
else.Returns: Updated process dictionary. Return type: dict
-
setMedianRadius
(s)¶ Sets size of median kernel and updates its value in
process
dictionary if median filter is turned on.See also http://scikit-image.org/docs/dev/api/skimage.filters.html#skimage.filters.median and http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.ndimage.filters.median_filter.html.
Parameters: s (float) – New radius.
-
setNBkgd
(n)¶ Sets the number of images used for the computation for the mean background image.
Parameters: n (int) – Number of images used.
-
setNFlatten
(n)¶ Sets the number of images used for the computation for the mean flattening image.
Parameters: n (int) – Number of images used.
-
setNPre
(n)¶ Sets the number of images used for the computation for the mean norming image.
Parameters: n (int) – Number of images used.
-
setNorm
(b)¶ Turns on/off norming by preimage for analysis.
Note
Will use
preMask
for norming.preMask
is updated viacomputePreMask()
and then automatically updated inprocess
dictionary.Parameters: b (bool) – True
if norming should be turned on,False
else.Returns: Updated process dictionary. Return type: dict
-
setProcess
(s)¶ Sets process dictionary.
Parameters: s (dict) – New process dictionary.
-
setQuad
(b)¶ Turns on/off if image should be flipped into first quadrant for analysis.
Warning
Quadrant reduction is still experimental.
Parameters: b (bool) – True
if quadrant reduction should be turned on,False
else.Returns: Updated process dictionary. Return type: dict
-
updateProcess
()¶ Updates all values in process dictionary with the ones saved in attributes of analysis object.
pyfrp.subclasses.pyfrp_conf module¶
-
class
pyfrp.subclasses.pyfrp_conf.
configuration
¶ -
addRecentFile
(fn)¶
-
backupPathFile
()¶
-
copyPathFileToDefaultLocation
()¶
-
getBackup2File
(h)¶
-
getBackup2Memory
(h)¶
-
getPathFile
()¶
-
getPlotHidden
(h)¶
-
getPropHidden
(h)¶
-
getRecentFiles
(r)¶
-
getTermHidden
(h)¶
-
printConfiguration
()¶
-
save
(fn=None)¶
-
setBackup2File
(h)¶
-
setBackup2Memory
(h)¶
-
setPathFile
(fn)¶
-
setPlotHidden
(h)¶
-
setPropHidden
(h)¶
-
setRecentFiles
(r)¶
-
setTermHidden
(h)¶
-
updateVersion
()¶
-
pyfrp.subclasses.pyfrp_embryo module¶
Essential PyFRAP module containing embryo
class.
-
class
pyfrp.subclasses.pyfrp_embryo.
embryo
(name)¶ Main PyFRAP class, gathering all the data and parameters of FRAP experiment.
The
embryo
class basically stores:- A minimum set of basic FRAP parameters.
- A list of
pyfrp.subclasses.pyfrp_ROI.ROI
classes, describing all ROIs used for for evaluating simulation and analysis results. - A
pyfrp.subclasses.pyfrp_geometry.geometry
class describing the 3-dimensional geometry of the experiment. - A
pyfrp.subclasses.pyfrp_analysis.analysis
class describing how the dataset is going to be analyzed. - A
pyfrp.subclasses.pyfrp_simulation.simulation
class describing how the dataset is going to be simulated. - A list of
pyfrp.subclasses.pyfrp_fit.fit
classes, storing different fitting options and results.
The
embryo
class comes with a comprehensive set of methods aimed at making it as powerful as possible, while still keeping it simple. The hierarchical structure should make it easy to navigate through a FRAP dataset.-
ROIs2Full
()¶ Sets ROIs to full mode.
Returns: Updated list of ROIs. Return type: list
-
ROIs2Quad
()¶ Reduces ROIs to quadrant reduced mode, mapping all their indices in first quadrant.
Note
Use :py:func:setEmbryo2Quad to make sure that both geometry and ROIs are reduced.
Warning
Quadrant reduction is still experimental.
Returns: Updated list of ROIs. Return type: list
-
addFit
(fit)¶ Appends fit object to list of fits
Parameters: fit (pyfrp.subclasses.pyfrp_fit.fit) – fit object. Returns: Updated fits
list.Return type: list
-
addROI
(roi)¶ Adds ROI to
ROIs
list.Parameters: roi (pyfrp.subclasses.pyfrp_ROI.ROI) – A PyFRAP ROI. Returns: Updated ROIs list. Return type: list
-
checkQuadReducable
(tryFix=False, auto=False, debug=False)¶ Checks if embryo is reducable to quadrant by checking if all ROIs are either point or axis symmetric around geometry center.
Note
You want to call :py:meth:showAllROIBoundaries and :py:meth:computeROIIdxs afterwards to make sure everything went properly.
Warning
Quadrant reduction is still experimental.
Keyword Arguments: - tryFix (bool) – Tries to readjust ROIs into reducable form.
- auto (bool) – Readjust ROIs automatically.
- debug (bool) – Print debugging messages.
Returns: True if embryo is reducable.
Return type: bool
-
checkROIIdxs
(debug=False)¶ Checks if all ROIs have their mesh and image indices computed.
Keyword Arguments: debug (bool) – Print debugging messages. Returns: Tuple containing: - img (bool): True if all ROIs have up-to-date image indices.
- mesh (bool): True if all ROIs have up-to-date mesh indices.
Return type: tuple
-
clearAllAttributes
()¶ Replaces all attribute values of embryo object with
None
, exceptname
.Useful if embryos are seperated and molecule file needs to be compressed.
Returns: True if success, False else. Return type: bool
-
compareFitsByAIC
(ROIs=None, sigma=1, fromSSD=True, thresh=None, printOut=True)¶ Compares all fits of embryo using the Akaike information criterion (AIC).
For a detailed explanation of the model selection procedure, please refer to
pyfrp.modules.pyfrp_stats_module.compareFitsByAIC()
.If
printOut
is selected, will print a list of selected fits and the underlying Akaike values in a readable table.If the AIC or the AICc should be used can be determined using
pyfrp.modules.pyfrp_stats_module.useAIC()
.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
-
compareFitsByCorrAIC
(ROIs=None, sigma=1, fromSSD=True, thresh=None, printOut=True)¶ Compares all fits of embryo using the corrected Akaike information criterion (AICc).
For a detailed explanation of the model selection procedure, please refer to
pyfrp.modules.pyfrp_stats_module.compareFitsByCorrAIC()
.If
printOut
is selected, will print a list of selected fits and the underlying Akaike values in a readable table.If the AIC or the AICc should be used can be determined using
pyfrp.modules.pyfrp_stats_module.useAIC()
.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
-
computeBkgd
(useMin=False, fromTS='both', debug=False)¶ Computes background value over all ROIs.
If
useMin==False
, will use value at first index of data/simulation vectors as norming value.Note
Use
fromTS='both'
to use values from both simulation and data for background computation. IffromTS='data'
, will only use data, offromTS='sim'
will only use simulation vectors.Keyword Arguments: - useMin (bool) – Use minimum value for background computation.
- fromTS (bool) – Which time series to use for background computation.
- debug (bool) – Print debugging messages.
Returns: Background value.
Return type: float
-
computeConvFact
(updateDim=True)¶ Computes conversion factor between um to px (unit=um/px).
If
updateDimensions
is selected, will update all dimensions of embryo object data rely onconvFact
.Keyword Arguments: updateDim (bool) – Automatically updated all convFact relevant attributes. Returns: New conversion factor. Return type: float
-
computeIdealFRAPPinVals
(bkgdName='Bleached Square', normName='Slice', debug=False, useMin=False, useMax=False, sepSim=True, switchThresh=0.95)¶ Computes background and norming value using optimized settings.
Idea: Instead using values from all ROIs to compute pinning values, select two ROIs that should lead to optimal pinning values. In the default case, this is the ROI describing the bleached region (here we expect the lowest intensities), and the slice (here we expect the overall end concentration the experiment is converging to).
If
useMin==False
, will use value at first index of data/simulation vectors as norming value.If
useMax==False
, will use value at last index of data/simulation vectors as norming value.Note
If
bkgdName
andnormName
are not set differently, will look for ROIs with these names for background and norming computation, respectively. If they don’t exist, will returnNone
.genDefaultROIs()
will make sure that both those ROIs exist.Warning
Not all ROIs are suitable for pinning value computation. Generally ROIs that have the least extended volume proof most suitable.
Note
switchThresh
checks if recovery is complete. This is important if recovery curves are very slow and bleached region does not reach full recovery. If this happens, we divide by a number that is smaller than 1 and hence boost all timeseries way above one instead of limiting it below oneWarning
sepSim==True
makes sure that we never get negative intensities in the pinned simulation vectors. Since interpolation is never perfect, this can happen if \(bkgdValue(data)>bkgdValue(sim)\).Keyword Arguments: - bkgdName (str) – Name of ROI used for background computation.
- normName (str) – Name of ROI used for norming computation.
- useMin (bool) – Use minimum value for background computation.
- useMax (bool) – Use maximum value for norm value computation.
- fromTS (bool) – Which time series to use for background computation.
- debug (bool) – Print debugging messages.
- sepSim (bool) – Use seperate pinning values for simulation vectors.
Returns: Tuple containing:
- bkgdVal (float): Background value for data vectors.
- normVal (float): Norming value for data vectors.
- bkgdValSim (float): Background value for simulation vectors.
- normValSim (float): Norming value for simulation vectors.
Return type: tuple
-
computeNorm
(bkgdVal, useMax=True, fromTS='both', debug=False)¶ Computes background value over all ROIs.
If
useMax==False
, will use value at last index of data/simulation vectors as norming value.Note
Use
fromTS='both'
to use values from both simulation and data for background computation. IffromTS='data'
, will only use data, offromTS='sim'
will only use simulation vectors.Parameters: bkgdVal (float) – Use this background value instead of newly computing it.
Keyword Arguments: - useMax (bool) – Use maximum value for norm value computation.
- fromTS (bool) – Which time series to use for background computation.
- debug (bool) – Print debugging messages.
Returns: Norming value.
Return type: float
-
computePinVals
(useMin=True, useMax=True, bkgdVal=None, debug=False)¶ Compute overall pinning values over all ROIs.
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
-
computeROIIdxs
(signal=None, debug=True)¶ Computes image, extended and mesh indices of all ROIs in embryo’s
ROIs
list.Keyword Arguments: - signal (PyQt4.QtCore.pyqtSignal) – PyQT signal to send progress to GUI.
- debug (bool) – Print final debugging messages and show debugging plots.
Returns: Updated list of ROIs.
Return type: list
-
copy
()¶ Copies embryo, preserving all attributes and methods.
Returns: Embryo copy. Return type: pyfrp.subclasses.pyfrp_embryo.embryo
-
deleteFit
(i)¶ Deletes fit with index
i
fromfits
list.Parameters: i (int) – Index of fit to be deleted. Returns: Updated fits
list.Return type: list
-
fixFilePaths
()¶ Fixes paths to geometry/meshfiles.
Returns: True if success for all paths. Return type: bool
-
genDefaultROIs
(center, radius, rimFactor=0.66, masterROI=None, bleachedROI=None, rimROI=None, sliceHeightPx=None, clean=True)¶ Creates a standard set of ROI objects and adds them to
ROIs
list.The set of ROIs covers the generally most useful ROIs used for FRAP experiments, providing already all the settings that PyFRAP uses for rim computation etc.
ROIs contain:
- All: ROI covering all pixels and mesh nodes.
pyfrp.subclasses.pyfrp_ROI.sliceROI
- All Square: ROI covering all pixels and mesh nodes inside bleached region.
pyfrp.subclasses.pyfrp_ROI.squareROI
- All Out: ROI covering all pixels and mesh nodes outside bleached region.
pyfrp.subclasses.pyfrp_ROI.customROI
- Slice: ROI covering all pixels and mesh nodes inside recorded field of view.
pyfrp.subclasses.pyfrp_ROI.radialSliceROI
- Slice rim: ROI covering all pixels that are not used for rim concentration computation.
pyfrp.subclasses.pyfrp_ROI.radialSliceROI
- Rim: ROI covering all pixels that are used for rim concentration computation.
pyfrp.subclasses.pyfrp_ROI.customROI
- Bleached Square: ROI covering all pixels and mesh nodes inside bleached region and imaging slice.
pyfrp.subclasses.pyfrp_ROI.squareSliceROI
- Out: ROI covering all pixels and mesh nodes outside bleached region but inside imaging slice.
pyfrp.subclasses.pyfrp_ROI.customROI
Note
Will automatically set
Slice
asmasterROI
.Note
If
masterROI
is given, will use this ROI instead of Slice as master ROI viasetMasterROIIdx()
. Will not create Slice at all. IfmasterROI
is not inROIs
list yet, it will be automatically added to the list.Note
If
bleachedROI
is given, will use this ROI instead of Bleached Square. Will generate copy ofbleachedROI
to generate All Square type ROI.Note
If
rimROI
is given, Slice rim is not created, andrimROI
is used instead.Note
If
sliceHeightPx
is given, will create ROIs Slice, Out, Bleached Square and Rim at this height, otherwise will use value stored inembryo.sliceHeightPx
.Parameters: - center (list) – Center of circle defining imaging slice.
- radius (float) – Radius of circle defining imaging slice.
Keyword Arguments: - rimFactor (float) – Factor describing percentage of imaging slice excluded from rim computation.
- sliceHeightPx (float) – Height of slice ROI in px.
- clean (bool) – Will remove all ROIs from embryo object before creating new ones.
- masterROI (pyfrp.subclasses.pyfrp_ROI.ROI) – ROI that is supposed to be used as a masterROI.
- bleachedROI (pyfrp.subclasses.pyfrp_ROI.ROI) – ROI that is supposed to be used to indicate the bleached region.
- rimROI (pyfrp.subclasses.pyfrp_ROI.ROI) – ROI that is substracted from Slice. Should lie withing Slice.
Returns: Updated list of ROIs.
Return type: list
- All: ROI covering all pixels and mesh nodes.
-
geometry2Full
()¶ If current geometry was in quadrant reduced version, converts it to full version, keeping essential parameters the same.
Warning
Quadrant reduction is still experimental.
Note
Will set
fnGeo
back to default value inmeshfiles
folder.Returns: Updated geometry. Return type: pyfrp.subclasses.pyfrp_geometry.geometry
-
geometry2Quad
()¶ Converts current geometry to quadrant reduced version if available, keeping essential parameters the same.
If geometry is already reduced or there is no quadrant version of the geometry, will do nothing and return unchanged geometry.
Warning
Quadrant reduction is still experimental.
Note
Will set
fnGeo
back to default value inmeshfiles
folder.Returns: Updated geometry. Return type: pyfrp.subclasses.pyfrp_geometry.geometry
-
getDataEnc
()¶ Returns current data encoding.
-
getDataFT
()¶ Returns current data filetype.
-
getDataFolder
()¶ Returns folder containing recovery data files.
-
getDataResMu
()¶ Returns resolution of data in \(\um m\) .
-
getDataResPx
()¶ Returns resolution of data in px.
-
getFileList
()¶ Returns list of recovery data files.
-
getFitByName
(name)¶ Returns fit in
fits
list with namename
.If it doesn’t exists, returns
None
.
-
getFrameInterval
()¶ Returns current frame interval.
-
getFreeROIId
()¶ Returns first free ID of ROIs.
-
getGeometry
()¶ Returns embryo’s geometry object.
Returns: PyFRAP geometry object. Return type: pyfrp.subclasses.pyfrp_geometry.geometry
-
getInterpolationError
()¶ Prints out interpolation error by ROI.
-
getMasterROI
()¶ Returns master ROI.
-
getMasterROIIdx
()¶ Returns index of master ROI
-
getNFrames
()¶ Returns current number of frames.
-
getName
()¶ Returns embryo name.
-
getOptimalAllROI
(name='All', makeNew=False)¶ Readjusts ROI with name All (if existent) to cover whole geometry.
-
getROIById
(Id)¶ Returns ROI in
ROIs
list with specified ID.If ROI with
Id
does not exist, returnsNone
.
-
getROIByName
(name)¶ Returns ROI in
ROIs
list with specified name.If ROI with
name
does not exist, returnsNone
.
-
getROIIdx
(r)¶ Returns index of ROI in
ROIs
list.Returns
-1
if ROI is not in list.Parameters: r (pyfrp.subclasses.pyfrp_ROI.ROI) – Some ROI. Returns: Index of ROI. Return type: int
-
getROIs
()¶ Returns
ROIs
list.
-
getRimFactorByPx
(radius, px)¶ Returns the correct rimFactor if a rim of with
px
in a ROI of radiusradius
is desired.Rim factor \(f\) is then given by:
\[f=1-\frac{p}{r},\]where \(p\) is
px
and \(r\) isradius
.Parameters: - radius (float) – Radius of ROI.
- px (float) – Number of pixels that rim should be wide.
Returns: Calculated rim factor.
Return type: float
-
getTEnd
()¶ Returns current exerpiment end time.
-
getTStart
()¶ Returns current exerpiment start time.
-
getTvecData
()¶ Returns current data time vector.
-
isAnalyzed
()¶ Returns
True
if all ROIs have been analyzed.
-
isFitted
()¶ Returns
True
if all fits are fitted.
-
isSimulated
()¶ Returns
True
if all ROIs have been simulated.
-
listROIs
()¶ Prints out all ROIs and their respective type.
-
loadDataImg
(idx)¶ Loads data image in
fnDatafolder
of indexidx
.Parameters: idx (int) – Index of data image to be loaded. Returns: Loaded image. Return type: numpy.ndarray
-
makeQuadReducable
(auto=False, debug=False)¶ Makes embryo quadrant reducable by:
- Checks if embryo is reducable to quadrant by checking if all ROIs are either point or axis symmetric around geometry center.
- Tries to readjust non-symmetric ROIs to make them quad-reducable.
- If ROIs are reducable, will center geometry at center of data image.
Note
You want to call :py:meth:showAllROIBoundaries and :py:meth:computeROIIdxs afterwards to make sure everything went properly.
Warning
Quadrant reduction is still experimental.
Keyword Arguments: - tryFix (bool) – Tries to readjust ROIs into reducable form.
- auto (bool) – Readjust ROIs automatically.
- debug (bool) – Print debugging messages.
Returns: True if embryo is reducable.
Return type: bool
-
newAnalysis
()¶ Creates new
pyfrp.subclasses.pyfrp_analysis.analysis
object and sets it as embryos’sanalysis
.Returns: New analysis object. Return type: pyfrp.subclasses.pyfrp_analysis.analysis
-
newCustomROI
(name, Id, color='b', asMaster=False)¶ Creates new
pyfrp.subclasses.pyfrp_ROI.customROI
object and adds it to theROIs
list of embryo object.Note
You can use
getFreeROIId()
to find a unused ID for the newROI.Parameters: - name (str) – Name of new ROI.
- Id (int) – ID of new ROI.
Keyword Arguments: - color (str) – Color of ROI.
- asMaster (bool) – Set ROI as master ROI?
Returns: Newly created ROI object.
Return type:
-
newFit
(name)¶ Creates new fit object and appends it to list of fits.
Parameters: name (str) – Name of fit object. Returns: Newly created fit. Return type: pyfrp.subclasses.pyfrp_fit.fit
-
newPolyROI
(name, Id, corners, color='b', asMaster=False)¶ Creates new
pyfrp.subclasses.pyfrp_ROI.polyROI
object and adds it to theROIs
list of embryo object.Each corner given in
corners
list must be a list of form[x,y]
.Note
Polygon is automatically closed.
Note
You can use
getFreeROIId()
to find a unused ID for the newROI.Parameters: - name (str) – Name of new ROI.
- Id (int) – ID of new ROI.
- corners (list) – List of
[x,y]
coordinates describing corners.
Keyword Arguments: - color (str) – Color of ROI.
- asMaster (bool) – Set ROI as master ROI?
Returns: Newly created ROI object.
Return type:
-
newPolySliceROI
(name, Id, corners, height, width, sliceBottom, color='b', asMaster=False)¶ Creates new
pyfrp.subclasses.pyfrp_ROI.polySliceROI
object and adds it to theROIs
list of embryo object.Each corner given in
corners
list must be a list of form[x,y]
.Note
Polygon is automatically closed.
Note
You can use
getFreeROIId()
to find a unused ID for the newROI.Note
If
sliceBottom==True
, slice ranges fromheight<=z<=height+width
, otherwise fromheight-width/2<=z<=height+width/2
.Parameters: - name (str) – Name of new ROI.
- Id (int) – ID of new ROI.
- center (list) – Center of radial ROI.
- corners (list) – List of
[x,y]
coordinates describing corners. - width (float) – width in z-direction of slice.
- sliceBottom (bool) – Put origin of slice at botton of slice.
Keyword Arguments: - color (str) – Color of ROI.
- asMaster (bool) – Set ROI as master ROI?
Returns: Newly created ROI object.
Return type:
-
newROI
(name, Id, zmin='-inf', zmax='inf', color='b', asMaster=False)¶ Creates new simple
pyfrp.subclasses.pyfrp_ROI.ROI
object and adds it to theROIs
list of embryo object.Note
You can use
getFreeROIId()
to find a unused ID for the newROI.Parameters: - name (str) – Name of new ROI.
- Id (int) – ID of new ROI.
Keyword Arguments: - zmin (float) – Lower boundary in z-direction.
- zmax (float) – upper boundary in z-direction.
- color (str) – Color of ROI.
- asMaster (bool) – Set ROI as master ROI?
Returns: Newly created ROI object.
Return type:
-
newRadialROI
(name, Id, center, radius, color='b', asMaster=False)¶ Creates new
pyfrp.subclasses.pyfrp_ROI.radialROI
object and adds it to theROIs
list of embryo object.Note
You can use
getFreeROIId()
to find a unused ID for the newROI.Parameters: - name (str) – Name of new ROI.
- Id (int) – ID of new ROI.
- center (list) – Center of radial ROI.
- radius (float) – Radius of radial ROI.
Keyword Arguments: - color (str) – Color of ROI.
- asMaster (bool) – Set ROI as master ROI?
Returns: Newly created ROI object.
Return type:
-
newRadialSliceROI
(name, Id, center, radius, height, width, sliceBottom, color='b', asMaster=False)¶ Creates new
pyfrp.subclasses.pyfrp_ROI.radialSliceROI
object and adds it to theROIs
list of embryo object.Note
You can use
getFreeROIId()
to find a unused ID for the newROI.Note
If
sliceBottom==True
, slice ranges fromheight<=z<=height+width
, otherwise fromheight-width/2<=z<=height+width/2
.Parameters: - name (str) – Name of new ROI.
- Id (int) – ID of new ROI.
- center (list) – Center of radial ROI.
- radius (float) – Radius of radial ROI.
- height (float) – z-coordinate of slice.
- width (float) – width in z-direction of slice.
- sliceBottom (bool) – Put origin of slice at botton of slice.
Keyword Arguments: - color (str) – Color of ROI.
- asMaster (bool) – Set ROI as master ROI?
Returns: Newly created ROI object.
Return type:
-
newRectangleROI
(name, Id, offset, sidelengthX, sidelengthY, color='b', asMaster=False)¶ Creates new
pyfrp.subclasses.pyfrp_ROI.rectangleROI
object and adds it to theROIs
list of embryo object.Note
Offset is set to be left-bottom corner of rectangle.
Note
You can use
getFreeROIId()
to find a unused ID for the newROI.Parameters: - name (str) – Name of new ROI.
- Id (int) – ID of new ROI.
- offset (list) – Offset of of square.
- sidelengthX (float) – Sidelength of rectangle in x-direction.
- sidelengthY (float) – Sidelength of rectangle in y-direction.
Keyword Arguments: - color (str) – Color of ROI.
- asMaster (bool) – Set ROI as master ROI?
Returns: Newly created ROI object.
Return type:
-
newRectangleSliceROI
(name, Id, offset, sidelengthX, sidelengthY, height, width, sliceBottom, color='b', asMaster=False)¶ Creates new
pyfrp.subclasses.pyfrp_ROI.rectangleSliceROI
object and adds it to theROIs
list of embryo object.Note
Offset is set to be left-bottom corner of rectangle.
Note
You can use
getFreeROIId()
to find a unused ID for the newROI.Note
If
sliceBottom==True
, slice ranges fromheight<=z<=height+width
, otherwise fromheight-width/2<=z<=height+width/2
.Parameters: - name (str) – Name of new ROI.
- Id (int) – ID of new ROI.
- center (list) – Center of radial ROI.
- offset (list) – Offset of of rectangle.
- sidelengthX (float) – Sidelength of rectangle in x-direction.
- sidelengthY (float) – Sidelength of rectangle in y-direction.
- width (float) – width in z-direction of slice.
- sliceBottom (bool) – Put origin of slice at botton of slice.
Keyword Arguments: - color (str) – Color of ROI.
- asMaster (bool) – Set ROI as master ROI?
Returns: Newly created ROI object.
Return type:
-
newSimulation
()¶ Creates new
pyfrp.subclasses.pyfrp_simulation.simulation
object and sets it as embryos’ssimulation
.Returns: New simulation object. Return type: pyfrp.subclasses.pyfrp_simulation.simulation
-
newSliceROI
(name, Id, height, width, sliceBottom, color='b', asMaster=False)¶ Creates new
pyfrp.subclasses.pyfrp_ROI.sliceROI
object and adds it to theROIs
list of embryo object.Note
You can use
getFreeROIId()
to find a unused ID for the newROI.Note
If
sliceBottom==True
, slice ranges fromheight<=z<=height+width
, otherwise fromheight-width/2<=z<=height+width/2
.Parameters: - name (str) – Name of new ROI.
- Id (int) – ID of new ROI.
- height (float) – z-coordinate of slice.
- width (float) – width in z-direction of slice.
- sliceBottom (bool) – Put origin of slice at botton of slice.
Keyword Arguments: - color (str) – Color of ROI.
- asMaster (bool) – Set ROI as master ROI?
Returns: Newly created ROI object.
Return type:
-
newSquareROI
(name, Id, offset, sidelength, color='b', asMaster=False)¶ Creates new
pyfrp.subclasses.pyfrp_ROI.squareROI
object and adds it to theROIs
list of embryo object.Note
Offset is set to be left-bottom corner of square.
Note
You can use
getFreeROIId()
to find a unused ID for the newROI.Parameters: - name (str) – Name of new ROI.
- Id (int) – ID of new ROI.
- offset (list) – Offset of of square.
- sidelength (float) – Sidelength of square.
Keyword Arguments: - color (str) – Color of ROI.
- asMaster (bool) – Set ROI as master ROI?
Returns: Newly created ROI object.
Return type:
-
newSquareSliceROI
(name, Id, offset, sidelength, height, width, sliceBottom, color='b', asMaster=False)¶ Creates new
pyfrp.subclasses.pyfrp_ROI.squareSliceROI
object and adds it to theROIs
list of embryo object.Note
Offset is set to be left-bottom corner of square.
Note
You can use
getFreeROIId()
to find a unused ID for the newROI.Note
If
sliceBottom==True
, slice ranges fromheight<=z<=height+width
, otherwise fromheight-width/2<=z<=height+width/2
.Parameters: - name (str) – Name of new ROI.
- Id (int) – ID of new ROI.
- center (list) – Center of radial ROI.
- offset (list) – Offset of of square.
- sidelength (float) – Sidelength of square.
- width (float) – width in z-direction of slice.
- sliceBottom (bool) – Put origin of slice at botton of slice.
Keyword Arguments: - color (str) – Color of ROI.
- asMaster (bool) – Set ROI as master ROI?
Returns: Newly created ROI object.
Return type:
-
pinAllROIs
(bkgdVal=None, normVal=None, bkgdValSim=None, normValSim=None, useMin=False, useMax=False, debug=False)¶ Pins both simulation and data vectors of all ROIs.
Note
If no bkgdVal or normVal is giving, will try to compute it using
computePinVals()
. Only then input ofuseMax
anduseMin
are relevant.Keyword Arguments: - bkgdVal (float) – Background value used for data pinning.
- normVal (float) – Norming value used for data pinning.
- bkgdValSim (float) – Background value used for simulation pinning.
- normValSim (float) – Norming value used for simulation pinning.
- useMin (bool) – Use minimum value for background computation.
- useMax (bool) – Use maximum value for norm value computation.
- debug (bool) – Print debugging messages.
Returns: Updated list of ROIs.
Return type: list
-
plotAllData
(ax=None, legend=True)¶ Plots all data timeseries for all ROIs in
ROIs
list.If no axes are given via
ax
, will create new matplotlib axes.Keyword Arguments: - ax (matplotlib.axes) – Axes to be plotted in.
- legend (bool) – Show legend in plot.
Returns: Axes used for plotting.
Return type: matplotlib.axes
-
plotAllDataPinned
(ax=None, legend=True)¶ Plots all pinned data timeseries for all ROIs in
ROIs
list.If no axes are given via
ax
, will create new matplotlib axes.Keyword Arguments: - ax (matplotlib.axes) – Axes to be plotted in.
- legend (bool) – Show legend in plot.
Returns: Axes used for plotting.
Return type: matplotlib.axes
-
plotAllSim
(ax=None, legend=True)¶ Plots all simulation timeseries for all ROIs in
ROIs
list.If no axes are given via
ax
, will create new matplotlib axes.Keyword Arguments: - ax (matplotlib.axes) – Axes to be plotted in.
- legend (bool) – Show legend in plot.
Returns: Axes used for plotting.
Return type: matplotlib.axes
-
plotAllSimPinned
(ax=None, legend=True)¶ Plots all pinned simulation timeseries for all ROIs in
ROIs
list.If no axes are given via
ax
, will create new matplotlib axes.Keyword Arguments: - ax (matplotlib.axes) – Axes to be plotted in.
- legend (bool) – Show legend in plot.
Returns: Axes used for plotting.
Return type: matplotlib.axes
-
printAllAttr
(full=False)¶ Prints out all attributes of embryo object.
-
quickAnalysis
(maxDExpPx=None, timeScale='log')¶ Performs complete FRAP analysis of embryo object including:
- Finding ROI indices by calling
computeROIIdxs()
. - Running image analysis through
pyfrp.subclasses.pyfrp_analysis.analysis.run()
. - Generating optimal time simulation vector through
pyfrp.subclasses.pyfrp_simulation.simulation.getOptTvecSim()
- Running simulation through
pyfrp.subclasses.pyfrp_simulation.simulation.run()
. - Pin simulation and data timeseries using
computeIdealFRAPPinVals()
andpinAllROIs()
. - Run all fits in
fits
list by callingpyfrp.subclasses.pyfrp_fit.fit.run()
Keyword Arguments: - maxDExpPx (float) – Maximum expected diffusion coefficient.
- timeScale (str) – Linear (
'lin'
) or logarithmic ('log'
) time scaling.
- Finding ROI indices by calling
-
removeROI
(i)¶ Removes ROI of index
i
.
-
renameMeshFiles
(fn=None, debug=False)¶ Renames meshfiles associated with embryo fo
fn
.If
fn=None
will rename toself.name.ext
, whereext
is either.geo
or.msh
.Example:
>>> emb.geometry.getFnGeo() >>> path/to/meshfiles/dome.geo >>> emb.getName() >>> myEmbryo >>> emb.renameMeshFiles() >>> emb.geometry.getFnGeo() >>> path/to/meshfiles/myEmbryo.geo
Note
Will automatically update
geometry.fnGeo
andsimulation.mesh.fnMesh
properties.Keyword Arguments: - fn (str) – Desired filename.
- debug (bool) – Print out debugging messages.
Returns: Tuple containing:
- fnGeoNew (str): New path to geometry file.
- fnMeshNew (str): New path to mesh file.
Return type: tuple
-
save
(fn=None, copyMeshFiles=True, debug=False)¶ Saves embryo object to pickle file.
If
fn=None
will save toself.name.emb
.Keyword Arguments: - fn (str) – Output filename.
- copyMeshFiles (bool) – Copy meshfiles to embryo file destination.
- debug (bool) – Print out debugging messages.
Returns: Output filename.
Return type: str
-
setDataEnc
(e)¶ Sets data encoding of datasets, for example
uint16
.
-
setDataFT
(f)¶ Sets data filetype of datasets, for example .tif .
-
setDataFolder
(fn)¶ Set folder containing recovery data files.
Will automatically try to update
fileList
by callingupdateFileList()
.Parameters: fn (str) – Path to folder containing data files. Returns: New data folder path. Return type: str
-
setDataResMu
(res)¶ Sets resolution of data in \(\mu m\).
-
setDataResPx
(res)¶ Sets resolution of data in px.
-
setEmbryo2Full
()¶ Sets both geometry and ROIs to full mode.
Returns: Tuple Containing: self.geometry
(pyfrp.subclasses.pyfrp_geometry.geometry): Updated geometry.self.ROIs
(list): Updated list of ROIs.
Return type: tuple
-
setEmbryo2Quad
()¶ Reduces both geometry and ROIs of embryo to quadrant, such that embryo object is fully quadrant reduced.
Returns: Tuple Containing: self.geometry
(pyfrp.subclasses.pyfrp_geometry.geometry): Updated geometry.self.ROIs
(list): Updated list of ROIs.
Return type: tuple
-
setFileList
(l)¶ Sets file list to
l
.
-
setFrameInterval
(dt)¶ Sets interval between imaging frames, then updates all time vectors.
Parameters: dt (float) – New frame interval in seconds. Returns: Set frame interval. Return type: float
-
setGeometry2Ball
(center, imagingRadius)¶ Sets embryo’s geometry to
pyfrp.subclasses.pyfrp_geometry.ball
.Parameters: - center (list) – Center of geometry.
- imagingRadius (float) – Radius of embryo in imaging slice.
Returns: New ball geometry.
Return type: pyfrp.subclasses.pyfrp_geometry.ball
-
setGeometry2BallQuad
(center, imagingRadius)¶ Sets embryo’s geometry to
pyfrp.subclasses.pyfrp_geometry.ballQuad
.Warning
Quadrant reduction is still experimental.
Parameters: - center (list) – Center of geometry.
- imagingRadius (float) – Radius of embryo in imaging slice.
Returns: New ball quadrant geometry.
Return type: pyfrp.subclasses.pyfrp_geometry.ball
-
setGeometry2Cone
(center, upperRadius, lowerRadius, height)¶ Sets embryo’s geometry to
pyfrp.subclasses.pyfrp_geometry.cone
.Parameters: - center (list) – Center of geometry.
- upperRadius (float) – Radius at upper end of cone.
- lowerRadius (float) – Radius at lower end of cone.
- height (float) – Height of cylinder.
Returns: New cone geometry.
Return type:
-
setGeometry2Custom
(center, fnGeo='')¶ Sets embryo’s geometry to
pyfrp.subclasses.pyfrp_geometry.custom
.Parameters: - center (list) – Center of geometry.
- fnGeo (str) – Path to geometry file.
Returns: New custom geometry.
Return type:
-
setGeometry2Cylinder
(center, radius, height)¶ Sets embryo’s geometry to
pyfrp.subclasses.pyfrp_geometry.cylinder
.Parameters: - center (list) – Center of geometry.
- radius (float) – Radius of cylinder.
- height (float) – Height of cylinder.
Returns: New cylinder geometry.
Return type:
-
setGeometry2CylinderQuad
(center, radius, height)¶ Sets embryo’s geometry to
pyfrp.subclasses.pyfrp_geometry.cylinderQuad
.Warning
Quadrant reduction is still experimental.
Parameters: - center (list) – Center of geometry.
- radius (float) – Radius of cylinder.
- height (float) – Height of cylinder.
Returns: New cylinder quadrant geometry.
Return type:
-
setGeometry2ZebraFishDomeStage
(center, imagingRadius, radiusScale=1.1)¶ Sets embryo’s geometry to
pyfrp.subclasses.pyfrp_geometry.zebrafishDomeStage
.Parameters: - center (list) – Center of geometry.
- imagingRadius (float) – Radius of embryo at imaging slice.
Keyword Arguments: radiusScale (float) – Scaling factor defining how much bigger outer radius is to inner radius.
Returns: New zebrafish geometry.
Return type:
-
setGeometry2ZebraFishDomeStageQuad
(center, imagingRadius, radiusScale=1.1)¶ Sets embryo’s geometry to
pyfrp.subclasses.pyfrp_geometry.zebrafishDomeStageQuad
.Warning
Quadrant reduction is still experimental.
Parameters: - center (list) – Center of geometry.
- imagingRadius (float) – Radius of embryo at imaging slice.
Keyword Arguments: radiusScale (float) – Scaling factor defining how much bigger outer radius is to inner radius.
Returns: New zebrafish quadrant geometry.
Return type:
-
setMasterROIIdx
(idx)¶ Define ROI with index
idx
as master ROI.
-
setNFrames
(n)¶ Sets number of frames, then updates all time vectors.
-
setName
(n)¶ Sets embryo name.
-
setSideLengthBleachedMu
(s)¶ Sets sidelength of bleached square in \(\mu m\), will then update bleached region parameters by calling
updateBleachedRegion()
.Warning
Attributes
sideLengthBleachedMu
andoffsetBleachedPx
will deprecated in further versions. Bleached region definition will then solely rely on ROI definitions.
-
setSliceDepthMu
(d, updateGeometry=True)¶ Sets resolution of data in \(\mu m\) and then updates all dimensions of embryo object data rely on
sliceDepthMu
.If
updateGeometry
is selected, will automatically update geometry.Note
Not every geometry depends on slice depth. If the geometry object has a method
restoreDefault
, this will be called. Otherwise geometry is not updated.Parameters: d (float) – New slice depth in \(\mu m\). Keyword Arguments: updateGeometry (bool) – Update geometry. Returns: New slice depth. Return type: float
-
setTEnd
(t)¶ Sets end time of experiment, then updates all time vectors.
Parameters: t (float) – End time in seconds. Returns: Set end time. Return type: float
-
setTStart
(t)¶ Sets start time of experiment, then updates all time vectors.
Parameters: t (float) – Start time in seconds. Returns: Set start time. Return type: float
-
showAllROIBoundaries
(ax=None, withImg=False, idx=0)¶ Shows boundaries of all ROIs in
ROIs
list.If no axes are given via
ax
, will create new matplotlib axes.Keyword Arguments: - ax (matplotlib.axes) – Axes to be plotted in.
- withImg (bool) – Shows data image inside same axes.
- idx (int) – Index of data image to be shown.
Returns: Axes used for plotting.
Return type: matplotlib.axes
-
showAllROIIdxs
(axes=None)¶ Shows image, extended and mesh indices of all ROIs in
ROIs
list.If no axes are given via
axes
, will create new list of matplotlib axes. If axes are given, they should havelen(axes)=3*len(ROIs)
.Note
If the mesh has a large number of nodes, this can take up a lot of memory due to every node being plotted in a matplotlib scatter plot.
Keyword Arguments: axes (list) – List of matplotlib.axes to be plotted in. Returns: List of axes used for plotting. Return type: matplotlib.axes
-
showDataImg
(ax=None, idx=0)¶ Shows data image in
fnDatafolder
of indexidx
.If no axes are given via
ax
, will create new matplotlib axes.Keyword Arguments: idx (int) – Index of data image to be shown. Returns: Axes used for plotting. Return type: matplotlib.axes
-
sliceEmbryo
(nSlices, direction='z')¶ Slices embryo in z-direction in
nSlices
.Creates
nSlices
newpyfrp.subclasses.pyfrp_ROI.sliceROI
ROIs and appends them toROIs
list.Note
Slice ROIs will be created with
sliceBottom=False
.Parameters: nSlices (int) – Number of slices embryo is supposed to get cut. Returns: Updates ROIs
list.Return type: list
-
updateBleachedRegion
()¶ Updates sidelength and offset of bleached square in px.
Bleached region is defined around center of image. That is, the offset is set to
\[x_{\mathrm{offset}} = \frac{1}{2}(r_{\mathrm{px}},r_{\mathrm{px}})^T - (s_{\mathrm{bleached,px}},s_{\mathrm{bleached,px}})^T\]where \(r_{\mathrm{px}}\) is the resolution of the data in pixel, and \(s_{\mathrm{bleached,px}\) is the sidelength of the bleached square in pixel.
Warning
Attributes
sideLengthBleachedMu
andoffsetBleachedPx
will deprecated in further versions. Bleached region definition will then solely rely on ROI definitions.
-
updateFileList
()¶ Updates file list containing all names of recovery images.
If new
fileList
is not empty, will update number of frames to match number of files infileList
by callingupdateNFrames()
.Returns: Updated file list. Return type: list
-
updateNFrames
()¶ Updates number of frames, then updates all time vectors.
Note
Gets number of frames by reading number of files of type
dataFT
infnDatafolder
. So you should make sure that there are no extra files infnDatafolder
.Returns: Updated number of frames. Return type: int
-
updatePxDimensions
()¶ Updates all all convFact relevant attributes.
Returns: Tuple containing: - sliceWidthPx (float): Updated slice width in px.
- sliceDepthPx (float): Updated slice depth in px.
- sliceHeightPx (float): Updated slice height in px.
- sideLengthBleachedPx (float): Updated side length of bleached square in px.
- offsetBleachedPx (float): Updated offset if bleached square in px.
Return type: tuple
-
updateTimeDimensions
(simUpdate=True)¶ Updates time dimensions using information in
frameInterval
,nFrames
andtStart
.Note
If embryo object already possesses simulation object, will update simulation time dimensions using
pyfrp.subclasses.pyfrp_simulation.simulation.toDefaultTvec()
. If you have different settings in simulation vector that you want to preserve, selectsimUpdate=False
.Keyword Arguments: simUpdate (bool) – Update simulation time dimensions. Returns: Updated data time vector. Return type: numpy.ndarray
-
updateVersion
()¶ Updates embryo object to current version, making sure that it possesses all attributes.
Creates a new embryo object and compares
self
with the new embryo object. If the new embryo object has a attribute thatself
does not have, will add attribute with default value from the new embryo object.Returns: self
Return type: pyfrp.subclasses.pyfrp_embryo.embryo
pyfrp.subclasses.pyfrp_fit module¶
Essential PyFRAP module containing pyfrp.subclasses.pyfrp_fit.fit
class.
-
class
pyfrp.subclasses.pyfrp_fit.
fit
(embryo, name)¶ Main fit class of PyFRAP.
The purpose of the fit class is to save all attributes used for fitting PyFRAP simulation results to data analysis results. The main attributes are:
Fitting algorithm specifics:
- Fitting algorithm, see also
setOptMeth()
. - Stopping criteria, see also
setMaxfun()
andsetOptTol()
. - Initial guess, see also
getX0()
. - Boundaries, see also
getBounds()
.
- Fitting algorithm, see also
Fitting options:
fitProd
, see alsogetFitProd()
.fitDegr
, see alsogetFitDegr()
.fitPinned
, see alsogetFitPinned()
.equOn
, see alsogetEqu()
.fitCutOffT
, see alsogetFitCutOffT()
.
The ROIs to be fitted, see also
getROIsFitted()
.Fitting results, see also
printResults()
.Fitted vectors.
The most important methods are:
run()
: Runs fitting.addROIByName()
: Adds ROI to be used for fitting.getX0()
: Builds and returns current initial guess.getBounds()
: Builds and returns current bounds.computeStats()
: Compares post-fitting statistics.
The fit uses simulation and data vectors stored in all
pyfrp.subclasses.pyfrp_ROI.ROI
objects defined inROIsFitted
list to compute the optimal values forDOptMu
(prodOpt
ordegrOpt
iffitProd
orfitDegr
is selected, respectively).After calling
run()
, will automatically compute properx0
viagetX0()
andgetBounds()
.Parameters: - embryo (pyfrp.subclasses.pyfrp_embryo.embryo) – Embryo object that fit belongs to.
- name (str) – Name of fit.
-
addROI
(r)¶ Adds ROI to the list of fitted ROIs.
Parameters: r (pyfrp.subclasses.pyfrp_ROI.ROI) – ROI to be used for fitting. Returns: Updated list of ROIs used for fitting. Return type: list
-
addROIById
(Id)¶ Adds ROI to the list of fitted ROIs, given a specific ROI Id.
Parameters: Id (int) – Id of ROI to be used for fitting. Returns: Updated list of ROIs used for fitting. Return type: list
-
addROIByName
(name)¶ Adds ROI to the list of fitted ROIs, given a specific name.
Parameters: name (str) – Name of ROI to be used for fitting. Returns: Updated list of ROIs used for fitting. Return type: list
-
assignOptParms
(res)¶ Assigns optimal parameters found by optimization algorithm to attributes in fit object depending on fit options chosen.
Parameters: res (list) – Result array from optimization algorithm. Returns: Tuple containing: - DOptPx (float): Optimal diffusion coefficient in \(\frac{\mathrm{px}^2}{s}}\).
- prod (float): Optimal production rate in \(\frac{\[c\]}{s}}\).
- degr (float): Optimal degradation rate in \(\frac{1}{s}}\).
- DOptMu (float): Optimal diffusion coefficient in \(\frac{\mu\mathrm{m}^2}{s}}\).
Return type: tuple
-
checkPinned
()¶ Checks if all ROIs in
ROIsFitted
have been pinned.Returns: True
if all ROIs have been pinned,False
else.Return type: bool
-
checkSimulated
()¶ Checks if all ROIs in
ROIsFitted
have been simulated.Returns: True
if all ROIs have been simulated,False
else.Return type: bool
-
computeStats
()¶ Computes stastics for fit.
Statistics include:
MeanRsq
Rsq
RsqByROI
-
getBounds
()¶ Generates tuple of boundary tuples, limiting parameters varied during SSD minimization.
Will generate exactly the boundary tuple that is currently useful to the optimization algorithm, meaning that only values that are needed since they are turned on via
fitProd
orfitDegr
will be included into tuple.Will use values that are stored in
LBx
andUBx
, wherex
isD
,Prod
, orDegr
for the creation of the tuples.Will also add a tuple of bounds defined via
LBEqu
andUBEqu
for each ROI inROIsFitted
.Note
Always gets executed at the start of
run
.Returns: Boundary value tuple. Return type: tuple
-
getBruteInitDArray
(steps=5)¶ Generates array of different possibilities to be used as initial guess for D.
If
LBD
andUBD
is given, will simply divide the range between the two in 4 equidistant values. Otherwise will vary aroundx0
in 2 orders of magnitude.Keyword Arguments: steps (int) – How many initial guesses to generate. Returns: Array with possible initial guesses for D. Return type: list
-
getCutOffT
()¶ Returns timepoint at which timeseries are cut if
fitCutOffT
is turned on.Warning
This option is currently VERY experimental. Fitting might crash.
Returns: Timepoint. Return type: float
-
getEqu
()¶ Returns equalization flag.
Returns: Current flag value. Return type: bool
-
getFitCutOffT
()¶ Returns flag controlling if only the first
cutOffT
timesteps are supposed to be fitted.Warning
This option is currently VERY experimental. Fitting might crash.
Returns: Current flag value. Return type: bool
-
getFitDegr
()¶ Returns flag controlling if a degredation term is supposed to be used for fitting.
Returns: Current flag value. Return type: bool
-
getFitPinned
()¶ Returns flag controlling if pinned timeseries are supposed to be used for fitting.
Returns: Current flag value. Return type: bool
-
getFitProd
()¶ Returns flag controlling if a production term is supposed to be used for fitting.
Returns: Current flag value. Return type: bool
-
getFittedParameterNames
()¶ Returns names of parameters that are selected for fitting.
Returns: Names of parameters fitted. Return type: list
-
getKineticTimeScale
()¶ Returns the kinetic time scale factor used for fitting.
Returns: Current kinetic time scale factor. Return type: float
-
getLBD
()¶ Returns the lower bound for the diffusion rate.
Returns: Current lower bound for diffusion rate. Return type: float
-
getLBDegr
()¶ Returns the lower bound for the degradation rate.
Returns: Current lower bound for degradation rate. Return type: float
-
getLBProd
()¶ Returns the lower bound for the production rate.
Returns: Current lower bound for production rate. Return type: float
-
getMaxfun
()¶ Returns maximum number of function evaluations at which optimization algorithm stops.
Returns: Current maximum number of function evaluations. Return type: int
-
getNParmsFitted
(inclEqu=True)¶ Returns the number of parameters fitted in this fit.
Note
If equlalization is turned on, each ROI in
ROIsFitted
counts as an extra parameter.Example: We fit production and equalization for 2 ROIs, then we have fitted
- D
- degradation
- equalization ROI 1
- equalization ROI 2
leading to in total 4 fitted parameters.
Keyword Arguments: inclEqu (bool) – Include equalization as additional fitted parameter. Returns: Number of parameters fitted. Return type: int
-
getName
()¶ Returns name of fit.
Returns: Name of fit. Return type: str
-
getOptMeth
()¶ Returns the currently used optimization algorithm.
Returns: Optimization algorithm. Return type: str
-
getOptTol
()¶ Returns tolerance level at which optimization algorithm stops.
Returns: Current tolerance level. Return type: float
-
getROIsFitted
()¶ Returns list of ROIs used for fitting.
Returns: list of ROIs used for fitting. Return type: list
-
getSaveTrack
()¶ Returns flag controlling if whole fitting process is supposed to be saved in fit object.
Returns: Current flag value. Return type: bool
-
getUBD
()¶ Returns the upper bound for the diffusion rate.
Returns: Current upper bound for diffusion rate. Return type: float
-
getUBDegr
()¶ Returns the upper bound for the degradation rate.
Returns: Current upper bound for degradation rate. Return type: float
-
getUBProd
()¶ Returns the upper bound for the production rate.
Returns: Current upper bound for production rate. Return type: float
-
getX0
()¶ Returns initial guess of fit in the form that is useful for the call of the optimization algorithm.
Copies x0 into local variable to pass to solver, pop entries that are currently not needed since they are turned off via
fitProd
orfitDegr
.Always appends initial guess for equalization factors, even though they might not been used.
Note
Always gets executed at the start of
run
.Returns: Currently used x0. Return type: list
-
getX0D
()¶ Returns the initial guess for the diffusion rate.
Returns: Initial guess for diffusion rate. Return type: float
-
getX0Degr
()¶ Returns the initial guess for the degradation rate.
Returns: Initial guess for degration rate. Return type: float
-
getX0Equ
(x)¶ Returns the initial guess for the equalization factor for all ROIs fitted.
Returns: Initial guess for equalization factor. Return type: list
-
getX0Prod
()¶ Returns the initial guess for the production rate.
Returns: Initial guess for production rate. Return type: float
-
isFitted
()¶ Checks if fit already has been run and succeeded.
Returns: True
if success.Return type: bool
-
plotFit
(ax=None, legend=True, title=None, show=True)¶ Plots fit, showing the result for all fitted ROIs.
Note
If no
ax
is given, will create new one.Keyword Arguments: - ax (matplotlib.axes) – Axes used for plotting.
- legend (bool) – Show legend.
- title (str) – Title of plot.
- show (bool) – Show plot.
Returns: Axes used for plotting.
Return type: matplotlib.axes
-
plotLikehoodProfiles
(epsPerc=0.1, steps=100, debug=False)¶ Plots likelihood profiles for all fitted parameters.
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.plotFitLikehoodProfiles()
.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
-
printAllAttr
()¶ Prints out all attributes of fit object.
-
printResults
()¶ Prints out main results of fit.
-
printRsqByROI
()¶ Prints out Rsq value per ROI.
-
removeROI
(r)¶ Removes ROI from the list of fitted ROIs.
Parameters: r (pyfrp.subclasses.pyfrp_ROI.ROI) – ROI to be removed. Returns: Updated list of ROIs used for fitting. Return type: list
-
reset2DefaultX0
()¶ Resets initial guess x0 to its default form.
The default form of x0 is
>>> [10., 0. ,0. , 1.,1.,1.]
The last entries are the initial guess of equlalization factors and is set to be list of of ones of the same length of
ROIsFitted
.Returns: New initial guess x0. Return type: list
-
resultsToDict
()¶ Extracts all important results into dictionary, making it easier for printout or csv extraction.
-
resultsToVec
()¶ Puts results back in vector as optimization algorithm would return it.
Returns: Result vector. Return type: list
-
run
(debug=False, ax=None)¶ Runs fit.
Fitting is done by passing fit object to
pyfrp.modules.pyfrp_fit_module.FRAPFitting()
. This function then calls all necessary methods of fit to prepare it for optimization and then passes it to optimization algorithm.Note
If
bruteInitD
is turned on, will executerunBruteInit()
instead.Keyword Arguments: - debug (bool) – Print debugging messages.
- ax (matplotlib.axes) – Axes to show debugging plots in.
Returns: self
.Return type:
-
runBruteInit
(debug=False, ax=None, steps=5, x0Ds=[])¶ Runs fit for different initial guesses of the diffusion constant D, then selects the one that actually yielded the minimal SSD.
Initially guesses are generated with
getBruteInitDArray()
if no arrayx0Ds
is given.Fitting is done by passing fit object to
pyfrp.modules.pyfrp_fit_module.FRAPFitting()
. This function then calls all necessary methods of fit to prepare it for optimization and then passes it to optimization algorithm.Will select the initial guess that yielded the minimal SSD and then rerun with this x0 again, making sure that everything is updated in fit object.
Keyword Arguments: - debug (bool) – Print debugging messages.
- ax (matplotlib.axes) – Axes to show debugging plots in.
- steps (int) – How many initial guesses to generate.
- x0Ds (list) – Array with possible initial guesses for D.
Returns: self
.Return type:
-
setBruteInitD
(b)¶ Turns on/off if the initial guess of for the diffusion rate D should be bruteforced.
Parameters: b (bool) – Flag value. Returns: Current flag value. Return type: bool
-
setCutOffT
(t)¶
-
setEqu
(b)¶ Turns on/off equalization.
Parameters: b (bool) – New flag value. Returns: New flag value. Return type: bool
-
setFitCutOffT
(b)¶ Turns on/off if only a certain fraction of the timeseries is supposed to be fitted.
Warning
This option is currently VERY experimental. Fitting might crash.
Parameters: b (bool) – New flag value. Returns: New flag value. Return type: bool
-
setFitDegr
(b)¶ Turns on/off if degradation is supposed to be considered in fit.
Parameters: b (bool) – New flag value. Returns: New flag value. Return type: bool
-
setFitPinned
(b)¶ Turns on/off if pinned series are supposed to be fitted.
Parameters: b (bool) – New flag value. Returns: New flag value. Return type: bool
-
setFitProd
(b)¶ Turns on/off if production is supposed to be considered in fit.
Parameters: b (bool) – New flag value. Returns: New flag value. Return type: bool
-
setKineticTimeScale
(s)¶ Sets the kinetic time scale factor used for fitting.
Parameters: s (float) – New kinetic time scale factor.
-
setLBD
(b)¶ Sets the lower bound for the diffusion rate.
Parameters: b (float) – New lower bound for diffusion rate.
-
setLBDegr
(b)¶ Sets the lower bound for the degradation rate.
Parameters: b (float) – New lower bound for degradation rate.
-
setLBProd
(b)¶ Sets the lower bound for the production rate.
Parameters: b (float) – New lower bound for production rate.
-
setMaxfun
(m)¶ Sets maximum number of function evaluations at which optimization algorithm stops.
Parameters: m (int) – New maximum number of function evaluations.
-
setName
(s)¶ Sets name of fit.
Parameters: s (str) – New name of fit.
-
setOptMeth
(m)¶ Sets optimization method.
Available optimization methods are:
- Constrained Nelder-Mead
- Nelder-Mead
- TNC
- L-BFGS-B
- SLSQP
- brute
- BFGS
- CG
See also http://docs.scipy.org/doc/scipy-0.17.0/reference/generated/scipy.optimize.minimize.html and http://docs.scipy.org/doc/scipy-0.17.0/reference/generated/scipy.optimize.brute.html#scipy.optimize.brute .
You can find out more about the constrained Nelder-Mead algorithm in the documentation of
pyfrp.modules.pyfrp_optimization_module.constrObjFunc()
.Parameters: m (str) – New method.
-
setOptTol
(m)¶ Sets tolerance level at which optimization algorithm stops.
Parameters: m (float) – New tolerance level.
-
setSaveTrack
(b)¶ Turns on/off if fitting process is supposed to be stored.
This then can then be used to following the convergence of the optimization algorithm and possibly to identify local minima.
Parameters: b (bool) – New flag value. Returns: New flag value. Return type: bool
-
setUBD
(b)¶ Sets the upper bound for the diffusion rate.
Parameters: b (float) – New upper bound for diffusion rate.
-
setUBDegr
(b)¶ Sets the upper bound for the degradation rate.
Parameters: b (float) – New upper bound for degradation rate.
-
setUBProd
(b)¶ Sets the upper bound for the production rate.
Parameters: b (float) – New upper bound for production rate.
-
setX0
(x)¶ Sets the initial guess
x0
.Argument
x
needs to have length 3, otherwise it is being rejected.Note
If
fitProd
orfitDegr
are not chosen, the values inx0
are going to be used as static parameters.Parameters: x (list) – New desired initial guess. Returns: New initial guess. Return type: list
-
setX0D
(x)¶ Sets the initial guess for the diffusion rate.
Parameters: x (float) – Initial guess for diffusion rate.
-
setX0Degr
(x)¶ Sets the initial guess for the degradation rate.
Parameters: x (float) – Initial guess for degradation rate.
-
setX0Equ
(x)¶ Sets the initial guess for the equalization factor.
Note
Does this for all ROIs in ROIsFitted.
Parameters: x (float) – Initial guess for equalization factor.
-
setX0Prod
(x)¶ Sets the initial guess for the production rate.
Parameters: x (float) – Initial guess for production rate.
-
updateVersion
()¶ Updates fit object to current version, making sure that it possesses all attributes.
Creates a new fit object and compares
self
with the new fit object. If the new fit object has a attribute thatself
does not have, will add attribute with default value from the new fit object.Returns: self
Return type: pyfrp.subclasses.pyfrp_fit.fit
pyfrp.subclasses.pyfrp_geometry module¶
PyFRAP module containing geometry classes. The geometry
class is
a simple geometry class providing basic parameters and methods, parenting different
more specific geometries such as:
zebrafishDomeStage
: Describing a zebrafish embryo in dome stage.cylinder
: A simple cylinder.xenopusBall
: A simple ball geometry (looking like a xenopus embryo).cone
: A (truncated) cone.
For most of the geometries, this module also provides quadrant reduced versions of the geometry, reducing the geometry to the first quadrant around the center.
Note
Rules for adding new geometries:
- Always subclass from
geometry
- Always center geometry around
geometry.center
. That includes having defining the center in the .geo file bycenter_x
andcenter_y
. - Unit is pixels.
- Be careful with method overwrites. Use them wisely.
- Include the geometries into the GUI.
- Make them accessable by sharing them.
-
class
pyfrp.subclasses.pyfrp_geometry.
cone
(embryo, center, upperRadius, lowerRadius, height)¶ Bases:
pyfrp.subclasses.pyfrp_geometry.geometry
Geometry describing a cut-off cone.
The crucial geometrical parameters are:
upperRadius
: Upper radius of cone.lowerRadius
: Lower radius of cone.height
: Height of cone.
Note
Can also be extended to a real cone by setting
lowerRadius=0
.-
computeRadiusFromSliceHeight
(height)¶ Returns the slice radius given a slice height.
Slice radius is computed by
\[r(s) = \frac{l-u}{h} s +u\]where \(l,u\) are lower and upper radius respectively and \(h\) is cone height.
Parameters: height (float) – Slice height. Returns: Slice radius. Return type: float
-
computeSliceHeightFromRadius
(radius)¶ Returns the slice height given a slice radius.
Slice height is computed by
\[s(r) = \frac{h}{l-u} (r-u)\]where \(l,u\) are lower and upper radius respectively and \(h\) is cone height.
Parameters: radius (float) – Slice radius. Returns: Slice height. Return type: float
-
genAsOpenscad
()¶ Generates cone geometry as solid python object.
Useful if geometry is used to be passed to openscad.
Returns:
-
getHeight
()¶ Returns cone radius.
-
getLowerRadius
()¶ Returns lower radius of cone.
-
getUpperRadius
()¶ Returns upper radius of cone.
-
getXYExtend
()¶ Overwrites
pyfrp.subclasses.pyfrp_geometry.geometry.getXYExtend()
.By default, cone geometry is set to range from
center[i]-max([self.upperRadius,self.lowerRadius])
tocenter[i]+max([self.upperRadius,self.lowerRadius])
.Returns: Tuple containing: - xmin (float): Minimum x-coordinate.
- xmax (float): Maximum x-coordinate.
- ymin (float): Minimum y-coordinate.
- ymax (float): Maximum y-coordinate.
Return type: tuple
-
getZExtend
()¶ Overwrites
pyfrp.subclasses.pyfrp_geometry.geometry.getZExtend()
.By default, cone geometry is set to range from
-height
to0
.
-
optimalAllROI
(name='', Id=0, color='b', asMaster=False, roi=None)¶ Sets optimal ROI to a
pyfrp.subclasses.pyfrp_ROI.radialSliceROI
with radiusupperRadius
, centercenter
, covering the whole z-range of geometry.Keyword Arguments: - name (str) – Name of new ROI.
- Id (int) – ID of new ROI.
- color (str) – Color that ROI is going to be associated with.
- asMaster (bool) – Make new ROI masterROI.
-
setHeight
(h)¶ Sets cone height.
Parameters: h (float) – New height. Returns: New height. Return type: float
-
setLowerRadius
(r)¶ Sets cone lower radius.
Parameters: h (float) – New lower radius. Returns: New lower radius. Return type: float
-
setUpperRadius
(r)¶ Sets cone upper radius.
Parameters: h (float) – New upper radius. Returns: New upper radius. Return type: float
-
updateGeoFile
(debug=False)¶ Updates .geo file of geometry.
Keyword Arguments: debug (bool) – Print debugging messages.
-
class
pyfrp.subclasses.pyfrp_geometry.
custom
(embryo, center, fnGeo)¶ Bases:
pyfrp.subclasses.pyfrp_geometry.geometry
Custom geometry class for custom geometry configurations.
-
class
pyfrp.subclasses.pyfrp_geometry.
cylinder
(embryo, center, radius, height)¶ Bases:
pyfrp.subclasses.pyfrp_geometry.geometry
Geometry describing a cylinder.
The crucial geometrical parameters are:
radius
: Radius of the cylinder.height
: Height of the cylinder.
-
genAsOpenscad
()¶ Generates cylinder geometry as solid python object.
Useful if geometry is used to be passed to openscad.
Returns:
-
getHeight
()¶ Returns cylinder height.
Returns: Height. Return type: float
-
getRadius
()¶ Returns cylinder radius.
Returns: Radius. Return type: float
-
getXYExtend
()¶ Overwrites
pyfrp.subclasses.pyfrp_geometry.geometry.getXYExtend()
.By default, cylinder geometry is set to range from
center[i]-radius
tocenter[i]+radius
.Returns: Tuple containing: - xmin (float): Minimum x-coordinate.
- xmax (float): Maximum x-coordinate.
- ymin (float): Minimum y-coordinate.
- ymax (float): Maximum y-coordinate.
Return type: tuple
-
getZExtend
()¶ Overwrites
pyfrp.subclasses.pyfrp_geometry.geometry.getZExtend()
.By default, cylinder geometry is set to range from
-height
to0
.
-
optimalAllROI
(name='', Id=0, color='b', asMaster=False, roi=None)¶ Sets optimal ROI to a
pyfrp.subclasses.pyfrp_ROI.radialSliceROI
with radiusradius
, centercenter
, covering the whole z-range of geometry.Keyword Arguments: - name (str) – Name of new ROI.
- Id (int) – ID of new ROI.
- color (str) – Color that ROI is going to be associated with.
- asMaster (bool) – Make new ROI masterROI.
-
setHeight
(h)¶ Sets cylinder height.
Parameters: h (float) – New height. Returns: New height. Return type: float
-
setRadius
(r)¶ Sets cylinder radius.
Parameters: h (float) – New radius. Returns: New radius. Return type: float
-
updateGeoFile
(debug=False)¶ Updates .geo file of geometry.
Keyword Arguments: debug (bool) – Print debugging messages.
-
class
pyfrp.subclasses.pyfrp_geometry.
cylinderQuad
(embryo, center, radius, height)¶ Bases:
pyfrp.subclasses.pyfrp_geometry.cylinder
Geometry describing a cylinder, reduced to first quadrant.
Inherits from
cylinder
. Please refer to its documentation for further details.
-
class
pyfrp.subclasses.pyfrp_geometry.
geometry
(embryo, typ, fnGeo, center)¶ Bases:
object
Basic PyFRAP geometry class.
Stores all the necessary information to describe a geometry. Comes with helpful methods for
- Centering (see
centerInImg()
) - Defining optimal ROIs (see
optimalAllROI()
) - Geometry file parsing (see
readGeoFile()
) - Geometry plotting (see
plotGeometry()
)
Parameters: - embryo (pyfrp.subclasses.pyfrp_emrbyo.embryo) – Embryo class that geometry belongs to.
- typ (str) – Type of geometry.
- fnGeo (str) – Path to gmsh .geo file describing the geometry.
- center (numpy.ndarray) – Center of geometry.
-
center2Mid
(updateInFile=True)¶ Sets geometry center to center of image.
Uses
embryo.dataResPx
to calculate image center.Note
The geometry
center
attribute is then also set in .geo file ifupdateInFile
is selected.Keyword Arguments: updateInFile (bool) – Update center in .geo file. Returns: New center. Return type: numpy.ndarray
-
centerInImg
()¶ Sets geometry center to center of image, updates .geo file and if avaialable remeshes.
Uses
embryo.dataResPx
to calculate image center.Note
The geometry
center
attribute is then also set in .geo file.Returns: New center. Return type: numpy.ndarray
-
getCenter
()¶ Returns geometry center.
Returns: New center. Return type: numpy.ndarray
-
getEmbryo
()¶ Returns
pyfrp.subclasses.pyfrp_embryo.embryo
instance that geometry belongs to.
-
getExtend
()¶ Returns extend in x/y/z-direction.
Will call
getXYExtend()
andgetZExtend()
for it.Returns: Tuple containing: - xmin (float): Minimum x-coordinate.
- xmax (float): Maximum x-coordinate.
- ymin (float): Minimum y-coordinate.
- ymax (float): Maximum y-coordinate.
- zmin (float): Minimum z-coordinate.
- zmax (float): Maximum z-coordinate.
Return type: tuple
-
getFnGeo
()¶ Returns path to .geo file.
Returns: Path to file. Return type: str
-
getMaxGeoID
()¶ Returns maximum ID over all elements in .geo file.
Sell also
readGeoFile()
andpyfrp.modules.pyfrp_gmsh_geometry.domain.getAllMaxID()
.Returns: Maximum ID. Return type: int
-
getTyp
()¶ Returns type of geometry.
Returns: Type of geometry. Return type: str
-
getXYExtend
()¶ Returns extend in x/y-direction by reading out vertices from .geo file and returning maximum and minimum x/y-coordinates.
Returns: Tuple containing: - xmin (float): Minimum x-coordinate.
- xmax (float): Maximum x-coordinate.
- ymin (float): Minimum y-coordinate.
- ymax (float): Maximum y-coordinate.
Return type: tuple
-
getZExtend
()¶ Returns extend in z-direction by reading out vertices from .geo file and returning maximum and minimum z-coordinates.
Returns: Tuple containing: - zmin (float): Minimum z-coordinate.
- zmax (float): Maximum z-coordinate.
Return type: tuple
-
moveGeoFile
(fn)¶ Moves geometry file to different directory.
Note
This function actually copies the file so that files in
pyfrp/meshfiles/
will not be removed.Will update
geometry.fnGeo
to the new file location.Note
If existent, will also copy the corresponding mesh file.
Parameters: fn (str) – Path of folder where geo file is supposed to go. Returns: New file location. Return type: str
-
plotGeometry
(ax=None, color='k', ann=False)¶ Plots geometry in 3D.
Reads the .geo file and parses it into a
pyfrp.modules.pyfrp_gmsh_geometry.domain
instance. Then draws the domain.If no axes are given via
ax
, will create new matplotlib axes.Keyword Arguments: - ax (matplotlib.axes) – Axes to draw in.
- color (str) – Color of plot.
- ann (bool) – Show annotations.
Returns: Axes used for plotting.
Return type: matplotlib.axes
-
printDetails
()¶ Prints out all details of geometry object.
-
readGeoFile
()¶ Reads the .geo file and parses it into a
pyfrp.modules.pyfrp_gmsh_geometry.domain
instance.Returns: Domain containing geometry. Return type: pyfrp.modules.pyfrp_gmsh_geometry.domain
-
render2Openscad
(fn=None, segments=48)¶ Generates .scad file for the geometry.
Note
If
fn=None
, then will use the same filename and path as .geo file.Keyword Arguments: - fn (str) – Output filename.
- segments (int) – Number of segments used for convex hull of surface.
-
render2Stl
(fn=None, segments=48)¶ Generates .stl file for the geometry.
Note
If
fn=None
, then will use the same filename and path as .geo file.Keyword Arguments: - fn (str) – Output filename.
- segments (int) – Number of segments used for convex hull of surface.
-
setAllROI
(name='All', makeNew=False, updateIdxs=False)¶ Tries to set the optimal All ROI for a specific geometry.
Keyword Arguments: - name (str) – Name of All ROI to look for.
- makeNew (bool) – Generate a new All ROI.
- updateIdxs (bool) – Update indices of new ROI.
Returns: New ROI instance.
Return type:
-
setCenter
(c, updateInFile=True)¶ Sets geometry center.
Note
The geometry
center
attribute is then also set in .geo file ifupdateInFile
is selected.Parameters: c (numpy.ndarray) – New center [x,y]
.Keyword Arguments: updateInFile (bool) – Update center in .geo file. Returns: New center. Return type: numpy.ndarray
-
setFnGeo
(fn)¶ Sets path to .geo file.
Parameters: fn (str) – Path to file. Returns: Path to file. Return type: str
- Centering (see
-
class
pyfrp.subclasses.pyfrp_geometry.
xenopusBall
(embryo, center, imagingRadius)¶ Bases:
pyfrp.subclasses.pyfrp_geometry.geometry
Geometry describing a ball.
This geometry is similar to a xenopus in stage 7-10, see http://www.xenbase.org/anatomy/alldev.do.
The crucial geometrical parameters are:
radius
: Radius of the ball.
PyFRAP automatically computes these parameters given
imagingRadius
: Radius of embryo at imaging depth.imagingHeight
: Imaging depth.
For details of this computations, see
computeBall()
.-
computeBall
()¶ Computes ball geometry from
imagingRadius
andimagingHeight
.Computes ball geometry as follows:
\[r=\frac{r_{\mathrm{imaging}}^2+h_{\mathrm{imaging}}^2}{-2 h_{\mathrm{imaging}}},\]where \(r\) is the
radius
, \(h_{\mathrm{imaging}}\) is theimagingHeight
and \(r_{\mathrm{imaging}}\) is theimagingRadius
.The center of the ball is set to
[center[0],center[1],-radius]
(Only in .geo file).
-
getImagingHeight
(h)¶ Returns imaging height.
-
getImagingRadius
(r)¶ Returns imaging radius.
-
getRadius
()¶ Returns ball radius.
-
getXYExtend
()¶ Overwrites
pyfrp.subclasses.pyfrp_geometry.geometry.getXYExtend()
.By default, ball geometry is set to range from
center[i]-radius
tocenter[i]+radius
.Returns: Tuple containing: - xmin (float): Minimum x-coordinate.
- xmax (float): Maximum x-coordinate.
- ymin (float): Minimum y-coordinate.
- ymax (float): Maximum y-coordinate.
Return type: tuple
-
getZExtend
()¶ Overwrites
pyfrp.subclasses.pyfrp_geometry.geometry.getZExtend()
.By default, ball geometry is set to range from
-imagingRadius
to0
.
-
optimalAllROI
(name='', Id=0, color='b', asMaster=False, roi=None)¶ Sets optimal ROI to a
pyfrp.subclasses.pyfrp_ROI.radialSliceROI
with radiusradius
, centercenter
, covering the whole z-range of geometry.Keyword Arguments: - name (str) – Name of new ROI.
- Id (int) – ID of new ROI.
- color (str) – Color that ROI is going to be associated with.
- asMaster (bool) – Make new ROI masterROI.
-
restoreDefault
()¶ Restores default values.
Only default value of ball geometry is that
imagingHeight
is set to be equal tosliceHeightPx
ofembryo
.
-
setImagingHeight
(h)¶ Sets imaging height and updates ball geometry.
Parameters: h (float) – New height. Returns: New height. Return type: float
-
setImagingRadius
(r)¶ Sets imaging radius and updates ball geometry.
Parameters: h (float) – New radius. Returns: New radius. Return type: float
-
updateGeoFile
(debug=False)¶ Updates .geo file of geometry.
Keyword Arguments: debug (bool) – Print debugging messages.
-
class
pyfrp.subclasses.pyfrp_geometry.
xenopusBallQuad
(embryo, center, imagingRadius)¶ Bases:
pyfrp.subclasses.pyfrp_geometry.xenopusBall
Geometry describing a ball, reduced to first quadrant.
Inherits from
xenopusBall
. Please refer to its documentation for further details.Warning
meshfiles/quad_ball.geo
does not exist yet.
-
class
pyfrp.subclasses.pyfrp_geometry.
zebrafishDomeStage
(embryo, center, imagingRadius, radiusScale=1.1)¶ Bases:
pyfrp.subclasses.pyfrp_geometry.geometry
Geometry describing a zebrafish embryo in dome stage.
For information about zebrafish stages, see http://onlinelibrary.wiley.com/doi/10.1002/aja.1002030302/abstract;jsessionid=1EAD19FE5563DAA94E3C22C5D5BEEC85.f01t03.
The zebrafish geometry is basically described by two half-balls with different radii piled on top of each other. The crucial geometrical parameters are:
outerRadius
: Radius of the outer ball.innerRadius
: Radius of the inner ball.centerDist
: Distance between the centers of the two balls.
PyFRAP automatically computes these parameters given
imagingRadius
: Radius of embryo at imaging depth.imagingHeight
: Imaging depth.radiusScale
: Scaling factor between radii.
For details of this computations, see
computeDome()
.-
computeDome
()¶ Updates zebrafish geometry.
Computes zebrafish geometry as follows:
\[\begin{split}r_{\mathrm{outer}}=\frac{r_{\mathrm{imaging}}^2+h_{\mathrm{imaging}}^2}{-2 h_{\mathrm{imaging}}},\\ r_{\mathrm{inner}}=s_{\mathrm{radius}}r_{\mathrm{outer}},\\ d_{\mathrm{center}}=\sqrt{r_{\mathrm{inner}}^2-r_{\mathrm{outer}}^2},\end{split}\]where \(r_{\mathrm{outer}}\) is the
outerRadius
, \(r_{\mathrm{inner}}\) is theinnerRadius
, \(h_{\mathrm{imaging}}\) is theimagingHeight
and \(r_{\mathrm{imaging}}\) is theimagingRadius
.Returns: Tuple containing: - innerRadius (float): New inner radius.
- centerDist (float): New distance between centers.
Return type: tuple
-
genAsOpenscad
()¶ Generates zebrafish geometry as solid python object.
Useful if geometry is used to be passed to openscad.
Returns:
-
getImagingHeight
()¶ Returns imaging height.
-
getImagingRadius
()¶ Returns imaging radius.
-
getInnerRadius
()¶ Returns inner radius.
-
getOuterRadius
()¶ Returns outer radius.
-
getRadiusScale
()¶ Returns radius scaling factor.
-
getVolume
()¶ Returns volume of geometry.
Volume is computed by:
\[V_{dome}=\frac{\pi}{6}(4 r_{\mathrm{outer}}^3 - (d_{\mathrm{center}}-r_{\mathrm{inner}})(3r_{\mathrm{outer}}^2+(d_{\mathrm{center}}-r_{\mathrm{inner}})^2))\]Returns: Volume of zebrafish dome. Return type: float
-
getXYExtend
()¶ Overwrites
pyfrp.subclasses.pyfrp_geometry.geometry.getXYExtend()
.By default, zebrafish geometry is set to range from
center[i]-outerRadius
tocenter[i]+outerRadius
.Returns: Tuple containing: - xmin (float): Minimum x-coordinate.
- xmax (float): Maximum x-coordinate.
- ymin (float): Minimum y-coordinate.
- ymax (float): Maximum y-coordinate.
Return type: tuple
-
getZExtend
()¶ Overwrites
pyfrp.subclasses.pyfrp_geometry.geometry.getZExtend()
.By default, zebrafish geometry is set to range from
-outerRadius
to0
.
-
optimalAllROI
(name='', Id=0, color='b', asMaster=False)¶ Sets optimal ROI to a
pyfrp.subclasses.pyfrp_ROI.radialSliceROI
with radiusouterRadius
, centercenter
, covering the whole z-range of geometry.Keyword Arguments: - name (str) – Name of new ROI.
- Id (int) – ID of new ROI.
- color (str) – Color that ROI is going to be associated with.
- asMaster (bool) – Make new ROI masterROI.
-
restoreDefault
()¶ Restores default values.
Only default value of zebrafish geometry is that
imagingHeight
is set to be equal tosliceHeightPx
ofembryo
.
-
setImagingHeight
(h)¶ Sets imaging height and updates zebrafish geometry.
Parameters: h (float) – New height. Returns: New height. Return type: float
-
setImagingRadius
(r)¶ Sets imaging radius and updates zebrafish geometry.
Parameters: r (float) – New radius. Returns: New radius. Return type: float
-
setOuterRadius
(r)¶ Sets outer radius and updates zebrafish geometry.
Parameters: r (float) – New radius. Returns: New radius. Return type: float
-
setRadiusScale
(s)¶ Sets scaling factor between outer and inner radius and updates zebrafish geometry.
Parameters: s (float) – New scaling factor. Returns: New scaling factor. Return type: float
-
updateGeoFile
(debug=False)¶ Updates .geo file of geometry.
Keyword Arguments: debug (bool) – Print debugging messages.
-
class
pyfrp.subclasses.pyfrp_geometry.
zebrafishDomeStageQuad
(embryo, center, imagingRadius, radiusScale=1.1)¶ Bases:
pyfrp.subclasses.pyfrp_geometry.zebrafishDomeStage
Geometry describing a zebrafish embryo in dome stage, reduced to first quadrant.
Inherits from
zebrafishDomeStage
. Please refer to its documentation for further details.
pyfrp.subclasses.pyfrp_mesh module¶
Essential PyFRAP module containing mesh
class.
-
class
pyfrp.subclasses.pyfrp_mesh.
mesh
(simulation)¶ Bases:
object
Mesh class for PyFRAP.
The mesh class stores all information about location and creation of the mesh used for a simulation. It is directly associated with the
pyfrp.subclasses.pyfrp_simulation.simulation
object that uses it.Meshes can either be created via running Gmsh onto the .geo file of the
pyfrp.subclasses.pyfrp_geometry.geometry
, or by running Gmsh internally from FiPy using some predefined functions (limited geometry support). See alsogenMesh()
.The most important attributes are:
mesh
: The actual mesh as afipy.GmshImporter3D
object.fromFile
: Flag that controls if mesh should be created from .geo file or not.volSizePx
: Mesh element size in px.
Besides mesh storage and creation, the mesh class contains useful functions such as:
- Mesh refinement, see
refine()
,addBoxField()
andforceMinMeshDensityInROI()
. - Information output, see
printStats()
. - Plotting, see
plotMesh()
andplotDensity()
.
Parameters: simulation (pyfrp.subclasses.pyfrp_simulation.simulation) – Simulation object. -
addBoundaryLayerAroundROI
(roi, fnOut=None, segments=48, simplify=True, iterations=3, triangIterations=2, fixSurfaces=True, debug=False, volSizePx=None, volSizeLayer=10, thickness=15.0, cleanUp=True, approxBySpline=True, angleThresh=0.95, faces='all', onlyAbs=True)¶ Adds boundary layer around ROI to the mesh.
Does this by:
- Generating a stl file describing ROI, see also
pyfrp.subclasses.pyfrp_ROI.ROI.render2StlInGeometry()
. - Read in stl file as new
pyfrp.modules.pyfrp_gmsh_geometry.domain
viapyfrp.modules.pyfrp_gmsh_IO_module.readStlFile()
. - Simplify new geometry via
pyfrp.modules.pyfrp_gmsh_geometry.domain.simplifySurfaces()
. - Extracting selected surfaces via
pyfrp.modules.pyfrp_gmsh_geometry.gmshElement.extract()
. - If selected, surface boundaries are approximated into splines via
pyfrp.modules.pyfrp_gmsh_geometry.gmshElement.extract()
. - Reading in geometry’s .geo file via
pyfrp.sublcasses.pyfrp_geometry.geometry.readGeoFile()
. - Merging ROI geometry into main geometry via
pyfrp.modules.pyfrp_gmsh_geometry.domain.merge()
. - Adding a boundary layer mesh via
pyfrp.modules.pyfrp_gmsh_geometry.domain.addBoundaryLayerField()
. - Adding all surfaces of ROI’s domain to boundary layer, see
pyfrp.modules.pyfrp_gmsh_geometry.boundaryLayerField.addFaceListByID()
. - Writing new .geo file.
- Setting new .geo file as
fnGeo
. - Running
genMesh()
. - Clean up .stl and .scad files that are not needed anymore.
Note
volSizeLayer
only allows a single definition of mesh size in layer. Note that thepyfrp.modules.pyfrp_gmsh_geometry.boundaryLayerField
class allows different mesh sizes normal and along surfaces. For more information, see its documentation.Note
If no
fnOut
is given, will save a new .geo file in same folder as originalfnGeo
with subfix:fnGeo_roiName_BL.geo
.Note
pyfrp.modules.pyfrp_gmsh_geometry.domain.simplifySurfaces()
is not a simple procedure, we recommend reading its documentation.If
volSizePx
is given, will overwrite mesh’svolSizePx
and set it globally at all nodes.Parameters: roi (pyfrp.subclasses.pyfrp_ROI.ROI) – An ROI.
Keyword Arguments: - fnOut (str) – Path to new .geo file.
- segments (int) – Number of segments used for convex hull of surface.
- simplify (bool) – Simplify surfaces of stl file.
- 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.
- volSizePx (float) – Global mesh density.
- volSizeLayer (float) – Boundary layer mesh size.
- thickness (float) – Thickness of boundary layer.
- cleanUp (bool) – Clean up temporary files when finished.
- approxBySpline (bool) – Approximate curvatures by spline.
- angleThresh (float) – Threshold angle under which loops are summarized.
- faces (list) – List of faces.
- onlyAbs (bool) – Take absolute value of faces into account.
Returns: Path to new .geo file.
Return type: str
- Generating a stl file describing ROI, see also
-
addBoxField
(volSizeIn, rangeX, rangeY, rangeZ, newFile=True, fnAppendix='_box', comment='newField', run=False, fnOut=None)¶ Adds box field to mesh.
Box fields allow to refine certain areas of the mesh, see also http://gmsh.info/doc/texinfo/gmsh.html#Specifying-mesh-element-sizes .
Note
Will keep
volSizePx
as volSize outside of the box.Note
If
fnOut
is not specified, will do the following:- If
newFile=True
, will create new file with pathfnGeo+/field/custom/fnGeo+fnAppendix.geo
- Else writes into
fnGeo
.
Parameters: - volSizeIn (float) – volSize in px inside the 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]
. - newFile (bool) – Write new mesh into a new .geo file.
- fnAppendix (str) – Append this to new file name.
- comment (str) – Comment in .geo file before definition of box field.
- run (bool) – Run Gmsh on new .geo file afterwards.
- fnOut (str) – Path to output geo file.
Returns: Path to new .geo file.
Return type: str
- If
-
calcAllTetSidelenghts
()¶ Calculates sidelengths of all tetrahedra.
See also
pyfrp.modules.pyfrp_integration_module.calcTetSidelengths()
.Returns: List of all sidelengths. Return type: list
-
forceMinMeshDensityInROI
(ROI, density, stepPercentage=0.1, debug=False, findIdxs=True, method='refine', maxCells=100000)¶ Forces global mensh density such that a certain density is reached in a given ROI.
Tries to achive a mesh density
density
inROI
by globally refining mesh either through decreasingvolSizePx
bystepPercentage
percent (method=volSize
), or by using Gmsh’s-refine
option (method=refine
). If maximum number of cells is exceeded, will use the last mesh that did not exceedmaxCells
.Parameters: - ROI (pyfrp.subclasses.pyfrp_ROI.ROI) – ROI object.
- density (float) – Desired density.
Keyword Arguments: - stepPercentage (float) – If method is
volSize
, percentage ofvolSize
decrease. - method (str) – Refinement method (
refine
/volSize
). - maxCells (int) – Total maximum number of mesh cells allowed.
- findIdxs (bool) – Find ROI indices after refinement.
- debug (bool) – Print debugging messages.
Returns: New
volSizePx
Return type: float
-
genMesh
(fnOut=None, debug=False)¶ Main mesh generation function.
Note
If
fnOut=None
, will usegeometry.fnGeo
.Note
If
fromFile=True
, will generate from .geo file running gmsh directly on the file. If not, will try to run hard coded FiPy version for mesh generation viarunFiPyMeshGenerator()
.Keyword Arguments: - fnOut (str) – Output filepath for meshfile.
- debug (bool) – Print debugging messages.
Returns: Gmsh mesh object.
Return type: fipy.GmshImporter3D
-
getFnMesh
()¶ Returns the filepath of meshfile.
-
getMaxNodeDistance
()¶ Returns maximum node distance in x/y/z direction.
Returns: Tuple containing: - dmaxX (float): Maximum distance in x-direction
- dmaxY (float): Maximum distance in y-direction
- dmaxZ (float): Maximum distance in z-direction
Return type: tuple
-
getMesh
()¶ Returns mesh that is used for simulation.
Returns: Gmsh mesh object. Return type: fipy.GmshImporter3D
-
getNNodes
()¶ Returns number of nodes in mesh.
If no mesh has been generated yet, will return 0.
Returns: Number of nodes. Return type: int
-
getSimulation
()¶ Returns
pyfrp.subclasses.pyfrp_simulation
that mesh belongs to.Returns: Simulation object. Return type: pyfrp.subclasses.pyfrp_simulation
-
getVolSizePx
()¶ Returns mesh volSize in px.
Returns: VolSize. Return type: float
-
importMeshFromFile
(fn)¶ Imports mesh from a Gmsh .msh file.
See also http://www.ctcms.nist.gov/fipy/fipy/generated/fipy.meshes.html.
Parameters: fn (str) – Filepath to meshfile. Returns: Gmsh mesh object. Return type: fipy.GmshImporter3D
-
importVTKFile
(fnVTK='', sub=False)¶ Imports a .vtk file into a vtk renderer.
If
fnVTK
is not given, will generate .vtk file from meshfile stored infnMesh
usingwriteVTKFile()
.If
sub==True
, will start a seperate subprocess and submitpyfrp_meshIO_script.py
to it. This can be sometimes useful, since PyFRAP sometimes tends to crash otherwise.Note
This function imports vtk. vtk is only necessary in a few functions, hence only imported when needed. This should make PyFRAP more portable.
Keyword Arguments: - fnVTK (str) – Path to input vtk file.
- sub (bool) – Subprocess flag.
Returns: Renderer object.
Return type: vtk.vtkRenderer
-
plotCellCenters
(ax=None, proj=None, color='k', indicateHeight=False, s=5.0, roi=None)¶ Plots location of cell centers of mesh.
Note
If no
ax
are given will create new ones.If
proj=[3d]
, will create 3D scatter plot, otherwise project cell centers in 2D.Example:
Create figure
>>> fig,axes = pyfrp_plot_module.makeSubplot([2,2],titles=['2D','2D indicate','3D','3D indicate'],proj=[None,None,'3d','3d'])
Plot in 4 different ways
>>> mesh.plotCellCenters(ax=axes[0],s=1.) >>> mesh.plotCellCenters(ax=axes[1],indicateHeight=True,s=5.) >>> mesh.plotCellCenters(ax=axes[2],s=3.) >>> mesh.plotCellCenters(ax=axes[3],indicateHeight=True,s=3.)
Keyword Arguments: - ax (matplotlib.axes) – Axes to plot in.
- proj (list) – List of projections.
- color (str) – Color of mesh nodes.
- indicateHeight (bool) – Indicate height by color.
- s (float) – Size of marker.
- roi (pyfrp.subclasses.pyfrp_ROI) – ROI.
Returns: Matplotlib axes.
Return type: matplotlib.axes
-
plotDensity
(axes=None, hist=True, bins=100, color='b')¶ Plots the mesh density in x/y/z-direction.
hist=True
is recommended, since otherwise plots generally appear fairly noisy.Note
If no
axes
are given or they do not have the necessary size, will create new ones.Keyword Arguments: - axes (list) – List of
matplotlib.axes
. - hist (bool) – Summarize densities in bins.
- bins (int) – Number of bins used for hist.
- color (str) – Color of plot.
Returns: List of
matplotlib.axes
.Return type: list
- axes (list) – List of
-
plotMesh
(fnVTK='')¶ Plots the mesh using VTK.
If
fnVTK
is not given, will generate .vtk file from meshfile stored infnMesh
usingwriteVTKFile()
.Note
This function imports vtk. vtk is only necessary in a few functions, hence only imported when needed. This should make PyFRAP more portable.
Keyword Arguments: fnVTK (str) – Path to input vtk file. Returns: RenderWindow object. Return type: vtk.vtkRenderWindow
-
printAllAttr
()¶ Prints out all attributes of mesh object.
-
printStats
(tetLenghts=False)¶ Prints out statistics of mesh.
Also calculates all tetraheder lengths if
tetLenghts
is selected. This might take some time depending on mesh size.Keyword Arguments: tetLenghts (bool) – Also calculate and print out tetrahedra sidelengths.
-
refine
(debug=False)¶ Refines mesh by splitting.
See also http://gmsh.info/doc/texinfo/gmsh.html .
Keyword Arguments: debug (bool) – Print debugging messages.
-
restoreDefaults
()¶ Restores default parameters of mesh.
Default parameters are:
mesh.geometry=mesh.simulation.embryo.geometry
mesh.fromFile=True
mesh.volSizePx=20
mesh.fnMesh=""
-
runFiPyMeshGenerator
(typ)¶ Runs gmsh on the via FiPy internally defined meshes.
Available meshes:
- cylinder
- zebrafishDomeStage
- xenopusBall
Note
Any refinement method will not work if mesh is created this way.
Parameters: typ (str) – Type of mesh to be created (see list above). Returns: Gmsh mesh object. Return type: fipy.GmshImporter3D
-
saveMeshToImg
(fnOut, fnVTK='', renderer=None, magnification=10, show=True)¶ Saves mesh to image file.
Supported extensions are:
- ‘.ps’ (PostScript)
- ‘.eps’ (Encapsualted PostScript)
- ‘.pdf’ (Portable Document Format)
- ‘.jpg’ (Joint Photographic Experts Group)
- ‘.png’ (Portable Network Graphics)
- ‘.pnm’ (Portable Any Map)
- ‘.tif’ (Tagged Image File Format)
- ‘.bmp’ (Bitmap Image)
If
fnVTK
is not given, will generate .vtk file from meshfile stored infnMesh
usingwriteVTKFile()
.If no
renderer
is given, will create one usingplotMesh()
.Note
This function imports vtk. vtk is only necessary in a few functions, hence only imported when needed. This should make PyFRAP more portable.
Some code taken from http://www.programcreek.com/python/example/23102/vtk.vtkGL2PSExporter .
Parameters: fnOut (str) – Path to output file.
Keyword Arguments: - fnVTK (str) – Path to input vtk file.
- renderer (vtk.vtkOpenGLRenderer) – Renderer.
- magnification (int) – Degree of magnification.
- show (bool) – Show vtk render window.
Returns: Exporter object.
Return type: vtk.vtkExporter
-
saveMeshToPS
(fnOut, fnVTK='', renderer=None)¶ Saves mesh to postscript file.
Supported extensions are:
- ‘.ps’ (PostScript)
- ‘.eps’ (Encapsualted PostScript)
- ‘.pdf’ (Portable Document Format)
- ‘.tex’ (LaTeX)
- ‘.svg’ (Scalable Vector Graphics)
If
fnVTK
is not given, will generate .vtk file from meshfile stored infnMesh
usingwriteVTKFile()
.If no
renderer
is given, will create one usingplotMesh()
.Note
This function imports vtk. vtk is only necessary in a few functions, hence only imported when needed. This should make PyFRAP more portable.
Some code taken from http://www.programcreek.com/python/example/23102/vtk.vtkGL2PSExporter .
Parameters: fnOut (str) – Path to output file.
Keyword Arguments: - fnVTK (str) – Path to input vtk file.
- renderer (vtk.vtkOpenGLRenderer) – Renderer.
- magnification (int) – Degree of magnification.
Returns: Exporter object.
Return type: vtk.vtkGL2PSExporter
-
setFnMesh
(fn)¶ Sets the filepath of meshfile.
Imports the new mesh right away using
importMeshFromFile()
.
-
setFromFile
(v)¶ Sets flag if mesh is supposed to be created from file (recommended) or from internally defined mesh creation method.
Parameters: v (bool) – New flag value. Returns: New flag value. Return type: bool
-
setMesh
(m)¶ Sets
mesh
attribute to a new mesh.Parameters: m (fipy.GmshImporter3D) – New mesh. Returns: Gmsh mesh object. Return type: fipy.GmshImporter3D
-
setVolSizePx
(v, remesh=True, fnOut=None)¶ Sets volSize of mesh in px.
Note
If
fnOut=None
, then eitherfnMesh
will be used, or, iffnMesh
is not set yet, will usegeometry.fnGeo
.Parameters: v (float) – New volSize.
Keyword Arguments: - remesh (bool) – Generate mesh with new volSize.
- fnOut (str) – Output filepath for meshfile.
Returns: New volSize.
Return type: float
-
updateGeoFile
(debug=False)¶ Updates geometry file by writing new
volSizePx
intoembryo.geometry.fnGeo
.Keyword Arguments: debug (bool) – Print debugging messages. Returns: Path to ouput meshfile. Return type: str
-
writeVTKFile
(fn='', sub=False)¶ Writes mesh into vtk file.
Uses meshIO (https://github.com/nschloe/meshio), to convert the mesh saved in
fnMesh
to a .vtk file.If
sub==True
, will start a seperate subprocess and submitpyfrp_meshIO_script.py
to it. This can be sometimes useful, since PyFRAP sometimes tends to crash otherwise.If no output path is given via
fn
, will use same path asfnMesh
.Note
meshIO only gets imported inside this function, making PyFRAP running even without the package installed. However, this feature will only run with meshIO.
Keyword Arguments: - fn (str) – Optional output path.
- sub (bool) – Subprocess flag.
Returns: Used output path.
Return type: str
pyfrp.subclasses.pyfrp_molecule module¶
-
class
pyfrp.subclasses.pyfrp_molecule.
molecule
(name)¶ Molecule class, collecting information about a series of FRAP experiments.
The main purpose of the molecule class is to gather and summarize multiple FRAP experiments. Embryo objects are stored in a
embryos
list. From those embryo objects, fit objects can be added to theselFits
list to then be summarized to calculate measurement statistics. Fits can be forced to overlap in a set of parameters defined incrucialParameters
.-
addEmbryo
(embryo)¶ Appends embryo object to
embryos
list.Parameters: embryo (pyfrp.subclasses.pyfrp_embryo) – Embryo to append. Returns: Updated pyfrp.subclasses.pyfrp_molecule.embryos list Return type: list
-
checkEmbryoNames
()¶ Check if all embryos in
embryos
list have different names.Returns: True if all different, False else. Return type: bool
-
clearAllEmbryos
()¶ Replaces all attribute values of each embryo in embryos list with
None
, exceptname
.Useful if embryos are seperated and molecule file needs to be compressed.
Note
Embryos should have all different names, so there will not be any missassignment when reimporting embryo files.
Returns: True if success, False else. Return type: bool
-
extractEmbryos2Files
(fn='', copyMeshFiles=True, debug=False)¶ Extracts embryos in
embryos
list into seperate pickled files.Note
Will create folder
fn
if non-existent. Iffn
is not specified, will assumefn='embryoFiles/'
.Keyword Arguments: - fn (str) – Path of folder where to save embryo files.
- copyMeshFiles (bool) – Copy meshfiles to embryo file destination.
- debug (bool) – Print out debugging messages.
Returns: True if success, False else.
Return type: bool
-
getEmbryoByName
(s)¶ Returns embryo with name
s
fromembryos
list, otherwiseFalse
.
-
getName
()¶
-
newEmbryo
(name)¶ Creates new embryo and appends it to
embryos
list.Parameters: name (str) – Name of new embryo. Returns: New embryo object. Return type: pyfrp.subclasses.pyfrp_embryo
-
printResults
()¶ Prints results summarized in
pyfrp.subclasses.pyfrp_molecule.sumUpResults()
.
-
removeEmbryo
(embryo)¶ Removes embryo object from
embryos
list.Parameters: embryo (pyfrp.subclasses.pyfrp_embryo) – Embryo object. Returns: Updated pyfrp.subclasses.pyfrp_molecule.embryos list Return type: list
-
replaceEmbryo
(embryo, name='')¶ Replaces embryo with same name that
embryo
in molecule’sembryos
list.If no embryo with the same name exists, will simply add embryo. If
name
is given, will try to replace embryo with namename
inembryos
list.Parameters: embryo (pyfrp.subclasses.pyfrp_embryo) – New embryo to be inserted. Keyword Arguments: name (str) – Optional name of embryo embryo to be replaced. Returns: True if anything was replaced, False if anything was appended. Return type: bool
-
save
(fn=None)¶ Saves molecule to pickle file.
Note
If
fn
is not specified, will assumefn=self.name
.Keyword Arguments: fn (str) – Molecule file name. Returns: Filename of molecule file. Return type: str
-
saveExtract
(fn=None, copyMeshFiles=True, debug=False)¶ Saves molecule to pickle file in compressed version by doing:
- Extracts embryos in
embryos
list into seperate pickled files. - Clears all attributes of embryo objects
- Saves molecule file
This function is really useful if molecule file size gets out-of-hand.
Note
Embryo files will be saved in path/to/moculefile/moleculename/ .
Note
If
fn
is not specified, will assumefn=self.name
.Keyword Arguments: - fn (str) – Molecule file name.
- copyMeshFiles (bool) – Copy meshfiles to embryo file destination.
- debug (bool) – Print out debugging messages.
Returns: True if success, False else.
Return type: bool
- Extracts embryos in
-
setName
(n)¶
-
sumUpResults
(sameSettings=False)¶ Sums up results from all fits in
selFits
list.Keyword Arguments: sameSettings (bool) – Fits must overlap in parameters defined in crucialParameters
.Returns: True if success, False else. Return type: bool
-
updateVersion
()¶ Updates molecule file to current version, making sure that it possesses all attributes.
Creates a new molecule object and compares
self
with the new molecule file. If the new molecule object has a attribute thatself
does not have, will add attribute with default value from the new molecle file.Note
Will also update all subobject, making sure that embryo and fit objects are up-to-date.
Returns: self
Return type: pyfrp.subclasses.pyfrp_molecule
-
pyfrp.subclasses.pyfrp_simulation module¶
-
class
pyfrp.subclasses.pyfrp_simulation.
simulation
(embryo)¶ Bases:
object
PyFRAP simulation class.
Stores all important properties about how FRAP simulation is performed, such as:
-
compareICInterpolation
(axes=None, roi=None)¶ Shows initial image, its interpolation, the resulting initial condition and its interpolation back onto an image.
See also
showICimg()
,showInterpolatedICImg()
,showIC()
,showInterpolatedIC()
.Will create new axes if necessary.
Warning
Some images might be flipped due to plotting functions. Will be fixed in future version.
Keyword Arguments: - roi (pyfrp.subclasses.pyfrp_ROI.ROI) – A PyFRAP ROI.
- axes (matplotlib.axes) – List of axes of length 4.
Returns: List of axes.
Return type: list
-
computeInterpolatedICImg
(roi=None)¶ Interpolates ICs back onto 2D image.
Uses
scipy.interpolate.griddata
, see also http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.griddata.htmlIf
roi
is specified, will only interpolate nodes of this ROI.Keyword Arguments: roi (pyfrp.subclasses.pyfrp_ROI.ROI) – A PyFRAP ROI. Returns: Tuple containing: - X (numpy.ndarray): Meshgrid x-coordinates.
- Y (numpy.ndarray): Meshgrid y-coordinates.
- interpIC (numpy.ndarray): Interpolated ICs.
Return type: tuple
-
computeInterpolatedSolutionToImg
(vals, roi=None, method='linear')¶ Interpolates solution back onto 2D image.
Uses
scipy.interpolate.griddata
, see also http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.griddata.htmlIf
roi
is specified, will only interpolate nodes of this ROI.For more details about interpolation methods, check out https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.griddata.html .
Keyword Arguments: - vals (numpy.ndarray) – Solution to be interpolated.
- roi (pyfrp.subclasses.pyfrp_ROI.ROI) – A PyFRAP ROI.
- method (str) – Interpolation method.
- fillVal (float) – Value applied outside of ROI.
Returns: Tuple containing:
- X (numpy.ndarray): Meshgrid x-coordinates.
- Y (numpy.ndarray): Meshgrid y-coordinates.
- interpIC (numpy.ndarray): Interpolated solution.
Return type: tuple
-
getD
()¶ Returns current diffusion coefficient used for simulation.
Returns: Current diffusion coefficient in \(\mathrm{px}^2/s\). Return type: float
-
getDegr
()¶ Returns degradation rate used for simulation.
Returns: Current degradation rate in \(1/[c]s\). Return type: float
-
getICImgSmoothness
()¶ Returns smoothness of initial condition.
See also
pyfrp.modules.pyfrp_img_module.getICImgSmoothness()
.Returns: Tuple containing: - s (float): Smoothmess coefficient.
- dmax(float): Maximum diff.
Return type: tuple
-
getICSmoothness
(roi=None)¶ Returns smoothness of initial condition.
See also
getSolutionVariableSmoothness()
.Note
If
roi!=None
, will only evaluate smoothness over this specific ROI.Keyword Arguments: roi (pyfrp.subclasses.pyfrp_ROI.ROI) – PyFRAP ROI. Returns: Tuple containing: - s (float): Smoothmess coefficient.
- dmax(float): Maximum diff.
Return type: tuple
-
getICimg
()¶ Returns image for initial condition interpolation.
Returns: Current ICimg. Return type: numpy.ndarray
-
getIterations
()¶ Returns current iterations.
Returns: Current solver Return type: str
-
getOptTvecSim
(maxDExpectedPx)¶ Generates time vector that is optimal to fit experiments with expected diffusion coefficients up to
maxDExpectedPx
.Basically computes how long a simulation needs to run in seconds to capture the dynamics of an experiment with diffusion coefficient of
maxDExpectedPx
. Does this by setting end time point to\[t_{\mathrm{end,sim}} = \frac{D_{\mathrm{max. exp.}}}{D_{\mathrm{sim}}} t_{\mathrm{end,data}}\]Note
Keeps time scaling.
Parameters: maxDExpectedPx (float) – Maximum expected diffusion coefficient. Returns: New simulation time vector. Return type: numpy.ndarray
-
getProd
()¶ Returns production rate used for simulation.
Returns: Current production rate in \(1/s\). Return type: float
-
getSaveSim
()¶ Returns flag if simulation should be saved.
Returns: Current flag value. Return type: bool
-
getSolutionVariableSmoothness
(vals, roi=None)¶ Returns smoothness of solution variable.
Smoothness \(s\) is computed as:
\[s=\frac{d_{\mathrm{max}}}{\bar{d}}\]where \(d_{\mathrm{max}}\) is the maximum derivative from the nearest neighbour over the whole array, and \(\bar{d}\) the average derivation. Derivative from nearest neighbour is computed by
\[d=\frac{c-c_\mathrm{nearest}}{||\textbf{x}-\textbf{x}_\mathrm{nearest}||_2}\]Note
If
roi!=None
, will only evaluate smoothness over this specific ROI.Warning
Nearest neighbour finding algorithm is slow. Should be changed to
ckdTree
at some point.Keyword Arguments: roi (pyfrp.subclasses.pyfrp_ROI.ROI) – PyFRAP ROI. Returns: Tuple containing: - s (float): Smoothmess coefficient.
- dmax(float): Maximum diff.
Return type: tuple
-
getSolver
()¶ Returns current solver.
Returns: Current solver Return type: str
-
getTolerance
()¶ Returns current tolerance.
Returns: Current solver Return type: str
-
isLogTimeScale
()¶ Returns if time spacing of simulation is logarithmic.
Returns: Time spacing is logarithmic. Return type: bool
-
mapOntoImgs
(tvec=None, roi=None, fnOut='', showProgress=True, method='linear', fillVal=0.0, scale=True, enc='uint16')¶ Maps simulation solution back onto images.
See also
computeInterpolatedSolutionToImg()
.Note
Only works if simulation has been run before and saved via
saveSim
.For more details about interpolation methods, check out https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.griddata.html .
Keyword Arguments: - tvec (numpy.ndarray) – Timepoints at which solution is saved to image.
- roi (pyfrp.subclasses.pyfrp_ROI.ROI) – PyFRAP ROI.
- fnOut (str) – Path where images should be saved.
- showProgress (bool) – Show progress of output.
- method (str) – Interpolation method.
- fillVal (float) – Value applied outside of ROI.
Returns: True if everything ran through, False else.
Return type: bool
-
plotICStack
(ROIs, withGeometry=True, vmin=None, vmax=None, ax=None, colorbar=False)¶ Plots a stack of the initial conditions in a given list of ROIs.
Will automatically compute the direction in which ROI lies in the 3D space and reduce the ROI into this plane for contour plot.
If
vmin=None
orvmax=None
, will compute overall maximum and minimum values over all ROIs.Parameters: - phi (fipy.CellVariable) – Simulation solution variable (or numpy array).
- ROIs (list) – List of
pyfrp.subclasses.pyfrp_ROI.ROI
objects.
Keyword Arguments: - withGeometry (bool) – Show geometry inside plot.
- vmin (float) – Overall minimum value to be displayed in plot.
- vmax (float) – Overall maximum value to be displayed in plot.
- ax (matplotlib.axes) – Axes used for plotting.
- colorbar (bool) – Display color bar.
Returns: Axes used for plotting.
Return type: matplotlib.axes
-
plotSolStack
(phi, ROIs, withGeometry=True, vmin=None, vmax=None, ax=None, colorbar=False)¶ Plots a stack of the solution variable in a given list of ROIs.
Will automatically compute the direction in which ROI lies in the 3D space and reduce the ROI into this plane for contour plot.
If
vmin=None
orvmax=None
, will compute overall maximum and minimum values over all ROIs.Parameters: - phi (fipy.CellVariable) – Simulation solution variable (or numpy array).
- ROIs (list) – List of
pyfrp.subclasses.pyfrp_ROI.ROI
objects.
Keyword Arguments: - withGeometry (bool) – Show geometry inside plot.
- vmin (float) – Overall minimum value to be displayed in plot.
- vmax (float) – Overall maximum value to be displayed in plot.
- ax (matplotlib.axes) – Axes used for plotting.
- colorbar (bool) – Display color bar.
Returns: Axes used for plotting.
Return type: matplotlib.axes
-
printAllAttr
()¶ Prints out all attributes of embryo object.
-
rerun
(signal=None, embCount=None, showProgress=True, debug=False)¶ Reruns simulation.
Note
Only works if simulation has been run before with
saveSim
enabled.See also
pyfrp.modules.pyfrp_sim_module.rerunReactDiff()
.Keyword Arguments: - signal (PyQt4.QtCore.pyqtSignal) – PyQT signal to send progress to GUI.
- embCount (int) – Counter of counter process if multiple datasets are simulated.
- debug (bool) – Print debugging messages and show debugging plots.
- showProgress (bool) – Print out progress.
Returns: Updated simulation instance.
Return type:
-
restoreDefaults
()¶ Restores default parameters for simulations.
-
run
(signal=None, embCount=None, showProgress=True, debug=False)¶ Runs simulation.
Checks if ROI indices are computed, if not, computes them. Then passes simulation object to
pyfrp.modules.pyfrp_sim_module.simulateReactDiff()
.Keyword Arguments: - signal (PyQt4.QtCore.pyqtSignal) – PyQT signal to send progress to GUI.
- embCount (int) – Counter of counter process if multiple datasets are simulated.
- debug (bool) – Print debugging messages and show debugging plots.
- showProgress (bool) – Print out progress.
Returns: True if success, False otherwise.
Return type: bool
-
setBleachedROI
(r)¶ Sets bleached ROI that is used when ideal ICs (ICmode=4) is selected.
Parameters: r (pyfrp.subclasses.pyfrp_ROI.ROI) – ROI to be set bleached ROI.
-
setD
(D)¶ Sets diffusion coefficient used for simulation.
Parameters: D (float) – New diffusion coefficient in \(\mu\mathrm{m}^2/s\). Returns: New diffusion coefficient in \(\mathrm{px}^2/s\). Return type: float
-
setDegr
(degr)¶ Sets degradation rate used for simulation.
Parameters: prod (float) – New degradation rate in \(1/[c]s\). Returns: New degradation rate in \(1/[c]s\). Return type: float
-
setICMode
(m)¶ Sets the mode of initial conditions.
Initial condition modes are defined as:
- 0: ROI-based: 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.modules.pyfrp_sim_module.applyROIBasedICs()
. - 1: Radial: Concentrations get radially approximated around some center.
See also
pyfrp.modules.pyfrp_sim_module.applyRadialICs()
. - 2: Imperfect: Interpolates
ICimg
onto mesh, fills nodes that are not covered by image withembryo.analysis.concRim
and then mimics imperfect bleaching via sigmoid function in z-direction. See alsopyfrp.modules.pyfrp_sim_module.applyImperfectICs()
. - 3: Inpterpolated: Interpolates
ICimg
onto mesh, fills nodes that are not covered by image withembryo.analysis.concRim
. See alsopyfrp.modules.pyfrp_sim_module.applyInterpolatedICs()
. - 4: Ideal: Ideal ICs, that is, single value inside and single value outside of bleached region.
See also
pyfrp.modules.pyfrp_sim_module.applyIdealICs()
,setValOut()
andsetBleachedROI()
.
Note
The default mode is Interpolated (
m=3
) and is highly recommended to obtain most realistic results.Parameters: m (int) – Which mode to be used. Returns: Current initial condition mode used. Return type: int - 0: ROI-based: Mesh nodes get assigned the value of the first entry
-
setICimg
(img)¶ Sets image for initial condition interpolation.
Parameters: img (numpy.ndarray) – A 2D image. Returns: New ICimg. Return type: numpy.ndarray
-
setICimgByFn
(fn)¶ Sets image for initial condition interpolation given a filepath.
Parameters: fn (str) – Path to file. Returns: New ICimg. Return type: numpy.ndarray
-
setIterations
(tol)¶ Sets iterations of solver.
Parameters: tol (float) – New iterations. Returns: Current iterations. Return type: float
-
setMesh
(m)¶ Sets mesh to a new mesh object.
Parameters: m (pyfrp.subclasses.pyfrp_mesh.mesh) – PyFRAP mesh object. Returns: Updated mesh instance. Return type: pyfrp.subclasses.pyfrp_mesh.mesh
-
setProd
(prod)¶ Sets production rate used for simulation.
Parameters: prod (float) – New production rate in \(1/s\). Returns: New production rate in \(1/s\). Return type: float
-
setSaveSim
(b)¶ Sets flag if simulation should be saved.
Parameters: b (bool) – New flag value. Returns: Updated flag value. Return type: bool
-
setSolver
(solver)¶ Sets solver to use.
Implemented solvers are:
- PCG
- LU
Parameters: solver (str) – Solver to use. Returns: Current solver Return type: str
-
setTEnd
(T)¶ Updates timevector of simulation to end at new time point.
Note
Keeps scaling.
Parameters: T (float) – New end timepoint. Returns: New simulation time vector. Return type: numpy.ndarray
-
setTimesteps
(n)¶ Sets number of simulation time steps and updates time vector.
Parameters: n (int) – New number of time steps. Returns: New number of time steps. Return type: int
-
setTolerance
(tol)¶ Sets tolerance of solver.
Parameters: tol (float) – New tolerance. Returns: Current tolerance. Return type: float
-
setValOut
(v)¶ Sets valOut that is used when ideal ICs (ICmode=4) is selected.
Parameters: v (float) – Value that is to assigned outside of bleachedROI.
-
showIC
(ax=None, roi=None, nlevels=25, vmin=None, vmax=None, typ='contour')¶ Plots initial conditions applied to mesh in 2D or 3D.
If
roi
is given, will only plot initial conditions for nodes inside ROI, else will plot initial condition for all nodes in mesh.Note
Simulation needs to be run first before this plotting function can be used.
Example:
>>> simulation.plotIC(typ='contour')
will produce the following:
See also
pyfrp.modules.pyfrp_plot_module.plotSolutionVariable()
andpyfrp.subclasses.pyfrp_ROI.plotSolutionVariable()
.Keyword Arguments: - roi (pyfrp.subclasses.pyfrp_ROI.ROI) – A PyFRAP ROI object.
- vmin (float) – Overall minimum value to be displayed in plot.
- vmax (float) – Overall maximum value to be displayed in plot.
- ax (matplotlib.axes) – Axes used for plotting.
- nlevels (int) – Number of contour levels to display.
- typ (str) – Typ of plot.
Returns: Axes used for plotting.
Return type: matplotlib.axes
-
showICimg
(ax=None, typ='contour', colorbar=True)¶ Plots image used for initial 2D.
Keyword Arguments: ax (matplotlib.axes) – Axes used for plotting. Returns: Axes used for plotting. Return type: matplotlib.axes
-
showInterpolatedIC
(ax=None, roi=None)¶ Shows ICs interpolated back onto 2D image.
If
roi
is specified, will only interpolate nodes of this ROI.See also
computeInterpolatedIC()
.Keyword Arguments: - roi (pyfrp.subclasses.pyfrp_ROI.ROI) – A PyFRAP ROI.
- ax (matplotlib.axes) – Axes to be used for plotting.
Returns: Axes used for plotting.
Return type: matplotlib.axes
-
showInterpolatedICImg
(ax=None)¶ Shows interpolation of initial condition image.
See also
computeInterpolatedICImg()
.Keyword Arguments: ax (matplotlib.axes) – Axes to be used for plotting. Returns: Axes used for plotting. Return type: matplotlib.axes
-
toDefaultTvec
()¶ Sets time vector for simulation to default range.
Default range is given by
tStart
andtEnd
inembryo
object and is linearly scaled.Returns: New simulation time vector. Return type: numpy.ndarray
-
toLinearTimeScale
()¶ Converts time vector for simulation to linear scale.
Returns: New simulation time vector. Return type: numpy.ndarray
-
toLogTimeScale
(spacer=1e-10)¶ Converts time vector for simulation to logarithmic scale.
Keyword Arguments: spacer (float) – Small offset to avoid log(0). Returns: New simulation time vector. Return type: numpy.ndarray
-
updateTvec
()¶ Updates time vector for simulation to match experiment start and end time.
Does not change scaling of time vector.
Returns: New simulation time vector. Return type: numpy.ndarray
-
updateVersion
()¶ Updates simulation object to current version, making sure that it possesses all attributes.
Creates a new simulation object and compares
self
with the new simulation object. If the new simulation object has a attribute thatself
does not have, will add attribute with default value from the new simulation object.Returns: self
Return type: pyfrp.subclasses.pyfrp_simulation.simulation
-
Module contents¶
PyFRAP: A Python based FRAP analysis tool box. Subclass module.