text
stringlengths
81
112k
Updates the ordering of tasks in the positions object with the given ID to the ordering in the given values. See https://developer.wunderlist.com/documentation/endpoints/positions for more info Return: The updated TaskPositionsObj-mapped object defining the order of list layout def update_tas...
Updates the ordering of subtasks in the positions object with the given ID to the ordering in the given values. See https://developer.wunderlist.com/documentation/endpoints/positions for more info Return: The updated SubtaskPositionsObj-mapped object defining the order of list layout def upda...
Checks that the given date string conforms to the given API's date format specification def _check_date_format(date, api): ''' Checks that the given date string conforms to the given API's date format specification ''' try: datetime.datetime.strptime(date, api.DATE_FORMAT) except ValueError: ...
Gets un/completed tasks for the given list ID def get_tasks(client, list_id, completed=False): ''' Gets un/completed tasks for the given list ID ''' params = { 'list_id' : str(list_id), 'completed' : completed } response = client.authenticated_request(client.api.Endpo...
Gets task information for the given ID def get_task(client, task_id): ''' Gets task information for the given ID ''' endpoint = '/'.join([client.api.Endpoints.TASKS, str(task_id)]) response = client.authenticated_request(endpoint) return response.json()
Creates a task in the given list See https://developer.wunderlist.com/documentation/endpoints/task for detailed parameter information def create_task(client, list_id, title, assignee_id=None, completed=None, recurrence_type=None, recurrence_count=None, due_date=None, starred=None): ''' Creates a task in...
Updates the task with the given ID See https://developer.wunderlist.com/documentation/endpoints/task for detailed parameter information def update_task(client, task_id, revision, title=None, assignee_id=None, completed=None, recurrence_type=None, recurrence_count=None, due_date=None, starred=None, remove=None): ...
Checks the given title against the given API specifications to ensure it's short enough def _check_title_length(title, api): ''' Checks the given title against the given API specifications to ensure it's short enough ''' if len(title) > api.MAX_LIST_TITLE_LENGTH: raise ValueError("Title cannot be longe...
Gets all the client's lists def get_lists(client): ''' Gets all the client's lists ''' response = client.authenticated_request(client.api.Endpoints.LISTS) return response.json()
Gets the given list def get_list(client, list_id): ''' Gets the given list ''' endpoint = '/'.join([client.api.Endpoints.LISTS, str(list_id)]) response = client.authenticated_request(endpoint) return response.json()
Creates a new list with the given title def create_list(client, title): ''' Creates a new list with the given title ''' _check_title_length(title, client.api) data = { 'title' : title, } response = client.authenticated_request(client.api.Endpoints.LISTS, method='POST', data=data...
Updates the list with the given ID to have the given properties See https://developer.wunderlist.com/documentation/endpoints/list for detailed parameter information def update_list(client, list_id, revision, title=None, public=None): ''' Updates the list with the given ID to have the given properties ...
Gets the object that defines how lists are ordered (there will always be only one of these) See https://developer.wunderlist.com/documentation/endpoints/positions for more info Return: A ListPositionsObj-mapped object defining the order of list layout def get_list_positions_obj(client, positions_obj_id):...
Updates the ordering of lists to have the given value. The given ID and revision should match the singleton object defining how lists are laid out. See https://developer.wunderlist.com/documentation/endpoints/positions for more info Return: The updated ListPositionsObj-mapped object defining the order of ...
Gets a list containing the object that encapsulates information about the order lists are laid out in. This list will always contain exactly one object. See https://developer.wunderlist.com/documentation/endpoints/positions for more info Return: A list containing a single ListPositionsObj-mapped object d...
Gets a list of the positions of a single task's subtasks Each task should (will?) only have one positions object defining how its subtasks are laid out def get_task_subtask_positions_objs(client, task_id): ''' Gets a list of the positions of a single task's subtasks Each task should (will?) only have...
Gets all subtask positions objects for the tasks within a given list. This is a convenience method so you don't have to get all the list's tasks before getting subtasks, though I can't fathom how mass subtask reordering is useful. Returns: List of SubtaskPositionsObj-mapped objects representing the order of su...
Checks the given title against the given API specifications to ensure it's short enough def _check_title_length(title, api): ''' Checks the given title against the given API specifications to ensure it's short enough ''' if len(title) > api.MAX_SUBTASK_TITLE_LENGTH: raise ValueError("Title cannot be lo...
Gets subtasks for task with given ID def get_task_subtasks(client, task_id, completed=False): ''' Gets subtasks for task with given ID ''' params = { 'task_id' : int(task_id), 'completed' : completed, } response = client.authenticated_request(client.api.Endpoints.SUBTASK...
Gets subtasks for the list with given ID def get_list_subtasks(client, list_id, completed=False): ''' Gets subtasks for the list with given ID ''' params = { 'list_id' : int(list_id), 'completed' : completed, } response = client.authenticated_request(client.api.Endpoints...
Gets the subtask with the given ID def get_subtask(client, subtask_id): ''' Gets the subtask with the given ID ''' endpoint = '/'.join([client.api.Endpoints.SUBTASKS, str(subtask_id)]) response = client.authenticated_request(endpoint) return response.json()
Creates a subtask with the given title under the task with the given ID def create_subtask(client, task_id, title, completed=False): ''' Creates a subtask with the given title under the task with the given ID ''' _check_title_length(title, client.api) data = { 'task_id' : int(task_id) if task_i...
Updates the subtask with the given ID See https://developer.wunderlist.com/documentation/endpoints/subtask for detailed parameter information def update_subtask(client, subtask_id, revision, title=None, completed=None): ''' Updates the subtask with the given ID See https://developer.wunderlist.com/do...
Deletes the subtask with the given ID provided the given revision equals the revision the server has def delete_subtask(client, subtask_id, revision): ''' Deletes the subtask with the given ID provided the given revision equals the revision the server has ''' params = { 'revision' : int(revision), ...
Decorator for adding wait animation to long running functions. Args: animation (str, tuple): String reference to animation or tuple with custom animation. speed (float): Number of seconds each cycle of animation. Examples: >>> @animation.wait('bar') >>> def long...
Decorator for adding simple text wait animation to long running functions. Examples: >>> @animation.simple_wait >>> def long_running_function(): >>> ... 5 seconds later ... >>> return def simple_wait(func): """ Decorator for adding simple text wait animation to ...
Start animation thread. def start(self): """ Start animation thread. """ self.thread = threading.Thread(target=self._animate) self.thread.start() return
Stop animation thread. def stop(self): """ Stop animation thread. """ time.sleep(self.speed) self._count = -9999 sys.stdout.write(self.reverser + '\r\033[K\033[A') sys.stdout.flush() return
Merge several timeseries Arguments: tup: sequence of Timeseries, with the same shape except for axis 0 Returns: Resulting merged timeseries which can have duplicate time points. def merge(tup): """Merge several timeseries Arguments: tup: sequence of Timeseries, with the same shape ex...
Dynamically add new analysis methods to the Timeseries class. Args: source: Can be a function, module or the filename of a python file. If a filename or a module is given, then all functions defined inside not starting with _ will be added as methods. The only restric...
Calculate the absolute value element-wise. Returns: absolute (Timeseries): Absolute value. For complex input (a + b*j) gives sqrt(a**a + b**2) def absolute(self): """Calculate the absolute value element-wise. Returns: absolute (Timeseries): Absolute...
Return the angle of the complex argument. Args: deg (bool, optional): Return angle in degrees if True, radians if False (default). Returns: angle (Timeseries): The counterclockwise angle from the positive real axis on the complex plane, with dtyp...
Interchange two axes of a Timeseries. def swapaxes(self, axis1, axis2): """Interchange two axes of a Timeseries.""" if self.ndim <=1 or axis1 == axis2: return self ar = np.asarray(self).swapaxes(axis1, axis2) if axis1 != 0 and axis2 != 0: # then axis 0 is unaffec...
Permute the dimensions of a Timeseries. def transpose(self, *axes): """Permute the dimensions of a Timeseries.""" if self.ndim <= 1: return self ar = np.asarray(self).transpose(*axes) if axes[0] != 0: # then axis 0 is unaffected by the transposition n...
If axis 0 is unaffected by the reshape, then returns a Timeseries, otherwise returns an ndarray. Preserves labels of axis j only if all axes<=j are unaffected by the reshape. See ``numpy.ndarray.reshape()`` for more information def reshape(self, newshape, order='C'): """If axis 0 is ...
Merge another timeseries with this one Arguments: ts (Timeseries): The two timeseries being merged must have the same shape except for axis 0. Returns: Resulting merged timeseries which can have duplicate time points. def merge(self, ts): """Merge another timese...
Insert a new axis, at a given position in the array shape Args: axis (int): Position (amongst axes) where new axis is to be inserted. def expand_dims(self, axis): """Insert a new axis, at a given position in the array shape Args: axis (int): Position (amongst axes) where new...
Join a sequence of Timeseries to this one Args: tup (sequence of Timeseries): timeseries to be joined with this one. They must have the same shape as this Timeseries, except in the dimension corresponding to `axis`. axis (int, optional): The axis along which timeseri...
Split a timeseries into multiple sub-timeseries def split(self, indices_or_sections, axis=0): """Split a timeseries into multiple sub-timeseries""" if not isinstance(indices_or_sections, numbers.Integral): raise Error('splitting by array of indices is not yet implemented') n = indic...
Plot a distributed timeseries Args: dts (DistTimeseries) title (str, optional) points (int, optional): Limit the number of time points plotted. If specified, will downsample to use this total number of time points, and only fetch back the necessary points to the client for plott...
Plot a polar histogram of a phase variable's probability distribution Args: dts: DistTimeseries with axis 2 ranging over separate instances of an oscillator (time series values are assumed to represent an angle) times (float or sequence of floats): The target times at which to plot the ...
plot Welch estimate of power spectral density, using nperseg samples per segment, with noverlap samples overlap and Hamming window. def psd(ts, nperseg=1500, noverlap=1200, plot=True): """plot Welch estimate of power spectral density, using nperseg samples per segment, with noverlap samples overlap and Ham...
forward-backward butterworth low-pass filter def lowpass(ts, cutoff_hz, order=3): """forward-backward butterworth low-pass filter""" orig_ndim = ts.ndim if ts.ndim is 1: ts = ts[:, np.newaxis] channels = ts.shape[1] fs = (len(ts) - 1.0) / (ts.tspan[-1] - ts.tspan[0]) nyq = 0.5 * fs ...
forward-backward butterworth band-pass filter def bandpass(ts, low_hz, high_hz, order=3): """forward-backward butterworth band-pass filter""" orig_ndim = ts.ndim if ts.ndim is 1: ts = ts[:, np.newaxis] channels = ts.shape[1] fs = (len(ts) - 1.0) / (ts.tspan[-1] - ts.tspan[0]) nyq = 0.5 ...
notch filter to remove remove a particular frequency Adapted from code by Sturla Molden def notch(ts, freq_hz, bandwidth_hz=1.0): """notch filter to remove remove a particular frequency Adapted from code by Sturla Molden """ orig_ndim = ts.ndim if ts.ndim is 1: ts = ts[:, np.newaxis] ...
Analytic signal, using the Hilbert transform def hilbert(ts): """Analytic signal, using the Hilbert transform""" output = signal.hilbert(signal.detrend(ts, axis=0), axis=0) return Timeseries(output, ts.tspan, labels=ts.labels)
Amplitude of the analytic signal, using the Hilbert transform def hilbert_amplitude(ts): """Amplitude of the analytic signal, using the Hilbert transform""" output = np.abs(signal.hilbert(signal.detrend(ts, axis=0), axis=0)) return Timeseries(output, ts.tspan, labels=ts.labels)
Phase of the analytic signal, using the Hilbert transform def hilbert_phase(ts): """Phase of the analytic signal, using the Hilbert transform""" output = np.angle(signal.hilbert(signal.detrend(ts, axis=0), axis=0)) return Timeseries(output, ts.tspan, labels=ts.labels)
Continuous wavelet transform Note the full results can use a huge amount of memory at 64-bit precision Args: ts: Timeseries of m variables, shape (n, m). Assumed constant timestep. freqs: list of frequencies (in Hz) to use for the tranform. (default is 50 frequency bins logarithmic from 1H...
Continuous wavelet transform using distributed computation. (Currently just splits the data by channel. TODO split it further.) Note: this function requires an IPython cluster to be started first. Args: ts: Timeseries of m variables, shape (n, m). Assumed constant timestep. freqs: list of frequ...
Plot time resolved power spectral density from cwt results Args: ts: the original Timeseries coefs: continuous wavelet transform coefficients as calculated by cwt() freqs: list of frequencies (in Hz) corresponding to coefs. tsize, fsize: size of the plot (time axis and frequency axis, in pi...
For an ensemble of time series, return the set of all time intervals between successive returns to value c for all instances in the ensemble. If c is not given, the default is the mean across all times and across all time series in the ensemble. Args: dts (DistTimeseries) c (float): Option...
Example variability function. Gives two continuous, time-resolved measures of the variability of a time series, ranging between -1 and 1. The two measures are based on variance of the centroid frequency and variance of the height of the spectral peak, respectively. (Centroid frequency meaning the ...
Identify "stationary" epochs within a time series, based on a continuous measure of variability. Epochs are defined to contain the points of minimal variability, and to extend as wide as possible with variability not exceeding the threshold. Args: ts Timeseries of m variables, shape (n, m). ...
Identify epochs within a multivariate time series where at least a certain proportion of channels are "stationary", based on a previously computed variability measure. (Note: This requires an IPython cluster to be started first, e.g. on a workstation type 'ipcluster start') Args: ts Tim...
For an ensemble of oscillators, return the set of periods lengths of all successive oscillations of all oscillators. An individual oscillation is defined to start and end when the phase passes phi (by default zero) after completing a full cycle. If the timeseries of an oscillator phase begins (or en...
Circular mean phase def circmean(dts, axis=2): """Circular mean phase""" return np.exp(1.0j * dts).mean(axis=axis).angle()
Order parameter of phase synchronization def order_param(dts, axis=2): """Order parameter of phase synchronization""" return np.abs(np.exp(1.0j * dts).mean(axis=axis))
Circular standard deviation def circstd(dts, axis=2): """Circular standard deviation""" R = np.abs(np.exp(1.0j * dts).mean(axis=axis)) return np.sqrt(-2.0 * np.log(R))
Aburn2012 equations right hand side, noise free term Args: v: (8,) array state vector t: number scalar time Returns: (8,) array def f(self, v, t): """Aburn2012 equations right hand side, noise free term Args: v: (8,) a...
Aburn2012 equations right hand side, noise term Args: v: (8,) array state vector t: number scalar time Returns: (8,1) array Only one matrix column, meaning that in this example we are modelling the noise input to pyramidal and...
How to couple the output of one node to the input of another. Args: source_y (array of shape (8,)): state of the source node target_y (array of shape (8,)): state of the target node weight (float): the connection strength Returns: input (array of shape (8,)): valu...
Compute the Hurst exponent of X. If the output H=0.5,the behavior of the time-series is similar to random walk. If H<0.5, the time-series cover less "distance" than a random walk, vice verse. Parameters ---------- X list a time series Returns ------- H float...
Build a set of embedding sequences from given time series X with lag Tau and embedding dimension DE. Let X = [x(1), x(2), ... , x(N)], then for each i such that 1 < i < N - (D - 1) * Tau, we build an embedding sequence, Y(i) = [x(i), x(i + Tau), ... , x(i + (D - 1) * Tau)]. All embedding sequence are p...
Compute power in each frequency bin specified by Band from FFT result of X. By default, X is a real signal. Note ----- A real signal can be synthesized, thus not real. Parameters ----------- Band list boundary frequencies (in Hz) of bins. They can be unequal bins, e.g. ...
Compute Petrosian Fractal Dimension of a time series from either two cases below: 1. X, the time series of type list (default) 2. D, the first order differential sequence of X (if D is provided, recommended to speed up) In case 1, D is computed using Numpy's difference function. ...
Compute Hjorth Fractal Dimension of a time series X, kmax is an HFD parameter def hfd(X, Kmax): """ Compute Hjorth Fractal Dimension of a time series X, kmax is an HFD parameter """ L = [] x = [] N = len(X) for k in range(1, Kmax): Lk = [] for m in range(0, k): ...
Compute Hjorth mobility and complexity of a time series from either two cases below: 1. X, the time series of type list (default) 2. D, a first order differential sequence of X (if D is provided, recommended to speed up) In case 1, D is computed using Numpy's Difference function. ...
Compute spectral entropy of a time series from either two cases below: 1. X, the time series (default) 2. Power_Ratio, a list of normalized signal power in a set of frequency bins defined in Band (if Power_Ratio is provided, recommended to speed up) In case 1, Power_Ratio is computed by bin_power() fun...
Compute SVD Entropy from either two cases below: 1. a time series X, with lag tau and embedding dimension dE (default) 2. a list, W, of normalized singular values of a matrix (if W is provided, recommend to speed up.) If W is None, the function will do as follows to prepare singular spectrum: ...
Computer approximate entropy (ApEN) of series X, specified by M and R. Suppose given time series is X = [x(1), x(2), ... , x(N)]. We first build embedding matrix Em, of dimension (N-M+1)-by-M, such that the i-th row of Em is x(i),x(i+1), ... , x(i+M-1). Hence, the embedding lag and dimension are 1 and ...
Computer sample entropy (SampEn) of series X, specified by M and R. SampEn is very close to ApEn. Suppose given time series is X = [x(1), x(2), ... , x(N)]. We first build embedding matrix Em, of dimension (N-M+1)-by-M, such that the i-th row of Em is x(i),x(i+1), ... , x(i+M-1). Hence, the embedding ...
Compute Detrended Fluctuation Analysis from a time series X and length of boxes L. The first step to compute DFA is to integrate the signal. Let original series be X= [x(1), x(2), ..., x(N)]. The integrated signal Y = [y(1), y(2), ..., y(N)] is obtained as follows y(k) = \sum_{i=1}^{k}{x(i)-Ave} w...
Compute Permutation Entropy of a given time series x, specified by permutation order n and embedding lag tau. Parameters ---------- x list a time series n integer Permutation order tau integer Embedding lag Returns ---------- P...
Calculates the information based similarity of two time series x and y. Parameters ---------- x list a time series y list a time series n integer word order Returns ---------- IBS float Information based si...
Calculate largest Lyauponov exponent of a given time series x using Rosenstein algorithm. Parameters ---------- x list a time series n integer embedding dimension tau integer Embedding lag fs integer Sampling frequency ...
For a timeseries where all variables represent phases (in radians), return an equivalent timeseries where all values are in the range (-pi, pi] def mod2pi(ts): """For a timeseries where all variables represent phases (in radians), return an equivalent timeseries where all values are in the range (-pi, pi] ...
For a single variable timeseries representing the phase of an oscillator, find the times at which the phase crosses angle phi, with the condition that the phase must visit phi+pi between crossings. (Thus if noise causes the phase to wander back and forth across angle phi without the oscillator doing a...
For a single variable timeseries representing the phase of an oscillator, measure the period of each successive oscillation. An individual oscillation is defined to start and end when the phase passes phi (by default zero) after completing a full cycle. If the timeseries begins (or ends) exactly at p...
Circular mean phase def circmean(ts, axis=2): """Circular mean phase""" return np.exp(1.0j * ts).mean(axis=axis).angle()
Order parameter of phase synchronization def order_param(ts, axis=2): """Order parameter of phase synchronization""" return np.abs(np.exp(1.0j * ts).mean(axis=axis))
complex morlet wavelet function compatible with scipy.signal.cwt Parameters: points: int Number of points in `vector`. width: scalar Width parameter of wavelet. Equals (sample rate / fundamental frequency of wavelet) Returns: `vector`: ...
Continuous wavelet transform. Performs a continuous wavelet transform on `data`, using the `wavelet` function. A CWT performs a convolution with `data` using the `wavelet` function, which is characterized by a width parameter and length parameter. Parameters ---------- data : (N,) ndarray ...
Example variability function. Gives two continuous, time-resolved measures of the variability of a time series, ranging between -1 and 1. The two measures are based on variance of the centroid frequency and variance of the height of the spectral peak, respectively. (Centroid frequency meaning the ...
Shift and rescale array ar to the interval [-1, 1] def _rescale(ar): """Shift and rescale array ar to the interval [-1, 1]""" max = np.nanmax(ar) min = np.nanmin(ar) midpoint = (max + min) / 2.0 return 2.0 * (ar - midpoint) / (max - min)
Get cycle of colors in a way compatible with all matplotlib versions def _get_color_list(): """Get cycle of colors in a way compatible with all matplotlib versions""" if 'axes.prop_cycle' in plt.rcParams: return [p['color'] for p in list(plt.rcParams['axes.prop_cycle'])] else: return plt.rc...
Plot the timeseries and variability. Optionally plot epochs. def _plot_variability(ts, variability, threshold=None, epochs=None): """Plot the timeseries and variability. Optionally plot epochs.""" import matplotlib.style import matplotlib as mpl mpl.style.use('classic') import matplotlib.pyplot as ...
Identify "stationary" epochs within a time series, based on a continuous measure of variability. Epochs are defined to contain the points of minimal variability, and to extend as wide as possible with variability not exceeding the threshold. Args: ts Timeseries of m variables, shape (n, m). ...
Same as `epochs()`, but computes channels in parallel for speed. (Note: This requires an IPython cluster to be started first, e.g. on a workstation type 'ipcluster start') Identify "stationary" epochs within a time series, based on a continuous measure of variability. Epochs are defined t...
Identify epochs within a multivariate time series where at least a certain proportion of channels are "stationary", based on a previously computed variability measure. (Note: This requires an IPython cluster to be started first, e.g. on a workstation type 'ipcluster start') Args: ts Tim...
Plot a Timeseries Args: ts Timeseries title str show bool whether to display the figure or just return a figure object def plot(ts, title=None, show=True): """Plot a Timeseries Args: ts Timeseries title str show bool whether to display the figure or just return a...
For each variable in the Timeseries, checks whether it represents a phase variable ranging from -pi to pi. If so, set all points where the phase crosses pi to 'nan' so that spurious lines will not be plotted. If ts does not need adjustment, then return ts. Otherwise return a modified copy. def _remov...
load a multi-channel Timeseries from a MATLAB .mat file Args: filename (str): .mat file to load varname (str): variable name. only needed if there is more than one variable saved in the .mat file fs (scalar): sample rate of timeseries in Hz. (constant timestep assumed) Returns: ...
save a Timeseries to a MATLAB .mat file Args: ts (Timeseries): the timeseries to save filename (str): .mat filename to save to def save_mat(ts, filename): """save a Timeseries to a MATLAB .mat file Args: ts (Timeseries): the timeseries to save filename (str): .mat filename to save t...
Load a multi-channel Timeseries from any file type supported by `biosig` Supported file formats include EDF/EDF+, BDF/BDF+, EEG, CNT and GDF. Full list is here: http://pub.ist.ac.at/~schloegl/biosig/TESTED For EDF, EDF+, BDF and BDF+ files, we will use python-edf if it is installed, otherwise will fa...
load a multi-channel Timeseries from an EDF (European Data Format) file or EDF+ file, using edflib. Args: filename: EDF+ file Returns: Timeseries def _load_edflib(filename): """load a multi-channel Timeseries from an EDF (European Data Format) file or EDF+ file, using edflib. Arg...
Get a list of event annotations from an EDF (European Data Format file or EDF+ file, using edflib. Args: filename: EDF+ file Returns: list: annotation events, each in the form [start_time, duration, text] def annotations_from_file(filename): """Get a list of event annotations from an EDF ...
After using the superclass __numpy_ufunc__ to route ufunc computations on the array data, convert any resulting ndarray, RemoteArray and DistArray instances into Timeseries, RemoteTimeseries and DistTimeseries instances if appropriate def _ufunc_wrap(out_arr, ufunc, method, i, inputs, **kwargs): """Af...
construct a RemoteTimeseries from a RemoteArray def _rts_from_ra(ra, tspan, labels, block=True): """construct a RemoteTimeseries from a RemoteArray""" def _convert(a, tspan, labels): from nsim import Timeseries return Timeseries(a, tspan, labels) return distob.call( _convert, ra...
construct a DistTimeseries from a DistArray def _dts_from_da(da, tspan, labels): """construct a DistTimeseries from a DistArray""" sublabels = labels[:] new_subarrays = [] for i, ra in enumerate(da._subarrays): if isinstance(ra, RemoteTimeseries): new_subarrays.append(ra) el...