Methods¶
Core gating functions¶
Contains core gating functions for common gating operations.
- AGCore.axisStats(fcsDF, xCol, vI=None, bins=300, sigma=3, scale='linear', T=1000)¶
Report mean, median, standard deviation and maximum value on axis.
Parameters
- fcsDFpandas.DataFrame
Flow data loaded in a pandas DataFrame.
If data is stored in an AGSample object this can be retrieved by calling the sample, i.e. mysample().
- xColstr
Marker label.
- vIlist-like or AGgate object
Parent population to apply the gating to.
- binsint, optional, default: 300
Number of bins in density histogram.
- scalestr, optional, default: ‘linear’
The returned values can be transformed to a plotting scale;
options: ‘linear’, ‘logicle’
Note
If a scale is changed from the default ‘linear’,
The returned values will then also be the mean, median, sigma and maxval in transformed coordinates.
(i.e. what you would visually see if plotting with this scale)
To reverse transform see aligater.AGPlotRoutines.inverseTransformWrapper. When setting a treshold based on these values (such as mean+2*sigma), use transformed values and then invert.
- Tint, optional, default: 1000
If plotting enabled and scale is logicle, the threshold for linear-loglike transition
Returns
- float, float, float, float
mean, median, standard deviation, maximum value
Note
The input heatmap is smoothed using a gaussian filter to avoid finding noisy local minima.
The returned maxvalue will be the center of the (smoothed) bin where it occured. This means it has an inbuilt approximation error of:
+- ( bin width / 2 )
Examples
None currently.
- AGCore.backGate(fcs, xCol, yCol, population, background_population=None, markersize=2, scale='linear', xscale='linear', yscale='linear', T=1000, filePlot=None, color='#f10c45')¶
Highlights a population onto another view/population.
Typically used to see where rarer populations are located on an earlier view in a gating strategy.
Parameters
- fcsAGClasses.AGSample object
Flow data loaded in a sample object.
- xCol,yColstr
Marker labels.
- populationAGgate object
Population that should be highlighted.
- background_populationAGgate object
Background population.
- markersizefloat, optional, default: 2
Size of events of the overlayed/highlighted population.
- scalestr, optional, default: ‘linear’
Which scale to be used on axis.
- xscalestr, optional, default: ‘linear’
Which scale to be used on x-axis.
- yscalestr, optional, default: ‘linear’
Which scale to be used on y-axis.
- Tint, optional, default: 1000
If scale is logicle, the threshold for linear-loglike transition.
- filePlotstr, optional, default: None
Option to plot the gate to file to specified path.
Warning: might overwrite stuff.
- colorstr, optional, default: ‘#f10c45’
Color of the highlighted population
default is ‘pinkish red’ from XKCD’s color survey https://xkcd.com/color/rgb/
Note
If the scale parameter is changed from default (linear) this will override any settings in xscale, yscale.
Returns
None
Examples
None currently.
- AGCore.customQuadGate(fcs, names, xCol, yCol, threshList, parentGate=None, scale='linear', T=1000, filePlot=None)¶
A quadgate function with one axis fix and the other variable. The threshList argument decides which axis is fix and which can vary.
Parameters
- fcsAGClasses.AGSample object
Flow data loaded in an sample object.
- xCol, yColstr
Marker labels.
- parentGateAGgate object, optional
Parent population to apply the gating to. If no AGgate object is passed gating is applied to the ungated data frame.
- threshListlist-like of float or int
Requires four float or int values. These are the thresholds in each direction for the gate.
In order; bottom x threshold, top x threshold, left y threshold, right y threshold. Either the x or y thresholds must be equal (that axis will be fix).
- scalestr, optional, default: ‘linear’
If plotting enabled, which scale to be used on both axis.
- Tint, optional, default: 1000
If plotting enabled and scale is logicle, the threshold for linear-loglike transition.
- filePlotstr, optional, default: None
Option to plot the gate to file to specified path.
Warning: might overwrite stuff.
Returns
- AGClasses.AGgate, AGClasses.AGgate, AGClasses.AGgate, AGClasses.AGgate
Returns AGClasses.AGgate objects for the four gated populations.
In clockwise order; top-left, top-right, bottom-right, bottom-left
Note
All limits are considered greater than inclusive (<=) and less than exclusive (>)
Examples
None currently.
- AGCore.gateBox(fcs, name, xCol, yCol, xThreshRight, yThreshTop, xThreshLeft, yThreshBottom, Outer=False, parentGate=None, bins=300, scale='linear', T=1000, update=False, filePlot=None, QC=False)¶
Gates a box in the view.
Parameters
- fcsAGClasses.AGSample object
Flow data loaded in an sample object.
- xCol, yColstr
Marker labels.
- namestr
Name to the resulting gated population.
- parentGateAGClasses.AGgate object, optional
Parent population to apply the gating to. If no AGgate object is passed gating is applied to the ungated data frame.
- xThreshLeft, xThreshRight, yThreshTop, yThreshBottomfloat
The X- and Y-axis thresholds for the gate.
- outerbool, optional, default: False
If True, instead returns all events outside of the defined box.
- binsint, optional, default: 300
If plotting, defines the resolution of the heatmap.
- scalestr, optional, default: ‘linear’
If plotting enabled, which scale to be used on both axis.
- Tint, optional, default: 1000
If plotting enabled and scale is logicle, the threshold for linear-loglike transition.
- filePlotstr, optional, default: None
Option to plot the gate to file to specified path.
Warning: might overwrite stuff.
- updatebool, optional, default: False
If True will add the resulting gated population(s) to the sample objects gate list in adition to returning the gate object.
If False (default), returns an AGgate object without adding it to the sample object.
- QCbool, optional, default: False
If True, adds a downsampled image of the gating view to the gate object. These can be collected by an AGExperiment object if it’s QC flag is also True.
Returns
AGClasses.AGgate object
Examples
None currently.
- AGCore.gateCorner(fcs, name, xCol, yCol, xThresh, yThresh, xOrientation='upper', yOrientation='upper', Outer=False, parentGate=None, bins=300, scale='linear', T=1000, update=False, filePlot=None, QC=False)¶
Gates a corner in the view, with xOrientation and yOrientation parameters deciding the shape (which corner to gate).
Parameters
- fcsAGClasses.AGSample object
Flow data loaded in an sample object.
- xCol, yColstr
Marker labels.
- namestr
Name to the resulting gated population.
- parentGateAGClasses.AGgate object, optional
Parent population to apply the gating to. If no AGgate object is passed gating is applied to the ungated data frame.
- xThresh, yThreshfloat
The X- and Y-axis thresholds for the gate.
- xOrientation, yOrientationstr, optional, default: ‘upper’
Defines which population is gated as positive in relation to the x- and y- thresholds. The default parameter means top right corner.
- outerbool, optional, default: False
If True, instead returns all events outside of the defined corner.
- binsint, optional, default: 300
If plotting, defines the resolution of the heatmap.
- scalestr, optional, default: ‘linear’
If plotting enabled, which scale to be used on both axis.
- Tint, optional, default: 1000
If plotting enabled and scale is logicle, the threshold for linear-loglike transition.
- filePlotstr, optional, default: None
Option to plot the gate to file to specified path.
Warning: might overwrite stuff.
- updatebool, optional, default: False
If True will add the resulting gated population(s) to the sample objects gate list in adition to returning the gate object.
If False (default), returns an AGgate object without adding it to the sample object.
- QCbool, optional, default: False
If True, adds a downsampled image of the gating view to the gate object. These can be collected by an AGExperiment object if it’s QC flag is also True.
Returns
AGClasses.AGgate object
Examples
None currently.
- AGCore.gateGMM(fcs, name, xCol, yCol, gmm, parentGate=None, sigma=1, widthScale=1, heightScale=1, update=False, QC=False, scale='linear', T=1000)¶
Function that can interpret and gate data based on a GaussianMixture object from sklearn.mixture
Parameters
- fcsAGClasses.AGSample object
Flow data loaded in an sample object.
- xCol, yColstr
Marker labels.
- parentGateAGgate object, optional
Parent population to apply the gating to. If no AGgate object is passed gating is applied to the ungated data frame.
- sigmafloat, optional, default: 1
Number of standard deviations to scale the mixture model with.
- updatebool, optional, default: False
If True will add the resulting gated population(s) to the sample objects gate list in adition to returning the gate object.
If False (default), returns an AGgate object without adding it to the sample object.
- QCbool, optional, default: False
If True, adds a downsampled image of the gating view to the gate object. These can be collected by an AGExperiment object if it’s QC flag is also True.
Returns
AGClasses.AGgate object
Examples
None currently.
- AGCore.gatePC(fcs, xCol, yCol, name, parentGate=None, widthScale=1, heightScale=1, center='centroid', customCenter=None, filePlot=None, scale='linear', T=1000, **kwargs)¶
Function that performs a 2D principal component analysis and gates an ellipse based on the results.
Parameters
- fcsAGClasses.AGSample object
Flow data loaded in an sample object.
- xCol, yColstr
Marker labels.
- namestr
Name to the resulting gated population.F
- parentGateAGgate object, optional
Parent population to apply the gating to. If no AGgate object is passed gating is applied to the ungated data frame.
- widthScale, heightScalefloat, optional, default: 1
Number of standard deviations to scale eigenvectors with, corresponding to the width and height of the ellipse.
- centerstr, optional, default: ‘centroid’
Where to center the image for PC analysis, options are ‘density’, ‘centroid’ or ‘custom’
Data will temporarily be centered around this point for the PC analysis.
- customCenterNone or list-like, optional, default: None
Only used if center option is ‘custom’. Then takes a list-like of two being the coordinates of the center point.
- filePlotstr, optional, default: None
Option to plot the gate to file to specified path.
Warning: might overwrite stuff.
- scalestr, optional, default: ‘linear’
Which scale to be used on axis.
- Tint, optional, default: 1000
If the threshold for linear-loglike transition for bilog or logicle scales.
Returns
AGClasses.AGgate object
Examples
None currently.
- AGCore.gateTiltedLine(fcs, xCol, yCol, theta, name, parentGate=None, startPoint=(None, None), endLimits=(None, None), population='upper', scale='linear', xscale='linear', yscale='linear', T=1000, filePlot=None)¶
Gates the population from a line given by an angle (-90 < theta < 90) and optionally a startpoint and/or endlimit(s).
Parameters
- fcsAGClasses.AGSample object
Flow data loaded in a sample object.
- xCol,yColstr
Marker labels.
- populationAGgate object
Population that should be highlighted.
- thetafloat/int
The angle in degrees, (-90 < theta < 90)
- namestr
Name of the resulting gated population.
- parentGateAGgate object, optional
Parent population to apply the gating to. If no AGgate object is passed gating is applied to the ungated data frame.
- startPointtuple(float/int), optional, default(None, None)
Optional start point where to start the tilted line.
- endLimitstuple(float/int), optional, default(None, None)
Optional end limits, if the tilted line passes through EITHER the x or y limit specified by endLimits it will stop and proceed acoording to endOrientation.
- population, str, optional, default: ‘upper’
This parameter determines which population should be returned.
‘upper’ means any events with a value above the tresholds are returned.
‘lower’ means any events with a value below the tresholds will be returned.
The default setting means the population that’s considered ‘positive’ in flow cytometry terms is returned.
- scalestr, optional, default: ‘linear’
Which scale to be used on axis.
- xscalestr, optional, default: ‘linear’
Which scale to be used on x-axis.
- yscalestr, optional, default: ‘linear’
Which scale to be used on y-axis.
- Tint, optional, default: 1000
If scale is logicle, the threshold for linear-loglike transition.
- filePlotstr, optional, default: None
Option to plot the gate to file to specified path.
Warning: might overwrite stuff.
Returns
None
Examples
None currently.
- AGCore.getHighestDensityPoint(fcs, xCol, yCol, parentGate=None, bins=300, scale='linear', T=1000)¶
Returns coordinates for the point in the view with the highest number of events.
Parameters
- fcsAGClasses.AGSample object
Flow data loaded in a sample object.
- xCol, yColstr
Marker labels.
- parentGateAGgate object, optional
Parent population to apply the gating to. If no AGgate object is passed gating is applied to the ungated data frame.
- binsint, optional, default: 300
Resolution of the heatmap used to calculate the highest density point
- scalestr, optional, default: ‘linear’
Which scale to be used on axis.
- Tint, optional, default: 1000
If the threshold for linear-loglike transition for bilog or logicle scales.
Returns
- List-like
Returns approximate coordinates of the highest density point; [x-coord, y-coord].
Precision can be increased by increasing the resolution (the bins parameter)
Examples
None currently.
- AGCore.gmm2D(fcs, xCol, yCol, nOfComponents, parentGate=None, scale='linear', T=1000, *args, **kwargs)¶
Fits a scikit.learn GaussianMixture object to the data and returns the gmm object.
Parameters
- fcsAGClasses.AGSample object
Flow data loaded in an sample object.
- xCol, yColstr
Marker labels.
- nOfComponentsint
Number of components to use in the mixture model.
- parentGateAGgate object, optional
Parent population to apply the gating to. If no AGgate object is passed gating is applied to the ungated data frame.
- args, kwargs
Optional arguments passed on to scipy.ndimage.filters.GaussianMixture, see it’s sklearn documentation for options.
Returns
GaussianMixture object fit to the data.
Examples
None currently.
- AGCore.quadGate(fcs, names, xCol, yCol, xThresh, yThresh, parentGate=None, scale='linear', T=1000, filePlot=None, QC=False)¶
Function that gates four populations from one view by drawing a cross.
Parameters
- fcsAGClasses.AGSample object
Flow data loaded in a sample object.
- nameslist-like
- list of string with four names for the output gated populations in clockwise order from top-left;Top-left, top-right, bottom-right, bottom-left
- xCol, yColstr
Marker labels.
- xThreshfloat
Threshold for vertical line.
- yThreshfloat
Threshold for horizontal line.
- parentGateAGgate object, optional
Parent population to apply the gating to. If no AGgate object is passed gating is applied to the ungated data frame.
- scalestr, optional, default: ‘linear’
If plotting enabled, which scale to be used on both axis.
- Tint, optional, default: 1000
If plotting enabled and scale is logicle, the threshold for linear-loglike transition
- filePlotstr, optional, default: None
Option to plot the gate to file to specified path.
Warning: might overwrite stuff.
- QCbool, optional, default: False
If True, adds a downsampled image of the gating view to the gate object. These can be collected by an AGExperiment object if it’s QC flag is also True.
Returns
- AGClasses.AGgate, AGClasses.AGgate, AGClasses.AGgate, AGClasses.AGgate
Returns AGClasses.AGgate objects for the four gated populations.
In clockwise order; top-left, top-right, bottom-right, bottom-left
Note
All limits are considered greater than inclusive (<=) and less than exclusive (>)
Examples
None currently.
- AGCore.valleySeek(fcs, xCol, parentGate=None, interval=['start', 'end'], sigma=3, bins=300, require_local_min=False, scale='linear', T=1000)¶
Function that finds the least dense point in a given interval by searching a smoothed density function. Can, optionally, be required to find local minima.
Parameters
- fcsAGClasses.AGSample object
Flow data loaded in an sample object.
- xColstr
Marker label.
- parentGateAGgate object, optional, default: None
Parent population to apply the gating to. If no AGgate object is passed, the algorithm is applied to the ungated data frame.
- intervallist-like, optional, default: [‘start’,’end’]
Interval to limit the search, defaults to entire axis.
Some examples: [5, ‘end’], [‘start’, 6800], [30, 1500] Accepts text-strings ‘start’ and ‘first’ as synonyms and similarly for ‘end’, ‘last’
- sigmafloat, optional, default: 3
Smoothing factor of density function (gaussian kernel smooth).
- binsint, optional, default: 300
Number of bins in density histogram.
- require_local_minbool, default: False
If True, will find lowest density point with added requirement of being a local_minima. If no local minima is found, returns numpy.inf
- scalestr, optional, default: ‘linear’
If plotting enabled, which scale to be used on axis.
- Tint, optional, default: 1000
If plotting enabled and scale is logicle, the threshold for linear-loglike transition
Returns
- float
Coordinate on axis with lowest density in given interval.
Note
If require_local_min is set to True and no local minima is found, returns numpy.inf
Note
If less than 5 events are passed in parentGate, returns mid interval without attempting to valleyseek
Since the lowest density point is estimated on a smoothed histogram/density func there is an built-in error of +- ( bin width / 2 )
Examples
None currently.
Advanced gating functions¶
Contains more advanced gating functions that can be tricky to use, developed for specific purposes.
- AGExperimental.densityDelimitation(fcs, xCol, parentGate=None, interval=['start', 'end'], sigma=3, bins=300, limit_threshold=0.05, direction='left', scale='linear', T=1000)¶
Function that finds a threshold where the density is some fraction of the maximum density in the specified interval. Returns the rough coordinate where this occurs.
Parameters
- fcsAGClasses.AGSample object
Flow data loaded in an sample object.
- xColstr
Marker label.
- namestr
Name to the resulting gated population.
- parentGateAGgate object, optional
Parent population to apply the gating to. If no AGgate object is passed gating is applied to the ungated data frame.
- intervallist-like, optional, default: [‘start’,’end’]
Interval to limit the search, defaults to entire axis.
Some examples: [5, ‘end’], [‘start’, 6800], [30, 1500] Accepts text-strings ‘start’ and ‘first’ as synonyms and similarly for ‘end’, ‘last’
- limit_thresholdfloat, optional, default: 0.05
Fraction based threshold relative to the maximum density in the given interval.
- directionstr, optional, default‘right’
The search direction in the density function.
- sigmafloat, optional, default: 3
Smoothing factor of density function (kernel smooth).
- binsint, optional, default: 300
Number of bins in density histogram.
- scalestr, optional, default: ‘linear’
If plotting enabled, which scale to be used on axis.
- Tint, optional, default: 1000
If plotting enabled and scale is logicle, the threshold for linear-loglike transition
Returns
- float
Coordinate on axis with lowest density in given interval.
Note
If less than 5 events are passed in parentGate, returns mid interval without attempting to valleyseek
Since the lowest density point is estimated on a smoothed histogram/density func there is an built-in error of +- ( bin width / 2 )
Examples
None currently.
- AGExperimental.gateBezier(fcs, xCol, yCol, name, parentGate=None, points=None, xParam=0, yParam=0, population='upper', startExtension='left', endExtension='right', scale='linear', xscale='linear', yscale='linear', T=1000, filePlot=None)¶
Gates the population by drawing a quadratic Bézier curve between two points with tunable parameters.
Parameters
- fcsAGClasses.AGSample object
Flow data loaded in a sample object.
- xCol,yColstr
Marker labels.
- pointslist-like of tuple
The points defining start and end of the bezier curve (a list of two tuples).
- namestr
Name of the resulting gated population.
- parentGateAGgate object, optional
Parent population to apply the gating to. If no AGgate object is passed gating is applied to the ungated data frame.
- xParamfloat or list-like
Parameter defining the x-coordinate of the midpoint in the quadratic Bézier curve.
Should be a floating point value between which will be translated into a scaled coordinate between the start- and endpoints x coordinates.
I.e. 0.0 means the midpoints x coordinate is the same as the starting x-coordinate and 1.0 gives a midpoint x-coordinate equal to the endpoint.
If multiple sets of start and end points have been passed this argument expects a list with xParams for each Bézier curve in order.
- yParamfloat or list-like
Parameter defining the y-coordinate of the midpoint in the quadratic Bézier curve.
Should be a floating point value between which will be translated into a scaled coordinate between the start- and endpoints y coordinates.
I.e. 0.0 means the midpoints y coordinate is the same as the starting y-coordinate and 1.0 gives a midpoint y-coordinate equal to the endpoint.
If multiple sets of start and end points have been passed this argument expects a list with yParams for each Bézier curve in order.
- population, str, optional, default: ‘upper’
This parameter determines which population should be returned.
‘upper’ means any events with a value above the tresholds are returned.
‘lower’ means any events with a value below the tresholds will be returned.
The default setting means the population that’s considered ‘positive’ in flow cytometry terms is returned.
- startExtensionstr, optional, default: ‘left’
If the start point is somewhere in the middle of the gating view, this parameter defines how events falling outside the extend of the Bézier curve are treated.
Options are ‘up’, ‘down’, ‘left’ and will extend the line in the specified direction
- endExtensionstr, optional, default: ‘right’
If the end point is somewhere in the middle of the gating view, this parameter defines how events falling outside the extend of the Bézier curve are treated.
Options are ‘up’, ‘down’, ‘left’ and will extend the line in the specified direction
- scalestr, optional, default: ‘linear’
Which scale to be used on axis.
- xscalestr, optional, default: ‘linear’
Which scale to be used on x-axis.
- yscalestr, optional, default: ‘linear’
Which scale to be used on y-axis.
- Tint, optional, default: 1000
If scale is logicle, the threshold for linear-loglike transition.
- filePlotstr, optional, default: None
Option to plot the gate to file to specified path.
Warning: might overwrite stuff.
Returns
None
Examples
None currently.
- AGExperimental.halfNormalDistribution(fcs, xCol, mean, direction, parentGate=None, bins=300, scale='linear', T=1000)¶
Estimates a normal distribution in an axis by only evaluating one direction from a given mean.
Parameters
- fcsAGClasses.AGSample object
Flow data loaded in an sample object.
- xCol, yColstr
Marker labels.
- meanfloat
Mean for the normal distribution that should be estimated.
- directionstr
Direction to estimate the normal distribution. Options are “left” “right”
- parentGateAGgate object, optional, default: None
Parent population to apply the gating to. If no AGgate object is passed gating is applied to the ungated data frame.
- binsint, optional, default: 300
Defines the resolution of the density histogram from which the normal distribution is estimated.
- scalestr, optional, default: ‘linear’
Which scale to be used on axis.
WARNING: in contrast to many other functions, this actually affects more than plotting behaviour. See notes!
- Tint, optional, default: 1000
If scale is logicle, the threshold for linear-loglike transition.
Note
If a scale is changed from the default ‘linear’, the normal distribution is estimated on the transformed values (i.e. what you would see if plotting with this scale)
The returned values will then also be the mean and sigma of the transformed values.
To reverse transform see aligater.AGPlotRoutines.inverseTransformWrapper. When setting a treshold based on these values (such as mean+2*sigma), use transformed values and then invert.
Returns
- float, float
Mean, standard deviation
Examples
None currently.
- AGExperimental.penaltyValleySeek(fcs, xCol, x0, xEnd=None, parentGate=None, direction='up', phi=1, sigma=3, bins=300, scale='linear', T=1000)¶
Similar to valleySeek, but searches from a starting point in a given direction with penalty.
Prefers the starting position unless a new threshold is better even with penalty.
Parameters
- fcsAGClasses.AGSample object
Flow data loaded in an sample object.
- xColstr
Marker label.
- x0float
Starting position for search.
- xEndfloat, optional, default: None
Endpoint for search
- parentGateAGgate object, optional, default: None
Parent population to apply the gating to. If no AGgate object is passed gating is applied to the ungated data frame.
- direction, str, optional, default: ‘up’
Which direction to perform search.
‘up’ means from starting point to increasing values on the axis.
‘down’ means from starting point towards decreasing values on the axis.
- phifloat, optional, default: 1
Factor for the penalty function. See notes.
- sigmafloat, optional, default: 3
Smoothing factor of density function (kernel smooth).
- binsint, optional, default: 300
Number of bins in density histogram.
- scalestr, optional, default: ‘linear’
If plotting enabled, which scale to be used on axis.
- Tint, optional, default: 1000
If plotting enabled and scale is logicle, the threshold for linear-loglike transition
Returns
- float
Coordinate on axis with lowest density in given interval.
Note
The penalty function adds the absolute difference between starting coordinate and end coordinate multiplied by phi to the score of a solution.
Higher phi will apply heavier penalty for increasing distance from the starting position (larger ‘jumps’).
If phi is set very low (or 0) it’s likely that the best threshold will be found at the very end of the axis.
Note
The input heatmap is smoothed to avoid finding localized minima due to noise. This has the drawback that returned thresholds are approximate of the least dense point, the error is:
+- ( bin width / 2 )
Examples
None currently.
- AGExperimental.variableQuadGate(fcs, names, xCol, yCol, threshList, testRange, position, testSteps=20, parentGate=None, scale='linear', bins=300, sigma=2, T=1000, only_solution=False, scoreThresh=1, filePlot=None, QC=False, update=False)¶
A quadgate function that tests the threshold on one axis and attempts to find the least-dense point to set that limit.
Does not plot by itself, it does that through a subcall to customQuadGate
Parameters
- fcsAGClasses.AGSample object
Flow data loaded in a sample object.
- nameslist-like
- list of string with four names for the output gated populations in clockwise order from top-left;Top-left, top-right, bottom-right, bottom-left
- xCol, yColstr
Marker labels.
- threshListlist-like of float or int
Requires four float or int values. These are the thresholds in each direction for the gate.
In order; bottom x threshold, top x threshold, left y threshold, right y threshold. Either the x or y thresholds must be equal (that axis will be fix).
- testRangelist-like of float or int
Requires two float or int values, this is the interval in which the function will search for the least dense point to set the threshold.
- positionstr
Which direction to test.
Options are: ‘left’, ‘right’, ‘top’, ‘bottom’
- testSteps, int, optional, default: 20
The testRange will be equally divided into this many limits and each tested.
Increase this to increase precision.
- parentGateAGgate object, optional, default: None
Parent population to apply the gating to. If no AGgate object is passed gating is applied to the ungated data frame.
- scalestr, optional, default: ‘linear’
If plotting enabled, which scale to be used on both axis.
- Tint, optional, default: 1000
If plotting enabled and scale is logicle, the threshold for linear-loglike transition.
- binsint, optional, default: 300
Defines the resolution of the heatmap.
- sigmafloat, optional, default: 2
Smoothing factor for the heatmap.
- only_solutionbool, optional, default: False
Changes return behaviour.
If True the function does not plot and only returns the resulting float threshold.
- scoreThreshfloat, optional, default: 1
Changes the acceptance of new solutions.
A solution will be accepted if it’s better when multiplied by this value.
Can be both higher and lower than one.
- filePlotstr, optional, default: None
Option to plot the gate to file to specified path.
Warning: might overwrite stuff.
- updatebool, optional, default: False
If True will add the resulting gated population(s) to the sample objects gate list in adition to returning the gate object.
If False (default), returns an AGgate object without adding it to the sample object.
- QCbool, optional, default: False
If True, adds a downsampled image of the gating view to the gate object. These can be collected by an AGExperiment object if it’s QC flag is also True.
Returns
- AGClasses.AGgate, AGClasses.AGgate, AGClasses.AGgate, AGClasses.AGgate, float
Returns AGClasses.AGgate objects for the four gated populations and then the treshold with the highest score.
The populations are returned in clockwise order; top-left, top-right, bottom-right, bottom-left and then the highest scoring threshold.
- float
If only_solution is True, returns the threshold with the best score.
Note
Can be called iteratively to test many variations of the gate by setting only_solution to True.
A final call can then be made with only_solution set to False to apply the gate.
Examples
None currently.
Loading single files¶
Contains functions to collect fcs files recursively with filtering etc. Mainly use internally by AGExperiment, but can be used to load individual fcs files for exploring data and develop gating strategies.
- exception AGFileSystem.AliGaterError¶
- exception AGFileSystem.ExceptionTemplate¶
- AGFileSystem.getGatedVector(fcsDF, gate, vI=None, return_type='pdseries', dtype=<class 'numpy.float64'>)¶
Collects list-like of measured intensities for a population. Also see getGatedVectors
Parameters
- fcsDFpandas.DataFrame
Flow data loaded in a pandas DataFrame.
If data is stored in an AGSample object this can be retrieved by calling the sample, i.e. mysample().
- gatestr
Marker label.
- vIlist-like or AGgate object
Population to collect.
- return_typestr, optional, default: “pdseries”
Format of returned list-like, options are: “pdseries” “nparray”
- dtypeType, optional, default: numpy.float64
Data type of values in the returned listlike
Returns
List-like
Examples
None currently.
- AGFileSystem.getGatedVectors(fcsDF, gate1, gate2, vI=None, return_type='pdseries')¶
Collects list-like of measured intensities for a population.
Useful to collect both intensity coordinates for events in a view.
Parameters
- fcsDFpandas.DataFrame
Flow data loaded in a pandas DataFrame. If data is stored in an AGSample object this can be retrieved by calling the sample, i.e. mysample().
- gate1, gate2str
Marker labels.
- vIlist-like or AGgate object
Population to collect.
- return_typestr, optional, default: “pdseries”
Format of returned list-like, options are: “pdseries” “nparray”, matrix
- dtypeType, optional, default: numpy.float64
Data type of values in the returned list-like
Returns
- numpy.array[numpy.array, numpy.array]
If return type is ‘nparray’ numpy array of arrays in order: x-array, y-array
- numpy.array[list]
If return_type is ‘matrix’ returns a numpy array with list-likes of two; x-coord, y-coord
- list-like, list-like
if return_type is ‘pdseries’ returns two pandas.Series objects in order; X, Y
Examples
None currently.
- AGFileSystem.loadFCS(path, compensate=True, metadata=False, comp_matrix=None, return_type='index', markers=None, marker_names='label', ignore_minCell_filter=False, flourochrome_area_filter=False, sampling_resolution=32, nOfEvents=None)¶
Loads an fcs file from given path into an aligater.AGClasses.AGSample object.
Multiple settings dealing with compensation, checking for markers etc.
Parameters
- pathstr
Absolute path to .fcs file.
- compensatebool, default: True
Apply compensation based on the compensation matrix in file metadata.
- comp_matrixnp.ndarray or None, default: None
Optional passed external compensation matrix to apply for compensation.
- return_typestr, optional, default: “index”
Specifies if the loaded flow intensities should be return as an aligater.AGClasses.AGSample object (“agsample”) or a pandas.Dataframe (“index”).
- markerslist-like, optional, default: None
A list-like containing str names of the expected markers in the sample. Loading will fail if any marker is missing and None is instead returned.
- marker_namesstr, default: ‘label’
Options are ‘label’ or ‘color’
Specify which labelling style should be used for the flow data - the flourochrome marker or the labels, both are read from the .fcs files metadata.
- ignore_minCell_filterbool, default: False
If true, ignores the minCell filter for total sample events specified in aligater.AGConf.minCells and loads the sample anyway.
- flourochrome_area_filterbool, defaultFalse
Some machines/fcs files report Area, width and height for each flourochrome, some only report the area signal.
This flag enables filtering of the height and width channels for flourochromes and only return the area.
For side- and forward-scatter channels all three are always returned.
- sampling_resolutionint, default: 32
To-be-deprecated. Used to specify downsampling dimensions for batch runs through aligater.AGClasses.AGExperiments, this parameter is just passed through.
Will be moved into a
*args
**kwargs
style parameter.Should always be ignored if loading single files - it does nothing.
Returns
- dict (optional)
if metadata is True a dictionary object containing metadata information is returned first, in addition to the flow data.
- pandas.core.dataframe
If return type is ‘index’
- aligater.AGClasses.AGSample
If return_type is ‘agsample’ returns an AGSample object with the flow data loaded
Note
If any checks fail such as marker names were supplied and do not match marker names in the sample or the sample containing fewer total events than aligater.AGConf.minCell, None is instead returned.
Examples
None currently.
- AGFileSystem.loadHDF5sample(path, sampling_resolution=32)¶
Loads a HDF5 compressed fcs file, these are created with aligater.AGClasses.AGExperiment.create_HDF5_files This function is mainly intended for internal use in the aligater.AGClasses.AGExperiment.apply function.
Parameters
- pathstr
Absolute path to .fcs file.
- sampling_resolutionint, default: 32
To-be-deprecated. Used to specify downsampling dimensions for batch runs through aligater.AGClasses.AGExperiments, this parameter is just passed through.
Will be moved into a
*args
**kwargs
style parameter.Should always be ignored if loading single files - it does nothing.
Returns
aligater.AGClasses.AGSample
Plotting functions¶
Contains methods for visualisation of flow data.
- class AGPlotRoutines.BiLogFormatter(labelOnlyBase=True, minor_thresholds=None, linCutOff=20)¶
Base class for formatting ticks on a log or symlog scale. It may be instantiated directly, or subclassed.
Parameters
- basefloat, optional, default: 10.
Base of the logarithm used in all calculations.
- labelOnlyBasebool, optional, default: False
If True, label ticks only at integer powers of base. This is normally True for major ticks and False for minor ticks.
- minor_thresholds(subset, all), optional, default: (1, 0.4)
If labelOnlyBase is False, these two numbers control the labeling of ticks that are not at integer powers of base; normally these are the minor ticks. The controlling parameter is the log of the axis data range. In the typical case where base is 10 it is the number of decades spanned by the axis, so we can call it ‘numdec’. If
numdec <= all
, all minor ticks will be labeled. Ifall < numdec <= subset
, then only a subset of minor ticks will be labeled, so as to avoid crowding. Ifnumdec > subset
then no minor ticks will be labeled.- linthreshNone or float, optional, default: None
If a symmetric log scale is in use, its
linthresh
parameter must be supplied here.
Notes
The set_locs method must be called to enable the subsetting logic controlled by the
minor_thresholds
parameter. In some cases such as the colorbar, there is no distinction between major and minor ticks; the tick locations might be set manually, or by a locator that puts ticks at integer powers of base and at intermediate locations. For this situation, disable the minor_thresholds logic by usingminor_thresholds=(np.inf, np.inf)
, so that all ticks will be labeled. To disable labeling of minor ticks when ‘labelOnlyBase’ is False, useminor_thresholds=(0, 0)
. This is the default for the “classic” style.Examples
To label a subset of minor ticks when the view limits span up to 2 decades, and all of the ticks when zoomed in to 0.5 decades or less, use
minor_thresholds=(2, 0.5)
. To label all minor ticks when the view limits span up to 1.5 decades, useminor_thresholds=(1.5, 1.5)
.
- class AGPlotRoutines.BiLogLocator(subs=(1.0,), linCutOff=100)¶
Modified version of SymmetricalLogLocator. Only locates and formats tics for the plot view. Transform of underlying data and heatmap is handled outside matplotlib classes. Determine the tick locations for symmetric log axes
- set_params(subs=None, numticks=None)¶
Set parameters within this locator.
- tick_values(vmin, vmax)¶
Return the values of the located ticks given vmin and vmax.
Note
To get tick locations with the vmin and vmax values defined automatically for the associated
axis
simply call the Locator instance:>>> print(type(loc)) <type 'Locator'> >>> print(loc()) [1, 2, 3, 4]
- view_limits(vmin=None, vmax=None)¶
Try to choose the view limits intelligently
- class AGPlotRoutines.SymmetricalLogLocator(subs=None, linthresh=None)¶
Determine the tick locations for symmetric log axes
- set_params(subs=None, numticks=None)¶
Set parameters within this locator.
- tick_values(vmin, vmax)¶
Return the values of the located ticks given vmin and vmax.
Note
To get tick locations with the vmin and vmax values defined automatically for the associated
axis
simply call the Locator instance:>>> print(type(loc)) <type 'Locator'> >>> print(loc()) [1, 2, 3, 4]
- view_limits(vmin, vmax)¶
Try to choose the view limits intelligently
- AGPlotRoutines.decade_down(x, base=10)¶
floor x to the nearest lower decade
- AGPlotRoutines.decade_up(x, base=10)¶
ceil x to the nearest higher decade
- AGPlotRoutines.imagePCA(imlist)¶
Perform Principal Component Analysis of downsampled heatmap images, plots results. Takes a list-like of heatmap images, flattens them and calls image_pca.
Parameters
- X, list-like of list-like
Matrix with image data stored
Returns
None
Examples
None currently.
- AGPlotRoutines.image_pca(X)¶
Principal Component Analysis of flattened heatmap images, main purpose is to be called internally by imagePCA
Parameters
- X, list-like
List-like matrix with image data stored as flattened arrays in rows.
Returns
- List-like
Projection matrix (with important dimensions first)
- Float
Variance
- Float
Mean
Examples
None currently.
- AGPlotRoutines.inverseTransformWrapper(vX, T, scale)¶
General function for converting values or arrays of values from AliGater scales; bilog and logicle back to linear values. See transformWrapper to convert into AliGater scales.
Parameters
- vX, list-like or float/int
value or values to convert.
- T, int/float
Threshold for linear-log transition for bilog and logicle scales
- scale, str
Scale to convert from; ‘bilog’ or ‘logicle’
- Returns
If a scalar is passed, scalar If list like is passed, list
Examples
None currently.
- class AGPlotRoutines.logicleFormatter(labelOnlyBase=True, minor_thresholds=None, linCutOff=1000)¶
Base class for formatting ticks on a logicle scale. Only locates and formats tics for the plot view. Transform of underlying data and heatmap is handled outside matplotlib. Modfied version of LogFormatter that covers normal usecases of the logicle scale Only defined with formatting ticlabels for data in range -1 000 000 < x The passed parameters only affect plotting of the log-part of the scale
Parameters¶
- labelOnlyBasebool, optional, default: False
If True, label ticks only at integer powers of base. This is normally True for major ticks and False for minor ticks.
- minor_thresholds(subset, all), optional, default: (1, 0.4)
If labelOnlyBase is False, these two numbers control the labeling of ticks that are not at integer powers of base; normally these are the minor ticks. The controlling parameter is the log of the axis data range. In the typical case where base is 10 it is the number of decades spanned by the axis, so we can call it ‘numdec’. If
numdec <= all
, all minor ticks will be labeled. Ifall < numdec <= subset
, then only a subset of minor ticks will be labeled, so as to avoid crowding. Ifnumdec > subset
then no minor ticks will be labeled.- linthreshfloat, optional, default: 1000
The threshold for the logicle scale change from linear-like to log-like scaling
Notes¶
The set_locs method must be called to enable the subsetting logic controlled by the
minor_thresholds
parameter. In some cases such as the colorbar, there is no distinction between major and minor ticks; the tick locations might be set manually, or by a locator that puts ticks at integer powers of base and at intermediate locations. For this situation, disable the minor_thresholds logic by usingminor_thresholds=(np.inf, np.inf)
, so that all ticks will be labeled. To disable labeling of minor ticks when ‘labelOnlyBase’ is False, useminor_thresholds=(0, 0)
. This is the default for the “classic” style. Examples ——– To label a subset of minor ticks when the view limits span up to 2 decades, and all of the ticks when zoomed in to 0.5 decades or less, useminor_thresholds=(2, 0.5)
. To label all minor ticks when the view limits span up to 1.5 decades, useminor_thresholds=(1.5, 1.5)
.
- class AGPlotRoutines.logicleLocator(linCutOff=1000, subs=(1.0,), numdecs=4, numticks=None)¶
Determine the tick locations for logicle axes based on LogLocator. Only locates and formats tics for the plot view. Transform of underlying data and heatmap is handled outside matplotlib. Hacked version of LogLogator that covers normal usecases of the logicle scale Only defined with ticlocations for data in range -1 000 000 < x
- set_params(subs=None, numdecs=4, numticks=None)¶
Set parameters within this locator.
- subs(subs)¶
set the minor ticks for the log scaling every base**i*subs[j]
- tick_values(vmin, vmax)¶
Return the values of the located ticks given vmin and vmax.
Note
To get tick locations with the vmin and vmax values defined automatically for the associated
axis
simply call the Locator instance:>>> print(type(loc)) <type 'Locator'> >>> print(loc()) [1, 2, 3, 4]
- view_limits(vmin=None, vmax=None)¶
Try to choose the view limits intelligently
- AGPlotRoutines.plotHeatmap(fcsDF, x, y, vI=<object object>, bins=300, scale='linear', xscale='linear', yscale='linear', thresh=1000, aspect='auto', **kwargs)¶
Core plotting function of AliGater. Mainly intended to be called internally, but may be called directly. Only plots. No gating functionalities.
Parameters
- fcsDFpandas.DataFrame
Flow data loaded in a pandas DataFrame.
- x, ystr
Marker labels.
- vIlist-like, optional
list-like index of events in the fcsDF that correspond to the parent population. Defaults to plotting all events in fcsDF.
- binsint, optional, default: 300
Resolution of the plotted heatmap.
- scalestr, optional, default: ‘linear’
Which scale to be used on both axes.
- xscalestr, optional, default: ‘linear’
Which scale to be used on the x-axis.
- yscalestr, optional, default: ‘linear’
Which scale to be used on the y-axis.
- Tint, optional, default: 1000
If the threshold for linear-loglike transition for bilog or logicle scales.
- aspectstr
Aspect of plotted heatmap. Passed on to matplotlib.pyplot.imshow()
Keyword arguments
- cmapmatplotlib.colors.Colormap or str, default: ‘jet’
Color map to use. Either string name of existing matplotlib colormap, or a colormap object.
- rcParamsmatplotlib.rcParams
Overrides rcParams with the passed rcParams object.
- mask_wherefloat,int, default0
scalar of heatmap values to mask, these become white when plotted
Returns
- fig, matplotlib.pyplot.Figure
matplotlib Figure object
- ax. matplotlib.pyplot.Axes
matplotlib axes object
Examples
None currently.
- AGPlotRoutines.plot_densityFunc(fcsDF, xCol, vI=<object object>, sigma=3, bins=300, scale='linear', T=1000, *args, **kwargs)¶
General function for converting values or arrays of values from AliGater scales; bilog and logicle back to linear values. See transformWrapper to convert into AliGater scales.
Parameters
- vX, list-like or float/int
value or values to convert.
- T, int/float
Threshold for linear-log transition for bilog and logicle scales
- scale, str
Scale to convert from; ‘bilog’ or ‘logicle’
- Returns
If a scalar is passed, scalar If list like is passed, list
Examples
None currently.
- AGPlotRoutines.transformWrapper(vX, T, scale)¶
General function for converting values or arrays of values to AliGater scales; bilog and logicle. See inverseTransformWrapper to convert the other way around.
Parameters
- vX, list-like or float/int
value or values to convert.
- T, int/float
Threshold for linear-log transition for bilog and logicle scales
- scale, str
Scale to convert to; ‘bilog’ or ‘logicle’
- Returns
If a scalar is passed, scalar If list like is passed, list
Examples
None currently.