MGSurvE package
Submodules
MGSurvE.auxiliary module
Various functions that are serve I/O purposes or not relevant to any specific module.
- MGSurvE.auxiliary.dumpLandscape(landscape, fPath, fName, fExt='bz2')
Exports a serialized landscape to disk.
- Parameters
landscape (object) – Landscape object to export.
fPath (path) – Path to where the landscape will be exported.
fName (string) – Filename.
fExt (string) – File extension.
- MGSurvE.auxiliary.exportLandscape(landscape, fPath, fName)
Exports a landscape to disk to CSV files (for use in MGDrivE).
- Parameters
landscape (object) – Landscape object to export.
fPath (path) – Path to where the landscape will be exported.
fName (string) – Filename.
- MGSurvE.auxiliary.isNotebook()
Checks if the script is running from a Jupyter environment.
- Returns
Flags Jupyter environment.
- Return type
bool
- MGSurvE.auxiliary.loadLandscape(fPath, fName, fExt='bz2')
Loads a serialized landscape from disk.
- Parameters
fPath (path) – Path from where the landscape will be loaded.
fName (string) – Filename.
fExt (string) – File extension.
- Returns
Landscape object.
- Return type
(object)
- MGSurvE.auxiliary.makeFolder(path)
Crates a folder in the specified directory.
- Parameters
path (string) – Path of the folder than needs to be created.
- MGSurvE.auxiliary.makeFolders(pathsList)
Creates a list of folders if they don’t exist.
- Parameters
paths (list) – List path to the desired directories.
- MGSurvE.auxiliary.vincentyDistance(pointA, pointB, meters=False)
Calculates the Vincenty arc distance between points.
- Parameters
pointA (tuple) – First point in (lon, lat) format.
pointB (tuple) – Second point in (lon, lat) format.
- Returns
Distance between points
- Return type
(float)
MGSurvE.colors module
Color-related functions for alphas and cmaps.
- MGSurvE.colors.colorPaletteFromHexList(clist)
Generates a matplotlib-compliant cmap from a list of hex colors.
- Parameters
clist (list) – List of hex codes (eg. ‘#f72585’) to blend in the map.
- Returns
Matplotlib’s colormap object.
- Return type
cmap
MGSurvE.constants module
Constants used across the pkg (colors, symbols, bio).
- MGSurvE.constants.AEDES_EXP_PARAMS = [0.01848777, 1e-10, inf]
Aedes aegypti’s migration parameters for kernel.
- MGSurvE.constants.BASIC_EXP_TRAP = {'A': 0.5, 'b': 0.15}
Generic params for an exponential-decay trap
- MGSurvE.constants.LAND_TUPLES = (('10m', '#dfe7fd55', 30), ('10m', '#ffffffDD', 5))
Base colors for land boundaries.
- MGSurvE.constants.MCOL = ('#bdb2ff', '#a0c4ff', '#e0c3fc', '#ffd6a5', '#caffbf', '#d0d1ff')
A cute pastel colors list.
- MGSurvE.constants.MKRS = ('o', '^', 's', 'p', 'd', 'X')
Markers for point-types
- MGSurvE.constants.PINK_NAVY = <matplotlib.colors.LinearSegmentedColormap object>
Pink to Navy Blue cmap.
- MGSurvE.constants.SHORT_EXP_PARAMS = [1, 1e-10, inf]
Dummy migration parameters for short-distance kernel.
- MGSurvE.constants.TRP_COLS = {0: '#f7258515', 1: '#5ddeb125', 2: '#fe5f5515', 3: '#f038ff15', 4: '#e2ef7015', 5: '#9381ff15'}
Base colors for trap types.
MGSurvE.kernels module
Kernel functions and operations used for movement and traps attractivenesses.
- MGSurvE.kernels.exponentialAttractiveness(dist, A=1, k=1, s=1, gamma=1, epsilon=1)
Calculates the probability of moving between points as a complex decaying exponential.
- Parameters
dist (float) – Distance between points.
A (float) – Maximum amplitude at distance 0 (attractiveness).
k (float) –
s (float) –
gamma (float) –
epsilon (float) – Error term
- Returns
Movement probability.
- Return type
float
- MGSurvE.kernels.exponentialDecay(dist, A=1, b=1)
Calculates the probability of moving between points as a decaying exponential.
- Parameters
dist (float) – Distance between points.
A (float) – Maximum amplitude at distance 0.
b (float) – Decay rate (higher means tighter kernel).
- Returns
Movement probability.
- Return type
float
- MGSurvE.kernels.inverseLinearStep(distance, params=[0.75, 1])
Calculates the zero-inflated linear distance-based movement probability.
- Parameters
distMat (numpy array) – Distances matrix.
- Returns
Migration matrix.
- Return type
numpy array
- MGSurvE.kernels.nSolveKernel(kernelDict, yVal, guess=0, latlon=False, R=6371)
Calculates the distance it takes for the kernel to match a given probability (yVar).
- Parameters
kernelDict (dict) – Dictionary with the kernel info {‘kernel’, ‘params’}.
yVal (float) – Probability for which we are solving the distance.
guess (float) – Initial guess for the distance.
- Returns
Distance for the probability value.
- Return type
float
- MGSurvE.kernels.sigmoidDecay(dist, A=1, rate=0.5, x0=10)
Calculates the probability of moving between points as a sigmod.
- Parameters
dist (float) – Distance between points.
A (float) – Maximum amplitude at distance 0.
rate (float) – Logistic growth rate or steepness of the curve.
x0 (float) – The x value of the sigmoid’s midpoint
- Returns
Movement probability.
- Return type
float
- MGSurvE.kernels.truncatedExponential(distance, params=[0.01848777, 1e-10, inf])
Calculates the zero-inflated exponential distance-based movement probability.
- Parameters
distance (float) – Distances matrix.
params (list) – Shape distribution parameters [rate, a, b].
- Returns
Migration probability.
- Return type
float
- MGSurvE.kernels.zeroInflatedExponentialKernel(distMat, params=[0.01848777, 1e-10, inf], zeroInflation=0.75)
Calculates the migration matrix using a zero-inflated exponential function.
- Parameters
distMat (numpy array) – Distances matrix.
params (list) – Shape distribution parameters [rate, a, b].
zeroInflation (float) – Probability to stay in the same place.
- Returns
Migration matrix.
- Return type
numpy array
- MGSurvE.kernels.zeroInflatedLinearMigrationKernel(distMat, params=[0.75, 1])
Calculates the zero-inflated linear distance-based movement probability.
- Parameters
distMat (numpy array) – Distances matrix.
- Returns
Migration matrix.
- Return type
numpy array
MGSurvE.landscape module
Main object with sites, traps, and masks to optimize and visualize the landscape to be analyzed.
- class MGSurvE.landscape.Landscape(points, maskingMatrix=None, attractionVector=None, distanceMatrix=None, distanceFunction=None, migrationMatrix=None, kernelFunction=<function zeroInflatedExponentialKernel>, kernelParams={'params': [1, 1e-10, inf], 'zeroInflation': 0.75}, maskedMigrationMatrix=None, traps=None, trapsKernels={0: {'inverse': None, 'kernel': <function exponentialDecay>, 'params': {'A': 0.5, 'b': 0.15}}}, trapsMask=None, trapsRadii=[0.25, 0.2, 0.1, 0.05], landLimits=None, populations=None)
Bases:
object
Stores the information for a mosquito landscape. Works with different point-types in the form of matrices and coordinates.
- Parameters
points (pandas dataframe) – Sites positions with mandatory {x,y} coordinates and optional {t: type, a: attractiveness} values for each site in the landscape.
kernelFunction (function) – Function that determines de relationship between distances and migration probabilities.
kernelParams (dict) – Parameters required for the kernel function to determine migration probabilities.
maskingMatrix (numpy array) – Matrix that determines the probability of shifting from one point-type to another one (squared with size equal to the number of point types). If None, every point-type transition is equiprobable.
distanceMatrix (numpy array) – Matrix with the distances between all the points in the landscape. If None, it’s auto-calculated (see calcPointsDistances).
migrationMatrix (numpy array) – Markov matrix that determines the probability of moving from one site to another. If None, it’s auto-calculated (see calcPointsMigration).
maskedMigrationMatrix (numpy array) – Markov matrix that biases migration probabilities as dictated by the masking matrix. If None, it’s auto-calculated (see calcPointsMaskedMigration).
distanceFunction (function) – Function that takes two points in the landscape and calculates the distance between them.
traps (pandas dataframe) – Traps positions with mandatory {x,y} coordinates and optional {t: trap type integer, f: fixed bool (immovable)}.
trapsKernels (dict) – Traps’ kernels functions and parameters in dictionary form (where the indices must match the “t” values in the traps dataframe).
trapsMask (numpy array) – Traps’ masking matrix to make traps act upon mosquitos searching for a specific resource (shape: {trapsNum, sitesNum}).
trapsRadii (list) – List of probability values at which we want rings to be plotted in dataviz functions.
landLimits (tuple) – Landscape’s bounding box.
- calcFundamentalMatrix()
Calculates the Markov fundamental matrix on the landscape.
- calcPointsDistances()
Calculates the distancesMatrix amongst the points (in place).
- calcPointsMaskedMigration()
Calculates the maskedMigrationMatrix depending on point-type (in place).
- calcPointsMigration()
Calculates the migrationMatrix amongst the points (in place).
- calcTrapsDistances()
Calculates the trapsDistances matrix (in place).
- calcTrapsMigration()
Replaces section in the trapsMigration matrix (in place).
- getBoundingBox()
Returns the landscape’s ((minX, maxX), (minY, maxY)).
- getDaysTillTrapped(fitFuns={'inner': <function amax>, 'outer': <function mean>})
Gets the number of timesteps until a walker falls into a trap
- plotDirectedNetwork(fig, ax, markers=('o', '^', 's', 'p', 'd', 'X'), colors=('#bdb2ff', '#a0c4ff', '#e0c3fc', '#ffd6a5', '#caffbf', '#d0d1ff'), edgecolors='black')
- plotLandBoundary(fig, ax, landTuples=(('10m', '#dfe7fd55', 30), ('10m', '#ffffffDD', 5)))
- plotMaskedMigrationNetwork(fig, ax, lineColor='#03045e', lineWidth=20, alphaMin=0.5, alphaAmplitude=2.5, zorder=0, **kwargs)
Plots the base sites migration network.
- plotMigrationNetwork(fig, ax, lineColor='#03045e', lineWidth=20, alphaMin=0.5, alphaAmplitude=2.5, zorder=0, **kwargs)
Plots the base sites migration network.
- plotSites(fig, ax, markers=('o', '^', 's', 'p', 'd', 'X'), colors=('#bdb2ff', '#a0c4ff', '#e0c3fc', '#ffd6a5', '#caffbf', '#d0d1ff'), size=350, edgecolors='w', linewidths=2, zorder=5, **kwargs)
Plots the sites coordinates.
- plotTraps(fig, ax, colors={0: '#f7258515', 1: '#5ddeb125', 2: '#fe5f5515', 3: '#f038ff15', 4: '#e2ef7015', 5: '#9381ff15'}, marker='X', edgecolor='w', lws=(2, 0), ls=':', size=300, zorders=(25, - 5), **kwargs)
Plots the traps locations.
- plotTrapsNetwork(fig, ax, lineColor='#f72585', lineWidth=20, alphaMin=0.5, alphaAmplitude=1.5, zorder=0, **kwargs)
Plots the traps networks.
- updateTraps(traps, trapsKernels)
Updates the traps locations and migration matrices (in place).
- Parameters
traps (pandas dataframe) –
trapsKernel (dictionary) –
- updateTrapsCoords(trapsCoords)
- updateTrapsRadii(probValues)
MGSurvE.matrices module
Migration and masking operations upon matrices.
- MGSurvE.matrices.calcAttractiveness(migrationMtx, attractionVector)
Calculates the effects of attractiveness in the migration matrix.
- Parameters
migrationMtx (numpy array) – Original migration matrix (Tau).
attractivenessVct (numpy array) – Relative attractiveness modifier for sites.
- Returns
Full migration matrix with attractiveness effects.
- Return type
(numpy array)
- MGSurvE.matrices.calcDistanceMatrix(pointCoords, distFun=<built-in function dist>)
Calculates the distance matrix between all the provided coordinates.
- Parameters
pointCoords (numpy array) – Coordinates of the sites.
distFun (function) – Distance function to be used in the computations.
- Returns
Distances matrix
- Return type
(numpy array)
- MGSurvE.matrices.calcMaskedMigrationMatrix(migrationMatrix, maskingMatrix, pointTypes)
Calculates the masked migration matrix between points according to their types.
- Parameters
migrationMatrix (numpy array) – Migration probabilities amongst points.
maskingMatrix (numpy array) – Transition probabilities between point-types.
pointTypes (numpy vector) – Point-types for each one of the sites in the matrix (in the same order).
- Returns
Masked migration matrix
- Return type
(numpy array)
- MGSurvE.matrices.calcTrapsProbabilities(trapsDistances, trapsTypes, trapsKernels, trapsMask, pointTypes)
Calculates the traps probabilities given distances to points in the landscape and their effectiveness kernels.
- Parameters
trapsDistances (numpy array) – Distances to all points.
trapsTypes (numpy array) – Types of the traps.
trapsKernels (function) – Kernels functions and params for trap types.
trapsMask (np array) – Traps’ catching bias mask (with shape: trapTypes, pointTypes)
pointTypes (list) –
- Returns
Traps probabilities
- Return type
(numpy array)
- MGSurvE.matrices.calcTrapsToPointsDistances(trapsCoords, pointCoords, dFun=<built-in function dist>)
Generates the distances matrix between the traps and the sites.
- Parameters
trapsCoords (numpy array) – Coordinates of the traps.
pointsCoords (numpy array) – Coordinates of the sites.
dFun (function) – Distance function to be used in the computations.
- Returns
Distances matrix
- Return type
(numpy array)
- MGSurvE.matrices.genVoidFullMigrationMatrix(migrationMatrix, trapsNumber)
Calculates a migration matrix with sections for traps (Xi) to be filled in place.
- Parameters
migrationMatrix (numpy array) – Migration matrix without any traps (Tau).
trapsNumber (int) – Number of traps in the landscape
- Returns
Full migration matrix with no traps effects
- Return type
(numpy array)
MGSurvE.network module
Network-analysis operations.
- MGSurvE.network.calculateNetworkCentralities(transitionsMatrix, nodeCentrality=<function newman_betweenness_centrality>, edgeCentrality=<function edge_betweenness_centrality>, weight='distance')
MGSurvE.optimization module
Operators to calculate fitness and perform operations to search through optimization space.
- MGSurvE.optimization.calcFitness(chromosome, landscape=None, optimFunction=<function getDaysTillTrapped>, optimFunctionArgs={'inner': <function amax>, 'outer': <function mean>}, dims=2, clipValue=1000)
Calculates the fitness function of the landscape given a chromosome (in place, so not thread-safe).
- Parameters
chromosome (floats numpy array) – GA’s float chromosome generated by initChromosome.
landscape (object) – Landscape object to use for the analysis.
optimFunction (function) – Function that turns a matrix into a fitness value.
optimFunctionArgs (dict) – Dictionary with the outer (row) and inner (col) functions to use on the matrix.
- Returns
Landscape’s fitness function.
- Return type
(tuple of floats)
- MGSurvE.optimization.calcSexFitness(chromosome, landscapeMale=None, landscapeFemale=None, weightMale=1, weightFemale=1, optimFunction=<function getDaysTillTrapped>, optimFunctionArgs={'inner': <function amax>, 'outer': <function mean>}, dims=2)
Calculates the fitness function of a Male/Female set of landscapes with a weighted sum of the time-to catch between them.
- Parameters
chromosome (floats numpy array) – GA’s float chromosome generated by initChromosome.
landscapeMale (object) – Male landscape object to use for the analysis.
landscapeFemale (object) – Female landscape object to use for the analysis.
weightMale (float) – Preference on catching males over females.
weightFemale (float) – Preference on catching females over males.
optimFunction (function) – Function that turns a matrix into a fitness value.
optimFunctionArgs (dict) – Dictionary with the outer (row) and inner (col) functions to use on the matrix.
- Returns
Landscape’s fitness function.
- Return type
(tuple of floats)
- MGSurvE.optimization.cxBlend(ind1, ind2, fixedTrapsMask, alpha=0.5)
Mates two chromosomes by “blend” based on the provided mask (in place).
This implementation is similar to DEAP’s cxBlend (https://deap.readthedocs.io/en/master/api/tools.html#deap.tools.cxBlend). Follow this link for the original code: https://github.com/DEAP/deap/blob/master/deap/tools/crossover.py
- Parameters
ind1 (floats numpy array) – GA’s float chromosome generated by initChromosome.
ind2 (floats numpy array) – GA’s float chromosome generated by initChromosome.
fxdTrpsMsk (bool numpy array) – Array of bools that define which alleles can be mutated (1).
alpha (float) – weight for each of the chromosomes.
- Returns
Mated individuals.
- Return type
(list of chromosomes)
- MGSurvE.optimization.exportLog(logbook, outPath, filename)
Dumps a dataframe with the report of the GA’s history.
- Parameters
logbook (object) – DEAP GA object.
outPath (path) – Path where the file will be exported.
F_NAME (string) – Filenamme (without extension).
- MGSurvE.optimization.genFixedTrapsMask(trapsFixed, dims=2)
Creates a mask for the fixed traps (non-movable).
- Parameters
trapsFixed (bool numpy array) – Boolean array with the traps that are not movable (lnd.trapsFixed).
dims (int) – Unused for now, but it’s the number of dimensions for the landscape.
- Returns
Mask of the elements that can be moved in the GA operations.
- Return type
(numpy array)
- MGSurvE.optimization.getDaysTillTrapped(landscape, fitFuns={'inner': <function amax>, 'outer': <function mean>})
Gets the number of timesteps until a walker falls into a trap.
- Parameters
landscape (object) – Landscape object to use for the analysis.
fitFuns (dict) – Dictionary with the outer (row) and inner (col) functions to use on the matrix.
- Returns
Number of days for mosquitoes to fall into traps given the fitFuns.
- Return type
(float)
- MGSurvE.optimization.getFundamentalFitness(fundamentalMatrix, fitFuns={'inner': <function amax>, 'outer': <function mean>})
Get fitness from Markov’s fundamental matrix.
- Parameters
fundamentalMatrix (numpy array) – Markov’s fundamental matrix (calcFundamentalMatrix)
fitFuns (dict) – Dictionary containing the inner (row) and outer (col) operations for the fundamental matrix.
- Returns
Summarized fitness function for the fundamental matrix.
- Return type
(float)
- MGSurvE.optimization.getFundamentalMatrix(tau, sitesN, trapsN)
Get Markov’s fundamental matrix.
- Equivalent to using reshapeInCanonicalForm and getMarkovAbsorbing (which
should be deprecated).
- Parameters
tau (numpy array) – Traps migration matrix in canonical form.
sitesN (int) – Number of sites.
trapsN (int) – Number of traps.
- Returns
Time to fall into absorbing states from anywhere in landscape.
- Return type
(numpy array)
- MGSurvE.optimization.getMarkovAbsorbing(tauCan, trapsN)
Get Markov’s absorbing states (deprecated).
- Parameters
tauCan (numpy array) – Traps migration matrix in canonical form.
trapsN (int) – Number of traps.
- Returns
Time to fall into absorbing states from anywhere in landscape.
- Return type
(numpy array)
- MGSurvE.optimization.importLog(inPath, filename)
Gets the number of timesteps until a walker falls into a trap.
- Parameters
LOG_PTH (path) – Path where the file is stored.
F_NAME (dict) – Filename with extension.
- Returns
GA optimization log.
- Return type
(pandas dataframe)
- MGSurvE.optimization.initChromosome(trapsCoords, fixedTrapsMask, coordsRange)
Generates a random uniform chromosome for GA optimization.
- Parameters
trapsNum (int) – Number of traps to lay down in the landscape.
xRan (tuple of tuples of floats) – XY Range for the coordinates.
- Returns
List of xy coordinates for the traps’ positions.
- Return type
(list)
- MGSurvE.optimization.mutateChromosome(chromosome, fixedTrapsMask, randFun=<built-in method normal of numpy.random.mtrand.RandomState object>, randArgs={'loc': 0, 'scale': 0.1}, indpb=0.5)
Mutates a chromosome with a probability distribution based on the mutation mask (in place).
- Parameters
chromosome (floats numpy array) – GA’s float chromosome generated by initChromosome.
fxdTrpsMsk (bool numpy array) – Array of bools that define which alleles can be mutated (1).
randFun (function) – Probability function for the mutation operation.
randArgs (dict) – Arguments to control the shape of the probability function.
indpb (float) – Independent probability to mutate each allele.
- Returns
Selectively-mutated chromosome.
- Return type
(numpy array list)
- MGSurvE.optimization.mutateChromosomeAsymmetric(chromosome, fixedTrapsMask, randFun=<built-in method normal of numpy.random.mtrand.RandomState object>, randArgs={'x': {'loc': 0, 'scale': 0.1}, 'y': {'loc': 0, 'scale': 0.1}}, indpb=0.5)
Mutates a chromosome with a probability distribution based on the mutation mask with different probabilities for XY elements (in place).
- Parameters
chromosome (floats numpy array) – GA’s float chromosome generated by initChromosome.
fxdTrpsMsk (bool numpy array) – Array of bools that define which alleles can be mutated (1).
randFun (function) – Probability function for the mutation operation.
randArgs (dict) – Arguments to control the shape of the probability function (‘x’ and ‘y’ entries).
indpb (float) – Independent probability to mutate each allele.
- Returns
Selectively-mutated chromosome.
- Return type
(numpy array list)
- MGSurvE.optimization.reshapeInCanonicalForm(tau, sitesN, trapsN)
Reshapes a migration matrix into canonical form (deprecated).
- Parameters
tau (numpy array) – Traps migration matrix.
sitesN (int) – Number of sites.
trapsN (int) – Number of traps.
- Returns
Reshaped matrix in canonical form.
- Return type
(numpy array)
MGSurvE.plots module
Data-Visualization functions.
- MGSurvE.plots.plotClean(fig, ax, frame=False, bbox=None, labels=False)
Makes axes equally spaced and removes frame.
- Parameters
fig (matplotlib) – Matplotlib fig object.
ax (matplotlib) – Matplotlib ax object.
frame (bool) – Flag to remove plot’s frame.
- Returns
Matplotlib (fig, ax) tuple.
- Return type
(fig, ax)
- MGSurvE.plots.plotDirectedNetwork(fig, ax, sites, pTypes, transMtx, markers=('o', '^', 's', 'p', 'd', 'X'), colors=('#bdb2ff', '#a0c4ff', '#e0c3fc', '#ffd6a5', '#caffbf', '#d0d1ff'), alphaNodeMin=1, alphaEdgeMin=1, alphaNodeAmplitude=50, alphaEdgeAmplitude=100, sizeNodeAmplitude=10000000000, widthEdgeAmplitude=10, edgecolors='black', transform=None, **kwargs)
Plots edge and node centrality.
- Parameters
fig (matplotlib) – Matplotlib fig object.
ax (matplotlib) – Matplotlib ax object.
sites (numpy array) – Coordinates of the points.
pTypes (numpy array) – Point types.
transMtx (numpy matrix) – Transitions matrix.
markers (list) – List of marker shapes for point-types (matplotlib).
colors (list) – List of colors for point-types (matplotlib).
alphaNodeMin (float) – Minimum alpha value allowed for nodes.
alphaEdgeMin (float) – Minimum alpha value allowed for edges.
alphaNodeAmplitude (float) – Alpha multiplier for nodes of matrix.
alphaEdgeAmplitude (float) – Alpha multiplier for edges of matrix.
sizeNodeAmplitude (float) – Size multiplier for nodes of matrix.
widthEdgeAmplitude (float) – Width multiplier for edges of matrix.
edgecolors (color) – Edge color.
kwargs (dict) – Matplotlib’s plot-compliant kwargs.
- Returns
Matplotlib (fig, ax) tuple.
- Return type
(fig, ax)
- MGSurvE.plots.plotFitness(fig, ax, fitness, pos=(0.5, 0.5), fmt='{:.2f}', fontSize=125, color='#00000011', zorder=5, **kwargs)
Adds the fitness value to the plot.
- Parameters
fig (matplotlib) – Matplotlib fig object.
ax (matplotlib) – Matplotlib ax object.
pos (floats tuple) – Position for the text.
fmt (string formating) – String format for the fitness text.
fontSize (float) – Text’s font size.
color (color) – Font color
zorder (int) – Zorder for the text.
**kwargs – Matplotlib’s text kwargs.
- Returns
Matplotlib (fig, ax) tuple.
- Return type
(fig, ax)
- MGSurvE.plots.plotGAEvolution(fig, ax, gaLog, colors={'envelope': '#1565c0', 'mean': '#ffffff'}, alphas={'envelope': 0.5, 'mean': 0.75}, aspect=0.3333333333333333)
Makes axes equally spaced and removes frame.
- Parameters
fig (matplotlib) – Matplotlib fig object.
ax (matplotlib) – Matplotlib ax object.
gaLog (pandas dataframe) – Flag to remove plot’s frame.
colors (dict) – Mean and envelope colors
alphas (dict) – Mean and envelope alphas
- Returns
Matplotlib (fig, ax) tuple.
- Return type
(fig, ax)
- MGSurvE.plots.plotLandBoundary(fig, ax, landTuples=(('10m', '#dfe7fd55', 30), ('10m', '#ffffffDD', 5)))
Plots the land’s boundary as a polygon.
- Parameters
fig (matplotlib) – Matplotlib fig object.
ax (matplotlib) – Matplotlib ax object.
landTuples (list of tuples) – Check the constants.py file for format.
- Returns
Matplotlib (fig, ax) tuple.
- Return type
(fig, ax)
- MGSurvE.plots.plotMatrix(fig, ax, matrix, trapsNumber=None, vmin=0, vmax=1, cmap='Purples', linecolor='#222222', linestyle=':', lw=0.5, ticks=False, **kwargs)
Block matrix plot for the connection network.
- Parameters
fig (matplotlib) – Matplotlib fig object.
ax (matplotlib) – Matplotlib ax object.
trapsNumber (int) – Number of traps in landscape.
vmin (float) – Lower clipping value.
vmax (float) – Higher clipping value.
cmap (matplotlib colormap) – Matplotlib’s colormap object.
lineColor (color) – Color for the block’s boundaries.
lineStyle (matplotlib linestyle) – Linestyle for the block matrix’ boundaries.
lw (float) – Linewidth for block matrix boundaries.
ticks (bool) – Imshow ticks on/off
zorders (tuple) – Zorders for marker and circles.
kwargs (dict) – Matplotlib’s plot-compliant kwargs.
- Returns
Matplotlib (fig, ax) tuple.
- Return type
(fig, ax)
- MGSurvE.plots.plotMigrationNetwork(fig, ax, transMtx, sitesB, sitesA, lineColor='#03045e', lineMin=0.025, lineWidth=20, alphaMin=0.5, alphaAmplitude=2.5, zorder=0, transform=None, **kwargs)
Plots a transitions matrix.
- Parameters
fig (matplotlib) – Matplotlib fig object.
ax (matplotlib) – Matplotlib ax object.
transMtx (numpy matrix) – Transitions matrix.
sitesB (numpy array) – Coordinates of the vertices origins (sites/traps).
sitesA (numpy array) – Coordinates of the vertices desinations (sites/traps).
lineColor (color) – Color for the network.
lineWidth (float) – Amplitude for the linewidth.
alphaMin (float) – Minimum alpha value allowed.
alphaAmplitude (float) – Alpha multiplier for matrix.
zorder (int) – Matplotlib’s zorder.
kwargs (dict) – Matplotlib’s plot-compliant kwargs.
- Returns
Matplotlib (fig, ax) tuple.
- Return type
(fig, ax)
- MGSurvE.plots.plotSites(fig, ax, sites, pTypes, markers=('o', '^', 's', 'p', 'd', 'X'), colors=('#bdb2ff', '#a0c4ff', '#e0c3fc', '#ffd6a5', '#caffbf', '#d0d1ff'), size=350, edgecolors='w', linewidths=1.25, zorder=5, transform=None, **kwargs)
Plots a transitions matrix.
- Parameters
fig (matplotlib) – Matplotlib fig object.
ax (matplotlib) – Matplotlib ax object.
sites (numpy array) – Coordinates of the points.
pTypes (numpy array) – Point types.
markers (list) – List of marker shapes for point-types (matplotlib).
colors (list) – List of colors for point-types (matplotlib).
size (float) – Marker size.
edgecolors (color) – Edge color for markers.
linewidths (float) – Edge line width for markers.
zorder (int) – Matplotlib’s zorder.
kwargs (dict) – Matplotlib’s plot-compliant kwargs.
- Returns
Matplotlib (fig, ax) tuple.
- Return type
(fig, ax)
- MGSurvE.plots.plotTraps(fig, ax, trapsCoords, trapsTypes, trapsKernels, trapsFixed, colors={0: '#f7258515', 1: '#5ddeb125', 2: '#fe5f5515', 3: '#f038ff15', 4: '#e2ef7015', 5: '#9381ff15'}, marker='X', edgecolors=('w', 'k'), lws=(2, 0), ls=':', size=350, zorders=(25, - 5), fill=True, transform=None, **kwargs)
Plots the traps with the radii of effectiveness.
- Parameters
fig (matplotlib) – Matplotlib fig object.
ax (matplotlib) – Matplotlib ax object.
trapsCoords (numpy array) – Coordinates of the vertices.
trapsTypes (list ints) – Trap types IDs.
trapsKernels (dict) – Dictionary of traps kernels.
colors (dict) – List of colors for different trap types.
marker (mrk) – Marker type for matplotlib.
edgecolor (color) – Edgecolor for trap marker.
lws (tuple) – Line widths for marker and radii (in order).
ls (str) – Linestyle for the radii.
size (float) – Size of the marker.
zorders (tuple) – Zorders for marker and circles.
kwargs (dict) – Matplotlib’s plot-compliant kwargs.
- Returns
Matplotlib (fig, ax) tuple.
- Return type
(fig, ax)
- MGSurvE.plots.plotTrapsNetwork(fig, ax, transMtx, traps, sites, lineColor='#3d0e61', lineWidth=20, alphaMin=0.5, alphaAmplitude=2.5, zorder=0, transform=None, **kwargs)
Plots the connectivity network of traps in the landscape.
- Parameters
fig (matplotlib) – Matplotlib fig object.
ax (matplotlib) – Matplotlib ax object.
transMtx (numpy array) – Full transitions matrix.
traps (numpy array) – Traps’ coordinates.
sites (numpy array) – Sites’ coordinates.
lineColor (color) – Color for the network’s line.
lineWidth (float) – Base width for the connections.
alphaMin (float) – Minimum alpha value for connections.
alphaAmplitude (float) – Multiplier for the alpha (proportional to connection).
zorders (tuple) – Z-orders for marker and circles.
kwargs (dict) – Matplotlib’s plot-compliant kwargs.
- Returns
Matplotlib (fig, ax) tuple.
- Return type
(fig, ax)
- MGSurvE.plots.saveFig(fig, ax, filepath, filename, dpi=300, facecolor='w', transparent=False, bbox_inches='tight', pad_inches=0, **kwargs)
Save figure to disk.
- Parameters
fig (matplotlib) – Matplotlib fig object.
ax (matplotlib) – Matplotlib ax object.
filepath (string) – Path for figure export.
filename (string) – Filename for the export.
dpi (int) – Image resolution.
facecolor (color) – Background for the plot.
transparent (bool) – Transparent background.
bbox_inches (string) – Bounding box inches.
pad_inches (float) – Padding inches.
**kwargs – Matplotlib savefig kwargs.
- Returns
Matplotlib (fig, ax) tuple.
- Return type
(fig, ax)
MGSurvE.pointProcess module
Synthetic Landscape generation functions.
- MGSurvE.pointProcess.ptsDonut(pointsNumber, radii, center=(0, 0))
Creates a distribution of points laid around a donut shape.
- Parameters
pointsNumber (int) – Number of sites.
radii (tuple of floats) – Minimum and maximum radii for the donut shape.
center (tuple of floats) – Coordinates for the center of the donut (x, y).
- Returns
Points’ coordinates.
- Return type
(numpy array)
- MGSurvE.pointProcess.ptsPossion(pointsNumber, clustersNumber, radius, randomState=1647376353.3706, bbox=None, polygon=None)
Generates a synthetic landscape from a Poisson distribution.
- Parameters
pointsNumber (int) – Number of sites.
clustersNumber (int) – Number of sites’ clusters.
radius (float) – Radius of the circle centered on each parent.
randomState (int) – Random seed.
bbox (tuple of tuples) – Bounding box in the form ((xLo, xHi), (yLo, yHi))
polygon (name of shp file) – Shape-file for the points to be generated within.
- Returns
Points’ coordinates
- Return type
(numpy array)
- MGSurvE.pointProcess.ptsRandUniform(pointsNumber, bbox)
Creates a random unifor distribution of points.
- Parameters
pointsNumber (int) – Number of sites
bbox (tuple of tuples) – Bounding box in the form ((xLo, xHi), (yLo, yHi))
- Returns
Points’ coordinates
- Return type
(numpy array)
- MGSurvE.pointProcess.ptsRegularGrid(pointsNumber, bbox)
Creates a regular grid (lattice) of points.
- Parameters
pointsNumber (int) – Number of sites.
bbox (tuple of tuples) – Bounding box in the form ((xLo, xHi), (yLo, yHi)).
- Returns
Points’ coordinates.
- Return type
(numpy array)