INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Keep user. email in sync with user. emailaddress_set.
def sync_user_email_addresses(user): """ Keep user.email in sync with user.emailaddress_set. Under some circumstances the user.email may not have ended up as an EmailAddress record, e.g. in the case of manually created admin users. """ from .models import EmailAddress email = user_email...
Return list of users by email address
def filter_users_by_email(email): """Return list of users by email address Typically one, at most just a few in length. First we look through EmailAddress table, than customisable User model table. Add results together avoiding SQL joins and deduplicate. """ from .models import EmailAddress ...
This should return a string.
def user_pk_to_url_str(user): """ This should return a string. """ User = get_user_model() if issubclass(type(User._meta.pk), models.UUIDField): if isinstance(user.pk, six.string_types): return user.pk return user.pk.hex ret = user.pk if isinstance(ret, six.integ...
allauth needs tokens for OAuth based providers. So let s setup some dummy tokens
def setup_dummy_social_apps(sender, **kwargs): """ `allauth` needs tokens for OAuth based providers. So let's setup some dummy tokens """ from allauth.socialaccount.providers import registry from allauth.socialaccount.models import SocialApp from allauth.socialaccount.providers.oauth.provide...
Return value dumped to string.
def value_from_object(self, obj): """Return value dumped to string.""" val = super(JSONField, self).value_from_object(obj) return self.get_prep_value(val)
See e - mail verification method
def EMAIL_VERIFICATION(self): """ See e-mail verification method """ ret = self._setting("EMAIL_VERIFICATION", self.EmailVerificationMethod.OPTIONAL) # Deal with legacy (boolean based) setting if ret is True: ret = self.EmailVerific...
Minimum password Length
def PASSWORD_MIN_LENGTH(self): """ Minimum password Length """ from django.conf import settings ret = None if not settings.AUTH_PASSWORD_VALIDATORS: ret = self._setting("PASSWORD_MIN_LENGTH", 6) return ret
Small helper function to call a function ( map_function ) on a list of data chunks ( chunk_list ) and convert the results into a flattened list. This function is used to send chunks of data with a size larger than 1 to the workers in parallel and process these on the worker.
def _function_with_partly_reduce(chunk_list, map_function, kwargs): """ Small helper function to call a function (map_function) on a list of data chunks (chunk_list) and convert the results into a flattened list. This function is used to send chunks of data with a size larger than 1 to the ...
This generator chunks a list of data into slices of length chunk_size. If the chunk_size is not a divider of the data length the last slice will be shorter than chunk_size.
def partition(data, chunk_size): """ This generator chunks a list of data into slices of length chunk_size. If the chunk_size is not a divider of the data length, the last slice will be shorter than chunk_size. :param data: The data to chunk. :type data: list :param chun...
Calculates the best chunk size for a list of length data_length. The current implemented formula is more or less an empirical result for multiprocessing case on one machine.: param data_length: A length which defines how many calculations there need to be.: type data_length: int: return: the calculated chunk size: rtyp...
def calculate_best_chunk_size(self, data_length): """ Calculates the best chunk size for a list of length data_length. The current implemented formula is more or less an empirical result for multiprocessing case on one machine. :param data_length: A length which defines how man...
This method contains the core functionality of the DistributorBaseClass class. It maps the map_function to each element of the data and reduces the results to return a flattened list.
def map_reduce(self, map_function, data, function_kwargs=None, chunk_size=None, data_length=None): """ This method contains the core functionality of the DistributorBaseClass class. It maps the map_function to each element of the data and reduces the results to return a flattened list. ...
Calculates the features in a sequential fashion by pythons map command
def distribute(self, func, partitioned_chunks, kwargs): """ Calculates the features in a sequential fashion by pythons map command :param func: the function to send to each worker. :type func: callable :param partitioned_chunks: The list of data chunks - each element is again ...
Calculates the features in a parallel fashion by distributing the map command to the dask workers on a local machine
def distribute(self, func, partitioned_chunks, kwargs): """ Calculates the features in a parallel fashion by distributing the map command to the dask workers on a local machine :param func: the function to send to each worker. :type func: callable :param partitioned_chun...
Uses the number of dask workers in the cluster ( during execution time meaning when you start the extraction ) to find the optimal chunk_size.
def calculate_best_chunk_size(self, data_length): """ Uses the number of dask workers in the cluster (during execution time, meaning when you start the extraction) to find the optimal chunk_size. :param data_length: A length which defines how many calculations there need to be. ...
Calculates the features in a parallel fashion by distributing the map command to a thread pool
def distribute(self, func, partitioned_chunks, kwargs): """ Calculates the features in a parallel fashion by distributing the map command to a thread pool :param func: the function to send to each worker. :type func: callable :param partitioned_chunks: The list of data chunks - ...
Collects the result from the workers and closes the thread pool.
def close(self): """ Collects the result from the workers and closes the thread pool. """ self.pool.close() self.pool.terminate() self.pool.join()
Creates a mapping from kind names to fc_parameters objects ( which are itself mappings from feature calculators to settings ) to extract only the features contained in the columns. To do so for every feature name in columns this method
def from_columns(columns, columns_to_ignore=None): """ Creates a mapping from kind names to fc_parameters objects (which are itself mappings from feature calculators to settings) to extract only the features contained in the columns. To do so, for every feature name in columns this method 1. sp...
Roll 1D array elements. Improves the performance of numpy. roll () by reducing the overhead introduced from the flexibility of the numpy. roll () method such as the support for rolling over multiple dimensions. Elements that roll beyond the last position are re - introduced at the beginning. Similarly elements that rol...
def _roll(a, shift): """ Roll 1D array elements. Improves the performance of numpy.roll() by reducing the overhead introduced from the flexibility of the numpy.roll() method such as the support for rolling over multiple dimensions. Elements that roll beyond the last position are re-introduced at ...
This method calculates the length of all sub - sequences where the array x is either True or 1.
def _get_length_sequences_where(x): """ This method calculates the length of all sub-sequences where the array x is either True or 1. Examples -------- >>> x = [0,1,0,0,1,1,1,0,0,1,0,1,1] >>> _get_length_sequences_where(x) >>> [1, 3, 1, 2] >>> x = [0,True,0,0,True,True,True,0,0,True,0,...
Coefficients of polynomial: math: h ( x ) which has been fitted to the deterministic dynamics of Langevin model.. math:: \ dot { x } ( t ) = h ( x ( t )) + \ mathcal { N } ( 0 R )
def _estimate_friedrich_coefficients(x, m, r): """ Coefficients of polynomial :math:`h(x)`, which has been fitted to the deterministic dynamics of Langevin model .. math:: \dot{x}(t) = h(x(t)) + \mathcal{N}(0,R) As described by Friedrich et al. (2000): Physics Letters A 271, p. 217...
Takes the time series x and constructs a lower sampled version of it by applying the aggregation function f_agg on consecutive chunks of length chunk_len
def _aggregate_on_chunks(x, f_agg, chunk_len): """ Takes the time series x and constructs a lower sampled version of it by applying the aggregation function f_agg on consecutive chunks of length chunk_len :param x: the time series to calculate the aggregation of :type x: numpy.ndarray :param f_...
This method returns a decorator that sets the property key of the function to value
def set_property(key, value): """ This method returns a decorator that sets the property key of the function to value """ def decorate_func(func): setattr(func, key, value) if func.__doc__ and key == "fctype": func.__doc__ = func.__doc__ + "\n\n *This function is of type: ...
Boolean variable denoting if the variance of x is greater than its standard deviation. Is equal to variance of x being larger than 1
def variance_larger_than_standard_deviation(x): """ Boolean variable denoting if the variance of x is greater than its standard deviation. Is equal to variance of x being larger than 1 :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this featur...
Ratio of values that are more than r * std ( x ) ( so r sigma ) away from the mean of x.
def ratio_beyond_r_sigma(x, r): """ Ratio of values that are more than r*std(x) (so r sigma) away from the mean of x. :param x: the time series to calculate the feature of :type x: iterable :return: the value of this feature :return type: float """ if not isinstance(x, (np.ndarray, pd.S...
Boolean variable denoting if the standard dev of x is higher than r times the range = difference between max and min of x. Hence it checks if
def large_standard_deviation(x, r): """ Boolean variable denoting if the standard dev of x is higher than 'r' times the range = difference between max and min of x. Hence it checks if .. math:: std(x) > r * (max(X)-min(X)) According to a rule of the thumb, the standard deviation shoul...
Boolean variable denoting if the distribution of x * looks symmetric *. This is the case if
def symmetry_looking(x, param): """ Boolean variable denoting if the distribution of x *looks symmetric*. This is the case if .. math:: | mean(X)-median(X)| < r * (max(X)-min(X)) :param x: the time series to calculate the feature of :type x: numpy.ndarray :param r: the percentage of t...
Checks if the maximum value of x is observed more than once
def has_duplicate_max(x): """ Checks if the maximum value of x is observed more than once :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: bool """ if not isinstance(x, (np.ndarray, pd.Series)): x = np....
Checks if the minimal value of x is observed more than once
def has_duplicate_min(x): """ Checks if the minimal value of x is observed more than once :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: bool """ if not isinstance(x, (np.ndarray, pd.Series)): x = np....
Checks if any value in x occurs more than once
def has_duplicate(x): """ Checks if any value in x occurs more than once :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: bool """ if not isinstance(x, (np.ndarray, pd.Series)): x = np.asarray(x) re...
r Calculates the value of an aggregation function: math: f_ { agg } ( e. g. the variance or the mean ) over the autocorrelation: math: R ( l ) for different lags. The autocorrelation: math: R ( l ) for lag: math: l is defined as
def agg_autocorrelation(x, param): r""" Calculates the value of an aggregation function :math:`f_{agg}` (e.g. the variance or the mean) over the autocorrelation :math:`R(l)` for different lags. The autocorrelation :math:`R(l)` for lag :math:`l` is defined as .. math:: R(l) = \frac{1}{(n-l)\sig...
Calculates the value of the partial autocorrelation function at the given lag. The lag k partial autocorrelation of a time series: math: \\ lbrace x_t t = 1 \\ ldots T \\ rbrace equals the partial correlation of: math: x_t and: math: x_ { t - k } adjusted for the intermediate variables: math: \\ lbrace x_ { t - 1 } \\ ...
def partial_autocorrelation(x, param): """ Calculates the value of the partial autocorrelation function at the given lag. The lag `k` partial autocorrelation of a time series :math:`\\lbrace x_t, t = 1 \\ldots T \\rbrace` equals the partial correlation of :math:`x_t` and :math:`x_{t-k}`, adjusted for th...
The Augmented Dickey - Fuller test is a hypothesis test which checks whether a unit root is present in a time series sample. This feature calculator returns the value of the respective test statistic.
def augmented_dickey_fuller(x, param): """ The Augmented Dickey-Fuller test is a hypothesis test which checks whether a unit root is present in a time series sample. This feature calculator returns the value of the respective test statistic. See the statsmodels implementation for references and more de...
Returns the absolute energy of the time series which is the sum over the squared values
def abs_energy(x): """ Returns the absolute energy of the time series which is the sum over the squared values .. math:: E = \\sum_{i=1,\ldots, n} x_i^2 :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: fl...
This function calculator is an estimate for a time series complexity [ 1 ] ( A more complex time series has more peaks valleys etc. ). It calculates the value of
def cid_ce(x, normalize): """ This function calculator is an estimate for a time series complexity [1] (A more complex time series has more peaks, valleys etc.). It calculates the value of .. math:: \\sqrt{ \\sum_{i=0}^{n-2lag} ( x_{i} - x_{i+1})^2 } .. rubric:: References | [1] Bat...
Returns the mean value of a central approximation of the second derivative
def mean_second_derivative_central(x): """ Returns the mean value of a central approximation of the second derivative .. math:: \\frac{1}{n} \\sum_{i=1,\ldots, n-1} \\frac{1}{2} (x_{i+2} - 2 \\cdot x_{i+1} + x_i) :param x: the time series to calculate the feature of :type x: numpy.ndarra...
Returns the sample skewness of x ( calculated with the adjusted Fisher - Pearson standardized moment coefficient G1 ).
def skewness(x): """ Returns the sample skewness of x (calculated with the adjusted Fisher-Pearson standardized moment coefficient G1). :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ if not isin...
Returns the kurtosis of x ( calculated with the adjusted Fisher - Pearson standardized moment coefficient G2 ).
def kurtosis(x): """ Returns the kurtosis of x (calculated with the adjusted Fisher-Pearson standardized moment coefficient G2). :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ if not isinstance(...
Returns the length of the longest consecutive subsequence in x that is smaller than the mean of x
def longest_strike_below_mean(x): """ Returns the length of the longest consecutive subsequence in x that is smaller than the mean of x :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ if not isinstan...
Returns the number of values in x that are higher than the mean of x
def count_above_mean(x): """ Returns the number of values in x that are higher than the mean of x :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ m = np.mean(x) return np.where(x > m)[0].size
Returns the number of values in x that are lower than the mean of x
def count_below_mean(x): """ Returns the number of values in x that are lower than the mean of x :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ m = np.mean(x) return np.where(x < m)[0].size
Returns the relative last location of the maximum value of x. The position is calculated relatively to the length of x.
def last_location_of_maximum(x): """ Returns the relative last location of the maximum value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float ...
Returns the first location of the maximum value of x. The position is calculated relatively to the length of x.
def first_location_of_maximum(x): """ Returns the first location of the maximum value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ ...
Returns the last location of the minimal value of x. The position is calculated relatively to the length of x.
def last_location_of_minimum(x): """ Returns the last location of the minimal value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ ...
Returns the first location of the minimal value of x. The position is calculated relatively to the length of x.
def first_location_of_minimum(x): """ Returns the first location of the minimal value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ ...
Returns the percentage of unique values that are present in the time series more than once.
def percentage_of_reoccurring_datapoints_to_all_datapoints(x): """ Returns the percentage of unique values, that are present in the time series more than once. len(different values occurring more than once) / len(different values) This means the percentage is normalized to the number of unique...
Returns the ratio of unique values that are present in the time series more than once.
def percentage_of_reoccurring_values_to_all_values(x): """ Returns the ratio of unique values, that are present in the time series more than once. # of data points occurring more than once / # of all data points This means the ratio is normalized to the number of data points in the time series...
Returns the sum of all values that are present in the time series more than once.
def sum_of_reoccurring_values(x): """ Returns the sum of all values, that are present in the time series more than once. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ unique, counts = np.unique...
Returns the sum of all data points that are present in the time series more than once.
def sum_of_reoccurring_data_points(x): """ Returns the sum of all data points, that are present in the time series more than once. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ unique, counts =...
Returns a factor which is 1 if all values in the time series occur only once and below one if this is not the case. In principle it just returns
def ratio_value_number_to_time_series_length(x): """ Returns a factor which is 1 if all values in the time series occur only once, and below one if this is not the case. In principle, it just returns # unique values / # values :param x: the time series to calculate the feature of :type...
Calculates the fourier coefficients of the one - dimensional discrete Fourier Transform for real input by fast fourier transformation algorithm
def fft_coefficient(x, param): """ Calculates the fourier coefficients of the one-dimensional discrete Fourier Transform for real input by fast fourier transformation algorithm .. math:: A_k = \\sum_{m=0}^{n-1} a_m \\exp \\left \\{ -2 \\pi i \\frac{m k}{n} \\right \\}, \\qquad k = 0, \...
Returns the spectral centroid ( mean ) variance skew and kurtosis of the absolute fourier transform spectrum.
def fft_aggregated(x, param): """ Returns the spectral centroid (mean), variance, skew, and kurtosis of the absolute fourier transform spectrum. :param x: the time series to calculate the feature of :type x: numpy.ndarray :param param: contains dictionaries {"aggtype": s} where s str and in ["centr...
Calculates the number of peaks of at least support n in the time series x. A peak of support n is defined as a subsequence of x where a value occurs which is bigger than its n neighbours to the left and to the right.
def number_peaks(x, n): """ Calculates the number of peaks of at least support n in the time series x. A peak of support n is defined as a subsequence of x where a value occurs, which is bigger than its n neighbours to the left and to the right. Hence in the sequence >>> x = [3, 0, 0, 4, 0, 0, 13]...
Those apply features calculate the relative index i where q% of the mass of the time series x lie left of i. For example for q = 50% this feature calculator will return the mass center of the time series
def index_mass_quantile(x, param): """ Those apply features calculate the relative index i where q% of the mass of the time series x lie left of i. For example for q = 50% this feature calculator will return the mass center of the time series :param x: the time series to calculate the feature of :t...
This feature calculator searches for different peaks in x. To do so x is smoothed by a ricker wavelet and for widths ranging from 1 to n. This feature calculator returns the number of peaks that occur at enough width scales and with sufficiently high Signal - to - Noise - Ratio ( SNR )
def number_cwt_peaks(x, n): """ This feature calculator searches for different peaks in x. To do so, x is smoothed by a ricker wavelet and for widths ranging from 1 to n. This feature calculator returns the number of peaks that occur at enough width scales and with sufficiently high Signal-to-Noise-Rati...
Calculate a linear least - squares regression for the values of the time series versus the sequence from 0 to length of the time series minus one. This feature assumes the signal to be uniformly sampled. It will not use the time stamps to fit the model. The parameters control which of the characteristics are returned.
def linear_trend(x, param): """ Calculate a linear least-squares regression for the values of the time series versus the sequence from 0 to length of the time series minus one. This feature assumes the signal to be uniformly sampled. It will not use the time stamps to fit the model. The parameters c...
Calculates a Continuous wavelet transform for the Ricker wavelet also known as the Mexican hat wavelet which is defined by
def cwt_coefficients(x, param): """ Calculates a Continuous wavelet transform for the Ricker wavelet, also known as the "Mexican hat wavelet" which is defined by .. math:: \\frac{2}{\\sqrt{3a} \\pi^{\\frac{1}{4}}} (1 - \\frac{x^2}{a^2}) exp(-\\frac{x^2}{2a^2}) where :math:`a` is the width ...
This feature calculator estimates the cross power spectral density of the time series x at different frequencies. To do so the time series is first shifted from the time domain to the frequency domain.
def spkt_welch_density(x, param): """ This feature calculator estimates the cross power spectral density of the time series x at different frequencies. To do so, the time series is first shifted from the time domain to the frequency domain. The feature calculators returns the power spectrum of the diff...
This feature calculator fits the unconditional maximum likelihood of an autoregressive AR ( k ) process. The k parameter is the maximum lag of the process
def ar_coefficient(x, param): """ This feature calculator fits the unconditional maximum likelihood of an autoregressive AR(k) process. The k parameter is the maximum lag of the process .. math:: X_{t}=\\varphi_0 +\\sum _{{i=1}}^{k}\\varphi_{i}X_{{t-i}}+\\varepsilon_{t} For the config...
First fixes a corridor given by the quantiles ql and qh of the distribution of x. Then calculates the average absolute value of consecutive changes of the series x inside this corridor.
def change_quantiles(x, ql, qh, isabs, f_agg): """ First fixes a corridor given by the quantiles ql and qh of the distribution of x. Then calculates the average, absolute value of consecutive changes of the series x inside this corridor. Think about selecting a corridor on the y-Axis and only calcu...
This function calculates the value of
def time_reversal_asymmetry_statistic(x, lag): """ This function calculates the value of .. math:: \\frac{1}{n-2lag} \sum_{i=0}^{n-2lag} x_{i + 2 \cdot lag}^2 \cdot x_{i + lag} - x_{i + lag} \cdot x_{i}^2 which is .. math:: \\mathbb{E}[L^2(X)^2 \cdot L(X) - L(X) \cdot X^2] ...
This function calculates the value of
def c3(x, lag): """ This function calculates the value of .. math:: \\frac{1}{n-2lag} \sum_{i=0}^{n-2lag} x_{i + 2 \cdot lag}^2 \cdot x_{i + lag} \cdot x_{i} which is .. math:: \\mathbb{E}[L^2(X)^2 \cdot L(X) \cdot X] where :math:`\\mathbb{E}` is the mean and :math:`L` is t...
First bins the values of x into max_bins equidistant bins. Then calculates the value of
def binned_entropy(x, max_bins): """ First bins the values of x into max_bins equidistant bins. Then calculates the value of .. math:: - \\sum_{k=0}^{min(max\\_bins, len(x))} p_k log(p_k) \\cdot \\mathbf{1}_{(p_k > 0)} where :math:`p_k` is the percentage of samples in bin :math:`k`. ...
Calculate and return sample entropy of x.
def sample_entropy(x): """ Calculate and return sample entropy of x. .. rubric:: References | [1] http://en.wikipedia.org/wiki/Sample_Entropy | [2] https://www.ncbi.nlm.nih.gov/pubmed/10843903?dopt=Abstract :param x: the time series to calculate the feature of :type x: numpy.ndarray ...
Calculates the autocorrelation of the specified lag according to the formula [ 1 ]
def autocorrelation(x, lag): """ Calculates the autocorrelation of the specified lag, according to the formula [1] .. math:: \\frac{1}{(n-l)\sigma^{2}} \\sum_{t=1}^{n-l}(X_{t}-\\mu )(X_{t+l}-\\mu) where :math:`n` is the length of the time series :math:`X_i`, :math:`\sigma^2` its variance and ...
Calculates the q quantile of x. This is the value of x greater than q% of the ordered values from x.
def quantile(x, q): """ Calculates the q quantile of x. This is the value of x greater than q% of the ordered values from x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :param q: the quantile to calculate :type q: float :return: the value of this feature ...
Calculates the number of crossings of x on m. A crossing is defined as two sequential values where the first value is lower than m and the next is greater or vice - versa. If you set m to zero you will get the number of zero crossings.
def number_crossing_m(x, m): """ Calculates the number of crossings of x on m. A crossing is defined as two sequential values where the first value is lower than m and the next is greater, or vice-versa. If you set m to zero, you will get the number of zero crossings. :param x: the time series to c...
Count occurrences of value in time series x.
def value_count(x, value): """ Count occurrences of `value` in time series x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :param value: the value to be counted :type value: int or float :return: the count :rtype: int """ if not isinstance(x, (np....
Count observed values within the interval [ min max ).
def range_count(x, min, max): """ Count observed values within the interval [min, max). :param x: the time series to calculate the feature of :type x: numpy.ndarray :param min: the inclusive lower bound of the range :type min: int or float :param max: the exclusive upper bound of the range ...
Implements a vectorized Approximate entropy algorithm.
def approximate_entropy(x, m, r): """ Implements a vectorized Approximate entropy algorithm. https://en.wikipedia.org/wiki/Approximate_entropy For short time-series this method is highly dependent on the parameters, but should be stable for N > 2000, see: Yentes et al. (2012) - ...
Coefficients of polynomial: math: h ( x ) which has been fitted to the deterministic dynamics of Langevin model
def friedrich_coefficients(x, param): """ Coefficients of polynomial :math:`h(x)`, which has been fitted to the deterministic dynamics of Langevin model .. math:: \dot{x}(t) = h(x(t)) + \mathcal{N}(0,R) as described by [1]. For short time-series this method is highly dependent on the ...
Largest fixed point of dynamics: math: argmax_x { h ( x ) = 0 } estimated from polynomial: math: h ( x ) which has been fitted to the deterministic dynamics of Langevin model
def max_langevin_fixed_point(x, r, m): """ Largest fixed point of dynamics :math:argmax_x {h(x)=0}` estimated from polynomial :math:`h(x)`, which has been fitted to the deterministic dynamics of Langevin model .. math:: \dot(x)(t) = h(x(t)) + R \mathcal(N)(0,1) as described by Fr...
Calculates a linear least - squares regression for values of the time series that were aggregated over chunks versus the sequence from 0 up to the number of chunks minus one.
def agg_linear_trend(x, param): """ Calculates a linear least-squares regression for values of the time series that were aggregated over chunks versus the sequence from 0 up to the number of chunks minus one. This feature assumes the signal to be uniformly sampled. It will not use the time stamps to fi...
Calculates the sum of squares of chunk i out of N chunks expressed as a ratio with the sum of squares over the whole series.
def energy_ratio_by_chunks(x, param): """ Calculates the sum of squares of chunk i out of N chunks expressed as a ratio with the sum of squares over the whole series. Takes as input parameters the number num_segments of segments to divide the series into and segment_focus which is the segment numbe...
Calculate a linear least - squares regression for the values of the time series versus the sequence from 0 to length of the time series minus one. This feature uses the index of the time series to fit the model which must be of a datetime dtype. The parameters control which of the characteristics are returned.
def linear_trend_timewise(x, param): """ Calculate a linear least-squares regression for the values of the time series versus the sequence from 0 to length of the time series minus one. This feature uses the index of the time series to fit the model, which must be of a datetime dtype. The parame...
Extract the information which of the features are relevent using the given target.
def fit(self, X, y): """ Extract the information, which of the features are relevent using the given target. For more information, please see the :func:`~tsfresh.festure_selection.festure_selector.check_fs_sig_bh` function. All columns in the input data sample are treated as feature. Th...
Delete all features which were not relevant in the fit phase.
def transform(self, X): """ Delete all features, which were not relevant in the fit phase. :param X: data sample with all features, which will be reduced to only those that are relevant :type X: pandas.DataSeries or numpy.array :return: same data sample as X, but with only the ...
Download human activity recognition dataset from UCI ML Repository and store it at/ tsfresh/ notebooks/ data. Examples ========
def download_har_dataset(): """ Download human activity recognition dataset from UCI ML Repository and store it at /tsfresh/notebooks/data. Examples ======== >>> from tsfresh.examples import har_dataset >>> har_dataset.download_har_dataset() """ zipurl = 'https://github.com/MaxBen...
Add the features calculated using the timeseries_container and add them to the corresponding rows in the input pandas. DataFrame X.
def transform(self, X): """ Add the features calculated using the timeseries_container and add them to the corresponding rows in the input pandas.DataFrame X. To save some computing time, you should only include those time serieses in the container, that you need. You can set th...
Use the given timeseries from: func: ~set_timeseries_container and calculate features from it and add them to the data sample X ( which can contain other manually - designed features ).
def fit(self, X, y): """ Use the given timeseries from :func:`~set_timeseries_container` and calculate features from it and add them to the data sample X (which can contain other manually-designed features). Then determine which of the features of X are relevant for the given target y. ...
After the fit step it is known which features are relevant Only extract those from the time series handed in with the function: func: ~set_timeseries_container.
def transform(self, X): """ After the fit step, it is known which features are relevant, Only extract those from the time series handed in with the function :func:`~set_timeseries_container`. If filter_only_tsfresh_features is False, also delete the irrelevant, already present features ...
given a DataFrame where records are stored row - wise rearrange it such that records are stored column - wise.
def _preprocess(df): """ given a DataFrame where records are stored row-wise, rearrange it such that records are stored column-wise. """ df = df.stack() df.index.rename(["id", "time"], inplace=True) # .reset_index() df.name = "value" df = df.reset_index() return df
Calculate the relevance table for the features contained in feature matrix X with respect to target vector y. The relevance table is calculated for the intended machine learning task ml_task.
def calculate_relevance_table(X, y, ml_task='auto', n_jobs=defaults.N_PROCESSES, chunksize=defaults.CHUNKSIZE, test_for_binary_target_binary_feature=defaults.TEST_FOR_BINARY_TARGET_BINARY_FEATURE, test_for_binary_target_real_feature=defaults.TEST_FOR_BINARY_TARGET_REAL_FEATURE, ...
Infer the machine learning task to select for. The result will be either regression or classification. If the target vector only consists of integer typed values or objects we assume the task is classification. Else regression.
def infer_ml_task(y): """ Infer the machine learning task to select for. The result will be either `'regression'` or `'classification'`. If the target vector only consists of integer typed values or objects, we assume the task is `'classification'`. Else `'regression'`. :param y: The target vec...
Create a combined relevance table out of a list of relevance tables aggregating the p - values and the relevances.
def combine_relevance_tables(relevance_tables): """ Create a combined relevance table out of a list of relevance tables, aggregating the p-values and the relevances. :param relevance_tables: A list of relevance tables :type relevance_tables: List[pd.DataFrame] :return: The combined relevance ta...
For a given feature determine if it is real binary or constant. Here binary means that only two unique values occur in the feature.
def get_feature_type(feature_column): """ For a given feature, determine if it is real, binary or constant. Here binary means that only two unique values occur in the feature. :param feature_column: The feature column :type feature_column: pandas.Series :return: 'constant', 'binary' or 'real' ...
Extract features from
def extract_features(timeseries_container, default_fc_parameters=None, kind_to_fc_parameters=None, column_id=None, column_sort=None, column_kind=None, column_value=None, chunksize=defaults.CHUNKSIZE, n_jobs=defaults.N_PROCESSES, show_wa...
Converts the dataframe df in into a list of individual time seriess.
def generate_data_chunk_format(df, column_id, column_kind, column_value): """Converts the dataframe df in into a list of individual time seriess. E.g. the DataFrame ==== ====== ========= id kind val ==== ====== ========= 1 a -0.21761 1 a ...
Wrapper around the _do_extraction_on_chunk which calls it on all chunks in the data frame. A chunk is a subset of the data with a given kind and id - so a single time series.
def _do_extraction(df, column_id, column_value, column_kind, default_fc_parameters, kind_to_fc_parameters, n_jobs, chunk_size, disable_progressbar, distributor): """ Wrapper around the _do_extraction_on_chunk, which calls it on all chunks in the data frame. A chunk is a...
Main function of this module: use the feature calculators defined in the default_fc_parameters or kind_to_fc_parameters parameters and extract all features on the chunk.
def _do_extraction_on_chunk(chunk, default_fc_parameters, kind_to_fc_parameters): """ Main function of this module: use the feature calculators defined in the default_fc_parameters or kind_to_fc_parameters parameters and extract all features on the chunk. The chunk consists of the chunk id, the chu...
Helper function to extract the configuration of a certain function from the column name. The column name parts ( split by __ ) should be passed to this function. It will skip the kind name and the function name and only use the parameter parts. These parts will be split up on _ into the parameter name and the parameter...
def get_config_from_string(parts): """ Helper function to extract the configuration of a certain function from the column name. The column name parts (split by "__") should be passed to this function. It will skip the kind name and the function name and only use the parameter parts. These parts will be ...
Helper function to convert parameters to a valid string that can be used in a column name. Does the opposite which is used in the from_columns function.
def convert_to_output_format(param): """ Helper function to convert parameters to a valid string, that can be used in a column name. Does the opposite which is used in the from_columns function. The parameters are sorted by their name and written out in the form <param name>_<param value>__<par...
Helper function to stop the profiling process and write out the profiled data into the given filename. Before this sort the stats by the passed sorting.
def end_profiling(profiler, filename, sorting=None): """ Helper function to stop the profiling process and write out the profiled data into the given filename. Before this, sort the stats by the passed sorting. :param profiler: An already started profiler (probably by start_profiling). :type profil...
Compute the min max and median for all columns in the DataFrame. For more information please see the: func: ~tsfresh. utilities. dataframe_functions. get_range_values_per_column function.
def fit(self, X, y=None): """ Compute the min, max and median for all columns in the DataFrame. For more information, please see the :func:`~tsfresh.utilities.dataframe_functions.get_range_values_per_column` function. :param X: DataFrame to calculate min, max and median ...
Column - wise replace all NaNs - inf and + inf in the DataFrame X with average/ extreme values from the provided dictionaries.
def transform(self, X): """ Column-wise replace all ``NaNs``, ``-inf`` and ``+inf`` in the DataFrame `X` with average/extreme values from the provided dictionaries. :param X: DataFrame to impute :type X: pandas.DataFrame :return: imputed DataFram...
Download the Robot Execution Failures LP1 Data Set [ #1 ] from the UCI Machine Learning Repository [ #2 ] and store it locally.
def download_robot_execution_failures(): """ Download the Robot Execution Failures LP1 Data Set[#1] from the UCI Machine Learning Repository [#2] and store it locally. :return: Examples ======== >>> from tsfresh.examples import download_robot_execution_failures >>> download_robot_exec...
Load the Robot Execution Failures LP1 Data Set [ 1 ]. The Time series are passed as a flat DataFrame.
def load_robot_execution_failures(multiclass=False): """ Load the Robot Execution Failures LP1 Data Set[1]. The Time series are passed as a flat DataFrame. Examples ======== >>> from tsfresh.examples import load_robot_execution_failures >>> df, y = load_robot_execution_failures() >>> p...
High level convenience function to extract time series features from timeseries_container. Then return feature matrix X possibly augmented with relevant features with respect to target vector y.
def extract_relevant_features(timeseries_container, y, X=None, default_fc_parameters=None, kind_to_fc_parameters=None, column_id=None, column_sort=None, column_kind=None, column_value=None, show_warni...
Return list of control parameters
def sample_tau(n=10, kappa_3=0.3, ratio=0.5, rel_increase=0.15): """ Return list of control parameters :param n: number of samples :type n: int :param kappa_3: inverse bifurcation point :type kappa_3: float :param ratio: ratio (default 0.5) of samples before and beyond drift-bifurcatio...
Simulates n time - series with l time steps each for the m - dimensional velocity of a dissipative soliton
def load_driftbif(n, l, m=2, classification=True, kappa_3=0.3, seed=False): """ Simulates n time-series with l time steps each for the m-dimensional velocity of a dissipative soliton classification=True: target 0 means tau<=1/0.3, Dissipative Soliton with Brownian motion (purely noise driven) targe...
Helper function to check for NaN in the data frame and raise a ValueError if there is one.
def check_for_nans_in_columns(df, columns=None): """ Helper function to check for ``NaN`` in the data frame and raise a ``ValueError`` if there is one. :param df: the pandas DataFrame to test for NaNs :type df: pandas.DataFrame :param columns: a list of columns to test for NaNs. If left empty, all ...