output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Updates the ordering of subtasks in the positions object with the given ID to the given values. | Can you generate a brief explanation for the following Python 3 code
def update_subtask_positions_obj(self, positions_obj_id, revision, values):
'''
Updates the ordering of subtasks in the positions object with the given ID to the ordering in the given values.
See https://developer.wunderlist.c... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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:
raise ValueError("Date '{}' does not conform to API format: {}".format(date, api.DATE_F... | Create a Python 3 function for
checking that the given date string conforms to the given API s date format specification. | You are a Python code generator, capable of creating scripts from specifications. |
Gets un / completed tasks for the given list ID | Given the following Python 3 function, write the documentation
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(... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Gets the task information for the given ID | How would you explain what the following Python 3 function does
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() | You are a Python code architect, reviewing and designing scalable and efficient code |
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 the given list
See https://developer.wunderlist.com/documentation/endpoints/task for detailed parameter information
'''
_check... | Can you create a Python 3 function that
creates a task in the given list. | You are a Python code generator, capable of creating scripts from specifications. |
Updates the task with the given ID. | Can you generate a brief explanation for the following Python 3 code
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):
'''
Updates the task with the given ID
See https://developer.... | As a python code expert, you are capable of creating scripts from specifications. |
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 longer than {} characters".format(api.MAX_TASK_TITLE_LENGTH)) | Implement a Python 3 function for
checking the given title against the given API specifications to ensure it s short enough. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_lists(client):
''' Gets all the client's lists '''
response = client.authenticated_request(client.api.Endpoints.LISTS)
return response.json() | Create a Python 3 function to
get all the client s lists | As a Python code translator, you convert algorithms and pseudocode into Python. |
Gets the given list | Make a summary of the following Python 3 code
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() | As a python code expert, you are capable of creating scripts from specifications. |
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)
return response.json() | Implement a function in Python 3 to
create a new list with the given title | You are a Python code generator, capable of creating scripts from specifications. |
Updates the list with the given ID to have the given properties. | Here you have a function in Python 3, explain what it does
def update_list(client, list_id, revision, title=None, public=None):
'''
Updates the list with the given ID to have the given properties
See https://developer.wunderlist.com/documentation/endpoints/list for detailed parameter information
'''
... | As a Python code composer, you craft elegant and concise scripts. |
def get_list_positions_obj(client, positions_obj_id):
'''
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 ... | Implement a Python 3 function for
getting the object that defines how lists are ordered | You are a Python code generator, capable of creating scripts from specifications. |
Updates the ordering of lists to have the given value. | Can you generate the documentation for the following Python 3 function
def update_list_positions_obj(client, positions_obj_id, revision, values):
'''
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... | As a python code expert, you are capable of creating scripts from specifications. |
Gets a list containing the object that encapsulates information about the order lists are laid out in. | How would you explain what the following Python 3 function does
def get_task_positions_objs(client, list_id):
'''
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/doc... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_list_subtask_positions_objs(client, list_id):
'''
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 ... | Can you write a function in Python 3 where it
gets all subtask positions objects for the tasks within a given list. | You are a Python code architect, reviewing and designing scalable and efficient code |
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 longer than {} characters".format(api.MAX_SUBTASK_TITLE_LENGTH)) | Can you create a Python 3 function that
checks the given title against the given API specifications to ensure it s short enough. | As a python code expert, you are capable of creating scripts from specifications. |
Gets the subtasks for a task with given ID | Can you tell what is the following Python 3 function doing
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.... | You are a Python code generator, capable of creating scripts from specifications. |
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.SUBTASKS, params=params)
return respo... | Can you create a Python 3 function that
gets the subtasks for the list with given ID | As a Python code analyst, you investigate and solve complex coding mysteries |
Gets the subtask with the given ID | Explain what the following Python 3 code does
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() | You are a Python code architect, reviewing and designing scalable and efficient code |
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_id else None,
'title' : title,
'completed' : compl... | Write a Python 3 script for
creating a subtask under the task with the given title under the task with the given ID | As a Python code translator, you convert algorithms and pseudocode into Python. |
Updates the subtask with the given ID
WorkItem. | Given the following Python 3 function, write the documentation
def update_subtask(client, subtask_id, revision, title=None, completed=None):
'''
Updates the subtask with the given ID
See https://developer.wunderlist.com/documentation/endpoints/subtask for detailed parameter information
'''
if title... | You are a Python code architect, reviewing and designing scalable and efficient code |
Deletes the subtask with the given ID provided the given revision equals the revision of the server has. | Explain what the following Python 3 code does
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),
}
endpoint = '/'.join([client.api.Endpoi... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Decorator for adding wait animation to long running functions. | Can you tell what is the following Python 3 function doing
def wait(animation='elipses', text='', speed=0.2):
def decorator(func):
func.animation = animation
func.speed = speed
func.text = text
@wraps(func)
def wrapper(*args, **kwargs):
animation = func.animation... | As a Python code analyst, you investigate and solve complex coding mysteries |
Merge several Timeseries into a single timeseries with the same shape except for axis 0. | How would you explain what the following Python 3 function does
def merge(tup):
if not all(tuple(ts.shape[1:] == tup[0].shape[1:] for ts in tup[1:])):
raise ValueError('Timeseries to merge must have compatible shapes')
indices = np.vstack(tuple(ts.tspan for ts in tup)).argsort()
return np.vstack((tu... | As a Python code analyst, you investigate and solve complex coding mysteries |
Dynamically add new analysis methods to the Timeseries class. | Can you generate the documentation for the following Python 3 function
def add_analyses(cls, source):
if isinstance(source, types.FunctionType):
_add_single_method(source.__name__, source)
else:
if isinstance(source, types.ModuleType):
mod = source
eli... | You are a Python code architect, reviewing and designing scalable and efficient code |
Calculate the absolute value element - wise. | How would you explain what the following Python 3 function does
def absolute(self):
return Timeseries(np.absolute(self), self.tspan, self.labels) | You are a Python code analyst, evaluating scripts for potential improvements. |
def angle(self, deg=False):
"""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
... | Write a Python 3 script for
returning the angle of the complex argument. | As a python code expert, you are capable of creating scripts from specifications. |
Interchange two axes of a Timeseries. | Make a summary of the following Python 3 code
def swapaxes(self, axis1, axis2):
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 unaffected by the swap
labels = self.lab... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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
newlabels = [self.labels[ax] for ax in axe... | Write a Python 3 script to
permute the dimensions of a Timeseries. | As a Python code analyst, you investigate and solve complex coding mysteries |
def merge(self, ts):
"""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.
"""
i... | Create a Python 3 function to
merge another timeseries with this one returning a new one whose time points are the same. | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a new array with the same shape as self. | Can you generate a brief explanation for the following Python 3 code
def expand_dims(self, axis):
if axis == -1:
axis = self.ndim
array = np.expand_dims(self, axis)
if axis == 0:
# prepended an axis: no longer a Timeseries
return array
else:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a new array with the elements of tup joined along the specified axis. | Here you have a function in Python 3, explain what it does
def concatenate(self, tup, axis=0):
if not isinstance(tup, Sequence):
tup = (tup,)
if tup is (None,) or len(tup) is 0:
return self
tup = (self,) + tuple(tup)
new_array = np.concatenate(tup, axis)
i... | You are a Python code architect, reviewing and designing scalable and efficient code |
Split a timeseries into multiple sub - timeseries. | Given the following Python 3 function, write the documentation
def split(self, indices_or_sections, axis=0):
if not isinstance(indices_or_sections, numbers.Integral):
raise Error('splitting by array of indices is not yet implemented')
n = indices_or_sections
if self.shape[axis] % n !... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Plot a distributed timeseries. | Can you generate the documentation for the following Python 3 function
def plot(dts, title=None, points=None, show=True):
if points is not None and len(dts.tspan) > points:
# then downsample (TODO: use interpolation)
ix = np.linspace(0, len(dts.tspan) - 1, points).astype(np.int64)
dts = dts... | As a Python code analyst, you investigate and solve complex coding mysteries |
Plot a polar histogram of a phase variable s probability distribution. | Can you generate the documentation for the following Python 3 function
def phase_histogram(dts, times=None, nbins=30, colormap=mpl.cm.Blues):
if times is None:
times = np.linspace(dts.tspan[0], dts.tspan[-1], num=4)
elif isinstance(times, numbers.Number):
times = np.array([times], dtype=np.float... | As a Python code analyst, you investigate and solve complex coding mysteries |
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 Hamming window."""
ts = ts.squeeze()
if ts.ndim is 1:
ts = ts.reshape((-1, 1))
fs = (len(ts) - 1.0) / (ts.tspan[-1] - ts... | Can you implement a function in Python 3 that
plots Welch estimate of power spectral density using nperseg samples per segment with noverlap samples overlap and Hamming window. | As a Python code translator, you convert algorithms and pseudocode into Python. |
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
cutoff = cutoff_hz/nyq
b, a = signal.butte... | Create a Python 3 function to
forward - backward butterworth low - pass filter | As a python code expert, you are capable of creating scripts from specifications. |
forward - backward butterworth band - pass filter | How would you explain what the following Python 3 function does
def bandpass(ts, low_hz, high_hz, order=3):
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
low = low_hz/nyq
high = hi... | As a python code expert, you are capable of creating scripts from specifications. |
notch filter to remove a particular frequency
| How would you explain what the following Python 3 function does
def notch(ts, freq_hz, bandwidth_hz=1.0):
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
freq = freq_hz/nyq
bandwidth... | As a Python code analyst, you investigate and solve complex coding mysteries |
Analytic signal using the Hilbert transform | Can you generate a brief explanation for the following Python 3 code
def hilbert(ts):
output = signal.hilbert(signal.detrend(ts, axis=0), axis=0)
return Timeseries(output, ts.tspan, labels=ts.labels) | As a Python code analyst, you investigate and solve complex coding mysteries |
Amplitude of the analytic signal using the Hilbert transform | Make a summary of the following Python 3 code
def hilbert_amplitude(ts):
output = np.abs(signal.hilbert(signal.detrend(ts, axis=0), axis=0))
return Timeseries(output, ts.tspan, labels=ts.labels) | You are a Python code analyst, evaluating scripts for potential improvements. |
Phase of the analytic signal using the Hilbert transform | How would you explain what the following Python 3 function does
def hilbert_phase(ts):
output = np.angle(signal.hilbert(signal.detrend(ts, axis=0), axis=0))
return Timeseries(output, ts.tspan, labels=ts.labels) | As a Python code composer, you craft elegant and concise scripts. |
Continuous wavelet transform using distributed computation. | Explain what the following Python 3 code does
def cwt_distributed(ts, freqs=np.logspace(0, 2), wavelet=cwtmorlet, plot=True):
if ts.ndim is 1 or ts.shape[1] is 1:
return cwt(ts, freqs, wavelet, plot)
import distob
vcwt = distob.vectorize(cwt)
coefs = vcwt(ts, freqs, wavelet, plot=False)
if p... | As a python code expert, you are capable of creating scripts from specifications. |
def _plot_cwt(ts, coefs, freqs, tsize=1024, fsize=512):
"""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.
tsiz... | Can you write a function in Python 3 where it
plots time resolved power spectral density from cwt results. | As a python code expert, you are capable of creating scripts from specifications. |
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. | Can you generate the documentation for the following Python 3 function
def first_return_times(dts, c=None, d=0.0):
if c is None:
c = dts.mean()
vmrt = distob.vectorize(analyses1.first_return_times)
all_intervals = vmrt(dts, c, d)
if hasattr(type(all_intervals), '__array_interface__'):
re... | You are a Python code architect, reviewing and designing scalable and efficient code |
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 ... | Make a summary of the following Python 3 code
def variability_fp(ts, freqs=None, ncycles=6, plot=True):
if ts.ndim <= 2:
return analyses1.variability_fp(ts, freqs, ncycles, plot)
else:
return distob.vectorize(analyses1.variability_fp)(
ts, freqs, ncycles, plot) | As a Python code analyst, you investigate and solve complex coding mysteries |
def epochs(ts, variability=None, threshold=0.0, minlength=1.0, plot=True):
"""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 exceedi... | Can you create a Python 3 function that
identifies stationary epochs within a time series. | You are a Python code analyst, evaluating scripts for potential improvements. |
def epochs_joint(ts, variability=None, threshold=0.0, minlength=1.0,
proportion=0.75, plot=True):
"""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 req... | Create a Python 3 function to
identify epochs within a multivariate time series where at least a certain proportion of channels are stationary. | You are a Python code generator, capable of creating scripts from specifications. |
Order parameter of phase synchronization | Explain what the following Python 3 code does
def order_param(dts, axis=2):
return np.abs(np.exp(1.0j * dts).mean(axis=axis)) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Aburn2012 equations right hand side noise term
ArcGIS | Can you generate the documentation for the following Python 3 function
def G(self, v, t):
ret = np.zeros((8, 1))
ret[4,0] = self.ke1 * self.He1 * self.u_sdev
ret[5,0] = self.ke2 * self.He2 * self.p_sdev
return ret | As a Python code composer, you craft elegant and concise scripts. |
def hurst(X):
""" 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
------... | Can you create a Python 3 function that
computes the Hurst exponent of X. | As a python code expert, you are capable of creating scripts from specifications. |
Build a set of embedding sequences from given time series X with lag Tau
and embedding dimension D. | Explain what the following Python 3 code does
def embed_seq(X, Tau, D):
shape = (X.size - Tau * (D - 1), D)
strides = (X.itemsize, Tau * X.itemsize)
return numpy.lib.stride_tricks.as_strided(X, shape=shape, strides=strides) | You are a Python code architect, reviewing and designing scalable and efficient code |
def bin_power(X, Band, Fs):
"""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... | Implement a function in Python 3 to
compute the power of each frequency bin specified by Band from FFT result of X. | You are a Python code architect, reviewing and designing scalable and efficient code |
Compute Petrosian Fractal Dimension of a time series X. | Can you generate a brief explanation for the following Python 3 code
def pfd(X, D=None):
if D is None:
D = numpy.diff(X)
D = D.tolist()
N_delta = 0 # number of sign changes in derivative of the signal
for i in range(1, len(D)):
if D[i] * D[i - 1] < 0:
N_delta += 1
n ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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):
Lmk = 0
for i in range(1, int(numpy.floor((N - m) / k))):
... | Implement a Python 3 function for
computing Hjorth Fractal Dimension of a time series X and kmax is an HFD parameter | You are a Python code architect, reviewing and designing scalable and efficient code |
Compute Hjorth mobility and complexity of a time series X and D. | Explain what the following Python 3 code does
def hjorth(X, D=None):
if D is None:
D = numpy.diff(X)
D = D.tolist()
D.insert(0, X[0]) # pad the first difference
D = numpy.array(D)
n = len(X)
M2 = float(sum(D ** 2)) / n
TP = sum(numpy.array(X) ** 2)
M4 = 0
for i in ra... | As a python code expert, you are capable of creating scripts from specifications. |
def spectral_entropy(X, Band, Fs, Power_Ratio=None):
"""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... | Implement a function in Python 3 to
compute the spectral entropy of a time series X in a frequency domain band and frequency spectrum Fs. | You are a Python code generator, capable of creating scripts from specifications. |
Compute SVD Entropy from two cases below. | Given the following Python 3 function, write the documentation
def svd_entropy(X, Tau, DE, W=None):
if W is None:
Y = embed_seq(X, Tau, DE)
W = numpy.linalg.svd(Y, compute_uv=0)
W /= sum(W) # normalize singular values
return -1 * sum(W * numpy.log(W)) | As a Python code analyst, you investigate and solve complex coding mysteries |
Computeer approximate entropy of series X specified by M and R. | Explain what the following Python 3 code does
def ap_entropy(X, M, R):
N = len(X)
Em = embed_seq(X, 1, M)
A = numpy.tile(Em, (len(Em), 1, 1))
B = numpy.transpose(A, [1, 0, 2])
D = numpy.abs(A - B) # D[i,j,k] = |Em[i][k] - Em[j][k]|
InRange = numpy.max(D, axis=2) <= R
Cm = InRange.mean(axis... | You are a Python code generator, capable of creating scripts from specifications. |
def dfa(X, Ave=None, L=None):
"""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
... | Can you implement a function in Python 3 that
computes Detrended Fluctuation Analysis from a time series X and length of boxes L. | As a Python code composer, you craft elegant and concise scripts. |
Compute the Permutation Entropy of a given time series x. | Given the following Python 3 function, write the documentation
def permutation_entropy(x, n, tau):
PeSeq = []
Em = embed_seq(x, tau, n)
for i in range(0, len(Em)):
r = []
z = []
for j in range(0, len(Em[i])):
z.append(Em[i][j])
for j in range(0, len(Em[i])):
... | As a python code expert, you are capable of creating scripts from specifications. |
Calculates the information based similarity between two time series x and y. | Here you have a function in Python 3, explain what it does
def information_based_similarity(x, y, n):
Wordlist = []
Space = [[0, 0], [0, 1], [1, 0], [1, 1]]
Sample = [0, 1]
if (n == 1):
Wordlist = Sample
if (n == 2):
Wordlist = Space
elif (n > 1):
Wordlist = Space
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def LLE(x, tau, n, T, fs):
"""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
in... | Write a Python 3 function for
calculating the largest Lyauponov exponent of a given time series x using the Losenstein algorithm. | You are a Python code generator, capable of creating scripts from specifications. |
def periods(ts, phi=0.0):
"""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 timeser... | Implement a Python 3 function for
returning a list of time series representing the period of each successive oscillation in the given time series. | You are a Python code generator, capable of creating scripts from specifications. |
Order parameter of phase synchronization | Explain what the following Python 3 code does
def order_param(ts, axis=2):
return np.abs(np.exp(1.0j * ts).mean(axis=axis)) | As a Python code composer, you craft elegant and concise scripts. |
Complex morlet wavelet function compatible with scipy. signal. cwt
| Explain what the following Python 3 code does
def cwtmorlet(points, width):
omega = 5.0
s = points / (2.0 * omega * width)
return wavelets.morlet(points, omega, s, complete=True) | As a Python code analyst, you investigate and solve complex coding mysteries |
A CWT implementation that uses a continuous wavelet transform on data. | Explain what the following Python 3 code does
def roughcwt(data, wavelet, widths):
out_dtype = wavelet(widths[0], widths[0]).dtype
output = np.zeros([len(widths), len(data)], dtype=out_dtype)
for ind, width in enumerate(widths):
wavelet_data = wavelet(min(3 * width, len(data)), width)
output... | You are a Python code generator, capable of creating scripts from specifications. |
Shift and rescale array ar to the interval - 1 1 | Can you tell what is the following Python 3 function doing
def _rescale(ar):
max = np.nanmax(ar)
min = np.nanmin(ar)
midpoint = (max + min) / 2.0
return 2.0 * (ar - midpoint) / (max - min) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get cycle of colors in a way compatible with all matplotlib versions | How would you explain what the following Python 3 function does
def _get_color_list():
if 'axes.prop_cycle' in plt.rcParams:
return [p['color'] for p in list(plt.rcParams['axes.prop_cycle'])]
else:
return plt.rcParams['axes.color_cycle'] | As a python code expert, you are capable of creating scripts from specifications. |
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 plt
if variability.ndim is 1:
variability = variab... | Write a Python 3 script to
plot the timeseries and variability. Optionally plot epochs. | You are a Python code architect, reviewing and designing scalable and efficient code |
Identify stationary epochs within a time series. | Explain what the following Python 3 code does
def epochs(ts, variability=None, threshold=0.0, minlength=1.0, plot=True):
if variability is None:
variability = ts.variability_fp(plot=False)
orig_ndim = ts.ndim
if ts.ndim is 1:
ts = ts[:, np.newaxis]
if variability.ndim is 1:
varia... | As a Python code analyst, you investigate and solve complex coding mysteries |
def epochs_distributed(ts, variability=None, threshold=0.0, minlength=1.0,
plot=True):
"""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... | Implement a function in Python 3 to
distribute epochs for a time series. | You are a Python code generator, capable of creating scripts from specifications. |
def epochs_joint(ts, variability=None, threshold=0.0, minlength=1.0,
proportion=0.75, plot=True):
"""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 req... | How would you code a function in Python 3 to
identify epochs within a multivariate time series where at least one of the specified variability is stationary. | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 figure object
"""
ts = _remove_pi_crossings(ts)
fig = plt.figure()
ylabelprops = dict(rotation=0,
hor... | How would you implement a function in Python 3 that
plots a Timeseries containing a single variable and a single simulation time series. | You are a Python code analyst, evaluating scripts for potential improvements. |
Removes all pi crossings from the time series ts. | Can you generate the documentation for the following Python 3 function
def _remove_pi_crossings(ts):
orig_ts = ts
if ts.ndim is 1:
ts = ts[:, np.newaxis, np.newaxis]
elif ts.ndim is 2:
ts = ts[:, np.newaxis]
# Get the indices of those variables that have range of approx -pi to pi
tsm... | You are a Python code generator, capable of creating scripts from specifications. |
Load a multi - channel Timeseries from a MATLAB. mat file. | Can you generate a brief explanation for the following Python 3 code
def timeseries_from_mat(filename, varname=None, fs=1.0):
import scipy.io as sio
if varname is None:
mat_dict = sio.loadmat(filename)
if len(mat_dict) > 1:
raise ValueError('Must specify varname: file contains '
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
save a Timeseries to a MATLAB. mat file | Given the following Python 3 function, write the documentation
def save_mat(ts, filename):
import scipy.io as sio
tspan = ts.tspan
fs = (1.0*len(tspan) - 1) / (tspan[-1] - tspan[0])
mat_dict = {'data': np.asarray(ts),
'fs': fs,
'labels': ts.labels[1]}
sio.savemat(file... | You are a Python code architect, reviewing and designing scalable and efficient code |
def timeseries_from_file(filename):
"""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... | Can you implement a function in Python 3 that
loads a multi - channel Timeseries from a file. | As a python code expert, you are capable of creating scripts from specifications. |
def _load_edflib(filename):
"""load a multi-channel Timeseries from an EDF (European Data Format) file
or EDF+ file, using edflib.
Args:
filename: EDF+ file
Returns:
Timeseries
"""
import edflib
e = edflib.EdfReader(filename, annotations_mode='all')
if np.ptp(e.get_samples_... | Create a Python 3 function for
loading a multi - channel Timeseries from an EDF file using edflib. | As a Python code analyst, you investigate and solve complex coding mysteries |
Get a list of event annotations from an EDF file using edflib. | Can you generate the documentation for the following Python 3 function
def annotations_from_file(filename):
import edflib
e = edflib.EdfReader(filename, annotations_mode='all')
return e.read_annotations() | As a python code expert, you are capable of creating scripts from specifications. |
This function wraps the ufunc function in a Timeseries and DistTimeseries instance. | Explain what the following Python 3 code does
def _ufunc_wrap(out_arr, ufunc, method, i, inputs, **kwargs):
# Assigns tspan/labels to an axis only if inputs do not disagree on them.
shape = out_arr.shape
ndim = out_arr.ndim
if ndim is 0 or shape[0] is 0:
# not a timeseries
return out_arr... | As a Python code composer, you craft elegant and concise scripts. |
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, tspan, labels, prefer_local=False, block=block) | Write a Python 3 function for
constructing a RemoteTimeseries from a RemoteArray | As a Python code translator, you convert algorithms and pseudocode into Python. |
construct a DistTimeseries from a DistArray | Can you generate a brief explanation for the following Python 3 code
def _dts_from_da(da, tspan, labels):
sublabels = labels[:]
new_subarrays = []
for i, ra in enumerate(da._subarrays):
if isinstance(ra, RemoteTimeseries):
new_subarrays.append(ra)
else:
if labels[da._... | You are a Python code architect, reviewing and designing scalable and efficient code |
def newsim(f, G, y0, name='NewModel', modelType=ItoModel, T=60.0, dt=0.005, repeat=1, identical=True):
"""Make a simulation of the system defined by functions f and G.
dy = f(y,t)dt + G(y,t).dW with initial condition y0
This helper function is for convenience, making it easy to define
one-off simulati... | Can you create a Python 3 function that
makes a simulation of the system defined by functions f and G. | You are a Python code analyst, evaluating scripts for potential improvements. |
def newmodel(f, G, y0, name='NewModel', modelType=ItoModel):
"""Use the functions f and G to define a new Model class for simulations.
It will take functions f and G from global scope and make a new Model class
out of them. It will automatically gather any globals used in the definition
of f and G and... | Write a Python 3 script for
using the functions f and G to define a new Model class for simulations. It will take functions f and G from global scope and make a new Model class out of them. It will automatically gather any globals used in the definition of f and G and turn them into attributes of the new Model. Args: f... | As a python code expert, you are capable of creating scripts from specifications. |
def __clone_function(f, name=None):
"""Make a new version of a function that has its own independent copy
of any globals that it uses directly, and has its own name.
All other attributes are assigned from the original function.
Args:
f: the function to clone
name (str): the name for the ... | Can you implement a function in Python 3 that
makes a new version of a function that has its own independent copy of any globals that it uses directly and has its own independent copy of any globals that it uses directly and has its own name assigned from the original function. | As a python code expert, you are capable of creating scripts from specifications. |
Insert a new axis at a given position in the array shape. | Make a summary of the following Python 3 code
def expand_dims(self, axis):
if axis <= self._distaxis:
subaxis = axis
new_distaxis = self._distaxis + 1
else:
subaxis = axis - 1
new_distaxis = self._distaxis
new_subts = [rts.expand_dims(subaxis) for ... | As a Python code analyst, you investigate and solve complex coding mysteries |
def absolute(self):
"""Calculate the absolute value element-wise.
Returns:
absolute (Timeseries):
Absolute value. For complex input (a + b*j) gives sqrt(a**a + b**2)
"""
da = distob.vectorize(np.absolute)(self)
return _dts_from_da(da, self.tspan, self.label... | Can you write a function in Python 3 where it
calculates the absolute value element - wise. | You are a Python code analyst, evaluating scripts for potential improvements. |
def angle(self, deg=False):
"""Return the angle of a complex Timeseries
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
... | Create a Python 3 function to
return the angle of a complex Timeseries | As a Python code composer, you craft elegant and concise scripts. |
This example coupling function is used to couple the output of one subsystem to the input of another subsystem. | Can you generate the documentation for the following Python 3 function
def coupling(self, source_y, target_y, weight):
return np.ones_like(target_y)*np.mean(source_y)*weight | You are a Python code analyst, evaluating scripts for potential improvements. |
Deterministic term f of the complete network system. | Given the following Python 3 function, write the documentation
def f(self, y, t):
coupling = self.coupling_function[0]
res = np.empty_like(self.y0)
for j, m in enumerate(self.submodels):
slicej = slice(self._si[j], self._si[j+1])
target_y = y[slicej] # target node state
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def G(self, y, t):
"""Noise coefficient matrix G of the complete network system
dy = f(y, t)dt + G(y, t).dot(dW)
(for an ODE network system without noise this function is not used)
Args:
y (array of shape (d,)): where d is the dimension of the overall
state space ... | Can you write a function in Python 3 where it
noises coefficient matrix G of the complete network system. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _scalar_to_vector(self, m):
"""Allow submodels with scalar equations. Convert to 1D vector systems.
Args:
m (Model)
"""
if not isinstance(m.y0, numbers.Number):
return m
else:
m = copy.deepcopy(m)
t0 = 0.0
if isinstanc... | Can you implement a function in Python 3 that
converts a scalar model to 1D vector systems. | You are a Python code generator, capable of creating scripts from specifications. |
Introduce a new axis 2 that ranges across nodes of the network | Explain what the following Python 3 code does
def _reshape_timeseries(self, ts):
if np.count_nonzero(np.diff(self._sublengths)) == 0:
# then all submodels have the same dimension, so can reshape array
# in place without copying data:
subdim = self.dimension // self._n
... | As a Python code composer, you craft elegant and concise scripts. |
def _reshape_output(self, ts):
"""Introduce a new axis 2 that ranges across nodes of the network"""
subodim = len(self.submodels[0].output_vars)
shp = list(ts.shape)
shp[1] = subodim
shp.insert(2, self._n)
ts = ts.reshape(tuple(shp))
ts.labels[2] = self._node_labe... | Create a Python 3 function to
introduce a new axis 2 that ranges across nodes of the network | As a Python code analyst, you investigate and solve complex coding mysteries |
Rank 3 array representing output time series. Axis 0 is time axis 1 ranges across output variables of a single simulation instance axis 2 ranges across different simulation instances. | Make a summary of the following Python 3 code
def output(self):
subts = [s.output for s in self.sims]
sub_ndim = subts[0].ndim
if sub_ndim is 1:
subts = [distob.expand_dims(ts, 1) for ts in subts]
sub_ndim += 1
nodeaxis = sub_ndim
subts = [distob.expand_di... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _tosub(self, ix):
"""Given an integer index ix into the list of sims, returns the pair
(s, m) where s is the relevant subsim and m is the subindex into s.
So self[ix] == self._subsims[s][m]
"""
N = self._n
if ix >= N or ix < -N:
raise IndexError(
... | Write a Python 3 function for
giving an integer index ix into the list of sims returns the relevant subsim and subindex into s where s is the relevant subsim and m is the relevant subindex into s where s is the relevant subsim. | You are a Python code architect, reviewing and designing scalable and efficient code |
Maps a list of integer indices to sub - indices. | Can you tell what is the following Python 3 function doing
def _tosubs(self, ixlist):
n = len(ixlist)
N = self._n
ss = []
ms = []
if n == 0:
return ss, ms
j = 0 # the position in ixlist currently being processed
ix = ixlist[j]
if ix >= N or ix ... | You are a Python code analyst, evaluating scripts for potential improvements. |
Rank 3 array representing output time series. Axis 0 is time axis 1 ranges across output variables of a single simulation axis 2 isSetNodeCounts = True | Can you tell what is the following Python 3 function doing
def output(self):
subts = [rms.output for rms in self._subsims]
distaxis = subts[0].ndim - 1
return DistTimeseries(subts, distaxis, self._node_labels()) | You are a Python code generator, capable of creating scripts from specifications. |
def crossing_times(ts, c=0.0, d=0.0):
"""For a single variable timeseries, find the times at which the
value crosses ``c`` from above or below. Can optionally set a non-zero
``d`` to impose the condition that the value must wander at least ``d``
units away from ``c`` between crossings.
If the time... | Write a Python 3 script for
giving a time series ts find the times at which the value c crosses at least d. | As a Python code analyst, you investigate and solve complex coding mysteries |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.