Search is not available for this dataset
text
stringlengths
75
104k
def rangecalcx(x, pad=0.05): """ Calculate padded range limits for axes. """ mn = np.nanmin(x) mx = np.nanmax(x) rn = mx - mn return (mn - pad * rn, mx + pad * rn)
def bland_altman(x, y, interval=None, indep_conf=None, ax=None, c=None, **kwargs): """ Draw a Bland-Altman plot of x and y data. https://en.wikipedia.org/wiki/Bland%E2%80%93Altman_plot Parameters ---------- x, y : array-like x and y data to compare. interval : float ...
def autorange(t, sig, gwin=7, swin=None, win=30, on_mult=(1.5, 1.), off_mult=(1., 1.5), nbin=10, transform='log', thresh=None): """ Automatically separates signal and background in an on/off data stream. **Step 1: Thresholding.** The background signal is determined using a g...
def autorange_components(t, sig, transform='log', gwin=7, swin=None, win=30, on_mult=(1.5, 1.), off_mult=(1., 1.5), thresh=None): """ Returns the components underlying the autorange algorithm. Returns ------- t : array-like Time axis (indepe...
def elements(all_isotopes=True): """ Loads a DataFrame of all elements and isotopes. Scraped from https://www.webelements.com/ Returns ------- pandas DataFrame with columns (element, atomic_number, isotope, atomic_weight, percent) """ el = pd.read_pickle(pkgrs.resource_filename('latool...
def calc_M(molecule): """ Returns molecular weight of molecule. Where molecule is in standard chemical notation, e.g. 'CO2', 'HCO3' or B(OH)4 Returns ------- molecular_weight : float """ # load periodic table els = elements() # define regexs parens = re.compile('\(([A...
def gen_keywords(*args: Union[ANSIColors, ANSIStyles], **kwargs: Union[ANSIColors, ANSIStyles]) -> tuple: '''generate single escape sequence mapping.''' fields: tuple = tuple() values: tuple = tuple() for tpl in args: fields += tpl._fields values += tpl for prefix, tpl in kwargs.item...
def zero_break(stack: tuple) -> tuple: '''Handle Resets in input stack. Breaks the input stack if a Reset operator (zero) is encountered. ''' reducer = lambda x, y: tuple() if y == 0 else x + (y,) return reduce(reducer, stack, tuple())
def annihilate(predicate: tuple, stack: tuple) -> tuple: '''Squash and reduce the input stack. Removes the elements of input that match predicate and only keeps the last match at the end of the stack. ''' extra = tuple(filter(lambda x: x not in predicate, stack)) head = reduce(lambda x, y: y if ...
def dedup(stack: tuple) -> tuple: '''Remove duplicates from the stack in first-seen order.''' # Initializes with an accumulator and then reduces the stack with first match # deduplication. reducer = lambda x, y: x if y in x else x + (y,) return reduce(reducer, stack, tuple())
def gauss_weighted_stats(x, yarray, x_new, fwhm): """ Calculate gaussian weigted moving mean, SD and SE. Parameters ---------- x : array-like The independent variable yarray : (n,m) array Where n = x.size, and m is the number of dependent variables to smooth. x_new :...
def gauss(x, *p): """ Gaussian function. Parameters ---------- x : array_like Independent variable. *p : parameters unpacked to A, mu, sigma A = amplitude, mu = centre, sigma = width Return ------ array_like gaussian descriped by *p. """ A, mu, sigma = p...
def stderr(a): """ Calculate the standard error of a. """ return np.nanstd(a) / np.sqrt(sum(np.isfinite(a)))
def H15_mean(x): """ Calculate the Huber (H15) Robust mean of x. For details, see: http://www.cscjp.co.jp/fera/document/ANALYSTVol114Decpgs1693-97_1989.pdf http://www.rsc.org/images/robust-statistics-technical-brief-6_tcm18-214850.pdf """ mu = np.nanmean(x) sd = np.nanstd(x) * 1...
def H15_se(x): """ Calculate the Huber (H15) Robust standard deviation of x. For details, see: http://www.cscjp.co.jp/fera/document/ANALYSTVol114Decpgs1693-97_1989.pdf http://www.rsc.org/images/robust-statistics-technical-brief-6_tcm18-214850.pdf """ sd = H15_std(x) return sd / ...
def reproduce(past_analysis, plotting=False, data_folder=None, srm_table=None, custom_stat_functions=None): """ Reproduce a previous analysis exported with :func:`latools.analyse.minimal_export` For normal use, supplying `log_file` and specifying a plotting option should be enough to repr...
def _get_samples(self, subset=None): """ Helper function to get sample names from subset. Parameters ---------- subset : str Subset name. If None, returns all samples. Returns ------- List of sample names """ if subset is None...
def autorange(self, analyte='total_counts', gwin=5, swin=3, win=20, on_mult=[1., 1.5], off_mult=[1.5, 1], transform='log', ploterrs=True, focus_stage='despiked'): """ Automatically separates signal and background data regions. Automatically detect signal and ...
def find_expcoef(self, nsd_below=0., plot=False, trimlim=None, autorange_kwargs={}): """ Determines exponential decay coefficient for despike filter. Fits an exponential decay function to the washout phase of standards to determine the washout time of your laser cel...
def despike(self, expdecay_despiker=False, exponent=None, noise_despiker=True, win=3, nlim=12., exponentplot=False, maxiter=4, autorange_kwargs={}, focus_stage='rawdata'): """ Despikes data with exponential decay and noise filters. Parameters ---------- ...
def get_background(self, n_min=10, n_max=None, focus_stage='despiked', bkg_filter=False, f_win=5, f_n_lim=3): """ Extract all background data from all samples on universal time scale. Used by both 'polynomial' and 'weightedmean' methods. Parameters ---------- n_min : int...
def bkg_calc_weightedmean(self, analytes=None, weight_fwhm=None, n_min=20, n_max=None, cstep=None, bkg_filter=False, f_win=7, f_n_lim=3, focus_stage='despiked'): """ Background calculation using a gaussian weighted mean. Parameters ...
def bkg_calc_interp1d(self, analytes=None, kind=1, n_min=10, n_max=None, cstep=None, bkg_filter=False, f_win=7, f_n_lim=3, focus_stage='despiked'): """ Background calculation using a 1D interpolation. scipy.interpolate.interp1D is used for interpolation. Param...
def bkg_subtract(self, analytes=None, errtype='stderr', focus_stage='despiked'): """ Subtract calculated background from data. Must run bkg_calc first! Parameters ---------- analytes : str or iterable Which analyte(s) to subtract. errtype : str ...
def correct_spectral_interference(self, target_analyte, source_analyte, f): """ Correct spectral interference. Subtract interference counts from target_analyte, based on the intensity of a source_analayte and a known fractional contribution (f). Correction takes the form: ...
def bkg_plot(self, analytes=None, figsize=None, yscale='log', ylim=None, err='stderr', save=True): """ Plot the calculated background. Parameters ---------- analytes : str or iterable Which analyte(s) to plot. figsize : tuple The ...
def ratio(self, internal_standard=None): """ Calculates the ratio of all analytes to a single analyte. Parameters ---------- internal_standard : str The name of the analyte to divide all other analytes by. Returns ------- None ...
def srm_id_auto(self, srms_used=['NIST610', 'NIST612', 'NIST614'], n_min=10, reload_srm_database=False): """ Function for automarically identifying SRMs Parameters ---------- srms_used : iterable Which SRMs have been used. Must match SRM names in SRM ...
def calibrate(self, analytes=None, drift_correct=True, srms_used=['NIST610', 'NIST612', 'NIST614'], zero_intercept=True, n_min=10, reload_srm_database=False): """ Calibrates the data to measured SRM values. Assumes that y intercept is zero. Parameter...
def make_subset(self, samples=None, name=None): """ Creates a subset of samples, which can be treated independently. Parameters ---------- samples : str or array - like Name of sample, or list of sample names. name : (optional) str or number The n...
def zeroscreen(self, focus_stage=None): """ Remove all points containing data below zero (which are impossible!) """ if focus_stage is None: focus_stage = self.focus_stage for s in self.data.values(): ind = np.ones(len(s.Time), dtype=bool) for...
def filter_threshold(self, analyte, threshold, samples=None, subset=None): """ Applies a threshold filter to the data. Generates two filters above and below the threshold value for a given analyte. Parameters ---------- analyte : str ...
def filter_threshold_percentile(self, analyte, percentiles, level='population', filt=False, samples=None, subset=None): """ Applies a threshold filter to the data. Generates two filters above and below the threshold value for a given analyte. ...
def filter_gradient_threshold_percentile(self, analyte, percentiles, level='population', win=15, filt=False, samples=None, subset=None): """ Calculate a gradient threshold filter to the data. Generates two filters above and below the threshold value ...
def filter_clustering(self, analytes, filt=False, normalise=True, method='kmeans', include_time=False, samples=None, sort=True, subset=None, level='sample', min_data=10, **kwargs): """ Applies an n - dimensional clustering filter to the data. ...
def fit_classifier(self, name, analytes, method, samples=None, subset=None, filt=True, sort_by=0, **kwargs): """ Create a clustering classifier based on all samples, or a subset. Parameters ---------- name : str The name of the classifier. ...
def apply_classifier(self, name, samples=None, subset=None): """ Apply a clustering classifier based on all samples, or a subset. Parameters ---------- name : str The name of the classifier to apply. subset : str The subset of samples to apply the...
def filter_correlation(self, x_analyte, y_analyte, window=None, r_threshold=0.9, p_threshold=0.05, filt=True, samples=None, subset=None): """ Applies a correlation filter to the data. Calculates a rolling correlation between every `window` p...
def correlation_plots(self, x_analyte, y_analyte, window=15, filt=True, recalc=False, samples=None, subset=None, outdir=None): """ Plot the local correlation between two analytes. Parameters ---------- x_analyte, y_analyte : str The names of the x and y analytes to c...
def filter_on(self, filt=None, analyte=None, samples=None, subset=None, show_status=False): """ Turns data filters on for particular analytes and samples. Parameters ---------- filt : optional, str or array_like Name, partial name or list of names of filters. Support...
def filter_off(self, filt=None, analyte=None, samples=None, subset=None, show_status=False): """ Turns data filters off for particular analytes and samples. Parameters ---------- filt : optional, str or array_like Name, partial name or list of names of filters. Suppo...
def filter_status(self, sample=None, subset=None, stds=False): """ Prints the current status of filters for specified samples. Parameters ---------- sample : str Which sample to print. subset : str Specify a subset stds : bool ...
def filter_clear(self, samples=None, subset=None): """ Clears (deletes) all data filters. """ if samples is not None: subset = self.make_subset(samples) samples = self._get_samples(subset) for s in samples: self.data[s].filt.clear()
def filter_defragment(self, threshold, mode='include', filt=True, samples=None, subset=None): """ Remove 'fragments' from the calculated filter Parameters ---------- threshold : int Contiguous data regions that contain this number or fewer points are cons...
def filter_exclude_downhole(self, threshold, filt=True, samples=None, subset=None): """ Exclude all points down-hole (after) the first excluded data. Parameters ---------- threhold : int The minimum number of contiguous excluded data points that must exis...
def filter_trim(self, start=1, end=1, filt=True, samples=None, subset=None): """ Remove points from the start and end of filter regions. Parameters ---------- start, end : int The number of points to remove from the start and end of the specified ...
def filter_nremoved(self, filt=True, quiet=False): """ Report how many data are removed by the active filters. """ rminfo = {} for n in self.subsets['All_Samples']: s = self.data[n] rminfo[n] = s.filt_nremoved(filt) if not quiet: maxL =...
def optimise_signal(self, analytes, min_points=5, threshold_mode='kde_first_max', threshold_mult=1., x_bias=0, filt=True, weights=None, mode='minimise', samples=None, subset=None): """ Optimise data selectio...
def optimisation_plots(self, overlay_alpha=0.5, samples=None, subset=None, **kwargs): """ Plot the result of signal_optimise. `signal_optimiser` must be run first, and the output stored in the `opt` attribute of the latools.D object. Parameters ---------- d : la...
def set_focus(self, focus_stage=None, samples=None, subset=None): """ Set the 'focus' attribute of the data file. The 'focus' attribute of the object points towards data from a particular stage of analysis. It is used to identify the 'working stage' of the data. Processing funct...
def get_focus(self, filt=False, samples=None, subset=None, nominal=False): """ Collect all data from all samples into a single array. Data from standards is not collected. Parameters ---------- filt : str, dict or bool Either logical filter expression contain...
def get_gradients(self, analytes=None, win=15, filt=False, samples=None, subset=None, recalc=True): """ Collect all data from all samples into a single array. Data from standards is not collected. Parameters ---------- filt : str, dict or bool Either logical ...
def gradient_histogram(self, analytes=None, win=15, filt=False, bins=None, samples=None, subset=None, recalc=True, ncol=4): """ Plot a histogram of the gradients in all samples. Parameters ---------- filt : str, dict or bool Either logical filter expression contained...
def crossplot(self, analytes=None, lognorm=True, bins=25, filt=False, samples=None, subset=None, figsize=(12, 12), save=False, colourful=True, mode='hist2d', **kwargs): """ Plot analytes against each other. Parameters ---------- ...
def gradient_crossplot(self, analytes=None, win=15, lognorm=True, bins=25, filt=False, samples=None, subset=None, figsize=(12, 12), save=False, colourful=True, mode='hist2d', recalc=True, **kwargs): """ Plot analyte gradien...
def histograms(self, analytes=None, bins=25, logy=False, filt=False, colourful=True): """ Plot histograms of analytes. Parameters ---------- analytes : optional, array_like or str The analyte(s) to plot. Defaults to all analytes. bins : int...
def filter_effect(self, analytes=None, stats=['mean', 'std'], filt=True): """ Quantify the effects of the active filters. Parameters ---------- analytes : str or list Which analytes to consider. stats : list Which statistics to calculate. ...
def trace_plots(self, analytes=None, samples=None, ranges=False, focus=None, outdir=None, filt=None, scale='log', figsize=[10, 4], stats=False, stat='nanmean', err='nanstd', subset='All_Analyses'): """ Plot analytes as a function of time. ...
def gradient_plots(self, analytes=None, win=15, samples=None, ranges=False, focus=None, outdir=None, figsize=[10, 4], subset='All_Analyses'): """ Plot analyte gradients as a function of time. Parameters ---------- analytes : optional...
def filter_reports(self, analytes, filt_str='all', nbin=5, samples=None, outdir=None, subset='All_Samples'): """ Plot filter reports for all filters that contain ``filt_str`` in the name. """ if outdir is None: outdir = self.report_dir + '/filte...
def sample_stats(self, analytes=None, filt=True, stats=['mean', 'std'], eachtrace=True, csf_dict={}): """ Calculate sample statistics. Returns samples, analytes, and arrays of statistics of shape (samples, analytes). Statistics are calculated ...
def statplot(self, analytes=None, samples=None, figsize=None, stat='mean', err='std', subset=None): """ Function for visualising per-ablation and per-sample means. Parameters ---------- analytes : str or iterable Which analyte(s) to plot samp...
def getstats(self, save=True, filename=None, samples=None, subset=None, ablation_time=False): """ Return pandas dataframe of all sample statistics. """ slst = [] if samples is not None: subset = self.make_subset(samples) samples = self._get_samples(subset) ...
def _minimal_export_traces(self, outdir=None, analytes=None, samples=None, subset='All_Analyses'): """ Used for exporting minimal dataset. DON'T USE. """ if analytes is None: analytes = self.analytes elif isinstance(analytes, str): ...
def export_traces(self, outdir=None, focus_stage=None, analytes=None, samples=None, subset='All_Analyses', filt=False, zip_archive=False): """ Function to export raw data. Parameters ---------- outdir : str directory to save toe traces. Defaults...
def save_log(self, directory=None, logname=None, header=None): """ Save analysis.lalog in specified location """ if directory is None: directory = self.export_dir if not os.path.isdir(directory): directory = os.path.dirname(directory) if logname i...
def minimal_export(self, target_analytes=None, path=None): """ Exports a analysis parameters, standard info and a minimal dataset, which can be imported by another user. Parameters ---------- target_analytes : str or iterable Which analytes to include in the ...
def by_regex(file, outdir=None, split_pattern=None, global_header_rows=0, fname_pattern=None, trim_tail_lines=0, trim_head_lines=0): """ Split one long analysis file into multiple smaller ones. Parameters ---------- file : str The path to the file you want to split. outdir : str ...
def long_file(data_file, dataformat, sample_list, savedir=None, srm_id=None, **autorange_args): """ TODO: Check for existing files in savedir, don't overwrite? """ if isinstance(sample_list, str): if os.path.exists(sample_list): sample_list = np.genfromtxt(sample_list, dtype=str) ...
def fold_map(self, fa: F[A], z: B, f: Callable[[A], B], g: Callable[[Z, B], Z]=operator.add) -> Z: ''' map `f` over the traversable, then fold over the result using the supplied initial element `z` and operation `g`, defaulting to addition for the latter. ''' mapped = Functor.fat...
def pca_calc(nc, d): """ Calculates pca of d. Parameters ---------- nc : int Number of components d : np.ndarray An NxM array, containing M observations of N variables. Data must be floats. Can contain NaN values. Returns ------- pca, dt : tuple ...
def pca_plot(pca, dt, xlabs=None, mode='scatter', lognorm=True): """ Plot a fitted PCA, and all components. """ nc = pca.n_components f = np.arange(pca.n_features_) cs = list(itertools.combinations(range(nc), 2)) ind = ~np.apply_along_axis(any, 1, np.isnan(dt)) cylim = (pca.co...
def calc_windows(fn, s, min_points): """ Apply fn to all contiguous regions in s that have at least min_points. """ max_points = np.sum(~np.isnan(s)) n_points = max_points - min_points out = np.full((n_points, s.size), np.nan) # skip nans, for speed ind = ~np.isnan(s) s = s[ind] ...
def calc_window_mean_std(s, min_points, ind=None): """ Apply fn to all contiguous regions in s that have at least min_points. """ max_points = np.sum(~np.isnan(s)) n_points = max_points - min_points mean = np.full((n_points, s.size), np.nan) std = np.full((n_points, s.size), np.nan) # ...
def bayes_scale(s): """ Remove mean and divide by standard deviation, using bayes_kvm statistics. """ if sum(~np.isnan(s)) > 1: bm, bv, bs = bayes_mvs(s[~np.isnan(s)]) return (s - bm.statistic) / bs.statistic else: return np.full(s.shape, np.nan)
def median_scaler(s): """ Remove median, divide by IQR. """ if sum(~np.isnan(s)) > 2: ss = s[~np.isnan(s)] median = np.median(ss) IQR = np.diff(np.percentile(ss, [25, 75])) return (s - median) / IQR else: return np.full(s.shape, np.nan)
def signal_optimiser(d, analytes, min_points=5, threshold_mode='kde_first_max', threshold_mult=1., x_bias=0, weights=None, ind=None, mode='minimise'): """ Optimise data selection based on specified analytes. Identifies the longest possible cont...
def optimisation_plot(d, overlay_alpha=0.5, **kwargs): """ Plot the result of signal_optimise. `signal_optimiser` must be run first, and the output stored in the `opt` attribute of the latools.D object. Parameters ---------- d : latools.D object A latools data object. overlay_a...
def noise_despike(sig, win=3, nlim=24., maxiter=4): """ Apply standard deviation filter to remove anomalous values. Parameters ---------- win : int The window used to calculate rolling statistics. nlim : float The number of standard deviations above the rolling mean abov...
def expdecay_despike(sig, expdecay_coef, tstep, maxiter=3): """ Apply exponential decay filter to remove physically impossible data based on instrumental washout. The filter is re-applied until no more points are removed, or maxiter is reached. Parameters ---------- exponent : float Ex...
def _flat_map(self, f: Callable): ''' **f** must return the same stack type as **self.value** has. Iterates over the effects, sequences the inner instance successively to the top and joins with the outer instance. Example: List(Right(Just(1))) => List(Right(Just(List(Right(Just(5...
def add(self, name, filt, info='', params=(), setn=None): """ Add filter. Parameters ---------- name : str filter name filt : array_like boolean filter array info : str informative description of the filter params : tup...
def remove(self, name=None, setn=None): """ Remove filter. Parameters ---------- name : str name of the filter to remove setn : int or True int: number of set to remove True: remove all filters in set that 'name' belongs to Re...
def clear(self): """ Clear all filters. """ self.components = {} self.info = {} self.params = {} self.switches = {} self.keys = {} self.index = {} self.sets = {} self.maxset = -1 self.n = 0 for a in self.analytes: ...
def clean(self): """ Remove unused filters. """ for f in sorted(self.components.keys()): unused = not any(self.switches[a][f] for a in self.analytes) if unused: self.remove(f)
def on(self, analyte=None, filt=None): """ Turn on specified filter(s) for specified analyte(s). Parameters ---------- analyte : optional, str or array_like Name or list of names of analytes. Defaults to all analytes. filt : optional. int, str or ...
def make(self, analyte): """ Make filter for specified analyte(s). Filter specified in filt.switches. Parameters ---------- analyte : str or array_like Name or list of names of analytes. Returns ------- array_like boolean...
def fuzzmatch(self, fuzzkey, multi=False): """ Identify a filter by fuzzy string matching. Partial ('fuzzy') matching performed by `fuzzywuzzy.fuzzy.ratio` Parameters ---------- fuzzkey : str A string that partially matches one filter name more than the othe...
def make_fromkey(self, key): """ Make filter from logical expression. Takes a logical expression as an input, and returns a filter. Used for advanced filtering, where combinations of nested and/or filters are desired. Filter names must exactly match the names listed by print(fil...
def make_keydict(self, analyte=None): """ Make logical expressions describing the filter(s) for specified analyte(s). Parameters ---------- analyte : optional, str or array_like Name or list of names of analytes. Defaults to all analytes. Returns...
def grab_filt(self, filt, analyte=None): """ Flexible access to specific filter using any key format. Parameters ---------- f : str, dict or bool either logical filter expression, dict of expressions, or a boolean analyte : str name of...
def get_components(self, key, analyte=None): """ Extract filter components for specific analyte(s). Parameters ---------- key : str string present in one or more filter names. e.g. 'Al27' will return all filters with 'Al27' in their names. ...
def get_info(self): """ Get info for all filters. """ out = '' for k in sorted(self.components.keys()): out += '{:s}: {:s}'.format(k, self.info[k]) + '\n' return(out)
def read_data(data_file, dataformat, name_mode): """ Load data_file described by a dataformat dict. Parameters ---------- data_file : str Path to data file, including extension. dataformat : dict A dataformat dict, see example below. name_mode : str How to identyfy s...
def residual_plots(df, rep_stats=None, els=['Mg', 'Sr', 'Al', 'Mn', 'Fe', 'Cu', 'Zn', 'B']): """ Function for plotting Test User and LAtools data comparison. Parameters ---------- df : pandas.DataFrame A dataframe containing reference ('X/Ca_r'), test user ('X/Ca_t') and LAtools ('...
def comparison_stats(df, els=None): """ Compute comparison stats for test and LAtools data. Population-level similarity assessed by a Kolmogorov-Smirnov test. Individual similarity assessed by a pairwise Wilcoxon signed rank test. Trends in residuals assessed by regression analysis, w...
def _log(func): """ Function for logging method calls and parameters """ @wraps(func) def wrapper(self, *args, **kwargs): a = func(self, *args, **kwargs) self.log.append(func.__name__ + ' :: args={} kwargs={}'.format(args, kwargs)) return a return wrapper
def write_logfile(log, header, file_name): """ Write and analysis log to a file. Parameters ---------- log : list latools.analyse analysis log header : list File header lines. file_name : str Destination file. If no file extension specified, uses '.lalog' ...
def read_logfile(log_file): """ Reads an latools analysis.log file, and returns dicts of arguments. Parameters ---------- log_file : str Path to an analysis.log file produced by latools. Returns ------- runargs, paths : tuple Two dictionaries. runargs contains all t...
def zipdir(directory, name=None, delete=False): """ Compresses the target directory, and saves it to ../name.zip Parameters ---------- directory : str Path to the directory you want to compress. Compressed file will be saved at directory/../name.zip name : str (default=None) ...